@kamrankhan027/probe-ai 1.0.0

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