@naparnik/mcp 0.1.0 → 0.10.9

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.
@@ -1,4989 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // ../../super-agent-core/node_modules/zod/v3/external.js
8
- var external_exports = {};
9
- __export(external_exports, {
10
- BRAND: () => BRAND,
11
- DIRTY: () => DIRTY,
12
- EMPTY_PATH: () => EMPTY_PATH,
13
- INVALID: () => INVALID,
14
- NEVER: () => NEVER,
15
- OK: () => OK,
16
- ParseStatus: () => ParseStatus,
17
- Schema: () => ZodType,
18
- ZodAny: () => ZodAny,
19
- ZodArray: () => ZodArray,
20
- ZodBigInt: () => ZodBigInt,
21
- ZodBoolean: () => ZodBoolean,
22
- ZodBranded: () => ZodBranded,
23
- ZodCatch: () => ZodCatch,
24
- ZodDate: () => ZodDate,
25
- ZodDefault: () => ZodDefault,
26
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
27
- ZodEffects: () => ZodEffects,
28
- ZodEnum: () => ZodEnum,
29
- ZodError: () => ZodError,
30
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
31
- ZodFunction: () => ZodFunction,
32
- ZodIntersection: () => ZodIntersection,
33
- ZodIssueCode: () => ZodIssueCode,
34
- ZodLazy: () => ZodLazy,
35
- ZodLiteral: () => ZodLiteral,
36
- ZodMap: () => ZodMap,
37
- ZodNaN: () => ZodNaN,
38
- ZodNativeEnum: () => ZodNativeEnum,
39
- ZodNever: () => ZodNever,
40
- ZodNull: () => ZodNull,
41
- ZodNullable: () => ZodNullable,
42
- ZodNumber: () => ZodNumber,
43
- ZodObject: () => ZodObject,
44
- ZodOptional: () => ZodOptional,
45
- ZodParsedType: () => ZodParsedType,
46
- ZodPipeline: () => ZodPipeline,
47
- ZodPromise: () => ZodPromise,
48
- ZodReadonly: () => ZodReadonly,
49
- ZodRecord: () => ZodRecord,
50
- ZodSchema: () => ZodType,
51
- ZodSet: () => ZodSet,
52
- ZodString: () => ZodString,
53
- ZodSymbol: () => ZodSymbol,
54
- ZodTransformer: () => ZodEffects,
55
- ZodTuple: () => ZodTuple,
56
- ZodType: () => ZodType,
57
- ZodUndefined: () => ZodUndefined,
58
- ZodUnion: () => ZodUnion,
59
- ZodUnknown: () => ZodUnknown,
60
- ZodVoid: () => ZodVoid,
61
- addIssueToContext: () => addIssueToContext,
62
- any: () => anyType,
63
- array: () => arrayType,
64
- bigint: () => bigIntType,
65
- boolean: () => booleanType,
66
- coerce: () => coerce,
67
- custom: () => custom,
68
- date: () => dateType,
69
- datetimeRegex: () => datetimeRegex,
70
- defaultErrorMap: () => en_default,
71
- discriminatedUnion: () => discriminatedUnionType,
72
- effect: () => effectsType,
73
- enum: () => enumType,
74
- function: () => functionType,
75
- getErrorMap: () => getErrorMap,
76
- getParsedType: () => getParsedType,
77
- instanceof: () => instanceOfType,
78
- intersection: () => intersectionType,
79
- isAborted: () => isAborted,
80
- isAsync: () => isAsync,
81
- isDirty: () => isDirty,
82
- isValid: () => isValid,
83
- late: () => late,
84
- lazy: () => lazyType,
85
- literal: () => literalType,
86
- makeIssue: () => makeIssue,
87
- map: () => mapType,
88
- nan: () => nanType,
89
- nativeEnum: () => nativeEnumType,
90
- never: () => neverType,
91
- null: () => nullType,
92
- nullable: () => nullableType,
93
- number: () => numberType,
94
- object: () => objectType,
95
- objectUtil: () => objectUtil,
96
- oboolean: () => oboolean,
97
- onumber: () => onumber,
98
- optional: () => optionalType,
99
- ostring: () => ostring,
100
- pipeline: () => pipelineType,
101
- preprocess: () => preprocessType,
102
- promise: () => promiseType,
103
- quotelessJson: () => quotelessJson,
104
- record: () => recordType,
105
- set: () => setType,
106
- setErrorMap: () => setErrorMap,
107
- strictObject: () => strictObjectType,
108
- string: () => stringType,
109
- symbol: () => symbolType,
110
- transformer: () => effectsType,
111
- tuple: () => tupleType,
112
- undefined: () => undefinedType,
113
- union: () => unionType,
114
- unknown: () => unknownType,
115
- util: () => util,
116
- void: () => voidType
117
- });
118
-
119
- // ../../super-agent-core/node_modules/zod/v3/helpers/util.js
120
- var util;
121
- (function(util2) {
122
- util2.assertEqual = (_) => {
123
- };
124
- function assertIs(_arg) {
125
- }
126
- util2.assertIs = assertIs;
127
- function assertNever(_x) {
128
- throw new Error();
129
- }
130
- util2.assertNever = assertNever;
131
- util2.arrayToEnum = (items) => {
132
- const obj = {};
133
- for (const item of items) {
134
- obj[item] = item;
135
- }
136
- return obj;
137
- };
138
- util2.getValidEnumValues = (obj) => {
139
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
140
- const filtered = {};
141
- for (const k of validKeys) {
142
- filtered[k] = obj[k];
143
- }
144
- return util2.objectValues(filtered);
145
- };
146
- util2.objectValues = (obj) => {
147
- return util2.objectKeys(obj).map(function(e) {
148
- return obj[e];
149
- });
150
- };
151
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
152
- const keys = [];
153
- for (const key in object) {
154
- if (Object.prototype.hasOwnProperty.call(object, key)) {
155
- keys.push(key);
156
- }
157
- }
158
- return keys;
159
- };
160
- util2.find = (arr, checker) => {
161
- for (const item of arr) {
162
- if (checker(item))
163
- return item;
164
- }
165
- return void 0;
166
- };
167
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
168
- function joinValues(array, separator = " | ") {
169
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
170
- }
171
- util2.joinValues = joinValues;
172
- util2.jsonStringifyReplacer = (_, value) => {
173
- if (typeof value === "bigint") {
174
- return value.toString();
175
- }
176
- return value;
177
- };
178
- })(util || (util = {}));
179
- var objectUtil;
180
- (function(objectUtil2) {
181
- objectUtil2.mergeShapes = (first, second) => {
182
- return {
183
- ...first,
184
- ...second
185
- // second overwrites first
186
- };
187
- };
188
- })(objectUtil || (objectUtil = {}));
189
- var ZodParsedType = util.arrayToEnum([
190
- "string",
191
- "nan",
192
- "number",
193
- "integer",
194
- "float",
195
- "boolean",
196
- "date",
197
- "bigint",
198
- "symbol",
199
- "function",
200
- "undefined",
201
- "null",
202
- "array",
203
- "object",
204
- "unknown",
205
- "promise",
206
- "void",
207
- "never",
208
- "map",
209
- "set"
210
- ]);
211
- var getParsedType = (data) => {
212
- const t = typeof data;
213
- switch (t) {
214
- case "undefined":
215
- return ZodParsedType.undefined;
216
- case "string":
217
- return ZodParsedType.string;
218
- case "number":
219
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
220
- case "boolean":
221
- return ZodParsedType.boolean;
222
- case "function":
223
- return ZodParsedType.function;
224
- case "bigint":
225
- return ZodParsedType.bigint;
226
- case "symbol":
227
- return ZodParsedType.symbol;
228
- case "object":
229
- if (Array.isArray(data)) {
230
- return ZodParsedType.array;
231
- }
232
- if (data === null) {
233
- return ZodParsedType.null;
234
- }
235
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
236
- return ZodParsedType.promise;
237
- }
238
- if (typeof Map !== "undefined" && data instanceof Map) {
239
- return ZodParsedType.map;
240
- }
241
- if (typeof Set !== "undefined" && data instanceof Set) {
242
- return ZodParsedType.set;
243
- }
244
- if (typeof Date !== "undefined" && data instanceof Date) {
245
- return ZodParsedType.date;
246
- }
247
- return ZodParsedType.object;
248
- default:
249
- return ZodParsedType.unknown;
250
- }
251
- };
252
-
253
- // ../../super-agent-core/node_modules/zod/v3/ZodError.js
254
- var ZodIssueCode = util.arrayToEnum([
255
- "invalid_type",
256
- "invalid_literal",
257
- "custom",
258
- "invalid_union",
259
- "invalid_union_discriminator",
260
- "invalid_enum_value",
261
- "unrecognized_keys",
262
- "invalid_arguments",
263
- "invalid_return_type",
264
- "invalid_date",
265
- "invalid_string",
266
- "too_small",
267
- "too_big",
268
- "invalid_intersection_types",
269
- "not_multiple_of",
270
- "not_finite"
271
- ]);
272
- var quotelessJson = (obj) => {
273
- const json = JSON.stringify(obj, null, 2);
274
- return json.replace(/"([^"]+)":/g, "$1:");
275
- };
276
- var ZodError = class _ZodError extends Error {
277
- get errors() {
278
- return this.issues;
279
- }
280
- constructor(issues) {
281
- super();
282
- this.issues = [];
283
- this.addIssue = (sub) => {
284
- this.issues = [...this.issues, sub];
285
- };
286
- this.addIssues = (subs = []) => {
287
- this.issues = [...this.issues, ...subs];
288
- };
289
- const actualProto = new.target.prototype;
290
- if (Object.setPrototypeOf) {
291
- Object.setPrototypeOf(this, actualProto);
292
- } else {
293
- this.__proto__ = actualProto;
294
- }
295
- this.name = "ZodError";
296
- this.issues = issues;
297
- }
298
- format(_mapper) {
299
- const mapper = _mapper || function(issue) {
300
- return issue.message;
301
- };
302
- const fieldErrors = { _errors: [] };
303
- const processError = (error) => {
304
- for (const issue of error.issues) {
305
- if (issue.code === "invalid_union") {
306
- issue.unionErrors.map(processError);
307
- } else if (issue.code === "invalid_return_type") {
308
- processError(issue.returnTypeError);
309
- } else if (issue.code === "invalid_arguments") {
310
- processError(issue.argumentsError);
311
- } else if (issue.path.length === 0) {
312
- fieldErrors._errors.push(mapper(issue));
313
- } else {
314
- let curr = fieldErrors;
315
- let i = 0;
316
- while (i < issue.path.length) {
317
- const el = issue.path[i];
318
- const terminal = i === issue.path.length - 1;
319
- if (!terminal) {
320
- curr[el] = curr[el] || { _errors: [] };
321
- } else {
322
- curr[el] = curr[el] || { _errors: [] };
323
- curr[el]._errors.push(mapper(issue));
324
- }
325
- curr = curr[el];
326
- i++;
327
- }
328
- }
329
- }
330
- };
331
- processError(this);
332
- return fieldErrors;
333
- }
334
- static assert(value) {
335
- if (!(value instanceof _ZodError)) {
336
- throw new Error(`Not a ZodError: ${value}`);
337
- }
338
- }
339
- toString() {
340
- return this.message;
341
- }
342
- get message() {
343
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
344
- }
345
- get isEmpty() {
346
- return this.issues.length === 0;
347
- }
348
- flatten(mapper = (issue) => issue.message) {
349
- const fieldErrors = {};
350
- const formErrors = [];
351
- for (const sub of this.issues) {
352
- if (sub.path.length > 0) {
353
- const firstEl = sub.path[0];
354
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
355
- fieldErrors[firstEl].push(mapper(sub));
356
- } else {
357
- formErrors.push(mapper(sub));
358
- }
359
- }
360
- return { formErrors, fieldErrors };
361
- }
362
- get formErrors() {
363
- return this.flatten();
364
- }
365
- };
366
- ZodError.create = (issues) => {
367
- const error = new ZodError(issues);
368
- return error;
369
- };
370
-
371
- // ../../super-agent-core/node_modules/zod/v3/locales/en.js
372
- var errorMap = (issue, _ctx) => {
373
- let message;
374
- switch (issue.code) {
375
- case ZodIssueCode.invalid_type:
376
- if (issue.received === ZodParsedType.undefined) {
377
- message = "Required";
378
- } else {
379
- message = `Expected ${issue.expected}, received ${issue.received}`;
380
- }
381
- break;
382
- case ZodIssueCode.invalid_literal:
383
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
384
- break;
385
- case ZodIssueCode.unrecognized_keys:
386
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
387
- break;
388
- case ZodIssueCode.invalid_union:
389
- message = `Invalid input`;
390
- break;
391
- case ZodIssueCode.invalid_union_discriminator:
392
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
393
- break;
394
- case ZodIssueCode.invalid_enum_value:
395
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
396
- break;
397
- case ZodIssueCode.invalid_arguments:
398
- message = `Invalid function arguments`;
399
- break;
400
- case ZodIssueCode.invalid_return_type:
401
- message = `Invalid function return type`;
402
- break;
403
- case ZodIssueCode.invalid_date:
404
- message = `Invalid date`;
405
- break;
406
- case ZodIssueCode.invalid_string:
407
- if (typeof issue.validation === "object") {
408
- if ("includes" in issue.validation) {
409
- message = `Invalid input: must include "${issue.validation.includes}"`;
410
- if (typeof issue.validation.position === "number") {
411
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
412
- }
413
- } else if ("startsWith" in issue.validation) {
414
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
415
- } else if ("endsWith" in issue.validation) {
416
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
417
- } else {
418
- util.assertNever(issue.validation);
419
- }
420
- } else if (issue.validation !== "regex") {
421
- message = `Invalid ${issue.validation}`;
422
- } else {
423
- message = "Invalid";
424
- }
425
- break;
426
- case ZodIssueCode.too_small:
427
- if (issue.type === "array")
428
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
429
- else if (issue.type === "string")
430
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
431
- else if (issue.type === "number")
432
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
433
- else if (issue.type === "bigint")
434
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
435
- else if (issue.type === "date")
436
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
437
- else
438
- message = "Invalid input";
439
- break;
440
- case ZodIssueCode.too_big:
441
- if (issue.type === "array")
442
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
443
- else if (issue.type === "string")
444
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
445
- else if (issue.type === "number")
446
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
447
- else if (issue.type === "bigint")
448
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
449
- else if (issue.type === "date")
450
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
451
- else
452
- message = "Invalid input";
453
- break;
454
- case ZodIssueCode.custom:
455
- message = `Invalid input`;
456
- break;
457
- case ZodIssueCode.invalid_intersection_types:
458
- message = `Intersection results could not be merged`;
459
- break;
460
- case ZodIssueCode.not_multiple_of:
461
- message = `Number must be a multiple of ${issue.multipleOf}`;
462
- break;
463
- case ZodIssueCode.not_finite:
464
- message = "Number must be finite";
465
- break;
466
- default:
467
- message = _ctx.defaultError;
468
- util.assertNever(issue);
469
- }
470
- return { message };
471
- };
472
- var en_default = errorMap;
473
-
474
- // ../../super-agent-core/node_modules/zod/v3/errors.js
475
- var overrideErrorMap = en_default;
476
- function setErrorMap(map) {
477
- overrideErrorMap = map;
478
- }
479
- function getErrorMap() {
480
- return overrideErrorMap;
481
- }
482
-
483
- // ../../super-agent-core/node_modules/zod/v3/helpers/parseUtil.js
484
- var makeIssue = (params) => {
485
- const { data, path, errorMaps, issueData } = params;
486
- const fullPath = [...path, ...issueData.path || []];
487
- const fullIssue = {
488
- ...issueData,
489
- path: fullPath
490
- };
491
- if (issueData.message !== void 0) {
492
- return {
493
- ...issueData,
494
- path: fullPath,
495
- message: issueData.message
496
- };
497
- }
498
- let errorMessage = "";
499
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
500
- for (const map of maps) {
501
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
502
- }
503
- return {
504
- ...issueData,
505
- path: fullPath,
506
- message: errorMessage
507
- };
508
- };
509
- var EMPTY_PATH = [];
510
- function addIssueToContext(ctx, issueData) {
511
- const overrideMap = getErrorMap();
512
- const issue = makeIssue({
513
- issueData,
514
- data: ctx.data,
515
- path: ctx.path,
516
- errorMaps: [
517
- ctx.common.contextualErrorMap,
518
- // contextual error map is first priority
519
- ctx.schemaErrorMap,
520
- // then schema-bound map if available
521
- overrideMap,
522
- // then global override map
523
- overrideMap === en_default ? void 0 : en_default
524
- // then global default map
525
- ].filter((x) => !!x)
526
- });
527
- ctx.common.issues.push(issue);
528
- }
529
- var ParseStatus = class _ParseStatus {
530
- constructor() {
531
- this.value = "valid";
532
- }
533
- dirty() {
534
- if (this.value === "valid")
535
- this.value = "dirty";
536
- }
537
- abort() {
538
- if (this.value !== "aborted")
539
- this.value = "aborted";
540
- }
541
- static mergeArray(status, results) {
542
- const arrayValue = [];
543
- for (const s of results) {
544
- if (s.status === "aborted")
545
- return INVALID;
546
- if (s.status === "dirty")
547
- status.dirty();
548
- arrayValue.push(s.value);
549
- }
550
- return { status: status.value, value: arrayValue };
551
- }
552
- static async mergeObjectAsync(status, pairs) {
553
- const syncPairs = [];
554
- for (const pair of pairs) {
555
- const key = await pair.key;
556
- const value = await pair.value;
557
- syncPairs.push({
558
- key,
559
- value
560
- });
561
- }
562
- return _ParseStatus.mergeObjectSync(status, syncPairs);
563
- }
564
- static mergeObjectSync(status, pairs) {
565
- const finalObject = {};
566
- for (const pair of pairs) {
567
- const { key, value } = pair;
568
- if (key.status === "aborted")
569
- return INVALID;
570
- if (value.status === "aborted")
571
- return INVALID;
572
- if (key.status === "dirty")
573
- status.dirty();
574
- if (value.status === "dirty")
575
- status.dirty();
576
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
577
- finalObject[key.value] = value.value;
578
- }
579
- }
580
- return { status: status.value, value: finalObject };
581
- }
582
- };
583
- var INVALID = Object.freeze({
584
- status: "aborted"
585
- });
586
- var DIRTY = (value) => ({ status: "dirty", value });
587
- var OK = (value) => ({ status: "valid", value });
588
- var isAborted = (x) => x.status === "aborted";
589
- var isDirty = (x) => x.status === "dirty";
590
- var isValid = (x) => x.status === "valid";
591
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
592
-
593
- // ../../super-agent-core/node_modules/zod/v3/helpers/errorUtil.js
594
- var errorUtil;
595
- (function(errorUtil2) {
596
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
597
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
598
- })(errorUtil || (errorUtil = {}));
599
-
600
- // ../../super-agent-core/node_modules/zod/v3/types.js
601
- var ParseInputLazyPath = class {
602
- constructor(parent, value, path, key) {
603
- this._cachedPath = [];
604
- this.parent = parent;
605
- this.data = value;
606
- this._path = path;
607
- this._key = key;
608
- }
609
- get path() {
610
- if (!this._cachedPath.length) {
611
- if (Array.isArray(this._key)) {
612
- this._cachedPath.push(...this._path, ...this._key);
613
- } else {
614
- this._cachedPath.push(...this._path, this._key);
615
- }
616
- }
617
- return this._cachedPath;
618
- }
619
- };
620
- var handleResult = (ctx, result) => {
621
- if (isValid(result)) {
622
- return { success: true, data: result.value };
623
- } else {
624
- if (!ctx.common.issues.length) {
625
- throw new Error("Validation failed but no issues detected.");
626
- }
627
- return {
628
- success: false,
629
- get error() {
630
- if (this._error)
631
- return this._error;
632
- const error = new ZodError(ctx.common.issues);
633
- this._error = error;
634
- return this._error;
635
- }
636
- };
637
- }
638
- };
639
- function processCreateParams(params) {
640
- if (!params)
641
- return {};
642
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
643
- if (errorMap2 && (invalid_type_error || required_error)) {
644
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
645
- }
646
- if (errorMap2)
647
- return { errorMap: errorMap2, description };
648
- const customMap = (iss, ctx) => {
649
- const { message } = params;
650
- if (iss.code === "invalid_enum_value") {
651
- return { message: message ?? ctx.defaultError };
652
- }
653
- if (typeof ctx.data === "undefined") {
654
- return { message: message ?? required_error ?? ctx.defaultError };
655
- }
656
- if (iss.code !== "invalid_type")
657
- return { message: ctx.defaultError };
658
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
659
- };
660
- return { errorMap: customMap, description };
661
- }
662
- var ZodType = class {
663
- get description() {
664
- return this._def.description;
665
- }
666
- _getType(input) {
667
- return getParsedType(input.data);
668
- }
669
- _getOrReturnCtx(input, ctx) {
670
- return ctx || {
671
- common: input.parent.common,
672
- data: input.data,
673
- parsedType: getParsedType(input.data),
674
- schemaErrorMap: this._def.errorMap,
675
- path: input.path,
676
- parent: input.parent
677
- };
678
- }
679
- _processInputParams(input) {
680
- return {
681
- status: new ParseStatus(),
682
- ctx: {
683
- common: input.parent.common,
684
- data: input.data,
685
- parsedType: getParsedType(input.data),
686
- schemaErrorMap: this._def.errorMap,
687
- path: input.path,
688
- parent: input.parent
689
- }
690
- };
691
- }
692
- _parseSync(input) {
693
- const result = this._parse(input);
694
- if (isAsync(result)) {
695
- throw new Error("Synchronous parse encountered promise.");
696
- }
697
- return result;
698
- }
699
- _parseAsync(input) {
700
- const result = this._parse(input);
701
- return Promise.resolve(result);
702
- }
703
- parse(data, params) {
704
- const result = this.safeParse(data, params);
705
- if (result.success)
706
- return result.data;
707
- throw result.error;
708
- }
709
- safeParse(data, params) {
710
- const ctx = {
711
- common: {
712
- issues: [],
713
- async: params?.async ?? false,
714
- contextualErrorMap: params?.errorMap
715
- },
716
- path: params?.path || [],
717
- schemaErrorMap: this._def.errorMap,
718
- parent: null,
719
- data,
720
- parsedType: getParsedType(data)
721
- };
722
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
723
- return handleResult(ctx, result);
724
- }
725
- "~validate"(data) {
726
- const ctx = {
727
- common: {
728
- issues: [],
729
- async: !!this["~standard"].async
730
- },
731
- path: [],
732
- schemaErrorMap: this._def.errorMap,
733
- parent: null,
734
- data,
735
- parsedType: getParsedType(data)
736
- };
737
- if (!this["~standard"].async) {
738
- try {
739
- const result = this._parseSync({ data, path: [], parent: ctx });
740
- return isValid(result) ? {
741
- value: result.value
742
- } : {
743
- issues: ctx.common.issues
744
- };
745
- } catch (err) {
746
- if (err?.message?.toLowerCase()?.includes("encountered")) {
747
- this["~standard"].async = true;
748
- }
749
- ctx.common = {
750
- issues: [],
751
- async: true
752
- };
753
- }
754
- }
755
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
756
- value: result.value
757
- } : {
758
- issues: ctx.common.issues
759
- });
760
- }
761
- async parseAsync(data, params) {
762
- const result = await this.safeParseAsync(data, params);
763
- if (result.success)
764
- return result.data;
765
- throw result.error;
766
- }
767
- async safeParseAsync(data, params) {
768
- const ctx = {
769
- common: {
770
- issues: [],
771
- contextualErrorMap: params?.errorMap,
772
- async: true
773
- },
774
- path: params?.path || [],
775
- schemaErrorMap: this._def.errorMap,
776
- parent: null,
777
- data,
778
- parsedType: getParsedType(data)
779
- };
780
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
781
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
782
- return handleResult(ctx, result);
783
- }
784
- refine(check, message) {
785
- const getIssueProperties = (val) => {
786
- if (typeof message === "string" || typeof message === "undefined") {
787
- return { message };
788
- } else if (typeof message === "function") {
789
- return message(val);
790
- } else {
791
- return message;
792
- }
793
- };
794
- return this._refinement((val, ctx) => {
795
- const result = check(val);
796
- const setError = () => ctx.addIssue({
797
- code: ZodIssueCode.custom,
798
- ...getIssueProperties(val)
799
- });
800
- if (typeof Promise !== "undefined" && result instanceof Promise) {
801
- return result.then((data) => {
802
- if (!data) {
803
- setError();
804
- return false;
805
- } else {
806
- return true;
807
- }
808
- });
809
- }
810
- if (!result) {
811
- setError();
812
- return false;
813
- } else {
814
- return true;
815
- }
816
- });
817
- }
818
- refinement(check, refinementData) {
819
- return this._refinement((val, ctx) => {
820
- if (!check(val)) {
821
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
822
- return false;
823
- } else {
824
- return true;
825
- }
826
- });
827
- }
828
- _refinement(refinement) {
829
- return new ZodEffects({
830
- schema: this,
831
- typeName: ZodFirstPartyTypeKind.ZodEffects,
832
- effect: { type: "refinement", refinement }
833
- });
834
- }
835
- superRefine(refinement) {
836
- return this._refinement(refinement);
837
- }
838
- constructor(def) {
839
- this.spa = this.safeParseAsync;
840
- this._def = def;
841
- this.parse = this.parse.bind(this);
842
- this.safeParse = this.safeParse.bind(this);
843
- this.parseAsync = this.parseAsync.bind(this);
844
- this.safeParseAsync = this.safeParseAsync.bind(this);
845
- this.spa = this.spa.bind(this);
846
- this.refine = this.refine.bind(this);
847
- this.refinement = this.refinement.bind(this);
848
- this.superRefine = this.superRefine.bind(this);
849
- this.optional = this.optional.bind(this);
850
- this.nullable = this.nullable.bind(this);
851
- this.nullish = this.nullish.bind(this);
852
- this.array = this.array.bind(this);
853
- this.promise = this.promise.bind(this);
854
- this.or = this.or.bind(this);
855
- this.and = this.and.bind(this);
856
- this.transform = this.transform.bind(this);
857
- this.brand = this.brand.bind(this);
858
- this.default = this.default.bind(this);
859
- this.catch = this.catch.bind(this);
860
- this.describe = this.describe.bind(this);
861
- this.pipe = this.pipe.bind(this);
862
- this.readonly = this.readonly.bind(this);
863
- this.isNullable = this.isNullable.bind(this);
864
- this.isOptional = this.isOptional.bind(this);
865
- this["~standard"] = {
866
- version: 1,
867
- vendor: "zod",
868
- validate: (data) => this["~validate"](data)
869
- };
870
- }
871
- optional() {
872
- return ZodOptional.create(this, this._def);
873
- }
874
- nullable() {
875
- return ZodNullable.create(this, this._def);
876
- }
877
- nullish() {
878
- return this.nullable().optional();
879
- }
880
- array() {
881
- return ZodArray.create(this);
882
- }
883
- promise() {
884
- return ZodPromise.create(this, this._def);
885
- }
886
- or(option) {
887
- return ZodUnion.create([this, option], this._def);
888
- }
889
- and(incoming) {
890
- return ZodIntersection.create(this, incoming, this._def);
891
- }
892
- transform(transform) {
893
- return new ZodEffects({
894
- ...processCreateParams(this._def),
895
- schema: this,
896
- typeName: ZodFirstPartyTypeKind.ZodEffects,
897
- effect: { type: "transform", transform }
898
- });
899
- }
900
- default(def) {
901
- const defaultValueFunc = typeof def === "function" ? def : () => def;
902
- return new ZodDefault({
903
- ...processCreateParams(this._def),
904
- innerType: this,
905
- defaultValue: defaultValueFunc,
906
- typeName: ZodFirstPartyTypeKind.ZodDefault
907
- });
908
- }
909
- brand() {
910
- return new ZodBranded({
911
- typeName: ZodFirstPartyTypeKind.ZodBranded,
912
- type: this,
913
- ...processCreateParams(this._def)
914
- });
915
- }
916
- catch(def) {
917
- const catchValueFunc = typeof def === "function" ? def : () => def;
918
- return new ZodCatch({
919
- ...processCreateParams(this._def),
920
- innerType: this,
921
- catchValue: catchValueFunc,
922
- typeName: ZodFirstPartyTypeKind.ZodCatch
923
- });
924
- }
925
- describe(description) {
926
- const This = this.constructor;
927
- return new This({
928
- ...this._def,
929
- description
930
- });
931
- }
932
- pipe(target) {
933
- return ZodPipeline.create(this, target);
934
- }
935
- readonly() {
936
- return ZodReadonly.create(this);
937
- }
938
- isOptional() {
939
- return this.safeParse(void 0).success;
940
- }
941
- isNullable() {
942
- return this.safeParse(null).success;
943
- }
944
- };
945
- var cuidRegex = /^c[^\s-]{8,}$/i;
946
- var cuid2Regex = /^[0-9a-z]+$/;
947
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
948
- 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;
949
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
950
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
951
- 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)?)??$/;
952
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
953
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
954
- var emojiRegex;
955
- 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])$/;
956
- 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])$/;
957
- 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]))$/;
958
- 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])$/;
959
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
960
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
961
- 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])))`;
962
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
963
- function timeRegexSource(args) {
964
- let secondsRegexSource = `[0-5]\\d`;
965
- if (args.precision) {
966
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
967
- } else if (args.precision == null) {
968
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
969
- }
970
- const secondsQuantifier = args.precision ? "+" : "?";
971
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
972
- }
973
- function timeRegex(args) {
974
- return new RegExp(`^${timeRegexSource(args)}$`);
975
- }
976
- function datetimeRegex(args) {
977
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
978
- const opts = [];
979
- opts.push(args.local ? `Z?` : `Z`);
980
- if (args.offset)
981
- opts.push(`([+-]\\d{2}:?\\d{2})`);
982
- regex = `${regex}(${opts.join("|")})`;
983
- return new RegExp(`^${regex}$`);
984
- }
985
- function isValidIP(ip, version) {
986
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
987
- return true;
988
- }
989
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
990
- return true;
991
- }
992
- return false;
993
- }
994
- function isValidJWT(jwt, alg) {
995
- if (!jwtRegex.test(jwt))
996
- return false;
997
- try {
998
- const [header] = jwt.split(".");
999
- if (!header)
1000
- return false;
1001
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1002
- const decoded = JSON.parse(atob(base64));
1003
- if (typeof decoded !== "object" || decoded === null)
1004
- return false;
1005
- if ("typ" in decoded && decoded?.typ !== "JWT")
1006
- return false;
1007
- if (!decoded.alg)
1008
- return false;
1009
- if (alg && decoded.alg !== alg)
1010
- return false;
1011
- return true;
1012
- } catch {
1013
- return false;
1014
- }
1015
- }
1016
- function isValidCidr(ip, version) {
1017
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1018
- return true;
1019
- }
1020
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1021
- return true;
1022
- }
1023
- return false;
1024
- }
1025
- var ZodString = class _ZodString extends ZodType {
1026
- _parse(input) {
1027
- if (this._def.coerce) {
1028
- input.data = String(input.data);
1029
- }
1030
- const parsedType = this._getType(input);
1031
- if (parsedType !== ZodParsedType.string) {
1032
- const ctx2 = this._getOrReturnCtx(input);
1033
- addIssueToContext(ctx2, {
1034
- code: ZodIssueCode.invalid_type,
1035
- expected: ZodParsedType.string,
1036
- received: ctx2.parsedType
1037
- });
1038
- return INVALID;
1039
- }
1040
- const status = new ParseStatus();
1041
- let ctx = void 0;
1042
- for (const check of this._def.checks) {
1043
- if (check.kind === "min") {
1044
- if (input.data.length < check.value) {
1045
- ctx = this._getOrReturnCtx(input, ctx);
1046
- addIssueToContext(ctx, {
1047
- code: ZodIssueCode.too_small,
1048
- minimum: check.value,
1049
- type: "string",
1050
- inclusive: true,
1051
- exact: false,
1052
- message: check.message
1053
- });
1054
- status.dirty();
1055
- }
1056
- } else if (check.kind === "max") {
1057
- if (input.data.length > check.value) {
1058
- ctx = this._getOrReturnCtx(input, ctx);
1059
- addIssueToContext(ctx, {
1060
- code: ZodIssueCode.too_big,
1061
- maximum: check.value,
1062
- type: "string",
1063
- inclusive: true,
1064
- exact: false,
1065
- message: check.message
1066
- });
1067
- status.dirty();
1068
- }
1069
- } else if (check.kind === "length") {
1070
- const tooBig = input.data.length > check.value;
1071
- const tooSmall = input.data.length < check.value;
1072
- if (tooBig || tooSmall) {
1073
- ctx = this._getOrReturnCtx(input, ctx);
1074
- if (tooBig) {
1075
- addIssueToContext(ctx, {
1076
- code: ZodIssueCode.too_big,
1077
- maximum: check.value,
1078
- type: "string",
1079
- inclusive: true,
1080
- exact: true,
1081
- message: check.message
1082
- });
1083
- } else if (tooSmall) {
1084
- addIssueToContext(ctx, {
1085
- code: ZodIssueCode.too_small,
1086
- minimum: check.value,
1087
- type: "string",
1088
- inclusive: true,
1089
- exact: true,
1090
- message: check.message
1091
- });
1092
- }
1093
- status.dirty();
1094
- }
1095
- } else if (check.kind === "email") {
1096
- if (!emailRegex.test(input.data)) {
1097
- ctx = this._getOrReturnCtx(input, ctx);
1098
- addIssueToContext(ctx, {
1099
- validation: "email",
1100
- code: ZodIssueCode.invalid_string,
1101
- message: check.message
1102
- });
1103
- status.dirty();
1104
- }
1105
- } else if (check.kind === "emoji") {
1106
- if (!emojiRegex) {
1107
- emojiRegex = new RegExp(_emojiRegex, "u");
1108
- }
1109
- if (!emojiRegex.test(input.data)) {
1110
- ctx = this._getOrReturnCtx(input, ctx);
1111
- addIssueToContext(ctx, {
1112
- validation: "emoji",
1113
- code: ZodIssueCode.invalid_string,
1114
- message: check.message
1115
- });
1116
- status.dirty();
1117
- }
1118
- } else if (check.kind === "uuid") {
1119
- if (!uuidRegex.test(input.data)) {
1120
- ctx = this._getOrReturnCtx(input, ctx);
1121
- addIssueToContext(ctx, {
1122
- validation: "uuid",
1123
- code: ZodIssueCode.invalid_string,
1124
- message: check.message
1125
- });
1126
- status.dirty();
1127
- }
1128
- } else if (check.kind === "nanoid") {
1129
- if (!nanoidRegex.test(input.data)) {
1130
- ctx = this._getOrReturnCtx(input, ctx);
1131
- addIssueToContext(ctx, {
1132
- validation: "nanoid",
1133
- code: ZodIssueCode.invalid_string,
1134
- message: check.message
1135
- });
1136
- status.dirty();
1137
- }
1138
- } else if (check.kind === "cuid") {
1139
- if (!cuidRegex.test(input.data)) {
1140
- ctx = this._getOrReturnCtx(input, ctx);
1141
- addIssueToContext(ctx, {
1142
- validation: "cuid",
1143
- code: ZodIssueCode.invalid_string,
1144
- message: check.message
1145
- });
1146
- status.dirty();
1147
- }
1148
- } else if (check.kind === "cuid2") {
1149
- if (!cuid2Regex.test(input.data)) {
1150
- ctx = this._getOrReturnCtx(input, ctx);
1151
- addIssueToContext(ctx, {
1152
- validation: "cuid2",
1153
- code: ZodIssueCode.invalid_string,
1154
- message: check.message
1155
- });
1156
- status.dirty();
1157
- }
1158
- } else if (check.kind === "ulid") {
1159
- if (!ulidRegex.test(input.data)) {
1160
- ctx = this._getOrReturnCtx(input, ctx);
1161
- addIssueToContext(ctx, {
1162
- validation: "ulid",
1163
- code: ZodIssueCode.invalid_string,
1164
- message: check.message
1165
- });
1166
- status.dirty();
1167
- }
1168
- } else if (check.kind === "url") {
1169
- try {
1170
- new URL(input.data);
1171
- } catch {
1172
- ctx = this._getOrReturnCtx(input, ctx);
1173
- addIssueToContext(ctx, {
1174
- validation: "url",
1175
- code: ZodIssueCode.invalid_string,
1176
- message: check.message
1177
- });
1178
- status.dirty();
1179
- }
1180
- } else if (check.kind === "regex") {
1181
- check.regex.lastIndex = 0;
1182
- const testResult = check.regex.test(input.data);
1183
- if (!testResult) {
1184
- ctx = this._getOrReturnCtx(input, ctx);
1185
- addIssueToContext(ctx, {
1186
- validation: "regex",
1187
- code: ZodIssueCode.invalid_string,
1188
- message: check.message
1189
- });
1190
- status.dirty();
1191
- }
1192
- } else if (check.kind === "trim") {
1193
- input.data = input.data.trim();
1194
- } else if (check.kind === "includes") {
1195
- if (!input.data.includes(check.value, check.position)) {
1196
- ctx = this._getOrReturnCtx(input, ctx);
1197
- addIssueToContext(ctx, {
1198
- code: ZodIssueCode.invalid_string,
1199
- validation: { includes: check.value, position: check.position },
1200
- message: check.message
1201
- });
1202
- status.dirty();
1203
- }
1204
- } else if (check.kind === "toLowerCase") {
1205
- input.data = input.data.toLowerCase();
1206
- } else if (check.kind === "toUpperCase") {
1207
- input.data = input.data.toUpperCase();
1208
- } else if (check.kind === "startsWith") {
1209
- if (!input.data.startsWith(check.value)) {
1210
- ctx = this._getOrReturnCtx(input, ctx);
1211
- addIssueToContext(ctx, {
1212
- code: ZodIssueCode.invalid_string,
1213
- validation: { startsWith: check.value },
1214
- message: check.message
1215
- });
1216
- status.dirty();
1217
- }
1218
- } else if (check.kind === "endsWith") {
1219
- if (!input.data.endsWith(check.value)) {
1220
- ctx = this._getOrReturnCtx(input, ctx);
1221
- addIssueToContext(ctx, {
1222
- code: ZodIssueCode.invalid_string,
1223
- validation: { endsWith: check.value },
1224
- message: check.message
1225
- });
1226
- status.dirty();
1227
- }
1228
- } else if (check.kind === "datetime") {
1229
- const regex = datetimeRegex(check);
1230
- if (!regex.test(input.data)) {
1231
- ctx = this._getOrReturnCtx(input, ctx);
1232
- addIssueToContext(ctx, {
1233
- code: ZodIssueCode.invalid_string,
1234
- validation: "datetime",
1235
- message: check.message
1236
- });
1237
- status.dirty();
1238
- }
1239
- } else if (check.kind === "date") {
1240
- const regex = dateRegex;
1241
- if (!regex.test(input.data)) {
1242
- ctx = this._getOrReturnCtx(input, ctx);
1243
- addIssueToContext(ctx, {
1244
- code: ZodIssueCode.invalid_string,
1245
- validation: "date",
1246
- message: check.message
1247
- });
1248
- status.dirty();
1249
- }
1250
- } else if (check.kind === "time") {
1251
- const regex = timeRegex(check);
1252
- if (!regex.test(input.data)) {
1253
- ctx = this._getOrReturnCtx(input, ctx);
1254
- addIssueToContext(ctx, {
1255
- code: ZodIssueCode.invalid_string,
1256
- validation: "time",
1257
- message: check.message
1258
- });
1259
- status.dirty();
1260
- }
1261
- } else if (check.kind === "duration") {
1262
- if (!durationRegex.test(input.data)) {
1263
- ctx = this._getOrReturnCtx(input, ctx);
1264
- addIssueToContext(ctx, {
1265
- validation: "duration",
1266
- code: ZodIssueCode.invalid_string,
1267
- message: check.message
1268
- });
1269
- status.dirty();
1270
- }
1271
- } else if (check.kind === "ip") {
1272
- if (!isValidIP(input.data, check.version)) {
1273
- ctx = this._getOrReturnCtx(input, ctx);
1274
- addIssueToContext(ctx, {
1275
- validation: "ip",
1276
- code: ZodIssueCode.invalid_string,
1277
- message: check.message
1278
- });
1279
- status.dirty();
1280
- }
1281
- } else if (check.kind === "jwt") {
1282
- if (!isValidJWT(input.data, check.alg)) {
1283
- ctx = this._getOrReturnCtx(input, ctx);
1284
- addIssueToContext(ctx, {
1285
- validation: "jwt",
1286
- code: ZodIssueCode.invalid_string,
1287
- message: check.message
1288
- });
1289
- status.dirty();
1290
- }
1291
- } else if (check.kind === "cidr") {
1292
- if (!isValidCidr(input.data, check.version)) {
1293
- ctx = this._getOrReturnCtx(input, ctx);
1294
- addIssueToContext(ctx, {
1295
- validation: "cidr",
1296
- code: ZodIssueCode.invalid_string,
1297
- message: check.message
1298
- });
1299
- status.dirty();
1300
- }
1301
- } else if (check.kind === "base64") {
1302
- if (!base64Regex.test(input.data)) {
1303
- ctx = this._getOrReturnCtx(input, ctx);
1304
- addIssueToContext(ctx, {
1305
- validation: "base64",
1306
- code: ZodIssueCode.invalid_string,
1307
- message: check.message
1308
- });
1309
- status.dirty();
1310
- }
1311
- } else if (check.kind === "base64url") {
1312
- if (!base64urlRegex.test(input.data)) {
1313
- ctx = this._getOrReturnCtx(input, ctx);
1314
- addIssueToContext(ctx, {
1315
- validation: "base64url",
1316
- code: ZodIssueCode.invalid_string,
1317
- message: check.message
1318
- });
1319
- status.dirty();
1320
- }
1321
- } else {
1322
- util.assertNever(check);
1323
- }
1324
- }
1325
- return { status: status.value, value: input.data };
1326
- }
1327
- _regex(regex, validation, message) {
1328
- return this.refinement((data) => regex.test(data), {
1329
- validation,
1330
- code: ZodIssueCode.invalid_string,
1331
- ...errorUtil.errToObj(message)
1332
- });
1333
- }
1334
- _addCheck(check) {
1335
- return new _ZodString({
1336
- ...this._def,
1337
- checks: [...this._def.checks, check]
1338
- });
1339
- }
1340
- email(message) {
1341
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1342
- }
1343
- url(message) {
1344
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1345
- }
1346
- emoji(message) {
1347
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1348
- }
1349
- uuid(message) {
1350
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1351
- }
1352
- nanoid(message) {
1353
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1354
- }
1355
- cuid(message) {
1356
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1357
- }
1358
- cuid2(message) {
1359
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1360
- }
1361
- ulid(message) {
1362
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1363
- }
1364
- base64(message) {
1365
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1366
- }
1367
- base64url(message) {
1368
- return this._addCheck({
1369
- kind: "base64url",
1370
- ...errorUtil.errToObj(message)
1371
- });
1372
- }
1373
- jwt(options) {
1374
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1375
- }
1376
- ip(options) {
1377
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1378
- }
1379
- cidr(options) {
1380
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1381
- }
1382
- datetime(options) {
1383
- if (typeof options === "string") {
1384
- return this._addCheck({
1385
- kind: "datetime",
1386
- precision: null,
1387
- offset: false,
1388
- local: false,
1389
- message: options
1390
- });
1391
- }
1392
- return this._addCheck({
1393
- kind: "datetime",
1394
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1395
- offset: options?.offset ?? false,
1396
- local: options?.local ?? false,
1397
- ...errorUtil.errToObj(options?.message)
1398
- });
1399
- }
1400
- date(message) {
1401
- return this._addCheck({ kind: "date", message });
1402
- }
1403
- time(options) {
1404
- if (typeof options === "string") {
1405
- return this._addCheck({
1406
- kind: "time",
1407
- precision: null,
1408
- message: options
1409
- });
1410
- }
1411
- return this._addCheck({
1412
- kind: "time",
1413
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1414
- ...errorUtil.errToObj(options?.message)
1415
- });
1416
- }
1417
- duration(message) {
1418
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1419
- }
1420
- regex(regex, message) {
1421
- return this._addCheck({
1422
- kind: "regex",
1423
- regex,
1424
- ...errorUtil.errToObj(message)
1425
- });
1426
- }
1427
- includes(value, options) {
1428
- return this._addCheck({
1429
- kind: "includes",
1430
- value,
1431
- position: options?.position,
1432
- ...errorUtil.errToObj(options?.message)
1433
- });
1434
- }
1435
- startsWith(value, message) {
1436
- return this._addCheck({
1437
- kind: "startsWith",
1438
- value,
1439
- ...errorUtil.errToObj(message)
1440
- });
1441
- }
1442
- endsWith(value, message) {
1443
- return this._addCheck({
1444
- kind: "endsWith",
1445
- value,
1446
- ...errorUtil.errToObj(message)
1447
- });
1448
- }
1449
- min(minLength, message) {
1450
- return this._addCheck({
1451
- kind: "min",
1452
- value: minLength,
1453
- ...errorUtil.errToObj(message)
1454
- });
1455
- }
1456
- max(maxLength, message) {
1457
- return this._addCheck({
1458
- kind: "max",
1459
- value: maxLength,
1460
- ...errorUtil.errToObj(message)
1461
- });
1462
- }
1463
- length(len, message) {
1464
- return this._addCheck({
1465
- kind: "length",
1466
- value: len,
1467
- ...errorUtil.errToObj(message)
1468
- });
1469
- }
1470
- /**
1471
- * Equivalent to `.min(1)`
1472
- */
1473
- nonempty(message) {
1474
- return this.min(1, errorUtil.errToObj(message));
1475
- }
1476
- trim() {
1477
- return new _ZodString({
1478
- ...this._def,
1479
- checks: [...this._def.checks, { kind: "trim" }]
1480
- });
1481
- }
1482
- toLowerCase() {
1483
- return new _ZodString({
1484
- ...this._def,
1485
- checks: [...this._def.checks, { kind: "toLowerCase" }]
1486
- });
1487
- }
1488
- toUpperCase() {
1489
- return new _ZodString({
1490
- ...this._def,
1491
- checks: [...this._def.checks, { kind: "toUpperCase" }]
1492
- });
1493
- }
1494
- get isDatetime() {
1495
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
1496
- }
1497
- get isDate() {
1498
- return !!this._def.checks.find((ch) => ch.kind === "date");
1499
- }
1500
- get isTime() {
1501
- return !!this._def.checks.find((ch) => ch.kind === "time");
1502
- }
1503
- get isDuration() {
1504
- return !!this._def.checks.find((ch) => ch.kind === "duration");
1505
- }
1506
- get isEmail() {
1507
- return !!this._def.checks.find((ch) => ch.kind === "email");
1508
- }
1509
- get isURL() {
1510
- return !!this._def.checks.find((ch) => ch.kind === "url");
1511
- }
1512
- get isEmoji() {
1513
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1514
- }
1515
- get isUUID() {
1516
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1517
- }
1518
- get isNANOID() {
1519
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1520
- }
1521
- get isCUID() {
1522
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1523
- }
1524
- get isCUID2() {
1525
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1526
- }
1527
- get isULID() {
1528
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1529
- }
1530
- get isIP() {
1531
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1532
- }
1533
- get isCIDR() {
1534
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1535
- }
1536
- get isBase64() {
1537
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1538
- }
1539
- get isBase64url() {
1540
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1541
- }
1542
- get minLength() {
1543
- let min = null;
1544
- for (const ch of this._def.checks) {
1545
- if (ch.kind === "min") {
1546
- if (min === null || ch.value > min)
1547
- min = ch.value;
1548
- }
1549
- }
1550
- return min;
1551
- }
1552
- get maxLength() {
1553
- let max = null;
1554
- for (const ch of this._def.checks) {
1555
- if (ch.kind === "max") {
1556
- if (max === null || ch.value < max)
1557
- max = ch.value;
1558
- }
1559
- }
1560
- return max;
1561
- }
1562
- };
1563
- ZodString.create = (params) => {
1564
- return new ZodString({
1565
- checks: [],
1566
- typeName: ZodFirstPartyTypeKind.ZodString,
1567
- coerce: params?.coerce ?? false,
1568
- ...processCreateParams(params)
1569
- });
1570
- };
1571
- function floatSafeRemainder(val, step) {
1572
- const valDecCount = (val.toString().split(".")[1] || "").length;
1573
- const stepDecCount = (step.toString().split(".")[1] || "").length;
1574
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1575
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1576
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1577
- return valInt % stepInt / 10 ** decCount;
1578
- }
1579
- var ZodNumber = class _ZodNumber extends ZodType {
1580
- constructor() {
1581
- super(...arguments);
1582
- this.min = this.gte;
1583
- this.max = this.lte;
1584
- this.step = this.multipleOf;
1585
- }
1586
- _parse(input) {
1587
- if (this._def.coerce) {
1588
- input.data = Number(input.data);
1589
- }
1590
- const parsedType = this._getType(input);
1591
- if (parsedType !== ZodParsedType.number) {
1592
- const ctx2 = this._getOrReturnCtx(input);
1593
- addIssueToContext(ctx2, {
1594
- code: ZodIssueCode.invalid_type,
1595
- expected: ZodParsedType.number,
1596
- received: ctx2.parsedType
1597
- });
1598
- return INVALID;
1599
- }
1600
- let ctx = void 0;
1601
- const status = new ParseStatus();
1602
- for (const check of this._def.checks) {
1603
- if (check.kind === "int") {
1604
- if (!util.isInteger(input.data)) {
1605
- ctx = this._getOrReturnCtx(input, ctx);
1606
- addIssueToContext(ctx, {
1607
- code: ZodIssueCode.invalid_type,
1608
- expected: "integer",
1609
- received: "float",
1610
- message: check.message
1611
- });
1612
- status.dirty();
1613
- }
1614
- } else if (check.kind === "min") {
1615
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1616
- if (tooSmall) {
1617
- ctx = this._getOrReturnCtx(input, ctx);
1618
- addIssueToContext(ctx, {
1619
- code: ZodIssueCode.too_small,
1620
- minimum: check.value,
1621
- type: "number",
1622
- inclusive: check.inclusive,
1623
- exact: false,
1624
- message: check.message
1625
- });
1626
- status.dirty();
1627
- }
1628
- } else if (check.kind === "max") {
1629
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1630
- if (tooBig) {
1631
- ctx = this._getOrReturnCtx(input, ctx);
1632
- addIssueToContext(ctx, {
1633
- code: ZodIssueCode.too_big,
1634
- maximum: 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 === "multipleOf") {
1643
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1644
- ctx = this._getOrReturnCtx(input, ctx);
1645
- addIssueToContext(ctx, {
1646
- code: ZodIssueCode.not_multiple_of,
1647
- multipleOf: check.value,
1648
- message: check.message
1649
- });
1650
- status.dirty();
1651
- }
1652
- } else if (check.kind === "finite") {
1653
- if (!Number.isFinite(input.data)) {
1654
- ctx = this._getOrReturnCtx(input, ctx);
1655
- addIssueToContext(ctx, {
1656
- code: ZodIssueCode.not_finite,
1657
- message: check.message
1658
- });
1659
- status.dirty();
1660
- }
1661
- } else {
1662
- util.assertNever(check);
1663
- }
1664
- }
1665
- return { status: status.value, value: input.data };
1666
- }
1667
- gte(value, message) {
1668
- return this.setLimit("min", value, true, errorUtil.toString(message));
1669
- }
1670
- gt(value, message) {
1671
- return this.setLimit("min", value, false, errorUtil.toString(message));
1672
- }
1673
- lte(value, message) {
1674
- return this.setLimit("max", value, true, errorUtil.toString(message));
1675
- }
1676
- lt(value, message) {
1677
- return this.setLimit("max", value, false, errorUtil.toString(message));
1678
- }
1679
- setLimit(kind, value, inclusive, message) {
1680
- return new _ZodNumber({
1681
- ...this._def,
1682
- checks: [
1683
- ...this._def.checks,
1684
- {
1685
- kind,
1686
- value,
1687
- inclusive,
1688
- message: errorUtil.toString(message)
1689
- }
1690
- ]
1691
- });
1692
- }
1693
- _addCheck(check) {
1694
- return new _ZodNumber({
1695
- ...this._def,
1696
- checks: [...this._def.checks, check]
1697
- });
1698
- }
1699
- int(message) {
1700
- return this._addCheck({
1701
- kind: "int",
1702
- message: errorUtil.toString(message)
1703
- });
1704
- }
1705
- positive(message) {
1706
- return this._addCheck({
1707
- kind: "min",
1708
- value: 0,
1709
- inclusive: false,
1710
- message: errorUtil.toString(message)
1711
- });
1712
- }
1713
- negative(message) {
1714
- return this._addCheck({
1715
- kind: "max",
1716
- value: 0,
1717
- inclusive: false,
1718
- message: errorUtil.toString(message)
1719
- });
1720
- }
1721
- nonpositive(message) {
1722
- return this._addCheck({
1723
- kind: "max",
1724
- value: 0,
1725
- inclusive: true,
1726
- message: errorUtil.toString(message)
1727
- });
1728
- }
1729
- nonnegative(message) {
1730
- return this._addCheck({
1731
- kind: "min",
1732
- value: 0,
1733
- inclusive: true,
1734
- message: errorUtil.toString(message)
1735
- });
1736
- }
1737
- multipleOf(value, message) {
1738
- return this._addCheck({
1739
- kind: "multipleOf",
1740
- value,
1741
- message: errorUtil.toString(message)
1742
- });
1743
- }
1744
- finite(message) {
1745
- return this._addCheck({
1746
- kind: "finite",
1747
- message: errorUtil.toString(message)
1748
- });
1749
- }
1750
- safe(message) {
1751
- return this._addCheck({
1752
- kind: "min",
1753
- inclusive: true,
1754
- value: Number.MIN_SAFE_INTEGER,
1755
- message: errorUtil.toString(message)
1756
- })._addCheck({
1757
- kind: "max",
1758
- inclusive: true,
1759
- value: Number.MAX_SAFE_INTEGER,
1760
- message: errorUtil.toString(message)
1761
- });
1762
- }
1763
- get minValue() {
1764
- let min = null;
1765
- for (const ch of this._def.checks) {
1766
- if (ch.kind === "min") {
1767
- if (min === null || ch.value > min)
1768
- min = ch.value;
1769
- }
1770
- }
1771
- return min;
1772
- }
1773
- get maxValue() {
1774
- let max = null;
1775
- for (const ch of this._def.checks) {
1776
- if (ch.kind === "max") {
1777
- if (max === null || ch.value < max)
1778
- max = ch.value;
1779
- }
1780
- }
1781
- return max;
1782
- }
1783
- get isInt() {
1784
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1785
- }
1786
- get isFinite() {
1787
- let max = null;
1788
- let min = null;
1789
- for (const ch of this._def.checks) {
1790
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1791
- return true;
1792
- } else if (ch.kind === "min") {
1793
- if (min === null || ch.value > min)
1794
- min = ch.value;
1795
- } else if (ch.kind === "max") {
1796
- if (max === null || ch.value < max)
1797
- max = ch.value;
1798
- }
1799
- }
1800
- return Number.isFinite(min) && Number.isFinite(max);
1801
- }
1802
- };
1803
- ZodNumber.create = (params) => {
1804
- return new ZodNumber({
1805
- checks: [],
1806
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1807
- coerce: params?.coerce || false,
1808
- ...processCreateParams(params)
1809
- });
1810
- };
1811
- var ZodBigInt = class _ZodBigInt extends ZodType {
1812
- constructor() {
1813
- super(...arguments);
1814
- this.min = this.gte;
1815
- this.max = this.lte;
1816
- }
1817
- _parse(input) {
1818
- if (this._def.coerce) {
1819
- try {
1820
- input.data = BigInt(input.data);
1821
- } catch {
1822
- return this._getInvalidInput(input);
1823
- }
1824
- }
1825
- const parsedType = this._getType(input);
1826
- if (parsedType !== ZodParsedType.bigint) {
1827
- return this._getInvalidInput(input);
1828
- }
1829
- let ctx = void 0;
1830
- const status = new ParseStatus();
1831
- for (const check of this._def.checks) {
1832
- if (check.kind === "min") {
1833
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1834
- if (tooSmall) {
1835
- ctx = this._getOrReturnCtx(input, ctx);
1836
- addIssueToContext(ctx, {
1837
- code: ZodIssueCode.too_small,
1838
- type: "bigint",
1839
- minimum: check.value,
1840
- inclusive: check.inclusive,
1841
- message: check.message
1842
- });
1843
- status.dirty();
1844
- }
1845
- } else if (check.kind === "max") {
1846
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1847
- if (tooBig) {
1848
- ctx = this._getOrReturnCtx(input, ctx);
1849
- addIssueToContext(ctx, {
1850
- code: ZodIssueCode.too_big,
1851
- type: "bigint",
1852
- maximum: check.value,
1853
- inclusive: check.inclusive,
1854
- message: check.message
1855
- });
1856
- status.dirty();
1857
- }
1858
- } else if (check.kind === "multipleOf") {
1859
- if (input.data % check.value !== BigInt(0)) {
1860
- ctx = this._getOrReturnCtx(input, ctx);
1861
- addIssueToContext(ctx, {
1862
- code: ZodIssueCode.not_multiple_of,
1863
- multipleOf: check.value,
1864
- message: check.message
1865
- });
1866
- status.dirty();
1867
- }
1868
- } else {
1869
- util.assertNever(check);
1870
- }
1871
- }
1872
- return { status: status.value, value: input.data };
1873
- }
1874
- _getInvalidInput(input) {
1875
- const ctx = this._getOrReturnCtx(input);
1876
- addIssueToContext(ctx, {
1877
- code: ZodIssueCode.invalid_type,
1878
- expected: ZodParsedType.bigint,
1879
- received: ctx.parsedType
1880
- });
1881
- return INVALID;
1882
- }
1883
- gte(value, message) {
1884
- return this.setLimit("min", value, true, errorUtil.toString(message));
1885
- }
1886
- gt(value, message) {
1887
- return this.setLimit("min", value, false, errorUtil.toString(message));
1888
- }
1889
- lte(value, message) {
1890
- return this.setLimit("max", value, true, errorUtil.toString(message));
1891
- }
1892
- lt(value, message) {
1893
- return this.setLimit("max", value, false, errorUtil.toString(message));
1894
- }
1895
- setLimit(kind, value, inclusive, message) {
1896
- return new _ZodBigInt({
1897
- ...this._def,
1898
- checks: [
1899
- ...this._def.checks,
1900
- {
1901
- kind,
1902
- value,
1903
- inclusive,
1904
- message: errorUtil.toString(message)
1905
- }
1906
- ]
1907
- });
1908
- }
1909
- _addCheck(check) {
1910
- return new _ZodBigInt({
1911
- ...this._def,
1912
- checks: [...this._def.checks, check]
1913
- });
1914
- }
1915
- positive(message) {
1916
- return this._addCheck({
1917
- kind: "min",
1918
- value: BigInt(0),
1919
- inclusive: false,
1920
- message: errorUtil.toString(message)
1921
- });
1922
- }
1923
- negative(message) {
1924
- return this._addCheck({
1925
- kind: "max",
1926
- value: BigInt(0),
1927
- inclusive: false,
1928
- message: errorUtil.toString(message)
1929
- });
1930
- }
1931
- nonpositive(message) {
1932
- return this._addCheck({
1933
- kind: "max",
1934
- value: BigInt(0),
1935
- inclusive: true,
1936
- message: errorUtil.toString(message)
1937
- });
1938
- }
1939
- nonnegative(message) {
1940
- return this._addCheck({
1941
- kind: "min",
1942
- value: BigInt(0),
1943
- inclusive: true,
1944
- message: errorUtil.toString(message)
1945
- });
1946
- }
1947
- multipleOf(value, message) {
1948
- return this._addCheck({
1949
- kind: "multipleOf",
1950
- value,
1951
- message: errorUtil.toString(message)
1952
- });
1953
- }
1954
- get minValue() {
1955
- let min = null;
1956
- for (const ch of this._def.checks) {
1957
- if (ch.kind === "min") {
1958
- if (min === null || ch.value > min)
1959
- min = ch.value;
1960
- }
1961
- }
1962
- return min;
1963
- }
1964
- get maxValue() {
1965
- let max = null;
1966
- for (const ch of this._def.checks) {
1967
- if (ch.kind === "max") {
1968
- if (max === null || ch.value < max)
1969
- max = ch.value;
1970
- }
1971
- }
1972
- return max;
1973
- }
1974
- };
1975
- ZodBigInt.create = (params) => {
1976
- return new ZodBigInt({
1977
- checks: [],
1978
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
1979
- coerce: params?.coerce ?? false,
1980
- ...processCreateParams(params)
1981
- });
1982
- };
1983
- var ZodBoolean = class extends ZodType {
1984
- _parse(input) {
1985
- if (this._def.coerce) {
1986
- input.data = Boolean(input.data);
1987
- }
1988
- const parsedType = this._getType(input);
1989
- if (parsedType !== ZodParsedType.boolean) {
1990
- const ctx = this._getOrReturnCtx(input);
1991
- addIssueToContext(ctx, {
1992
- code: ZodIssueCode.invalid_type,
1993
- expected: ZodParsedType.boolean,
1994
- received: ctx.parsedType
1995
- });
1996
- return INVALID;
1997
- }
1998
- return OK(input.data);
1999
- }
2000
- };
2001
- ZodBoolean.create = (params) => {
2002
- return new ZodBoolean({
2003
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2004
- coerce: params?.coerce || false,
2005
- ...processCreateParams(params)
2006
- });
2007
- };
2008
- var ZodDate = class _ZodDate extends ZodType {
2009
- _parse(input) {
2010
- if (this._def.coerce) {
2011
- input.data = new Date(input.data);
2012
- }
2013
- const parsedType = this._getType(input);
2014
- if (parsedType !== ZodParsedType.date) {
2015
- const ctx2 = this._getOrReturnCtx(input);
2016
- addIssueToContext(ctx2, {
2017
- code: ZodIssueCode.invalid_type,
2018
- expected: ZodParsedType.date,
2019
- received: ctx2.parsedType
2020
- });
2021
- return INVALID;
2022
- }
2023
- if (Number.isNaN(input.data.getTime())) {
2024
- const ctx2 = this._getOrReturnCtx(input);
2025
- addIssueToContext(ctx2, {
2026
- code: ZodIssueCode.invalid_date
2027
- });
2028
- return INVALID;
2029
- }
2030
- const status = new ParseStatus();
2031
- let ctx = void 0;
2032
- for (const check of this._def.checks) {
2033
- if (check.kind === "min") {
2034
- if (input.data.getTime() < check.value) {
2035
- ctx = this._getOrReturnCtx(input, ctx);
2036
- addIssueToContext(ctx, {
2037
- code: ZodIssueCode.too_small,
2038
- message: check.message,
2039
- inclusive: true,
2040
- exact: false,
2041
- minimum: check.value,
2042
- type: "date"
2043
- });
2044
- status.dirty();
2045
- }
2046
- } else if (check.kind === "max") {
2047
- if (input.data.getTime() > check.value) {
2048
- ctx = this._getOrReturnCtx(input, ctx);
2049
- addIssueToContext(ctx, {
2050
- code: ZodIssueCode.too_big,
2051
- message: check.message,
2052
- inclusive: true,
2053
- exact: false,
2054
- maximum: check.value,
2055
- type: "date"
2056
- });
2057
- status.dirty();
2058
- }
2059
- } else {
2060
- util.assertNever(check);
2061
- }
2062
- }
2063
- return {
2064
- status: status.value,
2065
- value: new Date(input.data.getTime())
2066
- };
2067
- }
2068
- _addCheck(check) {
2069
- return new _ZodDate({
2070
- ...this._def,
2071
- checks: [...this._def.checks, check]
2072
- });
2073
- }
2074
- min(minDate, message) {
2075
- return this._addCheck({
2076
- kind: "min",
2077
- value: minDate.getTime(),
2078
- message: errorUtil.toString(message)
2079
- });
2080
- }
2081
- max(maxDate, message) {
2082
- return this._addCheck({
2083
- kind: "max",
2084
- value: maxDate.getTime(),
2085
- message: errorUtil.toString(message)
2086
- });
2087
- }
2088
- get minDate() {
2089
- let min = null;
2090
- for (const ch of this._def.checks) {
2091
- if (ch.kind === "min") {
2092
- if (min === null || ch.value > min)
2093
- min = ch.value;
2094
- }
2095
- }
2096
- return min != null ? new Date(min) : null;
2097
- }
2098
- get maxDate() {
2099
- let max = null;
2100
- for (const ch of this._def.checks) {
2101
- if (ch.kind === "max") {
2102
- if (max === null || ch.value < max)
2103
- max = ch.value;
2104
- }
2105
- }
2106
- return max != null ? new Date(max) : null;
2107
- }
2108
- };
2109
- ZodDate.create = (params) => {
2110
- return new ZodDate({
2111
- checks: [],
2112
- coerce: params?.coerce || false,
2113
- typeName: ZodFirstPartyTypeKind.ZodDate,
2114
- ...processCreateParams(params)
2115
- });
2116
- };
2117
- var ZodSymbol = class extends ZodType {
2118
- _parse(input) {
2119
- const parsedType = this._getType(input);
2120
- if (parsedType !== ZodParsedType.symbol) {
2121
- const ctx = this._getOrReturnCtx(input);
2122
- addIssueToContext(ctx, {
2123
- code: ZodIssueCode.invalid_type,
2124
- expected: ZodParsedType.symbol,
2125
- received: ctx.parsedType
2126
- });
2127
- return INVALID;
2128
- }
2129
- return OK(input.data);
2130
- }
2131
- };
2132
- ZodSymbol.create = (params) => {
2133
- return new ZodSymbol({
2134
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2135
- ...processCreateParams(params)
2136
- });
2137
- };
2138
- var ZodUndefined = class extends ZodType {
2139
- _parse(input) {
2140
- const parsedType = this._getType(input);
2141
- if (parsedType !== ZodParsedType.undefined) {
2142
- const ctx = this._getOrReturnCtx(input);
2143
- addIssueToContext(ctx, {
2144
- code: ZodIssueCode.invalid_type,
2145
- expected: ZodParsedType.undefined,
2146
- received: ctx.parsedType
2147
- });
2148
- return INVALID;
2149
- }
2150
- return OK(input.data);
2151
- }
2152
- };
2153
- ZodUndefined.create = (params) => {
2154
- return new ZodUndefined({
2155
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2156
- ...processCreateParams(params)
2157
- });
2158
- };
2159
- var ZodNull = class extends ZodType {
2160
- _parse(input) {
2161
- const parsedType = this._getType(input);
2162
- if (parsedType !== ZodParsedType.null) {
2163
- const ctx = this._getOrReturnCtx(input);
2164
- addIssueToContext(ctx, {
2165
- code: ZodIssueCode.invalid_type,
2166
- expected: ZodParsedType.null,
2167
- received: ctx.parsedType
2168
- });
2169
- return INVALID;
2170
- }
2171
- return OK(input.data);
2172
- }
2173
- };
2174
- ZodNull.create = (params) => {
2175
- return new ZodNull({
2176
- typeName: ZodFirstPartyTypeKind.ZodNull,
2177
- ...processCreateParams(params)
2178
- });
2179
- };
2180
- var ZodAny = class extends ZodType {
2181
- constructor() {
2182
- super(...arguments);
2183
- this._any = true;
2184
- }
2185
- _parse(input) {
2186
- return OK(input.data);
2187
- }
2188
- };
2189
- ZodAny.create = (params) => {
2190
- return new ZodAny({
2191
- typeName: ZodFirstPartyTypeKind.ZodAny,
2192
- ...processCreateParams(params)
2193
- });
2194
- };
2195
- var ZodUnknown = class extends ZodType {
2196
- constructor() {
2197
- super(...arguments);
2198
- this._unknown = true;
2199
- }
2200
- _parse(input) {
2201
- return OK(input.data);
2202
- }
2203
- };
2204
- ZodUnknown.create = (params) => {
2205
- return new ZodUnknown({
2206
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2207
- ...processCreateParams(params)
2208
- });
2209
- };
2210
- var ZodNever = class extends ZodType {
2211
- _parse(input) {
2212
- const ctx = this._getOrReturnCtx(input);
2213
- addIssueToContext(ctx, {
2214
- code: ZodIssueCode.invalid_type,
2215
- expected: ZodParsedType.never,
2216
- received: ctx.parsedType
2217
- });
2218
- return INVALID;
2219
- }
2220
- };
2221
- ZodNever.create = (params) => {
2222
- return new ZodNever({
2223
- typeName: ZodFirstPartyTypeKind.ZodNever,
2224
- ...processCreateParams(params)
2225
- });
2226
- };
2227
- var ZodVoid = class extends ZodType {
2228
- _parse(input) {
2229
- const parsedType = this._getType(input);
2230
- if (parsedType !== ZodParsedType.undefined) {
2231
- const ctx = this._getOrReturnCtx(input);
2232
- addIssueToContext(ctx, {
2233
- code: ZodIssueCode.invalid_type,
2234
- expected: ZodParsedType.void,
2235
- received: ctx.parsedType
2236
- });
2237
- return INVALID;
2238
- }
2239
- return OK(input.data);
2240
- }
2241
- };
2242
- ZodVoid.create = (params) => {
2243
- return new ZodVoid({
2244
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2245
- ...processCreateParams(params)
2246
- });
2247
- };
2248
- var ZodArray = class _ZodArray extends ZodType {
2249
- _parse(input) {
2250
- const { ctx, status } = this._processInputParams(input);
2251
- const def = this._def;
2252
- if (ctx.parsedType !== ZodParsedType.array) {
2253
- addIssueToContext(ctx, {
2254
- code: ZodIssueCode.invalid_type,
2255
- expected: ZodParsedType.array,
2256
- received: ctx.parsedType
2257
- });
2258
- return INVALID;
2259
- }
2260
- if (def.exactLength !== null) {
2261
- const tooBig = ctx.data.length > def.exactLength.value;
2262
- const tooSmall = ctx.data.length < def.exactLength.value;
2263
- if (tooBig || tooSmall) {
2264
- addIssueToContext(ctx, {
2265
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2266
- minimum: tooSmall ? def.exactLength.value : void 0,
2267
- maximum: tooBig ? def.exactLength.value : void 0,
2268
- type: "array",
2269
- inclusive: true,
2270
- exact: true,
2271
- message: def.exactLength.message
2272
- });
2273
- status.dirty();
2274
- }
2275
- }
2276
- if (def.minLength !== null) {
2277
- if (ctx.data.length < def.minLength.value) {
2278
- addIssueToContext(ctx, {
2279
- code: ZodIssueCode.too_small,
2280
- minimum: def.minLength.value,
2281
- type: "array",
2282
- inclusive: true,
2283
- exact: false,
2284
- message: def.minLength.message
2285
- });
2286
- status.dirty();
2287
- }
2288
- }
2289
- if (def.maxLength !== null) {
2290
- if (ctx.data.length > def.maxLength.value) {
2291
- addIssueToContext(ctx, {
2292
- code: ZodIssueCode.too_big,
2293
- maximum: def.maxLength.value,
2294
- type: "array",
2295
- inclusive: true,
2296
- exact: false,
2297
- message: def.maxLength.message
2298
- });
2299
- status.dirty();
2300
- }
2301
- }
2302
- if (ctx.common.async) {
2303
- return Promise.all([...ctx.data].map((item, i) => {
2304
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2305
- })).then((result2) => {
2306
- return ParseStatus.mergeArray(status, result2);
2307
- });
2308
- }
2309
- const result = [...ctx.data].map((item, i) => {
2310
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2311
- });
2312
- return ParseStatus.mergeArray(status, result);
2313
- }
2314
- get element() {
2315
- return this._def.type;
2316
- }
2317
- min(minLength, message) {
2318
- return new _ZodArray({
2319
- ...this._def,
2320
- minLength: { value: minLength, message: errorUtil.toString(message) }
2321
- });
2322
- }
2323
- max(maxLength, message) {
2324
- return new _ZodArray({
2325
- ...this._def,
2326
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
2327
- });
2328
- }
2329
- length(len, message) {
2330
- return new _ZodArray({
2331
- ...this._def,
2332
- exactLength: { value: len, message: errorUtil.toString(message) }
2333
- });
2334
- }
2335
- nonempty(message) {
2336
- return this.min(1, message);
2337
- }
2338
- };
2339
- ZodArray.create = (schema, params) => {
2340
- return new ZodArray({
2341
- type: schema,
2342
- minLength: null,
2343
- maxLength: null,
2344
- exactLength: null,
2345
- typeName: ZodFirstPartyTypeKind.ZodArray,
2346
- ...processCreateParams(params)
2347
- });
2348
- };
2349
- function deepPartialify(schema) {
2350
- if (schema instanceof ZodObject) {
2351
- const newShape = {};
2352
- for (const key in schema.shape) {
2353
- const fieldSchema = schema.shape[key];
2354
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2355
- }
2356
- return new ZodObject({
2357
- ...schema._def,
2358
- shape: () => newShape
2359
- });
2360
- } else if (schema instanceof ZodArray) {
2361
- return new ZodArray({
2362
- ...schema._def,
2363
- type: deepPartialify(schema.element)
2364
- });
2365
- } else if (schema instanceof ZodOptional) {
2366
- return ZodOptional.create(deepPartialify(schema.unwrap()));
2367
- } else if (schema instanceof ZodNullable) {
2368
- return ZodNullable.create(deepPartialify(schema.unwrap()));
2369
- } else if (schema instanceof ZodTuple) {
2370
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2371
- } else {
2372
- return schema;
2373
- }
2374
- }
2375
- var ZodObject = class _ZodObject extends ZodType {
2376
- constructor() {
2377
- super(...arguments);
2378
- this._cached = null;
2379
- this.nonstrict = this.passthrough;
2380
- this.augment = this.extend;
2381
- }
2382
- _getCached() {
2383
- if (this._cached !== null)
2384
- return this._cached;
2385
- const shape = this._def.shape();
2386
- const keys = util.objectKeys(shape);
2387
- this._cached = { shape, keys };
2388
- return this._cached;
2389
- }
2390
- _parse(input) {
2391
- const parsedType = this._getType(input);
2392
- if (parsedType !== ZodParsedType.object) {
2393
- const ctx2 = this._getOrReturnCtx(input);
2394
- addIssueToContext(ctx2, {
2395
- code: ZodIssueCode.invalid_type,
2396
- expected: ZodParsedType.object,
2397
- received: ctx2.parsedType
2398
- });
2399
- return INVALID;
2400
- }
2401
- const { status, ctx } = this._processInputParams(input);
2402
- const { shape, keys: shapeKeys } = this._getCached();
2403
- const extraKeys = [];
2404
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2405
- for (const key in ctx.data) {
2406
- if (!shapeKeys.includes(key)) {
2407
- extraKeys.push(key);
2408
- }
2409
- }
2410
- }
2411
- const pairs = [];
2412
- for (const key of shapeKeys) {
2413
- const keyValidator = shape[key];
2414
- const value = ctx.data[key];
2415
- pairs.push({
2416
- key: { status: "valid", value: key },
2417
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2418
- alwaysSet: key in ctx.data
2419
- });
2420
- }
2421
- if (this._def.catchall instanceof ZodNever) {
2422
- const unknownKeys = this._def.unknownKeys;
2423
- if (unknownKeys === "passthrough") {
2424
- for (const key of extraKeys) {
2425
- pairs.push({
2426
- key: { status: "valid", value: key },
2427
- value: { status: "valid", value: ctx.data[key] }
2428
- });
2429
- }
2430
- } else if (unknownKeys === "strict") {
2431
- if (extraKeys.length > 0) {
2432
- addIssueToContext(ctx, {
2433
- code: ZodIssueCode.unrecognized_keys,
2434
- keys: extraKeys
2435
- });
2436
- status.dirty();
2437
- }
2438
- } else if (unknownKeys === "strip") ; else {
2439
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2440
- }
2441
- } else {
2442
- const catchall = this._def.catchall;
2443
- for (const key of extraKeys) {
2444
- const value = ctx.data[key];
2445
- pairs.push({
2446
- key: { status: "valid", value: key },
2447
- value: catchall._parse(
2448
- new ParseInputLazyPath(ctx, value, ctx.path, key)
2449
- //, ctx.child(key), value, getParsedType(value)
2450
- ),
2451
- alwaysSet: key in ctx.data
2452
- });
2453
- }
2454
- }
2455
- if (ctx.common.async) {
2456
- return Promise.resolve().then(async () => {
2457
- const syncPairs = [];
2458
- for (const pair of pairs) {
2459
- const key = await pair.key;
2460
- const value = await pair.value;
2461
- syncPairs.push({
2462
- key,
2463
- value,
2464
- alwaysSet: pair.alwaysSet
2465
- });
2466
- }
2467
- return syncPairs;
2468
- }).then((syncPairs) => {
2469
- return ParseStatus.mergeObjectSync(status, syncPairs);
2470
- });
2471
- } else {
2472
- return ParseStatus.mergeObjectSync(status, pairs);
2473
- }
2474
- }
2475
- get shape() {
2476
- return this._def.shape();
2477
- }
2478
- strict(message) {
2479
- errorUtil.errToObj;
2480
- return new _ZodObject({
2481
- ...this._def,
2482
- unknownKeys: "strict",
2483
- ...message !== void 0 ? {
2484
- errorMap: (issue, ctx) => {
2485
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2486
- if (issue.code === "unrecognized_keys")
2487
- return {
2488
- message: errorUtil.errToObj(message).message ?? defaultError
2489
- };
2490
- return {
2491
- message: defaultError
2492
- };
2493
- }
2494
- } : {}
2495
- });
2496
- }
2497
- strip() {
2498
- return new _ZodObject({
2499
- ...this._def,
2500
- unknownKeys: "strip"
2501
- });
2502
- }
2503
- passthrough() {
2504
- return new _ZodObject({
2505
- ...this._def,
2506
- unknownKeys: "passthrough"
2507
- });
2508
- }
2509
- // const AugmentFactory =
2510
- // <Def extends ZodObjectDef>(def: Def) =>
2511
- // <Augmentation extends ZodRawShape>(
2512
- // augmentation: Augmentation
2513
- // ): ZodObject<
2514
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2515
- // Def["unknownKeys"],
2516
- // Def["catchall"]
2517
- // > => {
2518
- // return new ZodObject({
2519
- // ...def,
2520
- // shape: () => ({
2521
- // ...def.shape(),
2522
- // ...augmentation,
2523
- // }),
2524
- // }) as any;
2525
- // };
2526
- extend(augmentation) {
2527
- return new _ZodObject({
2528
- ...this._def,
2529
- shape: () => ({
2530
- ...this._def.shape(),
2531
- ...augmentation
2532
- })
2533
- });
2534
- }
2535
- /**
2536
- * Prior to zod@1.0.12 there was a bug in the
2537
- * inferred type of merged objects. Please
2538
- * upgrade if you are experiencing issues.
2539
- */
2540
- merge(merging) {
2541
- const merged = new _ZodObject({
2542
- unknownKeys: merging._def.unknownKeys,
2543
- catchall: merging._def.catchall,
2544
- shape: () => ({
2545
- ...this._def.shape(),
2546
- ...merging._def.shape()
2547
- }),
2548
- typeName: ZodFirstPartyTypeKind.ZodObject
2549
- });
2550
- return merged;
2551
- }
2552
- // merge<
2553
- // Incoming extends AnyZodObject,
2554
- // Augmentation extends Incoming["shape"],
2555
- // NewOutput extends {
2556
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2557
- // ? Augmentation[k]["_output"]
2558
- // : k extends keyof Output
2559
- // ? Output[k]
2560
- // : never;
2561
- // },
2562
- // NewInput extends {
2563
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2564
- // ? Augmentation[k]["_input"]
2565
- // : k extends keyof Input
2566
- // ? Input[k]
2567
- // : never;
2568
- // }
2569
- // >(
2570
- // merging: Incoming
2571
- // ): ZodObject<
2572
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2573
- // Incoming["_def"]["unknownKeys"],
2574
- // Incoming["_def"]["catchall"],
2575
- // NewOutput,
2576
- // NewInput
2577
- // > {
2578
- // const merged: any = new ZodObject({
2579
- // unknownKeys: merging._def.unknownKeys,
2580
- // catchall: merging._def.catchall,
2581
- // shape: () =>
2582
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2583
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2584
- // }) as any;
2585
- // return merged;
2586
- // }
2587
- setKey(key, schema) {
2588
- return this.augment({ [key]: schema });
2589
- }
2590
- // merge<Incoming extends AnyZodObject>(
2591
- // merging: Incoming
2592
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2593
- // ZodObject<
2594
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2595
- // Incoming["_def"]["unknownKeys"],
2596
- // Incoming["_def"]["catchall"]
2597
- // > {
2598
- // // const mergedShape = objectUtil.mergeShapes(
2599
- // // this._def.shape(),
2600
- // // merging._def.shape()
2601
- // // );
2602
- // const merged: any = new ZodObject({
2603
- // unknownKeys: merging._def.unknownKeys,
2604
- // catchall: merging._def.catchall,
2605
- // shape: () =>
2606
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2607
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2608
- // }) as any;
2609
- // return merged;
2610
- // }
2611
- catchall(index) {
2612
- return new _ZodObject({
2613
- ...this._def,
2614
- catchall: index
2615
- });
2616
- }
2617
- pick(mask) {
2618
- const shape = {};
2619
- for (const key of util.objectKeys(mask)) {
2620
- if (mask[key] && this.shape[key]) {
2621
- shape[key] = this.shape[key];
2622
- }
2623
- }
2624
- return new _ZodObject({
2625
- ...this._def,
2626
- shape: () => shape
2627
- });
2628
- }
2629
- omit(mask) {
2630
- const shape = {};
2631
- for (const key of util.objectKeys(this.shape)) {
2632
- if (!mask[key]) {
2633
- shape[key] = this.shape[key];
2634
- }
2635
- }
2636
- return new _ZodObject({
2637
- ...this._def,
2638
- shape: () => shape
2639
- });
2640
- }
2641
- /**
2642
- * @deprecated
2643
- */
2644
- deepPartial() {
2645
- return deepPartialify(this);
2646
- }
2647
- partial(mask) {
2648
- const newShape = {};
2649
- for (const key of util.objectKeys(this.shape)) {
2650
- const fieldSchema = this.shape[key];
2651
- if (mask && !mask[key]) {
2652
- newShape[key] = fieldSchema;
2653
- } else {
2654
- newShape[key] = fieldSchema.optional();
2655
- }
2656
- }
2657
- return new _ZodObject({
2658
- ...this._def,
2659
- shape: () => newShape
2660
- });
2661
- }
2662
- required(mask) {
2663
- const newShape = {};
2664
- for (const key of util.objectKeys(this.shape)) {
2665
- if (mask && !mask[key]) {
2666
- newShape[key] = this.shape[key];
2667
- } else {
2668
- const fieldSchema = this.shape[key];
2669
- let newField = fieldSchema;
2670
- while (newField instanceof ZodOptional) {
2671
- newField = newField._def.innerType;
2672
- }
2673
- newShape[key] = newField;
2674
- }
2675
- }
2676
- return new _ZodObject({
2677
- ...this._def,
2678
- shape: () => newShape
2679
- });
2680
- }
2681
- keyof() {
2682
- return createZodEnum(util.objectKeys(this.shape));
2683
- }
2684
- };
2685
- ZodObject.create = (shape, params) => {
2686
- return new ZodObject({
2687
- shape: () => shape,
2688
- unknownKeys: "strip",
2689
- catchall: ZodNever.create(),
2690
- typeName: ZodFirstPartyTypeKind.ZodObject,
2691
- ...processCreateParams(params)
2692
- });
2693
- };
2694
- ZodObject.strictCreate = (shape, params) => {
2695
- return new ZodObject({
2696
- shape: () => shape,
2697
- unknownKeys: "strict",
2698
- catchall: ZodNever.create(),
2699
- typeName: ZodFirstPartyTypeKind.ZodObject,
2700
- ...processCreateParams(params)
2701
- });
2702
- };
2703
- ZodObject.lazycreate = (shape, params) => {
2704
- return new ZodObject({
2705
- shape,
2706
- unknownKeys: "strip",
2707
- catchall: ZodNever.create(),
2708
- typeName: ZodFirstPartyTypeKind.ZodObject,
2709
- ...processCreateParams(params)
2710
- });
2711
- };
2712
- var ZodUnion = class extends ZodType {
2713
- _parse(input) {
2714
- const { ctx } = this._processInputParams(input);
2715
- const options = this._def.options;
2716
- function handleResults(results) {
2717
- for (const result of results) {
2718
- if (result.result.status === "valid") {
2719
- return result.result;
2720
- }
2721
- }
2722
- for (const result of results) {
2723
- if (result.result.status === "dirty") {
2724
- ctx.common.issues.push(...result.ctx.common.issues);
2725
- return result.result;
2726
- }
2727
- }
2728
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2729
- addIssueToContext(ctx, {
2730
- code: ZodIssueCode.invalid_union,
2731
- unionErrors
2732
- });
2733
- return INVALID;
2734
- }
2735
- if (ctx.common.async) {
2736
- return Promise.all(options.map(async (option) => {
2737
- const childCtx = {
2738
- ...ctx,
2739
- common: {
2740
- ...ctx.common,
2741
- issues: []
2742
- },
2743
- parent: null
2744
- };
2745
- return {
2746
- result: await option._parseAsync({
2747
- data: ctx.data,
2748
- path: ctx.path,
2749
- parent: childCtx
2750
- }),
2751
- ctx: childCtx
2752
- };
2753
- })).then(handleResults);
2754
- } else {
2755
- let dirty = void 0;
2756
- const issues = [];
2757
- for (const option of options) {
2758
- const childCtx = {
2759
- ...ctx,
2760
- common: {
2761
- ...ctx.common,
2762
- issues: []
2763
- },
2764
- parent: null
2765
- };
2766
- const result = option._parseSync({
2767
- data: ctx.data,
2768
- path: ctx.path,
2769
- parent: childCtx
2770
- });
2771
- if (result.status === "valid") {
2772
- return result;
2773
- } else if (result.status === "dirty" && !dirty) {
2774
- dirty = { result, ctx: childCtx };
2775
- }
2776
- if (childCtx.common.issues.length) {
2777
- issues.push(childCtx.common.issues);
2778
- }
2779
- }
2780
- if (dirty) {
2781
- ctx.common.issues.push(...dirty.ctx.common.issues);
2782
- return dirty.result;
2783
- }
2784
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
2785
- addIssueToContext(ctx, {
2786
- code: ZodIssueCode.invalid_union,
2787
- unionErrors
2788
- });
2789
- return INVALID;
2790
- }
2791
- }
2792
- get options() {
2793
- return this._def.options;
2794
- }
2795
- };
2796
- ZodUnion.create = (types, params) => {
2797
- return new ZodUnion({
2798
- options: types,
2799
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2800
- ...processCreateParams(params)
2801
- });
2802
- };
2803
- var getDiscriminator = (type) => {
2804
- if (type instanceof ZodLazy) {
2805
- return getDiscriminator(type.schema);
2806
- } else if (type instanceof ZodEffects) {
2807
- return getDiscriminator(type.innerType());
2808
- } else if (type instanceof ZodLiteral) {
2809
- return [type.value];
2810
- } else if (type instanceof ZodEnum) {
2811
- return type.options;
2812
- } else if (type instanceof ZodNativeEnum) {
2813
- return util.objectValues(type.enum);
2814
- } else if (type instanceof ZodDefault) {
2815
- return getDiscriminator(type._def.innerType);
2816
- } else if (type instanceof ZodUndefined) {
2817
- return [void 0];
2818
- } else if (type instanceof ZodNull) {
2819
- return [null];
2820
- } else if (type instanceof ZodOptional) {
2821
- return [void 0, ...getDiscriminator(type.unwrap())];
2822
- } else if (type instanceof ZodNullable) {
2823
- return [null, ...getDiscriminator(type.unwrap())];
2824
- } else if (type instanceof ZodBranded) {
2825
- return getDiscriminator(type.unwrap());
2826
- } else if (type instanceof ZodReadonly) {
2827
- return getDiscriminator(type.unwrap());
2828
- } else if (type instanceof ZodCatch) {
2829
- return getDiscriminator(type._def.innerType);
2830
- } else {
2831
- return [];
2832
- }
2833
- };
2834
- var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2835
- _parse(input) {
2836
- const { ctx } = this._processInputParams(input);
2837
- if (ctx.parsedType !== ZodParsedType.object) {
2838
- addIssueToContext(ctx, {
2839
- code: ZodIssueCode.invalid_type,
2840
- expected: ZodParsedType.object,
2841
- received: ctx.parsedType
2842
- });
2843
- return INVALID;
2844
- }
2845
- const discriminator = this.discriminator;
2846
- const discriminatorValue = ctx.data[discriminator];
2847
- const option = this.optionsMap.get(discriminatorValue);
2848
- if (!option) {
2849
- addIssueToContext(ctx, {
2850
- code: ZodIssueCode.invalid_union_discriminator,
2851
- options: Array.from(this.optionsMap.keys()),
2852
- path: [discriminator]
2853
- });
2854
- return INVALID;
2855
- }
2856
- if (ctx.common.async) {
2857
- return option._parseAsync({
2858
- data: ctx.data,
2859
- path: ctx.path,
2860
- parent: ctx
2861
- });
2862
- } else {
2863
- return option._parseSync({
2864
- data: ctx.data,
2865
- path: ctx.path,
2866
- parent: ctx
2867
- });
2868
- }
2869
- }
2870
- get discriminator() {
2871
- return this._def.discriminator;
2872
- }
2873
- get options() {
2874
- return this._def.options;
2875
- }
2876
- get optionsMap() {
2877
- return this._def.optionsMap;
2878
- }
2879
- /**
2880
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2881
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2882
- * have a different value for each object in the union.
2883
- * @param discriminator the name of the discriminator property
2884
- * @param types an array of object schemas
2885
- * @param params
2886
- */
2887
- static create(discriminator, options, params) {
2888
- const optionsMap = /* @__PURE__ */ new Map();
2889
- for (const type of options) {
2890
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2891
- if (!discriminatorValues.length) {
2892
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2893
- }
2894
- for (const value of discriminatorValues) {
2895
- if (optionsMap.has(value)) {
2896
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2897
- }
2898
- optionsMap.set(value, type);
2899
- }
2900
- }
2901
- return new _ZodDiscriminatedUnion({
2902
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2903
- discriminator,
2904
- options,
2905
- optionsMap,
2906
- ...processCreateParams(params)
2907
- });
2908
- }
2909
- };
2910
- function mergeValues(a, b) {
2911
- const aType = getParsedType(a);
2912
- const bType = getParsedType(b);
2913
- if (a === b) {
2914
- return { valid: true, data: a };
2915
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2916
- const bKeys = util.objectKeys(b);
2917
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2918
- const newObj = { ...a, ...b };
2919
- for (const key of sharedKeys) {
2920
- const sharedValue = mergeValues(a[key], b[key]);
2921
- if (!sharedValue.valid) {
2922
- return { valid: false };
2923
- }
2924
- newObj[key] = sharedValue.data;
2925
- }
2926
- return { valid: true, data: newObj };
2927
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2928
- if (a.length !== b.length) {
2929
- return { valid: false };
2930
- }
2931
- const newArray = [];
2932
- for (let index = 0; index < a.length; index++) {
2933
- const itemA = a[index];
2934
- const itemB = b[index];
2935
- const sharedValue = mergeValues(itemA, itemB);
2936
- if (!sharedValue.valid) {
2937
- return { valid: false };
2938
- }
2939
- newArray.push(sharedValue.data);
2940
- }
2941
- return { valid: true, data: newArray };
2942
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2943
- return { valid: true, data: a };
2944
- } else {
2945
- return { valid: false };
2946
- }
2947
- }
2948
- var ZodIntersection = class extends ZodType {
2949
- _parse(input) {
2950
- const { status, ctx } = this._processInputParams(input);
2951
- const handleParsed = (parsedLeft, parsedRight) => {
2952
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2953
- return INVALID;
2954
- }
2955
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2956
- if (!merged.valid) {
2957
- addIssueToContext(ctx, {
2958
- code: ZodIssueCode.invalid_intersection_types
2959
- });
2960
- return INVALID;
2961
- }
2962
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2963
- status.dirty();
2964
- }
2965
- return { status: status.value, value: merged.data };
2966
- };
2967
- if (ctx.common.async) {
2968
- return Promise.all([
2969
- this._def.left._parseAsync({
2970
- data: ctx.data,
2971
- path: ctx.path,
2972
- parent: ctx
2973
- }),
2974
- this._def.right._parseAsync({
2975
- data: ctx.data,
2976
- path: ctx.path,
2977
- parent: ctx
2978
- })
2979
- ]).then(([left, right]) => handleParsed(left, right));
2980
- } else {
2981
- return handleParsed(this._def.left._parseSync({
2982
- data: ctx.data,
2983
- path: ctx.path,
2984
- parent: ctx
2985
- }), this._def.right._parseSync({
2986
- data: ctx.data,
2987
- path: ctx.path,
2988
- parent: ctx
2989
- }));
2990
- }
2991
- }
2992
- };
2993
- ZodIntersection.create = (left, right, params) => {
2994
- return new ZodIntersection({
2995
- left,
2996
- right,
2997
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
2998
- ...processCreateParams(params)
2999
- });
3000
- };
3001
- var ZodTuple = class _ZodTuple extends ZodType {
3002
- _parse(input) {
3003
- const { status, ctx } = this._processInputParams(input);
3004
- if (ctx.parsedType !== ZodParsedType.array) {
3005
- addIssueToContext(ctx, {
3006
- code: ZodIssueCode.invalid_type,
3007
- expected: ZodParsedType.array,
3008
- received: ctx.parsedType
3009
- });
3010
- return INVALID;
3011
- }
3012
- if (ctx.data.length < this._def.items.length) {
3013
- addIssueToContext(ctx, {
3014
- code: ZodIssueCode.too_small,
3015
- minimum: this._def.items.length,
3016
- inclusive: true,
3017
- exact: false,
3018
- type: "array"
3019
- });
3020
- return INVALID;
3021
- }
3022
- const rest = this._def.rest;
3023
- if (!rest && ctx.data.length > this._def.items.length) {
3024
- addIssueToContext(ctx, {
3025
- code: ZodIssueCode.too_big,
3026
- maximum: this._def.items.length,
3027
- inclusive: true,
3028
- exact: false,
3029
- type: "array"
3030
- });
3031
- status.dirty();
3032
- }
3033
- const items = [...ctx.data].map((item, itemIndex) => {
3034
- const schema = this._def.items[itemIndex] || this._def.rest;
3035
- if (!schema)
3036
- return null;
3037
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3038
- }).filter((x) => !!x);
3039
- if (ctx.common.async) {
3040
- return Promise.all(items).then((results) => {
3041
- return ParseStatus.mergeArray(status, results);
3042
- });
3043
- } else {
3044
- return ParseStatus.mergeArray(status, items);
3045
- }
3046
- }
3047
- get items() {
3048
- return this._def.items;
3049
- }
3050
- rest(rest) {
3051
- return new _ZodTuple({
3052
- ...this._def,
3053
- rest
3054
- });
3055
- }
3056
- };
3057
- ZodTuple.create = (schemas, params) => {
3058
- if (!Array.isArray(schemas)) {
3059
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3060
- }
3061
- return new ZodTuple({
3062
- items: schemas,
3063
- typeName: ZodFirstPartyTypeKind.ZodTuple,
3064
- rest: null,
3065
- ...processCreateParams(params)
3066
- });
3067
- };
3068
- var ZodRecord = class _ZodRecord extends ZodType {
3069
- get keySchema() {
3070
- return this._def.keyType;
3071
- }
3072
- get valueSchema() {
3073
- return this._def.valueType;
3074
- }
3075
- _parse(input) {
3076
- const { status, ctx } = this._processInputParams(input);
3077
- if (ctx.parsedType !== ZodParsedType.object) {
3078
- addIssueToContext(ctx, {
3079
- code: ZodIssueCode.invalid_type,
3080
- expected: ZodParsedType.object,
3081
- received: ctx.parsedType
3082
- });
3083
- return INVALID;
3084
- }
3085
- const pairs = [];
3086
- const keyType = this._def.keyType;
3087
- const valueType = this._def.valueType;
3088
- for (const key in ctx.data) {
3089
- pairs.push({
3090
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3091
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3092
- alwaysSet: key in ctx.data
3093
- });
3094
- }
3095
- if (ctx.common.async) {
3096
- return ParseStatus.mergeObjectAsync(status, pairs);
3097
- } else {
3098
- return ParseStatus.mergeObjectSync(status, pairs);
3099
- }
3100
- }
3101
- get element() {
3102
- return this._def.valueType;
3103
- }
3104
- static create(first, second, third) {
3105
- if (second instanceof ZodType) {
3106
- return new _ZodRecord({
3107
- keyType: first,
3108
- valueType: second,
3109
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3110
- ...processCreateParams(third)
3111
- });
3112
- }
3113
- return new _ZodRecord({
3114
- keyType: ZodString.create(),
3115
- valueType: first,
3116
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3117
- ...processCreateParams(second)
3118
- });
3119
- }
3120
- };
3121
- var ZodMap = class extends ZodType {
3122
- get keySchema() {
3123
- return this._def.keyType;
3124
- }
3125
- get valueSchema() {
3126
- return this._def.valueType;
3127
- }
3128
- _parse(input) {
3129
- const { status, ctx } = this._processInputParams(input);
3130
- if (ctx.parsedType !== ZodParsedType.map) {
3131
- addIssueToContext(ctx, {
3132
- code: ZodIssueCode.invalid_type,
3133
- expected: ZodParsedType.map,
3134
- received: ctx.parsedType
3135
- });
3136
- return INVALID;
3137
- }
3138
- const keyType = this._def.keyType;
3139
- const valueType = this._def.valueType;
3140
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3141
- return {
3142
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3143
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3144
- };
3145
- });
3146
- if (ctx.common.async) {
3147
- const finalMap = /* @__PURE__ */ new Map();
3148
- return Promise.resolve().then(async () => {
3149
- for (const pair of pairs) {
3150
- const key = await pair.key;
3151
- const value = await pair.value;
3152
- if (key.status === "aborted" || value.status === "aborted") {
3153
- return INVALID;
3154
- }
3155
- if (key.status === "dirty" || value.status === "dirty") {
3156
- status.dirty();
3157
- }
3158
- finalMap.set(key.value, value.value);
3159
- }
3160
- return { status: status.value, value: finalMap };
3161
- });
3162
- } else {
3163
- const finalMap = /* @__PURE__ */ new Map();
3164
- for (const pair of pairs) {
3165
- const key = pair.key;
3166
- const value = pair.value;
3167
- if (key.status === "aborted" || value.status === "aborted") {
3168
- return INVALID;
3169
- }
3170
- if (key.status === "dirty" || value.status === "dirty") {
3171
- status.dirty();
3172
- }
3173
- finalMap.set(key.value, value.value);
3174
- }
3175
- return { status: status.value, value: finalMap };
3176
- }
3177
- }
3178
- };
3179
- ZodMap.create = (keyType, valueType, params) => {
3180
- return new ZodMap({
3181
- valueType,
3182
- keyType,
3183
- typeName: ZodFirstPartyTypeKind.ZodMap,
3184
- ...processCreateParams(params)
3185
- });
3186
- };
3187
- var ZodSet = class _ZodSet extends ZodType {
3188
- _parse(input) {
3189
- const { status, ctx } = this._processInputParams(input);
3190
- if (ctx.parsedType !== ZodParsedType.set) {
3191
- addIssueToContext(ctx, {
3192
- code: ZodIssueCode.invalid_type,
3193
- expected: ZodParsedType.set,
3194
- received: ctx.parsedType
3195
- });
3196
- return INVALID;
3197
- }
3198
- const def = this._def;
3199
- if (def.minSize !== null) {
3200
- if (ctx.data.size < def.minSize.value) {
3201
- addIssueToContext(ctx, {
3202
- code: ZodIssueCode.too_small,
3203
- minimum: def.minSize.value,
3204
- type: "set",
3205
- inclusive: true,
3206
- exact: false,
3207
- message: def.minSize.message
3208
- });
3209
- status.dirty();
3210
- }
3211
- }
3212
- if (def.maxSize !== null) {
3213
- if (ctx.data.size > def.maxSize.value) {
3214
- addIssueToContext(ctx, {
3215
- code: ZodIssueCode.too_big,
3216
- maximum: def.maxSize.value,
3217
- type: "set",
3218
- inclusive: true,
3219
- exact: false,
3220
- message: def.maxSize.message
3221
- });
3222
- status.dirty();
3223
- }
3224
- }
3225
- const valueType = this._def.valueType;
3226
- function finalizeSet(elements2) {
3227
- const parsedSet = /* @__PURE__ */ new Set();
3228
- for (const element of elements2) {
3229
- if (element.status === "aborted")
3230
- return INVALID;
3231
- if (element.status === "dirty")
3232
- status.dirty();
3233
- parsedSet.add(element.value);
3234
- }
3235
- return { status: status.value, value: parsedSet };
3236
- }
3237
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3238
- if (ctx.common.async) {
3239
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3240
- } else {
3241
- return finalizeSet(elements);
3242
- }
3243
- }
3244
- min(minSize, message) {
3245
- return new _ZodSet({
3246
- ...this._def,
3247
- minSize: { value: minSize, message: errorUtil.toString(message) }
3248
- });
3249
- }
3250
- max(maxSize, message) {
3251
- return new _ZodSet({
3252
- ...this._def,
3253
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
3254
- });
3255
- }
3256
- size(size, message) {
3257
- return this.min(size, message).max(size, message);
3258
- }
3259
- nonempty(message) {
3260
- return this.min(1, message);
3261
- }
3262
- };
3263
- ZodSet.create = (valueType, params) => {
3264
- return new ZodSet({
3265
- valueType,
3266
- minSize: null,
3267
- maxSize: null,
3268
- typeName: ZodFirstPartyTypeKind.ZodSet,
3269
- ...processCreateParams(params)
3270
- });
3271
- };
3272
- var ZodFunction = class _ZodFunction extends ZodType {
3273
- constructor() {
3274
- super(...arguments);
3275
- this.validate = this.implement;
3276
- }
3277
- _parse(input) {
3278
- const { ctx } = this._processInputParams(input);
3279
- if (ctx.parsedType !== ZodParsedType.function) {
3280
- addIssueToContext(ctx, {
3281
- code: ZodIssueCode.invalid_type,
3282
- expected: ZodParsedType.function,
3283
- received: ctx.parsedType
3284
- });
3285
- return INVALID;
3286
- }
3287
- function makeArgsIssue(args, error) {
3288
- return makeIssue({
3289
- data: args,
3290
- path: ctx.path,
3291
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3292
- issueData: {
3293
- code: ZodIssueCode.invalid_arguments,
3294
- argumentsError: error
3295
- }
3296
- });
3297
- }
3298
- function makeReturnsIssue(returns, error) {
3299
- return makeIssue({
3300
- data: returns,
3301
- path: ctx.path,
3302
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3303
- issueData: {
3304
- code: ZodIssueCode.invalid_return_type,
3305
- returnTypeError: error
3306
- }
3307
- });
3308
- }
3309
- const params = { errorMap: ctx.common.contextualErrorMap };
3310
- const fn = ctx.data;
3311
- if (this._def.returns instanceof ZodPromise) {
3312
- const me = this;
3313
- return OK(async function(...args) {
3314
- const error = new ZodError([]);
3315
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3316
- error.addIssue(makeArgsIssue(args, e));
3317
- throw error;
3318
- });
3319
- const result = await Reflect.apply(fn, this, parsedArgs);
3320
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3321
- error.addIssue(makeReturnsIssue(result, e));
3322
- throw error;
3323
- });
3324
- return parsedReturns;
3325
- });
3326
- } else {
3327
- const me = this;
3328
- return OK(function(...args) {
3329
- const parsedArgs = me._def.args.safeParse(args, params);
3330
- if (!parsedArgs.success) {
3331
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3332
- }
3333
- const result = Reflect.apply(fn, this, parsedArgs.data);
3334
- const parsedReturns = me._def.returns.safeParse(result, params);
3335
- if (!parsedReturns.success) {
3336
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3337
- }
3338
- return parsedReturns.data;
3339
- });
3340
- }
3341
- }
3342
- parameters() {
3343
- return this._def.args;
3344
- }
3345
- returnType() {
3346
- return this._def.returns;
3347
- }
3348
- args(...items) {
3349
- return new _ZodFunction({
3350
- ...this._def,
3351
- args: ZodTuple.create(items).rest(ZodUnknown.create())
3352
- });
3353
- }
3354
- returns(returnType) {
3355
- return new _ZodFunction({
3356
- ...this._def,
3357
- returns: returnType
3358
- });
3359
- }
3360
- implement(func) {
3361
- const validatedFunc = this.parse(func);
3362
- return validatedFunc;
3363
- }
3364
- strictImplement(func) {
3365
- const validatedFunc = this.parse(func);
3366
- return validatedFunc;
3367
- }
3368
- static create(args, returns, params) {
3369
- return new _ZodFunction({
3370
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3371
- returns: returns || ZodUnknown.create(),
3372
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3373
- ...processCreateParams(params)
3374
- });
3375
- }
3376
- };
3377
- var ZodLazy = class extends ZodType {
3378
- get schema() {
3379
- return this._def.getter();
3380
- }
3381
- _parse(input) {
3382
- const { ctx } = this._processInputParams(input);
3383
- const lazySchema = this._def.getter();
3384
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3385
- }
3386
- };
3387
- ZodLazy.create = (getter, params) => {
3388
- return new ZodLazy({
3389
- getter,
3390
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3391
- ...processCreateParams(params)
3392
- });
3393
- };
3394
- var ZodLiteral = class extends ZodType {
3395
- _parse(input) {
3396
- if (input.data !== this._def.value) {
3397
- const ctx = this._getOrReturnCtx(input);
3398
- addIssueToContext(ctx, {
3399
- received: ctx.data,
3400
- code: ZodIssueCode.invalid_literal,
3401
- expected: this._def.value
3402
- });
3403
- return INVALID;
3404
- }
3405
- return { status: "valid", value: input.data };
3406
- }
3407
- get value() {
3408
- return this._def.value;
3409
- }
3410
- };
3411
- ZodLiteral.create = (value, params) => {
3412
- return new ZodLiteral({
3413
- value,
3414
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3415
- ...processCreateParams(params)
3416
- });
3417
- };
3418
- function createZodEnum(values, params) {
3419
- return new ZodEnum({
3420
- values,
3421
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3422
- ...processCreateParams(params)
3423
- });
3424
- }
3425
- var ZodEnum = class _ZodEnum extends ZodType {
3426
- _parse(input) {
3427
- if (typeof input.data !== "string") {
3428
- const ctx = this._getOrReturnCtx(input);
3429
- const expectedValues = this._def.values;
3430
- addIssueToContext(ctx, {
3431
- expected: util.joinValues(expectedValues),
3432
- received: ctx.parsedType,
3433
- code: ZodIssueCode.invalid_type
3434
- });
3435
- return INVALID;
3436
- }
3437
- if (!this._cache) {
3438
- this._cache = new Set(this._def.values);
3439
- }
3440
- if (!this._cache.has(input.data)) {
3441
- const ctx = this._getOrReturnCtx(input);
3442
- const expectedValues = this._def.values;
3443
- addIssueToContext(ctx, {
3444
- received: ctx.data,
3445
- code: ZodIssueCode.invalid_enum_value,
3446
- options: expectedValues
3447
- });
3448
- return INVALID;
3449
- }
3450
- return OK(input.data);
3451
- }
3452
- get options() {
3453
- return this._def.values;
3454
- }
3455
- get enum() {
3456
- const enumValues = {};
3457
- for (const val of this._def.values) {
3458
- enumValues[val] = val;
3459
- }
3460
- return enumValues;
3461
- }
3462
- get Values() {
3463
- const enumValues = {};
3464
- for (const val of this._def.values) {
3465
- enumValues[val] = val;
3466
- }
3467
- return enumValues;
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
- extract(values, newDef = this._def) {
3477
- return _ZodEnum.create(values, {
3478
- ...this._def,
3479
- ...newDef
3480
- });
3481
- }
3482
- exclude(values, newDef = this._def) {
3483
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3484
- ...this._def,
3485
- ...newDef
3486
- });
3487
- }
3488
- };
3489
- ZodEnum.create = createZodEnum;
3490
- var ZodNativeEnum = class extends ZodType {
3491
- _parse(input) {
3492
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3493
- const ctx = this._getOrReturnCtx(input);
3494
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3495
- const expectedValues = util.objectValues(nativeEnumValues);
3496
- addIssueToContext(ctx, {
3497
- expected: util.joinValues(expectedValues),
3498
- received: ctx.parsedType,
3499
- code: ZodIssueCode.invalid_type
3500
- });
3501
- return INVALID;
3502
- }
3503
- if (!this._cache) {
3504
- this._cache = new Set(util.getValidEnumValues(this._def.values));
3505
- }
3506
- if (!this._cache.has(input.data)) {
3507
- const expectedValues = util.objectValues(nativeEnumValues);
3508
- addIssueToContext(ctx, {
3509
- received: ctx.data,
3510
- code: ZodIssueCode.invalid_enum_value,
3511
- options: expectedValues
3512
- });
3513
- return INVALID;
3514
- }
3515
- return OK(input.data);
3516
- }
3517
- get enum() {
3518
- return this._def.values;
3519
- }
3520
- };
3521
- ZodNativeEnum.create = (values, params) => {
3522
- return new ZodNativeEnum({
3523
- values,
3524
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3525
- ...processCreateParams(params)
3526
- });
3527
- };
3528
- var ZodPromise = class extends ZodType {
3529
- unwrap() {
3530
- return this._def.type;
3531
- }
3532
- _parse(input) {
3533
- const { ctx } = this._processInputParams(input);
3534
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3535
- addIssueToContext(ctx, {
3536
- code: ZodIssueCode.invalid_type,
3537
- expected: ZodParsedType.promise,
3538
- received: ctx.parsedType
3539
- });
3540
- return INVALID;
3541
- }
3542
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3543
- return OK(promisified.then((data) => {
3544
- return this._def.type.parseAsync(data, {
3545
- path: ctx.path,
3546
- errorMap: ctx.common.contextualErrorMap
3547
- });
3548
- }));
3549
- }
3550
- };
3551
- ZodPromise.create = (schema, params) => {
3552
- return new ZodPromise({
3553
- type: schema,
3554
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3555
- ...processCreateParams(params)
3556
- });
3557
- };
3558
- var ZodEffects = class extends ZodType {
3559
- innerType() {
3560
- return this._def.schema;
3561
- }
3562
- sourceType() {
3563
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3564
- }
3565
- _parse(input) {
3566
- const { status, ctx } = this._processInputParams(input);
3567
- const effect = this._def.effect || null;
3568
- const checkCtx = {
3569
- addIssue: (arg) => {
3570
- addIssueToContext(ctx, arg);
3571
- if (arg.fatal) {
3572
- status.abort();
3573
- } else {
3574
- status.dirty();
3575
- }
3576
- },
3577
- get path() {
3578
- return ctx.path;
3579
- }
3580
- };
3581
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3582
- if (effect.type === "preprocess") {
3583
- const processed = effect.transform(ctx.data, checkCtx);
3584
- if (ctx.common.async) {
3585
- return Promise.resolve(processed).then(async (processed2) => {
3586
- if (status.value === "aborted")
3587
- return INVALID;
3588
- const result = await this._def.schema._parseAsync({
3589
- data: processed2,
3590
- path: ctx.path,
3591
- parent: ctx
3592
- });
3593
- if (result.status === "aborted")
3594
- return INVALID;
3595
- if (result.status === "dirty")
3596
- return DIRTY(result.value);
3597
- if (status.value === "dirty")
3598
- return DIRTY(result.value);
3599
- return result;
3600
- });
3601
- } else {
3602
- if (status.value === "aborted")
3603
- return INVALID;
3604
- const result = this._def.schema._parseSync({
3605
- data: processed,
3606
- path: ctx.path,
3607
- parent: ctx
3608
- });
3609
- if (result.status === "aborted")
3610
- return INVALID;
3611
- if (result.status === "dirty")
3612
- return DIRTY(result.value);
3613
- if (status.value === "dirty")
3614
- return DIRTY(result.value);
3615
- return result;
3616
- }
3617
- }
3618
- if (effect.type === "refinement") {
3619
- const executeRefinement = (acc) => {
3620
- const result = effect.refinement(acc, checkCtx);
3621
- if (ctx.common.async) {
3622
- return Promise.resolve(result);
3623
- }
3624
- if (result instanceof Promise) {
3625
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3626
- }
3627
- return acc;
3628
- };
3629
- if (ctx.common.async === false) {
3630
- const inner = this._def.schema._parseSync({
3631
- data: ctx.data,
3632
- path: ctx.path,
3633
- parent: ctx
3634
- });
3635
- if (inner.status === "aborted")
3636
- return INVALID;
3637
- if (inner.status === "dirty")
3638
- status.dirty();
3639
- executeRefinement(inner.value);
3640
- return { status: status.value, value: inner.value };
3641
- } else {
3642
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3643
- if (inner.status === "aborted")
3644
- return INVALID;
3645
- if (inner.status === "dirty")
3646
- status.dirty();
3647
- return executeRefinement(inner.value).then(() => {
3648
- return { status: status.value, value: inner.value };
3649
- });
3650
- });
3651
- }
3652
- }
3653
- if (effect.type === "transform") {
3654
- if (ctx.common.async === false) {
3655
- const base = this._def.schema._parseSync({
3656
- data: ctx.data,
3657
- path: ctx.path,
3658
- parent: ctx
3659
- });
3660
- if (!isValid(base))
3661
- return INVALID;
3662
- const result = effect.transform(base.value, checkCtx);
3663
- if (result instanceof Promise) {
3664
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3665
- }
3666
- return { status: status.value, value: result };
3667
- } else {
3668
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3669
- if (!isValid(base))
3670
- return INVALID;
3671
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3672
- status: status.value,
3673
- value: result
3674
- }));
3675
- });
3676
- }
3677
- }
3678
- util.assertNever(effect);
3679
- }
3680
- };
3681
- ZodEffects.create = (schema, effect, params) => {
3682
- return new ZodEffects({
3683
- schema,
3684
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3685
- effect,
3686
- ...processCreateParams(params)
3687
- });
3688
- };
3689
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3690
- return new ZodEffects({
3691
- schema,
3692
- effect: { type: "preprocess", transform: preprocess },
3693
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3694
- ...processCreateParams(params)
3695
- });
3696
- };
3697
- var ZodOptional = class extends ZodType {
3698
- _parse(input) {
3699
- const parsedType = this._getType(input);
3700
- if (parsedType === ZodParsedType.undefined) {
3701
- return OK(void 0);
3702
- }
3703
- return this._def.innerType._parse(input);
3704
- }
3705
- unwrap() {
3706
- return this._def.innerType;
3707
- }
3708
- };
3709
- ZodOptional.create = (type, params) => {
3710
- return new ZodOptional({
3711
- innerType: type,
3712
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3713
- ...processCreateParams(params)
3714
- });
3715
- };
3716
- var ZodNullable = class extends ZodType {
3717
- _parse(input) {
3718
- const parsedType = this._getType(input);
3719
- if (parsedType === ZodParsedType.null) {
3720
- return OK(null);
3721
- }
3722
- return this._def.innerType._parse(input);
3723
- }
3724
- unwrap() {
3725
- return this._def.innerType;
3726
- }
3727
- };
3728
- ZodNullable.create = (type, params) => {
3729
- return new ZodNullable({
3730
- innerType: type,
3731
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3732
- ...processCreateParams(params)
3733
- });
3734
- };
3735
- var ZodDefault = class extends ZodType {
3736
- _parse(input) {
3737
- const { ctx } = this._processInputParams(input);
3738
- let data = ctx.data;
3739
- if (ctx.parsedType === ZodParsedType.undefined) {
3740
- data = this._def.defaultValue();
3741
- }
3742
- return this._def.innerType._parse({
3743
- data,
3744
- path: ctx.path,
3745
- parent: ctx
3746
- });
3747
- }
3748
- removeDefault() {
3749
- return this._def.innerType;
3750
- }
3751
- };
3752
- ZodDefault.create = (type, params) => {
3753
- return new ZodDefault({
3754
- innerType: type,
3755
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3756
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3757
- ...processCreateParams(params)
3758
- });
3759
- };
3760
- var ZodCatch = class extends ZodType {
3761
- _parse(input) {
3762
- const { ctx } = this._processInputParams(input);
3763
- const newCtx = {
3764
- ...ctx,
3765
- common: {
3766
- ...ctx.common,
3767
- issues: []
3768
- }
3769
- };
3770
- const result = this._def.innerType._parse({
3771
- data: newCtx.data,
3772
- path: newCtx.path,
3773
- parent: {
3774
- ...newCtx
3775
- }
3776
- });
3777
- if (isAsync(result)) {
3778
- return result.then((result2) => {
3779
- return {
3780
- status: "valid",
3781
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
3782
- get error() {
3783
- return new ZodError(newCtx.common.issues);
3784
- },
3785
- input: newCtx.data
3786
- })
3787
- };
3788
- });
3789
- } else {
3790
- return {
3791
- status: "valid",
3792
- value: result.status === "valid" ? result.value : this._def.catchValue({
3793
- get error() {
3794
- return new ZodError(newCtx.common.issues);
3795
- },
3796
- input: newCtx.data
3797
- })
3798
- };
3799
- }
3800
- }
3801
- removeCatch() {
3802
- return this._def.innerType;
3803
- }
3804
- };
3805
- ZodCatch.create = (type, params) => {
3806
- return new ZodCatch({
3807
- innerType: type,
3808
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3809
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3810
- ...processCreateParams(params)
3811
- });
3812
- };
3813
- var ZodNaN = class extends ZodType {
3814
- _parse(input) {
3815
- const parsedType = this._getType(input);
3816
- if (parsedType !== ZodParsedType.nan) {
3817
- const ctx = this._getOrReturnCtx(input);
3818
- addIssueToContext(ctx, {
3819
- code: ZodIssueCode.invalid_type,
3820
- expected: ZodParsedType.nan,
3821
- received: ctx.parsedType
3822
- });
3823
- return INVALID;
3824
- }
3825
- return { status: "valid", value: input.data };
3826
- }
3827
- };
3828
- ZodNaN.create = (params) => {
3829
- return new ZodNaN({
3830
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3831
- ...processCreateParams(params)
3832
- });
3833
- };
3834
- var BRAND = /* @__PURE__ */ Symbol("zod_brand");
3835
- var ZodBranded = class extends ZodType {
3836
- _parse(input) {
3837
- const { ctx } = this._processInputParams(input);
3838
- const data = ctx.data;
3839
- return this._def.type._parse({
3840
- data,
3841
- path: ctx.path,
3842
- parent: ctx
3843
- });
3844
- }
3845
- unwrap() {
3846
- return this._def.type;
3847
- }
3848
- };
3849
- var ZodPipeline = class _ZodPipeline extends ZodType {
3850
- _parse(input) {
3851
- const { status, ctx } = this._processInputParams(input);
3852
- if (ctx.common.async) {
3853
- const handleAsync = async () => {
3854
- const inResult = await this._def.in._parseAsync({
3855
- data: ctx.data,
3856
- path: ctx.path,
3857
- parent: ctx
3858
- });
3859
- if (inResult.status === "aborted")
3860
- return INVALID;
3861
- if (inResult.status === "dirty") {
3862
- status.dirty();
3863
- return DIRTY(inResult.value);
3864
- } else {
3865
- return this._def.out._parseAsync({
3866
- data: inResult.value,
3867
- path: ctx.path,
3868
- parent: ctx
3869
- });
3870
- }
3871
- };
3872
- return handleAsync();
3873
- } else {
3874
- const inResult = this._def.in._parseSync({
3875
- data: ctx.data,
3876
- path: ctx.path,
3877
- parent: ctx
3878
- });
3879
- if (inResult.status === "aborted")
3880
- return INVALID;
3881
- if (inResult.status === "dirty") {
3882
- status.dirty();
3883
- return {
3884
- status: "dirty",
3885
- value: inResult.value
3886
- };
3887
- } else {
3888
- return this._def.out._parseSync({
3889
- data: inResult.value,
3890
- path: ctx.path,
3891
- parent: ctx
3892
- });
3893
- }
3894
- }
3895
- }
3896
- static create(a, b) {
3897
- return new _ZodPipeline({
3898
- in: a,
3899
- out: b,
3900
- typeName: ZodFirstPartyTypeKind.ZodPipeline
3901
- });
3902
- }
3903
- };
3904
- var ZodReadonly = class extends ZodType {
3905
- _parse(input) {
3906
- const result = this._def.innerType._parse(input);
3907
- const freeze = (data) => {
3908
- if (isValid(data)) {
3909
- data.value = Object.freeze(data.value);
3910
- }
3911
- return data;
3912
- };
3913
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3914
- }
3915
- unwrap() {
3916
- return this._def.innerType;
3917
- }
3918
- };
3919
- ZodReadonly.create = (type, params) => {
3920
- return new ZodReadonly({
3921
- innerType: type,
3922
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3923
- ...processCreateParams(params)
3924
- });
3925
- };
3926
- function cleanParams(params, data) {
3927
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3928
- const p2 = typeof p === "string" ? { message: p } : p;
3929
- return p2;
3930
- }
3931
- function custom(check, _params = {}, fatal) {
3932
- if (check)
3933
- return ZodAny.create().superRefine((data, ctx) => {
3934
- const r = check(data);
3935
- if (r instanceof Promise) {
3936
- return r.then((r2) => {
3937
- if (!r2) {
3938
- const params = cleanParams(_params, data);
3939
- const _fatal = params.fatal ?? fatal ?? true;
3940
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3941
- }
3942
- });
3943
- }
3944
- if (!r) {
3945
- const params = cleanParams(_params, data);
3946
- const _fatal = params.fatal ?? fatal ?? true;
3947
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3948
- }
3949
- return;
3950
- });
3951
- return ZodAny.create();
3952
- }
3953
- var late = {
3954
- object: ZodObject.lazycreate
3955
- };
3956
- var ZodFirstPartyTypeKind;
3957
- (function(ZodFirstPartyTypeKind2) {
3958
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3959
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3960
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3961
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3962
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3963
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3964
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3965
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3966
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3967
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3968
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3969
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3970
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3971
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3972
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3973
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3974
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3975
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3976
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3977
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3978
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3979
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3980
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3981
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3982
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3983
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3984
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3985
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3986
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3987
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3988
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3989
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3990
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
3991
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
3992
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
3993
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
3994
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3995
- var instanceOfType = (cls, params = {
3996
- message: `Input not instance of ${cls.name}`
3997
- }) => custom((data) => data instanceof cls, params);
3998
- var stringType = ZodString.create;
3999
- var numberType = ZodNumber.create;
4000
- var nanType = ZodNaN.create;
4001
- var bigIntType = ZodBigInt.create;
4002
- var booleanType = ZodBoolean.create;
4003
- var dateType = ZodDate.create;
4004
- var symbolType = ZodSymbol.create;
4005
- var undefinedType = ZodUndefined.create;
4006
- var nullType = ZodNull.create;
4007
- var anyType = ZodAny.create;
4008
- var unknownType = ZodUnknown.create;
4009
- var neverType = ZodNever.create;
4010
- var voidType = ZodVoid.create;
4011
- var arrayType = ZodArray.create;
4012
- var objectType = ZodObject.create;
4013
- var strictObjectType = ZodObject.strictCreate;
4014
- var unionType = ZodUnion.create;
4015
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
4016
- var intersectionType = ZodIntersection.create;
4017
- var tupleType = ZodTuple.create;
4018
- var recordType = ZodRecord.create;
4019
- var mapType = ZodMap.create;
4020
- var setType = ZodSet.create;
4021
- var functionType = ZodFunction.create;
4022
- var lazyType = ZodLazy.create;
4023
- var literalType = ZodLiteral.create;
4024
- var enumType = ZodEnum.create;
4025
- var nativeEnumType = ZodNativeEnum.create;
4026
- var promiseType = ZodPromise.create;
4027
- var effectsType = ZodEffects.create;
4028
- var optionalType = ZodOptional.create;
4029
- var nullableType = ZodNullable.create;
4030
- var preprocessType = ZodEffects.createWithPreprocess;
4031
- var pipelineType = ZodPipeline.create;
4032
- var ostring = () => stringType().optional();
4033
- var onumber = () => numberType().optional();
4034
- var oboolean = () => booleanType().optional();
4035
- var coerce = {
4036
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4037
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4038
- boolean: ((arg) => ZodBoolean.create({
4039
- ...arg,
4040
- coerce: true
4041
- })),
4042
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4043
- date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4044
- };
4045
- var NEVER = INVALID;
4046
-
4047
- // ../../super-agent-core/dist/mcp/index.js
4048
- var MCP_PROTOCOL_VERSION = "2024-11-05";
4049
- var JSONRPC_VERSION = "2.0";
4050
- var McpErrorCode = {
4051
- /** Некорректный JSON в запросе */
4052
- ParseError: -32700,
4053
- /** Запрошенный метод не существует */
4054
- MethodNotFound: -32601,
4055
- /** Некорректные параметры метода */
4056
- InvalidParams: -32602,
4057
- /** Внутренняя ошибка сервера */
4058
- InternalError: -32603};
4059
- var McpError = class extends Error {
4060
- /** Числовой код ошибки JSON-RPC/MCP */
4061
- code;
4062
- /** Дополнительные данные об ошибке */
4063
- data;
4064
- constructor(code, message, data) {
4065
- super(message);
4066
- this.name = "McpError";
4067
- this.code = code;
4068
- if (data !== void 0) {
4069
- this.data = data;
4070
- }
4071
- }
4072
- /** Сериализация в JSON-RPC формат для передачи клиенту */
4073
- toJsonRpcError() {
4074
- const error = { code: this.code, message: this.message };
4075
- if (this.data !== void 0) {
4076
- error.data = this.data;
4077
- }
4078
- return error;
4079
- }
4080
- };
4081
- var MAX_LINE_LENGTH = 10 * 1024 * 1024;
4082
- var NdjsonFramer = class {
4083
- constructor(callbacks) {
4084
- this.callbacks = callbacks;
4085
- }
4086
- /** Хвост последнего чанка без завершающего \n. */
4087
- buffer = "";
4088
- /**
4089
- * Скармливает очередной кусок потока. Все полные строки будут разобраны
4090
- * синхронно, неполный хвост останется в буфере до следующего вызова.
4091
- */
4092
- push(chunk) {
4093
- this.buffer += chunk;
4094
- if (this.buffer.length > MAX_LINE_LENGTH) {
4095
- this.buffer = "";
4096
- this.callbacks.onOverflow(new McpError(
4097
- McpErrorCode.ParseError,
4098
- `\u0411\u0443\u0444\u0435\u0440 stdio \u043F\u0440\u0435\u0432\u044B\u0441\u0438\u043B \u043B\u0438\u043C\u0438\u0442 ${MAX_LINE_LENGTH} \u0431\u0430\u0439\u0442`
4099
- ));
4100
- return;
4101
- }
4102
- let newlineIndex;
4103
- while ((newlineIndex = this.buffer.indexOf("\n")) !== -1) {
4104
- const line = this.buffer.slice(0, newlineIndex).trim();
4105
- this.buffer = this.buffer.slice(newlineIndex + 1);
4106
- if (line.length === 0) continue;
4107
- this.parseLine(line);
4108
- }
4109
- }
4110
- /** Сбрасывает накопленный хвост (при закрытии соединения). */
4111
- reset() {
4112
- this.buffer = "";
4113
- }
4114
- parseLine(line) {
4115
- let raw;
4116
- try {
4117
- raw = JSON.parse(line);
4118
- } catch {
4119
- this.callbacks.onInvalidLine?.(line, "\u043E\u0448\u0438\u0431\u043A\u0430 \u043F\u0430\u0440\u0441\u0438\u043D\u0433\u0430 JSON");
4120
- return;
4121
- }
4122
- if (typeof raw !== "object" || raw === null || !("jsonrpc" in raw) || raw["jsonrpc"] !== JSONRPC_VERSION) {
4123
- this.callbacks.onInvalidLine?.(line, "\u043D\u0435 JSON-RPC 2.0");
4124
- return;
4125
- }
4126
- this.callbacks.onMessage(raw);
4127
- }
4128
- };
4129
- function encodeNdjsonLine(message) {
4130
- return JSON.stringify(message) + "\n";
4131
- }
4132
- var StdioServerTransport = class {
4133
- messageCallback = null;
4134
- closeCallback = null;
4135
- /** Транспорт закрыт — повторные close() и поздние чанки игнорируются. */
4136
- closed = false;
4137
- /** connect() уже отработал — защита от двойной подписки на stdin. */
4138
- connected = false;
4139
- /** Разбор входящего потока — общий с клиентским транспортом (правило 21). */
4140
- framer = new NdjsonFramer({
4141
- onMessage: (message) => this.messageCallback?.(message),
4142
- onInvalidLine: (line, reason) => {
4143
- process.stderr.write(`[MCP:server] ${reason}: ${line}
4144
- `);
4145
- },
4146
- onOverflow: (error) => this.handleClose(error)
4147
- });
4148
- // Ссылки на слушатели нужны, чтобы отписаться в close(): без этого процесс
4149
- // не завершится (открытый listener на stdin держит event loop).
4150
- onStdinData = (chunk) => {
4151
- if (this.closed) return;
4152
- this.framer.push(chunk);
4153
- };
4154
- onStdinEnd = () => {
4155
- this.handleClose();
4156
- };
4157
- onStdinError = (err) => {
4158
- this.handleClose(new McpError(
4159
- McpErrorCode.InternalError,
4160
- `\u041E\u0448\u0438\u0431\u043A\u0430 \u0447\u0442\u0435\u043D\u0438\u044F stdin: ${err.message}`,
4161
- err
4162
- ));
4163
- };
4164
- onMessage(callback) {
4165
- this.messageCallback = callback;
4166
- }
4167
- onClose(callback) {
4168
- this.closeCallback = callback;
4169
- }
4170
- /**
4171
- * Подписывается на собственный stdin. В отличие от клиентского транспорта
4172
- * ничего не запускает — процесс уже создан тем, кто нас вызвал.
4173
- */
4174
- async connect() {
4175
- if (this.closed) {
4176
- throw new McpError(McpErrorCode.InternalError, "Stdio-\u0442\u0440\u0430\u043D\u0441\u043F\u043E\u0440\u0442 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u0443\u0436\u0435 \u0437\u0430\u043A\u0440\u044B\u0442");
4177
- }
4178
- if (this.connected) {
4179
- throw new McpError(McpErrorCode.InternalError, "Stdio-\u0442\u0440\u0430\u043D\u0441\u043F\u043E\u0440\u0442 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u0443\u0436\u0435 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0451\u043D");
4180
- }
4181
- this.connected = true;
4182
- process.stdin.setEncoding("utf8");
4183
- process.stdin.on("data", this.onStdinData);
4184
- process.stdin.on("end", this.onStdinEnd);
4185
- process.stdin.on("error", this.onStdinError);
4186
- process.stdin.resume();
4187
- return Promise.resolve();
4188
- }
4189
- /**
4190
- * Пишет JSON-RPC сообщение в stdout одной строкой.
4191
- *
4192
- * Ждём callback записи (и drain при заполненном буфере), чтобы порядок
4193
- * сообщений сохранялся: без ожидания большой ответ tools/call мог бы
4194
- * перемешаться со следующим уведомлением.
4195
- */
4196
- async send(message) {
4197
- if (this.closed) {
4198
- throw new McpError(McpErrorCode.InternalError, "Stdio-\u0442\u0440\u0430\u043D\u0441\u043F\u043E\u0440\u0442 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043D\u0435 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0451\u043D");
4199
- }
4200
- const line = encodeNdjsonLine(message);
4201
- await new Promise((resolve, reject) => {
4202
- let settled = false;
4203
- const done = () => {
4204
- if (settled) return;
4205
- settled = true;
4206
- resolve();
4207
- };
4208
- const flushed = process.stdout.write(line, "utf8", (err) => {
4209
- if (err !== null && err !== void 0) {
4210
- reject(new McpError(McpErrorCode.InternalError, `\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u043F\u0438\u0441\u0438 \u0432 stdout: ${err.message}`, err));
4211
- return;
4212
- }
4213
- done();
4214
- });
4215
- if (!flushed) {
4216
- process.stdout.once("drain", done);
4217
- }
4218
- });
4219
- }
4220
- /**
4221
- * Отписывается от stdin. Процесс НЕ убивает — им владеет тот, кто нас
4222
- * запустил; наше дело — перестать держать event loop, чтобы Node мог выйти сам.
4223
- * Идемпотентен.
4224
- */
4225
- async close() {
4226
- if (this.closed) return;
4227
- this.detach();
4228
- this.handleClose();
4229
- return Promise.resolve();
4230
- }
4231
- /** Снимает слушатели и отпускает stdin. */
4232
- detach() {
4233
- process.stdin.off("data", this.onStdinData);
4234
- process.stdin.off("end", this.onStdinEnd);
4235
- process.stdin.off("error", this.onStdinError);
4236
- process.stdin.pause();
4237
- }
4238
- handleClose(error) {
4239
- if (this.closed) return;
4240
- this.closed = true;
4241
- this.detach();
4242
- this.framer.reset();
4243
- this.closeCallback?.(error);
4244
- }
4245
- };
4246
- external_exports.object({
4247
- name: external_exports.string().min(1).regex(/^[a-z][a-z0-9_]*$/, "\u0418\u043C\u044F \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C snake_case"),
4248
- description: external_exports.string().min(1),
4249
- inputSchema: external_exports.object({
4250
- type: external_exports.literal("object"),
4251
- properties: external_exports.record(external_exports.unknown()),
4252
- required: external_exports.array(external_exports.string()).optional()
4253
- })
4254
- });
4255
- function toolSuccess(content) {
4256
- return { type: "success", content };
4257
- }
4258
- function toolError(error, code) {
4259
- return { type: "error", error };
4260
- }
4261
- var SERVER_INFO = {
4262
- name: "@naparnik/super-agent-core",
4263
- version: "0.1.0"
4264
- };
4265
- var SERVER_CAPABILITIES = {
4266
- tools: {
4267
- listChanged: true
4268
- }
4269
- };
4270
- var McpServer = class {
4271
- /** Зарегистрированные инструменты: имя → инструмент */
4272
- tools = /* @__PURE__ */ new Map();
4273
- /** Активный транспорт */
4274
- transport = null;
4275
- /** Контекст выполнения инструментов */
4276
- toolContext;
4277
- /** Флаг запущенного сервера */
4278
- running = false;
4279
- /** Флаг инициализации клиента (после handshake) */
4280
- clientInitialized = false;
4281
- constructor(toolContext) {
4282
- this.toolContext = {
4283
- sessionId: `mcp-server-${Date.now()}`,
4284
- env: "server",
4285
- readFileTimestamps: {},
4286
- ...toolContext
4287
- };
4288
- }
4289
- /**
4290
- * Регистрирует инструмент агента для экспорта через MCP.
4291
- * Если инструмент с таким именем уже есть — перезаписывает.
4292
- */
4293
- addTool(tool) {
4294
- this.tools.set(tool.name, tool);
4295
- if (this.clientInitialized && this.transport !== null) {
4296
- void this.sendNotification("notifications/tools/list_changed");
4297
- }
4298
- }
4299
- /**
4300
- * Удаляет инструмент из MCP-экспорта.
4301
- * @returns true если инструмент был найден и удалён
4302
- */
4303
- removeTool(name) {
4304
- const removed = this.tools.delete(name);
4305
- if (removed && this.clientInitialized && this.transport !== null) {
4306
- void this.sendNotification("notifications/tools/list_changed");
4307
- }
4308
- return removed;
4309
- }
4310
- /**
4311
- * Запускает MCP-сервер на указанном транспорте.
4312
- * Начинает принимать и обрабатывать запросы.
4313
- */
4314
- async start(transport) {
4315
- if (this.running) {
4316
- throw new McpError(McpErrorCode.InternalError, "\u0421\u0435\u0440\u0432\u0435\u0440 \u0443\u0436\u0435 \u0437\u0430\u043F\u0443\u0449\u0435\u043D");
4317
- }
4318
- this.transport = transport;
4319
- this.running = true;
4320
- transport.onMessage((message) => void this.handleMessage(message));
4321
- transport.onClose(() => {
4322
- this.running = false;
4323
- this.clientInitialized = false;
4324
- this.transport = null;
4325
- });
4326
- }
4327
- /**
4328
- * Останавливает MCP-сервер.
4329
- */
4330
- async stop() {
4331
- if (!this.running) return;
4332
- this.running = false;
4333
- this.clientInitialized = false;
4334
- await this.transport?.close();
4335
- this.transport = null;
4336
- }
4337
- /** Возвращает список зарегистрированных инструментов в формате MCP */
4338
- listMcpTools() {
4339
- const result = [];
4340
- for (const tool of this.tools.values()) {
4341
- result.push(this.toolToMcpTool(tool));
4342
- }
4343
- return result;
4344
- }
4345
- // ─── Внутренние методы ────────────────────────────────────────────────────
4346
- /**
4347
- * Маршрутизирует входящее JSON-RPC сообщение.
4348
- */
4349
- async handleMessage(message) {
4350
- if (!("id" in message) && "method" in message) {
4351
- const method = message.method;
4352
- if (method === "notifications/initialized") {
4353
- this.clientInitialized = true;
4354
- }
4355
- return;
4356
- }
4357
- if ("id" in message && "method" in message) {
4358
- await this.handleRequest(message);
4359
- }
4360
- }
4361
- /**
4362
- * Обрабатывает JSON-RPC запрос и отправляет ответ.
4363
- */
4364
- async handleRequest(request) {
4365
- const { id, method, params } = request;
4366
- try {
4367
- const result = await this.dispatchMethod(method, params);
4368
- await this.sendResponse(id, result);
4369
- } catch (err) {
4370
- const error = err instanceof McpError ? err : new McpError(McpErrorCode.InternalError, err instanceof Error ? err.message : String(err));
4371
- await this.sendError(id, error);
4372
- }
4373
- }
4374
- /**
4375
- * Диспетчеризует вызов метода на соответствующий обработчик.
4376
- */
4377
- async dispatchMethod(method, params) {
4378
- switch (method) {
4379
- case "initialize":
4380
- return this.handleInitialize(params);
4381
- case "ping":
4382
- return {};
4383
- case "tools/list":
4384
- return { tools: this.listMcpTools() };
4385
- case "tools/call":
4386
- return await this.handleToolCall(params);
4387
- default:
4388
- throw new McpError(McpErrorCode.MethodNotFound, `\u041C\u0435\u0442\u043E\u0434 \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F: ${method}`);
4389
- }
4390
- }
4391
- /**
4392
- * Обрабатывает запрос инициализации.
4393
- */
4394
- handleInitialize(params) {
4395
- const clientVersion = params?.["protocolVersion"];
4396
- const negotiatedVersion = typeof clientVersion === "string" && clientVersion.length > 0 ? clientVersion : MCP_PROTOCOL_VERSION;
4397
- return {
4398
- protocolVersion: negotiatedVersion,
4399
- capabilities: SERVER_CAPABILITIES,
4400
- serverInfo: SERVER_INFO
4401
- };
4402
- }
4403
- /**
4404
- * Обрабатывает запрос вызова инструмента.
4405
- */
4406
- async handleToolCall(params) {
4407
- if (params === void 0) {
4408
- throw new McpError(McpErrorCode.InvalidParams, "\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B tools/call \u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u044B");
4409
- }
4410
- const name = params["name"];
4411
- if (typeof name !== "string" || name.length === 0) {
4412
- throw new McpError(McpErrorCode.InvalidParams, "\u041F\u043E\u043B\u0435 name \u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E \u0438 \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u0441\u0442\u0440\u043E\u043A\u043E\u0439");
4413
- }
4414
- const tool = this.tools.get(name);
4415
- if (tool === void 0) {
4416
- throw new McpError(McpErrorCode.MethodNotFound, `\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442 \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D: ${name}`);
4417
- }
4418
- const args = params["arguments"] ?? {};
4419
- try {
4420
- const result = await tool.execute(args, this.toolContext);
4421
- if (result.type === "success") {
4422
- const content = typeof result.content === "string" ? [{ type: "text", text: result.content }] : result.content.map((block) => {
4423
- if (block.type === "text") {
4424
- return { type: "text", text: block.text };
4425
- }
4426
- if (block.type === "image_ref") {
4427
- return {
4428
- type: "text",
4429
- text: `[image ${block.mediaType} \u2014 \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u0447\u0435\u0440\u0435\u0437 MCP]`
4430
- };
4431
- }
4432
- return {
4433
- type: "image",
4434
- data: block.base64,
4435
- mimeType: block.mediaType
4436
- };
4437
- });
4438
- return { content };
4439
- } else {
4440
- return {
4441
- content: [{ type: "text", text: result.error }],
4442
- isError: true
4443
- };
4444
- }
4445
- } catch (err) {
4446
- const errorMessage = err instanceof Error ? err.message : String(err);
4447
- return {
4448
- content: [{ type: "text", text: `\u0412\u043D\u0443\u0442\u0440\u0435\u043D\u043D\u044F\u044F \u043E\u0448\u0438\u0431\u043A\u0430 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F: ${errorMessage}` }],
4449
- isError: true
4450
- };
4451
- }
4452
- }
4453
- /**
4454
- * Конвертирует инструмент агента в формат MCP.
4455
- */
4456
- toolToMcpTool(tool) {
4457
- return {
4458
- name: tool.name,
4459
- description: tool.description,
4460
- // ToolInputSchema совместим с McpJsonSchema — приводим через unknown
4461
- inputSchema: tool.inputSchema
4462
- };
4463
- }
4464
- /**
4465
- * Отправляет успешный JSON-RPC ответ.
4466
- */
4467
- async sendResponse(id, result) {
4468
- if (this.transport === null) return;
4469
- await this.transport.send({
4470
- jsonrpc: JSONRPC_VERSION,
4471
- id,
4472
- result
4473
- });
4474
- }
4475
- /**
4476
- * Отправляет JSON-RPC ответ с ошибкой.
4477
- */
4478
- async sendError(id, error) {
4479
- if (this.transport === null) return;
4480
- await this.transport.send({
4481
- jsonrpc: JSONRPC_VERSION,
4482
- id,
4483
- error: error.toJsonRpcError()
4484
- });
4485
- }
4486
- /**
4487
- * Отправляет JSON-RPC уведомление (без ответа).
4488
- */
4489
- async sendNotification(method, params) {
4490
- if (this.transport === null) return;
4491
- const message = {
4492
- jsonrpc: JSONRPC_VERSION,
4493
- method,
4494
- ...params !== void 0 ? { params } : {}
4495
- };
4496
- await this.transport.send(message);
4497
- }
4498
- };
4499
-
4500
- // src/errors.ts
4501
- var NaparnikError = class extends Error {
4502
- constructor(message, cause) {
4503
- super(message);
4504
- this.cause = cause;
4505
- this.name = new.target.name;
4506
- }
4507
- cause;
4508
- /**
4509
- * Имеет ли смысл повторять запрос. По умолчанию нет: повтор — осознанное
4510
- * решение для конкретных подклассов, а не поведение по умолчанию.
4511
- */
4512
- get retryable() {
4513
- return false;
4514
- }
4515
- };
4516
- var NaparnikAuthError = class extends NaparnikError {
4517
- };
4518
- var NaparnikScopeError = class extends NaparnikError {
4519
- constructor(message, requiredScope) {
4520
- super(message);
4521
- this.requiredScope = requiredScope;
4522
- }
4523
- requiredScope;
4524
- };
4525
- var NaparnikInsufficientBalanceError = class extends NaparnikError {
4526
- constructor(message, details) {
4527
- super(message);
4528
- this.details = details;
4529
- }
4530
- details;
4531
- };
4532
- var NaparnikClientError = class extends NaparnikError {
4533
- constructor(message, status, body) {
4534
- super(message);
4535
- this.status = status;
4536
- this.body = body;
4537
- }
4538
- status;
4539
- body;
4540
- };
4541
- var NaparnikServerError = class extends NaparnikError {
4542
- constructor(message, status, body) {
4543
- super(message);
4544
- this.status = status;
4545
- this.body = body;
4546
- }
4547
- status;
4548
- body;
4549
- get retryable() {
4550
- return true;
4551
- }
4552
- };
4553
- var NaparnikTimeoutError = class extends NaparnikError {
4554
- };
4555
- var NaparnikConfigError = class extends NaparnikError {
4556
- };
4557
-
4558
- // src/config.ts
4559
- var API_KEY_REGEX = /^npk_[a-f0-9]{64}$/;
4560
- var DEFAULT_BASE_URL = "https://company.naparnik.ai";
4561
- var DEFAULT_TIMEOUT_MS = 3e4;
4562
- var DEFAULT_LONG_TIMEOUT_MS = 18e4;
4563
- function loadConfig(env = process.env) {
4564
- const apiKey = (env["NAPARNIK_API_KEY"] ?? "").trim();
4565
- if (apiKey === "") {
4566
- throw new NaparnikConfigError(
4567
- "\u041D\u0435 \u0437\u0430\u0434\u0430\u043D \u043A\u043B\u044E\u0447 \u0434\u043E\u0441\u0442\u0443\u043F\u0430. \u0414\u043E\u0431\u0430\u0432\u044C\u0442\u0435 NAPARNIK_API_KEY \u0432 \u0441\u0435\u043A\u0446\u0438\u044E env \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u0430. \u041A\u043B\u044E\u0447 \u0432\u044B\u043F\u0443\u0441\u043A\u0430\u0435\u0442\u0441\u044F \u0432 \u041D\u0430\u043F\u0430\u0440\u043D\u0438\u043A\u0435: \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u2192 API-\u043A\u043B\u044E\u0447\u0438."
4568
- );
4569
- }
4570
- if (!API_KEY_REGEX.test(apiKey)) {
4571
- throw new NaparnikConfigError(
4572
- `\u041A\u043B\u044E\u0447 NAPARNIK_API_KEY \u0438\u043C\u0435\u0435\u0442 \u043D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0444\u043E\u0440\u043C\u0430\u0442 (\u043E\u0436\u0438\u0434\u0430\u0435\u0442\u0441\u044F npk_ \u0438 64 \u0441\u0438\u043C\u0432\u043E\u043B\u0430, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${apiKey.length}). \u0421\u043A\u043E\u043F\u0438\u0440\u0443\u0439\u0442\u0435 \u043A\u043B\u044E\u0447 \u0446\u0435\u043B\u0438\u043A\u043E\u043C \u0438\u0437 \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u2192 API-\u043A\u043B\u044E\u0447\u0438; \u0435\u0441\u043B\u0438 \u043E\u043D \u043F\u043E\u0442\u0435\u0440\u044F\u043D, \u0432\u044B\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u043D\u043E\u0432\u044B\u0439.`
4573
- );
4574
- }
4575
- const baseUrl = (env["NAPARNIK_API_URL"] ?? DEFAULT_BASE_URL).trim().replace(/\/+$/, "");
4576
- return {
4577
- apiKey,
4578
- baseUrl,
4579
- timeoutMs: parsePositiveInt(env["NAPARNIK_TIMEOUT_MS"], DEFAULT_TIMEOUT_MS),
4580
- longTimeoutMs: parsePositiveInt(env["NAPARNIK_LONG_TIMEOUT_MS"], DEFAULT_LONG_TIMEOUT_MS)
4581
- };
4582
- }
4583
- function parsePositiveInt(raw, fallback) {
4584
- if (raw === void 0) return fallback;
4585
- const parsed = Number.parseInt(raw, 10);
4586
- return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
4587
- }
4588
-
4589
- // src/http.ts
4590
- var MAX_RETRIES = 3;
4591
- var RETRY_BASE_MS = 300;
4592
- var RETRY_MAX_MS = 4e3;
4593
- var NaparnikApiClient = class {
4594
- constructor(config) {
4595
- this.config = config;
4596
- }
4597
- config;
4598
- /**
4599
- * POST к sdk-эндпоинту. Все automation-эндпоинты только POST — таково
4600
- * ограничение VerbFilter на сервере, отдельного GET-пути нет.
4601
- *
4602
- * @param path путь относительно /api/internal/automation/sdk
4603
- * @param body тело запроса
4604
- * @param opts long: использовать увеличенный таймаут (генерация, поиск)
4605
- */
4606
- async post(path, body = {}, opts = {}) {
4607
- const url = `${this.config.baseUrl}/api/internal/automation/sdk${path}`;
4608
- const timeoutMs = opts.long === true ? this.config.longTimeoutMs : this.config.timeoutMs;
4609
- let lastError;
4610
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt += 1) {
4611
- try {
4612
- return await this.attempt(url, body, timeoutMs);
4613
- } catch (err) {
4614
- lastError = err;
4615
- const retryable = err instanceof NaparnikServerError && err.retryable;
4616
- if (!retryable || attempt === MAX_RETRIES) throw err;
4617
- await sleep(Math.min(RETRY_BASE_MS * 2 ** attempt, RETRY_MAX_MS));
4618
- }
4619
- }
4620
- throw lastError;
4621
- }
4622
- async attempt(url, body, timeoutMs) {
4623
- const controller = new AbortController();
4624
- const timer = setTimeout(() => controller.abort(), timeoutMs);
4625
- let response;
4626
- try {
4627
- response = await fetch(url, {
4628
- method: "POST",
4629
- headers: {
4630
- "Authorization": `Bearer ${this.config.apiKey}`,
4631
- "Content-Type": "application/json; charset=utf-8",
4632
- "Accept": "application/json",
4633
- "User-Agent": "naparnik-mcp/0.1"
4634
- },
4635
- body: JSON.stringify(body ?? {}),
4636
- signal: controller.signal
4637
- });
4638
- } catch (err) {
4639
- if (controller.signal.aborted) {
4640
- throw new NaparnikTimeoutError(
4641
- `\u041D\u0430\u043F\u0430\u0440\u043D\u0438\u043A \u043D\u0435 \u043E\u0442\u0432\u0435\u0442\u0438\u043B \u0437\u0430 ${Math.round(timeoutMs / 1e3)} \u0441. \u041E\u043F\u0435\u0440\u0430\u0446\u0438\u044F \u043C\u043E\u0433\u043B\u0430 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C\u0441\u044F \u043D\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\u0435 \u2014 \u043F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442, \u043F\u0440\u0435\u0436\u0434\u0435 \u0447\u0435\u043C \u043F\u043E\u0432\u0442\u043E\u0440\u044F\u0442\u044C.`,
4642
- err
4643
- );
4644
- }
4645
- throw new NaparnikServerError(`\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u044C\u0441\u044F \u0441 \u041D\u0430\u043F\u0430\u0440\u043D\u0438\u043A\u043E\u043C: ${describe(err)}`, void 0, void 0);
4646
- } finally {
4647
- clearTimeout(timer);
4648
- }
4649
- return await this.parse(response);
4650
- }
4651
- async parse(response) {
4652
- let text;
4653
- try {
4654
- text = await response.text();
4655
- } catch (err) {
4656
- throw new NaparnikServerError(
4657
- `\u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u043E\u0431\u043E\u0440\u0432\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u0438 \u0447\u0442\u0435\u043D\u0438\u0438 \u043E\u0442\u0432\u0435\u0442\u0430 \u041D\u0430\u043F\u0430\u0440\u043D\u0438\u043A\u0430: ${describe(err)}`,
4658
- response.status
4659
- );
4660
- }
4661
- if (response.ok) {
4662
- if (text === "") return {};
4663
- try {
4664
- return JSON.parse(text);
4665
- } catch {
4666
- throw new NaparnikServerError("\u041D\u0430\u043F\u0430\u0440\u043D\u0438\u043A \u0432\u0435\u0440\u043D\u0443\u043B \u043D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 JSON", response.status, truncate(text));
4667
- }
4668
- }
4669
- const payload = safeJson(text);
4670
- switch (response.status) {
4671
- case 401:
4672
- throw new NaparnikAuthError(
4673
- messageFrom(payload) ?? "\u041A\u043B\u044E\u0447 \u043D\u0435 \u043F\u0440\u0438\u043D\u044F\u0442: \u043E\u043D \u043E\u0442\u043E\u0437\u0432\u0430\u043D, \u0438\u0441\u0442\u0451\u043A \u0438\u043B\u0438 \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D \u043D\u0435 \u043F\u043E\u043B\u043D\u043E\u0441\u0442\u044C\u044E. \u0412\u044B\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u043D\u043E\u0432\u044B\u0439 \u0432 \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u2192 API-\u043A\u043B\u044E\u0447\u0438."
4674
- );
4675
- case 403:
4676
- throw new NaparnikScopeError(
4677
- messageFrom(payload) ?? "\u0423 \u043A\u043B\u044E\u0447\u0430 \u043D\u0435\u0442 \u043F\u0440\u0430\u0432 \u043D\u0430 \u044D\u0442\u0443 \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u044E. \u0412\u044B\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u043A\u043B\u044E\u0447 \u0441 \u043D\u0443\u0436\u043D\u044B\u043C\u0438 \u043F\u0440\u0430\u0432\u0430\u043C\u0438 \u0432 \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u2192 API-\u043A\u043B\u044E\u0447\u0438."
4678
- );
4679
- case 402: {
4680
- const d = payload;
4681
- throw new NaparnikInsufficientBalanceError(
4682
- messageFrom(payload) ?? "\u041D\u0435\u0434\u043E\u0441\u0442\u0430\u0442\u043E\u0447\u043D\u043E \u0441\u0440\u0435\u0434\u0441\u0442\u0432 \u0434\u043B\u044F \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0438.",
4683
- {
4684
- limit: d?.["limit"] === "token_daily" ? "token_daily" : "company_balance",
4685
- balanceRub: numberOr(d?.["balance_rub"], 0),
4686
- requiredRub: numberOr(d?.["required_rub"], 0),
4687
- actionUrl: typeof d?.["action_url"] === "string" ? d["action_url"] : ""
4688
- }
4689
- );
4690
- }
4691
- default:
4692
- if (response.status >= 500) {
4693
- throw new NaparnikServerError(
4694
- `\u041D\u0430\u043F\u0430\u0440\u043D\u0438\u043A \u043E\u0442\u0432\u0435\u0442\u0438\u043B \u043E\u0448\u0438\u0431\u043A\u043E\u0439 ${response.status}. \u042D\u0442\u043E \u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0439 \u0441\u0431\u043E\u0439 \u043D\u0430 \u043D\u0430\u0448\u0435\u0439 \u0441\u0442\u043E\u0440\u043E\u043D\u0435.`,
4695
- response.status,
4696
- truncate(text)
4697
- );
4698
- }
4699
- throw new NaparnikClientError(
4700
- messageFrom(payload) ?? `\u0417\u0430\u043F\u0440\u043E\u0441 \u043E\u0442\u043A\u043B\u043E\u043D\u0451\u043D (${response.status}).`,
4701
- response.status,
4702
- truncate(text)
4703
- );
4704
- }
4705
- }
4706
- };
4707
- function safeJson(text) {
4708
- try {
4709
- return JSON.parse(text);
4710
- } catch {
4711
- return null;
4712
- }
4713
- }
4714
- function messageFrom(payload) {
4715
- if (typeof payload !== "object" || payload === null) return null;
4716
- const obj = payload;
4717
- for (const key of ["message", "error", "detail"]) {
4718
- const value = obj[key];
4719
- if (typeof value === "string" && value.trim() !== "") return value;
4720
- }
4721
- return null;
4722
- }
4723
- function numberOr(value, fallback) {
4724
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
4725
- }
4726
- function truncate(text, limit = 500) {
4727
- return text.length > limit ? `${text.slice(0, limit)}\u2026` : text;
4728
- }
4729
- function describe(err) {
4730
- return err instanceof Error ? err.message : String(err);
4731
- }
4732
- function sleep(ms) {
4733
- return new Promise((resolve) => setTimeout(resolve, ms));
4734
- }
4735
-
4736
- // src/tools.ts
4737
- var DEFAULT_REELS_LIMIT = 20;
4738
- function createNaparnikTools(client) {
4739
- return [
4740
- balanceTool(client),
4741
- brandUnpackingGetTool(client),
4742
- brandUnpackingSaveTool(client),
4743
- reelsListTool(client),
4744
- reelGetTool(client)
4745
- ];
4746
- }
4747
- function balanceTool(client) {
4748
- return {
4749
- name: "get_balance",
4750
- description: "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u0442 \u0431\u0430\u043B\u0430\u043D\u0441 \u043A\u043E\u043C\u043F\u0430\u043D\u0438\u0438 \u0432 \u041D\u0430\u043F\u0430\u0440\u043D\u0438\u043A\u0435 \u0438 \u043E\u0441\u0442\u0430\u0442\u043E\u043A \u0434\u043D\u0435\u0432\u043D\u043E\u0433\u043E \u043B\u0438\u043C\u0438\u0442\u0430 \u0442\u0435\u043A\u0443\u0449\u0435\u0433\u043E \u043A\u043B\u044E\u0447\u0430. \u0412\u044B\u0437\u044B\u0432\u0430\u0439 \u043F\u0435\u0440\u0435\u0434 \u0441\u0435\u0440\u0438\u0435\u0439 \u043F\u043B\u0430\u0442\u043D\u044B\u0445 \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0439 (\u043F\u043E\u0438\u0441\u043A \u0440\u0438\u043B\u0441\u043E\u0432, \u0433\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u044F \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0439), \u0447\u0442\u043E\u0431\u044B \u043D\u0435 \u0443\u043F\u0435\u0440\u0435\u0442\u044C\u0441\u044F \u0432 \u043B\u0438\u043C\u0438\u0442 \u043D\u0430 \u0441\u0435\u0440\u0435\u0434\u0438\u043D\u0435 \u0440\u0430\u0431\u043E\u0442\u044B.",
4751
- inputSchema: { type: "object", properties: {}, required: [] },
4752
- readOnly: true,
4753
- async execute() {
4754
- return await guard(async () => {
4755
- const r = await client.post("/balance-get");
4756
- const lines = [
4757
- `\u0411\u0430\u043B\u0430\u043D\u0441 \u043A\u043E\u043C\u043F\u0430\u043D\u0438\u0438: ${money(r.balance_rub)} \u20BD`,
4758
- `\u0420\u0435\u0436\u0438\u043C: ${billingModeRu(r.billing_mode)}`,
4759
- `\u041F\u043E \u044D\u0442\u043E\u043C\u0443 \u043A\u043B\u044E\u0447\u0443 \u0437\u0430 \u0441\u0435\u0433\u043E\u0434\u043D\u044F: ${money(r.token_spent_today_rub)} \u20BD, \u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C ${money(r.token_daily_remaining_rub)} \u20BD`
4760
- ];
4761
- if (r.trial_days_left !== null) lines.push(`\u041F\u0440\u043E\u0431\u043D\u044B\u0439 \u043F\u0435\u0440\u0438\u043E\u0434: \u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C \u0434\u043D\u0435\u0439 \u2014 ${r.trial_days_left}`);
4762
- if (!r.allowed) {
4763
- lines.push(`\u26A0\uFE0F \u041E\u043F\u0435\u0440\u0430\u0446\u0438\u0438 \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u044B${r.reason !== null ? `: ${r.reason}` : ""}.`);
4764
- lines.push(`\u041F\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u044C: ${r.topup_url}`);
4765
- }
4766
- return toolSuccess(lines.join("\n"));
4767
- });
4768
- }
4769
- };
4770
- }
4771
- function brandUnpackingGetTool(client) {
4772
- return {
4773
- name: "get_brand_unpacking",
4774
- description: "\u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u0440\u0430\u0441\u043F\u0430\u043A\u043E\u0432\u043A\u0443 \u0431\u0440\u0435\u043D\u0434\u0430 \u043A\u043E\u043C\u043F\u0430\u043D\u0438\u0438 \u2014 \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u043E \u043D\u0438\u0448\u0435, \u0446\u0435\u043B\u0435\u0432\u043E\u0439 \u0430\u0443\u0434\u0438\u0442\u043E\u0440\u0438\u0438, \u043F\u0440\u043E\u0434\u0443\u043A\u0442\u0435, \u0431\u043E\u043B\u044F\u0445 \u0438 \u0442\u0435\u043C\u0430\u0445 \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430. \u042D\u0442\u043E \u043E\u0441\u043D\u043E\u0432\u0430 \u0434\u043B\u044F \u043B\u044E\u0431\u043E\u0439 \u0440\u0430\u0431\u043E\u0442\u044B \u0441 \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u043E\u043C: \u0441\u0446\u0435\u043D\u0430\u0440\u0438\u0435\u0432, \u0440\u0438\u043B\u0441\u043E\u0432, \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0439. \u0427\u0438\u0442\u0430\u0439 \u0435\u0451 \u043F\u0440\u0435\u0436\u0434\u0435, \u0447\u0435\u043C \u043F\u0440\u0435\u0434\u043B\u0430\u0433\u0430\u0442\u044C \u0438\u0434\u0435\u0438.",
4775
- inputSchema: { type: "object", properties: {}, required: [] },
4776
- readOnly: true,
4777
- async execute() {
4778
- return await guard(async () => {
4779
- const r = await client.post("/brand-unpacking-get");
4780
- if (r.content_md === null || r.content_md.trim() === "") {
4781
- return toolSuccess(
4782
- "\u0420\u0430\u0441\u043F\u0430\u043A\u043E\u0432\u043A\u0430 \u0431\u0440\u0435\u043D\u0434\u0430 \u0435\u0449\u0451 \u043D\u0435 \u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0430. \u0415\u0451 \u043D\u0443\u0436\u043D\u043E \u0441\u0434\u0435\u043B\u0430\u0442\u044C \u2014 \u0431\u0435\u0437 \u043D\u0435\u0451 \u043F\u043E\u0438\u0441\u043A \u0440\u0438\u043B\u0441\u043E\u0432 \u0438 \u0441\u043A\u043E\u0440\u0438\u043D\u0433 \u0440\u0430\u0431\u043E\u0442\u0430\u044E\u0442 \u0432\u0441\u043B\u0435\u043F\u0443\u044E. \u041C\u043E\u0436\u043D\u043E \u043F\u0440\u043E\u0432\u0435\u0441\u0442\u0438 \u0440\u0430\u0441\u043F\u0430\u043A\u043E\u0432\u043A\u0443 \u043F\u0440\u044F\u043C\u043E \u0437\u0434\u0435\u0441\u044C \u0438 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u043C save_brand_unpacking."
4783
- );
4784
- }
4785
- const header = [
4786
- r.niche !== null ? `\u041D\u0438\u0448\u0430: ${r.niche}` : null,
4787
- r.search_queries.length > 0 ? `\u041F\u043E\u0438\u0441\u043A\u043E\u0432\u044B\u0435 \u043A\u043B\u044E\u0447\u0438: ${r.search_queries.join(", ")}` : null,
4788
- r.updated_at !== null ? `\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0430: ${r.updated_at}` : null
4789
- ].filter((x) => x !== null);
4790
- return toolSuccess(`${header.join("\n")}
4791
-
4792
- ${r.content_md}`);
4793
- });
4794
- }
4795
- };
4796
- }
4797
- function brandUnpackingSaveTool(client) {
4798
- return {
4799
- name: "save_brand_unpacking",
4800
- description: "\u0421\u043E\u0445\u0440\u0430\u043D\u044F\u0435\u0442 \u0440\u0430\u0441\u043F\u0430\u043A\u043E\u0432\u043A\u0443 \u0431\u0440\u0435\u043D\u0434\u0430 \u0432 \u041D\u0430\u043F\u0430\u0440\u043D\u0438\u043A (\u043E\u0434\u043D\u0430 \u043D\u0430 \u043A\u043E\u043C\u043F\u0430\u043D\u0438\u044E, \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0438\u0441\u044B\u0432\u0430\u0435\u0442\u0441\u044F \u0446\u0435\u043B\u0438\u043A\u043E\u043C). \u0412\u044B\u0437\u044B\u0432\u0430\u0439 \u0422\u041E\u041B\u042C\u041A\u041E \u043F\u043E\u0441\u043B\u0435 \u0442\u043E\u0433\u043E, \u043A\u0430\u043A \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u043B \u0438\u0442\u043E\u0433\u043E\u0432\u044B\u0439 \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442. \u041D\u0438\u0448\u0430 \u0438 \u043F\u043E\u0438\u0441\u043A\u043E\u0432\u044B\u0435 \u043A\u043B\u044E\u0447\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044E\u0442\u0441\u044F \u043F\u043E\u0438\u0441\u043A\u043E\u043C \u0440\u0438\u043B\u0441\u043E\u0432.",
4801
- inputSchema: {
4802
- type: "object",
4803
- properties: {
4804
- content_md: {
4805
- type: "string",
4806
- description: "\u0418\u0442\u043E\u0433\u043E\u0432\u044B\u0439 \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u0440\u0430\u0441\u043F\u0430\u043A\u043E\u0432\u043A\u0438 \u0432 markdown, \u0446\u0435\u043B\u0438\u043A\u043E\u043C."
4807
- },
4808
- niche: {
4809
- type: "string",
4810
- description: "\u041D\u0438\u0448\u0430 \u043E\u0434\u043D\u043E\u0439 \u0444\u0440\u0430\u0437\u043E\u0439 \u2014 \u043E\u0440\u0438\u0435\u043D\u0442\u0438\u0440 \u0434\u043B\u044F \u043F\u043E\u0438\u0441\u043A\u0430 \u0438 \u0441\u043A\u043E\u0440\u0438\u043D\u0433\u0430 \u0440\u0438\u043B\u0441\u043E\u0432."
4811
- },
4812
- search_queries: {
4813
- type: "array",
4814
- items: { type: "string" },
4815
- description: "\u041F\u043E\u0438\u0441\u043A\u043E\u0432\u044B\u0435 \u043A\u043B\u044E\u0447\u0438 \u043F\u043E\u0434 \u0431\u043E\u043B\u0438 \u0438 \u0442\u0435\u043C\u044B \u0430\u0443\u0434\u0438\u0442\u043E\u0440\u0438\u0438, \u0434\u043E 20 \u0448\u0442\u0443\u043A."
4816
- }
4817
- },
4818
- required: ["content_md"]
4819
- },
4820
- // Перезаписывает документ компании — не readOnly и наружу видимо для команды.
4821
- readOnly: false,
4822
- async execute(input) {
4823
- return await guard(async () => {
4824
- const r = await client.post("/brand-unpacking-save", input);
4825
- const lines = [`\u0420\u0430\u0441\u043F\u0430\u043A\u043E\u0432\u043A\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0430 (${r.updated_at}).`];
4826
- if (r.warning !== null && r.warning !== "") lines.push(`\u26A0\uFE0F ${r.warning}`);
4827
- return toolSuccess(lines.join("\n"));
4828
- });
4829
- }
4830
- };
4831
- }
4832
- function reelsListTool(client) {
4833
- return {
4834
- name: "list_reels",
4835
- description: "\u0418\u0449\u0435\u0442 \u043F\u043E \u0441\u043E\u0445\u0440\u0430\u043D\u0451\u043D\u043D\u044B\u043C \u0440\u0438\u043B\u0441\u0430\u043C \u043A\u043E\u043C\u043F\u0430\u043D\u0438\u0438: \u043F\u043E \u043D\u0438\u0448\u0435, \u043F\u043B\u043E\u0449\u0430\u0434\u043A\u0435, \u0440\u0435\u0439\u0442\u0438\u043D\u0433\u0443, \u0441\u0442\u0430\u0442\u0443\u0441\u0443, \u0442\u0435\u043A\u0441\u0442\u0443. \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u041A\u0420\u0410\u0422\u041A\u0418\u0415 \u043A\u0430\u0440\u0442\u043E\u0447\u043A\u0438 \u2014 \u0434\u043B\u044F \u043F\u043E\u043B\u043D\u043E\u0433\u043E \u0440\u0430\u0437\u0431\u043E\u0440\u0430 (\u0442\u0440\u0430\u043D\u0441\u043A\u0440\u0438\u043F\u0442, \u0441\u0446\u0435\u043D\u0430\u0440\u0438\u0439, \u0440\u0430\u0441\u043A\u0430\u0434\u0440\u043E\u0432\u043A\u0430) \u0431\u0435\u0440\u0438 \u043A\u043E\u043D\u043A\u0440\u0435\u0442\u043D\u044B\u0439 \u0440\u0438\u043B\u0441 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u043C get_reel.",
4836
- inputSchema: {
4837
- type: "object",
4838
- properties: {
4839
- query: { type: "string", description: "\u0422\u0435\u043A\u0441\u0442 \u0434\u043B\u044F \u043F\u043E\u0438\u0441\u043A\u0430 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u044E, \u0445\u0443\u043A\u0443, \u0441\u0446\u0435\u043D\u0430\u0440\u0438\u044E \u0438 \u0442\u0440\u0430\u043D\u0441\u043A\u0440\u0438\u043F\u0442\u0443." },
4840
- niche: { type: "string", description: "\u041D\u0438\u0448\u0430, \u043F\u043E \u043A\u043E\u0442\u043E\u0440\u043E\u0439 \u0440\u0438\u043B\u0441 \u0431\u044B\u043B \u043D\u0430\u0439\u0434\u0435\u043D." },
4841
- platform: { type: "string", description: "\u041F\u043B\u043E\u0449\u0430\u0434\u043A\u0430: instagram, tiktok, youtube." },
4842
- score_min: { type: "number", description: "\u041C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439 \u0440\u0435\u0439\u0442\u0438\u043D\u0433 0-100. \u0425\u043E\u0440\u043E\u0448\u0438\u0435 \u0440\u0435\u0444\u0435\u0440\u0435\u043D\u0441\u044B \u2014 \u043E\u0431\u044B\u0447\u043D\u043E \u043E\u0442 70." },
4843
- status: { type: "string", description: "\u0421\u0442\u0430\u0442\u0443\u0441 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438: found, prepared, scored, failed." },
4844
- favorite: { type: "boolean", description: "true \u2014 \u0442\u043E\u043B\u044C\u043A\u043E \u0438\u0437\u0431\u0440\u0430\u043D\u043D\u044B\u0435." },
4845
- limit: { type: "number", description: `\u0421\u043A\u043E\u043B\u044C\u043A\u043E \u0432\u0435\u0440\u043D\u0443\u0442\u044C, \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E ${DEFAULT_REELS_LIMIT}, \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C 200.` },
4846
- offset: { type: "number", description: "\u0421\u043C\u0435\u0449\u0435\u043D\u0438\u0435 \u0434\u043B\u044F \u043B\u0438\u0441\u0442\u0430\u043D\u0438\u044F." }
4847
- },
4848
- required: []
4849
- },
4850
- readOnly: true,
4851
- async execute(input) {
4852
- return await guard(async () => {
4853
- const body = { ...input, limit: input["limit"] ?? DEFAULT_REELS_LIMIT };
4854
- const r = await client.post("/reels-list", body);
4855
- if (r.reels.length === 0) {
4856
- return toolSuccess("\u041F\u043E\u0434 \u044D\u0442\u0438 \u0443\u0441\u043B\u043E\u0432\u0438\u044F \u0440\u0438\u043B\u0441\u043E\u0432 \u043D\u0435\u0442. \u041F\u043E\u043F\u0440\u043E\u0431\u0443\u0439 \u043E\u0441\u043B\u0430\u0431\u0438\u0442\u044C \u0444\u0438\u043B\u044C\u0442\u0440\u044B \u0438\u043B\u0438 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u043F\u043E\u0438\u0441\u043A.");
4857
- }
4858
- const shown = r.reels.map(formatReelBrief).join("\n\n");
4859
- const tail = r.total > r.reels.length ? `
4860
-
4861
- \u041F\u043E\u043A\u0430\u0437\u0430\u043D\u043E ${r.reels.length} \u0438\u0437 ${r.total}. \u0414\u0430\u043B\u044C\u0448\u0435 \u2014 offset.` : `
4862
-
4863
- \u0412\u0441\u0435\u0433\u043E: ${r.total}.`;
4864
- return toolSuccess(shown + tail);
4865
- });
4866
- }
4867
- };
4868
- }
4869
- function reelGetTool(client) {
4870
- return {
4871
- name: "get_reel",
4872
- description: "\u041F\u043E\u043B\u043D\u044B\u0439 \u0440\u0430\u0437\u0431\u043E\u0440 \u043E\u0434\u043D\u043E\u0433\u043E \u0440\u0438\u043B\u0441\u0430: \u0442\u0440\u0430\u043D\u0441\u043A\u0440\u0438\u043F\u0442, \u0445\u0443\u043A, \u0430\u0434\u0430\u043F\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u0446\u0435\u043D\u0430\u0440\u0438\u0439, \u043E\u0446\u0435\u043D\u043A\u0430 \u043F\u043E \u043A\u0440\u0438\u0442\u0435\u0440\u0438\u044F\u043C, \u043A\u0430\u0434\u0440\u044B \u0440\u0430\u0441\u043A\u0430\u0434\u0440\u043E\u0432\u043A\u0438, \u043C\u0435\u0442\u0440\u0438\u043A\u0438. \u0418\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440 \u0431\u0435\u0440\u0451\u0442\u0441\u044F \u0438\u0437 list_reels.",
4873
- inputSchema: {
4874
- type: "object",
4875
- properties: {
4876
- reel_id: { type: "string", description: "UUID \u0440\u0438\u043B\u0441\u0430 \u0438\u0437 list_reels." }
4877
- },
4878
- required: ["reel_id"]
4879
- },
4880
- readOnly: true,
4881
- async execute(input) {
4882
- return await guard(async () => {
4883
- const r = await client.post("/reel-get", input);
4884
- return toolSuccess(formatReelFull(r.reel));
4885
- });
4886
- }
4887
- };
4888
- }
4889
- function formatReelBrief(r) {
4890
- const head = [
4891
- r.score !== null && r.score !== void 0 ? `[${r.score}]` : "[\u2014]",
4892
- r.author !== null && r.author !== void 0 ? `@${r.author}` : r.platform,
4893
- `${compactNumber(r.views)} \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u043E\u0432`,
4894
- r.verdict !== null && r.verdict !== void 0 ? r.verdict : null,
4895
- r.favorite ? "\u2605" : null
4896
- ].filter((x) => x !== null).join(" \xB7 ");
4897
- const body = [
4898
- r.hook !== null && r.hook !== void 0 ? `\u0425\u0443\u043A: ${truncate2(r.hook, 160)}` : null,
4899
- r.summary !== null && r.summary !== void 0 ? truncate2(r.summary, 200) : null,
4900
- `id: ${r.id}`
4901
- ].filter((x) => x !== null).join("\n");
4902
- return `${head}
4903
- ${body}`;
4904
- }
4905
- function formatReelFull(r) {
4906
- const parts = [];
4907
- parts.push([
4908
- r.author !== null && r.author !== void 0 ? `\u0410\u0432\u0442\u043E\u0440: @${r.author}` : null,
4909
- `\u041F\u043B\u043E\u0449\u0430\u0434\u043A\u0430: ${r.platform}`,
4910
- `\u0421\u0441\u044B\u043B\u043A\u0430: ${r.reel_url}`,
4911
- r.niche !== null && r.niche !== void 0 ? `\u041D\u0438\u0448\u0430: ${r.niche}` : null,
4912
- r.taken_at !== null && r.taken_at !== void 0 ? `\u041E\u043F\u0443\u0431\u043B\u0438\u043A\u043E\u0432\u0430\u043D: ${r.taken_at}` : null,
4913
- r.duration_sec !== null && r.duration_sec !== void 0 ? `\u0414\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C: ${r.duration_sec} \u0441` : null
4914
- ].filter((x) => x !== null).join("\n"));
4915
- parts.push(
4916
- `\u041C\u0435\u0442\u0440\u0438\u043A\u0438: ${compactNumber(r.views)} \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u043E\u0432, ${compactNumber(r.like_count)} \u043B\u0430\u0439\u043A\u043E\u0432, ${compactNumber(r.comment_count)} \u043A\u043E\u043C\u043C\u0435\u043D\u0442\u0430\u0440\u0438\u0435\u0432` + (r.shares !== null && r.shares !== void 0 ? `, ${compactNumber(r.shares)} \u0440\u0435\u043F\u043E\u0441\u0442\u043E\u0432` : "")
4917
- );
4918
- if (r.score !== null && r.score !== void 0) {
4919
- parts.push(`\u041E\u0446\u0435\u043D\u043A\u0430: ${r.score}/100${r.verdict !== null && r.verdict !== void 0 ? ` \u2014 ${r.verdict}` : ""}`);
4920
- } else {
4921
- parts.push(`\u0421\u0442\u0430\u0442\u0443\u0441 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438: ${r.status} (\u043E\u0446\u0435\u043D\u043A\u0438 \u043F\u043E\u043A\u0430 \u043D\u0435\u0442)`);
4922
- }
4923
- pushIf(parts, "\u0425\u0443\u043A", r.hook);
4924
- pushIf(parts, "\u041E \u0447\u0451\u043C", r.summary);
4925
- pushIf(parts, "\u041F\u043E\u0447\u0435\u043C\u0443 \u0437\u0430\u0432\u0438\u0440\u0443\u0441\u0438\u043B\u0441\u044F", r.why_viral);
4926
- pushIf(parts, "\u0427\u0435\u043C \u043F\u043E\u0434\u0445\u043E\u0434\u0438\u0442", r.why_fits);
4927
- pushIf(parts, "\u0421\u0446\u0435\u043D\u0430\u0440\u0438\u0439 \u043F\u043E\u0434 \u0432\u0430\u0448 \u043A\u0430\u043D\u0430\u043B", r.script);
4928
- pushIf(parts, "\u0422\u0440\u0430\u043D\u0441\u043A\u0440\u0438\u043F\u0442", r.transcript_ru ?? r.transcript);
4929
- if (r.hashtags !== null && r.hashtags !== void 0 && r.hashtags.length > 0) {
4930
- parts.push(`\u0425\u0435\u0448\u0442\u0435\u0433\u0438: ${r.hashtags.join(" ")}`);
4931
- }
4932
- if (r.frames !== null && r.frames !== void 0 && r.frames.length > 0) {
4933
- parts.push(`\u041A\u0430\u0434\u0440\u044B \u0440\u0430\u0441\u043A\u0430\u0434\u0440\u043E\u0432\u043A\u0438 (${r.frames.length}):
4934
- ${r.frames.join("\n")}`);
4935
- }
4936
- return parts.join("\n\n");
4937
- }
4938
- function pushIf(parts, label, value) {
4939
- if (value !== null && value !== void 0 && value.trim() !== "") parts.push(`${label}: ${value}`);
4940
- }
4941
- async function guard(fn) {
4942
- try {
4943
- return await fn();
4944
- } catch (err) {
4945
- if (err instanceof NaparnikInsufficientBalanceError) {
4946
- const d = err.details;
4947
- const what = d.limit === "token_daily" ? "\u0418\u0441\u0447\u0435\u0440\u043F\u0430\u043D \u0434\u043D\u0435\u0432\u043D\u043E\u0439 \u043B\u0438\u043C\u0438\u0442 \u0442\u0440\u0430\u0442 \u043F\u043E \u044D\u0442\u043E\u043C\u0443 \u043A\u043B\u044E\u0447\u0443" : "\u041D\u0435\u0434\u043E\u0441\u0442\u0430\u0442\u043E\u0447\u043D\u043E \u0441\u0440\u0435\u0434\u0441\u0442\u0432 \u043D\u0430 \u0431\u0430\u043B\u0430\u043D\u0441\u0435 \u043A\u043E\u043C\u043F\u0430\u043D\u0438\u0438";
4948
- return toolError(
4949
- `${what}. \u041D\u0443\u0436\u043D\u043E ${money(d.requiredRub)} \u20BD, \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E ${money(d.balanceRub)} \u20BD.
4950
- ` + (d.limit === "token_daily" ? `\u041B\u0438\u043C\u0438\u0442 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u0441\u044F \u0437\u0430\u0432\u0442\u0440\u0430, \u043B\u0438\u0431\u043E \u043F\u043E\u0434\u043D\u0438\u043C\u0438\u0442\u0435 \u0435\u0433\u043E: ${d.actionUrl}` : `\u041F\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u0431\u0430\u043B\u0430\u043D\u0441: ${d.actionUrl}`)
4951
- );
4952
- }
4953
- if (err instanceof NaparnikScopeError) {
4954
- return toolError(`${err.message} \u041F\u0440\u0430\u0432\u0430 \u043A\u043B\u044E\u0447\u0430 \u043C\u0435\u043D\u044F\u044E\u0442\u0441\u044F \u043F\u0440\u0438 \u0432\u044B\u043F\u0443\u0441\u043A\u0435 \u043D\u043E\u0432\u043E\u0433\u043E \u0432 \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u2192 API-\u043A\u043B\u044E\u0447\u0438.`);
4955
- }
4956
- if (err instanceof NaparnikAuthError) {
4957
- return toolError(err.message);
4958
- }
4959
- if (err instanceof NaparnikError) {
4960
- return toolError(err.message);
4961
- }
4962
- return toolError(`\u041D\u0435\u043F\u0440\u0435\u0434\u0432\u0438\u0434\u0435\u043D\u043D\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430: ${err instanceof Error ? err.message : String(err)}`);
4963
- }
4964
- }
4965
- function money(value) {
4966
- return value.toFixed(2).replace(/\.00$/, "");
4967
- }
4968
- function compactNumber(value) {
4969
- if (value >= 1e6) return `${(value / 1e6).toFixed(1)} \u043C\u043B\u043D`;
4970
- if (value >= 1e3) return `${(value / 1e3).toFixed(1)} \u0442\u044B\u0441`;
4971
- return String(value);
4972
- }
4973
- function truncate2(text, limit) {
4974
- return text.length > limit ? `${text.slice(0, limit)}\u2026` : text;
4975
- }
4976
- function billingModeRu(mode) {
4977
- switch (mode) {
4978
- case "trial":
4979
- return "\u043F\u0440\u043E\u0431\u043D\u044B\u0439 \u043F\u0435\u0440\u0438\u043E\u0434";
4980
- case "subscription":
4981
- return "\u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0430 (\u0431\u0435\u0437 \u0441\u043F\u0438\u0441\u0430\u043D\u0438\u0439)";
4982
- case "standard":
4983
- return "\u043E\u043F\u043B\u0430\u0442\u0430 \u043F\u043E \u0440\u0430\u0441\u0445\u043E\u0434\u0443";
4984
- default:
4985
- return mode;
4986
- }
4987
- }
4988
-
4989
- export { McpServer, NaparnikApiClient, NaparnikAuthError, NaparnikClientError, NaparnikConfigError, NaparnikError, NaparnikInsufficientBalanceError, NaparnikScopeError, NaparnikServerError, NaparnikTimeoutError, StdioServerTransport, createNaparnikTools, loadConfig };