sqlite-zod-orm 3.0.0 → 3.2.1

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