PluginProbe
Elementor Website Builder – more than just a page builder / 4.3.1
Elementor Website Builder – more than just a page builder v4.3.1
4.3.2 4.3.1 4.3.0 4.3.0-beta3 4.3.0-beta2 4.3.0-beta1 4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.5 4.2.0-beta2 4.2.0-dev2 4.2.0-beta1 4.1.4 4.1.3 4.1.2 4.1.1 4.1.0 4.1.0-beta3 4.1.0-dev3 4.0.9 4.1.0-beta2 4.1.0-dev2 All 455 releases
elementor / assets / js / packages / editor-mcp / editor-mcp.js

editor-mcp.js in Elementor Website Builder – more than just a page builder 4.3.1, at assets/js/packages/editor-mcp/editor-mcp.js

25,110 lines 875.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function(_elementor_schema, _wordpress_api_fetch) {
2
3 //#region \0rolldown/runtime.js
4 var __create = Object.create;
5 var __defProp$3 = Object.defineProperty;
6 var __name = (target, value) => __defProp$3(target, "name", {
7 value,
8 configurable: true
9 });
10 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11 var __getOwnPropNames = Object.getOwnPropertyNames;
12 var __getProtoOf = Object.getPrototypeOf;
13 var __hasOwnProp = Object.prototype.hasOwnProperty;
14 var __esmMin = (fn, res, err) => () => {
15 if (err) throw err[0];
16 try {
17 return fn && (res = fn(fn = 0)), res;
18 } catch (e) {
19 throw err = [e], e;
20 }
21 };
22 var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
23 var __exportAll = (all, no_symbols) => {
24 let target = {};
25 for (var name in all) {
26 __defProp$3(target, name, {
27 get: all[name],
28 enumerable: true
29 });
30 }
31 if (!no_symbols) {
32 __defProp$3(target, Symbol.toStringTag, { value: "Module" });
33 }
34 return target;
35 };
36 var __copyProps = (to, from, except, desc) => {
37 if (from && typeof from === "object" || typeof from === "function") {
38 for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
39 key = keys[i];
40 if (!__hasOwnProp.call(to, key) && key !== except) {
41 __defProp$3(to, key, {
42 get: ((k) => from[k]).bind(null, key),
43 enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
44 });
45 }
46 }
47 }
48 return to;
49 };
50 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp$3(target, "default", {
51 value: mod,
52 enumerable: true
53 }) : target, mod));
54 var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp$3({}, "__esModule", { value: true }), mod);
55
56 //#endregion
57 _wordpress_api_fetch = __toESM(_wordpress_api_fetch);
58
59 //#region node_modules/zod/v4/core/core.js
60 /** A special constant with type `never` */
61 var NEVER = Object.freeze({ status: "aborted" });
62 function $constructor(name, initializer, params) {
63 function init(inst, def) {
64 var _a;
65 Object.defineProperty(inst, "_zod", {
66 value: inst._zod ?? {},
67 enumerable: false
68 });
69 (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set());
70 inst._zod.traits.add(name);
71 initializer(inst, def);
72 for (const k in _.prototype) if (!(k in inst)) Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
73 inst._zod.constr = _;
74 inst._zod.def = def;
75 }
76 const Parent = params?.Parent ?? Object;
77 class Definition extends Parent {}
78 Object.defineProperty(Definition, "name", { value: name });
79 function _(def) {
80 var _a;
81 const inst = params?.Parent ? new Definition() : this;
82 init(inst, def);
83 (_a = inst._zod).deferred ?? (_a.deferred = []);
84 for (const fn of inst._zod.deferred) fn();
85 return inst;
86 }
87 Object.defineProperty(_, "init", { value: init });
88 Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
89 if (params?.Parent && inst instanceof params.Parent) return true;
90 return inst?._zod?.traits?.has(name);
91 } });
92 Object.defineProperty(_, "name", { value: name });
93 return _;
94 }
95 var $ZodAsyncError = class extends Error {
96 constructor() {
97 super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
98 }
99 };
100 var globalConfig = {};
101 function config(newConfig) {
102 if (newConfig) Object.assign(globalConfig, newConfig);
103 return globalConfig;
104 }
105
106 //#endregion
107 //#region node_modules/zod/v4/core/util.js
108 function getEnumValues(entries) {
109 const numericValues = Object.values(entries).filter((v) => typeof v === "number");
110 return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
111 }
112 function jsonStringifyReplacer(_, value) {
113 if (typeof value === "bigint") return value.toString();
114 return value;
115 }
116 function cached(getter) {
117 return { get value() {
118 {
119 const value = getter();
120 Object.defineProperty(this, "value", { value });
121 return value;
122 }
123 } };
124 }
125 function nullish(input) {
126 return input === null || input === void 0;
127 }
128 function cleanRegex(source) {
129 const start = source.startsWith("^") ? 1 : 0;
130 const end = source.endsWith("$") ? source.length - 1 : source.length;
131 return source.slice(start, end);
132 }
133 function floatSafeRemainder$1(val, step) {
134 const valDecCount = (val.toString().split(".")[1] || "").length;
135 const stepDecCount = (step.toString().split(".")[1] || "").length;
136 const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
137 return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
138 }
139 __name(floatSafeRemainder$1, "floatSafeRemainder");
140 function defineLazy(object, key, getter) {
141 Object.defineProperty(object, key, {
142 get() {
143 {
144 const value = getter();
145 object[key] = value;
146 return value;
147 }
148 },
149 set(v) {
150 Object.defineProperty(object, key, { value: v });
151 },
152 configurable: true
153 });
154 }
155 function assignProp(target, prop, value) {
156 Object.defineProperty(target, prop, {
157 value,
158 writable: true,
159 enumerable: true,
160 configurable: true
161 });
162 }
163 function esc(str) {
164 return JSON.stringify(str);
165 }
166 var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {};
167 function isObject(data) {
168 return typeof data === "object" && data !== null && !Array.isArray(data);
169 }
170 var allowsEval = cached(() => {
171 if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
172 try {
173 new Function("");
174 return true;
175 } catch (_) {
176 return false;
177 }
178 });
179 function isPlainObject$1(o) {
180 if (isObject(o) === false) return false;
181 const ctor = o.constructor;
182 if (ctor === void 0) return true;
183 const prot = ctor.prototype;
184 if (isObject(prot) === false) return false;
185 if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
186 return true;
187 }
188 __name(isPlainObject$1, "isPlainObject");
189 var propertyKeyTypes = /* @__PURE__ */ new Set([
190 "string",
191 "number",
192 "symbol"
193 ]);
194 function escapeRegex(str) {
195 return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
196 }
197 function clone(inst, def, params) {
198 const cl = new inst._zod.constr(def ?? inst._zod.def);
199 if (!def || params?.parent) cl._zod.parent = inst;
200 return cl;
201 }
202 function normalizeParams(_params) {
203 const params = _params;
204 if (!params) return {};
205 if (typeof params === "string") return { error: () => params };
206 if (params?.message !== void 0) {
207 if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
208 params.error = params.message;
209 }
210 delete params.message;
211 if (typeof params.error === "string") return {
212 ...params,
213 error: () => params.error
214 };
215 return params;
216 }
217 function optionalKeys(shape) {
218 return Object.keys(shape).filter((k) => {
219 return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
220 });
221 }
222 var NUMBER_FORMAT_RANGES = {
223 safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
224 int32: [-2147483648, 2147483647],
225 uint32: [0, 4294967295],
226 float32: [-34028234663852886e22, 34028234663852886e22],
227 float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
228 };
229 function pick(schema, mask) {
230 const newShape = {};
231 const currDef = schema._zod.def;
232 for (const key in mask) {
233 if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
234 if (!mask[key]) continue;
235 newShape[key] = currDef.shape[key];
236 }
237 return clone(schema, {
238 ...schema._zod.def,
239 shape: newShape,
240 checks: []
241 });
242 }
243 function omit(schema, mask) {
244 const newShape = { ...schema._zod.def.shape };
245 const currDef = schema._zod.def;
246 for (const key in mask) {
247 if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
248 if (!mask[key]) continue;
249 delete newShape[key];
250 }
251 return clone(schema, {
252 ...schema._zod.def,
253 shape: newShape,
254 checks: []
255 });
256 }
257 function extend(schema, shape) {
258 if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
259 return clone(schema, {
260 ...schema._zod.def,
261 get shape() {
262 const _shape = {
263 ...schema._zod.def.shape,
264 ...shape
265 };
266 assignProp(this, "shape", _shape);
267 return _shape;
268 },
269 checks: []
270 });
271 }
272 function merge(a, b) {
273 return clone(a, {
274 ...a._zod.def,
275 get shape() {
276 const _shape = {
277 ...a._zod.def.shape,
278 ...b._zod.def.shape
279 };
280 assignProp(this, "shape", _shape);
281 return _shape;
282 },
283 catchall: b._zod.def.catchall,
284 checks: []
285 });
286 }
287 function partial(Class, schema, mask) {
288 const oldShape = schema._zod.def.shape;
289 const shape = { ...oldShape };
290 if (mask) for (const key in mask) {
291 if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
292 if (!mask[key]) continue;
293 shape[key] = Class ? new Class({
294 type: "optional",
295 innerType: oldShape[key]
296 }) : oldShape[key];
297 }
298 else for (const key in oldShape) shape[key] = Class ? new Class({
299 type: "optional",
300 innerType: oldShape[key]
301 }) : oldShape[key];
302 return clone(schema, {
303 ...schema._zod.def,
304 shape,
305 checks: []
306 });
307 }
308 function required$1(Class, schema, mask) {
309 const oldShape = schema._zod.def.shape;
310 const shape = { ...oldShape };
311 if (mask) for (const key in mask) {
312 if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
313 if (!mask[key]) continue;
314 shape[key] = new Class({
315 type: "nonoptional",
316 innerType: oldShape[key]
317 });
318 }
319 else for (const key in oldShape) shape[key] = new Class({
320 type: "nonoptional",
321 innerType: oldShape[key]
322 });
323 return clone(schema, {
324 ...schema._zod.def,
325 shape,
326 checks: []
327 });
328 }
329 __name(required$1, "required");
330 function aborted(x, startIndex = 0) {
331 for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
332 return false;
333 }
334 function prefixIssues(path, issues) {
335 return issues.map((iss) => {
336 var _a;
337 (_a = iss).path ?? (_a.path = []);
338 iss.path.unshift(path);
339 return iss;
340 });
341 }
342 function unwrapMessage(message) {
343 return typeof message === "string" ? message : message?.message;
344 }
345 function finalizeIssue(iss, ctx, config) {
346 const full = {
347 ...iss,
348 path: iss.path ?? []
349 };
350 if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
351 delete full.inst;
352 delete full.continue;
353 if (!ctx?.reportInput) delete full.input;
354 return full;
355 }
356 function getLengthableOrigin(input) {
357 if (Array.isArray(input)) return "array";
358 if (typeof input === "string") return "string";
359 return "unknown";
360 }
361 function issue(...args) {
362 const [iss, input, inst] = args;
363 if (typeof iss === "string") return {
364 message: iss,
365 code: "custom",
366 input,
367 inst
368 };
369 return { ...iss };
370 }
371
372 //#endregion
373 //#region node_modules/zod/v4/core/errors.js
374 var initializer$1 = /* @__PURE__ */ __name((inst, def) => {
375 inst.name = "$ZodError";
376 Object.defineProperty(inst, "_zod", {
377 value: inst._zod,
378 enumerable: false
379 });
380 Object.defineProperty(inst, "issues", {
381 value: def,
382 enumerable: false
383 });
384 Object.defineProperty(inst, "message", {
385 get() {
386 return JSON.stringify(def, jsonStringifyReplacer, 2);
387 },
388 enumerable: true
389 });
390 Object.defineProperty(inst, "toString", {
391 value: () => inst.message,
392 enumerable: false
393 });
394 }, "initializer");
395 var $ZodError = $constructor("$ZodError", initializer$1);
396 var $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
397 function flattenError(error, mapper = (issue) => issue.message) {
398 const fieldErrors = {};
399 const formErrors = [];
400 for (const sub of error.issues) if (sub.path.length > 0) {
401 fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
402 fieldErrors[sub.path[0]].push(mapper(sub));
403 } else formErrors.push(mapper(sub));
404 return {
405 formErrors,
406 fieldErrors
407 };
408 }
409 function formatError(error, _mapper) {
410 const mapper = _mapper || function(issue) {
411 return issue.message;
412 };
413 const fieldErrors = { _errors: [] };
414 const processError = (error) => {
415 for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }));
416 else if (issue.code === "invalid_key") processError({ issues: issue.issues });
417 else if (issue.code === "invalid_element") processError({ issues: issue.issues });
418 else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
419 else {
420 let curr = fieldErrors;
421 let i = 0;
422 while (i < issue.path.length) {
423 const el = issue.path[i];
424 if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
425 else {
426 curr[el] = curr[el] || { _errors: [] };
427 curr[el]._errors.push(mapper(issue));
428 }
429 curr = curr[el];
430 i++;
431 }
432 }
433 };
434 processError(error);
435 return fieldErrors;
436 }
437
438 //#endregion
439 //#region node_modules/zod/v4/core/parse.js
440 var _parse = (_Err) => (schema, value, _ctx, _params) => {
441 const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
442 const result = schema._zod.run({
443 value,
444 issues: []
445 }, ctx);
446 if (result instanceof Promise) throw new $ZodAsyncError();
447 if (result.issues.length) {
448 const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
449 captureStackTrace(e, _params?.callee);
450 throw e;
451 }
452 return result.value;
453 };
454 var parse$1 = /* @__PURE__*/ _parse($ZodRealError);
455 var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
456 const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
457 let result = schema._zod.run({
458 value,
459 issues: []
460 }, ctx);
461 if (result instanceof Promise) result = await result;
462 if (result.issues.length) {
463 const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
464 captureStackTrace(e, params?.callee);
465 throw e;
466 }
467 return result.value;
468 };
469 var parseAsync$1 = /* @__PURE__*/ _parseAsync($ZodRealError);
470 var _safeParse = (_Err) => (schema, value, _ctx) => {
471 const ctx = _ctx ? {
472 ..._ctx,
473 async: false
474 } : { async: false };
475 const result = schema._zod.run({
476 value,
477 issues: []
478 }, ctx);
479 if (result instanceof Promise) throw new $ZodAsyncError();
480 return result.issues.length ? {
481 success: false,
482 error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
483 } : {
484 success: true,
485 data: result.value
486 };
487 };
488 var safeParse$2 = /* @__PURE__*/ _safeParse($ZodRealError);
489 var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
490 const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
491 let result = schema._zod.run({
492 value,
493 issues: []
494 }, ctx);
495 if (result instanceof Promise) result = await result;
496 return result.issues.length ? {
497 success: false,
498 error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
499 } : {
500 success: true,
501 data: result.value
502 };
503 };
504 var safeParseAsync$2 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
505
506 //#endregion
507 //#region node_modules/zod/v4/core/regexes.js
508 var cuid = /^[cC][^\s-]{8,}$/;
509 var cuid2 = /^[0-9a-z]+$/;
510 var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
511 var xid = /^[0-9a-vA-V]{20}$/;
512 var ksuid = /^[A-Za-z0-9]{27}$/;
513 var nanoid = /^[a-zA-Z0-9_-]{21}$/;
514 /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
515 var duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
516 /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
517 var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
518 /** Returns a regex for validating an RFC 4122 UUID.
519 *
520 * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
521 var uuid = (version) => {
522 if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
523 return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
524 };
525 /** Practical email validation */
526 var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
527 var _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
528 function emoji() {
529 return new RegExp(_emoji$1, "u");
530 }
531 var ipv4 = /^(?:(?: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])$/;
532 var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
533 var cidrv4 = /^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/;
534 var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
535 var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
536 var base64url = /^[A-Za-z0-9_-]*$/;
537 var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
538 var e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
539 var dateSource = `(?:(?:\\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])))`;
540 var date$1 = /*@__PURE__*/ new RegExp(`^${dateSource}$`);
541 function timeSource(args) {
542 const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
543 return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
544 }
545 function time$1(args) {
546 return new RegExp(`^${timeSource(args)}$`);
547 }
548 __name(time$1, "time");
549 function datetime$1(args) {
550 const time = timeSource({ precision: args.precision });
551 const opts = ["Z"];
552 if (args.local) opts.push("");
553 if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
554 const timeRegex = `${time}(?:${opts.join("|")})`;
555 return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
556 }
557 __name(datetime$1, "datetime");
558 var string$1 = /* @__PURE__ */ __name((params) => {
559 const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
560 return new RegExp(`^${regex}$`);
561 }, "string");
562 var integer = /^\d+$/;
563 var number$1 = /^-?\d+(?:\.\d+)?/i;
564 var boolean$1 = /true|false/i;
565 var _null$2 = /null/i;
566 var lowercase = /^[^A-Z]*$/;
567 var uppercase = /^[^a-z]*$/;
568
569 //#endregion
570 //#region node_modules/zod/v4/core/checks.js
571 var $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
572 var _a;
573 inst._zod ?? (inst._zod = {});
574 inst._zod.def = def;
575 (_a = inst._zod).onattach ?? (_a.onattach = []);
576 });
577 var numericOriginMap = {
578 number: "number",
579 bigint: "bigint",
580 object: "date"
581 };
582 var $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => {
583 $ZodCheck.init(inst, def);
584 const origin = numericOriginMap[typeof def.value];
585 inst._zod.onattach.push((inst) => {
586 const bag = inst._zod.bag;
587 const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
588 if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
589 else bag.exclusiveMaximum = def.value;
590 });
591 inst._zod.check = (payload) => {
592 if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
593 payload.issues.push({
594 origin,
595 code: "too_big",
596 maximum: def.value,
597 input: payload.value,
598 inclusive: def.inclusive,
599 inst,
600 continue: !def.abort
601 });
602 };
603 });
604 var $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => {
605 $ZodCheck.init(inst, def);
606 const origin = numericOriginMap[typeof def.value];
607 inst._zod.onattach.push((inst) => {
608 const bag = inst._zod.bag;
609 const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
610 if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
611 else bag.exclusiveMinimum = def.value;
612 });
613 inst._zod.check = (payload) => {
614 if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
615 payload.issues.push({
616 origin,
617 code: "too_small",
618 minimum: def.value,
619 input: payload.value,
620 inclusive: def.inclusive,
621 inst,
622 continue: !def.abort
623 });
624 };
625 });
626 var $ZodCheckMultipleOf = /*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => {
627 $ZodCheck.init(inst, def);
628 inst._zod.onattach.push((inst) => {
629 var _a;
630 (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
631 });
632 inst._zod.check = (payload) => {
633 if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
634 if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder$1(payload.value, def.value) === 0) return;
635 payload.issues.push({
636 origin: typeof payload.value,
637 code: "not_multiple_of",
638 divisor: def.value,
639 input: payload.value,
640 inst,
641 continue: !def.abort
642 });
643 };
644 });
645 var $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => {
646 $ZodCheck.init(inst, def);
647 def.format = def.format || "float64";
648 const isInt = def.format?.includes("int");
649 const origin = isInt ? "int" : "number";
650 const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
651 inst._zod.onattach.push((inst) => {
652 const bag = inst._zod.bag;
653 bag.format = def.format;
654 bag.minimum = minimum;
655 bag.maximum = maximum;
656 if (isInt) bag.pattern = integer;
657 });
658 inst._zod.check = (payload) => {
659 const input = payload.value;
660 if (isInt) {
661 if (!Number.isInteger(input)) {
662 payload.issues.push({
663 expected: origin,
664 format: def.format,
665 code: "invalid_type",
666 input,
667 inst
668 });
669 return;
670 }
671 if (!Number.isSafeInteger(input)) {
672 if (input > 0) payload.issues.push({
673 input,
674 code: "too_big",
675 maximum: Number.MAX_SAFE_INTEGER,
676 note: "Integers must be within the safe integer range.",
677 inst,
678 origin,
679 continue: !def.abort
680 });
681 else payload.issues.push({
682 input,
683 code: "too_small",
684 minimum: Number.MIN_SAFE_INTEGER,
685 note: "Integers must be within the safe integer range.",
686 inst,
687 origin,
688 continue: !def.abort
689 });
690 return;
691 }
692 }
693 if (input < minimum) payload.issues.push({
694 origin: "number",
695 input,
696 code: "too_small",
697 minimum,
698 inclusive: true,
699 inst,
700 continue: !def.abort
701 });
702 if (input > maximum) payload.issues.push({
703 origin: "number",
704 input,
705 code: "too_big",
706 maximum,
707 inst
708 });
709 };
710 });
711 var $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => {
712 var _a;
713 $ZodCheck.init(inst, def);
714 (_a = inst._zod.def).when ?? (_a.when = (payload) => {
715 const val = payload.value;
716 return !nullish(val) && val.length !== void 0;
717 });
718 inst._zod.onattach.push((inst) => {
719 const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
720 if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
721 });
722 inst._zod.check = (payload) => {
723 const input = payload.value;
724 if (input.length <= def.maximum) return;
725 const origin = getLengthableOrigin(input);
726 payload.issues.push({
727 origin,
728 code: "too_big",
729 maximum: def.maximum,
730 inclusive: true,
731 input,
732 inst,
733 continue: !def.abort
734 });
735 };
736 });
737 var $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
738 var _a;
739 $ZodCheck.init(inst, def);
740 (_a = inst._zod.def).when ?? (_a.when = (payload) => {
741 const val = payload.value;
742 return !nullish(val) && val.length !== void 0;
743 });
744 inst._zod.onattach.push((inst) => {
745 const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
746 if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
747 });
748 inst._zod.check = (payload) => {
749 const input = payload.value;
750 if (input.length >= def.minimum) return;
751 const origin = getLengthableOrigin(input);
752 payload.issues.push({
753 origin,
754 code: "too_small",
755 minimum: def.minimum,
756 inclusive: true,
757 input,
758 inst,
759 continue: !def.abort
760 });
761 };
762 });
763 var $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => {
764 var _a;
765 $ZodCheck.init(inst, def);
766 (_a = inst._zod.def).when ?? (_a.when = (payload) => {
767 const val = payload.value;
768 return !nullish(val) && val.length !== void 0;
769 });
770 inst._zod.onattach.push((inst) => {
771 const bag = inst._zod.bag;
772 bag.minimum = def.length;
773 bag.maximum = def.length;
774 bag.length = def.length;
775 });
776 inst._zod.check = (payload) => {
777 const input = payload.value;
778 const length = input.length;
779 if (length === def.length) return;
780 const origin = getLengthableOrigin(input);
781 const tooBig = length > def.length;
782 payload.issues.push({
783 origin,
784 ...tooBig ? {
785 code: "too_big",
786 maximum: def.length
787 } : {
788 code: "too_small",
789 minimum: def.length
790 },
791 inclusive: true,
792 exact: true,
793 input: payload.value,
794 inst,
795 continue: !def.abort
796 });
797 };
798 });
799 var $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => {
800 var _a;
801 var _b;
802 $ZodCheck.init(inst, def);
803 inst._zod.onattach.push((inst) => {
804 const bag = inst._zod.bag;
805 bag.format = def.format;
806 if (def.pattern) {
807 bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
808 bag.patterns.add(def.pattern);
809 }
810 });
811 if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
812 def.pattern.lastIndex = 0;
813 if (def.pattern.test(payload.value)) return;
814 payload.issues.push({
815 origin: "string",
816 code: "invalid_format",
817 format: def.format,
818 input: payload.value,
819 ...def.pattern ? { pattern: def.pattern.toString() } : {},
820 inst,
821 continue: !def.abort
822 });
823 });
824 else (_b = inst._zod).check ?? (_b.check = () => {});
825 });
826 var $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
827 $ZodCheckStringFormat.init(inst, def);
828 inst._zod.check = (payload) => {
829 def.pattern.lastIndex = 0;
830 if (def.pattern.test(payload.value)) return;
831 payload.issues.push({
832 origin: "string",
833 code: "invalid_format",
834 format: "regex",
835 input: payload.value,
836 pattern: def.pattern.toString(),
837 inst,
838 continue: !def.abort
839 });
840 };
841 });
842 var $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
843 def.pattern ?? (def.pattern = lowercase);
844 $ZodCheckStringFormat.init(inst, def);
845 });
846 var $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
847 def.pattern ?? (def.pattern = uppercase);
848 $ZodCheckStringFormat.init(inst, def);
849 });
850 var $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => {
851 $ZodCheck.init(inst, def);
852 const escapedRegex = escapeRegex(def.includes);
853 const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
854 def.pattern = pattern;
855 inst._zod.onattach.push((inst) => {
856 const bag = inst._zod.bag;
857 bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
858 bag.patterns.add(pattern);
859 });
860 inst._zod.check = (payload) => {
861 if (payload.value.includes(def.includes, def.position)) return;
862 payload.issues.push({
863 origin: "string",
864 code: "invalid_format",
865 format: "includes",
866 includes: def.includes,
867 input: payload.value,
868 inst,
869 continue: !def.abort
870 });
871 };
872 });
873 var $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
874 $ZodCheck.init(inst, def);
875 const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
876 def.pattern ?? (def.pattern = pattern);
877 inst._zod.onattach.push((inst) => {
878 const bag = inst._zod.bag;
879 bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
880 bag.patterns.add(pattern);
881 });
882 inst._zod.check = (payload) => {
883 if (payload.value.startsWith(def.prefix)) return;
884 payload.issues.push({
885 origin: "string",
886 code: "invalid_format",
887 format: "starts_with",
888 prefix: def.prefix,
889 input: payload.value,
890 inst,
891 continue: !def.abort
892 });
893 };
894 });
895 var $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
896 $ZodCheck.init(inst, def);
897 const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
898 def.pattern ?? (def.pattern = pattern);
899 inst._zod.onattach.push((inst) => {
900 const bag = inst._zod.bag;
901 bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
902 bag.patterns.add(pattern);
903 });
904 inst._zod.check = (payload) => {
905 if (payload.value.endsWith(def.suffix)) return;
906 payload.issues.push({
907 origin: "string",
908 code: "invalid_format",
909 format: "ends_with",
910 suffix: def.suffix,
911 input: payload.value,
912 inst,
913 continue: !def.abort
914 });
915 };
916 });
917 var $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
918 $ZodCheck.init(inst, def);
919 inst._zod.check = (payload) => {
920 payload.value = def.tx(payload.value);
921 };
922 });
923
924 //#endregion
925 //#region node_modules/zod/v4/core/doc.js
926 var Doc = class {
927 constructor(args = []) {
928 this.content = [];
929 this.indent = 0;
930 if (this) this.args = args;
931 }
932 indented(fn) {
933 this.indent += 1;
934 fn(this);
935 this.indent -= 1;
936 }
937 write(arg) {
938 if (typeof arg === "function") {
939 arg(this, { execution: "sync" });
940 arg(this, { execution: "async" });
941 return;
942 }
943 const lines = arg.split("\n").filter((x) => x);
944 const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
945 const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
946 for (const line of dedented) this.content.push(line);
947 }
948 compile() {
949 const F = Function;
950 const args = this?.args;
951 const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
952 return new F(...args, lines.join("\n"));
953 }
954 };
955
956 //#endregion
957 //#region node_modules/zod/v4/core/versions.js
958 var version = {
959 major: 4,
960 minor: 0,
961 patch: 0
962 };
963
964 //#endregion
965 //#region node_modules/zod/v4/core/schemas.js
966 var $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
967 var _a;
968 inst ?? (inst = {});
969 inst._zod.def = def;
970 inst._zod.bag = inst._zod.bag || {};
971 inst._zod.version = version;
972 const checks = [...inst._zod.def.checks ?? []];
973 if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
974 for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
975 if (checks.length === 0) {
976 (_a = inst._zod).deferred ?? (_a.deferred = []);
977 inst._zod.deferred?.push(() => {
978 inst._zod.run = inst._zod.parse;
979 });
980 } else {
981 const runChecks = (payload, checks, ctx) => {
982 let isAborted = aborted(payload);
983 let asyncResult;
984 for (const ch of checks) {
985 if (ch._zod.def.when) {
986 if (!ch._zod.def.when(payload)) continue;
987 } else if (isAborted) continue;
988 const currLen = payload.issues.length;
989 const _ = ch._zod.check(payload);
990 if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
991 if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
992 await _;
993 if (payload.issues.length === currLen) return;
994 if (!isAborted) isAborted = aborted(payload, currLen);
995 });
996 else {
997 if (payload.issues.length === currLen) continue;
998 if (!isAborted) isAborted = aborted(payload, currLen);
999 }
1000 }
1001 if (asyncResult) return asyncResult.then(() => {
1002 return payload;
1003 });
1004 return payload;
1005 };
1006 inst._zod.run = (payload, ctx) => {
1007 const result = inst._zod.parse(payload, ctx);
1008 if (result instanceof Promise) {
1009 if (ctx.async === false) throw new $ZodAsyncError();
1010 return result.then((result) => runChecks(result, checks, ctx));
1011 }
1012 return runChecks(result, checks, ctx);
1013 };
1014 }
1015 inst["~standard"] = {
1016 validate: (value) => {
1017 try {
1018 const r = safeParse$2(inst, value);
1019 return r.success ? { value: r.data } : { issues: r.error?.issues };
1020 } catch (_) {
1021 return safeParseAsync$2(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
1022 }
1023 },
1024 vendor: "zod",
1025 version: 1
1026 };
1027 });
1028 var $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
1029 $ZodType.init(inst, def);
1030 inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
1031 inst._zod.parse = (payload, _) => {
1032 if (def.coerce) try {
1033 payload.value = String(payload.value);
1034 } catch (_) {}
1035 if (typeof payload.value === "string") return payload;
1036 payload.issues.push({
1037 expected: "string",
1038 code: "invalid_type",
1039 input: payload.value,
1040 inst
1041 });
1042 return payload;
1043 };
1044 });
1045 var $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => {
1046 $ZodCheckStringFormat.init(inst, def);
1047 $ZodString.init(inst, def);
1048 });
1049 var $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
1050 def.pattern ?? (def.pattern = guid);
1051 $ZodStringFormat.init(inst, def);
1052 });
1053 var $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
1054 if (def.version) {
1055 const v = {
1056 v1: 1,
1057 v2: 2,
1058 v3: 3,
1059 v4: 4,
1060 v5: 5,
1061 v6: 6,
1062 v7: 7,
1063 v8: 8
1064 }[def.version];
1065 if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
1066 def.pattern ?? (def.pattern = uuid(v));
1067 } else def.pattern ?? (def.pattern = uuid());
1068 $ZodStringFormat.init(inst, def);
1069 });
1070 var $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
1071 def.pattern ?? (def.pattern = email);
1072 $ZodStringFormat.init(inst, def);
1073 });
1074 var $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
1075 $ZodStringFormat.init(inst, def);
1076 inst._zod.check = (payload) => {
1077 try {
1078 const orig = payload.value;
1079 const url = new URL(orig);
1080 const href = url.href;
1081 if (def.hostname) {
1082 def.hostname.lastIndex = 0;
1083 if (!def.hostname.test(url.hostname)) payload.issues.push({
1084 code: "invalid_format",
1085 format: "url",
1086 note: "Invalid hostname",
1087 pattern: hostname.source,
1088 input: payload.value,
1089 inst,
1090 continue: !def.abort
1091 });
1092 }
1093 if (def.protocol) {
1094 def.protocol.lastIndex = 0;
1095 if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
1096 code: "invalid_format",
1097 format: "url",
1098 note: "Invalid protocol",
1099 pattern: def.protocol.source,
1100 input: payload.value,
1101 inst,
1102 continue: !def.abort
1103 });
1104 }
1105 if (!orig.endsWith("/") && href.endsWith("/")) payload.value = href.slice(0, -1);
1106 else payload.value = href;
1107 return;
1108 } catch (_) {
1109 payload.issues.push({
1110 code: "invalid_format",
1111 format: "url",
1112 input: payload.value,
1113 inst,
1114 continue: !def.abort
1115 });
1116 }
1117 };
1118 });
1119 var $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => {
1120 def.pattern ?? (def.pattern = emoji());
1121 $ZodStringFormat.init(inst, def);
1122 });
1123 var $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => {
1124 def.pattern ?? (def.pattern = nanoid);
1125 $ZodStringFormat.init(inst, def);
1126 });
1127 var $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => {
1128 def.pattern ?? (def.pattern = cuid);
1129 $ZodStringFormat.init(inst, def);
1130 });
1131 var $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => {
1132 def.pattern ?? (def.pattern = cuid2);
1133 $ZodStringFormat.init(inst, def);
1134 });
1135 var $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => {
1136 def.pattern ?? (def.pattern = ulid);
1137 $ZodStringFormat.init(inst, def);
1138 });
1139 var $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => {
1140 def.pattern ?? (def.pattern = xid);
1141 $ZodStringFormat.init(inst, def);
1142 });
1143 var $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
1144 def.pattern ?? (def.pattern = ksuid);
1145 $ZodStringFormat.init(inst, def);
1146 });
1147 var $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
1148 def.pattern ?? (def.pattern = datetime$1(def));
1149 $ZodStringFormat.init(inst, def);
1150 });
1151 var $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
1152 def.pattern ?? (def.pattern = date$1);
1153 $ZodStringFormat.init(inst, def);
1154 });
1155 var $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => {
1156 def.pattern ?? (def.pattern = time$1(def));
1157 $ZodStringFormat.init(inst, def);
1158 });
1159 var $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => {
1160 def.pattern ?? (def.pattern = duration$1);
1161 $ZodStringFormat.init(inst, def);
1162 });
1163 var $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
1164 def.pattern ?? (def.pattern = ipv4);
1165 $ZodStringFormat.init(inst, def);
1166 inst._zod.onattach.push((inst) => {
1167 const bag = inst._zod.bag;
1168 bag.format = `ipv4`;
1169 });
1170 });
1171 var $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
1172 def.pattern ?? (def.pattern = ipv6);
1173 $ZodStringFormat.init(inst, def);
1174 inst._zod.onattach.push((inst) => {
1175 const bag = inst._zod.bag;
1176 bag.format = `ipv6`;
1177 });
1178 inst._zod.check = (payload) => {
1179 try {
1180 new URL(`http://[${payload.value}]`);
1181 } catch {
1182 payload.issues.push({
1183 code: "invalid_format",
1184 format: "ipv6",
1185 input: payload.value,
1186 inst,
1187 continue: !def.abort
1188 });
1189 }
1190 };
1191 });
1192 var $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => {
1193 def.pattern ?? (def.pattern = cidrv4);
1194 $ZodStringFormat.init(inst, def);
1195 });
1196 var $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
1197 def.pattern ?? (def.pattern = cidrv6);
1198 $ZodStringFormat.init(inst, def);
1199 inst._zod.check = (payload) => {
1200 const [address, prefix] = payload.value.split("/");
1201 try {
1202 if (!prefix) throw new Error();
1203 const prefixNum = Number(prefix);
1204 if (`${prefixNum}` !== prefix) throw new Error();
1205 if (prefixNum < 0 || prefixNum > 128) throw new Error();
1206 new URL(`http://[${address}]`);
1207 } catch {
1208 payload.issues.push({
1209 code: "invalid_format",
1210 format: "cidrv6",
1211 input: payload.value,
1212 inst,
1213 continue: !def.abort
1214 });
1215 }
1216 };
1217 });
1218 function isValidBase64(data) {
1219 if (data === "") return true;
1220 if (data.length % 4 !== 0) return false;
1221 try {
1222 atob(data);
1223 return true;
1224 } catch {
1225 return false;
1226 }
1227 }
1228 var $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
1229 def.pattern ?? (def.pattern = base64);
1230 $ZodStringFormat.init(inst, def);
1231 inst._zod.onattach.push((inst) => {
1232 inst._zod.bag.contentEncoding = "base64";
1233 });
1234 inst._zod.check = (payload) => {
1235 if (isValidBase64(payload.value)) return;
1236 payload.issues.push({
1237 code: "invalid_format",
1238 format: "base64",
1239 input: payload.value,
1240 inst,
1241 continue: !def.abort
1242 });
1243 };
1244 });
1245 function isValidBase64URL(data) {
1246 if (!base64url.test(data)) return false;
1247 const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
1248 return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
1249 }
1250 var $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
1251 def.pattern ?? (def.pattern = base64url);
1252 $ZodStringFormat.init(inst, def);
1253 inst._zod.onattach.push((inst) => {
1254 inst._zod.bag.contentEncoding = "base64url";
1255 });
1256 inst._zod.check = (payload) => {
1257 if (isValidBase64URL(payload.value)) return;
1258 payload.issues.push({
1259 code: "invalid_format",
1260 format: "base64url",
1261 input: payload.value,
1262 inst,
1263 continue: !def.abort
1264 });
1265 };
1266 });
1267 var $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => {
1268 def.pattern ?? (def.pattern = e164);
1269 $ZodStringFormat.init(inst, def);
1270 });
1271 function isValidJWT$1(token, algorithm = null) {
1272 try {
1273 const tokensParts = token.split(".");
1274 if (tokensParts.length !== 3) return false;
1275 const [header] = tokensParts;
1276 if (!header) return false;
1277 const parsedHeader = JSON.parse(atob(header));
1278 if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
1279 if (!parsedHeader.alg) return false;
1280 if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
1281 return true;
1282 } catch {
1283 return false;
1284 }
1285 }
1286 __name(isValidJWT$1, "isValidJWT");
1287 var $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
1288 $ZodStringFormat.init(inst, def);
1289 inst._zod.check = (payload) => {
1290 if (isValidJWT$1(payload.value, def.alg)) return;
1291 payload.issues.push({
1292 code: "invalid_format",
1293 format: "jwt",
1294 input: payload.value,
1295 inst,
1296 continue: !def.abort
1297 });
1298 };
1299 });
1300 var $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
1301 $ZodType.init(inst, def);
1302 inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
1303 inst._zod.parse = (payload, _ctx) => {
1304 if (def.coerce) try {
1305 payload.value = Number(payload.value);
1306 } catch (_) {}
1307 const input = payload.value;
1308 if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
1309 const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
1310 payload.issues.push({
1311 expected: "number",
1312 code: "invalid_type",
1313 input,
1314 inst,
1315 ...received ? { received } : {}
1316 });
1317 return payload;
1318 };
1319 });
1320 var $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
1321 $ZodCheckNumberFormat.init(inst, def);
1322 $ZodNumber.init(inst, def);
1323 });
1324 var $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
1325 $ZodType.init(inst, def);
1326 inst._zod.pattern = boolean$1;
1327 inst._zod.parse = (payload, _ctx) => {
1328 if (def.coerce) try {
1329 payload.value = Boolean(payload.value);
1330 } catch (_) {}
1331 const input = payload.value;
1332 if (typeof input === "boolean") return payload;
1333 payload.issues.push({
1334 expected: "boolean",
1335 code: "invalid_type",
1336 input,
1337 inst
1338 });
1339 return payload;
1340 };
1341 });
1342 var $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => {
1343 $ZodType.init(inst, def);
1344 inst._zod.pattern = _null$2;
1345 inst._zod.values = /* @__PURE__ */ new Set([null]);
1346 inst._zod.parse = (payload, _ctx) => {
1347 const input = payload.value;
1348 if (input === null) return payload;
1349 payload.issues.push({
1350 expected: "null",
1351 code: "invalid_type",
1352 input,
1353 inst
1354 });
1355 return payload;
1356 };
1357 });
1358 var $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
1359 $ZodType.init(inst, def);
1360 inst._zod.parse = (payload) => payload;
1361 });
1362 var $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
1363 $ZodType.init(inst, def);
1364 inst._zod.parse = (payload, _ctx) => {
1365 payload.issues.push({
1366 expected: "never",
1367 code: "invalid_type",
1368 input: payload.value,
1369 inst
1370 });
1371 return payload;
1372 };
1373 });
1374 function handleArrayResult(result, final, index) {
1375 if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
1376 final.value[index] = result.value;
1377 }
1378 var $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
1379 $ZodType.init(inst, def);
1380 inst._zod.parse = (payload, ctx) => {
1381 const input = payload.value;
1382 if (!Array.isArray(input)) {
1383 payload.issues.push({
1384 expected: "array",
1385 code: "invalid_type",
1386 input,
1387 inst
1388 });
1389 return payload;
1390 }
1391 payload.value = Array(input.length);
1392 const proms = [];
1393 for (let i = 0; i < input.length; i++) {
1394 const item = input[i];
1395 const result = def.element._zod.run({
1396 value: item,
1397 issues: []
1398 }, ctx);
1399 if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
1400 else handleArrayResult(result, payload, i);
1401 }
1402 if (proms.length) return Promise.all(proms).then(() => payload);
1403 return payload;
1404 };
1405 });
1406 function handleObjectResult(result, final, key) {
1407 if (result.issues.length) final.issues.push(...prefixIssues(key, result.issues));
1408 final.value[key] = result.value;
1409 }
1410 function handleOptionalObjectResult(result, final, key, input) {
1411 if (result.issues.length) if (input[key] === void 0) if (key in input) final.value[key] = void 0;
1412 else final.value[key] = result.value;
1413 else final.issues.push(...prefixIssues(key, result.issues));
1414 else if (result.value === void 0) {
1415 if (key in input) final.value[key] = void 0;
1416 } else final.value[key] = result.value;
1417 }
1418 var $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1419 $ZodType.init(inst, def);
1420 const _normalized = cached(() => {
1421 const keys = Object.keys(def.shape);
1422 for (const k of keys) if (!(def.shape[k] instanceof $ZodType)) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1423 const okeys = optionalKeys(def.shape);
1424 return {
1425 shape: def.shape,
1426 keys,
1427 keySet: new Set(keys),
1428 numKeys: keys.length,
1429 optionalKeys: new Set(okeys)
1430 };
1431 });
1432 defineLazy(inst._zod, "propValues", () => {
1433 const shape = def.shape;
1434 const propValues = {};
1435 for (const key in shape) {
1436 const field = shape[key]._zod;
1437 if (field.values) {
1438 propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
1439 for (const v of field.values) propValues[key].add(v);
1440 }
1441 }
1442 return propValues;
1443 });
1444 const generateFastpass = (shape) => {
1445 const doc = new Doc([
1446 "shape",
1447 "payload",
1448 "ctx"
1449 ]);
1450 const normalized = _normalized.value;
1451 const parseStr = (key) => {
1452 const k = esc(key);
1453 return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
1454 };
1455 doc.write(`const input = payload.value;`);
1456 const ids = Object.create(null);
1457 let counter = 0;
1458 for (const key of normalized.keys) ids[key] = `key_${counter++}`;
1459 doc.write(`const newResult = {}`);
1460 for (const key of normalized.keys) if (normalized.optionalKeys.has(key)) {
1461 const id = ids[key];
1462 doc.write(`const ${id} = ${parseStr(key)};`);
1463 const k = esc(key);
1464 doc.write(`
1465 if (${id}.issues.length) {
1466 if (input[${k}] === undefined) {
1467 if (${k} in input) {
1468 newResult[${k}] = undefined;
1469 }
1470 } else {
1471 payload.issues = payload.issues.concat(
1472 ${id}.issues.map((iss) => ({
1473 ...iss,
1474 path: iss.path ? [${k}, ...iss.path] : [${k}],
1475 }))
1476 );
1477 }
1478 } else if (${id}.value === undefined) {
1479 if (${k} in input) newResult[${k}] = undefined;
1480 } else {
1481 newResult[${k}] = ${id}.value;
1482 }
1483 `);
1484 } else {
1485 const id = ids[key];
1486 doc.write(`const ${id} = ${parseStr(key)};`);
1487 doc.write(`
1488 if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1489 ...iss,
1490 path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
1491 })));`);
1492 doc.write(`newResult[${esc(key)}] = ${id}.value`);
1493 }
1494 doc.write(`payload.value = newResult;`);
1495 doc.write(`return payload;`);
1496 const fn = doc.compile();
1497 return (payload, ctx) => fn(shape, payload, ctx);
1498 };
1499 let fastpass;
1500 const isObject$1 = isObject;
1501 const jit = !globalConfig.jitless;
1502 const allowsEval$1 = allowsEval;
1503 const fastEnabled = jit && allowsEval$1.value;
1504 const catchall = def.catchall;
1505 let value;
1506 inst._zod.parse = (payload, ctx) => {
1507 value ?? (value = _normalized.value);
1508 const input = payload.value;
1509 if (!isObject$1(input)) {
1510 payload.issues.push({
1511 expected: "object",
1512 code: "invalid_type",
1513 input,
1514 inst
1515 });
1516 return payload;
1517 }
1518 const proms = [];
1519 if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1520 if (!fastpass) fastpass = generateFastpass(def.shape);
1521 payload = fastpass(payload, ctx);
1522 } else {
1523 payload.value = {};
1524 const shape = value.shape;
1525 for (const key of value.keys) {
1526 const el = shape[key];
1527 const r = el._zod.run({
1528 value: input[key],
1529 issues: []
1530 }, ctx);
1531 const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
1532 if (r instanceof Promise) proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key)));
1533 else if (isOptional) handleOptionalObjectResult(r, payload, key, input);
1534 else handleObjectResult(r, payload, key);
1535 }
1536 }
1537 if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
1538 const unrecognized = [];
1539 const keySet = value.keySet;
1540 const _catchall = catchall._zod;
1541 const t = _catchall.def.type;
1542 for (const key of Object.keys(input)) {
1543 if (keySet.has(key)) continue;
1544 if (t === "never") {
1545 unrecognized.push(key);
1546 continue;
1547 }
1548 const r = _catchall.run({
1549 value: input[key],
1550 issues: []
1551 }, ctx);
1552 if (r instanceof Promise) proms.push(r.then((r) => handleObjectResult(r, payload, key)));
1553 else handleObjectResult(r, payload, key);
1554 }
1555 if (unrecognized.length) payload.issues.push({
1556 code: "unrecognized_keys",
1557 keys: unrecognized,
1558 input,
1559 inst
1560 });
1561 if (!proms.length) return payload;
1562 return Promise.all(proms).then(() => {
1563 return payload;
1564 });
1565 };
1566 });
1567 function handleUnionResults(results, final, inst, ctx) {
1568 for (const result of results) if (result.issues.length === 0) {
1569 final.value = result.value;
1570 return final;
1571 }
1572 final.issues.push({
1573 code: "invalid_union",
1574 input: final.value,
1575 inst,
1576 errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1577 });
1578 return final;
1579 }
1580 var $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
1581 $ZodType.init(inst, def);
1582 defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
1583 defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
1584 defineLazy(inst._zod, "values", () => {
1585 if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1586 });
1587 defineLazy(inst._zod, "pattern", () => {
1588 if (def.options.every((o) => o._zod.pattern)) {
1589 const patterns = def.options.map((o) => o._zod.pattern);
1590 return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1591 }
1592 });
1593 inst._zod.parse = (payload, ctx) => {
1594 let async = false;
1595 const results = [];
1596 for (const option of def.options) {
1597 const result = option._zod.run({
1598 value: payload.value,
1599 issues: []
1600 }, ctx);
1601 if (result instanceof Promise) {
1602 results.push(result);
1603 async = true;
1604 } else {
1605 if (result.issues.length === 0) return result;
1606 results.push(result);
1607 }
1608 }
1609 if (!async) return handleUnionResults(results, payload, inst, ctx);
1610 return Promise.all(results).then((results) => {
1611 return handleUnionResults(results, payload, inst, ctx);
1612 });
1613 };
1614 });
1615 var $ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
1616 $ZodUnion.init(inst, def);
1617 const _super = inst._zod.parse;
1618 defineLazy(inst._zod, "propValues", () => {
1619 const propValues = {};
1620 for (const option of def.options) {
1621 const pv = option._zod.propValues;
1622 if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
1623 for (const [k, v] of Object.entries(pv)) {
1624 if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set();
1625 for (const val of v) propValues[k].add(val);
1626 }
1627 }
1628 return propValues;
1629 });
1630 const disc = cached(() => {
1631 const opts = def.options;
1632 const map = /* @__PURE__ */ new Map();
1633 for (const o of opts) {
1634 const values = o._zod.propValues[def.discriminator];
1635 if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
1636 for (const v of values) {
1637 if (map.has(v)) throw new Error(`Duplicate discriminator value "${String(v)}"`);
1638 map.set(v, o);
1639 }
1640 }
1641 return map;
1642 });
1643 inst._zod.parse = (payload, ctx) => {
1644 const input = payload.value;
1645 if (!isObject(input)) {
1646 payload.issues.push({
1647 code: "invalid_type",
1648 expected: "object",
1649 input,
1650 inst
1651 });
1652 return payload;
1653 }
1654 const opt = disc.value.get(input?.[def.discriminator]);
1655 if (opt) return opt._zod.run(payload, ctx);
1656 if (def.unionFallback) return _super(payload, ctx);
1657 payload.issues.push({
1658 code: "invalid_union",
1659 errors: [],
1660 note: "No matching discriminator",
1661 input,
1662 path: [def.discriminator],
1663 inst
1664 });
1665 return payload;
1666 };
1667 });
1668 var $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
1669 $ZodType.init(inst, def);
1670 inst._zod.parse = (payload, ctx) => {
1671 const input = payload.value;
1672 const left = def.left._zod.run({
1673 value: input,
1674 issues: []
1675 }, ctx);
1676 const right = def.right._zod.run({
1677 value: input,
1678 issues: []
1679 }, ctx);
1680 if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => {
1681 return handleIntersectionResults(payload, left, right);
1682 });
1683 return handleIntersectionResults(payload, left, right);
1684 };
1685 });
1686 function mergeValues$1(a, b) {
1687 if (a === b) return {
1688 valid: true,
1689 data: a
1690 };
1691 if (a instanceof Date && b instanceof Date && +a === +b) return {
1692 valid: true,
1693 data: a
1694 };
1695 if (isPlainObject$1(a) && isPlainObject$1(b)) {
1696 const bKeys = Object.keys(b);
1697 const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1698 const newObj = {
1699 ...a,
1700 ...b
1701 };
1702 for (const key of sharedKeys) {
1703 const sharedValue = mergeValues$1(a[key], b[key]);
1704 if (!sharedValue.valid) return {
1705 valid: false,
1706 mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
1707 };
1708 newObj[key] = sharedValue.data;
1709 }
1710 return {
1711 valid: true,
1712 data: newObj
1713 };
1714 }
1715 if (Array.isArray(a) && Array.isArray(b)) {
1716 if (a.length !== b.length) return {
1717 valid: false,
1718 mergeErrorPath: []
1719 };
1720 const newArray = [];
1721 for (let index = 0; index < a.length; index++) {
1722 const itemA = a[index];
1723 const itemB = b[index];
1724 const sharedValue = mergeValues$1(itemA, itemB);
1725 if (!sharedValue.valid) return {
1726 valid: false,
1727 mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
1728 };
1729 newArray.push(sharedValue.data);
1730 }
1731 return {
1732 valid: true,
1733 data: newArray
1734 };
1735 }
1736 return {
1737 valid: false,
1738 mergeErrorPath: []
1739 };
1740 }
1741 __name(mergeValues$1, "mergeValues");
1742 function handleIntersectionResults(result, left, right) {
1743 if (left.issues.length) result.issues.push(...left.issues);
1744 if (right.issues.length) result.issues.push(...right.issues);
1745 if (aborted(result)) return result;
1746 const merged = mergeValues$1(left.value, right.value);
1747 if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
1748 result.value = merged.data;
1749 return result;
1750 }
1751 var $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
1752 $ZodType.init(inst, def);
1753 inst._zod.parse = (payload, ctx) => {
1754 const input = payload.value;
1755 if (!isPlainObject$1(input)) {
1756 payload.issues.push({
1757 expected: "record",
1758 code: "invalid_type",
1759 input,
1760 inst
1761 });
1762 return payload;
1763 }
1764 const proms = [];
1765 if (def.keyType._zod.values) {
1766 const values = def.keyType._zod.values;
1767 payload.value = {};
1768 for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
1769 const result = def.valueType._zod.run({
1770 value: input[key],
1771 issues: []
1772 }, ctx);
1773 if (result instanceof Promise) proms.push(result.then((result) => {
1774 if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1775 payload.value[key] = result.value;
1776 }));
1777 else {
1778 if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1779 payload.value[key] = result.value;
1780 }
1781 }
1782 let unrecognized;
1783 for (const key in input) if (!values.has(key)) {
1784 unrecognized = unrecognized ?? [];
1785 unrecognized.push(key);
1786 }
1787 if (unrecognized && unrecognized.length > 0) payload.issues.push({
1788 code: "unrecognized_keys",
1789 input,
1790 inst,
1791 keys: unrecognized
1792 });
1793 } else {
1794 payload.value = {};
1795 for (const key of Reflect.ownKeys(input)) {
1796 if (key === "__proto__") continue;
1797 const keyResult = def.keyType._zod.run({
1798 value: key,
1799 issues: []
1800 }, ctx);
1801 if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
1802 if (keyResult.issues.length) {
1803 payload.issues.push({
1804 origin: "record",
1805 code: "invalid_key",
1806 issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1807 input: key,
1808 path: [key],
1809 inst
1810 });
1811 payload.value[keyResult.value] = keyResult.value;
1812 continue;
1813 }
1814 const result = def.valueType._zod.run({
1815 value: input[key],
1816 issues: []
1817 }, ctx);
1818 if (result instanceof Promise) proms.push(result.then((result) => {
1819 if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1820 payload.value[keyResult.value] = result.value;
1821 }));
1822 else {
1823 if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1824 payload.value[keyResult.value] = result.value;
1825 }
1826 }
1827 }
1828 if (proms.length) return Promise.all(proms).then(() => payload);
1829 return payload;
1830 };
1831 });
1832 var $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
1833 $ZodType.init(inst, def);
1834 const values = getEnumValues(def.entries);
1835 inst._zod.values = new Set(values);
1836 inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
1837 inst._zod.parse = (payload, _ctx) => {
1838 const input = payload.value;
1839 if (inst._zod.values.has(input)) return payload;
1840 payload.issues.push({
1841 code: "invalid_value",
1842 values,
1843 input,
1844 inst
1845 });
1846 return payload;
1847 };
1848 });
1849 var $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => {
1850 $ZodType.init(inst, def);
1851 inst._zod.values = new Set(def.values);
1852 inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`);
1853 inst._zod.parse = (payload, _ctx) => {
1854 const input = payload.value;
1855 if (inst._zod.values.has(input)) return payload;
1856 payload.issues.push({
1857 code: "invalid_value",
1858 values: def.values,
1859 input,
1860 inst
1861 });
1862 return payload;
1863 };
1864 });
1865 var $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
1866 $ZodType.init(inst, def);
1867 inst._zod.parse = (payload, _ctx) => {
1868 const _out = def.transform(payload.value, payload);
1869 if (_ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
1870 payload.value = output;
1871 return payload;
1872 });
1873 if (_out instanceof Promise) throw new $ZodAsyncError();
1874 payload.value = _out;
1875 return payload;
1876 };
1877 });
1878 var $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
1879 $ZodType.init(inst, def);
1880 inst._zod.optin = "optional";
1881 inst._zod.optout = "optional";
1882 defineLazy(inst._zod, "values", () => {
1883 return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
1884 });
1885 defineLazy(inst._zod, "pattern", () => {
1886 const pattern = def.innerType._zod.pattern;
1887 return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
1888 });
1889 inst._zod.parse = (payload, ctx) => {
1890 if (def.innerType._zod.optin === "optional") return def.innerType._zod.run(payload, ctx);
1891 if (payload.value === void 0) return payload;
1892 return def.innerType._zod.run(payload, ctx);
1893 };
1894 });
1895 var $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
1896 $ZodType.init(inst, def);
1897 defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1898 defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1899 defineLazy(inst._zod, "pattern", () => {
1900 const pattern = def.innerType._zod.pattern;
1901 return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
1902 });
1903 defineLazy(inst._zod, "values", () => {
1904 return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
1905 });
1906 inst._zod.parse = (payload, ctx) => {
1907 if (payload.value === null) return payload;
1908 return def.innerType._zod.run(payload, ctx);
1909 };
1910 });
1911 var $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
1912 $ZodType.init(inst, def);
1913 inst._zod.optin = "optional";
1914 defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1915 inst._zod.parse = (payload, ctx) => {
1916 if (payload.value === void 0) {
1917 payload.value = def.defaultValue;
1918 /**
1919 * $ZodDefault always returns the default value immediately.
1920 * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
1921 return payload;
1922 }
1923 const result = def.innerType._zod.run(payload, ctx);
1924 if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));
1925 return handleDefaultResult(result, def);
1926 };
1927 });
1928 function handleDefaultResult(payload, def) {
1929 if (payload.value === void 0) payload.value = def.defaultValue;
1930 return payload;
1931 }
1932 var $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
1933 $ZodType.init(inst, def);
1934 inst._zod.optin = "optional";
1935 defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1936 inst._zod.parse = (payload, ctx) => {
1937 if (payload.value === void 0) payload.value = def.defaultValue;
1938 return def.innerType._zod.run(payload, ctx);
1939 };
1940 });
1941 var $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => {
1942 $ZodType.init(inst, def);
1943 defineLazy(inst._zod, "values", () => {
1944 const v = def.innerType._zod.values;
1945 return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
1946 });
1947 inst._zod.parse = (payload, ctx) => {
1948 const result = def.innerType._zod.run(payload, ctx);
1949 if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst));
1950 return handleNonOptionalResult(result, inst);
1951 };
1952 });
1953 function handleNonOptionalResult(payload, inst) {
1954 if (!payload.issues.length && payload.value === void 0) payload.issues.push({
1955 code: "invalid_type",
1956 expected: "nonoptional",
1957 input: payload.value,
1958 inst
1959 });
1960 return payload;
1961 }
1962 var $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
1963 $ZodType.init(inst, def);
1964 inst._zod.optin = "optional";
1965 defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1966 defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1967 inst._zod.parse = (payload, ctx) => {
1968 const result = def.innerType._zod.run(payload, ctx);
1969 if (result instanceof Promise) return result.then((result) => {
1970 payload.value = result.value;
1971 if (result.issues.length) {
1972 payload.value = def.catchValue({
1973 ...payload,
1974 error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
1975 input: payload.value
1976 });
1977 payload.issues = [];
1978 }
1979 return payload;
1980 });
1981 payload.value = result.value;
1982 if (result.issues.length) {
1983 payload.value = def.catchValue({
1984 ...payload,
1985 error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
1986 input: payload.value
1987 });
1988 payload.issues = [];
1989 }
1990 return payload;
1991 };
1992 });
1993 var $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
1994 $ZodType.init(inst, def);
1995 defineLazy(inst._zod, "values", () => def.in._zod.values);
1996 defineLazy(inst._zod, "optin", () => def.in._zod.optin);
1997 defineLazy(inst._zod, "optout", () => def.out._zod.optout);
1998 inst._zod.parse = (payload, ctx) => {
1999 const left = def.in._zod.run(payload, ctx);
2000 if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def, ctx));
2001 return handlePipeResult(left, def, ctx);
2002 };
2003 });
2004 function handlePipeResult(left, def, ctx) {
2005 if (aborted(left)) return left;
2006 return def.out._zod.run({
2007 value: left.value,
2008 issues: left.issues
2009 }, ctx);
2010 }
2011 var $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
2012 $ZodType.init(inst, def);
2013 defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
2014 defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2015 defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2016 defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2017 inst._zod.parse = (payload, ctx) => {
2018 const result = def.innerType._zod.run(payload, ctx);
2019 if (result instanceof Promise) return result.then(handleReadonlyResult);
2020 return handleReadonlyResult(result);
2021 };
2022 });
2023 function handleReadonlyResult(payload) {
2024 payload.value = Object.freeze(payload.value);
2025 return payload;
2026 }
2027 var $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => {
2028 $ZodCheck.init(inst, def);
2029 $ZodType.init(inst, def);
2030 inst._zod.parse = (payload, _) => {
2031 return payload;
2032 };
2033 inst._zod.check = (payload) => {
2034 const input = payload.value;
2035 const r = def.fn(input);
2036 if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst));
2037 handleRefineResult(r, payload, input, inst);
2038 };
2039 });
2040 function handleRefineResult(result, payload, input, inst) {
2041 if (!result) {
2042 const _iss = {
2043 code: "custom",
2044 input,
2045 inst,
2046 path: [...inst._zod.def.path ?? []],
2047 continue: !inst._zod.def.abort
2048 };
2049 if (inst._zod.def.params) _iss.params = inst._zod.def.params;
2050 payload.issues.push(issue(_iss));
2051 }
2052 }
2053
2054 //#endregion
2055 //#region node_modules/zod/v4/core/registries.js
2056 var $ZodRegistry = class {
2057 constructor() {
2058 this._map = /* @__PURE__ */ new Map();
2059 this._idmap = /* @__PURE__ */ new Map();
2060 }
2061 add(schema, ..._meta) {
2062 const meta = _meta[0];
2063 this._map.set(schema, meta);
2064 if (meta && typeof meta === "object" && "id" in meta) {
2065 if (this._idmap.has(meta.id)) throw new Error(`ID ${meta.id} already exists in the registry`);
2066 this._idmap.set(meta.id, schema);
2067 }
2068 return this;
2069 }
2070 clear() {
2071 this._map = /* @__PURE__ */ new Map();
2072 this._idmap = /* @__PURE__ */ new Map();
2073 return this;
2074 }
2075 remove(schema) {
2076 const meta = this._map.get(schema);
2077 if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
2078 this._map.delete(schema);
2079 return this;
2080 }
2081 get(schema) {
2082 const p = schema._zod.parent;
2083 if (p) {
2084 const pm = { ...this.get(p) ?? {} };
2085 delete pm.id;
2086 return {
2087 ...pm,
2088 ...this._map.get(schema)
2089 };
2090 }
2091 return this._map.get(schema);
2092 }
2093 has(schema) {
2094 return this._map.has(schema);
2095 }
2096 };
2097 function registry() {
2098 return new $ZodRegistry();
2099 }
2100 var globalRegistry = /*@__PURE__*/ registry();
2101
2102 //#endregion
2103 //#region node_modules/zod/v4/core/api.js
2104 function _string(Class, params) {
2105 return new Class({
2106 type: "string",
2107 ...normalizeParams(params)
2108 });
2109 }
2110 function _email(Class, params) {
2111 return new Class({
2112 type: "string",
2113 format: "email",
2114 check: "string_format",
2115 abort: false,
2116 ...normalizeParams(params)
2117 });
2118 }
2119 function _guid(Class, params) {
2120 return new Class({
2121 type: "string",
2122 format: "guid",
2123 check: "string_format",
2124 abort: false,
2125 ...normalizeParams(params)
2126 });
2127 }
2128 function _uuid(Class, params) {
2129 return new Class({
2130 type: "string",
2131 format: "uuid",
2132 check: "string_format",
2133 abort: false,
2134 ...normalizeParams(params)
2135 });
2136 }
2137 function _uuidv4(Class, params) {
2138 return new Class({
2139 type: "string",
2140 format: "uuid",
2141 check: "string_format",
2142 abort: false,
2143 version: "v4",
2144 ...normalizeParams(params)
2145 });
2146 }
2147 function _uuidv6(Class, params) {
2148 return new Class({
2149 type: "string",
2150 format: "uuid",
2151 check: "string_format",
2152 abort: false,
2153 version: "v6",
2154 ...normalizeParams(params)
2155 });
2156 }
2157 function _uuidv7(Class, params) {
2158 return new Class({
2159 type: "string",
2160 format: "uuid",
2161 check: "string_format",
2162 abort: false,
2163 version: "v7",
2164 ...normalizeParams(params)
2165 });
2166 }
2167 function _url(Class, params) {
2168 return new Class({
2169 type: "string",
2170 format: "url",
2171 check: "string_format",
2172 abort: false,
2173 ...normalizeParams(params)
2174 });
2175 }
2176 function _emoji(Class, params) {
2177 return new Class({
2178 type: "string",
2179 format: "emoji",
2180 check: "string_format",
2181 abort: false,
2182 ...normalizeParams(params)
2183 });
2184 }
2185 function _nanoid(Class, params) {
2186 return new Class({
2187 type: "string",
2188 format: "nanoid",
2189 check: "string_format",
2190 abort: false,
2191 ...normalizeParams(params)
2192 });
2193 }
2194 function _cuid(Class, params) {
2195 return new Class({
2196 type: "string",
2197 format: "cuid",
2198 check: "string_format",
2199 abort: false,
2200 ...normalizeParams(params)
2201 });
2202 }
2203 function _cuid2(Class, params) {
2204 return new Class({
2205 type: "string",
2206 format: "cuid2",
2207 check: "string_format",
2208 abort: false,
2209 ...normalizeParams(params)
2210 });
2211 }
2212 function _ulid(Class, params) {
2213 return new Class({
2214 type: "string",
2215 format: "ulid",
2216 check: "string_format",
2217 abort: false,
2218 ...normalizeParams(params)
2219 });
2220 }
2221 function _xid(Class, params) {
2222 return new Class({
2223 type: "string",
2224 format: "xid",
2225 check: "string_format",
2226 abort: false,
2227 ...normalizeParams(params)
2228 });
2229 }
2230 function _ksuid(Class, params) {
2231 return new Class({
2232 type: "string",
2233 format: "ksuid",
2234 check: "string_format",
2235 abort: false,
2236 ...normalizeParams(params)
2237 });
2238 }
2239 function _ipv4(Class, params) {
2240 return new Class({
2241 type: "string",
2242 format: "ipv4",
2243 check: "string_format",
2244 abort: false,
2245 ...normalizeParams(params)
2246 });
2247 }
2248 function _ipv6(Class, params) {
2249 return new Class({
2250 type: "string",
2251 format: "ipv6",
2252 check: "string_format",
2253 abort: false,
2254 ...normalizeParams(params)
2255 });
2256 }
2257 function _cidrv4(Class, params) {
2258 return new Class({
2259 type: "string",
2260 format: "cidrv4",
2261 check: "string_format",
2262 abort: false,
2263 ...normalizeParams(params)
2264 });
2265 }
2266 function _cidrv6(Class, params) {
2267 return new Class({
2268 type: "string",
2269 format: "cidrv6",
2270 check: "string_format",
2271 abort: false,
2272 ...normalizeParams(params)
2273 });
2274 }
2275 function _base64(Class, params) {
2276 return new Class({
2277 type: "string",
2278 format: "base64",
2279 check: "string_format",
2280 abort: false,
2281 ...normalizeParams(params)
2282 });
2283 }
2284 function _base64url(Class, params) {
2285 return new Class({
2286 type: "string",
2287 format: "base64url",
2288 check: "string_format",
2289 abort: false,
2290 ...normalizeParams(params)
2291 });
2292 }
2293 function _e164(Class, params) {
2294 return new Class({
2295 type: "string",
2296 format: "e164",
2297 check: "string_format",
2298 abort: false,
2299 ...normalizeParams(params)
2300 });
2301 }
2302 function _jwt(Class, params) {
2303 return new Class({
2304 type: "string",
2305 format: "jwt",
2306 check: "string_format",
2307 abort: false,
2308 ...normalizeParams(params)
2309 });
2310 }
2311 function _isoDateTime(Class, params) {
2312 return new Class({
2313 type: "string",
2314 format: "datetime",
2315 check: "string_format",
2316 offset: false,
2317 local: false,
2318 precision: null,
2319 ...normalizeParams(params)
2320 });
2321 }
2322 function _isoDate(Class, params) {
2323 return new Class({
2324 type: "string",
2325 format: "date",
2326 check: "string_format",
2327 ...normalizeParams(params)
2328 });
2329 }
2330 function _isoTime(Class, params) {
2331 return new Class({
2332 type: "string",
2333 format: "time",
2334 check: "string_format",
2335 precision: null,
2336 ...normalizeParams(params)
2337 });
2338 }
2339 function _isoDuration(Class, params) {
2340 return new Class({
2341 type: "string",
2342 format: "duration",
2343 check: "string_format",
2344 ...normalizeParams(params)
2345 });
2346 }
2347 function _number(Class, params) {
2348 return new Class({
2349 type: "number",
2350 checks: [],
2351 ...normalizeParams(params)
2352 });
2353 }
2354 function _int(Class, params) {
2355 return new Class({
2356 type: "number",
2357 check: "number_format",
2358 abort: false,
2359 format: "safeint",
2360 ...normalizeParams(params)
2361 });
2362 }
2363 function _boolean(Class, params) {
2364 return new Class({
2365 type: "boolean",
2366 ...normalizeParams(params)
2367 });
2368 }
2369 function _null$1(Class, params) {
2370 return new Class({
2371 type: "null",
2372 ...normalizeParams(params)
2373 });
2374 }
2375 __name(_null$1, "_null");
2376 function _unknown(Class) {
2377 return new Class({ type: "unknown" });
2378 }
2379 function _never(Class, params) {
2380 return new Class({
2381 type: "never",
2382 ...normalizeParams(params)
2383 });
2384 }
2385 function _lt(value, params) {
2386 return new $ZodCheckLessThan({
2387 check: "less_than",
2388 ...normalizeParams(params),
2389 value,
2390 inclusive: false
2391 });
2392 }
2393 function _lte(value, params) {
2394 return new $ZodCheckLessThan({
2395 check: "less_than",
2396 ...normalizeParams(params),
2397 value,
2398 inclusive: true
2399 });
2400 }
2401 function _gt(value, params) {
2402 return new $ZodCheckGreaterThan({
2403 check: "greater_than",
2404 ...normalizeParams(params),
2405 value,
2406 inclusive: false
2407 });
2408 }
2409 function _gte(value, params) {
2410 return new $ZodCheckGreaterThan({
2411 check: "greater_than",
2412 ...normalizeParams(params),
2413 value,
2414 inclusive: true
2415 });
2416 }
2417 function _multipleOf(value, params) {
2418 return new $ZodCheckMultipleOf({
2419 check: "multiple_of",
2420 ...normalizeParams(params),
2421 value
2422 });
2423 }
2424 function _maxLength(maximum, params) {
2425 return new $ZodCheckMaxLength({
2426 check: "max_length",
2427 ...normalizeParams(params),
2428 maximum
2429 });
2430 }
2431 function _minLength(minimum, params) {
2432 return new $ZodCheckMinLength({
2433 check: "min_length",
2434 ...normalizeParams(params),
2435 minimum
2436 });
2437 }
2438 function _length(length, params) {
2439 return new $ZodCheckLengthEquals({
2440 check: "length_equals",
2441 ...normalizeParams(params),
2442 length
2443 });
2444 }
2445 function _regex(pattern, params) {
2446 return new $ZodCheckRegex({
2447 check: "string_format",
2448 format: "regex",
2449 ...normalizeParams(params),
2450 pattern
2451 });
2452 }
2453 function _lowercase(params) {
2454 return new $ZodCheckLowerCase({
2455 check: "string_format",
2456 format: "lowercase",
2457 ...normalizeParams(params)
2458 });
2459 }
2460 function _uppercase(params) {
2461 return new $ZodCheckUpperCase({
2462 check: "string_format",
2463 format: "uppercase",
2464 ...normalizeParams(params)
2465 });
2466 }
2467 function _includes(includes, params) {
2468 return new $ZodCheckIncludes({
2469 check: "string_format",
2470 format: "includes",
2471 ...normalizeParams(params),
2472 includes
2473 });
2474 }
2475 function _startsWith(prefix, params) {
2476 return new $ZodCheckStartsWith({
2477 check: "string_format",
2478 format: "starts_with",
2479 ...normalizeParams(params),
2480 prefix
2481 });
2482 }
2483 function _endsWith(suffix, params) {
2484 return new $ZodCheckEndsWith({
2485 check: "string_format",
2486 format: "ends_with",
2487 ...normalizeParams(params),
2488 suffix
2489 });
2490 }
2491 function _overwrite(tx) {
2492 return new $ZodCheckOverwrite({
2493 check: "overwrite",
2494 tx
2495 });
2496 }
2497 function _normalize(form) {
2498 return _overwrite((input) => input.normalize(form));
2499 }
2500 function _trim() {
2501 return _overwrite((input) => input.trim());
2502 }
2503 function _toLowerCase() {
2504 return _overwrite((input) => input.toLowerCase());
2505 }
2506 function _toUpperCase() {
2507 return _overwrite((input) => input.toUpperCase());
2508 }
2509 function _array(Class, element, params) {
2510 return new Class({
2511 type: "array",
2512 element,
2513 ...normalizeParams(params)
2514 });
2515 }
2516 function _custom(Class, fn, _params) {
2517 const norm = normalizeParams(_params);
2518 norm.abort ?? (norm.abort = true);
2519 return new Class({
2520 type: "custom",
2521 check: "custom",
2522 fn,
2523 ...norm
2524 });
2525 }
2526 function _refine(Class, fn, _params) {
2527 return new Class({
2528 type: "custom",
2529 check: "custom",
2530 fn,
2531 ...normalizeParams(_params)
2532 });
2533 }
2534
2535 //#endregion
2536 //#region node_modules/zod/v4/core/to-json-schema.js
2537 var JSONSchemaGenerator = class {
2538 constructor(params) {
2539 this.counter = 0;
2540 this.metadataRegistry = params?.metadata ?? globalRegistry;
2541 this.target = params?.target ?? "draft-2020-12";
2542 this.unrepresentable = params?.unrepresentable ?? "throw";
2543 this.override = params?.override ?? (() => {});
2544 this.io = params?.io ?? "output";
2545 this.seen = /* @__PURE__ */ new Map();
2546 }
2547 process(schema, _params = {
2548 path: [],
2549 schemaPath: []
2550 }) {
2551 var _a;
2552 const def = schema._zod.def;
2553 const formatMap = {
2554 guid: "uuid",
2555 url: "uri",
2556 datetime: "date-time",
2557 json_string: "json-string",
2558 regex: ""
2559 };
2560 const seen = this.seen.get(schema);
2561 if (seen) {
2562 seen.count++;
2563 if (_params.schemaPath.includes(schema)) seen.cycle = _params.path;
2564 return seen.schema;
2565 }
2566 const result = {
2567 schema: {},
2568 count: 1,
2569 cycle: void 0,
2570 path: _params.path
2571 };
2572 this.seen.set(schema, result);
2573 const overrideSchema = schema._zod.toJSONSchema?.();
2574 if (overrideSchema) result.schema = overrideSchema;
2575 else {
2576 const params = {
2577 ..._params,
2578 schemaPath: [..._params.schemaPath, schema],
2579 path: _params.path
2580 };
2581 const parent = schema._zod.parent;
2582 if (parent) {
2583 result.ref = parent;
2584 this.process(parent, params);
2585 this.seen.get(parent).isParent = true;
2586 } else {
2587 const _json = result.schema;
2588 switch (def.type) {
2589 case "string": {
2590 const json = _json;
2591 json.type = "string";
2592 const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
2593 if (typeof minimum === "number") json.minLength = minimum;
2594 if (typeof maximum === "number") json.maxLength = maximum;
2595 if (format) {
2596 json.format = formatMap[format] ?? format;
2597 if (json.format === "") delete json.format;
2598 }
2599 if (contentEncoding) json.contentEncoding = contentEncoding;
2600 if (patterns && patterns.size > 0) {
2601 const regexes = [...patterns];
2602 if (regexes.length === 1) json.pattern = regexes[0].source;
2603 else if (regexes.length > 1) result.schema.allOf = [...regexes.map((regex) => ({
2604 ...this.target === "draft-7" ? { type: "string" } : {},
2605 pattern: regex.source
2606 }))];
2607 }
2608 break;
2609 }
2610 case "number": {
2611 const json = _json;
2612 const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
2613 if (typeof format === "string" && format.includes("int")) json.type = "integer";
2614 else json.type = "number";
2615 if (typeof exclusiveMinimum === "number") json.exclusiveMinimum = exclusiveMinimum;
2616 if (typeof minimum === "number") {
2617 json.minimum = minimum;
2618 if (typeof exclusiveMinimum === "number") if (exclusiveMinimum >= minimum) delete json.minimum;
2619 else delete json.exclusiveMinimum;
2620 }
2621 if (typeof exclusiveMaximum === "number") json.exclusiveMaximum = exclusiveMaximum;
2622 if (typeof maximum === "number") {
2623 json.maximum = maximum;
2624 if (typeof exclusiveMaximum === "number") if (exclusiveMaximum <= maximum) delete json.maximum;
2625 else delete json.exclusiveMaximum;
2626 }
2627 if (typeof multipleOf === "number") json.multipleOf = multipleOf;
2628 break;
2629 }
2630 case "boolean": {
2631 const json = _json;
2632 json.type = "boolean";
2633 break;
2634 }
2635 case "bigint":
2636 if (this.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
2637 break;
2638 case "symbol":
2639 if (this.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
2640 break;
2641 case "null":
2642 _json.type = "null";
2643 break;
2644 case "any": break;
2645 case "unknown": break;
2646 case "undefined":
2647 if (this.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
2648 break;
2649 case "void":
2650 if (this.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
2651 break;
2652 case "never":
2653 _json.not = {};
2654 break;
2655 case "date":
2656 if (this.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
2657 break;
2658 case "array": {
2659 const json = _json;
2660 const { minimum, maximum } = schema._zod.bag;
2661 if (typeof minimum === "number") json.minItems = minimum;
2662 if (typeof maximum === "number") json.maxItems = maximum;
2663 json.type = "array";
2664 json.items = this.process(def.element, {
2665 ...params,
2666 path: [...params.path, "items"]
2667 });
2668 break;
2669 }
2670 case "object": {
2671 const json = _json;
2672 json.type = "object";
2673 json.properties = {};
2674 const shape = def.shape;
2675 for (const key in shape) json.properties[key] = this.process(shape[key], {
2676 ...params,
2677 path: [
2678 ...params.path,
2679 "properties",
2680 key
2681 ]
2682 });
2683 const allKeys = new Set(Object.keys(shape));
2684 const requiredKeys = new Set([...allKeys].filter((key) => {
2685 const v = def.shape[key]._zod;
2686 if (this.io === "input") return v.optin === void 0;
2687 else return v.optout === void 0;
2688 }));
2689 if (requiredKeys.size > 0) json.required = Array.from(requiredKeys);
2690 if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
2691 else if (!def.catchall) {
2692 if (this.io === "output") json.additionalProperties = false;
2693 } else if (def.catchall) json.additionalProperties = this.process(def.catchall, {
2694 ...params,
2695 path: [...params.path, "additionalProperties"]
2696 });
2697 break;
2698 }
2699 case "union": {
2700 const json = _json;
2701 json.anyOf = def.options.map((x, i) => this.process(x, {
2702 ...params,
2703 path: [
2704 ...params.path,
2705 "anyOf",
2706 i
2707 ]
2708 }));
2709 break;
2710 }
2711 case "intersection": {
2712 const json = _json;
2713 const a = this.process(def.left, {
2714 ...params,
2715 path: [
2716 ...params.path,
2717 "allOf",
2718 0
2719 ]
2720 });
2721 const b = this.process(def.right, {
2722 ...params,
2723 path: [
2724 ...params.path,
2725 "allOf",
2726 1
2727 ]
2728 });
2729 const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
2730 json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
2731 break;
2732 }
2733 case "tuple": {
2734 const json = _json;
2735 json.type = "array";
2736 const prefixItems = def.items.map((x, i) => this.process(x, {
2737 ...params,
2738 path: [
2739 ...params.path,
2740 "prefixItems",
2741 i
2742 ]
2743 }));
2744 if (this.target === "draft-2020-12") json.prefixItems = prefixItems;
2745 else json.items = prefixItems;
2746 if (def.rest) {
2747 const rest = this.process(def.rest, {
2748 ...params,
2749 path: [...params.path, "items"]
2750 });
2751 if (this.target === "draft-2020-12") json.items = rest;
2752 else json.additionalItems = rest;
2753 }
2754 if (def.rest) json.items = this.process(def.rest, {
2755 ...params,
2756 path: [...params.path, "items"]
2757 });
2758 const { minimum, maximum } = schema._zod.bag;
2759 if (typeof minimum === "number") json.minItems = minimum;
2760 if (typeof maximum === "number") json.maxItems = maximum;
2761 break;
2762 }
2763 case "record": {
2764 const json = _json;
2765 json.type = "object";
2766 json.propertyNames = this.process(def.keyType, {
2767 ...params,
2768 path: [...params.path, "propertyNames"]
2769 });
2770 json.additionalProperties = this.process(def.valueType, {
2771 ...params,
2772 path: [...params.path, "additionalProperties"]
2773 });
2774 break;
2775 }
2776 case "map":
2777 if (this.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
2778 break;
2779 case "set":
2780 if (this.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
2781 break;
2782 case "enum": {
2783 const json = _json;
2784 const values = getEnumValues(def.entries);
2785 if (values.every((v) => typeof v === "number")) json.type = "number";
2786 if (values.every((v) => typeof v === "string")) json.type = "string";
2787 json.enum = values;
2788 break;
2789 }
2790 case "literal": {
2791 const json = _json;
2792 const vals = [];
2793 for (const val of def.values) if (val === void 0) {
2794 if (this.unrepresentable === "throw") throw new Error("Literal `undefined` cannot be represented in JSON Schema");
2795 } else if (typeof val === "bigint") if (this.unrepresentable === "throw") throw new Error("BigInt literals cannot be represented in JSON Schema");
2796 else vals.push(Number(val));
2797 else vals.push(val);
2798 if (vals.length === 0) {} else if (vals.length === 1) {
2799 const val = vals[0];
2800 json.type = val === null ? "null" : typeof val;
2801 json.const = val;
2802 } else {
2803 if (vals.every((v) => typeof v === "number")) json.type = "number";
2804 if (vals.every((v) => typeof v === "string")) json.type = "string";
2805 if (vals.every((v) => typeof v === "boolean")) json.type = "string";
2806 if (vals.every((v) => v === null)) json.type = "null";
2807 json.enum = vals;
2808 }
2809 break;
2810 }
2811 case "file": {
2812 const json = _json;
2813 const file = {
2814 type: "string",
2815 format: "binary",
2816 contentEncoding: "binary"
2817 };
2818 const { minimum, maximum, mime } = schema._zod.bag;
2819 if (minimum !== void 0) file.minLength = minimum;
2820 if (maximum !== void 0) file.maxLength = maximum;
2821 if (mime) if (mime.length === 1) {
2822 file.contentMediaType = mime[0];
2823 Object.assign(json, file);
2824 } else json.anyOf = mime.map((m) => {
2825 return {
2826 ...file,
2827 contentMediaType: m
2828 };
2829 });
2830 else Object.assign(json, file);
2831 break;
2832 }
2833 case "transform":
2834 if (this.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
2835 break;
2836 case "nullable":
2837 _json.anyOf = [this.process(def.innerType, params), { type: "null" }];
2838 break;
2839 case "nonoptional":
2840 this.process(def.innerType, params);
2841 result.ref = def.innerType;
2842 break;
2843 case "success": {
2844 const json = _json;
2845 json.type = "boolean";
2846 break;
2847 }
2848 case "default":
2849 this.process(def.innerType, params);
2850 result.ref = def.innerType;
2851 _json.default = JSON.parse(JSON.stringify(def.defaultValue));
2852 break;
2853 case "prefault":
2854 this.process(def.innerType, params);
2855 result.ref = def.innerType;
2856 if (this.io === "input") _json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
2857 break;
2858 case "catch": {
2859 this.process(def.innerType, params);
2860 result.ref = def.innerType;
2861 let catchValue;
2862 try {
2863 catchValue = def.catchValue(void 0);
2864 } catch {
2865 throw new Error("Dynamic catch values are not supported in JSON Schema");
2866 }
2867 _json.default = catchValue;
2868 break;
2869 }
2870 case "nan":
2871 if (this.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
2872 break;
2873 case "template_literal": {
2874 const json = _json;
2875 const pattern = schema._zod.pattern;
2876 if (!pattern) throw new Error("Pattern not found in template literal");
2877 json.type = "string";
2878 json.pattern = pattern.source;
2879 break;
2880 }
2881 case "pipe": {
2882 const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
2883 this.process(innerType, params);
2884 result.ref = innerType;
2885 break;
2886 }
2887 case "readonly":
2888 this.process(def.innerType, params);
2889 result.ref = def.innerType;
2890 _json.readOnly = true;
2891 break;
2892 case "promise":
2893 this.process(def.innerType, params);
2894 result.ref = def.innerType;
2895 break;
2896 case "optional":
2897 this.process(def.innerType, params);
2898 result.ref = def.innerType;
2899 break;
2900 case "lazy": {
2901 const innerType = schema._zod.innerType;
2902 this.process(innerType, params);
2903 result.ref = innerType;
2904 break;
2905 }
2906 case "custom":
2907 if (this.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
2908 break;
2909 default:
2910 }
2911 }
2912 }
2913 const meta = this.metadataRegistry.get(schema);
2914 if (meta) Object.assign(result.schema, meta);
2915 if (this.io === "input" && isTransforming(schema)) {
2916 delete result.schema.examples;
2917 delete result.schema.default;
2918 }
2919 if (this.io === "input" && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
2920 delete result.schema._prefault;
2921 return this.seen.get(schema).schema;
2922 }
2923 emit(schema, _params) {
2924 const params = {
2925 cycles: _params?.cycles ?? "ref",
2926 reused: _params?.reused ?? "inline",
2927 external: _params?.external ?? void 0
2928 };
2929 const root = this.seen.get(schema);
2930 if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2931 const makeURI = (entry) => {
2932 const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
2933 if (params.external) {
2934 const externalId = params.external.registry.get(entry[0])?.id;
2935 const uriGenerator = params.external.uri ?? ((id) => id);
2936 if (externalId) return { ref: uriGenerator(externalId) };
2937 const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
2938 entry[1].defId = id;
2939 return {
2940 defId: id,
2941 ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}`
2942 };
2943 }
2944 if (entry[1] === root) return { ref: "#" };
2945 const defUriPrefix = `#/${defsSegment}/`;
2946 const defId = entry[1].schema.id ?? `__schema${this.counter++}`;
2947 return {
2948 defId,
2949 ref: defUriPrefix + defId
2950 };
2951 };
2952 const extractToDef = (entry) => {
2953 if (entry[1].schema.$ref) return;
2954 const seen = entry[1];
2955 const { ref, defId } = makeURI(entry);
2956 seen.def = { ...seen.schema };
2957 if (defId) seen.defId = defId;
2958 const schema = seen.schema;
2959 for (const key in schema) delete schema[key];
2960 schema.$ref = ref;
2961 };
2962 if (params.cycles === "throw") for (const entry of this.seen.entries()) {
2963 const seen = entry[1];
2964 if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
2965
2966 Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
2967 }
2968 for (const entry of this.seen.entries()) {
2969 const seen = entry[1];
2970 if (schema === entry[0]) {
2971 extractToDef(entry);
2972 continue;
2973 }
2974 if (params.external) {
2975 const ext = params.external.registry.get(entry[0])?.id;
2976 if (schema !== entry[0] && ext) {
2977 extractToDef(entry);
2978 continue;
2979 }
2980 }
2981 if (this.metadataRegistry.get(entry[0])?.id) {
2982 extractToDef(entry);
2983 continue;
2984 }
2985 if (seen.cycle) {
2986 extractToDef(entry);
2987 continue;
2988 }
2989 if (seen.count > 1) {
2990 if (params.reused === "ref") {
2991 extractToDef(entry);
2992 continue;
2993 }
2994 }
2995 }
2996 const flattenRef = (zodSchema, params) => {
2997 const seen = this.seen.get(zodSchema);
2998 const schema = seen.def ?? seen.schema;
2999 const _cached = { ...schema };
3000 if (seen.ref === null) return;
3001 const ref = seen.ref;
3002 seen.ref = null;
3003 if (ref) {
3004 flattenRef(ref, params);
3005 const refSchema = this.seen.get(ref).schema;
3006 if (refSchema.$ref && params.target === "draft-7") {
3007 schema.allOf = schema.allOf ?? [];
3008 schema.allOf.push(refSchema);
3009 } else {
3010 Object.assign(schema, refSchema);
3011 Object.assign(schema, _cached);
3012 }
3013 }
3014 if (!seen.isParent) this.override({
3015 zodSchema,
3016 jsonSchema: schema,
3017 path: seen.path ?? []
3018 });
3019 };
3020 for (const entry of [...this.seen.entries()].reverse()) flattenRef(entry[0], { target: this.target });
3021 const result = {};
3022 if (this.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema";
3023 else if (this.target === "draft-7") result.$schema = "http://json-schema.org/draft-07/schema#";
3024 else console.warn(`Invalid target: ${this.target}`);
3025 if (params.external?.uri) {
3026 const id = params.external.registry.get(schema)?.id;
3027 if (!id) throw new Error("Schema is missing an `id` property");
3028 result.$id = params.external.uri(id);
3029 }
3030 Object.assign(result, root.def);
3031 const defs = params.external?.defs ?? {};
3032 for (const entry of this.seen.entries()) {
3033 const seen = entry[1];
3034 if (seen.def && seen.defId) defs[seen.defId] = seen.def;
3035 }
3036 if (params.external) {} else if (Object.keys(defs).length > 0) if (this.target === "draft-2020-12") result.$defs = defs;
3037 else result.definitions = defs;
3038 try {
3039 return JSON.parse(JSON.stringify(result));
3040 } catch (_err) {
3041 throw new Error("Error converting schema to JSON.");
3042 }
3043 }
3044 };
3045 function toJSONSchema(input, _params) {
3046 if (input instanceof $ZodRegistry) {
3047 const gen = new JSONSchemaGenerator(_params);
3048 const defs = {};
3049 for (const entry of input._idmap.entries()) {
3050 const [_, schema] = entry;
3051 gen.process(schema);
3052 }
3053 const schemas = {};
3054 const external = {
3055 registry: input,
3056 uri: _params?.uri,
3057 defs
3058 };
3059 for (const entry of input._idmap.entries()) {
3060 const [key, schema] = entry;
3061 schemas[key] = gen.emit(schema, {
3062 ..._params,
3063 external
3064 });
3065 }
3066 if (Object.keys(defs).length > 0) schemas.__shared = { [gen.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
3067 return { schemas };
3068 }
3069 const gen = new JSONSchemaGenerator(_params);
3070 gen.process(input);
3071 return gen.emit(input, _params);
3072 }
3073 function isTransforming(_schema, _ctx) {
3074 const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
3075 if (ctx.seen.has(_schema)) return false;
3076 ctx.seen.add(_schema);
3077 const def = _schema._zod.def;
3078 switch (def.type) {
3079 case "string":
3080 case "number":
3081 case "bigint":
3082 case "boolean":
3083 case "date":
3084 case "symbol":
3085 case "undefined":
3086 case "null":
3087 case "any":
3088 case "unknown":
3089 case "never":
3090 case "void":
3091 case "literal":
3092 case "enum":
3093 case "nan":
3094 case "file":
3095 case "template_literal": return false;
3096 case "array": return isTransforming(def.element, ctx);
3097 case "object":
3098 for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true;
3099 return false;
3100 case "union":
3101 for (const option of def.options) if (isTransforming(option, ctx)) return true;
3102 return false;
3103 case "intersection": return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
3104 case "tuple":
3105 for (const item of def.items) if (isTransforming(item, ctx)) return true;
3106 if (def.rest && isTransforming(def.rest, ctx)) return true;
3107 return false;
3108 case "record": return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
3109 case "map": return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
3110 case "set": return isTransforming(def.valueType, ctx);
3111 case "promise":
3112 case "optional":
3113 case "nonoptional":
3114 case "nullable":
3115 case "readonly": return isTransforming(def.innerType, ctx);
3116 case "lazy": return isTransforming(def.getter(), ctx);
3117 case "default": return isTransforming(def.innerType, ctx);
3118 case "prefault": return isTransforming(def.innerType, ctx);
3119 case "custom": return false;
3120 case "transform": return true;
3121 case "pipe": return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
3122 case "success": return false;
3123 case "catch": return false;
3124 default:
3125 }
3126 throw new Error(`Unknown schema type: ${def.type}`);
3127 }
3128
3129 //#endregion
3130 //#region node_modules/zod/v4/classic/iso.js
3131 var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
3132 $ZodISODateTime.init(inst, def);
3133 ZodStringFormat.init(inst, def);
3134 });
3135 function datetime(params) {
3136 return _isoDateTime(ZodISODateTime, params);
3137 }
3138 var ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => {
3139 $ZodISODate.init(inst, def);
3140 ZodStringFormat.init(inst, def);
3141 });
3142 function date(params) {
3143 return _isoDate(ZodISODate, params);
3144 }
3145 var ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => {
3146 $ZodISOTime.init(inst, def);
3147 ZodStringFormat.init(inst, def);
3148 });
3149 function time(params) {
3150 return _isoTime(ZodISOTime, params);
3151 }
3152 var ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => {
3153 $ZodISODuration.init(inst, def);
3154 ZodStringFormat.init(inst, def);
3155 });
3156 function duration(params) {
3157 return _isoDuration(ZodISODuration, params);
3158 }
3159
3160 //#endregion
3161 //#region node_modules/zod/v4/classic/errors.js
3162 var initializer = (inst, issues) => {
3163 $ZodError.init(inst, issues);
3164 inst.name = "ZodError";
3165 Object.defineProperties(inst, {
3166 format: { value: (mapper) => formatError(inst, mapper) },
3167 flatten: { value: (mapper) => flattenError(inst, mapper) },
3168 addIssue: { value: (issue) => inst.issues.push(issue) },
3169 addIssues: { value: (issues) => inst.issues.push(...issues) },
3170 isEmpty: { get() {
3171 return inst.issues.length === 0;
3172 } }
3173 });
3174 };
3175 var ZodError$1 = $constructor("ZodError", initializer);
3176 var ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
3177
3178 //#endregion
3179 //#region node_modules/zod/v4/classic/parse.js
3180 var parse = /* @__PURE__ */ _parse(ZodRealError);
3181 var parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
3182 var safeParse$1 = /* @__PURE__ */ _safeParse(ZodRealError);
3183 var safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3184
3185 //#endregion
3186 //#region node_modules/zod/v4/classic/schemas.js
3187 var ZodType$1 = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
3188 $ZodType.init(inst, def);
3189 inst.def = def;
3190 Object.defineProperty(inst, "_def", { value: def });
3191 inst.check = (...checks) => {
3192 return inst.clone({
3193 ...def,
3194 checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
3195 check: ch,
3196 def: { check: "custom" },
3197 onattach: []
3198 } } : ch)]
3199 });
3200 };
3201 inst.clone = (def, params) => clone(inst, def, params);
3202 inst.brand = () => inst;
3203 inst.register = ((reg, meta) => {
3204 reg.add(inst, meta);
3205 return inst;
3206 });
3207 inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
3208 inst.safeParse = (data, params) => safeParse$1(inst, data, params);
3209 inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
3210 inst.safeParseAsync = async (data, params) => safeParseAsync$1(inst, data, params);
3211 inst.spa = inst.safeParseAsync;
3212 inst.refine = (check, params) => inst.check(refine(check, params));
3213 inst.superRefine = (refinement) => inst.check(superRefine(refinement));
3214 inst.overwrite = (fn) => inst.check(_overwrite(fn));
3215 inst.optional = () => optional(inst);
3216 inst.nullable = () => nullable(inst);
3217 inst.nullish = () => optional(nullable(inst));
3218 inst.nonoptional = (params) => nonoptional(inst, params);
3219 inst.array = () => array(inst);
3220 inst.or = (arg) => union([inst, arg]);
3221 inst.and = (arg) => intersection(inst, arg);
3222 inst.transform = (tx) => pipe(inst, transform(tx));
3223 inst.default = (def) => _default(inst, def);
3224 inst.prefault = (def) => prefault(inst, def);
3225 inst.catch = (params) => _catch(inst, params);
3226 inst.pipe = (target) => pipe(inst, target);
3227 inst.readonly = () => readonly(inst);
3228 inst.describe = (description) => {
3229 const cl = inst.clone();
3230 globalRegistry.add(cl, { description });
3231 return cl;
3232 };
3233 Object.defineProperty(inst, "description", {
3234 get() {
3235 return globalRegistry.get(inst)?.description;
3236 },
3237 configurable: true
3238 });
3239 inst.meta = (...args) => {
3240 if (args.length === 0) return globalRegistry.get(inst);
3241 const cl = inst.clone();
3242 globalRegistry.add(cl, args[0]);
3243 return cl;
3244 };
3245 inst.isOptional = () => inst.safeParse(void 0).success;
3246 inst.isNullable = () => inst.safeParse(null).success;
3247 return inst;
3248 });
3249 /** @internal */
3250 var _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
3251 $ZodString.init(inst, def);
3252 ZodType$1.init(inst, def);
3253 const bag = inst._zod.bag;
3254 inst.format = bag.format ?? null;
3255 inst.minLength = bag.minimum ?? null;
3256 inst.maxLength = bag.maximum ?? null;
3257 inst.regex = (...args) => inst.check(_regex(...args));
3258 inst.includes = (...args) => inst.check(_includes(...args));
3259 inst.startsWith = (...args) => inst.check(_startsWith(...args));
3260 inst.endsWith = (...args) => inst.check(_endsWith(...args));
3261 inst.min = (...args) => inst.check(_minLength(...args));
3262 inst.max = (...args) => inst.check(_maxLength(...args));
3263 inst.length = (...args) => inst.check(_length(...args));
3264 inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
3265 inst.lowercase = (params) => inst.check(_lowercase(params));
3266 inst.uppercase = (params) => inst.check(_uppercase(params));
3267 inst.trim = () => inst.check(_trim());
3268 inst.normalize = (...args) => inst.check(_normalize(...args));
3269 inst.toLowerCase = () => inst.check(_toLowerCase());
3270 inst.toUpperCase = () => inst.check(_toUpperCase());
3271 });
3272 var ZodString$1 = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
3273 $ZodString.init(inst, def);
3274 _ZodString.init(inst, def);
3275 inst.email = (params) => inst.check(_email(ZodEmail, params));
3276 inst.url = (params) => inst.check(_url(ZodURL, params));
3277 inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
3278 inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
3279 inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3280 inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
3281 inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
3282 inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
3283 inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
3284 inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
3285 inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3286 inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
3287 inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
3288 inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
3289 inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
3290 inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
3291 inst.xid = (params) => inst.check(_xid(ZodXID, params));
3292 inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
3293 inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
3294 inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
3295 inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
3296 inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
3297 inst.e164 = (params) => inst.check(_e164(ZodE164, params));
3298 inst.datetime = (params) => inst.check(datetime(params));
3299 inst.date = (params) => inst.check(date(params));
3300 inst.time = (params) => inst.check(time(params));
3301 inst.duration = (params) => inst.check(duration(params));
3302 });
3303 function string(params) {
3304 return _string(ZodString$1, params);
3305 }
3306 var ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => {
3307 $ZodStringFormat.init(inst, def);
3308 _ZodString.init(inst, def);
3309 });
3310 var ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => {
3311 $ZodEmail.init(inst, def);
3312 ZodStringFormat.init(inst, def);
3313 });
3314 var ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => {
3315 $ZodGUID.init(inst, def);
3316 ZodStringFormat.init(inst, def);
3317 });
3318 var ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
3319 $ZodUUID.init(inst, def);
3320 ZodStringFormat.init(inst, def);
3321 });
3322 var ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
3323 $ZodURL.init(inst, def);
3324 ZodStringFormat.init(inst, def);
3325 });
3326 var ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
3327 $ZodEmoji.init(inst, def);
3328 ZodStringFormat.init(inst, def);
3329 });
3330 var ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => {
3331 $ZodNanoID.init(inst, def);
3332 ZodStringFormat.init(inst, def);
3333 });
3334 var ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => {
3335 $ZodCUID.init(inst, def);
3336 ZodStringFormat.init(inst, def);
3337 });
3338 var ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => {
3339 $ZodCUID2.init(inst, def);
3340 ZodStringFormat.init(inst, def);
3341 });
3342 var ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => {
3343 $ZodULID.init(inst, def);
3344 ZodStringFormat.init(inst, def);
3345 });
3346 var ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => {
3347 $ZodXID.init(inst, def);
3348 ZodStringFormat.init(inst, def);
3349 });
3350 var ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => {
3351 $ZodKSUID.init(inst, def);
3352 ZodStringFormat.init(inst, def);
3353 });
3354 var ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => {
3355 $ZodIPv4.init(inst, def);
3356 ZodStringFormat.init(inst, def);
3357 });
3358 var ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => {
3359 $ZodIPv6.init(inst, def);
3360 ZodStringFormat.init(inst, def);
3361 });
3362 var ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => {
3363 $ZodCIDRv4.init(inst, def);
3364 ZodStringFormat.init(inst, def);
3365 });
3366 var ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => {
3367 $ZodCIDRv6.init(inst, def);
3368 ZodStringFormat.init(inst, def);
3369 });
3370 var ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => {
3371 $ZodBase64.init(inst, def);
3372 ZodStringFormat.init(inst, def);
3373 });
3374 var ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => {
3375 $ZodBase64URL.init(inst, def);
3376 ZodStringFormat.init(inst, def);
3377 });
3378 var ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => {
3379 $ZodE164.init(inst, def);
3380 ZodStringFormat.init(inst, def);
3381 });
3382 var ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => {
3383 $ZodJWT.init(inst, def);
3384 ZodStringFormat.init(inst, def);
3385 });
3386 var ZodNumber$1 = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => {
3387 $ZodNumber.init(inst, def);
3388 ZodType$1.init(inst, def);
3389 inst.gt = (value, params) => inst.check(_gt(value, params));
3390 inst.gte = (value, params) => inst.check(_gte(value, params));
3391 inst.min = (value, params) => inst.check(_gte(value, params));
3392 inst.lt = (value, params) => inst.check(_lt(value, params));
3393 inst.lte = (value, params) => inst.check(_lte(value, params));
3394 inst.max = (value, params) => inst.check(_lte(value, params));
3395 inst.int = (params) => inst.check(int(params));
3396 inst.safe = (params) => inst.check(int(params));
3397 inst.positive = (params) => inst.check(_gt(0, params));
3398 inst.nonnegative = (params) => inst.check(_gte(0, params));
3399 inst.negative = (params) => inst.check(_lt(0, params));
3400 inst.nonpositive = (params) => inst.check(_lte(0, params));
3401 inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
3402 inst.step = (value, params) => inst.check(_multipleOf(value, params));
3403 inst.finite = () => inst;
3404 const bag = inst._zod.bag;
3405 inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
3406 inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
3407 inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
3408 inst.isFinite = true;
3409 inst.format = bag.format ?? null;
3410 });
3411 function number(params) {
3412 return _number(ZodNumber$1, params);
3413 }
3414 var ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => {
3415 $ZodNumberFormat.init(inst, def);
3416 ZodNumber$1.init(inst, def);
3417 });
3418 function int(params) {
3419 return _int(ZodNumberFormat, params);
3420 }
3421 var ZodBoolean$1 = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => {
3422 $ZodBoolean.init(inst, def);
3423 ZodType$1.init(inst, def);
3424 });
3425 function boolean(params) {
3426 return _boolean(ZodBoolean$1, params);
3427 }
3428 var ZodNull$1 = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => {
3429 $ZodNull.init(inst, def);
3430 ZodType$1.init(inst, def);
3431 });
3432 function _null(params) {
3433 return _null$1(ZodNull$1, params);
3434 }
3435 var ZodUnknown$1 = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => {
3436 $ZodUnknown.init(inst, def);
3437 ZodType$1.init(inst, def);
3438 });
3439 function unknown() {
3440 return _unknown(ZodUnknown$1);
3441 }
3442 var ZodNever$1 = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => {
3443 $ZodNever.init(inst, def);
3444 ZodType$1.init(inst, def);
3445 });
3446 function never(params) {
3447 return _never(ZodNever$1, params);
3448 }
3449 var ZodArray$1 = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => {
3450 $ZodArray.init(inst, def);
3451 ZodType$1.init(inst, def);
3452 inst.element = def.element;
3453 inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
3454 inst.nonempty = (params) => inst.check(_minLength(1, params));
3455 inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
3456 inst.length = (len, params) => inst.check(_length(len, params));
3457 inst.unwrap = () => inst.element;
3458 });
3459 function array(element, params) {
3460 return _array(ZodArray$1, element, params);
3461 }
3462 var ZodObject$1 = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
3463 $ZodObject.init(inst, def);
3464 ZodType$1.init(inst, def);
3465 defineLazy(inst, "shape", () => def.shape);
3466 inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
3467 inst.catchall = (catchall) => inst.clone({
3468 ...inst._zod.def,
3469 catchall
3470 });
3471 inst.passthrough = () => inst.clone({
3472 ...inst._zod.def,
3473 catchall: unknown()
3474 });
3475 inst.loose = () => inst.clone({
3476 ...inst._zod.def,
3477 catchall: unknown()
3478 });
3479 inst.strict = () => inst.clone({
3480 ...inst._zod.def,
3481 catchall: never()
3482 });
3483 inst.strip = () => inst.clone({
3484 ...inst._zod.def,
3485 catchall: void 0
3486 });
3487 inst.extend = (incoming) => {
3488 return extend(inst, incoming);
3489 };
3490 inst.merge = (other) => merge(inst, other);
3491 inst.pick = (mask) => pick(inst, mask);
3492 inst.omit = (mask) => omit(inst, mask);
3493 inst.partial = (...args) => partial(ZodOptional$1, inst, args[0]);
3494 inst.required = (...args) => required$1(ZodNonOptional, inst, args[0]);
3495 });
3496 function object$1(shape, params) {
3497 const def = {
3498 type: "object",
3499 get shape() {
3500 assignProp(this, "shape", { ...shape });
3501 return this.shape;
3502 },
3503 ...normalizeParams(params)
3504 };
3505 return new ZodObject$1(def);
3506 }
3507 __name(object$1, "object");
3508 function looseObject(shape, params) {
3509 return new ZodObject$1({
3510 type: "object",
3511 get shape() {
3512 assignProp(this, "shape", { ...shape });
3513 return this.shape;
3514 },
3515 catchall: unknown(),
3516 ...normalizeParams(params)
3517 });
3518 }
3519 var ZodUnion$1 = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
3520 $ZodUnion.init(inst, def);
3521 ZodType$1.init(inst, def);
3522 inst.options = def.options;
3523 });
3524 function union(options, params) {
3525 return new ZodUnion$1({
3526 type: "union",
3527 options,
3528 ...normalizeParams(params)
3529 });
3530 }
3531 var ZodDiscriminatedUnion$1 = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => {
3532 ZodUnion$1.init(inst, def);
3533 $ZodDiscriminatedUnion.init(inst, def);
3534 });
3535 function discriminatedUnion(discriminator, options, params) {
3536 return new ZodDiscriminatedUnion$1({
3537 type: "union",
3538 options,
3539 discriminator,
3540 ...normalizeParams(params)
3541 });
3542 }
3543 var ZodIntersection$1 = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
3544 $ZodIntersection.init(inst, def);
3545 ZodType$1.init(inst, def);
3546 });
3547 function intersection(left, right) {
3548 return new ZodIntersection$1({
3549 type: "intersection",
3550 left,
3551 right
3552 });
3553 }
3554 var ZodRecord$1 = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => {
3555 $ZodRecord.init(inst, def);
3556 ZodType$1.init(inst, def);
3557 inst.keyType = def.keyType;
3558 inst.valueType = def.valueType;
3559 });
3560 function record(keyType, valueType, params) {
3561 return new ZodRecord$1({
3562 type: "record",
3563 keyType,
3564 valueType,
3565 ...normalizeParams(params)
3566 });
3567 }
3568 var ZodEnum$1 = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => {
3569 $ZodEnum.init(inst, def);
3570 ZodType$1.init(inst, def);
3571 inst.enum = def.entries;
3572 inst.options = Object.values(def.entries);
3573 const keys = new Set(Object.keys(def.entries));
3574 inst.extract = (values, params) => {
3575 const newEntries = {};
3576 for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
3577 else throw new Error(`Key ${value} not found in enum`);
3578 return new ZodEnum$1({
3579 ...def,
3580 checks: [],
3581 ...normalizeParams(params),
3582 entries: newEntries
3583 });
3584 };
3585 inst.exclude = (values, params) => {
3586 const newEntries = { ...def.entries };
3587 for (const value of values) if (keys.has(value)) delete newEntries[value];
3588 else throw new Error(`Key ${value} not found in enum`);
3589 return new ZodEnum$1({
3590 ...def,
3591 checks: [],
3592 ...normalizeParams(params),
3593 entries: newEntries
3594 });
3595 };
3596 });
3597 function _enum(values, params) {
3598 const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
3599 return new ZodEnum$1({
3600 type: "enum",
3601 entries,
3602 ...normalizeParams(params)
3603 });
3604 }
3605 var ZodLiteral$1 = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => {
3606 $ZodLiteral.init(inst, def);
3607 ZodType$1.init(inst, def);
3608 inst.values = new Set(def.values);
3609 Object.defineProperty(inst, "value", { get() {
3610 if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
3611 return def.values[0];
3612 } });
3613 });
3614 function literal(value, params) {
3615 return new ZodLiteral$1({
3616 type: "literal",
3617 values: Array.isArray(value) ? value : [value],
3618 ...normalizeParams(params)
3619 });
3620 }
3621 var ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
3622 $ZodTransform.init(inst, def);
3623 ZodType$1.init(inst, def);
3624 inst._zod.parse = (payload, _ctx) => {
3625 payload.addIssue = (issue$2) => {
3626 if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, def));
3627 else {
3628 const _issue = issue$2;
3629 if (_issue.fatal) _issue.continue = false;
3630 _issue.code ?? (_issue.code = "custom");
3631 _issue.input ?? (_issue.input = payload.value);
3632 _issue.inst ?? (_issue.inst = inst);
3633 _issue.continue ?? (_issue.continue = true);
3634 payload.issues.push(issue(_issue));
3635 }
3636 };
3637 const output = def.transform(payload.value, payload);
3638 if (output instanceof Promise) return output.then((output) => {
3639 payload.value = output;
3640 return payload;
3641 });
3642 payload.value = output;
3643 return payload;
3644 };
3645 });
3646 function transform(fn) {
3647 return new ZodTransform({
3648 type: "transform",
3649 transform: fn
3650 });
3651 }
3652 var ZodOptional$1 = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => {
3653 $ZodOptional.init(inst, def);
3654 ZodType$1.init(inst, def);
3655 inst.unwrap = () => inst._zod.def.innerType;
3656 });
3657 function optional(innerType) {
3658 return new ZodOptional$1({
3659 type: "optional",
3660 innerType
3661 });
3662 }
3663 var ZodNullable$1 = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => {
3664 $ZodNullable.init(inst, def);
3665 ZodType$1.init(inst, def);
3666 inst.unwrap = () => inst._zod.def.innerType;
3667 });
3668 function nullable(innerType) {
3669 return new ZodNullable$1({
3670 type: "nullable",
3671 innerType
3672 });
3673 }
3674 var ZodDefault$1 = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => {
3675 $ZodDefault.init(inst, def);
3676 ZodType$1.init(inst, def);
3677 inst.unwrap = () => inst._zod.def.innerType;
3678 inst.removeDefault = inst.unwrap;
3679 });
3680 function _default(innerType, defaultValue) {
3681 return new ZodDefault$1({
3682 type: "default",
3683 innerType,
3684 get defaultValue() {
3685 return typeof defaultValue === "function" ? defaultValue() : defaultValue;
3686 }
3687 });
3688 }
3689 var ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => {
3690 $ZodPrefault.init(inst, def);
3691 ZodType$1.init(inst, def);
3692 inst.unwrap = () => inst._zod.def.innerType;
3693 });
3694 function prefault(innerType, defaultValue) {
3695 return new ZodPrefault({
3696 type: "prefault",
3697 innerType,
3698 get defaultValue() {
3699 return typeof defaultValue === "function" ? defaultValue() : defaultValue;
3700 }
3701 });
3702 }
3703 var ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
3704 $ZodNonOptional.init(inst, def);
3705 ZodType$1.init(inst, def);
3706 inst.unwrap = () => inst._zod.def.innerType;
3707 });
3708 function nonoptional(innerType, params) {
3709 return new ZodNonOptional({
3710 type: "nonoptional",
3711 innerType,
3712 ...normalizeParams(params)
3713 });
3714 }
3715 var ZodCatch$1 = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
3716 $ZodCatch.init(inst, def);
3717 ZodType$1.init(inst, def);
3718 inst.unwrap = () => inst._zod.def.innerType;
3719 inst.removeCatch = inst.unwrap;
3720 });
3721 function _catch(innerType, catchValue) {
3722 return new ZodCatch$1({
3723 type: "catch",
3724 innerType,
3725 catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
3726 });
3727 }
3728 var ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
3729 $ZodPipe.init(inst, def);
3730 ZodType$1.init(inst, def);
3731 inst.in = def.in;
3732 inst.out = def.out;
3733 });
3734 function pipe(in_, out) {
3735 return new ZodPipe({
3736 type: "pipe",
3737 in: in_,
3738 out
3739 });
3740 }
3741 var ZodReadonly$1 = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
3742 $ZodReadonly.init(inst, def);
3743 ZodType$1.init(inst, def);
3744 });
3745 function readonly(innerType) {
3746 return new ZodReadonly$1({
3747 type: "readonly",
3748 innerType
3749 });
3750 }
3751 var ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
3752 $ZodCustom.init(inst, def);
3753 ZodType$1.init(inst, def);
3754 });
3755 function check(fn) {
3756 const ch = new $ZodCheck({ check: "custom" });
3757 ch._zod.check = fn;
3758 return ch;
3759 }
3760 function custom(fn, _params) {
3761 return _custom(ZodCustom, fn ?? (() => true), _params);
3762 }
3763 function refine(fn, _params = {}) {
3764 return _refine(ZodCustom, fn, _params);
3765 }
3766 function superRefine(fn) {
3767 const ch = check((payload) => {
3768 payload.addIssue = (issue$1) => {
3769 if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
3770 else {
3771 const _issue = issue$1;
3772 if (_issue.fatal) _issue.continue = false;
3773 _issue.code ?? (_issue.code = "custom");
3774 _issue.input ?? (_issue.input = payload.value);
3775 _issue.inst ?? (_issue.inst = ch);
3776 _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
3777 payload.issues.push(issue(_issue));
3778 }
3779 };
3780 return fn(payload.value, payload);
3781 });
3782 return ch;
3783 }
3784 function preprocess(fn, schema) {
3785 return pipe(transform(fn), schema);
3786 }
3787
3788 //#endregion
3789 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
3790 var LATEST_PROTOCOL_VERSION = "2025-11-25";
3791 var SUPPORTED_PROTOCOL_VERSIONS = [
3792 LATEST_PROTOCOL_VERSION,
3793 "2025-06-18",
3794 "2025-03-26",
3795 "2024-11-05",
3796 "2024-10-07"
3797 ];
3798 var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
3799 var JSONRPC_VERSION = "2.0";
3800 /**
3801 * Assert 'object' type schema.
3802 *
3803 * @internal
3804 */
3805 var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
3806 /**
3807 * A progress token, used to associate progress notifications with the original request.
3808 */
3809 var ProgressTokenSchema = union([string(), number().int()]);
3810 /**
3811 * An opaque token used to represent a cursor for pagination.
3812 */
3813 var CursorSchema = string();
3814 /**
3815 * Task creation parameters, used to ask that the server create a task to represent a request.
3816 */
3817 var TaskCreationParamsSchema = looseObject({
3818 /**
3819 * Time in milliseconds to keep task results available after completion.
3820 * If null, the task has unlimited lifetime until manually cleaned up.
3821 */
3822 ttl: union([number(), _null()]).optional(),
3823 /**
3824 * Time in milliseconds to wait between task status requests.
3825 */
3826 pollInterval: number().optional()
3827 });
3828 var TaskMetadataSchema = object$1({ ttl: number().optional() });
3829 /**
3830 * Metadata for associating messages with a task.
3831 * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.
3832 */
3833 var RelatedTaskMetadataSchema = object$1({ taskId: string() });
3834 var RequestMetaSchema = looseObject({
3835 /**
3836 * 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.
3837 */
3838 progressToken: ProgressTokenSchema.optional(),
3839 /**
3840 * If specified, this request is related to the provided task.
3841 */
3842 [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
3843 });
3844 /**
3845 * Common params for any request.
3846 */
3847 var BaseRequestParamsSchema = object$1({
3848 /**
3849 * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
3850 */
3851 _meta: RequestMetaSchema.optional() });
3852 /**
3853 * Common params for any task-augmented request.
3854 */
3855 var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
3856 /**
3857 * If specified, the caller is requesting task-augmented execution for this request.
3858 * The request will return a CreateTaskResult immediately, and the actual result can be
3859 * retrieved later via tasks/result.
3860 *
3861 * Task augmentation is subject to capability negotiation - receivers MUST declare support
3862 * for task augmentation of specific request types in their capabilities.
3863 */
3864 task: TaskMetadataSchema.optional() });
3865 /**
3866 * Checks if a value is a valid TaskAugmentedRequestParams.
3867 * @param value - The value to check.
3868 *
3869 * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.
3870 */
3871 var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
3872 var RequestSchema = object$1({
3873 method: string(),
3874 params: BaseRequestParamsSchema.loose().optional()
3875 });
3876 var NotificationsParamsSchema = object$1({
3877 /**
3878 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3879 * for notes on _meta usage.
3880 */
3881 _meta: RequestMetaSchema.optional() });
3882 var NotificationSchema = object$1({
3883 method: string(),
3884 params: NotificationsParamsSchema.loose().optional()
3885 });
3886 var ResultSchema = looseObject({
3887 /**
3888 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3889 * for notes on _meta usage.
3890 */
3891 _meta: RequestMetaSchema.optional() });
3892 /**
3893 * A uniquely identifying ID for a request in JSON-RPC.
3894 */
3895 var RequestIdSchema = union([string(), number().int()]);
3896 /**
3897 * A request that expects a response.
3898 */
3899 var JSONRPCRequestSchema = object$1({
3900 jsonrpc: literal("2.0"),
3901 id: RequestIdSchema,
3902 ...RequestSchema.shape
3903 }).strict();
3904 var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
3905 /**
3906 * A notification which does not expect a response.
3907 */
3908 var JSONRPCNotificationSchema = object$1({
3909 jsonrpc: literal("2.0"),
3910 ...NotificationSchema.shape
3911 }).strict();
3912 var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
3913 /**
3914 * A successful (non-error) response to a request.
3915 */
3916 var JSONRPCResultResponseSchema = object$1({
3917 jsonrpc: literal("2.0"),
3918 id: RequestIdSchema,
3919 result: ResultSchema
3920 }).strict();
3921 /**
3922 * Checks if a value is a valid JSONRPCResultResponse.
3923 * @param value - The value to check.
3924 *
3925 * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.
3926 */
3927 var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
3928 /**
3929 * Error codes defined by the JSON-RPC specification.
3930 */
3931 var ErrorCode;
3932 (function(ErrorCode) {
3933 ErrorCode[ErrorCode["ConnectionClosed"] = -32e3] = "ConnectionClosed";
3934 ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout";
3935 ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError";
3936 ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest";
3937 ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound";
3938 ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams";
3939 ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError";
3940 ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
3941 })(ErrorCode || (ErrorCode = {}));
3942 /**
3943 * A response to a request that indicates an error occurred.
3944 */
3945 var JSONRPCErrorResponseSchema = object$1({
3946 jsonrpc: literal("2.0"),
3947 id: RequestIdSchema.optional(),
3948 error: object$1({
3949 /**
3950 * The error type that occurred.
3951 */
3952 code: number().int(),
3953 /**
3954 * A short description of the error. The message SHOULD be limited to a concise single sentence.
3955 */
3956 message: string(),
3957 /**
3958 * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
3959 */
3960 data: unknown().optional()
3961 })
3962 }).strict();
3963 /**
3964 * Checks if a value is a valid JSONRPCErrorResponse.
3965 * @param value - The value to check.
3966 *
3967 * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.
3968 */
3969 var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
3970 var JSONRPCMessageSchema = union([
3971 JSONRPCRequestSchema,
3972 JSONRPCNotificationSchema,
3973 JSONRPCResultResponseSchema,
3974 JSONRPCErrorResponseSchema
3975 ]);
3976 var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
3977 /**
3978 * A response that indicates success but carries no data.
3979 */
3980 var EmptyResultSchema = ResultSchema.strict();
3981 var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
3982 /**
3983 * The ID of the request to cancel.
3984 *
3985 * This MUST correspond to the ID of a request previously issued in the same direction.
3986 */
3987 requestId: RequestIdSchema.optional(),
3988 /**
3989 * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
3990 */
3991 reason: string().optional()
3992 });
3993 /**
3994 * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.
3995 *
3996 * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.
3997 *
3998 * This notification indicates that the result will be unused, so any associated processing SHOULD cease.
3999 *
4000 * A client MUST NOT attempt to cancel its `initialize` request.
4001 */
4002 var CancelledNotificationSchema = NotificationSchema.extend({
4003 method: literal("notifications/cancelled"),
4004 params: CancelledNotificationParamsSchema
4005 });
4006 /**
4007 * Icon schema for use in tools, prompts, resources, and implementations.
4008 */
4009 var IconSchema = object$1({
4010 /**
4011 * URL or data URI for the icon.
4012 */
4013 src: string(),
4014 /**
4015 * Optional MIME type for the icon.
4016 */
4017 mimeType: string().optional(),
4018 /**
4019 * Optional array of strings that specify sizes at which the icon can be used.
4020 * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
4021 *
4022 * If not provided, the client should assume that the icon can be used at any size.
4023 */
4024 sizes: array(string()).optional(),
4025 /**
4026 * Optional specifier for the theme this icon is designed for. `light` indicates
4027 * the icon is designed to be used with a light background, and `dark` indicates
4028 * the icon is designed to be used with a dark background.
4029 *
4030 * If not provided, the client should assume the icon can be used with any theme.
4031 */
4032 theme: _enum(["light", "dark"]).optional()
4033 });
4034 /**
4035 * Base schema to add `icons` property.
4036 *
4037 */
4038 var IconsSchema = object$1({
4039 /**
4040 * Optional set of sized icons that the client can display in a user interface.
4041 *
4042 * Clients that support rendering icons MUST support at least the following MIME types:
4043 * - `image/png` - PNG images (safe, universal compatibility)
4044 * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
4045 *
4046 * Clients that support rendering icons SHOULD also support:
4047 * - `image/svg+xml` - SVG images (scalable but requires security precautions)
4048 * - `image/webp` - WebP images (modern, efficient format)
4049 */
4050 icons: array(IconSchema).optional() });
4051 /**
4052 * Base metadata interface for common properties across resources, tools, prompts, and implementations.
4053 */
4054 var BaseMetadataSchema = object$1({
4055 /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
4056 name: string(),
4057 /**
4058 * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
4059 * even by those unfamiliar with domain-specific terminology.
4060 *
4061 * If not provided, the name should be used for display (except for Tool,
4062 * where `annotations.title` should be given precedence over using `name`,
4063 * if present).
4064 */
4065 title: string().optional()
4066 });
4067 /**
4068 * Describes the name and version of an MCP implementation.
4069 */
4070 var ImplementationSchema = BaseMetadataSchema.extend({
4071 ...BaseMetadataSchema.shape,
4072 ...IconsSchema.shape,
4073 version: string(),
4074 /**
4075 * An optional URL of the website for this implementation.
4076 */
4077 websiteUrl: string().optional(),
4078 /**
4079 * An optional human-readable description of what this implementation does.
4080 *
4081 * This can be used by clients or servers to provide context about their purpose
4082 * and capabilities. For example, a server might describe the types of resources
4083 * or tools it provides, while a client might describe its intended use case.
4084 */
4085 description: string().optional()
4086 });
4087 var FormElicitationCapabilitySchema = intersection(object$1({ applyDefaults: boolean().optional() }), record(string(), unknown()));
4088 var ElicitationCapabilitySchema = preprocess((value) => {
4089 if (value && typeof value === "object" && !Array.isArray(value)) {
4090 if (Object.keys(value).length === 0) return { form: {} };
4091 }
4092 return value;
4093 }, intersection(object$1({
4094 form: FormElicitationCapabilitySchema.optional(),
4095 url: AssertObjectSchema.optional()
4096 }), record(string(), unknown()).optional()));
4097 /**
4098 * Task capabilities for clients, indicating which request types support task creation.
4099 */
4100 var ClientTasksCapabilitySchema = looseObject({
4101 /**
4102 * Present if the client supports listing tasks.
4103 */
4104 list: AssertObjectSchema.optional(),
4105 /**
4106 * Present if the client supports cancelling tasks.
4107 */
4108 cancel: AssertObjectSchema.optional(),
4109 /**
4110 * Capabilities for task creation on specific request types.
4111 */
4112 requests: looseObject({
4113 /**
4114 * Task support for sampling requests.
4115 */
4116 sampling: looseObject({ createMessage: AssertObjectSchema.optional() }).optional(),
4117 /**
4118 * Task support for elicitation requests.
4119 */
4120 elicitation: looseObject({ create: AssertObjectSchema.optional() }).optional()
4121 }).optional()
4122 });
4123 /**
4124 * Task capabilities for servers, indicating which request types support task creation.
4125 */
4126 var ServerTasksCapabilitySchema = looseObject({
4127 /**
4128 * Present if the server supports listing tasks.
4129 */
4130 list: AssertObjectSchema.optional(),
4131 /**
4132 * Present if the server supports cancelling tasks.
4133 */
4134 cancel: AssertObjectSchema.optional(),
4135 /**
4136 * Capabilities for task creation on specific request types.
4137 */
4138 requests: looseObject({
4139 /**
4140 * Task support for tool requests.
4141 */
4142 tools: looseObject({ call: AssertObjectSchema.optional() }).optional() }).optional()
4143 });
4144 /**
4145 * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
4146 */
4147 var ClientCapabilitiesSchema = object$1({
4148 /**
4149 * Experimental, non-standard capabilities that the client supports.
4150 */
4151 experimental: record(string(), AssertObjectSchema).optional(),
4152 /**
4153 * Present if the client supports sampling from an LLM.
4154 */
4155 sampling: object$1({
4156 /**
4157 * Present if the client supports context inclusion via includeContext parameter.
4158 * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
4159 */
4160 context: AssertObjectSchema.optional(),
4161 /**
4162 * Present if the client supports tool use via tools and toolChoice parameters.
4163 */
4164 tools: AssertObjectSchema.optional()
4165 }).optional(),
4166 /**
4167 * Present if the client supports eliciting user input.
4168 */
4169 elicitation: ElicitationCapabilitySchema.optional(),
4170 /**
4171 * Present if the client supports listing roots.
4172 */
4173 roots: object$1({
4174 /**
4175 * Whether the client supports issuing notifications for changes to the roots list.
4176 */
4177 listChanged: boolean().optional() }).optional(),
4178 /**
4179 * Present if the client supports task creation.
4180 */
4181 tasks: ClientTasksCapabilitySchema.optional()
4182 });
4183 var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
4184 /**
4185 * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
4186 */
4187 protocolVersion: string(),
4188 capabilities: ClientCapabilitiesSchema,
4189 clientInfo: ImplementationSchema
4190 });
4191 /**
4192 * This request is sent from the client to the server when it first connects, asking it to begin initialization.
4193 */
4194 var InitializeRequestSchema = RequestSchema.extend({
4195 method: literal("initialize"),
4196 params: InitializeRequestParamsSchema
4197 });
4198 /**
4199 * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
4200 */
4201 var ServerCapabilitiesSchema = object$1({
4202 /**
4203 * Experimental, non-standard capabilities that the server supports.
4204 */
4205 experimental: record(string(), AssertObjectSchema).optional(),
4206 /**
4207 * Present if the server supports sending log messages to the client.
4208 */
4209 logging: AssertObjectSchema.optional(),
4210 /**
4211 * Present if the server supports sending completions to the client.
4212 */
4213 completions: AssertObjectSchema.optional(),
4214 /**
4215 * Present if the server offers any prompt templates.
4216 */
4217 prompts: object$1({
4218 /**
4219 * Whether this server supports issuing notifications for changes to the prompt list.
4220 */
4221 listChanged: boolean().optional() }).optional(),
4222 /**
4223 * Present if the server offers any resources to read.
4224 */
4225 resources: object$1({
4226 /**
4227 * Whether this server supports clients subscribing to resource updates.
4228 */
4229 subscribe: boolean().optional(),
4230 /**
4231 * Whether this server supports issuing notifications for changes to the resource list.
4232 */
4233 listChanged: boolean().optional()
4234 }).optional(),
4235 /**
4236 * Present if the server offers any tools to call.
4237 */
4238 tools: object$1({
4239 /**
4240 * Whether this server supports issuing notifications for changes to the tool list.
4241 */
4242 listChanged: boolean().optional() }).optional(),
4243 /**
4244 * Present if the server supports task creation.
4245 */
4246 tasks: ServerTasksCapabilitySchema.optional()
4247 });
4248 /**
4249 * After receiving an initialize request from the client, the server sends this response.
4250 */
4251 var InitializeResultSchema = ResultSchema.extend({
4252 /**
4253 * 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.
4254 */
4255 protocolVersion: string(),
4256 capabilities: ServerCapabilitiesSchema,
4257 serverInfo: ImplementationSchema,
4258 /**
4259 * Instructions describing how to use the server and its features.
4260 *
4261 * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
4262 */
4263 instructions: string().optional()
4264 });
4265 /**
4266 * This notification is sent from the client to the server after initialization has finished.
4267 */
4268 var InitializedNotificationSchema = NotificationSchema.extend({
4269 method: literal("notifications/initialized"),
4270 params: NotificationsParamsSchema.optional()
4271 });
4272 /**
4273 * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.
4274 */
4275 var PingRequestSchema = RequestSchema.extend({
4276 method: literal("ping"),
4277 params: BaseRequestParamsSchema.optional()
4278 });
4279 var ProgressSchema = object$1({
4280 /**
4281 * The progress thus far. This should increase every time progress is made, even if the total is unknown.
4282 */
4283 progress: number(),
4284 /**
4285 * Total number of items to process (or total progress required), if known.
4286 */
4287 total: optional(number()),
4288 /**
4289 * An optional message describing the current progress.
4290 */
4291 message: optional(string())
4292 });
4293 var ProgressNotificationParamsSchema = object$1({
4294 ...NotificationsParamsSchema.shape,
4295 ...ProgressSchema.shape,
4296 /**
4297 * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
4298 */
4299 progressToken: ProgressTokenSchema
4300 });
4301 /**
4302 * An out-of-band notification used to inform the receiver of a progress update for a long-running request.
4303 *
4304 * @category notifications/progress
4305 */
4306 var ProgressNotificationSchema = NotificationSchema.extend({
4307 method: literal("notifications/progress"),
4308 params: ProgressNotificationParamsSchema
4309 });
4310 var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
4311 /**
4312 * An opaque token representing the current pagination position.
4313 * If provided, the server should return results starting after this cursor.
4314 */
4315 cursor: CursorSchema.optional() });
4316 var PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() });
4317 var PaginatedResultSchema = ResultSchema.extend({
4318 /**
4319 * An opaque token representing the pagination position after the last returned result.
4320 * If present, there may be more results available.
4321 */
4322 nextCursor: CursorSchema.optional() });
4323 /**
4324 * The status of a task.
4325 * */
4326 var TaskStatusSchema = _enum([
4327 "working",
4328 "input_required",
4329 "completed",
4330 "failed",
4331 "cancelled"
4332 ]);
4333 /**
4334 * A pollable state object associated with a request.
4335 */
4336 var TaskSchema = object$1({
4337 taskId: string(),
4338 status: TaskStatusSchema,
4339 /**
4340 * Time in milliseconds to keep task results available after completion.
4341 * If null, the task has unlimited lifetime until manually cleaned up.
4342 */
4343 ttl: union([number(), _null()]),
4344 /**
4345 * ISO 8601 timestamp when the task was created.
4346 */
4347 createdAt: string(),
4348 /**
4349 * ISO 8601 timestamp when the task was last updated.
4350 */
4351 lastUpdatedAt: string(),
4352 pollInterval: optional(number()),
4353 /**
4354 * Optional diagnostic message for failed tasks or other status information.
4355 */
4356 statusMessage: optional(string())
4357 });
4358 /**
4359 * Result returned when a task is created, containing the task data wrapped in a task field.
4360 */
4361 var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema });
4362 /**
4363 * Parameters for task status notification.
4364 */
4365 var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
4366 /**
4367 * A notification sent when a task's status changes.
4368 */
4369 var TaskStatusNotificationSchema = NotificationSchema.extend({
4370 method: literal("notifications/tasks/status"),
4371 params: TaskStatusNotificationParamsSchema
4372 });
4373 /**
4374 * A request to get the state of a specific task.
4375 */
4376 var GetTaskRequestSchema = RequestSchema.extend({
4377 method: literal("tasks/get"),
4378 params: BaseRequestParamsSchema.extend({ taskId: string() })
4379 });
4380 /**
4381 * The response to a tasks/get request.
4382 */
4383 var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
4384 /**
4385 * A request to get the result of a specific task.
4386 */
4387 var GetTaskPayloadRequestSchema = RequestSchema.extend({
4388 method: literal("tasks/result"),
4389 params: BaseRequestParamsSchema.extend({ taskId: string() })
4390 });
4391 /**
4392 * The response to a tasks/result request.
4393 * The structure matches the result type of the original request.
4394 * For example, a tools/call task would return the CallToolResult structure.
4395 *
4396 */
4397 var GetTaskPayloadResultSchema = ResultSchema.loose();
4398 /**
4399 * A request to list tasks.
4400 */
4401 var ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") });
4402 /**
4403 * The response to a tasks/list request.
4404 */
4405 var ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) });
4406 /**
4407 * A request to cancel a specific task.
4408 */
4409 var CancelTaskRequestSchema = RequestSchema.extend({
4410 method: literal("tasks/cancel"),
4411 params: BaseRequestParamsSchema.extend({ taskId: string() })
4412 });
4413 /**
4414 * The response to a tasks/cancel request.
4415 */
4416 var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
4417 /**
4418 * The contents of a specific resource or sub-resource.
4419 */
4420 var ResourceContentsSchema = object$1({
4421 /**
4422 * The URI of this resource.
4423 */
4424 uri: string(),
4425 /**
4426 * The MIME type of this resource, if known.
4427 */
4428 mimeType: optional(string()),
4429 /**
4430 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4431 * for notes on _meta usage.
4432 */
4433 _meta: record(string(), unknown()).optional()
4434 });
4435 var TextResourceContentsSchema = ResourceContentsSchema.extend({
4436 /**
4437 * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
4438 */
4439 text: string() });
4440 /**
4441 * A Zod schema for validating Base64 strings that is more performant and
4442 * robust for very large inputs than the default regex-based check. It avoids
4443 * stack overflows by using the native `atob` function for validation.
4444 */
4445 var Base64Schema = string().refine((val) => {
4446 try {
4447 atob(val);
4448 return true;
4449 } catch {
4450 return false;
4451 }
4452 }, { message: "Invalid Base64 string" });
4453 var BlobResourceContentsSchema = ResourceContentsSchema.extend({
4454 /**
4455 * A base64-encoded string representing the binary data of the item.
4456 */
4457 blob: Base64Schema });
4458 /**
4459 * The sender or recipient of messages and data in a conversation.
4460 */
4461 var RoleSchema = _enum(["user", "assistant"]);
4462 /**
4463 * Optional annotations providing clients additional context about a resource.
4464 */
4465 var AnnotationsSchema = object$1({
4466 /**
4467 * Intended audience(s) for the resource.
4468 */
4469 audience: array(RoleSchema).optional(),
4470 /**
4471 * Importance hint for the resource, from 0 (least) to 1 (most).
4472 */
4473 priority: number().min(0).max(1).optional(),
4474 /**
4475 * ISO 8601 timestamp for the most recent modification.
4476 */
4477 lastModified: datetime({ offset: true }).optional()
4478 });
4479 /**
4480 * A known resource that the server is capable of reading.
4481 */
4482 var ResourceSchema = object$1({
4483 ...BaseMetadataSchema.shape,
4484 ...IconsSchema.shape,
4485 /**
4486 * The URI of this resource.
4487 */
4488 uri: string(),
4489 /**
4490 * A description of what this resource represents.
4491 *
4492 * 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.
4493 */
4494 description: optional(string()),
4495 /**
4496 * The MIME type of this resource, if known.
4497 */
4498 mimeType: optional(string()),
4499 /**
4500 * Optional annotations for the client.
4501 */
4502 annotations: AnnotationsSchema.optional(),
4503 /**
4504 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4505 * for notes on _meta usage.
4506 */
4507 _meta: optional(looseObject({}))
4508 });
4509 /**
4510 * A template description for resources available on the server.
4511 */
4512 var ResourceTemplateSchema = object$1({
4513 ...BaseMetadataSchema.shape,
4514 ...IconsSchema.shape,
4515 /**
4516 * A URI template (according to RFC 6570) that can be used to construct resource URIs.
4517 */
4518 uriTemplate: string(),
4519 /**
4520 * A description of what this template is for.
4521 *
4522 * 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.
4523 */
4524 description: optional(string()),
4525 /**
4526 * 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.
4527 */
4528 mimeType: optional(string()),
4529 /**
4530 * Optional annotations for the client.
4531 */
4532 annotations: AnnotationsSchema.optional(),
4533 /**
4534 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4535 * for notes on _meta usage.
4536 */
4537 _meta: optional(looseObject({}))
4538 });
4539 /**
4540 * Sent from the client to request a list of resources the server has.
4541 */
4542 var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") });
4543 /**
4544 * The server's response to a resources/list request from the client.
4545 */
4546 var ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) });
4547 /**
4548 * Sent from the client to request a list of resource templates the server has.
4549 */
4550 var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") });
4551 /**
4552 * The server's response to a resources/templates/list request from the client.
4553 */
4554 var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) });
4555 var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
4556 /**
4557 * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
4558 *
4559 * @format uri
4560 */
4561 uri: string() });
4562 /**
4563 * Parameters for a `resources/read` request.
4564 */
4565 var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
4566 /**
4567 * Sent from the client to the server, to read a specific resource URI.
4568 */
4569 var ReadResourceRequestSchema = RequestSchema.extend({
4570 method: literal("resources/read"),
4571 params: ReadResourceRequestParamsSchema
4572 });
4573 /**
4574 * The server's response to a resources/read request from the client.
4575 */
4576 var ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) });
4577 /**
4578 * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.
4579 */
4580 var ResourceListChangedNotificationSchema = NotificationSchema.extend({
4581 method: literal("notifications/resources/list_changed"),
4582 params: NotificationsParamsSchema.optional()
4583 });
4584 var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
4585 /**
4586 * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.
4587 */
4588 var SubscribeRequestSchema = RequestSchema.extend({
4589 method: literal("resources/subscribe"),
4590 params: SubscribeRequestParamsSchema
4591 });
4592 var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
4593 /**
4594 * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.
4595 */
4596 var UnsubscribeRequestSchema = RequestSchema.extend({
4597 method: literal("resources/unsubscribe"),
4598 params: UnsubscribeRequestParamsSchema
4599 });
4600 /**
4601 * Parameters for a `notifications/resources/updated` notification.
4602 */
4603 var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
4604 /**
4605 * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
4606 */
4607 uri: string() });
4608 /**
4609 * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.
4610 */
4611 var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
4612 method: literal("notifications/resources/updated"),
4613 params: ResourceUpdatedNotificationParamsSchema
4614 });
4615 /**
4616 * Describes an argument that a prompt can accept.
4617 */
4618 var PromptArgumentSchema = object$1({
4619 /**
4620 * The name of the argument.
4621 */
4622 name: string(),
4623 /**
4624 * A human-readable description of the argument.
4625 */
4626 description: optional(string()),
4627 /**
4628 * Whether this argument must be provided.
4629 */
4630 required: optional(boolean())
4631 });
4632 /**
4633 * A prompt or prompt template that the server offers.
4634 */
4635 var PromptSchema = object$1({
4636 ...BaseMetadataSchema.shape,
4637 ...IconsSchema.shape,
4638 /**
4639 * An optional description of what this prompt provides
4640 */
4641 description: optional(string()),
4642 /**
4643 * A list of arguments to use for templating the prompt.
4644 */
4645 arguments: optional(array(PromptArgumentSchema)),
4646 /**
4647 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4648 * for notes on _meta usage.
4649 */
4650 _meta: optional(looseObject({}))
4651 });
4652 /**
4653 * Sent from the client to request a list of prompts and prompt templates the server has.
4654 */
4655 var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") });
4656 /**
4657 * The server's response to a prompts/list request from the client.
4658 */
4659 var ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) });
4660 /**
4661 * Parameters for a `prompts/get` request.
4662 */
4663 var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
4664 /**
4665 * The name of the prompt or prompt template.
4666 */
4667 name: string(),
4668 /**
4669 * Arguments to use for templating the prompt.
4670 */
4671 arguments: record(string(), string()).optional()
4672 });
4673 /**
4674 * Used by the client to get a prompt provided by the server.
4675 */
4676 var GetPromptRequestSchema = RequestSchema.extend({
4677 method: literal("prompts/get"),
4678 params: GetPromptRequestParamsSchema
4679 });
4680 /**
4681 * Text provided to or from an LLM.
4682 */
4683 var TextContentSchema = object$1({
4684 type: literal("text"),
4685 /**
4686 * The text content of the message.
4687 */
4688 text: string(),
4689 /**
4690 * Optional annotations for the client.
4691 */
4692 annotations: AnnotationsSchema.optional(),
4693 /**
4694 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4695 * for notes on _meta usage.
4696 */
4697 _meta: record(string(), unknown()).optional()
4698 });
4699 /**
4700 * An image provided to or from an LLM.
4701 */
4702 var ImageContentSchema = object$1({
4703 type: literal("image"),
4704 /**
4705 * The base64-encoded image data.
4706 */
4707 data: Base64Schema,
4708 /**
4709 * The MIME type of the image. Different providers may support different image types.
4710 */
4711 mimeType: string(),
4712 /**
4713 * Optional annotations for the client.
4714 */
4715 annotations: AnnotationsSchema.optional(),
4716 /**
4717 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4718 * for notes on _meta usage.
4719 */
4720 _meta: record(string(), unknown()).optional()
4721 });
4722 /**
4723 * An Audio provided to or from an LLM.
4724 */
4725 var AudioContentSchema = object$1({
4726 type: literal("audio"),
4727 /**
4728 * The base64-encoded audio data.
4729 */
4730 data: Base64Schema,
4731 /**
4732 * The MIME type of the audio. Different providers may support different audio types.
4733 */
4734 mimeType: string(),
4735 /**
4736 * Optional annotations for the client.
4737 */
4738 annotations: AnnotationsSchema.optional(),
4739 /**
4740 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4741 * for notes on _meta usage.
4742 */
4743 _meta: record(string(), unknown()).optional()
4744 });
4745 /**
4746 * A tool call request from an assistant (LLM).
4747 * Represents the assistant's request to use a tool.
4748 */
4749 var ToolUseContentSchema = object$1({
4750 type: literal("tool_use"),
4751 /**
4752 * The name of the tool to invoke.
4753 * Must match a tool name from the request's tools array.
4754 */
4755 name: string(),
4756 /**
4757 * Unique identifier for this tool call.
4758 * Used to correlate with ToolResultContent in subsequent messages.
4759 */
4760 id: string(),
4761 /**
4762 * Arguments to pass to the tool.
4763 * Must conform to the tool's inputSchema.
4764 */
4765 input: record(string(), unknown()),
4766 /**
4767 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4768 * for notes on _meta usage.
4769 */
4770 _meta: record(string(), unknown()).optional()
4771 });
4772 /**
4773 * The contents of a resource, embedded into a prompt or tool call result.
4774 */
4775 var EmbeddedResourceSchema = object$1({
4776 type: literal("resource"),
4777 resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
4778 /**
4779 * Optional annotations for the client.
4780 */
4781 annotations: AnnotationsSchema.optional(),
4782 /**
4783 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4784 * for notes on _meta usage.
4785 */
4786 _meta: record(string(), unknown()).optional()
4787 });
4788 /**
4789 * A resource that the server is capable of reading, included in a prompt or tool call result.
4790 *
4791 * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.
4792 */
4793 var ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") });
4794 /**
4795 * A content block that can be used in prompts and tool results.
4796 */
4797 var ContentBlockSchema = union([
4798 TextContentSchema,
4799 ImageContentSchema,
4800 AudioContentSchema,
4801 ResourceLinkSchema,
4802 EmbeddedResourceSchema
4803 ]);
4804 /**
4805 * Describes a message returned as part of a prompt.
4806 */
4807 var PromptMessageSchema = object$1({
4808 role: RoleSchema,
4809 content: ContentBlockSchema
4810 });
4811 /**
4812 * The server's response to a prompts/get request from the client.
4813 */
4814 var GetPromptResultSchema = ResultSchema.extend({
4815 /**
4816 * An optional description for the prompt.
4817 */
4818 description: string().optional(),
4819 messages: array(PromptMessageSchema)
4820 });
4821 /**
4822 * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.
4823 */
4824 var PromptListChangedNotificationSchema = NotificationSchema.extend({
4825 method: literal("notifications/prompts/list_changed"),
4826 params: NotificationsParamsSchema.optional()
4827 });
4828 /**
4829 * Additional properties describing a Tool to clients.
4830 *
4831 * NOTE: all properties in ToolAnnotations are **hints**.
4832 * They are not guaranteed to provide a faithful description of
4833 * tool behavior (including descriptive properties like `title`).
4834 *
4835 * Clients should never make tool use decisions based on ToolAnnotations
4836 * received from untrusted servers.
4837 */
4838 var ToolAnnotationsSchema = object$1({
4839 /**
4840 * A human-readable title for the tool.
4841 */
4842 title: string().optional(),
4843 /**
4844 * If true, the tool does not modify its environment.
4845 *
4846 * Default: false
4847 */
4848 readOnlyHint: boolean().optional(),
4849 /**
4850 * If true, the tool may perform destructive updates to its environment.
4851 * If false, the tool performs only additive updates.
4852 *
4853 * (This property is meaningful only when `readOnlyHint == false`)
4854 *
4855 * Default: true
4856 */
4857 destructiveHint: boolean().optional(),
4858 /**
4859 * If true, calling the tool repeatedly with the same arguments
4860 * will have no additional effect on the its environment.
4861 *
4862 * (This property is meaningful only when `readOnlyHint == false`)
4863 *
4864 * Default: false
4865 */
4866 idempotentHint: boolean().optional(),
4867 /**
4868 * If true, this tool may interact with an "open world" of external
4869 * entities. If false, the tool's domain of interaction is closed.
4870 * For example, the world of a web search tool is open, whereas that
4871 * of a memory tool is not.
4872 *
4873 * Default: true
4874 */
4875 openWorldHint: boolean().optional()
4876 });
4877 /**
4878 * Execution-related properties for a tool.
4879 */
4880 var ToolExecutionSchema = object$1({
4881 /**
4882 * Indicates the tool's preference for task-augmented execution.
4883 * - "required": Clients MUST invoke the tool as a task
4884 * - "optional": Clients MAY invoke the tool as a task or normal request
4885 * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
4886 *
4887 * If not present, defaults to "forbidden".
4888 */
4889 taskSupport: _enum([
4890 "required",
4891 "optional",
4892 "forbidden"
4893 ]).optional() });
4894 /**
4895 * Definition for a tool the client can call.
4896 */
4897 var ToolSchema = object$1({
4898 ...BaseMetadataSchema.shape,
4899 ...IconsSchema.shape,
4900 /**
4901 * A human-readable description of the tool.
4902 */
4903 description: string().optional(),
4904 /**
4905 * A JSON Schema 2020-12 object defining the expected parameters for the tool.
4906 * Must have type: 'object' at the root level per MCP spec.
4907 */
4908 inputSchema: object$1({
4909 type: literal("object"),
4910 properties: record(string(), AssertObjectSchema).optional(),
4911 required: array(string()).optional()
4912 }).catchall(unknown()),
4913 /**
4914 * An optional JSON Schema 2020-12 object defining the structure of the tool's output
4915 * returned in the structuredContent field of a CallToolResult.
4916 * Must have type: 'object' at the root level per MCP spec.
4917 */
4918 outputSchema: object$1({
4919 type: literal("object"),
4920 properties: record(string(), AssertObjectSchema).optional(),
4921 required: array(string()).optional()
4922 }).catchall(unknown()).optional(),
4923 /**
4924 * Optional additional tool information.
4925 */
4926 annotations: ToolAnnotationsSchema.optional(),
4927 /**
4928 * Execution-related properties for this tool.
4929 */
4930 execution: ToolExecutionSchema.optional(),
4931 /**
4932 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4933 * for notes on _meta usage.
4934 */
4935 _meta: record(string(), unknown()).optional()
4936 });
4937 /**
4938 * Sent from the client to request a list of tools the server has.
4939 */
4940 var ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") });
4941 /**
4942 * The server's response to a tools/list request from the client.
4943 */
4944 var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) });
4945 /**
4946 * The server's response to a tool call.
4947 */
4948 var CallToolResultSchema = ResultSchema.extend({
4949 /**
4950 * A list of content objects that represent the result of the tool call.
4951 *
4952 * If the Tool does not define an outputSchema, this field MUST be present in the result.
4953 * For backwards compatibility, this field is always present, but it may be empty.
4954 */
4955 content: array(ContentBlockSchema).default([]),
4956 /**
4957 * An object containing structured tool output.
4958 *
4959 * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
4960 */
4961 structuredContent: record(string(), unknown()).optional(),
4962 /**
4963 * Whether the tool call ended in an error.
4964 *
4965 * If not set, this is assumed to be false (the call was successful).
4966 *
4967 * Any errors that originate from the tool SHOULD be reported inside the result
4968 * object, with `isError` set to true, _not_ as an MCP protocol-level error
4969 * response. Otherwise, the LLM would not be able to see that an error occurred
4970 * and self-correct.
4971 *
4972 * However, any errors in _finding_ the tool, an error indicating that the
4973 * server does not support tool calls, or any other exceptional conditions,
4974 * should be reported as an MCP error response.
4975 */
4976 isError: boolean().optional()
4977 });
4978 /**
4979 * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.
4980 */
4981 var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() }));
4982 /**
4983 * Parameters for a `tools/call` request.
4984 */
4985 var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
4986 /**
4987 * The name of the tool to call.
4988 */
4989 name: string(),
4990 /**
4991 * Arguments to pass to the tool.
4992 */
4993 arguments: record(string(), unknown()).optional()
4994 });
4995 /**
4996 * Used by the client to invoke a tool provided by the server.
4997 */
4998 var CallToolRequestSchema = RequestSchema.extend({
4999 method: literal("tools/call"),
5000 params: CallToolRequestParamsSchema
5001 });
5002 /**
5003 * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.
5004 */
5005 var ToolListChangedNotificationSchema = NotificationSchema.extend({
5006 method: literal("notifications/tools/list_changed"),
5007 params: NotificationsParamsSchema.optional()
5008 });
5009 /**
5010 * Base schema for list changed subscription options (without callback).
5011 * Used internally for Zod validation of autoRefresh and debounceMs.
5012 */
5013 var ListChangedOptionsBaseSchema = object$1({
5014 /**
5015 * If true, the list will be refreshed automatically when a list changed notification is received.
5016 * The callback will be called with the updated list.
5017 *
5018 * If false, the callback will be called with null items, allowing manual refresh.
5019 *
5020 * @default true
5021 */
5022 autoRefresh: boolean().default(true),
5023 /**
5024 * Debounce time in milliseconds for list changed notification processing.
5025 *
5026 * Multiple notifications received within this timeframe will only trigger one refresh.
5027 * Set to 0 to disable debouncing.
5028 *
5029 * @default 300
5030 */
5031 debounceMs: number().int().nonnegative().default(300)
5032 });
5033 /**
5034 * The severity of a log message.
5035 */
5036 var LoggingLevelSchema = _enum([
5037 "debug",
5038 "info",
5039 "notice",
5040 "warning",
5041 "error",
5042 "critical",
5043 "alert",
5044 "emergency"
5045 ]);
5046 /**
5047 * Parameters for a `logging/setLevel` request.
5048 */
5049 var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
5050 /**
5051 * 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.
5052 */
5053 level: LoggingLevelSchema });
5054 /**
5055 * A request from the client to the server, to enable or adjust logging.
5056 */
5057 var SetLevelRequestSchema = RequestSchema.extend({
5058 method: literal("logging/setLevel"),
5059 params: SetLevelRequestParamsSchema
5060 });
5061 /**
5062 * Parameters for a `notifications/message` notification.
5063 */
5064 var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
5065 /**
5066 * The severity of this log message.
5067 */
5068 level: LoggingLevelSchema,
5069 /**
5070 * An optional name of the logger issuing this message.
5071 */
5072 logger: string().optional(),
5073 /**
5074 * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
5075 */
5076 data: unknown()
5077 });
5078 /**
5079 * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.
5080 */
5081 var LoggingMessageNotificationSchema = NotificationSchema.extend({
5082 method: literal("notifications/message"),
5083 params: LoggingMessageNotificationParamsSchema
5084 });
5085 /**
5086 * Hints to use for model selection.
5087 */
5088 var ModelHintSchema = object$1({
5089 /**
5090 * A hint for a model name.
5091 */
5092 name: string().optional() });
5093 /**
5094 * The server's preferences for model selection, requested of the client during sampling.
5095 */
5096 var ModelPreferencesSchema = object$1({
5097 /**
5098 * Optional hints to use for model selection.
5099 */
5100 hints: array(ModelHintSchema).optional(),
5101 /**
5102 * How much to prioritize cost when selecting a model.
5103 */
5104 costPriority: number().min(0).max(1).optional(),
5105 /**
5106 * How much to prioritize sampling speed (latency) when selecting a model.
5107 */
5108 speedPriority: number().min(0).max(1).optional(),
5109 /**
5110 * How much to prioritize intelligence and capabilities when selecting a model.
5111 */
5112 intelligencePriority: number().min(0).max(1).optional()
5113 });
5114 /**
5115 * Controls tool usage behavior in sampling requests.
5116 */
5117 var ToolChoiceSchema = object$1({
5118 /**
5119 * Controls when tools are used:
5120 * - "auto": Model decides whether to use tools (default)
5121 * - "required": Model MUST use at least one tool before completing
5122 * - "none": Model MUST NOT use any tools
5123 */
5124 mode: _enum([
5125 "auto",
5126 "required",
5127 "none"
5128 ]).optional() });
5129 /**
5130 * The result of a tool execution, provided by the user (server).
5131 * Represents the outcome of invoking a tool requested via ToolUseContent.
5132 */
5133 var ToolResultContentSchema = object$1({
5134 type: literal("tool_result"),
5135 toolUseId: string().describe("The unique identifier for the corresponding tool call."),
5136 content: array(ContentBlockSchema).default([]),
5137 structuredContent: object$1({}).loose().optional(),
5138 isError: boolean().optional(),
5139 /**
5140 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
5141 * for notes on _meta usage.
5142 */
5143 _meta: record(string(), unknown()).optional()
5144 });
5145 /**
5146 * Basic content types for sampling responses (without tool use).
5147 * Used for backwards-compatible CreateMessageResult when tools are not used.
5148 */
5149 var SamplingContentSchema = discriminatedUnion("type", [
5150 TextContentSchema,
5151 ImageContentSchema,
5152 AudioContentSchema
5153 ]);
5154 /**
5155 * Content block types allowed in sampling messages.
5156 * This includes text, image, audio, tool use requests, and tool results.
5157 */
5158 var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
5159 TextContentSchema,
5160 ImageContentSchema,
5161 AudioContentSchema,
5162 ToolUseContentSchema,
5163 ToolResultContentSchema
5164 ]);
5165 /**
5166 * Describes a message issued to or received from an LLM API.
5167 */
5168 var SamplingMessageSchema = object$1({
5169 role: RoleSchema,
5170 content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
5171 /**
5172 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
5173 * for notes on _meta usage.
5174 */
5175 _meta: record(string(), unknown()).optional()
5176 });
5177 /**
5178 * Parameters for a `sampling/createMessage` request.
5179 */
5180 var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
5181 messages: array(SamplingMessageSchema),
5182 /**
5183 * The server's preferences for which model to select. The client MAY modify or omit this request.
5184 */
5185 modelPreferences: ModelPreferencesSchema.optional(),
5186 /**
5187 * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
5188 */
5189 systemPrompt: string().optional(),
5190 /**
5191 * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
5192 * The client MAY ignore this request.
5193 *
5194 * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
5195 * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
5196 */
5197 includeContext: _enum([
5198 "none",
5199 "thisServer",
5200 "allServers"
5201 ]).optional(),
5202 temperature: number().optional(),
5203 /**
5204 * The requested maximum number of tokens to sample (to prevent runaway completions).
5205 *
5206 * The client MAY choose to sample fewer tokens than the requested maximum.
5207 */
5208 maxTokens: number().int(),
5209 stopSequences: array(string()).optional(),
5210 /**
5211 * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
5212 */
5213 metadata: AssertObjectSchema.optional(),
5214 /**
5215 * Tools that the model may use during generation.
5216 * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
5217 */
5218 tools: array(ToolSchema).optional(),
5219 /**
5220 * Controls how the model uses tools.
5221 * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
5222 * Default is `{ mode: "auto" }`.
5223 */
5224 toolChoice: ToolChoiceSchema.optional()
5225 });
5226 /**
5227 * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.
5228 */
5229 var CreateMessageRequestSchema = RequestSchema.extend({
5230 method: literal("sampling/createMessage"),
5231 params: CreateMessageRequestParamsSchema
5232 });
5233 /**
5234 * The client's response to a sampling/create_message request from the server.
5235 * This is the backwards-compatible version that returns single content (no arrays).
5236 * Used when the request does not include tools.
5237 */
5238 var CreateMessageResultSchema = ResultSchema.extend({
5239 /**
5240 * The name of the model that generated the message.
5241 */
5242 model: string(),
5243 /**
5244 * The reason why sampling stopped, if known.
5245 *
5246 * Standard values:
5247 * - "endTurn": Natural end of the assistant's turn
5248 * - "stopSequence": A stop sequence was encountered
5249 * - "maxTokens": Maximum token limit was reached
5250 *
5251 * This field is an open string to allow for provider-specific stop reasons.
5252 */
5253 stopReason: optional(_enum([
5254 "endTurn",
5255 "stopSequence",
5256 "maxTokens"
5257 ]).or(string())),
5258 role: RoleSchema,
5259 /**
5260 * Response content. Single content block (text, image, or audio).
5261 */
5262 content: SamplingContentSchema
5263 });
5264 /**
5265 * The client's response to a sampling/create_message request when tools were provided.
5266 * This version supports array content for tool use flows.
5267 */
5268 var CreateMessageResultWithToolsSchema = ResultSchema.extend({
5269 /**
5270 * The name of the model that generated the message.
5271 */
5272 model: string(),
5273 /**
5274 * The reason why sampling stopped, if known.
5275 *
5276 * Standard values:
5277 * - "endTurn": Natural end of the assistant's turn
5278 * - "stopSequence": A stop sequence was encountered
5279 * - "maxTokens": Maximum token limit was reached
5280 * - "toolUse": The model wants to use one or more tools
5281 *
5282 * This field is an open string to allow for provider-specific stop reasons.
5283 */
5284 stopReason: optional(_enum([
5285 "endTurn",
5286 "stopSequence",
5287 "maxTokens",
5288 "toolUse"
5289 ]).or(string())),
5290 role: RoleSchema,
5291 /**
5292 * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
5293 */
5294 content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
5295 });
5296 /**
5297 * Primitive schema definition for boolean fields.
5298 */
5299 var BooleanSchemaSchema = object$1({
5300 type: literal("boolean"),
5301 title: string().optional(),
5302 description: string().optional(),
5303 default: boolean().optional()
5304 });
5305 /**
5306 * Primitive schema definition for string fields.
5307 */
5308 var StringSchemaSchema = object$1({
5309 type: literal("string"),
5310 title: string().optional(),
5311 description: string().optional(),
5312 minLength: number().optional(),
5313 maxLength: number().optional(),
5314 format: _enum([
5315 "email",
5316 "uri",
5317 "date",
5318 "date-time"
5319 ]).optional(),
5320 default: string().optional()
5321 });
5322 /**
5323 * Primitive schema definition for number fields.
5324 */
5325 var NumberSchemaSchema = object$1({
5326 type: _enum(["number", "integer"]),
5327 title: string().optional(),
5328 description: string().optional(),
5329 minimum: number().optional(),
5330 maximum: number().optional(),
5331 default: number().optional()
5332 });
5333 /**
5334 * Schema for single-selection enumeration without display titles for options.
5335 */
5336 var UntitledSingleSelectEnumSchemaSchema = object$1({
5337 type: literal("string"),
5338 title: string().optional(),
5339 description: string().optional(),
5340 enum: array(string()),
5341 default: string().optional()
5342 });
5343 /**
5344 * Schema for single-selection enumeration with display titles for each option.
5345 */
5346 var TitledSingleSelectEnumSchemaSchema = object$1({
5347 type: literal("string"),
5348 title: string().optional(),
5349 description: string().optional(),
5350 oneOf: array(object$1({
5351 const: string(),
5352 title: string()
5353 })),
5354 default: string().optional()
5355 });
5356 /**
5357 * Use TitledSingleSelectEnumSchema instead.
5358 * This interface will be removed in a future version.
5359 */
5360 var LegacyTitledEnumSchemaSchema = object$1({
5361 type: literal("string"),
5362 title: string().optional(),
5363 description: string().optional(),
5364 enum: array(string()),
5365 enumNames: array(string()).optional(),
5366 default: string().optional()
5367 });
5368 var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
5369 /**
5370 * Schema for multiple-selection enumeration without display titles for options.
5371 */
5372 var UntitledMultiSelectEnumSchemaSchema = object$1({
5373 type: literal("array"),
5374 title: string().optional(),
5375 description: string().optional(),
5376 minItems: number().optional(),
5377 maxItems: number().optional(),
5378 items: object$1({
5379 type: literal("string"),
5380 enum: array(string())
5381 }),
5382 default: array(string()).optional()
5383 });
5384 /**
5385 * Schema for multiple-selection enumeration with display titles for each option.
5386 */
5387 var TitledMultiSelectEnumSchemaSchema = object$1({
5388 type: literal("array"),
5389 title: string().optional(),
5390 description: string().optional(),
5391 minItems: number().optional(),
5392 maxItems: number().optional(),
5393 items: object$1({ anyOf: array(object$1({
5394 const: string(),
5395 title: string()
5396 })) }),
5397 default: array(string()).optional()
5398 });
5399 /**
5400 * Combined schema for multiple-selection enumeration
5401 */
5402 var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
5403 /**
5404 * Primitive schema definition for enum fields.
5405 */
5406 var EnumSchemaSchema = union([
5407 LegacyTitledEnumSchemaSchema,
5408 SingleSelectEnumSchemaSchema,
5409 MultiSelectEnumSchemaSchema
5410 ]);
5411 /**
5412 * Union of all primitive schema definitions.
5413 */
5414 var PrimitiveSchemaDefinitionSchema = union([
5415 EnumSchemaSchema,
5416 BooleanSchemaSchema,
5417 StringSchemaSchema,
5418 NumberSchemaSchema
5419 ]);
5420 /**
5421 * Parameters for an `elicitation/create` request for form-based elicitation.
5422 */
5423 var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
5424 /**
5425 * The elicitation mode.
5426 *
5427 * Optional for backward compatibility. Clients MUST treat missing mode as "form".
5428 */
5429 mode: literal("form").optional(),
5430 /**
5431 * The message to present to the user describing what information is being requested.
5432 */
5433 message: string(),
5434 /**
5435 * A restricted subset of JSON Schema.
5436 * Only top-level properties are allowed, without nesting.
5437 */
5438 requestedSchema: object$1({
5439 type: literal("object"),
5440 properties: record(string(), PrimitiveSchemaDefinitionSchema),
5441 required: array(string()).optional()
5442 })
5443 });
5444 /**
5445 * Parameters for an `elicitation/create` request for URL-based elicitation.
5446 */
5447 var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
5448 /**
5449 * The elicitation mode.
5450 */
5451 mode: literal("url"),
5452 /**
5453 * The message to present to the user explaining why the interaction is needed.
5454 */
5455 message: string(),
5456 /**
5457 * The ID of the elicitation, which must be unique within the context of the server.
5458 * The client MUST treat this ID as an opaque value.
5459 */
5460 elicitationId: string(),
5461 /**
5462 * The URL that the user should navigate to.
5463 */
5464 url: string().url()
5465 });
5466 /**
5467 * The parameters for a request to elicit additional information from the user via the client.
5468 */
5469 var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
5470 /**
5471 * A request from the server to elicit user input via the client.
5472 * The client should present the message and form fields to the user (form mode)
5473 * or navigate to a URL (URL mode).
5474 */
5475 var ElicitRequestSchema = RequestSchema.extend({
5476 method: literal("elicitation/create"),
5477 params: ElicitRequestParamsSchema
5478 });
5479 /**
5480 * Parameters for a `notifications/elicitation/complete` notification.
5481 *
5482 * @category notifications/elicitation/complete
5483 */
5484 var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
5485 /**
5486 * The ID of the elicitation that completed.
5487 */
5488 elicitationId: string() });
5489 /**
5490 * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.
5491 *
5492 * @category notifications/elicitation/complete
5493 */
5494 var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
5495 method: literal("notifications/elicitation/complete"),
5496 params: ElicitationCompleteNotificationParamsSchema
5497 });
5498 /**
5499 * The client's response to an elicitation/create request from the server.
5500 */
5501 var ElicitResultSchema = ResultSchema.extend({
5502 /**
5503 * The user action in response to the elicitation.
5504 * - "accept": User submitted the form/confirmed the action
5505 * - "decline": User explicitly decline the action
5506 * - "cancel": User dismissed without making an explicit choice
5507 */
5508 action: _enum([
5509 "accept",
5510 "decline",
5511 "cancel"
5512 ]),
5513 /**
5514 * The submitted form data, only present when action is "accept".
5515 * Contains values matching the requested schema.
5516 * Per MCP spec, content is "typically omitted" for decline/cancel actions.
5517 * We normalize null to undefined for leniency while maintaining type compatibility.
5518 */
5519 content: preprocess((val) => val === null ? void 0 : val, record(string(), union([
5520 string(),
5521 number(),
5522 boolean(),
5523 array(string())
5524 ])).optional())
5525 });
5526 /**
5527 * A reference to a resource or resource template definition.
5528 */
5529 var ResourceTemplateReferenceSchema = object$1({
5530 type: literal("ref/resource"),
5531 /**
5532 * The URI or URI template of the resource.
5533 */
5534 uri: string()
5535 });
5536 /**
5537 * Identifies a prompt.
5538 */
5539 var PromptReferenceSchema = object$1({
5540 type: literal("ref/prompt"),
5541 /**
5542 * The name of the prompt or prompt template
5543 */
5544 name: string()
5545 });
5546 /**
5547 * Parameters for a `completion/complete` request.
5548 */
5549 var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
5550 ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
5551 /**
5552 * The argument's information
5553 */
5554 argument: object$1({
5555 /**
5556 * The name of the argument
5557 */
5558 name: string(),
5559 /**
5560 * The value of the argument to use for completion matching.
5561 */
5562 value: string()
5563 }),
5564 context: object$1({
5565 /**
5566 * Previously-resolved variables in a URI template or prompt.
5567 */
5568 arguments: record(string(), string()).optional() }).optional()
5569 });
5570 /**
5571 * A request from the client to the server, to ask for completion options.
5572 */
5573 var CompleteRequestSchema = RequestSchema.extend({
5574 method: literal("completion/complete"),
5575 params: CompleteRequestParamsSchema
5576 });
5577 function assertCompleteRequestPrompt(request) {
5578 if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);
5579 }
5580 function assertCompleteRequestResourceTemplate(request) {
5581 if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);
5582 }
5583 /**
5584 * The server's response to a completion/complete request
5585 */
5586 var CompleteResultSchema = ResultSchema.extend({ completion: looseObject({
5587 /**
5588 * An array of completion values. Must not exceed 100 items.
5589 */
5590 values: array(string()).max(100),
5591 /**
5592 * The total number of completion options available. This can exceed the number of values actually sent in the response.
5593 */
5594 total: optional(number().int()),
5595 /**
5596 * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
5597 */
5598 hasMore: optional(boolean())
5599 }) });
5600 /**
5601 * Represents a root directory or file that the server can operate on.
5602 */
5603 var RootSchema = object$1({
5604 /**
5605 * The URI identifying the root. This *must* start with file:// for now.
5606 */
5607 uri: string().startsWith("file://"),
5608 /**
5609 * An optional name for the root.
5610 */
5611 name: string().optional(),
5612 /**
5613 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
5614 * for notes on _meta usage.
5615 */
5616 _meta: record(string(), unknown()).optional()
5617 });
5618 /**
5619 * Sent from the server to request a list of root URIs from the client.
5620 */
5621 var ListRootsRequestSchema = RequestSchema.extend({
5622 method: literal("roots/list"),
5623 params: BaseRequestParamsSchema.optional()
5624 });
5625 /**
5626 * The client's response to a roots/list request from the server.
5627 */
5628 var ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) });
5629 /**
5630 * A notification from the client to the server, informing it that the list of roots has changed.
5631 */
5632 var RootsListChangedNotificationSchema = NotificationSchema.extend({
5633 method: literal("notifications/roots/list_changed"),
5634 params: NotificationsParamsSchema.optional()
5635 });
5636 var ClientRequestSchema = union([
5637 PingRequestSchema,
5638 InitializeRequestSchema,
5639 CompleteRequestSchema,
5640 SetLevelRequestSchema,
5641 GetPromptRequestSchema,
5642 ListPromptsRequestSchema,
5643 ListResourcesRequestSchema,
5644 ListResourceTemplatesRequestSchema,
5645 ReadResourceRequestSchema,
5646 SubscribeRequestSchema,
5647 UnsubscribeRequestSchema,
5648 CallToolRequestSchema,
5649 ListToolsRequestSchema,
5650 GetTaskRequestSchema,
5651 GetTaskPayloadRequestSchema,
5652 ListTasksRequestSchema,
5653 CancelTaskRequestSchema
5654 ]);
5655 var ClientNotificationSchema = union([
5656 CancelledNotificationSchema,
5657 ProgressNotificationSchema,
5658 InitializedNotificationSchema,
5659 RootsListChangedNotificationSchema,
5660 TaskStatusNotificationSchema
5661 ]);
5662 var ClientResultSchema = union([
5663 EmptyResultSchema,
5664 CreateMessageResultSchema,
5665 CreateMessageResultWithToolsSchema,
5666 ElicitResultSchema,
5667 ListRootsResultSchema,
5668 GetTaskResultSchema,
5669 ListTasksResultSchema,
5670 CreateTaskResultSchema
5671 ]);
5672 var ServerRequestSchema = union([
5673 PingRequestSchema,
5674 CreateMessageRequestSchema,
5675 ElicitRequestSchema,
5676 ListRootsRequestSchema,
5677 GetTaskRequestSchema,
5678 GetTaskPayloadRequestSchema,
5679 ListTasksRequestSchema,
5680 CancelTaskRequestSchema
5681 ]);
5682 var ServerNotificationSchema = union([
5683 CancelledNotificationSchema,
5684 ProgressNotificationSchema,
5685 LoggingMessageNotificationSchema,
5686 ResourceUpdatedNotificationSchema,
5687 ResourceListChangedNotificationSchema,
5688 ToolListChangedNotificationSchema,
5689 PromptListChangedNotificationSchema,
5690 TaskStatusNotificationSchema,
5691 ElicitationCompleteNotificationSchema
5692 ]);
5693 var ServerResultSchema = union([
5694 EmptyResultSchema,
5695 InitializeResultSchema,
5696 CompleteResultSchema,
5697 GetPromptResultSchema,
5698 ListPromptsResultSchema,
5699 ListResourcesResultSchema,
5700 ListResourceTemplatesResultSchema,
5701 ReadResourceResultSchema,
5702 CallToolResultSchema,
5703 ListToolsResultSchema,
5704 GetTaskResultSchema,
5705 ListTasksResultSchema,
5706 CreateTaskResultSchema
5707 ]);
5708 var McpError = class McpError extends Error {
5709 constructor(code, message, data) {
5710 super(`MCP error ${code}: ${message}`);
5711 this.code = code;
5712 this.data = data;
5713 this.name = "McpError";
5714 }
5715 /**
5716 * Factory method to create the appropriate error type based on the error code and data
5717 */
5718 static fromError(code, message, data) {
5719 if (code === ErrorCode.UrlElicitationRequired && data) {
5720 const errorData = data;
5721 if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message);
5722 }
5723 return new McpError(code, message, data);
5724 }
5725 };
5726 /**
5727 * Specialized error type when a tool requires a URL mode elicitation.
5728 * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.
5729 */
5730 var UrlElicitationRequiredError = class extends McpError {
5731 constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
5732 super(ErrorCode.UrlElicitationRequired, message, { elicitations });
5733 }
5734 get elicitations() {
5735 return this.data?.elicitations ?? [];
5736 }
5737 };
5738
5739 //#endregion
5740 //#region node_modules/@elementor-external/angie-sdk/dist/index.js
5741 var t = {
5742 none: 0,
5743 error: 1,
5744 warn: 2,
5745 info: 3,
5746 debug: 4
5747 };
5748 var i = {
5749 error: "error",
5750 warn: "warn",
5751 info: "info",
5752 log: "info",
5753 debug: "debug"
5754 };
5755 var n = (e, i) => t[e] <= t[i];
5756 var s = (e) => "string" == typeof e ? e : JSON.stringify(e);
5757 var r = (e, t) => `${s(e)} > ${s(t)}`;
5758 var o = (e, t) => {
5759 let i = `[${s(e)}]`;
5760 return typeof window < "u" ? {
5761 text: `%c${i}`,
5762 style: `color: ${t.color || "#00bcd4"}; font-weight: bold;`
5763 } : { text: i };
5764 };
5765 var a = (e, t, s, r) => (...a) => {
5766 if (!n(i[e], r())) return;
5767 if (!t) return void console[e](...a);
5768 let { text: c, style: d } = o(t, s);
5769 d ? console[e](c, d, ...a) : console[e](c, ...a);
5770 };
5771 var c = (e, t) => {
5772 let i = t.logLevel ?? "debug";
5773 let n = () => i;
5774 return {
5775 log: a("log", e, t, n),
5776 info: a("info", e, t, n),
5777 warn: a("warn", e, t, n),
5778 error: a("error", e, t, n),
5779 debug: a("debug", e, t, n),
5780 setLogLevel: (e) => {
5781 i = e;
5782 },
5783 extend: (n) => c(e ? r(e, n) : n, {
5784 ...t,
5785 logLevel: i
5786 })
5787 };
5788 };
5789 var d = (e, t) => c(e, {
5790 color: "#00bcd4",
5791 logLevel: "debug",
5792 ...t
5793 });
5794 var l = d("angie-sdk", {
5795 color: "#00BCD4",
5796 logLevel: "error"
5797 });
5798 var g = (e) => l.extend(e);
5799 var u;
5800 var h;
5801 var p;
5802 var _;
5803 var w;
5804 var m;
5805 var f;
5806 var y;
5807 (function(e) {
5808 e.POST_MESSAGE = "postMessage";
5809 })(u || (u = {})), function(e) {
5810 e.POST_MESSAGE = "postMessage";
5811 }(h || (h = {})), function(e) {
5812 e.STREAMABLE_HTTP = "streamableHttp", e.SSE = "sse";
5813 }(p || (p = {})), function(e) {
5814 e.LOCAL = "local", e.REMOTE = "remote";
5815 }(_ || (_ = {})), function(e) {
5816 e.AGENT = "agent", e.PLAN = "plan", e.ASK = "ask", e.SUPER_ADMIN = "super-admin";
5817 }(w || (w = {})), function(e) {
5818 e.SDK_ANGIE_READY_PING = "sdk-angie-ready-ping", e.SDK_ANGIE_REFRESH_PING = "sdk-angie-refresh-ping", e.SDK_ANGIE_ALL_SERVERS_REGISTERED = "sdk-angie-all-servers-registered", e.SDK_REQUEST_CLIENT_CREATION = "sdk-request-client-creation", e.SDK_REQUEST_INIT_SERVER = "sdk-request-init-server", e.SDK_TRIGGER_ANGIE = "sdk-trigger-angie", e.SDK_TRIGGER_ANGIE_RESPONSE = "sdk-trigger-angie-response", e.ANGIE_SIDEBAR_RESIZED = "angie-sidebar-resized", e.ANGIE_SIDEBAR_TOGGLED = "angie-sidebar-toggled", e.ANGIE_CHAT_TOGGLE = "angie-chat-toggle", e.ANGIE_STUDIO_TOGGLE = "angie-studio-toggle", e.ANGIE_NAVIGATE_TO_URL = "angie/navigate-to-url", e.ANGIE_PAGE_RELOAD = "angie/page-reload", e.ANGIE_DISABLE_NAVIGATION_PREVENTION = "angie/disable-navigation-prevention", e.ANGIE_NAVIGATE_AFTER_RESPONSE = "angie/navigate-after-response", e.ANGIE_SET_INTERACTION_MODE = "angie/set-interaction-mode";
5819 }(m || (m = {})), function(e) {
5820 e.SET = "ANGIE_SET_LOCALSTORAGE", e.GET = "ANGIE_GET_LOCALSTORAGE";
5821 }(f || (f = {})), function(e) {
5822 e.RESET_HASH = "reset-hash", e.HOST_READY = "host/ready", e.ANGIE_LOADED = "angie/loaded", e.ANGIE_READY = "angie/ready";
5823 }(y || (y = {}));
5824 var S = g("angie-detector");
5825 var b = class {
5826 isAngieReady = !1;
5827 readyPromise;
5828 readyResolve;
5829 getInstanceId;
5830 constructor(e) {
5831 if (this.getInstanceId = e, this.readyPromise = new Promise((e) => {
5832 this.readyResolve = e;
5833 }), "undefined" == typeof window) return;
5834 let t = 0;
5835 const i = () => {
5836 if (this.isAngieReady || t >= 500) return void (!this.isAngieReady && t >= 500 && this.handleDetectionTimeout());
5837 const e = new MessageChannel();
5838 e.port1.onmessage = (t) => {
5839 this.handleAngieReady(t.data), e.port1.close(), e.port2.close();
5840 };
5841 const n = {
5842 type: m.SDK_ANGIE_READY_PING,
5843 payload: { instanceId: this.getInstanceId?.() },
5844 timestamp: Date.now()
5845 };
5846 window.postMessage(n, window.location.origin, [e.port2]), t++, setTimeout(i, 500);
5847 };
5848 i();
5849 }
5850 handleAngieReady(e) {
5851 this.isAngieReady = !0;
5852 const t = {
5853 isReady: !0,
5854 version: e.version,
5855 capabilities: e.capabilities
5856 };
5857 this.readyResolve && this.readyResolve(t);
5858 }
5859 handleDetectionTimeout() {
5860 this.readyResolve && this.readyResolve({ isReady: !1 }), S.warn("Detection timeout - Angie may not be available");
5861 }
5862 isReady() {
5863 return this.isAngieReady;
5864 }
5865 async waitForReady() {
5866 return this.readyPromise;
5867 }
5868 async waitUntilReady(e) {
5869 return this.isAngieReady ? this.readyPromise : Promise.race([this.readyPromise, new Promise((t) => {
5870 setTimeout(() => t({ isReady: !1 }), e);
5871 })]);
5872 }
5873 };
5874 var v = class {
5875 sessionId;
5876 onmessage;
5877 onerror;
5878 onclose;
5879 _port;
5880 _started = !1;
5881 _closed = !1;
5882 constructor(t) {
5883 if (!t) throw new Error("MessagePort is required");
5884 this._port = t, this._port.onmessage = (t) => {
5885 try {
5886 const i = JSONRPCMessageSchema.parse(t.data);
5887 this.onmessage?.(i);
5888 } catch (e) {
5889 const t = /* @__PURE__ */ new Error(`Failed to parse message: ${e}`);
5890 this.onerror?.(t);
5891 }
5892 }, this._port.onmessageerror = (e) => {
5893 const t = /* @__PURE__ */ new Error(`MessagePort error: ${JSON.stringify(e)}`);
5894 this.onerror?.(t);
5895 };
5896 }
5897 async start() {
5898 if (this._started) throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");
5899 if (this._closed) throw new Error("Cannot start a closed BrowserContextTransport");
5900 this._started = !0, this._port.start();
5901 }
5902 async send(e) {
5903 if (this._closed) throw new Error("Cannot send on a closed BrowserContextTransport");
5904 return new Promise((t, i) => {
5905 try {
5906 this._port.postMessage(e), t();
5907 } catch (e) {
5908 const t = e instanceof Error ? e : new Error(String(e));
5909 this.onerror?.(t), i(t);
5910 }
5911 });
5912 }
5913 async close() {
5914 this._closed || (this._closed = !0, this._port.close(), this.onclose?.());
5915 }
5916 };
5917 var I = class {
5918 async requestClientCreation(e) {
5919 const { config: t } = e, i = {
5920 serverId: e.id,
5921 serverName: t.name,
5922 serverTitle: t.title,
5923 serverVersion: t.version,
5924 description: t.description,
5925 transport: t.transport || h.POST_MESSAGE,
5926 capabilities: t.capabilities,
5927 instanceId: e.instanceId
5928 };
5929 return "type" in t && "remote" === t.type && (i.remote = { url: t.url }), new Promise((e, t) => {
5930 const n = new MessageChannel();
5931 const s = setTimeout(() => {
5932 t(/* @__PURE__ */ new Error("Client creation request timed out after 15000ms"));
5933 }, 15e3);
5934 n.port1.onmessage = (t) => {
5935 clearTimeout(s), e(t.data);
5936 };
5937 const r = {
5938 type: m.SDK_REQUEST_CLIENT_CREATION,
5939 payload: i,
5940 timestamp: Date.now()
5941 };
5942 window.postMessage(r, window.location.origin, [n.port2]);
5943 });
5944 }
5945 };
5946 var E = "angie-sidebar-container";
5947 var k = "angie-iframe";
5948 var T = () => ({
5949 open: !1,
5950 iframe: null,
5951 iframeUrlObject: null,
5952 containerId: E,
5953 instanceId: "",
5954 layout: "",
5955 iframeElementId: k
5956 });
5957 var R = T();
5958 var A = class extends Error {};
5959 A.prototype.name = "InvalidTokenError";
5960 var C;
5961 var x;
5962 var P;
5963 var O = {
5964 debug: () => {},
5965 info: () => {},
5966 warn: () => {},
5967 error: () => {}
5968 };
5969 var U = ((e) => (e[e.NONE = 0] = "NONE", e[e.ERROR = 1] = "ERROR", e[e.WARN = 2] = "WARN", e[e.INFO = 3] = "INFO", e[e.DEBUG = 4] = "DEBUG", e))(U || {});
5970 (P = U || (U = {})).reset = function() {
5971 C = 3, x = O;
5972 }, P.setLevel = function(e) {
5973 if (!(0 <= e && e <= 4)) throw new Error("Invalid log level");
5974 C = e;
5975 }, P.setLogger = function(e) {
5976 x = e;
5977 };
5978 var L = class e {
5979 constructor(e) {
5980 this._name = e;
5981 }
5982 debug(...t) {
5983 C >= 4 && x.debug(e._format(this._name, this._method), ...t);
5984 }
5985 info(...t) {
5986 C >= 3 && x.info(e._format(this._name, this._method), ...t);
5987 }
5988 warn(...t) {
5989 C >= 2 && x.warn(e._format(this._name, this._method), ...t);
5990 }
5991 error(...t) {
5992 C >= 1 && x.error(e._format(this._name, this._method), ...t);
5993 }
5994 throw(e) {
5995 throw this.error(e), e;
5996 }
5997 create(e) {
5998 const t = Object.create(this);
5999 return t._method = e, t.debug("begin"), t;
6000 }
6001 static createStatic(t, i) {
6002 const n = new e(`${t}.${i}`);
6003 return n.debug("begin"), n;
6004 }
6005 static _format(e, t) {
6006 const i = `[${e}]`;
6007 return t ? `${i} ${t}:` : i;
6008 }
6009 static debug(t, ...i) {
6010 C >= 4 && x.debug(e._format(t), ...i);
6011 }
6012 static info(t, ...i) {
6013 C >= 3 && x.info(e._format(t), ...i);
6014 }
6015 static warn(t, ...i) {
6016 C >= 2 && x.warn(e._format(t), ...i);
6017 }
6018 static error(t, ...i) {
6019 C >= 1 && x.error(e._format(t), ...i);
6020 }
6021 };
6022 U.reset();
6023 var D = class {
6024 static decode(e) {
6025 try {
6026 return function(e, t) {
6027 if ("string" != typeof e) throw new A("Invalid token specified: must be a string");
6028 t || (t = {});
6029 const i = !0 === t.header ? 0 : 1;
6030 const n = e.split(".")[i];
6031 if ("string" != typeof n) throw new A(`Invalid token specified: missing part #${i + 1}`);
6032 let s;
6033 try {
6034 s = function(e) {
6035 let t = e.replace(/-/g, "+").replace(/_/g, "/");
6036 switch (t.length % 4) {
6037 case 0: break;
6038 case 2:
6039 t += "==";
6040 break;
6041 case 3:
6042 t += "=";
6043 break;
6044 default: throw new Error("base64 string is not of the correct length");
6045 }
6046 try {
6047 return function(e) {
6048 return decodeURIComponent(atob(e).replace(/(.)/g, (e, t) => {
6049 let i = t.charCodeAt(0).toString(16).toUpperCase();
6050 return i.length < 2 && (i = "0" + i), "%" + i;
6051 }));
6052 }(t);
6053 } catch (e) {
6054 return atob(t);
6055 }
6056 }(n);
6057 } catch (e) {
6058 throw new A(`Invalid token specified: invalid base64 for part #${i + 1} (${e.message})`);
6059 }
6060 try {
6061 return JSON.parse(s);
6062 } catch (e) {
6063 throw new A(`Invalid token specified: invalid json for part #${i + 1} (${e.message})`);
6064 }
6065 }(e);
6066 } catch (e) {
6067 throw L.error("JwtUtils.decode", e), e;
6068 }
6069 }
6070 static async generateSignedJwt(e, t, i) {
6071 const n = `${$.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e)))}.${$.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t)))}`;
6072 const s = await window.crypto.subtle.sign({
6073 name: "ECDSA",
6074 hash: { name: "SHA-256" }
6075 }, i, new TextEncoder().encode(n));
6076 return `${n}.${$.encodeBase64Url(new Uint8Array(s))}`;
6077 }
6078 static async generateSignedJwtWithHmac(e, t, i) {
6079 const n = `${$.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e)))}.${$.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t)))}`;
6080 const s = await window.crypto.subtle.sign("HMAC", i, new TextEncoder().encode(n));
6081 return `${n}.${$.encodeBase64Url(new Uint8Array(s))}`;
6082 }
6083 };
6084 var N = (e) => btoa([...new Uint8Array(e)].map((e) => String.fromCharCode(e)).join(""));
6085 var q = class e {
6086 static _randomWord() {
6087 const e = /* @__PURE__ */ new Uint32Array(1);
6088 return crypto.getRandomValues(e), e[0];
6089 }
6090 static generateUUIDv4() {
6091 return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (t) => (+t ^ e._randomWord() & 15 >> +t / 4).toString(16)).replace(/-/g, "");
6092 }
6093 static generateCodeVerifier() {
6094 return e.generateUUIDv4() + e.generateUUIDv4() + e.generateUUIDv4();
6095 }
6096 static async generateCodeChallenge(e) {
6097 if (!crypto.subtle) throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");
6098 try {
6099 const t = new TextEncoder().encode(e);
6100 return N(await crypto.subtle.digest("SHA-256", t)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
6101 } catch (e) {
6102 throw L.error("CryptoUtils.generateCodeChallenge", e), e;
6103 }
6104 }
6105 static generateBasicAuth(e, t) {
6106 return N(new TextEncoder().encode([e, t].join(":")));
6107 }
6108 static async hash(e, t) {
6109 const i = new TextEncoder().encode(t);
6110 const n = await crypto.subtle.digest(e, i);
6111 return new Uint8Array(n);
6112 }
6113 static async customCalculateJwkThumbprint(t) {
6114 let i;
6115 switch (t.kty) {
6116 case "RSA":
6117 i = {
6118 e: t.e,
6119 kty: t.kty,
6120 n: t.n
6121 };
6122 break;
6123 case "EC":
6124 i = {
6125 crv: t.crv,
6126 kty: t.kty,
6127 x: t.x,
6128 y: t.y
6129 };
6130 break;
6131 case "OKP":
6132 i = {
6133 crv: t.crv,
6134 kty: t.kty,
6135 x: t.x
6136 };
6137 break;
6138 case "oct":
6139 i = {
6140 crv: t.k,
6141 kty: t.kty
6142 };
6143 break;
6144 default: throw new Error("Unknown jwk type");
6145 }
6146 const n = await e.hash("SHA-256", JSON.stringify(i));
6147 return e.encodeBase64Url(n);
6148 }
6149 static async generateDPoPProof({ url: t, accessToken: i, httpMethod: n, keyPair: s, nonce: r }) {
6150 let o;
6151 let a;
6152 const c = {
6153 jti: window.crypto.randomUUID(),
6154 htm: null != n ? n : "GET",
6155 htu: t,
6156 iat: Math.floor(Date.now() / 1e3)
6157 };
6158 i && (o = await e.hash("SHA-256", i), a = e.encodeBase64Url(o), c.ath = a), r && (c.nonce = r);
6159 try {
6160 const e = await crypto.subtle.exportKey("jwk", s.publicKey);
6161 const t = {
6162 alg: "ES256",
6163 typ: "dpop+jwt",
6164 jwk: {
6165 crv: e.crv,
6166 kty: e.kty,
6167 x: e.x,
6168 y: e.y
6169 }
6170 };
6171 return await D.generateSignedJwt(t, c, s.privateKey);
6172 } catch (e) {
6173 throw e instanceof TypeError ? /* @__PURE__ */ new Error(`Error exporting dpop public key: ${e.message}`) : e;
6174 }
6175 }
6176 static async generateDPoPJkt(t) {
6177 try {
6178 const i = await crypto.subtle.exportKey("jwk", t.publicKey);
6179 return await e.customCalculateJwkThumbprint(i);
6180 } catch (e) {
6181 throw e instanceof TypeError ? /* @__PURE__ */ new Error(`Could not retrieve dpop keys from storage: ${e.message}`) : e;
6182 }
6183 }
6184 static async generateDPoPKeys() {
6185 return await window.crypto.subtle.generateKey({
6186 name: "ECDSA",
6187 namedCurve: "P-256"
6188 }, !1, ["sign", "verify"]);
6189 }
6190 static async generateClientAssertionJwt(t, i, n, s = "HS256") {
6191 const r = Math.floor(Date.now() / 1e3);
6192 const o = {
6193 alg: s,
6194 typ: "JWT"
6195 };
6196 const a = {
6197 iss: t,
6198 sub: t,
6199 aud: n,
6200 jti: e.generateUUIDv4(),
6201 exp: r + 300,
6202 iat: r
6203 };
6204 const c = {
6205 HS256: "SHA-256",
6206 HS384: "SHA-384",
6207 HS512: "SHA-512"
6208 }[s];
6209 if (!c) throw new Error(`Unsupported algorithm: ${s}. Supported algorithms are: HS256, HS384, HS512`);
6210 const d = new TextEncoder();
6211 const l = await crypto.subtle.importKey("raw", d.encode(i), {
6212 name: "HMAC",
6213 hash: c
6214 }, !1, ["sign"]);
6215 return await D.generateSignedJwtWithHmac(o, a, l);
6216 }
6217 };
6218 q.encodeBase64Url = (e) => N(e).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
6219 var $ = q;
6220 var M = class {
6221 constructor(e) {
6222 this._name = e, this._callbacks = [], this._logger = new L(`Event('${this._name}')`);
6223 }
6224 addHandler(e) {
6225 return this._callbacks.push(e), () => this.removeHandler(e);
6226 }
6227 removeHandler(e) {
6228 const t = this._callbacks.lastIndexOf(e);
6229 t >= 0 && this._callbacks.splice(t, 1);
6230 }
6231 async raise(...e) {
6232 this._logger.debug("raise:", ...e);
6233 for (const t of this._callbacks) await t(...e);
6234 }
6235 };
6236 var H = class {
6237 static center({ ...e }) {
6238 var t;
6239 return e.width ??= null != (t = [
6240 800,
6241 720,
6242 600,
6243 480
6244 ].find((e) => e <= window.outerWidth / 1.618)) ? t : 360, e.left ??= Math.max(0, Math.round(window.screenX + (window.outerWidth - e.width) / 2)), null != e.height && (e.top ??= Math.max(0, Math.round(window.screenY + (window.outerHeight - e.height) / 2))), e;
6245 }
6246 static serialize(e) {
6247 return Object.entries(e).filter(([, e]) => null != e).map(([e, t]) => `${e}=${"boolean" != typeof t ? t : t ? "yes" : "no"}`).join(",");
6248 }
6249 };
6250 var j = class e extends M {
6251 constructor() {
6252 super(...arguments), this._logger = new L(`Timer('${this._name}')`), this._timerHandle = null, this._expiration = 0, this._callback = () => {
6253 const t = this._expiration - e.getEpochTime();
6254 this._logger.debug("timer completes in", t), this._expiration <= e.getEpochTime() && (this.cancel(), super.raise());
6255 };
6256 }
6257 static getEpochTime() {
6258 return Math.floor(Date.now() / 1e3);
6259 }
6260 init(t) {
6261 const i = this._logger.create("init");
6262 t = Math.max(Math.floor(t), 1);
6263 const n = e.getEpochTime() + t;
6264 if (this.expiration === n && this._timerHandle) return void i.debug("skipping since already initialized for expiration at", this.expiration);
6265 this.cancel(), i.debug("using duration", t), this._expiration = n;
6266 const s = Math.min(t, 5);
6267 this._timerHandle = setInterval(this._callback, 1e3 * s);
6268 }
6269 get expiration() {
6270 return this._expiration;
6271 }
6272 cancel() {
6273 this._logger.create("cancel"), this._timerHandle && (clearInterval(this._timerHandle), this._timerHandle = null);
6274 }
6275 };
6276 var G = class {
6277 static readParams(e, t = "query") {
6278 if (!e) throw new TypeError("Invalid URL");
6279 const i = new URL(e, "http://127.0.0.1")["fragment" === t ? "hash" : "search"];
6280 return new URLSearchParams(i.slice(1));
6281 }
6282 };
6283 var z$2 = ";";
6284 var B = class extends Error {
6285 constructor(e, t) {
6286 var i;
6287 var n;
6288 var s;
6289 if (super(e.error_description || e.error || ""), this.form = t, this.name = "ErrorResponse", !e.error) throw L.error("ErrorResponse", "No error passed"), /* @__PURE__ */ new Error("No error passed");
6290 this.error = e.error, this.error_description = null != (i = e.error_description) ? i : null, this.error_uri = null != (n = e.error_uri) ? n : null, this.state = e.userState, this.session_state = null != (s = e.session_state) ? s : null, this.url_state = e.url_state;
6291 }
6292 };
6293 var W = class extends Error {
6294 constructor(e) {
6295 super(e), this.name = "ErrorTimeout";
6296 }
6297 };
6298 var F = class {
6299 constructor(e) {
6300 this._logger = new L("AccessTokenEvents"), this._expiringTimer = new j("Access token expiring"), this._expiredTimer = new j("Access token expired"), this._expiringNotificationTimeInSeconds = e.expiringNotificationTimeInSeconds;
6301 }
6302 async load(e) {
6303 const t = this._logger.create("load");
6304 if (e.access_token && void 0 !== e.expires_in) {
6305 const i = e.expires_in;
6306 if (t.debug("access token present, remaining duration:", i), i > 0) {
6307 let e = i - this._expiringNotificationTimeInSeconds;
6308 e <= 0 && (e = 1), t.debug("registering expiring timer, raising in", e, "seconds"), this._expiringTimer.init(e);
6309 } else t.debug("canceling existing expiring timer because we're past expiration."), this._expiringTimer.cancel();
6310 const n = i + 1;
6311 t.debug("registering expired timer, raising in", n, "seconds"), this._expiredTimer.init(n);
6312 } else this._expiringTimer.cancel(), this._expiredTimer.cancel();
6313 }
6314 async unload() {
6315 this._logger.debug("unload: canceling existing access token timers"), this._expiringTimer.cancel(), this._expiredTimer.cancel();
6316 }
6317 addAccessTokenExpiring(e) {
6318 return this._expiringTimer.addHandler(e);
6319 }
6320 removeAccessTokenExpiring(e) {
6321 this._expiringTimer.removeHandler(e);
6322 }
6323 addAccessTokenExpired(e) {
6324 return this._expiredTimer.addHandler(e);
6325 }
6326 removeAccessTokenExpired(e) {
6327 this._expiredTimer.removeHandler(e);
6328 }
6329 };
6330 var K = class {
6331 constructor(e, t, i, n, s) {
6332 this._callback = e, this._client_id = t, this._intervalInSeconds = n, this._stopOnError = s, this._logger = new L("CheckSessionIFrame"), this._timer = null, this._session_state = null, this._message = (e) => {
6333 e.origin === this._frame_origin && e.source === this._frame.contentWindow && ("error" === e.data ? (this._logger.error("error message from check session op iframe"), this._stopOnError && this.stop()) : "changed" === e.data ? (this._logger.debug("changed message from check session op iframe"), this.stop(), this._callback()) : this._logger.debug(e.data + " message from check session op iframe"));
6334 };
6335 const r = new URL(i);
6336 this._frame_origin = r.origin, this._frame = window.document.createElement("iframe"), this._frame.style.visibility = "hidden", this._frame.style.position = "fixed", this._frame.style.left = "-1000px", this._frame.style.top = "0", this._frame.width = "0", this._frame.height = "0", this._frame.src = r.href;
6337 }
6338 load() {
6339 return new Promise((e) => {
6340 this._frame.onload = () => {
6341 e();
6342 }, window.document.body.appendChild(this._frame), window.addEventListener("message", this._message, !1);
6343 });
6344 }
6345 start(e) {
6346 if (this._session_state === e) return;
6347 this._logger.create("start"), this.stop(), this._session_state = e;
6348 const t = () => {
6349 this._frame.contentWindow && this._session_state && this._frame.contentWindow.postMessage(this._client_id + " " + this._session_state, this._frame_origin);
6350 };
6351 t(), this._timer = setInterval(t, 1e3 * this._intervalInSeconds);
6352 }
6353 stop() {
6354 this._logger.create("stop"), this._session_state = null, this._timer && (clearInterval(this._timer), this._timer = null);
6355 }
6356 };
6357 var J = class {
6358 constructor() {
6359 this._logger = new L("InMemoryWebStorage"), this._data = {};
6360 }
6361 clear() {
6362 this._logger.create("clear"), this._data = {};
6363 }
6364 getItem(e) {
6365 return this._logger.create(`getItem('${e}')`), this._data[e];
6366 }
6367 setItem(e, t) {
6368 this._logger.create(`setItem('${e}')`), this._data[e] = t;
6369 }
6370 removeItem(e) {
6371 this._logger.create(`removeItem('${e}')`), delete this._data[e];
6372 }
6373 get length() {
6374 return Object.getOwnPropertyNames(this._data).length;
6375 }
6376 key(e) {
6377 return Object.getOwnPropertyNames(this._data)[e];
6378 }
6379 };
6380 var V = class extends Error {
6381 constructor(e, t) {
6382 super(t), this.name = "ErrorDPoPNonce", this.nonce = e;
6383 }
6384 };
6385 var Q = class {
6386 constructor(e = [], t = null, i = {}) {
6387 this._jwtHandler = t, this._extraHeaders = i, this._logger = new L("JsonService"), this._contentTypes = [], this._contentTypes.push(...e, "application/json"), t && this._contentTypes.push("application/jwt");
6388 }
6389 async fetchWithTimeout(e, t = {}) {
6390 const { timeoutInSeconds: i, ...n } = t;
6391 if (!i) return await fetch(e, n);
6392 const s = new AbortController();
6393 const r = setTimeout(() => s.abort(), 1e3 * i);
6394 try {
6395 return await fetch(e, {
6396 ...t,
6397 signal: s.signal
6398 });
6399 } catch (e) {
6400 if (e instanceof DOMException && "AbortError" === e.name) throw new W("Network timed out");
6401 throw e;
6402 } finally {
6403 clearTimeout(r);
6404 }
6405 }
6406 async getJson(e, { token: t, credentials: i, timeoutInSeconds: n } = {}) {
6407 const s = this._logger.create("getJson");
6408 const r = { Accept: this._contentTypes.join(", ") };
6409 let o;
6410 t && (s.debug("token passed, setting Authorization header"), r.Authorization = "Bearer " + t), this._appendExtraHeaders(r);
6411 try {
6412 s.debug("url:", e), o = await this.fetchWithTimeout(e, {
6413 method: "GET",
6414 headers: r,
6415 timeoutInSeconds: n,
6416 credentials: i
6417 });
6418 } catch (e) {
6419 throw s.error("Network Error"), e;
6420 }
6421 s.debug("HTTP response received, status", o.status);
6422 const a = o.headers.get("Content-Type");
6423 if (a && !this._contentTypes.find((e) => a.startsWith(e)) && s.throw(/* @__PURE__ */ new Error(`Invalid response Content-Type: ${null != a ? a : "undefined"}, from URL: ${e}`)), o.ok && this._jwtHandler && (null == a ? void 0 : a.startsWith("application/jwt"))) return await this._jwtHandler(await o.text());
6424 let c;
6425 try {
6426 c = await o.json();
6427 } catch (e) {
6428 if (s.error("Error parsing JSON response", e), o.ok) throw e;
6429 throw new Error(`${o.statusText} (${o.status})`);
6430 }
6431 if (!o.ok) {
6432 if (s.error("Error from server:", c), c.error) throw new B(c);
6433 throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`);
6434 }
6435 return c;
6436 }
6437 async postForm(e, { body: t, basicAuth: i, timeoutInSeconds: n, initCredentials: s, extraHeaders: r }) {
6438 const o = this._logger.create("postForm");
6439 const a = {
6440 Accept: this._contentTypes.join(", "),
6441 "Content-Type": "application/x-www-form-urlencoded",
6442 ...r
6443 };
6444 let c;
6445 void 0 !== i && (a.Authorization = "Basic " + i), this._appendExtraHeaders(a);
6446 try {
6447 o.debug("url:", e), c = await this.fetchWithTimeout(e, {
6448 method: "POST",
6449 headers: a,
6450 body: t,
6451 timeoutInSeconds: n,
6452 credentials: s
6453 });
6454 } catch (e) {
6455 throw o.error("Network error"), e;
6456 }
6457 o.debug("HTTP response received, status", c.status);
6458 const d = c.headers.get("Content-Type");
6459 if (d && !this._contentTypes.find((e) => d.startsWith(e))) throw new Error(`Invalid response Content-Type: ${null != d ? d : "undefined"}, from URL: ${e}`);
6460 const l = await c.text();
6461 let g = {};
6462 if (l) try {
6463 g = JSON.parse(l);
6464 } catch (e) {
6465 if (o.error("Error parsing JSON response", e), c.ok) throw e;
6466 throw new Error(`${c.statusText} (${c.status})`);
6467 }
6468 if (!c.ok) {
6469 if (o.error("Error from server:", g), c.headers.has("dpop-nonce")) throw new V(c.headers.get("dpop-nonce"), `${JSON.stringify(g)}`);
6470 if (g.error) throw new B(g, t);
6471 throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(g)}`);
6472 }
6473 return g;
6474 }
6475 _appendExtraHeaders(e) {
6476 const t = this._logger.create("appendExtraHeaders");
6477 const i = Object.keys(this._extraHeaders);
6478 const n = ["accept", "content-type"];
6479 const s = ["authorization"];
6480 0 !== i.length && i.forEach((i) => {
6481 if (n.includes(i.toLocaleLowerCase())) return void t.warn("Protected header could not be set", i, n);
6482 if (s.includes(i.toLocaleLowerCase()) && Object.keys(e).includes(i)) return void t.warn("Header could not be overridden", i, s);
6483 const r = "function" == typeof this._extraHeaders[i] ? this._extraHeaders[i]() : this._extraHeaders[i];
6484 r && "" !== r && (e[i] = r);
6485 });
6486 }
6487 };
6488 var X = class {
6489 constructor(e) {
6490 this._settings = e, this._logger = new L("MetadataService"), this._signingKeys = null, this._metadata = null, this._metadataUrl = this._settings.metadataUrl, this._jsonService = new Q(["application/jwk-set+json"], null, this._settings.extraHeaders), this._settings.signingKeys && (this._logger.debug("using signingKeys from settings"), this._signingKeys = this._settings.signingKeys), this._settings.metadata && (this._logger.debug("using metadata from settings"), this._metadata = this._settings.metadata), this._settings.fetchRequestCredentials && (this._logger.debug("using fetchRequestCredentials from settings"), this._fetchRequestCredentials = this._settings.fetchRequestCredentials);
6491 }
6492 resetSigningKeys() {
6493 this._signingKeys = null;
6494 }
6495 async getMetadata() {
6496 const e = this._logger.create("getMetadata");
6497 if (this._metadata) return e.debug("using cached values"), this._metadata;
6498 if (!this._metadataUrl) throw e.throw(/* @__PURE__ */ new Error("No authority or metadataUrl configured on settings")), null;
6499 e.debug("getting metadata from", this._metadataUrl);
6500 const t = await this._jsonService.getJson(this._metadataUrl, {
6501 credentials: this._fetchRequestCredentials,
6502 timeoutInSeconds: this._settings.requestTimeoutInSeconds
6503 });
6504 return e.debug("merging remote JSON with seed metadata"), this._metadata = Object.assign({}, t, this._settings.metadataSeed), this._metadata;
6505 }
6506 getIssuer() {
6507 return this._getMetadataProperty("issuer");
6508 }
6509 getAuthorizationEndpoint() {
6510 return this._getMetadataProperty("authorization_endpoint");
6511 }
6512 getUserInfoEndpoint() {
6513 return this._getMetadataProperty("userinfo_endpoint");
6514 }
6515 getTokenEndpoint(e = !0) {
6516 return this._getMetadataProperty("token_endpoint", e);
6517 }
6518 getCheckSessionIframe() {
6519 return this._getMetadataProperty("check_session_iframe", !0);
6520 }
6521 getEndSessionEndpoint() {
6522 return this._getMetadataProperty("end_session_endpoint", !0);
6523 }
6524 getRevocationEndpoint(e = !0) {
6525 return this._getMetadataProperty("revocation_endpoint", e);
6526 }
6527 getKeysEndpoint(e = !0) {
6528 return this._getMetadataProperty("jwks_uri", e);
6529 }
6530 async _getMetadataProperty(e, t = !1) {
6531 const i = this._logger.create(`_getMetadataProperty('${e}')`);
6532 const n = await this.getMetadata();
6533 if (i.debug("resolved"), void 0 === n[e]) {
6534 if (!0 === t) return void i.warn("Metadata does not contain optional property");
6535 i.throw(/* @__PURE__ */ new Error("Metadata does not contain property " + e));
6536 }
6537 return n[e];
6538 }
6539 async getSigningKeys() {
6540 const e = this._logger.create("getSigningKeys");
6541 if (this._signingKeys) return e.debug("returning signingKeys from cache"), this._signingKeys;
6542 const t = await this.getKeysEndpoint(!1);
6543 e.debug("got jwks_uri", t);
6544 const i = await this._jsonService.getJson(t, { timeoutInSeconds: this._settings.requestTimeoutInSeconds });
6545 if (e.debug("got key set", i), !Array.isArray(i.keys)) throw e.throw(/* @__PURE__ */ new Error("Missing keys on keyset")), null;
6546 return this._signingKeys = i.keys, this._signingKeys;
6547 }
6548 };
6549 var Y = class {
6550 constructor({ prefix: e = "oidc.", store: t = localStorage } = {}) {
6551 this._logger = new L("WebStorageStateStore"), this._store = t, this._prefix = e;
6552 }
6553 async set(e, t) {
6554 this._logger.create(`set('${e}')`), e = this._prefix + e, await this._store.setItem(e, t);
6555 }
6556 async get(e) {
6557 return this._logger.create(`get('${e}')`), e = this._prefix + e, await this._store.getItem(e);
6558 }
6559 async remove(e) {
6560 this._logger.create(`remove('${e}')`), e = this._prefix + e;
6561 const t = await this._store.getItem(e);
6562 return await this._store.removeItem(e), t;
6563 }
6564 async getAllKeys() {
6565 this._logger.create("getAllKeys");
6566 const e = await this._store.length;
6567 const t = [];
6568 for (let i = 0; i < e; i++) {
6569 const e = await this._store.key(i);
6570 e && 0 === e.indexOf(this._prefix) && t.push(e.substr(this._prefix.length));
6571 }
6572 return t;
6573 }
6574 };
6575 var Z = class {
6576 constructor({ authority: e, metadataUrl: t, metadata: i, signingKeys: n, metadataSeed: s, client_id: r, client_secret: o, response_type: a = "code", scope: c = "openid", redirect_uri: d, post_logout_redirect_uri: l, client_authentication: g = "client_secret_post", token_endpoint_auth_signing_alg: u = "HS256", prompt: h, display: p, max_age: _, ui_locales: w, acr_values: m, resource: f, response_mode: y, filterProtocolClaims: S = !0, loadUserInfo: b = !1, requestTimeoutInSeconds: v, staleStateAgeInSeconds: I = 900, mergeClaimsStrategy: E = { array: "replace" }, disablePKCE: k = !1, stateStore: T, revokeTokenAdditionalContentTypes: R, fetchRequestCredentials: A, refreshTokenAllowedScope: C, extraQueryParams: x = {}, extraTokenParams: P = {}, extraHeaders: O = {}, dpop: U, omitScopeWhenRequesting: L = !1 }) {
6577 var D;
6578 if (this.authority = e, t ? this.metadataUrl = t : (this.metadataUrl = e, e && (this.metadataUrl.endsWith("/") || (this.metadataUrl += "/"), this.metadataUrl += ".well-known/openid-configuration")), this.metadata = i, this.metadataSeed = s, this.signingKeys = n, this.client_id = r, this.client_secret = o, this.response_type = a, this.scope = c, this.redirect_uri = d, this.post_logout_redirect_uri = l, this.client_authentication = g, this.token_endpoint_auth_signing_alg = u, this.prompt = h, this.display = p, this.max_age = _, this.ui_locales = w, this.acr_values = m, this.resource = f, this.response_mode = y, this.filterProtocolClaims = null == S || S, this.loadUserInfo = !!b, this.staleStateAgeInSeconds = I, this.mergeClaimsStrategy = E, this.omitScopeWhenRequesting = L, this.disablePKCE = !!k, this.revokeTokenAdditionalContentTypes = R, this.fetchRequestCredentials = A || "same-origin", this.requestTimeoutInSeconds = v, T) this.stateStore = T;
6579 else {
6580 const e = "undefined" != typeof window ? window.localStorage : new J();
6581 this.stateStore = new Y({ store: e });
6582 }
6583 if (this.refreshTokenAllowedScope = C, this.extraQueryParams = x, this.extraTokenParams = P, this.extraHeaders = O, this.dpop = U, this.dpop && !(null == (D = this.dpop) ? void 0 : D.store)) throw new Error("A DPoPStore is required when dpop is enabled");
6584 }
6585 };
6586 var ee = class {
6587 constructor(e, t) {
6588 this._settings = e, this._metadataService = t, this._logger = new L("UserInfoService"), this._getClaimsFromJwt = async (e) => {
6589 const t = this._logger.create("_getClaimsFromJwt");
6590 try {
6591 const i = D.decode(e);
6592 return t.debug("JWT decoding successful"), i;
6593 } catch (e) {
6594 throw t.error("Error parsing JWT response"), e;
6595 }
6596 }, this._jsonService = new Q(void 0, this._getClaimsFromJwt, this._settings.extraHeaders);
6597 }
6598 async getClaims(e) {
6599 const t = this._logger.create("getClaims");
6600 e || this._logger.throw(/* @__PURE__ */ new Error("No token passed"));
6601 const i = await this._metadataService.getUserInfoEndpoint();
6602 t.debug("got userinfo url", i);
6603 const n = await this._jsonService.getJson(i, {
6604 token: e,
6605 credentials: this._settings.fetchRequestCredentials,
6606 timeoutInSeconds: this._settings.requestTimeoutInSeconds
6607 });
6608 return t.debug("got claims", n), n;
6609 }
6610 };
6611 var te = class {
6612 constructor(e, t) {
6613 this._settings = e, this._metadataService = t, this._logger = new L("TokenClient"), this._jsonService = new Q(this._settings.revokeTokenAdditionalContentTypes, null, this._settings.extraHeaders);
6614 }
6615 async exchangeCode({ grant_type: e = "authorization_code", redirect_uri: t = this._settings.redirect_uri, client_id: i = this._settings.client_id, client_secret: n = this._settings.client_secret, extraHeaders: s, ...r }) {
6616 const o = this._logger.create("exchangeCode");
6617 i || o.throw(/* @__PURE__ */ new Error("A client_id is required")), t || o.throw(/* @__PURE__ */ new Error("A redirect_uri is required")), r.code || o.throw(/* @__PURE__ */ new Error("A code is required"));
6618 const a = new URLSearchParams({
6619 grant_type: e,
6620 redirect_uri: t
6621 });
6622 for (const [e, t] of Object.entries(r)) null != t && a.set(e, t);
6623 if (("client_secret_basic" === this._settings.client_authentication || "client_secret_jwt" === this._settings.client_authentication) && null == n) throw o.throw(/* @__PURE__ */ new Error("A client_secret is required")), null;
6624 let c;
6625 const d = await this._metadataService.getTokenEndpoint(!1);
6626 switch (this._settings.client_authentication) {
6627 case "client_secret_basic":
6628 c = $.generateBasicAuth(i, n);
6629 break;
6630 case "client_secret_post":
6631 a.append("client_id", i), n && a.append("client_secret", n);
6632 break;
6633 case "client_secret_jwt": {
6634 const e = await $.generateClientAssertionJwt(i, n, d, this._settings.token_endpoint_auth_signing_alg);
6635 a.append("client_id", i), a.append("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"), a.append("client_assertion", e);
6636 break;
6637 }
6638 }
6639 o.debug("got token endpoint");
6640 const l = await this._jsonService.postForm(d, {
6641 body: a,
6642 basicAuth: c,
6643 timeoutInSeconds: this._settings.requestTimeoutInSeconds,
6644 initCredentials: this._settings.fetchRequestCredentials,
6645 extraHeaders: s
6646 });
6647 return o.debug("got response"), l;
6648 }
6649 async exchangeCredentials({ grant_type: e = "password", client_id: t = this._settings.client_id, client_secret: i = this._settings.client_secret, scope: n = this._settings.scope, ...s }) {
6650 const r = this._logger.create("exchangeCredentials");
6651 t || r.throw(/* @__PURE__ */ new Error("A client_id is required"));
6652 const o = new URLSearchParams({ grant_type: e });
6653 this._settings.omitScopeWhenRequesting || o.set("scope", n);
6654 for (const [e, t] of Object.entries(s)) null != t && o.set(e, t);
6655 if (("client_secret_basic" === this._settings.client_authentication || "client_secret_jwt" === this._settings.client_authentication) && null == i) throw r.throw(/* @__PURE__ */ new Error("A client_secret is required")), null;
6656 let a;
6657 const c = await this._metadataService.getTokenEndpoint(!1);
6658 switch (this._settings.client_authentication) {
6659 case "client_secret_basic":
6660 a = $.generateBasicAuth(t, i);
6661 break;
6662 case "client_secret_post":
6663 o.append("client_id", t), i && o.append("client_secret", i);
6664 break;
6665 case "client_secret_jwt": {
6666 const e = await $.generateClientAssertionJwt(t, i, c, this._settings.token_endpoint_auth_signing_alg);
6667 o.append("client_id", t), o.append("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"), o.append("client_assertion", e);
6668 break;
6669 }
6670 }
6671 r.debug("got token endpoint");
6672 const d = await this._jsonService.postForm(c, {
6673 body: o,
6674 basicAuth: a,
6675 timeoutInSeconds: this._settings.requestTimeoutInSeconds,
6676 initCredentials: this._settings.fetchRequestCredentials
6677 });
6678 return r.debug("got response"), d;
6679 }
6680 async exchangeRefreshToken({ grant_type: e = "refresh_token", client_id: t = this._settings.client_id, client_secret: i = this._settings.client_secret, timeoutInSeconds: n, extraHeaders: s, ...r }) {
6681 const o = this._logger.create("exchangeRefreshToken");
6682 t || o.throw(/* @__PURE__ */ new Error("A client_id is required")), r.refresh_token || o.throw(/* @__PURE__ */ new Error("A refresh_token is required"));
6683 const a = new URLSearchParams({ grant_type: e });
6684 for (const [e, t] of Object.entries(r)) Array.isArray(t) ? t.forEach((t) => a.append(e, t)) : null != t && a.set(e, t);
6685 if (("client_secret_basic" === this._settings.client_authentication || "client_secret_jwt" === this._settings.client_authentication) && null == i) throw o.throw(/* @__PURE__ */ new Error("A client_secret is required")), null;
6686 let c;
6687 const d = await this._metadataService.getTokenEndpoint(!1);
6688 switch (this._settings.client_authentication) {
6689 case "client_secret_basic":
6690 c = $.generateBasicAuth(t, i);
6691 break;
6692 case "client_secret_post":
6693 a.append("client_id", t), i && a.append("client_secret", i);
6694 break;
6695 case "client_secret_jwt": {
6696 const e = await $.generateClientAssertionJwt(t, i, d, this._settings.token_endpoint_auth_signing_alg);
6697 a.append("client_id", t), a.append("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"), a.append("client_assertion", e);
6698 break;
6699 }
6700 }
6701 o.debug("got token endpoint");
6702 const l = await this._jsonService.postForm(d, {
6703 body: a,
6704 basicAuth: c,
6705 timeoutInSeconds: n,
6706 initCredentials: this._settings.fetchRequestCredentials,
6707 extraHeaders: s
6708 });
6709 return o.debug("got response"), l;
6710 }
6711 async revoke(e) {
6712 var t;
6713 const i = this._logger.create("revoke");
6714 e.token || i.throw(/* @__PURE__ */ new Error("A token is required"));
6715 const n = await this._metadataService.getRevocationEndpoint(!1);
6716 i.debug(`got revocation endpoint, revoking ${null != (t = e.token_type_hint) ? t : "default token type"}`);
6717 const s = new URLSearchParams();
6718 for (const [t, i] of Object.entries(e)) null != i && s.set(t, i);
6719 s.set("client_id", this._settings.client_id), this._settings.client_secret && s.set("client_secret", this._settings.client_secret), await this._jsonService.postForm(n, {
6720 body: s,
6721 timeoutInSeconds: this._settings.requestTimeoutInSeconds
6722 }), i.debug("got response");
6723 }
6724 };
6725 var ie = class {
6726 constructor(e, t, i) {
6727 this._settings = e, this._metadataService = t, this._claimsService = i, this._logger = new L("ResponseValidator"), this._userInfoService = new ee(this._settings, this._metadataService), this._tokenClient = new te(this._settings, this._metadataService);
6728 }
6729 async validateSigninResponse(e, t, i) {
6730 const n = this._logger.create("validateSigninResponse");
6731 this._processSigninState(e, t), n.debug("state processed"), await this._processCode(e, t, i), n.debug("code processed"), e.isOpenId && this._validateIdTokenAttributes(e), n.debug("tokens validated"), await this._processClaims(e, null == t ? void 0 : t.skipUserInfo, e.isOpenId), n.debug("claims processed");
6732 }
6733 async validateCredentialsResponse(e, t) {
6734 const i = this._logger.create("validateCredentialsResponse");
6735 const n = e.isOpenId && !!e.id_token;
6736 n && this._validateIdTokenAttributes(e), i.debug("tokens validated"), await this._processClaims(e, t, n), i.debug("claims processed");
6737 }
6738 async validateRefreshResponse(e, t) {
6739 const i = this._logger.create("validateRefreshResponse");
6740 e.userState = t.data, e.session_state ??= t.session_state, e.scope ??= t.scope, e.isOpenId && e.id_token && (this._validateIdTokenAttributes(e, t.id_token), i.debug("ID Token validated")), e.id_token || (e.id_token = t.id_token, e.profile = t.profile);
6741 const n = e.isOpenId && !!e.id_token;
6742 await this._processClaims(e, !1, n), i.debug("claims processed");
6743 }
6744 validateSignoutResponse(e, t) {
6745 const i = this._logger.create("validateSignoutResponse");
6746 if (t.id !== e.state && i.throw(/* @__PURE__ */ new Error("State does not match")), i.debug("state validated"), e.userState = t.data, e.error) throw i.warn("Response was error", e.error), new B(e);
6747 }
6748 _processSigninState(e, t) {
6749 const i = this._logger.create("_processSigninState");
6750 if (t.id !== e.state && i.throw(/* @__PURE__ */ new Error("State does not match")), t.client_id || i.throw(/* @__PURE__ */ new Error("No client_id on state")), t.authority || i.throw(/* @__PURE__ */ new Error("No authority on state")), this._settings.authority !== t.authority && i.throw(/* @__PURE__ */ new Error("authority mismatch on settings vs. signin state")), this._settings.client_id && this._settings.client_id !== t.client_id && i.throw(/* @__PURE__ */ new Error("client_id mismatch on settings vs. signin state")), i.debug("state validated"), e.userState = t.data, e.url_state = t.url_state, e.scope ??= t.scope, e.error) throw i.warn("Response was error", e.error), new B(e);
6751 t.code_verifier && !e.code && i.throw(/* @__PURE__ */ new Error("Expected code in response"));
6752 }
6753 async _processClaims(e, t = !1, i = !0) {
6754 const n = this._logger.create("_processClaims");
6755 if (e.profile = this._claimsService.filterProtocolClaims(e.profile), t || !this._settings.loadUserInfo || !e.access_token) return void n.debug("not loading user info");
6756 n.debug("loading user info");
6757 const s = await this._userInfoService.getClaims(e.access_token);
6758 n.debug("user info claims received from user info endpoint"), i && s.sub !== e.profile.sub && n.throw(/* @__PURE__ */ new Error("subject from UserInfo response does not match subject in ID Token")), e.profile = this._claimsService.mergeClaims(e.profile, this._claimsService.filterProtocolClaims(s)), n.debug("user info claims received, updated profile:", e.profile);
6759 }
6760 async _processCode(e, t, i) {
6761 const n = this._logger.create("_processCode");
6762 if (e.code) {
6763 n.debug("Validating code");
6764 const s = await this._tokenClient.exchangeCode({
6765 client_id: t.client_id,
6766 client_secret: t.client_secret,
6767 code: e.code,
6768 redirect_uri: t.redirect_uri,
6769 code_verifier: t.code_verifier,
6770 extraHeaders: i,
6771 ...t.extraTokenParams
6772 });
6773 Object.assign(e, s);
6774 } else n.debug("No code to process");
6775 }
6776 _validateIdTokenAttributes(e, t) {
6777 var i;
6778 const n = this._logger.create("_validateIdTokenAttributes");
6779 n.debug("decoding ID Token JWT");
6780 const s = D.decode(null != (i = e.id_token) ? i : "");
6781 if (s.sub || n.throw(/* @__PURE__ */ new Error("ID Token is missing a subject claim")), t) {
6782 const e = D.decode(t);
6783 s.sub !== e.sub && n.throw(/* @__PURE__ */ new Error("sub in id_token does not match current sub")), s.auth_time && s.auth_time !== e.auth_time && n.throw(/* @__PURE__ */ new Error("auth_time in id_token does not match original auth_time")), s.azp && s.azp !== e.azp && n.throw(/* @__PURE__ */ new Error("azp in id_token does not match original azp")), !s.azp && e.azp && n.throw(/* @__PURE__ */ new Error("azp not in id_token, but present in original id_token"));
6784 }
6785 e.profile = s;
6786 }
6787 };
6788 var ne = class e {
6789 constructor(e) {
6790 this.id = e.id || $.generateUUIDv4(), this.data = e.data, e.created && e.created > 0 ? this.created = e.created : this.created = j.getEpochTime(), this.request_type = e.request_type, this.url_state = e.url_state;
6791 }
6792 toStorageString() {
6793 return new L("State").create("toStorageString"), JSON.stringify({
6794 id: this.id,
6795 data: this.data,
6796 created: this.created,
6797 request_type: this.request_type,
6798 url_state: this.url_state
6799 });
6800 }
6801 static fromStorageString(t) {
6802 return L.createStatic("State", "fromStorageString"), Promise.resolve(new e(JSON.parse(t)));
6803 }
6804 static async clearStaleState(t, i) {
6805 const n = L.createStatic("State", "clearStaleState");
6806 const s = j.getEpochTime() - i;
6807 const r = await t.getAllKeys();
6808 n.debug("got keys", r);
6809 for (let i = 0; i < r.length; i++) {
6810 const o = r[i];
6811 const a = await t.get(o);
6812 let c = !1;
6813 if (a) try {
6814 const t = await e.fromStorageString(a);
6815 n.debug("got item from key:", o, t.created), t.created <= s && (c = !0);
6816 } catch (e) {
6817 n.error("Error parsing state for key:", o, e), c = !0;
6818 }
6819 else n.debug("no item in storage for key:", o), c = !0;
6820 c && (n.debug("removed item for key:", o), t.remove(o));
6821 }
6822 }
6823 };
6824 var se = class e extends ne {
6825 constructor(e) {
6826 super(e), this.code_verifier = e.code_verifier, this.code_challenge = e.code_challenge, this.authority = e.authority, this.client_id = e.client_id, this.redirect_uri = e.redirect_uri, this.scope = e.scope, this.client_secret = e.client_secret, this.extraTokenParams = e.extraTokenParams, this.response_mode = e.response_mode, this.skipUserInfo = e.skipUserInfo;
6827 }
6828 static async create(t) {
6829 const i = !0 === t.code_verifier ? $.generateCodeVerifier() : t.code_verifier || void 0;
6830 const n = i ? await $.generateCodeChallenge(i) : void 0;
6831 return new e({
6832 ...t,
6833 code_verifier: i,
6834 code_challenge: n
6835 });
6836 }
6837 toStorageString() {
6838 return new L("SigninState").create("toStorageString"), JSON.stringify({
6839 id: this.id,
6840 data: this.data,
6841 created: this.created,
6842 request_type: this.request_type,
6843 url_state: this.url_state,
6844 code_verifier: this.code_verifier,
6845 authority: this.authority,
6846 client_id: this.client_id,
6847 redirect_uri: this.redirect_uri,
6848 scope: this.scope,
6849 client_secret: this.client_secret,
6850 extraTokenParams: this.extraTokenParams,
6851 response_mode: this.response_mode,
6852 skipUserInfo: this.skipUserInfo
6853 });
6854 }
6855 static fromStorageString(t) {
6856 L.createStatic("SigninState", "fromStorageString");
6857 const i = JSON.parse(t);
6858 return e.create(i);
6859 }
6860 };
6861 var re = class e {
6862 constructor(e) {
6863 this.url = e.url, this.state = e.state;
6864 }
6865 static async create({ url: t, authority: i, client_id: n, redirect_uri: s, response_type: r, scope: o, state_data: a, response_mode: c, request_type: d, client_secret: l, nonce: g, url_state: u, resource: h, skipUserInfo: p, extraQueryParams: _, extraTokenParams: w, disablePKCE: m, dpopJkt: f, omitScopeWhenRequesting: y, ...S }) {
6866 if (!t) throw this._logger.error("create: No url passed"), /* @__PURE__ */ new Error("url");
6867 if (!n) throw this._logger.error("create: No client_id passed"), /* @__PURE__ */ new Error("client_id");
6868 if (!s) throw this._logger.error("create: No redirect_uri passed"), /* @__PURE__ */ new Error("redirect_uri");
6869 if (!r) throw this._logger.error("create: No response_type passed"), /* @__PURE__ */ new Error("response_type");
6870 if (!o) throw this._logger.error("create: No scope passed"), /* @__PURE__ */ new Error("scope");
6871 if (!i) throw this._logger.error("create: No authority passed"), /* @__PURE__ */ new Error("authority");
6872 const b = await se.create({
6873 data: a,
6874 request_type: d,
6875 url_state: u,
6876 code_verifier: !m,
6877 client_id: n,
6878 authority: i,
6879 redirect_uri: s,
6880 response_mode: c,
6881 client_secret: l,
6882 scope: o,
6883 extraTokenParams: w,
6884 skipUserInfo: p
6885 });
6886 const v = new URL(t);
6887 v.searchParams.append("client_id", n), v.searchParams.append("redirect_uri", s), v.searchParams.append("response_type", r), y || v.searchParams.append("scope", o), g && v.searchParams.append("nonce", g), f && v.searchParams.append("dpop_jkt", f);
6888 let I = b.id;
6889 u && (I = `${I}${z$2}${u}`), v.searchParams.append("state", I), b.code_challenge && (v.searchParams.append("code_challenge", b.code_challenge), v.searchParams.append("code_challenge_method", "S256")), h && (Array.isArray(h) ? h : [h]).forEach((e) => v.searchParams.append("resource", e));
6890 for (const [e, t] of Object.entries({
6891 response_mode: c,
6892 ...S,
6893 ..._
6894 })) null != t && v.searchParams.append(e, t.toString());
6895 return new e({
6896 url: v.href,
6897 state: b
6898 });
6899 }
6900 };
6901 re._logger = new L("SigninRequest");
6902 var oe = re;
6903 var ae = class {
6904 constructor(e) {
6905 if (this.access_token = "", this.token_type = "", this.profile = {}, this.state = e.get("state"), this.session_state = e.get("session_state"), this.state) {
6906 const e = decodeURIComponent(this.state).split(z$2);
6907 this.state = e[0], e.length > 1 && (this.url_state = e.slice(1).join(z$2));
6908 }
6909 this.error = e.get("error"), this.error_description = e.get("error_description"), this.error_uri = e.get("error_uri"), this.code = e.get("code");
6910 }
6911 get expires_in() {
6912 if (void 0 !== this.expires_at) return this.expires_at - j.getEpochTime();
6913 }
6914 set expires_in(e) {
6915 "string" == typeof e && (e = Number(e)), void 0 !== e && e >= 0 && (this.expires_at = Math.floor(e) + j.getEpochTime());
6916 }
6917 get isOpenId() {
6918 var e;
6919 return (null == (e = this.scope) ? void 0 : e.split(" ").includes("openid")) || !!this.id_token;
6920 }
6921 };
6922 var ce = class {
6923 constructor({ url: e, state_data: t, id_token_hint: i, post_logout_redirect_uri: n, extraQueryParams: s, request_type: r, client_id: o, url_state: a }) {
6924 if (this._logger = new L("SignoutRequest"), !e) throw this._logger.error("ctor: No url passed"), /* @__PURE__ */ new Error("url");
6925 const c = new URL(e);
6926 if (i && c.searchParams.append("id_token_hint", i), o && c.searchParams.append("client_id", o), n && (c.searchParams.append("post_logout_redirect_uri", n), t || a)) {
6927 this.state = new ne({
6928 data: t,
6929 request_type: r,
6930 url_state: a
6931 });
6932 let e = this.state.id;
6933 a && (e = `${e}${z$2}${a}`), c.searchParams.append("state", e);
6934 }
6935 for (const [e, t] of Object.entries({ ...s })) null != t && c.searchParams.append(e, t.toString());
6936 this.url = c.href;
6937 }
6938 };
6939 var de = class {
6940 constructor(e) {
6941 if (this.state = e.get("state"), this.state) {
6942 const e = decodeURIComponent(this.state).split(z$2);
6943 this.state = e[0], e.length > 1 && (this.url_state = e.slice(1).join(z$2));
6944 }
6945 this.error = e.get("error"), this.error_description = e.get("error_description"), this.error_uri = e.get("error_uri");
6946 }
6947 };
6948 var le = [
6949 "nbf",
6950 "jti",
6951 "auth_time",
6952 "nonce",
6953 "acr",
6954 "amr",
6955 "azp",
6956 "at_hash"
6957 ];
6958 var ge = [
6959 "sub",
6960 "iss",
6961 "aud",
6962 "exp",
6963 "iat"
6964 ];
6965 var ue = class {
6966 constructor(e) {
6967 this._settings = e, this._logger = new L("ClaimsService");
6968 }
6969 filterProtocolClaims(e) {
6970 const t = { ...e };
6971 if (this._settings.filterProtocolClaims) {
6972 let e;
6973 e = Array.isArray(this._settings.filterProtocolClaims) ? this._settings.filterProtocolClaims : le;
6974 for (const i of e) ge.includes(i) || delete t[i];
6975 }
6976 return t;
6977 }
6978 mergeClaims(e, t) {
6979 const i = { ...e };
6980 for (const [e, n] of Object.entries(t)) if (i[e] !== n) if (Array.isArray(i[e]) || Array.isArray(n)) if ("replace" == this._settings.mergeClaimsStrategy.array) i[e] = n;
6981 else {
6982 const t = Array.isArray(i[e]) ? i[e] : [i[e]];
6983 for (const e of Array.isArray(n) ? n : [n]) t.includes(e) || t.push(e);
6984 i[e] = t;
6985 }
6986 else "object" == typeof i[e] && "object" == typeof n ? i[e] = this.mergeClaims(i[e], n) : i[e] = n;
6987 return i;
6988 }
6989 };
6990 var he = class {
6991 constructor(e, t) {
6992 this.keys = e, this.nonce = t;
6993 }
6994 };
6995 var pe = class {
6996 constructor(e, t) {
6997 this._logger = new L("OidcClient"), this.settings = e instanceof Z ? e : new Z(e), this.metadataService = null != t ? t : new X(this.settings), this._claimsService = new ue(this.settings), this._validator = new ie(this.settings, this.metadataService, this._claimsService), this._tokenClient = new te(this.settings, this.metadataService);
6998 }
6999 async createSigninRequest({ state: e, request: t, request_uri: i, request_type: n, id_token_hint: s, login_hint: r, skipUserInfo: o, nonce: a, url_state: c, response_type: d = this.settings.response_type, scope: l = this.settings.scope, redirect_uri: g = this.settings.redirect_uri, prompt: u = this.settings.prompt, display: h = this.settings.display, max_age: p = this.settings.max_age, ui_locales: _ = this.settings.ui_locales, acr_values: w = this.settings.acr_values, resource: m = this.settings.resource, response_mode: f = this.settings.response_mode, extraQueryParams: y = this.settings.extraQueryParams, extraTokenParams: S = this.settings.extraTokenParams, dpopJkt: b, omitScopeWhenRequesting: v = this.settings.omitScopeWhenRequesting }) {
7000 const I = this._logger.create("createSigninRequest");
7001 if ("code" !== d) throw new Error("Only the Authorization Code flow (with PKCE) is supported");
7002 const E = await this.metadataService.getAuthorizationEndpoint();
7003 I.debug("Received authorization endpoint", E);
7004 const k = await oe.create({
7005 url: E,
7006 authority: this.settings.authority,
7007 client_id: this.settings.client_id,
7008 redirect_uri: g,
7009 response_type: d,
7010 scope: l,
7011 state_data: e,
7012 url_state: c,
7013 prompt: u,
7014 display: h,
7015 max_age: p,
7016 ui_locales: _,
7017 id_token_hint: s,
7018 login_hint: r,
7019 acr_values: w,
7020 dpopJkt: b,
7021 resource: m,
7022 request: t,
7023 request_uri: i,
7024 extraQueryParams: y,
7025 extraTokenParams: S,
7026 request_type: n,
7027 response_mode: f,
7028 client_secret: this.settings.client_secret,
7029 skipUserInfo: o,
7030 nonce: a,
7031 disablePKCE: this.settings.disablePKCE,
7032 omitScopeWhenRequesting: v
7033 });
7034 await this.clearStaleState();
7035 const T = k.state;
7036 return await this.settings.stateStore.set(T.id, T.toStorageString()), k;
7037 }
7038 async readSigninResponseState(e, t = !1) {
7039 const i = this._logger.create("readSigninResponseState");
7040 const n = new ae(G.readParams(e, this.settings.response_mode));
7041 if (!n.state) throw i.throw(/* @__PURE__ */ new Error("No state in response")), null;
7042 const s = await this.settings.stateStore[t ? "remove" : "get"](n.state);
7043 if (!s) throw i.throw(/* @__PURE__ */ new Error("No matching state found in storage")), null;
7044 return {
7045 state: await se.fromStorageString(s),
7046 response: n
7047 };
7048 }
7049 async processSigninResponse(e, t, i = !0) {
7050 const n = this._logger.create("processSigninResponse"), { state: s, response: r } = await this.readSigninResponseState(e, i);
7051 if (n.debug("received state from storage; validating response"), this.settings.dpop && this.settings.dpop.store) {
7052 const e = await this.getDpopProof(this.settings.dpop.store);
7053 t = {
7054 ...t,
7055 DPoP: e
7056 };
7057 }
7058 try {
7059 await this._validator.validateSigninResponse(r, s, t);
7060 } catch (e) {
7061 if (!(e instanceof V && this.settings.dpop)) throw e;
7062 {
7063 const i = await this.getDpopProof(this.settings.dpop.store, e.nonce);
7064 t.DPoP = i, await this._validator.validateSigninResponse(r, s, t);
7065 }
7066 }
7067 return r;
7068 }
7069 async getDpopProof(e, t) {
7070 let i;
7071 let n;
7072 return (await e.getAllKeys()).includes(this.settings.client_id) ? (n = await e.get(this.settings.client_id), n.nonce !== t && t && (n.nonce = t, await e.set(this.settings.client_id, n))) : (i = await $.generateDPoPKeys(), n = new he(i, t), await e.set(this.settings.client_id, n)), await $.generateDPoPProof({
7073 url: await this.metadataService.getTokenEndpoint(!1),
7074 httpMethod: "POST",
7075 keyPair: n.keys,
7076 nonce: n.nonce
7077 });
7078 }
7079 async processResourceOwnerPasswordCredentials({ username: e, password: t, skipUserInfo: i = !1, extraTokenParams: n = {} }) {
7080 const s = await this._tokenClient.exchangeCredentials({
7081 username: e,
7082 password: t,
7083 ...n
7084 });
7085 const r = new ae(new URLSearchParams());
7086 return Object.assign(r, s), await this._validator.validateCredentialsResponse(r, i), r;
7087 }
7088 async useRefreshToken({ state: e, redirect_uri: t, resource: i, timeoutInSeconds: n, extraHeaders: s, extraTokenParams: r }) {
7089 var o;
7090 const a = this._logger.create("useRefreshToken");
7091 let c;
7092 let d;
7093 if (void 0 === this.settings.refreshTokenAllowedScope) c = e.scope;
7094 else {
7095 const t = this.settings.refreshTokenAllowedScope.split(" ");
7096 c = ((null == (o = e.scope) ? void 0 : o.split(" ")) || []).filter((e) => t.includes(e)).join(" ");
7097 }
7098 if (this.settings.dpop && this.settings.dpop.store) {
7099 const e = await this.getDpopProof(this.settings.dpop.store);
7100 s = {
7101 ...s,
7102 DPoP: e
7103 };
7104 }
7105 try {
7106 d = await this._tokenClient.exchangeRefreshToken({
7107 refresh_token: e.refresh_token,
7108 scope: c,
7109 redirect_uri: t,
7110 resource: i,
7111 timeoutInSeconds: n,
7112 extraHeaders: s,
7113 ...r
7114 });
7115 } catch (o) {
7116 if (!(o instanceof V && this.settings.dpop)) throw o;
7117 s.DPoP = await this.getDpopProof(this.settings.dpop.store, o.nonce), d = await this._tokenClient.exchangeRefreshToken({
7118 refresh_token: e.refresh_token,
7119 scope: c,
7120 redirect_uri: t,
7121 resource: i,
7122 timeoutInSeconds: n,
7123 extraHeaders: s,
7124 ...r
7125 });
7126 }
7127 const l = new ae(new URLSearchParams());
7128 return Object.assign(l, d), a.debug("validating response", l), await this._validator.validateRefreshResponse(l, {
7129 ...e,
7130 scope: c
7131 }), l;
7132 }
7133 async createSignoutRequest({ state: e, id_token_hint: t, client_id: i, request_type: n, url_state: s, post_logout_redirect_uri: r = this.settings.post_logout_redirect_uri, extraQueryParams: o = this.settings.extraQueryParams } = {}) {
7134 const a = this._logger.create("createSignoutRequest");
7135 const c = await this.metadataService.getEndSessionEndpoint();
7136 if (!c) throw a.throw(/* @__PURE__ */ new Error("No end session endpoint")), null;
7137 a.debug("Received end session endpoint", c), i || !r || t || (i = this.settings.client_id);
7138 const d = new ce({
7139 url: c,
7140 id_token_hint: t,
7141 client_id: i,
7142 post_logout_redirect_uri: r,
7143 state_data: e,
7144 extraQueryParams: o,
7145 request_type: n,
7146 url_state: s
7147 });
7148 await this.clearStaleState();
7149 const l = d.state;
7150 return l && (a.debug("Signout request has state to persist"), await this.settings.stateStore.set(l.id, l.toStorageString())), d;
7151 }
7152 async readSignoutResponseState(e, t = !1) {
7153 const i = this._logger.create("readSignoutResponseState");
7154 const n = new de(G.readParams(e, this.settings.response_mode));
7155 if (!n.state) {
7156 if (i.debug("No state in response"), n.error) throw i.warn("Response was error:", n.error), new B(n);
7157 return {
7158 state: void 0,
7159 response: n
7160 };
7161 }
7162 const s = await this.settings.stateStore[t ? "remove" : "get"](n.state);
7163 if (!s) throw i.throw(/* @__PURE__ */ new Error("No matching state found in storage")), null;
7164 return {
7165 state: await ne.fromStorageString(s),
7166 response: n
7167 };
7168 }
7169 async processSignoutResponse(e) {
7170 const t = this._logger.create("processSignoutResponse"), { state: i, response: n } = await this.readSignoutResponseState(e, !0);
7171 return i ? (t.debug("Received state from storage; validating response"), this._validator.validateSignoutResponse(n, i)) : t.debug("No state from storage; skipping response validation"), n;
7172 }
7173 clearStaleState() {
7174 return this._logger.create("clearStaleState"), ne.clearStaleState(this.settings.stateStore, this.settings.staleStateAgeInSeconds);
7175 }
7176 async revokeToken(e, t) {
7177 return this._logger.create("revokeToken"), await this._tokenClient.revoke({
7178 token: e,
7179 token_type_hint: t
7180 });
7181 }
7182 };
7183 var _e = class {
7184 constructor(e) {
7185 this._userManager = e, this._logger = new L("SessionMonitor"), this._start = async (e) => {
7186 const t = e.session_state;
7187 if (!t) return;
7188 const i = this._logger.create("_start");
7189 if (e.profile ? (this._sub = e.profile.sub, i.debug("session_state", t, ", sub", this._sub)) : (this._sub = void 0, i.debug("session_state", t, ", anonymous user")), this._checkSessionIFrame) this._checkSessionIFrame.start(t);
7190 else try {
7191 const e = await this._userManager.metadataService.getCheckSessionIframe();
7192 if (e) {
7193 i.debug("initializing check session iframe");
7194 const n = this._userManager.settings.client_id;
7195 const s = this._userManager.settings.checkSessionIntervalInSeconds;
7196 const r = this._userManager.settings.stopCheckSessionOnError;
7197 const o = new K(this._callback, n, e, s, r);
7198 await o.load(), this._checkSessionIFrame = o, o.start(t);
7199 } else i.warn("no check session iframe found in the metadata");
7200 } catch (e) {
7201 i.error("Error from getCheckSessionIframe:", e instanceof Error ? e.message : e);
7202 }
7203 }, this._stop = () => {
7204 const e = this._logger.create("_stop");
7205 if (this._sub = void 0, this._checkSessionIFrame && this._checkSessionIFrame.stop(), this._userManager.settings.monitorAnonymousSession) {
7206 const t = setInterval(async () => {
7207 clearInterval(t);
7208 try {
7209 const e = await this._userManager.querySessionStatus();
7210 if (e) {
7211 const t = {
7212 session_state: e.session_state,
7213 profile: e.sub ? { sub: e.sub } : null
7214 };
7215 this._start(t);
7216 }
7217 } catch (t) {
7218 e.error("error from querySessionStatus", t instanceof Error ? t.message : t);
7219 }
7220 }, 1e3);
7221 }
7222 }, this._callback = async () => {
7223 const e = this._logger.create("_callback");
7224 try {
7225 const t = await this._userManager.querySessionStatus();
7226 let i = !0;
7227 t && this._checkSessionIFrame ? t.sub === this._sub ? (i = !1, this._checkSessionIFrame.start(t.session_state), e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state", t.session_state), await this._userManager.events._raiseUserSessionChanged()) : e.debug("different subject signed into OP", t.sub) : e.debug("subject no longer signed into OP"), i ? this._sub ? await this._userManager.events._raiseUserSignedOut() : await this._userManager.events._raiseUserSignedIn() : e.debug("no change in session detected, no event to raise");
7228 } catch (t) {
7229 this._sub && (e.debug("Error calling queryCurrentSigninSession; raising signed out event", t), await this._userManager.events._raiseUserSignedOut());
7230 }
7231 }, e || this._logger.throw(/* @__PURE__ */ new Error("No user manager passed")), this._userManager.events.addUserLoaded(this._start), this._userManager.events.addUserUnloaded(this._stop), this._init().catch((e) => {
7232 this._logger.error(e);
7233 });
7234 }
7235 async _init() {
7236 this._logger.create("_init");
7237 const e = await this._userManager.getUser();
7238 if (e) this._start(e);
7239 else if (this._userManager.settings.monitorAnonymousSession) {
7240 const e = await this._userManager.querySessionStatus();
7241 if (e) {
7242 const t = {
7243 session_state: e.session_state,
7244 profile: e.sub ? { sub: e.sub } : null
7245 };
7246 this._start(t);
7247 }
7248 }
7249 }
7250 };
7251 var we = class e {
7252 constructor(e) {
7253 var t;
7254 this.id_token = e.id_token, this.session_state = null != (t = e.session_state) ? t : null, this.access_token = e.access_token, this.refresh_token = e.refresh_token, this.token_type = e.token_type, this.scope = e.scope, this.profile = e.profile, this.expires_at = e.expires_at, this.state = e.userState, this.url_state = e.url_state;
7255 }
7256 get expires_in() {
7257 if (void 0 !== this.expires_at) return this.expires_at - j.getEpochTime();
7258 }
7259 set expires_in(e) {
7260 void 0 !== e && (this.expires_at = Math.floor(e) + j.getEpochTime());
7261 }
7262 get expired() {
7263 const e = this.expires_in;
7264 if (void 0 !== e) return e <= 0;
7265 }
7266 get scopes() {
7267 var e;
7268 var t;
7269 return null != (t = null == (e = this.scope) ? void 0 : e.split(" ")) ? t : [];
7270 }
7271 toStorageString() {
7272 return new L("User").create("toStorageString"), JSON.stringify({
7273 id_token: this.id_token,
7274 session_state: this.session_state,
7275 access_token: this.access_token,
7276 refresh_token: this.refresh_token,
7277 token_type: this.token_type,
7278 scope: this.scope,
7279 profile: this.profile,
7280 expires_at: this.expires_at
7281 });
7282 }
7283 static fromStorageString(t) {
7284 return L.createStatic("User", "fromStorageString"), new e(JSON.parse(t));
7285 }
7286 };
7287 var me = "oidc-client";
7288 var fe = class {
7289 constructor() {
7290 this._abort = new M("Window navigation aborted"), this._disposeHandlers = /* @__PURE__ */ new Set(), this._window = null;
7291 }
7292 async navigate(e) {
7293 const t = this._logger.create("navigate");
7294 if (!this._window) throw new Error("Attempted to navigate on a disposed window");
7295 t.debug("setting URL in window"), this._window.location.replace(e.url);
7296 const { url: i, keepOpen: n } = await new Promise((i, n) => {
7297 const s = (s) => {
7298 var r;
7299 const o = s.data;
7300 const a = null != (r = e.scriptOrigin) ? r : window.location.origin;
7301 if (s.origin === a && (null == o ? void 0 : o.source) === me) {
7302 try {
7303 const i = G.readParams(o.url, e.response_mode).get("state");
7304 if (i || t.warn("no state found in response url"), s.source !== this._window && i !== e.state) return;
7305 } catch {
7306 this._dispose(), n(/* @__PURE__ */ new Error("Invalid response from window"));
7307 }
7308 i(o);
7309 }
7310 };
7311 window.addEventListener("message", s, !1), this._disposeHandlers.add(() => window.removeEventListener("message", s, !1));
7312 const r = new BroadcastChannel(`oidc-client-popup-${e.state}`);
7313 r.addEventListener("message", s, !1), this._disposeHandlers.add(() => r.close()), this._disposeHandlers.add(this._abort.addHandler((e) => {
7314 this._dispose(), n(e);
7315 }));
7316 });
7317 return t.debug("got response from window"), this._dispose(), n || this.close(), { url: i };
7318 }
7319 _dispose() {
7320 this._logger.create("_dispose");
7321 for (const e of this._disposeHandlers) e();
7322 this._disposeHandlers.clear();
7323 }
7324 static _notifyParent(e, t, i = !1, n = window.location.origin) {
7325 const s = {
7326 source: me,
7327 url: t,
7328 keepOpen: i
7329 };
7330 const r = new L("_notifyParent");
7331 if (e) r.debug("With parent. Using parent.postMessage."), e.postMessage(s, n);
7332 else {
7333 r.debug("No parent. Using BroadcastChannel.");
7334 const e = new URL(t).searchParams.get("state");
7335 if (!e) throw new Error("No parent and no state in URL. Can't complete notification.");
7336 const i = new BroadcastChannel(`oidc-client-popup-${e}`);
7337 i.postMessage(s), i.close();
7338 }
7339 }
7340 };
7341 var ye = {
7342 location: !1,
7343 toolbar: !1,
7344 height: 640,
7345 closePopupWindowAfterInSeconds: -1
7346 };
7347 var Se = "_blank";
7348 var be = 60;
7349 var ve = 2;
7350 var Ie = class extends Z {
7351 constructor(e) {
7352 const { popup_redirect_uri: t = e.redirect_uri, popup_post_logout_redirect_uri: i = e.post_logout_redirect_uri, popupWindowFeatures: n = ye, popupWindowTarget: s = Se, redirectMethod: r = "assign", redirectTarget: o = "self", iframeNotifyParentOrigin: a = e.iframeNotifyParentOrigin, iframeScriptOrigin: c = e.iframeScriptOrigin, requestTimeoutInSeconds: d, silent_redirect_uri: l = e.redirect_uri, silentRequestTimeoutInSeconds: g, automaticSilentRenew: u = !0, validateSubOnSilentRenew: h = !0, includeIdTokenInSilentRenew: p = !1, monitorSession: _ = !1, monitorAnonymousSession: w = !1, checkSessionIntervalInSeconds: m = ve, query_status_response_type: f = "code", stopCheckSessionOnError: y = !0, revokeTokenTypes: S = ["access_token", "refresh_token"], revokeTokensOnSignout: b = !1, includeIdTokenInSilentSignout: v = !1, accessTokenExpiringNotificationTimeInSeconds: I = be, userStore: E } = e;
7353 if (super(e), this.popup_redirect_uri = t, this.popup_post_logout_redirect_uri = i, this.popupWindowFeatures = n, this.popupWindowTarget = s, this.redirectMethod = r, this.redirectTarget = o, this.iframeNotifyParentOrigin = a, this.iframeScriptOrigin = c, this.silent_redirect_uri = l, this.silentRequestTimeoutInSeconds = g || d || 10, this.automaticSilentRenew = u, this.validateSubOnSilentRenew = h, this.includeIdTokenInSilentRenew = p, this.monitorSession = _, this.monitorAnonymousSession = w, this.checkSessionIntervalInSeconds = m, this.stopCheckSessionOnError = y, this.query_status_response_type = f, this.revokeTokenTypes = S, this.revokeTokensOnSignout = b, this.includeIdTokenInSilentSignout = v, this.accessTokenExpiringNotificationTimeInSeconds = I, E) this.userStore = E;
7354 else {
7355 const e = "undefined" != typeof window ? window.sessionStorage : new J();
7356 this.userStore = new Y({ store: e });
7357 }
7358 }
7359 };
7360 var Ee = class e extends fe {
7361 constructor({ silentRequestTimeoutInSeconds: t = 10 }) {
7362 super(), this._logger = new L("IFrameWindow"), this._timeoutInSeconds = t, this._frame = e.createHiddenIframe(), this._window = this._frame.contentWindow;
7363 }
7364 static createHiddenIframe() {
7365 const e = window.document.createElement("iframe");
7366 return e.style.visibility = "hidden", e.style.position = "fixed", e.style.left = "-1000px", e.style.top = "0", e.width = "0", e.height = "0", window.document.body.appendChild(e), e;
7367 }
7368 async navigate(e) {
7369 this._logger.debug("navigate: Using timeout of:", this._timeoutInSeconds);
7370 const t = setTimeout(() => {
7371 this._abort.raise(new W("IFrame timed out without a response"));
7372 }, 1e3 * this._timeoutInSeconds);
7373 return this._disposeHandlers.add(() => clearTimeout(t)), await super.navigate(e);
7374 }
7375 close() {
7376 var e;
7377 this._frame && (this._frame.parentNode && (this._frame.addEventListener("load", (e) => {
7378 var t;
7379 const i = e.target;
7380 null == (t = i.parentNode) || t.removeChild(i), this._abort.raise(/* @__PURE__ */ new Error("IFrame removed from DOM"));
7381 }, !0), null == (e = this._frame.contentWindow) || e.location.replace("about:blank")), this._frame = null), this._window = null;
7382 }
7383 static notifyParent(e, t) {
7384 return super._notifyParent(window.parent, e, !1, t);
7385 }
7386 };
7387 var ke = class {
7388 constructor(e) {
7389 this._settings = e, this._logger = new L("IFrameNavigator");
7390 }
7391 async prepare({ silentRequestTimeoutInSeconds: e = this._settings.silentRequestTimeoutInSeconds }) {
7392 return new Ee({ silentRequestTimeoutInSeconds: e });
7393 }
7394 async callback(e) {
7395 this._logger.create("callback"), Ee.notifyParent(e, this._settings.iframeNotifyParentOrigin);
7396 }
7397 };
7398 var Te = class extends fe {
7399 constructor({ popupWindowTarget: e = Se, popupWindowFeatures: t = {}, popupSignal: i, popupAbortOnClose: n }) {
7400 super(), this._logger = new L("PopupWindow");
7401 const s = H.center({
7402 ...ye,
7403 ...t
7404 });
7405 this._window = window.open(void 0, e, H.serialize(s)), this.abortOnClose = Boolean(n), i && i.addEventListener("abort", () => {
7406 var e;
7407 this._abort.raise(new Error(null != (e = i.reason) ? e : "Popup aborted"));
7408 }), t.closePopupWindowAfterInSeconds && t.closePopupWindowAfterInSeconds > 0 && setTimeout(() => {
7409 this._window && "boolean" == typeof this._window.closed && !this._window.closed ? this.close() : this._abort.raise(/* @__PURE__ */ new Error("Popup blocked by user"));
7410 }, 1e3 * t.closePopupWindowAfterInSeconds);
7411 }
7412 async navigate(e) {
7413 var t;
7414 null == (t = this._window) || t.focus();
7415 const i = setInterval(() => {
7416 this._window && !this._window.closed || (this._logger.debug("Popup closed by user or isolated by redirect"), n(), this._disposeHandlers.delete(n), this.abortOnClose && this._abort.raise(/* @__PURE__ */ new Error("Popup closed by user")));
7417 }, 500);
7418 const n = () => clearInterval(i);
7419 return this._disposeHandlers.add(n), await super.navigate(e);
7420 }
7421 close() {
7422 this._window && (this._window.closed || (this._window.close(), this._abort.raise(/* @__PURE__ */ new Error("Popup closed")))), this._window = null;
7423 }
7424 static notifyOpener(e, t) {
7425 super._notifyParent(window.opener, e, t), t || window.opener || window.close();
7426 }
7427 };
7428 var Re = class {
7429 constructor(e) {
7430 this._settings = e, this._logger = new L("PopupNavigator");
7431 }
7432 async prepare({ popupWindowFeatures: e = this._settings.popupWindowFeatures, popupWindowTarget: t = this._settings.popupWindowTarget, popupSignal: i, popupAbortOnClose: n }) {
7433 return new Te({
7434 popupWindowFeatures: e,
7435 popupWindowTarget: t,
7436 popupSignal: i,
7437 popupAbortOnClose: n
7438 });
7439 }
7440 async callback(e, { keepOpen: t = !1 }) {
7441 this._logger.create("callback"), Te.notifyOpener(e, t);
7442 }
7443 };
7444 var Ae = class {
7445 constructor(e) {
7446 this._settings = e, this._logger = new L("RedirectNavigator");
7447 }
7448 async prepare({ redirectMethod: e = this._settings.redirectMethod, redirectTarget: t = this._settings.redirectTarget }) {
7449 var i;
7450 this._logger.create("prepare");
7451 let n = window.self;
7452 "top" === t && (n = null != (i = window.top) ? i : window.self);
7453 const s = n.location[e].bind(n.location);
7454 let r;
7455 return {
7456 navigate: async (e) => {
7457 this._logger.create("navigate");
7458 return await new Promise((t, i) => {
7459 r = i, window.addEventListener("pageshow", () => t(window.location.href)), s(e.url);
7460 });
7461 },
7462 close: () => {
7463 this._logger.create("close"), r?.(/* @__PURE__ */ new Error("Redirect aborted")), n.stop();
7464 }
7465 };
7466 }
7467 async callback() {}
7468 };
7469 var Ce = class extends F {
7470 constructor(e) {
7471 super({ expiringNotificationTimeInSeconds: e.accessTokenExpiringNotificationTimeInSeconds }), this._logger = new L("UserManagerEvents"), this._userLoaded = new M("User loaded"), this._userUnloaded = new M("User unloaded"), this._silentRenewError = new M("Silent renew error"), this._userSignedIn = new M("User signed in"), this._userSignedOut = new M("User signed out"), this._userSessionChanged = new M("User session changed");
7472 }
7473 async load(e, t = !0) {
7474 await super.load(e), t && await this._userLoaded.raise(e);
7475 }
7476 async unload() {
7477 await super.unload(), await this._userUnloaded.raise();
7478 }
7479 addUserLoaded(e) {
7480 return this._userLoaded.addHandler(e);
7481 }
7482 removeUserLoaded(e) {
7483 return this._userLoaded.removeHandler(e);
7484 }
7485 addUserUnloaded(e) {
7486 return this._userUnloaded.addHandler(e);
7487 }
7488 removeUserUnloaded(e) {
7489 return this._userUnloaded.removeHandler(e);
7490 }
7491 addSilentRenewError(e) {
7492 return this._silentRenewError.addHandler(e);
7493 }
7494 removeSilentRenewError(e) {
7495 return this._silentRenewError.removeHandler(e);
7496 }
7497 async _raiseSilentRenewError(e) {
7498 await this._silentRenewError.raise(e);
7499 }
7500 addUserSignedIn(e) {
7501 return this._userSignedIn.addHandler(e);
7502 }
7503 removeUserSignedIn(e) {
7504 this._userSignedIn.removeHandler(e);
7505 }
7506 async _raiseUserSignedIn() {
7507 await this._userSignedIn.raise();
7508 }
7509 addUserSignedOut(e) {
7510 return this._userSignedOut.addHandler(e);
7511 }
7512 removeUserSignedOut(e) {
7513 this._userSignedOut.removeHandler(e);
7514 }
7515 async _raiseUserSignedOut() {
7516 await this._userSignedOut.raise();
7517 }
7518 addUserSessionChanged(e) {
7519 return this._userSessionChanged.addHandler(e);
7520 }
7521 removeUserSessionChanged(e) {
7522 this._userSessionChanged.removeHandler(e);
7523 }
7524 async _raiseUserSessionChanged() {
7525 await this._userSessionChanged.raise();
7526 }
7527 };
7528 var xe = class {
7529 constructor(e) {
7530 this._userManager = e, this._logger = new L("SilentRenewService"), this._isStarted = !1, this._retryTimer = new j("Retry Silent Renew"), this._tokenExpiring = async () => {
7531 const e = this._logger.create("_tokenExpiring");
7532 try {
7533 await this._userManager.signinSilent(), e.debug("silent token renewal successful");
7534 } catch (t) {
7535 if (t instanceof W) return e.warn("ErrorTimeout from signinSilent:", t, "retry in 5s"), void this._retryTimer.init(5);
7536 e.error("Error from signinSilent:", t), await this._userManager.events._raiseSilentRenewError(t);
7537 }
7538 };
7539 }
7540 async start() {
7541 const e = this._logger.create("start");
7542 if (!this._isStarted) {
7543 this._isStarted = !0, this._userManager.events.addAccessTokenExpiring(this._tokenExpiring), this._retryTimer.addHandler(this._tokenExpiring);
7544 try {
7545 await this._userManager.getUser();
7546 } catch (t) {
7547 e.error("getUser error", t);
7548 }
7549 }
7550 }
7551 stop() {
7552 this._isStarted && (this._retryTimer.cancel(), this._retryTimer.removeHandler(this._tokenExpiring), this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring), this._isStarted = !1);
7553 }
7554 };
7555 var Pe = class {
7556 constructor(e) {
7557 this.refresh_token = e.refresh_token, this.id_token = e.id_token, this.session_state = e.session_state, this.scope = e.scope, this.profile = e.profile, this.data = e.state;
7558 }
7559 };
7560 var Oe = class {
7561 constructor(e, t, i, n) {
7562 this._logger = new L("UserManager"), this.settings = new Ie(e), this._client = new pe(e), this._redirectNavigator = null != t ? t : new Ae(this.settings), this._popupNavigator = null != i ? i : new Re(this.settings), this._iframeNavigator = null != n ? n : new ke(this.settings), this._events = new Ce(this.settings), this._silentRenewService = new xe(this), this.settings.automaticSilentRenew && this.startSilentRenew(), this._sessionMonitor = null, this.settings.monitorSession && (this._sessionMonitor = new _e(this));
7563 }
7564 get events() {
7565 return this._events;
7566 }
7567 get metadataService() {
7568 return this._client.metadataService;
7569 }
7570 async getUser(e = !1) {
7571 const t = this._logger.create("getUser");
7572 const i = await this._loadUser();
7573 return i ? (t.info("user loaded"), await this._events.load(i, e), i) : (t.info("user not found in storage"), null);
7574 }
7575 async removeUser() {
7576 const e = this._logger.create("removeUser");
7577 await this.storeUser(null), e.info("user removed from storage"), await this._events.unload();
7578 }
7579 async signinRedirect(e = {}) {
7580 var t;
7581 this._logger.create("signinRedirect");
7582 const { redirectMethod: i, ...n } = e;
7583 let s;
7584 null != (t = this.settings.dpop) && t.bind_authorization_code && (s = await this.generateDPoPJkt(this.settings.dpop));
7585 const r = await this._redirectNavigator.prepare({ redirectMethod: i });
7586 await this._signinStart({
7587 request_type: "si:r",
7588 dpopJkt: s,
7589 ...n
7590 }, r);
7591 }
7592 async signinRedirectCallback(e = window.location.href) {
7593 const t = this._logger.create("signinRedirectCallback");
7594 const i = await this._signinEnd(e);
7595 return i.profile && i.profile.sub ? t.info("success, signed in subject", i.profile.sub) : t.info("no subject"), i;
7596 }
7597 async signinResourceOwnerCredentials({ username: e, password: t, skipUserInfo: i = !1 }) {
7598 const n = this._logger.create("signinResourceOwnerCredential");
7599 const s = await this._client.processResourceOwnerPasswordCredentials({
7600 username: e,
7601 password: t,
7602 skipUserInfo: i,
7603 extraTokenParams: this.settings.extraTokenParams
7604 });
7605 n.debug("got signin response");
7606 const r = await this._buildUser(s);
7607 return r.profile && r.profile.sub ? n.info("success, signed in subject", r.profile.sub) : n.info("no subject"), r;
7608 }
7609 async signinPopup(e = {}) {
7610 var t;
7611 const i = this._logger.create("signinPopup");
7612 let n;
7613 null != (t = this.settings.dpop) && t.bind_authorization_code && (n = await this.generateDPoPJkt(this.settings.dpop));
7614 const { popupWindowFeatures: s, popupWindowTarget: r, popupSignal: o, popupAbortOnClose: a, ...c } = e, d = this.settings.popup_redirect_uri;
7615 d || i.throw(/* @__PURE__ */ new Error("No popup_redirect_uri configured"));
7616 const l = await this._popupNavigator.prepare({
7617 popupWindowFeatures: s,
7618 popupWindowTarget: r,
7619 popupSignal: o,
7620 popupAbortOnClose: a
7621 });
7622 const g = await this._signin({
7623 request_type: "si:p",
7624 redirect_uri: d,
7625 display: "popup",
7626 dpopJkt: n,
7627 ...c
7628 }, l);
7629 return g && (g.profile && g.profile.sub ? i.info("success, signed in subject", g.profile.sub) : i.info("no subject")), g;
7630 }
7631 async signinPopupCallback(e = window.location.href, t = !1) {
7632 const i = this._logger.create("signinPopupCallback");
7633 await this._popupNavigator.callback(e, { keepOpen: t }), i.info("success");
7634 }
7635 async signinSilent(e = {}) {
7636 var t;
7637 var i;
7638 const n = this._logger.create("signinSilent"), { silentRequestTimeoutInSeconds: s, ...r } = e;
7639 let o;
7640 let a = await this._loadUser();
7641 if (!e.forceIframeAuth && (null == a ? void 0 : a.refresh_token)) {
7642 n.debug("using refresh token");
7643 const e = new Pe(a);
7644 return await this._useRefreshToken({
7645 state: e,
7646 redirect_uri: r.redirect_uri,
7647 resource: r.resource,
7648 extraTokenParams: r.extraTokenParams,
7649 timeoutInSeconds: s
7650 });
7651 }
7652 null != (t = this.settings.dpop) && t.bind_authorization_code && (o = await this.generateDPoPJkt(this.settings.dpop));
7653 const c = this.settings.silent_redirect_uri;
7654 let d;
7655 c || n.throw(/* @__PURE__ */ new Error("No silent_redirect_uri configured")), a && this.settings.validateSubOnSilentRenew && (n.debug("subject prior to silent renew:", a.profile.sub), d = a.profile.sub);
7656 const l = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds: s });
7657 return a = await this._signin({
7658 request_type: "si:s",
7659 redirect_uri: c,
7660 prompt: "none",
7661 id_token_hint: this.settings.includeIdTokenInSilentRenew ? null == a ? void 0 : a.id_token : void 0,
7662 dpopJkt: o,
7663 ...r
7664 }, l, d), a && ((null == (i = a.profile) ? void 0 : i.sub) ? n.info("success, signed in subject", a.profile.sub) : n.info("no subject")), a;
7665 }
7666 async _useRefreshToken(e) {
7667 const t = await this._client.useRefreshToken({
7668 timeoutInSeconds: this.settings.silentRequestTimeoutInSeconds,
7669 ...e
7670 });
7671 const i = new we({
7672 ...e.state,
7673 ...t
7674 });
7675 return await this.storeUser(i), await this._events.load(i), i;
7676 }
7677 async signinSilentCallback(e = window.location.href) {
7678 const t = this._logger.create("signinSilentCallback");
7679 await this._iframeNavigator.callback(e), t.info("success");
7680 }
7681 async signinCallback(e = window.location.href) {
7682 const { state: t } = await this._client.readSigninResponseState(e);
7683 switch (t.request_type) {
7684 case "si:r": return await this.signinRedirectCallback(e);
7685 case "si:p":
7686 await this.signinPopupCallback(e);
7687 break;
7688 case "si:s":
7689 await this.signinSilentCallback(e);
7690 break;
7691 default: throw new Error("invalid response_type in state");
7692 }
7693 }
7694 async signoutCallback(e = window.location.href, t = !1) {
7695 const { state: i } = await this._client.readSignoutResponseState(e);
7696 if (i) switch (i.request_type) {
7697 case "so:r": return await this.signoutRedirectCallback(e);
7698 case "so:p":
7699 await this.signoutPopupCallback(e, t);
7700 break;
7701 case "so:s":
7702 await this.signoutSilentCallback(e);
7703 break;
7704 default: throw new Error("invalid response_type in state");
7705 }
7706 }
7707 async querySessionStatus(e = {}) {
7708 const t = this._logger.create("querySessionStatus"), { silentRequestTimeoutInSeconds: i, ...n } = e, s = this.settings.silent_redirect_uri;
7709 s || t.throw(/* @__PURE__ */ new Error("No silent_redirect_uri configured"));
7710 const r = await this._loadUser();
7711 const o = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds: i });
7712 const a = await this._signinStart({
7713 request_type: "si:s",
7714 redirect_uri: s,
7715 prompt: "none",
7716 id_token_hint: this.settings.includeIdTokenInSilentRenew ? null == r ? void 0 : r.id_token : void 0,
7717 response_type: this.settings.query_status_response_type,
7718 scope: "openid",
7719 skipUserInfo: !0,
7720 ...n
7721 }, o);
7722 try {
7723 const i = await this._client.processSigninResponse(a.url, {});
7724 return t.debug("got signin response"), i.session_state && i.profile.sub ? (t.info("success for subject", i.profile.sub), {
7725 session_state: i.session_state,
7726 sub: i.profile.sub
7727 }) : (t.info("success, user not authenticated"), null);
7728 } catch (e) {
7729 if (this.settings.monitorAnonymousSession && e instanceof B) switch (e.error) {
7730 case "login_required":
7731 case "consent_required":
7732 case "interaction_required":
7733 case "account_selection_required": return t.info("success for anonymous user"), { session_state: e.session_state };
7734 }
7735 throw e;
7736 }
7737 }
7738 async _signin(e, t, i) {
7739 const n = await this._signinStart(e, t);
7740 return await this._signinEnd(n.url, i);
7741 }
7742 async _signinStart(e, t) {
7743 const i = this._logger.create("_signinStart");
7744 try {
7745 const n = await this._client.createSigninRequest(e);
7746 return i.debug("got signin request"), await t.navigate({
7747 url: n.url,
7748 state: n.state.id,
7749 response_mode: n.state.response_mode,
7750 scriptOrigin: this.settings.iframeScriptOrigin
7751 });
7752 } catch (e) {
7753 throw i.debug("error after preparing navigator, closing navigator window"), t.close(), e;
7754 }
7755 }
7756 async _signinEnd(e, t) {
7757 const i = this._logger.create("_signinEnd");
7758 const n = await this._client.processSigninResponse(e, {});
7759 return i.debug("got signin response"), await this._buildUser(n, t);
7760 }
7761 async _buildUser(e, t) {
7762 const i = this._logger.create("_buildUser");
7763 const n = new we(e);
7764 if (t) {
7765 if (t !== n.profile.sub) throw i.debug("current user does not match user returned from signin. sub from signin:", n.profile.sub), new B({
7766 ...e,
7767 error: "login_required"
7768 });
7769 i.debug("current user matches user returned from signin");
7770 }
7771 return await this.storeUser(n), i.debug("user stored"), await this._events.load(n), n;
7772 }
7773 async signoutRedirect(e = {}) {
7774 const t = this._logger.create("signoutRedirect"), { redirectMethod: i, ...n } = e, s = await this._redirectNavigator.prepare({ redirectMethod: i });
7775 await this._signoutStart({
7776 request_type: "so:r",
7777 post_logout_redirect_uri: this.settings.post_logout_redirect_uri,
7778 ...n
7779 }, s), t.info("success");
7780 }
7781 async signoutRedirectCallback(e = window.location.href) {
7782 const t = this._logger.create("signoutRedirectCallback");
7783 const i = await this._signoutEnd(e);
7784 return t.info("success"), i;
7785 }
7786 async signoutPopup(e = {}) {
7787 const t = this._logger.create("signoutPopup"), { popupWindowFeatures: i, popupWindowTarget: n, popupSignal: s, ...r } = e, o = this.settings.popup_post_logout_redirect_uri, a = await this._popupNavigator.prepare({
7788 popupWindowFeatures: i,
7789 popupWindowTarget: n,
7790 popupSignal: s
7791 });
7792 await this._signout({
7793 request_type: "so:p",
7794 post_logout_redirect_uri: o,
7795 state: null == o ? void 0 : {},
7796 ...r
7797 }, a), t.info("success");
7798 }
7799 async signoutPopupCallback(e = window.location.href, t = !1) {
7800 const i = this._logger.create("signoutPopupCallback");
7801 await this._popupNavigator.callback(e, { keepOpen: t }), i.info("success");
7802 }
7803 async _signout(e, t) {
7804 const i = await this._signoutStart(e, t);
7805 return await this._signoutEnd(i.url);
7806 }
7807 async _signoutStart(e = {}, t) {
7808 var i;
7809 const n = this._logger.create("_signoutStart");
7810 try {
7811 const s = await this._loadUser();
7812 n.debug("loaded current user from storage"), this.settings.revokeTokensOnSignout && await this._revokeInternal(s);
7813 const r = e.id_token_hint || s && s.id_token;
7814 r && (n.debug("setting id_token_hint in signout request"), e.id_token_hint = r), await this.removeUser(), n.debug("user removed, creating signout request");
7815 const o = await this._client.createSignoutRequest(e);
7816 return n.debug("got signout request"), await t.navigate({
7817 url: o.url,
7818 state: null == (i = o.state) ? void 0 : i.id,
7819 scriptOrigin: this.settings.iframeScriptOrigin
7820 });
7821 } catch (e) {
7822 throw n.debug("error after preparing navigator, closing navigator window"), t.close(), e;
7823 }
7824 }
7825 async _signoutEnd(e) {
7826 const t = this._logger.create("_signoutEnd");
7827 const i = await this._client.processSignoutResponse(e);
7828 return t.debug("got signout response"), i;
7829 }
7830 async signoutSilent(e = {}) {
7831 var t;
7832 const i = this._logger.create("signoutSilent"), { silentRequestTimeoutInSeconds: n, ...s } = e, r = this.settings.includeIdTokenInSilentSignout ? null == (t = await this._loadUser()) ? void 0 : t.id_token : void 0, o = this.settings.popup_post_logout_redirect_uri, a = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds: n });
7833 await this._signout({
7834 request_type: "so:s",
7835 post_logout_redirect_uri: o,
7836 id_token_hint: r,
7837 ...s
7838 }, a), i.info("success");
7839 }
7840 async signoutSilentCallback(e = window.location.href) {
7841 const t = this._logger.create("signoutSilentCallback");
7842 await this._iframeNavigator.callback(e), t.info("success");
7843 }
7844 async revokeTokens(e) {
7845 const t = await this._loadUser();
7846 await this._revokeInternal(t, e);
7847 }
7848 async _revokeInternal(e, t = this.settings.revokeTokenTypes) {
7849 const i = this._logger.create("_revokeInternal");
7850 if (!e) return;
7851 const n = t.filter((t) => "string" == typeof e[t]);
7852 if (n.length) {
7853 for (const t of n) await this._client.revokeToken(e[t], t), i.info(`${t} revoked successfully`), "access_token" !== t && (e[t] = null);
7854 await this.storeUser(e), i.debug("user stored"), await this._events.load(e);
7855 } else i.debug("no need to revoke due to no token(s)");
7856 }
7857 startSilentRenew() {
7858 this._logger.create("startSilentRenew"), this._silentRenewService.start();
7859 }
7860 stopSilentRenew() {
7861 this._silentRenewService.stop();
7862 }
7863 get _userStoreKey() {
7864 return `user:${this.settings.authority}:${this.settings.client_id}`;
7865 }
7866 async _loadUser() {
7867 const e = this._logger.create("_loadUser");
7868 const t = await this.settings.userStore.get(this._userStoreKey);
7869 return t ? (e.debug("user storageString loaded"), we.fromStorageString(t)) : (e.debug("no user storageString"), null);
7870 }
7871 async storeUser(e) {
7872 const t = this._logger.create("storeUser");
7873 if (e) {
7874 t.debug("storing user");
7875 const i = e.toStorageString();
7876 await this.settings.userStore.set(this._userStoreKey, i);
7877 } else this._logger.debug("removing user"), await this.settings.userStore.remove(this._userStoreKey), this.settings.dpop && await this.settings.dpop.store.remove(this.settings.client_id);
7878 }
7879 async clearStaleState() {
7880 await this._client.clearStaleState();
7881 }
7882 async dpopProof(e, t, i, n) {
7883 var s;
7884 var r;
7885 const o = await (null == (r = null == (s = this.settings.dpop) ? void 0 : s.store) ? void 0 : r.get(this.settings.client_id));
7886 if (o) return await $.generateDPoPProof({
7887 url: e,
7888 accessToken: null == t ? void 0 : t.access_token,
7889 httpMethod: i,
7890 keyPair: o.keys,
7891 nonce: n
7892 });
7893 }
7894 async generateDPoPJkt(e) {
7895 let t = await e.store.get(this.settings.client_id);
7896 if (!t) t = new he(await $.generateDPoPKeys()), await e.store.set(this.settings.client_id, t);
7897 return await $.generateDPoPJkt(t.keys);
7898 }
7899 };
7900 var Ue = "OAUTH2_LOGIN_FLOW_COMPLETE_EVENT";
7901 var Le = "OAUTH_GET_TOP_URL";
7902 var De = "OAUTH_REDIRECT_TOP_WINDOW";
7903 var Ne = "OAUTH_UPDATE_URL";
7904 var qe = "OAUTH2_CHECK_PENDING";
7905 var $e = "oauth2_top_origin";
7906 var Me = "oauth2_login_success";
7907 var He = "oauth2_state";
7908 var je = 60;
7909 var Ge = Math.max(je - 15, 20);
7910 var ze = d("oidc-auth", { color: "green" });
7911 var Be = (e) => ze.extend(e);
7912 d("oidc-auth-utils");
7913 var We = () => "undefined" == typeof window ? "" : new URLSearchParams(window.location.search).get("origin") || "";
7914 var Fe = class Fe {
7915 static instance = null;
7916 settings = null;
7917 constructor() {}
7918 static getInstance() {
7919 return Fe.instance || (Fe.instance = new Fe()), Fe.instance;
7920 }
7921 configure(e) {
7922 this.settings = e;
7923 }
7924 isConfigured() {
7925 return null !== this.settings;
7926 }
7927 getSettings() {
7928 if (!this.settings) throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");
7929 return this.settings;
7930 }
7931 getAuthOrigin() {
7932 const { authOrigin: e, authEndpoint: t } = this.getSettings();
7933 return e || new URL(t).origin;
7934 }
7935 isAccessTokenProactiveRefreshEnabled() {
7936 return this.settings?.accessTokenProactiveRefreshEnabled ?? !0;
7937 }
7938 getOidcSettings() {
7939 const e = "undefined" == typeof window ? "" : window.location.origin, { clientId: t, authEndpoint: i } = this.getSettings(), n = this.getAuthOrigin(), s = "undefined" != typeof window ? new Y({ store: window.localStorage }) : void 0, { accessTokenExpiringNotificationTimeInSeconds: r = je } = this.getSettings();
7940 return {
7941 client_id: t,
7942 authority: n,
7943 redirect_uri: `${e}/login/oauth-callback`,
7944 post_logout_redirect_uri: e,
7945 response_type: "code",
7946 scope: "openid offline_access",
7947 automaticSilentRenew: !1,
7948 accessTokenExpiringNotificationTimeInSeconds: r,
7949 stateStore: s,
7950 userStore: s,
7951 metadata: {
7952 issuer: n,
7953 authorization_endpoint: i,
7954 token_endpoint: `${n}/connect/api/v1/oauth2/token`,
7955 end_session_endpoint: `${n}/logout/`
7956 }
7957 };
7958 }
7959 getAccessTokenExpiringNotificationTimeInSeconds() {
7960 return this.getSettings().accessTokenExpiringNotificationTimeInSeconds ?? je;
7961 }
7962 getAccessTokenFreshnessThresholdInSeconds() {
7963 return this.getSettings().accessTokenFreshnessThresholdInSeconds ?? Ge;
7964 }
7965 getAllowedParentOrigins() {
7966 return this.settings?.allowedParentOrigins;
7967 }
7968 };
7969 var Ke = Fe.getInstance();
7970 var Je = Be("oidc-auth:host-api");
7971 var Ve = async (e) => new Promise((t, i) => {
7972 const n = new MessageChannel();
7973 let s = !1;
7974 const r = () => {
7975 s = !0, n.port1.close();
7976 };
7977 const o = setTimeout(() => {
7978 s || (r(), i(/* @__PURE__ */ new Error(`Host message timeout: ${e.type}`)));
7979 }, 1e4);
7980 n.port1.onmessage = (e) => {
7981 clearTimeout(o), r(), "success" !== e.data.status ? i(e.data.payload) : t(e.data.payload);
7982 };
7983 const a = new URLSearchParams(window.location.search).get("origin") || "";
7984 if (!function(e) {
7985 if (!e.startsWith("http://") && !e.startsWith("https://")) return !1;
7986 const t = Ke.getAllowedParentOrigins();
7987 return !t || 0 === t.length || t.includes(e);
7988 }(a)) return clearTimeout(o), r(), void i(/* @__PURE__ */ new Error("Origin not allowed"));
7989 Je.log("posting message to host", e), window.top.postMessage({
7990 type: e.type,
7991 payload: e.payload,
7992 ...e.data || {}
7993 }, a, [n.port2]);
7994 });
7995 var Qe = Be("oidc-auth:OidcAuthTimer");
7996 var Xe = class {
7997 timerHandle = null;
7998 expiration = null;
7999 initialized = !1;
8000 callback = () => {};
8001 constructor() {
8002 this.timerHandle = null;
8003 }
8004 init(e, t, i) {
8005 const n = e - this.getEpochTime();
8006 const s = Math.max(n - t, 10);
8007 this.cancel(), this.expiration = s, this.callback = i, Qe.debug("OIDC: timer - using expiration", s, n, t, e, n - t), this.timerHandle = setTimeout(this.callback, 1e3 * s), this.initialized = !0;
8008 }
8009 cancel() {
8010 this.timerHandle && (clearTimeout(this.timerHandle), this.timerHandle = null), this.expiration = null;
8011 }
8012 getEpochTime() {
8013 return Math.floor(Date.now() / 1e3);
8014 }
8015 isInitialized() {
8016 return this.initialized;
8017 }
8018 };
8019 var Ye = Be("oidc-auth:OidcAuthClient");
8020 var Ze = class Ze {
8021 static instance = null;
8022 userManager = null;
8023 initialized = !1;
8024 accessTokenExpiringTimer = null;
8025 retryTimers = /* @__PURE__ */ new Set();
8026 constructor() {}
8027 static getInstance() {
8028 return Ze.instance || (Ze.instance = new Ze()), Ze.instance;
8029 }
8030 isInitialized() {
8031 return this.initialized;
8032 }
8033 ensureInitialized() {
8034 if (!this.userManager) throw new Error("OidcAuthClient not initialized. Call initialize() first.");
8035 return this.userManager;
8036 }
8037 initialize(e) {
8038 if (e && (this.initialized = !1, Ke.configure(e)), this.initialized) Ye.info("OIDC: initialize() - already initialized, skipping");
8039 else if ("undefined" != typeof window) if (Ke.isConfigured()) try {
8040 Ye.info("OIDC: initialize() - starting initialization");
8041 const e = Ke.getOidcSettings();
8042 this.userManager = new Oe(e), U.setLogger(Ye), U.setLevel(U.ERROR), this.initAccessTokenExpiringTimer(), this.initialized = !0;
8043 } catch (e) {
8044 throw Ye.error("OIDC: initialize() - FAILED:", e), e;
8045 }
8046 else Ye.warn("OIDC: initialize() - skipped, config not set");
8047 else Ye.warn("OidcAuthClient cannot initialize on server side");
8048 }
8049 async initAccessTokenExpiringTimer() {
8050 Ke.isAccessTokenProactiveRefreshEnabled() ? this.getUser().then((e) => {
8051 const t = e?.expires_at;
8052 t && (this.accessTokenExpiringTimer || (this.accessTokenExpiringTimer = new Xe()), this.accessTokenExpiringTimer.init(t, Ke.getAccessTokenExpiringNotificationTimeInSeconds(), async () => {
8053 Ye.info("OIDC: timer proactive refresh access token expiring timer fired", t), this.proactiveRefreshWithRetry();
8054 }));
8055 }).catch((e) => {
8056 Ye.error("OIDC: initAccessTokenExpiringTimer - FAILED:", e);
8057 }) : Ye.warn("OIDC: timer - not starting, access token proactive refresh is disabled");
8058 }
8059 async getUser() {
8060 if (!this.userManager) return null;
8061 try {
8062 return await this.userManager.getUser();
8063 } catch (e) {
8064 return Ye.error("OIDC: getUser - FAILED:", e), null;
8065 }
8066 }
8067 async storeUser(e) {
8068 await this.ensureInitialized().storeUser(e);
8069 }
8070 async getAccessToken() {
8071 const e = await this.getUser();
8072 if (!e) return Ye.info("OIDC: getAccessToken - no user found"), null;
8073 if (e.expired) try {
8074 return (await this.signinSilent())?.access_token || null;
8075 } catch (e) {
8076 return Ye.error("OIDC: getAccessToken - silent renew failed:", e), null;
8077 }
8078 return this.isTokenFresh(e) || this.signinSilent().catch((e) => {
8079 Ye.error("OIDC: getAccessToken - background refresh failed:", e);
8080 }), e.access_token;
8081 }
8082 getUserData() {
8083 if ("undefined" == typeof window) return null;
8084 try {
8085 const e = Ke.getOidcSettings();
8086 const t = `oidc.user:${e.authority}:${e.client_id}`;
8087 const i = localStorage.getItem(t);
8088 if (!i) return null;
8089 const s = JSON.parse(i)?.profile;
8090 return s?.sub ? (Ye.info("OIDC: USER:", { profile: s }), {
8091 id: s.sub,
8092 email: s.email || "",
8093 first_name: s.given_name,
8094 last_name: s.family_name
8095 }) : null;
8096 } catch (e) {
8097 return Ye.error("OIDC: getUserData - FAILED:", e), null;
8098 }
8099 }
8100 async isAuthenticated() {
8101 const e = await this.getUser();
8102 return null !== e && !e.expired;
8103 }
8104 async signinRedirect(e) {
8105 await this.ensureInitialized().signinRedirect({
8106 state: e ? { data: e } : void 0,
8107 prompt: "login"
8108 });
8109 }
8110 async signinCallback() {
8111 const t = await this.ensureInitialized().signinCallback();
8112 if (!t) throw Ye.error("OIDC: signinCallback - FAILED: no user returned"), /* @__PURE__ */ new Error("Signin callback failed: no user returned");
8113 return t;
8114 }
8115 async signinSilent(e) {
8116 return this.ensureInitialized(), "undefined" != typeof navigator && navigator.locks ? navigator.locks.request("oidc-token-refresh", async () => {
8117 const t = await this.getUser();
8118 return t && this.isTokenFresh(t, e) ? t : this.doSigninSilent();
8119 }) : (Ye.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"), this.doSigninSilent());
8120 }
8121 isTokenFresh(e, t) {
8122 if (!e.expires_at) return !1;
8123 const i = t ?? Ke.getAccessTokenFreshnessThresholdInSeconds();
8124 const n = Math.floor(Date.now() / 1e3);
8125 return e.expires_at - n > i;
8126 }
8127 async doSigninSilent() {
8128 const e = this.ensureInitialized();
8129 try {
8130 return await e.signinSilent();
8131 } catch (e) {
8132 throw Ye.error("OIDC: doSigninSilent - FAILED:", e), e;
8133 }
8134 }
8135 proactiveRefreshWithRetry(e = 1) {
8136 if ("undefined" != typeof document && "hidden" === document.visibilityState) {
8137 Ye.info("OIDC: tab is hidden, deferring proactive refresh until visible");
8138 const t = () => {
8139 "visible" === document.visibilityState && (document.removeEventListener("visibilitychange", t), this.proactiveRefreshWithRetry(e));
8140 };
8141 document.addEventListener("visibilitychange", t);
8142 return;
8143 }
8144 this.signinSilent(Ke.getAccessTokenExpiringNotificationTimeInSeconds()).then(() => {
8145 this.initAccessTokenExpiringTimer();
8146 }).catch((t) => {
8147 if (Ye.error(`OIDC: proactive refresh failed (attempt ${e}/2):`, t), e < 2) {
8148 const t = setTimeout(() => {
8149 this.retryTimers.delete(t), this.proactiveRefreshWithRetry(e + 1);
8150 }, 3e3);
8151 this.retryTimers.add(t);
8152 } else Ye.error("OIDC: proactive refresh exhausted all retries");
8153 });
8154 }
8155 async removeUser() {
8156 const e = this.ensureInitialized();
8157 this.accessTokenExpiringTimer?.cancel(), this.retryTimers.forEach(clearTimeout), this.retryTimers.clear(), await e.removeUser();
8158 }
8159 onUserLoaded(e) {
8160 this.ensureInitialized().events.addUserLoaded(e);
8161 }
8162 offUserLoaded(e) {
8163 this.ensureInitialized().events.removeUserLoaded(e);
8164 }
8165 onUserUnloaded(e) {
8166 this.ensureInitialized().events.addUserUnloaded(e);
8167 }
8168 offUserUnloaded(e) {
8169 this.ensureInitialized().events.removeUserUnloaded(e);
8170 }
8171 onSilentRenewError(e) {
8172 this.ensureInitialized().events.addSilentRenewError(e);
8173 }
8174 offSilentRenewError(e) {
8175 this.ensureInitialized().events.removeSilentRenewError(e);
8176 }
8177 onAccessTokenExpiring(e) {
8178 this.ensureInitialized().events.addAccessTokenExpiring(e);
8179 }
8180 offAccessTokenExpiring(e) {
8181 this.ensureInitialized().events.removeAccessTokenExpiring(e);
8182 }
8183 onAccessTokenExpired(e) {
8184 this.ensureInitialized().events.addAccessTokenExpired(e);
8185 }
8186 offAccessTokenExpired(e) {
8187 this.ensureInitialized().events.removeAccessTokenExpired(e);
8188 }
8189 getLogoutUrl(e, t) {
8190 const i = new URL(function(e) {
8191 return `${Ke.getAuthOrigin()}${e.logoutPath}`;
8192 }(e));
8193 return t && i.searchParams.set("redirect_to", t), i.toString();
8194 }
8195 getWindowOriginParam() {
8196 const e = new URL(window.location.href).searchParams.get("origin");
8197 if (!e) throw new Error("iframe origin param is required");
8198 return e;
8199 }
8200 async getTopUrl() {
8201 return (await Ve({ type: Le })).topUrl;
8202 }
8203 async isOAuthFlowPending() {
8204 try {
8205 return (await Ve({ type: qe })).isPending;
8206 } catch (e) {
8207 return Ye.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:", e), !1;
8208 }
8209 }
8210 async triggerLoginFlowViaParent({ loginPath: e, windowPath: t }) {
8211 Ye.info("OIDC: triggerLoginFlowViaParent() - starting");
8212 const i = await this.getTopUrl();
8213 const n = new URL(i).origin;
8214 const s = `${n}${t}`;
8215 const r = new URL(`${window.location.origin}${e}`);
8216 r.searchParams.set($e, n), r.searchParams.set("oauth2_top_wp_url", s), Ye.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:", r.toString()), await Ve({
8217 type: De,
8218 payload: { url: r.toString() }
8219 });
8220 }
8221 async handleLoginFlowComplete(e, t) {
8222 if (!t) throw new Error("oauthUserState is required");
8223 const i = this.getWindowOriginParam();
8224 const s = t.state?.data?.[$e];
8225 if (i !== s) throw Ye.error("OIDC: handleLoginFlowComplete - origin mismatch:", i, "!==", s), /* @__PURE__ */ new Error("Invalid origin in OAuth state");
8226 try {
8227 const e = new we(t);
8228 await this.storeUser(e), this.initAccessTokenExpiringTimer(), window.dispatchEvent(new CustomEvent("oidc-auth-completed"));
8229 } catch (t) {
8230 Ye.error("OIDC: handleLoginFlowComplete - FAILED to store user:", t), await this.triggerLoginFlowViaParent(e);
8231 }
8232 }
8233 async triggerLogoutViaParent(e, t = !0) {
8234 const i = await this.getTopUrl();
8235 const n = new URL(i).origin;
8236 const s = t ? `${n}${e.windowPath}` : n;
8237 await this.removeUser();
8238 const r = this.getLogoutUrl(e, s);
8239 await Ve({
8240 type: De,
8241 payload: { url: r }
8242 });
8243 }
8244 async cleanOAuthParamsFromUrl() {
8245 try {
8246 const e = await this.getTopUrl();
8247 const t = new URL(e);
8248 t.searchParams.delete("oauth_code"), t.searchParams.delete("oauth_state"), t.searchParams.delete("start-oauth"), t.searchParams.delete(Me), t.searchParams.delete(He), await Ve({
8249 type: Ne,
8250 payload: { url: t.toString() }
8251 });
8252 } catch (e) {
8253 Ye.warn("Failed to clean OAuth params from URL:", e);
8254 }
8255 }
8256 setupLoginFlowMessageListener(e) {
8257 let t = !1;
8258 const i = (i) => {
8259 if (i.data?.type !== Ue) return;
8260 if (i.origin !== We()) return void Ye.error("OIDC: origin mismatch - expected:", We(), "received:", i.origin);
8261 if (t) return void Ye.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");
8262 const n = i.data.payload;
8263 n?.oauthState ? (t = !0, this.handleLoginFlowComplete(e, n.oauthState).catch((e) => {
8264 Ye.error("OIDC: Failed to handle login flow complete:", e), t = !1;
8265 })) : Ye.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload");
8266 };
8267 return window.addEventListener("message", i), () => {
8268 window.removeEventListener("message", i);
8269 };
8270 }
8271 async getTokenExpirationInfo() {
8272 const e = await this.getUser();
8273 if (!e || !e.expires_at) return {
8274 expiresAt: null,
8275 expiresInSeconds: null,
8276 isExpired: !0
8277 };
8278 const t = /* @__PURE__ */ new Date(1e3 * e.expires_at);
8279 const i = Date.now();
8280 const n = Math.floor((1e3 * e.expires_at - i) / 1e3);
8281 return {
8282 expiresAt: t,
8283 expiresInSeconds: n,
8284 isExpired: n <= 0
8285 };
8286 }
8287 async forceTokenRefresh() {
8288 return Ye.info("OIDC: forceTokenRefresh() - manually triggering token refresh"), this.signinSilent();
8289 }
8290 };
8291 var et = Ze.getInstance();
8292 "undefined" != typeof window && (window.oidcAuthClient = et);
8293 var tt = Be("oidc-auth:oidc-auth-redirect");
8294 function it(e, t) {
8295 e.postMessage({
8296 status: "success",
8297 payload: t
8298 });
8299 }
8300 function nt(e, t) {
8301 e.postMessage({
8302 status: "error",
8303 payload: t
8304 });
8305 }
8306 function st({ targets: e, onSuccess: t, attempt: i = 1 }) {
8307 const n = new URLSearchParams(window.location.search);
8308 if (!n.get(Me)) return void tt.warn("OIDC: No login_success param found, skipping");
8309 const s = n.get(He);
8310 if (s) {
8311 if (!e.window?.contentWindow || !e.windowURL) return tt.warn("Cannot forward OIDC state: iframe not available"), void (i < 5 ? setTimeout(() => {
8312 st({
8313 targets: e,
8314 onSuccess: t,
8315 attempt: i + 1
8316 });
8317 }, 500) : tt.error("OIDC: Failed to forward login flow after", 5, "attempts - iframe never became available"));
8318 try {
8319 const i = JSON.parse(s);
8320 const n = i.state?.data?.[$e];
8321 if (n && n !== window.location.origin) return void tt.error("Origin mismatch in OIDC state:", n, "vs", window.location.origin);
8322 (function(e, t) {
8323 const i = t.window?.contentWindow;
8324 const n = t.windowURL?.origin;
8325 i && n ? i.postMessage({
8326 type: Ue,
8327 payload: e
8328 }, n) : tt.warn("Cannot send OIDC state: window or origin not available");
8329 })({ oauthState: i }, e);
8330 const r = new URL(window.location.href);
8331 r.searchParams.delete(Me), r.searchParams.delete(He), history.replaceState({}, "", r.toString()), t?.();
8332 } catch (e) {
8333 tt.error("Failed to parse or forward OIDC state:", e);
8334 }
8335 } else tt.warn("OIDC login complete but no state found in URL");
8336 }
8337 var rt = g("iframe-utils");
8338 var ot = null;
8339 var at = (e) => !!e && document.contains(e);
8340 var ct = (e) => {
8341 try {
8342 return new URL(e.src).origin;
8343 } catch (e) {
8344 return rt.error("Error parsing iframe URL:", e), null;
8345 }
8346 };
8347 var dt = (e, t, i) => !!e?.contentWindow && (t ? (e.contentWindow.postMessage(i, t), !0) : (rt.error("Could not determine target origin for Angie iframe"), !1));
8348 var lt = (e) => at(e.iframe) ? e.iframe : null;
8349 var gt = (e, t) => dt(lt(e), ((e) => {
8350 if (e.iframeUrlObject) return e.iframeUrlObject.origin;
8351 const t = lt(e);
8352 return t ? ct(t) : null;
8353 })(e), t);
8354 var ut = () => lt(R) || (at(ot) || (ot = document.querySelector("iframe[src*=\"angie/\"]")), ot);
8355 var ht = (e, t) => (rt.log("postMessageToAngieIframe", e, t), dt(ut(), t || (() => {
8356 const e = ut();
8357 return e ? ct(e) : null;
8358 })(), e));
8359 var pt = (e, t, i) => {
8360 const n = document.getElementById(i ?? R.containerId);
8361 n && n.setAttribute("aria-hidden", t ? "false" : "true"), t ? e.removeAttribute("tabindex") : e.setAttribute("tabindex", "-1");
8362 };
8363 var _t = (e, t) => {
8364 const i = t?.contentWindow;
8365 return !i || !e.source || e.source === i;
8366 };
8367 var wt = (e, t, i) => e.origin === t && _t(e, i);
8368 var mt = () => Math.random().toString(36).substring(2, 8);
8369 var ft = (e, t) => {
8370 e.postMessage({
8371 status: "success",
8372 payload: t
8373 });
8374 };
8375 var St = g("sidebar");
8376 var bt = !1;
8377 var vt = "open";
8378 var It = "closed";
8379 var Et = "angie_sidebar_state";
8380 var kt = "angie_sidebar_width";
8381 function Tt() {
8382 if ("undefined" == typeof window) return 370;
8383 try {
8384 const e = window.localStorage.getItem(kt);
8385 if (e) {
8386 const t = parseInt(e, 10);
8387 if (t >= 350 && t <= 590) return t;
8388 }
8389 } catch (e) {
8390 St.warn("localStorage not available");
8391 }
8392 return 370;
8393 }
8394 function Rt() {
8395 return "undefined" == typeof window ? null : localStorage.getItem(Et);
8396 }
8397 function At(e) {
8398 try {
8399 localStorage.setItem(Et, e);
8400 } catch (e) {
8401 St.warn("localStorage not available");
8402 }
8403 }
8404 function Ct(e) {
8405 try {
8406 localStorage.setItem(kt, e.toString());
8407 } catch (e) {
8408 St.warn("localStorage not available");
8409 }
8410 }
8411 function xt(e) {
8412 document.documentElement.style.setProperty("--angie-sidebar-width", `${e}px`);
8413 }
8414 function Pt(e = vt) {
8415 !function() {
8416 if ("undefined" == typeof window) return !1;
8417 const e = new URLSearchParams(window.location.search);
8418 return e.has(Me) || e.has(He) || e.has($e);
8419 }() ? Ot(Rt() || e) : function() {
8420 Ot(It);
8421 try {
8422 localStorage.setItem(Et, It);
8423 } catch (e) {
8424 St.warn("localStorage not available");
8425 }
8426 }();
8427 }
8428 function Ot(e) {
8429 "undefined" != typeof window && window.toggleAngieSidebar && window.toggleAngieSidebar(e === "open", !0);
8430 }
8431 function Ut(e = R) {
8432 const t = document.getElementById(e.containerId);
8433 if (!t) return;
8434 let i = !1;
8435 let n = 0;
8436 let s = 0;
8437 t.addEventListener("mousedown", (e) => {
8438 const r = t.getBoundingClientRect();
8439 ("rtl" === document.documentElement.dir ? e.clientX <= r.left + 4 : e.clientX >= r.right - 4) && (i = !0, n = e.clientX, s = r.width, t.classList.add("angie-resizing"), document.body.style.cursor = "ew-resize", document.body.style.userSelect = "none", e.preventDefault(), e.stopPropagation());
8440 }), document.addEventListener("mousemove", (e) => {
8441 if (!i) return;
8442 let t;
8443 t = "rtl" === document.documentElement.dir ? n - e.clientX : e.clientX - n, xt(Math.max(350, Math.min(590, s + t))), e.preventDefault(), e.stopPropagation();
8444 }), document.addEventListener("mouseup", (n) => {
8445 if (i) {
8446 i = !1, t.classList.remove("angie-resizing"), document.body.style.cursor = "", document.body.style.userSelect = "";
8447 const r = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"), 10);
8448 Ct(r), gt(e, {
8449 type: m.ANGIE_SIDEBAR_RESIZED,
8450 payload: {
8451 initialWidth: s,
8452 width: r
8453 }
8454 }), n.preventDefault(), n.stopPropagation();
8455 }
8456 }), xt(Tt());
8457 }
8458 var Lt = !1;
8459 function Dt(e) {
8460 e?.skipDefaultCss || function() {
8461 if ("undefined" == typeof document || bt) return;
8462 const e = "angie-sidebar-styles";
8463 if (document.getElementById(e)) return void (bt = !0);
8464 const t = document.createElement("style");
8465 t.id = e, t.textContent = "/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";
8466 const i = document.head || document.getElementsByTagName("head")[0];
8467 i.insertBefore(t, i.firstChild), bt = !0;
8468 }();
8469 const t = e?.instance ?? R;
8470 "undefined" != typeof window && (window.toggleAngieSidebar = function(e, t = R) {
8471 return function(i, n) {
8472 const s = document.body;
8473 const r = document.getElementById(t.containerId);
8474 if (!r) return void St.warn("Required elements not found!");
8475 const o = s.classList.contains("angie-sidebar-active");
8476 const a = void 0 !== i ? i : !o;
8477 n || (s.classList.add("angie-sidebar-transitioning"), setTimeout(function() {
8478 s.classList.remove("angie-sidebar-transitioning");
8479 }, 300)), a ? s.classList.add("angie-sidebar-active") : s.classList.remove("angie-sidebar-active"), t.iframe && pt(t.iframe, a, t.containerId), function(e, t, i = R) {
8480 e && setTimeout(function() {
8481 gt(i, { type: "focusInput" });
8482 }, t);
8483 }(a, n ? 0 : 300, t), e && e(a, r, n), At(a ? "open" : It);
8484 const c = new CustomEvent("angieSidebarToggle", { detail: {
8485 isOpen: a,
8486 sidebar: r,
8487 skipTransition: n
8488 } });
8489 document.dispatchEvent(c), gt(t, {
8490 type: m.ANGIE_SIDEBAR_TOGGLED,
8491 payload: { state: a ? "opened" : "closed" }
8492 });
8493 };
8494 }(e?.onToggle, t), function(e = R) {
8495 Lt || (Lt = !0, window.addEventListener("message", function(t) {
8496 if ("toggleAngieSidebar" !== t.data?.type) return;
8497 const i = e.iframeUrlObject?.origin;
8498 if (!(i ? wt(t, i, e.iframe) : _t(t, e.iframe))) return;
8499 const { force: n, skipTransition: s } = t.data.payload || {};
8500 window.toggleAngieSidebar && window.toggleAngieSidebar(n, s);
8501 const r = t.ports?.[0];
8502 r && ft(r);
8503 }));
8504 }(t));
8505 }
8506 var Nt = "angie_return_url";
8507 var qt = g("referrer-redirect");
8508 function $t(e) {
8509 try {
8510 return new URL(e, window.location.origin).origin === window.location.origin;
8511 } catch {
8512 return !1;
8513 }
8514 }
8515 function Mt(e, t) {
8516 if (!$t(e)) return qt.warn("Invalid redirect URL rejected:", e), !1;
8517 try {
8518 const i = { url: e };
8519 return t && (i.prompt = t), localStorage.setItem(Nt, JSON.stringify(i)), !0;
8520 } catch (e) {
8521 return qt.warn("localStorage not available"), !1;
8522 }
8523 }
8524 function Ht() {
8525 try {
8526 const e = localStorage.getItem(Nt);
8527 if (!e) return null;
8528 let t;
8529 try {
8530 t = JSON.parse(e);
8531 } catch {
8532 return qt.warn("Stored redirect data is not valid JSON, returning null"), null;
8533 }
8534 return t.url && "string" == typeof t.url ? $t(t.url) ? t : (qt.warn("Stored redirect URL is invalid, returning null:", t.url), null) : (qt.warn("Stored redirect data missing url field, returning null"), null);
8535 } catch (e) {
8536 return qt.warn("localStorage not available"), null;
8537 }
8538 }
8539 function jt() {
8540 try {
8541 localStorage.removeItem(Nt);
8542 } catch (e) {
8543 qt.warn("localStorage not available");
8544 }
8545 }
8546 function Gt(e, t) {
8547 return t ? `${e}#angie-prompt=${encodeURIComponent(t)}` : e;
8548 }
8549 function zt() {
8550 const e = Ht();
8551 return !!e && (jt(), window.location.href = Gt(e.url, e.prompt), !0);
8552 }
8553 var Bt = g("oauth");
8554 var Wt = [];
8555 var Ft = !1;
8556 var Kt = !1;
8557 var Jt = () => {
8558 (() => {
8559 try {
8560 const e = new URL(window.location.href, window.location.origin).searchParams;
8561 return e.has("start-oauth") && "angie-app" === e.get("page");
8562 } catch {
8563 return !1;
8564 }
8565 })() && (Bt.log("Post-consent flow detected, checking for referrer redirect"), zt());
8566 };
8567 function Vt() {
8568 const e = Ht();
8569 if (e) return jt(), void (window.location.href = Gt(e.url, e.prompt));
8570 try {
8571 localStorage.setItem(Et, "open");
8572 } catch (e) {
8573 Bt.warn("localStorage not available");
8574 }
8575 setTimeout(() => {
8576 window.toggleAngieSidebar(!0);
8577 }, 500);
8578 }
8579 var Qt = (e) => {
8580 Wt.includes(e) || Wt.push(e);
8581 };
8582 var Xt = () => {
8583 for (const e of Wt.flatMap((e) => e.iframe && e.iframeUrlObject ? [{
8584 window: e.iframe,
8585 windowURL: e.iframeUrlObject
8586 }] : [])) st({
8587 targets: e,
8588 onSuccess: Vt
8589 });
8590 };
8591 var Yt = "sidebar";
8592 var Zt = "floatingChat";
8593 var ei = [];
8594 var ti = (e) => ei.find((t) => t.instanceId === e) ?? null;
8595 var ii = () => ei.some((e) => e.layout === Yt);
8596 var ni = g("sdk");
8597 var si;
8598 (si || (si = {})).POST_MESSAGE = "postMessage";
8599 var ri = /* @__PURE__ */ new Map();
8600 var oi = [];
8601 var ai = null;
8602 var ci = () => {
8603 0 === oi.length || ai || (ai = (e) => {
8604 const t = ((e) => {
8605 if (e.origin === window.location.origin) return oi.find((t) => ((e, t) => !(!t || t !== e.instanceId) || (!t || !ti(t)) && (() => {
8606 return ei.find((e) => null !== e.iframe) || (0 === ei.length && R.iframe ? R : null);
8607 })() === e)(t, e?.data?.payload?.instanceId)) ?? null;
8608 const t = oi.find((t) => t.iframe?.contentWindow === e.source);
8609 return t && wt(e, t.iframeUrlObject?.origin, t.iframe) ? t : null;
8610 })(e);
8611 if (t) switch (e?.data?.type) {
8612 case m.SDK_ANGIE_ALL_SERVERS_REGISTERED: break;
8613 case m.SDK_ANGIE_READY_PING: {
8614 const t = e.ports[0];
8615 ni.log("Angie is ready", e), ft(t, { message: "Angie is ready" });
8616 break;
8617 }
8618 case m.SDK_REQUEST_CLIENT_CREATION: {
8619 const i = e.data.payload;
8620 const n = e.ports[0];
8621 ((e, t) => {
8622 if (e.iframe) return void t();
8623 let i = ri.get(e);
8624 i || (i = [], ri.set(e, i)), i.push(t);
8625 })(t, () => {
8626 try {
8627 const s = new MessageChannel();
8628 s.port1.onmessage = (e) => {
8629 n.postMessage({
8630 success: !0,
8631 data: e.data
8632 });
8633 };
8634 const r = {
8635 type: m.SDK_REQUEST_CLIENT_CREATION,
8636 payload: {
8637 success: !0,
8638 ...i,
8639 clientId: `dynamic-client-${i.serverName}-${i.serverVersion}`,
8640 requestId: e.data.payload.requestId
8641 },
8642 timestamp: Date.now()
8643 };
8644 t.iframe?.contentWindow?.postMessage(r, t.iframeUrlObject?.origin || "", [s.port2]);
8645 } catch (e) {
8646 ni.error(`Failed to create client for SDK server "${i.serverName}":`, e);
8647 }
8648 });
8649 break;
8650 }
8651 case m.SDK_TRIGGER_ANGIE:
8652 ni.log("SDK Trigger Angie received", e.data);
8653 try {
8654 const { requestId: i, prompt: n, context: s, options: r } = e.data.payload;
8655 if (!t.iframe) throw new Error("Iframe not found");
8656 t.iframe.contentWindow?.postMessage({
8657 type: m.SDK_TRIGGER_ANGIE,
8658 payload: {
8659 requestId: i,
8660 prompt: n,
8661 context: s,
8662 options: r
8663 }
8664 }, t.iframeUrlObject?.origin || ""), window.postMessage({
8665 type: m.SDK_TRIGGER_ANGIE_RESPONSE,
8666 payload: {
8667 success: !0,
8668 requestId: i,
8669 response: "Angie triggered successfully"
8670 }
8671 }, window.location.origin);
8672 } catch (t) {
8673 ni.error("Failed to trigger Angie:", t), window.postMessage({
8674 type: m.SDK_TRIGGER_ANGIE_RESPONSE,
8675 payload: {
8676 success: !1,
8677 requestId: e.data.payload?.requestId,
8678 error: t instanceof Error ? t.message : "Unknown error"
8679 }
8680 }, window.location.origin);
8681 }
8682 }
8683 }, window.addEventListener("message", ai));
8684 };
8685 var di = (e) => {
8686 oi.includes(e) || oi.push(e);
8687 };
8688 var li = g("iframe");
8689 var gi = [];
8690 var ui = null;
8691 var hi = (e) => {
8692 if (e.includes("://") || e.startsWith("//")) return !1;
8693 try {
8694 const t = "https://test.com";
8695 return new URL(e, t).origin === t;
8696 } catch {
8697 return !1;
8698 }
8699 };
8700 var pi = async (e = R) => {
8701 if (e.iframe?.contentWindow && e.iframeUrlObject) try {
8702 li.log("Disabling navigation prevention in Angie iframe"), e.iframe.contentWindow.postMessage({ type: m.ANGIE_DISABLE_NAVIGATION_PREVENTION }, e.iframeUrlObject.origin), await new Promise((e) => setTimeout(e, 100));
8703 } catch (e) {
8704 throw li.error("Failed to disable navigation prevention:", e), e;
8705 }
8706 else li.warn("Cannot disable navigation prevention: iframe or origin not available");
8707 };
8708 var _i = (e) => {
8709 gi.push(e), ui || (ui = (e) => {
8710 const t = gi.find((t) => _t(e, t.instance.iframe));
8711 t && t.trustedOrigins.includes(e.origin) && (async (e, t) => {
8712 if (e?.data?.type === m.ANGIE_CHAT_TOGGLE) t.open = e.data.open, t.iframe && pt(t.iframe, t.open, t.containerId);
8713 else if (e?.data?.type === m.ANGIE_STUDIO_TOGGLE) {
8714 const i = e.data.isStudioOpen;
8715 if (!t.iframe) return;
8716 if (i) document.documentElement.classList.add("angie-studio-active");
8717 else {
8718 const e = Tt();
8719 document.documentElement.style.setProperty("--angie-sidebar-width", `${e}px`), document.documentElement.classList.remove("angie-studio-active");
8720 }
8721 } else if (e?.data?.type === m.ANGIE_NAVIGATE_TO_URL) {
8722 const { url: i = "", confirmed: n = !1 } = e.data.payload || {};
8723 if (!n) return void li.log("Navigation requires user confirmation");
8724 ((e, t = []) => {
8725 const i = 0 === t.length && "undefined" != typeof window ? [window.location.origin] : t;
8726 if (!e.startsWith("http")) return !1;
8727 try {
8728 const t = new URL(e);
8729 return i.includes(t.origin);
8730 } catch {
8731 return !1;
8732 }
8733 })(i) ? (await pi(t), window.location.assign(i)) : li.error("Navigation blocked: Invalid or unsafe URL", { url: i });
8734 } else if (e?.data?.type === m.ANGIE_PAGE_RELOAD) {
8735 const { confirmed: i = !1 } = e.data.payload || {};
8736 if (!i) return void li.log("Page reload requires user confirmation");
8737 li.log("Page reload confirmed - disabling navigation prevention and reloading"), await pi(t), setTimeout(() => {
8738 window.location.reload();
8739 }, 50);
8740 } else e?.data?.type === y.RESET_HASH && (window.location.hash = "", ft(e.ports[0], { message: "Hash reset successfully" }));
8741 })(e, t.instance);
8742 }, window.addEventListener("message", ui));
8743 };
8744 var wi = async (e, t = R) => {
8745 if (window.screen.availWidth <= 768) return void li.log("Mobile detected, skipping iframe injection");
8746 const i = t.containerId;
8747 let n = document.getElementById(i);
8748 if (!n) {
8749 const e = performance.now();
8750 if (li.log("⏱️ Waiting for sidebar container..."), await new Promise((e) => {
8751 let t = 0;
8752 const s = setInterval(() => {
8753 n = document.getElementById(i), t++, (n || t > 20) && (clearInterval(s), n && e());
8754 }, 100);
8755 setTimeout(() => {
8756 if (clearInterval(s), n) return void e();
8757 const t = new MutationObserver(() => {
8758 n = document.getElementById(i), n && (t.disconnect(), e());
8759 });
8760 t.observe(document.body, {
8761 childList: !0,
8762 subtree: !0
8763 }), setTimeout(() => {
8764 t.disconnect(), e();
8765 }, 8e3);
8766 }, 2e3);
8767 }), li.log(`⏱️ Sidebar container detection took: ${(performance.now() - e).toFixed(2)}ms`), !n) return void li.error("Sidebar container not found");
8768 }
8769 const { iframe: s, iframeUrlObject: r } = await (async (e) => {
8770 const t = e.origin;
8771 const i = new URL(e.path, t);
8772 const n = e.instanceId || mt();
8773 const s = i.pathname.slice(1).replace(/\//, "--") + "-" + n;
8774 return new Promise((n) => {
8775 const r = new URL(t);
8776 r.pathname = i.pathname;
8777 const o = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
8778 if (r.searchParams.append("colorScheme", e.uiTheme || o || "light"), r.searchParams.append("sdkVersion", e.sdkVersion), r.searchParams.append("instanceId", s), r.searchParams.append("origin", window.location.origin), e.isRTL && r.searchParams.append("isRTL", e.isRTL ? "true" : "false"), "localhost" === window.location.hostname && window.location.search.includes("debug_error")) {
8779 const e = new URLSearchParams(window.location.search).get("debug_error");
8780 e && r.searchParams.append("debug_error", e);
8781 }
8782 i.searchParams.forEach((e, t) => {
8783 r.searchParams.set(t, e);
8784 }), r.searchParams.set("ver", (/* @__PURE__ */ new Date()).getTime().toString());
8785 const a = e.parent || document;
8786 const c = a.createElement("iframe");
8787 const d = {
8788 "background-color": "transparent",
8789 "color-scheme": "normal",
8790 ...e.css
8791 };
8792 window.addEventListener("message", async (t) => {
8793 if (wt(t, r.origin, c)) switch (t.data.type) {
8794 case y.ANGIE_READY:
8795 n({
8796 iframe: c,
8797 iframeUrlObject: r
8798 });
8799 break;
8800 case y.ANGIE_LOADED: c.contentWindow?.postMessage({
8801 type: y.HOST_READY,
8802 instanceId: s,
8803 ...e.embeddedConfig ? { embedded: e.embeddedConfig } : {}
8804 }, r.origin);
8805 }
8806 }), c.setAttribute("src", r.href), c.id = e.iframeElementId || "angie-iframe", c.setAttribute("frameborder", "0"), c.setAttribute("scrolling", "no"), c.setAttribute("style", Object.entries(d).map(([e, t]) => `${e}: ${t}`).join("; ")), c.setAttribute("allow", "clipboard-write; clipboard-read"), e.insertCallback ? e.insertCallback(c) : a.body.appendChild(c);
8807 });
8808 })({
8809 origin: e.origin || "https://angie.elementor.com",
8810 path: e.path && hi(e.path) ? e.path : "angie/wp-admin",
8811 insertCallback: (e) => {
8812 li.log("Injecting Angie iframe into sidebar container"), e.setAttribute("title", "Angie AI Assistant"), e.setAttribute("role", "application"), e.setAttribute("aria-label", "Angie AI Assistant Interface");
8813 const t = document.getElementById("angie-sidebar-loading");
8814 t && (t.textContent = ""), n?.appendChild(e);
8815 },
8816 embeddedConfig: e.embeddedConfig,
8817 css: {
8818 width: "100%",
8819 height: "100%",
8820 border: "none",
8821 outline: "none"
8822 },
8823 uiTheme: e.uiTheme,
8824 isRTL: e.isRTL,
8825 sdkVersion: "1.7.1",
8826 iframeElementId: t.iframeElementId,
8827 instanceId: t.instanceId
8828 });
8829 return t.iframe = s, t.iframeUrlObject = r, ((e) => {
8830 ci();
8831 const t = ri.get(e);
8832 t?.length && (ri.delete(e), t.forEach((e) => e()));
8833 })(t), di(t), ci(), ((e = R) => {
8834 Qt(e), Ft || (Ft = !0, function({ trustedOrigin: e, onOAuthParamsCleared: t }) {
8835 window.addEventListener("message", (i) => {
8836 if (i.origin !== e) return;
8837 const n = i.ports?.[0];
8838 switch (i.data.type) {
8839 case Le:
8840 if (!n) return;
8841 it(n, { topUrl: window.location.href });
8842 break;
8843 case De:
8844 window.location.href = i.data.payload.url;
8845 break;
8846 case Ne: {
8847 if (!n) return;
8848 const e = i.data.payload.url;
8849 if (!history?.replaceState) return void nt(n, { message: "URL update not supported in this browser" });
8850 try {
8851 const i = window.location.href;
8852 history.replaceState({}, "", e), function(e, t) {
8853 const i = new URL(e).searchParams;
8854 const n = new URL(t).searchParams;
8855 const s = [
8856 Me,
8857 He,
8858 $e
8859 ];
8860 return s.some((e) => i.has(e)) && !s.some((e) => n.has(e));
8861 }(i, e) && t?.(), it(n, { message: "URL updated successfully" });
8862 } catch (e) {
8863 nt(n, { message: "URL update failed: " + (e instanceof Error ? e.message : "Unknown error") });
8864 }
8865 break;
8866 }
8867 case qe:
8868 if (!n) return;
8869 it(n, { isPending: "true" === new URLSearchParams(window.location.search).get(Me) });
8870 }
8871 });
8872 }({
8873 trustedOrigin: e.iframeUrlObject?.origin ?? "",
8874 onOAuthParamsCleared: Vt
8875 }));
8876 })(t), ((e = R) => {
8877 Qt(e), Xt(), Kt || (Kt = !0, window.addEventListener("load", () => {
8878 Bt.log("OIDC: Window load event fired, forwarding OIDC state if present"), Xt();
8879 }));
8880 })(t), _i({
8881 instance: t,
8882 trustedOrigins: [window.location.origin, e.origin || "https://angie.elementor.com"]
8883 }), {
8884 iframe: s,
8885 iframeOrigin: r.origin
8886 };
8887 };
8888 var mi = g("registration-queue");
8889 var fi = class {
8890 queue = [];
8891 isProcessing = !1;
8892 add(e) {
8893 const t = {
8894 id: this.generateId(e),
8895 config: e,
8896 timestamp: Date.now(),
8897 status: "pending"
8898 };
8899 return this.queue.push(t), mi.log(`Added server "${e.name}" to queue`), t;
8900 }
8901 getAll() {
8902 return [...this.queue];
8903 }
8904 getPending() {
8905 return this.queue.filter((e) => "pending" === e.status);
8906 }
8907 updateStatus(e, t, i) {
8908 const n = this.queue.find((t) => t.id === e);
8909 n && (n.status = t, i ? n.error = i : "pending" !== t && "registered" !== t || delete n.error, mi.log(`Updated server ${e} status to ${t}`));
8910 }
8911 async processQueue(e) {
8912 if (this.isProcessing) return void mi.log("Already processing queue");
8913 this.isProcessing = !0;
8914 const t = this.getPending();
8915 mi.log(`Processing ${t.length} pending registrations`);
8916 try {
8917 for (const i of t) try {
8918 await e(i), this.updateStatus(i.id, "registered");
8919 } catch (e) {
8920 const t = e instanceof Error ? e.message : String(e);
8921 this.updateStatus(i.id, "failed", t), mi.error(`Failed to process registration ${i.id}:`, t);
8922 }
8923 } finally {
8924 this.isProcessing = !1;
8925 }
8926 }
8927 clear() {
8928 this.queue = [], mi.log("Cleared all registrations");
8929 }
8930 resetAllToPending() {
8931 if (this.isProcessing) return mi.log("Cannot reset to pending - processing in progress"), !1;
8932 const e = this.queue.filter((e) => "registered" === e.status).length;
8933 const t = this.queue.filter((e) => "failed" === e.status).length;
8934 return this.queue.forEach((e) => {
8935 "pending" !== e.status && (e.status = "pending", delete e.error);
8936 }), mi.log(`Reset ${e + t} registrations to pending`), !0;
8937 }
8938 remove(e) {
8939 const t = this.queue.findIndex((t) => t.id === e);
8940 return -1 !== t && (this.queue.splice(t, 1), mi.log(`Removed registration ${e}`), !0);
8941 }
8942 generateId(e) {
8943 return `reg_${e.name}_${e.version}_${Date.now()}`;
8944 }
8945 };
8946 var yi = {
8947 layout: Yt,
8948 styleTheme: "",
8949 persistOpenState: !0,
8950 resizable: !0,
8951 chatToggleButtonEnabled: !1
8952 };
8953 var Si = "#angie-widget-toggle";
8954 var bi = {
8955 boot: { allowInIframe: !1 },
8956 container: {
8957 layout: yi.layout,
8958 styleTheme: yi.styleTheme,
8959 persistOpenState: yi.persistOpenState,
8960 resizable: yi.resizable,
8961 chatToggleButtonSelector: Si
8962 },
8963 iframe: {
8964 origin: "https://angie.elementor.com",
8965 path: "angie/embedded",
8966 uiTheme: "light"
8967 }
8968 };
8969 var vi = /* @__PURE__ */ new Map();
8970 var Ii = !1;
8971 var Ei = (e, t) => e && t ? `${e}::__angie::${t}` : e;
8972 var ki = (e, t) => {
8973 const i = Ei(e, t);
8974 try {
8975 const t = window.localStorage.getItem(i);
8976 return null !== t ? t : i === e ? null : window.localStorage.getItem(e);
8977 } catch {
8978 return null;
8979 }
8980 };
8981 var Ti = async (e) => {
8982 const t = ((e) => {
8983 const t = [...vi.values()].filter((t) => t.iframeOrigin === e.origin);
8984 return t.length <= 1 ? t[0] ?? null : t.find((t) => t.instance.iframe?.contentWindow === e.source) ?? null;
8985 })(e);
8986 if (!t) return;
8987 const i = e.data?.type;
8988 const n = e.ports?.[0];
8989 switch (i) {
8990 case "GET_EXTERNAL_HEADERS":
8991 if (!n) return;
8992 await (async (e, t) => {
8993 try {
8994 const i = t ? await t() : {};
8995 ft(e, ((e) => Object.fromEntries(Object.entries(e).filter(([, e]) => void 0 !== e)))(i));
8996 } catch (t) {
8997 ((e, t) => {
8998 e.postMessage({
8999 status: "error",
9000 payload: t
9001 });
9002 })(e, { message: t instanceof Error ? t.message : String(t) });
9003 }
9004 })(n, t.getExternalHeaders);
9005 break;
9006 case "angie/context/get-website-context":
9007 if (!n) return;
9008 ft(n, (s = t.host, { payload: {
9009 name: document.title,
9010 tagline: "",
9011 homeUrl: window.location.origin,
9012 siteLang: document.documentElement.lang,
9013 docTitle: document.title,
9014 platform: "frontend",
9015 timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
9016 today: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
9017 ...s?.website
9018 } }));
9019 break;
9020 case "angie/context/get-analytics-context":
9021 if (!n) return;
9022 ft(n, ((e) => ({ payload: {
9023 screenPath: window.location.pathname,
9024 ...e?.analytics
9025 } }))(t.host));
9026 break;
9027 case f.GET:
9028 if (!n) return;
9029 n.postMessage({ value: ki(e.data.key, t.host?.instanceId) });
9030 break;
9031 case f.SET: ((e, t, i) => {
9032 try {
9033 window.localStorage.setItem(Ei(e, i), t);
9034 } catch {}
9035 })(e.data.key, e.data.value, t.host?.instanceId);
9036 }
9037 var s;
9038 };
9039 var Ri = "data-angie-toggle-wired";
9040 var Ai = (e, t) => {
9041 const i = document.querySelector(e);
9042 i && (i.setAttribute("aria-expanded", t ? "true" : "false"), i.setAttribute("aria-label", t ? "Close Angie" : "Open Angie"));
9043 };
9044 var Ci = (e) => {
9045 const t = document.querySelector(e.toggleButtonSelector);
9046 t && "true" !== t.getAttribute(Ri) && (t.setAttribute(Ri, "true"), t.addEventListener("click", e.onClick));
9047 };
9048 var xi = /* @__PURE__ */ new Set();
9049 var Pi = !1;
9050 var Oi = (e) => {
9051 for (const t of xi) t(e);
9052 };
9053 var Ui = "angie-widget-toggle";
9054 var Li = "angie-widget-hidden";
9055 var Di = "angie-widget-fullscreen";
9056 var Ni = "angie-widget-container";
9057 var qi = "angie-chat-widget-styles";
9058 var $i = /^#([^\s#.[:]+)$/;
9059 var Mi = /^\[([^\]=]+)(?:="([^"]*)")?\]$/;
9060 var Hi = (e) => document.querySelector(e);
9061 var ji = /* @__PURE__ */ new Map();
9062 var Gi = (e) => {
9063 const t = document.getElementById(e.containerId);
9064 t && (e.isOpen ? t.classList.remove(Li) : t.classList.add(Li), e.instance.iframe && pt(e.instance.iframe, e.isOpen, e.containerId), Ai(e.toggleButtonSelector, e.isOpen));
9065 };
9066 var zi = (e, t) => {
9067 Gi({
9068 containerId: e.containerId,
9069 toggleButtonSelector: e.toggleButtonSelector,
9070 isOpen: t,
9071 instance: e.instance
9072 });
9073 };
9074 var Bi = (e, t) => {
9075 const i = t?.force;
9076 if (void 0 !== i) return zi(e, i), void (i || e.onClose?.());
9077 const n = ((e) => {
9078 const t = document.getElementById(e);
9079 return !!t && !t.classList.contains(Li);
9080 })(e.containerId);
9081 zi(e, !n), n && e.onClose?.();
9082 };
9083 var Wi = (e) => {
9084 const { instance: t } = e;
9085 var i;
9086 ji.get(t)?.(), ji.set(t, (i = (i) => {
9087 if (!wt(i, e.iframeOrigin, t.iframe)) return;
9088 const n = i.ports?.[0], { type: s, payload: r } = i.data || {};
9089 switch (s) {
9090 case m.ANGIE_SIDEBAR_TOGGLED:
9091 case "toggleAngieSidebar":
9092 Bi(e, r), n && ft(n);
9093 break;
9094 case m.ANGIE_STUDIO_TOGGLE: {
9095 const t = !!i.data.isStudioOpen;
9096 ((e, t) => {
9097 const i = document.getElementById(e);
9098 i && (t ? i.classList.add(Di) : i.classList.remove(Di));
9099 })(e.containerId, t), t && zi(e, !0), n && ft(n);
9100 break;
9101 }
9102 }
9103 }, xi.add(i), Pi || (Pi = !0, window.addEventListener("message", Oi)), () => {
9104 xi.delete(i);
9105 }));
9106 };
9107 var Fi = (e) => {
9108 const t = ((e) => e === "angie-sidebar-container" ? qi : `${qi}-${e}`)(e);
9109 if (document.getElementById(t)) return;
9110 const i = document.createElement("style");
9111 i.id = t, i.textContent = ((e) => `\n#${e}.${Ni} {\n\t--angie-widget-width: 400px;\n\t--angie-widget-height: 600px;\n\t--angie-widget-z-index: 99999;\n\n\tposition: fixed !important;\n\ttop: auto !important;\n\tbottom: 20px !important;\n\tinset-inline-start: auto !important;\n\tinset-inline-end: 20px !important;\n\twidth: var(--angie-widget-width) !important;\n\theight: var(--angie-widget-height) !important;\n\tmax-height: calc(100vh - 40px) !important;\n\tmax-width: calc(100vw - 40px) !important;\n\tz-index: var(--angie-widget-z-index) !important;\n\ttransform: none !important;\n\tborder-radius: 12px !important;\n\toverflow: hidden !important;\n\tbox-shadow: 0 4px 24px rgba(0, 0, 0, 0.15) !important;\n\ttransition: opacity 0.2s ease, transform 0.2s ease !important;\n}\n\n#${e}.${Ni}.${Li} {\n\tdisplay: none !important;\n}\n\n#${e}.${Ni} iframe {\n\twidth: 100% !important;\n\theight: 100% !important;\n\tborder: none !important;\n\tborder-radius: 12px !important;\n}\n\n\n.${Ui} {\n\t--angie-toggle-size: 56px;\n\t--angie-widget-z-index: 99999;\n\n\tposition: fixed;\n\tbottom: 20px;\n\tinset-inline-end: 20px;\n\twidth: var(--angie-toggle-size);\n\theight: var(--angie-toggle-size);\n\tborder-radius: 50%;\n\tborder: none;\n\tbackground: #EB8EFB;\n\tcolor: white;\n\tcursor: pointer;\n\tz-index: var(--angie-widget-z-index);\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tbox-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);\n\ttransition: background 0.2s ease, transform 0.15s ease;\n\tpadding: 0;\n}\n\n.${Ui}:hover {\n\tbackground: #E070F5;\n\ttransform: scale(1.05);\n}\n\n.${Ui}:active {\n\ttransform: scale(0.95);\n}\n\n.${Ui}[aria-expanded="true"] {\n\tdisplay: none;\n}\n\n\n#${e}.${Ni}.${Di} {\n\tbottom: 0 !important;\n\tinset-inline-end: 0 !important;\n\twidth: 100vw !important;\n\theight: 100vh !important;\n\tmax-height: 100vh !important;\n\tmax-width: 100vw !important;\n\tborder-radius: 0 !important;\n}\n\n#${e}.${Ni}.${Di} iframe {\n\tborder-radius: 0 !important;\n}\n\n@media (max-width: 480px) {\n\t#${e}.${Ni} {\n\t\tbottom: 0 !important;\n\t\tinset-inline-end: 0 !important;\n\t\twidth: 100vw !important;\n\t\theight: 100vh !important;\n\t\tmax-height: 100vh !important;\n\t\tmax-width: 100vw !important;\n\t\tborder-radius: 0 !important;\n\t}\n\n\t#${e}.${Ni} iframe {\n\t\tborder-radius: 0 !important;\n\t}\n}\n`)(e), document.head.appendChild(i);
9112 };
9113 var Ki = (e) => {
9114 Fi(e.containerId), ((e) => {
9115 const t = document.getElementById(e);
9116 t && (t.classList.add(Ni, Li), t.setAttribute("role", "complementary"), t.setAttribute("aria-label", "Angie"), t.setAttribute("aria-hidden", "true"), t.setAttribute("tabindex", "-1"));
9117 })(e.containerId), e.injectToggleButton && ((e) => {
9118 if (Hi(e)) return;
9119 const t = document.createElement("button");
9120 ((e, t) => {
9121 const i = t.match($i);
9122 if (i) return void (e.id = i[1]);
9123 const n = t.match(Mi);
9124 n && e.setAttribute(n[1], n[2] ?? "");
9125 })(t, e), t.className = Ui, t.setAttribute("aria-label", "Open Angie"), t.setAttribute("aria-expanded", "false"), t.type = "button", t.innerHTML = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 16 16\" fill=\"none\">\n <path d=\"M15.0998 8.00414L14.622 8.18282C13.4991 8.60516 12.8142 9.50669 12.4001 10.6519L12.2249 11.1392L12.0497 10.6519C11.6356 9.50669 10.9109 8.60516 9.78801 8.18282L9.31018 8.00414L9.78801 7.82546C10.9109 7.40312 11.6356 6.50159 12.0497 5.3564L12.2249 4.86909L12.4001 5.3564C12.8142 6.50159 13.4991 7.40312 14.622 7.82546L15.0998 8.00414Z\" fill=\"white\"/>\n <path d=\"M2 8.42721C5.5608 8.42721 8.44479 11.3685 8.44479 15\" stroke=\"white\" stroke-width=\"2.05092\" stroke-miterlimit=\"10\"/>\n <path d=\"M2 7.57275C5.5608 7.57275 8.44479 4.6315 8.44479 0.999991\" stroke=\"white\" stroke-width=\"2.05092\" stroke-miterlimit=\"10\"/>\n</svg>", document.body.appendChild(t);
9126 })(e.toggleButtonSelector), ((e) => {
9127 ((e) => {
9128 Ci({
9129 toggleButtonSelector: e.toggleButtonSelector,
9130 onClick: () => {
9131 const i = "true" === Hi(e.toggleButtonSelector)?.getAttribute("aria-expanded");
9132 zi(e, !i), i && e.onClose?.();
9133 }
9134 });
9135 })(e), Wi(e), ii() || (window.toggleAngieSidebar = (t) => {
9136 Bi(e, { force: t });
9137 });
9138 })({
9139 containerId: e.containerId,
9140 iframeOrigin: e.iframeOrigin,
9141 onClose: e.onClose,
9142 toggleButtonSelector: e.toggleButtonSelector,
9143 instance: e.instance
9144 });
9145 };
9146 var Ji = !1;
9147 var Vi = {
9148 initShell: ({ config: e, instance: t }) => {
9149 ((e, t, i = R) => {
9150 const n = e.chatToggleButton.enabled ? e.chatToggleButton.selector : void 0;
9151 Dt({
9152 instance: i,
9153 onToggle: (e) => {
9154 n && Ai(n, e), !e && t.onClose && t.onClose();
9155 }
9156 }), ((e) => {
9157 if ("wordpress" !== e || "undefined" == typeof document) return;
9158 const t = "angie-sidebar-wordpress-styles";
9159 if (document.getElementById(t) || (Ji = !1), Ji) return;
9160 const i = document.createElement("style");
9161 i.id = t, i.textContent = "body.admin-bar {\n --angie-sidebar-z-index: 99999;\n}\n\n#angie-body-top-padding {\n height: 0;\n transition: height 0.3s ease-in-out;\n}\n\nbody.angie-sidebar-transitioning #wpadminbar {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n@media (min-width: 768px) {\n body.angie-sidebar-active #angie-body-top-padding {\n width: 100%;\n height: 0;\n }\n\n body.angie-sidebar-active #wpadminbar {\n inset-inline-start: var(--angie-sidebar-width) !important;\n inset-inline-end: 0 !important;\n width: calc(100% - var(--angie-sidebar-width)) !important;\n margin-top: 0;\n }\n}\n\n@media (max-width: 768px) {\n body.angie-sidebar-active #wpadminbar {\n inset-inline-start: 0 !important;\n inset-inline-end: 0 !important;\n width: 100% !important;\n }\n}\n\nbody:not(.wp-admin) #angie-sidebar-container {\n margin-top: 3px;\n}\n", (document.head || document.getElementsByTagName("head")[0]).appendChild(i), Ji = !0;
9162 })(e.styleTheme), n && Ci({
9163 toggleButtonSelector: n,
9164 onClick: (e) => {
9165 e.preventDefault(), window.toggleAngieSidebar?.();
9166 }
9167 });
9168 })(e.container, e.callbacks, t);
9169 },
9170 beforeOpenIframe: ({ config: e }) => {
9171 var t;
9172 (t = e.container).chatToggleButton.enabled && (t.persistOpenState && Rt() === "open" || Ot(It));
9173 },
9174 afterOpenIframe: ({ config: e, instance: t }) => {
9175 ((e, t = R) => {
9176 e.persistOpenState && Pt(e.chatToggleButton.enabled ? It : "open"), e.resizable && Ut(t);
9177 })(e.container, t);
9178 }
9179 };
9180 var Qi = { initShell: ({ config: e, instance: t }) => {
9181 const { chatToggleButton: i } = e.container;
9182 Ki({
9183 containerId: e.container.id,
9184 iframeOrigin: e.iframe.origin,
9185 onClose: e.callbacks.onClose,
9186 toggleButtonSelector: i.selector,
9187 injectToggleButton: i.enabled,
9188 instance: t
9189 });
9190 } };
9191 var Xi = {
9192 [Yt]: Vi,
9193 [Zt]: Qi
9194 };
9195 var Yi = {
9196 layout: Zt,
9197 styleTheme: "",
9198 persistOpenState: !1,
9199 resizable: !1,
9200 chatToggleButtonEnabled: !0
9201 };
9202 var Zi = { closeButton: "collapse" };
9203 var en = (e, t) => e === "floatingChat" ? {
9204 closeButton: "close",
9205 ...t
9206 } : t ? {
9207 ...Zi,
9208 ...t
9209 } : Zi;
9210 var tn = async (e) => {
9211 Jt();
9212 const t = {
9213 browserUiTheme: "undefined" != typeof window && "function" == typeof window.matchMedia ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : bi.iframe.uiTheme,
9214 isInIframe: "undefined" != typeof window && window !== window.top,
9215 isRTL: "undefined" != typeof document && "rtl" === document.documentElement.dir
9216 };
9217 const i = ((e, t) => {
9218 const i = e.boot ?? {};
9219 const n = e.container ?? {};
9220 const s = e.iframe ?? {};
9221 const r = e.callbacks ?? {};
9222 const o = n.layout ?? bi.container.layout;
9223 const a = ((e) => e === "floatingChat" ? Yi : yi)(o);
9224 const c = n.chatToggleButton?.enabled ?? a.chatToggleButtonEnabled;
9225 return {
9226 host: {
9227 appId: e.host.appId,
9228 instanceId: e.host.instanceId,
9229 aiContext: e.host.aiContext,
9230 website: e.host.website,
9231 analytics: e.host.analytics
9232 },
9233 boot: { allowInIframe: i.allowInIframe ?? bi.boot.allowInIframe },
9234 container: {
9235 id: n.id?.trim() || "angie-sidebar-container",
9236 layout: o,
9237 styleTheme: n.styleTheme ?? a.styleTheme,
9238 persistOpenState: n.persistOpenState ?? a.persistOpenState,
9239 resizable: n.resizable ?? a.resizable,
9240 chatToggleButton: {
9241 enabled: c,
9242 selector: n.chatToggleButton?.selector?.trim() || bi.container.chatToggleButtonSelector
9243 }
9244 },
9245 iframe: {
9246 origin: s.origin?.trim() || bi.iframe.origin,
9247 path: s.path?.trim() || bi.iframe.path,
9248 uiTheme: s.uiTheme ?? t.browserUiTheme,
9249 isRTL: s.isRTL ?? t.isRTL
9250 },
9251 callbacks: {
9252 onClose: r.onClose,
9253 getExternalHeaders: r.getExternalHeaders
9254 },
9255 widgetConfig: en(o, e.widgetConfig)
9256 };
9257 })(e, t);
9258 if (!((e, t) => !(!e.boot.allowInIframe && t.isInIframe))(i, t)) return;
9259 if (i.container.layout === "sidebar" && ii()) throw new Error("Angie SDK: only one sidebar layout instance is supported on a page. Use container.layout \"floatingChat\" for the extra instance.");
9260 if (n = i.container.id, ei.find((e) => e.containerId === n)) throw new Error(`Angie SDK: container id "${i.container.id}" is already used by another Angie instance. Give this instance its own container.id.`);
9261 var n;
9262 const s = i.host.instanceId || e.sdkInstanceId || mt();
9263 if (ti(s)) throw new Error(`Angie SDK: instance id "${s}" is already used by another Angie instance. Give this instance its own host.instanceId.`);
9264 ei[0] && i.container.chatToggleButton.selector === Si && (i.container.chatToggleButton.selector = `${Si}-${s}`);
9265 const r = ((e) => {
9266 const t = 0 === ei.length;
9267 const i = {
9268 ...T(),
9269 ...e,
9270 iframeElementId: t ? k : `${k}-${e.instanceId}`
9271 };
9272 const n = t ? Object.assign(R, i) : i;
9273 return ei.push(n), n;
9274 })({
9275 containerId: i.container.id,
9276 instanceId: s,
9277 layout: i.container.layout
9278 });
9279 var o;
9280 di(r), ci(), o = {
9281 iframeOrigin: i.iframe.origin,
9282 host: i.host,
9283 getExternalHeaders: i.callbacks.getExternalHeaders,
9284 instance: r
9285 }, vi.set(o.instance, o), Ii || (Ii = !0, window.addEventListener("message", (e) => {
9286 Ti(e);
9287 })), ((e, t) => {
9288 if (document.getElementById(e)) return;
9289 const i = document.createElement("div");
9290 i.id = e, i.dir = t ? "rtl" : "ltr";
9291 const n = document.createElement("div");
9292 n.id = "angie-sidebar-loading", n.setAttribute("aria-live", "polite"), n.className = "angie-sr-only", i.appendChild(n), document.body.appendChild(i);
9293 })(i.container.id, t.isRTL);
9294 const a = Xi[i.container.layout];
9295 const c = {
9296 config: i,
9297 env: t,
9298 instance: r
9299 };
9300 a.initShell(c), a.beforeOpenIframe?.(c);
9301 const d = {
9302 aiContext: (l = i.host).aiContext,
9303 appId: l.appId,
9304 configVersion: 2,
9305 telemetry: { screenPath: window.location.pathname },
9306 website: {
9307 docTitle: document.title,
9308 homeUrl: window.location.origin,
9309 name: document.title,
9310 platform: "frontend",
9311 siteLang: document.documentElement.lang,
9312 tagline: "",
9313 ...l.website
9314 }
9315 };
9316 var l;
9317 const g = await (async (e) => {
9318 const t = e.instance ?? R;
9319 return !!await wi({
9320 isRTL: e.iframe.isRTL,
9321 origin: e.iframe.origin,
9322 path: e.iframe.path,
9323 uiTheme: e.iframe.uiTheme,
9324 embeddedConfig: e.embeddedConfig
9325 }, t) && (e.container.layout === "floatingChat" && e.container.chatToggleButton.enabled ? (Gi({
9326 containerId: e.container.id,
9327 toggleButtonSelector: e.container.chatToggleButton.selector,
9328 isOpen: !1,
9329 instance: t
9330 }), !0) : (t.iframe && pt(t.iframe, !1, t.containerId), e.container.chatToggleButton.enabled && Ai(e.container.chatToggleButton.selector, !1), !0));
9331 })({
9332 container: i.container,
9333 iframe: i.iframe,
9334 embeddedConfig: d,
9335 instance: r
9336 });
9337 a.afterOpenIframe?.(c), g && (((e, t = R) => {
9338 gt(t, {
9339 payload: e,
9340 type: "sdk-embedded-config"
9341 });
9342 })(d, r), i.widgetConfig && ((e, t = R) => {
9343 gt(t, {
9344 payload: e,
9345 type: "sdk-widget-config"
9346 });
9347 })(i.widgetConfig, r));
9348 };
9349 var nn = "angie-prompt";
9350 var sn = [];
9351 var rn = {
9352 origin: "https://angie.elementor.com",
9353 uiTheme: "light",
9354 isRTL: !1,
9355 containerId: E,
9356 skipDefaultCss: !1,
9357 path: "angie/wp-admin"
9358 };
9359 var on = class {
9360 angieDetector;
9361 clientManager;
9362 logger;
9363 registrationQueue;
9364 isInitialized = !1;
9365 instanceId;
9366 sidebarV2BootPromise = null;
9367 promptHashListenerAttached = !1;
9368 constructor() {
9369 this.instanceId = mt(), this.logger = g({ instanceId: this.instanceId }), this.logger.log("Constructor called - initializing SDK"), this.angieDetector = new b(() => this.instanceId), this.registrationQueue = new fi(), this.clientManager = new I(), this.logger.log("Setting up event handlers"), this.setupAngieReadyHandler(), this.setupServerInitHandler(), this.setupReRegistrationHandler(), this.logger.log("SDK initialization complete");
9370 }
9371 async loadSidebar(e) {
9372 Jt();
9373 const { widgetConfig: t, ...i } = e || {}, n = {
9374 ...rn,
9375 ...i
9376 };
9377 R.containerId = n.containerId, R.instanceId = this.instanceId, Dt({ skipDefaultCss: n.skipDefaultCss });
9378 const s = await wi(n);
9379 s && window.addEventListener("message", (e) => {
9380 if (e.origin === R.iframeUrlObject?.origin) switch (e.data.type) {
9381 case f.SET:
9382 window.localStorage.setItem(e.data.key, e.data.value);
9383 break;
9384 case f.GET: {
9385 const t = e.ports[0];
9386 const i = window.localStorage.getItem(e.data.key);
9387 t.postMessage({ value: i });
9388 break;
9389 }
9390 }
9391 }), s && t && s.iframe.contentWindow?.postMessage({
9392 type: "sdk-widget-config",
9393 payload: t
9394 }, s.iframeOrigin), this.setupPromptHashDetection();
9395 }
9396 loadSidebarV2(e) {
9397 return e.host.instanceId && (this.instanceId = e.host.instanceId), this.sidebarV2BootPromise = tn({
9398 ...e,
9399 sdkInstanceId: this.instanceId
9400 }), this.setupPromptHashDetection(), this.sidebarV2BootPromise;
9401 }
9402 setupReRegistrationHandler() {
9403 window.addEventListener("message", (e) => {
9404 if (e.data?.type === m.SDK_ANGIE_REFRESH_PING) {
9405 const t = ti(this.instanceId)?.iframeUrlObject?.origin;
9406 if (t && e.origin !== t) return void this.logger.log(`Ignoring refresh ping from unexpected origin. Event origin: ${e.origin}, iframe origin: ${t}`);
9407 const i = e.data?.payload?.instanceId;
9408 if (i && i !== this.instanceId) return void this.logger.log(`Ignoring refresh ping for different instance. Ping instanceId: ${i}, this instanceId: ${this.instanceId}`);
9409 if (this.logger.log("Angie refresh ping received"), this.registrationQueue.resetAllToPending()) {
9410 const e = this.registrationQueue.getPending().length;
9411 this.logger.log(`Successfully reset ${e} registrations, processing queue`), this.handleAngieReady();
9412 } else this.logger.log("Skipping queue reset - processing already in progress");
9413 }
9414 });
9415 }
9416 setupAngieReadyHandler() {
9417 this.angieDetector.waitForReady().then((e) => {
9418 e.isReady ? this.handleAngieReady() : this.logger.warn("Angie not detected - servers will remain queued");
9419 }).catch((e) => {
9420 this.logger.error("Error waiting for Angie:", e);
9421 });
9422 }
9423 async handleAngieReady() {
9424 this.logger.log("Angie is ready, processing queued registrations");
9425 try {
9426 await this.registrationQueue.processQueue(async (e) => {
9427 this.logger.log(`processQueue callback called for "${e.config.name}"`), await this.processRegistration(e);
9428 }), this.isInitialized = !0, this.logger.log("Initialization complete");
9429 } catch (e) {
9430 this.logger.error("Error processing registration queue:", e);
9431 }
9432 }
9433 async processRegistration(e) {
9434 this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);
9435 try {
9436 this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);
9437 const t = {
9438 ...e,
9439 instanceId: this.instanceId
9440 };
9441 await this.clientManager.requestClientCreation(t), this.logger.log(`Successfully registered server "${e.config.name}"`);
9442 } catch (t) {
9443 throw this.logger.error(`Failed to register server "${e.config.name}":`, t), t;
9444 }
9445 }
9446 registerLocalServer(e) {
9447 return e.type = _.LOCAL, e.transport = h.POST_MESSAGE, this.registerServer(e);
9448 }
9449 registerRemoteServer(e) {
9450 return e.type = _.REMOTE, this.registerServer(e);
9451 }
9452 isLocalServerConfig(e) {
9453 return e.type === _.LOCAL || !e.type && "server" in e;
9454 }
9455 isRemoteServerConfig(e) {
9456 return e.type === _.REMOTE && "url" in e;
9457 }
9458 async registerServer(e) {
9459 if (!e.type) return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"), void this.registerLocalServer(e);
9460 if (this.logger.log(`registerServer called for "${e.name}"`), !e.name) throw new Error("Server name is required");
9461 if (!e.description) throw new Error("Server description is required");
9462 if (this.isLocalServerConfig(e) && !e.server) throw new Error("Server instance is required for local servers");
9463 this.logger.log(`Registering server "${e.name}"`);
9464 const t = this.registrationQueue.add(e);
9465 if (this.logger.log(`Added registration to queue: ${t.id}`), this.angieDetector.isReady()) try {
9466 await this.processRegistration(t), this.registrationQueue.updateStatus(t.id, "registered"), this.logger.log(`Server "${e.name}" registered successfully`);
9467 } catch (e) {
9468 const i = e instanceof Error ? e.message : String(e);
9469 throw this.registrationQueue.updateStatus(t.id, "failed", i), e;
9470 }
9471 else this.logger.log(`Server "${e.name}" queued until Angie is ready`);
9472 }
9473 getRegistrations() {
9474 return this.registrationQueue.getAll();
9475 }
9476 getPendingRegistrations() {
9477 return this.registrationQueue.getPending();
9478 }
9479 isAngieReady() {
9480 return this.angieDetector.isReady();
9481 }
9482 isReady() {
9483 return this.isInitialized;
9484 }
9485 async waitForReady() {
9486 if (this.sidebarV2BootPromise) await this.sidebarV2BootPromise;
9487 else for (; !R.iframe;) await new Promise((e) => setTimeout(e, 100));
9488 if (!(await this.angieDetector.waitForReady()).isReady) throw new Error("Angie is not available");
9489 for (; !this.isInitialized;) await new Promise((e) => setTimeout(e, 100));
9490 }
9491 async triggerAngie(e) {
9492 if (!this.isAngieReady()) throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");
9493 const t = this.generateRequestId();
9494 const i = e.options?.timeout || 3e4;
9495 return new Promise((n, s) => {
9496 const r = setTimeout(() => {
9497 s(/* @__PURE__ */ new Error("Angie trigger request timed out"));
9498 }, i);
9499 const o = (e) => {
9500 e.data?.type === m.SDK_TRIGGER_ANGIE_RESPONSE && e.data?.payload?.requestId === t && (clearTimeout(r), window.removeEventListener("message", o), n(e.data.payload));
9501 };
9502 window.addEventListener("message", o);
9503 const a = {
9504 type: m.SDK_TRIGGER_ANGIE,
9505 payload: {
9506 requestId: t,
9507 instanceId: this.instanceId,
9508 prompt: e.prompt,
9509 options: e.options,
9510 context: {
9511 pageUrl: window.location.href,
9512 pageTitle: document.title,
9513 ...e.context
9514 }
9515 },
9516 timestamp: Date.now()
9517 };
9518 this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`), window.postMessage(a, window.location.origin);
9519 });
9520 }
9521 destroy() {
9522 this.registrationQueue.clear(), this.logger.log("SDK destroyed");
9523 }
9524 setupServerInitHandler() {
9525 window.addEventListener("message", (e) => {
9526 e.data?.type === m.SDK_REQUEST_INIT_SERVER && (this.logger.log("Server init request received"), this.handleServerInitRequest(e));
9527 });
9528 }
9529 handleServerInitRequest(e) {
9530 const { clientId: t, serverId: i, instanceId: n } = e.data.payload || {};
9531 if (t && i) if (this.logger.log(`Server init request received - Request instanceId: ${n}, This instanceId: ${this.instanceId}`), n && n !== this.instanceId) this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${n}, this instanceId: ${this.instanceId}`);
9532 else {
9533 this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${i}`);
9534 try {
9535 const t = this.registrationQueue.getAll().find((e) => e.id === i);
9536 if (!t) return void this.logger.log(`No registration found for serverId: ${i} (likely belongs to another instance)`);
9537 if ("type" in t.config && "remote" === t.config.type) return void this.logger.log("Remote server registration detected; skipping local connect");
9538 const n = e.ports[0];
9539 if (!n) return void this.logger.error("No port provided in server init request");
9540 const s = t.config.server;
9541 this.migrateInstructionsCompat(s);
9542 const r = new v(n);
9543 s.connect(r), this.logger.log(`Server "${t.config.name}" initialized successfully`);
9544 } catch (e) {
9545 this.logger.error(`Error initializing server for clientId ${t}:`, e);
9546 }
9547 }
9548 else this.logger.error("Invalid server init request - missing clientId or serverId");
9549 }
9550 migrateInstructionsCompat(e) {
9551 try {
9552 const t = "server" in e && e.server ? e.server : e;
9553 const i = t._serverInfo;
9554 const n = t._instructions;
9555 i?.instructions && !n && (t._instructions = i.instructions, this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"));
9556 } catch {}
9557 }
9558 generateRequestId() {
9559 return `${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
9560 }
9561 parseHashParams(e) {
9562 const t = e.startsWith("#") ? e.substring(1) : e;
9563 return new URLSearchParams(t);
9564 }
9565 shouldHandlePromptHash(e) {
9566 const t = e.get("angie-instance");
9567 return t ? t === this.instanceId : 0 === sn.length || sn[0] === this;
9568 }
9569 async handlePromptHash() {
9570 const e = window.location.hash;
9571 if (e.includes(`${nn}=`)) try {
9572 const t = this.parseHashParams(e);
9573 if (!this.shouldHandlePromptHash(t)) return;
9574 const i = t.get(nn) || "";
9575 if (!i) return void this.logger.warn("Empty prompt detected in hash");
9576 const n = "true" === t.get("angie-new-chat");
9577 this.logger.log("Detected prompt in hash:", {
9578 prompt: i,
9579 newChat: n
9580 }), await this.waitForReady();
9581 const s = await this.triggerAngie({
9582 prompt: i,
9583 context: {
9584 source: "hash-parameter",
9585 pageUrl: window.location.href,
9586 timestamp: (/* @__PURE__ */ new Date()).toISOString()
9587 },
9588 options: { newChat: n }
9589 });
9590 this.logger.log("Triggered successfully from hash:", s), window.location.hash = "";
9591 } catch (e) {
9592 this.logger.error("Failed to trigger from hash:", e);
9593 }
9594 }
9595 setupPromptHashDetection() {
9596 this.promptHashListenerAttached || (this.promptHashListenerAttached = !0, sn.push(this), window.addEventListener("hashchange", () => this.handlePromptHash())), this.handlePromptHash();
9597 }
9598 };
9599 var pn = g("navigation");
9600 var wn = g("interaction-mode");
9601 var mn = (e) => ut() ? !!ht({
9602 type: m.ANGIE_SET_INTERACTION_MODE,
9603 payload: { mode: e }
9604 }) || (wn.error("Failed to post interaction mode message to Angie iframe"), !1) : (wn.error("Angie iframe not found"), !1);
9605 var vn;
9606 (function(e) {
9607 e.Inline = "inline", e.EndOfTurn = "end-of-turn";
9608 })(vn || (vn = {}));
9609
9610 //#endregion
9611 //#region packages/packages/libs/editor-mcp/src/utils/get-sdk.ts
9612 var sdk;
9613 var RetriableAngieSDK = class extends on {
9614 async waitForReady() {
9615 let retryCount = 3;
9616 while (retryCount > 0) try {
9617 await super.waitForReady();
9618 return;
9619 } catch {
9620 retryCount--;
9621 await sleep();
9622 }
9623 return new Promise(() => {});
9624 }
9625 };
9626 var sleep = (ms = 1e4) => new Promise((resolve) => {
9627 setTimeout(resolve, ms);
9628 });
9629 var getSDK = () => {
9630 if (!!globalThis.__ELEMENTOR_MCP_DISABLED__) return {};
9631 if (!sdk) sdk = new RetriableAngieSDK();
9632 return sdk;
9633 };
9634
9635 //#endregion
9636 //#region node_modules/zod/v3/helpers/util.js
9637 var util;
9638 (function(util) {
9639 util.assertEqual = (_) => {};
9640 function assertIs(_arg) {}
9641 util.assertIs = assertIs;
9642 function assertNever(_x) {
9643 throw new Error();
9644 }
9645 util.assertNever = assertNever;
9646 util.arrayToEnum = (items) => {
9647 const obj = {};
9648 for (const item of items) obj[item] = item;
9649 return obj;
9650 };
9651 util.getValidEnumValues = (obj) => {
9652 const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
9653 const filtered = {};
9654 for (const k of validKeys) filtered[k] = obj[k];
9655 return util.objectValues(filtered);
9656 };
9657 util.objectValues = (obj) => {
9658 return util.objectKeys(obj).map(function(e) {
9659 return obj[e];
9660 });
9661 };
9662 util.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
9663 const keys = [];
9664 for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
9665 return keys;
9666 };
9667 util.find = (arr, checker) => {
9668 for (const item of arr) if (checker(item)) return item;
9669 };
9670 util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
9671 function joinValues(array, separator = " | ") {
9672 return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
9673 }
9674 util.joinValues = joinValues;
9675 util.jsonStringifyReplacer = (_, value) => {
9676 if (typeof value === "bigint") return value.toString();
9677 return value;
9678 };
9679 })(util || (util = {}));
9680 var objectUtil;
9681 (function(objectUtil) {
9682 objectUtil.mergeShapes = (first, second) => {
9683 return {
9684 ...first,
9685 ...second
9686 };
9687 };
9688 })(objectUtil || (objectUtil = {}));
9689 var ZodParsedType = util.arrayToEnum([
9690 "string",
9691 "nan",
9692 "number",
9693 "integer",
9694 "float",
9695 "boolean",
9696 "date",
9697 "bigint",
9698 "symbol",
9699 "function",
9700 "undefined",
9701 "null",
9702 "array",
9703 "object",
9704 "unknown",
9705 "promise",
9706 "void",
9707 "never",
9708 "map",
9709 "set"
9710 ]);
9711 var getParsedType = (data) => {
9712 switch (typeof data) {
9713 case "undefined": return ZodParsedType.undefined;
9714 case "string": return ZodParsedType.string;
9715 case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
9716 case "boolean": return ZodParsedType.boolean;
9717 case "function": return ZodParsedType.function;
9718 case "bigint": return ZodParsedType.bigint;
9719 case "symbol": return ZodParsedType.symbol;
9720 case "object":
9721 if (Array.isArray(data)) return ZodParsedType.array;
9722 if (data === null) return ZodParsedType.null;
9723 if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") return ZodParsedType.promise;
9724 if (typeof Map !== "undefined" && data instanceof Map) return ZodParsedType.map;
9725 if (typeof Set !== "undefined" && data instanceof Set) return ZodParsedType.set;
9726 if (typeof Date !== "undefined" && data instanceof Date) return ZodParsedType.date;
9727 return ZodParsedType.object;
9728 default: return ZodParsedType.unknown;
9729 }
9730 };
9731
9732 //#endregion
9733 //#region node_modules/zod/v3/ZodError.js
9734 var ZodIssueCode = util.arrayToEnum([
9735 "invalid_type",
9736 "invalid_literal",
9737 "custom",
9738 "invalid_union",
9739 "invalid_union_discriminator",
9740 "invalid_enum_value",
9741 "unrecognized_keys",
9742 "invalid_arguments",
9743 "invalid_return_type",
9744 "invalid_date",
9745 "invalid_string",
9746 "too_small",
9747 "too_big",
9748 "invalid_intersection_types",
9749 "not_multiple_of",
9750 "not_finite"
9751 ]);
9752 var ZodError = class ZodError extends Error {
9753 get errors() {
9754 return this.issues;
9755 }
9756 constructor(issues) {
9757 super();
9758 this.issues = [];
9759 this.addIssue = (sub) => {
9760 this.issues = [...this.issues, sub];
9761 };
9762 this.addIssues = (subs = []) => {
9763 this.issues = [...this.issues, ...subs];
9764 };
9765 const actualProto = new.target.prototype;
9766 if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
9767 else this.__proto__ = actualProto;
9768 this.name = "ZodError";
9769 this.issues = issues;
9770 }
9771 format(_mapper) {
9772 const mapper = _mapper || function(issue) {
9773 return issue.message;
9774 };
9775 const fieldErrors = { _errors: [] };
9776 const processError = (error) => {
9777 for (const issue of error.issues) if (issue.code === "invalid_union") issue.unionErrors.map(processError);
9778 else if (issue.code === "invalid_return_type") processError(issue.returnTypeError);
9779 else if (issue.code === "invalid_arguments") processError(issue.argumentsError);
9780 else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
9781 else {
9782 let curr = fieldErrors;
9783 let i = 0;
9784 while (i < issue.path.length) {
9785 const el = issue.path[i];
9786 if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
9787 else {
9788 curr[el] = curr[el] || { _errors: [] };
9789 curr[el]._errors.push(mapper(issue));
9790 }
9791 curr = curr[el];
9792 i++;
9793 }
9794 }
9795 };
9796 processError(this);
9797 return fieldErrors;
9798 }
9799 static assert(value) {
9800 if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
9801 }
9802 toString() {
9803 return this.message;
9804 }
9805 get message() {
9806 return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
9807 }
9808 get isEmpty() {
9809 return this.issues.length === 0;
9810 }
9811 flatten(mapper = (issue) => issue.message) {
9812 const fieldErrors = {};
9813 const formErrors = [];
9814 for (const sub of this.issues) if (sub.path.length > 0) {
9815 const firstEl = sub.path[0];
9816 fieldErrors[firstEl] = fieldErrors[firstEl] || [];
9817 fieldErrors[firstEl].push(mapper(sub));
9818 } else formErrors.push(mapper(sub));
9819 return {
9820 formErrors,
9821 fieldErrors
9822 };
9823 }
9824 get formErrors() {
9825 return this.flatten();
9826 }
9827 };
9828 ZodError.create = (issues) => {
9829 return new ZodError(issues);
9830 };
9831
9832 //#endregion
9833 //#region node_modules/zod/v3/locales/en.js
9834 var errorMap = (issue, _ctx) => {
9835 let message;
9836 switch (issue.code) {
9837 case ZodIssueCode.invalid_type:
9838 if (issue.received === ZodParsedType.undefined) message = "Required";
9839 else message = `Expected ${issue.expected}, received ${issue.received}`;
9840 break;
9841 case ZodIssueCode.invalid_literal:
9842 message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
9843 break;
9844 case ZodIssueCode.unrecognized_keys:
9845 message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
9846 break;
9847 case ZodIssueCode.invalid_union:
9848 message = `Invalid input`;
9849 break;
9850 case ZodIssueCode.invalid_union_discriminator:
9851 message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
9852 break;
9853 case ZodIssueCode.invalid_enum_value:
9854 message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
9855 break;
9856 case ZodIssueCode.invalid_arguments:
9857 message = `Invalid function arguments`;
9858 break;
9859 case ZodIssueCode.invalid_return_type:
9860 message = `Invalid function return type`;
9861 break;
9862 case ZodIssueCode.invalid_date:
9863 message = `Invalid date`;
9864 break;
9865 case ZodIssueCode.invalid_string:
9866 if (typeof issue.validation === "object") if ("includes" in issue.validation) {
9867 message = `Invalid input: must include "${issue.validation.includes}"`;
9868 if (typeof issue.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
9869 } else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`;
9870 else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`;
9871 else util.assertNever(issue.validation);
9872 else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
9873 else message = "Invalid";
9874 break;
9875 case ZodIssueCode.too_small:
9876 if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
9877 else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
9878 else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
9879 else if (issue.type === "bigint") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
9880 else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
9881 else message = "Invalid input";
9882 break;
9883 case ZodIssueCode.too_big:
9884 if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
9885 else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
9886 else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
9887 else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
9888 else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
9889 else message = "Invalid input";
9890 break;
9891 case ZodIssueCode.custom:
9892 message = `Invalid input`;
9893 break;
9894 case ZodIssueCode.invalid_intersection_types:
9895 message = `Intersection results could not be merged`;
9896 break;
9897 case ZodIssueCode.not_multiple_of:
9898 message = `Number must be a multiple of ${issue.multipleOf}`;
9899 break;
9900 case ZodIssueCode.not_finite:
9901 message = "Number must be finite";
9902 break;
9903 default:
9904 message = _ctx.defaultError;
9905 util.assertNever(issue);
9906 }
9907 return { message };
9908 };
9909
9910 //#endregion
9911 //#region node_modules/zod/v3/errors.js
9912 var overrideErrorMap = errorMap;
9913 function getErrorMap() {
9914 return overrideErrorMap;
9915 }
9916
9917 //#endregion
9918 //#region node_modules/zod/v3/helpers/parseUtil.js
9919 var makeIssue = (params) => {
9920 const { data, path, errorMaps, issueData } = params;
9921 const fullPath = [...path, ...issueData.path || []];
9922 const fullIssue = {
9923 ...issueData,
9924 path: fullPath
9925 };
9926 if (issueData.message !== void 0) return {
9927 ...issueData,
9928 path: fullPath,
9929 message: issueData.message
9930 };
9931 let errorMessage = "";
9932 const maps = errorMaps.filter((m) => !!m).slice().reverse();
9933 for (const map of maps) errorMessage = map(fullIssue, {
9934 data,
9935 defaultError: errorMessage
9936 }).message;
9937 return {
9938 ...issueData,
9939 path: fullPath,
9940 message: errorMessage
9941 };
9942 };
9943 function addIssueToContext(ctx, issueData) {
9944 const overrideMap = getErrorMap();
9945 const issue = makeIssue({
9946 issueData,
9947 data: ctx.data,
9948 path: ctx.path,
9949 errorMaps: [
9950 ctx.common.contextualErrorMap,
9951 ctx.schemaErrorMap,
9952 overrideMap,
9953 overrideMap === errorMap ? void 0 : errorMap
9954 ].filter((x) => !!x)
9955 });
9956 ctx.common.issues.push(issue);
9957 }
9958 var ParseStatus = class ParseStatus {
9959 constructor() {
9960 this.value = "valid";
9961 }
9962 dirty() {
9963 if (this.value === "valid") this.value = "dirty";
9964 }
9965 abort() {
9966 if (this.value !== "aborted") this.value = "aborted";
9967 }
9968 static mergeArray(status, results) {
9969 const arrayValue = [];
9970 for (const s of results) {
9971 if (s.status === "aborted") return INVALID;
9972 if (s.status === "dirty") status.dirty();
9973 arrayValue.push(s.value);
9974 }
9975 return {
9976 status: status.value,
9977 value: arrayValue
9978 };
9979 }
9980 static async mergeObjectAsync(status, pairs) {
9981 const syncPairs = [];
9982 for (const pair of pairs) {
9983 const key = await pair.key;
9984 const value = await pair.value;
9985 syncPairs.push({
9986 key,
9987 value
9988 });
9989 }
9990 return ParseStatus.mergeObjectSync(status, syncPairs);
9991 }
9992 static mergeObjectSync(status, pairs) {
9993 const finalObject = {};
9994 for (const pair of pairs) {
9995 const { key, value } = pair;
9996 if (key.status === "aborted") return INVALID;
9997 if (value.status === "aborted") return INVALID;
9998 if (key.status === "dirty") status.dirty();
9999 if (value.status === "dirty") status.dirty();
10000 if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
10001 }
10002 return {
10003 status: status.value,
10004 value: finalObject
10005 };
10006 }
10007 };
10008 var INVALID = Object.freeze({ status: "aborted" });
10009 var DIRTY = (value) => ({
10010 status: "dirty",
10011 value
10012 });
10013 var OK = (value) => ({
10014 status: "valid",
10015 value
10016 });
10017 var isAborted = (x) => x.status === "aborted";
10018 var isDirty = (x) => x.status === "dirty";
10019 var isValid = (x) => x.status === "valid";
10020 var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
10021
10022 //#endregion
10023 //#region node_modules/zod/v3/helpers/errorUtil.js
10024 var errorUtil;
10025 (function(errorUtil) {
10026 errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
10027 errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
10028 })(errorUtil || (errorUtil = {}));
10029
10030 //#endregion
10031 //#region node_modules/zod/v3/types.js
10032 var ParseInputLazyPath = class {
10033 constructor(parent, value, path, key) {
10034 this._cachedPath = [];
10035 this.parent = parent;
10036 this.data = value;
10037 this._path = path;
10038 this._key = key;
10039 }
10040 get path() {
10041 if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
10042 else this._cachedPath.push(...this._path, this._key);
10043 return this._cachedPath;
10044 }
10045 };
10046 var handleResult = (ctx, result) => {
10047 if (isValid(result)) return {
10048 success: true,
10049 data: result.value
10050 };
10051 else {
10052 if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
10053 return {
10054 success: false,
10055 get error() {
10056 if (this._error) return this._error;
10057 const error = new ZodError(ctx.common.issues);
10058 this._error = error;
10059 return this._error;
10060 }
10061 };
10062 }
10063 };
10064 function processCreateParams(params) {
10065 if (!params) return {};
10066 const { errorMap, invalid_type_error, required_error, description } = params;
10067 if (errorMap && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
10068 if (errorMap) return {
10069 errorMap,
10070 description
10071 };
10072 const customMap = (iss, ctx) => {
10073 const { message } = params;
10074 if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError };
10075 if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError };
10076 if (iss.code !== "invalid_type") return { message: ctx.defaultError };
10077 return { message: message ?? invalid_type_error ?? ctx.defaultError };
10078 };
10079 return {
10080 errorMap: customMap,
10081 description
10082 };
10083 }
10084 var ZodType = class {
10085 get description() {
10086 return this._def.description;
10087 }
10088 _getType(input) {
10089 return getParsedType(input.data);
10090 }
10091 _getOrReturnCtx(input, ctx) {
10092 return ctx || {
10093 common: input.parent.common,
10094 data: input.data,
10095 parsedType: getParsedType(input.data),
10096 schemaErrorMap: this._def.errorMap,
10097 path: input.path,
10098 parent: input.parent
10099 };
10100 }
10101 _processInputParams(input) {
10102 return {
10103 status: new ParseStatus(),
10104 ctx: {
10105 common: input.parent.common,
10106 data: input.data,
10107 parsedType: getParsedType(input.data),
10108 schemaErrorMap: this._def.errorMap,
10109 path: input.path,
10110 parent: input.parent
10111 }
10112 };
10113 }
10114 _parseSync(input) {
10115 const result = this._parse(input);
10116 if (isAsync(result)) throw new Error("Synchronous parse encountered promise.");
10117 return result;
10118 }
10119 _parseAsync(input) {
10120 const result = this._parse(input);
10121 return Promise.resolve(result);
10122 }
10123 parse(data, params) {
10124 const result = this.safeParse(data, params);
10125 if (result.success) return result.data;
10126 throw result.error;
10127 }
10128 safeParse(data, params) {
10129 const ctx = {
10130 common: {
10131 issues: [],
10132 async: params?.async ?? false,
10133 contextualErrorMap: params?.errorMap
10134 },
10135 path: params?.path || [],
10136 schemaErrorMap: this._def.errorMap,
10137 parent: null,
10138 data,
10139 parsedType: getParsedType(data)
10140 };
10141 const result = this._parseSync({
10142 data,
10143 path: ctx.path,
10144 parent: ctx
10145 });
10146 return handleResult(ctx, result);
10147 }
10148 "~validate"(data) {
10149 const ctx = {
10150 common: {
10151 issues: [],
10152 async: !!this["~standard"].async
10153 },
10154 path: [],
10155 schemaErrorMap: this._def.errorMap,
10156 parent: null,
10157 data,
10158 parsedType: getParsedType(data)
10159 };
10160 if (!this["~standard"].async) try {
10161 const result = this._parseSync({
10162 data,
10163 path: [],
10164 parent: ctx
10165 });
10166 return isValid(result) ? { value: result.value } : { issues: ctx.common.issues };
10167 } catch (err) {
10168 if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
10169 ctx.common = {
10170 issues: [],
10171 async: true
10172 };
10173 }
10174 return this._parseAsync({
10175 data,
10176 path: [],
10177 parent: ctx
10178 }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues });
10179 }
10180 async parseAsync(data, params) {
10181 const result = await this.safeParseAsync(data, params);
10182 if (result.success) return result.data;
10183 throw result.error;
10184 }
10185 async safeParseAsync(data, params) {
10186 const ctx = {
10187 common: {
10188 issues: [],
10189 contextualErrorMap: params?.errorMap,
10190 async: true
10191 },
10192 path: params?.path || [],
10193 schemaErrorMap: this._def.errorMap,
10194 parent: null,
10195 data,
10196 parsedType: getParsedType(data)
10197 };
10198 const maybeAsyncResult = this._parse({
10199 data,
10200 path: ctx.path,
10201 parent: ctx
10202 });
10203 const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
10204 return handleResult(ctx, result);
10205 }
10206 refine(check, message) {
10207 const getIssueProperties = (val) => {
10208 if (typeof message === "string" || typeof message === "undefined") return { message };
10209 else if (typeof message === "function") return message(val);
10210 else return message;
10211 };
10212 return this._refinement((val, ctx) => {
10213 const result = check(val);
10214 const setError = () => ctx.addIssue({
10215 code: ZodIssueCode.custom,
10216 ...getIssueProperties(val)
10217 });
10218 if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data) => {
10219 if (!data) {
10220 setError();
10221 return false;
10222 } else return true;
10223 });
10224 if (!result) {
10225 setError();
10226 return false;
10227 } else return true;
10228 });
10229 }
10230 refinement(check, refinementData) {
10231 return this._refinement((val, ctx) => {
10232 if (!check(val)) {
10233 ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
10234 return false;
10235 } else return true;
10236 });
10237 }
10238 _refinement(refinement) {
10239 return new ZodEffects({
10240 schema: this,
10241 typeName: ZodFirstPartyTypeKind.ZodEffects,
10242 effect: {
10243 type: "refinement",
10244 refinement
10245 }
10246 });
10247 }
10248 superRefine(refinement) {
10249 return this._refinement(refinement);
10250 }
10251 constructor(def) {
10252 /** Alias of safeParseAsync */
10253 this.spa = this.safeParseAsync;
10254 this._def = def;
10255 this.parse = this.parse.bind(this);
10256 this.safeParse = this.safeParse.bind(this);
10257 this.parseAsync = this.parseAsync.bind(this);
10258 this.safeParseAsync = this.safeParseAsync.bind(this);
10259 this.spa = this.spa.bind(this);
10260 this.refine = this.refine.bind(this);
10261 this.refinement = this.refinement.bind(this);
10262 this.superRefine = this.superRefine.bind(this);
10263 this.optional = this.optional.bind(this);
10264 this.nullable = this.nullable.bind(this);
10265 this.nullish = this.nullish.bind(this);
10266 this.array = this.array.bind(this);
10267 this.promise = this.promise.bind(this);
10268 this.or = this.or.bind(this);
10269 this.and = this.and.bind(this);
10270 this.transform = this.transform.bind(this);
10271 this.brand = this.brand.bind(this);
10272 this.default = this.default.bind(this);
10273 this.catch = this.catch.bind(this);
10274 this.describe = this.describe.bind(this);
10275 this.pipe = this.pipe.bind(this);
10276 this.readonly = this.readonly.bind(this);
10277 this.isNullable = this.isNullable.bind(this);
10278 this.isOptional = this.isOptional.bind(this);
10279 this["~standard"] = {
10280 version: 1,
10281 vendor: "zod",
10282 validate: (data) => this["~validate"](data)
10283 };
10284 }
10285 optional() {
10286 return ZodOptional.create(this, this._def);
10287 }
10288 nullable() {
10289 return ZodNullable.create(this, this._def);
10290 }
10291 nullish() {
10292 return this.nullable().optional();
10293 }
10294 array() {
10295 return ZodArray.create(this);
10296 }
10297 promise() {
10298 return ZodPromise.create(this, this._def);
10299 }
10300 or(option) {
10301 return ZodUnion.create([this, option], this._def);
10302 }
10303 and(incoming) {
10304 return ZodIntersection.create(this, incoming, this._def);
10305 }
10306 transform(transform) {
10307 return new ZodEffects({
10308 ...processCreateParams(this._def),
10309 schema: this,
10310 typeName: ZodFirstPartyTypeKind.ZodEffects,
10311 effect: {
10312 type: "transform",
10313 transform
10314 }
10315 });
10316 }
10317 default(def) {
10318 const defaultValueFunc = typeof def === "function" ? def : () => def;
10319 return new ZodDefault({
10320 ...processCreateParams(this._def),
10321 innerType: this,
10322 defaultValue: defaultValueFunc,
10323 typeName: ZodFirstPartyTypeKind.ZodDefault
10324 });
10325 }
10326 brand() {
10327 return new ZodBranded({
10328 typeName: ZodFirstPartyTypeKind.ZodBranded,
10329 type: this,
10330 ...processCreateParams(this._def)
10331 });
10332 }
10333 catch(def) {
10334 const catchValueFunc = typeof def === "function" ? def : () => def;
10335 return new ZodCatch({
10336 ...processCreateParams(this._def),
10337 innerType: this,
10338 catchValue: catchValueFunc,
10339 typeName: ZodFirstPartyTypeKind.ZodCatch
10340 });
10341 }
10342 describe(description) {
10343 const This = this.constructor;
10344 return new This({
10345 ...this._def,
10346 description
10347 });
10348 }
10349 pipe(target) {
10350 return ZodPipeline.create(this, target);
10351 }
10352 readonly() {
10353 return ZodReadonly.create(this);
10354 }
10355 isOptional() {
10356 return this.safeParse(void 0).success;
10357 }
10358 isNullable() {
10359 return this.safeParse(null).success;
10360 }
10361 };
10362 var cuidRegex = /^c[^\s-]{8,}$/i;
10363 var cuid2Regex = /^[0-9a-z]+$/;
10364 var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
10365 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;
10366 var nanoidRegex = /^[a-z0-9_-]{21}$/i;
10367 var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
10368 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)?)??$/;
10369 var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
10370 var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
10371 var emojiRegex$2;
10372 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])$/;
10373 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])$/;
10374 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]))$/;
10375 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])$/;
10376 var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
10377 var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
10378 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])))`;
10379 var dateRegex = new RegExp(`^${dateRegexSource}$`);
10380 function timeRegexSource(args) {
10381 let secondsRegexSource = `[0-5]\\d`;
10382 if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
10383 else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
10384 const secondsQuantifier = args.precision ? "+" : "?";
10385 return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
10386 }
10387 function timeRegex(args) {
10388 return new RegExp(`^${timeRegexSource(args)}$`);
10389 }
10390 function datetimeRegex(args) {
10391 let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
10392 const opts = [];
10393 opts.push(args.local ? `Z?` : `Z`);
10394 if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`);
10395 regex = `${regex}(${opts.join("|")})`;
10396 return new RegExp(`^${regex}$`);
10397 }
10398 function isValidIP(ip, version) {
10399 if ((version === "v4" || !version) && ipv4Regex.test(ip)) return true;
10400 if ((version === "v6" || !version) && ipv6Regex.test(ip)) return true;
10401 return false;
10402 }
10403 function isValidJWT(jwt, alg) {
10404 if (!jwtRegex.test(jwt)) return false;
10405 try {
10406 const [header] = jwt.split(".");
10407 if (!header) return false;
10408 const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
10409 const decoded = JSON.parse(atob(base64));
10410 if (typeof decoded !== "object" || decoded === null) return false;
10411 if ("typ" in decoded && decoded?.typ !== "JWT") return false;
10412 if (!decoded.alg) return false;
10413 if (alg && decoded.alg !== alg) return false;
10414 return true;
10415 } catch {
10416 return false;
10417 }
10418 }
10419 function isValidCidr(ip, version) {
10420 if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) return true;
10421 if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) return true;
10422 return false;
10423 }
10424 var ZodString = class ZodString extends ZodType {
10425 _parse(input) {
10426 if (this._def.coerce) input.data = String(input.data);
10427 if (this._getType(input) !== ZodParsedType.string) {
10428 const ctx = this._getOrReturnCtx(input);
10429 addIssueToContext(ctx, {
10430 code: ZodIssueCode.invalid_type,
10431 expected: ZodParsedType.string,
10432 received: ctx.parsedType
10433 });
10434 return INVALID;
10435 }
10436 const status = new ParseStatus();
10437 let ctx = void 0;
10438 for (const check of this._def.checks) if (check.kind === "min") {
10439 if (input.data.length < check.value) {
10440 ctx = this._getOrReturnCtx(input, ctx);
10441 addIssueToContext(ctx, {
10442 code: ZodIssueCode.too_small,
10443 minimum: check.value,
10444 type: "string",
10445 inclusive: true,
10446 exact: false,
10447 message: check.message
10448 });
10449 status.dirty();
10450 }
10451 } else if (check.kind === "max") {
10452 if (input.data.length > check.value) {
10453 ctx = this._getOrReturnCtx(input, ctx);
10454 addIssueToContext(ctx, {
10455 code: ZodIssueCode.too_big,
10456 maximum: check.value,
10457 type: "string",
10458 inclusive: true,
10459 exact: false,
10460 message: check.message
10461 });
10462 status.dirty();
10463 }
10464 } else if (check.kind === "length") {
10465 const tooBig = input.data.length > check.value;
10466 const tooSmall = input.data.length < check.value;
10467 if (tooBig || tooSmall) {
10468 ctx = this._getOrReturnCtx(input, ctx);
10469 if (tooBig) addIssueToContext(ctx, {
10470 code: ZodIssueCode.too_big,
10471 maximum: check.value,
10472 type: "string",
10473 inclusive: true,
10474 exact: true,
10475 message: check.message
10476 });
10477 else if (tooSmall) addIssueToContext(ctx, {
10478 code: ZodIssueCode.too_small,
10479 minimum: check.value,
10480 type: "string",
10481 inclusive: true,
10482 exact: true,
10483 message: check.message
10484 });
10485 status.dirty();
10486 }
10487 } else if (check.kind === "email") {
10488 if (!emailRegex.test(input.data)) {
10489 ctx = this._getOrReturnCtx(input, ctx);
10490 addIssueToContext(ctx, {
10491 validation: "email",
10492 code: ZodIssueCode.invalid_string,
10493 message: check.message
10494 });
10495 status.dirty();
10496 }
10497 } else if (check.kind === "emoji") {
10498 if (!emojiRegex$2) emojiRegex$2 = new RegExp(_emojiRegex, "u");
10499 if (!emojiRegex$2.test(input.data)) {
10500 ctx = this._getOrReturnCtx(input, ctx);
10501 addIssueToContext(ctx, {
10502 validation: "emoji",
10503 code: ZodIssueCode.invalid_string,
10504 message: check.message
10505 });
10506 status.dirty();
10507 }
10508 } else if (check.kind === "uuid") {
10509 if (!uuidRegex.test(input.data)) {
10510 ctx = this._getOrReturnCtx(input, ctx);
10511 addIssueToContext(ctx, {
10512 validation: "uuid",
10513 code: ZodIssueCode.invalid_string,
10514 message: check.message
10515 });
10516 status.dirty();
10517 }
10518 } else if (check.kind === "nanoid") {
10519 if (!nanoidRegex.test(input.data)) {
10520 ctx = this._getOrReturnCtx(input, ctx);
10521 addIssueToContext(ctx, {
10522 validation: "nanoid",
10523 code: ZodIssueCode.invalid_string,
10524 message: check.message
10525 });
10526 status.dirty();
10527 }
10528 } else if (check.kind === "cuid") {
10529 if (!cuidRegex.test(input.data)) {
10530 ctx = this._getOrReturnCtx(input, ctx);
10531 addIssueToContext(ctx, {
10532 validation: "cuid",
10533 code: ZodIssueCode.invalid_string,
10534 message: check.message
10535 });
10536 status.dirty();
10537 }
10538 } else if (check.kind === "cuid2") {
10539 if (!cuid2Regex.test(input.data)) {
10540 ctx = this._getOrReturnCtx(input, ctx);
10541 addIssueToContext(ctx, {
10542 validation: "cuid2",
10543 code: ZodIssueCode.invalid_string,
10544 message: check.message
10545 });
10546 status.dirty();
10547 }
10548 } else if (check.kind === "ulid") {
10549 if (!ulidRegex.test(input.data)) {
10550 ctx = this._getOrReturnCtx(input, ctx);
10551 addIssueToContext(ctx, {
10552 validation: "ulid",
10553 code: ZodIssueCode.invalid_string,
10554 message: check.message
10555 });
10556 status.dirty();
10557 }
10558 } else if (check.kind === "url") try {
10559 new URL(input.data);
10560 } catch {
10561 ctx = this._getOrReturnCtx(input, ctx);
10562 addIssueToContext(ctx, {
10563 validation: "url",
10564 code: ZodIssueCode.invalid_string,
10565 message: check.message
10566 });
10567 status.dirty();
10568 }
10569 else if (check.kind === "regex") {
10570 check.regex.lastIndex = 0;
10571 if (!check.regex.test(input.data)) {
10572 ctx = this._getOrReturnCtx(input, ctx);
10573 addIssueToContext(ctx, {
10574 validation: "regex",
10575 code: ZodIssueCode.invalid_string,
10576 message: check.message
10577 });
10578 status.dirty();
10579 }
10580 } else if (check.kind === "trim") input.data = input.data.trim();
10581 else if (check.kind === "includes") {
10582 if (!input.data.includes(check.value, check.position)) {
10583 ctx = this._getOrReturnCtx(input, ctx);
10584 addIssueToContext(ctx, {
10585 code: ZodIssueCode.invalid_string,
10586 validation: {
10587 includes: check.value,
10588 position: check.position
10589 },
10590 message: check.message
10591 });
10592 status.dirty();
10593 }
10594 } else if (check.kind === "toLowerCase") input.data = input.data.toLowerCase();
10595 else if (check.kind === "toUpperCase") input.data = input.data.toUpperCase();
10596 else if (check.kind === "startsWith") {
10597 if (!input.data.startsWith(check.value)) {
10598 ctx = this._getOrReturnCtx(input, ctx);
10599 addIssueToContext(ctx, {
10600 code: ZodIssueCode.invalid_string,
10601 validation: { startsWith: check.value },
10602 message: check.message
10603 });
10604 status.dirty();
10605 }
10606 } else if (check.kind === "endsWith") {
10607 if (!input.data.endsWith(check.value)) {
10608 ctx = this._getOrReturnCtx(input, ctx);
10609 addIssueToContext(ctx, {
10610 code: ZodIssueCode.invalid_string,
10611 validation: { endsWith: check.value },
10612 message: check.message
10613 });
10614 status.dirty();
10615 }
10616 } else if (check.kind === "datetime") {
10617 if (!datetimeRegex(check).test(input.data)) {
10618 ctx = this._getOrReturnCtx(input, ctx);
10619 addIssueToContext(ctx, {
10620 code: ZodIssueCode.invalid_string,
10621 validation: "datetime",
10622 message: check.message
10623 });
10624 status.dirty();
10625 }
10626 } else if (check.kind === "date") {
10627 if (!dateRegex.test(input.data)) {
10628 ctx = this._getOrReturnCtx(input, ctx);
10629 addIssueToContext(ctx, {
10630 code: ZodIssueCode.invalid_string,
10631 validation: "date",
10632 message: check.message
10633 });
10634 status.dirty();
10635 }
10636 } else if (check.kind === "time") {
10637 if (!timeRegex(check).test(input.data)) {
10638 ctx = this._getOrReturnCtx(input, ctx);
10639 addIssueToContext(ctx, {
10640 code: ZodIssueCode.invalid_string,
10641 validation: "time",
10642 message: check.message
10643 });
10644 status.dirty();
10645 }
10646 } else if (check.kind === "duration") {
10647 if (!durationRegex.test(input.data)) {
10648 ctx = this._getOrReturnCtx(input, ctx);
10649 addIssueToContext(ctx, {
10650 validation: "duration",
10651 code: ZodIssueCode.invalid_string,
10652 message: check.message
10653 });
10654 status.dirty();
10655 }
10656 } else if (check.kind === "ip") {
10657 if (!isValidIP(input.data, check.version)) {
10658 ctx = this._getOrReturnCtx(input, ctx);
10659 addIssueToContext(ctx, {
10660 validation: "ip",
10661 code: ZodIssueCode.invalid_string,
10662 message: check.message
10663 });
10664 status.dirty();
10665 }
10666 } else if (check.kind === "jwt") {
10667 if (!isValidJWT(input.data, check.alg)) {
10668 ctx = this._getOrReturnCtx(input, ctx);
10669 addIssueToContext(ctx, {
10670 validation: "jwt",
10671 code: ZodIssueCode.invalid_string,
10672 message: check.message
10673 });
10674 status.dirty();
10675 }
10676 } else if (check.kind === "cidr") {
10677 if (!isValidCidr(input.data, check.version)) {
10678 ctx = this._getOrReturnCtx(input, ctx);
10679 addIssueToContext(ctx, {
10680 validation: "cidr",
10681 code: ZodIssueCode.invalid_string,
10682 message: check.message
10683 });
10684 status.dirty();
10685 }
10686 } else if (check.kind === "base64") {
10687 if (!base64Regex.test(input.data)) {
10688 ctx = this._getOrReturnCtx(input, ctx);
10689 addIssueToContext(ctx, {
10690 validation: "base64",
10691 code: ZodIssueCode.invalid_string,
10692 message: check.message
10693 });
10694 status.dirty();
10695 }
10696 } else if (check.kind === "base64url") {
10697 if (!base64urlRegex.test(input.data)) {
10698 ctx = this._getOrReturnCtx(input, ctx);
10699 addIssueToContext(ctx, {
10700 validation: "base64url",
10701 code: ZodIssueCode.invalid_string,
10702 message: check.message
10703 });
10704 status.dirty();
10705 }
10706 } else util.assertNever(check);
10707 return {
10708 status: status.value,
10709 value: input.data
10710 };
10711 }
10712 _regex(regex, validation, message) {
10713 return this.refinement((data) => regex.test(data), {
10714 validation,
10715 code: ZodIssueCode.invalid_string,
10716 ...errorUtil.errToObj(message)
10717 });
10718 }
10719 _addCheck(check) {
10720 return new ZodString({
10721 ...this._def,
10722 checks: [...this._def.checks, check]
10723 });
10724 }
10725 email(message) {
10726 return this._addCheck({
10727 kind: "email",
10728 ...errorUtil.errToObj(message)
10729 });
10730 }
10731 url(message) {
10732 return this._addCheck({
10733 kind: "url",
10734 ...errorUtil.errToObj(message)
10735 });
10736 }
10737 emoji(message) {
10738 return this._addCheck({
10739 kind: "emoji",
10740 ...errorUtil.errToObj(message)
10741 });
10742 }
10743 uuid(message) {
10744 return this._addCheck({
10745 kind: "uuid",
10746 ...errorUtil.errToObj(message)
10747 });
10748 }
10749 nanoid(message) {
10750 return this._addCheck({
10751 kind: "nanoid",
10752 ...errorUtil.errToObj(message)
10753 });
10754 }
10755 cuid(message) {
10756 return this._addCheck({
10757 kind: "cuid",
10758 ...errorUtil.errToObj(message)
10759 });
10760 }
10761 cuid2(message) {
10762 return this._addCheck({
10763 kind: "cuid2",
10764 ...errorUtil.errToObj(message)
10765 });
10766 }
10767 ulid(message) {
10768 return this._addCheck({
10769 kind: "ulid",
10770 ...errorUtil.errToObj(message)
10771 });
10772 }
10773 base64(message) {
10774 return this._addCheck({
10775 kind: "base64",
10776 ...errorUtil.errToObj(message)
10777 });
10778 }
10779 base64url(message) {
10780 return this._addCheck({
10781 kind: "base64url",
10782 ...errorUtil.errToObj(message)
10783 });
10784 }
10785 jwt(options) {
10786 return this._addCheck({
10787 kind: "jwt",
10788 ...errorUtil.errToObj(options)
10789 });
10790 }
10791 ip(options) {
10792 return this._addCheck({
10793 kind: "ip",
10794 ...errorUtil.errToObj(options)
10795 });
10796 }
10797 cidr(options) {
10798 return this._addCheck({
10799 kind: "cidr",
10800 ...errorUtil.errToObj(options)
10801 });
10802 }
10803 datetime(options) {
10804 if (typeof options === "string") return this._addCheck({
10805 kind: "datetime",
10806 precision: null,
10807 offset: false,
10808 local: false,
10809 message: options
10810 });
10811 return this._addCheck({
10812 kind: "datetime",
10813 precision: typeof options?.precision === "undefined" ? null : options?.precision,
10814 offset: options?.offset ?? false,
10815 local: options?.local ?? false,
10816 ...errorUtil.errToObj(options?.message)
10817 });
10818 }
10819 date(message) {
10820 return this._addCheck({
10821 kind: "date",
10822 message
10823 });
10824 }
10825 time(options) {
10826 if (typeof options === "string") return this._addCheck({
10827 kind: "time",
10828 precision: null,
10829 message: options
10830 });
10831 return this._addCheck({
10832 kind: "time",
10833 precision: typeof options?.precision === "undefined" ? null : options?.precision,
10834 ...errorUtil.errToObj(options?.message)
10835 });
10836 }
10837 duration(message) {
10838 return this._addCheck({
10839 kind: "duration",
10840 ...errorUtil.errToObj(message)
10841 });
10842 }
10843 regex(regex, message) {
10844 return this._addCheck({
10845 kind: "regex",
10846 regex,
10847 ...errorUtil.errToObj(message)
10848 });
10849 }
10850 includes(value, options) {
10851 return this._addCheck({
10852 kind: "includes",
10853 value,
10854 position: options?.position,
10855 ...errorUtil.errToObj(options?.message)
10856 });
10857 }
10858 startsWith(value, message) {
10859 return this._addCheck({
10860 kind: "startsWith",
10861 value,
10862 ...errorUtil.errToObj(message)
10863 });
10864 }
10865 endsWith(value, message) {
10866 return this._addCheck({
10867 kind: "endsWith",
10868 value,
10869 ...errorUtil.errToObj(message)
10870 });
10871 }
10872 min(minLength, message) {
10873 return this._addCheck({
10874 kind: "min",
10875 value: minLength,
10876 ...errorUtil.errToObj(message)
10877 });
10878 }
10879 max(maxLength, message) {
10880 return this._addCheck({
10881 kind: "max",
10882 value: maxLength,
10883 ...errorUtil.errToObj(message)
10884 });
10885 }
10886 length(len, message) {
10887 return this._addCheck({
10888 kind: "length",
10889 value: len,
10890 ...errorUtil.errToObj(message)
10891 });
10892 }
10893 /**
10894 * Equivalent to `.min(1)`
10895 */
10896 nonempty(message) {
10897 return this.min(1, errorUtil.errToObj(message));
10898 }
10899 trim() {
10900 return new ZodString({
10901 ...this._def,
10902 checks: [...this._def.checks, { kind: "trim" }]
10903 });
10904 }
10905 toLowerCase() {
10906 return new ZodString({
10907 ...this._def,
10908 checks: [...this._def.checks, { kind: "toLowerCase" }]
10909 });
10910 }
10911 toUpperCase() {
10912 return new ZodString({
10913 ...this._def,
10914 checks: [...this._def.checks, { kind: "toUpperCase" }]
10915 });
10916 }
10917 get isDatetime() {
10918 return !!this._def.checks.find((ch) => ch.kind === "datetime");
10919 }
10920 get isDate() {
10921 return !!this._def.checks.find((ch) => ch.kind === "date");
10922 }
10923 get isTime() {
10924 return !!this._def.checks.find((ch) => ch.kind === "time");
10925 }
10926 get isDuration() {
10927 return !!this._def.checks.find((ch) => ch.kind === "duration");
10928 }
10929 get isEmail() {
10930 return !!this._def.checks.find((ch) => ch.kind === "email");
10931 }
10932 get isURL() {
10933 return !!this._def.checks.find((ch) => ch.kind === "url");
10934 }
10935 get isEmoji() {
10936 return !!this._def.checks.find((ch) => ch.kind === "emoji");
10937 }
10938 get isUUID() {
10939 return !!this._def.checks.find((ch) => ch.kind === "uuid");
10940 }
10941 get isNANOID() {
10942 return !!this._def.checks.find((ch) => ch.kind === "nanoid");
10943 }
10944 get isCUID() {
10945 return !!this._def.checks.find((ch) => ch.kind === "cuid");
10946 }
10947 get isCUID2() {
10948 return !!this._def.checks.find((ch) => ch.kind === "cuid2");
10949 }
10950 get isULID() {
10951 return !!this._def.checks.find((ch) => ch.kind === "ulid");
10952 }
10953 get isIP() {
10954 return !!this._def.checks.find((ch) => ch.kind === "ip");
10955 }
10956 get isCIDR() {
10957 return !!this._def.checks.find((ch) => ch.kind === "cidr");
10958 }
10959 get isBase64() {
10960 return !!this._def.checks.find((ch) => ch.kind === "base64");
10961 }
10962 get isBase64url() {
10963 return !!this._def.checks.find((ch) => ch.kind === "base64url");
10964 }
10965 get minLength() {
10966 let min = null;
10967 for (const ch of this._def.checks) if (ch.kind === "min") {
10968 if (min === null || ch.value > min) min = ch.value;
10969 }
10970 return min;
10971 }
10972 get maxLength() {
10973 let max = null;
10974 for (const ch of this._def.checks) if (ch.kind === "max") {
10975 if (max === null || ch.value < max) max = ch.value;
10976 }
10977 return max;
10978 }
10979 };
10980 ZodString.create = (params) => {
10981 return new ZodString({
10982 checks: [],
10983 typeName: ZodFirstPartyTypeKind.ZodString,
10984 coerce: params?.coerce ?? false,
10985 ...processCreateParams(params)
10986 });
10987 };
10988 function floatSafeRemainder(val, step) {
10989 const valDecCount = (val.toString().split(".")[1] || "").length;
10990 const stepDecCount = (step.toString().split(".")[1] || "").length;
10991 const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
10992 return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
10993 }
10994 var ZodNumber = class ZodNumber extends ZodType {
10995 constructor() {
10996 super(...arguments);
10997 this.min = this.gte;
10998 this.max = this.lte;
10999 this.step = this.multipleOf;
11000 }
11001 _parse(input) {
11002 if (this._def.coerce) input.data = Number(input.data);
11003 if (this._getType(input) !== ZodParsedType.number) {
11004 const ctx = this._getOrReturnCtx(input);
11005 addIssueToContext(ctx, {
11006 code: ZodIssueCode.invalid_type,
11007 expected: ZodParsedType.number,
11008 received: ctx.parsedType
11009 });
11010 return INVALID;
11011 }
11012 let ctx = void 0;
11013 const status = new ParseStatus();
11014 for (const check of this._def.checks) if (check.kind === "int") {
11015 if (!util.isInteger(input.data)) {
11016 ctx = this._getOrReturnCtx(input, ctx);
11017 addIssueToContext(ctx, {
11018 code: ZodIssueCode.invalid_type,
11019 expected: "integer",
11020 received: "float",
11021 message: check.message
11022 });
11023 status.dirty();
11024 }
11025 } else if (check.kind === "min") {
11026 if (check.inclusive ? input.data < check.value : input.data <= check.value) {
11027 ctx = this._getOrReturnCtx(input, ctx);
11028 addIssueToContext(ctx, {
11029 code: ZodIssueCode.too_small,
11030 minimum: check.value,
11031 type: "number",
11032 inclusive: check.inclusive,
11033 exact: false,
11034 message: check.message
11035 });
11036 status.dirty();
11037 }
11038 } else if (check.kind === "max") {
11039 if (check.inclusive ? input.data > check.value : input.data >= check.value) {
11040 ctx = this._getOrReturnCtx(input, ctx);
11041 addIssueToContext(ctx, {
11042 code: ZodIssueCode.too_big,
11043 maximum: check.value,
11044 type: "number",
11045 inclusive: check.inclusive,
11046 exact: false,
11047 message: check.message
11048 });
11049 status.dirty();
11050 }
11051 } else if (check.kind === "multipleOf") {
11052 if (floatSafeRemainder(input.data, check.value) !== 0) {
11053 ctx = this._getOrReturnCtx(input, ctx);
11054 addIssueToContext(ctx, {
11055 code: ZodIssueCode.not_multiple_of,
11056 multipleOf: check.value,
11057 message: check.message
11058 });
11059 status.dirty();
11060 }
11061 } else if (check.kind === "finite") {
11062 if (!Number.isFinite(input.data)) {
11063 ctx = this._getOrReturnCtx(input, ctx);
11064 addIssueToContext(ctx, {
11065 code: ZodIssueCode.not_finite,
11066 message: check.message
11067 });
11068 status.dirty();
11069 }
11070 } else util.assertNever(check);
11071 return {
11072 status: status.value,
11073 value: input.data
11074 };
11075 }
11076 gte(value, message) {
11077 return this.setLimit("min", value, true, errorUtil.toString(message));
11078 }
11079 gt(value, message) {
11080 return this.setLimit("min", value, false, errorUtil.toString(message));
11081 }
11082 lte(value, message) {
11083 return this.setLimit("max", value, true, errorUtil.toString(message));
11084 }
11085 lt(value, message) {
11086 return this.setLimit("max", value, false, errorUtil.toString(message));
11087 }
11088 setLimit(kind, value, inclusive, message) {
11089 return new ZodNumber({
11090 ...this._def,
11091 checks: [...this._def.checks, {
11092 kind,
11093 value,
11094 inclusive,
11095 message: errorUtil.toString(message)
11096 }]
11097 });
11098 }
11099 _addCheck(check) {
11100 return new ZodNumber({
11101 ...this._def,
11102 checks: [...this._def.checks, check]
11103 });
11104 }
11105 int(message) {
11106 return this._addCheck({
11107 kind: "int",
11108 message: errorUtil.toString(message)
11109 });
11110 }
11111 positive(message) {
11112 return this._addCheck({
11113 kind: "min",
11114 value: 0,
11115 inclusive: false,
11116 message: errorUtil.toString(message)
11117 });
11118 }
11119 negative(message) {
11120 return this._addCheck({
11121 kind: "max",
11122 value: 0,
11123 inclusive: false,
11124 message: errorUtil.toString(message)
11125 });
11126 }
11127 nonpositive(message) {
11128 return this._addCheck({
11129 kind: "max",
11130 value: 0,
11131 inclusive: true,
11132 message: errorUtil.toString(message)
11133 });
11134 }
11135 nonnegative(message) {
11136 return this._addCheck({
11137 kind: "min",
11138 value: 0,
11139 inclusive: true,
11140 message: errorUtil.toString(message)
11141 });
11142 }
11143 multipleOf(value, message) {
11144 return this._addCheck({
11145 kind: "multipleOf",
11146 value,
11147 message: errorUtil.toString(message)
11148 });
11149 }
11150 finite(message) {
11151 return this._addCheck({
11152 kind: "finite",
11153 message: errorUtil.toString(message)
11154 });
11155 }
11156 safe(message) {
11157 return this._addCheck({
11158 kind: "min",
11159 inclusive: true,
11160 value: Number.MIN_SAFE_INTEGER,
11161 message: errorUtil.toString(message)
11162 })._addCheck({
11163 kind: "max",
11164 inclusive: true,
11165 value: Number.MAX_SAFE_INTEGER,
11166 message: errorUtil.toString(message)
11167 });
11168 }
11169 get minValue() {
11170 let min = null;
11171 for (const ch of this._def.checks) if (ch.kind === "min") {
11172 if (min === null || ch.value > min) min = ch.value;
11173 }
11174 return min;
11175 }
11176 get maxValue() {
11177 let max = null;
11178 for (const ch of this._def.checks) if (ch.kind === "max") {
11179 if (max === null || ch.value < max) max = ch.value;
11180 }
11181 return max;
11182 }
11183 get isInt() {
11184 return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
11185 }
11186 get isFinite() {
11187 let max = null;
11188 let min = null;
11189 for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
11190 else if (ch.kind === "min") {
11191 if (min === null || ch.value > min) min = ch.value;
11192 } else if (ch.kind === "max") {
11193 if (max === null || ch.value < max) max = ch.value;
11194 }
11195 return Number.isFinite(min) && Number.isFinite(max);
11196 }
11197 };
11198 ZodNumber.create = (params) => {
11199 return new ZodNumber({
11200 checks: [],
11201 typeName: ZodFirstPartyTypeKind.ZodNumber,
11202 coerce: params?.coerce || false,
11203 ...processCreateParams(params)
11204 });
11205 };
11206 var ZodBigInt = class ZodBigInt extends ZodType {
11207 constructor() {
11208 super(...arguments);
11209 this.min = this.gte;
11210 this.max = this.lte;
11211 }
11212 _parse(input) {
11213 if (this._def.coerce) try {
11214 input.data = BigInt(input.data);
11215 } catch {
11216 return this._getInvalidInput(input);
11217 }
11218 if (this._getType(input) !== ZodParsedType.bigint) return this._getInvalidInput(input);
11219 let ctx = void 0;
11220 const status = new ParseStatus();
11221 for (const check of this._def.checks) if (check.kind === "min") {
11222 if (check.inclusive ? input.data < check.value : input.data <= check.value) {
11223 ctx = this._getOrReturnCtx(input, ctx);
11224 addIssueToContext(ctx, {
11225 code: ZodIssueCode.too_small,
11226 type: "bigint",
11227 minimum: check.value,
11228 inclusive: check.inclusive,
11229 message: check.message
11230 });
11231 status.dirty();
11232 }
11233 } else if (check.kind === "max") {
11234 if (check.inclusive ? input.data > check.value : input.data >= check.value) {
11235 ctx = this._getOrReturnCtx(input, ctx);
11236 addIssueToContext(ctx, {
11237 code: ZodIssueCode.too_big,
11238 type: "bigint",
11239 maximum: check.value,
11240 inclusive: check.inclusive,
11241 message: check.message
11242 });
11243 status.dirty();
11244 }
11245 } else if (check.kind === "multipleOf") {
11246 if (input.data % check.value !== BigInt(0)) {
11247 ctx = this._getOrReturnCtx(input, ctx);
11248 addIssueToContext(ctx, {
11249 code: ZodIssueCode.not_multiple_of,
11250 multipleOf: check.value,
11251 message: check.message
11252 });
11253 status.dirty();
11254 }
11255 } else util.assertNever(check);
11256 return {
11257 status: status.value,
11258 value: input.data
11259 };
11260 }
11261 _getInvalidInput(input) {
11262 const ctx = this._getOrReturnCtx(input);
11263 addIssueToContext(ctx, {
11264 code: ZodIssueCode.invalid_type,
11265 expected: ZodParsedType.bigint,
11266 received: ctx.parsedType
11267 });
11268 return INVALID;
11269 }
11270 gte(value, message) {
11271 return this.setLimit("min", value, true, errorUtil.toString(message));
11272 }
11273 gt(value, message) {
11274 return this.setLimit("min", value, false, errorUtil.toString(message));
11275 }
11276 lte(value, message) {
11277 return this.setLimit("max", value, true, errorUtil.toString(message));
11278 }
11279 lt(value, message) {
11280 return this.setLimit("max", value, false, errorUtil.toString(message));
11281 }
11282 setLimit(kind, value, inclusive, message) {
11283 return new ZodBigInt({
11284 ...this._def,
11285 checks: [...this._def.checks, {
11286 kind,
11287 value,
11288 inclusive,
11289 message: errorUtil.toString(message)
11290 }]
11291 });
11292 }
11293 _addCheck(check) {
11294 return new ZodBigInt({
11295 ...this._def,
11296 checks: [...this._def.checks, check]
11297 });
11298 }
11299 positive(message) {
11300 return this._addCheck({
11301 kind: "min",
11302 value: BigInt(0),
11303 inclusive: false,
11304 message: errorUtil.toString(message)
11305 });
11306 }
11307 negative(message) {
11308 return this._addCheck({
11309 kind: "max",
11310 value: BigInt(0),
11311 inclusive: false,
11312 message: errorUtil.toString(message)
11313 });
11314 }
11315 nonpositive(message) {
11316 return this._addCheck({
11317 kind: "max",
11318 value: BigInt(0),
11319 inclusive: true,
11320 message: errorUtil.toString(message)
11321 });
11322 }
11323 nonnegative(message) {
11324 return this._addCheck({
11325 kind: "min",
11326 value: BigInt(0),
11327 inclusive: true,
11328 message: errorUtil.toString(message)
11329 });
11330 }
11331 multipleOf(value, message) {
11332 return this._addCheck({
11333 kind: "multipleOf",
11334 value,
11335 message: errorUtil.toString(message)
11336 });
11337 }
11338 get minValue() {
11339 let min = null;
11340 for (const ch of this._def.checks) if (ch.kind === "min") {
11341 if (min === null || ch.value > min) min = ch.value;
11342 }
11343 return min;
11344 }
11345 get maxValue() {
11346 let max = null;
11347 for (const ch of this._def.checks) if (ch.kind === "max") {
11348 if (max === null || ch.value < max) max = ch.value;
11349 }
11350 return max;
11351 }
11352 };
11353 ZodBigInt.create = (params) => {
11354 return new ZodBigInt({
11355 checks: [],
11356 typeName: ZodFirstPartyTypeKind.ZodBigInt,
11357 coerce: params?.coerce ?? false,
11358 ...processCreateParams(params)
11359 });
11360 };
11361 var ZodBoolean = class extends ZodType {
11362 _parse(input) {
11363 if (this._def.coerce) input.data = Boolean(input.data);
11364 if (this._getType(input) !== ZodParsedType.boolean) {
11365 const ctx = this._getOrReturnCtx(input);
11366 addIssueToContext(ctx, {
11367 code: ZodIssueCode.invalid_type,
11368 expected: ZodParsedType.boolean,
11369 received: ctx.parsedType
11370 });
11371 return INVALID;
11372 }
11373 return OK(input.data);
11374 }
11375 };
11376 ZodBoolean.create = (params) => {
11377 return new ZodBoolean({
11378 typeName: ZodFirstPartyTypeKind.ZodBoolean,
11379 coerce: params?.coerce || false,
11380 ...processCreateParams(params)
11381 });
11382 };
11383 var ZodDate = class ZodDate extends ZodType {
11384 _parse(input) {
11385 if (this._def.coerce) input.data = new Date(input.data);
11386 if (this._getType(input) !== ZodParsedType.date) {
11387 const ctx = this._getOrReturnCtx(input);
11388 addIssueToContext(ctx, {
11389 code: ZodIssueCode.invalid_type,
11390 expected: ZodParsedType.date,
11391 received: ctx.parsedType
11392 });
11393 return INVALID;
11394 }
11395 if (Number.isNaN(input.data.getTime())) {
11396 addIssueToContext(this._getOrReturnCtx(input), { code: ZodIssueCode.invalid_date });
11397 return INVALID;
11398 }
11399 const status = new ParseStatus();
11400 let ctx = void 0;
11401 for (const check of this._def.checks) if (check.kind === "min") {
11402 if (input.data.getTime() < check.value) {
11403 ctx = this._getOrReturnCtx(input, ctx);
11404 addIssueToContext(ctx, {
11405 code: ZodIssueCode.too_small,
11406 message: check.message,
11407 inclusive: true,
11408 exact: false,
11409 minimum: check.value,
11410 type: "date"
11411 });
11412 status.dirty();
11413 }
11414 } else if (check.kind === "max") {
11415 if (input.data.getTime() > check.value) {
11416 ctx = this._getOrReturnCtx(input, ctx);
11417 addIssueToContext(ctx, {
11418 code: ZodIssueCode.too_big,
11419 message: check.message,
11420 inclusive: true,
11421 exact: false,
11422 maximum: check.value,
11423 type: "date"
11424 });
11425 status.dirty();
11426 }
11427 } else util.assertNever(check);
11428 return {
11429 status: status.value,
11430 value: new Date(input.data.getTime())
11431 };
11432 }
11433 _addCheck(check) {
11434 return new ZodDate({
11435 ...this._def,
11436 checks: [...this._def.checks, check]
11437 });
11438 }
11439 min(minDate, message) {
11440 return this._addCheck({
11441 kind: "min",
11442 value: minDate.getTime(),
11443 message: errorUtil.toString(message)
11444 });
11445 }
11446 max(maxDate, message) {
11447 return this._addCheck({
11448 kind: "max",
11449 value: maxDate.getTime(),
11450 message: errorUtil.toString(message)
11451 });
11452 }
11453 get minDate() {
11454 let min = null;
11455 for (const ch of this._def.checks) if (ch.kind === "min") {
11456 if (min === null || ch.value > min) min = ch.value;
11457 }
11458 return min != null ? new Date(min) : null;
11459 }
11460 get maxDate() {
11461 let max = null;
11462 for (const ch of this._def.checks) if (ch.kind === "max") {
11463 if (max === null || ch.value < max) max = ch.value;
11464 }
11465 return max != null ? new Date(max) : null;
11466 }
11467 };
11468 ZodDate.create = (params) => {
11469 return new ZodDate({
11470 checks: [],
11471 coerce: params?.coerce || false,
11472 typeName: ZodFirstPartyTypeKind.ZodDate,
11473 ...processCreateParams(params)
11474 });
11475 };
11476 var ZodSymbol = class extends ZodType {
11477 _parse(input) {
11478 if (this._getType(input) !== ZodParsedType.symbol) {
11479 const ctx = this._getOrReturnCtx(input);
11480 addIssueToContext(ctx, {
11481 code: ZodIssueCode.invalid_type,
11482 expected: ZodParsedType.symbol,
11483 received: ctx.parsedType
11484 });
11485 return INVALID;
11486 }
11487 return OK(input.data);
11488 }
11489 };
11490 ZodSymbol.create = (params) => {
11491 return new ZodSymbol({
11492 typeName: ZodFirstPartyTypeKind.ZodSymbol,
11493 ...processCreateParams(params)
11494 });
11495 };
11496 var ZodUndefined = class extends ZodType {
11497 _parse(input) {
11498 if (this._getType(input) !== ZodParsedType.undefined) {
11499 const ctx = this._getOrReturnCtx(input);
11500 addIssueToContext(ctx, {
11501 code: ZodIssueCode.invalid_type,
11502 expected: ZodParsedType.undefined,
11503 received: ctx.parsedType
11504 });
11505 return INVALID;
11506 }
11507 return OK(input.data);
11508 }
11509 };
11510 ZodUndefined.create = (params) => {
11511 return new ZodUndefined({
11512 typeName: ZodFirstPartyTypeKind.ZodUndefined,
11513 ...processCreateParams(params)
11514 });
11515 };
11516 var ZodNull = class extends ZodType {
11517 _parse(input) {
11518 if (this._getType(input) !== ZodParsedType.null) {
11519 const ctx = this._getOrReturnCtx(input);
11520 addIssueToContext(ctx, {
11521 code: ZodIssueCode.invalid_type,
11522 expected: ZodParsedType.null,
11523 received: ctx.parsedType
11524 });
11525 return INVALID;
11526 }
11527 return OK(input.data);
11528 }
11529 };
11530 ZodNull.create = (params) => {
11531 return new ZodNull({
11532 typeName: ZodFirstPartyTypeKind.ZodNull,
11533 ...processCreateParams(params)
11534 });
11535 };
11536 var ZodAny = class extends ZodType {
11537 constructor() {
11538 super(...arguments);
11539 this._any = true;
11540 }
11541 _parse(input) {
11542 return OK(input.data);
11543 }
11544 };
11545 ZodAny.create = (params) => {
11546 return new ZodAny({
11547 typeName: ZodFirstPartyTypeKind.ZodAny,
11548 ...processCreateParams(params)
11549 });
11550 };
11551 var ZodUnknown = class extends ZodType {
11552 constructor() {
11553 super(...arguments);
11554 this._unknown = true;
11555 }
11556 _parse(input) {
11557 return OK(input.data);
11558 }
11559 };
11560 ZodUnknown.create = (params) => {
11561 return new ZodUnknown({
11562 typeName: ZodFirstPartyTypeKind.ZodUnknown,
11563 ...processCreateParams(params)
11564 });
11565 };
11566 var ZodNever = class extends ZodType {
11567 _parse(input) {
11568 const ctx = this._getOrReturnCtx(input);
11569 addIssueToContext(ctx, {
11570 code: ZodIssueCode.invalid_type,
11571 expected: ZodParsedType.never,
11572 received: ctx.parsedType
11573 });
11574 return INVALID;
11575 }
11576 };
11577 ZodNever.create = (params) => {
11578 return new ZodNever({
11579 typeName: ZodFirstPartyTypeKind.ZodNever,
11580 ...processCreateParams(params)
11581 });
11582 };
11583 var ZodVoid = class extends ZodType {
11584 _parse(input) {
11585 if (this._getType(input) !== ZodParsedType.undefined) {
11586 const ctx = this._getOrReturnCtx(input);
11587 addIssueToContext(ctx, {
11588 code: ZodIssueCode.invalid_type,
11589 expected: ZodParsedType.void,
11590 received: ctx.parsedType
11591 });
11592 return INVALID;
11593 }
11594 return OK(input.data);
11595 }
11596 };
11597 ZodVoid.create = (params) => {
11598 return new ZodVoid({
11599 typeName: ZodFirstPartyTypeKind.ZodVoid,
11600 ...processCreateParams(params)
11601 });
11602 };
11603 var ZodArray = class ZodArray extends ZodType {
11604 _parse(input) {
11605 const { ctx, status } = this._processInputParams(input);
11606 const def = this._def;
11607 if (ctx.parsedType !== ZodParsedType.array) {
11608 addIssueToContext(ctx, {
11609 code: ZodIssueCode.invalid_type,
11610 expected: ZodParsedType.array,
11611 received: ctx.parsedType
11612 });
11613 return INVALID;
11614 }
11615 if (def.exactLength !== null) {
11616 const tooBig = ctx.data.length > def.exactLength.value;
11617 const tooSmall = ctx.data.length < def.exactLength.value;
11618 if (tooBig || tooSmall) {
11619 addIssueToContext(ctx, {
11620 code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
11621 minimum: tooSmall ? def.exactLength.value : void 0,
11622 maximum: tooBig ? def.exactLength.value : void 0,
11623 type: "array",
11624 inclusive: true,
11625 exact: true,
11626 message: def.exactLength.message
11627 });
11628 status.dirty();
11629 }
11630 }
11631 if (def.minLength !== null) {
11632 if (ctx.data.length < def.minLength.value) {
11633 addIssueToContext(ctx, {
11634 code: ZodIssueCode.too_small,
11635 minimum: def.minLength.value,
11636 type: "array",
11637 inclusive: true,
11638 exact: false,
11639 message: def.minLength.message
11640 });
11641 status.dirty();
11642 }
11643 }
11644 if (def.maxLength !== null) {
11645 if (ctx.data.length > def.maxLength.value) {
11646 addIssueToContext(ctx, {
11647 code: ZodIssueCode.too_big,
11648 maximum: def.maxLength.value,
11649 type: "array",
11650 inclusive: true,
11651 exact: false,
11652 message: def.maxLength.message
11653 });
11654 status.dirty();
11655 }
11656 }
11657 if (ctx.common.async) return Promise.all([...ctx.data].map((item, i) => {
11658 return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
11659 })).then((result) => {
11660 return ParseStatus.mergeArray(status, result);
11661 });
11662 const result = [...ctx.data].map((item, i) => {
11663 return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
11664 });
11665 return ParseStatus.mergeArray(status, result);
11666 }
11667 get element() {
11668 return this._def.type;
11669 }
11670 min(minLength, message) {
11671 return new ZodArray({
11672 ...this._def,
11673 minLength: {
11674 value: minLength,
11675 message: errorUtil.toString(message)
11676 }
11677 });
11678 }
11679 max(maxLength, message) {
11680 return new ZodArray({
11681 ...this._def,
11682 maxLength: {
11683 value: maxLength,
11684 message: errorUtil.toString(message)
11685 }
11686 });
11687 }
11688 length(len, message) {
11689 return new ZodArray({
11690 ...this._def,
11691 exactLength: {
11692 value: len,
11693 message: errorUtil.toString(message)
11694 }
11695 });
11696 }
11697 nonempty(message) {
11698 return this.min(1, message);
11699 }
11700 };
11701 ZodArray.create = (schema, params) => {
11702 return new ZodArray({
11703 type: schema,
11704 minLength: null,
11705 maxLength: null,
11706 exactLength: null,
11707 typeName: ZodFirstPartyTypeKind.ZodArray,
11708 ...processCreateParams(params)
11709 });
11710 };
11711 function deepPartialify(schema) {
11712 if (schema instanceof ZodObject) {
11713 const newShape = {};
11714 for (const key in schema.shape) {
11715 const fieldSchema = schema.shape[key];
11716 newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
11717 }
11718 return new ZodObject({
11719 ...schema._def,
11720 shape: () => newShape
11721 });
11722 } else if (schema instanceof ZodArray) return new ZodArray({
11723 ...schema._def,
11724 type: deepPartialify(schema.element)
11725 });
11726 else if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap()));
11727 else if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap()));
11728 else if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
11729 else return schema;
11730 }
11731 var ZodObject = class ZodObject extends ZodType {
11732 constructor() {
11733 super(...arguments);
11734 this._cached = null;
11735 /**
11736 * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
11737 * If you want to pass through unknown properties, use `.passthrough()` instead.
11738 */
11739 this.nonstrict = this.passthrough;
11740 /**
11741 * @deprecated Use `.extend` instead
11742 * */
11743 this.augment = this.extend;
11744 }
11745 _getCached() {
11746 if (this._cached !== null) return this._cached;
11747 const shape = this._def.shape();
11748 const keys = util.objectKeys(shape);
11749 this._cached = {
11750 shape,
11751 keys
11752 };
11753 return this._cached;
11754 }
11755 _parse(input) {
11756 if (this._getType(input) !== ZodParsedType.object) {
11757 const ctx = this._getOrReturnCtx(input);
11758 addIssueToContext(ctx, {
11759 code: ZodIssueCode.invalid_type,
11760 expected: ZodParsedType.object,
11761 received: ctx.parsedType
11762 });
11763 return INVALID;
11764 }
11765 const { status, ctx } = this._processInputParams(input);
11766 const { shape, keys: shapeKeys } = this._getCached();
11767 const extraKeys = [];
11768 if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
11769 for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key);
11770 }
11771 const pairs = [];
11772 for (const key of shapeKeys) {
11773 const keyValidator = shape[key];
11774 const value = ctx.data[key];
11775 pairs.push({
11776 key: {
11777 status: "valid",
11778 value: key
11779 },
11780 value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
11781 alwaysSet: key in ctx.data
11782 });
11783 }
11784 if (this._def.catchall instanceof ZodNever) {
11785 const unknownKeys = this._def.unknownKeys;
11786 if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({
11787 key: {
11788 status: "valid",
11789 value: key
11790 },
11791 value: {
11792 status: "valid",
11793 value: ctx.data[key]
11794 }
11795 });
11796 else if (unknownKeys === "strict") {
11797 if (extraKeys.length > 0) {
11798 addIssueToContext(ctx, {
11799 code: ZodIssueCode.unrecognized_keys,
11800 keys: extraKeys
11801 });
11802 status.dirty();
11803 }
11804 } else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
11805 } else {
11806 const catchall = this._def.catchall;
11807 for (const key of extraKeys) {
11808 const value = ctx.data[key];
11809 pairs.push({
11810 key: {
11811 status: "valid",
11812 value: key
11813 },
11814 value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
11815 alwaysSet: key in ctx.data
11816 });
11817 }
11818 }
11819 if (ctx.common.async) return Promise.resolve().then(async () => {
11820 const syncPairs = [];
11821 for (const pair of pairs) {
11822 const key = await pair.key;
11823 const value = await pair.value;
11824 syncPairs.push({
11825 key,
11826 value,
11827 alwaysSet: pair.alwaysSet
11828 });
11829 }
11830 return syncPairs;
11831 }).then((syncPairs) => {
11832 return ParseStatus.mergeObjectSync(status, syncPairs);
11833 });
11834 else return ParseStatus.mergeObjectSync(status, pairs);
11835 }
11836 get shape() {
11837 return this._def.shape();
11838 }
11839 strict(message) {
11840 errorUtil.errToObj;
11841 return new ZodObject({
11842 ...this._def,
11843 unknownKeys: "strict",
11844 ...message !== void 0 ? { errorMap: (issue, ctx) => {
11845 const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
11846 if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError };
11847 return { message: defaultError };
11848 } } : {}
11849 });
11850 }
11851 strip() {
11852 return new ZodObject({
11853 ...this._def,
11854 unknownKeys: "strip"
11855 });
11856 }
11857 passthrough() {
11858 return new ZodObject({
11859 ...this._def,
11860 unknownKeys: "passthrough"
11861 });
11862 }
11863 extend(augmentation) {
11864 return new ZodObject({
11865 ...this._def,
11866 shape: () => ({
11867 ...this._def.shape(),
11868 ...augmentation
11869 })
11870 });
11871 }
11872 /**
11873 * Prior to [email protected] there was a bug in the
11874 * inferred type of merged objects. Please
11875 * upgrade if you are experiencing issues.
11876 */
11877 merge(merging) {
11878 return new ZodObject({
11879 unknownKeys: merging._def.unknownKeys,
11880 catchall: merging._def.catchall,
11881 shape: () => ({
11882 ...this._def.shape(),
11883 ...merging._def.shape()
11884 }),
11885 typeName: ZodFirstPartyTypeKind.ZodObject
11886 });
11887 }
11888 setKey(key, schema) {
11889 return this.augment({ [key]: schema });
11890 }
11891 catchall(index) {
11892 return new ZodObject({
11893 ...this._def,
11894 catchall: index
11895 });
11896 }
11897 pick(mask) {
11898 const shape = {};
11899 for (const key of util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
11900 return new ZodObject({
11901 ...this._def,
11902 shape: () => shape
11903 });
11904 }
11905 omit(mask) {
11906 const shape = {};
11907 for (const key of util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key];
11908 return new ZodObject({
11909 ...this._def,
11910 shape: () => shape
11911 });
11912 }
11913 /**
11914 * @deprecated
11915 */
11916 deepPartial() {
11917 return deepPartialify(this);
11918 }
11919 partial(mask) {
11920 const newShape = {};
11921 for (const key of util.objectKeys(this.shape)) {
11922 const fieldSchema = this.shape[key];
11923 if (mask && !mask[key]) newShape[key] = fieldSchema;
11924 else newShape[key] = fieldSchema.optional();
11925 }
11926 return new ZodObject({
11927 ...this._def,
11928 shape: () => newShape
11929 });
11930 }
11931 required(mask) {
11932 const newShape = {};
11933 for (const key of util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key];
11934 else {
11935 let newField = this.shape[key];
11936 while (newField instanceof ZodOptional) newField = newField._def.innerType;
11937 newShape[key] = newField;
11938 }
11939 return new ZodObject({
11940 ...this._def,
11941 shape: () => newShape
11942 });
11943 }
11944 keyof() {
11945 return createZodEnum(util.objectKeys(this.shape));
11946 }
11947 };
11948 ZodObject.create = (shape, params) => {
11949 return new ZodObject({
11950 shape: () => shape,
11951 unknownKeys: "strip",
11952 catchall: ZodNever.create(),
11953 typeName: ZodFirstPartyTypeKind.ZodObject,
11954 ...processCreateParams(params)
11955 });
11956 };
11957 ZodObject.strictCreate = (shape, params) => {
11958 return new ZodObject({
11959 shape: () => shape,
11960 unknownKeys: "strict",
11961 catchall: ZodNever.create(),
11962 typeName: ZodFirstPartyTypeKind.ZodObject,
11963 ...processCreateParams(params)
11964 });
11965 };
11966 ZodObject.lazycreate = (shape, params) => {
11967 return new ZodObject({
11968 shape,
11969 unknownKeys: "strip",
11970 catchall: ZodNever.create(),
11971 typeName: ZodFirstPartyTypeKind.ZodObject,
11972 ...processCreateParams(params)
11973 });
11974 };
11975 var ZodUnion = class extends ZodType {
11976 _parse(input) {
11977 const { ctx } = this._processInputParams(input);
11978 const options = this._def.options;
11979 function handleResults(results) {
11980 for (const result of results) if (result.result.status === "valid") return result.result;
11981 for (const result of results) if (result.result.status === "dirty") {
11982 ctx.common.issues.push(...result.ctx.common.issues);
11983 return result.result;
11984 }
11985 const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
11986 addIssueToContext(ctx, {
11987 code: ZodIssueCode.invalid_union,
11988 unionErrors
11989 });
11990 return INVALID;
11991 }
11992 if (ctx.common.async) return Promise.all(options.map(async (option) => {
11993 const childCtx = {
11994 ...ctx,
11995 common: {
11996 ...ctx.common,
11997 issues: []
11998 },
11999 parent: null
12000 };
12001 return {
12002 result: await option._parseAsync({
12003 data: ctx.data,
12004 path: ctx.path,
12005 parent: childCtx
12006 }),
12007 ctx: childCtx
12008 };
12009 })).then(handleResults);
12010 else {
12011 let dirty = void 0;
12012 const issues = [];
12013 for (const option of options) {
12014 const childCtx = {
12015 ...ctx,
12016 common: {
12017 ...ctx.common,
12018 issues: []
12019 },
12020 parent: null
12021 };
12022 const result = option._parseSync({
12023 data: ctx.data,
12024 path: ctx.path,
12025 parent: childCtx
12026 });
12027 if (result.status === "valid") return result;
12028 else if (result.status === "dirty" && !dirty) dirty = {
12029 result,
12030 ctx: childCtx
12031 };
12032 if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
12033 }
12034 if (dirty) {
12035 ctx.common.issues.push(...dirty.ctx.common.issues);
12036 return dirty.result;
12037 }
12038 const unionErrors = issues.map((issues) => new ZodError(issues));
12039 addIssueToContext(ctx, {
12040 code: ZodIssueCode.invalid_union,
12041 unionErrors
12042 });
12043 return INVALID;
12044 }
12045 }
12046 get options() {
12047 return this._def.options;
12048 }
12049 };
12050 ZodUnion.create = (types, params) => {
12051 return new ZodUnion({
12052 options: types,
12053 typeName: ZodFirstPartyTypeKind.ZodUnion,
12054 ...processCreateParams(params)
12055 });
12056 };
12057 var getDiscriminator = (type) => {
12058 if (type instanceof ZodLazy) return getDiscriminator(type.schema);
12059 else if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
12060 else if (type instanceof ZodLiteral) return [type.value];
12061 else if (type instanceof ZodEnum) return type.options;
12062 else if (type instanceof ZodNativeEnum) return util.objectValues(type.enum);
12063 else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
12064 else if (type instanceof ZodUndefined) return [void 0];
12065 else if (type instanceof ZodNull) return [null];
12066 else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())];
12067 else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())];
12068 else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
12069 else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
12070 else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
12071 else return [];
12072 };
12073 var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
12074 _parse(input) {
12075 const { ctx } = this._processInputParams(input);
12076 if (ctx.parsedType !== ZodParsedType.object) {
12077 addIssueToContext(ctx, {
12078 code: ZodIssueCode.invalid_type,
12079 expected: ZodParsedType.object,
12080 received: ctx.parsedType
12081 });
12082 return INVALID;
12083 }
12084 const discriminator = this.discriminator;
12085 const discriminatorValue = ctx.data[discriminator];
12086 const option = this.optionsMap.get(discriminatorValue);
12087 if (!option) {
12088 addIssueToContext(ctx, {
12089 code: ZodIssueCode.invalid_union_discriminator,
12090 options: Array.from(this.optionsMap.keys()),
12091 path: [discriminator]
12092 });
12093 return INVALID;
12094 }
12095 if (ctx.common.async) return option._parseAsync({
12096 data: ctx.data,
12097 path: ctx.path,
12098 parent: ctx
12099 });
12100 else return option._parseSync({
12101 data: ctx.data,
12102 path: ctx.path,
12103 parent: ctx
12104 });
12105 }
12106 get discriminator() {
12107 return this._def.discriminator;
12108 }
12109 get options() {
12110 return this._def.options;
12111 }
12112 get optionsMap() {
12113 return this._def.optionsMap;
12114 }
12115 /**
12116 * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
12117 * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
12118 * have a different value for each object in the union.
12119 * @param discriminator the name of the discriminator property
12120 * @param types an array of object schemas
12121 * @param params
12122 */
12123 static create(discriminator, options, params) {
12124 const optionsMap = /* @__PURE__ */ new Map();
12125 for (const type of options) {
12126 const discriminatorValues = getDiscriminator(type.shape[discriminator]);
12127 if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
12128 for (const value of discriminatorValues) {
12129 if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
12130 optionsMap.set(value, type);
12131 }
12132 }
12133 return new ZodDiscriminatedUnion({
12134 typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
12135 discriminator,
12136 options,
12137 optionsMap,
12138 ...processCreateParams(params)
12139 });
12140 }
12141 };
12142 function mergeValues(a, b) {
12143 const aType = getParsedType(a);
12144 const bType = getParsedType(b);
12145 if (a === b) return {
12146 valid: true,
12147 data: a
12148 };
12149 else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
12150 const bKeys = util.objectKeys(b);
12151 const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
12152 const newObj = {
12153 ...a,
12154 ...b
12155 };
12156 for (const key of sharedKeys) {
12157 const sharedValue = mergeValues(a[key], b[key]);
12158 if (!sharedValue.valid) return { valid: false };
12159 newObj[key] = sharedValue.data;
12160 }
12161 return {
12162 valid: true,
12163 data: newObj
12164 };
12165 } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
12166 if (a.length !== b.length) return { valid: false };
12167 const newArray = [];
12168 for (let index = 0; index < a.length; index++) {
12169 const itemA = a[index];
12170 const itemB = b[index];
12171 const sharedValue = mergeValues(itemA, itemB);
12172 if (!sharedValue.valid) return { valid: false };
12173 newArray.push(sharedValue.data);
12174 }
12175 return {
12176 valid: true,
12177 data: newArray
12178 };
12179 } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return {
12180 valid: true,
12181 data: a
12182 };
12183 else return { valid: false };
12184 }
12185 var ZodIntersection = class extends ZodType {
12186 _parse(input) {
12187 const { status, ctx } = this._processInputParams(input);
12188 const handleParsed = (parsedLeft, parsedRight) => {
12189 if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID;
12190 const merged = mergeValues(parsedLeft.value, parsedRight.value);
12191 if (!merged.valid) {
12192 addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types });
12193 return INVALID;
12194 }
12195 if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty();
12196 return {
12197 status: status.value,
12198 value: merged.data
12199 };
12200 };
12201 if (ctx.common.async) return Promise.all([this._def.left._parseAsync({
12202 data: ctx.data,
12203 path: ctx.path,
12204 parent: ctx
12205 }), this._def.right._parseAsync({
12206 data: ctx.data,
12207 path: ctx.path,
12208 parent: ctx
12209 })]).then(([left, right]) => handleParsed(left, right));
12210 else return handleParsed(this._def.left._parseSync({
12211 data: ctx.data,
12212 path: ctx.path,
12213 parent: ctx
12214 }), this._def.right._parseSync({
12215 data: ctx.data,
12216 path: ctx.path,
12217 parent: ctx
12218 }));
12219 }
12220 };
12221 ZodIntersection.create = (left, right, params) => {
12222 return new ZodIntersection({
12223 left,
12224 right,
12225 typeName: ZodFirstPartyTypeKind.ZodIntersection,
12226 ...processCreateParams(params)
12227 });
12228 };
12229 var ZodTuple = class ZodTuple extends ZodType {
12230 _parse(input) {
12231 const { status, ctx } = this._processInputParams(input);
12232 if (ctx.parsedType !== ZodParsedType.array) {
12233 addIssueToContext(ctx, {
12234 code: ZodIssueCode.invalid_type,
12235 expected: ZodParsedType.array,
12236 received: ctx.parsedType
12237 });
12238 return INVALID;
12239 }
12240 if (ctx.data.length < this._def.items.length) {
12241 addIssueToContext(ctx, {
12242 code: ZodIssueCode.too_small,
12243 minimum: this._def.items.length,
12244 inclusive: true,
12245 exact: false,
12246 type: "array"
12247 });
12248 return INVALID;
12249 }
12250 if (!this._def.rest && ctx.data.length > this._def.items.length) {
12251 addIssueToContext(ctx, {
12252 code: ZodIssueCode.too_big,
12253 maximum: this._def.items.length,
12254 inclusive: true,
12255 exact: false,
12256 type: "array"
12257 });
12258 status.dirty();
12259 }
12260 const items = [...ctx.data].map((item, itemIndex) => {
12261 const schema = this._def.items[itemIndex] || this._def.rest;
12262 if (!schema) return null;
12263 return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
12264 }).filter((x) => !!x);
12265 if (ctx.common.async) return Promise.all(items).then((results) => {
12266 return ParseStatus.mergeArray(status, results);
12267 });
12268 else return ParseStatus.mergeArray(status, items);
12269 }
12270 get items() {
12271 return this._def.items;
12272 }
12273 rest(rest) {
12274 return new ZodTuple({
12275 ...this._def,
12276 rest
12277 });
12278 }
12279 };
12280 ZodTuple.create = (schemas, params) => {
12281 if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
12282 return new ZodTuple({
12283 items: schemas,
12284 typeName: ZodFirstPartyTypeKind.ZodTuple,
12285 rest: null,
12286 ...processCreateParams(params)
12287 });
12288 };
12289 var ZodRecord = class ZodRecord extends ZodType {
12290 get keySchema() {
12291 return this._def.keyType;
12292 }
12293 get valueSchema() {
12294 return this._def.valueType;
12295 }
12296 _parse(input) {
12297 const { status, ctx } = this._processInputParams(input);
12298 if (ctx.parsedType !== ZodParsedType.object) {
12299 addIssueToContext(ctx, {
12300 code: ZodIssueCode.invalid_type,
12301 expected: ZodParsedType.object,
12302 received: ctx.parsedType
12303 });
12304 return INVALID;
12305 }
12306 const pairs = [];
12307 const keyType = this._def.keyType;
12308 const valueType = this._def.valueType;
12309 for (const key in ctx.data) pairs.push({
12310 key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
12311 value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
12312 alwaysSet: key in ctx.data
12313 });
12314 if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs);
12315 else return ParseStatus.mergeObjectSync(status, pairs);
12316 }
12317 get element() {
12318 return this._def.valueType;
12319 }
12320 static create(first, second, third) {
12321 if (second instanceof ZodType) return new ZodRecord({
12322 keyType: first,
12323 valueType: second,
12324 typeName: ZodFirstPartyTypeKind.ZodRecord,
12325 ...processCreateParams(third)
12326 });
12327 return new ZodRecord({
12328 keyType: ZodString.create(),
12329 valueType: first,
12330 typeName: ZodFirstPartyTypeKind.ZodRecord,
12331 ...processCreateParams(second)
12332 });
12333 }
12334 };
12335 var ZodMap = class extends ZodType {
12336 get keySchema() {
12337 return this._def.keyType;
12338 }
12339 get valueSchema() {
12340 return this._def.valueType;
12341 }
12342 _parse(input) {
12343 const { status, ctx } = this._processInputParams(input);
12344 if (ctx.parsedType !== ZodParsedType.map) {
12345 addIssueToContext(ctx, {
12346 code: ZodIssueCode.invalid_type,
12347 expected: ZodParsedType.map,
12348 received: ctx.parsedType
12349 });
12350 return INVALID;
12351 }
12352 const keyType = this._def.keyType;
12353 const valueType = this._def.valueType;
12354 const pairs = [...ctx.data.entries()].map(([key, value], index) => {
12355 return {
12356 key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
12357 value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
12358 };
12359 });
12360 if (ctx.common.async) {
12361 const finalMap = /* @__PURE__ */ new Map();
12362 return Promise.resolve().then(async () => {
12363 for (const pair of pairs) {
12364 const key = await pair.key;
12365 const value = await pair.value;
12366 if (key.status === "aborted" || value.status === "aborted") return INVALID;
12367 if (key.status === "dirty" || value.status === "dirty") status.dirty();
12368 finalMap.set(key.value, value.value);
12369 }
12370 return {
12371 status: status.value,
12372 value: finalMap
12373 };
12374 });
12375 } else {
12376 const finalMap = /* @__PURE__ */ new Map();
12377 for (const pair of pairs) {
12378 const key = pair.key;
12379 const value = pair.value;
12380 if (key.status === "aborted" || value.status === "aborted") return INVALID;
12381 if (key.status === "dirty" || value.status === "dirty") status.dirty();
12382 finalMap.set(key.value, value.value);
12383 }
12384 return {
12385 status: status.value,
12386 value: finalMap
12387 };
12388 }
12389 }
12390 };
12391 ZodMap.create = (keyType, valueType, params) => {
12392 return new ZodMap({
12393 valueType,
12394 keyType,
12395 typeName: ZodFirstPartyTypeKind.ZodMap,
12396 ...processCreateParams(params)
12397 });
12398 };
12399 var ZodSet = class ZodSet extends ZodType {
12400 _parse(input) {
12401 const { status, ctx } = this._processInputParams(input);
12402 if (ctx.parsedType !== ZodParsedType.set) {
12403 addIssueToContext(ctx, {
12404 code: ZodIssueCode.invalid_type,
12405 expected: ZodParsedType.set,
12406 received: ctx.parsedType
12407 });
12408 return INVALID;
12409 }
12410 const def = this._def;
12411 if (def.minSize !== null) {
12412 if (ctx.data.size < def.minSize.value) {
12413 addIssueToContext(ctx, {
12414 code: ZodIssueCode.too_small,
12415 minimum: def.minSize.value,
12416 type: "set",
12417 inclusive: true,
12418 exact: false,
12419 message: def.minSize.message
12420 });
12421 status.dirty();
12422 }
12423 }
12424 if (def.maxSize !== null) {
12425 if (ctx.data.size > def.maxSize.value) {
12426 addIssueToContext(ctx, {
12427 code: ZodIssueCode.too_big,
12428 maximum: def.maxSize.value,
12429 type: "set",
12430 inclusive: true,
12431 exact: false,
12432 message: def.maxSize.message
12433 });
12434 status.dirty();
12435 }
12436 }
12437 const valueType = this._def.valueType;
12438 function finalizeSet(elements) {
12439 const parsedSet = /* @__PURE__ */ new Set();
12440 for (const element of elements) {
12441 if (element.status === "aborted") return INVALID;
12442 if (element.status === "dirty") status.dirty();
12443 parsedSet.add(element.value);
12444 }
12445 return {
12446 status: status.value,
12447 value: parsedSet
12448 };
12449 }
12450 const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
12451 if (ctx.common.async) return Promise.all(elements).then((elements) => finalizeSet(elements));
12452 else return finalizeSet(elements);
12453 }
12454 min(minSize, message) {
12455 return new ZodSet({
12456 ...this._def,
12457 minSize: {
12458 value: minSize,
12459 message: errorUtil.toString(message)
12460 }
12461 });
12462 }
12463 max(maxSize, message) {
12464 return new ZodSet({
12465 ...this._def,
12466 maxSize: {
12467 value: maxSize,
12468 message: errorUtil.toString(message)
12469 }
12470 });
12471 }
12472 size(size, message) {
12473 return this.min(size, message).max(size, message);
12474 }
12475 nonempty(message) {
12476 return this.min(1, message);
12477 }
12478 };
12479 ZodSet.create = (valueType, params) => {
12480 return new ZodSet({
12481 valueType,
12482 minSize: null,
12483 maxSize: null,
12484 typeName: ZodFirstPartyTypeKind.ZodSet,
12485 ...processCreateParams(params)
12486 });
12487 };
12488 var ZodFunction = class ZodFunction extends ZodType {
12489 constructor() {
12490 super(...arguments);
12491 this.validate = this.implement;
12492 }
12493 _parse(input) {
12494 const { ctx } = this._processInputParams(input);
12495 if (ctx.parsedType !== ZodParsedType.function) {
12496 addIssueToContext(ctx, {
12497 code: ZodIssueCode.invalid_type,
12498 expected: ZodParsedType.function,
12499 received: ctx.parsedType
12500 });
12501 return INVALID;
12502 }
12503 function makeArgsIssue(args, error) {
12504 return makeIssue({
12505 data: args,
12506 path: ctx.path,
12507 errorMaps: [
12508 ctx.common.contextualErrorMap,
12509 ctx.schemaErrorMap,
12510 getErrorMap(),
12511 errorMap
12512 ].filter((x) => !!x),
12513 issueData: {
12514 code: ZodIssueCode.invalid_arguments,
12515 argumentsError: error
12516 }
12517 });
12518 }
12519 function makeReturnsIssue(returns, error) {
12520 return makeIssue({
12521 data: returns,
12522 path: ctx.path,
12523 errorMaps: [
12524 ctx.common.contextualErrorMap,
12525 ctx.schemaErrorMap,
12526 getErrorMap(),
12527 errorMap
12528 ].filter((x) => !!x),
12529 issueData: {
12530 code: ZodIssueCode.invalid_return_type,
12531 returnTypeError: error
12532 }
12533 });
12534 }
12535 const params = { errorMap: ctx.common.contextualErrorMap };
12536 const fn = ctx.data;
12537 if (this._def.returns instanceof ZodPromise) {
12538 const me = this;
12539 return OK(async function(...args) {
12540 const error = new ZodError([]);
12541 const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
12542 error.addIssue(makeArgsIssue(args, e));
12543 throw error;
12544 });
12545 const result = await Reflect.apply(fn, this, parsedArgs);
12546 return await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
12547 error.addIssue(makeReturnsIssue(result, e));
12548 throw error;
12549 });
12550 });
12551 } else {
12552 const me = this;
12553 return OK(function(...args) {
12554 const parsedArgs = me._def.args.safeParse(args, params);
12555 if (!parsedArgs.success) throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
12556 const result = Reflect.apply(fn, this, parsedArgs.data);
12557 const parsedReturns = me._def.returns.safeParse(result, params);
12558 if (!parsedReturns.success) throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
12559 return parsedReturns.data;
12560 });
12561 }
12562 }
12563 parameters() {
12564 return this._def.args;
12565 }
12566 returnType() {
12567 return this._def.returns;
12568 }
12569 args(...items) {
12570 return new ZodFunction({
12571 ...this._def,
12572 args: ZodTuple.create(items).rest(ZodUnknown.create())
12573 });
12574 }
12575 returns(returnType) {
12576 return new ZodFunction({
12577 ...this._def,
12578 returns: returnType
12579 });
12580 }
12581 implement(func) {
12582 return this.parse(func);
12583 }
12584 strictImplement(func) {
12585 return this.parse(func);
12586 }
12587 static create(args, returns, params) {
12588 return new ZodFunction({
12589 args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
12590 returns: returns || ZodUnknown.create(),
12591 typeName: ZodFirstPartyTypeKind.ZodFunction,
12592 ...processCreateParams(params)
12593 });
12594 }
12595 };
12596 var ZodLazy = class extends ZodType {
12597 get schema() {
12598 return this._def.getter();
12599 }
12600 _parse(input) {
12601 const { ctx } = this._processInputParams(input);
12602 return this._def.getter()._parse({
12603 data: ctx.data,
12604 path: ctx.path,
12605 parent: ctx
12606 });
12607 }
12608 };
12609 ZodLazy.create = (getter, params) => {
12610 return new ZodLazy({
12611 getter,
12612 typeName: ZodFirstPartyTypeKind.ZodLazy,
12613 ...processCreateParams(params)
12614 });
12615 };
12616 var ZodLiteral = class extends ZodType {
12617 _parse(input) {
12618 if (input.data !== this._def.value) {
12619 const ctx = this._getOrReturnCtx(input);
12620 addIssueToContext(ctx, {
12621 received: ctx.data,
12622 code: ZodIssueCode.invalid_literal,
12623 expected: this._def.value
12624 });
12625 return INVALID;
12626 }
12627 return {
12628 status: "valid",
12629 value: input.data
12630 };
12631 }
12632 get value() {
12633 return this._def.value;
12634 }
12635 };
12636 ZodLiteral.create = (value, params) => {
12637 return new ZodLiteral({
12638 value,
12639 typeName: ZodFirstPartyTypeKind.ZodLiteral,
12640 ...processCreateParams(params)
12641 });
12642 };
12643 function createZodEnum(values, params) {
12644 return new ZodEnum({
12645 values,
12646 typeName: ZodFirstPartyTypeKind.ZodEnum,
12647 ...processCreateParams(params)
12648 });
12649 }
12650 var ZodEnum = class ZodEnum extends ZodType {
12651 _parse(input) {
12652 if (typeof input.data !== "string") {
12653 const ctx = this._getOrReturnCtx(input);
12654 const expectedValues = this._def.values;
12655 addIssueToContext(ctx, {
12656 expected: util.joinValues(expectedValues),
12657 received: ctx.parsedType,
12658 code: ZodIssueCode.invalid_type
12659 });
12660 return INVALID;
12661 }
12662 if (!this._cache) this._cache = new Set(this._def.values);
12663 if (!this._cache.has(input.data)) {
12664 const ctx = this._getOrReturnCtx(input);
12665 const expectedValues = this._def.values;
12666 addIssueToContext(ctx, {
12667 received: ctx.data,
12668 code: ZodIssueCode.invalid_enum_value,
12669 options: expectedValues
12670 });
12671 return INVALID;
12672 }
12673 return OK(input.data);
12674 }
12675 get options() {
12676 return this._def.values;
12677 }
12678 get enum() {
12679 const enumValues = {};
12680 for (const val of this._def.values) enumValues[val] = val;
12681 return enumValues;
12682 }
12683 get Values() {
12684 const enumValues = {};
12685 for (const val of this._def.values) enumValues[val] = val;
12686 return enumValues;
12687 }
12688 get Enum() {
12689 const enumValues = {};
12690 for (const val of this._def.values) enumValues[val] = val;
12691 return enumValues;
12692 }
12693 extract(values, newDef = this._def) {
12694 return ZodEnum.create(values, {
12695 ...this._def,
12696 ...newDef
12697 });
12698 }
12699 exclude(values, newDef = this._def) {
12700 return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
12701 ...this._def,
12702 ...newDef
12703 });
12704 }
12705 };
12706 ZodEnum.create = createZodEnum;
12707 var ZodNativeEnum = class extends ZodType {
12708 _parse(input) {
12709 const nativeEnumValues = util.getValidEnumValues(this._def.values);
12710 const ctx = this._getOrReturnCtx(input);
12711 if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
12712 const expectedValues = util.objectValues(nativeEnumValues);
12713 addIssueToContext(ctx, {
12714 expected: util.joinValues(expectedValues),
12715 received: ctx.parsedType,
12716 code: ZodIssueCode.invalid_type
12717 });
12718 return INVALID;
12719 }
12720 if (!this._cache) this._cache = new Set(util.getValidEnumValues(this._def.values));
12721 if (!this._cache.has(input.data)) {
12722 const expectedValues = util.objectValues(nativeEnumValues);
12723 addIssueToContext(ctx, {
12724 received: ctx.data,
12725 code: ZodIssueCode.invalid_enum_value,
12726 options: expectedValues
12727 });
12728 return INVALID;
12729 }
12730 return OK(input.data);
12731 }
12732 get enum() {
12733 return this._def.values;
12734 }
12735 };
12736 ZodNativeEnum.create = (values, params) => {
12737 return new ZodNativeEnum({
12738 values,
12739 typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
12740 ...processCreateParams(params)
12741 });
12742 };
12743 var ZodPromise = class extends ZodType {
12744 unwrap() {
12745 return this._def.type;
12746 }
12747 _parse(input) {
12748 const { ctx } = this._processInputParams(input);
12749 if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
12750 addIssueToContext(ctx, {
12751 code: ZodIssueCode.invalid_type,
12752 expected: ZodParsedType.promise,
12753 received: ctx.parsedType
12754 });
12755 return INVALID;
12756 }
12757 return OK((ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data)).then((data) => {
12758 return this._def.type.parseAsync(data, {
12759 path: ctx.path,
12760 errorMap: ctx.common.contextualErrorMap
12761 });
12762 }));
12763 }
12764 };
12765 ZodPromise.create = (schema, params) => {
12766 return new ZodPromise({
12767 type: schema,
12768 typeName: ZodFirstPartyTypeKind.ZodPromise,
12769 ...processCreateParams(params)
12770 });
12771 };
12772 var ZodEffects = class extends ZodType {
12773 innerType() {
12774 return this._def.schema;
12775 }
12776 sourceType() {
12777 return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
12778 }
12779 _parse(input) {
12780 const { status, ctx } = this._processInputParams(input);
12781 const effect = this._def.effect || null;
12782 const checkCtx = {
12783 addIssue: (arg) => {
12784 addIssueToContext(ctx, arg);
12785 if (arg.fatal) status.abort();
12786 else status.dirty();
12787 },
12788 get path() {
12789 return ctx.path;
12790 }
12791 };
12792 checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
12793 if (effect.type === "preprocess") {
12794 const processed = effect.transform(ctx.data, checkCtx);
12795 if (ctx.common.async) return Promise.resolve(processed).then(async (processed) => {
12796 if (status.value === "aborted") return INVALID;
12797 const result = await this._def.schema._parseAsync({
12798 data: processed,
12799 path: ctx.path,
12800 parent: ctx
12801 });
12802 if (result.status === "aborted") return INVALID;
12803 if (result.status === "dirty") return DIRTY(result.value);
12804 if (status.value === "dirty") return DIRTY(result.value);
12805 return result;
12806 });
12807 else {
12808 if (status.value === "aborted") return INVALID;
12809 const result = this._def.schema._parseSync({
12810 data: processed,
12811 path: ctx.path,
12812 parent: ctx
12813 });
12814 if (result.status === "aborted") return INVALID;
12815 if (result.status === "dirty") return DIRTY(result.value);
12816 if (status.value === "dirty") return DIRTY(result.value);
12817 return result;
12818 }
12819 }
12820 if (effect.type === "refinement") {
12821 const executeRefinement = (acc) => {
12822 const result = effect.refinement(acc, checkCtx);
12823 if (ctx.common.async) return Promise.resolve(result);
12824 if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
12825 return acc;
12826 };
12827 if (ctx.common.async === false) {
12828 const inner = this._def.schema._parseSync({
12829 data: ctx.data,
12830 path: ctx.path,
12831 parent: ctx
12832 });
12833 if (inner.status === "aborted") return INVALID;
12834 if (inner.status === "dirty") status.dirty();
12835 executeRefinement(inner.value);
12836 return {
12837 status: status.value,
12838 value: inner.value
12839 };
12840 } else return this._def.schema._parseAsync({
12841 data: ctx.data,
12842 path: ctx.path,
12843 parent: ctx
12844 }).then((inner) => {
12845 if (inner.status === "aborted") return INVALID;
12846 if (inner.status === "dirty") status.dirty();
12847 return executeRefinement(inner.value).then(() => {
12848 return {
12849 status: status.value,
12850 value: inner.value
12851 };
12852 });
12853 });
12854 }
12855 if (effect.type === "transform") if (ctx.common.async === false) {
12856 const base = this._def.schema._parseSync({
12857 data: ctx.data,
12858 path: ctx.path,
12859 parent: ctx
12860 });
12861 if (!isValid(base)) return INVALID;
12862 const result = effect.transform(base.value, checkCtx);
12863 if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
12864 return {
12865 status: status.value,
12866 value: result
12867 };
12868 } else return this._def.schema._parseAsync({
12869 data: ctx.data,
12870 path: ctx.path,
12871 parent: ctx
12872 }).then((base) => {
12873 if (!isValid(base)) return INVALID;
12874 return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
12875 status: status.value,
12876 value: result
12877 }));
12878 });
12879 util.assertNever(effect);
12880 }
12881 };
12882 ZodEffects.create = (schema, effect, params) => {
12883 return new ZodEffects({
12884 schema,
12885 typeName: ZodFirstPartyTypeKind.ZodEffects,
12886 effect,
12887 ...processCreateParams(params)
12888 });
12889 };
12890 ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
12891 return new ZodEffects({
12892 schema,
12893 effect: {
12894 type: "preprocess",
12895 transform: preprocess
12896 },
12897 typeName: ZodFirstPartyTypeKind.ZodEffects,
12898 ...processCreateParams(params)
12899 });
12900 };
12901 var ZodOptional = class extends ZodType {
12902 _parse(input) {
12903 if (this._getType(input) === ZodParsedType.undefined) return OK(void 0);
12904 return this._def.innerType._parse(input);
12905 }
12906 unwrap() {
12907 return this._def.innerType;
12908 }
12909 };
12910 ZodOptional.create = (type, params) => {
12911 return new ZodOptional({
12912 innerType: type,
12913 typeName: ZodFirstPartyTypeKind.ZodOptional,
12914 ...processCreateParams(params)
12915 });
12916 };
12917 var ZodNullable = class extends ZodType {
12918 _parse(input) {
12919 if (this._getType(input) === ZodParsedType.null) return OK(null);
12920 return this._def.innerType._parse(input);
12921 }
12922 unwrap() {
12923 return this._def.innerType;
12924 }
12925 };
12926 ZodNullable.create = (type, params) => {
12927 return new ZodNullable({
12928 innerType: type,
12929 typeName: ZodFirstPartyTypeKind.ZodNullable,
12930 ...processCreateParams(params)
12931 });
12932 };
12933 var ZodDefault = class extends ZodType {
12934 _parse(input) {
12935 const { ctx } = this._processInputParams(input);
12936 let data = ctx.data;
12937 if (ctx.parsedType === ZodParsedType.undefined) data = this._def.defaultValue();
12938 return this._def.innerType._parse({
12939 data,
12940 path: ctx.path,
12941 parent: ctx
12942 });
12943 }
12944 removeDefault() {
12945 return this._def.innerType;
12946 }
12947 };
12948 ZodDefault.create = (type, params) => {
12949 return new ZodDefault({
12950 innerType: type,
12951 typeName: ZodFirstPartyTypeKind.ZodDefault,
12952 defaultValue: typeof params.default === "function" ? params.default : () => params.default,
12953 ...processCreateParams(params)
12954 });
12955 };
12956 var ZodCatch = class extends ZodType {
12957 _parse(input) {
12958 const { ctx } = this._processInputParams(input);
12959 const newCtx = {
12960 ...ctx,
12961 common: {
12962 ...ctx.common,
12963 issues: []
12964 }
12965 };
12966 const result = this._def.innerType._parse({
12967 data: newCtx.data,
12968 path: newCtx.path,
12969 parent: { ...newCtx }
12970 });
12971 if (isAsync(result)) return result.then((result) => {
12972 return {
12973 status: "valid",
12974 value: result.status === "valid" ? result.value : this._def.catchValue({
12975 get error() {
12976 return new ZodError(newCtx.common.issues);
12977 },
12978 input: newCtx.data
12979 })
12980 };
12981 });
12982 else return {
12983 status: "valid",
12984 value: result.status === "valid" ? result.value : this._def.catchValue({
12985 get error() {
12986 return new ZodError(newCtx.common.issues);
12987 },
12988 input: newCtx.data
12989 })
12990 };
12991 }
12992 removeCatch() {
12993 return this._def.innerType;
12994 }
12995 };
12996 ZodCatch.create = (type, params) => {
12997 return new ZodCatch({
12998 innerType: type,
12999 typeName: ZodFirstPartyTypeKind.ZodCatch,
13000 catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
13001 ...processCreateParams(params)
13002 });
13003 };
13004 var ZodNaN = class extends ZodType {
13005 _parse(input) {
13006 if (this._getType(input) !== ZodParsedType.nan) {
13007 const ctx = this._getOrReturnCtx(input);
13008 addIssueToContext(ctx, {
13009 code: ZodIssueCode.invalid_type,
13010 expected: ZodParsedType.nan,
13011 received: ctx.parsedType
13012 });
13013 return INVALID;
13014 }
13015 return {
13016 status: "valid",
13017 value: input.data
13018 };
13019 }
13020 };
13021 ZodNaN.create = (params) => {
13022 return new ZodNaN({
13023 typeName: ZodFirstPartyTypeKind.ZodNaN,
13024 ...processCreateParams(params)
13025 });
13026 };
13027 var ZodBranded = class extends ZodType {
13028 _parse(input) {
13029 const { ctx } = this._processInputParams(input);
13030 const data = ctx.data;
13031 return this._def.type._parse({
13032 data,
13033 path: ctx.path,
13034 parent: ctx
13035 });
13036 }
13037 unwrap() {
13038 return this._def.type;
13039 }
13040 };
13041 var ZodPipeline = class ZodPipeline extends ZodType {
13042 _parse(input) {
13043 const { status, ctx } = this._processInputParams(input);
13044 if (ctx.common.async) {
13045 const handleAsync = async () => {
13046 const inResult = await this._def.in._parseAsync({
13047 data: ctx.data,
13048 path: ctx.path,
13049 parent: ctx
13050 });
13051 if (inResult.status === "aborted") return INVALID;
13052 if (inResult.status === "dirty") {
13053 status.dirty();
13054 return DIRTY(inResult.value);
13055 } else return this._def.out._parseAsync({
13056 data: inResult.value,
13057 path: ctx.path,
13058 parent: ctx
13059 });
13060 };
13061 return handleAsync();
13062 } else {
13063 const inResult = this._def.in._parseSync({
13064 data: ctx.data,
13065 path: ctx.path,
13066 parent: ctx
13067 });
13068 if (inResult.status === "aborted") return INVALID;
13069 if (inResult.status === "dirty") {
13070 status.dirty();
13071 return {
13072 status: "dirty",
13073 value: inResult.value
13074 };
13075 } else return this._def.out._parseSync({
13076 data: inResult.value,
13077 path: ctx.path,
13078 parent: ctx
13079 });
13080 }
13081 }
13082 static create(a, b) {
13083 return new ZodPipeline({
13084 in: a,
13085 out: b,
13086 typeName: ZodFirstPartyTypeKind.ZodPipeline
13087 });
13088 }
13089 };
13090 var ZodReadonly = class extends ZodType {
13091 _parse(input) {
13092 const result = this._def.innerType._parse(input);
13093 const freeze = (data) => {
13094 if (isValid(data)) data.value = Object.freeze(data.value);
13095 return data;
13096 };
13097 return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
13098 }
13099 unwrap() {
13100 return this._def.innerType;
13101 }
13102 };
13103 ZodReadonly.create = (type, params) => {
13104 return new ZodReadonly({
13105 innerType: type,
13106 typeName: ZodFirstPartyTypeKind.ZodReadonly,
13107 ...processCreateParams(params)
13108 });
13109 };
13110 var late = { object: ZodObject.lazycreate };
13111 var ZodFirstPartyTypeKind;
13112 (function(ZodFirstPartyTypeKind) {
13113 ZodFirstPartyTypeKind["ZodString"] = "ZodString";
13114 ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
13115 ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
13116 ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
13117 ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
13118 ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
13119 ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
13120 ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
13121 ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
13122 ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
13123 ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
13124 ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
13125 ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
13126 ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
13127 ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
13128 ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
13129 ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
13130 ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
13131 ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
13132 ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
13133 ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
13134 ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
13135 ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
13136 ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
13137 ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
13138 ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
13139 ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
13140 ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
13141 ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
13142 ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
13143 ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
13144 ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
13145 ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
13146 ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
13147 ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
13148 ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
13149 })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
13150 var stringType = ZodString.create;
13151 var numberType = ZodNumber.create;
13152 var nanType = ZodNaN.create;
13153 var bigIntType = ZodBigInt.create;
13154 var booleanType = ZodBoolean.create;
13155 var dateType = ZodDate.create;
13156 var symbolType = ZodSymbol.create;
13157 var undefinedType = ZodUndefined.create;
13158 var nullType = ZodNull.create;
13159 var anyType = ZodAny.create;
13160 var unknownType = ZodUnknown.create;
13161 var neverType = ZodNever.create;
13162 var voidType = ZodVoid.create;
13163 var arrayType = ZodArray.create;
13164 var objectType = ZodObject.create;
13165 var strictObjectType = ZodObject.strictCreate;
13166 var unionType = ZodUnion.create;
13167 var discriminatedUnionType = ZodDiscriminatedUnion.create;
13168 var intersectionType = ZodIntersection.create;
13169 var tupleType = ZodTuple.create;
13170 var recordType = ZodRecord.create;
13171 var mapType = ZodMap.create;
13172 var setType = ZodSet.create;
13173 var functionType = ZodFunction.create;
13174 var lazyType = ZodLazy.create;
13175 var literalType = ZodLiteral.create;
13176 var enumType = ZodEnum.create;
13177 var nativeEnumType = ZodNativeEnum.create;
13178 var promiseType = ZodPromise.create;
13179 var effectsType = ZodEffects.create;
13180 var optionalType = ZodOptional.create;
13181 var nullableType = ZodNullable.create;
13182 var preprocessType = ZodEffects.createWithPreprocess;
13183 var pipelineType = ZodPipeline.create;
13184
13185 //#endregion
13186 //#region node_modules/zod/v4/mini/schemas.js
13187 var ZodMiniType = /*@__PURE__*/ $constructor("ZodMiniType", (inst, def) => {
13188 if (!inst._zod) throw new Error("Uninitialized schema in ZodMiniType.");
13189 $ZodType.init(inst, def);
13190 inst.def = def;
13191 inst.parse = (data, params) => parse$1(inst, data, params, { callee: inst.parse });
13192 inst.safeParse = (data, params) => safeParse$2(inst, data, params);
13193 inst.parseAsync = async (data, params) => parseAsync$1(inst, data, params, { callee: inst.parseAsync });
13194 inst.safeParseAsync = async (data, params) => safeParseAsync$2(inst, data, params);
13195 inst.check = (...checks) => {
13196 return inst.clone({
13197 ...def,
13198 checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
13199 check: ch,
13200 def: { check: "custom" },
13201 onattach: []
13202 } } : ch)]
13203 });
13204 };
13205 inst.clone = (_def, params) => clone(inst, _def, params);
13206 inst.brand = () => inst;
13207 inst.register = ((reg, meta) => {
13208 reg.add(inst, meta);
13209 return inst;
13210 });
13211 });
13212 var ZodMiniObject = /*@__PURE__*/ $constructor("ZodMiniObject", (inst, def) => {
13213 $ZodObject.init(inst, def);
13214 ZodMiniType.init(inst, def);
13215 defineLazy(inst, "shape", () => def.shape);
13216 });
13217 function object(shape, params) {
13218 const def = {
13219 type: "object",
13220 get shape() {
13221 assignProp(this, "shape", { ...shape });
13222 return this.shape;
13223 },
13224 ...normalizeParams(params)
13225 };
13226 return new ZodMiniObject(def);
13227 }
13228
13229 //#endregion
13230 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
13231 function isZ4Schema(s) {
13232 return !!s._zod;
13233 }
13234 function objectFromShape(shape) {
13235 const values = Object.values(shape);
13236 if (values.length === 0) return object({});
13237 const allV4 = values.every(isZ4Schema);
13238 const allV3 = values.every((s) => !isZ4Schema(s));
13239 if (allV4) return object(shape);
13240 if (allV3) return objectType(shape);
13241 throw new Error("Mixed Zod versions detected in object shape.");
13242 }
13243 function safeParse(schema, data) {
13244 if (isZ4Schema(schema)) return safeParse$2(schema, data);
13245 return schema.safeParse(data);
13246 }
13247 async function safeParseAsync(schema, data) {
13248 if (isZ4Schema(schema)) return await safeParseAsync$2(schema, data);
13249 return await schema.safeParseAsync(data);
13250 }
13251 function getObjectShape(schema) {
13252 if (!schema) return void 0;
13253 let rawShape;
13254 if (isZ4Schema(schema)) rawShape = schema._zod?.def?.shape;
13255 else rawShape = schema.shape;
13256 if (!rawShape) return void 0;
13257 if (typeof rawShape === "function") try {
13258 return rawShape();
13259 } catch {
13260 return;
13261 }
13262 return rawShape;
13263 }
13264 /**
13265 * Normalizes a schema to an object schema. Handles both:
13266 * - Already-constructed object schemas (v3 or v4)
13267 * - Raw shapes that need to be wrapped into object schemas
13268 */
13269 function normalizeObjectSchema(schema) {
13270 if (!schema) return void 0;
13271 if (typeof schema === "object") {
13272 const asV3 = schema;
13273 const asV4 = schema;
13274 if (!asV3._def && !asV4._zod) {
13275 const values = Object.values(schema);
13276 if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function"))) return objectFromShape(schema);
13277 }
13278 }
13279 if (isZ4Schema(schema)) {
13280 const def = schema._zod?.def;
13281 if (def && (def.type === "object" || def.shape !== void 0)) return schema;
13282 } else if (schema.shape !== void 0) return schema;
13283 }
13284 /**
13285 * Safely extracts an error message from a parse result error.
13286 * Zod errors can have different structures, so we handle various cases.
13287 */
13288 function getParseErrorMessage(error) {
13289 if (error && typeof error === "object") {
13290 if ("message" in error && typeof error.message === "string") return error.message;
13291 if ("issues" in error && Array.isArray(error.issues) && error.issues.length > 0) {
13292 const firstIssue = error.issues[0];
13293 if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) return String(firstIssue.message);
13294 }
13295 try {
13296 return JSON.stringify(error);
13297 } catch {
13298 return String(error);
13299 }
13300 }
13301 return String(error);
13302 }
13303 /**
13304 * Gets the description from a schema, if available.
13305 * Works with both Zod v3 and v4.
13306 *
13307 * Both versions expose a `.description` getter that returns the description
13308 * from their respective internal storage (v3: _def, v4: globalRegistry).
13309 */
13310 function getSchemaDescription(schema) {
13311 return schema.description;
13312 }
13313 /**
13314 * Checks if a schema is optional.
13315 * Works with both Zod v3 and v4.
13316 */
13317 function isSchemaOptional(schema) {
13318 if (isZ4Schema(schema)) return schema._zod?.def?.type === "optional";
13319 const v3Schema = schema;
13320 if (typeof schema.isOptional === "function") return schema.isOptional();
13321 return v3Schema._def?.typeName === "ZodOptional";
13322 }
13323 /**
13324 * Gets the literal value from a schema, if it's a literal schema.
13325 * Works with both Zod v3 and v4.
13326 * Returns undefined if the schema is not a literal or the value cannot be determined.
13327 */
13328 function getLiteralValue(schema) {
13329 if (isZ4Schema(schema)) {
13330 const def = schema._zod?.def;
13331 if (def) {
13332 if (def.value !== void 0) return def.value;
13333 if (Array.isArray(def.values) && def.values.length > 0) return def.values[0];
13334 }
13335 }
13336 const def = schema._def;
13337 if (def) {
13338 if (def.value !== void 0) return def.value;
13339 if (Array.isArray(def.values) && def.values.length > 0) return def.values[0];
13340 }
13341 const directValue = schema.value;
13342 if (directValue !== void 0) return directValue;
13343 }
13344
13345 //#endregion
13346 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
13347 /**
13348 * Experimental task interfaces for MCP SDK.
13349 * WARNING: These APIs are experimental and may change without notice.
13350 */
13351 /**
13352 * Checks if a task status represents a terminal state.
13353 * Terminal states are those where the task has finished and will not change.
13354 *
13355 * @param status - The task status to check
13356 * @returns True if the status is terminal (completed, failed, or cancelled)
13357 * @experimental
13358 */
13359 function isTerminal(status) {
13360 return status === "completed" || status === "failed" || status === "cancelled";
13361 }
13362
13363 //#endregion
13364 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/Options.js
13365 var ignoreOverride$1 = Symbol("Let zodToJsonSchema decide on which parser to use");
13366 var defaultOptions$1 = {
13367 name: void 0,
13368 $refStrategy: "root",
13369 basePath: ["#"],
13370 effectStrategy: "input",
13371 pipeStrategy: "all",
13372 dateStrategy: "format:date-time",
13373 mapStrategy: "entries",
13374 removeAdditionalStrategy: "passthrough",
13375 allowedAdditionalProperties: true,
13376 rejectedAdditionalProperties: false,
13377 definitionPath: "definitions",
13378 target: "jsonSchema7",
13379 strictUnions: false,
13380 definitions: {},
13381 errorMessages: false,
13382 markdownDescription: false,
13383 patternStrategy: "escape",
13384 applyRegexFlags: false,
13385 emailStrategy: "format:email",
13386 base64Strategy: "contentEncoding:base64",
13387 nameStrategy: "ref",
13388 openAiAnyTypeName: "OpenAiAnyType"
13389 };
13390 var getDefaultOptions$1 = /* @__PURE__ */ __name((options) => typeof options === "string" ? {
13391 ...defaultOptions$1,
13392 name: options
13393 } : {
13394 ...defaultOptions$1,
13395 ...options
13396 }, "getDefaultOptions");
13397
13398 //#endregion
13399 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/Refs.js
13400 var getRefs$1 = /* @__PURE__ */ __name((options) => {
13401 const _options = getDefaultOptions$1(options);
13402 const currentPath = _options.name !== void 0 ? [
13403 ..._options.basePath,
13404 _options.definitionPath,
13405 _options.name
13406 ] : _options.basePath;
13407 return {
13408 ..._options,
13409 flags: { hasReferencedOpenAiAnyType: false },
13410 currentPath,
13411 propertyPath: void 0,
13412 seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, {
13413 def: def._def,
13414 path: [
13415 ..._options.basePath,
13416 _options.definitionPath,
13417 name
13418 ],
13419 jsonSchema: void 0
13420 }]))
13421 };
13422 }, "getRefs");
13423
13424 //#endregion
13425 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
13426 function addErrorMessage$1(res, key, errorMessage, refs) {
13427 if (!refs?.errorMessages) return;
13428 if (errorMessage) res.errorMessage = {
13429 ...res.errorMessage,
13430 [key]: errorMessage
13431 };
13432 }
13433 __name(addErrorMessage$1, "addErrorMessage");
13434 function setResponseValueAndErrors$1(res, key, value, errorMessage, refs) {
13435 res[key] = value;
13436 addErrorMessage$1(res, key, errorMessage, refs);
13437 }
13438 __name(setResponseValueAndErrors$1, "setResponseValueAndErrors");
13439
13440 //#endregion
13441 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
13442 var getRelativePath$1 = /* @__PURE__ */ __name((pathA, pathB) => {
13443 let i = 0;
13444 for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;
13445 return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
13446 }, "getRelativePath");
13447
13448 //#endregion
13449 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
13450 function parseAnyDef$1(refs) {
13451 if (refs.target !== "openAi") return {};
13452 const anyDefinitionPath = [
13453 ...refs.basePath,
13454 refs.definitionPath,
13455 refs.openAiAnyTypeName
13456 ];
13457 refs.flags.hasReferencedOpenAiAnyType = true;
13458 return { $ref: refs.$refStrategy === "relative" ? getRelativePath$1(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") };
13459 }
13460 __name(parseAnyDef$1, "parseAnyDef");
13461
13462 //#endregion
13463 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
13464 function parseArrayDef$1(def, refs) {
13465 const res = { type: "array" };
13466 if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef$1(def.type._def, {
13467 ...refs,
13468 currentPath: [...refs.currentPath, "items"]
13469 });
13470 if (def.minLength) setResponseValueAndErrors$1(res, "minItems", def.minLength.value, def.minLength.message, refs);
13471 if (def.maxLength) setResponseValueAndErrors$1(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
13472 if (def.exactLength) {
13473 setResponseValueAndErrors$1(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
13474 setResponseValueAndErrors$1(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
13475 }
13476 return res;
13477 }
13478 __name(parseArrayDef$1, "parseArrayDef");
13479
13480 //#endregion
13481 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
13482 function parseBigintDef$1(def, refs) {
13483 const res = {
13484 type: "integer",
13485 format: "int64"
13486 };
13487 if (!def.checks) return res;
13488 for (const check of def.checks) switch (check.kind) {
13489 case "min":
13490 if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors$1(res, "minimum", check.value, check.message, refs);
13491 else setResponseValueAndErrors$1(res, "exclusiveMinimum", check.value, check.message, refs);
13492 else {
13493 if (!check.inclusive) res.exclusiveMinimum = true;
13494 setResponseValueAndErrors$1(res, "minimum", check.value, check.message, refs);
13495 }
13496 break;
13497 case "max":
13498 if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors$1(res, "maximum", check.value, check.message, refs);
13499 else setResponseValueAndErrors$1(res, "exclusiveMaximum", check.value, check.message, refs);
13500 else {
13501 if (!check.inclusive) res.exclusiveMaximum = true;
13502 setResponseValueAndErrors$1(res, "maximum", check.value, check.message, refs);
13503 }
13504 break;
13505 case "multipleOf":
13506 setResponseValueAndErrors$1(res, "multipleOf", check.value, check.message, refs);
13507 break;
13508 }
13509 return res;
13510 }
13511 __name(parseBigintDef$1, "parseBigintDef");
13512
13513 //#endregion
13514 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
13515 function parseBooleanDef$1() {
13516 return { type: "boolean" };
13517 }
13518 __name(parseBooleanDef$1, "parseBooleanDef");
13519
13520 //#endregion
13521 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
13522 function parseBrandedDef$1(_def, refs) {
13523 return parseDef$1(_def.type._def, refs);
13524 }
13525 __name(parseBrandedDef$1, "parseBrandedDef");
13526
13527 //#endregion
13528 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
13529 var parseCatchDef$1 = /* @__PURE__ */ __name((def, refs) => {
13530 return parseDef$1(def.innerType._def, refs);
13531 }, "parseCatchDef");
13532
13533 //#endregion
13534 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
13535 function parseDateDef$1(def, refs, overrideDateStrategy) {
13536 const strategy = overrideDateStrategy ?? refs.dateStrategy;
13537 if (Array.isArray(strategy)) return { anyOf: strategy.map((item, i) => parseDateDef$1(def, refs, item)) };
13538 switch (strategy) {
13539 case "string":
13540 case "format:date-time": return {
13541 type: "string",
13542 format: "date-time"
13543 };
13544 case "format:date": return {
13545 type: "string",
13546 format: "date"
13547 };
13548 case "integer": return integerDateParser$1(def, refs);
13549 }
13550 }
13551 __name(parseDateDef$1, "parseDateDef");
13552 var integerDateParser$1 = /* @__PURE__ */ __name((def, refs) => {
13553 const res = {
13554 type: "integer",
13555 format: "unix-time"
13556 };
13557 if (refs.target === "openApi3") return res;
13558 for (const check of def.checks) switch (check.kind) {
13559 case "min":
13560 setResponseValueAndErrors$1(res, "minimum", check.value, check.message, refs);
13561 break;
13562 case "max":
13563 setResponseValueAndErrors$1(res, "maximum", check.value, check.message, refs);
13564 break;
13565 }
13566 return res;
13567 }, "integerDateParser");
13568
13569 //#endregion
13570 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
13571 function parseDefaultDef$1(_def, refs) {
13572 return {
13573 ...parseDef$1(_def.innerType._def, refs),
13574 default: _def.defaultValue()
13575 };
13576 }
13577 __name(parseDefaultDef$1, "parseDefaultDef");
13578
13579 //#endregion
13580 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
13581 function parseEffectsDef$1(_def, refs) {
13582 return refs.effectStrategy === "input" ? parseDef$1(_def.schema._def, refs) : parseAnyDef$1(refs);
13583 }
13584 __name(parseEffectsDef$1, "parseEffectsDef");
13585
13586 //#endregion
13587 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
13588 function parseEnumDef$1(def) {
13589 return {
13590 type: "string",
13591 enum: Array.from(def.values)
13592 };
13593 }
13594 __name(parseEnumDef$1, "parseEnumDef");
13595
13596 //#endregion
13597 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
13598 var isJsonSchema7AllOfType$1 = /* @__PURE__ */ __name((type) => {
13599 if ("type" in type && type.type === "string") return false;
13600 return "allOf" in type;
13601 }, "isJsonSchema7AllOfType");
13602 function parseIntersectionDef$1(def, refs) {
13603 const allOf = [parseDef$1(def.left._def, {
13604 ...refs,
13605 currentPath: [
13606 ...refs.currentPath,
13607 "allOf",
13608 "0"
13609 ]
13610 }), parseDef$1(def.right._def, {
13611 ...refs,
13612 currentPath: [
13613 ...refs.currentPath,
13614 "allOf",
13615 "1"
13616 ]
13617 })].filter((x) => !!x);
13618 let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
13619 const mergedAllOf = [];
13620 allOf.forEach((schema) => {
13621 if (isJsonSchema7AllOfType$1(schema)) {
13622 mergedAllOf.push(...schema.allOf);
13623 if (schema.unevaluatedProperties === void 0) unevaluatedProperties = void 0;
13624 } else {
13625 let nestedSchema = schema;
13626 if ("additionalProperties" in schema && schema.additionalProperties === false) {
13627 const { additionalProperties, ...rest } = schema;
13628 nestedSchema = rest;
13629 } else unevaluatedProperties = void 0;
13630 mergedAllOf.push(nestedSchema);
13631 }
13632 });
13633 return mergedAllOf.length ? {
13634 allOf: mergedAllOf,
13635 ...unevaluatedProperties
13636 } : void 0;
13637 }
13638 __name(parseIntersectionDef$1, "parseIntersectionDef");
13639
13640 //#endregion
13641 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
13642 function parseLiteralDef$1(def, refs) {
13643 const parsedType = typeof def.value;
13644 if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" };
13645 if (refs.target === "openApi3") return {
13646 type: parsedType === "bigint" ? "integer" : parsedType,
13647 enum: [def.value]
13648 };
13649 return {
13650 type: parsedType === "bigint" ? "integer" : parsedType,
13651 const: def.value
13652 };
13653 }
13654 __name(parseLiteralDef$1, "parseLiteralDef");
13655
13656 //#endregion
13657 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
13658 var emojiRegex$1 = void 0;
13659 /**
13660 * Generated from the regular expressions found here as of 2024-05-22:
13661 * https://github.com/colinhacks/zod/blob/master/src/types.ts.
13662 *
13663 * Expressions with /i flag have been changed accordingly.
13664 */
13665 var zodPatterns$1 = {
13666 /**
13667 * `c` was changed to `[cC]` to replicate /i flag
13668 */
13669 cuid: /^[cC][^\s-]{8,}$/,
13670 cuid2: /^[0-9a-z]+$/,
13671 ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
13672 /**
13673 * `a-z` was added to replicate /i flag
13674 */
13675 email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
13676 /**
13677 * Constructed a valid Unicode RegExp
13678 *
13679 * Lazily instantiate since this type of regex isn't supported
13680 * in all envs (e.g. React Native).
13681 *
13682 * See:
13683 * https://github.com/colinhacks/zod/issues/2433
13684 * Fix in Zod:
13685 * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
13686 */
13687 emoji: () => {
13688 if (emojiRegex$1 === void 0) emojiRegex$1 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
13689 return emojiRegex$1;
13690 },
13691 /**
13692 * Unused
13693 */
13694 uuid: /^[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}$/,
13695 /**
13696 * Unused
13697 */
13698 ipv4: /^(?:(?: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])$/,
13699 ipv4Cidr: /^(?:(?: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])$/,
13700 /**
13701 * Unused
13702 */
13703 ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
13704 ipv6Cidr: /^(([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])$/,
13705 base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
13706 base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
13707 nanoid: /^[a-zA-Z0-9_-]{21}$/,
13708 jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
13709 };
13710 function parseStringDef$1(def, refs) {
13711 const res = { type: "string" };
13712 if (def.checks) for (const check of def.checks) switch (check.kind) {
13713 case "min":
13714 setResponseValueAndErrors$1(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
13715 break;
13716 case "max":
13717 setResponseValueAndErrors$1(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
13718 break;
13719 case "email":
13720 switch (refs.emailStrategy) {
13721 case "format:email":
13722 addFormat$1(res, "email", check.message, refs);
13723 break;
13724 case "format:idn-email":
13725 addFormat$1(res, "idn-email", check.message, refs);
13726 break;
13727 case "pattern:zod":
13728 addPattern$1(res, zodPatterns$1.email, check.message, refs);
13729 break;
13730 }
13731 break;
13732 case "url":
13733 addFormat$1(res, "uri", check.message, refs);
13734 break;
13735 case "uuid":
13736 addFormat$1(res, "uuid", check.message, refs);
13737 break;
13738 case "regex":
13739 addPattern$1(res, check.regex, check.message, refs);
13740 break;
13741 case "cuid":
13742 addPattern$1(res, zodPatterns$1.cuid, check.message, refs);
13743 break;
13744 case "cuid2":
13745 addPattern$1(res, zodPatterns$1.cuid2, check.message, refs);
13746 break;
13747 case "startsWith":
13748 addPattern$1(res, RegExp(`^${escapeLiteralCheckValue$1(check.value, refs)}`), check.message, refs);
13749 break;
13750 case "endsWith":
13751 addPattern$1(res, RegExp(`${escapeLiteralCheckValue$1(check.value, refs)}$`), check.message, refs);
13752 break;
13753 case "datetime":
13754 addFormat$1(res, "date-time", check.message, refs);
13755 break;
13756 case "date":
13757 addFormat$1(res, "date", check.message, refs);
13758 break;
13759 case "time":
13760 addFormat$1(res, "time", check.message, refs);
13761 break;
13762 case "duration":
13763 addFormat$1(res, "duration", check.message, refs);
13764 break;
13765 case "length":
13766 setResponseValueAndErrors$1(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
13767 setResponseValueAndErrors$1(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
13768 break;
13769 case "includes":
13770 addPattern$1(res, RegExp(escapeLiteralCheckValue$1(check.value, refs)), check.message, refs);
13771 break;
13772 case "ip":
13773 if (check.version !== "v6") addFormat$1(res, "ipv4", check.message, refs);
13774 if (check.version !== "v4") addFormat$1(res, "ipv6", check.message, refs);
13775 break;
13776 case "base64url":
13777 addPattern$1(res, zodPatterns$1.base64url, check.message, refs);
13778 break;
13779 case "jwt":
13780 addPattern$1(res, zodPatterns$1.jwt, check.message, refs);
13781 break;
13782 case "cidr":
13783 if (check.version !== "v6") addPattern$1(res, zodPatterns$1.ipv4Cidr, check.message, refs);
13784 if (check.version !== "v4") addPattern$1(res, zodPatterns$1.ipv6Cidr, check.message, refs);
13785 break;
13786 case "emoji":
13787 addPattern$1(res, zodPatterns$1.emoji(), check.message, refs);
13788 break;
13789 case "ulid":
13790 addPattern$1(res, zodPatterns$1.ulid, check.message, refs);
13791 break;
13792 case "base64":
13793 switch (refs.base64Strategy) {
13794 case "format:binary":
13795 addFormat$1(res, "binary", check.message, refs);
13796 break;
13797 case "contentEncoding:base64":
13798 setResponseValueAndErrors$1(res, "contentEncoding", "base64", check.message, refs);
13799 break;
13800 case "pattern:zod":
13801 addPattern$1(res, zodPatterns$1.base64, check.message, refs);
13802 break;
13803 }
13804 break;
13805 case "nanoid": addPattern$1(res, zodPatterns$1.nanoid, check.message, refs);
13806 case "toLowerCase":
13807 case "toUpperCase":
13808 case "trim": break;
13809 default:
13810 }
13811 return res;
13812 }
13813 __name(parseStringDef$1, "parseStringDef");
13814 function escapeLiteralCheckValue$1(literal, refs) {
13815 return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric$1(literal) : literal;
13816 }
13817 __name(escapeLiteralCheckValue$1, "escapeLiteralCheckValue");
13818 var ALPHA_NUMERIC$1 = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
13819 function escapeNonAlphaNumeric$1(source) {
13820 let result = "";
13821 for (let i = 0; i < source.length; i++) {
13822 if (!ALPHA_NUMERIC$1.has(source[i])) result += "\\";
13823 result += source[i];
13824 }
13825 return result;
13826 }
13827 __name(escapeNonAlphaNumeric$1, "escapeNonAlphaNumeric");
13828 function addFormat$1(schema, value, message, refs) {
13829 if (schema.format || schema.anyOf?.some((x) => x.format)) {
13830 if (!schema.anyOf) schema.anyOf = [];
13831 if (schema.format) {
13832 schema.anyOf.push({
13833 format: schema.format,
13834 ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } }
13835 });
13836 delete schema.format;
13837 if (schema.errorMessage) {
13838 delete schema.errorMessage.format;
13839 if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage;
13840 }
13841 }
13842 schema.anyOf.push({
13843 format: value,
13844 ...message && refs.errorMessages && { errorMessage: { format: message } }
13845 });
13846 } else setResponseValueAndErrors$1(schema, "format", value, message, refs);
13847 }
13848 __name(addFormat$1, "addFormat");
13849 function addPattern$1(schema, regex, message, refs) {
13850 if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
13851 if (!schema.allOf) schema.allOf = [];
13852 if (schema.pattern) {
13853 schema.allOf.push({
13854 pattern: schema.pattern,
13855 ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } }
13856 });
13857 delete schema.pattern;
13858 if (schema.errorMessage) {
13859 delete schema.errorMessage.pattern;
13860 if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage;
13861 }
13862 }
13863 schema.allOf.push({
13864 pattern: stringifyRegExpWithFlags$1(regex, refs),
13865 ...message && refs.errorMessages && { errorMessage: { pattern: message } }
13866 });
13867 } else setResponseValueAndErrors$1(schema, "pattern", stringifyRegExpWithFlags$1(regex, refs), message, refs);
13868 }
13869 __name(addPattern$1, "addPattern");
13870 function stringifyRegExpWithFlags$1(regex, refs) {
13871 if (!refs.applyRegexFlags || !regex.flags) return regex.source;
13872 const flags = {
13873 i: regex.flags.includes("i"),
13874 m: regex.flags.includes("m"),
13875 s: regex.flags.includes("s")
13876 };
13877 const source = flags.i ? regex.source.toLowerCase() : regex.source;
13878 let pattern = "";
13879 let isEscaped = false;
13880 let inCharGroup = false;
13881 let inCharRange = false;
13882 for (let i = 0; i < source.length; i++) {
13883 if (isEscaped) {
13884 pattern += source[i];
13885 isEscaped = false;
13886 continue;
13887 }
13888 if (flags.i) {
13889 if (inCharGroup) {
13890 if (source[i].match(/[a-z]/)) {
13891 if (inCharRange) {
13892 pattern += source[i];
13893 pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
13894 inCharRange = false;
13895 } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
13896 pattern += source[i];
13897 inCharRange = true;
13898 } else pattern += `${source[i]}${source[i].toUpperCase()}`;
13899 continue;
13900 }
13901 } else if (source[i].match(/[a-z]/)) {
13902 pattern += `[${source[i]}${source[i].toUpperCase()}]`;
13903 continue;
13904 }
13905 }
13906 if (flags.m) {
13907 if (source[i] === "^") {
13908 pattern += `(^|(?<=[\r\n]))`;
13909 continue;
13910 } else if (source[i] === "$") {
13911 pattern += `($|(?=[\r\n]))`;
13912 continue;
13913 }
13914 }
13915 if (flags.s && source[i] === ".") {
13916 pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
13917 continue;
13918 }
13919 pattern += source[i];
13920 if (source[i] === "\\") isEscaped = true;
13921 else if (inCharGroup && source[i] === "]") inCharGroup = false;
13922 else if (!inCharGroup && source[i] === "[") inCharGroup = true;
13923 }
13924 try {
13925 new RegExp(pattern);
13926 } catch {
13927 console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
13928 return regex.source;
13929 }
13930 return pattern;
13931 }
13932 __name(stringifyRegExpWithFlags$1, "stringifyRegExpWithFlags");
13933
13934 //#endregion
13935 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
13936 function parseRecordDef$1(def, refs) {
13937 if (refs.target === "openAi") console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
13938 if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return {
13939 type: "object",
13940 required: def.keyType._def.values,
13941 properties: def.keyType._def.values.reduce((acc, key) => ({
13942 ...acc,
13943 [key]: parseDef$1(def.valueType._def, {
13944 ...refs,
13945 currentPath: [
13946 ...refs.currentPath,
13947 "properties",
13948 key
13949 ]
13950 }) ?? parseAnyDef$1(refs)
13951 }), {}),
13952 additionalProperties: refs.rejectedAdditionalProperties
13953 };
13954 const schema = {
13955 type: "object",
13956 additionalProperties: parseDef$1(def.valueType._def, {
13957 ...refs,
13958 currentPath: [...refs.currentPath, "additionalProperties"]
13959 }) ?? refs.allowedAdditionalProperties
13960 };
13961 if (refs.target === "openApi3") return schema;
13962 if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
13963 const { type, ...keyType } = parseStringDef$1(def.keyType._def, refs);
13964 return {
13965 ...schema,
13966 propertyNames: keyType
13967 };
13968 } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return {
13969 ...schema,
13970 propertyNames: { enum: def.keyType._def.values }
13971 };
13972 else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
13973 const { type, ...keyType } = parseBrandedDef$1(def.keyType._def, refs);
13974 return {
13975 ...schema,
13976 propertyNames: keyType
13977 };
13978 }
13979 return schema;
13980 }
13981 __name(parseRecordDef$1, "parseRecordDef");
13982
13983 //#endregion
13984 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
13985 function parseMapDef$1(def, refs) {
13986 if (refs.mapStrategy === "record") return parseRecordDef$1(def, refs);
13987 return {
13988 type: "array",
13989 maxItems: 125,
13990 items: {
13991 type: "array",
13992 items: [parseDef$1(def.keyType._def, {
13993 ...refs,
13994 currentPath: [
13995 ...refs.currentPath,
13996 "items",
13997 "items",
13998 "0"
13999 ]
14000 }) || parseAnyDef$1(refs), parseDef$1(def.valueType._def, {
14001 ...refs,
14002 currentPath: [
14003 ...refs.currentPath,
14004 "items",
14005 "items",
14006 "1"
14007 ]
14008 }) || parseAnyDef$1(refs)],
14009 minItems: 2,
14010 maxItems: 2
14011 }
14012 };
14013 }
14014 __name(parseMapDef$1, "parseMapDef");
14015
14016 //#endregion
14017 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
14018 function parseNativeEnumDef$1(def) {
14019 const object = def.values;
14020 const actualValues = Object.keys(def.values).filter((key) => {
14021 return typeof object[object[key]] !== "number";
14022 }).map((key) => object[key]);
14023 const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
14024 return {
14025 type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
14026 enum: actualValues
14027 };
14028 }
14029 __name(parseNativeEnumDef$1, "parseNativeEnumDef");
14030
14031 //#endregion
14032 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
14033 function parseNeverDef$1(refs) {
14034 return refs.target === "openAi" ? void 0 : { not: parseAnyDef$1({
14035 ...refs,
14036 currentPath: [...refs.currentPath, "not"]
14037 }) };
14038 }
14039 __name(parseNeverDef$1, "parseNeverDef");
14040
14041 //#endregion
14042 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
14043 function parseNullDef$1(refs) {
14044 return refs.target === "openApi3" ? {
14045 enum: ["null"],
14046 nullable: true
14047 } : { type: "null" };
14048 }
14049 __name(parseNullDef$1, "parseNullDef");
14050
14051 //#endregion
14052 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
14053 var primitiveMappings$1 = {
14054 ZodString: "string",
14055 ZodNumber: "number",
14056 ZodBigInt: "integer",
14057 ZodBoolean: "boolean",
14058 ZodNull: "null"
14059 };
14060 function parseUnionDef$1(def, refs) {
14061 if (refs.target === "openApi3") return asAnyOf$1(def, refs);
14062 const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
14063 if (options.every((x) => x._def.typeName in primitiveMappings$1 && (!x._def.checks || !x._def.checks.length))) {
14064 const types = options.reduce((types, x) => {
14065 const type = primitiveMappings$1[x._def.typeName];
14066 return type && !types.includes(type) ? [...types, type] : types;
14067 }, []);
14068 return { type: types.length > 1 ? types : types[0] };
14069 } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
14070 const types = options.reduce((acc, x) => {
14071 const type = typeof x._def.value;
14072 switch (type) {
14073 case "string":
14074 case "number":
14075 case "boolean": return [...acc, type];
14076 case "bigint": return [...acc, "integer"];
14077 case "object": if (x._def.value === null) return [...acc, "null"];
14078 default: return acc;
14079 }
14080 }, []);
14081 if (types.length === options.length) {
14082 const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
14083 return {
14084 type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
14085 enum: options.reduce((acc, x) => {
14086 return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
14087 }, [])
14088 };
14089 }
14090 } else if (options.every((x) => x._def.typeName === "ZodEnum")) return {
14091 type: "string",
14092 enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], [])
14093 };
14094 return asAnyOf$1(def, refs);
14095 }
14096 __name(parseUnionDef$1, "parseUnionDef");
14097 var asAnyOf$1 = /* @__PURE__ */ __name((def, refs) => {
14098 const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef$1(x._def, {
14099 ...refs,
14100 currentPath: [
14101 ...refs.currentPath,
14102 "anyOf",
14103 `${i}`
14104 ]
14105 })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
14106 return anyOf.length ? { anyOf } : void 0;
14107 }, "asAnyOf");
14108
14109 //#endregion
14110 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
14111 function parseNullableDef$1(def, refs) {
14112 if ([
14113 "ZodString",
14114 "ZodNumber",
14115 "ZodBigInt",
14116 "ZodBoolean",
14117 "ZodNull"
14118 ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
14119 if (refs.target === "openApi3") return {
14120 type: primitiveMappings$1[def.innerType._def.typeName],
14121 nullable: true
14122 };
14123 return { type: [primitiveMappings$1[def.innerType._def.typeName], "null"] };
14124 }
14125 if (refs.target === "openApi3") {
14126 const base = parseDef$1(def.innerType._def, {
14127 ...refs,
14128 currentPath: [...refs.currentPath]
14129 });
14130 if (base && "$ref" in base) return {
14131 allOf: [base],
14132 nullable: true
14133 };
14134 return base && {
14135 ...base,
14136 nullable: true
14137 };
14138 }
14139 const base = parseDef$1(def.innerType._def, {
14140 ...refs,
14141 currentPath: [
14142 ...refs.currentPath,
14143 "anyOf",
14144 "0"
14145 ]
14146 });
14147 return base && { anyOf: [base, { type: "null" }] };
14148 }
14149 __name(parseNullableDef$1, "parseNullableDef");
14150
14151 //#endregion
14152 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
14153 function parseNumberDef$1(def, refs) {
14154 const res = { type: "number" };
14155 if (!def.checks) return res;
14156 for (const check of def.checks) switch (check.kind) {
14157 case "int":
14158 res.type = "integer";
14159 addErrorMessage$1(res, "type", check.message, refs);
14160 break;
14161 case "min":
14162 if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors$1(res, "minimum", check.value, check.message, refs);
14163 else setResponseValueAndErrors$1(res, "exclusiveMinimum", check.value, check.message, refs);
14164 else {
14165 if (!check.inclusive) res.exclusiveMinimum = true;
14166 setResponseValueAndErrors$1(res, "minimum", check.value, check.message, refs);
14167 }
14168 break;
14169 case "max":
14170 if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors$1(res, "maximum", check.value, check.message, refs);
14171 else setResponseValueAndErrors$1(res, "exclusiveMaximum", check.value, check.message, refs);
14172 else {
14173 if (!check.inclusive) res.exclusiveMaximum = true;
14174 setResponseValueAndErrors$1(res, "maximum", check.value, check.message, refs);
14175 }
14176 break;
14177 case "multipleOf":
14178 setResponseValueAndErrors$1(res, "multipleOf", check.value, check.message, refs);
14179 break;
14180 }
14181 return res;
14182 }
14183 __name(parseNumberDef$1, "parseNumberDef");
14184
14185 //#endregion
14186 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
14187 function parseObjectDef$1(def, refs) {
14188 const forceOptionalIntoNullable = refs.target === "openAi";
14189 const result = {
14190 type: "object",
14191 properties: {}
14192 };
14193 const required = [];
14194 const shape = def.shape();
14195 for (const propName in shape) {
14196 let propDef = shape[propName];
14197 if (propDef === void 0 || propDef._def === void 0) continue;
14198 let propOptional = safeIsOptional$1(propDef);
14199 if (propOptional && forceOptionalIntoNullable) {
14200 if (propDef._def.typeName === "ZodOptional") propDef = propDef._def.innerType;
14201 if (!propDef.isNullable()) propDef = propDef.nullable();
14202 propOptional = false;
14203 }
14204 const parsedDef = parseDef$1(propDef._def, {
14205 ...refs,
14206 currentPath: [
14207 ...refs.currentPath,
14208 "properties",
14209 propName
14210 ],
14211 propertyPath: [
14212 ...refs.currentPath,
14213 "properties",
14214 propName
14215 ]
14216 });
14217 if (parsedDef === void 0) continue;
14218 result.properties[propName] = parsedDef;
14219 if (!propOptional) required.push(propName);
14220 }
14221 if (required.length) result.required = required;
14222 const additionalProperties = decideAdditionalProperties$1(def, refs);
14223 if (additionalProperties !== void 0) result.additionalProperties = additionalProperties;
14224 return result;
14225 }
14226 __name(parseObjectDef$1, "parseObjectDef");
14227 function decideAdditionalProperties$1(def, refs) {
14228 if (def.catchall._def.typeName !== "ZodNever") return parseDef$1(def.catchall._def, {
14229 ...refs,
14230 currentPath: [...refs.currentPath, "additionalProperties"]
14231 });
14232 switch (def.unknownKeys) {
14233 case "passthrough": return refs.allowedAdditionalProperties;
14234 case "strict": return refs.rejectedAdditionalProperties;
14235 case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
14236 }
14237 }
14238 __name(decideAdditionalProperties$1, "decideAdditionalProperties");
14239 function safeIsOptional$1(schema) {
14240 try {
14241 return schema.isOptional();
14242 } catch {
14243 return true;
14244 }
14245 }
14246 __name(safeIsOptional$1, "safeIsOptional");
14247
14248 //#endregion
14249 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
14250 var parseOptionalDef$1 = /* @__PURE__ */ __name((def, refs) => {
14251 if (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef$1(def.innerType._def, refs);
14252 const innerSchema = parseDef$1(def.innerType._def, {
14253 ...refs,
14254 currentPath: [
14255 ...refs.currentPath,
14256 "anyOf",
14257 "1"
14258 ]
14259 });
14260 return innerSchema ? { anyOf: [{ not: parseAnyDef$1(refs) }, innerSchema] } : parseAnyDef$1(refs);
14261 }, "parseOptionalDef");
14262
14263 //#endregion
14264 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
14265 var parsePipelineDef$1 = /* @__PURE__ */ __name((def, refs) => {
14266 if (refs.pipeStrategy === "input") return parseDef$1(def.in._def, refs);
14267 else if (refs.pipeStrategy === "output") return parseDef$1(def.out._def, refs);
14268 const a = parseDef$1(def.in._def, {
14269 ...refs,
14270 currentPath: [
14271 ...refs.currentPath,
14272 "allOf",
14273 "0"
14274 ]
14275 });
14276 return { allOf: [a, parseDef$1(def.out._def, {
14277 ...refs,
14278 currentPath: [
14279 ...refs.currentPath,
14280 "allOf",
14281 a ? "1" : "0"
14282 ]
14283 })].filter((x) => x !== void 0) };
14284 }, "parsePipelineDef");
14285
14286 //#endregion
14287 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
14288 function parsePromiseDef$1(def, refs) {
14289 return parseDef$1(def.type._def, refs);
14290 }
14291 __name(parsePromiseDef$1, "parsePromiseDef");
14292
14293 //#endregion
14294 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
14295 function parseSetDef$1(def, refs) {
14296 const schema = {
14297 type: "array",
14298 uniqueItems: true,
14299 items: parseDef$1(def.valueType._def, {
14300 ...refs,
14301 currentPath: [...refs.currentPath, "items"]
14302 })
14303 };
14304 if (def.minSize) setResponseValueAndErrors$1(schema, "minItems", def.minSize.value, def.minSize.message, refs);
14305 if (def.maxSize) setResponseValueAndErrors$1(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
14306 return schema;
14307 }
14308 __name(parseSetDef$1, "parseSetDef");
14309
14310 //#endregion
14311 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
14312 function parseTupleDef$1(def, refs) {
14313 if (def.rest) return {
14314 type: "array",
14315 minItems: def.items.length,
14316 items: def.items.map((x, i) => parseDef$1(x._def, {
14317 ...refs,
14318 currentPath: [
14319 ...refs.currentPath,
14320 "items",
14321 `${i}`
14322 ]
14323 })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
14324 additionalItems: parseDef$1(def.rest._def, {
14325 ...refs,
14326 currentPath: [...refs.currentPath, "additionalItems"]
14327 })
14328 };
14329 else return {
14330 type: "array",
14331 minItems: def.items.length,
14332 maxItems: def.items.length,
14333 items: def.items.map((x, i) => parseDef$1(x._def, {
14334 ...refs,
14335 currentPath: [
14336 ...refs.currentPath,
14337 "items",
14338 `${i}`
14339 ]
14340 })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
14341 };
14342 }
14343 __name(parseTupleDef$1, "parseTupleDef");
14344
14345 //#endregion
14346 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
14347 function parseUndefinedDef$1(refs) {
14348 return { not: parseAnyDef$1(refs) };
14349 }
14350 __name(parseUndefinedDef$1, "parseUndefinedDef");
14351
14352 //#endregion
14353 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
14354 function parseUnknownDef$1(refs) {
14355 return parseAnyDef$1(refs);
14356 }
14357 __name(parseUnknownDef$1, "parseUnknownDef");
14358
14359 //#endregion
14360 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
14361 var parseReadonlyDef$1 = /* @__PURE__ */ __name((def, refs) => {
14362 return parseDef$1(def.innerType._def, refs);
14363 }, "parseReadonlyDef");
14364
14365 //#endregion
14366 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/selectParser.js
14367 var selectParser$1 = /* @__PURE__ */ __name((def, typeName, refs) => {
14368 switch (typeName) {
14369 case ZodFirstPartyTypeKind.ZodString: return parseStringDef$1(def, refs);
14370 case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef$1(def, refs);
14371 case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef$1(def, refs);
14372 case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef$1(def, refs);
14373 case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef$1();
14374 case ZodFirstPartyTypeKind.ZodDate: return parseDateDef$1(def, refs);
14375 case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef$1(refs);
14376 case ZodFirstPartyTypeKind.ZodNull: return parseNullDef$1(refs);
14377 case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef$1(def, refs);
14378 case ZodFirstPartyTypeKind.ZodUnion:
14379 case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef$1(def, refs);
14380 case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef$1(def, refs);
14381 case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef$1(def, refs);
14382 case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef$1(def, refs);
14383 case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef$1(def, refs);
14384 case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef$1(def);
14385 case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef$1(def);
14386 case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef$1(def, refs);
14387 case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef$1(def, refs);
14388 case ZodFirstPartyTypeKind.ZodMap: return parseMapDef$1(def, refs);
14389 case ZodFirstPartyTypeKind.ZodSet: return parseSetDef$1(def, refs);
14390 case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
14391 case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef$1(def, refs);
14392 case ZodFirstPartyTypeKind.ZodNaN:
14393 case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef$1(refs);
14394 case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef$1(def, refs);
14395 case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef$1(refs);
14396 case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef$1(refs);
14397 case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef$1(def, refs);
14398 case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef$1(def, refs);
14399 case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef$1(def, refs);
14400 case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef$1(def, refs);
14401 case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef$1(def, refs);
14402 case ZodFirstPartyTypeKind.ZodFunction:
14403 case ZodFirstPartyTypeKind.ZodVoid:
14404 case ZodFirstPartyTypeKind.ZodSymbol: return;
14405 default: return ((_) => void 0)(typeName);
14406 }
14407 }, "selectParser");
14408
14409 //#endregion
14410 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parseDef.js
14411 function parseDef$1(def, refs, forceResolution = false) {
14412 const seenItem = refs.seen.get(def);
14413 if (refs.override) {
14414 const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
14415 if (overrideResult !== ignoreOverride$1) return overrideResult;
14416 }
14417 if (seenItem && !forceResolution) {
14418 const seenSchema = get$ref$1(seenItem, refs);
14419 if (seenSchema !== void 0) return seenSchema;
14420 }
14421 const newItem = {
14422 def,
14423 path: refs.currentPath,
14424 jsonSchema: void 0
14425 };
14426 refs.seen.set(def, newItem);
14427 const jsonSchemaOrGetter = selectParser$1(def, def.typeName, refs);
14428 const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef$1(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
14429 if (jsonSchema) addMeta$1(def, refs, jsonSchema);
14430 if (refs.postProcess) {
14431 const postProcessResult = refs.postProcess(jsonSchema, def, refs);
14432 newItem.jsonSchema = jsonSchema;
14433 return postProcessResult;
14434 }
14435 newItem.jsonSchema = jsonSchema;
14436 return jsonSchema;
14437 }
14438 __name(parseDef$1, "parseDef");
14439 var get$ref$1 = /* @__PURE__ */ __name((item, refs) => {
14440 switch (refs.$refStrategy) {
14441 case "root": return { $ref: item.path.join("/") };
14442 case "relative": return { $ref: getRelativePath$1(refs.currentPath, item.path) };
14443 case "none":
14444 case "seen":
14445 if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
14446 console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
14447 return parseAnyDef$1(refs);
14448 }
14449 return refs.$refStrategy === "seen" ? parseAnyDef$1(refs) : void 0;
14450 }
14451 }, "get$ref");
14452 var addMeta$1 = /* @__PURE__ */ __name((def, refs, jsonSchema) => {
14453 if (def.description) {
14454 jsonSchema.description = def.description;
14455 if (refs.markdownDescription) jsonSchema.markdownDescription = def.description;
14456 }
14457 return jsonSchema;
14458 }, "addMeta");
14459
14460 //#endregion
14461 //#region node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
14462 var zodToJsonSchema$1 = /* @__PURE__ */ __name((schema, options) => {
14463 const refs = getRefs$1(options);
14464 let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({
14465 ...acc,
14466 [name]: parseDef$1(schema._def, {
14467 ...refs,
14468 currentPath: [
14469 ...refs.basePath,
14470 refs.definitionPath,
14471 name
14472 ]
14473 }, true) ?? parseAnyDef$1(refs)
14474 }), {}) : void 0;
14475 const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
14476 const main = parseDef$1(schema._def, name === void 0 ? refs : {
14477 ...refs,
14478 currentPath: [
14479 ...refs.basePath,
14480 refs.definitionPath,
14481 name
14482 ]
14483 }, false) ?? parseAnyDef$1(refs);
14484 const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
14485 if (title !== void 0) main.title = title;
14486 if (refs.flags.hasReferencedOpenAiAnyType) {
14487 if (!definitions) definitions = {};
14488 if (!definitions[refs.openAiAnyTypeName]) definitions[refs.openAiAnyTypeName] = {
14489 type: [
14490 "string",
14491 "number",
14492 "integer",
14493 "boolean",
14494 "array",
14495 "null"
14496 ],
14497 items: { $ref: refs.$refStrategy === "relative" ? "1" : [
14498 ...refs.basePath,
14499 refs.definitionPath,
14500 refs.openAiAnyTypeName
14501 ].join("/") }
14502 };
14503 }
14504 const combined = name === void 0 ? definitions ? {
14505 ...main,
14506 [refs.definitionPath]: definitions
14507 } : main : {
14508 $ref: [
14509 ...refs.$refStrategy === "relative" ? [] : refs.basePath,
14510 refs.definitionPath,
14511 name
14512 ].join("/"),
14513 [refs.definitionPath]: {
14514 ...definitions,
14515 [name]: main
14516 }
14517 };
14518 if (refs.target === "jsonSchema7") combined.$schema = "http://json-schema.org/draft-07/schema#";
14519 else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
14520 if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
14521 return combined;
14522 }, "zodToJsonSchema");
14523
14524 //#endregion
14525 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
14526 function mapMiniTarget(t) {
14527 if (!t) return "draft-7";
14528 if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
14529 if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
14530 return "draft-7";
14531 }
14532 function toJsonSchemaCompat(schema, opts) {
14533 if (isZ4Schema(schema)) return toJSONSchema(schema, {
14534 target: mapMiniTarget(opts?.target),
14535 io: opts?.pipeStrategy ?? "input"
14536 });
14537 return zodToJsonSchema$1(schema, {
14538 strictUnions: opts?.strictUnions ?? true,
14539 pipeStrategy: opts?.pipeStrategy ?? "input"
14540 });
14541 }
14542 function getMethodLiteral(schema) {
14543 const methodSchema = getObjectShape(schema)?.method;
14544 if (!methodSchema) throw new Error("Schema is missing a method literal");
14545 const value = getLiteralValue(methodSchema);
14546 if (typeof value !== "string") throw new Error("Schema method literal must be a string");
14547 return value;
14548 }
14549 function parseWithCompat(schema, data) {
14550 const result = safeParse(schema, data);
14551 if (!result.success) throw result.error;
14552 return result.data;
14553 }
14554
14555 //#endregion
14556 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
14557 /**
14558 * The default request timeout, in miliseconds.
14559 */
14560 var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
14561 /**
14562 * Implements MCP protocol framing on top of a pluggable transport, including
14563 * features like request/response linking, notifications, and progress.
14564 */
14565 var Protocol = class {
14566 constructor(_options) {
14567 this._options = _options;
14568 this._requestMessageId = 0;
14569 this._requestHandlers = /* @__PURE__ */ new Map();
14570 this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();
14571 this._notificationHandlers = /* @__PURE__ */ new Map();
14572 this._responseHandlers = /* @__PURE__ */ new Map();
14573 this._progressHandlers = /* @__PURE__ */ new Map();
14574 this._timeoutInfo = /* @__PURE__ */ new Map();
14575 this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
14576 this._taskProgressTokens = /* @__PURE__ */ new Map();
14577 this._requestResolvers = /* @__PURE__ */ new Map();
14578 this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
14579 this._oncancel(notification);
14580 });
14581 this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
14582 this._onprogress(notification);
14583 });
14584 this.setRequestHandler(PingRequestSchema, (_request) => ({}));
14585 this._taskStore = _options?.taskStore;
14586 this._taskMessageQueue = _options?.taskMessageQueue;
14587 if (this._taskStore) {
14588 this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
14589 const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
14590 if (!task) throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
14591 return { ...task };
14592 });
14593 this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
14594 const handleTaskResult = async () => {
14595 const taskId = request.params.taskId;
14596 if (this._taskMessageQueue) {
14597 let queuedMessage;
14598 while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
14599 if (queuedMessage.type === "response" || queuedMessage.type === "error") {
14600 const message = queuedMessage.message;
14601 const requestId = message.id;
14602 const resolver = this._requestResolvers.get(requestId);
14603 if (resolver) {
14604 this._requestResolvers.delete(requestId);
14605 if (queuedMessage.type === "response") resolver(message);
14606 else {
14607 const errorMessage = message;
14608 resolver(new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data));
14609 }
14610 } else {
14611 const messageType = queuedMessage.type === "response" ? "Response" : "Error";
14612 this._onerror(/* @__PURE__ */ new Error(`${messageType} handler missing for request ${requestId}`));
14613 }
14614 continue;
14615 }
14616 await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
14617 }
14618 }
14619 const task = await this._taskStore.getTask(taskId, extra.sessionId);
14620 if (!task) throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
14621 if (!isTerminal(task.status)) {
14622 await this._waitForTaskUpdate(taskId, extra.signal);
14623 return await handleTaskResult();
14624 }
14625 if (isTerminal(task.status)) {
14626 const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
14627 this._clearTaskQueue(taskId);
14628 return {
14629 ...result,
14630 _meta: {
14631 ...result._meta,
14632 [RELATED_TASK_META_KEY]: { taskId }
14633 }
14634 };
14635 }
14636 return await handleTaskResult();
14637 };
14638 return await handleTaskResult();
14639 });
14640 this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
14641 try {
14642 const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
14643 return {
14644 tasks,
14645 nextCursor,
14646 _meta: {}
14647 };
14648 } catch (error) {
14649 throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);
14650 }
14651 });
14652 this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
14653 try {
14654 const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
14655 if (!task) throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
14656 if (isTerminal(task.status)) throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
14657 await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
14658 this._clearTaskQueue(request.params.taskId);
14659 const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
14660 if (!cancelledTask) throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
14661 return {
14662 _meta: {},
14663 ...cancelledTask
14664 };
14665 } catch (error) {
14666 if (error instanceof McpError) throw error;
14667 throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);
14668 }
14669 });
14670 }
14671 }
14672 async _oncancel(notification) {
14673 if (!notification.params.requestId) return;
14674 this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason);
14675 }
14676 _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
14677 this._timeoutInfo.set(messageId, {
14678 timeoutId: setTimeout(onTimeout, timeout),
14679 startTime: Date.now(),
14680 timeout,
14681 maxTotalTimeout,
14682 resetTimeoutOnProgress,
14683 onTimeout
14684 });
14685 }
14686 _resetTimeout(messageId) {
14687 const info = this._timeoutInfo.get(messageId);
14688 if (!info) return false;
14689 const totalElapsed = Date.now() - info.startTime;
14690 if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
14691 this._timeoutInfo.delete(messageId);
14692 throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
14693 maxTotalTimeout: info.maxTotalTimeout,
14694 totalElapsed
14695 });
14696 }
14697 clearTimeout(info.timeoutId);
14698 info.timeoutId = setTimeout(info.onTimeout, info.timeout);
14699 return true;
14700 }
14701 _cleanupTimeout(messageId) {
14702 const info = this._timeoutInfo.get(messageId);
14703 if (info) {
14704 clearTimeout(info.timeoutId);
14705 this._timeoutInfo.delete(messageId);
14706 }
14707 }
14708 /**
14709 * Attaches to the given transport, starts it, and starts listening for messages.
14710 *
14711 * 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.
14712 */
14713 async connect(transport) {
14714 if (this._transport) throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");
14715 this._transport = transport;
14716 const _onclose = this.transport?.onclose;
14717 this._transport.onclose = () => {
14718 _onclose?.();
14719 this._onclose();
14720 };
14721 const _onerror = this.transport?.onerror;
14722 this._transport.onerror = (error) => {
14723 _onerror?.(error);
14724 this._onerror(error);
14725 };
14726 const _onmessage = this._transport?.onmessage;
14727 this._transport.onmessage = (message, extra) => {
14728 _onmessage?.(message, extra);
14729 if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) this._onresponse(message);
14730 else if (isJSONRPCRequest(message)) this._onrequest(message, extra);
14731 else if (isJSONRPCNotification(message)) this._onnotification(message);
14732 else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`));
14733 };
14734 await this._transport.start();
14735 }
14736 _onclose() {
14737 const responseHandlers = this._responseHandlers;
14738 this._responseHandlers = /* @__PURE__ */ new Map();
14739 this._progressHandlers.clear();
14740 this._taskProgressTokens.clear();
14741 this._pendingDebouncedNotifications.clear();
14742 for (const controller of this._requestHandlerAbortControllers.values()) controller.abort();
14743 this._requestHandlerAbortControllers.clear();
14744 const error = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
14745 this._transport = void 0;
14746 this.onclose?.();
14747 for (const handler of responseHandlers.values()) handler(error);
14748 }
14749 _onerror(error) {
14750 this.onerror?.(error);
14751 }
14752 _onnotification(notification) {
14753 const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
14754 if (handler === void 0) return;
14755 Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`)));
14756 }
14757 _onrequest(request, extra) {
14758 const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
14759 const capturedTransport = this._transport;
14760 const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
14761 if (handler === void 0) {
14762 const errorResponse = {
14763 jsonrpc: "2.0",
14764 id: request.id,
14765 error: {
14766 code: ErrorCode.MethodNotFound,
14767 message: "Method not found"
14768 }
14769 };
14770 if (relatedTaskId && this._taskMessageQueue) this._enqueueTaskMessage(relatedTaskId, {
14771 type: "error",
14772 message: errorResponse,
14773 timestamp: Date.now()
14774 }, capturedTransport?.sessionId).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to enqueue error response: ${error}`)));
14775 else capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`)));
14776 return;
14777 }
14778 const abortController = new AbortController();
14779 this._requestHandlerAbortControllers.set(request.id, abortController);
14780 const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
14781 const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;
14782 const fullExtra = {
14783 signal: abortController.signal,
14784 sessionId: capturedTransport?.sessionId,
14785 _meta: request.params?._meta,
14786 sendNotification: async (notification) => {
14787 if (abortController.signal.aborted) return;
14788 const notificationOptions = { relatedRequestId: request.id };
14789 if (relatedTaskId) notificationOptions.relatedTask = { taskId: relatedTaskId };
14790 await this.notification(notification, notificationOptions);
14791 },
14792 sendRequest: async (r, resultSchema, options) => {
14793 if (abortController.signal.aborted) throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
14794 const requestOptions = {
14795 ...options,
14796 relatedRequestId: request.id
14797 };
14798 if (relatedTaskId && !requestOptions.relatedTask) requestOptions.relatedTask = { taskId: relatedTaskId };
14799 const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
14800 if (effectiveTaskId && taskStore) await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
14801 return await this.request(r, resultSchema, requestOptions);
14802 },
14803 authInfo: extra?.authInfo,
14804 requestId: request.id,
14805 requestInfo: extra?.requestInfo,
14806 taskId: relatedTaskId,
14807 taskStore,
14808 taskRequestedTtl: taskCreationParams?.ttl,
14809 closeSSEStream: extra?.closeSSEStream,
14810 closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
14811 };
14812 Promise.resolve().then(() => {
14813 if (taskCreationParams) this.assertTaskHandlerCapability(request.method);
14814 }).then(() => handler(request, fullExtra)).then(async (result) => {
14815 if (abortController.signal.aborted) return;
14816 const response = {
14817 result,
14818 jsonrpc: "2.0",
14819 id: request.id
14820 };
14821 if (relatedTaskId && this._taskMessageQueue) await this._enqueueTaskMessage(relatedTaskId, {
14822 type: "response",
14823 message: response,
14824 timestamp: Date.now()
14825 }, capturedTransport?.sessionId);
14826 else await capturedTransport?.send(response);
14827 }, async (error) => {
14828 if (abortController.signal.aborted) return;
14829 const errorResponse = {
14830 jsonrpc: "2.0",
14831 id: request.id,
14832 error: {
14833 code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
14834 message: error.message ?? "Internal error",
14835 ...error["data"] !== void 0 && { data: error["data"] }
14836 }
14837 };
14838 if (relatedTaskId && this._taskMessageQueue) await this._enqueueTaskMessage(relatedTaskId, {
14839 type: "error",
14840 message: errorResponse,
14841 timestamp: Date.now()
14842 }, capturedTransport?.sessionId);
14843 else await capturedTransport?.send(errorResponse);
14844 }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => {
14845 this._requestHandlerAbortControllers.delete(request.id);
14846 });
14847 }
14848 _onprogress(notification) {
14849 const { progressToken, ...params } = notification.params;
14850 const messageId = Number(progressToken);
14851 const handler = this._progressHandlers.get(messageId);
14852 if (!handler) {
14853 this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
14854 return;
14855 }
14856 const responseHandler = this._responseHandlers.get(messageId);
14857 const timeoutInfo = this._timeoutInfo.get(messageId);
14858 if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try {
14859 this._resetTimeout(messageId);
14860 } catch (error) {
14861 this._responseHandlers.delete(messageId);
14862 this._progressHandlers.delete(messageId);
14863 this._cleanupTimeout(messageId);
14864 responseHandler(error);
14865 return;
14866 }
14867 handler(params);
14868 }
14869 _onresponse(response) {
14870 const messageId = Number(response.id);
14871 const resolver = this._requestResolvers.get(messageId);
14872 if (resolver) {
14873 this._requestResolvers.delete(messageId);
14874 if (isJSONRPCResultResponse(response)) resolver(response);
14875 else resolver(new McpError(response.error.code, response.error.message, response.error.data));
14876 return;
14877 }
14878 const handler = this._responseHandlers.get(messageId);
14879 if (handler === void 0) {
14880 this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
14881 return;
14882 }
14883 this._responseHandlers.delete(messageId);
14884 this._cleanupTimeout(messageId);
14885 let isTaskResponse = false;
14886 if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
14887 const result = response.result;
14888 if (result.task && typeof result.task === "object") {
14889 const task = result.task;
14890 if (typeof task.taskId === "string") {
14891 isTaskResponse = true;
14892 this._taskProgressTokens.set(task.taskId, messageId);
14893 }
14894 }
14895 }
14896 if (!isTaskResponse) this._progressHandlers.delete(messageId);
14897 if (isJSONRPCResultResponse(response)) handler(response);
14898 else handler(McpError.fromError(response.error.code, response.error.message, response.error.data));
14899 }
14900 get transport() {
14901 return this._transport;
14902 }
14903 /**
14904 * Closes the connection.
14905 */
14906 async close() {
14907 await this._transport?.close();
14908 }
14909 /**
14910 * Sends a request and returns an AsyncGenerator that yields response messages.
14911 * The generator is guaranteed to end with either a 'result' or 'error' message.
14912 *
14913 * @example
14914 * ```typescript
14915 * const stream = protocol.requestStream(request, resultSchema, options);
14916 * for await (const message of stream) {
14917 * switch (message.type) {
14918 * case 'taskCreated':
14919 * console.log('Task created:', message.task.taskId);
14920 * break;
14921 * case 'taskStatus':
14922 * console.log('Task status:', message.task.status);
14923 * break;
14924 * case 'result':
14925 * console.log('Final result:', message.result);
14926 * break;
14927 * case 'error':
14928 * console.error('Error:', message.error);
14929 * break;
14930 * }
14931 * }
14932 * ```
14933 *
14934 * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
14935 */
14936 async *requestStream(request, resultSchema, options) {
14937 const { task } = options ?? {};
14938 if (!task) {
14939 try {
14940 yield {
14941 type: "result",
14942 result: await this.request(request, resultSchema, options)
14943 };
14944 } catch (error) {
14945 yield {
14946 type: "error",
14947 error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
14948 };
14949 }
14950 return;
14951 }
14952 let taskId;
14953 try {
14954 const createResult = await this.request(request, CreateTaskResultSchema, options);
14955 if (createResult.task) {
14956 taskId = createResult.task.taskId;
14957 yield {
14958 type: "taskCreated",
14959 task: createResult.task
14960 };
14961 } else throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
14962 while (true) {
14963 const task = await this.getTask({ taskId }, options);
14964 yield {
14965 type: "taskStatus",
14966 task
14967 };
14968 if (isTerminal(task.status)) {
14969 if (task.status === "completed") yield {
14970 type: "result",
14971 result: await this.getTaskResult({ taskId }, resultSchema, options)
14972 };
14973 else if (task.status === "failed") yield {
14974 type: "error",
14975 error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
14976 };
14977 else if (task.status === "cancelled") yield {
14978 type: "error",
14979 error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
14980 };
14981 return;
14982 }
14983 if (task.status === "input_required") {
14984 yield {
14985 type: "result",
14986 result: await this.getTaskResult({ taskId }, resultSchema, options)
14987 };
14988 return;
14989 }
14990 const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
14991 await new Promise((resolve) => setTimeout(resolve, pollInterval));
14992 options?.signal?.throwIfAborted();
14993 }
14994 } catch (error) {
14995 yield {
14996 type: "error",
14997 error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
14998 };
14999 }
15000 }
15001 /**
15002 * Sends a request and waits for a response.
15003 *
15004 * Do not use this method to emit notifications! Use notification() instead.
15005 */
15006 request(request, resultSchema, options) {
15007 const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
15008 return new Promise((resolve, reject) => {
15009 const earlyReject = (error) => {
15010 reject(error);
15011 };
15012 if (!this._transport) {
15013 earlyReject(/* @__PURE__ */ new Error("Not connected"));
15014 return;
15015 }
15016 if (this._options?.enforceStrictCapabilities === true) try {
15017 this.assertCapabilityForMethod(request.method);
15018 if (task) this.assertTaskCapability(request.method);
15019 } catch (e) {
15020 earlyReject(e);
15021 return;
15022 }
15023 options?.signal?.throwIfAborted();
15024 const messageId = this._requestMessageId++;
15025 const jsonrpcRequest = {
15026 ...request,
15027 jsonrpc: "2.0",
15028 id: messageId
15029 };
15030 if (options?.onprogress) {
15031 this._progressHandlers.set(messageId, options.onprogress);
15032 jsonrpcRequest.params = {
15033 ...request.params,
15034 _meta: {
15035 ...request.params?._meta || {},
15036 progressToken: messageId
15037 }
15038 };
15039 }
15040 if (task) jsonrpcRequest.params = {
15041 ...jsonrpcRequest.params,
15042 task
15043 };
15044 if (relatedTask) jsonrpcRequest.params = {
15045 ...jsonrpcRequest.params,
15046 _meta: {
15047 ...jsonrpcRequest.params?._meta || {},
15048 [RELATED_TASK_META_KEY]: relatedTask
15049 }
15050 };
15051 const cancel = (reason) => {
15052 this._responseHandlers.delete(messageId);
15053 this._progressHandlers.delete(messageId);
15054 this._cleanupTimeout(messageId);
15055 this._transport?.send({
15056 jsonrpc: "2.0",
15057 method: "notifications/cancelled",
15058 params: {
15059 requestId: messageId,
15060 reason: String(reason)
15061 }
15062 }, {
15063 relatedRequestId,
15064 resumptionToken,
15065 onresumptiontoken
15066 }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`)));
15067 reject(reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)));
15068 };
15069 this._responseHandlers.set(messageId, (response) => {
15070 if (options?.signal?.aborted) return;
15071 if (response instanceof Error) return reject(response);
15072 try {
15073 const parseResult = safeParse(resultSchema, response.result);
15074 if (!parseResult.success) reject(parseResult.error);
15075 else resolve(parseResult.data);
15076 } catch (error) {
15077 reject(error);
15078 }
15079 });
15080 options?.signal?.addEventListener("abort", () => {
15081 cancel(options?.signal?.reason);
15082 });
15083 const timeout = options?.timeout ?? 6e4;
15084 const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
15085 this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
15086 const relatedTaskId = relatedTask?.taskId;
15087 if (relatedTaskId) {
15088 const responseResolver = (response) => {
15089 const handler = this._responseHandlers.get(messageId);
15090 if (handler) handler(response);
15091 else this._onerror(/* @__PURE__ */ new Error(`Response handler missing for side-channeled request ${messageId}`));
15092 };
15093 this._requestResolvers.set(messageId, responseResolver);
15094 this._enqueueTaskMessage(relatedTaskId, {
15095 type: "request",
15096 message: jsonrpcRequest,
15097 timestamp: Date.now()
15098 }).catch((error) => {
15099 this._cleanupTimeout(messageId);
15100 reject(error);
15101 });
15102 } else this._transport.send(jsonrpcRequest, {
15103 relatedRequestId,
15104 resumptionToken,
15105 onresumptiontoken
15106 }).catch((error) => {
15107 this._cleanupTimeout(messageId);
15108 reject(error);
15109 });
15110 });
15111 }
15112 /**
15113 * Gets the current status of a task.
15114 *
15115 * @experimental Use `client.experimental.tasks.getTask()` to access this method.
15116 */
15117 async getTask(params, options) {
15118 return this.request({
15119 method: "tasks/get",
15120 params
15121 }, GetTaskResultSchema, options);
15122 }
15123 /**
15124 * Retrieves the result of a completed task.
15125 *
15126 * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
15127 */
15128 async getTaskResult(params, resultSchema, options) {
15129 return this.request({
15130 method: "tasks/result",
15131 params
15132 }, resultSchema, options);
15133 }
15134 /**
15135 * Lists tasks, optionally starting from a pagination cursor.
15136 *
15137 * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
15138 */
15139 async listTasks(params, options) {
15140 return this.request({
15141 method: "tasks/list",
15142 params
15143 }, ListTasksResultSchema, options);
15144 }
15145 /**
15146 * Cancels a specific task.
15147 *
15148 * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
15149 */
15150 async cancelTask(params, options) {
15151 return this.request({
15152 method: "tasks/cancel",
15153 params
15154 }, CancelTaskResultSchema, options);
15155 }
15156 /**
15157 * Emits a notification, which is a one-way message that does not expect a response.
15158 */
15159 async notification(notification, options) {
15160 if (!this._transport) throw new Error("Not connected");
15161 this.assertNotificationCapability(notification.method);
15162 const relatedTaskId = options?.relatedTask?.taskId;
15163 if (relatedTaskId) {
15164 const jsonrpcNotification = {
15165 ...notification,
15166 jsonrpc: "2.0",
15167 params: {
15168 ...notification.params,
15169 _meta: {
15170 ...notification.params?._meta || {},
15171 [RELATED_TASK_META_KEY]: options.relatedTask
15172 }
15173 }
15174 };
15175 await this._enqueueTaskMessage(relatedTaskId, {
15176 type: "notification",
15177 message: jsonrpcNotification,
15178 timestamp: Date.now()
15179 });
15180 return;
15181 }
15182 if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask) {
15183 if (this._pendingDebouncedNotifications.has(notification.method)) return;
15184 this._pendingDebouncedNotifications.add(notification.method);
15185 Promise.resolve().then(() => {
15186 this._pendingDebouncedNotifications.delete(notification.method);
15187 if (!this._transport) return;
15188 let jsonrpcNotification = {
15189 ...notification,
15190 jsonrpc: "2.0"
15191 };
15192 if (options?.relatedTask) jsonrpcNotification = {
15193 ...jsonrpcNotification,
15194 params: {
15195 ...jsonrpcNotification.params,
15196 _meta: {
15197 ...jsonrpcNotification.params?._meta || {},
15198 [RELATED_TASK_META_KEY]: options.relatedTask
15199 }
15200 }
15201 };
15202 this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error));
15203 });
15204 return;
15205 }
15206 let jsonrpcNotification = {
15207 ...notification,
15208 jsonrpc: "2.0"
15209 };
15210 if (options?.relatedTask) jsonrpcNotification = {
15211 ...jsonrpcNotification,
15212 params: {
15213 ...jsonrpcNotification.params,
15214 _meta: {
15215 ...jsonrpcNotification.params?._meta || {},
15216 [RELATED_TASK_META_KEY]: options.relatedTask
15217 }
15218 }
15219 };
15220 await this._transport.send(jsonrpcNotification, options);
15221 }
15222 /**
15223 * Registers a handler to invoke when this protocol object receives a request with the given method.
15224 *
15225 * Note that this will replace any previous request handler for the same method.
15226 */
15227 setRequestHandler(requestSchema, handler) {
15228 const method = getMethodLiteral(requestSchema);
15229 this.assertRequestHandlerCapability(method);
15230 this._requestHandlers.set(method, (request, extra) => {
15231 const parsed = parseWithCompat(requestSchema, request);
15232 return Promise.resolve(handler(parsed, extra));
15233 });
15234 }
15235 /**
15236 * Removes the request handler for the given method.
15237 */
15238 removeRequestHandler(method) {
15239 this._requestHandlers.delete(method);
15240 }
15241 /**
15242 * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
15243 */
15244 assertCanSetRequestHandler(method) {
15245 if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`);
15246 }
15247 /**
15248 * Registers a handler to invoke when this protocol object receives a notification with the given method.
15249 *
15250 * Note that this will replace any previous notification handler for the same method.
15251 */
15252 setNotificationHandler(notificationSchema, handler) {
15253 const method = getMethodLiteral(notificationSchema);
15254 this._notificationHandlers.set(method, (notification) => {
15255 const parsed = parseWithCompat(notificationSchema, notification);
15256 return Promise.resolve(handler(parsed));
15257 });
15258 }
15259 /**
15260 * Removes the notification handler for the given method.
15261 */
15262 removeNotificationHandler(method) {
15263 this._notificationHandlers.delete(method);
15264 }
15265 /**
15266 * Cleans up the progress handler associated with a task.
15267 * This should be called when a task reaches a terminal status.
15268 */
15269 _cleanupTaskProgressHandler(taskId) {
15270 const progressToken = this._taskProgressTokens.get(taskId);
15271 if (progressToken !== void 0) {
15272 this._progressHandlers.delete(progressToken);
15273 this._taskProgressTokens.delete(taskId);
15274 }
15275 }
15276 /**
15277 * Enqueues a task-related message for side-channel delivery via tasks/result.
15278 * @param taskId The task ID to associate the message with
15279 * @param message The message to enqueue
15280 * @param sessionId Optional session ID for binding the operation to a specific session
15281 * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
15282 *
15283 * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
15284 * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
15285 * simply propagates the error.
15286 */
15287 async _enqueueTaskMessage(taskId, message, sessionId) {
15288 if (!this._taskStore || !this._taskMessageQueue) throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
15289 const maxQueueSize = this._options?.maxTaskQueueSize;
15290 await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
15291 }
15292 /**
15293 * Clears the message queue for a task and rejects any pending request resolvers.
15294 * @param taskId The task ID whose queue should be cleared
15295 * @param sessionId Optional session ID for binding the operation to a specific session
15296 */
15297 async _clearTaskQueue(taskId, sessionId) {
15298 if (this._taskMessageQueue) {
15299 const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
15300 for (const message of messages) if (message.type === "request" && isJSONRPCRequest(message.message)) {
15301 const requestId = message.message.id;
15302 const resolver = this._requestResolvers.get(requestId);
15303 if (resolver) {
15304 resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
15305 this._requestResolvers.delete(requestId);
15306 } else this._onerror(/* @__PURE__ */ new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
15307 }
15308 }
15309 }
15310 /**
15311 * Waits for a task update (new messages or status change) with abort signal support.
15312 * Uses polling to check for updates at the task's configured poll interval.
15313 * @param taskId The task ID to wait for
15314 * @param signal Abort signal to cancel the wait
15315 * @returns Promise that resolves when an update occurs or rejects if aborted
15316 */
15317 async _waitForTaskUpdate(taskId, signal) {
15318 let interval = this._options?.defaultTaskPollInterval ?? 1e3;
15319 try {
15320 const task = await this._taskStore?.getTask(taskId);
15321 if (task?.pollInterval) interval = task.pollInterval;
15322 } catch {}
15323 return new Promise((resolve, reject) => {
15324 if (signal.aborted) {
15325 reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
15326 return;
15327 }
15328 const timeoutId = setTimeout(resolve, interval);
15329 signal.addEventListener("abort", () => {
15330 clearTimeout(timeoutId);
15331 reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
15332 }, { once: true });
15333 });
15334 }
15335 requestTaskStore(request, sessionId) {
15336 const taskStore = this._taskStore;
15337 if (!taskStore) throw new Error("No task store configured");
15338 return {
15339 createTask: async (taskParams) => {
15340 if (!request) throw new Error("No request provided");
15341 return await taskStore.createTask(taskParams, request.id, {
15342 method: request.method,
15343 params: request.params
15344 }, sessionId);
15345 },
15346 getTask: async (taskId) => {
15347 const task = await taskStore.getTask(taskId, sessionId);
15348 if (!task) throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
15349 return task;
15350 },
15351 storeTaskResult: async (taskId, status, result) => {
15352 await taskStore.storeTaskResult(taskId, status, result, sessionId);
15353 const task = await taskStore.getTask(taskId, sessionId);
15354 if (task) {
15355 const notification = TaskStatusNotificationSchema.parse({
15356 method: "notifications/tasks/status",
15357 params: task
15358 });
15359 await this.notification(notification);
15360 if (isTerminal(task.status)) this._cleanupTaskProgressHandler(taskId);
15361 }
15362 },
15363 getTaskResult: (taskId) => {
15364 return taskStore.getTaskResult(taskId, sessionId);
15365 },
15366 updateTaskStatus: async (taskId, status, statusMessage) => {
15367 const task = await taskStore.getTask(taskId, sessionId);
15368 if (!task) throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
15369 if (isTerminal(task.status)) throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
15370 await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
15371 const updatedTask = await taskStore.getTask(taskId, sessionId);
15372 if (updatedTask) {
15373 const notification = TaskStatusNotificationSchema.parse({
15374 method: "notifications/tasks/status",
15375 params: updatedTask
15376 });
15377 await this.notification(notification);
15378 if (isTerminal(updatedTask.status)) this._cleanupTaskProgressHandler(taskId);
15379 }
15380 },
15381 listTasks: (cursor) => {
15382 return taskStore.listTasks(cursor, sessionId);
15383 }
15384 };
15385 }
15386 };
15387 function isPlainObject(value) {
15388 return value !== null && typeof value === "object" && !Array.isArray(value);
15389 }
15390 function mergeCapabilities(base, additional) {
15391 const result = { ...base };
15392 for (const key in additional) {
15393 const k = key;
15394 const addValue = additional[k];
15395 if (addValue === void 0) continue;
15396 const baseValue = result[k];
15397 if (isPlainObject(baseValue) && isPlainObject(addValue)) result[k] = {
15398 ...baseValue,
15399 ...addValue
15400 };
15401 else result[k] = addValue;
15402 }
15403 return result;
15404 }
15405
15406 //#endregion
15407 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/code.js
15408 var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
15409 Object.defineProperty(exports, "__esModule", { value: true });
15410 exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
15411 var _CodeOrName = class {};
15412 exports._CodeOrName = _CodeOrName;
15413 exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
15414 var Name = class extends _CodeOrName {
15415 constructor(s) {
15416 super();
15417 if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier");
15418 this.str = s;
15419 }
15420 toString() {
15421 return this.str;
15422 }
15423 emptyStr() {
15424 return false;
15425 }
15426 get names() {
15427 return { [this.str]: 1 };
15428 }
15429 };
15430 exports.Name = Name;
15431 var _Code = class extends _CodeOrName {
15432 constructor(code) {
15433 super();
15434 this._items = typeof code === "string" ? [code] : code;
15435 }
15436 toString() {
15437 return this.str;
15438 }
15439 emptyStr() {
15440 if (this._items.length > 1) return false;
15441 const item = this._items[0];
15442 return item === "" || item === "\"\"";
15443 }
15444 get str() {
15445 var _a;
15446 return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
15447 }
15448 get names() {
15449 var _a;
15450 return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => {
15451 if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1;
15452 return names;
15453 }, {});
15454 }
15455 };
15456 exports._Code = _Code;
15457 exports.nil = new _Code("");
15458 function _(strs, ...args) {
15459 const code = [strs[0]];
15460 let i = 0;
15461 while (i < args.length) {
15462 addCodeArg(code, args[i]);
15463 code.push(strs[++i]);
15464 }
15465 return new _Code(code);
15466 }
15467 exports._ = _;
15468 var plus = new _Code("+");
15469 function str(strs, ...args) {
15470 const expr = [safeStringify(strs[0])];
15471 let i = 0;
15472 while (i < args.length) {
15473 expr.push(plus);
15474 addCodeArg(expr, args[i]);
15475 expr.push(plus, safeStringify(strs[++i]));
15476 }
15477 optimize(expr);
15478 return new _Code(expr);
15479 }
15480 exports.str = str;
15481 function addCodeArg(code, arg) {
15482 if (arg instanceof _Code) code.push(...arg._items);
15483 else if (arg instanceof Name) code.push(arg);
15484 else code.push(interpolate(arg));
15485 }
15486 exports.addCodeArg = addCodeArg;
15487 function optimize(expr) {
15488 let i = 1;
15489 while (i < expr.length - 1) {
15490 if (expr[i] === plus) {
15491 const res = mergeExprItems(expr[i - 1], expr[i + 1]);
15492 if (res !== void 0) {
15493 expr.splice(i - 1, 3, res);
15494 continue;
15495 }
15496 expr[i++] = "+";
15497 }
15498 i++;
15499 }
15500 }
15501 function mergeExprItems(a, b) {
15502 if (b === "\"\"") return a;
15503 if (a === "\"\"") return b;
15504 if (typeof a == "string") {
15505 if (b instanceof Name || a[a.length - 1] !== "\"") return;
15506 if (typeof b != "string") return `${a.slice(0, -1)}${b}"`;
15507 if (b[0] === "\"") return a.slice(0, -1) + b.slice(1);
15508 return;
15509 }
15510 if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`;
15511 }
15512 function strConcat(c1, c2) {
15513 return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
15514 }
15515 exports.strConcat = strConcat;
15516 function interpolate(x) {
15517 return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
15518 }
15519 function stringify(x) {
15520 return new _Code(safeStringify(x));
15521 }
15522 exports.stringify = stringify;
15523 function safeStringify(x) {
15524 return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
15525 }
15526 exports.safeStringify = safeStringify;
15527 function getProperty(key) {
15528 return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
15529 }
15530 exports.getProperty = getProperty;
15531 function getEsmExportName(key) {
15532 if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`);
15533 throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
15534 }
15535 exports.getEsmExportName = getEsmExportName;
15536 function regexpCode(rx) {
15537 return new _Code(rx.toString());
15538 }
15539 exports.regexpCode = regexpCode;
15540 }));
15541
15542 //#endregion
15543 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/scope.js
15544 var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => {
15545 Object.defineProperty(exports, "__esModule", { value: true });
15546 exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
15547 var code_1 = require_code$1();
15548 var ValueError = class extends Error {
15549 constructor(name) {
15550 super(`CodeGen: "code" for ${name} not defined`);
15551 this.value = name.value;
15552 }
15553 };
15554 var UsedValueState;
15555 (function(UsedValueState) {
15556 UsedValueState[UsedValueState["Started"] = 0] = "Started";
15557 UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
15558 })(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
15559 exports.varKinds = {
15560 const: new code_1.Name("const"),
15561 let: new code_1.Name("let"),
15562 var: new code_1.Name("var")
15563 };
15564 var Scope = class {
15565 constructor({ prefixes, parent } = {}) {
15566 this._names = {};
15567 this._prefixes = prefixes;
15568 this._parent = parent;
15569 }
15570 toName(nameOrPrefix) {
15571 return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
15572 }
15573 name(prefix) {
15574 return new code_1.Name(this._newName(prefix));
15575 }
15576 _newName(prefix) {
15577 const ng = this._names[prefix] || this._nameGroup(prefix);
15578 return `${prefix}${ng.index++}`;
15579 }
15580 _nameGroup(prefix) {
15581 var _a;
15582 var _b;
15583 if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
15584 return this._names[prefix] = {
15585 prefix,
15586 index: 0
15587 };
15588 }
15589 };
15590 exports.Scope = Scope;
15591 var ValueScopeName = class extends code_1.Name {
15592 constructor(prefix, nameStr) {
15593 super(nameStr);
15594 this.prefix = prefix;
15595 }
15596 setValue(value, { property, itemIndex }) {
15597 this.value = value;
15598 this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
15599 }
15600 };
15601 exports.ValueScopeName = ValueScopeName;
15602 var line = (0, code_1._)`\n`;
15603 var ValueScope = class extends Scope {
15604 constructor(opts) {
15605 super(opts);
15606 this._values = {};
15607 this._scope = opts.scope;
15608 this.opts = {
15609 ...opts,
15610 _n: opts.lines ? line : code_1.nil
15611 };
15612 }
15613 get() {
15614 return this._scope;
15615 }
15616 name(prefix) {
15617 return new ValueScopeName(prefix, this._newName(prefix));
15618 }
15619 value(nameOrPrefix, value) {
15620 var _a;
15621 if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value");
15622 const name = this.toName(nameOrPrefix);
15623 const { prefix } = name;
15624 const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
15625 let vs = this._values[prefix];
15626 if (vs) {
15627 const _name = vs.get(valueKey);
15628 if (_name) return _name;
15629 } else vs = this._values[prefix] = /* @__PURE__ */ new Map();
15630 vs.set(valueKey, name);
15631 const s = this._scope[prefix] || (this._scope[prefix] = []);
15632 const itemIndex = s.length;
15633 s[itemIndex] = value.ref;
15634 name.setValue(value, {
15635 property: prefix,
15636 itemIndex
15637 });
15638 return name;
15639 }
15640 getValue(prefix, keyOrRef) {
15641 const vs = this._values[prefix];
15642 if (!vs) return;
15643 return vs.get(keyOrRef);
15644 }
15645 scopeRefs(scopeName, values = this._values) {
15646 return this._reduceValues(values, (name) => {
15647 if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`);
15648 return (0, code_1._)`${scopeName}${name.scopePath}`;
15649 });
15650 }
15651 scopeCode(values = this._values, usedValues, getCode) {
15652 return this._reduceValues(values, (name) => {
15653 if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`);
15654 return name.value.code;
15655 }, usedValues, getCode);
15656 }
15657 _reduceValues(values, valueCode, usedValues = {}, getCode) {
15658 let code = code_1.nil;
15659 for (const prefix in values) {
15660 const vs = values[prefix];
15661 if (!vs) continue;
15662 const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
15663 vs.forEach((name) => {
15664 if (nameSet.has(name)) return;
15665 nameSet.set(name, UsedValueState.Started);
15666 let c = valueCode(name);
15667 if (c) {
15668 const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
15669 code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`;
15670 } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`;
15671 else throw new ValueError(name);
15672 nameSet.set(name, UsedValueState.Completed);
15673 });
15674 }
15675 return code;
15676 }
15677 };
15678 exports.ValueScope = ValueScope;
15679 }));
15680
15681 //#endregion
15682 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/index.js
15683 var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
15684 Object.defineProperty(exports, "__esModule", { value: true });
15685 exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
15686 var code_1 = require_code$1();
15687 var scope_1 = require_scope();
15688 var code_2 = require_code$1();
15689 Object.defineProperty(exports, "_", {
15690 enumerable: true,
15691 get: function() {
15692 return code_2._;
15693 }
15694 });
15695 Object.defineProperty(exports, "str", {
15696 enumerable: true,
15697 get: function() {
15698 return code_2.str;
15699 }
15700 });
15701 Object.defineProperty(exports, "strConcat", {
15702 enumerable: true,
15703 get: function() {
15704 return code_2.strConcat;
15705 }
15706 });
15707 Object.defineProperty(exports, "nil", {
15708 enumerable: true,
15709 get: function() {
15710 return code_2.nil;
15711 }
15712 });
15713 Object.defineProperty(exports, "getProperty", {
15714 enumerable: true,
15715 get: function() {
15716 return code_2.getProperty;
15717 }
15718 });
15719 Object.defineProperty(exports, "stringify", {
15720 enumerable: true,
15721 get: function() {
15722 return code_2.stringify;
15723 }
15724 });
15725 Object.defineProperty(exports, "regexpCode", {
15726 enumerable: true,
15727 get: function() {
15728 return code_2.regexpCode;
15729 }
15730 });
15731 Object.defineProperty(exports, "Name", {
15732 enumerable: true,
15733 get: function() {
15734 return code_2.Name;
15735 }
15736 });
15737 var scope_2 = require_scope();
15738 Object.defineProperty(exports, "Scope", {
15739 enumerable: true,
15740 get: function() {
15741 return scope_2.Scope;
15742 }
15743 });
15744 Object.defineProperty(exports, "ValueScope", {
15745 enumerable: true,
15746 get: function() {
15747 return scope_2.ValueScope;
15748 }
15749 });
15750 Object.defineProperty(exports, "ValueScopeName", {
15751 enumerable: true,
15752 get: function() {
15753 return scope_2.ValueScopeName;
15754 }
15755 });
15756 Object.defineProperty(exports, "varKinds", {
15757 enumerable: true,
15758 get: function() {
15759 return scope_2.varKinds;
15760 }
15761 });
15762 exports.operators = {
15763 GT: new code_1._Code(">"),
15764 GTE: new code_1._Code(">="),
15765 LT: new code_1._Code("<"),
15766 LTE: new code_1._Code("<="),
15767 EQ: new code_1._Code("==="),
15768 NEQ: new code_1._Code("!=="),
15769 NOT: new code_1._Code("!"),
15770 OR: new code_1._Code("||"),
15771 AND: new code_1._Code("&&"),
15772 ADD: new code_1._Code("+")
15773 };
15774 var Node = class {
15775 optimizeNodes() {
15776 return this;
15777 }
15778 optimizeNames(_names, _constants) {
15779 return this;
15780 }
15781 };
15782 var Def = class extends Node {
15783 constructor(varKind, name, rhs) {
15784 super();
15785 this.varKind = varKind;
15786 this.name = name;
15787 this.rhs = rhs;
15788 }
15789 render({ es5, _n }) {
15790 const varKind = es5 ? scope_1.varKinds.var : this.varKind;
15791 const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
15792 return `${varKind} ${this.name}${rhs};` + _n;
15793 }
15794 optimizeNames(names, constants) {
15795 if (!names[this.name.str]) return;
15796 if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants);
15797 return this;
15798 }
15799 get names() {
15800 return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
15801 }
15802 };
15803 var Assign = class extends Node {
15804 constructor(lhs, rhs, sideEffects) {
15805 super();
15806 this.lhs = lhs;
15807 this.rhs = rhs;
15808 this.sideEffects = sideEffects;
15809 }
15810 render({ _n }) {
15811 return `${this.lhs} = ${this.rhs};` + _n;
15812 }
15813 optimizeNames(names, constants) {
15814 if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return;
15815 this.rhs = optimizeExpr(this.rhs, names, constants);
15816 return this;
15817 }
15818 get names() {
15819 return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs);
15820 }
15821 };
15822 var AssignOp = class extends Assign {
15823 constructor(lhs, op, rhs, sideEffects) {
15824 super(lhs, rhs, sideEffects);
15825 this.op = op;
15826 }
15827 render({ _n }) {
15828 return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
15829 }
15830 };
15831 var Label = class extends Node {
15832 constructor(label) {
15833 super();
15834 this.label = label;
15835 this.names = {};
15836 }
15837 render({ _n }) {
15838 return `${this.label}:` + _n;
15839 }
15840 };
15841 var Break = class extends Node {
15842 constructor(label) {
15843 super();
15844 this.label = label;
15845 this.names = {};
15846 }
15847 render({ _n }) {
15848 return `break${this.label ? ` ${this.label}` : ""};` + _n;
15849 }
15850 };
15851 var Throw = class extends Node {
15852 constructor(error) {
15853 super();
15854 this.error = error;
15855 }
15856 render({ _n }) {
15857 return `throw ${this.error};` + _n;
15858 }
15859 get names() {
15860 return this.error.names;
15861 }
15862 };
15863 var AnyCode = class extends Node {
15864 constructor(code) {
15865 super();
15866 this.code = code;
15867 }
15868 render({ _n }) {
15869 return `${this.code};` + _n;
15870 }
15871 optimizeNodes() {
15872 return `${this.code}` ? this : void 0;
15873 }
15874 optimizeNames(names, constants) {
15875 this.code = optimizeExpr(this.code, names, constants);
15876 return this;
15877 }
15878 get names() {
15879 return this.code instanceof code_1._CodeOrName ? this.code.names : {};
15880 }
15881 };
15882 var ParentNode = class extends Node {
15883 constructor(nodes = []) {
15884 super();
15885 this.nodes = nodes;
15886 }
15887 render(opts) {
15888 return this.nodes.reduce((code, n) => code + n.render(opts), "");
15889 }
15890 optimizeNodes() {
15891 const { nodes } = this;
15892 let i = nodes.length;
15893 while (i--) {
15894 const n = nodes[i].optimizeNodes();
15895 if (Array.isArray(n)) nodes.splice(i, 1, ...n);
15896 else if (n) nodes[i] = n;
15897 else nodes.splice(i, 1);
15898 }
15899 return nodes.length > 0 ? this : void 0;
15900 }
15901 optimizeNames(names, constants) {
15902 const { nodes } = this;
15903 let i = nodes.length;
15904 while (i--) {
15905 const n = nodes[i];
15906 if (n.optimizeNames(names, constants)) continue;
15907 subtractNames(names, n.names);
15908 nodes.splice(i, 1);
15909 }
15910 return nodes.length > 0 ? this : void 0;
15911 }
15912 get names() {
15913 return this.nodes.reduce((names, n) => addNames(names, n.names), {});
15914 }
15915 };
15916 var BlockNode = class extends ParentNode {
15917 render(opts) {
15918 return "{" + opts._n + super.render(opts) + "}" + opts._n;
15919 }
15920 };
15921 var Root = class extends ParentNode {};
15922 var Else = class extends BlockNode {};
15923 Else.kind = "else";
15924 var If = class If extends BlockNode {
15925 constructor(condition, nodes) {
15926 super(nodes);
15927 this.condition = condition;
15928 }
15929 render(opts) {
15930 let code = `if(${this.condition})` + super.render(opts);
15931 if (this.else) code += "else " + this.else.render(opts);
15932 return code;
15933 }
15934 optimizeNodes() {
15935 super.optimizeNodes();
15936 const cond = this.condition;
15937 if (cond === true) return this.nodes;
15938 let e = this.else;
15939 if (e) {
15940 const ns = e.optimizeNodes();
15941 e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
15942 }
15943 if (e) {
15944 if (cond === false) return e instanceof If ? e : e.nodes;
15945 if (this.nodes.length) return this;
15946 return new If(not(cond), e instanceof If ? [e] : e.nodes);
15947 }
15948 if (cond === false || !this.nodes.length) return void 0;
15949 return this;
15950 }
15951 optimizeNames(names, constants) {
15952 var _a;
15953 this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
15954 if (!(super.optimizeNames(names, constants) || this.else)) return;
15955 this.condition = optimizeExpr(this.condition, names, constants);
15956 return this;
15957 }
15958 get names() {
15959 const names = super.names;
15960 addExprNames(names, this.condition);
15961 if (this.else) addNames(names, this.else.names);
15962 return names;
15963 }
15964 };
15965 If.kind = "if";
15966 var For = class extends BlockNode {};
15967 For.kind = "for";
15968 var ForLoop = class extends For {
15969 constructor(iteration) {
15970 super();
15971 this.iteration = iteration;
15972 }
15973 render(opts) {
15974 return `for(${this.iteration})` + super.render(opts);
15975 }
15976 optimizeNames(names, constants) {
15977 if (!super.optimizeNames(names, constants)) return;
15978 this.iteration = optimizeExpr(this.iteration, names, constants);
15979 return this;
15980 }
15981 get names() {
15982 return addNames(super.names, this.iteration.names);
15983 }
15984 };
15985 var ForRange = class extends For {
15986 constructor(varKind, name, from, to) {
15987 super();
15988 this.varKind = varKind;
15989 this.name = name;
15990 this.from = from;
15991 this.to = to;
15992 }
15993 render(opts) {
15994 const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
15995 const { name, from, to } = this;
15996 return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
15997 }
15998 get names() {
15999 return addExprNames(addExprNames(super.names, this.from), this.to);
16000 }
16001 };
16002 var ForIter = class extends For {
16003 constructor(loop, varKind, name, iterable) {
16004 super();
16005 this.loop = loop;
16006 this.varKind = varKind;
16007 this.name = name;
16008 this.iterable = iterable;
16009 }
16010 render(opts) {
16011 return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
16012 }
16013 optimizeNames(names, constants) {
16014 if (!super.optimizeNames(names, constants)) return;
16015 this.iterable = optimizeExpr(this.iterable, names, constants);
16016 return this;
16017 }
16018 get names() {
16019 return addNames(super.names, this.iterable.names);
16020 }
16021 };
16022 var Func = class extends BlockNode {
16023 constructor(name, args, async) {
16024 super();
16025 this.name = name;
16026 this.args = args;
16027 this.async = async;
16028 }
16029 render(opts) {
16030 return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts);
16031 }
16032 };
16033 Func.kind = "func";
16034 var Return = class extends ParentNode {
16035 render(opts) {
16036 return "return " + super.render(opts);
16037 }
16038 };
16039 Return.kind = "return";
16040 var Try = class extends BlockNode {
16041 render(opts) {
16042 let code = "try" + super.render(opts);
16043 if (this.catch) code += this.catch.render(opts);
16044 if (this.finally) code += this.finally.render(opts);
16045 return code;
16046 }
16047 optimizeNodes() {
16048 var _a;
16049 var _b;
16050 super.optimizeNodes();
16051 (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes();
16052 (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes();
16053 return this;
16054 }
16055 optimizeNames(names, constants) {
16056 var _a;
16057 var _b;
16058 super.optimizeNames(names, constants);
16059 (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants);
16060 (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants);
16061 return this;
16062 }
16063 get names() {
16064 const names = super.names;
16065 if (this.catch) addNames(names, this.catch.names);
16066 if (this.finally) addNames(names, this.finally.names);
16067 return names;
16068 }
16069 };
16070 var Catch = class extends BlockNode {
16071 constructor(error) {
16072 super();
16073 this.error = error;
16074 }
16075 render(opts) {
16076 return `catch(${this.error})` + super.render(opts);
16077 }
16078 };
16079 Catch.kind = "catch";
16080 var Finally = class extends BlockNode {
16081 render(opts) {
16082 return "finally" + super.render(opts);
16083 }
16084 };
16085 Finally.kind = "finally";
16086 var CodeGen = class {
16087 constructor(extScope, opts = {}) {
16088 this._values = {};
16089 this._blockStarts = [];
16090 this._constants = {};
16091 this.opts = {
16092 ...opts,
16093 _n: opts.lines ? "\n" : ""
16094 };
16095 this._extScope = extScope;
16096 this._scope = new scope_1.Scope({ parent: extScope });
16097 this._nodes = [new Root()];
16098 }
16099 toString() {
16100 return this._root.render(this.opts);
16101 }
16102 name(prefix) {
16103 return this._scope.name(prefix);
16104 }
16105 scopeName(prefix) {
16106 return this._extScope.name(prefix);
16107 }
16108 scopeValue(prefixOrName, value) {
16109 const name = this._extScope.value(prefixOrName, value);
16110 (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name);
16111 return name;
16112 }
16113 getScopeValue(prefix, keyOrRef) {
16114 return this._extScope.getValue(prefix, keyOrRef);
16115 }
16116 scopeRefs(scopeName) {
16117 return this._extScope.scopeRefs(scopeName, this._values);
16118 }
16119 scopeCode() {
16120 return this._extScope.scopeCode(this._values);
16121 }
16122 _def(varKind, nameOrPrefix, rhs, constant) {
16123 const name = this._scope.toName(nameOrPrefix);
16124 if (rhs !== void 0 && constant) this._constants[name.str] = rhs;
16125 this._leafNode(new Def(varKind, name, rhs));
16126 return name;
16127 }
16128 const(nameOrPrefix, rhs, _constant) {
16129 return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
16130 }
16131 let(nameOrPrefix, rhs, _constant) {
16132 return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
16133 }
16134 var(nameOrPrefix, rhs, _constant) {
16135 return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
16136 }
16137 assign(lhs, rhs, sideEffects) {
16138 return this._leafNode(new Assign(lhs, rhs, sideEffects));
16139 }
16140 add(lhs, rhs) {
16141 return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
16142 }
16143 code(c) {
16144 if (typeof c == "function") c();
16145 else if (c !== code_1.nil) this._leafNode(new AnyCode(c));
16146 return this;
16147 }
16148 object(...keyValues) {
16149 const code = ["{"];
16150 for (const [key, value] of keyValues) {
16151 if (code.length > 1) code.push(",");
16152 code.push(key);
16153 if (key !== value || this.opts.es5) {
16154 code.push(":");
16155 (0, code_1.addCodeArg)(code, value);
16156 }
16157 }
16158 code.push("}");
16159 return new code_1._Code(code);
16160 }
16161 if(condition, thenBody, elseBody) {
16162 this._blockNode(new If(condition));
16163 if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf();
16164 else if (thenBody) this.code(thenBody).endIf();
16165 else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body");
16166 return this;
16167 }
16168 elseIf(condition) {
16169 return this._elseNode(new If(condition));
16170 }
16171 else() {
16172 return this._elseNode(new Else());
16173 }
16174 endIf() {
16175 return this._endBlockNode(If, Else);
16176 }
16177 _for(node, forBody) {
16178 this._blockNode(node);
16179 if (forBody) this.code(forBody).endFor();
16180 return this;
16181 }
16182 for(iteration, forBody) {
16183 return this._for(new ForLoop(iteration), forBody);
16184 }
16185 forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
16186 const name = this._scope.toName(nameOrPrefix);
16187 return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
16188 }
16189 forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
16190 const name = this._scope.toName(nameOrPrefix);
16191 if (this.opts.es5) {
16192 const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
16193 return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => {
16194 this.var(name, (0, code_1._)`${arr}[${i}]`);
16195 forBody(name);
16196 });
16197 }
16198 return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
16199 }
16200 forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
16201 if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
16202 const name = this._scope.toName(nameOrPrefix);
16203 return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
16204 }
16205 endFor() {
16206 return this._endBlockNode(For);
16207 }
16208 label(label) {
16209 return this._leafNode(new Label(label));
16210 }
16211 break(label) {
16212 return this._leafNode(new Break(label));
16213 }
16214 return(value) {
16215 const node = new Return();
16216 this._blockNode(node);
16217 this.code(value);
16218 if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node");
16219 return this._endBlockNode(Return);
16220 }
16221 try(tryBody, catchCode, finallyCode) {
16222 if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\"");
16223 const node = new Try();
16224 this._blockNode(node);
16225 this.code(tryBody);
16226 if (catchCode) {
16227 const error = this.name("e");
16228 this._currNode = node.catch = new Catch(error);
16229 catchCode(error);
16230 }
16231 if (finallyCode) {
16232 this._currNode = node.finally = new Finally();
16233 this.code(finallyCode);
16234 }
16235 return this._endBlockNode(Catch, Finally);
16236 }
16237 throw(error) {
16238 return this._leafNode(new Throw(error));
16239 }
16240 block(body, nodeCount) {
16241 this._blockStarts.push(this._nodes.length);
16242 if (body) this.code(body).endBlock(nodeCount);
16243 return this;
16244 }
16245 endBlock(nodeCount) {
16246 const len = this._blockStarts.pop();
16247 if (len === void 0) throw new Error("CodeGen: not in self-balancing block");
16248 const toClose = this._nodes.length - len;
16249 if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
16250 this._nodes.length = len;
16251 return this;
16252 }
16253 func(name, args = code_1.nil, async, funcBody) {
16254 this._blockNode(new Func(name, args, async));
16255 if (funcBody) this.code(funcBody).endFunc();
16256 return this;
16257 }
16258 endFunc() {
16259 return this._endBlockNode(Func);
16260 }
16261 optimize(n = 1) {
16262 while (n-- > 0) {
16263 this._root.optimizeNodes();
16264 this._root.optimizeNames(this._root.names, this._constants);
16265 }
16266 }
16267 _leafNode(node) {
16268 this._currNode.nodes.push(node);
16269 return this;
16270 }
16271 _blockNode(node) {
16272 this._currNode.nodes.push(node);
16273 this._nodes.push(node);
16274 }
16275 _endBlockNode(N1, N2) {
16276 const n = this._currNode;
16277 if (n instanceof N1 || N2 && n instanceof N2) {
16278 this._nodes.pop();
16279 return this;
16280 }
16281 throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
16282 }
16283 _elseNode(node) {
16284 const n = this._currNode;
16285 if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\"");
16286 this._currNode = n.else = node;
16287 return this;
16288 }
16289 get _root() {
16290 return this._nodes[0];
16291 }
16292 get _currNode() {
16293 const ns = this._nodes;
16294 return ns[ns.length - 1];
16295 }
16296 set _currNode(node) {
16297 const ns = this._nodes;
16298 ns[ns.length - 1] = node;
16299 }
16300 };
16301 exports.CodeGen = CodeGen;
16302 function addNames(names, from) {
16303 for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0);
16304 return names;
16305 }
16306 function addExprNames(names, from) {
16307 return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
16308 }
16309 function optimizeExpr(expr, names, constants) {
16310 if (expr instanceof code_1.Name) return replaceName(expr);
16311 if (!canOptimize(expr)) return expr;
16312 return new code_1._Code(expr._items.reduce((items, c) => {
16313 if (c instanceof code_1.Name) c = replaceName(c);
16314 if (c instanceof code_1._Code) items.push(...c._items);
16315 else items.push(c);
16316 return items;
16317 }, []));
16318 function replaceName(n) {
16319 const c = constants[n.str];
16320 if (c === void 0 || names[n.str] !== 1) return n;
16321 delete names[n.str];
16322 return c;
16323 }
16324 function canOptimize(e) {
16325 return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
16326 }
16327 }
16328 function subtractNames(names, from) {
16329 for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0);
16330 }
16331 function not(x) {
16332 return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
16333 }
16334 exports.not = not;
16335 var andCode = mappend(exports.operators.AND);
16336 function and(...args) {
16337 return args.reduce(andCode);
16338 }
16339 exports.and = and;
16340 var orCode = mappend(exports.operators.OR);
16341 function or(...args) {
16342 return args.reduce(orCode);
16343 }
16344 exports.or = or;
16345 function mappend(op) {
16346 return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;
16347 }
16348 function par(x) {
16349 return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
16350 }
16351 }));
16352
16353 //#endregion
16354 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/util.js
16355 var require_util = /* @__PURE__ */ __commonJSMin(((exports) => {
16356 Object.defineProperty(exports, "__esModule", { value: true });
16357 exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
16358 var codegen_1 = require_codegen();
16359 var code_1 = require_code$1();
16360 function toHash(arr) {
16361 const hash = {};
16362 for (const item of arr) hash[item] = true;
16363 return hash;
16364 }
16365 exports.toHash = toHash;
16366 function alwaysValidSchema(it, schema) {
16367 if (typeof schema == "boolean") return schema;
16368 if (Object.keys(schema).length === 0) return true;
16369 checkUnknownRules(it, schema);
16370 return !schemaHasRules(schema, it.self.RULES.all);
16371 }
16372 exports.alwaysValidSchema = alwaysValidSchema;
16373 function checkUnknownRules(it, schema = it.schema) {
16374 const { opts, self } = it;
16375 if (!opts.strictSchema) return;
16376 if (typeof schema === "boolean") return;
16377 const rules = self.RULES.keywords;
16378 for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`);
16379 }
16380 exports.checkUnknownRules = checkUnknownRules;
16381 function schemaHasRules(schema, rules) {
16382 if (typeof schema == "boolean") return !schema;
16383 for (const key in schema) if (rules[key]) return true;
16384 return false;
16385 }
16386 exports.schemaHasRules = schemaHasRules;
16387 function schemaHasRulesButRef(schema, RULES) {
16388 if (typeof schema == "boolean") return !schema;
16389 for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true;
16390 return false;
16391 }
16392 exports.schemaHasRulesButRef = schemaHasRulesButRef;
16393 function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
16394 if (!$data) {
16395 if (typeof schema == "number" || typeof schema == "boolean") return schema;
16396 if (typeof schema == "string") return (0, codegen_1._)`${schema}`;
16397 }
16398 return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
16399 }
16400 exports.schemaRefOrVal = schemaRefOrVal;
16401 function unescapeFragment(str) {
16402 return unescapeJsonPointer(decodeURIComponent(str));
16403 }
16404 exports.unescapeFragment = unescapeFragment;
16405 function escapeFragment(str) {
16406 return encodeURIComponent(escapeJsonPointer(str));
16407 }
16408 exports.escapeFragment = escapeFragment;
16409 function escapeJsonPointer(str) {
16410 if (typeof str == "number") return `${str}`;
16411 return str.replace(/~/g, "~0").replace(/\//g, "~1");
16412 }
16413 exports.escapeJsonPointer = escapeJsonPointer;
16414 function unescapeJsonPointer(str) {
16415 return str.replace(/~1/g, "/").replace(/~0/g, "~");
16416 }
16417 exports.unescapeJsonPointer = unescapeJsonPointer;
16418 function eachItem(xs, f) {
16419 if (Array.isArray(xs)) for (const x of xs) f(x);
16420 else f(xs);
16421 }
16422 exports.eachItem = eachItem;
16423 function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) {
16424 return (gen, from, to, toName) => {
16425 const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to);
16426 return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
16427 };
16428 }
16429 exports.mergeEvaluated = {
16430 props: makeMergeEvaluated({
16431 mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {
16432 gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`));
16433 }),
16434 mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {
16435 if (from === true) gen.assign(to, true);
16436 else {
16437 gen.assign(to, (0, codegen_1._)`${to} || {}`);
16438 setEvaluated(gen, to, from);
16439 }
16440 }),
16441 mergeValues: (from, to) => from === true ? true : {
16442 ...from,
16443 ...to
16444 },
16445 resultToName: evaluatedPropsToName
16446 }),
16447 items: makeMergeEvaluated({
16448 mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
16449 mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),
16450 mergeValues: (from, to) => from === true ? true : Math.max(from, to),
16451 resultToName: (gen, items) => gen.var("items", items)
16452 })
16453 };
16454 function evaluatedPropsToName(gen, ps) {
16455 if (ps === true) return gen.var("props", true);
16456 const props = gen.var("props", (0, codegen_1._)`{}`);
16457 if (ps !== void 0) setEvaluated(gen, props, ps);
16458 return props;
16459 }
16460 exports.evaluatedPropsToName = evaluatedPropsToName;
16461 function setEvaluated(gen, props, ps) {
16462 Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));
16463 }
16464 exports.setEvaluated = setEvaluated;
16465 var snippets = {};
16466 function useFunc(gen, f) {
16467 return gen.scopeValue("func", {
16468 ref: f,
16469 code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))
16470 });
16471 }
16472 exports.useFunc = useFunc;
16473 var Type;
16474 (function(Type) {
16475 Type[Type["Num"] = 0] = "Num";
16476 Type[Type["Str"] = 1] = "Str";
16477 })(Type || (exports.Type = Type = {}));
16478 function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
16479 if (dataProp instanceof codegen_1.Name) {
16480 const isNumber = dataPropType === Type.Num;
16481 return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
16482 }
16483 return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
16484 }
16485 exports.getErrorPath = getErrorPath;
16486 function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
16487 if (!mode) return;
16488 msg = `strict mode: ${msg}`;
16489 if (mode === true) throw new Error(msg);
16490 it.self.logger.warn(msg);
16491 }
16492 exports.checkStrictMode = checkStrictMode;
16493 }));
16494
16495 //#endregion
16496 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/names.js
16497 var require_names = /* @__PURE__ */ __commonJSMin(((exports) => {
16498 Object.defineProperty(exports, "__esModule", { value: true });
16499 var codegen_1 = require_codegen();
16500 var names = {
16501 data: new codegen_1.Name("data"),
16502 valCxt: new codegen_1.Name("valCxt"),
16503 instancePath: new codegen_1.Name("instancePath"),
16504 parentData: new codegen_1.Name("parentData"),
16505 parentDataProperty: new codegen_1.Name("parentDataProperty"),
16506 rootData: new codegen_1.Name("rootData"),
16507 dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
16508 vErrors: new codegen_1.Name("vErrors"),
16509 errors: new codegen_1.Name("errors"),
16510 this: new codegen_1.Name("this"),
16511 self: new codegen_1.Name("self"),
16512 scope: new codegen_1.Name("scope"),
16513 json: new codegen_1.Name("json"),
16514 jsonPos: new codegen_1.Name("jsonPos"),
16515 jsonLen: new codegen_1.Name("jsonLen"),
16516 jsonPart: new codegen_1.Name("jsonPart")
16517 };
16518 exports.default = names;
16519 }));
16520
16521 //#endregion
16522 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/errors.js
16523 var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => {
16524 Object.defineProperty(exports, "__esModule", { value: true });
16525 exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
16526 var codegen_1 = require_codegen();
16527 var util_1 = require_util();
16528 var names_1 = require_names();
16529 exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` };
16530 exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` };
16531 function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
16532 const { it } = cxt;
16533 const { gen, compositeRule, allErrors } = it;
16534 const errObj = errorObjectCode(cxt, error, errorPaths);
16535 if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj);
16536 else returnErrors(it, (0, codegen_1._)`[${errObj}]`);
16537 }
16538 exports.reportError = reportError;
16539 function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
16540 const { it } = cxt;
16541 const { gen, compositeRule, allErrors } = it;
16542 addError(gen, errorObjectCode(cxt, error, errorPaths));
16543 if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors);
16544 }
16545 exports.reportExtraError = reportExtraError;
16546 function resetErrorsCount(gen, errsCount) {
16547 gen.assign(names_1.default.errors, errsCount);
16548 gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
16549 }
16550 exports.resetErrorsCount = resetErrorsCount;
16551 function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
16552 /* istanbul ignore if */
16553 if (errsCount === void 0) throw new Error("ajv implementation error");
16554 const err = gen.name("err");
16555 gen.forRange("i", errsCount, names_1.default.errors, (i) => {
16556 gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
16557 gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
16558 gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
16559 if (it.opts.verbose) {
16560 gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
16561 gen.assign((0, codegen_1._)`${err}.data`, data);
16562 }
16563 });
16564 }
16565 exports.extendErrors = extendErrors;
16566 function addError(gen, errObj) {
16567 const err = gen.const("err", errObj);
16568 gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
16569 gen.code((0, codegen_1._)`${names_1.default.errors}++`);
16570 }
16571 function returnErrors(it, errs) {
16572 const { gen, validateName, schemaEnv } = it;
16573 if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);
16574 else {
16575 gen.assign((0, codegen_1._)`${validateName}.errors`, errs);
16576 gen.return(false);
16577 }
16578 }
16579 var E = {
16580 keyword: new codegen_1.Name("keyword"),
16581 schemaPath: new codegen_1.Name("schemaPath"),
16582 params: new codegen_1.Name("params"),
16583 propertyName: new codegen_1.Name("propertyName"),
16584 message: new codegen_1.Name("message"),
16585 schema: new codegen_1.Name("schema"),
16586 parentSchema: new codegen_1.Name("parentSchema")
16587 };
16588 function errorObjectCode(cxt, error, errorPaths) {
16589 const { createErrors } = cxt.it;
16590 if (createErrors === false) return (0, codegen_1._)`{}`;
16591 return errorObject(cxt, error, errorPaths);
16592 }
16593 function errorObject(cxt, error, errorPaths = {}) {
16594 const { gen, it } = cxt;
16595 const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)];
16596 extraErrorProps(cxt, error, keyValues);
16597 return gen.object(...keyValues);
16598 }
16599 function errorInstancePath({ errorPath }, { instancePath }) {
16600 const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;
16601 return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
16602 }
16603 function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
16604 let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;
16605 if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
16606 return [E.schemaPath, schPath];
16607 }
16608 function extraErrorProps(cxt, { params, message }, keyValues) {
16609 const { keyword, data, schemaValue, it } = cxt;
16610 const { opts, propertyName, topSchemaRef, schemaPath } = it;
16611 keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
16612 if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
16613 if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
16614 if (propertyName) keyValues.push([E.propertyName, propertyName]);
16615 }
16616 }));
16617
16618 //#endregion
16619 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/boolSchema.js
16620 var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => {
16621 Object.defineProperty(exports, "__esModule", { value: true });
16622 exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
16623 var errors_1 = require_errors();
16624 var codegen_1 = require_codegen();
16625 var names_1 = require_names();
16626 var boolError = { message: "boolean schema is false" };
16627 function topBoolOrEmptySchema(it) {
16628 const { gen, schema, validateName } = it;
16629 if (schema === false) falseSchemaError(it, false);
16630 else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data);
16631 else {
16632 gen.assign((0, codegen_1._)`${validateName}.errors`, null);
16633 gen.return(true);
16634 }
16635 }
16636 exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
16637 function boolOrEmptySchema(it, valid) {
16638 const { gen, schema } = it;
16639 if (schema === false) {
16640 gen.var(valid, false);
16641 falseSchemaError(it);
16642 } else gen.var(valid, true);
16643 }
16644 exports.boolOrEmptySchema = boolOrEmptySchema;
16645 function falseSchemaError(it, overrideAllErrors) {
16646 const { gen, data } = it;
16647 const cxt = {
16648 gen,
16649 keyword: "false schema",
16650 data,
16651 schema: false,
16652 schemaCode: false,
16653 schemaValue: false,
16654 params: {},
16655 it
16656 };
16657 (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
16658 }
16659 }));
16660
16661 //#endregion
16662 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/rules.js
16663 var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => {
16664 Object.defineProperty(exports, "__esModule", { value: true });
16665 exports.getRules = exports.isJSONType = void 0;
16666 var jsonTypes = /* @__PURE__ */ new Set([
16667 "string",
16668 "number",
16669 "integer",
16670 "boolean",
16671 "null",
16672 "object",
16673 "array"
16674 ]);
16675 function isJSONType(x) {
16676 return typeof x == "string" && jsonTypes.has(x);
16677 }
16678 exports.isJSONType = isJSONType;
16679 function getRules() {
16680 const groups = {
16681 number: {
16682 type: "number",
16683 rules: []
16684 },
16685 string: {
16686 type: "string",
16687 rules: []
16688 },
16689 array: {
16690 type: "array",
16691 rules: []
16692 },
16693 object: {
16694 type: "object",
16695 rules: []
16696 }
16697 };
16698 return {
16699 types: {
16700 ...groups,
16701 integer: true,
16702 boolean: true,
16703 null: true
16704 },
16705 rules: [
16706 { rules: [] },
16707 groups.number,
16708 groups.string,
16709 groups.array,
16710 groups.object
16711 ],
16712 post: { rules: [] },
16713 all: {},
16714 keywords: {}
16715 };
16716 }
16717 exports.getRules = getRules;
16718 }));
16719
16720 //#endregion
16721 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/applicability.js
16722 var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => {
16723 Object.defineProperty(exports, "__esModule", { value: true });
16724 exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
16725 function schemaHasRulesForType({ schema, self }, type) {
16726 const group = self.RULES.types[type];
16727 return group && group !== true && shouldUseGroup(schema, group);
16728 }
16729 exports.schemaHasRulesForType = schemaHasRulesForType;
16730 function shouldUseGroup(schema, group) {
16731 return group.rules.some((rule) => shouldUseRule(schema, rule));
16732 }
16733 exports.shouldUseGroup = shouldUseGroup;
16734 function shouldUseRule(schema, rule) {
16735 var _a;
16736 return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0));
16737 }
16738 exports.shouldUseRule = shouldUseRule;
16739 }));
16740
16741 //#endregion
16742 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/dataType.js
16743 var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => {
16744 Object.defineProperty(exports, "__esModule", { value: true });
16745 exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
16746 var rules_1 = require_rules();
16747 var applicability_1 = require_applicability();
16748 var errors_1 = require_errors();
16749 var codegen_1 = require_codegen();
16750 var util_1 = require_util();
16751 var DataType;
16752 (function(DataType) {
16753 DataType[DataType["Correct"] = 0] = "Correct";
16754 DataType[DataType["Wrong"] = 1] = "Wrong";
16755 })(DataType || (exports.DataType = DataType = {}));
16756 function getSchemaTypes(schema) {
16757 const types = getJSONTypes(schema.type);
16758 if (types.includes("null")) {
16759 if (schema.nullable === false) throw new Error("type: null contradicts nullable: false");
16760 } else {
16761 if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\"");
16762 if (schema.nullable === true) types.push("null");
16763 }
16764 return types;
16765 }
16766 exports.getSchemaTypes = getSchemaTypes;
16767 function getJSONTypes(ts) {
16768 const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
16769 if (types.every(rules_1.isJSONType)) return types;
16770 throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
16771 }
16772 exports.getJSONTypes = getJSONTypes;
16773 function coerceAndCheckDataType(it, types) {
16774 const { gen, data, opts } = it;
16775 const coerceTo = coerceToTypes(types, opts.coerceTypes);
16776 const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
16777 if (checkTypes) {
16778 const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
16779 gen.if(wrongType, () => {
16780 if (coerceTo.length) coerceData(it, types, coerceTo);
16781 else reportTypeError(it);
16782 });
16783 }
16784 return checkTypes;
16785 }
16786 exports.coerceAndCheckDataType = coerceAndCheckDataType;
16787 var COERCIBLE = /* @__PURE__ */ new Set([
16788 "string",
16789 "number",
16790 "integer",
16791 "boolean",
16792 "null"
16793 ]);
16794 function coerceToTypes(types, coerceTypes) {
16795 return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : [];
16796 }
16797 function coerceData(it, types, coerceTo) {
16798 const { gen, data, opts } = it;
16799 const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`);
16800 const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
16801 if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
16802 gen.if((0, codegen_1._)`${coerced} !== undefined`);
16803 for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t);
16804 gen.else();
16805 reportTypeError(it);
16806 gen.endIf();
16807 gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
16808 gen.assign(data, coerced);
16809 assignParentData(it, coerced);
16810 });
16811 function coerceSpecificType(t) {
16812 switch (t) {
16813 case "string":
16814 gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);
16815 return;
16816 case "number":
16817 gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null
16818 || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);
16819 return;
16820 case "integer":
16821 gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null
16822 || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`);
16823 return;
16824 case "boolean":
16825 gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true);
16826 return;
16827 case "null":
16828 gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`);
16829 gen.assign(coerced, null);
16830 return;
16831 case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number"
16832 || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
16833 }
16834 }
16835 }
16836 function assignParentData({ gen, parentData, parentDataProperty }, expr) {
16837 gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
16838 }
16839 function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
16840 const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
16841 let cond;
16842 switch (dataType) {
16843 case "null": return (0, codegen_1._)`${data} ${EQ} null`;
16844 case "array":
16845 cond = (0, codegen_1._)`Array.isArray(${data})`;
16846 break;
16847 case "object":
16848 cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
16849 break;
16850 case "integer":
16851 cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);
16852 break;
16853 case "number":
16854 cond = numCond();
16855 break;
16856 default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`;
16857 }
16858 return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
16859 function numCond(_cond = codegen_1.nil) {
16860 return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);
16861 }
16862 }
16863 exports.checkDataType = checkDataType;
16864 function checkDataTypes(dataTypes, data, strictNums, correct) {
16865 if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct);
16866 let cond;
16867 const types = (0, util_1.toHash)(dataTypes);
16868 if (types.array && types.object) {
16869 const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
16870 cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
16871 delete types.null;
16872 delete types.array;
16873 delete types.object;
16874 } else cond = codegen_1.nil;
16875 if (types.number) delete types.integer;
16876 for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
16877 return cond;
16878 }
16879 exports.checkDataTypes = checkDataTypes;
16880 var typeError = {
16881 message: ({ schema }) => `must be ${schema}`,
16882 params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
16883 };
16884 function reportTypeError(it) {
16885 const cxt = getTypeErrorContext(it);
16886 (0, errors_1.reportError)(cxt, typeError);
16887 }
16888 exports.reportTypeError = reportTypeError;
16889 function getTypeErrorContext(it) {
16890 const { gen, data, schema } = it;
16891 const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
16892 return {
16893 gen,
16894 keyword: "type",
16895 data,
16896 schema: schema.type,
16897 schemaCode,
16898 schemaValue: schemaCode,
16899 parentSchema: schema,
16900 params: {},
16901 it
16902 };
16903 }
16904 }));
16905
16906 //#endregion
16907 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/defaults.js
16908 var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => {
16909 Object.defineProperty(exports, "__esModule", { value: true });
16910 exports.assignDefaults = void 0;
16911 var codegen_1 = require_codegen();
16912 var util_1 = require_util();
16913 function assignDefaults(it, ty) {
16914 const { properties, items } = it.schema;
16915 if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default);
16916 else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default));
16917 }
16918 exports.assignDefaults = assignDefaults;
16919 function assignDefault(it, prop, defaultValue) {
16920 const { gen, compositeRule, data, opts } = it;
16921 if (defaultValue === void 0) return;
16922 const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
16923 if (compositeRule) {
16924 (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
16925 return;
16926 }
16927 let condition = (0, codegen_1._)`${childData} === undefined`;
16928 if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
16929 gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
16930 }
16931 }));
16932
16933 //#endregion
16934 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/code.js
16935 var require_code = /* @__PURE__ */ __commonJSMin(((exports) => {
16936 Object.defineProperty(exports, "__esModule", { value: true });
16937 exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
16938 var codegen_1 = require_codegen();
16939 var util_1 = require_util();
16940 var names_1 = require_names();
16941 var util_2 = require_util();
16942 function checkReportMissingProp(cxt, prop) {
16943 const { gen, data, it } = cxt;
16944 gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
16945 cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
16946 cxt.error();
16947 });
16948 }
16949 exports.checkReportMissingProp = checkReportMissingProp;
16950 function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
16951 return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
16952 }
16953 exports.checkMissingProp = checkMissingProp;
16954 function reportMissingProp(cxt, missing) {
16955 cxt.setParams({ missingProperty: missing }, true);
16956 cxt.error();
16957 }
16958 exports.reportMissingProp = reportMissingProp;
16959 function hasPropFunc(gen) {
16960 return gen.scopeValue("func", {
16961 ref: Object.prototype.hasOwnProperty,
16962 code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
16963 });
16964 }
16965 exports.hasPropFunc = hasPropFunc;
16966 function isOwnProperty(gen, data, property) {
16967 return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
16968 }
16969 exports.isOwnProperty = isOwnProperty;
16970 function propertyInData(gen, data, property, ownProperties) {
16971 const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
16972 return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
16973 }
16974 exports.propertyInData = propertyInData;
16975 function noPropertyInData(gen, data, property, ownProperties) {
16976 const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;
16977 return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
16978 }
16979 exports.noPropertyInData = noPropertyInData;
16980 function allSchemaProperties(schemaMap) {
16981 return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
16982 }
16983 exports.allSchemaProperties = allSchemaProperties;
16984 function schemaProperties(it, schemaMap) {
16985 return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
16986 }
16987 exports.schemaProperties = schemaProperties;
16988 function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
16989 const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
16990 const valCxt = [
16991 [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
16992 [names_1.default.parentData, it.parentData],
16993 [names_1.default.parentDataProperty, it.parentDataProperty],
16994 [names_1.default.rootData, names_1.default.rootData]
16995 ];
16996 if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
16997 const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
16998 return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
16999 }
17000 exports.callValidateCode = callValidateCode;
17001 var newRegExp = (0, codegen_1._)`new RegExp`;
17002 function usePattern({ gen, it: { opts } }, pattern) {
17003 const u = opts.unicodeRegExp ? "u" : "";
17004 const { regExp } = opts.code;
17005 const rx = regExp(pattern, u);
17006 return gen.scopeValue("pattern", {
17007 key: rx.toString(),
17008 ref: rx,
17009 code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`
17010 });
17011 }
17012 exports.usePattern = usePattern;
17013 function validateArray(cxt) {
17014 const { gen, data, keyword, it } = cxt;
17015 const valid = gen.name("valid");
17016 if (it.allErrors) {
17017 const validArr = gen.let("valid", true);
17018 validateItems(() => gen.assign(validArr, false));
17019 return validArr;
17020 }
17021 gen.var(valid, true);
17022 validateItems(() => gen.break());
17023 return valid;
17024 function validateItems(notValid) {
17025 const len = gen.const("len", (0, codegen_1._)`${data}.length`);
17026 gen.forRange("i", 0, len, (i) => {
17027 cxt.subschema({
17028 keyword,
17029 dataProp: i,
17030 dataPropType: util_1.Type.Num
17031 }, valid);
17032 gen.if((0, codegen_1.not)(valid), notValid);
17033 });
17034 }
17035 }
17036 exports.validateArray = validateArray;
17037 function validateUnion(cxt) {
17038 const { gen, schema, keyword, it } = cxt;
17039 /* istanbul ignore if */
17040 if (!Array.isArray(schema)) throw new Error("ajv implementation error");
17041 if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return;
17042 const valid = gen.let("valid", false);
17043 const schValid = gen.name("_valid");
17044 gen.block(() => schema.forEach((_sch, i) => {
17045 const schCxt = cxt.subschema({
17046 keyword,
17047 schemaProp: i,
17048 compositeRule: true
17049 }, schValid);
17050 gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
17051 if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid));
17052 }));
17053 cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
17054 }
17055 exports.validateUnion = validateUnion;
17056 }));
17057
17058 //#endregion
17059 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/keyword.js
17060 var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => {
17061 Object.defineProperty(exports, "__esModule", { value: true });
17062 exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
17063 var codegen_1 = require_codegen();
17064 var names_1 = require_names();
17065 var code_1 = require_code();
17066 var errors_1 = require_errors();
17067 function macroKeywordCode(cxt, def) {
17068 const { gen, keyword, schema, parentSchema, it } = cxt;
17069 const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
17070 const schemaRef = useKeyword(gen, keyword, macroSchema);
17071 if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true);
17072 const valid = gen.name("valid");
17073 cxt.subschema({
17074 schema: macroSchema,
17075 schemaPath: codegen_1.nil,
17076 errSchemaPath: `${it.errSchemaPath}/${keyword}`,
17077 topSchemaRef: schemaRef,
17078 compositeRule: true
17079 }, valid);
17080 cxt.pass(valid, () => cxt.error(true));
17081 }
17082 exports.macroKeywordCode = macroKeywordCode;
17083 function funcKeywordCode(cxt, def) {
17084 var _a;
17085 const { gen, keyword, schema, parentSchema, $data, it } = cxt;
17086 checkAsyncKeyword(it, def);
17087 const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate);
17088 const valid = gen.let("valid");
17089 cxt.block$data(valid, validateKeyword);
17090 cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
17091 function validateKeyword() {
17092 if (def.errors === false) {
17093 assignValid();
17094 if (def.modifying) modifyData(cxt);
17095 reportErrs(() => cxt.error());
17096 } else {
17097 const ruleErrs = def.async ? validateAsync() : validateSync();
17098 if (def.modifying) modifyData(cxt);
17099 reportErrs(() => addErrs(cxt, ruleErrs));
17100 }
17101 }
17102 function validateAsync() {
17103 const ruleErrs = gen.let("ruleErrs", null);
17104 gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e)));
17105 return ruleErrs;
17106 }
17107 function validateSync() {
17108 const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
17109 gen.assign(validateErrs, null);
17110 assignValid(codegen_1.nil);
17111 return validateErrs;
17112 }
17113 function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
17114 const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
17115 const passSchema = !("compile" in def && !$data || def.schema === false);
17116 gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
17117 }
17118 function reportErrs(errors) {
17119 var _a;
17120 gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
17121 }
17122 }
17123 exports.funcKeywordCode = funcKeywordCode;
17124 function modifyData(cxt) {
17125 const { gen, data, it } = cxt;
17126 gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
17127 }
17128 function addErrs(cxt, errs) {
17129 const { gen } = cxt;
17130 gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
17131 gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
17132 (0, errors_1.extendErrors)(cxt);
17133 }, () => cxt.error());
17134 }
17135 function checkAsyncKeyword({ schemaEnv }, def) {
17136 if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema");
17137 }
17138 function useKeyword(gen, keyword, result) {
17139 if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`);
17140 return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : {
17141 ref: result,
17142 code: (0, codegen_1.stringify)(result)
17143 });
17144 }
17145 function validSchemaType(schema, schemaType, allowUndefined = false) {
17146 return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
17147 }
17148 exports.validSchemaType = validSchemaType;
17149 function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
17150 /* istanbul ignore if */
17151 if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error");
17152 const deps = def.dependencies;
17153 if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
17154 if (def.validateSchema) {
17155 if (!def.validateSchema(schema[keyword])) {
17156 const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors);
17157 if (opts.validateSchema === "log") self.logger.error(msg);
17158 else throw new Error(msg);
17159 }
17160 }
17161 }
17162 exports.validateKeywordUsage = validateKeywordUsage;
17163 }));
17164
17165 //#endregion
17166 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/subschema.js
17167 var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => {
17168 Object.defineProperty(exports, "__esModule", { value: true });
17169 exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
17170 var codegen_1 = require_codegen();
17171 var util_1 = require_util();
17172 function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
17173 if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed");
17174 if (keyword !== void 0) {
17175 const sch = it.schema[keyword];
17176 return schemaProp === void 0 ? {
17177 schema: sch,
17178 schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
17179 errSchemaPath: `${it.errSchemaPath}/${keyword}`
17180 } : {
17181 schema: sch[schemaProp],
17182 schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
17183 errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`
17184 };
17185 }
17186 if (schema !== void 0) {
17187 if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"");
17188 return {
17189 schema,
17190 schemaPath,
17191 topSchemaRef,
17192 errSchemaPath
17193 };
17194 }
17195 throw new Error("either \"keyword\" or \"schema\" must be passed");
17196 }
17197 exports.getSubschema = getSubschema;
17198 function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
17199 if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed");
17200 const { gen } = it;
17201 if (dataProp !== void 0) {
17202 const { errorPath, dataPathArr, opts } = it;
17203 dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true));
17204 subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
17205 subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;
17206 subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
17207 }
17208 if (data !== void 0) {
17209 dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true));
17210 if (propertyName !== void 0) subschema.propertyName = propertyName;
17211 }
17212 if (dataTypes) subschema.dataTypes = dataTypes;
17213 function dataContextProps(_nextData) {
17214 subschema.data = _nextData;
17215 subschema.dataLevel = it.dataLevel + 1;
17216 subschema.dataTypes = [];
17217 it.definedProperties = /* @__PURE__ */ new Set();
17218 subschema.parentData = it.data;
17219 subschema.dataNames = [...it.dataNames, _nextData];
17220 }
17221 }
17222 exports.extendSubschemaData = extendSubschemaData;
17223 function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
17224 if (compositeRule !== void 0) subschema.compositeRule = compositeRule;
17225 if (createErrors !== void 0) subschema.createErrors = createErrors;
17226 if (allErrors !== void 0) subschema.allErrors = allErrors;
17227 subschema.jtdDiscriminator = jtdDiscriminator;
17228 subschema.jtdMetadata = jtdMetadata;
17229 }
17230 exports.extendSubschemaMode = extendSubschemaMode;
17231 }));
17232
17233 //#endregion
17234 //#region node_modules/fast-deep-equal/index.js
17235 var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17236 module.exports = function equal(a, b) {
17237 if (a === b) return true;
17238 if (a && b && typeof a == "object" && typeof b == "object") {
17239 if (a.constructor !== b.constructor) return false;
17240 var length;
17241 var i;
17242 var keys;
17243 if (Array.isArray(a)) {
17244 length = a.length;
17245 if (length != b.length) return false;
17246 for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;
17247 return true;
17248 }
17249 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
17250 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
17251 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
17252 keys = Object.keys(a);
17253 length = keys.length;
17254 if (length !== Object.keys(b).length) return false;
17255 for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
17256 for (i = length; i-- !== 0;) {
17257 var key = keys[i];
17258 if (!equal(a[key], b[key])) return false;
17259 }
17260 return true;
17261 }
17262 return a !== a && b !== b;
17263 };
17264 }));
17265
17266 //#endregion
17267 //#region node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse/index.js
17268 var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17269 var traverse = module.exports = function(schema, opts, cb) {
17270 if (typeof opts == "function") {
17271 cb = opts;
17272 opts = {};
17273 }
17274 cb = opts.cb || cb;
17275 var pre = typeof cb == "function" ? cb : cb.pre || function() {};
17276 var post = cb.post || function() {};
17277 _traverse(opts, pre, post, schema, "", schema);
17278 };
17279 traverse.keywords = {
17280 additionalItems: true,
17281 items: true,
17282 contains: true,
17283 additionalProperties: true,
17284 propertyNames: true,
17285 not: true,
17286 if: true,
17287 then: true,
17288 else: true
17289 };
17290 traverse.arrayKeywords = {
17291 items: true,
17292 allOf: true,
17293 anyOf: true,
17294 oneOf: true
17295 };
17296 traverse.propsKeywords = {
17297 $defs: true,
17298 definitions: true,
17299 properties: true,
17300 patternProperties: true,
17301 dependencies: true
17302 };
17303 traverse.skipKeywords = {
17304 default: true,
17305 enum: true,
17306 const: true,
17307 required: true,
17308 maximum: true,
17309 minimum: true,
17310 exclusiveMaximum: true,
17311 exclusiveMinimum: true,
17312 multipleOf: true,
17313 maxLength: true,
17314 minLength: true,
17315 pattern: true,
17316 format: true,
17317 maxItems: true,
17318 minItems: true,
17319 uniqueItems: true,
17320 maxProperties: true,
17321 minProperties: true
17322 };
17323 function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
17324 if (schema && typeof schema == "object" && !Array.isArray(schema)) {
17325 pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
17326 for (var key in schema) {
17327 var sch = schema[key];
17328 if (Array.isArray(sch)) {
17329 if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
17330 } else if (key in traverse.propsKeywords) {
17331 if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
17332 } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
17333 }
17334 post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
17335 }
17336 }
17337 function escapeJsonPtr(str) {
17338 return str.replace(/~/g, "~0").replace(/\//g, "~1");
17339 }
17340 }));
17341
17342 //#endregion
17343 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/resolve.js
17344 var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => {
17345 Object.defineProperty(exports, "__esModule", { value: true });
17346 exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
17347 var util_1 = require_util();
17348 var equal = require_fast_deep_equal();
17349 var traverse = require_json_schema_traverse();
17350 var SIMPLE_INLINED = /* @__PURE__ */ new Set([
17351 "type",
17352 "format",
17353 "pattern",
17354 "maxLength",
17355 "minLength",
17356 "maxProperties",
17357 "minProperties",
17358 "maxItems",
17359 "minItems",
17360 "maximum",
17361 "minimum",
17362 "uniqueItems",
17363 "multipleOf",
17364 "required",
17365 "enum",
17366 "const"
17367 ]);
17368 function inlineRef(schema, limit = true) {
17369 if (typeof schema == "boolean") return true;
17370 if (limit === true) return !hasRef(schema);
17371 if (!limit) return false;
17372 return countKeys(schema) <= limit;
17373 }
17374 exports.inlineRef = inlineRef;
17375 var REF_KEYWORDS = /* @__PURE__ */ new Set([
17376 "$ref",
17377 "$recursiveRef",
17378 "$recursiveAnchor",
17379 "$dynamicRef",
17380 "$dynamicAnchor"
17381 ]);
17382 function hasRef(schema) {
17383 for (const key in schema) {
17384 if (REF_KEYWORDS.has(key)) return true;
17385 const sch = schema[key];
17386 if (Array.isArray(sch) && sch.some(hasRef)) return true;
17387 if (typeof sch == "object" && hasRef(sch)) return true;
17388 }
17389 return false;
17390 }
17391 function countKeys(schema) {
17392 let count = 0;
17393 for (const key in schema) {
17394 if (key === "$ref") return Infinity;
17395 count++;
17396 if (SIMPLE_INLINED.has(key)) continue;
17397 if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
17398 if (count === Infinity) return Infinity;
17399 }
17400 return count;
17401 }
17402 function getFullPath(resolver, id = "", normalize) {
17403 if (normalize !== false) id = normalizeId(id);
17404 return _getFullPath(resolver, resolver.parse(id));
17405 }
17406 exports.getFullPath = getFullPath;
17407 function _getFullPath(resolver, p) {
17408 return resolver.serialize(p).split("#")[0] + "#";
17409 }
17410 exports._getFullPath = _getFullPath;
17411 var TRAILING_SLASH_HASH = /#\/?$/;
17412 function normalizeId(id) {
17413 return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
17414 }
17415 exports.normalizeId = normalizeId;
17416 function resolveUrl(resolver, baseId, id) {
17417 id = normalizeId(id);
17418 return resolver.resolve(baseId, id);
17419 }
17420 exports.resolveUrl = resolveUrl;
17421 var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
17422 function getSchemaRefs(schema, baseId) {
17423 if (typeof schema == "boolean") return {};
17424 const { schemaId, uriResolver } = this.opts;
17425 const schId = normalizeId(schema[schemaId] || baseId);
17426 const baseIds = { "": schId };
17427 const pathPrefix = getFullPath(uriResolver, schId, false);
17428 const localRefs = {};
17429 const schemaRefs = /* @__PURE__ */ new Set();
17430 traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
17431 if (parentJsonPtr === void 0) return;
17432 const fullPath = pathPrefix + jsonPtr;
17433 let innerBaseId = baseIds[parentJsonPtr];
17434 if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]);
17435 addAnchor.call(this, sch.$anchor);
17436 addAnchor.call(this, sch.$dynamicAnchor);
17437 baseIds[jsonPtr] = innerBaseId;
17438 function addRef(ref) {
17439 const _resolve = this.opts.uriResolver.resolve;
17440 ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
17441 if (schemaRefs.has(ref)) throw ambiguos(ref);
17442 schemaRefs.add(ref);
17443 let schOrRef = this.refs[ref];
17444 if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef];
17445 if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref);
17446 else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") {
17447 checkAmbiguosRef(sch, localRefs[ref], ref);
17448 localRefs[ref] = sch;
17449 } else this.refs[ref] = fullPath;
17450 return ref;
17451 }
17452 function addAnchor(anchor) {
17453 if (typeof anchor == "string") {
17454 if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`);
17455 addRef.call(this, `#${anchor}`);
17456 }
17457 }
17458 });
17459 return localRefs;
17460 function checkAmbiguosRef(sch1, sch2, ref) {
17461 if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref);
17462 }
17463 function ambiguos(ref) {
17464 return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`);
17465 }
17466 }
17467 exports.getSchemaRefs = getSchemaRefs;
17468 }));
17469
17470 //#endregion
17471 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/index.js
17472 var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => {
17473 Object.defineProperty(exports, "__esModule", { value: true });
17474 exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
17475 var boolSchema_1 = require_boolSchema();
17476 var dataType_1 = require_dataType();
17477 var applicability_1 = require_applicability();
17478 var dataType_2 = require_dataType();
17479 var defaults_1 = require_defaults();
17480 var keyword_1 = require_keyword();
17481 var subschema_1 = require_subschema();
17482 var codegen_1 = require_codegen();
17483 var names_1 = require_names();
17484 var resolve_1 = require_resolve();
17485 var util_1 = require_util();
17486 var errors_1 = require_errors();
17487 function validateFunctionCode(it) {
17488 if (isSchemaObj(it)) {
17489 checkKeywords(it);
17490 if (schemaCxtHasRules(it)) {
17491 topSchemaObjCode(it);
17492 return;
17493 }
17494 }
17495 validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
17496 }
17497 exports.validateFunctionCode = validateFunctionCode;
17498 function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
17499 if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
17500 gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
17501 destructureValCxtES5(gen, opts);
17502 gen.code(body);
17503 });
17504 else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
17505 }
17506 function destructureValCxt(opts) {
17507 return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
17508 }
17509 function destructureValCxtES5(gen, opts) {
17510 gen.if(names_1.default.valCxt, () => {
17511 gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
17512 gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
17513 gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
17514 gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
17515 if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
17516 }, () => {
17517 gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
17518 gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
17519 gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
17520 gen.var(names_1.default.rootData, names_1.default.data);
17521 if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
17522 });
17523 }
17524 function topSchemaObjCode(it) {
17525 const { schema, opts, gen } = it;
17526 validateFunction(it, () => {
17527 if (opts.$comment && schema.$comment) commentKeyword(it);
17528 checkNoDefault(it);
17529 gen.let(names_1.default.vErrors, null);
17530 gen.let(names_1.default.errors, 0);
17531 if (opts.unevaluated) resetEvaluated(it);
17532 typeAndKeywords(it);
17533 returnResults(it);
17534 });
17535 }
17536 function resetEvaluated(it) {
17537 const { gen, validateName } = it;
17538 it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
17539 gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
17540 gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
17541 }
17542 function funcSourceUrl(schema, opts) {
17543 const schId = typeof schema == "object" && schema[opts.schemaId];
17544 return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
17545 }
17546 function subschemaCode(it, valid) {
17547 if (isSchemaObj(it)) {
17548 checkKeywords(it);
17549 if (schemaCxtHasRules(it)) {
17550 subSchemaObjCode(it, valid);
17551 return;
17552 }
17553 }
17554 (0, boolSchema_1.boolOrEmptySchema)(it, valid);
17555 }
17556 function schemaCxtHasRules({ schema, self }) {
17557 if (typeof schema == "boolean") return !schema;
17558 for (const key in schema) if (self.RULES.all[key]) return true;
17559 return false;
17560 }
17561 function isSchemaObj(it) {
17562 return typeof it.schema != "boolean";
17563 }
17564 function subSchemaObjCode(it, valid) {
17565 const { schema, gen, opts } = it;
17566 if (opts.$comment && schema.$comment) commentKeyword(it);
17567 updateContext(it);
17568 checkAsyncSchema(it);
17569 const errsCount = gen.const("_errs", names_1.default.errors);
17570 typeAndKeywords(it, errsCount);
17571 gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
17572 }
17573 function checkKeywords(it) {
17574 (0, util_1.checkUnknownRules)(it);
17575 checkRefsAndKeywords(it);
17576 }
17577 function typeAndKeywords(it, errsCount) {
17578 if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount);
17579 const types = (0, dataType_1.getSchemaTypes)(it.schema);
17580 schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount);
17581 }
17582 function checkRefsAndKeywords(it) {
17583 const { schema, errSchemaPath, opts, self } = it;
17584 if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
17585 }
17586 function checkNoDefault(it) {
17587 const { schema, opts } = it;
17588 if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
17589 }
17590 function updateContext(it) {
17591 const schId = it.schema[it.opts.schemaId];
17592 if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
17593 }
17594 function checkAsyncSchema(it) {
17595 if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema");
17596 }
17597 function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
17598 const msg = schema.$comment;
17599 if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
17600 else if (typeof opts.$comment == "function") {
17601 const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
17602 const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
17603 gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
17604 }
17605 }
17606 function returnResults(it) {
17607 const { gen, schemaEnv, validateName, ValidationError, opts } = it;
17608 if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
17609 else {
17610 gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
17611 if (opts.unevaluated) assignEvaluated(it);
17612 gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
17613 }
17614 }
17615 function assignEvaluated({ gen, evaluated, props, items }) {
17616 if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props);
17617 if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items);
17618 }
17619 function schemaKeywords(it, types, typeErrors, errsCount) {
17620 const { gen, schema, data, allErrors, opts, self } = it;
17621 const { RULES } = self;
17622 if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
17623 gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
17624 return;
17625 }
17626 if (!opts.jtd) checkStrictTypes(it, types);
17627 gen.block(() => {
17628 for (const group of RULES.rules) groupKeywords(group);
17629 groupKeywords(RULES.post);
17630 });
17631 function groupKeywords(group) {
17632 if (!(0, applicability_1.shouldUseGroup)(schema, group)) return;
17633 if (group.type) {
17634 gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
17635 iterateKeywords(it, group);
17636 if (types.length === 1 && types[0] === group.type && typeErrors) {
17637 gen.else();
17638 (0, dataType_2.reportTypeError)(it);
17639 }
17640 gen.endIf();
17641 } else iterateKeywords(it, group);
17642 if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
17643 }
17644 }
17645 function iterateKeywords(it, group) {
17646 const { gen, schema, opts: { useDefaults } } = it;
17647 if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type);
17648 gen.block(() => {
17649 for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type);
17650 });
17651 }
17652 function checkStrictTypes(it, types) {
17653 if (it.schemaEnv.meta || !it.opts.strictTypes) return;
17654 checkContextTypes(it, types);
17655 if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types);
17656 checkKeywordTypes(it, it.dataTypes);
17657 }
17658 function checkContextTypes(it, types) {
17659 if (!types.length) return;
17660 if (!it.dataTypes.length) {
17661 it.dataTypes = types;
17662 return;
17663 }
17664 types.forEach((t) => {
17665 if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
17666 });
17667 narrowSchemaTypes(it, types);
17668 }
17669 function checkMultipleTypes(it, ts) {
17670 if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword");
17671 }
17672 function checkKeywordTypes(it, ts) {
17673 const rules = it.self.RULES.all;
17674 for (const keyword in rules) {
17675 const rule = rules[keyword];
17676 if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
17677 const { type } = rule.definition;
17678 if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
17679 }
17680 }
17681 }
17682 function hasApplicableType(schTs, kwdT) {
17683 return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
17684 }
17685 function includesType(ts, t) {
17686 return ts.includes(t) || t === "integer" && ts.includes("number");
17687 }
17688 function narrowSchemaTypes(it, withTypes) {
17689 const ts = [];
17690 for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t);
17691 else if (withTypes.includes("integer") && t === "number") ts.push("integer");
17692 it.dataTypes = ts;
17693 }
17694 function strictTypesError(it, msg) {
17695 const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
17696 msg += ` at "${schemaPath}" (strictTypes)`;
17697 (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
17698 }
17699 var KeywordCxt = class {
17700 constructor(it, def, keyword) {
17701 (0, keyword_1.validateKeywordUsage)(it, def, keyword);
17702 this.gen = it.gen;
17703 this.allErrors = it.allErrors;
17704 this.keyword = keyword;
17705 this.data = it.data;
17706 this.schema = it.schema[keyword];
17707 this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
17708 this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
17709 this.schemaType = def.schemaType;
17710 this.parentSchema = it.schema;
17711 this.params = {};
17712 this.it = it;
17713 this.def = def;
17714 if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
17715 else {
17716 this.schemaCode = this.schemaValue;
17717 if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
17718 }
17719 if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors);
17720 }
17721 result(condition, successAction, failAction) {
17722 this.failResult((0, codegen_1.not)(condition), successAction, failAction);
17723 }
17724 failResult(condition, successAction, failAction) {
17725 this.gen.if(condition);
17726 if (failAction) failAction();
17727 else this.error();
17728 if (successAction) {
17729 this.gen.else();
17730 successAction();
17731 if (this.allErrors) this.gen.endIf();
17732 } else if (this.allErrors) this.gen.endIf();
17733 else this.gen.else();
17734 }
17735 pass(condition, failAction) {
17736 this.failResult((0, codegen_1.not)(condition), void 0, failAction);
17737 }
17738 fail(condition) {
17739 if (condition === void 0) {
17740 this.error();
17741 if (!this.allErrors) this.gen.if(false);
17742 return;
17743 }
17744 this.gen.if(condition);
17745 this.error();
17746 if (this.allErrors) this.gen.endIf();
17747 else this.gen.else();
17748 }
17749 fail$data(condition) {
17750 if (!this.$data) return this.fail(condition);
17751 const { schemaCode } = this;
17752 this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
17753 }
17754 error(append, errorParams, errorPaths) {
17755 if (errorParams) {
17756 this.setParams(errorParams);
17757 this._error(append, errorPaths);
17758 this.setParams({});
17759 return;
17760 }
17761 this._error(append, errorPaths);
17762 }
17763 _error(append, errorPaths) {
17764 (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
17765 }
17766 $dataError() {
17767 (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
17768 }
17769 reset() {
17770 if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition");
17771 (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
17772 }
17773 ok(cond) {
17774 if (!this.allErrors) this.gen.if(cond);
17775 }
17776 setParams(obj, assign) {
17777 if (assign) Object.assign(this.params, obj);
17778 else this.params = obj;
17779 }
17780 block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
17781 this.gen.block(() => {
17782 this.check$data(valid, $dataValid);
17783 codeBlock();
17784 });
17785 }
17786 check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
17787 if (!this.$data) return;
17788 const { gen, schemaCode, schemaType, def } = this;
17789 gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
17790 if (valid !== codegen_1.nil) gen.assign(valid, true);
17791 if (schemaType.length || def.validateSchema) {
17792 gen.elseIf(this.invalid$data());
17793 this.$dataError();
17794 if (valid !== codegen_1.nil) gen.assign(valid, false);
17795 }
17796 gen.else();
17797 }
17798 invalid$data() {
17799 const { gen, schemaCode, schemaType, def, it } = this;
17800 return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
17801 function wrong$DataType() {
17802 if (schemaType.length) {
17803 /* istanbul ignore if */
17804 if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error");
17805 const st = Array.isArray(schemaType) ? schemaType : [schemaType];
17806 return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
17807 }
17808 return codegen_1.nil;
17809 }
17810 function invalid$DataSchema() {
17811 if (def.validateSchema) {
17812 const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
17813 return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
17814 }
17815 return codegen_1.nil;
17816 }
17817 }
17818 subschema(appl, valid) {
17819 const subschema = (0, subschema_1.getSubschema)(this.it, appl);
17820 (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
17821 (0, subschema_1.extendSubschemaMode)(subschema, appl);
17822 const nextContext = {
17823 ...this.it,
17824 ...subschema,
17825 items: void 0,
17826 props: void 0
17827 };
17828 subschemaCode(nextContext, valid);
17829 return nextContext;
17830 }
17831 mergeEvaluated(schemaCxt, toName) {
17832 const { it, gen } = this;
17833 if (!it.opts.unevaluated) return;
17834 if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
17835 if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
17836 }
17837 mergeValidEvaluated(schemaCxt, valid) {
17838 const { it, gen } = this;
17839 if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
17840 gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
17841 return true;
17842 }
17843 }
17844 };
17845 exports.KeywordCxt = KeywordCxt;
17846 function keywordCode(it, keyword, def, ruleType) {
17847 const cxt = new KeywordCxt(it, def, keyword);
17848 if ("code" in def) def.code(cxt, ruleType);
17849 else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def);
17850 else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def);
17851 else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def);
17852 }
17853 var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
17854 var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
17855 function getData($data, { dataLevel, dataNames, dataPathArr }) {
17856 let jsonPointer;
17857 let data;
17858 if ($data === "") return names_1.default.rootData;
17859 if ($data[0] === "/") {
17860 if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`);
17861 jsonPointer = $data;
17862 data = names_1.default.rootData;
17863 } else {
17864 const matches = RELATIVE_JSON_POINTER.exec($data);
17865 if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`);
17866 const up = +matches[1];
17867 jsonPointer = matches[2];
17868 if (jsonPointer === "#") {
17869 if (up >= dataLevel) throw new Error(errorMsg("property/index", up));
17870 return dataPathArr[dataLevel - up];
17871 }
17872 if (up > dataLevel) throw new Error(errorMsg("data", up));
17873 data = dataNames[dataLevel - up];
17874 if (!jsonPointer) return data;
17875 }
17876 let expr = data;
17877 const segments = jsonPointer.split("/");
17878 for (const segment of segments) if (segment) {
17879 data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
17880 expr = (0, codegen_1._)`${expr} && ${data}`;
17881 }
17882 return expr;
17883 function errorMsg(pointerType, up) {
17884 return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
17885 }
17886 }
17887 exports.getData = getData;
17888 }));
17889
17890 //#endregion
17891 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/validation_error.js
17892 var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => {
17893 Object.defineProperty(exports, "__esModule", { value: true });
17894 var ValidationError = class extends Error {
17895 constructor(errors) {
17896 super("validation failed");
17897 this.errors = errors;
17898 this.ajv = this.validation = true;
17899 }
17900 };
17901 exports.default = ValidationError;
17902 }));
17903
17904 //#endregion
17905 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/ref_error.js
17906 var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => {
17907 Object.defineProperty(exports, "__esModule", { value: true });
17908 var resolve_1 = require_resolve();
17909 var MissingRefError = class extends Error {
17910 constructor(resolver, baseId, ref, msg) {
17911 super(msg || `can't resolve reference ${ref} from id ${baseId}`);
17912 this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
17913 this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
17914 }
17915 };
17916 exports.default = MissingRefError;
17917 }));
17918
17919 //#endregion
17920 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/index.js
17921 var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
17922 Object.defineProperty(exports, "__esModule", { value: true });
17923 exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
17924 var codegen_1 = require_codegen();
17925 var validation_error_1 = require_validation_error();
17926 var names_1 = require_names();
17927 var resolve_1 = require_resolve();
17928 var util_1 = require_util();
17929 var validate_1 = require_validate();
17930 var SchemaEnv = class {
17931 constructor(env) {
17932 var _a;
17933 this.refs = {};
17934 this.dynamicAnchors = {};
17935 let schema;
17936 if (typeof env.schema == "object") schema = env.schema;
17937 this.schema = env.schema;
17938 this.schemaId = env.schemaId;
17939 this.root = env.root || this;
17940 this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
17941 this.schemaPath = env.schemaPath;
17942 this.localRefs = env.localRefs;
17943 this.meta = env.meta;
17944 this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
17945 this.refs = {};
17946 }
17947 };
17948 exports.SchemaEnv = SchemaEnv;
17949 function compileSchema(sch) {
17950 const _sch = getCompilingSchema.call(this, sch);
17951 if (_sch) return _sch;
17952 const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
17953 const { es5, lines } = this.opts.code;
17954 const { ownProperties } = this.opts;
17955 const gen = new codegen_1.CodeGen(this.scope, {
17956 es5,
17957 lines,
17958 ownProperties
17959 });
17960 let _ValidationError;
17961 if (sch.$async) _ValidationError = gen.scopeValue("Error", {
17962 ref: validation_error_1.default,
17963 code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
17964 });
17965 const validateName = gen.scopeName("validate");
17966 sch.validateName = validateName;
17967 const schemaCxt = {
17968 gen,
17969 allErrors: this.opts.allErrors,
17970 data: names_1.default.data,
17971 parentData: names_1.default.parentData,
17972 parentDataProperty: names_1.default.parentDataProperty,
17973 dataNames: [names_1.default.data],
17974 dataPathArr: [codegen_1.nil],
17975 dataLevel: 0,
17976 dataTypes: [],
17977 definedProperties: /* @__PURE__ */ new Set(),
17978 topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? {
17979 ref: sch.schema,
17980 code: (0, codegen_1.stringify)(sch.schema)
17981 } : { ref: sch.schema }),
17982 validateName,
17983 ValidationError: _ValidationError,
17984 schema: sch.schema,
17985 schemaEnv: sch,
17986 rootId,
17987 baseId: sch.baseId || rootId,
17988 schemaPath: codegen_1.nil,
17989 errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
17990 errorPath: (0, codegen_1._)`""`,
17991 opts: this.opts,
17992 self: this
17993 };
17994 let sourceCode;
17995 try {
17996 this._compilations.add(sch);
17997 (0, validate_1.validateFunctionCode)(schemaCxt);
17998 gen.optimize(this.opts.code.optimize);
17999 const validateCode = gen.toString();
18000 sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
18001 if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch);
18002 const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get());
18003 this.scope.value(validateName, { ref: validate });
18004 validate.errors = null;
18005 validate.schema = sch.schema;
18006 validate.schemaEnv = sch;
18007 if (sch.$async) validate.$async = true;
18008 if (this.opts.code.source === true) validate.source = {
18009 validateName,
18010 validateCode,
18011 scopeValues: gen._values
18012 };
18013 if (this.opts.unevaluated) {
18014 const { props, items } = schemaCxt;
18015 validate.evaluated = {
18016 props: props instanceof codegen_1.Name ? void 0 : props,
18017 items: items instanceof codegen_1.Name ? void 0 : items,
18018 dynamicProps: props instanceof codegen_1.Name,
18019 dynamicItems: items instanceof codegen_1.Name
18020 };
18021 if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
18022 }
18023 sch.validate = validate;
18024 return sch;
18025 } catch (e) {
18026 delete sch.validate;
18027 delete sch.validateName;
18028 if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode);
18029 throw e;
18030 } finally {
18031 this._compilations.delete(sch);
18032 }
18033 }
18034 exports.compileSchema = compileSchema;
18035 function resolveRef(root, baseId, ref) {
18036 var _a;
18037 ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
18038 const schOrFunc = root.refs[ref];
18039 if (schOrFunc) return schOrFunc;
18040 let _sch = resolve.call(this, root, ref);
18041 if (_sch === void 0) {
18042 const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
18043 const { schemaId } = this.opts;
18044 if (schema) _sch = new SchemaEnv({
18045 schema,
18046 schemaId,
18047 root,
18048 baseId
18049 });
18050 }
18051 if (_sch === void 0) return;
18052 return root.refs[ref] = inlineOrCompile.call(this, _sch);
18053 }
18054 exports.resolveRef = resolveRef;
18055 function inlineOrCompile(sch) {
18056 if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema;
18057 return sch.validate ? sch : compileSchema.call(this, sch);
18058 }
18059 function getCompilingSchema(schEnv) {
18060 for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch;
18061 }
18062 exports.getCompilingSchema = getCompilingSchema;
18063 function sameSchemaEnv(s1, s2) {
18064 return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
18065 }
18066 function resolve(root, ref) {
18067 let sch;
18068 while (typeof (sch = this.refs[ref]) == "string") ref = sch;
18069 return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
18070 }
18071 function resolveSchema(root, ref) {
18072 const p = this.opts.uriResolver.parse(ref);
18073 const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
18074 let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
18075 if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root);
18076 const id = (0, resolve_1.normalizeId)(refPath);
18077 const schOrRef = this.refs[id] || this.schemas[id];
18078 if (typeof schOrRef == "string") {
18079 const sch = resolveSchema.call(this, root, schOrRef);
18080 if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return;
18081 return getJsonPointer.call(this, p, sch);
18082 }
18083 if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return;
18084 if (!schOrRef.validate) compileSchema.call(this, schOrRef);
18085 if (id === (0, resolve_1.normalizeId)(ref)) {
18086 const { schema } = schOrRef;
18087 const { schemaId } = this.opts;
18088 const schId = schema[schemaId];
18089 if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
18090 return new SchemaEnv({
18091 schema,
18092 schemaId,
18093 root,
18094 baseId
18095 });
18096 }
18097 return getJsonPointer.call(this, p, schOrRef);
18098 }
18099 exports.resolveSchema = resolveSchema;
18100 var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
18101 "properties",
18102 "patternProperties",
18103 "enum",
18104 "dependencies",
18105 "definitions"
18106 ]);
18107 function getJsonPointer(parsedRef, { baseId, schema, root }) {
18108 var _a;
18109 if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return;
18110 for (const part of parsedRef.fragment.slice(1).split("/")) {
18111 if (typeof schema === "boolean") return;
18112 const partSchema = schema[(0, util_1.unescapeFragment)(part)];
18113 if (partSchema === void 0) return;
18114 schema = partSchema;
18115 const schId = typeof schema === "object" && schema[this.opts.schemaId];
18116 if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
18117 }
18118 let env;
18119 if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
18120 const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
18121 env = resolveSchema.call(this, root, $ref);
18122 }
18123 const { schemaId } = this.opts;
18124 env = env || new SchemaEnv({
18125 schema,
18126 schemaId,
18127 root,
18128 baseId
18129 });
18130 if (env.schema !== env.root.schema) return env;
18131 }
18132 }));
18133
18134 //#endregion
18135 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/data.json
18136 var data_exports = /* @__PURE__ */ __exportAll({
18137 $id: () => $id$1,
18138 additionalProperties: () => false,
18139 default: () => data_default,
18140 description: () => description,
18141 properties: () => properties$1,
18142 required: () => required,
18143 type: () => type$1
18144 });
18145 var $id$1, description, type$1, required, properties$1, additionalProperties, data_default;
18146 var init_data = __esmMin((() => {
18147 $id$1 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
18148 description = "Meta-schema for $data reference (JSON AnySchema extension proposal)";
18149 type$1 = "object";
18150 required = ["$data"];
18151 properties$1 = { "$data": {
18152 "type": "string",
18153 "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }]
18154 } };
18155 additionalProperties = false;
18156 data_default = {
18157 $id: $id$1,
18158 description,
18159 type: type$1,
18160 required,
18161 properties: properties$1,
18162 additionalProperties: false
18163 };
18164 }));
18165
18166 //#endregion
18167 //#region node_modules/fast-uri/lib/utils.js
18168 var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
18169 /** @type {(value: string) => boolean} */
18170 var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
18171 /** @type {(value: string) => boolean} */
18172 var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
18173 /**
18174 * @param {Array<string>} input
18175 * @returns {string}
18176 */
18177 function stringArrayToHexStripped(input) {
18178 let acc = "";
18179 let code = 0;
18180 let i = 0;
18181 for (i = 0; i < input.length; i++) {
18182 code = input[i].charCodeAt(0);
18183 if (code === 48) continue;
18184 if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return "";
18185 acc += input[i];
18186 break;
18187 }
18188 for (i += 1; i < input.length; i++) {
18189 code = input[i].charCodeAt(0);
18190 if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return "";
18191 acc += input[i];
18192 }
18193 return acc;
18194 }
18195 /**
18196 * @typedef {Object} GetIPV6Result
18197 * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.
18198 * @property {string} address - The parsed IPv6 address.
18199 * @property {string} [zone] - The zone identifier, if present.
18200 */
18201 /**
18202 * @param {string} value
18203 * @returns {boolean}
18204 */
18205 var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
18206 /**
18207 * @param {Array<string>} buffer
18208 * @returns {boolean}
18209 */
18210 function consumeIsZone(buffer) {
18211 buffer.length = 0;
18212 return true;
18213 }
18214 /**
18215 * @param {Array<string>} buffer
18216 * @param {Array<string>} address
18217 * @param {GetIPV6Result} output
18218 * @returns {boolean}
18219 */
18220 function consumeHextets(buffer, address, output) {
18221 if (buffer.length) {
18222 const hex = stringArrayToHexStripped(buffer);
18223 if (hex !== "") address.push(hex);
18224 else {
18225 output.error = true;
18226 return false;
18227 }
18228 buffer.length = 0;
18229 }
18230 return true;
18231 }
18232 /**
18233 * @param {string} input
18234 * @returns {GetIPV6Result}
18235 */
18236 function getIPV6(input) {
18237 let tokenCount = 0;
18238 const output = {
18239 error: false,
18240 address: "",
18241 zone: ""
18242 };
18243 /** @type {Array<string>} */
18244 const address = [];
18245 /** @type {Array<string>} */
18246 const buffer = [];
18247 let endipv6Encountered = false;
18248 let endIpv6 = false;
18249 let consume = consumeHextets;
18250 for (let i = 0; i < input.length; i++) {
18251 const cursor = input[i];
18252 if (cursor === "[" || cursor === "]") continue;
18253 if (cursor === ":") {
18254 if (endipv6Encountered === true) endIpv6 = true;
18255 if (!consume(buffer, address, output)) break;
18256 if (++tokenCount > 7) {
18257 output.error = true;
18258 break;
18259 }
18260 if (i > 0 && input[i - 1] === ":") endipv6Encountered = true;
18261 address.push(":");
18262 continue;
18263 } else if (cursor === "%") {
18264 if (!consume(buffer, address, output)) break;
18265 consume = consumeIsZone;
18266 } else {
18267 buffer.push(cursor);
18268 continue;
18269 }
18270 }
18271 if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join("");
18272 else if (endIpv6) address.push(buffer.join(""));
18273 else address.push(stringArrayToHexStripped(buffer));
18274 output.address = address.join("");
18275 return output;
18276 }
18277 /**
18278 * @typedef {Object} NormalizeIPv6Result
18279 * @property {string} host - The normalized host.
18280 * @property {string} [escapedHost] - The escaped host.
18281 * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.
18282 */
18283 /**
18284 * @param {string} host
18285 * @returns {NormalizeIPv6Result}
18286 */
18287 function normalizeIPv6(host) {
18288 if (findToken(host, ":") < 2) return {
18289 host,
18290 isIPV6: false
18291 };
18292 const ipv6 = getIPV6(host);
18293 if (!ipv6.error) {
18294 let newHost = ipv6.address;
18295 let escapedHost = ipv6.address;
18296 if (ipv6.zone) {
18297 newHost += "%" + ipv6.zone;
18298 escapedHost += "%25" + ipv6.zone;
18299 }
18300 return {
18301 host: newHost,
18302 isIPV6: true,
18303 escapedHost
18304 };
18305 } else return {
18306 host,
18307 isIPV6: false
18308 };
18309 }
18310 /**
18311 * @param {string} str
18312 * @param {string} token
18313 * @returns {number}
18314 */
18315 function findToken(str, token) {
18316 let ind = 0;
18317 for (let i = 0; i < str.length; i++) if (str[i] === token) ind++;
18318 return ind;
18319 }
18320 /**
18321 * @param {string} path
18322 * @returns {string}
18323 *
18324 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
18325 */
18326 function removeDotSegments(path) {
18327 let input = path;
18328 const output = [];
18329 let nextSlash = -1;
18330 let len = 0;
18331 while (len = input.length) {
18332 if (len === 1) if (input === ".") break;
18333 else if (input === "/") {
18334 output.push("/");
18335 break;
18336 } else {
18337 output.push(input);
18338 break;
18339 }
18340 else if (len === 2) {
18341 if (input[0] === ".") {
18342 if (input[1] === ".") break;
18343 else if (input[1] === "/") {
18344 input = input.slice(2);
18345 continue;
18346 }
18347 } else if (input[0] === "/") {
18348 if (input[1] === "." || input[1] === "/") {
18349 output.push("/");
18350 break;
18351 }
18352 }
18353 } else if (len === 3) {
18354 if (input === "/..") {
18355 if (output.length !== 0) output.pop();
18356 output.push("/");
18357 break;
18358 }
18359 }
18360 if (input[0] === ".") {
18361 if (input[1] === ".") {
18362 if (input[2] === "/") {
18363 input = input.slice(3);
18364 continue;
18365 }
18366 } else if (input[1] === "/") {
18367 input = input.slice(2);
18368 continue;
18369 }
18370 } else if (input[0] === "/") {
18371 if (input[1] === ".") {
18372 if (input[2] === "/") {
18373 input = input.slice(2);
18374 continue;
18375 } else if (input[2] === ".") {
18376 if (input[3] === "/") {
18377 input = input.slice(3);
18378 if (output.length !== 0) output.pop();
18379 continue;
18380 }
18381 }
18382 }
18383 }
18384 if ((nextSlash = input.indexOf("/", 1)) === -1) {
18385 output.push(input);
18386 break;
18387 } else {
18388 output.push(input.slice(0, nextSlash));
18389 input = input.slice(nextSlash);
18390 }
18391 }
18392 return output.join("");
18393 }
18394 /**
18395 * @param {import('../types/index').URIComponent} component
18396 * @param {boolean} esc
18397 * @returns {import('../types/index').URIComponent}
18398 */
18399 function normalizeComponentEncoding(component, esc) {
18400 const func = esc !== true ? escape : unescape;
18401 if (component.scheme !== void 0) component.scheme = func(component.scheme);
18402 if (component.userinfo !== void 0) component.userinfo = func(component.userinfo);
18403 if (component.host !== void 0) component.host = func(component.host);
18404 if (component.path !== void 0) component.path = func(component.path);
18405 if (component.query !== void 0) component.query = func(component.query);
18406 if (component.fragment !== void 0) component.fragment = func(component.fragment);
18407 return component;
18408 }
18409 /**
18410 * @param {import('../types/index').URIComponent} component
18411 * @returns {string|undefined}
18412 */
18413 function recomposeAuthority(component) {
18414 const uriTokens = [];
18415 if (component.userinfo !== void 0) {
18416 uriTokens.push(component.userinfo);
18417 uriTokens.push("@");
18418 }
18419 if (component.host !== void 0) {
18420 let host = unescape(component.host);
18421 if (!isIPv4(host)) {
18422 const ipV6res = normalizeIPv6(host);
18423 if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`;
18424 else host = component.host;
18425 }
18426 uriTokens.push(host);
18427 }
18428 if (typeof component.port === "number" || typeof component.port === "string") {
18429 uriTokens.push(":");
18430 uriTokens.push(String(component.port));
18431 }
18432 return uriTokens.length ? uriTokens.join("") : void 0;
18433 }
18434 module.exports = {
18435 nonSimpleDomain,
18436 recomposeAuthority,
18437 normalizeComponentEncoding,
18438 removeDotSegments,
18439 isIPv4,
18440 isUUID,
18441 normalizeIPv6,
18442 stringArrayToHexStripped
18443 };
18444 }));
18445
18446 //#endregion
18447 //#region node_modules/fast-uri/lib/schemes.js
18448 var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
18449 var { isUUID } = require_utils();
18450 var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
18451 var supportedSchemeNames = [
18452 "http",
18453 "https",
18454 "ws",
18455 "wss",
18456 "urn",
18457 "urn:uuid"
18458 ];
18459 /** @typedef {supportedSchemeNames[number]} SchemeName */
18460 /**
18461 * @param {string} name
18462 * @returns {name is SchemeName}
18463 */
18464 function isValidSchemeName(name) {
18465 return supportedSchemeNames.indexOf(name) !== -1;
18466 }
18467 /**
18468 * @callback SchemeFn
18469 * @param {import('../types/index').URIComponent} component
18470 * @param {import('../types/index').Options} options
18471 * @returns {import('../types/index').URIComponent}
18472 */
18473 /**
18474 * @typedef {Object} SchemeHandler
18475 * @property {SchemeName} scheme - The scheme name.
18476 * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.
18477 * @property {SchemeFn} parse - Function to parse the URI component for this scheme.
18478 * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.
18479 * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.
18480 * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.
18481 * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.
18482 */
18483 /**
18484 * @param {import('../types/index').URIComponent} wsComponent
18485 * @returns {boolean}
18486 */
18487 function wsIsSecure(wsComponent) {
18488 if (wsComponent.secure === true) return true;
18489 else if (wsComponent.secure === false) return false;
18490 else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");
18491 else return false;
18492 }
18493 /** @type {SchemeFn} */
18494 function httpParse(component) {
18495 if (!component.host) component.error = component.error || "HTTP URIs must have a host.";
18496 return component;
18497 }
18498 /** @type {SchemeFn} */
18499 function httpSerialize(component) {
18500 const secure = String(component.scheme).toLowerCase() === "https";
18501 if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0;
18502 if (!component.path) component.path = "/";
18503 return component;
18504 }
18505 /** @type {SchemeFn} */
18506 function wsParse(wsComponent) {
18507 wsComponent.secure = wsIsSecure(wsComponent);
18508 wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");
18509 wsComponent.path = void 0;
18510 wsComponent.query = void 0;
18511 return wsComponent;
18512 }
18513 /** @type {SchemeFn} */
18514 function wsSerialize(wsComponent) {
18515 if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0;
18516 if (typeof wsComponent.secure === "boolean") {
18517 wsComponent.scheme = wsComponent.secure ? "wss" : "ws";
18518 wsComponent.secure = void 0;
18519 }
18520 if (wsComponent.resourceName) {
18521 const [path, query] = wsComponent.resourceName.split("?");
18522 wsComponent.path = path && path !== "/" ? path : void 0;
18523 wsComponent.query = query;
18524 wsComponent.resourceName = void 0;
18525 }
18526 wsComponent.fragment = void 0;
18527 return wsComponent;
18528 }
18529 /** @type {SchemeFn} */
18530 function urnParse(urnComponent, options) {
18531 if (!urnComponent.path) {
18532 urnComponent.error = "URN can not be parsed";
18533 return urnComponent;
18534 }
18535 const matches = urnComponent.path.match(URN_REG);
18536 if (matches) {
18537 const scheme = options.scheme || urnComponent.scheme || "urn";
18538 urnComponent.nid = matches[1].toLowerCase();
18539 urnComponent.nss = matches[2];
18540 const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`);
18541 urnComponent.path = void 0;
18542 if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options);
18543 } else urnComponent.error = urnComponent.error || "URN can not be parsed.";
18544 return urnComponent;
18545 }
18546 /** @type {SchemeFn} */
18547 function urnSerialize(urnComponent, options) {
18548 if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized");
18549 const scheme = options.scheme || urnComponent.scheme || "urn";
18550 const nid = urnComponent.nid.toLowerCase();
18551 const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`);
18552 if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options);
18553 const uriComponent = urnComponent;
18554 const nss = urnComponent.nss;
18555 uriComponent.path = `${nid || options.nid}:${nss}`;
18556 options.skipEscape = true;
18557 return uriComponent;
18558 }
18559 /** @type {SchemeFn} */
18560 function urnuuidParse(urnComponent, options) {
18561 const uuidComponent = urnComponent;
18562 uuidComponent.uuid = uuidComponent.nss;
18563 uuidComponent.nss = void 0;
18564 if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid.";
18565 return uuidComponent;
18566 }
18567 /** @type {SchemeFn} */
18568 function urnuuidSerialize(uuidComponent) {
18569 const urnComponent = uuidComponent;
18570 urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();
18571 return urnComponent;
18572 }
18573 var http = {
18574 scheme: "http",
18575 domainHost: true,
18576 parse: httpParse,
18577 serialize: httpSerialize
18578 };
18579 var https = {
18580 scheme: "https",
18581 domainHost: http.domainHost,
18582 parse: httpParse,
18583 serialize: httpSerialize
18584 };
18585 var ws = {
18586 scheme: "ws",
18587 domainHost: true,
18588 parse: wsParse,
18589 serialize: wsSerialize
18590 };
18591 var SCHEMES = {
18592 http,
18593 https,
18594 ws,
18595 wss: {
18596 scheme: "wss",
18597 domainHost: ws.domainHost,
18598 parse: ws.parse,
18599 serialize: ws.serialize
18600 },
18601 urn: {
18602 scheme: "urn",
18603 parse: urnParse,
18604 serialize: urnSerialize,
18605 skipNormalize: true
18606 },
18607 "urn:uuid": {
18608 scheme: "urn:uuid",
18609 parse: urnuuidParse,
18610 serialize: urnuuidSerialize,
18611 skipNormalize: true
18612 }
18613 };
18614 Object.setPrototypeOf(SCHEMES, null);
18615 /**
18616 * @param {string|undefined} scheme
18617 * @returns {SchemeHandler|undefined}
18618 */
18619 function getSchemeHandler(scheme) {
18620 return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0;
18621 }
18622 module.exports = {
18623 wsIsSecure,
18624 SCHEMES,
18625 isValidSchemeName,
18626 getSchemeHandler
18627 };
18628 }));
18629
18630 //#endregion
18631 //#region node_modules/fast-uri/index.js
18632 var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
18633 var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
18634 var { SCHEMES, getSchemeHandler } = require_schemes();
18635 /**
18636 * @template {import('./types/index').URIComponent|string} T
18637 * @param {T} uri
18638 * @param {import('./types/index').Options} [options]
18639 * @returns {T}
18640 */
18641 function normalize(uri, options) {
18642 if (typeof uri === "string") uri = serialize(parse(uri, options), options);
18643 else if (typeof uri === "object") uri = parse(serialize(uri, options), options);
18644 return uri;
18645 }
18646 /**
18647 * @param {string} baseURI
18648 * @param {string} relativeURI
18649 * @param {import('./types/index').Options} [options]
18650 * @returns {string}
18651 */
18652 function resolve(baseURI, relativeURI, options) {
18653 const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
18654 const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
18655 schemelessOptions.skipEscape = true;
18656 return serialize(resolved, schemelessOptions);
18657 }
18658 /**
18659 * @param {import ('./types/index').URIComponent} base
18660 * @param {import ('./types/index').URIComponent} relative
18661 * @param {import('./types/index').Options} [options]
18662 * @param {boolean} [skipNormalization=false]
18663 * @returns {import ('./types/index').URIComponent}
18664 */
18665 function resolveComponent(base, relative, options, skipNormalization) {
18666 /** @type {import('./types/index').URIComponent} */
18667 const target = {};
18668 if (!skipNormalization) {
18669 base = parse(serialize(base, options), options);
18670 relative = parse(serialize(relative, options), options);
18671 }
18672 options = options || {};
18673 if (!options.tolerant && relative.scheme) {
18674 target.scheme = relative.scheme;
18675 target.userinfo = relative.userinfo;
18676 target.host = relative.host;
18677 target.port = relative.port;
18678 target.path = removeDotSegments(relative.path || "");
18679 target.query = relative.query;
18680 } else {
18681 if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
18682 target.userinfo = relative.userinfo;
18683 target.host = relative.host;
18684 target.port = relative.port;
18685 target.path = removeDotSegments(relative.path || "");
18686 target.query = relative.query;
18687 } else {
18688 if (!relative.path) {
18689 target.path = base.path;
18690 if (relative.query !== void 0) target.query = relative.query;
18691 else target.query = base.query;
18692 } else {
18693 if (relative.path[0] === "/") target.path = removeDotSegments(relative.path);
18694 else {
18695 if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path;
18696 else if (!base.path) target.path = relative.path;
18697 else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
18698 target.path = removeDotSegments(target.path);
18699 }
18700 target.query = relative.query;
18701 }
18702 target.userinfo = base.userinfo;
18703 target.host = base.host;
18704 target.port = base.port;
18705 }
18706 target.scheme = base.scheme;
18707 }
18708 target.fragment = relative.fragment;
18709 return target;
18710 }
18711 /**
18712 * @param {import ('./types/index').URIComponent|string} uriA
18713 * @param {import ('./types/index').URIComponent|string} uriB
18714 * @param {import ('./types/index').Options} options
18715 * @returns {boolean}
18716 */
18717 function equal(uriA, uriB, options) {
18718 if (typeof uriA === "string") {
18719 uriA = unescape(uriA);
18720 uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), {
18721 ...options,
18722 skipEscape: true
18723 });
18724 } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), {
18725 ...options,
18726 skipEscape: true
18727 });
18728 if (typeof uriB === "string") {
18729 uriB = unescape(uriB);
18730 uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), {
18731 ...options,
18732 skipEscape: true
18733 });
18734 } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), {
18735 ...options,
18736 skipEscape: true
18737 });
18738 return uriA.toLowerCase() === uriB.toLowerCase();
18739 }
18740 /**
18741 * @param {Readonly<import('./types/index').URIComponent>} cmpts
18742 * @param {import('./types/index').Options} [opts]
18743 * @returns {string}
18744 */
18745 function serialize(cmpts, opts) {
18746 const component = {
18747 host: cmpts.host,
18748 scheme: cmpts.scheme,
18749 userinfo: cmpts.userinfo,
18750 port: cmpts.port,
18751 path: cmpts.path,
18752 query: cmpts.query,
18753 nid: cmpts.nid,
18754 nss: cmpts.nss,
18755 uuid: cmpts.uuid,
18756 fragment: cmpts.fragment,
18757 reference: cmpts.reference,
18758 resourceName: cmpts.resourceName,
18759 secure: cmpts.secure,
18760 error: ""
18761 };
18762 const options = Object.assign({}, opts);
18763 const uriTokens = [];
18764 const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
18765 if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
18766 if (component.path !== void 0) if (!options.skipEscape) {
18767 component.path = escape(component.path);
18768 if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":");
18769 } else component.path = unescape(component.path);
18770 if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":");
18771 const authority = recomposeAuthority(component);
18772 if (authority !== void 0) {
18773 if (options.reference !== "suffix") uriTokens.push("//");
18774 uriTokens.push(authority);
18775 if (component.path && component.path[0] !== "/") uriTokens.push("/");
18776 }
18777 if (component.path !== void 0) {
18778 let s = component.path;
18779 if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s);
18780 if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2);
18781 uriTokens.push(s);
18782 }
18783 if (component.query !== void 0) uriTokens.push("?", component.query);
18784 if (component.fragment !== void 0) uriTokens.push("#", component.fragment);
18785 return uriTokens.join("");
18786 }
18787 var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
18788 /**
18789 * @param {string} uri
18790 * @param {import('./types/index').Options} [opts]
18791 * @returns
18792 */
18793 function parse(uri, opts) {
18794 const options = Object.assign({}, opts);
18795 /** @type {import('./types/index').URIComponent} */
18796 const parsed = {
18797 scheme: void 0,
18798 userinfo: void 0,
18799 host: "",
18800 port: void 0,
18801 path: "",
18802 query: void 0,
18803 fragment: void 0
18804 };
18805 let isIP = false;
18806 if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri;
18807 else uri = "//" + uri;
18808 const matches = uri.match(URI_PARSE);
18809 if (matches) {
18810 parsed.scheme = matches[1];
18811 parsed.userinfo = matches[3];
18812 parsed.host = matches[4];
18813 parsed.port = parseInt(matches[5], 10);
18814 parsed.path = matches[6] || "";
18815 parsed.query = matches[7];
18816 parsed.fragment = matches[8];
18817 if (isNaN(parsed.port)) parsed.port = matches[5];
18818 if (parsed.host) if (isIPv4(parsed.host) === false) {
18819 const ipv6result = normalizeIPv6(parsed.host);
18820 parsed.host = ipv6result.host.toLowerCase();
18821 isIP = ipv6result.isIPV6;
18822 } else isIP = true;
18823 if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document";
18824 else if (parsed.scheme === void 0) parsed.reference = "relative";
18825 else if (parsed.fragment === void 0) parsed.reference = "absolute";
18826 else parsed.reference = "uri";
18827 if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
18828 const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
18829 if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
18830 if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try {
18831 parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
18832 } catch (e) {
18833 parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
18834 }
18835 }
18836 if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
18837 if (uri.indexOf("%") !== -1) {
18838 if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme);
18839 if (parsed.host !== void 0) parsed.host = unescape(parsed.host);
18840 }
18841 if (parsed.path) parsed.path = escape(unescape(parsed.path));
18842 if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
18843 }
18844 if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options);
18845 } else parsed.error = parsed.error || "URI can not be parsed.";
18846 return parsed;
18847 }
18848 var fastUri = {
18849 SCHEMES,
18850 normalize,
18851 resolve,
18852 resolveComponent,
18853 equal,
18854 serialize,
18855 parse
18856 };
18857 module.exports = fastUri;
18858 module.exports.default = fastUri;
18859 module.exports.fastUri = fastUri;
18860 }));
18861
18862 //#endregion
18863 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/uri.js
18864 var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => {
18865 Object.defineProperty(exports, "__esModule", { value: true });
18866 var uri = require_fast_uri();
18867 uri.code = "require(\"ajv/dist/runtime/uri\").default";
18868 exports.default = uri;
18869 }));
18870
18871 //#endregion
18872 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/core.js
18873 var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
18874 Object.defineProperty(exports, "__esModule", { value: true });
18875 exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
18876 var validate_1 = require_validate();
18877 Object.defineProperty(exports, "KeywordCxt", {
18878 enumerable: true,
18879 get: function() {
18880 return validate_1.KeywordCxt;
18881 }
18882 });
18883 var codegen_1 = require_codegen();
18884 Object.defineProperty(exports, "_", {
18885 enumerable: true,
18886 get: function() {
18887 return codegen_1._;
18888 }
18889 });
18890 Object.defineProperty(exports, "str", {
18891 enumerable: true,
18892 get: function() {
18893 return codegen_1.str;
18894 }
18895 });
18896 Object.defineProperty(exports, "stringify", {
18897 enumerable: true,
18898 get: function() {
18899 return codegen_1.stringify;
18900 }
18901 });
18902 Object.defineProperty(exports, "nil", {
18903 enumerable: true,
18904 get: function() {
18905 return codegen_1.nil;
18906 }
18907 });
18908 Object.defineProperty(exports, "Name", {
18909 enumerable: true,
18910 get: function() {
18911 return codegen_1.Name;
18912 }
18913 });
18914 Object.defineProperty(exports, "CodeGen", {
18915 enumerable: true,
18916 get: function() {
18917 return codegen_1.CodeGen;
18918 }
18919 });
18920 var validation_error_1 = require_validation_error();
18921 var ref_error_1 = require_ref_error();
18922 var rules_1 = require_rules();
18923 var compile_1 = require_compile();
18924 var codegen_2 = require_codegen();
18925 var resolve_1 = require_resolve();
18926 var dataType_1 = require_dataType();
18927 var util_1 = require_util();
18928 var $dataRefSchema = (init_data(), __toCommonJS(data_exports).default);
18929 var uri_1 = require_uri();
18930 var defaultRegExp = (str, flags) => new RegExp(str, flags);
18931 defaultRegExp.code = "new RegExp";
18932 var META_IGNORE_OPTIONS = [
18933 "removeAdditional",
18934 "useDefaults",
18935 "coerceTypes"
18936 ];
18937 var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
18938 "validate",
18939 "serialize",
18940 "parse",
18941 "wrapper",
18942 "root",
18943 "schema",
18944 "keyword",
18945 "pattern",
18946 "formats",
18947 "validate$data",
18948 "func",
18949 "obj",
18950 "Error"
18951 ]);
18952 var removedOptions = {
18953 errorDataPath: "",
18954 format: "`validateFormats: false` can be used instead.",
18955 nullable: "\"nullable\" keyword is supported by default.",
18956 jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
18957 extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
18958 missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
18959 processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
18960 sourceCode: "Use option `code: {source: true}`",
18961 strictDefaults: "It is default now, see option `strict`.",
18962 strictKeywords: "It is default now, see option `strict`.",
18963 uniqueItems: "\"uniqueItems\" keyword is always validated.",
18964 unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
18965 cache: "Map is used as cache, schema object as key.",
18966 serialize: "Map is used as cache, schema object as key.",
18967 ajvErrors: "It is default now."
18968 };
18969 var deprecatedOptions = {
18970 ignoreKeywordsWithRef: "",
18971 jsPropertySyntax: "",
18972 unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default."
18973 };
18974 var MAX_EXPRESSION = 200;
18975 function requiredOptions(o) {
18976 var _a;
18977 var _b;
18978 var _c;
18979 var _d;
18980 var _e;
18981 var _f;
18982 var _g;
18983 var _h;
18984 var _j;
18985 var _k;
18986 var _l;
18987 var _m;
18988 var _o;
18989 var _p;
18990 var _q;
18991 var _r;
18992 var _s;
18993 var _t;
18994 var _u;
18995 var _v;
18996 var _w;
18997 var _x;
18998 var _y;
18999 var _z;
19000 var _0;
19001 const s = o.strict;
19002 const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
19003 const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
19004 const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
19005 const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
19006 return {
19007 strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
19008 strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
19009 strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
19010 strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
19011 strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
19012 code: o.code ? {
19013 ...o.code,
19014 optimize,
19015 regExp
19016 } : {
19017 optimize,
19018 regExp
19019 },
19020 loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
19021 loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
19022 meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
19023 messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
19024 inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
19025 schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
19026 addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
19027 validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
19028 validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
19029 unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
19030 int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
19031 uriResolver
19032 };
19033 }
19034 var Ajv = class {
19035 constructor(opts = {}) {
19036 this.schemas = {};
19037 this.refs = {};
19038 this.formats = {};
19039 this._compilations = /* @__PURE__ */ new Set();
19040 this._loading = {};
19041 this._cache = /* @__PURE__ */ new Map();
19042 opts = this.opts = {
19043 ...opts,
19044 ...requiredOptions(opts)
19045 };
19046 const { es5, lines } = this.opts.code;
19047 this.scope = new codegen_2.ValueScope({
19048 scope: {},
19049 prefixes: EXT_SCOPE_NAMES,
19050 es5,
19051 lines
19052 });
19053 this.logger = getLogger(opts.logger);
19054 const formatOpt = opts.validateFormats;
19055 opts.validateFormats = false;
19056 this.RULES = (0, rules_1.getRules)();
19057 checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
19058 checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
19059 this._metaOpts = getMetaSchemaOptions.call(this);
19060 if (opts.formats) addInitialFormats.call(this);
19061 this._addVocabularies();
19062 this._addDefaultMetaSchema();
19063 if (opts.keywords) addInitialKeywords.call(this, opts.keywords);
19064 if (typeof opts.meta == "object") this.addMetaSchema(opts.meta);
19065 addInitialSchemas.call(this);
19066 opts.validateFormats = formatOpt;
19067 }
19068 _addVocabularies() {
19069 this.addKeyword("$async");
19070 }
19071 _addDefaultMetaSchema() {
19072 const { $data, meta, schemaId } = this.opts;
19073 let _dataRefSchema = $dataRefSchema;
19074 if (schemaId === "id") {
19075 _dataRefSchema = { ...$dataRefSchema };
19076 _dataRefSchema.id = _dataRefSchema.$id;
19077 delete _dataRefSchema.$id;
19078 }
19079 if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
19080 }
19081 defaultMeta() {
19082 const { meta, schemaId } = this.opts;
19083 return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
19084 }
19085 validate(schemaKeyRef, data) {
19086 let v;
19087 if (typeof schemaKeyRef == "string") {
19088 v = this.getSchema(schemaKeyRef);
19089 if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
19090 } else v = this.compile(schemaKeyRef);
19091 const valid = v(data);
19092 if (!("$async" in v)) this.errors = v.errors;
19093 return valid;
19094 }
19095 compile(schema, _meta) {
19096 const sch = this._addSchema(schema, _meta);
19097 return sch.validate || this._compileSchemaEnv(sch);
19098 }
19099 compileAsync(schema, meta) {
19100 if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function");
19101 const { loadSchema } = this.opts;
19102 return runCompileAsync.call(this, schema, meta);
19103 async function runCompileAsync(_schema, _meta) {
19104 await loadMetaSchema.call(this, _schema.$schema);
19105 const sch = this._addSchema(_schema, _meta);
19106 return sch.validate || _compileAsync.call(this, sch);
19107 }
19108 async function loadMetaSchema($ref) {
19109 if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true);
19110 }
19111 async function _compileAsync(sch) {
19112 try {
19113 return this._compileSchemaEnv(sch);
19114 } catch (e) {
19115 if (!(e instanceof ref_error_1.default)) throw e;
19116 checkLoaded.call(this, e);
19117 await loadMissingSchema.call(this, e.missingSchema);
19118 return _compileAsync.call(this, sch);
19119 }
19120 }
19121 function checkLoaded({ missingSchema: ref, missingRef }) {
19122 if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
19123 }
19124 async function loadMissingSchema(ref) {
19125 const _schema = await _loadSchema.call(this, ref);
19126 if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema);
19127 if (!this.refs[ref]) this.addSchema(_schema, ref, meta);
19128 }
19129 async function _loadSchema(ref) {
19130 const p = this._loading[ref];
19131 if (p) return p;
19132 try {
19133 return await (this._loading[ref] = loadSchema(ref));
19134 } finally {
19135 delete this._loading[ref];
19136 }
19137 }
19138 }
19139 addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
19140 if (Array.isArray(schema)) {
19141 for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema);
19142 return this;
19143 }
19144 let id;
19145 if (typeof schema === "object") {
19146 const { schemaId } = this.opts;
19147 id = schema[schemaId];
19148 if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`);
19149 }
19150 key = (0, resolve_1.normalizeId)(key || id);
19151 this._checkUnique(key);
19152 this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
19153 return this;
19154 }
19155 addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
19156 this.addSchema(schema, key, true, _validateSchema);
19157 return this;
19158 }
19159 validateSchema(schema, throwOrLogError) {
19160 if (typeof schema == "boolean") return true;
19161 let $schema;
19162 $schema = schema.$schema;
19163 if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string");
19164 $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
19165 if (!$schema) {
19166 this.logger.warn("meta-schema not available");
19167 this.errors = null;
19168 return true;
19169 }
19170 const valid = this.validate($schema, schema);
19171 if (!valid && throwOrLogError) {
19172 const message = "schema is invalid: " + this.errorsText();
19173 if (this.opts.validateSchema === "log") this.logger.error(message);
19174 else throw new Error(message);
19175 }
19176 return valid;
19177 }
19178 getSchema(keyRef) {
19179 let sch;
19180 while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch;
19181 if (sch === void 0) {
19182 const { schemaId } = this.opts;
19183 const root = new compile_1.SchemaEnv({
19184 schema: {},
19185 schemaId
19186 });
19187 sch = compile_1.resolveSchema.call(this, root, keyRef);
19188 if (!sch) return;
19189 this.refs[keyRef] = sch;
19190 }
19191 return sch.validate || this._compileSchemaEnv(sch);
19192 }
19193 removeSchema(schemaKeyRef) {
19194 if (schemaKeyRef instanceof RegExp) {
19195 this._removeAllSchemas(this.schemas, schemaKeyRef);
19196 this._removeAllSchemas(this.refs, schemaKeyRef);
19197 return this;
19198 }
19199 switch (typeof schemaKeyRef) {
19200 case "undefined":
19201 this._removeAllSchemas(this.schemas);
19202 this._removeAllSchemas(this.refs);
19203 this._cache.clear();
19204 return this;
19205 case "string": {
19206 const sch = getSchEnv.call(this, schemaKeyRef);
19207 if (typeof sch == "object") this._cache.delete(sch.schema);
19208 delete this.schemas[schemaKeyRef];
19209 delete this.refs[schemaKeyRef];
19210 return this;
19211 }
19212 case "object": {
19213 const cacheKey = schemaKeyRef;
19214 this._cache.delete(cacheKey);
19215 let id = schemaKeyRef[this.opts.schemaId];
19216 if (id) {
19217 id = (0, resolve_1.normalizeId)(id);
19218 delete this.schemas[id];
19219 delete this.refs[id];
19220 }
19221 return this;
19222 }
19223 default: throw new Error("ajv.removeSchema: invalid parameter");
19224 }
19225 }
19226 addVocabulary(definitions) {
19227 for (const def of definitions) this.addKeyword(def);
19228 return this;
19229 }
19230 addKeyword(kwdOrDef, def) {
19231 let keyword;
19232 if (typeof kwdOrDef == "string") {
19233 keyword = kwdOrDef;
19234 if (typeof def == "object") {
19235 this.logger.warn("these parameters are deprecated, see docs for addKeyword");
19236 def.keyword = keyword;
19237 }
19238 } else if (typeof kwdOrDef == "object" && def === void 0) {
19239 def = kwdOrDef;
19240 keyword = def.keyword;
19241 if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array");
19242 } else throw new Error("invalid addKeywords parameters");
19243 checkKeyword.call(this, keyword, def);
19244 if (!def) {
19245 (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
19246 return this;
19247 }
19248 keywordMetaschema.call(this, def);
19249 const definition = {
19250 ...def,
19251 type: (0, dataType_1.getJSONTypes)(def.type),
19252 schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
19253 };
19254 (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
19255 return this;
19256 }
19257 getKeyword(keyword) {
19258 const rule = this.RULES.all[keyword];
19259 return typeof rule == "object" ? rule.definition : !!rule;
19260 }
19261 removeKeyword(keyword) {
19262 const { RULES } = this;
19263 delete RULES.keywords[keyword];
19264 delete RULES.all[keyword];
19265 for (const group of RULES.rules) {
19266 const i = group.rules.findIndex((rule) => rule.keyword === keyword);
19267 if (i >= 0) group.rules.splice(i, 1);
19268 }
19269 return this;
19270 }
19271 addFormat(name, format) {
19272 if (typeof format == "string") format = new RegExp(format);
19273 this.formats[name] = format;
19274 return this;
19275 }
19276 errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
19277 if (!errors || errors.length === 0) return "No errors";
19278 return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);
19279 }
19280 $dataMetaSchema(metaSchema, keywordsJsonPointers) {
19281 const rules = this.RULES.all;
19282 metaSchema = JSON.parse(JSON.stringify(metaSchema));
19283 for (const jsonPointer of keywordsJsonPointers) {
19284 const segments = jsonPointer.split("/").slice(1);
19285 let keywords = metaSchema;
19286 for (const seg of segments) keywords = keywords[seg];
19287 for (const key in rules) {
19288 const rule = rules[key];
19289 if (typeof rule != "object") continue;
19290 const { $data } = rule.definition;
19291 const schema = keywords[key];
19292 if ($data && schema) keywords[key] = schemaOrData(schema);
19293 }
19294 }
19295 return metaSchema;
19296 }
19297 _removeAllSchemas(schemas, regex) {
19298 for (const keyRef in schemas) {
19299 const sch = schemas[keyRef];
19300 if (!regex || regex.test(keyRef)) {
19301 if (typeof sch == "string") delete schemas[keyRef];
19302 else if (sch && !sch.meta) {
19303 this._cache.delete(sch.schema);
19304 delete schemas[keyRef];
19305 }
19306 }
19307 }
19308 }
19309 _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
19310 let id;
19311 const { schemaId } = this.opts;
19312 if (typeof schema == "object") id = schema[schemaId];
19313 else if (this.opts.jtd) throw new Error("schema must be object");
19314 else if (typeof schema != "boolean") throw new Error("schema must be object or boolean");
19315 let sch = this._cache.get(schema);
19316 if (sch !== void 0) return sch;
19317 baseId = (0, resolve_1.normalizeId)(id || baseId);
19318 const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
19319 sch = new compile_1.SchemaEnv({
19320 schema,
19321 schemaId,
19322 meta,
19323 baseId,
19324 localRefs
19325 });
19326 this._cache.set(sch.schema, sch);
19327 if (addSchema && !baseId.startsWith("#")) {
19328 if (baseId) this._checkUnique(baseId);
19329 this.refs[baseId] = sch;
19330 }
19331 if (validateSchema) this.validateSchema(schema, true);
19332 return sch;
19333 }
19334 _checkUnique(id) {
19335 if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`);
19336 }
19337 _compileSchemaEnv(sch) {
19338 if (sch.meta) this._compileMetaSchema(sch);
19339 else compile_1.compileSchema.call(this, sch);
19340 /* istanbul ignore if */
19341 if (!sch.validate) throw new Error("ajv implementation error");
19342 return sch.validate;
19343 }
19344 _compileMetaSchema(sch) {
19345 const currentOpts = this.opts;
19346 this.opts = this._metaOpts;
19347 try {
19348 compile_1.compileSchema.call(this, sch);
19349 } finally {
19350 this.opts = currentOpts;
19351 }
19352 }
19353 };
19354 Ajv.ValidationError = validation_error_1.default;
19355 Ajv.MissingRefError = ref_error_1.default;
19356 exports.default = Ajv;
19357 function checkOptions(checkOpts, options, msg, log = "error") {
19358 for (const key in checkOpts) {
19359 const opt = key;
19360 if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
19361 }
19362 }
19363 function getSchEnv(keyRef) {
19364 keyRef = (0, resolve_1.normalizeId)(keyRef);
19365 return this.schemas[keyRef] || this.refs[keyRef];
19366 }
19367 function addInitialSchemas() {
19368 const optsSchemas = this.opts.schemas;
19369 if (!optsSchemas) return;
19370 if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas);
19371 else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key);
19372 }
19373 function addInitialFormats() {
19374 for (const name in this.opts.formats) {
19375 const format = this.opts.formats[name];
19376 if (format) this.addFormat(name, format);
19377 }
19378 }
19379 function addInitialKeywords(defs) {
19380 if (Array.isArray(defs)) {
19381 this.addVocabulary(defs);
19382 return;
19383 }
19384 this.logger.warn("keywords option as map is deprecated, pass array");
19385 for (const keyword in defs) {
19386 const def = defs[keyword];
19387 if (!def.keyword) def.keyword = keyword;
19388 this.addKeyword(def);
19389 }
19390 }
19391 function getMetaSchemaOptions() {
19392 const metaOpts = { ...this.opts };
19393 for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt];
19394 return metaOpts;
19395 }
19396 var noLogs = {
19397 log() {},
19398 warn() {},
19399 error() {}
19400 };
19401 function getLogger(logger) {
19402 if (logger === false) return noLogs;
19403 if (logger === void 0) return console;
19404 if (logger.log && logger.warn && logger.error) return logger;
19405 throw new Error("logger must implement log, warn and error methods");
19406 }
19407 var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
19408 function checkKeyword(keyword, def) {
19409 const { RULES } = this;
19410 (0, util_1.eachItem)(keyword, (kwd) => {
19411 if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`);
19412 if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`);
19413 });
19414 if (!def) return;
19415 if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function");
19416 }
19417 function addRule(keyword, definition, dataType) {
19418 var _a;
19419 const post = definition === null || definition === void 0 ? void 0 : definition.post;
19420 if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\"");
19421 const { RULES } = this;
19422 let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
19423 if (!ruleGroup) {
19424 ruleGroup = {
19425 type: dataType,
19426 rules: []
19427 };
19428 RULES.rules.push(ruleGroup);
19429 }
19430 RULES.keywords[keyword] = true;
19431 if (!definition) return;
19432 const rule = {
19433 keyword,
19434 definition: {
19435 ...definition,
19436 type: (0, dataType_1.getJSONTypes)(definition.type),
19437 schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
19438 }
19439 };
19440 if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before);
19441 else ruleGroup.rules.push(rule);
19442 RULES.all[keyword] = rule;
19443 (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd));
19444 }
19445 function addBeforeRule(ruleGroup, rule, before) {
19446 const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
19447 if (i >= 0) ruleGroup.rules.splice(i, 0, rule);
19448 else {
19449 ruleGroup.rules.push(rule);
19450 this.logger.warn(`rule ${before} is not defined`);
19451 }
19452 }
19453 function keywordMetaschema(def) {
19454 let { metaSchema } = def;
19455 if (metaSchema === void 0) return;
19456 if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema);
19457 def.validateSchema = this.compile(metaSchema, true);
19458 }
19459 var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" };
19460 function schemaOrData(schema) {
19461 return { anyOf: [schema, $dataRef] };
19462 }
19463 }));
19464
19465 //#endregion
19466 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/id.js
19467 var require_id = /* @__PURE__ */ __commonJSMin(((exports) => {
19468 Object.defineProperty(exports, "__esModule", { value: true });
19469 var def = {
19470 keyword: "id",
19471 code() {
19472 throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID");
19473 }
19474 };
19475 exports.default = def;
19476 }));
19477
19478 //#endregion
19479 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/ref.js
19480 var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => {
19481 Object.defineProperty(exports, "__esModule", { value: true });
19482 exports.callRef = exports.getValidate = void 0;
19483 var ref_error_1 = require_ref_error();
19484 var code_1 = require_code();
19485 var codegen_1 = require_codegen();
19486 var names_1 = require_names();
19487 var compile_1 = require_compile();
19488 var util_1 = require_util();
19489 var def = {
19490 keyword: "$ref",
19491 schemaType: "string",
19492 code(cxt) {
19493 const { gen, schema: $ref, it } = cxt;
19494 const { baseId, schemaEnv: env, validateName, opts, self } = it;
19495 const { root } = env;
19496 if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef();
19497 const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
19498 if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
19499 if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv);
19500 return inlineRefSchema(schOrEnv);
19501 function callRootRef() {
19502 if (env === root) return callRef(cxt, validateName, env, env.$async);
19503 const rootName = gen.scopeValue("root", { ref: root });
19504 return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
19505 }
19506 function callValidate(sch) {
19507 callRef(cxt, getValidate(cxt, sch), sch, sch.$async);
19508 }
19509 function inlineRefSchema(sch) {
19510 const schName = gen.scopeValue("schema", opts.code.source === true ? {
19511 ref: sch,
19512 code: (0, codegen_1.stringify)(sch)
19513 } : { ref: sch });
19514 const valid = gen.name("valid");
19515 const schCxt = cxt.subschema({
19516 schema: sch,
19517 dataTypes: [],
19518 schemaPath: codegen_1.nil,
19519 topSchemaRef: schName,
19520 errSchemaPath: $ref
19521 }, valid);
19522 cxt.mergeEvaluated(schCxt);
19523 cxt.ok(valid);
19524 }
19525 }
19526 };
19527 function getValidate(cxt, sch) {
19528 const { gen } = cxt;
19529 return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
19530 }
19531 exports.getValidate = getValidate;
19532 function callRef(cxt, v, sch, $async) {
19533 const { gen, it } = cxt;
19534 const { allErrors, schemaEnv: env, opts } = it;
19535 const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
19536 if ($async) callAsyncRef();
19537 else callSyncRef();
19538 function callAsyncRef() {
19539 if (!env.$async) throw new Error("async schema referenced by sync schema");
19540 const valid = gen.let("valid");
19541 gen.try(() => {
19542 gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
19543 addEvaluatedFrom(v);
19544 if (!allErrors) gen.assign(valid, true);
19545 }, (e) => {
19546 gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
19547 addErrorsFrom(e);
19548 if (!allErrors) gen.assign(valid, false);
19549 });
19550 cxt.ok(valid);
19551 }
19552 function callSyncRef() {
19553 cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
19554 }
19555 function addErrorsFrom(source) {
19556 const errs = (0, codegen_1._)`${source}.errors`;
19557 gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
19558 gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
19559 }
19560 function addEvaluatedFrom(source) {
19561 var _a;
19562 if (!it.opts.unevaluated) return;
19563 const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
19564 if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) {
19565 if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
19566 } else {
19567 const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
19568 it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
19569 }
19570 if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) {
19571 if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
19572 } else {
19573 const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
19574 it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
19575 }
19576 }
19577 }
19578 exports.callRef = callRef;
19579 exports.default = def;
19580 }));
19581
19582 //#endregion
19583 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/index.js
19584 var require_core = /* @__PURE__ */ __commonJSMin(((exports) => {
19585 Object.defineProperty(exports, "__esModule", { value: true });
19586 var id_1 = require_id();
19587 var ref_1 = require_ref();
19588 var core = [
19589 "$schema",
19590 "$id",
19591 "$defs",
19592 "$vocabulary",
19593 { keyword: "$comment" },
19594 "definitions",
19595 id_1.default,
19596 ref_1.default
19597 ];
19598 exports.default = core;
19599 }));
19600
19601 //#endregion
19602 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitNumber.js
19603 var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => {
19604 Object.defineProperty(exports, "__esModule", { value: true });
19605 var codegen_1 = require_codegen();
19606 var ops = codegen_1.operators;
19607 var KWDs = {
19608 maximum: {
19609 okStr: "<=",
19610 ok: ops.LTE,
19611 fail: ops.GT
19612 },
19613 minimum: {
19614 okStr: ">=",
19615 ok: ops.GTE,
19616 fail: ops.LT
19617 },
19618 exclusiveMaximum: {
19619 okStr: "<",
19620 ok: ops.LT,
19621 fail: ops.GTE
19622 },
19623 exclusiveMinimum: {
19624 okStr: ">",
19625 ok: ops.GT,
19626 fail: ops.LTE
19627 }
19628 };
19629 var def = {
19630 keyword: Object.keys(KWDs),
19631 type: "number",
19632 schemaType: "number",
19633 $data: true,
19634 error: {
19635 message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,
19636 params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
19637 },
19638 code(cxt) {
19639 const { keyword, data, schemaCode } = cxt;
19640 cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
19641 }
19642 };
19643 exports.default = def;
19644 }));
19645
19646 //#endregion
19647 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/multipleOf.js
19648 var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => {
19649 Object.defineProperty(exports, "__esModule", { value: true });
19650 var codegen_1 = require_codegen();
19651 var def = {
19652 keyword: "multipleOf",
19653 type: "number",
19654 schemaType: "number",
19655 $data: true,
19656 error: {
19657 message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
19658 params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
19659 },
19660 code(cxt) {
19661 const { gen, data, schemaCode, it } = cxt;
19662 const prec = it.opts.multipleOfPrecision;
19663 const res = gen.let("res");
19664 const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
19665 cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
19666 }
19667 };
19668 exports.default = def;
19669 }));
19670
19671 //#endregion
19672 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/ucs2length.js
19673 var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => {
19674 Object.defineProperty(exports, "__esModule", { value: true });
19675 function ucs2length(str) {
19676 const len = str.length;
19677 let length = 0;
19678 let pos = 0;
19679 let value;
19680 while (pos < len) {
19681 length++;
19682 value = str.charCodeAt(pos++);
19683 if (value >= 55296 && value <= 56319 && pos < len) {
19684 value = str.charCodeAt(pos);
19685 if ((value & 64512) === 56320) pos++;
19686 }
19687 }
19688 return length;
19689 }
19690 exports.default = ucs2length;
19691 ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default";
19692 }));
19693
19694 //#endregion
19695 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitLength.js
19696 var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => {
19697 Object.defineProperty(exports, "__esModule", { value: true });
19698 var codegen_1 = require_codegen();
19699 var util_1 = require_util();
19700 var ucs2length_1 = require_ucs2length();
19701 var def = {
19702 keyword: ["maxLength", "minLength"],
19703 type: "string",
19704 schemaType: "number",
19705 $data: true,
19706 error: {
19707 message({ keyword, schemaCode }) {
19708 const comp = keyword === "maxLength" ? "more" : "fewer";
19709 return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
19710 },
19711 params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
19712 },
19713 code(cxt) {
19714 const { keyword, data, schemaCode, it } = cxt;
19715 const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
19716 const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
19717 cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);
19718 }
19719 };
19720 exports.default = def;
19721 }));
19722
19723 //#endregion
19724 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/pattern.js
19725 var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => {
19726 Object.defineProperty(exports, "__esModule", { value: true });
19727 var code_1 = require_code();
19728 var util_1 = require_util();
19729 var codegen_1 = require_codegen();
19730 var def = {
19731 keyword: "pattern",
19732 type: "string",
19733 schemaType: "string",
19734 $data: true,
19735 error: {
19736 message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
19737 params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
19738 },
19739 code(cxt) {
19740 const { gen, data, $data, schema, schemaCode, it } = cxt;
19741 const u = it.opts.unicodeRegExp ? "u" : "";
19742 if ($data) {
19743 const { regExp } = it.opts.code;
19744 const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
19745 const valid = gen.let("valid");
19746 gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
19747 cxt.fail$data((0, codegen_1._)`!${valid}`);
19748 } else {
19749 const regExp = (0, code_1.usePattern)(cxt, schema);
19750 cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
19751 }
19752 }
19753 };
19754 exports.default = def;
19755 }));
19756
19757 //#endregion
19758 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitProperties.js
19759 var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => {
19760 Object.defineProperty(exports, "__esModule", { value: true });
19761 var codegen_1 = require_codegen();
19762 var def = {
19763 keyword: ["maxProperties", "minProperties"],
19764 type: "object",
19765 schemaType: "number",
19766 $data: true,
19767 error: {
19768 message({ keyword, schemaCode }) {
19769 const comp = keyword === "maxProperties" ? "more" : "fewer";
19770 return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
19771 },
19772 params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
19773 },
19774 code(cxt) {
19775 const { keyword, data, schemaCode } = cxt;
19776 const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
19777 cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
19778 }
19779 };
19780 exports.default = def;
19781 }));
19782
19783 //#endregion
19784 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/required.js
19785 var require_required = /* @__PURE__ */ __commonJSMin(((exports) => {
19786 Object.defineProperty(exports, "__esModule", { value: true });
19787 var code_1 = require_code();
19788 var codegen_1 = require_codegen();
19789 var util_1 = require_util();
19790 var def = {
19791 keyword: "required",
19792 type: "object",
19793 schemaType: "array",
19794 $data: true,
19795 error: {
19796 message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
19797 params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
19798 },
19799 code(cxt) {
19800 const { gen, schema, schemaCode, data, $data, it } = cxt;
19801 const { opts } = it;
19802 if (!$data && schema.length === 0) return;
19803 const useLoop = schema.length >= opts.loopRequired;
19804 if (it.allErrors) allErrorsMode();
19805 else exitOnErrorMode();
19806 if (opts.strictRequired) {
19807 const props = cxt.parentSchema.properties;
19808 const { definedProperties } = cxt.it;
19809 for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
19810 const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`;
19811 (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
19812 }
19813 }
19814 function allErrorsMode() {
19815 if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired);
19816 else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop);
19817 }
19818 function exitOnErrorMode() {
19819 const missing = gen.let("missing");
19820 if (useLoop || $data) {
19821 const valid = gen.let("valid", true);
19822 cxt.block$data(valid, () => loopUntilMissing(missing, valid));
19823 cxt.ok(valid);
19824 } else {
19825 gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
19826 (0, code_1.reportMissingProp)(cxt, missing);
19827 gen.else();
19828 }
19829 }
19830 function loopAllRequired() {
19831 gen.forOf("prop", schemaCode, (prop) => {
19832 cxt.setParams({ missingProperty: prop });
19833 gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
19834 });
19835 }
19836 function loopUntilMissing(missing, valid) {
19837 cxt.setParams({ missingProperty: missing });
19838 gen.forOf(missing, schemaCode, () => {
19839 gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
19840 gen.if((0, codegen_1.not)(valid), () => {
19841 cxt.error();
19842 gen.break();
19843 });
19844 }, codegen_1.nil);
19845 }
19846 }
19847 };
19848 exports.default = def;
19849 }));
19850
19851 //#endregion
19852 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitItems.js
19853 var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => {
19854 Object.defineProperty(exports, "__esModule", { value: true });
19855 var codegen_1 = require_codegen();
19856 var def = {
19857 keyword: ["maxItems", "minItems"],
19858 type: "array",
19859 schemaType: "number",
19860 $data: true,
19861 error: {
19862 message({ keyword, schemaCode }) {
19863 const comp = keyword === "maxItems" ? "more" : "fewer";
19864 return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
19865 },
19866 params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
19867 },
19868 code(cxt) {
19869 const { keyword, data, schemaCode } = cxt;
19870 const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
19871 cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
19872 }
19873 };
19874 exports.default = def;
19875 }));
19876
19877 //#endregion
19878 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/equal.js
19879 var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => {
19880 Object.defineProperty(exports, "__esModule", { value: true });
19881 var equal = require_fast_deep_equal();
19882 equal.code = "require(\"ajv/dist/runtime/equal\").default";
19883 exports.default = equal;
19884 }));
19885
19886 //#endregion
19887 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
19888 var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => {
19889 Object.defineProperty(exports, "__esModule", { value: true });
19890 var dataType_1 = require_dataType();
19891 var codegen_1 = require_codegen();
19892 var util_1 = require_util();
19893 var equal_1 = require_equal();
19894 var def = {
19895 keyword: "uniqueItems",
19896 type: "array",
19897 schemaType: "boolean",
19898 $data: true,
19899 error: {
19900 message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
19901 params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`
19902 },
19903 code(cxt) {
19904 const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
19905 if (!$data && !schema) return;
19906 const valid = gen.let("valid");
19907 const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
19908 cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
19909 cxt.ok(valid);
19910 function validateUniqueItems() {
19911 const i = gen.let("i", (0, codegen_1._)`${data}.length`);
19912 const j = gen.let("j");
19913 cxt.setParams({
19914 i,
19915 j
19916 });
19917 gen.assign(valid, true);
19918 gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
19919 }
19920 function canOptimize() {
19921 return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
19922 }
19923 function loopN(i, j) {
19924 const item = gen.name("item");
19925 const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
19926 const indices = gen.const("indices", (0, codegen_1._)`{}`);
19927 gen.for((0, codegen_1._)`;${i}--;`, () => {
19928 gen.let(item, (0, codegen_1._)`${data}[${i}]`);
19929 gen.if(wrongType, (0, codegen_1._)`continue`);
19930 if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
19931 gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
19932 gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);
19933 cxt.error();
19934 gen.assign(valid, false).break();
19935 }).code((0, codegen_1._)`${indices}[${item}] = ${i}`);
19936 });
19937 }
19938 function loopN2(i, j) {
19939 const eql = (0, util_1.useFunc)(gen, equal_1.default);
19940 const outer = gen.name("outer");
19941 gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
19942 cxt.error();
19943 gen.assign(valid, false).break(outer);
19944 })));
19945 }
19946 }
19947 };
19948 exports.default = def;
19949 }));
19950
19951 //#endregion
19952 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/const.js
19953 var require_const = /* @__PURE__ */ __commonJSMin(((exports) => {
19954 Object.defineProperty(exports, "__esModule", { value: true });
19955 var codegen_1 = require_codegen();
19956 var util_1 = require_util();
19957 var equal_1 = require_equal();
19958 var def = {
19959 keyword: "const",
19960 $data: true,
19961 error: {
19962 message: "must be equal to constant",
19963 params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
19964 },
19965 code(cxt) {
19966 const { gen, data, $data, schemaCode, schema } = cxt;
19967 if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
19968 else cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
19969 }
19970 };
19971 exports.default = def;
19972 }));
19973
19974 //#endregion
19975 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/enum.js
19976 var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => {
19977 Object.defineProperty(exports, "__esModule", { value: true });
19978 var codegen_1 = require_codegen();
19979 var util_1 = require_util();
19980 var equal_1 = require_equal();
19981 var def = {
19982 keyword: "enum",
19983 schemaType: "array",
19984 $data: true,
19985 error: {
19986 message: "must be equal to one of the allowed values",
19987 params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
19988 },
19989 code(cxt) {
19990 const { gen, data, $data, schema, schemaCode, it } = cxt;
19991 if (!$data && schema.length === 0) throw new Error("enum must have non-empty array");
19992 const useLoop = schema.length >= it.opts.loopEnum;
19993 let eql;
19994 const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
19995 let valid;
19996 if (useLoop || $data) {
19997 valid = gen.let("valid");
19998 cxt.block$data(valid, loopEnum);
19999 } else {
20000 /* istanbul ignore if */
20001 if (!Array.isArray(schema)) throw new Error("ajv implementation error");
20002 const vSchema = gen.const("vSchema", schemaCode);
20003 valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
20004 }
20005 cxt.pass(valid);
20006 function loopEnum() {
20007 gen.assign(valid, false);
20008 gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
20009 }
20010 function equalCode(vSchema, i) {
20011 const sch = schema[i];
20012 return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
20013 }
20014 }
20015 };
20016 exports.default = def;
20017 }));
20018
20019 //#endregion
20020 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/index.js
20021 var require_validation = /* @__PURE__ */ __commonJSMin(((exports) => {
20022 Object.defineProperty(exports, "__esModule", { value: true });
20023 var limitNumber_1 = require_limitNumber();
20024 var multipleOf_1 = require_multipleOf();
20025 var limitLength_1 = require_limitLength();
20026 var pattern_1 = require_pattern();
20027 var limitProperties_1 = require_limitProperties();
20028 var required_1 = require_required();
20029 var limitItems_1 = require_limitItems();
20030 var uniqueItems_1 = require_uniqueItems();
20031 var const_1 = require_const();
20032 var enum_1 = require_enum();
20033 var validation = [
20034 limitNumber_1.default,
20035 multipleOf_1.default,
20036 limitLength_1.default,
20037 pattern_1.default,
20038 limitProperties_1.default,
20039 required_1.default,
20040 limitItems_1.default,
20041 uniqueItems_1.default,
20042 {
20043 keyword: "type",
20044 schemaType: ["string", "array"]
20045 },
20046 {
20047 keyword: "nullable",
20048 schemaType: "boolean"
20049 },
20050 const_1.default,
20051 enum_1.default
20052 ];
20053 exports.default = validation;
20054 }));
20055
20056 //#endregion
20057 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
20058 var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => {
20059 Object.defineProperty(exports, "__esModule", { value: true });
20060 exports.validateAdditionalItems = void 0;
20061 var codegen_1 = require_codegen();
20062 var util_1 = require_util();
20063 var def = {
20064 keyword: "additionalItems",
20065 type: "array",
20066 schemaType: ["boolean", "object"],
20067 before: "uniqueItems",
20068 error: {
20069 message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
20070 params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
20071 },
20072 code(cxt) {
20073 const { parentSchema, it } = cxt;
20074 const { items } = parentSchema;
20075 if (!Array.isArray(items)) {
20076 (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas");
20077 return;
20078 }
20079 validateAdditionalItems(cxt, items);
20080 }
20081 };
20082 function validateAdditionalItems(cxt, items) {
20083 const { gen, schema, data, keyword, it } = cxt;
20084 it.items = true;
20085 const len = gen.const("len", (0, codegen_1._)`${data}.length`);
20086 if (schema === false) {
20087 cxt.setParams({ len: items.length });
20088 cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
20089 } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
20090 const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);
20091 gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
20092 cxt.ok(valid);
20093 }
20094 function validateItems(valid) {
20095 gen.forRange("i", items.length, len, (i) => {
20096 cxt.subschema({
20097 keyword,
20098 dataProp: i,
20099 dataPropType: util_1.Type.Num
20100 }, valid);
20101 if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break());
20102 });
20103 }
20104 }
20105 exports.validateAdditionalItems = validateAdditionalItems;
20106 exports.default = def;
20107 }));
20108
20109 //#endregion
20110 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items.js
20111 var require_items = /* @__PURE__ */ __commonJSMin(((exports) => {
20112 Object.defineProperty(exports, "__esModule", { value: true });
20113 exports.validateTuple = void 0;
20114 var codegen_1 = require_codegen();
20115 var util_1 = require_util();
20116 var code_1 = require_code();
20117 var def = {
20118 keyword: "items",
20119 type: "array",
20120 schemaType: [
20121 "object",
20122 "array",
20123 "boolean"
20124 ],
20125 before: "uniqueItems",
20126 code(cxt) {
20127 const { schema, it } = cxt;
20128 if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema);
20129 it.items = true;
20130 if ((0, util_1.alwaysValidSchema)(it, schema)) return;
20131 cxt.ok((0, code_1.validateArray)(cxt));
20132 }
20133 };
20134 function validateTuple(cxt, extraItems, schArr = cxt.schema) {
20135 const { gen, parentSchema, data, keyword, it } = cxt;
20136 checkStrictTuple(parentSchema);
20137 if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
20138 const valid = gen.name("valid");
20139 const len = gen.const("len", (0, codegen_1._)`${data}.length`);
20140 schArr.forEach((sch, i) => {
20141 if ((0, util_1.alwaysValidSchema)(it, sch)) return;
20142 gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
20143 keyword,
20144 schemaProp: i,
20145 dataProp: i
20146 }, valid));
20147 cxt.ok(valid);
20148 });
20149 function checkStrictTuple(sch) {
20150 const { opts, errSchemaPath } = it;
20151 const l = schArr.length;
20152 const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
20153 if (opts.strictTuples && !fullTuple) {
20154 const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
20155 (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
20156 }
20157 }
20158 }
20159 exports.validateTuple = validateTuple;
20160 exports.default = def;
20161 }));
20162
20163 //#endregion
20164 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
20165 var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => {
20166 Object.defineProperty(exports, "__esModule", { value: true });
20167 var items_1 = require_items();
20168 var def = {
20169 keyword: "prefixItems",
20170 type: "array",
20171 schemaType: ["array"],
20172 before: "uniqueItems",
20173 code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
20174 };
20175 exports.default = def;
20176 }));
20177
20178 //#endregion
20179 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items2020.js
20180 var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => {
20181 Object.defineProperty(exports, "__esModule", { value: true });
20182 var codegen_1 = require_codegen();
20183 var util_1 = require_util();
20184 var code_1 = require_code();
20185 var additionalItems_1 = require_additionalItems();
20186 var def = {
20187 keyword: "items",
20188 type: "array",
20189 schemaType: ["object", "boolean"],
20190 before: "uniqueItems",
20191 error: {
20192 message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
20193 params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
20194 },
20195 code(cxt) {
20196 const { schema, parentSchema, it } = cxt;
20197 const { prefixItems } = parentSchema;
20198 it.items = true;
20199 if ((0, util_1.alwaysValidSchema)(it, schema)) return;
20200 if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
20201 else cxt.ok((0, code_1.validateArray)(cxt));
20202 }
20203 };
20204 exports.default = def;
20205 }));
20206
20207 //#endregion
20208 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/contains.js
20209 var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => {
20210 Object.defineProperty(exports, "__esModule", { value: true });
20211 var codegen_1 = require_codegen();
20212 var util_1 = require_util();
20213 var def = {
20214 keyword: "contains",
20215 type: "array",
20216 schemaType: ["object", "boolean"],
20217 before: "uniqueItems",
20218 trackErrors: true,
20219 error: {
20220 message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
20221 params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
20222 },
20223 code(cxt) {
20224 const { gen, schema, parentSchema, data, it } = cxt;
20225 let min;
20226 let max;
20227 const { minContains, maxContains } = parentSchema;
20228 if (it.opts.next) {
20229 min = minContains === void 0 ? 1 : minContains;
20230 max = maxContains;
20231 } else min = 1;
20232 const len = gen.const("len", (0, codegen_1._)`${data}.length`);
20233 cxt.setParams({
20234 min,
20235 max
20236 });
20237 if (max === void 0 && min === 0) {
20238 (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
20239 return;
20240 }
20241 if (max !== void 0 && min > max) {
20242 (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
20243 cxt.fail();
20244 return;
20245 }
20246 if ((0, util_1.alwaysValidSchema)(it, schema)) {
20247 let cond = (0, codegen_1._)`${len} >= ${min}`;
20248 if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
20249 cxt.pass(cond);
20250 return;
20251 }
20252 it.items = true;
20253 const valid = gen.name("valid");
20254 if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break()));
20255 else if (min === 0) {
20256 gen.let(valid, true);
20257 if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);
20258 } else {
20259 gen.let(valid, false);
20260 validateItemsWithCount();
20261 }
20262 cxt.result(valid, () => cxt.reset());
20263 function validateItemsWithCount() {
20264 const schValid = gen.name("_valid");
20265 const count = gen.let("count", 0);
20266 validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
20267 }
20268 function validateItems(_valid, block) {
20269 gen.forRange("i", 0, len, (i) => {
20270 cxt.subschema({
20271 keyword: "contains",
20272 dataProp: i,
20273 dataPropType: util_1.Type.Num,
20274 compositeRule: true
20275 }, _valid);
20276 block();
20277 });
20278 }
20279 function checkLimits(count) {
20280 gen.code((0, codegen_1._)`${count}++`);
20281 if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
20282 else {
20283 gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
20284 if (min === 1) gen.assign(valid, true);
20285 else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
20286 }
20287 }
20288 }
20289 };
20290 exports.default = def;
20291 }));
20292
20293 //#endregion
20294 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
20295 var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => {
20296 Object.defineProperty(exports, "__esModule", { value: true });
20297 exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
20298 var codegen_1 = require_codegen();
20299 var util_1 = require_util();
20300 var code_1 = require_code();
20301 exports.error = {
20302 message: ({ params: { property, depsCount, deps } }) => {
20303 const property_ies = depsCount === 1 ? "property" : "properties";
20304 return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
20305 },
20306 params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
20307 missingProperty: ${missingProperty},
20308 depsCount: ${depsCount},
20309 deps: ${deps}}`
20310 };
20311 var def = {
20312 keyword: "dependencies",
20313 type: "object",
20314 schemaType: "object",
20315 error: exports.error,
20316 code(cxt) {
20317 const [propDeps, schDeps] = splitDependencies(cxt);
20318 validatePropertyDeps(cxt, propDeps);
20319 validateSchemaDeps(cxt, schDeps);
20320 }
20321 };
20322 function splitDependencies({ schema }) {
20323 const propertyDeps = {};
20324 const schemaDeps = {};
20325 for (const key in schema) {
20326 if (key === "__proto__") continue;
20327 const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
20328 deps[key] = schema[key];
20329 }
20330 return [propertyDeps, schemaDeps];
20331 }
20332 function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
20333 const { gen, data, it } = cxt;
20334 if (Object.keys(propertyDeps).length === 0) return;
20335 const missing = gen.let("missing");
20336 for (const prop in propertyDeps) {
20337 const deps = propertyDeps[prop];
20338 if (deps.length === 0) continue;
20339 const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
20340 cxt.setParams({
20341 property: prop,
20342 depsCount: deps.length,
20343 deps: deps.join(", ")
20344 });
20345 if (it.allErrors) gen.if(hasProperty, () => {
20346 for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp);
20347 });
20348 else {
20349 gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
20350 (0, code_1.reportMissingProp)(cxt, missing);
20351 gen.else();
20352 }
20353 }
20354 }
20355 exports.validatePropertyDeps = validatePropertyDeps;
20356 function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
20357 const { gen, data, keyword, it } = cxt;
20358 const valid = gen.name("valid");
20359 for (const prop in schemaDeps) {
20360 if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue;
20361 gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
20362 const schCxt = cxt.subschema({
20363 keyword,
20364 schemaProp: prop
20365 }, valid);
20366 cxt.mergeValidEvaluated(schCxt, valid);
20367 }, () => gen.var(valid, true));
20368 cxt.ok(valid);
20369 }
20370 }
20371 exports.validateSchemaDeps = validateSchemaDeps;
20372 exports.default = def;
20373 }));
20374
20375 //#endregion
20376 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
20377 var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => {
20378 Object.defineProperty(exports, "__esModule", { value: true });
20379 var codegen_1 = require_codegen();
20380 var util_1 = require_util();
20381 var def = {
20382 keyword: "propertyNames",
20383 type: "object",
20384 schemaType: ["object", "boolean"],
20385 error: {
20386 message: "property name must be valid",
20387 params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
20388 },
20389 code(cxt) {
20390 const { gen, schema, data, it } = cxt;
20391 if ((0, util_1.alwaysValidSchema)(it, schema)) return;
20392 const valid = gen.name("valid");
20393 gen.forIn("key", data, (key) => {
20394 cxt.setParams({ propertyName: key });
20395 cxt.subschema({
20396 keyword: "propertyNames",
20397 data: key,
20398 dataTypes: ["string"],
20399 propertyName: key,
20400 compositeRule: true
20401 }, valid);
20402 gen.if((0, codegen_1.not)(valid), () => {
20403 cxt.error(true);
20404 if (!it.allErrors) gen.break();
20405 });
20406 });
20407 cxt.ok(valid);
20408 }
20409 };
20410 exports.default = def;
20411 }));
20412
20413 //#endregion
20414 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
20415 var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => {
20416 Object.defineProperty(exports, "__esModule", { value: true });
20417 var code_1 = require_code();
20418 var codegen_1 = require_codegen();
20419 var names_1 = require_names();
20420 var util_1 = require_util();
20421 var def = {
20422 keyword: "additionalProperties",
20423 type: ["object"],
20424 schemaType: ["boolean", "object"],
20425 allowUndefined: true,
20426 trackErrors: true,
20427 error: {
20428 message: "must NOT have additional properties",
20429 params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
20430 },
20431 code(cxt) {
20432 const { gen, schema, parentSchema, data, errsCount, it } = cxt;
20433 /* istanbul ignore if */
20434 if (!errsCount) throw new Error("ajv implementation error");
20435 const { allErrors, opts } = it;
20436 it.props = true;
20437 if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return;
20438 const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
20439 const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
20440 checkAdditionalProperties();
20441 cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
20442 function checkAdditionalProperties() {
20443 gen.forIn("key", data, (key) => {
20444 if (!props.length && !patProps.length) additionalPropertyCode(key);
20445 else gen.if(isAdditional(key), () => additionalPropertyCode(key));
20446 });
20447 }
20448 function isAdditional(key) {
20449 let definedProp;
20450 if (props.length > 8) {
20451 const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
20452 definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
20453 } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
20454 else definedProp = codegen_1.nil;
20455 if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
20456 return (0, codegen_1.not)(definedProp);
20457 }
20458 function deleteAdditional(key) {
20459 gen.code((0, codegen_1._)`delete ${data}[${key}]`);
20460 }
20461 function additionalPropertyCode(key) {
20462 if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
20463 deleteAdditional(key);
20464 return;
20465 }
20466 if (schema === false) {
20467 cxt.setParams({ additionalProperty: key });
20468 cxt.error();
20469 if (!allErrors) gen.break();
20470 return;
20471 }
20472 if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
20473 const valid = gen.name("valid");
20474 if (opts.removeAdditional === "failing") {
20475 applyAdditionalSchema(key, valid, false);
20476 gen.if((0, codegen_1.not)(valid), () => {
20477 cxt.reset();
20478 deleteAdditional(key);
20479 });
20480 } else {
20481 applyAdditionalSchema(key, valid);
20482 if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break());
20483 }
20484 }
20485 }
20486 function applyAdditionalSchema(key, valid, errors) {
20487 const subschema = {
20488 keyword: "additionalProperties",
20489 dataProp: key,
20490 dataPropType: util_1.Type.Str
20491 };
20492 if (errors === false) Object.assign(subschema, {
20493 compositeRule: true,
20494 createErrors: false,
20495 allErrors: false
20496 });
20497 cxt.subschema(subschema, valid);
20498 }
20499 }
20500 };
20501 exports.default = def;
20502 }));
20503
20504 //#endregion
20505 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/properties.js
20506 var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => {
20507 Object.defineProperty(exports, "__esModule", { value: true });
20508 var validate_1 = require_validate();
20509 var code_1 = require_code();
20510 var util_1 = require_util();
20511 var additionalProperties_1 = require_additionalProperties();
20512 var def = {
20513 keyword: "properties",
20514 type: "object",
20515 schemaType: "object",
20516 code(cxt) {
20517 const { gen, schema, parentSchema, data, it } = cxt;
20518 if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
20519 const allProps = (0, code_1.allSchemaProperties)(schema);
20520 for (const prop of allProps) it.definedProperties.add(prop);
20521 if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
20522 const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
20523 if (properties.length === 0) return;
20524 const valid = gen.name("valid");
20525 for (const prop of properties) {
20526 if (hasDefault(prop)) applyPropertySchema(prop);
20527 else {
20528 gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
20529 applyPropertySchema(prop);
20530 if (!it.allErrors) gen.else().var(valid, true);
20531 gen.endIf();
20532 }
20533 cxt.it.definedProperties.add(prop);
20534 cxt.ok(valid);
20535 }
20536 function hasDefault(prop) {
20537 return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
20538 }
20539 function applyPropertySchema(prop) {
20540 cxt.subschema({
20541 keyword: "properties",
20542 schemaProp: prop,
20543 dataProp: prop
20544 }, valid);
20545 }
20546 }
20547 };
20548 exports.default = def;
20549 }));
20550
20551 //#endregion
20552 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js
20553 var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => {
20554 Object.defineProperty(exports, "__esModule", { value: true });
20555 var code_1 = require_code();
20556 var codegen_1 = require_codegen();
20557 var util_1 = require_util();
20558 var util_2 = require_util();
20559 var def = {
20560 keyword: "patternProperties",
20561 type: "object",
20562 schemaType: "object",
20563 code(cxt) {
20564 const { gen, schema, data, parentSchema, it } = cxt;
20565 const { opts } = it;
20566 const patterns = (0, code_1.allSchemaProperties)(schema);
20567 const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
20568 if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return;
20569 const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
20570 const valid = gen.name("valid");
20571 if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
20572 const { props } = it;
20573 validatePatternProperties();
20574 function validatePatternProperties() {
20575 for (const pat of patterns) {
20576 if (checkProperties) checkMatchingProperties(pat);
20577 if (it.allErrors) validateProperties(pat);
20578 else {
20579 gen.var(valid, true);
20580 validateProperties(pat);
20581 gen.if(valid);
20582 }
20583 }
20584 }
20585 function checkMatchingProperties(pat) {
20586 for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
20587 }
20588 function validateProperties(pat) {
20589 gen.forIn("key", data, (key) => {
20590 gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
20591 const alwaysValid = alwaysValidPatterns.includes(pat);
20592 if (!alwaysValid) cxt.subschema({
20593 keyword: "patternProperties",
20594 schemaProp: pat,
20595 dataProp: key,
20596 dataPropType: util_2.Type.Str
20597 }, valid);
20598 if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true);
20599 else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break());
20600 });
20601 });
20602 }
20603 }
20604 };
20605 exports.default = def;
20606 }));
20607
20608 //#endregion
20609 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/not.js
20610 var require_not = /* @__PURE__ */ __commonJSMin(((exports) => {
20611 Object.defineProperty(exports, "__esModule", { value: true });
20612 var util_1 = require_util();
20613 var def = {
20614 keyword: "not",
20615 schemaType: ["object", "boolean"],
20616 trackErrors: true,
20617 code(cxt) {
20618 const { gen, schema, it } = cxt;
20619 if ((0, util_1.alwaysValidSchema)(it, schema)) {
20620 cxt.fail();
20621 return;
20622 }
20623 const valid = gen.name("valid");
20624 cxt.subschema({
20625 keyword: "not",
20626 compositeRule: true,
20627 createErrors: false,
20628 allErrors: false
20629 }, valid);
20630 cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
20631 },
20632 error: { message: "must NOT be valid" }
20633 };
20634 exports.default = def;
20635 }));
20636
20637 //#endregion
20638 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/anyOf.js
20639 var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => {
20640 Object.defineProperty(exports, "__esModule", { value: true });
20641 var def = {
20642 keyword: "anyOf",
20643 schemaType: "array",
20644 trackErrors: true,
20645 code: require_code().validateUnion,
20646 error: { message: "must match a schema in anyOf" }
20647 };
20648 exports.default = def;
20649 }));
20650
20651 //#endregion
20652 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/oneOf.js
20653 var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => {
20654 Object.defineProperty(exports, "__esModule", { value: true });
20655 var codegen_1 = require_codegen();
20656 var util_1 = require_util();
20657 var def = {
20658 keyword: "oneOf",
20659 schemaType: "array",
20660 trackErrors: true,
20661 error: {
20662 message: "must match exactly one schema in oneOf",
20663 params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
20664 },
20665 code(cxt) {
20666 const { gen, schema, parentSchema, it } = cxt;
20667 /* istanbul ignore if */
20668 if (!Array.isArray(schema)) throw new Error("ajv implementation error");
20669 if (it.opts.discriminator && parentSchema.discriminator) return;
20670 const schArr = schema;
20671 const valid = gen.let("valid", false);
20672 const passing = gen.let("passing", null);
20673 const schValid = gen.name("_valid");
20674 cxt.setParams({ passing });
20675 gen.block(validateOneOf);
20676 cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
20677 function validateOneOf() {
20678 schArr.forEach((sch, i) => {
20679 let schCxt;
20680 if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true);
20681 else schCxt = cxt.subschema({
20682 keyword: "oneOf",
20683 schemaProp: i,
20684 compositeRule: true
20685 }, schValid);
20686 if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();
20687 gen.if(schValid, () => {
20688 gen.assign(valid, true);
20689 gen.assign(passing, i);
20690 if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name);
20691 });
20692 });
20693 }
20694 }
20695 };
20696 exports.default = def;
20697 }));
20698
20699 //#endregion
20700 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/allOf.js
20701 var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => {
20702 Object.defineProperty(exports, "__esModule", { value: true });
20703 var util_1 = require_util();
20704 var def = {
20705 keyword: "allOf",
20706 schemaType: "array",
20707 code(cxt) {
20708 const { gen, schema, it } = cxt;
20709 /* istanbul ignore if */
20710 if (!Array.isArray(schema)) throw new Error("ajv implementation error");
20711 const valid = gen.name("valid");
20712 schema.forEach((sch, i) => {
20713 if ((0, util_1.alwaysValidSchema)(it, sch)) return;
20714 const schCxt = cxt.subschema({
20715 keyword: "allOf",
20716 schemaProp: i
20717 }, valid);
20718 cxt.ok(valid);
20719 cxt.mergeEvaluated(schCxt);
20720 });
20721 }
20722 };
20723 exports.default = def;
20724 }));
20725
20726 //#endregion
20727 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/if.js
20728 var require_if = /* @__PURE__ */ __commonJSMin(((exports) => {
20729 Object.defineProperty(exports, "__esModule", { value: true });
20730 var codegen_1 = require_codegen();
20731 var util_1 = require_util();
20732 var def = {
20733 keyword: "if",
20734 schemaType: ["object", "boolean"],
20735 trackErrors: true,
20736 error: {
20737 message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
20738 params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
20739 },
20740 code(cxt) {
20741 const { gen, parentSchema, it } = cxt;
20742 if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored");
20743 const hasThen = hasSchema(it, "then");
20744 const hasElse = hasSchema(it, "else");
20745 if (!hasThen && !hasElse) return;
20746 const valid = gen.let("valid", true);
20747 const schValid = gen.name("_valid");
20748 validateIf();
20749 cxt.reset();
20750 if (hasThen && hasElse) {
20751 const ifClause = gen.let("ifClause");
20752 cxt.setParams({ ifClause });
20753 gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
20754 } else if (hasThen) gen.if(schValid, validateClause("then"));
20755 else gen.if((0, codegen_1.not)(schValid), validateClause("else"));
20756 cxt.pass(valid, () => cxt.error(true));
20757 function validateIf() {
20758 const schCxt = cxt.subschema({
20759 keyword: "if",
20760 compositeRule: true,
20761 createErrors: false,
20762 allErrors: false
20763 }, schValid);
20764 cxt.mergeEvaluated(schCxt);
20765 }
20766 function validateClause(keyword, ifClause) {
20767 return () => {
20768 const schCxt = cxt.subschema({ keyword }, schValid);
20769 gen.assign(valid, schValid);
20770 cxt.mergeValidEvaluated(schCxt, valid);
20771 if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
20772 else cxt.setParams({ ifClause: keyword });
20773 };
20774 }
20775 }
20776 };
20777 function hasSchema(it, keyword) {
20778 const schema = it.schema[keyword];
20779 return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
20780 }
20781 exports.default = def;
20782 }));
20783
20784 //#endregion
20785 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/thenElse.js
20786 var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => {
20787 Object.defineProperty(exports, "__esModule", { value: true });
20788 var util_1 = require_util();
20789 var def = {
20790 keyword: ["then", "else"],
20791 schemaType: ["object", "boolean"],
20792 code({ keyword, parentSchema, it }) {
20793 if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
20794 }
20795 };
20796 exports.default = def;
20797 }));
20798
20799 //#endregion
20800 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/index.js
20801 var require_applicator = /* @__PURE__ */ __commonJSMin(((exports) => {
20802 Object.defineProperty(exports, "__esModule", { value: true });
20803 var additionalItems_1 = require_additionalItems();
20804 var prefixItems_1 = require_prefixItems();
20805 var items_1 = require_items();
20806 var items2020_1 = require_items2020();
20807 var contains_1 = require_contains();
20808 var dependencies_1 = require_dependencies();
20809 var propertyNames_1 = require_propertyNames();
20810 var additionalProperties_1 = require_additionalProperties();
20811 var properties_1 = require_properties();
20812 var patternProperties_1 = require_patternProperties();
20813 var not_1 = require_not();
20814 var anyOf_1 = require_anyOf();
20815 var oneOf_1 = require_oneOf();
20816 var allOf_1 = require_allOf();
20817 var if_1 = require_if();
20818 var thenElse_1 = require_thenElse();
20819 function getApplicator(draft2020 = false) {
20820 const applicator = [
20821 not_1.default,
20822 anyOf_1.default,
20823 oneOf_1.default,
20824 allOf_1.default,
20825 if_1.default,
20826 thenElse_1.default,
20827 propertyNames_1.default,
20828 additionalProperties_1.default,
20829 dependencies_1.default,
20830 properties_1.default,
20831 patternProperties_1.default
20832 ];
20833 if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default);
20834 else applicator.push(additionalItems_1.default, items_1.default);
20835 applicator.push(contains_1.default);
20836 return applicator;
20837 }
20838 exports.default = getApplicator;
20839 }));
20840
20841 //#endregion
20842 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/format.js
20843 var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
20844 Object.defineProperty(exports, "__esModule", { value: true });
20845 var codegen_1 = require_codegen();
20846 var def = {
20847 keyword: "format",
20848 type: ["number", "string"],
20849 schemaType: "string",
20850 $data: true,
20851 error: {
20852 message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
20853 params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
20854 },
20855 code(cxt, ruleType) {
20856 const { gen, data, $data, schema, schemaCode, it } = cxt;
20857 const { opts, errSchemaPath, schemaEnv, self } = it;
20858 if (!opts.validateFormats) return;
20859 if ($data) validate$DataFormat();
20860 else validateFormat();
20861 function validate$DataFormat() {
20862 const fmts = gen.scopeValue("formats", {
20863 ref: self.formats,
20864 code: opts.code.formats
20865 });
20866 const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
20867 const fType = gen.let("fType");
20868 const format = gen.let("format");
20869 gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef));
20870 cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
20871 function unknownFmt() {
20872 if (opts.strictSchema === false) return codegen_1.nil;
20873 return (0, codegen_1._)`${schemaCode} && !${format}`;
20874 }
20875 function invalidFmt() {
20876 const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;
20877 const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
20878 return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
20879 }
20880 }
20881 function validateFormat() {
20882 const formatDef = self.formats[schema];
20883 if (!formatDef) {
20884 unknownFormat();
20885 return;
20886 }
20887 if (formatDef === true) return;
20888 const [fmtType, format, fmtRef] = getFormat(formatDef);
20889 if (fmtType === ruleType) cxt.pass(validCondition());
20890 function unknownFormat() {
20891 if (opts.strictSchema === false) {
20892 self.logger.warn(unknownMsg());
20893 return;
20894 }
20895 throw new Error(unknownMsg());
20896 function unknownMsg() {
20897 return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
20898 }
20899 }
20900 function getFormat(fmtDef) {
20901 const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
20902 const fmt = gen.scopeValue("formats", {
20903 key: schema,
20904 ref: fmtDef,
20905 code
20906 });
20907 if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [
20908 fmtDef.type || "string",
20909 fmtDef.validate,
20910 (0, codegen_1._)`${fmt}.validate`
20911 ];
20912 return [
20913 "string",
20914 fmtDef,
20915 fmt
20916 ];
20917 }
20918 function validCondition() {
20919 if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
20920 if (!schemaEnv.$async) throw new Error("async format in sync schema");
20921 return (0, codegen_1._)`await ${fmtRef}(${data})`;
20922 }
20923 return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
20924 }
20925 }
20926 }
20927 };
20928 exports.default = def;
20929 }));
20930
20931 //#endregion
20932 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/index.js
20933 var require_format = /* @__PURE__ */ __commonJSMin(((exports) => {
20934 Object.defineProperty(exports, "__esModule", { value: true });
20935 var format = [require_format$1().default];
20936 exports.default = format;
20937 }));
20938
20939 //#endregion
20940 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/metadata.js
20941 var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => {
20942 Object.defineProperty(exports, "__esModule", { value: true });
20943 exports.contentVocabulary = exports.metadataVocabulary = void 0;
20944 exports.metadataVocabulary = [
20945 "title",
20946 "description",
20947 "default",
20948 "deprecated",
20949 "readOnly",
20950 "writeOnly",
20951 "examples"
20952 ];
20953 exports.contentVocabulary = [
20954 "contentMediaType",
20955 "contentEncoding",
20956 "contentSchema"
20957 ];
20958 }));
20959
20960 //#endregion
20961 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/draft7.js
20962 var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => {
20963 Object.defineProperty(exports, "__esModule", { value: true });
20964 var core_1 = require_core();
20965 var validation_1 = require_validation();
20966 var applicator_1 = require_applicator();
20967 var format_1 = require_format();
20968 var metadata_1 = require_metadata();
20969 var draft7Vocabularies = [
20970 core_1.default,
20971 validation_1.default,
20972 (0, applicator_1.default)(),
20973 format_1.default,
20974 metadata_1.metadataVocabulary,
20975 metadata_1.contentVocabulary
20976 ];
20977 exports.default = draft7Vocabularies;
20978 }));
20979
20980 //#endregion
20981 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/types.js
20982 var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
20983 Object.defineProperty(exports, "__esModule", { value: true });
20984 exports.DiscrError = void 0;
20985 var DiscrError;
20986 (function(DiscrError) {
20987 DiscrError["Tag"] = "tag";
20988 DiscrError["Mapping"] = "mapping";
20989 })(DiscrError || (exports.DiscrError = DiscrError = {}));
20990 }));
20991
20992 //#endregion
20993 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/index.js
20994 var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => {
20995 Object.defineProperty(exports, "__esModule", { value: true });
20996 var codegen_1 = require_codegen();
20997 var types_1 = require_types();
20998 var compile_1 = require_compile();
20999 var ref_error_1 = require_ref_error();
21000 var util_1 = require_util();
21001 var def = {
21002 keyword: "discriminator",
21003 type: "object",
21004 schemaType: "object",
21005 error: {
21006 message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
21007 params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
21008 },
21009 code(cxt) {
21010 const { gen, data, schema, parentSchema, it } = cxt;
21011 const { oneOf } = parentSchema;
21012 if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option");
21013 const tagName = schema.propertyName;
21014 if (typeof tagName != "string") throw new Error("discriminator: requires propertyName");
21015 if (schema.mapping) throw new Error("discriminator: mapping is not supported");
21016 if (!oneOf) throw new Error("discriminator: requires oneOf keyword");
21017 const valid = gen.let("valid", false);
21018 const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
21019 gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, {
21020 discrError: types_1.DiscrError.Tag,
21021 tag,
21022 tagName
21023 }));
21024 cxt.ok(valid);
21025 function validateMapping() {
21026 const mapping = getMapping();
21027 gen.if(false);
21028 for (const tagValue in mapping) {
21029 gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
21030 gen.assign(valid, applyTagSchema(mapping[tagValue]));
21031 }
21032 gen.else();
21033 cxt.error(false, {
21034 discrError: types_1.DiscrError.Mapping,
21035 tag,
21036 tagName
21037 });
21038 gen.endIf();
21039 }
21040 function applyTagSchema(schemaProp) {
21041 const _valid = gen.name("valid");
21042 const schCxt = cxt.subschema({
21043 keyword: "oneOf",
21044 schemaProp
21045 }, _valid);
21046 cxt.mergeEvaluated(schCxt, codegen_1.Name);
21047 return _valid;
21048 }
21049 function getMapping() {
21050 var _a;
21051 const oneOfMapping = {};
21052 const topRequired = hasRequired(parentSchema);
21053 let tagRequired = true;
21054 for (let i = 0; i < oneOf.length; i++) {
21055 let sch = oneOf[i];
21056 if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
21057 const ref = sch.$ref;
21058 sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
21059 if (sch instanceof compile_1.SchemaEnv) sch = sch.schema;
21060 if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
21061 }
21062 const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
21063 if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
21064 tagRequired = tagRequired && (topRequired || hasRequired(sch));
21065 addMappings(propSch, i);
21066 }
21067 if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`);
21068 return oneOfMapping;
21069 function hasRequired({ required }) {
21070 return Array.isArray(required) && required.includes(tagName);
21071 }
21072 function addMappings(sch, i) {
21073 if (sch.const) addMapping(sch.const, i);
21074 else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i);
21075 else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
21076 }
21077 function addMapping(tagValue, i) {
21078 if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`);
21079 oneOfMapping[tagValue] = i;
21080 }
21081 }
21082 }
21083 };
21084 exports.default = def;
21085 }));
21086
21087 //#endregion
21088 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/json-schema-draft-07.json
21089 var json_schema_draft_07_exports = /* @__PURE__ */ __exportAll({
21090 $id: () => $id,
21091 $schema: () => $schema,
21092 default: () => json_schema_draft_07_default,
21093 definitions: () => definitions,
21094 properties: () => properties,
21095 title: () => title,
21096 type: () => type
21097 });
21098 var $schema, $id, title, definitions, type, properties, json_schema_draft_07_default;
21099 var init_json_schema_draft_07 = __esmMin((() => {
21100 $schema = "http://json-schema.org/draft-07/schema#";
21101 $id = "http://json-schema.org/draft-07/schema#";
21102 title = "Core schema meta-schema";
21103 definitions = {
21104 "schemaArray": {
21105 "type": "array",
21106 "minItems": 1,
21107 "items": { "$ref": "#" }
21108 },
21109 "nonNegativeInteger": {
21110 "type": "integer",
21111 "minimum": 0
21112 },
21113 "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] },
21114 "simpleTypes": { "enum": [
21115 "array",
21116 "boolean",
21117 "integer",
21118 "null",
21119 "number",
21120 "object",
21121 "string"
21122 ] },
21123 "stringArray": {
21124 "type": "array",
21125 "items": { "type": "string" },
21126 "uniqueItems": true,
21127 "default": []
21128 }
21129 };
21130 type = ["object", "boolean"];
21131 properties = {
21132 "$id": {
21133 "type": "string",
21134 "format": "uri-reference"
21135 },
21136 "$schema": {
21137 "type": "string",
21138 "format": "uri"
21139 },
21140 "$ref": {
21141 "type": "string",
21142 "format": "uri-reference"
21143 },
21144 "$comment": { "type": "string" },
21145 "title": { "type": "string" },
21146 "description": { "type": "string" },
21147 "default": true,
21148 "readOnly": {
21149 "type": "boolean",
21150 "default": false
21151 },
21152 "examples": {
21153 "type": "array",
21154 "items": true
21155 },
21156 "multipleOf": {
21157 "type": "number",
21158 "exclusiveMinimum": 0
21159 },
21160 "maximum": { "type": "number" },
21161 "exclusiveMaximum": { "type": "number" },
21162 "minimum": { "type": "number" },
21163 "exclusiveMinimum": { "type": "number" },
21164 "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
21165 "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
21166 "pattern": {
21167 "type": "string",
21168 "format": "regex"
21169 },
21170 "additionalItems": { "$ref": "#" },
21171 "items": {
21172 "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }],
21173 "default": true
21174 },
21175 "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
21176 "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
21177 "uniqueItems": {
21178 "type": "boolean",
21179 "default": false
21180 },
21181 "contains": { "$ref": "#" },
21182 "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
21183 "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
21184 "required": { "$ref": "#/definitions/stringArray" },
21185 "additionalProperties": { "$ref": "#" },
21186 "definitions": {
21187 "type": "object",
21188 "additionalProperties": { "$ref": "#" },
21189 "default": {}
21190 },
21191 "properties": {
21192 "type": "object",
21193 "additionalProperties": { "$ref": "#" },
21194 "default": {}
21195 },
21196 "patternProperties": {
21197 "type": "object",
21198 "additionalProperties": { "$ref": "#" },
21199 "propertyNames": { "format": "regex" },
21200 "default": {}
21201 },
21202 "dependencies": {
21203 "type": "object",
21204 "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] }
21205 },
21206 "propertyNames": { "$ref": "#" },
21207 "const": true,
21208 "enum": {
21209 "type": "array",
21210 "items": true,
21211 "minItems": 1,
21212 "uniqueItems": true
21213 },
21214 "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, {
21215 "type": "array",
21216 "items": { "$ref": "#/definitions/simpleTypes" },
21217 "minItems": 1,
21218 "uniqueItems": true
21219 }] },
21220 "format": { "type": "string" },
21221 "contentMediaType": { "type": "string" },
21222 "contentEncoding": { "type": "string" },
21223 "if": { "$ref": "#" },
21224 "then": { "$ref": "#" },
21225 "else": { "$ref": "#" },
21226 "allOf": { "$ref": "#/definitions/schemaArray" },
21227 "anyOf": { "$ref": "#/definitions/schemaArray" },
21228 "oneOf": { "$ref": "#/definitions/schemaArray" },
21229 "not": { "$ref": "#" }
21230 };
21231 json_schema_draft_07_default = {
21232 $schema,
21233 $id,
21234 title,
21235 definitions,
21236 type,
21237 properties,
21238 "default": true
21239 };
21240 }));
21241
21242 //#endregion
21243 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/ajv.js
21244 var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21245 Object.defineProperty(exports, "__esModule", { value: true });
21246 exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
21247 var core_1 = require_core$1();
21248 var draft7_1 = require_draft7();
21249 var discriminator_1 = require_discriminator();
21250 var draft7MetaSchema = (init_json_schema_draft_07(), __toCommonJS(json_schema_draft_07_exports).default);
21251 var META_SUPPORT_DATA = ["/properties"];
21252 var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
21253 var Ajv = class extends core_1.default {
21254 _addVocabularies() {
21255 super._addVocabularies();
21256 draft7_1.default.forEach((v) => this.addVocabulary(v));
21257 if (this.opts.discriminator) this.addKeyword(discriminator_1.default);
21258 }
21259 _addDefaultMetaSchema() {
21260 super._addDefaultMetaSchema();
21261 if (!this.opts.meta) return;
21262 const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
21263 this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
21264 this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
21265 }
21266 defaultMeta() {
21267 return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
21268 }
21269 };
21270 exports.Ajv = Ajv;
21271 module.exports = exports = Ajv;
21272 module.exports.Ajv = Ajv;
21273 Object.defineProperty(exports, "__esModule", { value: true });
21274 exports.default = Ajv;
21275 var validate_1 = require_validate();
21276 Object.defineProperty(exports, "KeywordCxt", {
21277 enumerable: true,
21278 get: function() {
21279 return validate_1.KeywordCxt;
21280 }
21281 });
21282 var codegen_1 = require_codegen();
21283 Object.defineProperty(exports, "_", {
21284 enumerable: true,
21285 get: function() {
21286 return codegen_1._;
21287 }
21288 });
21289 Object.defineProperty(exports, "str", {
21290 enumerable: true,
21291 get: function() {
21292 return codegen_1.str;
21293 }
21294 });
21295 Object.defineProperty(exports, "stringify", {
21296 enumerable: true,
21297 get: function() {
21298 return codegen_1.stringify;
21299 }
21300 });
21301 Object.defineProperty(exports, "nil", {
21302 enumerable: true,
21303 get: function() {
21304 return codegen_1.nil;
21305 }
21306 });
21307 Object.defineProperty(exports, "Name", {
21308 enumerable: true,
21309 get: function() {
21310 return codegen_1.Name;
21311 }
21312 });
21313 Object.defineProperty(exports, "CodeGen", {
21314 enumerable: true,
21315 get: function() {
21316 return codegen_1.CodeGen;
21317 }
21318 });
21319 var validation_error_1 = require_validation_error();
21320 Object.defineProperty(exports, "ValidationError", {
21321 enumerable: true,
21322 get: function() {
21323 return validation_error_1.default;
21324 }
21325 });
21326 var ref_error_1 = require_ref_error();
21327 Object.defineProperty(exports, "MissingRefError", {
21328 enumerable: true,
21329 get: function() {
21330 return ref_error_1.default;
21331 }
21332 });
21333 }));
21334
21335 //#endregion
21336 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv-formats/dist/formats.js
21337 var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
21338 Object.defineProperty(exports, "__esModule", { value: true });
21339 exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
21340 function fmtDef(validate, compare) {
21341 return {
21342 validate,
21343 compare
21344 };
21345 }
21346 exports.fullFormats = {
21347 date: fmtDef(date, compareDate),
21348 time: fmtDef(getTime(true), compareTime),
21349 "date-time": fmtDef(getDateTime(true), compareDateTime),
21350 "iso-time": fmtDef(getTime(), compareIsoTime),
21351 "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
21352 duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
21353 uri,
21354 "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
21355 "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
21356 url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
21357 email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
21358 hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
21359 ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
21360 ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
21361 regex,
21362 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
21363 "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
21364 "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
21365 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
21366 byte,
21367 int32: {
21368 type: "number",
21369 validate: validateInt32
21370 },
21371 int64: {
21372 type: "number",
21373 validate: validateInt64
21374 },
21375 float: {
21376 type: "number",
21377 validate: validateNumber
21378 },
21379 double: {
21380 type: "number",
21381 validate: validateNumber
21382 },
21383 password: true,
21384 binary: true
21385 };
21386 exports.fastFormats = {
21387 ...exports.fullFormats,
21388 date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
21389 time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
21390 "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
21391 "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
21392 "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime),
21393 uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
21394 "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
21395 email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i
21396 };
21397 exports.formatNames = Object.keys(exports.fullFormats);
21398 function isLeapYear(year) {
21399 return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
21400 }
21401 var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
21402 var DAYS = [
21403 0,
21404 31,
21405 28,
21406 31,
21407 30,
21408 31,
21409 30,
21410 31,
21411 31,
21412 30,
21413 31,
21414 30,
21415 31
21416 ];
21417 function date(str) {
21418 const matches = DATE.exec(str);
21419 if (!matches) return false;
21420 const year = +matches[1];
21421 const month = +matches[2];
21422 const day = +matches[3];
21423 return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
21424 }
21425 function compareDate(d1, d2) {
21426 if (!(d1 && d2)) return void 0;
21427 if (d1 > d2) return 1;
21428 if (d1 < d2) return -1;
21429 return 0;
21430 }
21431 var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
21432 function getTime(strictTimeZone) {
21433 return function time(str) {
21434 const matches = TIME.exec(str);
21435 if (!matches) return false;
21436 const hr = +matches[1];
21437 const min = +matches[2];
21438 const sec = +matches[3];
21439 const tz = matches[4];
21440 const tzSign = matches[5] === "-" ? -1 : 1;
21441 const tzH = +(matches[6] || 0);
21442 const tzM = +(matches[7] || 0);
21443 if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false;
21444 if (hr <= 23 && min <= 59 && sec < 60) return true;
21445 const utcMin = min - tzM * tzSign;
21446 const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
21447 return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
21448 };
21449 }
21450 function compareTime(s1, s2) {
21451 if (!(s1 && s2)) return void 0;
21452 const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();
21453 const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf();
21454 if (!(t1 && t2)) return void 0;
21455 return t1 - t2;
21456 }
21457 function compareIsoTime(t1, t2) {
21458 if (!(t1 && t2)) return void 0;
21459 const a1 = TIME.exec(t1);
21460 const a2 = TIME.exec(t2);
21461 if (!(a1 && a2)) return void 0;
21462 t1 = a1[1] + a1[2] + a1[3];
21463 t2 = a2[1] + a2[2] + a2[3];
21464 if (t1 > t2) return 1;
21465 if (t1 < t2) return -1;
21466 return 0;
21467 }
21468 var DATE_TIME_SEPARATOR = /t|\s/i;
21469 function getDateTime(strictTimeZone) {
21470 const time = getTime(strictTimeZone);
21471 return function date_time(str) {
21472 const dateTime = str.split(DATE_TIME_SEPARATOR);
21473 return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);
21474 };
21475 }
21476 function compareDateTime(dt1, dt2) {
21477 if (!(dt1 && dt2)) return void 0;
21478 const d1 = new Date(dt1).valueOf();
21479 const d2 = new Date(dt2).valueOf();
21480 if (!(d1 && d2)) return void 0;
21481 return d1 - d2;
21482 }
21483 function compareIsoDateTime(dt1, dt2) {
21484 if (!(dt1 && dt2)) return void 0;
21485 const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
21486 const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
21487 const res = compareDate(d1, d2);
21488 if (res === void 0) return void 0;
21489 return res || compareTime(t1, t2);
21490 }
21491 var NOT_URI_FRAGMENT = /\/|:/;
21492 var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
21493 function uri(str) {
21494 return NOT_URI_FRAGMENT.test(str) && URI.test(str);
21495 }
21496 var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
21497 function byte(str) {
21498 BYTE.lastIndex = 0;
21499 return BYTE.test(str);
21500 }
21501 var MIN_INT32 = -(2 ** 31);
21502 var MAX_INT32 = 2 ** 31 - 1;
21503 function validateInt32(value) {
21504 return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
21505 }
21506 function validateInt64(value) {
21507 return Number.isInteger(value);
21508 }
21509 function validateNumber() {
21510 return true;
21511 }
21512 var Z_ANCHOR = /[^\\]\\Z/;
21513 function regex(str) {
21514 if (Z_ANCHOR.test(str)) return false;
21515 try {
21516 new RegExp(str);
21517 return true;
21518 } catch (e) {
21519 return false;
21520 }
21521 }
21522 }));
21523
21524 //#endregion
21525 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv-formats/dist/limit.js
21526 var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => {
21527 Object.defineProperty(exports, "__esModule", { value: true });
21528 exports.formatLimitDefinition = void 0;
21529 var ajv_1 = require_ajv();
21530 var codegen_1 = require_codegen();
21531 var ops = codegen_1.operators;
21532 var KWDs = {
21533 formatMaximum: {
21534 okStr: "<=",
21535 ok: ops.LTE,
21536 fail: ops.GT
21537 },
21538 formatMinimum: {
21539 okStr: ">=",
21540 ok: ops.GTE,
21541 fail: ops.LT
21542 },
21543 formatExclusiveMaximum: {
21544 okStr: "<",
21545 ok: ops.LT,
21546 fail: ops.GTE
21547 },
21548 formatExclusiveMinimum: {
21549 okStr: ">",
21550 ok: ops.GT,
21551 fail: ops.LTE
21552 }
21553 };
21554 var error = {
21555 message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,
21556 params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
21557 };
21558 exports.formatLimitDefinition = {
21559 keyword: Object.keys(KWDs),
21560 type: "string",
21561 schemaType: "string",
21562 $data: true,
21563 error,
21564 code(cxt) {
21565 const { gen, data, schemaCode, keyword, it } = cxt;
21566 const { opts, self } = it;
21567 if (!opts.validateFormats) return;
21568 const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format");
21569 if (fCxt.$data) validate$DataFormat();
21570 else validateFormat();
21571 function validate$DataFormat() {
21572 const fmts = gen.scopeValue("formats", {
21573 ref: self.formats,
21574 code: opts.code.formats
21575 });
21576 const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);
21577 cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));
21578 }
21579 function validateFormat() {
21580 const format = fCxt.schema;
21581 const fmtDef = self.formats[format];
21582 if (!fmtDef || fmtDef === true) return;
21583 if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
21584 const fmt = gen.scopeValue("formats", {
21585 key: format,
21586 ref: fmtDef,
21587 code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0
21588 });
21589 cxt.fail$data(compareCode(fmt));
21590 }
21591 function compareCode(fmt) {
21592 return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
21593 }
21594 },
21595 dependencies: ["format"]
21596 };
21597 var formatLimitPlugin = (ajv) => {
21598 ajv.addKeyword(exports.formatLimitDefinition);
21599 return ajv;
21600 };
21601 exports.default = formatLimitPlugin;
21602 }));
21603
21604 //#endregion
21605 //#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv-formats/dist/index.js
21606 var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21607 Object.defineProperty(exports, "__esModule", { value: true });
21608 var formats_1 = require_formats();
21609 var limit_1 = require_limit();
21610 var codegen_1 = require_codegen();
21611 var fullName = new codegen_1.Name("fullFormats");
21612 var fastName = new codegen_1.Name("fastFormats");
21613 var formatsPlugin = (ajv, opts = { keywords: true }) => {
21614 if (Array.isArray(opts)) {
21615 addFormats(ajv, opts, formats_1.fullFormats, fullName);
21616 return ajv;
21617 }
21618 const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
21619 addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName);
21620 if (opts.keywords) (0, limit_1.default)(ajv);
21621 return ajv;
21622 };
21623 formatsPlugin.get = (name, mode = "full") => {
21624 const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name];
21625 if (!f) throw new Error(`Unknown format "${name}"`);
21626 return f;
21627 };
21628 function addFormats(ajv, list, fs, exportName) {
21629 var _a;
21630 var _b;
21631 (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);
21632 for (const f of list) ajv.addFormat(f, fs[f]);
21633 }
21634 module.exports = exports = formatsPlugin;
21635 Object.defineProperty(exports, "__esModule", { value: true });
21636 exports.default = formatsPlugin;
21637 }));
21638
21639 //#endregion
21640 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
21641 var import_ajv = /* @__PURE__ */ __toESM(require_ajv(), 1);
21642 var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1);
21643 function createDefaultAjvInstance() {
21644 const ajv = new import_ajv.default({
21645 strict: false,
21646 validateFormats: true,
21647 validateSchema: false,
21648 allErrors: true
21649 });
21650 (0, import_dist.default)(ajv);
21651 return ajv;
21652 }
21653 /**
21654 * @example
21655 * ```typescript
21656 * // Use with default AJV instance (recommended)
21657 * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
21658 * const validator = new AjvJsonSchemaValidator();
21659 *
21660 * // Use with custom AJV instance
21661 * import { Ajv } from 'ajv';
21662 * const ajv = new Ajv({ strict: true, allErrors: true });
21663 * const validator = new AjvJsonSchemaValidator(ajv);
21664 * ```
21665 */
21666 var AjvJsonSchemaValidator = class {
21667 /**
21668 * Create an AJV validator
21669 *
21670 * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.
21671 *
21672 * @example
21673 * ```typescript
21674 * // Use default configuration (recommended for most cases)
21675 * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
21676 * const validator = new AjvJsonSchemaValidator();
21677 *
21678 * // Or provide custom AJV instance for advanced configuration
21679 * import { Ajv } from 'ajv';
21680 * import addFormats from 'ajv-formats';
21681 *
21682 * const ajv = new Ajv({ validateFormats: true });
21683 * addFormats(ajv);
21684 * const validator = new AjvJsonSchemaValidator(ajv);
21685 * ```
21686 */
21687 constructor(ajv) {
21688 this._ajv = ajv ?? createDefaultAjvInstance();
21689 }
21690 /**
21691 * Create a validator for the given JSON Schema
21692 *
21693 * The validator is compiled once and can be reused multiple times.
21694 * If the schema has an $id, it will be cached by AJV automatically.
21695 *
21696 * @param schema - Standard JSON Schema object
21697 * @returns A validator function that validates input data
21698 */
21699 getValidator(schema) {
21700 const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
21701 return (input) => {
21702 if (ajvValidator(input)) return {
21703 valid: true,
21704 data: input,
21705 errorMessage: void 0
21706 };
21707 else return {
21708 valid: false,
21709 data: void 0,
21710 errorMessage: this._ajv.errorsText(ajvValidator.errors)
21711 };
21712 };
21713 }
21714 };
21715
21716 //#endregion
21717 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
21718 /**
21719 * Experimental server task features for MCP SDK.
21720 * WARNING: These APIs are experimental and may change without notice.
21721 *
21722 * @experimental
21723 */
21724 /**
21725 * Experimental task features for low-level MCP servers.
21726 *
21727 * Access via `server.experimental.tasks`:
21728 * ```typescript
21729 * const stream = server.experimental.tasks.requestStream(request, schema, options);
21730 * ```
21731 *
21732 * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead.
21733 *
21734 * @experimental
21735 */
21736 var ExperimentalServerTasks = class {
21737 constructor(_server) {
21738 this._server = _server;
21739 }
21740 /**
21741 * Sends a request and returns an AsyncGenerator that yields response messages.
21742 * The generator is guaranteed to end with either a 'result' or 'error' message.
21743 *
21744 * This method provides streaming access to request processing, allowing you to
21745 * observe intermediate task status updates for task-augmented requests.
21746 *
21747 * @param request - The request to send
21748 * @param resultSchema - Zod schema for validating the result
21749 * @param options - Optional request options (timeout, signal, task creation params, etc.)
21750 * @returns AsyncGenerator that yields ResponseMessage objects
21751 *
21752 * @experimental
21753 */
21754 requestStream(request, resultSchema, options) {
21755 return this._server.requestStream(request, resultSchema, options);
21756 }
21757 /**
21758 * Sends a sampling request and returns an AsyncGenerator that yields response messages.
21759 * The generator is guaranteed to end with either a 'result' or 'error' message.
21760 *
21761 * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages
21762 * before the final result.
21763 *
21764 * @example
21765 * ```typescript
21766 * const stream = server.experimental.tasks.createMessageStream({
21767 * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
21768 * maxTokens: 100
21769 * }, {
21770 * onprogress: (progress) => {
21771 * // Handle streaming tokens via progress notifications
21772 * console.log('Progress:', progress.message);
21773 * }
21774 * });
21775 *
21776 * for await (const message of stream) {
21777 * switch (message.type) {
21778 * case 'taskCreated':
21779 * console.log('Task created:', message.task.taskId);
21780 * break;
21781 * case 'taskStatus':
21782 * console.log('Task status:', message.task.status);
21783 * break;
21784 * case 'result':
21785 * console.log('Final result:', message.result);
21786 * break;
21787 * case 'error':
21788 * console.error('Error:', message.error);
21789 * break;
21790 * }
21791 * }
21792 * ```
21793 *
21794 * @param params - The sampling request parameters
21795 * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)
21796 * @returns AsyncGenerator that yields ResponseMessage objects
21797 *
21798 * @experimental
21799 */
21800 createMessageStream(params, options) {
21801 const clientCapabilities = this._server.getClientCapabilities();
21802 if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) throw new Error("Client does not support sampling tools capability.");
21803 if (params.messages.length > 0) {
21804 const lastMessage = params.messages[params.messages.length - 1];
21805 const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
21806 const hasToolResults = lastContent.some((c) => c.type === "tool_result");
21807 const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
21808 const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
21809 const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
21810 if (hasToolResults) {
21811 if (lastContent.some((c) => c.type !== "tool_result")) throw new Error("The last message must contain only tool_result content if any is present");
21812 if (!hasPreviousToolUse) throw new Error("tool_result blocks are not matching any tool_use from the previous message");
21813 }
21814 if (hasPreviousToolUse) {
21815 const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
21816 const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
21817 if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
21818 }
21819 }
21820 return this.requestStream({
21821 method: "sampling/createMessage",
21822 params
21823 }, CreateMessageResultSchema, options);
21824 }
21825 /**
21826 * Sends an elicitation request and returns an AsyncGenerator that yields response messages.
21827 * The generator is guaranteed to end with either a 'result' or 'error' message.
21828 *
21829 * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'
21830 * and 'taskStatus' messages before the final result.
21831 *
21832 * @example
21833 * ```typescript
21834 * const stream = server.experimental.tasks.elicitInputStream({
21835 * mode: 'url',
21836 * message: 'Please authenticate',
21837 * elicitationId: 'auth-123',
21838 * url: 'https://example.com/auth'
21839 * }, {
21840 * task: { ttl: 300000 } // Task-augmented for long-running auth flow
21841 * });
21842 *
21843 * for await (const message of stream) {
21844 * switch (message.type) {
21845 * case 'taskCreated':
21846 * console.log('Task created:', message.task.taskId);
21847 * break;
21848 * case 'taskStatus':
21849 * console.log('Task status:', message.task.status);
21850 * break;
21851 * case 'result':
21852 * console.log('User action:', message.result.action);
21853 * break;
21854 * case 'error':
21855 * console.error('Error:', message.error);
21856 * break;
21857 * }
21858 * }
21859 * ```
21860 *
21861 * @param params - The elicitation request parameters
21862 * @param options - Optional request options (timeout, signal, task creation params, etc.)
21863 * @returns AsyncGenerator that yields ResponseMessage objects
21864 *
21865 * @experimental
21866 */
21867 elicitInputStream(params, options) {
21868 const clientCapabilities = this._server.getClientCapabilities();
21869 const mode = params.mode ?? "form";
21870 switch (mode) {
21871 case "url":
21872 if (!clientCapabilities?.elicitation?.url) throw new Error("Client does not support url elicitation.");
21873 break;
21874 case "form":
21875 if (!clientCapabilities?.elicitation?.form) throw new Error("Client does not support form elicitation.");
21876 break;
21877 }
21878 const normalizedParams = mode === "form" && params.mode === void 0 ? {
21879 ...params,
21880 mode: "form"
21881 } : params;
21882 return this.requestStream({
21883 method: "elicitation/create",
21884 params: normalizedParams
21885 }, ElicitResultSchema, options);
21886 }
21887 /**
21888 * Gets the current status of a task.
21889 *
21890 * @param taskId - The task identifier
21891 * @param options - Optional request options
21892 * @returns The task status
21893 *
21894 * @experimental
21895 */
21896 async getTask(taskId, options) {
21897 return this._server.getTask({ taskId }, options);
21898 }
21899 /**
21900 * Retrieves the result of a completed task.
21901 *
21902 * @param taskId - The task identifier
21903 * @param resultSchema - Zod schema for validating the result
21904 * @param options - Optional request options
21905 * @returns The task result
21906 *
21907 * @experimental
21908 */
21909 async getTaskResult(taskId, resultSchema, options) {
21910 return this._server.getTaskResult({ taskId }, resultSchema, options);
21911 }
21912 /**
21913 * Lists tasks with optional pagination.
21914 *
21915 * @param cursor - Optional pagination cursor
21916 * @param options - Optional request options
21917 * @returns List of tasks with optional next cursor
21918 *
21919 * @experimental
21920 */
21921 async listTasks(cursor, options) {
21922 return this._server.listTasks(cursor ? { cursor } : void 0, options);
21923 }
21924 /**
21925 * Cancels a running task.
21926 *
21927 * @param taskId - The task identifier
21928 * @param options - Optional request options
21929 *
21930 * @experimental
21931 */
21932 async cancelTask(taskId, options) {
21933 return this._server.cancelTask({ taskId }, options);
21934 }
21935 };
21936
21937 //#endregion
21938 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
21939 /**
21940 * Experimental task capability assertion helpers.
21941 * WARNING: These APIs are experimental and may change without notice.
21942 *
21943 * @experimental
21944 */
21945 /**
21946 * Asserts that task creation is supported for tools/call.
21947 * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability.
21948 *
21949 * @param requests - The task requests capability object
21950 * @param method - The method being checked
21951 * @param entityName - 'Server' or 'Client' for error messages
21952 * @throws Error if the capability is not supported
21953 *
21954 * @experimental
21955 */
21956 function assertToolsCallTaskCapability(requests, method, entityName) {
21957 if (!requests) throw new Error(`${entityName} does not support task creation (required for ${method})`);
21958 switch (method) {
21959 case "tools/call":
21960 if (!requests.tools?.call) throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
21961 break;
21962 default: break;
21963 }
21964 }
21965 /**
21966 * Asserts that task creation is supported for sampling/createMessage or elicitation/create.
21967 * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability.
21968 *
21969 * @param requests - The task requests capability object
21970 * @param method - The method being checked
21971 * @param entityName - 'Server' or 'Client' for error messages
21972 * @throws Error if the capability is not supported
21973 *
21974 * @experimental
21975 */
21976 function assertClientRequestTaskCapability(requests, method, entityName) {
21977 if (!requests) throw new Error(`${entityName} does not support task creation (required for ${method})`);
21978 switch (method) {
21979 case "sampling/createMessage":
21980 if (!requests.sampling?.createMessage) throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
21981 break;
21982 case "elicitation/create":
21983 if (!requests.elicitation?.create) throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
21984 break;
21985 default: break;
21986 }
21987 }
21988
21989 //#endregion
21990 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
21991 /**
21992 * An MCP server on top of a pluggable transport.
21993 *
21994 * This server will automatically respond to the initialization flow as initiated from the client.
21995 *
21996 * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
21997 *
21998 * ```typescript
21999 * // Custom schemas
22000 * const CustomRequestSchema = RequestSchema.extend({...})
22001 * const CustomNotificationSchema = NotificationSchema.extend({...})
22002 * const CustomResultSchema = ResultSchema.extend({...})
22003 *
22004 * // Type aliases
22005 * type CustomRequest = z.infer<typeof CustomRequestSchema>
22006 * type CustomNotification = z.infer<typeof CustomNotificationSchema>
22007 * type CustomResult = z.infer<typeof CustomResultSchema>
22008 *
22009 * // Create typed server
22010 * const server = new Server<CustomRequest, CustomNotification, CustomResult>({
22011 * name: "CustomServer",
22012 * version: "1.0.0"
22013 * })
22014 * ```
22015 * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases.
22016 */
22017 var Server = class extends Protocol {
22018 /**
22019 * Initializes this server with the given name and version information.
22020 */
22021 constructor(_serverInfo, options) {
22022 super(options);
22023 this._serverInfo = _serverInfo;
22024 this._loggingLevels = /* @__PURE__ */ new Map();
22025 this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));
22026 this.isMessageIgnored = (level, sessionId) => {
22027 const currentLevel = this._loggingLevels.get(sessionId);
22028 return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
22029 };
22030 this._capabilities = options?.capabilities ?? {};
22031 this._instructions = options?.instructions;
22032 this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
22033 this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
22034 this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());
22035 if (this._capabilities.logging) this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {
22036 const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;
22037 const { level } = request.params;
22038 const parseResult = LoggingLevelSchema.safeParse(level);
22039 if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data);
22040 return {};
22041 });
22042 }
22043 /**
22044 * Access experimental features.
22045 *
22046 * WARNING: These APIs are experimental and may change without notice.
22047 *
22048 * @experimental
22049 */
22050 get experimental() {
22051 if (!this._experimental) this._experimental = { tasks: new ExperimentalServerTasks(this) };
22052 return this._experimental;
22053 }
22054 /**
22055 * Registers new capabilities. This can only be called before connecting to a transport.
22056 *
22057 * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
22058 */
22059 registerCapabilities(capabilities) {
22060 if (this.transport) throw new Error("Cannot register capabilities after connecting to transport");
22061 this._capabilities = mergeCapabilities(this._capabilities, capabilities);
22062 }
22063 /**
22064 * Override request handler registration to enforce server-side validation for tools/call.
22065 */
22066 setRequestHandler(requestSchema, handler) {
22067 const methodSchema = getObjectShape(requestSchema)?.method;
22068 if (!methodSchema) throw new Error("Schema is missing a method literal");
22069 let methodValue;
22070 if (isZ4Schema(methodSchema)) {
22071 const v4Schema = methodSchema;
22072 methodValue = (v4Schema._zod?.def)?.value ?? v4Schema.value;
22073 } else {
22074 const v3Schema = methodSchema;
22075 methodValue = v3Schema._def?.value ?? v3Schema.value;
22076 }
22077 if (typeof methodValue !== "string") throw new Error("Schema method literal must be a string");
22078 if (methodValue === "tools/call") {
22079 const wrappedHandler = async (request, extra) => {
22080 const validatedRequest = safeParse(CallToolRequestSchema, request);
22081 if (!validatedRequest.success) {
22082 const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
22083 throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
22084 }
22085 const { params } = validatedRequest.data;
22086 const result = await Promise.resolve(handler(request, extra));
22087 if (params.task) {
22088 const taskValidationResult = safeParse(CreateTaskResultSchema, result);
22089 if (!taskValidationResult.success) {
22090 const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
22091 throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
22092 }
22093 return taskValidationResult.data;
22094 }
22095 const validationResult = safeParse(CallToolResultSchema, result);
22096 if (!validationResult.success) {
22097 const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
22098 throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
22099 }
22100 return validationResult.data;
22101 };
22102 return super.setRequestHandler(requestSchema, wrappedHandler);
22103 }
22104 return super.setRequestHandler(requestSchema, handler);
22105 }
22106 assertCapabilityForMethod(method) {
22107 switch (method) {
22108 case "sampling/createMessage":
22109 if (!this._clientCapabilities?.sampling) throw new Error(`Client does not support sampling (required for ${method})`);
22110 break;
22111 case "elicitation/create":
22112 if (!this._clientCapabilities?.elicitation) throw new Error(`Client does not support elicitation (required for ${method})`);
22113 break;
22114 case "roots/list":
22115 if (!this._clientCapabilities?.roots) throw new Error(`Client does not support listing roots (required for ${method})`);
22116 break;
22117 case "ping": break;
22118 }
22119 }
22120 assertNotificationCapability(method) {
22121 switch (method) {
22122 case "notifications/message":
22123 if (!this._capabilities.logging) throw new Error(`Server does not support logging (required for ${method})`);
22124 break;
22125 case "notifications/resources/updated":
22126 case "notifications/resources/list_changed":
22127 if (!this._capabilities.resources) throw new Error(`Server does not support notifying about resources (required for ${method})`);
22128 break;
22129 case "notifications/tools/list_changed":
22130 if (!this._capabilities.tools) throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
22131 break;
22132 case "notifications/prompts/list_changed":
22133 if (!this._capabilities.prompts) throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
22134 break;
22135 case "notifications/elicitation/complete":
22136 if (!this._clientCapabilities?.elicitation?.url) throw new Error(`Client does not support URL elicitation (required for ${method})`);
22137 break;
22138 case "notifications/cancelled": break;
22139 case "notifications/progress": break;
22140 }
22141 }
22142 assertRequestHandlerCapability(method) {
22143 if (!this._capabilities) return;
22144 switch (method) {
22145 case "completion/complete":
22146 if (!this._capabilities.completions) throw new Error(`Server does not support completions (required for ${method})`);
22147 break;
22148 case "logging/setLevel":
22149 if (!this._capabilities.logging) throw new Error(`Server does not support logging (required for ${method})`);
22150 break;
22151 case "prompts/get":
22152 case "prompts/list":
22153 if (!this._capabilities.prompts) throw new Error(`Server does not support prompts (required for ${method})`);
22154 break;
22155 case "resources/list":
22156 case "resources/templates/list":
22157 case "resources/read":
22158 if (!this._capabilities.resources) throw new Error(`Server does not support resources (required for ${method})`);
22159 break;
22160 case "tools/call":
22161 case "tools/list":
22162 if (!this._capabilities.tools) throw new Error(`Server does not support tools (required for ${method})`);
22163 break;
22164 case "tasks/get":
22165 case "tasks/list":
22166 case "tasks/result":
22167 case "tasks/cancel":
22168 if (!this._capabilities.tasks) throw new Error(`Server does not support tasks capability (required for ${method})`);
22169 break;
22170 case "ping":
22171 case "initialize": break;
22172 }
22173 }
22174 assertTaskCapability(method) {
22175 assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client");
22176 }
22177 assertTaskHandlerCapability(method) {
22178 if (!this._capabilities) return;
22179 assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");
22180 }
22181 async _oninitialize(request) {
22182 const requestedVersion = request.params.protocolVersion;
22183 this._clientCapabilities = request.params.capabilities;
22184 this._clientVersion = request.params.clientInfo;
22185 return {
22186 protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION,
22187 capabilities: this.getCapabilities(),
22188 serverInfo: this._serverInfo,
22189 ...this._instructions && { instructions: this._instructions }
22190 };
22191 }
22192 /**
22193 * After initialization has completed, this will be populated with the client's reported capabilities.
22194 */
22195 getClientCapabilities() {
22196 return this._clientCapabilities;
22197 }
22198 /**
22199 * After initialization has completed, this will be populated with information about the client's name and version.
22200 */
22201 getClientVersion() {
22202 return this._clientVersion;
22203 }
22204 getCapabilities() {
22205 return this._capabilities;
22206 }
22207 async ping() {
22208 return this.request({ method: "ping" }, EmptyResultSchema);
22209 }
22210 async createMessage(params, options) {
22211 if (params.tools || params.toolChoice) {
22212 if (!this._clientCapabilities?.sampling?.tools) throw new Error("Client does not support sampling tools capability.");
22213 }
22214 if (params.messages.length > 0) {
22215 const lastMessage = params.messages[params.messages.length - 1];
22216 const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
22217 const hasToolResults = lastContent.some((c) => c.type === "tool_result");
22218 const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
22219 const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
22220 const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
22221 if (hasToolResults) {
22222 if (lastContent.some((c) => c.type !== "tool_result")) throw new Error("The last message must contain only tool_result content if any is present");
22223 if (!hasPreviousToolUse) throw new Error("tool_result blocks are not matching any tool_use from the previous message");
22224 }
22225 if (hasPreviousToolUse) {
22226 const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
22227 const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
22228 if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
22229 }
22230 }
22231 if (params.tools) return this.request({
22232 method: "sampling/createMessage",
22233 params
22234 }, CreateMessageResultWithToolsSchema, options);
22235 return this.request({
22236 method: "sampling/createMessage",
22237 params
22238 }, CreateMessageResultSchema, options);
22239 }
22240 /**
22241 * Creates an elicitation request for the given parameters.
22242 * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.
22243 * @param params The parameters for the elicitation request.
22244 * @param options Optional request options.
22245 * @returns The result of the elicitation request.
22246 */
22247 async elicitInput(params, options) {
22248 switch (params.mode ?? "form") {
22249 case "url": {
22250 if (!this._clientCapabilities?.elicitation?.url) throw new Error("Client does not support url elicitation.");
22251 const urlParams = params;
22252 return this.request({
22253 method: "elicitation/create",
22254 params: urlParams
22255 }, ElicitResultSchema, options);
22256 }
22257 case "form": {
22258 if (!this._clientCapabilities?.elicitation?.form) throw new Error("Client does not support form elicitation.");
22259 const formParams = params.mode === "form" ? params : {
22260 ...params,
22261 mode: "form"
22262 };
22263 const result = await this.request({
22264 method: "elicitation/create",
22265 params: formParams
22266 }, ElicitResultSchema, options);
22267 if (result.action === "accept" && result.content && formParams.requestedSchema) try {
22268 const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);
22269 if (!validationResult.valid) throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
22270 } catch (error) {
22271 if (error instanceof McpError) throw error;
22272 throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);
22273 }
22274 return result;
22275 }
22276 }
22277 }
22278 /**
22279 * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
22280 * notification for the specified elicitation ID.
22281 *
22282 * @param elicitationId The ID of the elicitation to mark as complete.
22283 * @param options Optional notification options. Useful when the completion notification should be related to a prior request.
22284 * @returns A function that emits the completion notification when awaited.
22285 */
22286 createElicitationCompletionNotifier(elicitationId, options) {
22287 if (!this._clientCapabilities?.elicitation?.url) throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");
22288 return () => this.notification({
22289 method: "notifications/elicitation/complete",
22290 params: { elicitationId }
22291 }, options);
22292 }
22293 async listRoots(params, options) {
22294 return this.request({
22295 method: "roots/list",
22296 params
22297 }, ListRootsResultSchema, options);
22298 }
22299 /**
22300 * Sends a logging message to the client, if connected.
22301 * Note: You only need to send the parameters object, not the entire JSON RPC message
22302 * @see LoggingMessageNotification
22303 * @param params
22304 * @param sessionId optional for stateless and backward compatibility
22305 */
22306 async sendLoggingMessage(params, sessionId) {
22307 if (this._capabilities.logging) {
22308 if (!this.isMessageIgnored(params.level, sessionId)) return this.notification({
22309 method: "notifications/message",
22310 params
22311 });
22312 }
22313 }
22314 async sendResourceUpdated(params) {
22315 return this.notification({
22316 method: "notifications/resources/updated",
22317 params
22318 });
22319 }
22320 async sendResourceListChanged() {
22321 return this.notification({ method: "notifications/resources/list_changed" });
22322 }
22323 async sendToolListChanged() {
22324 return this.notification({ method: "notifications/tools/list_changed" });
22325 }
22326 async sendPromptListChanged() {
22327 return this.notification({ method: "notifications/prompts/list_changed" });
22328 }
22329 };
22330
22331 //#endregion
22332 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js
22333 var COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");
22334 /**
22335 * Checks if a schema is completable (has completion metadata).
22336 */
22337 function isCompletable(schema) {
22338 return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;
22339 }
22340 /**
22341 * Gets the completer callback from a completable schema, if it exists.
22342 */
22343 function getCompleter(schema) {
22344 return schema[COMPLETABLE_SYMBOL]?.complete;
22345 }
22346 var McpZodTypeKind;
22347 (function(McpZodTypeKind) {
22348 McpZodTypeKind["Completable"] = "McpCompletable";
22349 })(McpZodTypeKind || (McpZodTypeKind = {}));
22350
22351 //#endregion
22352 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js
22353 var MAX_TEMPLATE_LENGTH = 1e6;
22354 var MAX_VARIABLE_LENGTH = 1e6;
22355 var MAX_TEMPLATE_EXPRESSIONS = 1e4;
22356 var MAX_REGEX_LENGTH = 1e6;
22357 var UriTemplate = class UriTemplate {
22358 /**
22359 * Returns true if the given string contains any URI template expressions.
22360 * A template expression is a sequence of characters enclosed in curly braces,
22361 * like {foo} or {?bar}.
22362 */
22363 static isTemplate(str) {
22364 return /\{[^}\s]+\}/.test(str);
22365 }
22366 static validateLength(str, max, context) {
22367 if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`);
22368 }
22369 get variableNames() {
22370 return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names);
22371 }
22372 constructor(template) {
22373 UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template");
22374 this.template = template;
22375 this.parts = this.parse(template);
22376 }
22377 toString() {
22378 return this.template;
22379 }
22380 parse(template) {
22381 const parts = [];
22382 let currentText = "";
22383 let i = 0;
22384 let expressionCount = 0;
22385 while (i < template.length) if (template[i] === "{") {
22386 if (currentText) {
22387 parts.push(currentText);
22388 currentText = "";
22389 }
22390 const end = template.indexOf("}", i);
22391 if (end === -1) throw new Error("Unclosed template expression");
22392 expressionCount++;
22393 if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);
22394 const expr = template.slice(i + 1, end);
22395 const operator = this.getOperator(expr);
22396 const exploded = expr.includes("*");
22397 const names = this.getNames(expr);
22398 const name = names[0];
22399 for (const name of names) UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, "Variable name");
22400 parts.push({
22401 name,
22402 operator,
22403 names,
22404 exploded
22405 });
22406 i = end + 1;
22407 } else {
22408 currentText += template[i];
22409 i++;
22410 }
22411 if (currentText) parts.push(currentText);
22412 return parts;
22413 }
22414 getOperator(expr) {
22415 return [
22416 "+",
22417 "#",
22418 ".",
22419 "/",
22420 "?",
22421 "&"
22422 ].find((op) => expr.startsWith(op)) || "";
22423 }
22424 getNames(expr) {
22425 const operator = this.getOperator(expr);
22426 return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0);
22427 }
22428 encodeValue(value, operator) {
22429 UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value");
22430 if (operator === "+" || operator === "#") return encodeURI(value);
22431 return encodeURIComponent(value);
22432 }
22433 expandPart(part, variables) {
22434 if (part.operator === "?" || part.operator === "&") {
22435 const pairs = part.names.map((name) => {
22436 const value = variables[name];
22437 if (value === void 0) return "";
22438 return `${name}=${Array.isArray(value) ? value.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value.toString(), part.operator)}`;
22439 }).filter((pair) => pair.length > 0);
22440 if (pairs.length === 0) return "";
22441 return (part.operator === "?" ? "?" : "&") + pairs.join("&");
22442 }
22443 if (part.names.length > 1) {
22444 const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0);
22445 if (values.length === 0) return "";
22446 return values.map((v) => Array.isArray(v) ? v[0] : v).join(",");
22447 }
22448 const value = variables[part.name];
22449 if (value === void 0) return "";
22450 const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator));
22451 switch (part.operator) {
22452 case "": return encoded.join(",");
22453 case "+": return encoded.join(",");
22454 case "#": return "#" + encoded.join(",");
22455 case ".": return "." + encoded.join(".");
22456 case "/": return "/" + encoded.join("/");
22457 default: return encoded.join(",");
22458 }
22459 }
22460 expand(variables) {
22461 let result = "";
22462 let hasQueryParam = false;
22463 for (const part of this.parts) {
22464 if (typeof part === "string") {
22465 result += part;
22466 continue;
22467 }
22468 const expanded = this.expandPart(part, variables);
22469 if (!expanded) continue;
22470 if ((part.operator === "?" || part.operator === "&") && hasQueryParam) result += expanded.replace("?", "&");
22471 else result += expanded;
22472 if (part.operator === "?" || part.operator === "&") hasQueryParam = true;
22473 }
22474 return result;
22475 }
22476 escapeRegExp(str) {
22477 return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22478 }
22479 partToRegExp(part) {
22480 const patterns = [];
22481 for (const name of part.names) UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, "Variable name");
22482 if (part.operator === "?" || part.operator === "&") {
22483 for (let i = 0; i < part.names.length; i++) {
22484 const name = part.names[i];
22485 const prefix = i === 0 ? "\\" + part.operator : "&";
22486 patterns.push({
22487 pattern: prefix + this.escapeRegExp(name) + "=([^&]+)",
22488 name
22489 });
22490 }
22491 return patterns;
22492 }
22493 let pattern;
22494 const name = part.name;
22495 switch (part.operator) {
22496 case "":
22497 pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)";
22498 break;
22499 case "+":
22500 case "#":
22501 pattern = "(.+)";
22502 break;
22503 case ".":
22504 pattern = "\\.([^/,]+)";
22505 break;
22506 case "/":
22507 pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)");
22508 break;
22509 default: pattern = "([^/]+)";
22510 }
22511 patterns.push({
22512 pattern,
22513 name
22514 });
22515 return patterns;
22516 }
22517 match(uri) {
22518 UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI");
22519 let pattern = "^";
22520 const names = [];
22521 for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part);
22522 else {
22523 const patterns = this.partToRegExp(part);
22524 for (const { pattern: partPattern, name } of patterns) {
22525 pattern += partPattern;
22526 names.push({
22527 name,
22528 exploded: part.exploded
22529 });
22530 }
22531 }
22532 pattern += "$";
22533 UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern");
22534 const regex = new RegExp(pattern);
22535 const match = uri.match(regex);
22536 if (!match) return null;
22537 const result = {};
22538 for (let i = 0; i < names.length; i++) {
22539 const { name, exploded } = names[i];
22540 const value = match[i + 1];
22541 const cleanName = name.replace("*", "");
22542 if (exploded && value.includes(",")) result[cleanName] = value.split(",");
22543 else result[cleanName] = value;
22544 }
22545 return result;
22546 }
22547 };
22548
22549 //#endregion
22550 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js
22551 /**
22552 * Tool name validation utilities according to SEP: Specify Format for Tool Names
22553 *
22554 * Tool names SHOULD be between 1 and 128 characters in length (inclusive).
22555 * Tool names are case-sensitive.
22556 * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits
22557 * (0-9), underscore (_), dash (-), and dot (.).
22558 * Tool names SHOULD NOT contain spaces, commas, or other special characters.
22559 */
22560 /**
22561 * Regular expression for valid tool names according to SEP-986 specification
22562 */
22563 var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
22564 /**
22565 * Validates a tool name according to the SEP specification
22566 * @param name - The tool name to validate
22567 * @returns An object containing validation result and any warnings
22568 */
22569 function validateToolName(name) {
22570 const warnings = [];
22571 if (name.length === 0) return {
22572 isValid: false,
22573 warnings: ["Tool name cannot be empty"]
22574 };
22575 if (name.length > 128) return {
22576 isValid: false,
22577 warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
22578 };
22579 if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues");
22580 if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues");
22581 if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");
22582 if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");
22583 if (!TOOL_NAME_REGEX.test(name)) {
22584 const invalidChars = name.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);
22585 warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");
22586 return {
22587 isValid: false,
22588 warnings
22589 };
22590 }
22591 return {
22592 isValid: true,
22593 warnings
22594 };
22595 }
22596 /**
22597 * Issues warnings for non-conforming tool names
22598 * @param name - The tool name that triggered the warnings
22599 * @param warnings - Array of warning messages
22600 */
22601 function issueToolNameWarning(name, warnings) {
22602 if (warnings.length > 0) {
22603 console.warn(`Tool name validation warning for "${name}":`);
22604 for (const warning of warnings) console.warn(` - ${warning}`);
22605 console.warn("Tool registration will proceed, but this may cause compatibility issues.");
22606 console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");
22607 console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");
22608 }
22609 }
22610 /**
22611 * Validates a tool name and issues warnings for non-conforming names
22612 * @param name - The tool name to validate
22613 * @returns true if the name is valid, false otherwise
22614 */
22615 function validateAndWarnToolName(name) {
22616 const result = validateToolName(name);
22617 issueToolNameWarning(name, result.warnings);
22618 return result.isValid;
22619 }
22620
22621 //#endregion
22622 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js
22623 /**
22624 * Experimental McpServer task features for MCP SDK.
22625 * WARNING: These APIs are experimental and may change without notice.
22626 *
22627 * @experimental
22628 */
22629 /**
22630 * Experimental task features for McpServer.
22631 *
22632 * Access via `server.experimental.tasks`:
22633 * ```typescript
22634 * server.experimental.tasks.registerToolTask('long-running', config, handler);
22635 * ```
22636 *
22637 * @experimental
22638 */
22639 var ExperimentalMcpServerTasks = class {
22640 constructor(_mcpServer) {
22641 this._mcpServer = _mcpServer;
22642 }
22643 registerToolTask(name, config, handler) {
22644 const execution = {
22645 taskSupport: "required",
22646 ...config.execution
22647 };
22648 if (execution.taskSupport === "forbidden") throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);
22649 return this._mcpServer._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler);
22650 }
22651 };
22652
22653 //#endregion
22654 //#region node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
22655 /**
22656 * High-level MCP server that provides a simpler API for working with resources, tools, and prompts.
22657 * For advanced usage (like sending notifications or setting custom request handlers), use the underlying
22658 * Server instance available via the `server` property.
22659 */
22660 var McpServer = class {
22661 constructor(serverInfo, options) {
22662 this._registeredResources = {};
22663 this._registeredResourceTemplates = {};
22664 this._registeredTools = {};
22665 this._registeredPrompts = {};
22666 this._toolHandlersInitialized = false;
22667 this._completionHandlerInitialized = false;
22668 this._resourceHandlersInitialized = false;
22669 this._promptHandlersInitialized = false;
22670 this.server = new Server(serverInfo, options);
22671 }
22672 /**
22673 * Access experimental features.
22674 *
22675 * WARNING: These APIs are experimental and may change without notice.
22676 *
22677 * @experimental
22678 */
22679 get experimental() {
22680 if (!this._experimental) this._experimental = { tasks: new ExperimentalMcpServerTasks(this) };
22681 return this._experimental;
22682 }
22683 /**
22684 * Attaches to the given transport, starts it, and starts listening for messages.
22685 *
22686 * The `server` 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.
22687 */
22688 async connect(transport) {
22689 return await this.server.connect(transport);
22690 }
22691 /**
22692 * Closes the connection.
22693 */
22694 async close() {
22695 await this.server.close();
22696 }
22697 setToolRequestHandlers() {
22698 if (this._toolHandlersInitialized) return;
22699 this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));
22700 this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));
22701 this.server.registerCapabilities({ tools: { listChanged: true } });
22702 this.server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {
22703 const toolDefinition = {
22704 name,
22705 title: tool.title,
22706 description: tool.description,
22707 inputSchema: (() => {
22708 const obj = normalizeObjectSchema(tool.inputSchema);
22709 return obj ? toJsonSchemaCompat(obj, {
22710 strictUnions: true,
22711 pipeStrategy: "input"
22712 }) : EMPTY_OBJECT_JSON_SCHEMA;
22713 })(),
22714 annotations: tool.annotations,
22715 execution: tool.execution,
22716 _meta: tool._meta
22717 };
22718 if (tool.outputSchema) {
22719 const obj = normalizeObjectSchema(tool.outputSchema);
22720 if (obj) toolDefinition.outputSchema = toJsonSchemaCompat(obj, {
22721 strictUnions: true,
22722 pipeStrategy: "output"
22723 });
22724 }
22725 return toolDefinition;
22726 }) }));
22727 this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
22728 try {
22729 const tool = this._registeredTools[request.params.name];
22730 if (!tool) throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
22731 if (!tool.enabled) throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
22732 const isTaskRequest = !!request.params.task;
22733 const taskSupport = tool.execution?.taskSupport;
22734 const isTaskHandler = "createTask" in tool.handler;
22735 if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
22736 if (taskSupport === "required" && !isTaskRequest) throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);
22737 if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) return await this.handleAutomaticTaskPolling(tool, request, extra);
22738 const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
22739 const result = await this.executeToolHandler(tool, args, extra);
22740 if (isTaskRequest) return result;
22741 await this.validateToolOutput(tool, result, request.params.name);
22742 return result;
22743 } catch (error) {
22744 if (error instanceof McpError) {
22745 if (error.code === ErrorCode.UrlElicitationRequired) throw error;
22746 }
22747 return this.createToolError(error instanceof Error ? error.message : String(error));
22748 }
22749 });
22750 this._toolHandlersInitialized = true;
22751 }
22752 /**
22753 * Creates a tool error result.
22754 *
22755 * @param errorMessage - The error message.
22756 * @returns The tool error result.
22757 */
22758 createToolError(errorMessage) {
22759 return {
22760 content: [{
22761 type: "text",
22762 text: errorMessage
22763 }],
22764 isError: true
22765 };
22766 }
22767 /**
22768 * Validates tool input arguments against the tool's input schema.
22769 */
22770 async validateToolInput(tool, args, toolName) {
22771 if (!tool.inputSchema) return;
22772 const parseResult = await safeParseAsync(normalizeObjectSchema(tool.inputSchema) ?? tool.inputSchema, args);
22773 if (!parseResult.success) {
22774 const errorMessage = getParseErrorMessage("error" in parseResult ? parseResult.error : "Unknown error");
22775 throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);
22776 }
22777 return parseResult.data;
22778 }
22779 /**
22780 * Validates tool output against the tool's output schema.
22781 */
22782 async validateToolOutput(tool, result, toolName) {
22783 if (!tool.outputSchema) return;
22784 if (!("content" in result)) return;
22785 if (result.isError) return;
22786 if (!result.structuredContent) throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
22787 const parseResult = await safeParseAsync(normalizeObjectSchema(tool.outputSchema), result.structuredContent);
22788 if (!parseResult.success) {
22789 const errorMessage = getParseErrorMessage("error" in parseResult ? parseResult.error : "Unknown error");
22790 throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);
22791 }
22792 }
22793 /**
22794 * Executes a tool handler (either regular or task-based).
22795 */
22796 async executeToolHandler(tool, args, extra) {
22797 const handler = tool.handler;
22798 if ("createTask" in handler) {
22799 if (!extra.taskStore) throw new Error("No task store provided.");
22800 const taskExtra = {
22801 ...extra,
22802 taskStore: extra.taskStore
22803 };
22804 if (tool.inputSchema) {
22805 const typedHandler = handler;
22806 return await Promise.resolve(typedHandler.createTask(args, taskExtra));
22807 } else {
22808 const typedHandler = handler;
22809 return await Promise.resolve(typedHandler.createTask(taskExtra));
22810 }
22811 }
22812 if (tool.inputSchema) {
22813 const typedHandler = handler;
22814 return await Promise.resolve(typedHandler(args, extra));
22815 } else {
22816 const typedHandler = handler;
22817 return await Promise.resolve(typedHandler(extra));
22818 }
22819 }
22820 /**
22821 * Handles automatic task polling for tools with taskSupport 'optional'.
22822 */
22823 async handleAutomaticTaskPolling(tool, request, extra) {
22824 if (!extra.taskStore) throw new Error("No task store provided for task-capable tool.");
22825 const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
22826 const handler = tool.handler;
22827 const taskExtra = {
22828 ...extra,
22829 taskStore: extra.taskStore
22830 };
22831 const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : await Promise.resolve(handler.createTask(taskExtra));
22832 const taskId = createTaskResult.task.taskId;
22833 let task = createTaskResult.task;
22834 const pollInterval = task.pollInterval ?? 5e3;
22835 while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
22836 await new Promise((resolve) => setTimeout(resolve, pollInterval));
22837 const updatedTask = await extra.taskStore.getTask(taskId);
22838 if (!updatedTask) throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
22839 task = updatedTask;
22840 }
22841 return await extra.taskStore.getTaskResult(taskId);
22842 }
22843 setCompletionRequestHandler() {
22844 if (this._completionHandlerInitialized) return;
22845 this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));
22846 this.server.registerCapabilities({ completions: {} });
22847 this.server.setRequestHandler(CompleteRequestSchema, async (request) => {
22848 switch (request.params.ref.type) {
22849 case "ref/prompt":
22850 assertCompleteRequestPrompt(request);
22851 return this.handlePromptCompletion(request, request.params.ref);
22852 case "ref/resource":
22853 assertCompleteRequestResourceTemplate(request);
22854 return this.handleResourceCompletion(request, request.params.ref);
22855 default: throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
22856 }
22857 });
22858 this._completionHandlerInitialized = true;
22859 }
22860 async handlePromptCompletion(request, ref) {
22861 const prompt = this._registeredPrompts[ref.name];
22862 if (!prompt) throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
22863 if (!prompt.enabled) throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
22864 if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT;
22865 const field = getObjectShape(prompt.argsSchema)?.[request.params.argument.name];
22866 if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT;
22867 const completer = getCompleter(field);
22868 if (!completer) return EMPTY_COMPLETION_RESULT;
22869 return createCompletionResult(await completer(request.params.argument.value, request.params.context));
22870 }
22871 async handleResourceCompletion(request, ref) {
22872 const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);
22873 if (!template) {
22874 if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT;
22875 throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
22876 }
22877 const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
22878 if (!completer) return EMPTY_COMPLETION_RESULT;
22879 return createCompletionResult(await completer(request.params.argument.value, request.params.context));
22880 }
22881 setResourceRequestHandlers() {
22882 if (this._resourceHandlersInitialized) return;
22883 this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));
22884 this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));
22885 this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));
22886 this.server.registerCapabilities({ resources: { listChanged: true } });
22887 this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
22888 const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({
22889 uri,
22890 name: resource.name,
22891 ...resource.metadata
22892 }));
22893 const templateResources = [];
22894 for (const template of Object.values(this._registeredResourceTemplates)) {
22895 if (!template.resourceTemplate.listCallback) continue;
22896 const result = await template.resourceTemplate.listCallback(extra);
22897 for (const resource of result.resources) templateResources.push({
22898 ...template.metadata,
22899 ...resource
22900 });
22901 }
22902 return { resources: [...resources, ...templateResources] };
22903 });
22904 this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
22905 return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
22906 name,
22907 uriTemplate: template.resourceTemplate.uriTemplate.toString(),
22908 ...template.metadata
22909 })) };
22910 });
22911 this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
22912 const uri = new URL(request.params.uri);
22913 const resource = this._registeredResources[uri.toString()];
22914 if (resource) {
22915 if (!resource.enabled) throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);
22916 return resource.readCallback(uri, extra);
22917 }
22918 for (const template of Object.values(this._registeredResourceTemplates)) {
22919 const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
22920 if (variables) return template.readCallback(uri, variables, extra);
22921 }
22922 throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);
22923 });
22924 this._resourceHandlersInitialized = true;
22925 }
22926 setPromptRequestHandlers() {
22927 if (this._promptHandlersInitialized) return;
22928 this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));
22929 this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));
22930 this.server.registerCapabilities({ prompts: { listChanged: true } });
22931 this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
22932 return {
22933 name,
22934 title: prompt.title,
22935 description: prompt.description,
22936 arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0
22937 };
22938 }) }));
22939 this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
22940 const prompt = this._registeredPrompts[request.params.name];
22941 if (!prompt) throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
22942 if (!prompt.enabled) throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
22943 if (prompt.argsSchema) {
22944 const parseResult = await safeParseAsync(normalizeObjectSchema(prompt.argsSchema), request.params.arguments);
22945 if (!parseResult.success) {
22946 const errorMessage = getParseErrorMessage("error" in parseResult ? parseResult.error : "Unknown error");
22947 throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);
22948 }
22949 const args = parseResult.data;
22950 const cb = prompt.callback;
22951 return await Promise.resolve(cb(args, extra));
22952 } else {
22953 const cb = prompt.callback;
22954 return await Promise.resolve(cb(extra));
22955 }
22956 });
22957 this._promptHandlersInitialized = true;
22958 }
22959 resource(name, uriOrTemplate, ...rest) {
22960 let metadata;
22961 if (typeof rest[0] === "object") metadata = rest.shift();
22962 const readCallback = rest[0];
22963 if (typeof uriOrTemplate === "string") {
22964 if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
22965 const registeredResource = this._createRegisteredResource(name, void 0, uriOrTemplate, metadata, readCallback);
22966 this.setResourceRequestHandlers();
22967 this.sendResourceListChanged();
22968 return registeredResource;
22969 } else {
22970 if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
22971 const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, void 0, uriOrTemplate, metadata, readCallback);
22972 this.setResourceRequestHandlers();
22973 this.sendResourceListChanged();
22974 return registeredResourceTemplate;
22975 }
22976 }
22977 registerResource(name, uriOrTemplate, config, readCallback) {
22978 if (typeof uriOrTemplate === "string") {
22979 if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
22980 const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback);
22981 this.setResourceRequestHandlers();
22982 this.sendResourceListChanged();
22983 return registeredResource;
22984 } else {
22985 if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
22986 const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback);
22987 this.setResourceRequestHandlers();
22988 this.sendResourceListChanged();
22989 return registeredResourceTemplate;
22990 }
22991 }
22992 _createRegisteredResource(name, title, uri, metadata, readCallback) {
22993 const registeredResource = {
22994 name,
22995 title,
22996 metadata,
22997 readCallback,
22998 enabled: true,
22999 disable: () => registeredResource.update({ enabled: false }),
23000 enable: () => registeredResource.update({ enabled: true }),
23001 remove: () => registeredResource.update({ uri: null }),
23002 update: (updates) => {
23003 if (typeof updates.uri !== "undefined" && updates.uri !== uri) {
23004 delete this._registeredResources[uri];
23005 if (updates.uri) this._registeredResources[updates.uri] = registeredResource;
23006 }
23007 if (typeof updates.name !== "undefined") registeredResource.name = updates.name;
23008 if (typeof updates.title !== "undefined") registeredResource.title = updates.title;
23009 if (typeof updates.metadata !== "undefined") registeredResource.metadata = updates.metadata;
23010 if (typeof updates.callback !== "undefined") registeredResource.readCallback = updates.callback;
23011 if (typeof updates.enabled !== "undefined") registeredResource.enabled = updates.enabled;
23012 this.sendResourceListChanged();
23013 }
23014 };
23015 this._registeredResources[uri] = registeredResource;
23016 return registeredResource;
23017 }
23018 _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
23019 const registeredResourceTemplate = {
23020 resourceTemplate: template,
23021 title,
23022 metadata,
23023 readCallback,
23024 enabled: true,
23025 disable: () => registeredResourceTemplate.update({ enabled: false }),
23026 enable: () => registeredResourceTemplate.update({ enabled: true }),
23027 remove: () => registeredResourceTemplate.update({ name: null }),
23028 update: (updates) => {
23029 if (typeof updates.name !== "undefined" && updates.name !== name) {
23030 delete this._registeredResourceTemplates[name];
23031 if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
23032 }
23033 if (typeof updates.title !== "undefined") registeredResourceTemplate.title = updates.title;
23034 if (typeof updates.template !== "undefined") registeredResourceTemplate.resourceTemplate = updates.template;
23035 if (typeof updates.metadata !== "undefined") registeredResourceTemplate.metadata = updates.metadata;
23036 if (typeof updates.callback !== "undefined") registeredResourceTemplate.readCallback = updates.callback;
23037 if (typeof updates.enabled !== "undefined") registeredResourceTemplate.enabled = updates.enabled;
23038 this.sendResourceListChanged();
23039 }
23040 };
23041 this._registeredResourceTemplates[name] = registeredResourceTemplate;
23042 const variableNames = template.uriTemplate.variableNames;
23043 if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler();
23044 return registeredResourceTemplate;
23045 }
23046 _createRegisteredPrompt(name, title, description, argsSchema, callback) {
23047 const registeredPrompt = {
23048 title,
23049 description,
23050 argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema),
23051 callback,
23052 enabled: true,
23053 disable: () => registeredPrompt.update({ enabled: false }),
23054 enable: () => registeredPrompt.update({ enabled: true }),
23055 remove: () => registeredPrompt.update({ name: null }),
23056 update: (updates) => {
23057 if (typeof updates.name !== "undefined" && updates.name !== name) {
23058 delete this._registeredPrompts[name];
23059 if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt;
23060 }
23061 if (typeof updates.title !== "undefined") registeredPrompt.title = updates.title;
23062 if (typeof updates.description !== "undefined") registeredPrompt.description = updates.description;
23063 if (typeof updates.argsSchema !== "undefined") registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);
23064 if (typeof updates.callback !== "undefined") registeredPrompt.callback = updates.callback;
23065 if (typeof updates.enabled !== "undefined") registeredPrompt.enabled = updates.enabled;
23066 this.sendPromptListChanged();
23067 }
23068 };
23069 this._registeredPrompts[name] = registeredPrompt;
23070 if (argsSchema) {
23071 if (Object.values(argsSchema).some((field) => {
23072 return isCompletable(field instanceof ZodOptional ? field._def?.innerType : field);
23073 })) this.setCompletionRequestHandler();
23074 }
23075 return registeredPrompt;
23076 }
23077 _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {
23078 validateAndWarnToolName(name);
23079 const registeredTool = {
23080 title,
23081 description,
23082 inputSchema: getZodSchemaObject(inputSchema),
23083 outputSchema: getZodSchemaObject(outputSchema),
23084 annotations,
23085 execution,
23086 _meta,
23087 handler,
23088 enabled: true,
23089 disable: () => registeredTool.update({ enabled: false }),
23090 enable: () => registeredTool.update({ enabled: true }),
23091 remove: () => registeredTool.update({ name: null }),
23092 update: (updates) => {
23093 if (typeof updates.name !== "undefined" && updates.name !== name) {
23094 if (typeof updates.name === "string") validateAndWarnToolName(updates.name);
23095 delete this._registeredTools[name];
23096 if (updates.name) this._registeredTools[updates.name] = registeredTool;
23097 }
23098 if (typeof updates.title !== "undefined") registeredTool.title = updates.title;
23099 if (typeof updates.description !== "undefined") registeredTool.description = updates.description;
23100 if (typeof updates.paramsSchema !== "undefined") registeredTool.inputSchema = objectFromShape(updates.paramsSchema);
23101 if (typeof updates.outputSchema !== "undefined") registeredTool.outputSchema = objectFromShape(updates.outputSchema);
23102 if (typeof updates.callback !== "undefined") registeredTool.handler = updates.callback;
23103 if (typeof updates.annotations !== "undefined") registeredTool.annotations = updates.annotations;
23104 if (typeof updates._meta !== "undefined") registeredTool._meta = updates._meta;
23105 if (typeof updates.enabled !== "undefined") registeredTool.enabled = updates.enabled;
23106 this.sendToolListChanged();
23107 }
23108 };
23109 this._registeredTools[name] = registeredTool;
23110 this.setToolRequestHandlers();
23111 this.sendToolListChanged();
23112 return registeredTool;
23113 }
23114 /**
23115 * tool() implementation. Parses arguments passed to overrides defined above.
23116 */
23117 tool(name, ...rest) {
23118 if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
23119 let description;
23120 let inputSchema;
23121 let outputSchema;
23122 let annotations;
23123 if (typeof rest[0] === "string") description = rest.shift();
23124 if (rest.length > 1) {
23125 const firstArg = rest[0];
23126 if (isZodRawShapeCompat(firstArg)) {
23127 inputSchema = rest.shift();
23128 if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) annotations = rest.shift();
23129 } else if (typeof firstArg === "object" && firstArg !== null) annotations = rest.shift();
23130 }
23131 const callback = rest[0];
23132 return this._createRegisteredTool(name, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);
23133 }
23134 /**
23135 * Registers a tool with a config object and callback.
23136 */
23137 registerTool(name, config, cb) {
23138 if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
23139 const { title, description, inputSchema, outputSchema, annotations, _meta } = config;
23140 return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);
23141 }
23142 prompt(name, ...rest) {
23143 if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
23144 let description;
23145 if (typeof rest[0] === "string") description = rest.shift();
23146 let argsSchema;
23147 if (rest.length > 1) argsSchema = rest.shift();
23148 const cb = rest[0];
23149 const registeredPrompt = this._createRegisteredPrompt(name, void 0, description, argsSchema, cb);
23150 this.setPromptRequestHandlers();
23151 this.sendPromptListChanged();
23152 return registeredPrompt;
23153 }
23154 /**
23155 * Registers a prompt with a config object and callback.
23156 */
23157 registerPrompt(name, config, cb) {
23158 if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
23159 const { title, description, argsSchema } = config;
23160 const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);
23161 this.setPromptRequestHandlers();
23162 this.sendPromptListChanged();
23163 return registeredPrompt;
23164 }
23165 /**
23166 * Checks if the server is connected to a transport.
23167 * @returns True if the server is connected
23168 */
23169 isConnected() {
23170 return this.server.transport !== void 0;
23171 }
23172 /**
23173 * Sends a logging message to the client, if connected.
23174 * Note: You only need to send the parameters object, not the entire JSON RPC message
23175 * @see LoggingMessageNotification
23176 * @param params
23177 * @param sessionId optional for stateless and backward compatibility
23178 */
23179 async sendLoggingMessage(params, sessionId) {
23180 return this.server.sendLoggingMessage(params, sessionId);
23181 }
23182 /**
23183 * Sends a resource list changed event to the client, if connected.
23184 */
23185 sendResourceListChanged() {
23186 if (this.isConnected()) this.server.sendResourceListChanged();
23187 }
23188 /**
23189 * Sends a tool list changed event to the client, if connected.
23190 */
23191 sendToolListChanged() {
23192 if (this.isConnected()) this.server.sendToolListChanged();
23193 }
23194 /**
23195 * Sends a prompt list changed event to the client, if connected.
23196 */
23197 sendPromptListChanged() {
23198 if (this.isConnected()) this.server.sendPromptListChanged();
23199 }
23200 };
23201 /**
23202 * A resource template combines a URI pattern with optional functionality to enumerate
23203 * all resources matching that pattern.
23204 */
23205 var ResourceTemplate = class {
23206 constructor(uriTemplate, _callbacks) {
23207 this._callbacks = _callbacks;
23208 this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate;
23209 }
23210 /**
23211 * Gets the URI template pattern.
23212 */
23213 get uriTemplate() {
23214 return this._uriTemplate;
23215 }
23216 /**
23217 * Gets the list callback, if one was provided.
23218 */
23219 get listCallback() {
23220 return this._callbacks.list;
23221 }
23222 /**
23223 * Gets the callback for completing a specific URI template variable, if one was provided.
23224 */
23225 completeCallback(variable) {
23226 return this._callbacks.complete?.[variable];
23227 }
23228 };
23229 var EMPTY_OBJECT_JSON_SCHEMA = {
23230 type: "object",
23231 properties: {}
23232 };
23233 /**
23234 * Checks if a value looks like a Zod schema by checking for parse/safeParse methods.
23235 */
23236 function isZodTypeLike(value) {
23237 return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
23238 }
23239 /**
23240 * Checks if an object is a Zod schema instance (v3 or v4).
23241 *
23242 * Zod schemas have internal markers:
23243 * - v3: `_def` property
23244 * - v4: `_zod` property
23245 *
23246 * This includes transformed schemas like z.preprocess(), z.transform(), z.pipe().
23247 */
23248 function isZodSchemaInstance(obj) {
23249 return "_def" in obj || "_zod" in obj || isZodTypeLike(obj);
23250 }
23251 /**
23252 * Checks if an object is a "raw shape" - a plain object where values are Zod schemas.
23253 *
23254 * Raw shapes are used as shorthand: `{ name: z.string() }` instead of `z.object({ name: z.string() })`.
23255 *
23256 * IMPORTANT: This must NOT match actual Zod schema instances (like z.preprocess, z.pipe),
23257 * which have internal properties that could be mistaken for schema values.
23258 */
23259 function isZodRawShapeCompat(obj) {
23260 if (typeof obj !== "object" || obj === null) return false;
23261 if (isZodSchemaInstance(obj)) return false;
23262 if (Object.keys(obj).length === 0) return true;
23263 return Object.values(obj).some(isZodTypeLike);
23264 }
23265 /**
23266 * Converts a provided Zod schema to a Zod object if it is a ZodRawShapeCompat,
23267 * otherwise returns the schema as is.
23268 */
23269 function getZodSchemaObject(schema) {
23270 if (!schema) return;
23271 if (isZodRawShapeCompat(schema)) return objectFromShape(schema);
23272 return schema;
23273 }
23274 function promptArgumentsFromSchema(schema) {
23275 const shape = getObjectShape(schema);
23276 if (!shape) return [];
23277 return Object.entries(shape).map(([name, field]) => {
23278 return {
23279 name,
23280 description: getSchemaDescription(field),
23281 required: !isSchemaOptional(field)
23282 };
23283 });
23284 }
23285 function getMethodValue(schema) {
23286 const methodSchema = getObjectShape(schema)?.method;
23287 if (!methodSchema) throw new Error("Schema is missing a method literal");
23288 const value = getLiteralValue(methodSchema);
23289 if (typeof value === "string") return value;
23290 throw new Error("Schema method literal must be a string");
23291 }
23292 function createCompletionResult(suggestions) {
23293 return { completion: {
23294 values: suggestions.slice(0, 100),
23295 total: suggestions.length,
23296 hasMore: suggestions.length > 100
23297 } };
23298 }
23299 var EMPTY_COMPLETION_RESULT = { completion: {
23300 values: [],
23301 hasMore: false
23302 } };
23303
23304 //#endregion
23305 //#region packages/packages/libs/editor-mcp/src/utils/is-angie-available.ts
23306 var isAngieAvailable = () => {
23307 return !!ut();
23308 };
23309
23310 //#endregion
23311 //#region packages/packages/libs/editor-mcp/src/utils/is-angie-sidebar-open.ts
23312 var isAngieSidebarOpen = () => {
23313 return Rt() === vt;
23314 };
23315
23316 //#endregion
23317 //#region packages/packages/libs/editor-mcp/src/utils/to-mcp-title.ts
23318 var toMCPTitle = (namespace) => {
23319 return `Editor ${namespace.charAt(0).toUpperCase() + namespace.slice(1)}`;
23320 };
23321
23322 //#endregion
23323 //#region packages/packages/libs/editor-mcp/src/adapters/angie-adapter.ts
23324 var __defProp$2 = Object.defineProperty;
23325 var __defNormalProp$2 = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp$2(obj, key, {
23326 enumerable: true,
23327 configurable: true,
23328 writable: true,
23329 value
23330 }) : obj[key] = value, "__defNormalProp");
23331 var __publicField$2 = /* @__PURE__ */ __name((obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value), "__publicField");
23332 var MAX_RETRIES = 3;
23333 var AngieMcpAdapter = class {
23334 constructor(sdk, getRegisteredMcpServers) {
23335 __publicField$2(this, "sdk", sdk);
23336 __publicField$2(this, "getRegisteredMcpServers", getRegisteredMcpServers);
23337 }
23338 async activate() {
23339 await this.registerEntries(this.getRegisteredMcpServers(), MAX_RETRIES);
23340 }
23341 async registerEntries(entries, retry) {
23342 if (retry === 0) {
23343 console.error("Failed to register MCP after 3 retries. failed entries: ", entries.map(([key]) => key));
23344 return;
23345 }
23346 const failed = [];
23347 for (const [key, mcpServer, description] of entries) try {
23348 await this.sdk.registerLocalServer({
23349 title: toMCPTitle(key),
23350 name: `editor-${key}`,
23351 server: mcpServer,
23352 version: "1.0.0",
23353 description
23354 });
23355 } catch {
23356 failed.push([
23357 key,
23358 mcpServer,
23359 description
23360 ]);
23361 }
23362 if (failed.length > 0) return this.registerEntries(failed, retry - 1);
23363 }
23364 onToolRegistered() {}
23365 onResourceRegistered() {}
23366 sendResourceUpdated() {}
23367 };
23368
23369 //#endregion
23370 //#region node_modules/zod-to-json-schema/dist/esm/Options.js
23371 var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
23372 var defaultOptions = {
23373 name: void 0,
23374 $refStrategy: "root",
23375 basePath: ["#"],
23376 effectStrategy: "input",
23377 pipeStrategy: "all",
23378 dateStrategy: "format:date-time",
23379 mapStrategy: "entries",
23380 removeAdditionalStrategy: "passthrough",
23381 allowedAdditionalProperties: true,
23382 rejectedAdditionalProperties: false,
23383 definitionPath: "definitions",
23384 target: "jsonSchema7",
23385 strictUnions: false,
23386 definitions: {},
23387 errorMessages: false,
23388 markdownDescription: false,
23389 patternStrategy: "escape",
23390 applyRegexFlags: false,
23391 emailStrategy: "format:email",
23392 base64Strategy: "contentEncoding:base64",
23393 nameStrategy: "ref",
23394 openAiAnyTypeName: "OpenAiAnyType"
23395 };
23396 var getDefaultOptions = (options) => typeof options === "string" ? {
23397 ...defaultOptions,
23398 name: options
23399 } : {
23400 ...defaultOptions,
23401 ...options
23402 };
23403
23404 //#endregion
23405 //#region node_modules/zod-to-json-schema/dist/esm/Refs.js
23406 var getRefs = (options) => {
23407 const _options = getDefaultOptions(options);
23408 const currentPath = _options.name !== void 0 ? [
23409 ..._options.basePath,
23410 _options.definitionPath,
23411 _options.name
23412 ] : _options.basePath;
23413 return {
23414 ..._options,
23415 flags: { hasReferencedOpenAiAnyType: false },
23416 currentPath,
23417 propertyPath: void 0,
23418 seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, {
23419 def: def._def,
23420 path: [
23421 ..._options.basePath,
23422 _options.definitionPath,
23423 name
23424 ],
23425 jsonSchema: void 0
23426 }]))
23427 };
23428 };
23429
23430 //#endregion
23431 //#region node_modules/zod-to-json-schema/dist/esm/errorMessages.js
23432 function addErrorMessage(res, key, errorMessage, refs) {
23433 if (!refs?.errorMessages) return;
23434 if (errorMessage) res.errorMessage = {
23435 ...res.errorMessage,
23436 [key]: errorMessage
23437 };
23438 }
23439 function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
23440 res[key] = value;
23441 addErrorMessage(res, key, errorMessage, refs);
23442 }
23443
23444 //#endregion
23445 //#region node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
23446 var getRelativePath = (pathA, pathB) => {
23447 let i = 0;
23448 for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;
23449 return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
23450 };
23451
23452 //#endregion
23453 //#region node_modules/zod-to-json-schema/dist/esm/parsers/any.js
23454 function parseAnyDef(refs) {
23455 if (refs.target !== "openAi") return {};
23456 const anyDefinitionPath = [
23457 ...refs.basePath,
23458 refs.definitionPath,
23459 refs.openAiAnyTypeName
23460 ];
23461 refs.flags.hasReferencedOpenAiAnyType = true;
23462 return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") };
23463 }
23464
23465 //#endregion
23466 //#region node_modules/zod-to-json-schema/dist/esm/parsers/array.js
23467 function parseArrayDef(def, refs) {
23468 const res = { type: "array" };
23469 if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {
23470 ...refs,
23471 currentPath: [...refs.currentPath, "items"]
23472 });
23473 if (def.minLength) setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
23474 if (def.maxLength) setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
23475 if (def.exactLength) {
23476 setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
23477 setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
23478 }
23479 return res;
23480 }
23481
23482 //#endregion
23483 //#region node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
23484 function parseBigintDef(def, refs) {
23485 const res = {
23486 type: "integer",
23487 format: "int64"
23488 };
23489 if (!def.checks) return res;
23490 for (const check of def.checks) switch (check.kind) {
23491 case "min":
23492 if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
23493 else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
23494 else {
23495 if (!check.inclusive) res.exclusiveMinimum = true;
23496 setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
23497 }
23498 break;
23499 case "max":
23500 if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
23501 else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
23502 else {
23503 if (!check.inclusive) res.exclusiveMaximum = true;
23504 setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
23505 }
23506 break;
23507 case "multipleOf":
23508 setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
23509 break;
23510 }
23511 return res;
23512 }
23513
23514 //#endregion
23515 //#region node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
23516 function parseBooleanDef() {
23517 return { type: "boolean" };
23518 }
23519
23520 //#endregion
23521 //#region node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
23522 function parseBrandedDef(_def, refs) {
23523 return parseDef(_def.type._def, refs);
23524 }
23525
23526 //#endregion
23527 //#region node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
23528 var parseCatchDef = (def, refs) => {
23529 return parseDef(def.innerType._def, refs);
23530 };
23531
23532 //#endregion
23533 //#region node_modules/zod-to-json-schema/dist/esm/parsers/date.js
23534 function parseDateDef(def, refs, overrideDateStrategy) {
23535 const strategy = overrideDateStrategy ?? refs.dateStrategy;
23536 if (Array.isArray(strategy)) return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) };
23537 switch (strategy) {
23538 case "string":
23539 case "format:date-time": return {
23540 type: "string",
23541 format: "date-time"
23542 };
23543 case "format:date": return {
23544 type: "string",
23545 format: "date"
23546 };
23547 case "integer": return integerDateParser(def, refs);
23548 }
23549 }
23550 var integerDateParser = (def, refs) => {
23551 const res = {
23552 type: "integer",
23553 format: "unix-time"
23554 };
23555 if (refs.target === "openApi3") return res;
23556 for (const check of def.checks) switch (check.kind) {
23557 case "min":
23558 setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
23559 break;
23560 case "max":
23561 setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
23562 break;
23563 }
23564 return res;
23565 };
23566
23567 //#endregion
23568 //#region node_modules/zod-to-json-schema/dist/esm/parsers/default.js
23569 function parseDefaultDef(_def, refs) {
23570 return {
23571 ...parseDef(_def.innerType._def, refs),
23572 default: _def.defaultValue()
23573 };
23574 }
23575
23576 //#endregion
23577 //#region node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
23578 function parseEffectsDef(_def, refs) {
23579 return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);
23580 }
23581
23582 //#endregion
23583 //#region node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
23584 function parseEnumDef(def) {
23585 return {
23586 type: "string",
23587 enum: Array.from(def.values)
23588 };
23589 }
23590
23591 //#endregion
23592 //#region node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
23593 var isJsonSchema7AllOfType = (type) => {
23594 if ("type" in type && type.type === "string") return false;
23595 return "allOf" in type;
23596 };
23597 function parseIntersectionDef(def, refs) {
23598 const allOf = [parseDef(def.left._def, {
23599 ...refs,
23600 currentPath: [
23601 ...refs.currentPath,
23602 "allOf",
23603 "0"
23604 ]
23605 }), parseDef(def.right._def, {
23606 ...refs,
23607 currentPath: [
23608 ...refs.currentPath,
23609 "allOf",
23610 "1"
23611 ]
23612 })].filter((x) => !!x);
23613 let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
23614 const mergedAllOf = [];
23615 allOf.forEach((schema) => {
23616 if (isJsonSchema7AllOfType(schema)) {
23617 mergedAllOf.push(...schema.allOf);
23618 if (schema.unevaluatedProperties === void 0) unevaluatedProperties = void 0;
23619 } else {
23620 let nestedSchema = schema;
23621 if ("additionalProperties" in schema && schema.additionalProperties === false) {
23622 const { additionalProperties, ...rest } = schema;
23623 nestedSchema = rest;
23624 } else unevaluatedProperties = void 0;
23625 mergedAllOf.push(nestedSchema);
23626 }
23627 });
23628 return mergedAllOf.length ? {
23629 allOf: mergedAllOf,
23630 ...unevaluatedProperties
23631 } : void 0;
23632 }
23633
23634 //#endregion
23635 //#region node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
23636 function parseLiteralDef(def, refs) {
23637 const parsedType = typeof def.value;
23638 if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" };
23639 if (refs.target === "openApi3") return {
23640 type: parsedType === "bigint" ? "integer" : parsedType,
23641 enum: [def.value]
23642 };
23643 return {
23644 type: parsedType === "bigint" ? "integer" : parsedType,
23645 const: def.value
23646 };
23647 }
23648
23649 //#endregion
23650 //#region node_modules/zod-to-json-schema/dist/esm/parsers/string.js
23651 var emojiRegex = void 0;
23652 /**
23653 * Generated from the regular expressions found here as of 2024-05-22:
23654 * https://github.com/colinhacks/zod/blob/master/src/types.ts.
23655 *
23656 * Expressions with /i flag have been changed accordingly.
23657 */
23658 var zodPatterns = {
23659 /**
23660 * `c` was changed to `[cC]` to replicate /i flag
23661 */
23662 cuid: /^[cC][^\s-]{8,}$/,
23663 cuid2: /^[0-9a-z]+$/,
23664 ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
23665 /**
23666 * `a-z` was added to replicate /i flag
23667 */
23668 email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
23669 /**
23670 * Constructed a valid Unicode RegExp
23671 *
23672 * Lazily instantiate since this type of regex isn't supported
23673 * in all envs (e.g. React Native).
23674 *
23675 * See:
23676 * https://github.com/colinhacks/zod/issues/2433
23677 * Fix in Zod:
23678 * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
23679 */
23680 emoji: () => {
23681 if (emojiRegex === void 0) emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
23682 return emojiRegex;
23683 },
23684 /**
23685 * Unused
23686 */
23687 uuid: /^[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}$/,
23688 /**
23689 * Unused
23690 */
23691 ipv4: /^(?:(?: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])$/,
23692 ipv4Cidr: /^(?:(?: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])$/,
23693 /**
23694 * Unused
23695 */
23696 ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
23697 ipv6Cidr: /^(([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])$/,
23698 base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
23699 base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
23700 nanoid: /^[a-zA-Z0-9_-]{21}$/,
23701 jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
23702 };
23703 function parseStringDef(def, refs) {
23704 const res = { type: "string" };
23705 if (def.checks) for (const check of def.checks) switch (check.kind) {
23706 case "min":
23707 setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
23708 break;
23709 case "max":
23710 setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
23711 break;
23712 case "email":
23713 switch (refs.emailStrategy) {
23714 case "format:email":
23715 addFormat(res, "email", check.message, refs);
23716 break;
23717 case "format:idn-email":
23718 addFormat(res, "idn-email", check.message, refs);
23719 break;
23720 case "pattern:zod":
23721 addPattern(res, zodPatterns.email, check.message, refs);
23722 break;
23723 }
23724 break;
23725 case "url":
23726 addFormat(res, "uri", check.message, refs);
23727 break;
23728 case "uuid":
23729 addFormat(res, "uuid", check.message, refs);
23730 break;
23731 case "regex":
23732 addPattern(res, check.regex, check.message, refs);
23733 break;
23734 case "cuid":
23735 addPattern(res, zodPatterns.cuid, check.message, refs);
23736 break;
23737 case "cuid2":
23738 addPattern(res, zodPatterns.cuid2, check.message, refs);
23739 break;
23740 case "startsWith":
23741 addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
23742 break;
23743 case "endsWith":
23744 addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
23745 break;
23746 case "datetime":
23747 addFormat(res, "date-time", check.message, refs);
23748 break;
23749 case "date":
23750 addFormat(res, "date", check.message, refs);
23751 break;
23752 case "time":
23753 addFormat(res, "time", check.message, refs);
23754 break;
23755 case "duration":
23756 addFormat(res, "duration", check.message, refs);
23757 break;
23758 case "length":
23759 setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
23760 setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
23761 break;
23762 case "includes":
23763 addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
23764 break;
23765 case "ip":
23766 if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs);
23767 if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs);
23768 break;
23769 case "base64url":
23770 addPattern(res, zodPatterns.base64url, check.message, refs);
23771 break;
23772 case "jwt":
23773 addPattern(res, zodPatterns.jwt, check.message, refs);
23774 break;
23775 case "cidr":
23776 if (check.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
23777 if (check.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
23778 break;
23779 case "emoji":
23780 addPattern(res, zodPatterns.emoji(), check.message, refs);
23781 break;
23782 case "ulid":
23783 addPattern(res, zodPatterns.ulid, check.message, refs);
23784 break;
23785 case "base64":
23786 switch (refs.base64Strategy) {
23787 case "format:binary":
23788 addFormat(res, "binary", check.message, refs);
23789 break;
23790 case "contentEncoding:base64":
23791 setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
23792 break;
23793 case "pattern:zod":
23794 addPattern(res, zodPatterns.base64, check.message, refs);
23795 break;
23796 }
23797 break;
23798 case "nanoid": addPattern(res, zodPatterns.nanoid, check.message, refs);
23799 case "toLowerCase":
23800 case "toUpperCase":
23801 case "trim": break;
23802 default:
23803 }
23804 return res;
23805 }
23806 function escapeLiteralCheckValue(literal, refs) {
23807 return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
23808 }
23809 var ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
23810 function escapeNonAlphaNumeric(source) {
23811 let result = "";
23812 for (let i = 0; i < source.length; i++) {
23813 if (!ALPHA_NUMERIC.has(source[i])) result += "\\";
23814 result += source[i];
23815 }
23816 return result;
23817 }
23818 function addFormat(schema, value, message, refs) {
23819 if (schema.format || schema.anyOf?.some((x) => x.format)) {
23820 if (!schema.anyOf) schema.anyOf = [];
23821 if (schema.format) {
23822 schema.anyOf.push({
23823 format: schema.format,
23824 ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } }
23825 });
23826 delete schema.format;
23827 if (schema.errorMessage) {
23828 delete schema.errorMessage.format;
23829 if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage;
23830 }
23831 }
23832 schema.anyOf.push({
23833 format: value,
23834 ...message && refs.errorMessages && { errorMessage: { format: message } }
23835 });
23836 } else setResponseValueAndErrors(schema, "format", value, message, refs);
23837 }
23838 function addPattern(schema, regex, message, refs) {
23839 if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
23840 if (!schema.allOf) schema.allOf = [];
23841 if (schema.pattern) {
23842 schema.allOf.push({
23843 pattern: schema.pattern,
23844 ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } }
23845 });
23846 delete schema.pattern;
23847 if (schema.errorMessage) {
23848 delete schema.errorMessage.pattern;
23849 if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage;
23850 }
23851 }
23852 schema.allOf.push({
23853 pattern: stringifyRegExpWithFlags(regex, refs),
23854 ...message && refs.errorMessages && { errorMessage: { pattern: message } }
23855 });
23856 } else setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
23857 }
23858 function stringifyRegExpWithFlags(regex, refs) {
23859 if (!refs.applyRegexFlags || !regex.flags) return regex.source;
23860 const flags = {
23861 i: regex.flags.includes("i"),
23862 m: regex.flags.includes("m"),
23863 s: regex.flags.includes("s")
23864 };
23865 const source = flags.i ? regex.source.toLowerCase() : regex.source;
23866 let pattern = "";
23867 let isEscaped = false;
23868 let inCharGroup = false;
23869 let inCharRange = false;
23870 for (let i = 0; i < source.length; i++) {
23871 if (isEscaped) {
23872 pattern += source[i];
23873 isEscaped = false;
23874 continue;
23875 }
23876 if (flags.i) {
23877 if (inCharGroup) {
23878 if (source[i].match(/[a-z]/)) {
23879 if (inCharRange) {
23880 pattern += source[i];
23881 pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
23882 inCharRange = false;
23883 } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
23884 pattern += source[i];
23885 inCharRange = true;
23886 } else pattern += `${source[i]}${source[i].toUpperCase()}`;
23887 continue;
23888 }
23889 } else if (source[i].match(/[a-z]/)) {
23890 pattern += `[${source[i]}${source[i].toUpperCase()}]`;
23891 continue;
23892 }
23893 }
23894 if (flags.m) {
23895 if (source[i] === "^") {
23896 pattern += `(^|(?<=[\r\n]))`;
23897 continue;
23898 } else if (source[i] === "$") {
23899 pattern += `($|(?=[\r\n]))`;
23900 continue;
23901 }
23902 }
23903 if (flags.s && source[i] === ".") {
23904 pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
23905 continue;
23906 }
23907 pattern += source[i];
23908 if (source[i] === "\\") isEscaped = true;
23909 else if (inCharGroup && source[i] === "]") inCharGroup = false;
23910 else if (!inCharGroup && source[i] === "[") inCharGroup = true;
23911 }
23912 try {
23913 new RegExp(pattern);
23914 } catch {
23915 console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
23916 return regex.source;
23917 }
23918 return pattern;
23919 }
23920
23921 //#endregion
23922 //#region node_modules/zod-to-json-schema/dist/esm/parsers/record.js
23923 function parseRecordDef(def, refs) {
23924 if (refs.target === "openAi") console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
23925 if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return {
23926 type: "object",
23927 required: def.keyType._def.values,
23928 properties: def.keyType._def.values.reduce((acc, key) => ({
23929 ...acc,
23930 [key]: parseDef(def.valueType._def, {
23931 ...refs,
23932 currentPath: [
23933 ...refs.currentPath,
23934 "properties",
23935 key
23936 ]
23937 }) ?? parseAnyDef(refs)
23938 }), {}),
23939 additionalProperties: refs.rejectedAdditionalProperties
23940 };
23941 const schema = {
23942 type: "object",
23943 additionalProperties: parseDef(def.valueType._def, {
23944 ...refs,
23945 currentPath: [...refs.currentPath, "additionalProperties"]
23946 }) ?? refs.allowedAdditionalProperties
23947 };
23948 if (refs.target === "openApi3") return schema;
23949 if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
23950 const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
23951 return {
23952 ...schema,
23953 propertyNames: keyType
23954 };
23955 } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return {
23956 ...schema,
23957 propertyNames: { enum: def.keyType._def.values }
23958 };
23959 else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
23960 const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
23961 return {
23962 ...schema,
23963 propertyNames: keyType
23964 };
23965 }
23966 return schema;
23967 }
23968
23969 //#endregion
23970 //#region node_modules/zod-to-json-schema/dist/esm/parsers/map.js
23971 function parseMapDef(def, refs) {
23972 if (refs.mapStrategy === "record") return parseRecordDef(def, refs);
23973 return {
23974 type: "array",
23975 maxItems: 125,
23976 items: {
23977 type: "array",
23978 items: [parseDef(def.keyType._def, {
23979 ...refs,
23980 currentPath: [
23981 ...refs.currentPath,
23982 "items",
23983 "items",
23984 "0"
23985 ]
23986 }) || parseAnyDef(refs), parseDef(def.valueType._def, {
23987 ...refs,
23988 currentPath: [
23989 ...refs.currentPath,
23990 "items",
23991 "items",
23992 "1"
23993 ]
23994 }) || parseAnyDef(refs)],
23995 minItems: 2,
23996 maxItems: 2
23997 }
23998 };
23999 }
24000
24001 //#endregion
24002 //#region node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
24003 function parseNativeEnumDef(def) {
24004 const object = def.values;
24005 const actualValues = Object.keys(def.values).filter((key) => {
24006 return typeof object[object[key]] !== "number";
24007 }).map((key) => object[key]);
24008 const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
24009 return {
24010 type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
24011 enum: actualValues
24012 };
24013 }
24014
24015 //#endregion
24016 //#region node_modules/zod-to-json-schema/dist/esm/parsers/never.js
24017 function parseNeverDef(refs) {
24018 return refs.target === "openAi" ? void 0 : { not: parseAnyDef({
24019 ...refs,
24020 currentPath: [...refs.currentPath, "not"]
24021 }) };
24022 }
24023
24024 //#endregion
24025 //#region node_modules/zod-to-json-schema/dist/esm/parsers/null.js
24026 function parseNullDef(refs) {
24027 return refs.target === "openApi3" ? {
24028 enum: ["null"],
24029 nullable: true
24030 } : { type: "null" };
24031 }
24032
24033 //#endregion
24034 //#region node_modules/zod-to-json-schema/dist/esm/parsers/union.js
24035 var primitiveMappings = {
24036 ZodString: "string",
24037 ZodNumber: "number",
24038 ZodBigInt: "integer",
24039 ZodBoolean: "boolean",
24040 ZodNull: "null"
24041 };
24042 function parseUnionDef(def, refs) {
24043 if (refs.target === "openApi3") return asAnyOf(def, refs);
24044 const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
24045 if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
24046 const types = options.reduce((types, x) => {
24047 const type = primitiveMappings[x._def.typeName];
24048 return type && !types.includes(type) ? [...types, type] : types;
24049 }, []);
24050 return { type: types.length > 1 ? types : types[0] };
24051 } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
24052 const types = options.reduce((acc, x) => {
24053 const type = typeof x._def.value;
24054 switch (type) {
24055 case "string":
24056 case "number":
24057 case "boolean": return [...acc, type];
24058 case "bigint": return [...acc, "integer"];
24059 case "object": if (x._def.value === null) return [...acc, "null"];
24060 default: return acc;
24061 }
24062 }, []);
24063 if (types.length === options.length) {
24064 const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
24065 return {
24066 type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
24067 enum: options.reduce((acc, x) => {
24068 return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
24069 }, [])
24070 };
24071 }
24072 } else if (options.every((x) => x._def.typeName === "ZodEnum")) return {
24073 type: "string",
24074 enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], [])
24075 };
24076 return asAnyOf(def, refs);
24077 }
24078 var asAnyOf = (def, refs) => {
24079 const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
24080 ...refs,
24081 currentPath: [
24082 ...refs.currentPath,
24083 "anyOf",
24084 `${i}`
24085 ]
24086 })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
24087 return anyOf.length ? { anyOf } : void 0;
24088 };
24089
24090 //#endregion
24091 //#region node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
24092 function parseNullableDef(def, refs) {
24093 if ([
24094 "ZodString",
24095 "ZodNumber",
24096 "ZodBigInt",
24097 "ZodBoolean",
24098 "ZodNull"
24099 ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
24100 if (refs.target === "openApi3") return {
24101 type: primitiveMappings[def.innerType._def.typeName],
24102 nullable: true
24103 };
24104 return { type: [primitiveMappings[def.innerType._def.typeName], "null"] };
24105 }
24106 if (refs.target === "openApi3") {
24107 const base = parseDef(def.innerType._def, {
24108 ...refs,
24109 currentPath: [...refs.currentPath]
24110 });
24111 if (base && "$ref" in base) return {
24112 allOf: [base],
24113 nullable: true
24114 };
24115 return base && {
24116 ...base,
24117 nullable: true
24118 };
24119 }
24120 const base = parseDef(def.innerType._def, {
24121 ...refs,
24122 currentPath: [
24123 ...refs.currentPath,
24124 "anyOf",
24125 "0"
24126 ]
24127 });
24128 return base && { anyOf: [base, { type: "null" }] };
24129 }
24130
24131 //#endregion
24132 //#region node_modules/zod-to-json-schema/dist/esm/parsers/number.js
24133 function parseNumberDef(def, refs) {
24134 const res = { type: "number" };
24135 if (!def.checks) return res;
24136 for (const check of def.checks) switch (check.kind) {
24137 case "int":
24138 res.type = "integer";
24139 addErrorMessage(res, "type", check.message, refs);
24140 break;
24141 case "min":
24142 if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
24143 else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
24144 else {
24145 if (!check.inclusive) res.exclusiveMinimum = true;
24146 setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
24147 }
24148 break;
24149 case "max":
24150 if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
24151 else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
24152 else {
24153 if (!check.inclusive) res.exclusiveMaximum = true;
24154 setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
24155 }
24156 break;
24157 case "multipleOf":
24158 setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
24159 break;
24160 }
24161 return res;
24162 }
24163
24164 //#endregion
24165 //#region node_modules/zod-to-json-schema/dist/esm/parsers/object.js
24166 function parseObjectDef(def, refs) {
24167 const forceOptionalIntoNullable = refs.target === "openAi";
24168 const result = {
24169 type: "object",
24170 properties: {}
24171 };
24172 const required = [];
24173 const shape = def.shape();
24174 for (const propName in shape) {
24175 let propDef = shape[propName];
24176 if (propDef === void 0 || propDef._def === void 0) continue;
24177 let propOptional = safeIsOptional(propDef);
24178 if (propOptional && forceOptionalIntoNullable) {
24179 if (propDef._def.typeName === "ZodOptional") propDef = propDef._def.innerType;
24180 if (!propDef.isNullable()) propDef = propDef.nullable();
24181 propOptional = false;
24182 }
24183 const parsedDef = parseDef(propDef._def, {
24184 ...refs,
24185 currentPath: [
24186 ...refs.currentPath,
24187 "properties",
24188 propName
24189 ],
24190 propertyPath: [
24191 ...refs.currentPath,
24192 "properties",
24193 propName
24194 ]
24195 });
24196 if (parsedDef === void 0) continue;
24197 result.properties[propName] = parsedDef;
24198 if (!propOptional) required.push(propName);
24199 }
24200 if (required.length) result.required = required;
24201 const additionalProperties = decideAdditionalProperties(def, refs);
24202 if (additionalProperties !== void 0) result.additionalProperties = additionalProperties;
24203 return result;
24204 }
24205 function decideAdditionalProperties(def, refs) {
24206 if (def.catchall._def.typeName !== "ZodNever") return parseDef(def.catchall._def, {
24207 ...refs,
24208 currentPath: [...refs.currentPath, "additionalProperties"]
24209 });
24210 switch (def.unknownKeys) {
24211 case "passthrough": return refs.allowedAdditionalProperties;
24212 case "strict": return refs.rejectedAdditionalProperties;
24213 case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
24214 }
24215 }
24216 function safeIsOptional(schema) {
24217 try {
24218 return schema.isOptional();
24219 } catch {
24220 return true;
24221 }
24222 }
24223
24224 //#endregion
24225 //#region node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
24226 var parseOptionalDef = (def, refs) => {
24227 if (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs);
24228 const innerSchema = parseDef(def.innerType._def, {
24229 ...refs,
24230 currentPath: [
24231 ...refs.currentPath,
24232 "anyOf",
24233 "1"
24234 ]
24235 });
24236 return innerSchema ? { anyOf: [{ not: parseAnyDef(refs) }, innerSchema] } : parseAnyDef(refs);
24237 };
24238
24239 //#endregion
24240 //#region node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
24241 var parsePipelineDef = (def, refs) => {
24242 if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs);
24243 else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs);
24244 const a = parseDef(def.in._def, {
24245 ...refs,
24246 currentPath: [
24247 ...refs.currentPath,
24248 "allOf",
24249 "0"
24250 ]
24251 });
24252 return { allOf: [a, parseDef(def.out._def, {
24253 ...refs,
24254 currentPath: [
24255 ...refs.currentPath,
24256 "allOf",
24257 a ? "1" : "0"
24258 ]
24259 })].filter((x) => x !== void 0) };
24260 };
24261
24262 //#endregion
24263 //#region node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
24264 function parsePromiseDef(def, refs) {
24265 return parseDef(def.type._def, refs);
24266 }
24267
24268 //#endregion
24269 //#region node_modules/zod-to-json-schema/dist/esm/parsers/set.js
24270 function parseSetDef(def, refs) {
24271 const schema = {
24272 type: "array",
24273 uniqueItems: true,
24274 items: parseDef(def.valueType._def, {
24275 ...refs,
24276 currentPath: [...refs.currentPath, "items"]
24277 })
24278 };
24279 if (def.minSize) setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
24280 if (def.maxSize) setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
24281 return schema;
24282 }
24283
24284 //#endregion
24285 //#region node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
24286 function parseTupleDef(def, refs) {
24287 if (def.rest) return {
24288 type: "array",
24289 minItems: def.items.length,
24290 items: def.items.map((x, i) => parseDef(x._def, {
24291 ...refs,
24292 currentPath: [
24293 ...refs.currentPath,
24294 "items",
24295 `${i}`
24296 ]
24297 })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
24298 additionalItems: parseDef(def.rest._def, {
24299 ...refs,
24300 currentPath: [...refs.currentPath, "additionalItems"]
24301 })
24302 };
24303 else return {
24304 type: "array",
24305 minItems: def.items.length,
24306 maxItems: def.items.length,
24307 items: def.items.map((x, i) => parseDef(x._def, {
24308 ...refs,
24309 currentPath: [
24310 ...refs.currentPath,
24311 "items",
24312 `${i}`
24313 ]
24314 })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
24315 };
24316 }
24317
24318 //#endregion
24319 //#region node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
24320 function parseUndefinedDef(refs) {
24321 return { not: parseAnyDef(refs) };
24322 }
24323
24324 //#endregion
24325 //#region node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
24326 function parseUnknownDef(refs) {
24327 return parseAnyDef(refs);
24328 }
24329
24330 //#endregion
24331 //#region node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
24332 var parseReadonlyDef = (def, refs) => {
24333 return parseDef(def.innerType._def, refs);
24334 };
24335
24336 //#endregion
24337 //#region node_modules/zod-to-json-schema/dist/esm/selectParser.js
24338 var selectParser = (def, typeName, refs) => {
24339 switch (typeName) {
24340 case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);
24341 case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs);
24342 case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);
24343 case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs);
24344 case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();
24345 case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);
24346 case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(refs);
24347 case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs);
24348 case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);
24349 case ZodFirstPartyTypeKind.ZodUnion:
24350 case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);
24351 case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);
24352 case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);
24353 case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);
24354 case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs);
24355 case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);
24356 case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);
24357 case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);
24358 case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);
24359 case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);
24360 case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);
24361 case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
24362 case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);
24363 case ZodFirstPartyTypeKind.ZodNaN:
24364 case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(refs);
24365 case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);
24366 case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(refs);
24367 case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(refs);
24368 case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);
24369 case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);
24370 case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);
24371 case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);
24372 case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);
24373 case ZodFirstPartyTypeKind.ZodFunction:
24374 case ZodFirstPartyTypeKind.ZodVoid:
24375 case ZodFirstPartyTypeKind.ZodSymbol: return;
24376 default:
24377 /* c8 ignore next */
24378 return ((_) => void 0)(typeName);
24379 }
24380 };
24381
24382 //#endregion
24383 //#region node_modules/zod-to-json-schema/dist/esm/parseDef.js
24384 function parseDef(def, refs, forceResolution = false) {
24385 const seenItem = refs.seen.get(def);
24386 if (refs.override) {
24387 const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
24388 if (overrideResult !== ignoreOverride) return overrideResult;
24389 }
24390 if (seenItem && !forceResolution) {
24391 const seenSchema = get$ref(seenItem, refs);
24392 if (seenSchema !== void 0) return seenSchema;
24393 }
24394 const newItem = {
24395 def,
24396 path: refs.currentPath,
24397 jsonSchema: void 0
24398 };
24399 refs.seen.set(def, newItem);
24400 const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
24401 const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
24402 if (jsonSchema) addMeta(def, refs, jsonSchema);
24403 if (refs.postProcess) {
24404 const postProcessResult = refs.postProcess(jsonSchema, def, refs);
24405 newItem.jsonSchema = jsonSchema;
24406 return postProcessResult;
24407 }
24408 newItem.jsonSchema = jsonSchema;
24409 return jsonSchema;
24410 }
24411 var get$ref = (item, refs) => {
24412 switch (refs.$refStrategy) {
24413 case "root": return { $ref: item.path.join("/") };
24414 case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) };
24415 case "none":
24416 case "seen":
24417 if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
24418 console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
24419 return parseAnyDef(refs);
24420 }
24421 return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;
24422 }
24423 };
24424 var addMeta = (def, refs, jsonSchema) => {
24425 if (def.description) {
24426 jsonSchema.description = def.description;
24427 if (refs.markdownDescription) jsonSchema.markdownDescription = def.description;
24428 }
24429 return jsonSchema;
24430 };
24431
24432 //#endregion
24433 //#region node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
24434 var zodToJsonSchema = (schema, options) => {
24435 const refs = getRefs(options);
24436 let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({
24437 ...acc,
24438 [name]: parseDef(schema._def, {
24439 ...refs,
24440 currentPath: [
24441 ...refs.basePath,
24442 refs.definitionPath,
24443 name
24444 ]
24445 }, true) ?? parseAnyDef(refs)
24446 }), {}) : void 0;
24447 const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
24448 const main = parseDef(schema._def, name === void 0 ? refs : {
24449 ...refs,
24450 currentPath: [
24451 ...refs.basePath,
24452 refs.definitionPath,
24453 name
24454 ]
24455 }, false) ?? parseAnyDef(refs);
24456 const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
24457 if (title !== void 0) main.title = title;
24458 if (refs.flags.hasReferencedOpenAiAnyType) {
24459 if (!definitions) definitions = {};
24460 if (!definitions[refs.openAiAnyTypeName]) definitions[refs.openAiAnyTypeName] = {
24461 type: [
24462 "string",
24463 "number",
24464 "integer",
24465 "boolean",
24466 "array",
24467 "null"
24468 ],
24469 items: { $ref: refs.$refStrategy === "relative" ? "1" : [
24470 ...refs.basePath,
24471 refs.definitionPath,
24472 refs.openAiAnyTypeName
24473 ].join("/") }
24474 };
24475 }
24476 const combined = name === void 0 ? definitions ? {
24477 ...main,
24478 [refs.definitionPath]: definitions
24479 } : main : {
24480 $ref: [
24481 ...refs.$refStrategy === "relative" ? [] : refs.basePath,
24482 refs.definitionPath,
24483 name
24484 ].join("/"),
24485 [refs.definitionPath]: {
24486 ...definitions,
24487 [name]: main
24488 }
24489 };
24490 if (refs.target === "jsonSchema7") combined.$schema = "http://json-schema.org/draft-07/schema#";
24491 else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
24492 if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
24493 return combined;
24494 };
24495
24496 //#endregion
24497 //#region packages/packages/libs/editor-mcp/src/utils/register-model-context-tool.ts
24498 async function registerModelContextTool(registerTool, tool) {
24499 try {
24500 await Promise.resolve(registerTool(tool));
24501 } catch (error) {
24502 console.error("Tool registration failed:", error);
24503 }
24504 }
24505
24506 //#endregion
24507 //#region packages/packages/libs/editor-mcp/src/adapters/web-mcp-adapter.ts
24508 var __defProp$1 = Object.defineProperty;
24509 var __defNormalProp$1 = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp$1(obj, key, {
24510 enumerable: true,
24511 configurable: true,
24512 writable: true,
24513 value
24514 }) : obj[key] = value, "__defNormalProp");
24515 var __publicField$1 = /* @__PURE__ */ __name((obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value), "__publicField");
24516 var WebMCPAdapter = class {
24517 constructor(ctx) {
24518 __publicField$1(this, "ctx", ctx);
24519 __publicField$1(this, "registeredToolNames", /* @__PURE__ */ new Set());
24520 __publicField$1(this, "resourceEntries", []);
24521 __publicField$1(this, "activated", false);
24522 }
24523 activate() {
24524 if (this.activated) return Promise.resolve();
24525 this.activated = true;
24526 return registerModelContextTool(this.ctx.registerTool, {
24527 name: "editor-resource-getter",
24528 description: "Get an editor resource by URI, or search for available resources by partial URI. Pass a full URI to retrieve content, or a partial string to discover matching patterns.",
24529 inputSchema: {
24530 type: "object",
24531 properties: { uri: {
24532 type: "string",
24533 description: "A full resource URI (e.g. elementor://style/best-practices) or a partial string to search across available resource patterns."
24534 } },
24535 required: ["uri"]
24536 },
24537 execute: async (params) => {
24538 const query = params.uri;
24539 const entries = this.resourceEntries;
24540 if (entries.length === 0) return "No resources are registered yet.";
24541 for (const entry of entries) {
24542 const variables = entry.match(query);
24543 if (variables !== null) {
24544 let resourceUrl;
24545 try {
24546 resourceUrl = new URL(query);
24547 } catch {
24548 return `Invalid URI '${query}'. Provide a valid resource URI or a partial string to search patterns.`;
24549 }
24550 const result = await entry.handler(resourceUrl, variables);
24551 return result.contents?.[0]?.text ?? JSON.stringify(result);
24552 }
24553 }
24554 const matches = entries.map((e) => e.pattern).filter((pattern) => pattern.includes(query));
24555 if (matches.length > 0) return `Found ${matches.length} matching resource pattern(s):
24556 ${matches.join("\n")}
24557
24558 Provide a full URI to retrieve the resource content.`;
24559 const available = entries.map((e) => e.pattern).join("\n");
24560 throw new Error(`No resource matched '${query}'.
24561
24562 Available patterns:
24563 ${available}`);
24564 }
24565 });
24566 }
24567 onToolRegistered(tool, extraData) {
24568 let jsonSchema;
24569 try {
24570 jsonSchema = zodToJsonSchema(_elementor_schema.z.object(tool.inputSchema));
24571 } catch {
24572 jsonSchema = tool.inputSchema;
24573 }
24574 if (this.registeredToolNames.has(tool.name)) {
24575 this.ctx.unregisterTool?.(tool.name);
24576 this.registeredToolNames.delete(tool.name);
24577 }
24578 let resourcesDescription = "";
24579 if (extraData) {
24580 if (extraData.resources?.length > 0) resourcesDescription += `#Resources:
24581 ${extraData.resources?.join("\n")}
24582
24583 `;
24584 if (extraData.requiredResources?.length > 0) resourcesDescription += `#Required Resources:
24585 ${extraData.requiredResources?.join("\n")}
24586
24587 `;
24588 resourcesDescription += `To read resources, use editor-resource-getter tool.
24589
24590 `;
24591 }
24592 registerModelContextTool(this.ctx.registerTool, {
24593 name: tool.name,
24594 description: `${resourcesDescription}${tool.description}`,
24595 inputSchema: jsonSchema,
24596 execute: tool.execute
24597 }).then(() => {
24598 this.registeredToolNames.add(tool.name);
24599 });
24600 }
24601 onResourceRegistered(_name, uriOrTemplate, handler) {
24602 if (typeof uriOrTemplate === "string") this.resourceEntries.push({
24603 pattern: uriOrTemplate,
24604 match: (uri) => uri === uriOrTemplate ? {} : null,
24605 handler
24606 });
24607 else {
24608 const template = uriOrTemplate.uriTemplate;
24609 this.resourceEntries.push({
24610 pattern: template.toString(),
24611 match: (uri) => template.match(uri),
24612 handler
24613 });
24614 }
24615 }
24616 sendResourceUpdated() {}
24617 };
24618
24619 //#endregion
24620 //#region packages/packages/libs/editor-mcp/src/angie-annotations.ts
24621 var ANGIE_MODEL_PREFERENCES = "angie/modelPreferences";
24622 var ANGIE_REQUIRED_RESOURCES = "angie/requiredResources";
24623 function createDefaultModelPreferences() {
24624 return { hints: [{ name: "claude-sonnet-4-6" }] };
24625 }
24626
24627 //#endregion
24628 //#region packages/packages/libs/editor-mcp/src/test-utils/mock-mcp-registry.ts
24629 var mock = new Proxy({}, { get: () => {
24630 function mockedFn(..._) {}
24631 return mockedFn;
24632 } });
24633 var mockMcpRegistry = () => {
24634 return {
24635 resource: async () => {},
24636 sendResourceUpdated: () => {},
24637 addTool: () => {},
24638 setMCPDescription: () => {},
24639 mcpServer: mock
24640 };
24641 };
24642
24643 //#endregion
24644 //#region packages/packages/libs/editor-mcp/src/utils/get-model-context.ts
24645 function bindModelContextMethods(host) {
24646 return {
24647 registerTool: host.registerTool.bind(host),
24648 unregisterTool: host.unregisterTool ? host.unregisterTool.bind(host) : void 0
24649 };
24650 }
24651 function getModelContext() {
24652 const documentModelContext = typeof document !== "undefined" ? document.modelContext : void 0;
24653 if (documentModelContext?.registerTool) return bindModelContextMethods(documentModelContext);
24654 const navigatorModelContext = typeof navigator !== "undefined" ? navigator.modelContext : void 0;
24655 if (navigatorModelContext?.registerTool) return bindModelContextMethods(navigatorModelContext);
24656 }
24657
24658 //#endregion
24659 //#region packages/packages/libs/editor-mcp/src/utils/merge-required-resources.ts
24660 var mergeRequiredResources = (toolResources, serverDocsUri) => {
24661 if (!serverDocsUri) return toolResources;
24662 if (toolResources?.some((r) => r.uri === serverDocsUri)) return toolResources;
24663 return [...toolResources ?? [], {
24664 uri: serverDocsUri,
24665 description: "Server docs"
24666 }];
24667 };
24668
24669 //#endregion
24670 //#region packages/packages/libs/editor-mcp/src/utils/create-simple-resource-handler.ts
24671 var createSimpleResourceHandler = (text) => async (uri) => ({ contents: [{
24672 uri: uri.href,
24673 mimeType: "text/plain",
24674 text
24675 }] });
24676
24677 //#endregion
24678 //#region packages/packages/libs/editor-mcp/src/utils/register-server-docs-resource.ts
24679 var registerServerDocsResource = (server, namespace, title, docs, onRegistered) => {
24680 const uri = `elementor://${namespace}/server-docs`;
24681 const name = `${namespace}-server-docs`;
24682 const handler = createSimpleResourceHandler(docs);
24683 server.registerResource(name, uri, {
24684 title: `${title} server docs`,
24685 description: "Full MCP documentation (lazy-loaded)",
24686 mimeType: "text/plain"
24687 }, handler);
24688 onRegistered(name, uri, handler);
24689 };
24690
24691 //#endregion
24692 //#region packages/packages/libs/editor-mcp/src/mcp-registry.ts
24693 var mcpRegistry = {};
24694 var mcpDescriptions = {};
24695 var isMcpRegistrationActivated = typeof globalThis.jest !== "undefined";
24696 var registrationAdapters = [];
24697 var bufferedTools = [];
24698 var bufferedResources = [];
24699 var resolveReady;
24700 var readyPromise = new Promise((resolve) => {
24701 resolveReady = resolve;
24702 });
24703 var registerMcpAdapter = (adapter) => {
24704 registrationAdapters.push(adapter);
24705 for (const tool of bufferedTools) try {
24706 adapter.onToolRegistered(tool[0], tool[1]);
24707 } catch {}
24708 for (const resource of bufferedResources) try {
24709 adapter.onResourceRegistered(...resource);
24710 } catch {}
24711 };
24712 var signalMcpReady = () => {
24713 resolveReady();
24714 };
24715 var createAndRegisterAdapters = async () => {
24716 const modelContext = getModelContext();
24717 if (modelContext) registerMcpAdapter(new WebMCPAdapter(modelContext));
24718 if (isAngieAvailable()) registerMcpAdapter(new AngieMcpAdapter(getSDK(), getRegisteredMcpServers));
24719 await Promise.all(registrationAdapters.map((adapter) => adapter.activate()));
24720 };
24721 function callAdapters(fn) {
24722 for (const adapter of registrationAdapters) try {
24723 fn(adapter);
24724 } catch {}
24725 }
24726 var registerMcp = (mcp, name) => {
24727 const mcpName = isAlphabet(name);
24728 mcpRegistry[mcpName] = mcp;
24729 };
24730 var getRegisteredMcpServers = () => {
24731 return Object.entries(mcpRegistry).map(([key, server]) => [
24732 key,
24733 server,
24734 mcpDescriptions[key] || key
24735 ]);
24736 };
24737 var isAlphabet = (str) => {
24738 if (!(!!str && /^[a-z_]+$/.test(str))) throw new Error("Not alphabet");
24739 return str;
24740 };
24741 var getMCPByDomain = (namespace, options) => {
24742 const mcpName = `editor-${isAlphabet(namespace)}`;
24743 const title = toMCPTitle(namespace);
24744 if (typeof globalThis.jest !== "undefined") return mockMcpRegistry();
24745 if (!mcpRegistry[namespace]) {
24746 mcpRegistry[namespace] = new McpServer({
24747 name: mcpName,
24748 title,
24749 version: "1.0.0"
24750 }, {
24751 instructions: options?.instructions,
24752 capabilities: { resources: { subscribe: true } }
24753 });
24754 if (options?.docs) registerServerDocsResource(mcpRegistry[namespace], namespace, title, options.docs, (...args) => {
24755 bufferedResources.push(args);
24756 callAdapters((adapter) => adapter.onResourceRegistered(...args));
24757 });
24758 }
24759 const mcpServer = mcpRegistry[namespace];
24760 const { addTool } = createToolRegistry(mcpServer, mcpName, options?.docs ? `elementor://${namespace}/server-docs` : void 0);
24761 return {
24762 waitForReady: () => readyPromise,
24763 resource: async (...args) => {
24764 const [name, uriOrTemplate, ...rest] = args;
24765 const resourceArgs = [
24766 name,
24767 uriOrTemplate,
24768 rest[rest.length - 1]
24769 ];
24770 bufferedResources.push(resourceArgs);
24771 callAdapters((adapter) => adapter.onResourceRegistered(...resourceArgs));
24772 return mcpServer.registerResource(...args);
24773 },
24774 sendResourceUpdated: (...args) => {
24775 callAdapters((adapter) => adapter.sendResourceUpdated({ uri: args[0].uri }));
24776 return Promise.resolve(mcpServer.server.sendResourceUpdated(...args)).catch((error) => {
24777 if (error?.message?.includes("Not connected")) return;
24778 if (error?.message?.includes("does not support notifying about resources")) return;
24779 throw error;
24780 });
24781 },
24782 addTool,
24783 setMCPDescription: (description) => {
24784 mcpDescriptions[namespace] = description;
24785 }
24786 };
24787 };
24788 function createToolRegistry(server, serverName, serverDocsUri) {
24789 function addTool(opts) {
24790 const outputSchema = opts.outputSchema;
24791 if (outputSchema) Object.assign(outputSchema, outputSchema.errors ?? { errors: _elementor_schema.z.string().optional().describe("Error message if the tool failed") });
24792 const inputSchema = opts.schema ? opts.schema : {};
24793 const toolCallback = async function(args, extra) {
24794 try {
24795 const invocationResult = await opts.handler(opts.schema ? args : {}, extra);
24796 return { content: [{
24797 type: "text",
24798 text: typeof invocationResult === "string" ? invocationResult : JSON.stringify(invocationResult)
24799 }] };
24800 } catch (error) {
24801 return {
24802 isError: true,
24803 structuredContent: { errors: error.message || "Unknown error" },
24804 content: [{
24805 type: "text",
24806 text: (error.message || "Unknown error") + JSON.stringify(error.response?.data || error)
24807 }]
24808 };
24809 }
24810 };
24811 const annotations = {
24812 destructiveHint: opts.isDestructive,
24813 readOnlyHint: opts.isDestructive ? false : void 0,
24814 title: opts.name
24815 };
24816 const mergedResources = mergeRequiredResources(opts.requiredResources, serverDocsUri);
24817 const angieAnnotations = {
24818 [ANGIE_MODEL_PREFERENCES]: opts.modelPreferences ?? createDefaultModelPreferences(),
24819 [ANGIE_REQUIRED_RESOURCES]: mergedResources
24820 };
24821 server.registerTool(opts.name, {
24822 description: opts.description,
24823 inputSchema,
24824 title: opts.name,
24825 annotations,
24826 _meta: angieAnnotations
24827 }, toolCallback);
24828 const toolDescriptor = {
24829 name: opts.name,
24830 description: opts.description,
24831 inputSchema,
24832 execute: (params) => toolCallback(params, {})
24833 };
24834 const extraData = {
24835 resources: [`Server resource name: ${serverName}, Required to fetch!`],
24836 requiredResources: mergedResources?.map((resource) => resource.uri) ?? []
24837 };
24838 bufferedTools.push([toolDescriptor, extraData]);
24839 callAdapters((adapter) => adapter.onToolRegistered(toolDescriptor, extraData));
24840 if (isMcpRegistrationActivated) server.sendToolListChanged();
24841 }
24842 return { addTool };
24843 }
24844
24845 //#endregion
24846 //#region packages/packages/libs/editor-mcp/src/sampler.ts
24847 var DEFAULT_OPTS = {
24848 maxTokens: 1e4,
24849 modelPreferences: "openai",
24850 model: "gpt-4o"
24851 };
24852 var DEFAULT_STRUCTURED_OUTPUT = {
24853 type: "object",
24854 properties: { content: {
24855 type: "string",
24856 description: "Result"
24857 } },
24858 required: ["content"],
24859 additionalProperties: false
24860 };
24861 var createSampler = (server, opts = DEFAULT_OPTS) => {
24862 const { maxTokens = 1e3, modelPreferences = "openai", model = "gpt-4o" } = opts;
24863 const exec = async (payload) => {
24864 const systemPromptObject = { ...payload.systemPrompt ? { systemPrompt: payload.systemPrompt } : {} };
24865 const requestParams = payload.requestParams || {};
24866 return (await server.sendRequest({
24867 method: "sampling/createMessage",
24868 params: {
24869 ...requestParams,
24870 maxTokens,
24871 modelPreferences: { hints: [{ name: modelPreferences }] },
24872 metadata: {
24873 model,
24874 ...systemPromptObject,
24875 structured_output: payload.structuredOutput || DEFAULT_STRUCTURED_OUTPUT
24876 },
24877 messages: payload.messages
24878 }
24879 }, SamplingMessageSchema)).content;
24880 };
24881 return exec;
24882 };
24883
24884 //#endregion
24885 //#region packages/packages/libs/editor-mcp/src/utils/prompt-builder.ts
24886 var __defProp = Object.defineProperty;
24887 var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
24888 enumerable: true,
24889 configurable: true,
24890 writable: true,
24891 value
24892 }) : obj[key] = value;
24893 var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
24894 var ToolPrompts = class {
24895 constructor(name) {
24896 __publicField(this, "name", name);
24897 __publicField(this, "_description", "");
24898 __publicField(this, "_parameters", {});
24899 __publicField(this, "_examples", []);
24900 __publicField(this, "_furtherInstructions", []);
24901 }
24902 description(desc) {
24903 if (typeof desc === "undefined") return this._description;
24904 this._description = desc;
24905 return this;
24906 }
24907 parameter(key, description) {
24908 if (typeof description === "undefined") return this._parameters[key];
24909 this._parameters[key] = `**${key}**:
24910 ${description}`;
24911 return this;
24912 }
24913 instruction(instruction) {
24914 this._furtherInstructions.push(instruction);
24915 return this;
24916 }
24917 example(example) {
24918 this._examples.push(example);
24919 return this;
24920 }
24921 get examples() {
24922 return this._examples.join("\n\n");
24923 }
24924 prompt() {
24925 return `# ${this.name}
24926 # Description
24927 ${this._description}
24928 ${this._parameters.length ? "# Parameters\n" + Object.values(this._parameters).join("\n\n") : ""}
24929 ${this._examples.length ? "# Examples\n" + this.examples : ""}
24930 ${this._furtherInstructions.length ? "# Further Instructions\n" + this._furtherInstructions.join("\n\n") : ""}
24931 `.trim();
24932 }
24933 };
24934 var toolPrompts = (name) => {
24935 return new ToolPrompts(name);
24936 };
24937
24938 //#endregion
24939 //#region packages/packages/libs/editor-mcp/src/utils/get-active-chat-info.ts
24940 var getActiveChatInfo = () => {
24941 const info = localStorage.getItem("angie_active_chat_id");
24942 if (!info) return {
24943 expiresAt: 0,
24944 sessionId: ""
24945 };
24946 const rawData = JSON.parse(info);
24947 return {
24948 expiresAt: rawData.expiresAt,
24949 sessionId: rawData.sessionId
24950 };
24951 };
24952
24953 //#endregion
24954 //#region packages/packages/libs/editor-mcp/src/utils/open-angie-in-ask-mode.ts
24955 var openAngieInAskMode = (prompt) => {
24956 if (!isAngieAvailable()) return;
24957 const angieSidebar = ut();
24958 if (!angieSidebar) return;
24959 pt(angieSidebar, true);
24960 mn(w.ASK);
24961 if (prompt) window.location.hash = `angie-prompt=${encodeURIComponent(prompt)}`;
24962 };
24963
24964 //#endregion
24965 //#region packages/packages/libs/editor-mcp/src/utils/send-prompt-to-angie.ts
24966 var sendPromptToAngie = (prompt) => {
24967 const angieSidebar = ut();
24968 if (!angieSidebar) return;
24969 pt(angieSidebar, true);
24970 if (!prompt) return;
24971 window.location.hash = `angie-prompt=${encodeURIComponent(prompt)}`;
24972 };
24973
24974 //#endregion
24975 //#region packages/packages/libs/editor-mcp/src/utils/redirect-to-installation.ts
24976 var ANGIE_INSTALL_URL = "/wp-admin/plugin-install.php?s=angie&tab=search&type=term";
24977 var redirectToInstallation = (prompt) => {
24978 Mt(window.location.href, prompt);
24979 window.location.href = ANGIE_INSTALL_URL;
24980 };
24981
24982 //#endregion
24983 //#region packages/packages/libs/editor-mcp/src/utils/redirect-to-app-admin.ts
24984 var ANGIE_APP_URL = "/wp-admin/admin.php?page=angie-app";
24985 var redirectToAppAdmin = (prompt) => {
24986 Mt(window.location.href, prompt);
24987 At(vt);
24988 window.location.href = ANGIE_APP_URL;
24989 };
24990
24991 //#endregion
24992 //#region packages/packages/libs/editor-mcp/src/utils/install-angie-plugin.ts
24993 var ANGIE_SLUG = "angie";
24994 var isPluginErrorResponse = (response) => {
24995 return typeof response === "object" && response !== null && "code" in response && "message" in response;
24996 };
24997 var activatePlugin = async (pluginPath) => {
24998 return (0, _wordpress_api_fetch.default)({
24999 path: `/wp/v2/plugins/${pluginPath}`,
25000 method: "POST",
25001 data: { status: "active" }
25002 });
25003 };
25004 var installPlugin = async () => {
25005 try {
25006 return await (0, _wordpress_api_fetch.default)({
25007 path: "/wp/v2/plugins",
25008 method: "POST",
25009 data: {
25010 slug: ANGIE_SLUG,
25011 status: "active"
25012 }
25013 });
25014 } catch (error) {
25015 if (isPluginErrorResponse(error) && error.code === "folder_exists") return activatePlugin(`${ANGIE_SLUG}/${ANGIE_SLUG}`);
25016 throw error;
25017 }
25018 };
25019 var installAngiePlugin = async () => {
25020 try {
25021 await installPlugin();
25022 return { success: true };
25023 } catch (error) {
25024 if (isPluginErrorResponse(error)) return {
25025 success: false,
25026 error: error.message,
25027 code: error.code
25028 };
25029 return {
25030 success: false,
25031 error: "Unknown error occurred"
25032 };
25033 }
25034 };
25035
25036 //#endregion
25037 //#region packages/packages/libs/editor-mcp/src/utils/save-angie-consent.ts
25038 var saveAngieConsent = async () => {
25039 await (0, _wordpress_api_fetch.default)({
25040 path: "/elementor/v1/angie/consent",
25041 method: "POST"
25042 });
25043 };
25044
25045 //#endregion
25046 //#region packages/packages/libs/editor-mcp/src/init.ts
25047 var isInitialized = false;
25048 async function startMCPServer() {
25049 if (isInitialized) return;
25050 isInitialized = true;
25051 try {
25052 await createAndRegisterAdapters();
25053 } catch (error) {
25054 console.error("MCP adapter activation failed:", error);
25055 } finally {
25056 signalMcpReady();
25057 }
25058 }
25059 if (typeof document !== "undefined") document.addEventListener("DOMContentLoaded", () => void startMCPServer(), { once: true });
25060 else startMCPServer();
25061
25062 //#endregion
25063 //#region packages/packages/libs/editor-mcp/src/events/mcp-styles-applied-event.ts
25064 var MCP_STYLES_APPLIED_EVENT = "elementor/mcp/styles-applied";
25065 function dispatchMcpStylesAppliedEvent(payload) {
25066 window.dispatchEvent(new CustomEvent(MCP_STYLES_APPLIED_EVENT, { detail: payload }));
25067 }
25068
25069 //#endregion
25070 //#region packages/packages/libs/editor-mcp/src/index.ts
25071 var src_exports = /* @__PURE__ */ __exportAll({
25072 ANGIE_MODEL_PREFERENCES: () => ANGIE_MODEL_PREFERENCES,
25073 ANGIE_REQUIRED_RESOURCES: () => ANGIE_REQUIRED_RESOURCES,
25074 AngieMessageEvenetType: () => m,
25075 MCP_STYLES_APPLIED_EVENT: () => MCP_STYLES_APPLIED_EVENT,
25076 McpServer: () => McpServer,
25077 ResourceTemplate: () => ResourceTemplate,
25078 SamplingMessageSchema: () => SamplingMessageSchema,
25079 createAndRegisterAdapters: () => createAndRegisterAdapters,
25080 createSampler: () => createSampler,
25081 dispatchMcpStylesAppliedEvent: () => dispatchMcpStylesAppliedEvent,
25082 getActiveChatInfo: () => getActiveChatInfo,
25083 getAngieIframe: () => ut,
25084 getAngieSdk: () => getAngieSdk,
25085 getMCPByDomain: () => getMCPByDomain,
25086 getRegisteredMcpServers: () => getRegisteredMcpServers,
25087 installAngiePlugin: () => installAngiePlugin,
25088 isAngieAvailable: () => isAngieAvailable,
25089 isAngieSidebarOpen: () => isAngieSidebarOpen,
25090 openAngieInAskMode: () => openAngieInAskMode,
25091 redirectToAppAdmin: () => redirectToAppAdmin,
25092 redirectToInstallation: () => redirectToInstallation,
25093 registerMcp: () => registerMcp,
25094 registerMcpAdapter: () => registerMcpAdapter,
25095 saveAngieConsent: () => saveAngieConsent,
25096 sendPromptToAngie: () => sendPromptToAngie,
25097 signalMcpReady: () => signalMcpReady,
25098 startMCPServer: () => startMCPServer,
25099 toolPrompts: () => toolPrompts
25100 });
25101 var getAngieSdk = () => getSDK();
25102
25103 //#endregion
25104 //#region \0elementor-package-library-entry
25105 (window.elementorV2 = window.elementorV2 || {}).editorMcp = src_exports;
25106
25107 //#endregion
25108 })(elementorV2.schema, wp.apiFetch);
25109 window.elementorV2.editorMcp?.init?.();
25110 //# sourceMappingURL=editor-mcp.js.map