@hasna/search 0.0.2

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