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