@storybook/addon-mcp 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +31 -9
  2. package/dist/preset.js +269 -4313
  3. package/package.json +19 -37
  4. package/preset.js +1 -1
package/dist/preset.js CHANGED
@@ -1,4334 +1,290 @@
1
- import { randomUUID } from 'crypto';
2
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
- import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
- import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
5
- import path from 'path';
6
- import { storyNameFromExport } from 'storybook/internal/csf';
7
- import { logger } from 'storybook/internal/node-logger';
8
- import { telemetry } from 'storybook/internal/telemetry';
1
+ import { McpServer } from "tmcp";
2
+ import { ValibotJsonSchemaAdapter } from "@tmcp/adapter-valibot";
3
+ import { HttpTransport } from "@tmcp/transport-http";
4
+ import path from "node:path";
5
+ import { storyNameFromExport } from "storybook/internal/csf";
6
+ import { logger } from "storybook/internal/node-logger";
7
+ import * as v from "valibot";
8
+ import { telemetry } from "storybook/internal/telemetry";
9
+ import { buffer } from "node:stream/consumers";
9
10
 
10
- var __defProp = Object.defineProperty;
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
-
16
- // package.json
17
- var package_default = {
18
- name: "@storybook/addon-mcp",
19
- version: "0.0.5"};
20
-
21
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
22
- var external_exports = {};
23
- __export(external_exports, {
24
- BRAND: () => BRAND,
25
- DIRTY: () => DIRTY,
26
- EMPTY_PATH: () => EMPTY_PATH,
27
- INVALID: () => INVALID,
28
- NEVER: () => NEVER,
29
- OK: () => OK,
30
- ParseStatus: () => ParseStatus,
31
- Schema: () => ZodType,
32
- ZodAny: () => ZodAny,
33
- ZodArray: () => ZodArray,
34
- ZodBigInt: () => ZodBigInt,
35
- ZodBoolean: () => ZodBoolean,
36
- ZodBranded: () => ZodBranded,
37
- ZodCatch: () => ZodCatch,
38
- ZodDate: () => ZodDate,
39
- ZodDefault: () => ZodDefault,
40
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
41
- ZodEffects: () => ZodEffects,
42
- ZodEnum: () => ZodEnum,
43
- ZodError: () => ZodError,
44
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
45
- ZodFunction: () => ZodFunction,
46
- ZodIntersection: () => ZodIntersection,
47
- ZodIssueCode: () => ZodIssueCode,
48
- ZodLazy: () => ZodLazy,
49
- ZodLiteral: () => ZodLiteral,
50
- ZodMap: () => ZodMap,
51
- ZodNaN: () => ZodNaN,
52
- ZodNativeEnum: () => ZodNativeEnum,
53
- ZodNever: () => ZodNever,
54
- ZodNull: () => ZodNull,
55
- ZodNullable: () => ZodNullable,
56
- ZodNumber: () => ZodNumber,
57
- ZodObject: () => ZodObject,
58
- ZodOptional: () => ZodOptional,
59
- ZodParsedType: () => ZodParsedType,
60
- ZodPipeline: () => ZodPipeline,
61
- ZodPromise: () => ZodPromise,
62
- ZodReadonly: () => ZodReadonly,
63
- ZodRecord: () => ZodRecord,
64
- ZodSchema: () => ZodType,
65
- ZodSet: () => ZodSet,
66
- ZodString: () => ZodString,
67
- ZodSymbol: () => ZodSymbol,
68
- ZodTransformer: () => ZodEffects,
69
- ZodTuple: () => ZodTuple,
70
- ZodType: () => ZodType,
71
- ZodUndefined: () => ZodUndefined,
72
- ZodUnion: () => ZodUnion,
73
- ZodUnknown: () => ZodUnknown,
74
- ZodVoid: () => ZodVoid,
75
- addIssueToContext: () => addIssueToContext,
76
- any: () => anyType,
77
- array: () => arrayType,
78
- bigint: () => bigIntType,
79
- boolean: () => booleanType,
80
- coerce: () => coerce,
81
- custom: () => custom,
82
- date: () => dateType,
83
- datetimeRegex: () => datetimeRegex,
84
- defaultErrorMap: () => en_default,
85
- discriminatedUnion: () => discriminatedUnionType,
86
- effect: () => effectsType,
87
- enum: () => enumType,
88
- function: () => functionType,
89
- getErrorMap: () => getErrorMap,
90
- getParsedType: () => getParsedType,
91
- instanceof: () => instanceOfType,
92
- intersection: () => intersectionType,
93
- isAborted: () => isAborted,
94
- isAsync: () => isAsync,
95
- isDirty: () => isDirty,
96
- isValid: () => isValid,
97
- late: () => late,
98
- lazy: () => lazyType,
99
- literal: () => literalType,
100
- makeIssue: () => makeIssue,
101
- map: () => mapType,
102
- nan: () => nanType,
103
- nativeEnum: () => nativeEnumType,
104
- never: () => neverType,
105
- null: () => nullType,
106
- nullable: () => nullableType,
107
- number: () => numberType,
108
- object: () => objectType,
109
- objectUtil: () => objectUtil,
110
- oboolean: () => oboolean,
111
- onumber: () => onumber,
112
- optional: () => optionalType,
113
- ostring: () => ostring,
114
- pipeline: () => pipelineType,
115
- preprocess: () => preprocessType,
116
- promise: () => promiseType,
117
- quotelessJson: () => quotelessJson,
118
- record: () => recordType,
119
- set: () => setType,
120
- setErrorMap: () => setErrorMap,
121
- strictObject: () => strictObjectType,
122
- string: () => stringType,
123
- symbol: () => symbolType,
124
- transformer: () => effectsType,
125
- tuple: () => tupleType,
126
- undefined: () => undefinedType,
127
- union: () => unionType,
128
- unknown: () => unknownType,
129
- util: () => util,
130
- void: () => voidType
131
- });
132
-
133
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
134
- var util;
135
- (function(util2) {
136
- util2.assertEqual = (_) => {
137
- };
138
- function assertIs(_arg) {
139
- }
140
- util2.assertIs = assertIs;
141
- function assertNever(_x) {
142
- throw new Error();
143
- }
144
- util2.assertNever = assertNever;
145
- util2.arrayToEnum = (items) => {
146
- const obj = {};
147
- for (const item of items) {
148
- obj[item] = item;
149
- }
150
- return obj;
151
- };
152
- util2.getValidEnumValues = (obj) => {
153
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
154
- const filtered = {};
155
- for (const k of validKeys) {
156
- filtered[k] = obj[k];
157
- }
158
- return util2.objectValues(filtered);
159
- };
160
- util2.objectValues = (obj) => {
161
- return util2.objectKeys(obj).map(function(e) {
162
- return obj[e];
163
- });
164
- };
165
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
166
- const keys = [];
167
- for (const key in object) {
168
- if (Object.prototype.hasOwnProperty.call(object, key)) {
169
- keys.push(key);
170
- }
171
- }
172
- return keys;
173
- };
174
- util2.find = (arr, checker) => {
175
- for (const item of arr) {
176
- if (checker(item))
177
- return item;
178
- }
179
- return void 0;
180
- };
181
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
182
- function joinValues(array, separator = " | ") {
183
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
184
- }
185
- util2.joinValues = joinValues;
186
- util2.jsonStringifyReplacer = (_, value) => {
187
- if (typeof value === "bigint") {
188
- return value.toString();
189
- }
190
- return value;
191
- };
192
- })(util || (util = {}));
193
- var objectUtil;
194
- (function(objectUtil2) {
195
- objectUtil2.mergeShapes = (first, second) => {
196
- return {
197
- ...first,
198
- ...second
199
- // second overwrites first
200
- };
201
- };
202
- })(objectUtil || (objectUtil = {}));
203
- var ZodParsedType = util.arrayToEnum([
204
- "string",
205
- "nan",
206
- "number",
207
- "integer",
208
- "float",
209
- "boolean",
210
- "date",
211
- "bigint",
212
- "symbol",
213
- "function",
214
- "undefined",
215
- "null",
216
- "array",
217
- "object",
218
- "unknown",
219
- "promise",
220
- "void",
221
- "never",
222
- "map",
223
- "set"
224
- ]);
225
- var getParsedType = (data) => {
226
- const t = typeof data;
227
- switch (t) {
228
- case "undefined":
229
- return ZodParsedType.undefined;
230
- case "string":
231
- return ZodParsedType.string;
232
- case "number":
233
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
234
- case "boolean":
235
- return ZodParsedType.boolean;
236
- case "function":
237
- return ZodParsedType.function;
238
- case "bigint":
239
- return ZodParsedType.bigint;
240
- case "symbol":
241
- return ZodParsedType.symbol;
242
- case "object":
243
- if (Array.isArray(data)) {
244
- return ZodParsedType.array;
245
- }
246
- if (data === null) {
247
- return ZodParsedType.null;
248
- }
249
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
250
- return ZodParsedType.promise;
251
- }
252
- if (typeof Map !== "undefined" && data instanceof Map) {
253
- return ZodParsedType.map;
254
- }
255
- if (typeof Set !== "undefined" && data instanceof Set) {
256
- return ZodParsedType.set;
257
- }
258
- if (typeof Date !== "undefined" && data instanceof Date) {
259
- return ZodParsedType.date;
260
- }
261
- return ZodParsedType.object;
262
- default:
263
- return ZodParsedType.unknown;
264
- }
265
- };
266
-
267
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
268
- var ZodIssueCode = util.arrayToEnum([
269
- "invalid_type",
270
- "invalid_literal",
271
- "custom",
272
- "invalid_union",
273
- "invalid_union_discriminator",
274
- "invalid_enum_value",
275
- "unrecognized_keys",
276
- "invalid_arguments",
277
- "invalid_return_type",
278
- "invalid_date",
279
- "invalid_string",
280
- "too_small",
281
- "too_big",
282
- "invalid_intersection_types",
283
- "not_multiple_of",
284
- "not_finite"
285
- ]);
286
- var quotelessJson = (obj) => {
287
- const json = JSON.stringify(obj, null, 2);
288
- return json.replace(/"([^"]+)":/g, "$1:");
289
- };
290
- var ZodError = class _ZodError extends Error {
291
- get errors() {
292
- return this.issues;
293
- }
294
- constructor(issues) {
295
- super();
296
- this.issues = [];
297
- this.addIssue = (sub) => {
298
- this.issues = [...this.issues, sub];
299
- };
300
- this.addIssues = (subs = []) => {
301
- this.issues = [...this.issues, ...subs];
302
- };
303
- const actualProto = new.target.prototype;
304
- if (Object.setPrototypeOf) {
305
- Object.setPrototypeOf(this, actualProto);
306
- } else {
307
- this.__proto__ = actualProto;
308
- }
309
- this.name = "ZodError";
310
- this.issues = issues;
311
- }
312
- format(_mapper) {
313
- const mapper = _mapper || function(issue) {
314
- return issue.message;
315
- };
316
- const fieldErrors = { _errors: [] };
317
- const processError = (error) => {
318
- for (const issue of error.issues) {
319
- if (issue.code === "invalid_union") {
320
- issue.unionErrors.map(processError);
321
- } else if (issue.code === "invalid_return_type") {
322
- processError(issue.returnTypeError);
323
- } else if (issue.code === "invalid_arguments") {
324
- processError(issue.argumentsError);
325
- } else if (issue.path.length === 0) {
326
- fieldErrors._errors.push(mapper(issue));
327
- } else {
328
- let curr = fieldErrors;
329
- let i = 0;
330
- while (i < issue.path.length) {
331
- const el = issue.path[i];
332
- const terminal = i === issue.path.length - 1;
333
- if (!terminal) {
334
- curr[el] = curr[el] || { _errors: [] };
335
- } else {
336
- curr[el] = curr[el] || { _errors: [] };
337
- curr[el]._errors.push(mapper(issue));
338
- }
339
- curr = curr[el];
340
- i++;
341
- }
342
- }
343
- }
344
- };
345
- processError(this);
346
- return fieldErrors;
347
- }
348
- static assert(value) {
349
- if (!(value instanceof _ZodError)) {
350
- throw new Error(`Not a ZodError: ${value}`);
351
- }
352
- }
353
- toString() {
354
- return this.message;
355
- }
356
- get message() {
357
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
358
- }
359
- get isEmpty() {
360
- return this.issues.length === 0;
361
- }
362
- flatten(mapper = (issue) => issue.message) {
363
- const fieldErrors = {};
364
- const formErrors = [];
365
- for (const sub of this.issues) {
366
- if (sub.path.length > 0) {
367
- const firstEl = sub.path[0];
368
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
369
- fieldErrors[firstEl].push(mapper(sub));
370
- } else {
371
- formErrors.push(mapper(sub));
372
- }
373
- }
374
- return { formErrors, fieldErrors };
375
- }
376
- get formErrors() {
377
- return this.flatten();
378
- }
379
- };
380
- ZodError.create = (issues) => {
381
- const error = new ZodError(issues);
382
- return error;
383
- };
11
+ //#region package.json
12
+ var name = "@storybook/addon-mcp";
13
+ var version = "0.0.7";
14
+ var description = "Help agents automatically write and test stories for your UI components";
384
15
 
385
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
386
- var errorMap = (issue, _ctx) => {
387
- let message;
388
- switch (issue.code) {
389
- case ZodIssueCode.invalid_type:
390
- if (issue.received === ZodParsedType.undefined) {
391
- message = "Required";
392
- } else {
393
- message = `Expected ${issue.expected}, received ${issue.received}`;
394
- }
395
- break;
396
- case ZodIssueCode.invalid_literal:
397
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
398
- break;
399
- case ZodIssueCode.unrecognized_keys:
400
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
401
- break;
402
- case ZodIssueCode.invalid_union:
403
- message = `Invalid input`;
404
- break;
405
- case ZodIssueCode.invalid_union_discriminator:
406
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
407
- break;
408
- case ZodIssueCode.invalid_enum_value:
409
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
410
- break;
411
- case ZodIssueCode.invalid_arguments:
412
- message = `Invalid function arguments`;
413
- break;
414
- case ZodIssueCode.invalid_return_type:
415
- message = `Invalid function return type`;
416
- break;
417
- case ZodIssueCode.invalid_date:
418
- message = `Invalid date`;
419
- break;
420
- case ZodIssueCode.invalid_string:
421
- if (typeof issue.validation === "object") {
422
- if ("includes" in issue.validation) {
423
- message = `Invalid input: must include "${issue.validation.includes}"`;
424
- if (typeof issue.validation.position === "number") {
425
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
426
- }
427
- } else if ("startsWith" in issue.validation) {
428
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
429
- } else if ("endsWith" in issue.validation) {
430
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
431
- } else {
432
- util.assertNever(issue.validation);
433
- }
434
- } else if (issue.validation !== "regex") {
435
- message = `Invalid ${issue.validation}`;
436
- } else {
437
- message = "Invalid";
438
- }
439
- break;
440
- case ZodIssueCode.too_small:
441
- if (issue.type === "array")
442
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
443
- else if (issue.type === "string")
444
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
445
- else if (issue.type === "number")
446
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
447
- else if (issue.type === "bigint")
448
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
449
- else if (issue.type === "date")
450
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
451
- else
452
- message = "Invalid input";
453
- break;
454
- case ZodIssueCode.too_big:
455
- if (issue.type === "array")
456
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
457
- else if (issue.type === "string")
458
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
459
- else if (issue.type === "number")
460
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
461
- else if (issue.type === "bigint")
462
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
463
- else if (issue.type === "date")
464
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
465
- else
466
- message = "Invalid input";
467
- break;
468
- case ZodIssueCode.custom:
469
- message = `Invalid input`;
470
- break;
471
- case ZodIssueCode.invalid_intersection_types:
472
- message = `Intersection results could not be merged`;
473
- break;
474
- case ZodIssueCode.not_multiple_of:
475
- message = `Number must be a multiple of ${issue.multipleOf}`;
476
- break;
477
- case ZodIssueCode.not_finite:
478
- message = "Number must be finite";
479
- break;
480
- default:
481
- message = _ctx.defaultError;
482
- util.assertNever(issue);
483
- }
484
- return { message };
485
- };
486
- var en_default = errorMap;
487
-
488
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
489
- var overrideErrorMap = en_default;
490
- function setErrorMap(map) {
491
- overrideErrorMap = map;
492
- }
493
- function getErrorMap() {
494
- return overrideErrorMap;
16
+ //#endregion
17
+ //#region src/telemetry.ts
18
+ async function collectTelemetry({ event, server,...payload }) {
19
+ try {
20
+ return await telemetry("addon-mcp", {
21
+ event,
22
+ mcpSessionId: server.ctx.sessionId,
23
+ clientInfo: server.currentClientInfo(),
24
+ clientCapabilities: server.currentClientCapabilities(),
25
+ ...payload
26
+ });
27
+ } catch (error) {
28
+ logger.debug("Error collecting telemetry:", error);
29
+ }
495
30
  }
496
31
 
497
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
498
- var makeIssue = (params) => {
499
- const { data, path: path2, errorMaps, issueData } = params;
500
- const fullPath = [...path2, ...issueData.path || []];
501
- const fullIssue = {
502
- ...issueData,
503
- path: fullPath
504
- };
505
- if (issueData.message !== void 0) {
506
- return {
507
- ...issueData,
508
- path: fullPath,
509
- message: issueData.message
510
- };
511
- }
512
- let errorMessage = "";
513
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
514
- for (const map of maps) {
515
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
516
- }
517
- return {
518
- ...issueData,
519
- path: fullPath,
520
- message: errorMessage
521
- };
522
- };
523
- var EMPTY_PATH = [];
524
- function addIssueToContext(ctx, issueData) {
525
- const overrideMap = getErrorMap();
526
- const issue = makeIssue({
527
- issueData,
528
- data: ctx.data,
529
- path: ctx.path,
530
- errorMaps: [
531
- ctx.common.contextualErrorMap,
532
- // contextual error map is first priority
533
- ctx.schemaErrorMap,
534
- // then schema-bound map if available
535
- overrideMap,
536
- // then global override map
537
- overrideMap === en_default ? void 0 : en_default
538
- // then global default map
539
- ].filter((x) => !!x)
540
- });
541
- ctx.common.issues.push(issue);
32
+ //#endregion
33
+ //#region src/utils/fetch-story-index.ts
34
+ /**
35
+ * Fetches the Storybook story index from the running Storybook instance.
36
+ *
37
+ * @param origin - The origin URL of the Storybook instance (e.g., http://localhost:6006)
38
+ * @returns A promise that resolves to the StoryIndex
39
+ * @throws If the fetch fails or returns invalid data
40
+ */
41
+ async function fetchStoryIndex(origin$1) {
42
+ const indexUrl = `${origin$1}/index.json`;
43
+ logger.debug("Fetching story index from:", indexUrl);
44
+ const response = await fetch(indexUrl);
45
+ if (!response.ok) throw new Error(`Failed to fetch story index: ${response.status} ${response.statusText}`);
46
+ const index = await response.json();
47
+ logger.debug("Story index entries found:", Object.keys(index.entries).length);
48
+ return index;
542
49
  }
543
- var ParseStatus = class _ParseStatus {
544
- constructor() {
545
- this.value = "valid";
546
- }
547
- dirty() {
548
- if (this.value === "valid")
549
- this.value = "dirty";
550
- }
551
- abort() {
552
- if (this.value !== "aborted")
553
- this.value = "aborted";
554
- }
555
- static mergeArray(status, results) {
556
- const arrayValue = [];
557
- for (const s of results) {
558
- if (s.status === "aborted")
559
- return INVALID;
560
- if (s.status === "dirty")
561
- status.dirty();
562
- arrayValue.push(s.value);
563
- }
564
- return { status: status.value, value: arrayValue };
565
- }
566
- static async mergeObjectAsync(status, pairs) {
567
- const syncPairs = [];
568
- for (const pair of pairs) {
569
- const key = await pair.key;
570
- const value = await pair.value;
571
- syncPairs.push({
572
- key,
573
- value
574
- });
575
- }
576
- return _ParseStatus.mergeObjectSync(status, syncPairs);
577
- }
578
- static mergeObjectSync(status, pairs) {
579
- const finalObject = {};
580
- for (const pair of pairs) {
581
- const { key, value } = pair;
582
- if (key.status === "aborted")
583
- return INVALID;
584
- if (value.status === "aborted")
585
- return INVALID;
586
- if (key.status === "dirty")
587
- status.dirty();
588
- if (value.status === "dirty")
589
- status.dirty();
590
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
591
- finalObject[key.value] = value.value;
592
- }
593
- }
594
- return { status: status.value, value: finalObject };
595
- }
596
- };
597
- var INVALID = Object.freeze({
598
- status: "aborted"
599
- });
600
- var DIRTY = (value) => ({ status: "dirty", value });
601
- var OK = (value) => ({ status: "valid", value });
602
- var isAborted = (x) => x.status === "aborted";
603
- var isDirty = (x) => x.status === "dirty";
604
- var isValid = (x) => x.status === "valid";
605
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
606
50
 
607
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
608
- var errorUtil;
609
- (function(errorUtil2) {
610
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
611
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
612
- })(errorUtil || (errorUtil = {}));
613
-
614
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
615
- var ParseInputLazyPath = class {
616
- constructor(parent, value, path2, key) {
617
- this._cachedPath = [];
618
- this.parent = parent;
619
- this.data = value;
620
- this._path = path2;
621
- this._key = key;
622
- }
623
- get path() {
624
- if (!this._cachedPath.length) {
625
- if (Array.isArray(this._key)) {
626
- this._cachedPath.push(...this._path, ...this._key);
627
- } else {
628
- this._cachedPath.push(...this._path, this._key);
629
- }
630
- }
631
- return this._cachedPath;
632
- }
633
- };
634
- var handleResult = (ctx, result) => {
635
- if (isValid(result)) {
636
- return { success: true, data: result.value };
637
- } else {
638
- if (!ctx.common.issues.length) {
639
- throw new Error("Validation failed but no issues detected.");
640
- }
641
- return {
642
- success: false,
643
- get error() {
644
- if (this._error)
645
- return this._error;
646
- const error = new ZodError(ctx.common.issues);
647
- this._error = error;
648
- return this._error;
649
- }
650
- };
651
- }
652
- };
653
- function processCreateParams(params) {
654
- if (!params)
655
- return {};
656
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
657
- if (errorMap2 && (invalid_type_error || required_error)) {
658
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
659
- }
660
- if (errorMap2)
661
- return { errorMap: errorMap2, description };
662
- const customMap = (iss, ctx) => {
663
- const { message } = params;
664
- if (iss.code === "invalid_enum_value") {
665
- return { message: message ?? ctx.defaultError };
666
- }
667
- if (typeof ctx.data === "undefined") {
668
- return { message: message ?? required_error ?? ctx.defaultError };
669
- }
670
- if (iss.code !== "invalid_type")
671
- return { message: ctx.defaultError };
672
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
673
- };
674
- return { errorMap: customMap, description };
675
- }
676
- var ZodType = class {
677
- get description() {
678
- return this._def.description;
679
- }
680
- _getType(input) {
681
- return getParsedType(input.data);
682
- }
683
- _getOrReturnCtx(input, ctx) {
684
- return ctx || {
685
- common: input.parent.common,
686
- data: input.data,
687
- parsedType: getParsedType(input.data),
688
- schemaErrorMap: this._def.errorMap,
689
- path: input.path,
690
- parent: input.parent
691
- };
692
- }
693
- _processInputParams(input) {
694
- return {
695
- status: new ParseStatus(),
696
- ctx: {
697
- common: input.parent.common,
698
- data: input.data,
699
- parsedType: getParsedType(input.data),
700
- schemaErrorMap: this._def.errorMap,
701
- path: input.path,
702
- parent: input.parent
703
- }
704
- };
705
- }
706
- _parseSync(input) {
707
- const result = this._parse(input);
708
- if (isAsync(result)) {
709
- throw new Error("Synchronous parse encountered promise.");
710
- }
711
- return result;
712
- }
713
- _parseAsync(input) {
714
- const result = this._parse(input);
715
- return Promise.resolve(result);
716
- }
717
- parse(data, params) {
718
- const result = this.safeParse(data, params);
719
- if (result.success)
720
- return result.data;
721
- throw result.error;
722
- }
723
- safeParse(data, params) {
724
- const ctx = {
725
- common: {
726
- issues: [],
727
- async: params?.async ?? false,
728
- contextualErrorMap: params?.errorMap
729
- },
730
- path: params?.path || [],
731
- schemaErrorMap: this._def.errorMap,
732
- parent: null,
733
- data,
734
- parsedType: getParsedType(data)
735
- };
736
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
737
- return handleResult(ctx, result);
738
- }
739
- "~validate"(data) {
740
- const ctx = {
741
- common: {
742
- issues: [],
743
- async: !!this["~standard"].async
744
- },
745
- path: [],
746
- schemaErrorMap: this._def.errorMap,
747
- parent: null,
748
- data,
749
- parsedType: getParsedType(data)
750
- };
751
- if (!this["~standard"].async) {
752
- try {
753
- const result = this._parseSync({ data, path: [], parent: ctx });
754
- return isValid(result) ? {
755
- value: result.value
756
- } : {
757
- issues: ctx.common.issues
758
- };
759
- } catch (err) {
760
- if (err?.message?.toLowerCase()?.includes("encountered")) {
761
- this["~standard"].async = true;
762
- }
763
- ctx.common = {
764
- issues: [],
765
- async: true
766
- };
767
- }
768
- }
769
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
770
- value: result.value
771
- } : {
772
- issues: ctx.common.issues
773
- });
774
- }
775
- async parseAsync(data, params) {
776
- const result = await this.safeParseAsync(data, params);
777
- if (result.success)
778
- return result.data;
779
- throw result.error;
780
- }
781
- async safeParseAsync(data, params) {
782
- const ctx = {
783
- common: {
784
- issues: [],
785
- contextualErrorMap: params?.errorMap,
786
- async: true
787
- },
788
- path: params?.path || [],
789
- schemaErrorMap: this._def.errorMap,
790
- parent: null,
791
- data,
792
- parsedType: getParsedType(data)
793
- };
794
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
795
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
796
- return handleResult(ctx, result);
797
- }
798
- refine(check, message) {
799
- const getIssueProperties = (val) => {
800
- if (typeof message === "string" || typeof message === "undefined") {
801
- return { message };
802
- } else if (typeof message === "function") {
803
- return message(val);
804
- } else {
805
- return message;
806
- }
807
- };
808
- return this._refinement((val, ctx) => {
809
- const result = check(val);
810
- const setError = () => ctx.addIssue({
811
- code: ZodIssueCode.custom,
812
- ...getIssueProperties(val)
813
- });
814
- if (typeof Promise !== "undefined" && result instanceof Promise) {
815
- return result.then((data) => {
816
- if (!data) {
817
- setError();
818
- return false;
819
- } else {
820
- return true;
821
- }
822
- });
823
- }
824
- if (!result) {
825
- setError();
826
- return false;
827
- } else {
828
- return true;
829
- }
830
- });
831
- }
832
- refinement(check, refinementData) {
833
- return this._refinement((val, ctx) => {
834
- if (!check(val)) {
835
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
836
- return false;
837
- } else {
838
- return true;
839
- }
840
- });
841
- }
842
- _refinement(refinement) {
843
- return new ZodEffects({
844
- schema: this,
845
- typeName: ZodFirstPartyTypeKind.ZodEffects,
846
- effect: { type: "refinement", refinement }
847
- });
848
- }
849
- superRefine(refinement) {
850
- return this._refinement(refinement);
851
- }
852
- constructor(def) {
853
- this.spa = this.safeParseAsync;
854
- this._def = def;
855
- this.parse = this.parse.bind(this);
856
- this.safeParse = this.safeParse.bind(this);
857
- this.parseAsync = this.parseAsync.bind(this);
858
- this.safeParseAsync = this.safeParseAsync.bind(this);
859
- this.spa = this.spa.bind(this);
860
- this.refine = this.refine.bind(this);
861
- this.refinement = this.refinement.bind(this);
862
- this.superRefine = this.superRefine.bind(this);
863
- this.optional = this.optional.bind(this);
864
- this.nullable = this.nullable.bind(this);
865
- this.nullish = this.nullish.bind(this);
866
- this.array = this.array.bind(this);
867
- this.promise = this.promise.bind(this);
868
- this.or = this.or.bind(this);
869
- this.and = this.and.bind(this);
870
- this.transform = this.transform.bind(this);
871
- this.brand = this.brand.bind(this);
872
- this.default = this.default.bind(this);
873
- this.catch = this.catch.bind(this);
874
- this.describe = this.describe.bind(this);
875
- this.pipe = this.pipe.bind(this);
876
- this.readonly = this.readonly.bind(this);
877
- this.isNullable = this.isNullable.bind(this);
878
- this.isOptional = this.isOptional.bind(this);
879
- this["~standard"] = {
880
- version: 1,
881
- vendor: "zod",
882
- validate: (data) => this["~validate"](data)
883
- };
884
- }
885
- optional() {
886
- return ZodOptional.create(this, this._def);
887
- }
888
- nullable() {
889
- return ZodNullable.create(this, this._def);
890
- }
891
- nullish() {
892
- return this.nullable().optional();
893
- }
894
- array() {
895
- return ZodArray.create(this);
896
- }
897
- promise() {
898
- return ZodPromise.create(this, this._def);
899
- }
900
- or(option) {
901
- return ZodUnion.create([this, option], this._def);
902
- }
903
- and(incoming) {
904
- return ZodIntersection.create(this, incoming, this._def);
905
- }
906
- transform(transform) {
907
- return new ZodEffects({
908
- ...processCreateParams(this._def),
909
- schema: this,
910
- typeName: ZodFirstPartyTypeKind.ZodEffects,
911
- effect: { type: "transform", transform }
912
- });
913
- }
914
- default(def) {
915
- const defaultValueFunc = typeof def === "function" ? def : () => def;
916
- return new ZodDefault({
917
- ...processCreateParams(this._def),
918
- innerType: this,
919
- defaultValue: defaultValueFunc,
920
- typeName: ZodFirstPartyTypeKind.ZodDefault
921
- });
922
- }
923
- brand() {
924
- return new ZodBranded({
925
- typeName: ZodFirstPartyTypeKind.ZodBranded,
926
- type: this,
927
- ...processCreateParams(this._def)
928
- });
929
- }
930
- catch(def) {
931
- const catchValueFunc = typeof def === "function" ? def : () => def;
932
- return new ZodCatch({
933
- ...processCreateParams(this._def),
934
- innerType: this,
935
- catchValue: catchValueFunc,
936
- typeName: ZodFirstPartyTypeKind.ZodCatch
937
- });
938
- }
939
- describe(description) {
940
- const This = this.constructor;
941
- return new This({
942
- ...this._def,
943
- description
944
- });
945
- }
946
- pipe(target) {
947
- return ZodPipeline.create(this, target);
948
- }
949
- readonly() {
950
- return ZodReadonly.create(this);
951
- }
952
- isOptional() {
953
- return this.safeParse(void 0).success;
954
- }
955
- isNullable() {
956
- return this.safeParse(null).success;
957
- }
958
- };
959
- var cuidRegex = /^c[^\s-]{8,}$/i;
960
- var cuid2Regex = /^[0-9a-z]+$/;
961
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
962
- 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;
963
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
964
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
965
- 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)?)??$/;
966
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
967
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
968
- var emojiRegex;
969
- 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])$/;
970
- 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])$/;
971
- 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]))$/;
972
- 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])$/;
973
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
974
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
975
- 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])))`;
976
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
977
- function timeRegexSource(args) {
978
- let secondsRegexSource = `[0-5]\\d`;
979
- if (args.precision) {
980
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
981
- } else if (args.precision == null) {
982
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
983
- }
984
- const secondsQuantifier = args.precision ? "+" : "?";
985
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
986
- }
987
- function timeRegex(args) {
988
- return new RegExp(`^${timeRegexSource(args)}$`);
989
- }
990
- function datetimeRegex(args) {
991
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
992
- const opts = [];
993
- opts.push(args.local ? `Z?` : `Z`);
994
- if (args.offset)
995
- opts.push(`([+-]\\d{2}:?\\d{2})`);
996
- regex = `${regex}(${opts.join("|")})`;
997
- return new RegExp(`^${regex}$`);
998
- }
999
- function isValidIP(ip, version) {
1000
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1001
- return true;
1002
- }
1003
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1004
- return true;
1005
- }
1006
- return false;
1007
- }
1008
- function isValidJWT(jwt, alg) {
1009
- if (!jwtRegex.test(jwt))
1010
- return false;
1011
- try {
1012
- const [header] = jwt.split(".");
1013
- if (!header)
1014
- return false;
1015
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1016
- const decoded = JSON.parse(atob(base64));
1017
- if (typeof decoded !== "object" || decoded === null)
1018
- return false;
1019
- if ("typ" in decoded && decoded?.typ !== "JWT")
1020
- return false;
1021
- if (!decoded.alg)
1022
- return false;
1023
- if (alg && decoded.alg !== alg)
1024
- return false;
1025
- return true;
1026
- } catch {
1027
- return false;
1028
- }
1029
- }
1030
- function isValidCidr(ip, version) {
1031
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1032
- return true;
1033
- }
1034
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1035
- return true;
1036
- }
1037
- return false;
1038
- }
1039
- var ZodString = class _ZodString extends ZodType {
1040
- _parse(input) {
1041
- if (this._def.coerce) {
1042
- input.data = String(input.data);
1043
- }
1044
- const parsedType = this._getType(input);
1045
- if (parsedType !== ZodParsedType.string) {
1046
- const ctx2 = this._getOrReturnCtx(input);
1047
- addIssueToContext(ctx2, {
1048
- code: ZodIssueCode.invalid_type,
1049
- expected: ZodParsedType.string,
1050
- received: ctx2.parsedType
1051
- });
1052
- return INVALID;
1053
- }
1054
- const status = new ParseStatus();
1055
- let ctx = void 0;
1056
- for (const check of this._def.checks) {
1057
- if (check.kind === "min") {
1058
- if (input.data.length < check.value) {
1059
- ctx = this._getOrReturnCtx(input, ctx);
1060
- addIssueToContext(ctx, {
1061
- code: ZodIssueCode.too_small,
1062
- minimum: check.value,
1063
- type: "string",
1064
- inclusive: true,
1065
- exact: false,
1066
- message: check.message
1067
- });
1068
- status.dirty();
1069
- }
1070
- } else if (check.kind === "max") {
1071
- if (input.data.length > check.value) {
1072
- ctx = this._getOrReturnCtx(input, ctx);
1073
- addIssueToContext(ctx, {
1074
- code: ZodIssueCode.too_big,
1075
- maximum: check.value,
1076
- type: "string",
1077
- inclusive: true,
1078
- exact: false,
1079
- message: check.message
1080
- });
1081
- status.dirty();
1082
- }
1083
- } else if (check.kind === "length") {
1084
- const tooBig = input.data.length > check.value;
1085
- const tooSmall = input.data.length < check.value;
1086
- if (tooBig || tooSmall) {
1087
- ctx = this._getOrReturnCtx(input, ctx);
1088
- if (tooBig) {
1089
- addIssueToContext(ctx, {
1090
- code: ZodIssueCode.too_big,
1091
- maximum: check.value,
1092
- type: "string",
1093
- inclusive: true,
1094
- exact: true,
1095
- message: check.message
1096
- });
1097
- } else if (tooSmall) {
1098
- addIssueToContext(ctx, {
1099
- code: ZodIssueCode.too_small,
1100
- minimum: check.value,
1101
- type: "string",
1102
- inclusive: true,
1103
- exact: true,
1104
- message: check.message
1105
- });
1106
- }
1107
- status.dirty();
1108
- }
1109
- } else if (check.kind === "email") {
1110
- if (!emailRegex.test(input.data)) {
1111
- ctx = this._getOrReturnCtx(input, ctx);
1112
- addIssueToContext(ctx, {
1113
- validation: "email",
1114
- code: ZodIssueCode.invalid_string,
1115
- message: check.message
1116
- });
1117
- status.dirty();
1118
- }
1119
- } else if (check.kind === "emoji") {
1120
- if (!emojiRegex) {
1121
- emojiRegex = new RegExp(_emojiRegex, "u");
1122
- }
1123
- if (!emojiRegex.test(input.data)) {
1124
- ctx = this._getOrReturnCtx(input, ctx);
1125
- addIssueToContext(ctx, {
1126
- validation: "emoji",
1127
- code: ZodIssueCode.invalid_string,
1128
- message: check.message
1129
- });
1130
- status.dirty();
1131
- }
1132
- } else if (check.kind === "uuid") {
1133
- if (!uuidRegex.test(input.data)) {
1134
- ctx = this._getOrReturnCtx(input, ctx);
1135
- addIssueToContext(ctx, {
1136
- validation: "uuid",
1137
- code: ZodIssueCode.invalid_string,
1138
- message: check.message
1139
- });
1140
- status.dirty();
1141
- }
1142
- } else if (check.kind === "nanoid") {
1143
- if (!nanoidRegex.test(input.data)) {
1144
- ctx = this._getOrReturnCtx(input, ctx);
1145
- addIssueToContext(ctx, {
1146
- validation: "nanoid",
1147
- code: ZodIssueCode.invalid_string,
1148
- message: check.message
1149
- });
1150
- status.dirty();
1151
- }
1152
- } else if (check.kind === "cuid") {
1153
- if (!cuidRegex.test(input.data)) {
1154
- ctx = this._getOrReturnCtx(input, ctx);
1155
- addIssueToContext(ctx, {
1156
- validation: "cuid",
1157
- code: ZodIssueCode.invalid_string,
1158
- message: check.message
1159
- });
1160
- status.dirty();
1161
- }
1162
- } else if (check.kind === "cuid2") {
1163
- if (!cuid2Regex.test(input.data)) {
1164
- ctx = this._getOrReturnCtx(input, ctx);
1165
- addIssueToContext(ctx, {
1166
- validation: "cuid2",
1167
- code: ZodIssueCode.invalid_string,
1168
- message: check.message
1169
- });
1170
- status.dirty();
1171
- }
1172
- } else if (check.kind === "ulid") {
1173
- if (!ulidRegex.test(input.data)) {
1174
- ctx = this._getOrReturnCtx(input, ctx);
1175
- addIssueToContext(ctx, {
1176
- validation: "ulid",
1177
- code: ZodIssueCode.invalid_string,
1178
- message: check.message
1179
- });
1180
- status.dirty();
1181
- }
1182
- } else if (check.kind === "url") {
1183
- try {
1184
- new URL(input.data);
1185
- } catch {
1186
- ctx = this._getOrReturnCtx(input, ctx);
1187
- addIssueToContext(ctx, {
1188
- validation: "url",
1189
- code: ZodIssueCode.invalid_string,
1190
- message: check.message
1191
- });
1192
- status.dirty();
1193
- }
1194
- } else if (check.kind === "regex") {
1195
- check.regex.lastIndex = 0;
1196
- const testResult = check.regex.test(input.data);
1197
- if (!testResult) {
1198
- ctx = this._getOrReturnCtx(input, ctx);
1199
- addIssueToContext(ctx, {
1200
- validation: "regex",
1201
- code: ZodIssueCode.invalid_string,
1202
- message: check.message
1203
- });
1204
- status.dirty();
1205
- }
1206
- } else if (check.kind === "trim") {
1207
- input.data = input.data.trim();
1208
- } else if (check.kind === "includes") {
1209
- if (!input.data.includes(check.value, check.position)) {
1210
- ctx = this._getOrReturnCtx(input, ctx);
1211
- addIssueToContext(ctx, {
1212
- code: ZodIssueCode.invalid_string,
1213
- validation: { includes: check.value, position: check.position },
1214
- message: check.message
1215
- });
1216
- status.dirty();
1217
- }
1218
- } else if (check.kind === "toLowerCase") {
1219
- input.data = input.data.toLowerCase();
1220
- } else if (check.kind === "toUpperCase") {
1221
- input.data = input.data.toUpperCase();
1222
- } else if (check.kind === "startsWith") {
1223
- if (!input.data.startsWith(check.value)) {
1224
- ctx = this._getOrReturnCtx(input, ctx);
1225
- addIssueToContext(ctx, {
1226
- code: ZodIssueCode.invalid_string,
1227
- validation: { startsWith: check.value },
1228
- message: check.message
1229
- });
1230
- status.dirty();
1231
- }
1232
- } else if (check.kind === "endsWith") {
1233
- if (!input.data.endsWith(check.value)) {
1234
- ctx = this._getOrReturnCtx(input, ctx);
1235
- addIssueToContext(ctx, {
1236
- code: ZodIssueCode.invalid_string,
1237
- validation: { endsWith: check.value },
1238
- message: check.message
1239
- });
1240
- status.dirty();
1241
- }
1242
- } else if (check.kind === "datetime") {
1243
- const regex = datetimeRegex(check);
1244
- if (!regex.test(input.data)) {
1245
- ctx = this._getOrReturnCtx(input, ctx);
1246
- addIssueToContext(ctx, {
1247
- code: ZodIssueCode.invalid_string,
1248
- validation: "datetime",
1249
- message: check.message
1250
- });
1251
- status.dirty();
1252
- }
1253
- } else if (check.kind === "date") {
1254
- const regex = dateRegex;
1255
- if (!regex.test(input.data)) {
1256
- ctx = this._getOrReturnCtx(input, ctx);
1257
- addIssueToContext(ctx, {
1258
- code: ZodIssueCode.invalid_string,
1259
- validation: "date",
1260
- message: check.message
1261
- });
1262
- status.dirty();
1263
- }
1264
- } else if (check.kind === "time") {
1265
- const regex = timeRegex(check);
1266
- if (!regex.test(input.data)) {
1267
- ctx = this._getOrReturnCtx(input, ctx);
1268
- addIssueToContext(ctx, {
1269
- code: ZodIssueCode.invalid_string,
1270
- validation: "time",
1271
- message: check.message
1272
- });
1273
- status.dirty();
1274
- }
1275
- } else if (check.kind === "duration") {
1276
- if (!durationRegex.test(input.data)) {
1277
- ctx = this._getOrReturnCtx(input, ctx);
1278
- addIssueToContext(ctx, {
1279
- validation: "duration",
1280
- code: ZodIssueCode.invalid_string,
1281
- message: check.message
1282
- });
1283
- status.dirty();
1284
- }
1285
- } else if (check.kind === "ip") {
1286
- if (!isValidIP(input.data, check.version)) {
1287
- ctx = this._getOrReturnCtx(input, ctx);
1288
- addIssueToContext(ctx, {
1289
- validation: "ip",
1290
- code: ZodIssueCode.invalid_string,
1291
- message: check.message
1292
- });
1293
- status.dirty();
1294
- }
1295
- } else if (check.kind === "jwt") {
1296
- if (!isValidJWT(input.data, check.alg)) {
1297
- ctx = this._getOrReturnCtx(input, ctx);
1298
- addIssueToContext(ctx, {
1299
- validation: "jwt",
1300
- code: ZodIssueCode.invalid_string,
1301
- message: check.message
1302
- });
1303
- status.dirty();
1304
- }
1305
- } else if (check.kind === "cidr") {
1306
- if (!isValidCidr(input.data, check.version)) {
1307
- ctx = this._getOrReturnCtx(input, ctx);
1308
- addIssueToContext(ctx, {
1309
- validation: "cidr",
1310
- code: ZodIssueCode.invalid_string,
1311
- message: check.message
1312
- });
1313
- status.dirty();
1314
- }
1315
- } else if (check.kind === "base64") {
1316
- if (!base64Regex.test(input.data)) {
1317
- ctx = this._getOrReturnCtx(input, ctx);
1318
- addIssueToContext(ctx, {
1319
- validation: "base64",
1320
- code: ZodIssueCode.invalid_string,
1321
- message: check.message
1322
- });
1323
- status.dirty();
1324
- }
1325
- } else if (check.kind === "base64url") {
1326
- if (!base64urlRegex.test(input.data)) {
1327
- ctx = this._getOrReturnCtx(input, ctx);
1328
- addIssueToContext(ctx, {
1329
- validation: "base64url",
1330
- code: ZodIssueCode.invalid_string,
1331
- message: check.message
1332
- });
1333
- status.dirty();
1334
- }
1335
- } else {
1336
- util.assertNever(check);
1337
- }
1338
- }
1339
- return { status: status.value, value: input.data };
1340
- }
1341
- _regex(regex, validation, message) {
1342
- return this.refinement((data) => regex.test(data), {
1343
- validation,
1344
- code: ZodIssueCode.invalid_string,
1345
- ...errorUtil.errToObj(message)
1346
- });
1347
- }
1348
- _addCheck(check) {
1349
- return new _ZodString({
1350
- ...this._def,
1351
- checks: [...this._def.checks, check]
1352
- });
1353
- }
1354
- email(message) {
1355
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1356
- }
1357
- url(message) {
1358
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1359
- }
1360
- emoji(message) {
1361
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1362
- }
1363
- uuid(message) {
1364
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1365
- }
1366
- nanoid(message) {
1367
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1368
- }
1369
- cuid(message) {
1370
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1371
- }
1372
- cuid2(message) {
1373
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1374
- }
1375
- ulid(message) {
1376
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1377
- }
1378
- base64(message) {
1379
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1380
- }
1381
- base64url(message) {
1382
- return this._addCheck({
1383
- kind: "base64url",
1384
- ...errorUtil.errToObj(message)
1385
- });
1386
- }
1387
- jwt(options) {
1388
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1389
- }
1390
- ip(options) {
1391
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1392
- }
1393
- cidr(options) {
1394
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1395
- }
1396
- datetime(options) {
1397
- if (typeof options === "string") {
1398
- return this._addCheck({
1399
- kind: "datetime",
1400
- precision: null,
1401
- offset: false,
1402
- local: false,
1403
- message: options
1404
- });
1405
- }
1406
- return this._addCheck({
1407
- kind: "datetime",
1408
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1409
- offset: options?.offset ?? false,
1410
- local: options?.local ?? false,
1411
- ...errorUtil.errToObj(options?.message)
1412
- });
1413
- }
1414
- date(message) {
1415
- return this._addCheck({ kind: "date", message });
1416
- }
1417
- time(options) {
1418
- if (typeof options === "string") {
1419
- return this._addCheck({
1420
- kind: "time",
1421
- precision: null,
1422
- message: options
1423
- });
1424
- }
1425
- return this._addCheck({
1426
- kind: "time",
1427
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1428
- ...errorUtil.errToObj(options?.message)
1429
- });
1430
- }
1431
- duration(message) {
1432
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1433
- }
1434
- regex(regex, message) {
1435
- return this._addCheck({
1436
- kind: "regex",
1437
- regex,
1438
- ...errorUtil.errToObj(message)
1439
- });
1440
- }
1441
- includes(value, options) {
1442
- return this._addCheck({
1443
- kind: "includes",
1444
- value,
1445
- position: options?.position,
1446
- ...errorUtil.errToObj(options?.message)
1447
- });
1448
- }
1449
- startsWith(value, message) {
1450
- return this._addCheck({
1451
- kind: "startsWith",
1452
- value,
1453
- ...errorUtil.errToObj(message)
1454
- });
1455
- }
1456
- endsWith(value, message) {
1457
- return this._addCheck({
1458
- kind: "endsWith",
1459
- value,
1460
- ...errorUtil.errToObj(message)
1461
- });
1462
- }
1463
- min(minLength, message) {
1464
- return this._addCheck({
1465
- kind: "min",
1466
- value: minLength,
1467
- ...errorUtil.errToObj(message)
1468
- });
1469
- }
1470
- max(maxLength, message) {
1471
- return this._addCheck({
1472
- kind: "max",
1473
- value: maxLength,
1474
- ...errorUtil.errToObj(message)
1475
- });
1476
- }
1477
- length(len, message) {
1478
- return this._addCheck({
1479
- kind: "length",
1480
- value: len,
1481
- ...errorUtil.errToObj(message)
1482
- });
1483
- }
1484
- /**
1485
- * Equivalent to `.min(1)`
1486
- */
1487
- nonempty(message) {
1488
- return this.min(1, errorUtil.errToObj(message));
1489
- }
1490
- trim() {
1491
- return new _ZodString({
1492
- ...this._def,
1493
- checks: [...this._def.checks, { kind: "trim" }]
1494
- });
1495
- }
1496
- toLowerCase() {
1497
- return new _ZodString({
1498
- ...this._def,
1499
- checks: [...this._def.checks, { kind: "toLowerCase" }]
1500
- });
1501
- }
1502
- toUpperCase() {
1503
- return new _ZodString({
1504
- ...this._def,
1505
- checks: [...this._def.checks, { kind: "toUpperCase" }]
1506
- });
1507
- }
1508
- get isDatetime() {
1509
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
1510
- }
1511
- get isDate() {
1512
- return !!this._def.checks.find((ch) => ch.kind === "date");
1513
- }
1514
- get isTime() {
1515
- return !!this._def.checks.find((ch) => ch.kind === "time");
1516
- }
1517
- get isDuration() {
1518
- return !!this._def.checks.find((ch) => ch.kind === "duration");
1519
- }
1520
- get isEmail() {
1521
- return !!this._def.checks.find((ch) => ch.kind === "email");
1522
- }
1523
- get isURL() {
1524
- return !!this._def.checks.find((ch) => ch.kind === "url");
1525
- }
1526
- get isEmoji() {
1527
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1528
- }
1529
- get isUUID() {
1530
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1531
- }
1532
- get isNANOID() {
1533
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1534
- }
1535
- get isCUID() {
1536
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1537
- }
1538
- get isCUID2() {
1539
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1540
- }
1541
- get isULID() {
1542
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1543
- }
1544
- get isIP() {
1545
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1546
- }
1547
- get isCIDR() {
1548
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1549
- }
1550
- get isBase64() {
1551
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1552
- }
1553
- get isBase64url() {
1554
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1555
- }
1556
- get minLength() {
1557
- let min = null;
1558
- for (const ch of this._def.checks) {
1559
- if (ch.kind === "min") {
1560
- if (min === null || ch.value > min)
1561
- min = ch.value;
1562
- }
1563
- }
1564
- return min;
1565
- }
1566
- get maxLength() {
1567
- let max = null;
1568
- for (const ch of this._def.checks) {
1569
- if (ch.kind === "max") {
1570
- if (max === null || ch.value < max)
1571
- max = ch.value;
1572
- }
1573
- }
1574
- return max;
1575
- }
1576
- };
1577
- ZodString.create = (params) => {
1578
- return new ZodString({
1579
- checks: [],
1580
- typeName: ZodFirstPartyTypeKind.ZodString,
1581
- coerce: params?.coerce ?? false,
1582
- ...processCreateParams(params)
1583
- });
1584
- };
1585
- function floatSafeRemainder(val, step) {
1586
- const valDecCount = (val.toString().split(".")[1] || "").length;
1587
- const stepDecCount = (step.toString().split(".")[1] || "").length;
1588
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1589
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1590
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1591
- return valInt % stepInt / 10 ** decCount;
1592
- }
1593
- var ZodNumber = class _ZodNumber extends ZodType {
1594
- constructor() {
1595
- super(...arguments);
1596
- this.min = this.gte;
1597
- this.max = this.lte;
1598
- this.step = this.multipleOf;
1599
- }
1600
- _parse(input) {
1601
- if (this._def.coerce) {
1602
- input.data = Number(input.data);
1603
- }
1604
- const parsedType = this._getType(input);
1605
- if (parsedType !== ZodParsedType.number) {
1606
- const ctx2 = this._getOrReturnCtx(input);
1607
- addIssueToContext(ctx2, {
1608
- code: ZodIssueCode.invalid_type,
1609
- expected: ZodParsedType.number,
1610
- received: ctx2.parsedType
1611
- });
1612
- return INVALID;
1613
- }
1614
- let ctx = void 0;
1615
- const status = new ParseStatus();
1616
- for (const check of this._def.checks) {
1617
- if (check.kind === "int") {
1618
- if (!util.isInteger(input.data)) {
1619
- ctx = this._getOrReturnCtx(input, ctx);
1620
- addIssueToContext(ctx, {
1621
- code: ZodIssueCode.invalid_type,
1622
- expected: "integer",
1623
- received: "float",
1624
- message: check.message
1625
- });
1626
- status.dirty();
1627
- }
1628
- } else if (check.kind === "min") {
1629
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1630
- if (tooSmall) {
1631
- ctx = this._getOrReturnCtx(input, ctx);
1632
- addIssueToContext(ctx, {
1633
- code: ZodIssueCode.too_small,
1634
- minimum: check.value,
1635
- type: "number",
1636
- inclusive: check.inclusive,
1637
- exact: false,
1638
- message: check.message
1639
- });
1640
- status.dirty();
1641
- }
1642
- } else if (check.kind === "max") {
1643
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1644
- if (tooBig) {
1645
- ctx = this._getOrReturnCtx(input, ctx);
1646
- addIssueToContext(ctx, {
1647
- code: ZodIssueCode.too_big,
1648
- maximum: check.value,
1649
- type: "number",
1650
- inclusive: check.inclusive,
1651
- exact: false,
1652
- message: check.message
1653
- });
1654
- status.dirty();
1655
- }
1656
- } else if (check.kind === "multipleOf") {
1657
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1658
- ctx = this._getOrReturnCtx(input, ctx);
1659
- addIssueToContext(ctx, {
1660
- code: ZodIssueCode.not_multiple_of,
1661
- multipleOf: check.value,
1662
- message: check.message
1663
- });
1664
- status.dirty();
1665
- }
1666
- } else if (check.kind === "finite") {
1667
- if (!Number.isFinite(input.data)) {
1668
- ctx = this._getOrReturnCtx(input, ctx);
1669
- addIssueToContext(ctx, {
1670
- code: ZodIssueCode.not_finite,
1671
- message: check.message
1672
- });
1673
- status.dirty();
1674
- }
1675
- } else {
1676
- util.assertNever(check);
1677
- }
1678
- }
1679
- return { status: status.value, value: input.data };
1680
- }
1681
- gte(value, message) {
1682
- return this.setLimit("min", value, true, errorUtil.toString(message));
1683
- }
1684
- gt(value, message) {
1685
- return this.setLimit("min", value, false, errorUtil.toString(message));
1686
- }
1687
- lte(value, message) {
1688
- return this.setLimit("max", value, true, errorUtil.toString(message));
1689
- }
1690
- lt(value, message) {
1691
- return this.setLimit("max", value, false, errorUtil.toString(message));
1692
- }
1693
- setLimit(kind, value, inclusive, message) {
1694
- return new _ZodNumber({
1695
- ...this._def,
1696
- checks: [
1697
- ...this._def.checks,
1698
- {
1699
- kind,
1700
- value,
1701
- inclusive,
1702
- message: errorUtil.toString(message)
1703
- }
1704
- ]
1705
- });
1706
- }
1707
- _addCheck(check) {
1708
- return new _ZodNumber({
1709
- ...this._def,
1710
- checks: [...this._def.checks, check]
1711
- });
1712
- }
1713
- int(message) {
1714
- return this._addCheck({
1715
- kind: "int",
1716
- message: errorUtil.toString(message)
1717
- });
1718
- }
1719
- positive(message) {
1720
- return this._addCheck({
1721
- kind: "min",
1722
- value: 0,
1723
- inclusive: false,
1724
- message: errorUtil.toString(message)
1725
- });
1726
- }
1727
- negative(message) {
1728
- return this._addCheck({
1729
- kind: "max",
1730
- value: 0,
1731
- inclusive: false,
1732
- message: errorUtil.toString(message)
1733
- });
1734
- }
1735
- nonpositive(message) {
1736
- return this._addCheck({
1737
- kind: "max",
1738
- value: 0,
1739
- inclusive: true,
1740
- message: errorUtil.toString(message)
1741
- });
1742
- }
1743
- nonnegative(message) {
1744
- return this._addCheck({
1745
- kind: "min",
1746
- value: 0,
1747
- inclusive: true,
1748
- message: errorUtil.toString(message)
1749
- });
1750
- }
1751
- multipleOf(value, message) {
1752
- return this._addCheck({
1753
- kind: "multipleOf",
1754
- value,
1755
- message: errorUtil.toString(message)
1756
- });
1757
- }
1758
- finite(message) {
1759
- return this._addCheck({
1760
- kind: "finite",
1761
- message: errorUtil.toString(message)
1762
- });
1763
- }
1764
- safe(message) {
1765
- return this._addCheck({
1766
- kind: "min",
1767
- inclusive: true,
1768
- value: Number.MIN_SAFE_INTEGER,
1769
- message: errorUtil.toString(message)
1770
- })._addCheck({
1771
- kind: "max",
1772
- inclusive: true,
1773
- value: Number.MAX_SAFE_INTEGER,
1774
- message: errorUtil.toString(message)
1775
- });
1776
- }
1777
- get minValue() {
1778
- let min = null;
1779
- for (const ch of this._def.checks) {
1780
- if (ch.kind === "min") {
1781
- if (min === null || ch.value > min)
1782
- min = ch.value;
1783
- }
1784
- }
1785
- return min;
1786
- }
1787
- get maxValue() {
1788
- let max = null;
1789
- for (const ch of this._def.checks) {
1790
- if (ch.kind === "max") {
1791
- if (max === null || ch.value < max)
1792
- max = ch.value;
1793
- }
1794
- }
1795
- return max;
1796
- }
1797
- get isInt() {
1798
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1799
- }
1800
- get isFinite() {
1801
- let max = null;
1802
- let min = null;
1803
- for (const ch of this._def.checks) {
1804
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1805
- return true;
1806
- } else if (ch.kind === "min") {
1807
- if (min === null || ch.value > min)
1808
- min = ch.value;
1809
- } else if (ch.kind === "max") {
1810
- if (max === null || ch.value < max)
1811
- max = ch.value;
1812
- }
1813
- }
1814
- return Number.isFinite(min) && Number.isFinite(max);
1815
- }
1816
- };
1817
- ZodNumber.create = (params) => {
1818
- return new ZodNumber({
1819
- checks: [],
1820
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1821
- coerce: params?.coerce || false,
1822
- ...processCreateParams(params)
1823
- });
1824
- };
1825
- var ZodBigInt = class _ZodBigInt extends ZodType {
1826
- constructor() {
1827
- super(...arguments);
1828
- this.min = this.gte;
1829
- this.max = this.lte;
1830
- }
1831
- _parse(input) {
1832
- if (this._def.coerce) {
1833
- try {
1834
- input.data = BigInt(input.data);
1835
- } catch {
1836
- return this._getInvalidInput(input);
1837
- }
1838
- }
1839
- const parsedType = this._getType(input);
1840
- if (parsedType !== ZodParsedType.bigint) {
1841
- return this._getInvalidInput(input);
1842
- }
1843
- let ctx = void 0;
1844
- const status = new ParseStatus();
1845
- for (const check of this._def.checks) {
1846
- if (check.kind === "min") {
1847
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1848
- if (tooSmall) {
1849
- ctx = this._getOrReturnCtx(input, ctx);
1850
- addIssueToContext(ctx, {
1851
- code: ZodIssueCode.too_small,
1852
- type: "bigint",
1853
- minimum: check.value,
1854
- inclusive: check.inclusive,
1855
- message: check.message
1856
- });
1857
- status.dirty();
1858
- }
1859
- } else if (check.kind === "max") {
1860
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1861
- if (tooBig) {
1862
- ctx = this._getOrReturnCtx(input, ctx);
1863
- addIssueToContext(ctx, {
1864
- code: ZodIssueCode.too_big,
1865
- type: "bigint",
1866
- maximum: check.value,
1867
- inclusive: check.inclusive,
1868
- message: check.message
1869
- });
1870
- status.dirty();
1871
- }
1872
- } else if (check.kind === "multipleOf") {
1873
- if (input.data % check.value !== BigInt(0)) {
1874
- ctx = this._getOrReturnCtx(input, ctx);
1875
- addIssueToContext(ctx, {
1876
- code: ZodIssueCode.not_multiple_of,
1877
- multipleOf: check.value,
1878
- message: check.message
1879
- });
1880
- status.dirty();
1881
- }
1882
- } else {
1883
- util.assertNever(check);
1884
- }
1885
- }
1886
- return { status: status.value, value: input.data };
1887
- }
1888
- _getInvalidInput(input) {
1889
- const ctx = this._getOrReturnCtx(input);
1890
- addIssueToContext(ctx, {
1891
- code: ZodIssueCode.invalid_type,
1892
- expected: ZodParsedType.bigint,
1893
- received: ctx.parsedType
1894
- });
1895
- return INVALID;
1896
- }
1897
- gte(value, message) {
1898
- return this.setLimit("min", value, true, errorUtil.toString(message));
1899
- }
1900
- gt(value, message) {
1901
- return this.setLimit("min", value, false, errorUtil.toString(message));
1902
- }
1903
- lte(value, message) {
1904
- return this.setLimit("max", value, true, errorUtil.toString(message));
1905
- }
1906
- lt(value, message) {
1907
- return this.setLimit("max", value, false, errorUtil.toString(message));
1908
- }
1909
- setLimit(kind, value, inclusive, message) {
1910
- return new _ZodBigInt({
1911
- ...this._def,
1912
- checks: [
1913
- ...this._def.checks,
1914
- {
1915
- kind,
1916
- value,
1917
- inclusive,
1918
- message: errorUtil.toString(message)
1919
- }
1920
- ]
1921
- });
1922
- }
1923
- _addCheck(check) {
1924
- return new _ZodBigInt({
1925
- ...this._def,
1926
- checks: [...this._def.checks, check]
1927
- });
1928
- }
1929
- positive(message) {
1930
- return this._addCheck({
1931
- kind: "min",
1932
- value: BigInt(0),
1933
- inclusive: false,
1934
- message: errorUtil.toString(message)
1935
- });
1936
- }
1937
- negative(message) {
1938
- return this._addCheck({
1939
- kind: "max",
1940
- value: BigInt(0),
1941
- inclusive: false,
1942
- message: errorUtil.toString(message)
1943
- });
1944
- }
1945
- nonpositive(message) {
1946
- return this._addCheck({
1947
- kind: "max",
1948
- value: BigInt(0),
1949
- inclusive: true,
1950
- message: errorUtil.toString(message)
1951
- });
1952
- }
1953
- nonnegative(message) {
1954
- return this._addCheck({
1955
- kind: "min",
1956
- value: BigInt(0),
1957
- inclusive: true,
1958
- message: errorUtil.toString(message)
1959
- });
1960
- }
1961
- multipleOf(value, message) {
1962
- return this._addCheck({
1963
- kind: "multipleOf",
1964
- value,
1965
- message: errorUtil.toString(message)
1966
- });
1967
- }
1968
- get minValue() {
1969
- let min = null;
1970
- for (const ch of this._def.checks) {
1971
- if (ch.kind === "min") {
1972
- if (min === null || ch.value > min)
1973
- min = ch.value;
1974
- }
1975
- }
1976
- return min;
1977
- }
1978
- get maxValue() {
1979
- let max = null;
1980
- for (const ch of this._def.checks) {
1981
- if (ch.kind === "max") {
1982
- if (max === null || ch.value < max)
1983
- max = ch.value;
1984
- }
1985
- }
1986
- return max;
1987
- }
1988
- };
1989
- ZodBigInt.create = (params) => {
1990
- return new ZodBigInt({
1991
- checks: [],
1992
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
1993
- coerce: params?.coerce ?? false,
1994
- ...processCreateParams(params)
1995
- });
1996
- };
1997
- var ZodBoolean = class extends ZodType {
1998
- _parse(input) {
1999
- if (this._def.coerce) {
2000
- input.data = Boolean(input.data);
2001
- }
2002
- const parsedType = this._getType(input);
2003
- if (parsedType !== ZodParsedType.boolean) {
2004
- const ctx = this._getOrReturnCtx(input);
2005
- addIssueToContext(ctx, {
2006
- code: ZodIssueCode.invalid_type,
2007
- expected: ZodParsedType.boolean,
2008
- received: ctx.parsedType
2009
- });
2010
- return INVALID;
2011
- }
2012
- return OK(input.data);
2013
- }
2014
- };
2015
- ZodBoolean.create = (params) => {
2016
- return new ZodBoolean({
2017
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2018
- coerce: params?.coerce || false,
2019
- ...processCreateParams(params)
2020
- });
2021
- };
2022
- var ZodDate = class _ZodDate extends ZodType {
2023
- _parse(input) {
2024
- if (this._def.coerce) {
2025
- input.data = new Date(input.data);
2026
- }
2027
- const parsedType = this._getType(input);
2028
- if (parsedType !== ZodParsedType.date) {
2029
- const ctx2 = this._getOrReturnCtx(input);
2030
- addIssueToContext(ctx2, {
2031
- code: ZodIssueCode.invalid_type,
2032
- expected: ZodParsedType.date,
2033
- received: ctx2.parsedType
2034
- });
2035
- return INVALID;
2036
- }
2037
- if (Number.isNaN(input.data.getTime())) {
2038
- const ctx2 = this._getOrReturnCtx(input);
2039
- addIssueToContext(ctx2, {
2040
- code: ZodIssueCode.invalid_date
2041
- });
2042
- return INVALID;
2043
- }
2044
- const status = new ParseStatus();
2045
- let ctx = void 0;
2046
- for (const check of this._def.checks) {
2047
- if (check.kind === "min") {
2048
- if (input.data.getTime() < check.value) {
2049
- ctx = this._getOrReturnCtx(input, ctx);
2050
- addIssueToContext(ctx, {
2051
- code: ZodIssueCode.too_small,
2052
- message: check.message,
2053
- inclusive: true,
2054
- exact: false,
2055
- minimum: check.value,
2056
- type: "date"
2057
- });
2058
- status.dirty();
2059
- }
2060
- } else if (check.kind === "max") {
2061
- if (input.data.getTime() > check.value) {
2062
- ctx = this._getOrReturnCtx(input, ctx);
2063
- addIssueToContext(ctx, {
2064
- code: ZodIssueCode.too_big,
2065
- message: check.message,
2066
- inclusive: true,
2067
- exact: false,
2068
- maximum: check.value,
2069
- type: "date"
2070
- });
2071
- status.dirty();
2072
- }
2073
- } else {
2074
- util.assertNever(check);
2075
- }
2076
- }
2077
- return {
2078
- status: status.value,
2079
- value: new Date(input.data.getTime())
2080
- };
2081
- }
2082
- _addCheck(check) {
2083
- return new _ZodDate({
2084
- ...this._def,
2085
- checks: [...this._def.checks, check]
2086
- });
2087
- }
2088
- min(minDate, message) {
2089
- return this._addCheck({
2090
- kind: "min",
2091
- value: minDate.getTime(),
2092
- message: errorUtil.toString(message)
2093
- });
2094
- }
2095
- max(maxDate, message) {
2096
- return this._addCheck({
2097
- kind: "max",
2098
- value: maxDate.getTime(),
2099
- message: errorUtil.toString(message)
2100
- });
2101
- }
2102
- get minDate() {
2103
- let min = null;
2104
- for (const ch of this._def.checks) {
2105
- if (ch.kind === "min") {
2106
- if (min === null || ch.value > min)
2107
- min = ch.value;
2108
- }
2109
- }
2110
- return min != null ? new Date(min) : null;
2111
- }
2112
- get maxDate() {
2113
- let max = null;
2114
- for (const ch of this._def.checks) {
2115
- if (ch.kind === "max") {
2116
- if (max === null || ch.value < max)
2117
- max = ch.value;
2118
- }
2119
- }
2120
- return max != null ? new Date(max) : null;
2121
- }
2122
- };
2123
- ZodDate.create = (params) => {
2124
- return new ZodDate({
2125
- checks: [],
2126
- coerce: params?.coerce || false,
2127
- typeName: ZodFirstPartyTypeKind.ZodDate,
2128
- ...processCreateParams(params)
2129
- });
2130
- };
2131
- var ZodSymbol = class extends ZodType {
2132
- _parse(input) {
2133
- const parsedType = this._getType(input);
2134
- if (parsedType !== ZodParsedType.symbol) {
2135
- const ctx = this._getOrReturnCtx(input);
2136
- addIssueToContext(ctx, {
2137
- code: ZodIssueCode.invalid_type,
2138
- expected: ZodParsedType.symbol,
2139
- received: ctx.parsedType
2140
- });
2141
- return INVALID;
2142
- }
2143
- return OK(input.data);
2144
- }
2145
- };
2146
- ZodSymbol.create = (params) => {
2147
- return new ZodSymbol({
2148
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2149
- ...processCreateParams(params)
2150
- });
2151
- };
2152
- var ZodUndefined = class extends ZodType {
2153
- _parse(input) {
2154
- const parsedType = this._getType(input);
2155
- if (parsedType !== ZodParsedType.undefined) {
2156
- const ctx = this._getOrReturnCtx(input);
2157
- addIssueToContext(ctx, {
2158
- code: ZodIssueCode.invalid_type,
2159
- expected: ZodParsedType.undefined,
2160
- received: ctx.parsedType
2161
- });
2162
- return INVALID;
2163
- }
2164
- return OK(input.data);
2165
- }
2166
- };
2167
- ZodUndefined.create = (params) => {
2168
- return new ZodUndefined({
2169
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2170
- ...processCreateParams(params)
2171
- });
2172
- };
2173
- var ZodNull = class extends ZodType {
2174
- _parse(input) {
2175
- const parsedType = this._getType(input);
2176
- if (parsedType !== ZodParsedType.null) {
2177
- const ctx = this._getOrReturnCtx(input);
2178
- addIssueToContext(ctx, {
2179
- code: ZodIssueCode.invalid_type,
2180
- expected: ZodParsedType.null,
2181
- received: ctx.parsedType
2182
- });
2183
- return INVALID;
2184
- }
2185
- return OK(input.data);
2186
- }
2187
- };
2188
- ZodNull.create = (params) => {
2189
- return new ZodNull({
2190
- typeName: ZodFirstPartyTypeKind.ZodNull,
2191
- ...processCreateParams(params)
2192
- });
2193
- };
2194
- var ZodAny = class extends ZodType {
2195
- constructor() {
2196
- super(...arguments);
2197
- this._any = true;
2198
- }
2199
- _parse(input) {
2200
- return OK(input.data);
2201
- }
2202
- };
2203
- ZodAny.create = (params) => {
2204
- return new ZodAny({
2205
- typeName: ZodFirstPartyTypeKind.ZodAny,
2206
- ...processCreateParams(params)
2207
- });
2208
- };
2209
- var ZodUnknown = class extends ZodType {
2210
- constructor() {
2211
- super(...arguments);
2212
- this._unknown = true;
2213
- }
2214
- _parse(input) {
2215
- return OK(input.data);
2216
- }
2217
- };
2218
- ZodUnknown.create = (params) => {
2219
- return new ZodUnknown({
2220
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2221
- ...processCreateParams(params)
2222
- });
2223
- };
2224
- var ZodNever = class extends ZodType {
2225
- _parse(input) {
2226
- const ctx = this._getOrReturnCtx(input);
2227
- addIssueToContext(ctx, {
2228
- code: ZodIssueCode.invalid_type,
2229
- expected: ZodParsedType.never,
2230
- received: ctx.parsedType
2231
- });
2232
- return INVALID;
2233
- }
2234
- };
2235
- ZodNever.create = (params) => {
2236
- return new ZodNever({
2237
- typeName: ZodFirstPartyTypeKind.ZodNever,
2238
- ...processCreateParams(params)
2239
- });
2240
- };
2241
- var ZodVoid = class extends ZodType {
2242
- _parse(input) {
2243
- const parsedType = this._getType(input);
2244
- if (parsedType !== ZodParsedType.undefined) {
2245
- const ctx = this._getOrReturnCtx(input);
2246
- addIssueToContext(ctx, {
2247
- code: ZodIssueCode.invalid_type,
2248
- expected: ZodParsedType.void,
2249
- received: ctx.parsedType
2250
- });
2251
- return INVALID;
2252
- }
2253
- return OK(input.data);
2254
- }
2255
- };
2256
- ZodVoid.create = (params) => {
2257
- return new ZodVoid({
2258
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2259
- ...processCreateParams(params)
2260
- });
2261
- };
2262
- var ZodArray = class _ZodArray extends ZodType {
2263
- _parse(input) {
2264
- const { ctx, status } = this._processInputParams(input);
2265
- const def = this._def;
2266
- if (ctx.parsedType !== ZodParsedType.array) {
2267
- addIssueToContext(ctx, {
2268
- code: ZodIssueCode.invalid_type,
2269
- expected: ZodParsedType.array,
2270
- received: ctx.parsedType
2271
- });
2272
- return INVALID;
2273
- }
2274
- if (def.exactLength !== null) {
2275
- const tooBig = ctx.data.length > def.exactLength.value;
2276
- const tooSmall = ctx.data.length < def.exactLength.value;
2277
- if (tooBig || tooSmall) {
2278
- addIssueToContext(ctx, {
2279
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2280
- minimum: tooSmall ? def.exactLength.value : void 0,
2281
- maximum: tooBig ? def.exactLength.value : void 0,
2282
- type: "array",
2283
- inclusive: true,
2284
- exact: true,
2285
- message: def.exactLength.message
2286
- });
2287
- status.dirty();
2288
- }
2289
- }
2290
- if (def.minLength !== null) {
2291
- if (ctx.data.length < def.minLength.value) {
2292
- addIssueToContext(ctx, {
2293
- code: ZodIssueCode.too_small,
2294
- minimum: def.minLength.value,
2295
- type: "array",
2296
- inclusive: true,
2297
- exact: false,
2298
- message: def.minLength.message
2299
- });
2300
- status.dirty();
2301
- }
2302
- }
2303
- if (def.maxLength !== null) {
2304
- if (ctx.data.length > def.maxLength.value) {
2305
- addIssueToContext(ctx, {
2306
- code: ZodIssueCode.too_big,
2307
- maximum: def.maxLength.value,
2308
- type: "array",
2309
- inclusive: true,
2310
- exact: false,
2311
- message: def.maxLength.message
2312
- });
2313
- status.dirty();
2314
- }
2315
- }
2316
- if (ctx.common.async) {
2317
- return Promise.all([...ctx.data].map((item, i) => {
2318
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2319
- })).then((result2) => {
2320
- return ParseStatus.mergeArray(status, result2);
2321
- });
2322
- }
2323
- const result = [...ctx.data].map((item, i) => {
2324
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2325
- });
2326
- return ParseStatus.mergeArray(status, result);
2327
- }
2328
- get element() {
2329
- return this._def.type;
2330
- }
2331
- min(minLength, message) {
2332
- return new _ZodArray({
2333
- ...this._def,
2334
- minLength: { value: minLength, message: errorUtil.toString(message) }
2335
- });
2336
- }
2337
- max(maxLength, message) {
2338
- return new _ZodArray({
2339
- ...this._def,
2340
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
2341
- });
2342
- }
2343
- length(len, message) {
2344
- return new _ZodArray({
2345
- ...this._def,
2346
- exactLength: { value: len, message: errorUtil.toString(message) }
2347
- });
2348
- }
2349
- nonempty(message) {
2350
- return this.min(1, message);
2351
- }
2352
- };
2353
- ZodArray.create = (schema, params) => {
2354
- return new ZodArray({
2355
- type: schema,
2356
- minLength: null,
2357
- maxLength: null,
2358
- exactLength: null,
2359
- typeName: ZodFirstPartyTypeKind.ZodArray,
2360
- ...processCreateParams(params)
2361
- });
2362
- };
2363
- function deepPartialify(schema) {
2364
- if (schema instanceof ZodObject) {
2365
- const newShape = {};
2366
- for (const key in schema.shape) {
2367
- const fieldSchema = schema.shape[key];
2368
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2369
- }
2370
- return new ZodObject({
2371
- ...schema._def,
2372
- shape: () => newShape
2373
- });
2374
- } else if (schema instanceof ZodArray) {
2375
- return new ZodArray({
2376
- ...schema._def,
2377
- type: deepPartialify(schema.element)
2378
- });
2379
- } else if (schema instanceof ZodOptional) {
2380
- return ZodOptional.create(deepPartialify(schema.unwrap()));
2381
- } else if (schema instanceof ZodNullable) {
2382
- return ZodNullable.create(deepPartialify(schema.unwrap()));
2383
- } else if (schema instanceof ZodTuple) {
2384
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2385
- } else {
2386
- return schema;
2387
- }
2388
- }
2389
- var ZodObject = class _ZodObject extends ZodType {
2390
- constructor() {
2391
- super(...arguments);
2392
- this._cached = null;
2393
- this.nonstrict = this.passthrough;
2394
- this.augment = this.extend;
2395
- }
2396
- _getCached() {
2397
- if (this._cached !== null)
2398
- return this._cached;
2399
- const shape = this._def.shape();
2400
- const keys = util.objectKeys(shape);
2401
- this._cached = { shape, keys };
2402
- return this._cached;
2403
- }
2404
- _parse(input) {
2405
- const parsedType = this._getType(input);
2406
- if (parsedType !== ZodParsedType.object) {
2407
- const ctx2 = this._getOrReturnCtx(input);
2408
- addIssueToContext(ctx2, {
2409
- code: ZodIssueCode.invalid_type,
2410
- expected: ZodParsedType.object,
2411
- received: ctx2.parsedType
2412
- });
2413
- return INVALID;
2414
- }
2415
- const { status, ctx } = this._processInputParams(input);
2416
- const { shape, keys: shapeKeys } = this._getCached();
2417
- const extraKeys = [];
2418
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2419
- for (const key in ctx.data) {
2420
- if (!shapeKeys.includes(key)) {
2421
- extraKeys.push(key);
2422
- }
2423
- }
2424
- }
2425
- const pairs = [];
2426
- for (const key of shapeKeys) {
2427
- const keyValidator = shape[key];
2428
- const value = ctx.data[key];
2429
- pairs.push({
2430
- key: { status: "valid", value: key },
2431
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2432
- alwaysSet: key in ctx.data
2433
- });
2434
- }
2435
- if (this._def.catchall instanceof ZodNever) {
2436
- const unknownKeys = this._def.unknownKeys;
2437
- if (unknownKeys === "passthrough") {
2438
- for (const key of extraKeys) {
2439
- pairs.push({
2440
- key: { status: "valid", value: key },
2441
- value: { status: "valid", value: ctx.data[key] }
2442
- });
2443
- }
2444
- } else if (unknownKeys === "strict") {
2445
- if (extraKeys.length > 0) {
2446
- addIssueToContext(ctx, {
2447
- code: ZodIssueCode.unrecognized_keys,
2448
- keys: extraKeys
2449
- });
2450
- status.dirty();
2451
- }
2452
- } else if (unknownKeys === "strip") ; else {
2453
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2454
- }
2455
- } else {
2456
- const catchall = this._def.catchall;
2457
- for (const key of extraKeys) {
2458
- const value = ctx.data[key];
2459
- pairs.push({
2460
- key: { status: "valid", value: key },
2461
- value: catchall._parse(
2462
- new ParseInputLazyPath(ctx, value, ctx.path, key)
2463
- //, ctx.child(key), value, getParsedType(value)
2464
- ),
2465
- alwaysSet: key in ctx.data
2466
- });
2467
- }
2468
- }
2469
- if (ctx.common.async) {
2470
- return Promise.resolve().then(async () => {
2471
- const syncPairs = [];
2472
- for (const pair of pairs) {
2473
- const key = await pair.key;
2474
- const value = await pair.value;
2475
- syncPairs.push({
2476
- key,
2477
- value,
2478
- alwaysSet: pair.alwaysSet
2479
- });
2480
- }
2481
- return syncPairs;
2482
- }).then((syncPairs) => {
2483
- return ParseStatus.mergeObjectSync(status, syncPairs);
2484
- });
2485
- } else {
2486
- return ParseStatus.mergeObjectSync(status, pairs);
2487
- }
2488
- }
2489
- get shape() {
2490
- return this._def.shape();
2491
- }
2492
- strict(message) {
2493
- errorUtil.errToObj;
2494
- return new _ZodObject({
2495
- ...this._def,
2496
- unknownKeys: "strict",
2497
- ...message !== void 0 ? {
2498
- errorMap: (issue, ctx) => {
2499
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2500
- if (issue.code === "unrecognized_keys")
2501
- return {
2502
- message: errorUtil.errToObj(message).message ?? defaultError
2503
- };
2504
- return {
2505
- message: defaultError
2506
- };
2507
- }
2508
- } : {}
2509
- });
2510
- }
2511
- strip() {
2512
- return new _ZodObject({
2513
- ...this._def,
2514
- unknownKeys: "strip"
2515
- });
2516
- }
2517
- passthrough() {
2518
- return new _ZodObject({
2519
- ...this._def,
2520
- unknownKeys: "passthrough"
2521
- });
2522
- }
2523
- // const AugmentFactory =
2524
- // <Def extends ZodObjectDef>(def: Def) =>
2525
- // <Augmentation extends ZodRawShape>(
2526
- // augmentation: Augmentation
2527
- // ): ZodObject<
2528
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2529
- // Def["unknownKeys"],
2530
- // Def["catchall"]
2531
- // > => {
2532
- // return new ZodObject({
2533
- // ...def,
2534
- // shape: () => ({
2535
- // ...def.shape(),
2536
- // ...augmentation,
2537
- // }),
2538
- // }) as any;
2539
- // };
2540
- extend(augmentation) {
2541
- return new _ZodObject({
2542
- ...this._def,
2543
- shape: () => ({
2544
- ...this._def.shape(),
2545
- ...augmentation
2546
- })
2547
- });
2548
- }
2549
- /**
2550
- * Prior to zod@1.0.12 there was a bug in the
2551
- * inferred type of merged objects. Please
2552
- * upgrade if you are experiencing issues.
2553
- */
2554
- merge(merging) {
2555
- const merged = new _ZodObject({
2556
- unknownKeys: merging._def.unknownKeys,
2557
- catchall: merging._def.catchall,
2558
- shape: () => ({
2559
- ...this._def.shape(),
2560
- ...merging._def.shape()
2561
- }),
2562
- typeName: ZodFirstPartyTypeKind.ZodObject
2563
- });
2564
- return merged;
2565
- }
2566
- // merge<
2567
- // Incoming extends AnyZodObject,
2568
- // Augmentation extends Incoming["shape"],
2569
- // NewOutput extends {
2570
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2571
- // ? Augmentation[k]["_output"]
2572
- // : k extends keyof Output
2573
- // ? Output[k]
2574
- // : never;
2575
- // },
2576
- // NewInput extends {
2577
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2578
- // ? Augmentation[k]["_input"]
2579
- // : k extends keyof Input
2580
- // ? Input[k]
2581
- // : never;
2582
- // }
2583
- // >(
2584
- // merging: Incoming
2585
- // ): ZodObject<
2586
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2587
- // Incoming["_def"]["unknownKeys"],
2588
- // Incoming["_def"]["catchall"],
2589
- // NewOutput,
2590
- // NewInput
2591
- // > {
2592
- // const merged: any = new ZodObject({
2593
- // unknownKeys: merging._def.unknownKeys,
2594
- // catchall: merging._def.catchall,
2595
- // shape: () =>
2596
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2597
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2598
- // }) as any;
2599
- // return merged;
2600
- // }
2601
- setKey(key, schema) {
2602
- return this.augment({ [key]: schema });
2603
- }
2604
- // merge<Incoming extends AnyZodObject>(
2605
- // merging: Incoming
2606
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2607
- // ZodObject<
2608
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2609
- // Incoming["_def"]["unknownKeys"],
2610
- // Incoming["_def"]["catchall"]
2611
- // > {
2612
- // // const mergedShape = objectUtil.mergeShapes(
2613
- // // this._def.shape(),
2614
- // // merging._def.shape()
2615
- // // );
2616
- // const merged: any = new ZodObject({
2617
- // unknownKeys: merging._def.unknownKeys,
2618
- // catchall: merging._def.catchall,
2619
- // shape: () =>
2620
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2621
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2622
- // }) as any;
2623
- // return merged;
2624
- // }
2625
- catchall(index) {
2626
- return new _ZodObject({
2627
- ...this._def,
2628
- catchall: index
2629
- });
2630
- }
2631
- pick(mask) {
2632
- const shape = {};
2633
- for (const key of util.objectKeys(mask)) {
2634
- if (mask[key] && this.shape[key]) {
2635
- shape[key] = this.shape[key];
2636
- }
2637
- }
2638
- return new _ZodObject({
2639
- ...this._def,
2640
- shape: () => shape
2641
- });
2642
- }
2643
- omit(mask) {
2644
- const shape = {};
2645
- for (const key of util.objectKeys(this.shape)) {
2646
- if (!mask[key]) {
2647
- shape[key] = this.shape[key];
2648
- }
2649
- }
2650
- return new _ZodObject({
2651
- ...this._def,
2652
- shape: () => shape
2653
- });
2654
- }
2655
- /**
2656
- * @deprecated
2657
- */
2658
- deepPartial() {
2659
- return deepPartialify(this);
2660
- }
2661
- partial(mask) {
2662
- const newShape = {};
2663
- for (const key of util.objectKeys(this.shape)) {
2664
- const fieldSchema = this.shape[key];
2665
- if (mask && !mask[key]) {
2666
- newShape[key] = fieldSchema;
2667
- } else {
2668
- newShape[key] = fieldSchema.optional();
2669
- }
2670
- }
2671
- return new _ZodObject({
2672
- ...this._def,
2673
- shape: () => newShape
2674
- });
2675
- }
2676
- required(mask) {
2677
- const newShape = {};
2678
- for (const key of util.objectKeys(this.shape)) {
2679
- if (mask && !mask[key]) {
2680
- newShape[key] = this.shape[key];
2681
- } else {
2682
- const fieldSchema = this.shape[key];
2683
- let newField = fieldSchema;
2684
- while (newField instanceof ZodOptional) {
2685
- newField = newField._def.innerType;
2686
- }
2687
- newShape[key] = newField;
2688
- }
2689
- }
2690
- return new _ZodObject({
2691
- ...this._def,
2692
- shape: () => newShape
2693
- });
2694
- }
2695
- keyof() {
2696
- return createZodEnum(util.objectKeys(this.shape));
2697
- }
2698
- };
2699
- ZodObject.create = (shape, params) => {
2700
- return new ZodObject({
2701
- shape: () => shape,
2702
- unknownKeys: "strip",
2703
- catchall: ZodNever.create(),
2704
- typeName: ZodFirstPartyTypeKind.ZodObject,
2705
- ...processCreateParams(params)
2706
- });
51
+ //#endregion
52
+ //#region src/utils/errors.ts
53
+ /**
54
+ * Converts an error to MCP-compatible content format
55
+ *
56
+ * @param error - The error to convert (can be any type)
57
+ * @returns A tool result with error content and isError flag
58
+ */
59
+ const errorToMCPContent = (error) => {
60
+ return {
61
+ content: [{
62
+ type: "text",
63
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`
64
+ }],
65
+ isError: true
66
+ };
2707
67
  };
2708
- ZodObject.strictCreate = (shape, params) => {
2709
- return new ZodObject({
2710
- shape: () => shape,
2711
- unknownKeys: "strict",
2712
- catchall: ZodNever.create(),
2713
- typeName: ZodFirstPartyTypeKind.ZodObject,
2714
- ...processCreateParams(params)
2715
- });
2716
- };
2717
- ZodObject.lazycreate = (shape, params) => {
2718
- return new ZodObject({
2719
- shape,
2720
- unknownKeys: "strip",
2721
- catchall: ZodNever.create(),
2722
- typeName: ZodFirstPartyTypeKind.ZodObject,
2723
- ...processCreateParams(params)
2724
- });
2725
- };
2726
- var ZodUnion = class extends ZodType {
2727
- _parse(input) {
2728
- const { ctx } = this._processInputParams(input);
2729
- const options = this._def.options;
2730
- function handleResults(results) {
2731
- for (const result of results) {
2732
- if (result.result.status === "valid") {
2733
- return result.result;
2734
- }
2735
- }
2736
- for (const result of results) {
2737
- if (result.result.status === "dirty") {
2738
- ctx.common.issues.push(...result.ctx.common.issues);
2739
- return result.result;
2740
- }
2741
- }
2742
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2743
- addIssueToContext(ctx, {
2744
- code: ZodIssueCode.invalid_union,
2745
- unionErrors
2746
- });
2747
- return INVALID;
2748
- }
2749
- if (ctx.common.async) {
2750
- return Promise.all(options.map(async (option) => {
2751
- const childCtx = {
2752
- ...ctx,
2753
- common: {
2754
- ...ctx.common,
2755
- issues: []
2756
- },
2757
- parent: null
2758
- };
2759
- return {
2760
- result: await option._parseAsync({
2761
- data: ctx.data,
2762
- path: ctx.path,
2763
- parent: childCtx
2764
- }),
2765
- ctx: childCtx
2766
- };
2767
- })).then(handleResults);
2768
- } else {
2769
- let dirty = void 0;
2770
- const issues = [];
2771
- for (const option of options) {
2772
- const childCtx = {
2773
- ...ctx,
2774
- common: {
2775
- ...ctx.common,
2776
- issues: []
2777
- },
2778
- parent: null
2779
- };
2780
- const result = option._parseSync({
2781
- data: ctx.data,
2782
- path: ctx.path,
2783
- parent: childCtx
2784
- });
2785
- if (result.status === "valid") {
2786
- return result;
2787
- } else if (result.status === "dirty" && !dirty) {
2788
- dirty = { result, ctx: childCtx };
2789
- }
2790
- if (childCtx.common.issues.length) {
2791
- issues.push(childCtx.common.issues);
2792
- }
2793
- }
2794
- if (dirty) {
2795
- ctx.common.issues.push(...dirty.ctx.common.issues);
2796
- return dirty.result;
2797
- }
2798
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
2799
- addIssueToContext(ctx, {
2800
- code: ZodIssueCode.invalid_union,
2801
- unionErrors
2802
- });
2803
- return INVALID;
2804
- }
2805
- }
2806
- get options() {
2807
- return this._def.options;
2808
- }
2809
- };
2810
- ZodUnion.create = (types, params) => {
2811
- return new ZodUnion({
2812
- options: types,
2813
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2814
- ...processCreateParams(params)
2815
- });
2816
- };
2817
- var getDiscriminator = (type) => {
2818
- if (type instanceof ZodLazy) {
2819
- return getDiscriminator(type.schema);
2820
- } else if (type instanceof ZodEffects) {
2821
- return getDiscriminator(type.innerType());
2822
- } else if (type instanceof ZodLiteral) {
2823
- return [type.value];
2824
- } else if (type instanceof ZodEnum) {
2825
- return type.options;
2826
- } else if (type instanceof ZodNativeEnum) {
2827
- return util.objectValues(type.enum);
2828
- } else if (type instanceof ZodDefault) {
2829
- return getDiscriminator(type._def.innerType);
2830
- } else if (type instanceof ZodUndefined) {
2831
- return [void 0];
2832
- } else if (type instanceof ZodNull) {
2833
- return [null];
2834
- } else if (type instanceof ZodOptional) {
2835
- return [void 0, ...getDiscriminator(type.unwrap())];
2836
- } else if (type instanceof ZodNullable) {
2837
- return [null, ...getDiscriminator(type.unwrap())];
2838
- } else if (type instanceof ZodBranded) {
2839
- return getDiscriminator(type.unwrap());
2840
- } else if (type instanceof ZodReadonly) {
2841
- return getDiscriminator(type.unwrap());
2842
- } else if (type instanceof ZodCatch) {
2843
- return getDiscriminator(type._def.innerType);
2844
- } else {
2845
- return [];
2846
- }
2847
- };
2848
- var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2849
- _parse(input) {
2850
- const { ctx } = this._processInputParams(input);
2851
- if (ctx.parsedType !== ZodParsedType.object) {
2852
- addIssueToContext(ctx, {
2853
- code: ZodIssueCode.invalid_type,
2854
- expected: ZodParsedType.object,
2855
- received: ctx.parsedType
2856
- });
2857
- return INVALID;
2858
- }
2859
- const discriminator = this.discriminator;
2860
- const discriminatorValue = ctx.data[discriminator];
2861
- const option = this.optionsMap.get(discriminatorValue);
2862
- if (!option) {
2863
- addIssueToContext(ctx, {
2864
- code: ZodIssueCode.invalid_union_discriminator,
2865
- options: Array.from(this.optionsMap.keys()),
2866
- path: [discriminator]
2867
- });
2868
- return INVALID;
2869
- }
2870
- if (ctx.common.async) {
2871
- return option._parseAsync({
2872
- data: ctx.data,
2873
- path: ctx.path,
2874
- parent: ctx
2875
- });
2876
- } else {
2877
- return option._parseSync({
2878
- data: ctx.data,
2879
- path: ctx.path,
2880
- parent: ctx
2881
- });
2882
- }
2883
- }
2884
- get discriminator() {
2885
- return this._def.discriminator;
2886
- }
2887
- get options() {
2888
- return this._def.options;
2889
- }
2890
- get optionsMap() {
2891
- return this._def.optionsMap;
2892
- }
2893
- /**
2894
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2895
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2896
- * have a different value for each object in the union.
2897
- * @param discriminator the name of the discriminator property
2898
- * @param types an array of object schemas
2899
- * @param params
2900
- */
2901
- static create(discriminator, options, params) {
2902
- const optionsMap = /* @__PURE__ */ new Map();
2903
- for (const type of options) {
2904
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2905
- if (!discriminatorValues.length) {
2906
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2907
- }
2908
- for (const value of discriminatorValues) {
2909
- if (optionsMap.has(value)) {
2910
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2911
- }
2912
- optionsMap.set(value, type);
2913
- }
2914
- }
2915
- return new _ZodDiscriminatedUnion({
2916
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2917
- discriminator,
2918
- options,
2919
- optionsMap,
2920
- ...processCreateParams(params)
2921
- });
2922
- }
2923
- };
2924
- function mergeValues(a, b) {
2925
- const aType = getParsedType(a);
2926
- const bType = getParsedType(b);
2927
- if (a === b) {
2928
- return { valid: true, data: a };
2929
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2930
- const bKeys = util.objectKeys(b);
2931
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2932
- const newObj = { ...a, ...b };
2933
- for (const key of sharedKeys) {
2934
- const sharedValue = mergeValues(a[key], b[key]);
2935
- if (!sharedValue.valid) {
2936
- return { valid: false };
2937
- }
2938
- newObj[key] = sharedValue.data;
2939
- }
2940
- return { valid: true, data: newObj };
2941
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2942
- if (a.length !== b.length) {
2943
- return { valid: false };
2944
- }
2945
- const newArray = [];
2946
- for (let index = 0; index < a.length; index++) {
2947
- const itemA = a[index];
2948
- const itemB = b[index];
2949
- const sharedValue = mergeValues(itemA, itemB);
2950
- if (!sharedValue.valid) {
2951
- return { valid: false };
2952
- }
2953
- newArray.push(sharedValue.data);
2954
- }
2955
- return { valid: true, data: newArray };
2956
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2957
- return { valid: true, data: a };
2958
- } else {
2959
- return { valid: false };
2960
- }
2961
- }
2962
- var ZodIntersection = class extends ZodType {
2963
- _parse(input) {
2964
- const { status, ctx } = this._processInputParams(input);
2965
- const handleParsed = (parsedLeft, parsedRight) => {
2966
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2967
- return INVALID;
2968
- }
2969
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2970
- if (!merged.valid) {
2971
- addIssueToContext(ctx, {
2972
- code: ZodIssueCode.invalid_intersection_types
2973
- });
2974
- return INVALID;
2975
- }
2976
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2977
- status.dirty();
2978
- }
2979
- return { status: status.value, value: merged.data };
2980
- };
2981
- if (ctx.common.async) {
2982
- return Promise.all([
2983
- this._def.left._parseAsync({
2984
- data: ctx.data,
2985
- path: ctx.path,
2986
- parent: ctx
2987
- }),
2988
- this._def.right._parseAsync({
2989
- data: ctx.data,
2990
- path: ctx.path,
2991
- parent: ctx
2992
- })
2993
- ]).then(([left, right]) => handleParsed(left, right));
2994
- } else {
2995
- return handleParsed(this._def.left._parseSync({
2996
- data: ctx.data,
2997
- path: ctx.path,
2998
- parent: ctx
2999
- }), this._def.right._parseSync({
3000
- data: ctx.data,
3001
- path: ctx.path,
3002
- parent: ctx
3003
- }));
3004
- }
3005
- }
3006
- };
3007
- ZodIntersection.create = (left, right, params) => {
3008
- return new ZodIntersection({
3009
- left,
3010
- right,
3011
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
3012
- ...processCreateParams(params)
3013
- });
3014
- };
3015
- var ZodTuple = class _ZodTuple extends ZodType {
3016
- _parse(input) {
3017
- const { status, ctx } = this._processInputParams(input);
3018
- if (ctx.parsedType !== ZodParsedType.array) {
3019
- addIssueToContext(ctx, {
3020
- code: ZodIssueCode.invalid_type,
3021
- expected: ZodParsedType.array,
3022
- received: ctx.parsedType
3023
- });
3024
- return INVALID;
3025
- }
3026
- if (ctx.data.length < this._def.items.length) {
3027
- addIssueToContext(ctx, {
3028
- code: ZodIssueCode.too_small,
3029
- minimum: this._def.items.length,
3030
- inclusive: true,
3031
- exact: false,
3032
- type: "array"
3033
- });
3034
- return INVALID;
3035
- }
3036
- const rest = this._def.rest;
3037
- if (!rest && ctx.data.length > this._def.items.length) {
3038
- addIssueToContext(ctx, {
3039
- code: ZodIssueCode.too_big,
3040
- maximum: this._def.items.length,
3041
- inclusive: true,
3042
- exact: false,
3043
- type: "array"
3044
- });
3045
- status.dirty();
3046
- }
3047
- const items = [...ctx.data].map((item, itemIndex) => {
3048
- const schema = this._def.items[itemIndex] || this._def.rest;
3049
- if (!schema)
3050
- return null;
3051
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3052
- }).filter((x) => !!x);
3053
- if (ctx.common.async) {
3054
- return Promise.all(items).then((results) => {
3055
- return ParseStatus.mergeArray(status, results);
3056
- });
3057
- } else {
3058
- return ParseStatus.mergeArray(status, items);
3059
- }
3060
- }
3061
- get items() {
3062
- return this._def.items;
3063
- }
3064
- rest(rest) {
3065
- return new _ZodTuple({
3066
- ...this._def,
3067
- rest
3068
- });
3069
- }
3070
- };
3071
- ZodTuple.create = (schemas, params) => {
3072
- if (!Array.isArray(schemas)) {
3073
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3074
- }
3075
- return new ZodTuple({
3076
- items: schemas,
3077
- typeName: ZodFirstPartyTypeKind.ZodTuple,
3078
- rest: null,
3079
- ...processCreateParams(params)
3080
- });
3081
- };
3082
- var ZodRecord = class _ZodRecord extends ZodType {
3083
- get keySchema() {
3084
- return this._def.keyType;
3085
- }
3086
- get valueSchema() {
3087
- return this._def.valueType;
3088
- }
3089
- _parse(input) {
3090
- const { status, ctx } = this._processInputParams(input);
3091
- if (ctx.parsedType !== ZodParsedType.object) {
3092
- addIssueToContext(ctx, {
3093
- code: ZodIssueCode.invalid_type,
3094
- expected: ZodParsedType.object,
3095
- received: ctx.parsedType
3096
- });
3097
- return INVALID;
3098
- }
3099
- const pairs = [];
3100
- const keyType = this._def.keyType;
3101
- const valueType = this._def.valueType;
3102
- for (const key in ctx.data) {
3103
- pairs.push({
3104
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3105
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3106
- alwaysSet: key in ctx.data
3107
- });
3108
- }
3109
- if (ctx.common.async) {
3110
- return ParseStatus.mergeObjectAsync(status, pairs);
3111
- } else {
3112
- return ParseStatus.mergeObjectSync(status, pairs);
3113
- }
3114
- }
3115
- get element() {
3116
- return this._def.valueType;
3117
- }
3118
- static create(first, second, third) {
3119
- if (second instanceof ZodType) {
3120
- return new _ZodRecord({
3121
- keyType: first,
3122
- valueType: second,
3123
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3124
- ...processCreateParams(third)
3125
- });
3126
- }
3127
- return new _ZodRecord({
3128
- keyType: ZodString.create(),
3129
- valueType: first,
3130
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3131
- ...processCreateParams(second)
3132
- });
3133
- }
3134
- };
3135
- var ZodMap = class extends ZodType {
3136
- get keySchema() {
3137
- return this._def.keyType;
3138
- }
3139
- get valueSchema() {
3140
- return this._def.valueType;
3141
- }
3142
- _parse(input) {
3143
- const { status, ctx } = this._processInputParams(input);
3144
- if (ctx.parsedType !== ZodParsedType.map) {
3145
- addIssueToContext(ctx, {
3146
- code: ZodIssueCode.invalid_type,
3147
- expected: ZodParsedType.map,
3148
- received: ctx.parsedType
3149
- });
3150
- return INVALID;
3151
- }
3152
- const keyType = this._def.keyType;
3153
- const valueType = this._def.valueType;
3154
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3155
- return {
3156
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3157
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3158
- };
3159
- });
3160
- if (ctx.common.async) {
3161
- const finalMap = /* @__PURE__ */ new Map();
3162
- return Promise.resolve().then(async () => {
3163
- for (const pair of pairs) {
3164
- const key = await pair.key;
3165
- const value = await pair.value;
3166
- if (key.status === "aborted" || value.status === "aborted") {
3167
- return INVALID;
3168
- }
3169
- if (key.status === "dirty" || value.status === "dirty") {
3170
- status.dirty();
3171
- }
3172
- finalMap.set(key.value, value.value);
3173
- }
3174
- return { status: status.value, value: finalMap };
3175
- });
3176
- } else {
3177
- const finalMap = /* @__PURE__ */ new Map();
3178
- for (const pair of pairs) {
3179
- const key = pair.key;
3180
- const value = pair.value;
3181
- if (key.status === "aborted" || value.status === "aborted") {
3182
- return INVALID;
3183
- }
3184
- if (key.status === "dirty" || value.status === "dirty") {
3185
- status.dirty();
3186
- }
3187
- finalMap.set(key.value, value.value);
3188
- }
3189
- return { status: status.value, value: finalMap };
3190
- }
3191
- }
3192
- };
3193
- ZodMap.create = (keyType, valueType, params) => {
3194
- return new ZodMap({
3195
- valueType,
3196
- keyType,
3197
- typeName: ZodFirstPartyTypeKind.ZodMap,
3198
- ...processCreateParams(params)
3199
- });
3200
- };
3201
- var ZodSet = class _ZodSet extends ZodType {
3202
- _parse(input) {
3203
- const { status, ctx } = this._processInputParams(input);
3204
- if (ctx.parsedType !== ZodParsedType.set) {
3205
- addIssueToContext(ctx, {
3206
- code: ZodIssueCode.invalid_type,
3207
- expected: ZodParsedType.set,
3208
- received: ctx.parsedType
3209
- });
3210
- return INVALID;
3211
- }
3212
- const def = this._def;
3213
- if (def.minSize !== null) {
3214
- if (ctx.data.size < def.minSize.value) {
3215
- addIssueToContext(ctx, {
3216
- code: ZodIssueCode.too_small,
3217
- minimum: def.minSize.value,
3218
- type: "set",
3219
- inclusive: true,
3220
- exact: false,
3221
- message: def.minSize.message
3222
- });
3223
- status.dirty();
3224
- }
3225
- }
3226
- if (def.maxSize !== null) {
3227
- if (ctx.data.size > def.maxSize.value) {
3228
- addIssueToContext(ctx, {
3229
- code: ZodIssueCode.too_big,
3230
- maximum: def.maxSize.value,
3231
- type: "set",
3232
- inclusive: true,
3233
- exact: false,
3234
- message: def.maxSize.message
3235
- });
3236
- status.dirty();
3237
- }
3238
- }
3239
- const valueType = this._def.valueType;
3240
- function finalizeSet(elements2) {
3241
- const parsedSet = /* @__PURE__ */ new Set();
3242
- for (const element of elements2) {
3243
- if (element.status === "aborted")
3244
- return INVALID;
3245
- if (element.status === "dirty")
3246
- status.dirty();
3247
- parsedSet.add(element.value);
3248
- }
3249
- return { status: status.value, value: parsedSet };
3250
- }
3251
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3252
- if (ctx.common.async) {
3253
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3254
- } else {
3255
- return finalizeSet(elements);
3256
- }
3257
- }
3258
- min(minSize, message) {
3259
- return new _ZodSet({
3260
- ...this._def,
3261
- minSize: { value: minSize, message: errorUtil.toString(message) }
3262
- });
3263
- }
3264
- max(maxSize, message) {
3265
- return new _ZodSet({
3266
- ...this._def,
3267
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
3268
- });
3269
- }
3270
- size(size, message) {
3271
- return this.min(size, message).max(size, message);
3272
- }
3273
- nonempty(message) {
3274
- return this.min(1, message);
3275
- }
3276
- };
3277
- ZodSet.create = (valueType, params) => {
3278
- return new ZodSet({
3279
- valueType,
3280
- minSize: null,
3281
- maxSize: null,
3282
- typeName: ZodFirstPartyTypeKind.ZodSet,
3283
- ...processCreateParams(params)
3284
- });
3285
- };
3286
- var ZodFunction = class _ZodFunction extends ZodType {
3287
- constructor() {
3288
- super(...arguments);
3289
- this.validate = this.implement;
3290
- }
3291
- _parse(input) {
3292
- const { ctx } = this._processInputParams(input);
3293
- if (ctx.parsedType !== ZodParsedType.function) {
3294
- addIssueToContext(ctx, {
3295
- code: ZodIssueCode.invalid_type,
3296
- expected: ZodParsedType.function,
3297
- received: ctx.parsedType
3298
- });
3299
- return INVALID;
3300
- }
3301
- function makeArgsIssue(args, error) {
3302
- return makeIssue({
3303
- data: args,
3304
- path: ctx.path,
3305
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3306
- issueData: {
3307
- code: ZodIssueCode.invalid_arguments,
3308
- argumentsError: error
3309
- }
3310
- });
3311
- }
3312
- function makeReturnsIssue(returns, error) {
3313
- return makeIssue({
3314
- data: returns,
3315
- path: ctx.path,
3316
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3317
- issueData: {
3318
- code: ZodIssueCode.invalid_return_type,
3319
- returnTypeError: error
3320
- }
3321
- });
3322
- }
3323
- const params = { errorMap: ctx.common.contextualErrorMap };
3324
- const fn = ctx.data;
3325
- if (this._def.returns instanceof ZodPromise) {
3326
- const me = this;
3327
- return OK(async function(...args) {
3328
- const error = new ZodError([]);
3329
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3330
- error.addIssue(makeArgsIssue(args, e));
3331
- throw error;
3332
- });
3333
- const result = await Reflect.apply(fn, this, parsedArgs);
3334
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3335
- error.addIssue(makeReturnsIssue(result, e));
3336
- throw error;
3337
- });
3338
- return parsedReturns;
3339
- });
3340
- } else {
3341
- const me = this;
3342
- return OK(function(...args) {
3343
- const parsedArgs = me._def.args.safeParse(args, params);
3344
- if (!parsedArgs.success) {
3345
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3346
- }
3347
- const result = Reflect.apply(fn, this, parsedArgs.data);
3348
- const parsedReturns = me._def.returns.safeParse(result, params);
3349
- if (!parsedReturns.success) {
3350
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3351
- }
3352
- return parsedReturns.data;
3353
- });
3354
- }
3355
- }
3356
- parameters() {
3357
- return this._def.args;
3358
- }
3359
- returnType() {
3360
- return this._def.returns;
3361
- }
3362
- args(...items) {
3363
- return new _ZodFunction({
3364
- ...this._def,
3365
- args: ZodTuple.create(items).rest(ZodUnknown.create())
3366
- });
3367
- }
3368
- returns(returnType) {
3369
- return new _ZodFunction({
3370
- ...this._def,
3371
- returns: returnType
3372
- });
3373
- }
3374
- implement(func) {
3375
- const validatedFunc = this.parse(func);
3376
- return validatedFunc;
3377
- }
3378
- strictImplement(func) {
3379
- const validatedFunc = this.parse(func);
3380
- return validatedFunc;
3381
- }
3382
- static create(args, returns, params) {
3383
- return new _ZodFunction({
3384
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3385
- returns: returns || ZodUnknown.create(),
3386
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3387
- ...processCreateParams(params)
3388
- });
3389
- }
3390
- };
3391
- var ZodLazy = class extends ZodType {
3392
- get schema() {
3393
- return this._def.getter();
3394
- }
3395
- _parse(input) {
3396
- const { ctx } = this._processInputParams(input);
3397
- const lazySchema = this._def.getter();
3398
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3399
- }
3400
- };
3401
- ZodLazy.create = (getter, params) => {
3402
- return new ZodLazy({
3403
- getter,
3404
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3405
- ...processCreateParams(params)
3406
- });
3407
- };
3408
- var ZodLiteral = class extends ZodType {
3409
- _parse(input) {
3410
- if (input.data !== this._def.value) {
3411
- const ctx = this._getOrReturnCtx(input);
3412
- addIssueToContext(ctx, {
3413
- received: ctx.data,
3414
- code: ZodIssueCode.invalid_literal,
3415
- expected: this._def.value
3416
- });
3417
- return INVALID;
3418
- }
3419
- return { status: "valid", value: input.data };
3420
- }
3421
- get value() {
3422
- return this._def.value;
3423
- }
3424
- };
3425
- ZodLiteral.create = (value, params) => {
3426
- return new ZodLiteral({
3427
- value,
3428
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3429
- ...processCreateParams(params)
3430
- });
3431
- };
3432
- function createZodEnum(values, params) {
3433
- return new ZodEnum({
3434
- values,
3435
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3436
- ...processCreateParams(params)
3437
- });
3438
- }
3439
- var ZodEnum = class _ZodEnum extends ZodType {
3440
- _parse(input) {
3441
- if (typeof input.data !== "string") {
3442
- const ctx = this._getOrReturnCtx(input);
3443
- const expectedValues = this._def.values;
3444
- addIssueToContext(ctx, {
3445
- expected: util.joinValues(expectedValues),
3446
- received: ctx.parsedType,
3447
- code: ZodIssueCode.invalid_type
3448
- });
3449
- return INVALID;
3450
- }
3451
- if (!this._cache) {
3452
- this._cache = new Set(this._def.values);
3453
- }
3454
- if (!this._cache.has(input.data)) {
3455
- const ctx = this._getOrReturnCtx(input);
3456
- const expectedValues = this._def.values;
3457
- addIssueToContext(ctx, {
3458
- received: ctx.data,
3459
- code: ZodIssueCode.invalid_enum_value,
3460
- options: expectedValues
3461
- });
3462
- return INVALID;
3463
- }
3464
- return OK(input.data);
3465
- }
3466
- get options() {
3467
- return this._def.values;
3468
- }
3469
- get enum() {
3470
- const enumValues = {};
3471
- for (const val of this._def.values) {
3472
- enumValues[val] = val;
3473
- }
3474
- return enumValues;
3475
- }
3476
- get Values() {
3477
- const enumValues = {};
3478
- for (const val of this._def.values) {
3479
- enumValues[val] = val;
3480
- }
3481
- return enumValues;
3482
- }
3483
- get Enum() {
3484
- const enumValues = {};
3485
- for (const val of this._def.values) {
3486
- enumValues[val] = val;
3487
- }
3488
- return enumValues;
3489
- }
3490
- extract(values, newDef = this._def) {
3491
- return _ZodEnum.create(values, {
3492
- ...this._def,
3493
- ...newDef
3494
- });
3495
- }
3496
- exclude(values, newDef = this._def) {
3497
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3498
- ...this._def,
3499
- ...newDef
3500
- });
3501
- }
3502
- };
3503
- ZodEnum.create = createZodEnum;
3504
- var ZodNativeEnum = class extends ZodType {
3505
- _parse(input) {
3506
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3507
- const ctx = this._getOrReturnCtx(input);
3508
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3509
- const expectedValues = util.objectValues(nativeEnumValues);
3510
- addIssueToContext(ctx, {
3511
- expected: util.joinValues(expectedValues),
3512
- received: ctx.parsedType,
3513
- code: ZodIssueCode.invalid_type
3514
- });
3515
- return INVALID;
3516
- }
3517
- if (!this._cache) {
3518
- this._cache = new Set(util.getValidEnumValues(this._def.values));
3519
- }
3520
- if (!this._cache.has(input.data)) {
3521
- const expectedValues = util.objectValues(nativeEnumValues);
3522
- addIssueToContext(ctx, {
3523
- received: ctx.data,
3524
- code: ZodIssueCode.invalid_enum_value,
3525
- options: expectedValues
3526
- });
3527
- return INVALID;
3528
- }
3529
- return OK(input.data);
3530
- }
3531
- get enum() {
3532
- return this._def.values;
3533
- }
3534
- };
3535
- ZodNativeEnum.create = (values, params) => {
3536
- return new ZodNativeEnum({
3537
- values,
3538
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3539
- ...processCreateParams(params)
3540
- });
3541
- };
3542
- var ZodPromise = class extends ZodType {
3543
- unwrap() {
3544
- return this._def.type;
3545
- }
3546
- _parse(input) {
3547
- const { ctx } = this._processInputParams(input);
3548
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3549
- addIssueToContext(ctx, {
3550
- code: ZodIssueCode.invalid_type,
3551
- expected: ZodParsedType.promise,
3552
- received: ctx.parsedType
3553
- });
3554
- return INVALID;
3555
- }
3556
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3557
- return OK(promisified.then((data) => {
3558
- return this._def.type.parseAsync(data, {
3559
- path: ctx.path,
3560
- errorMap: ctx.common.contextualErrorMap
3561
- });
3562
- }));
3563
- }
3564
- };
3565
- ZodPromise.create = (schema, params) => {
3566
- return new ZodPromise({
3567
- type: schema,
3568
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3569
- ...processCreateParams(params)
3570
- });
3571
- };
3572
- var ZodEffects = class extends ZodType {
3573
- innerType() {
3574
- return this._def.schema;
3575
- }
3576
- sourceType() {
3577
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3578
- }
3579
- _parse(input) {
3580
- const { status, ctx } = this._processInputParams(input);
3581
- const effect = this._def.effect || null;
3582
- const checkCtx = {
3583
- addIssue: (arg) => {
3584
- addIssueToContext(ctx, arg);
3585
- if (arg.fatal) {
3586
- status.abort();
3587
- } else {
3588
- status.dirty();
3589
- }
3590
- },
3591
- get path() {
3592
- return ctx.path;
3593
- }
3594
- };
3595
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3596
- if (effect.type === "preprocess") {
3597
- const processed = effect.transform(ctx.data, checkCtx);
3598
- if (ctx.common.async) {
3599
- return Promise.resolve(processed).then(async (processed2) => {
3600
- if (status.value === "aborted")
3601
- return INVALID;
3602
- const result = await this._def.schema._parseAsync({
3603
- data: processed2,
3604
- path: ctx.path,
3605
- parent: ctx
3606
- });
3607
- if (result.status === "aborted")
3608
- return INVALID;
3609
- if (result.status === "dirty")
3610
- return DIRTY(result.value);
3611
- if (status.value === "dirty")
3612
- return DIRTY(result.value);
3613
- return result;
3614
- });
3615
- } else {
3616
- if (status.value === "aborted")
3617
- return INVALID;
3618
- const result = this._def.schema._parseSync({
3619
- data: processed,
3620
- path: ctx.path,
3621
- parent: ctx
3622
- });
3623
- if (result.status === "aborted")
3624
- return INVALID;
3625
- if (result.status === "dirty")
3626
- return DIRTY(result.value);
3627
- if (status.value === "dirty")
3628
- return DIRTY(result.value);
3629
- return result;
3630
- }
3631
- }
3632
- if (effect.type === "refinement") {
3633
- const executeRefinement = (acc) => {
3634
- const result = effect.refinement(acc, checkCtx);
3635
- if (ctx.common.async) {
3636
- return Promise.resolve(result);
3637
- }
3638
- if (result instanceof Promise) {
3639
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3640
- }
3641
- return acc;
3642
- };
3643
- if (ctx.common.async === false) {
3644
- const inner = this._def.schema._parseSync({
3645
- data: ctx.data,
3646
- path: ctx.path,
3647
- parent: ctx
3648
- });
3649
- if (inner.status === "aborted")
3650
- return INVALID;
3651
- if (inner.status === "dirty")
3652
- status.dirty();
3653
- executeRefinement(inner.value);
3654
- return { status: status.value, value: inner.value };
3655
- } else {
3656
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3657
- if (inner.status === "aborted")
3658
- return INVALID;
3659
- if (inner.status === "dirty")
3660
- status.dirty();
3661
- return executeRefinement(inner.value).then(() => {
3662
- return { status: status.value, value: inner.value };
3663
- });
3664
- });
3665
- }
3666
- }
3667
- if (effect.type === "transform") {
3668
- if (ctx.common.async === false) {
3669
- const base = this._def.schema._parseSync({
3670
- data: ctx.data,
3671
- path: ctx.path,
3672
- parent: ctx
3673
- });
3674
- if (!isValid(base))
3675
- return INVALID;
3676
- const result = effect.transform(base.value, checkCtx);
3677
- if (result instanceof Promise) {
3678
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3679
- }
3680
- return { status: status.value, value: result };
3681
- } else {
3682
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3683
- if (!isValid(base))
3684
- return INVALID;
3685
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3686
- status: status.value,
3687
- value: result
3688
- }));
3689
- });
3690
- }
3691
- }
3692
- util.assertNever(effect);
3693
- }
3694
- };
3695
- ZodEffects.create = (schema, effect, params) => {
3696
- return new ZodEffects({
3697
- schema,
3698
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3699
- effect,
3700
- ...processCreateParams(params)
3701
- });
3702
- };
3703
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3704
- return new ZodEffects({
3705
- schema,
3706
- effect: { type: "preprocess", transform: preprocess },
3707
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3708
- ...processCreateParams(params)
3709
- });
3710
- };
3711
- var ZodOptional = class extends ZodType {
3712
- _parse(input) {
3713
- const parsedType = this._getType(input);
3714
- if (parsedType === ZodParsedType.undefined) {
3715
- return OK(void 0);
3716
- }
3717
- return this._def.innerType._parse(input);
3718
- }
3719
- unwrap() {
3720
- return this._def.innerType;
3721
- }
3722
- };
3723
- ZodOptional.create = (type, params) => {
3724
- return new ZodOptional({
3725
- innerType: type,
3726
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3727
- ...processCreateParams(params)
3728
- });
3729
- };
3730
- var ZodNullable = class extends ZodType {
3731
- _parse(input) {
3732
- const parsedType = this._getType(input);
3733
- if (parsedType === ZodParsedType.null) {
3734
- return OK(null);
3735
- }
3736
- return this._def.innerType._parse(input);
3737
- }
3738
- unwrap() {
3739
- return this._def.innerType;
3740
- }
3741
- };
3742
- ZodNullable.create = (type, params) => {
3743
- return new ZodNullable({
3744
- innerType: type,
3745
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3746
- ...processCreateParams(params)
3747
- });
3748
- };
3749
- var ZodDefault = class extends ZodType {
3750
- _parse(input) {
3751
- const { ctx } = this._processInputParams(input);
3752
- let data = ctx.data;
3753
- if (ctx.parsedType === ZodParsedType.undefined) {
3754
- data = this._def.defaultValue();
3755
- }
3756
- return this._def.innerType._parse({
3757
- data,
3758
- path: ctx.path,
3759
- parent: ctx
3760
- });
3761
- }
3762
- removeDefault() {
3763
- return this._def.innerType;
3764
- }
3765
- };
3766
- ZodDefault.create = (type, params) => {
3767
- return new ZodDefault({
3768
- innerType: type,
3769
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3770
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3771
- ...processCreateParams(params)
3772
- });
3773
- };
3774
- var ZodCatch = class extends ZodType {
3775
- _parse(input) {
3776
- const { ctx } = this._processInputParams(input);
3777
- const newCtx = {
3778
- ...ctx,
3779
- common: {
3780
- ...ctx.common,
3781
- issues: []
3782
- }
3783
- };
3784
- const result = this._def.innerType._parse({
3785
- data: newCtx.data,
3786
- path: newCtx.path,
3787
- parent: {
3788
- ...newCtx
3789
- }
3790
- });
3791
- if (isAsync(result)) {
3792
- return result.then((result2) => {
3793
- return {
3794
- status: "valid",
3795
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
3796
- get error() {
3797
- return new ZodError(newCtx.common.issues);
3798
- },
3799
- input: newCtx.data
3800
- })
3801
- };
3802
- });
3803
- } else {
3804
- return {
3805
- status: "valid",
3806
- value: result.status === "valid" ? result.value : this._def.catchValue({
3807
- get error() {
3808
- return new ZodError(newCtx.common.issues);
3809
- },
3810
- input: newCtx.data
3811
- })
3812
- };
3813
- }
3814
- }
3815
- removeCatch() {
3816
- return this._def.innerType;
3817
- }
3818
- };
3819
- ZodCatch.create = (type, params) => {
3820
- return new ZodCatch({
3821
- innerType: type,
3822
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3823
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3824
- ...processCreateParams(params)
3825
- });
3826
- };
3827
- var ZodNaN = class extends ZodType {
3828
- _parse(input) {
3829
- const parsedType = this._getType(input);
3830
- if (parsedType !== ZodParsedType.nan) {
3831
- const ctx = this._getOrReturnCtx(input);
3832
- addIssueToContext(ctx, {
3833
- code: ZodIssueCode.invalid_type,
3834
- expected: ZodParsedType.nan,
3835
- received: ctx.parsedType
3836
- });
3837
- return INVALID;
3838
- }
3839
- return { status: "valid", value: input.data };
3840
- }
3841
- };
3842
- ZodNaN.create = (params) => {
3843
- return new ZodNaN({
3844
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3845
- ...processCreateParams(params)
3846
- });
3847
- };
3848
- var BRAND = Symbol("zod_brand");
3849
- var ZodBranded = class extends ZodType {
3850
- _parse(input) {
3851
- const { ctx } = this._processInputParams(input);
3852
- const data = ctx.data;
3853
- return this._def.type._parse({
3854
- data,
3855
- path: ctx.path,
3856
- parent: ctx
3857
- });
3858
- }
3859
- unwrap() {
3860
- return this._def.type;
3861
- }
3862
- };
3863
- var ZodPipeline = class _ZodPipeline extends ZodType {
3864
- _parse(input) {
3865
- const { status, ctx } = this._processInputParams(input);
3866
- if (ctx.common.async) {
3867
- const handleAsync = async () => {
3868
- const inResult = await this._def.in._parseAsync({
3869
- data: ctx.data,
3870
- path: ctx.path,
3871
- parent: ctx
3872
- });
3873
- if (inResult.status === "aborted")
3874
- return INVALID;
3875
- if (inResult.status === "dirty") {
3876
- status.dirty();
3877
- return DIRTY(inResult.value);
3878
- } else {
3879
- return this._def.out._parseAsync({
3880
- data: inResult.value,
3881
- path: ctx.path,
3882
- parent: ctx
3883
- });
3884
- }
3885
- };
3886
- return handleAsync();
3887
- } else {
3888
- const inResult = this._def.in._parseSync({
3889
- data: ctx.data,
3890
- path: ctx.path,
3891
- parent: ctx
3892
- });
3893
- if (inResult.status === "aborted")
3894
- return INVALID;
3895
- if (inResult.status === "dirty") {
3896
- status.dirty();
3897
- return {
3898
- status: "dirty",
3899
- value: inResult.value
3900
- };
3901
- } else {
3902
- return this._def.out._parseSync({
3903
- data: inResult.value,
3904
- path: ctx.path,
3905
- parent: ctx
3906
- });
3907
- }
3908
- }
3909
- }
3910
- static create(a, b) {
3911
- return new _ZodPipeline({
3912
- in: a,
3913
- out: b,
3914
- typeName: ZodFirstPartyTypeKind.ZodPipeline
3915
- });
3916
- }
3917
- };
3918
- var ZodReadonly = class extends ZodType {
3919
- _parse(input) {
3920
- const result = this._def.innerType._parse(input);
3921
- const freeze = (data) => {
3922
- if (isValid(data)) {
3923
- data.value = Object.freeze(data.value);
3924
- }
3925
- return data;
3926
- };
3927
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3928
- }
3929
- unwrap() {
3930
- return this._def.innerType;
3931
- }
3932
- };
3933
- ZodReadonly.create = (type, params) => {
3934
- return new ZodReadonly({
3935
- innerType: type,
3936
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3937
- ...processCreateParams(params)
3938
- });
3939
- };
3940
- function cleanParams(params, data) {
3941
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3942
- const p2 = typeof p === "string" ? { message: p } : p;
3943
- return p2;
3944
- }
3945
- function custom(check, _params = {}, fatal) {
3946
- if (check)
3947
- return ZodAny.create().superRefine((data, ctx) => {
3948
- const r = check(data);
3949
- if (r instanceof Promise) {
3950
- return r.then((r2) => {
3951
- if (!r2) {
3952
- const params = cleanParams(_params, data);
3953
- const _fatal = params.fatal ?? fatal ?? true;
3954
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3955
- }
3956
- });
3957
- }
3958
- if (!r) {
3959
- const params = cleanParams(_params, data);
3960
- const _fatal = params.fatal ?? fatal ?? true;
3961
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3962
- }
3963
- return;
3964
- });
3965
- return ZodAny.create();
3966
- }
3967
- var late = {
3968
- object: ZodObject.lazycreate
3969
- };
3970
- var ZodFirstPartyTypeKind;
3971
- (function(ZodFirstPartyTypeKind2) {
3972
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3973
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3974
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3975
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3976
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3977
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3978
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3979
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3980
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3981
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3982
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3983
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3984
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3985
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3986
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3987
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3988
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3989
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3990
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3991
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3992
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3993
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3994
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3995
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3996
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3997
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3998
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3999
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4000
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4001
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4002
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4003
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4004
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4005
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4006
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4007
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4008
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4009
- var instanceOfType = (cls, params = {
4010
- message: `Input not instance of ${cls.name}`
4011
- }) => custom((data) => data instanceof cls, params);
4012
- var stringType = ZodString.create;
4013
- var numberType = ZodNumber.create;
4014
- var nanType = ZodNaN.create;
4015
- var bigIntType = ZodBigInt.create;
4016
- var booleanType = ZodBoolean.create;
4017
- var dateType = ZodDate.create;
4018
- var symbolType = ZodSymbol.create;
4019
- var undefinedType = ZodUndefined.create;
4020
- var nullType = ZodNull.create;
4021
- var anyType = ZodAny.create;
4022
- var unknownType = ZodUnknown.create;
4023
- var neverType = ZodNever.create;
4024
- var voidType = ZodVoid.create;
4025
- var arrayType = ZodArray.create;
4026
- var objectType = ZodObject.create;
4027
- var strictObjectType = ZodObject.strictCreate;
4028
- var unionType = ZodUnion.create;
4029
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
4030
- var intersectionType = ZodIntersection.create;
4031
- var tupleType = ZodTuple.create;
4032
- var recordType = ZodRecord.create;
4033
- var mapType = ZodMap.create;
4034
- var setType = ZodSet.create;
4035
- var functionType = ZodFunction.create;
4036
- var lazyType = ZodLazy.create;
4037
- var literalType = ZodLiteral.create;
4038
- var enumType = ZodEnum.create;
4039
- var nativeEnumType = ZodNativeEnum.create;
4040
- var promiseType = ZodPromise.create;
4041
- var effectsType = ZodEffects.create;
4042
- var optionalType = ZodOptional.create;
4043
- var nullableType = ZodNullable.create;
4044
- var preprocessType = ZodEffects.createWithPreprocess;
4045
- var pipelineType = ZodPipeline.create;
4046
- var ostring = () => stringType().optional();
4047
- var onumber = () => numberType().optional();
4048
- var oboolean = () => booleanType().optional();
4049
- var coerce = {
4050
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4051
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4052
- boolean: ((arg) => ZodBoolean.create({
4053
- ...arg,
4054
- coerce: true
4055
- })),
4056
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4057
- date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4058
- };
4059
- var NEVER = INVALID;
4060
68
 
4061
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/index.js
4062
- var zod_default = external_exports;
4063
- async function collectTelemetry({
4064
- event,
4065
- mcpSessionId,
4066
- ...payload
4067
- }) {
4068
- if (disableTelemetry) {
4069
- return;
4070
- }
4071
- try {
4072
- return await telemetry("addon-mcp", {
4073
- event,
4074
- mcpSessionId,
4075
- client: mcpSessionIdToClientMap[mcpSessionId],
4076
- ...payload
4077
- });
4078
- } catch (error) {
4079
- logger.debug("Error collecting telemetry:", error);
4080
- }
4081
- }
4082
- var mcpSessionIdToClientMap = {};
4083
- var disableTelemetry = false;
4084
- var setDisableTelemetry = (value = false) => {
4085
- disableTelemetry = value;
4086
- };
69
+ //#endregion
70
+ //#region src/types.ts
71
+ /**
72
+ * Schema for a single story input when requesting story URLs.
73
+ */
74
+ const StoryInput = v.object({
75
+ exportName: v.string(),
76
+ explicitStoryName: v.optional(v.string()),
77
+ absoluteStoryPath: v.string()
78
+ });
79
+ /**
80
+ * Schema for the array of stories to fetch URLs for.
81
+ */
82
+ const StoryInputArray = v.array(StoryInput);
83
+ /**
84
+ * Schema for the output URL array.
85
+ */
86
+ const StoryUrlArray = v.array(v.string());
4087
87
 
4088
- // src/tools/get-story-urls.ts
4089
- var inputStoriesSchema = zod_default.array(
4090
- zod_default.object({
4091
- exportName: zod_default.string(),
4092
- explicitStoryName: zod_default.string().optional(),
4093
- absoluteStoryPath: zod_default.string()
4094
- })
4095
- );
4096
- var outputUrlsSchema = zod_default.array(zod_default.string());
4097
- var GET_STORY_URLS_TOOL_NAME = "get_story_urls";
4098
- function registerStoryUrlsTool({
4099
- server,
4100
- options
4101
- }) {
4102
- const origin = `http://localhost:${options.port}`;
4103
- logger.debug("MCP server origin:", origin);
4104
- server.registerTool(
4105
- GET_STORY_URLS_TOOL_NAME,
4106
- {
4107
- title: "Get stories' URLs",
4108
- description: `Get the URL for one or more stories.`,
4109
- inputSchema: {
4110
- stories: inputStoriesSchema
4111
- },
4112
- outputSchema: {
4113
- urls: outputUrlsSchema
4114
- }
4115
- },
4116
- async ({ stories }, { sessionId }) => {
4117
- const index = await (await fetch(`${origin}/index.json`)).json();
4118
- const entriesList = Object.values(index.entries);
4119
- logger.debug("index entries found:", entriesList.length);
4120
- const result = [];
4121
- let foundStoryCount = 0;
4122
- for (const {
4123
- exportName,
4124
- explicitStoryName,
4125
- absoluteStoryPath
4126
- } of stories) {
4127
- const relativePath = `./${path.relative(process.cwd(), absoluteStoryPath)}`;
4128
- logger.debug("Searching for:");
4129
- logger.debug({
4130
- exportName,
4131
- explicitStoryName,
4132
- absoluteStoryPath,
4133
- relativePath
4134
- });
4135
- const foundStoryId = entriesList.find(
4136
- (entry) => entry.importPath === relativePath && [explicitStoryName, storyNameFromExport(exportName)].includes(
4137
- entry.name
4138
- )
4139
- )?.id;
4140
- if (foundStoryId) {
4141
- logger.debug("Found story ID:", foundStoryId);
4142
- result.push(`${origin}/?path=/story/${foundStoryId}`);
4143
- foundStoryCount++;
4144
- } else {
4145
- logger.debug("No story found");
4146
- let errorMessage = `No story found for export name "${exportName}" with absolute file path "${absoluteStoryPath}"`;
4147
- if (!explicitStoryName) {
4148
- errorMessage += ` (did you forget to pass the explicit story name?)`;
4149
- }
4150
- result.push(errorMessage);
4151
- }
4152
- }
4153
- await collectTelemetry({
4154
- event: "tool:getStoryUrls",
4155
- mcpSessionId: sessionId,
4156
- inputStoryCount: stories.length,
4157
- outputStoryCount: foundStoryCount
4158
- });
4159
- return {
4160
- content: result.map((text) => ({
4161
- type: "text",
4162
- text
4163
- })),
4164
- // Note: Claude Code seems to ignore structuredContent at the moment https://github.com/anthropics/claude-code/issues/4427
4165
- structuredContent: { urls: result }
4166
- };
4167
- }
4168
- );
88
+ //#endregion
89
+ //#region src/tools/get-story-urls.ts
90
+ const GET_STORY_URLS_TOOL_NAME = "get-story-urls";
91
+ const GetStoryUrlsInput = v.object({ stories: StoryInputArray });
92
+ async function addGetStoryUrlsTool(server) {
93
+ server.tool({
94
+ name: GET_STORY_URLS_TOOL_NAME,
95
+ title: "Get stories' URLs",
96
+ description: `Get the URL for one or more stories.`,
97
+ schema: GetStoryUrlsInput
98
+ }, async (input) => {
99
+ try {
100
+ const { origin: origin$1, disableTelemetry } = server.ctx.custom ?? {};
101
+ if (!origin$1) throw new Error("Origin is required in addon context");
102
+ const index = await fetchStoryIndex(origin$1);
103
+ const entriesList = Object.values(index.entries);
104
+ const result = [];
105
+ let foundStoryCount = 0;
106
+ for (const { exportName, explicitStoryName, absoluteStoryPath } of input.stories) {
107
+ const relativePath = `./${path.relative(process.cwd(), absoluteStoryPath)}`;
108
+ logger.debug("Searching for:");
109
+ logger.debug({
110
+ exportName,
111
+ explicitStoryName,
112
+ absoluteStoryPath,
113
+ relativePath
114
+ });
115
+ const foundStoryId = entriesList.find((entry) => entry.importPath === relativePath && [explicitStoryName, storyNameFromExport(exportName)].includes(entry.name))?.id;
116
+ if (foundStoryId) {
117
+ logger.debug("Found story ID:", foundStoryId);
118
+ result.push(`${origin$1}/?path=/story/${foundStoryId}`);
119
+ foundStoryCount++;
120
+ } else {
121
+ logger.debug("No story found");
122
+ let errorMessage = `No story found for export name "${exportName}" with absolute file path "${absoluteStoryPath}"`;
123
+ if (!explicitStoryName) errorMessage += ` (did you forget to pass the explicit story name?)`;
124
+ result.push(errorMessage);
125
+ }
126
+ }
127
+ if (!disableTelemetry) await collectTelemetry({
128
+ event: "tool:getStoryUrls",
129
+ server,
130
+ inputStoryCount: input.stories.length,
131
+ outputStoryCount: foundStoryCount
132
+ });
133
+ return { content: result.map((text) => ({
134
+ type: "text",
135
+ text
136
+ })) };
137
+ } catch (error) {
138
+ return errorToMCPContent(error);
139
+ }
140
+ });
4169
141
  }
4170
142
 
4171
- // src/ui-building-instructions.md
4172
- var ui_building_instructions_default = "# Writing User Interfaces\n\nWhen writing UI, prefer breaking larger components up into smaller parts.\n\nALWAYS write a Storybook story for any component written. If editing a component, ensure appropriate changes have been made to stories for that component.\n\n## Storybook 9 Essential Changes for Story Writing\n\n### Package Consolidation\n\n#### `Meta` and `StoryObj` imports\n\nUpdate story imports to use the framework package:\n\n```diff\n- import { Meta, StoryObj } from '{{RENDERER}}';\n+ import { Meta, StoryObj } from '{{FRAMEWORK}}';\n```\n\n#### Test utility imports\n\nUpdate test imports to use `storybook/test` instead of `@storybook/test`\n\n```diff\n- import { fn } from '@storybook/test';\n+ import { fn } from 'storybook/test';\n```\n\n### Global State Changes\n\nThe `globals` annotation has be renamed to `initialGlobals`:\n\n```diff\n// .storybook/preview.js\nexport default {\n- globals: { theme: 'light' }\n+ initialGlobals: { theme: 'light' }\n};\n```\n\n### Autodocs Configuration\n\nInstead of `parameters.docs.autodocs` in main.js, use tags:\n\n```js\n// .storybook/preview.js or in individual stories\nexport default {\n tags: [\"autodocs\"], // generates autodocs for all stories\n};\n```\n\n### Mocking imports in Storybook\n\nTo mock imports in Storybook, use Storybook's mocking features. ALWAYS mock external dependencies to ensure stories render consistently.\n\n1. **Register in the mock in Storybook's preview file**:\n To mock dependendencies, you MUST register a module mock in `.storybook/preview.ts` (or equivalent):\n\n```js\nimport { sb } from \"storybook/test\";\n\n// Full mock (replaces with empty fn functions)\nsb.mock(import(\"some-library\"));\n```\n\n2. **Specify mock values in stories**:\n You can override the behaviour of the mocks per-story using `beforeEach` and the `mocked()` type function:\n\n```js\nimport { expect, mocked, fn } from 'storybook/test';\nimport { library } from 'some-library';\n\nconst meta = {\n component: AuthButton,\n beforeEach: async () => {\n mocked(library).mockResolvedValue({ user: 'data' });\n },\n};\n\nexport const LoggedIn: Story = {\n play: async ({ canvas }) => {\n await expect(library).toHaveBeenCalled();\n },\n};\n```\n\nBefore doing this ensure you have mocked the import in the preview file.\n\n### Key Requirements\n\n- **Node.js 20+**, **TypeScript 4.9+**, **Vite 5+**\n- React Native uses `.rnstorybook` directory\n- `afterEach` hook is now stable (was `experimental_afterEach`)\n\n## Story Linking Agent Behavior\n\n- ALWAYS provide story links after any changes to stories files, including changes to existing stories.\n- After changing any UI components, ALWAYS search for related stories that might cover the changes you've made. If you find any, provide the story links to the user. THIS IS VERY IMPORTANT, as it allows the user to visually inspect the changes you've made. Even later in a session when changing UI components or stories that have already been linked to previously, YOU MUST PROVIDE THE LINKS AGAIN.\n- Use the {{GET_STORY_URLS_TOOL_NAME}} tool to get the correct URLs for links to stories.\n";
4173
- function registerUIBuildingTool({
4174
- server,
4175
- options
4176
- }) {
4177
- server.registerTool(
4178
- "get_ui_building_instructions",
4179
- {
4180
- title: "UI Component Building Instructions",
4181
- description: `Instructions on how to do UI component development.
143
+ //#endregion
144
+ //#region src/ui-building-instructions.md
145
+ var ui_building_instructions_default = "# Writing User Interfaces\n\nWhen writing UI, prefer breaking larger components up into smaller parts.\n\nALWAYS write a Storybook story for any component written. If editing a component, ensure appropriate changes have been made to stories for that component.\n\n## Storybook 9 Essential Changes for Story Writing\n\n### Package Consolidation\n\n#### `Meta` and `StoryObj` imports\n\nUpdate story imports to use the framework package:\n\n```diff\n- import { Meta, StoryObj } from '{{RENDERER}}';\n+ import { Meta, StoryObj } from '{{FRAMEWORK}}';\n```\n\n#### Test utility imports\n\nUpdate test imports to use `storybook/test` instead of `@storybook/test`\n\n```diff\n- import { fn } from '@storybook/test';\n+ import { fn } from 'storybook/test';\n```\n\n### Global State Changes\n\nThe `globals` annotation has be renamed to `initialGlobals`:\n\n```diff\n// .storybook/preview.js\nexport default {\n- globals: { theme: 'light' }\n+ initialGlobals: { theme: 'light' }\n};\n```\n\n### Autodocs Configuration\n\nInstead of `parameters.docs.autodocs` in main.js, use tags:\n\n```js\n// .storybook/preview.js or in individual stories\nexport default {\n tags: ['autodocs'], // generates autodocs for all stories\n};\n```\n\n### Mocking imports in Storybook\n\nTo mock imports in Storybook, use Storybook's mocking features. ALWAYS mock external dependencies to ensure stories render consistently.\n\n1. **Register in the mock in Storybook's preview file**:\n To mock dependendencies, you MUST register a module mock in `.storybook/preview.ts` (or equivalent):\n\n```js\nimport { sb } from 'storybook/test';\n\n// Full mock (replaces with empty fn functions)\nsb.mock(import('some-library'));\n```\n\n2. **Specify mock values in stories**:\n You can override the behaviour of the mocks per-story using `beforeEach` and the `mocked()` type function:\n\n```js\nimport { expect, mocked, fn } from 'storybook/test';\nimport { library } from 'some-library';\n\nconst meta = {\n component: AuthButton,\n beforeEach: async () => {\n mocked(library).mockResolvedValue({ user: 'data' });\n },\n};\n\nexport const LoggedIn: Story = {\n play: async ({ canvas }) => {\n await expect(library).toHaveBeenCalled();\n },\n};\n```\n\nBefore doing this ensure you have mocked the import in the preview file.\n\n### Key Requirements\n\n- **Node.js 20+**, **TypeScript 4.9+**, **Vite 5+**\n- React Native uses `.rnstorybook` directory\n- `afterEach` hook is now stable (was `experimental_afterEach`)\n\n## Story Linking Agent Behavior\n\n- ALWAYS provide story links after any changes to stories files, including changes to existing stories.\n- After changing any UI components, ALWAYS search for related stories that might cover the changes you've made. If you find any, provide the story links to the user. THIS IS VERY IMPORTANT, as it allows the user to visually inspect the changes you've made. Even later in a session when changing UI components or stories that have already been linked to previously, YOU MUST PROVIDE THE LINKS AGAIN.\n- Use the {{GET_STORY_URLS_TOOL_NAME}} tool to get the correct URLs for links to stories.\n";
146
+
147
+ //#endregion
148
+ //#region src/tools/get-ui-building-instructions.ts
149
+ const GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME = "get-ui-building-instructions";
150
+ async function addGetUIBuildingInstructionsTool(server) {
151
+ server.tool({
152
+ name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
153
+ title: "UI Component Building Instructions",
154
+ description: `Instructions on how to do UI component development.
4182
155
 
4183
156
  ALWAYS call this tool before doing any UI/frontend/React/component development, including but not
4184
- limited to adding or updating new components, pages, screens or layouts.`,
4185
- inputSchema: {}
4186
- },
4187
- async (_, { sessionId }) => {
4188
- await collectTelemetry({
4189
- event: "tool:getUIBuildingInstructions",
4190
- mcpSessionId: sessionId
4191
- });
4192
- const frameworkPreset = await options.presets.apply("framework");
4193
- const framework = typeof frameworkPreset === "string" ? frameworkPreset : frameworkPreset?.name;
4194
- const renderer = frameworkToRendererMap[framework];
4195
- if (!framework || !renderer) {
4196
- logger.debug("Unable to determine framework or renderer", {
4197
- frameworkPreset,
4198
- framework,
4199
- renderer
4200
- });
4201
- }
4202
- const uiInstructions = ui_building_instructions_default.replace("{{FRAMEWORK}}", framework).replace("{{RENDERER}}", renderer ?? framework).replace("{{GET_STORY_URLS_TOOL_NAME}}", GET_STORY_URLS_TOOL_NAME);
4203
- return {
4204
- content: [{ type: "text", text: uiInstructions }]
4205
- };
4206
- }
4207
- );
157
+ limited to adding or updating new components, pages, screens or layouts.`
158
+ }, async () => {
159
+ try {
160
+ const { options, disableTelemetry } = server.ctx.custom ?? {};
161
+ if (!options) throw new Error("Options are required in addon context");
162
+ if (!disableTelemetry) await collectTelemetry({
163
+ event: "tool:getUIBuildingInstructions",
164
+ server
165
+ });
166
+ const frameworkPreset = await options.presets.apply("framework");
167
+ const framework = typeof frameworkPreset === "string" ? frameworkPreset : frameworkPreset?.name;
168
+ const renderer = frameworkToRendererMap[framework];
169
+ return { content: [{
170
+ type: "text",
171
+ text: ui_building_instructions_default.replace("{{FRAMEWORK}}", framework).replace("{{RENDERER}}", renderer ?? framework).replace("{{GET_STORY_URLS_TOOL_NAME}}", GET_STORY_URLS_TOOL_NAME)
172
+ }] };
173
+ } catch (error) {
174
+ return errorToMCPContent(error);
175
+ }
176
+ });
4208
177
  }
4209
- var frameworkToRendererMap = {
4210
- "@storybook/react-vite": "@storybook/react",
4211
- "@storybook/react-webpack5": "@storybook/react",
4212
- "@storybook/nextjs": "@storybook/react",
4213
- "@storybook/nextjs-vite": "@storybook/react",
4214
- "@storybook/react-native-web-vite": "@storybook/react",
4215
- "@storybook/vue3-vite": "@storybook/vue3",
4216
- "@nuxtjs/storybook": "@storybook/vue3",
4217
- "@storybook/angular": "@storybook/angular",
4218
- "@storybook/svelte-vite": "@storybook/svelte",
4219
- "@storybook/sveltekit": "@storybook/svelte",
4220
- "@storybook/preact-vite": "@storybook/preact",
4221
- "@storybook/web-components-vite": "@storybook/web-components",
4222
- "@storybook/html-vite": "@storybook/html"
178
+ const frameworkToRendererMap = {
179
+ "@storybook/react-vite": "@storybook/react",
180
+ "@storybook/react-webpack5": "@storybook/react",
181
+ "@storybook/nextjs": "@storybook/react",
182
+ "@storybook/nextjs-vite": "@storybook/react",
183
+ "@storybook/react-native-web-vite": "@storybook/react",
184
+ "@storybook/vue3-vite": "@storybook/vue3",
185
+ "@nuxtjs/storybook": "@storybook/vue3",
186
+ "@storybook/angular": "@storybook/angular",
187
+ "@storybook/svelte-vite": "@storybook/svelte",
188
+ "@storybook/sveltekit": "@storybook/svelte",
189
+ "@storybook/preact-vite": "@storybook/preact",
190
+ "@storybook/web-components-vite": "@storybook/web-components",
191
+ "@storybook/html-vite": "@storybook/html"
4223
192
  };
4224
193
 
4225
- // src/mcp-handler.ts
4226
- async function createMcpServer(options, client) {
4227
- const transport = new StreamableHTTPServerTransport({
4228
- sessionIdGenerator: () => randomUUID(),
4229
- onsessioninitialized: async (sessionId) => {
4230
- transports[sessionId] = transport;
4231
- const { disableTelemetry: disableTelemetry2 } = await options.presets.apply(
4232
- "core",
4233
- {}
4234
- );
4235
- setDisableTelemetry(disableTelemetry2);
4236
- mcpSessionIdToClientMap[sessionId] = client;
4237
- await collectTelemetry({
4238
- event: "session:initialized",
4239
- mcpSessionId: sessionId
4240
- });
4241
- }
4242
- });
4243
- transport.onclose = () => {
4244
- if (!transport.sessionId) {
4245
- return;
4246
- }
4247
- delete transports[transport.sessionId];
4248
- if (mcpSessionIdToClientMap[transport.sessionId]) {
4249
- delete mcpSessionIdToClientMap[transport.sessionId];
4250
- }
4251
- };
4252
- const server = new McpServer({
4253
- name: package_default.name,
4254
- version: package_default.version
4255
- });
4256
- registerStoryUrlsTool({ server, options });
4257
- registerUIBuildingTool({ server, options });
4258
- server.connect(transport);
4259
- return transport;
194
+ //#endregion
195
+ //#region src/mcp-handler.ts
196
+ let transport;
197
+ let origin;
198
+ let initialize;
199
+ const initializeMCPServer = async (options) => {
200
+ const server = new McpServer({
201
+ name,
202
+ version,
203
+ description
204
+ }, {
205
+ adapter: new ValibotJsonSchemaAdapter(),
206
+ capabilities: { tools: { listChanged: true } }
207
+ }).withContext();
208
+ server.on("initialize", () => {
209
+ if (!options.disableTelemetry) collectTelemetry({
210
+ event: "session:initialized",
211
+ server
212
+ });
213
+ });
214
+ await addGetStoryUrlsTool(server);
215
+ await addGetUIBuildingInstructionsTool(server);
216
+ transport = new HttpTransport(server, { path: null });
217
+ origin = `http://localhost:${options.port}`;
218
+ logger.debug("MCP server origin:", origin);
219
+ };
220
+ /**
221
+ * Vite middleware handler that wraps the MCP handler.
222
+ * This converts Node.js IncomingMessage/ServerResponse to Web API Request/Response.
223
+ */
224
+ const mcpServerHandler = async (req, res, next, options) => {
225
+ const { disableTelemetry = false } = await options.presets.apply("core", {});
226
+ if (!initialize) initialize = initializeMCPServer(options);
227
+ await initialize;
228
+ const webRequest = await incomingMessageToWebRequest(req);
229
+ const addonContext = {
230
+ options,
231
+ origin,
232
+ disableTelemetry
233
+ };
234
+ const response = await transport.respond(webRequest, addonContext);
235
+ if (response) await webResponseToServerResponse(response, res);
236
+ };
237
+ /**
238
+ * Converts a Node.js IncomingMessage to a Web Request.
239
+ */
240
+ async function incomingMessageToWebRequest(req) {
241
+ const host = req.headers.host || "localhost";
242
+ const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
243
+ const url = new URL(req.url || "/", `${protocol}://${host}`);
244
+ const bodyBuffer = await buffer(req);
245
+ return new Request(url, {
246
+ method: req.method,
247
+ headers: req.headers,
248
+ body: bodyBuffer.length > 0 ? new Uint8Array(bodyBuffer) : void 0
249
+ });
4260
250
  }
4261
- var transports = {};
4262
- async function getJson(req) {
4263
- const chunks = [];
4264
- for await (const chunk of req) chunks.push(chunk);
4265
- return JSON.parse(Buffer.concat(chunks).toString());
251
+ /**
252
+ * Converts a Web Response to a Node.js ServerResponse.
253
+ */
254
+ async function webResponseToServerResponse(webResponse, nodeResponse) {
255
+ nodeResponse.statusCode = webResponse.status;
256
+ webResponse.headers.forEach((value, key) => {
257
+ nodeResponse.setHeader(key, value);
258
+ });
259
+ if (webResponse.body) {
260
+ const reader = webResponse.body.getReader();
261
+ try {
262
+ while (true) {
263
+ const { done, value } = await reader.read();
264
+ if (done) break;
265
+ nodeResponse.write(value);
266
+ }
267
+ } finally {
268
+ reader.releaseLock();
269
+ }
270
+ }
271
+ nodeResponse.end();
4266
272
  }
4267
- var handlePostRequest = async (req, res, options) => {
4268
- const sessionId = req.headers["mcp-session-id"];
4269
- let transport;
4270
- const body = await getJson(req);
4271
- if (sessionId && transports[sessionId]) {
4272
- transport = transports[sessionId];
4273
- } else if (!sessionId && isInitializeRequest(body)) {
4274
- transport = await createMcpServer(options, body.params.clientInfo.name);
4275
- } else {
4276
- res.statusCode = 400;
4277
- res.end(
4278
- JSON.stringify(
4279
- {
4280
- jsonrpc: "2.0",
4281
- error: {
4282
- code: -32e3,
4283
- message: "Bad Request: No valid session ID provided"
4284
- },
4285
- id: null
4286
- },
4287
- null,
4288
- 2
4289
- )
4290
- );
4291
- return;
4292
- }
4293
- await transport.handleRequest(req, res, body);
4294
- };
4295
- var handleSessionRequest = async (req, res) => {
4296
- const sessionId = req.headers["mcp-session-id"];
4297
- if (!sessionId || !transports[sessionId]) {
4298
- res.statusCode = 400;
4299
- res.end("Invalid or missing session ID");
4300
- return;
4301
- }
4302
- const transport = transports[sessionId];
4303
- return await transport.handleRequest(req, res);
4304
- };
4305
- var mcpServerHandler = async (req, res, next, options) => {
4306
- switch (req.method) {
4307
- case "POST":
4308
- return await handlePostRequest(req, res, options);
4309
- case "GET":
4310
- case "DELETE":
4311
- return await handleSessionRequest(req, res);
4312
- default:
4313
- next();
4314
- }
4315
- };
4316
273
 
4317
- // src/preset.ts
4318
- var viteFinal = async (config, options) => {
4319
- const mcpHandlerPlugin = {
4320
- name: "storybook:mcp-server",
4321
- configureServer(server) {
4322
- server.middlewares.use(
4323
- "/mcp",
4324
- (req, res, next) => mcpServerHandler(req, res, next, options)
4325
- );
4326
- }
4327
- };
4328
- return {
4329
- ...config,
4330
- plugins: config.plugins.concat(mcpHandlerPlugin)
4331
- };
274
+ //#endregion
275
+ //#region src/preset.ts
276
+ const viteFinal = async (config, options) => {
277
+ const mcpHandlerPlugin = {
278
+ name: "storybook:mcp-server",
279
+ configureServer(server) {
280
+ server.middlewares.use("/mcp", (req, res, next) => mcpServerHandler(req, res, next, options));
281
+ }
282
+ };
283
+ return {
284
+ ...config,
285
+ plugins: config.plugins.concat(mcpHandlerPlugin)
286
+ };
4332
287
  };
4333
288
 
4334
- export { viteFinal };
289
+ //#endregion
290
+ export { viteFinal };