@debugkit/dashboard 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/.env.example +30 -0
  2. package/dist/client/assets/_authed-BDx4Txp7.js +7 -0
  3. package/dist/client/assets/_authed-D6P9RBN1.js +1 -0
  4. package/dist/client/assets/charts-Covhtva2.js +55 -0
  5. package/dist/client/assets/index-BKQXehfa.js +12 -0
  6. package/dist/client/assets/issues._fingerprint-DtAqk0rC.js +1 -0
  7. package/dist/client/assets/login-Da8b3hjR.js +1 -0
  8. package/dist/client/assets/styles-CZZRuG1z.css +2 -0
  9. package/dist/client/assets/ui-DnKidKVi.js +1 -0
  10. package/dist/server/assets/_authed-BjmBAX3l.js +482 -0
  11. package/dist/server/assets/_authed-x9Ku8dyL.js +40 -0
  12. package/dist/server/assets/_tanstack-start-manifest_v-CY7PP5UB.js +40 -0
  13. package/dist/server/assets/charts-CNlV7Pga.js +221 -0
  14. package/dist/server/assets/demo-DTdlXNgj.js +333 -0
  15. package/dist/server/assets/dynamodb-DejcakaF.js +187 -0
  16. package/dist/server/assets/empty-plugin-adapters-BsRz-CQL.js +4 -0
  17. package/dist/server/assets/firestore-BH-gx9no.js +112 -0
  18. package/dist/server/assets/fns-CgB12FUN.js +31 -0
  19. package/dist/server/assets/fns-Yg8sT1Cb.js +87 -0
  20. package/dist/server/assets/issues._fingerprint-C2EdByPH.js +255 -0
  21. package/dist/server/assets/login-BMGNYcxB.js +107 -0
  22. package/dist/server/assets/memory-4DwW5cTO.js +59 -0
  23. package/dist/server/assets/queries-DIVV-5j6.js +4274 -0
  24. package/dist/server/assets/rollups-JXbazRNh.js +22 -0
  25. package/dist/server/assets/router-D2L7-BwF.js +222 -0
  26. package/dist/server/assets/src-D5jyi_C4.js +235 -0
  27. package/dist/server/assets/start-t09PGpZL.js +3 -0
  28. package/dist/server/assets/ui-Lv-KcOoP.js +131 -0
  29. package/dist/server/server.js +7825 -0
  30. package/package.json +52 -3
  31. package/scripts/hash-password.mjs +17 -0
  32. package/server.mjs +50 -0
  33. package/README.md +0 -3
@@ -0,0 +1,4274 @@
1
+ import { a as getCookie, i as deleteCookie, o as getRequestHeader, s as setCookie } from "../server.js";
2
+ import { createHmac, randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
3
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
4
+ var util;
5
+ (function(util) {
6
+ util.assertEqual = (_) => {};
7
+ function assertIs(_arg) {}
8
+ util.assertIs = assertIs;
9
+ function assertNever(_x) {
10
+ throw new Error();
11
+ }
12
+ util.assertNever = assertNever;
13
+ util.arrayToEnum = (items) => {
14
+ const obj = {};
15
+ for (const item of items) obj[item] = item;
16
+ return obj;
17
+ };
18
+ util.getValidEnumValues = (obj) => {
19
+ const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
20
+ const filtered = {};
21
+ for (const k of validKeys) filtered[k] = obj[k];
22
+ return util.objectValues(filtered);
23
+ };
24
+ util.objectValues = (obj) => {
25
+ return util.objectKeys(obj).map(function(e) {
26
+ return obj[e];
27
+ });
28
+ };
29
+ util.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
30
+ const keys = [];
31
+ for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
32
+ return keys;
33
+ };
34
+ util.find = (arr, checker) => {
35
+ for (const item of arr) if (checker(item)) return item;
36
+ };
37
+ util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
38
+ function joinValues(array, separator = " | ") {
39
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
40
+ }
41
+ util.joinValues = joinValues;
42
+ util.jsonStringifyReplacer = (_, value) => {
43
+ if (typeof value === "bigint") return value.toString();
44
+ return value;
45
+ };
46
+ })(util || (util = {}));
47
+ var objectUtil;
48
+ (function(objectUtil) {
49
+ objectUtil.mergeShapes = (first, second) => {
50
+ return {
51
+ ...first,
52
+ ...second
53
+ };
54
+ };
55
+ })(objectUtil || (objectUtil = {}));
56
+ var ZodParsedType = util.arrayToEnum([
57
+ "string",
58
+ "nan",
59
+ "number",
60
+ "integer",
61
+ "float",
62
+ "boolean",
63
+ "date",
64
+ "bigint",
65
+ "symbol",
66
+ "function",
67
+ "undefined",
68
+ "null",
69
+ "array",
70
+ "object",
71
+ "unknown",
72
+ "promise",
73
+ "void",
74
+ "never",
75
+ "map",
76
+ "set"
77
+ ]);
78
+ var getParsedType = (data) => {
79
+ switch (typeof data) {
80
+ case "undefined": return ZodParsedType.undefined;
81
+ case "string": return ZodParsedType.string;
82
+ case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
83
+ case "boolean": return ZodParsedType.boolean;
84
+ case "function": return ZodParsedType.function;
85
+ case "bigint": return ZodParsedType.bigint;
86
+ case "symbol": return ZodParsedType.symbol;
87
+ case "object":
88
+ if (Array.isArray(data)) return ZodParsedType.array;
89
+ if (data === null) return ZodParsedType.null;
90
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") return ZodParsedType.promise;
91
+ if (typeof Map !== "undefined" && data instanceof Map) return ZodParsedType.map;
92
+ if (typeof Set !== "undefined" && data instanceof Set) return ZodParsedType.set;
93
+ if (typeof Date !== "undefined" && data instanceof Date) return ZodParsedType.date;
94
+ return ZodParsedType.object;
95
+ default: return ZodParsedType.unknown;
96
+ }
97
+ };
98
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
99
+ var ZodIssueCode = util.arrayToEnum([
100
+ "invalid_type",
101
+ "invalid_literal",
102
+ "custom",
103
+ "invalid_union",
104
+ "invalid_union_discriminator",
105
+ "invalid_enum_value",
106
+ "unrecognized_keys",
107
+ "invalid_arguments",
108
+ "invalid_return_type",
109
+ "invalid_date",
110
+ "invalid_string",
111
+ "too_small",
112
+ "too_big",
113
+ "invalid_intersection_types",
114
+ "not_multiple_of",
115
+ "not_finite"
116
+ ]);
117
+ var ZodError = class ZodError extends Error {
118
+ get errors() {
119
+ return this.issues;
120
+ }
121
+ constructor(issues) {
122
+ super();
123
+ this.issues = [];
124
+ this.addIssue = (sub) => {
125
+ this.issues = [...this.issues, sub];
126
+ };
127
+ this.addIssues = (subs = []) => {
128
+ this.issues = [...this.issues, ...subs];
129
+ };
130
+ const actualProto = new.target.prototype;
131
+ if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
132
+ else this.__proto__ = actualProto;
133
+ this.name = "ZodError";
134
+ this.issues = issues;
135
+ }
136
+ format(_mapper) {
137
+ const mapper = _mapper || function(issue) {
138
+ return issue.message;
139
+ };
140
+ const fieldErrors = { _errors: [] };
141
+ const processError = (error) => {
142
+ for (const issue of error.issues) if (issue.code === "invalid_union") issue.unionErrors.map(processError);
143
+ else if (issue.code === "invalid_return_type") processError(issue.returnTypeError);
144
+ else if (issue.code === "invalid_arguments") processError(issue.argumentsError);
145
+ else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
146
+ else {
147
+ let curr = fieldErrors;
148
+ let i = 0;
149
+ while (i < issue.path.length) {
150
+ const el = issue.path[i];
151
+ if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
152
+ else {
153
+ curr[el] = curr[el] || { _errors: [] };
154
+ curr[el]._errors.push(mapper(issue));
155
+ }
156
+ curr = curr[el];
157
+ i++;
158
+ }
159
+ }
160
+ };
161
+ processError(this);
162
+ return fieldErrors;
163
+ }
164
+ static assert(value) {
165
+ if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
166
+ }
167
+ toString() {
168
+ return this.message;
169
+ }
170
+ get message() {
171
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
172
+ }
173
+ get isEmpty() {
174
+ return this.issues.length === 0;
175
+ }
176
+ flatten(mapper = (issue) => issue.message) {
177
+ const fieldErrors = {};
178
+ const formErrors = [];
179
+ for (const sub of this.issues) if (sub.path.length > 0) {
180
+ const firstEl = sub.path[0];
181
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
182
+ fieldErrors[firstEl].push(mapper(sub));
183
+ } else formErrors.push(mapper(sub));
184
+ return {
185
+ formErrors,
186
+ fieldErrors
187
+ };
188
+ }
189
+ get formErrors() {
190
+ return this.flatten();
191
+ }
192
+ };
193
+ ZodError.create = (issues) => {
194
+ return new ZodError(issues);
195
+ };
196
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
197
+ var errorMap = (issue, _ctx) => {
198
+ let message;
199
+ switch (issue.code) {
200
+ case ZodIssueCode.invalid_type:
201
+ if (issue.received === ZodParsedType.undefined) message = "Required";
202
+ else message = `Expected ${issue.expected}, received ${issue.received}`;
203
+ break;
204
+ case ZodIssueCode.invalid_literal:
205
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
206
+ break;
207
+ case ZodIssueCode.unrecognized_keys:
208
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
209
+ break;
210
+ case ZodIssueCode.invalid_union:
211
+ message = `Invalid input`;
212
+ break;
213
+ case ZodIssueCode.invalid_union_discriminator:
214
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
215
+ break;
216
+ case ZodIssueCode.invalid_enum_value:
217
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
218
+ break;
219
+ case ZodIssueCode.invalid_arguments:
220
+ message = `Invalid function arguments`;
221
+ break;
222
+ case ZodIssueCode.invalid_return_type:
223
+ message = `Invalid function return type`;
224
+ break;
225
+ case ZodIssueCode.invalid_date:
226
+ message = `Invalid date`;
227
+ break;
228
+ case ZodIssueCode.invalid_string:
229
+ if (typeof issue.validation === "object") {
230
+ if ("includes" in issue.validation) {
231
+ message = `Invalid input: must include "${issue.validation.includes}"`;
232
+ if (typeof issue.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
233
+ } else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`;
234
+ else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`;
235
+ else util.assertNever(issue.validation);
236
+ } else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
237
+ else message = "Invalid";
238
+ break;
239
+ case ZodIssueCode.too_small:
240
+ if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
241
+ else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
242
+ else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
243
+ else if (issue.type === "bigint") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
244
+ else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
245
+ else message = "Invalid input";
246
+ break;
247
+ case ZodIssueCode.too_big:
248
+ if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
249
+ else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
250
+ else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
251
+ else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
252
+ else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
253
+ else message = "Invalid input";
254
+ break;
255
+ case ZodIssueCode.custom:
256
+ message = `Invalid input`;
257
+ break;
258
+ case ZodIssueCode.invalid_intersection_types:
259
+ message = `Intersection results could not be merged`;
260
+ break;
261
+ case ZodIssueCode.not_multiple_of:
262
+ message = `Number must be a multiple of ${issue.multipleOf}`;
263
+ break;
264
+ case ZodIssueCode.not_finite:
265
+ message = "Number must be finite";
266
+ break;
267
+ default:
268
+ message = _ctx.defaultError;
269
+ util.assertNever(issue);
270
+ }
271
+ return { message };
272
+ };
273
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
274
+ var overrideErrorMap = errorMap;
275
+ function getErrorMap() {
276
+ return overrideErrorMap;
277
+ }
278
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
279
+ var makeIssue = (params) => {
280
+ const { data, path, errorMaps, issueData } = params;
281
+ const fullPath = [...path, ...issueData.path || []];
282
+ const fullIssue = {
283
+ ...issueData,
284
+ path: fullPath
285
+ };
286
+ if (issueData.message !== void 0) return {
287
+ ...issueData,
288
+ path: fullPath,
289
+ message: issueData.message
290
+ };
291
+ let errorMessage = "";
292
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
293
+ for (const map of maps) errorMessage = map(fullIssue, {
294
+ data,
295
+ defaultError: errorMessage
296
+ }).message;
297
+ return {
298
+ ...issueData,
299
+ path: fullPath,
300
+ message: errorMessage
301
+ };
302
+ };
303
+ function addIssueToContext(ctx, issueData) {
304
+ const overrideMap = getErrorMap();
305
+ const issue = makeIssue({
306
+ issueData,
307
+ data: ctx.data,
308
+ path: ctx.path,
309
+ errorMaps: [
310
+ ctx.common.contextualErrorMap,
311
+ ctx.schemaErrorMap,
312
+ overrideMap,
313
+ overrideMap === errorMap ? void 0 : errorMap
314
+ ].filter((x) => !!x)
315
+ });
316
+ ctx.common.issues.push(issue);
317
+ }
318
+ var ParseStatus = class ParseStatus {
319
+ constructor() {
320
+ this.value = "valid";
321
+ }
322
+ dirty() {
323
+ if (this.value === "valid") this.value = "dirty";
324
+ }
325
+ abort() {
326
+ if (this.value !== "aborted") this.value = "aborted";
327
+ }
328
+ static mergeArray(status, results) {
329
+ const arrayValue = [];
330
+ for (const s of results) {
331
+ if (s.status === "aborted") return INVALID;
332
+ if (s.status === "dirty") status.dirty();
333
+ arrayValue.push(s.value);
334
+ }
335
+ return {
336
+ status: status.value,
337
+ value: arrayValue
338
+ };
339
+ }
340
+ static async mergeObjectAsync(status, pairs) {
341
+ const syncPairs = [];
342
+ for (const pair of pairs) {
343
+ const key = await pair.key;
344
+ const value = await pair.value;
345
+ syncPairs.push({
346
+ key,
347
+ value
348
+ });
349
+ }
350
+ return ParseStatus.mergeObjectSync(status, syncPairs);
351
+ }
352
+ static mergeObjectSync(status, pairs) {
353
+ const finalObject = {};
354
+ for (const pair of pairs) {
355
+ const { key, value } = pair;
356
+ if (key.status === "aborted") return INVALID;
357
+ if (value.status === "aborted") return INVALID;
358
+ if (key.status === "dirty") status.dirty();
359
+ if (value.status === "dirty") status.dirty();
360
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
361
+ }
362
+ return {
363
+ status: status.value,
364
+ value: finalObject
365
+ };
366
+ }
367
+ };
368
+ var INVALID = Object.freeze({ status: "aborted" });
369
+ var DIRTY = (value) => ({
370
+ status: "dirty",
371
+ value
372
+ });
373
+ var OK = (value) => ({
374
+ status: "valid",
375
+ value
376
+ });
377
+ var isAborted = (x) => x.status === "aborted";
378
+ var isDirty = (x) => x.status === "dirty";
379
+ var isValid = (x) => x.status === "valid";
380
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
381
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
382
+ var errorUtil;
383
+ (function(errorUtil) {
384
+ errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
385
+ errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
386
+ })(errorUtil || (errorUtil = {}));
387
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
388
+ var ParseInputLazyPath = class {
389
+ constructor(parent, value, path, key) {
390
+ this._cachedPath = [];
391
+ this.parent = parent;
392
+ this.data = value;
393
+ this._path = path;
394
+ this._key = key;
395
+ }
396
+ get path() {
397
+ if (!this._cachedPath.length) {
398
+ if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
399
+ else this._cachedPath.push(...this._path, this._key);
400
+ }
401
+ return this._cachedPath;
402
+ }
403
+ };
404
+ var handleResult = (ctx, result) => {
405
+ if (isValid(result)) return {
406
+ success: true,
407
+ data: result.value
408
+ };
409
+ else {
410
+ if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
411
+ return {
412
+ success: false,
413
+ get error() {
414
+ if (this._error) return this._error;
415
+ const error = new ZodError(ctx.common.issues);
416
+ this._error = error;
417
+ return this._error;
418
+ }
419
+ };
420
+ }
421
+ };
422
+ function processCreateParams(params) {
423
+ if (!params) return {};
424
+ const { errorMap, invalid_type_error, required_error, description } = params;
425
+ if (errorMap && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
426
+ if (errorMap) return {
427
+ errorMap,
428
+ description
429
+ };
430
+ const customMap = (iss, ctx) => {
431
+ const { message } = params;
432
+ if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError };
433
+ if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError };
434
+ if (iss.code !== "invalid_type") return { message: ctx.defaultError };
435
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
436
+ };
437
+ return {
438
+ errorMap: customMap,
439
+ description
440
+ };
441
+ }
442
+ var ZodType = class {
443
+ get description() {
444
+ return this._def.description;
445
+ }
446
+ _getType(input) {
447
+ return getParsedType(input.data);
448
+ }
449
+ _getOrReturnCtx(input, ctx) {
450
+ return ctx || {
451
+ common: input.parent.common,
452
+ data: input.data,
453
+ parsedType: getParsedType(input.data),
454
+ schemaErrorMap: this._def.errorMap,
455
+ path: input.path,
456
+ parent: input.parent
457
+ };
458
+ }
459
+ _processInputParams(input) {
460
+ return {
461
+ status: new ParseStatus(),
462
+ ctx: {
463
+ common: input.parent.common,
464
+ data: input.data,
465
+ parsedType: getParsedType(input.data),
466
+ schemaErrorMap: this._def.errorMap,
467
+ path: input.path,
468
+ parent: input.parent
469
+ }
470
+ };
471
+ }
472
+ _parseSync(input) {
473
+ const result = this._parse(input);
474
+ if (isAsync(result)) throw new Error("Synchronous parse encountered promise.");
475
+ return result;
476
+ }
477
+ _parseAsync(input) {
478
+ const result = this._parse(input);
479
+ return Promise.resolve(result);
480
+ }
481
+ parse(data, params) {
482
+ const result = this.safeParse(data, params);
483
+ if (result.success) return result.data;
484
+ throw result.error;
485
+ }
486
+ safeParse(data, params) {
487
+ const ctx = {
488
+ common: {
489
+ issues: [],
490
+ async: params?.async ?? false,
491
+ contextualErrorMap: params?.errorMap
492
+ },
493
+ path: params?.path || [],
494
+ schemaErrorMap: this._def.errorMap,
495
+ parent: null,
496
+ data,
497
+ parsedType: getParsedType(data)
498
+ };
499
+ return handleResult(ctx, this._parseSync({
500
+ data,
501
+ path: ctx.path,
502
+ parent: ctx
503
+ }));
504
+ }
505
+ "~validate"(data) {
506
+ const ctx = {
507
+ common: {
508
+ issues: [],
509
+ async: !!this["~standard"].async
510
+ },
511
+ path: [],
512
+ schemaErrorMap: this._def.errorMap,
513
+ parent: null,
514
+ data,
515
+ parsedType: getParsedType(data)
516
+ };
517
+ if (!this["~standard"].async) try {
518
+ const result = this._parseSync({
519
+ data,
520
+ path: [],
521
+ parent: ctx
522
+ });
523
+ return isValid(result) ? { value: result.value } : { issues: ctx.common.issues };
524
+ } catch (err) {
525
+ if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
526
+ ctx.common = {
527
+ issues: [],
528
+ async: true
529
+ };
530
+ }
531
+ return this._parseAsync({
532
+ data,
533
+ path: [],
534
+ parent: ctx
535
+ }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues });
536
+ }
537
+ async parseAsync(data, params) {
538
+ const result = await this.safeParseAsync(data, params);
539
+ if (result.success) return result.data;
540
+ throw result.error;
541
+ }
542
+ async safeParseAsync(data, params) {
543
+ const ctx = {
544
+ common: {
545
+ issues: [],
546
+ contextualErrorMap: params?.errorMap,
547
+ async: true
548
+ },
549
+ path: params?.path || [],
550
+ schemaErrorMap: this._def.errorMap,
551
+ parent: null,
552
+ data,
553
+ parsedType: getParsedType(data)
554
+ };
555
+ const maybeAsyncResult = this._parse({
556
+ data,
557
+ path: ctx.path,
558
+ parent: ctx
559
+ });
560
+ return handleResult(ctx, await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)));
561
+ }
562
+ refine(check, message) {
563
+ const getIssueProperties = (val) => {
564
+ if (typeof message === "string" || typeof message === "undefined") return { message };
565
+ else if (typeof message === "function") return message(val);
566
+ else return message;
567
+ };
568
+ return this._refinement((val, ctx) => {
569
+ const result = check(val);
570
+ const setError = () => ctx.addIssue({
571
+ code: ZodIssueCode.custom,
572
+ ...getIssueProperties(val)
573
+ });
574
+ if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data) => {
575
+ if (!data) {
576
+ setError();
577
+ return false;
578
+ } else return true;
579
+ });
580
+ if (!result) {
581
+ setError();
582
+ return false;
583
+ } else return true;
584
+ });
585
+ }
586
+ refinement(check, refinementData) {
587
+ return this._refinement((val, ctx) => {
588
+ if (!check(val)) {
589
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
590
+ return false;
591
+ } else return true;
592
+ });
593
+ }
594
+ _refinement(refinement) {
595
+ return new ZodEffects({
596
+ schema: this,
597
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
598
+ effect: {
599
+ type: "refinement",
600
+ refinement
601
+ }
602
+ });
603
+ }
604
+ superRefine(refinement) {
605
+ return this._refinement(refinement);
606
+ }
607
+ constructor(def) {
608
+ /** Alias of safeParseAsync */
609
+ this.spa = this.safeParseAsync;
610
+ this._def = def;
611
+ this.parse = this.parse.bind(this);
612
+ this.safeParse = this.safeParse.bind(this);
613
+ this.parseAsync = this.parseAsync.bind(this);
614
+ this.safeParseAsync = this.safeParseAsync.bind(this);
615
+ this.spa = this.spa.bind(this);
616
+ this.refine = this.refine.bind(this);
617
+ this.refinement = this.refinement.bind(this);
618
+ this.superRefine = this.superRefine.bind(this);
619
+ this.optional = this.optional.bind(this);
620
+ this.nullable = this.nullable.bind(this);
621
+ this.nullish = this.nullish.bind(this);
622
+ this.array = this.array.bind(this);
623
+ this.promise = this.promise.bind(this);
624
+ this.or = this.or.bind(this);
625
+ this.and = this.and.bind(this);
626
+ this.transform = this.transform.bind(this);
627
+ this.brand = this.brand.bind(this);
628
+ this.default = this.default.bind(this);
629
+ this.catch = this.catch.bind(this);
630
+ this.describe = this.describe.bind(this);
631
+ this.pipe = this.pipe.bind(this);
632
+ this.readonly = this.readonly.bind(this);
633
+ this.isNullable = this.isNullable.bind(this);
634
+ this.isOptional = this.isOptional.bind(this);
635
+ this["~standard"] = {
636
+ version: 1,
637
+ vendor: "zod",
638
+ validate: (data) => this["~validate"](data)
639
+ };
640
+ }
641
+ optional() {
642
+ return ZodOptional.create(this, this._def);
643
+ }
644
+ nullable() {
645
+ return ZodNullable.create(this, this._def);
646
+ }
647
+ nullish() {
648
+ return this.nullable().optional();
649
+ }
650
+ array() {
651
+ return ZodArray.create(this);
652
+ }
653
+ promise() {
654
+ return ZodPromise.create(this, this._def);
655
+ }
656
+ or(option) {
657
+ return ZodUnion.create([this, option], this._def);
658
+ }
659
+ and(incoming) {
660
+ return ZodIntersection.create(this, incoming, this._def);
661
+ }
662
+ transform(transform) {
663
+ return new ZodEffects({
664
+ ...processCreateParams(this._def),
665
+ schema: this,
666
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
667
+ effect: {
668
+ type: "transform",
669
+ transform
670
+ }
671
+ });
672
+ }
673
+ default(def) {
674
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
675
+ return new ZodDefault({
676
+ ...processCreateParams(this._def),
677
+ innerType: this,
678
+ defaultValue: defaultValueFunc,
679
+ typeName: ZodFirstPartyTypeKind.ZodDefault
680
+ });
681
+ }
682
+ brand() {
683
+ return new ZodBranded({
684
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
685
+ type: this,
686
+ ...processCreateParams(this._def)
687
+ });
688
+ }
689
+ catch(def) {
690
+ const catchValueFunc = typeof def === "function" ? def : () => def;
691
+ return new ZodCatch({
692
+ ...processCreateParams(this._def),
693
+ innerType: this,
694
+ catchValue: catchValueFunc,
695
+ typeName: ZodFirstPartyTypeKind.ZodCatch
696
+ });
697
+ }
698
+ describe(description) {
699
+ const This = this.constructor;
700
+ return new This({
701
+ ...this._def,
702
+ description
703
+ });
704
+ }
705
+ pipe(target) {
706
+ return ZodPipeline.create(this, target);
707
+ }
708
+ readonly() {
709
+ return ZodReadonly.create(this);
710
+ }
711
+ isOptional() {
712
+ return this.safeParse(void 0).success;
713
+ }
714
+ isNullable() {
715
+ return this.safeParse(null).success;
716
+ }
717
+ };
718
+ var cuidRegex = /^c[^\s-]{8,}$/i;
719
+ var cuid2Regex = /^[0-9a-z]+$/;
720
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
721
+ 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;
722
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
723
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
724
+ 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)?)??$/;
725
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
726
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
727
+ var emojiRegex;
728
+ 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])$/;
729
+ 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])$/;
730
+ 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]))$/;
731
+ 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])$/;
732
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
733
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
734
+ 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])))`;
735
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
736
+ function timeRegexSource(args) {
737
+ let secondsRegexSource = `[0-5]\\d`;
738
+ if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
739
+ else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
740
+ const secondsQuantifier = args.precision ? "+" : "?";
741
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
742
+ }
743
+ function timeRegex(args) {
744
+ return new RegExp(`^${timeRegexSource(args)}$`);
745
+ }
746
+ function datetimeRegex(args) {
747
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
748
+ const opts = [];
749
+ opts.push(args.local ? `Z?` : `Z`);
750
+ if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`);
751
+ regex = `${regex}(${opts.join("|")})`;
752
+ return new RegExp(`^${regex}$`);
753
+ }
754
+ function isValidIP(ip, version) {
755
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) return true;
756
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) return true;
757
+ return false;
758
+ }
759
+ function isValidJWT(jwt, alg) {
760
+ if (!jwtRegex.test(jwt)) return false;
761
+ try {
762
+ const [header] = jwt.split(".");
763
+ if (!header) return false;
764
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
765
+ const decoded = JSON.parse(atob(base64));
766
+ if (typeof decoded !== "object" || decoded === null) return false;
767
+ if ("typ" in decoded && decoded?.typ !== "JWT") return false;
768
+ if (!decoded.alg) return false;
769
+ if (alg && decoded.alg !== alg) return false;
770
+ return true;
771
+ } catch {
772
+ return false;
773
+ }
774
+ }
775
+ function isValidCidr(ip, version) {
776
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) return true;
777
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) return true;
778
+ return false;
779
+ }
780
+ var ZodString = class ZodString extends ZodType {
781
+ _parse(input) {
782
+ if (this._def.coerce) input.data = String(input.data);
783
+ if (this._getType(input) !== ZodParsedType.string) {
784
+ const ctx = this._getOrReturnCtx(input);
785
+ addIssueToContext(ctx, {
786
+ code: ZodIssueCode.invalid_type,
787
+ expected: ZodParsedType.string,
788
+ received: ctx.parsedType
789
+ });
790
+ return INVALID;
791
+ }
792
+ const status = new ParseStatus();
793
+ let ctx = void 0;
794
+ for (const check of this._def.checks) if (check.kind === "min") {
795
+ if (input.data.length < check.value) {
796
+ ctx = this._getOrReturnCtx(input, ctx);
797
+ addIssueToContext(ctx, {
798
+ code: ZodIssueCode.too_small,
799
+ minimum: check.value,
800
+ type: "string",
801
+ inclusive: true,
802
+ exact: false,
803
+ message: check.message
804
+ });
805
+ status.dirty();
806
+ }
807
+ } else if (check.kind === "max") {
808
+ if (input.data.length > check.value) {
809
+ ctx = this._getOrReturnCtx(input, ctx);
810
+ addIssueToContext(ctx, {
811
+ code: ZodIssueCode.too_big,
812
+ maximum: check.value,
813
+ type: "string",
814
+ inclusive: true,
815
+ exact: false,
816
+ message: check.message
817
+ });
818
+ status.dirty();
819
+ }
820
+ } else if (check.kind === "length") {
821
+ const tooBig = input.data.length > check.value;
822
+ const tooSmall = input.data.length < check.value;
823
+ if (tooBig || tooSmall) {
824
+ ctx = this._getOrReturnCtx(input, ctx);
825
+ if (tooBig) addIssueToContext(ctx, {
826
+ code: ZodIssueCode.too_big,
827
+ maximum: check.value,
828
+ type: "string",
829
+ inclusive: true,
830
+ exact: true,
831
+ message: check.message
832
+ });
833
+ else if (tooSmall) addIssueToContext(ctx, {
834
+ code: ZodIssueCode.too_small,
835
+ minimum: check.value,
836
+ type: "string",
837
+ inclusive: true,
838
+ exact: true,
839
+ message: check.message
840
+ });
841
+ status.dirty();
842
+ }
843
+ } else if (check.kind === "email") {
844
+ if (!emailRegex.test(input.data)) {
845
+ ctx = this._getOrReturnCtx(input, ctx);
846
+ addIssueToContext(ctx, {
847
+ validation: "email",
848
+ code: ZodIssueCode.invalid_string,
849
+ message: check.message
850
+ });
851
+ status.dirty();
852
+ }
853
+ } else if (check.kind === "emoji") {
854
+ if (!emojiRegex) emojiRegex = new RegExp(_emojiRegex, "u");
855
+ if (!emojiRegex.test(input.data)) {
856
+ ctx = this._getOrReturnCtx(input, ctx);
857
+ addIssueToContext(ctx, {
858
+ validation: "emoji",
859
+ code: ZodIssueCode.invalid_string,
860
+ message: check.message
861
+ });
862
+ status.dirty();
863
+ }
864
+ } else if (check.kind === "uuid") {
865
+ if (!uuidRegex.test(input.data)) {
866
+ ctx = this._getOrReturnCtx(input, ctx);
867
+ addIssueToContext(ctx, {
868
+ validation: "uuid",
869
+ code: ZodIssueCode.invalid_string,
870
+ message: check.message
871
+ });
872
+ status.dirty();
873
+ }
874
+ } else if (check.kind === "nanoid") {
875
+ if (!nanoidRegex.test(input.data)) {
876
+ ctx = this._getOrReturnCtx(input, ctx);
877
+ addIssueToContext(ctx, {
878
+ validation: "nanoid",
879
+ code: ZodIssueCode.invalid_string,
880
+ message: check.message
881
+ });
882
+ status.dirty();
883
+ }
884
+ } else if (check.kind === "cuid") {
885
+ if (!cuidRegex.test(input.data)) {
886
+ ctx = this._getOrReturnCtx(input, ctx);
887
+ addIssueToContext(ctx, {
888
+ validation: "cuid",
889
+ code: ZodIssueCode.invalid_string,
890
+ message: check.message
891
+ });
892
+ status.dirty();
893
+ }
894
+ } else if (check.kind === "cuid2") {
895
+ if (!cuid2Regex.test(input.data)) {
896
+ ctx = this._getOrReturnCtx(input, ctx);
897
+ addIssueToContext(ctx, {
898
+ validation: "cuid2",
899
+ code: ZodIssueCode.invalid_string,
900
+ message: check.message
901
+ });
902
+ status.dirty();
903
+ }
904
+ } else if (check.kind === "ulid") {
905
+ if (!ulidRegex.test(input.data)) {
906
+ ctx = this._getOrReturnCtx(input, ctx);
907
+ addIssueToContext(ctx, {
908
+ validation: "ulid",
909
+ code: ZodIssueCode.invalid_string,
910
+ message: check.message
911
+ });
912
+ status.dirty();
913
+ }
914
+ } else if (check.kind === "url") try {
915
+ new URL(input.data);
916
+ } catch {
917
+ ctx = this._getOrReturnCtx(input, ctx);
918
+ addIssueToContext(ctx, {
919
+ validation: "url",
920
+ code: ZodIssueCode.invalid_string,
921
+ message: check.message
922
+ });
923
+ status.dirty();
924
+ }
925
+ else if (check.kind === "regex") {
926
+ check.regex.lastIndex = 0;
927
+ if (!check.regex.test(input.data)) {
928
+ ctx = this._getOrReturnCtx(input, ctx);
929
+ addIssueToContext(ctx, {
930
+ validation: "regex",
931
+ code: ZodIssueCode.invalid_string,
932
+ message: check.message
933
+ });
934
+ status.dirty();
935
+ }
936
+ } else if (check.kind === "trim") input.data = input.data.trim();
937
+ else if (check.kind === "includes") {
938
+ if (!input.data.includes(check.value, check.position)) {
939
+ ctx = this._getOrReturnCtx(input, ctx);
940
+ addIssueToContext(ctx, {
941
+ code: ZodIssueCode.invalid_string,
942
+ validation: {
943
+ includes: check.value,
944
+ position: check.position
945
+ },
946
+ message: check.message
947
+ });
948
+ status.dirty();
949
+ }
950
+ } else if (check.kind === "toLowerCase") input.data = input.data.toLowerCase();
951
+ else if (check.kind === "toUpperCase") input.data = input.data.toUpperCase();
952
+ else if (check.kind === "startsWith") {
953
+ if (!input.data.startsWith(check.value)) {
954
+ ctx = this._getOrReturnCtx(input, ctx);
955
+ addIssueToContext(ctx, {
956
+ code: ZodIssueCode.invalid_string,
957
+ validation: { startsWith: check.value },
958
+ message: check.message
959
+ });
960
+ status.dirty();
961
+ }
962
+ } else if (check.kind === "endsWith") {
963
+ if (!input.data.endsWith(check.value)) {
964
+ ctx = this._getOrReturnCtx(input, ctx);
965
+ addIssueToContext(ctx, {
966
+ code: ZodIssueCode.invalid_string,
967
+ validation: { endsWith: check.value },
968
+ message: check.message
969
+ });
970
+ status.dirty();
971
+ }
972
+ } else if (check.kind === "datetime") {
973
+ if (!datetimeRegex(check).test(input.data)) {
974
+ ctx = this._getOrReturnCtx(input, ctx);
975
+ addIssueToContext(ctx, {
976
+ code: ZodIssueCode.invalid_string,
977
+ validation: "datetime",
978
+ message: check.message
979
+ });
980
+ status.dirty();
981
+ }
982
+ } else if (check.kind === "date") {
983
+ if (!dateRegex.test(input.data)) {
984
+ ctx = this._getOrReturnCtx(input, ctx);
985
+ addIssueToContext(ctx, {
986
+ code: ZodIssueCode.invalid_string,
987
+ validation: "date",
988
+ message: check.message
989
+ });
990
+ status.dirty();
991
+ }
992
+ } else if (check.kind === "time") {
993
+ if (!timeRegex(check).test(input.data)) {
994
+ ctx = this._getOrReturnCtx(input, ctx);
995
+ addIssueToContext(ctx, {
996
+ code: ZodIssueCode.invalid_string,
997
+ validation: "time",
998
+ message: check.message
999
+ });
1000
+ status.dirty();
1001
+ }
1002
+ } else if (check.kind === "duration") {
1003
+ if (!durationRegex.test(input.data)) {
1004
+ ctx = this._getOrReturnCtx(input, ctx);
1005
+ addIssueToContext(ctx, {
1006
+ validation: "duration",
1007
+ code: ZodIssueCode.invalid_string,
1008
+ message: check.message
1009
+ });
1010
+ status.dirty();
1011
+ }
1012
+ } else if (check.kind === "ip") {
1013
+ if (!isValidIP(input.data, check.version)) {
1014
+ ctx = this._getOrReturnCtx(input, ctx);
1015
+ addIssueToContext(ctx, {
1016
+ validation: "ip",
1017
+ code: ZodIssueCode.invalid_string,
1018
+ message: check.message
1019
+ });
1020
+ status.dirty();
1021
+ }
1022
+ } else if (check.kind === "jwt") {
1023
+ if (!isValidJWT(input.data, check.alg)) {
1024
+ ctx = this._getOrReturnCtx(input, ctx);
1025
+ addIssueToContext(ctx, {
1026
+ validation: "jwt",
1027
+ code: ZodIssueCode.invalid_string,
1028
+ message: check.message
1029
+ });
1030
+ status.dirty();
1031
+ }
1032
+ } else if (check.kind === "cidr") {
1033
+ if (!isValidCidr(input.data, check.version)) {
1034
+ ctx = this._getOrReturnCtx(input, ctx);
1035
+ addIssueToContext(ctx, {
1036
+ validation: "cidr",
1037
+ code: ZodIssueCode.invalid_string,
1038
+ message: check.message
1039
+ });
1040
+ status.dirty();
1041
+ }
1042
+ } else if (check.kind === "base64") {
1043
+ if (!base64Regex.test(input.data)) {
1044
+ ctx = this._getOrReturnCtx(input, ctx);
1045
+ addIssueToContext(ctx, {
1046
+ validation: "base64",
1047
+ code: ZodIssueCode.invalid_string,
1048
+ message: check.message
1049
+ });
1050
+ status.dirty();
1051
+ }
1052
+ } else if (check.kind === "base64url") {
1053
+ if (!base64urlRegex.test(input.data)) {
1054
+ ctx = this._getOrReturnCtx(input, ctx);
1055
+ addIssueToContext(ctx, {
1056
+ validation: "base64url",
1057
+ code: ZodIssueCode.invalid_string,
1058
+ message: check.message
1059
+ });
1060
+ status.dirty();
1061
+ }
1062
+ } else util.assertNever(check);
1063
+ return {
1064
+ status: status.value,
1065
+ value: input.data
1066
+ };
1067
+ }
1068
+ _regex(regex, validation, message) {
1069
+ return this.refinement((data) => regex.test(data), {
1070
+ validation,
1071
+ code: ZodIssueCode.invalid_string,
1072
+ ...errorUtil.errToObj(message)
1073
+ });
1074
+ }
1075
+ _addCheck(check) {
1076
+ return new ZodString({
1077
+ ...this._def,
1078
+ checks: [...this._def.checks, check]
1079
+ });
1080
+ }
1081
+ email(message) {
1082
+ return this._addCheck({
1083
+ kind: "email",
1084
+ ...errorUtil.errToObj(message)
1085
+ });
1086
+ }
1087
+ url(message) {
1088
+ return this._addCheck({
1089
+ kind: "url",
1090
+ ...errorUtil.errToObj(message)
1091
+ });
1092
+ }
1093
+ emoji(message) {
1094
+ return this._addCheck({
1095
+ kind: "emoji",
1096
+ ...errorUtil.errToObj(message)
1097
+ });
1098
+ }
1099
+ uuid(message) {
1100
+ return this._addCheck({
1101
+ kind: "uuid",
1102
+ ...errorUtil.errToObj(message)
1103
+ });
1104
+ }
1105
+ nanoid(message) {
1106
+ return this._addCheck({
1107
+ kind: "nanoid",
1108
+ ...errorUtil.errToObj(message)
1109
+ });
1110
+ }
1111
+ cuid(message) {
1112
+ return this._addCheck({
1113
+ kind: "cuid",
1114
+ ...errorUtil.errToObj(message)
1115
+ });
1116
+ }
1117
+ cuid2(message) {
1118
+ return this._addCheck({
1119
+ kind: "cuid2",
1120
+ ...errorUtil.errToObj(message)
1121
+ });
1122
+ }
1123
+ ulid(message) {
1124
+ return this._addCheck({
1125
+ kind: "ulid",
1126
+ ...errorUtil.errToObj(message)
1127
+ });
1128
+ }
1129
+ base64(message) {
1130
+ return this._addCheck({
1131
+ kind: "base64",
1132
+ ...errorUtil.errToObj(message)
1133
+ });
1134
+ }
1135
+ base64url(message) {
1136
+ return this._addCheck({
1137
+ kind: "base64url",
1138
+ ...errorUtil.errToObj(message)
1139
+ });
1140
+ }
1141
+ jwt(options) {
1142
+ return this._addCheck({
1143
+ kind: "jwt",
1144
+ ...errorUtil.errToObj(options)
1145
+ });
1146
+ }
1147
+ ip(options) {
1148
+ return this._addCheck({
1149
+ kind: "ip",
1150
+ ...errorUtil.errToObj(options)
1151
+ });
1152
+ }
1153
+ cidr(options) {
1154
+ return this._addCheck({
1155
+ kind: "cidr",
1156
+ ...errorUtil.errToObj(options)
1157
+ });
1158
+ }
1159
+ datetime(options) {
1160
+ if (typeof options === "string") return this._addCheck({
1161
+ kind: "datetime",
1162
+ precision: null,
1163
+ offset: false,
1164
+ local: false,
1165
+ message: options
1166
+ });
1167
+ return this._addCheck({
1168
+ kind: "datetime",
1169
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1170
+ offset: options?.offset ?? false,
1171
+ local: options?.local ?? false,
1172
+ ...errorUtil.errToObj(options?.message)
1173
+ });
1174
+ }
1175
+ date(message) {
1176
+ return this._addCheck({
1177
+ kind: "date",
1178
+ message
1179
+ });
1180
+ }
1181
+ time(options) {
1182
+ if (typeof options === "string") return this._addCheck({
1183
+ kind: "time",
1184
+ precision: null,
1185
+ message: options
1186
+ });
1187
+ return this._addCheck({
1188
+ kind: "time",
1189
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1190
+ ...errorUtil.errToObj(options?.message)
1191
+ });
1192
+ }
1193
+ duration(message) {
1194
+ return this._addCheck({
1195
+ kind: "duration",
1196
+ ...errorUtil.errToObj(message)
1197
+ });
1198
+ }
1199
+ regex(regex, message) {
1200
+ return this._addCheck({
1201
+ kind: "regex",
1202
+ regex,
1203
+ ...errorUtil.errToObj(message)
1204
+ });
1205
+ }
1206
+ includes(value, options) {
1207
+ return this._addCheck({
1208
+ kind: "includes",
1209
+ value,
1210
+ position: options?.position,
1211
+ ...errorUtil.errToObj(options?.message)
1212
+ });
1213
+ }
1214
+ startsWith(value, message) {
1215
+ return this._addCheck({
1216
+ kind: "startsWith",
1217
+ value,
1218
+ ...errorUtil.errToObj(message)
1219
+ });
1220
+ }
1221
+ endsWith(value, message) {
1222
+ return this._addCheck({
1223
+ kind: "endsWith",
1224
+ value,
1225
+ ...errorUtil.errToObj(message)
1226
+ });
1227
+ }
1228
+ min(minLength, message) {
1229
+ return this._addCheck({
1230
+ kind: "min",
1231
+ value: minLength,
1232
+ ...errorUtil.errToObj(message)
1233
+ });
1234
+ }
1235
+ max(maxLength, message) {
1236
+ return this._addCheck({
1237
+ kind: "max",
1238
+ value: maxLength,
1239
+ ...errorUtil.errToObj(message)
1240
+ });
1241
+ }
1242
+ length(len, message) {
1243
+ return this._addCheck({
1244
+ kind: "length",
1245
+ value: len,
1246
+ ...errorUtil.errToObj(message)
1247
+ });
1248
+ }
1249
+ /**
1250
+ * Equivalent to `.min(1)`
1251
+ */
1252
+ nonempty(message) {
1253
+ return this.min(1, errorUtil.errToObj(message));
1254
+ }
1255
+ trim() {
1256
+ return new ZodString({
1257
+ ...this._def,
1258
+ checks: [...this._def.checks, { kind: "trim" }]
1259
+ });
1260
+ }
1261
+ toLowerCase() {
1262
+ return new ZodString({
1263
+ ...this._def,
1264
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1265
+ });
1266
+ }
1267
+ toUpperCase() {
1268
+ return new ZodString({
1269
+ ...this._def,
1270
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1271
+ });
1272
+ }
1273
+ get isDatetime() {
1274
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1275
+ }
1276
+ get isDate() {
1277
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1278
+ }
1279
+ get isTime() {
1280
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1281
+ }
1282
+ get isDuration() {
1283
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1284
+ }
1285
+ get isEmail() {
1286
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1287
+ }
1288
+ get isURL() {
1289
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1290
+ }
1291
+ get isEmoji() {
1292
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1293
+ }
1294
+ get isUUID() {
1295
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1296
+ }
1297
+ get isNANOID() {
1298
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1299
+ }
1300
+ get isCUID() {
1301
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1302
+ }
1303
+ get isCUID2() {
1304
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1305
+ }
1306
+ get isULID() {
1307
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1308
+ }
1309
+ get isIP() {
1310
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1311
+ }
1312
+ get isCIDR() {
1313
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1314
+ }
1315
+ get isBase64() {
1316
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1317
+ }
1318
+ get isBase64url() {
1319
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1320
+ }
1321
+ get minLength() {
1322
+ let min = null;
1323
+ for (const ch of this._def.checks) if (ch.kind === "min") {
1324
+ if (min === null || ch.value > min) min = ch.value;
1325
+ }
1326
+ return min;
1327
+ }
1328
+ get maxLength() {
1329
+ let max = null;
1330
+ for (const ch of this._def.checks) if (ch.kind === "max") {
1331
+ if (max === null || ch.value < max) max = ch.value;
1332
+ }
1333
+ return max;
1334
+ }
1335
+ };
1336
+ ZodString.create = (params) => {
1337
+ return new ZodString({
1338
+ checks: [],
1339
+ typeName: ZodFirstPartyTypeKind.ZodString,
1340
+ coerce: params?.coerce ?? false,
1341
+ ...processCreateParams(params)
1342
+ });
1343
+ };
1344
+ function floatSafeRemainder(val, step) {
1345
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1346
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1347
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1348
+ return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
1349
+ }
1350
+ var ZodNumber = class ZodNumber extends ZodType {
1351
+ constructor() {
1352
+ super(...arguments);
1353
+ this.min = this.gte;
1354
+ this.max = this.lte;
1355
+ this.step = this.multipleOf;
1356
+ }
1357
+ _parse(input) {
1358
+ if (this._def.coerce) input.data = Number(input.data);
1359
+ if (this._getType(input) !== ZodParsedType.number) {
1360
+ const ctx = this._getOrReturnCtx(input);
1361
+ addIssueToContext(ctx, {
1362
+ code: ZodIssueCode.invalid_type,
1363
+ expected: ZodParsedType.number,
1364
+ received: ctx.parsedType
1365
+ });
1366
+ return INVALID;
1367
+ }
1368
+ let ctx = void 0;
1369
+ const status = new ParseStatus();
1370
+ for (const check of this._def.checks) if (check.kind === "int") {
1371
+ if (!util.isInteger(input.data)) {
1372
+ ctx = this._getOrReturnCtx(input, ctx);
1373
+ addIssueToContext(ctx, {
1374
+ code: ZodIssueCode.invalid_type,
1375
+ expected: "integer",
1376
+ received: "float",
1377
+ message: check.message
1378
+ });
1379
+ status.dirty();
1380
+ }
1381
+ } else if (check.kind === "min") {
1382
+ if (check.inclusive ? input.data < check.value : input.data <= check.value) {
1383
+ ctx = this._getOrReturnCtx(input, ctx);
1384
+ addIssueToContext(ctx, {
1385
+ code: ZodIssueCode.too_small,
1386
+ minimum: check.value,
1387
+ type: "number",
1388
+ inclusive: check.inclusive,
1389
+ exact: false,
1390
+ message: check.message
1391
+ });
1392
+ status.dirty();
1393
+ }
1394
+ } else if (check.kind === "max") {
1395
+ if (check.inclusive ? input.data > check.value : input.data >= check.value) {
1396
+ ctx = this._getOrReturnCtx(input, ctx);
1397
+ addIssueToContext(ctx, {
1398
+ code: ZodIssueCode.too_big,
1399
+ maximum: check.value,
1400
+ type: "number",
1401
+ inclusive: check.inclusive,
1402
+ exact: false,
1403
+ message: check.message
1404
+ });
1405
+ status.dirty();
1406
+ }
1407
+ } else if (check.kind === "multipleOf") {
1408
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1409
+ ctx = this._getOrReturnCtx(input, ctx);
1410
+ addIssueToContext(ctx, {
1411
+ code: ZodIssueCode.not_multiple_of,
1412
+ multipleOf: check.value,
1413
+ message: check.message
1414
+ });
1415
+ status.dirty();
1416
+ }
1417
+ } else if (check.kind === "finite") {
1418
+ if (!Number.isFinite(input.data)) {
1419
+ ctx = this._getOrReturnCtx(input, ctx);
1420
+ addIssueToContext(ctx, {
1421
+ code: ZodIssueCode.not_finite,
1422
+ message: check.message
1423
+ });
1424
+ status.dirty();
1425
+ }
1426
+ } else util.assertNever(check);
1427
+ return {
1428
+ status: status.value,
1429
+ value: input.data
1430
+ };
1431
+ }
1432
+ gte(value, message) {
1433
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1434
+ }
1435
+ gt(value, message) {
1436
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1437
+ }
1438
+ lte(value, message) {
1439
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1440
+ }
1441
+ lt(value, message) {
1442
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1443
+ }
1444
+ setLimit(kind, value, inclusive, message) {
1445
+ return new ZodNumber({
1446
+ ...this._def,
1447
+ checks: [...this._def.checks, {
1448
+ kind,
1449
+ value,
1450
+ inclusive,
1451
+ message: errorUtil.toString(message)
1452
+ }]
1453
+ });
1454
+ }
1455
+ _addCheck(check) {
1456
+ return new ZodNumber({
1457
+ ...this._def,
1458
+ checks: [...this._def.checks, check]
1459
+ });
1460
+ }
1461
+ int(message) {
1462
+ return this._addCheck({
1463
+ kind: "int",
1464
+ message: errorUtil.toString(message)
1465
+ });
1466
+ }
1467
+ positive(message) {
1468
+ return this._addCheck({
1469
+ kind: "min",
1470
+ value: 0,
1471
+ inclusive: false,
1472
+ message: errorUtil.toString(message)
1473
+ });
1474
+ }
1475
+ negative(message) {
1476
+ return this._addCheck({
1477
+ kind: "max",
1478
+ value: 0,
1479
+ inclusive: false,
1480
+ message: errorUtil.toString(message)
1481
+ });
1482
+ }
1483
+ nonpositive(message) {
1484
+ return this._addCheck({
1485
+ kind: "max",
1486
+ value: 0,
1487
+ inclusive: true,
1488
+ message: errorUtil.toString(message)
1489
+ });
1490
+ }
1491
+ nonnegative(message) {
1492
+ return this._addCheck({
1493
+ kind: "min",
1494
+ value: 0,
1495
+ inclusive: true,
1496
+ message: errorUtil.toString(message)
1497
+ });
1498
+ }
1499
+ multipleOf(value, message) {
1500
+ return this._addCheck({
1501
+ kind: "multipleOf",
1502
+ value,
1503
+ message: errorUtil.toString(message)
1504
+ });
1505
+ }
1506
+ finite(message) {
1507
+ return this._addCheck({
1508
+ kind: "finite",
1509
+ message: errorUtil.toString(message)
1510
+ });
1511
+ }
1512
+ safe(message) {
1513
+ return this._addCheck({
1514
+ kind: "min",
1515
+ inclusive: true,
1516
+ value: Number.MIN_SAFE_INTEGER,
1517
+ message: errorUtil.toString(message)
1518
+ })._addCheck({
1519
+ kind: "max",
1520
+ inclusive: true,
1521
+ value: Number.MAX_SAFE_INTEGER,
1522
+ message: errorUtil.toString(message)
1523
+ });
1524
+ }
1525
+ get minValue() {
1526
+ let min = null;
1527
+ for (const ch of this._def.checks) if (ch.kind === "min") {
1528
+ if (min === null || ch.value > min) min = ch.value;
1529
+ }
1530
+ return min;
1531
+ }
1532
+ get maxValue() {
1533
+ let max = null;
1534
+ for (const ch of this._def.checks) if (ch.kind === "max") {
1535
+ if (max === null || ch.value < max) max = ch.value;
1536
+ }
1537
+ return max;
1538
+ }
1539
+ get isInt() {
1540
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1541
+ }
1542
+ get isFinite() {
1543
+ let max = null;
1544
+ let min = null;
1545
+ for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
1546
+ else if (ch.kind === "min") {
1547
+ if (min === null || ch.value > min) min = ch.value;
1548
+ } else if (ch.kind === "max") {
1549
+ if (max === null || ch.value < max) max = ch.value;
1550
+ }
1551
+ return Number.isFinite(min) && Number.isFinite(max);
1552
+ }
1553
+ };
1554
+ ZodNumber.create = (params) => {
1555
+ return new ZodNumber({
1556
+ checks: [],
1557
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1558
+ coerce: params?.coerce || false,
1559
+ ...processCreateParams(params)
1560
+ });
1561
+ };
1562
+ var ZodBigInt = class ZodBigInt extends ZodType {
1563
+ constructor() {
1564
+ super(...arguments);
1565
+ this.min = this.gte;
1566
+ this.max = this.lte;
1567
+ }
1568
+ _parse(input) {
1569
+ if (this._def.coerce) try {
1570
+ input.data = BigInt(input.data);
1571
+ } catch {
1572
+ return this._getInvalidInput(input);
1573
+ }
1574
+ if (this._getType(input) !== ZodParsedType.bigint) return this._getInvalidInput(input);
1575
+ let ctx = void 0;
1576
+ const status = new ParseStatus();
1577
+ for (const check of this._def.checks) if (check.kind === "min") {
1578
+ if (check.inclusive ? input.data < check.value : input.data <= check.value) {
1579
+ ctx = this._getOrReturnCtx(input, ctx);
1580
+ addIssueToContext(ctx, {
1581
+ code: ZodIssueCode.too_small,
1582
+ type: "bigint",
1583
+ minimum: check.value,
1584
+ inclusive: check.inclusive,
1585
+ message: check.message
1586
+ });
1587
+ status.dirty();
1588
+ }
1589
+ } else if (check.kind === "max") {
1590
+ if (check.inclusive ? input.data > check.value : input.data >= check.value) {
1591
+ ctx = this._getOrReturnCtx(input, ctx);
1592
+ addIssueToContext(ctx, {
1593
+ code: ZodIssueCode.too_big,
1594
+ type: "bigint",
1595
+ maximum: check.value,
1596
+ inclusive: check.inclusive,
1597
+ message: check.message
1598
+ });
1599
+ status.dirty();
1600
+ }
1601
+ } else if (check.kind === "multipleOf") {
1602
+ if (input.data % check.value !== BigInt(0)) {
1603
+ ctx = this._getOrReturnCtx(input, ctx);
1604
+ addIssueToContext(ctx, {
1605
+ code: ZodIssueCode.not_multiple_of,
1606
+ multipleOf: check.value,
1607
+ message: check.message
1608
+ });
1609
+ status.dirty();
1610
+ }
1611
+ } else util.assertNever(check);
1612
+ return {
1613
+ status: status.value,
1614
+ value: input.data
1615
+ };
1616
+ }
1617
+ _getInvalidInput(input) {
1618
+ const ctx = this._getOrReturnCtx(input);
1619
+ addIssueToContext(ctx, {
1620
+ code: ZodIssueCode.invalid_type,
1621
+ expected: ZodParsedType.bigint,
1622
+ received: ctx.parsedType
1623
+ });
1624
+ return INVALID;
1625
+ }
1626
+ gte(value, message) {
1627
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1628
+ }
1629
+ gt(value, message) {
1630
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1631
+ }
1632
+ lte(value, message) {
1633
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1634
+ }
1635
+ lt(value, message) {
1636
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1637
+ }
1638
+ setLimit(kind, value, inclusive, message) {
1639
+ return new ZodBigInt({
1640
+ ...this._def,
1641
+ checks: [...this._def.checks, {
1642
+ kind,
1643
+ value,
1644
+ inclusive,
1645
+ message: errorUtil.toString(message)
1646
+ }]
1647
+ });
1648
+ }
1649
+ _addCheck(check) {
1650
+ return new ZodBigInt({
1651
+ ...this._def,
1652
+ checks: [...this._def.checks, check]
1653
+ });
1654
+ }
1655
+ positive(message) {
1656
+ return this._addCheck({
1657
+ kind: "min",
1658
+ value: BigInt(0),
1659
+ inclusive: false,
1660
+ message: errorUtil.toString(message)
1661
+ });
1662
+ }
1663
+ negative(message) {
1664
+ return this._addCheck({
1665
+ kind: "max",
1666
+ value: BigInt(0),
1667
+ inclusive: false,
1668
+ message: errorUtil.toString(message)
1669
+ });
1670
+ }
1671
+ nonpositive(message) {
1672
+ return this._addCheck({
1673
+ kind: "max",
1674
+ value: BigInt(0),
1675
+ inclusive: true,
1676
+ message: errorUtil.toString(message)
1677
+ });
1678
+ }
1679
+ nonnegative(message) {
1680
+ return this._addCheck({
1681
+ kind: "min",
1682
+ value: BigInt(0),
1683
+ inclusive: true,
1684
+ message: errorUtil.toString(message)
1685
+ });
1686
+ }
1687
+ multipleOf(value, message) {
1688
+ return this._addCheck({
1689
+ kind: "multipleOf",
1690
+ value,
1691
+ message: errorUtil.toString(message)
1692
+ });
1693
+ }
1694
+ get minValue() {
1695
+ let min = null;
1696
+ for (const ch of this._def.checks) if (ch.kind === "min") {
1697
+ if (min === null || ch.value > min) min = ch.value;
1698
+ }
1699
+ return min;
1700
+ }
1701
+ get maxValue() {
1702
+ let max = null;
1703
+ for (const ch of this._def.checks) if (ch.kind === "max") {
1704
+ if (max === null || ch.value < max) max = ch.value;
1705
+ }
1706
+ return max;
1707
+ }
1708
+ };
1709
+ ZodBigInt.create = (params) => {
1710
+ return new ZodBigInt({
1711
+ checks: [],
1712
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
1713
+ coerce: params?.coerce ?? false,
1714
+ ...processCreateParams(params)
1715
+ });
1716
+ };
1717
+ var ZodBoolean = class extends ZodType {
1718
+ _parse(input) {
1719
+ if (this._def.coerce) input.data = Boolean(input.data);
1720
+ if (this._getType(input) !== ZodParsedType.boolean) {
1721
+ const ctx = this._getOrReturnCtx(input);
1722
+ addIssueToContext(ctx, {
1723
+ code: ZodIssueCode.invalid_type,
1724
+ expected: ZodParsedType.boolean,
1725
+ received: ctx.parsedType
1726
+ });
1727
+ return INVALID;
1728
+ }
1729
+ return OK(input.data);
1730
+ }
1731
+ };
1732
+ ZodBoolean.create = (params) => {
1733
+ return new ZodBoolean({
1734
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
1735
+ coerce: params?.coerce || false,
1736
+ ...processCreateParams(params)
1737
+ });
1738
+ };
1739
+ var ZodDate = class ZodDate extends ZodType {
1740
+ _parse(input) {
1741
+ if (this._def.coerce) input.data = new Date(input.data);
1742
+ if (this._getType(input) !== ZodParsedType.date) {
1743
+ const ctx = this._getOrReturnCtx(input);
1744
+ addIssueToContext(ctx, {
1745
+ code: ZodIssueCode.invalid_type,
1746
+ expected: ZodParsedType.date,
1747
+ received: ctx.parsedType
1748
+ });
1749
+ return INVALID;
1750
+ }
1751
+ if (Number.isNaN(input.data.getTime())) {
1752
+ addIssueToContext(this._getOrReturnCtx(input), { code: ZodIssueCode.invalid_date });
1753
+ return INVALID;
1754
+ }
1755
+ const status = new ParseStatus();
1756
+ let ctx = void 0;
1757
+ for (const check of this._def.checks) if (check.kind === "min") {
1758
+ if (input.data.getTime() < check.value) {
1759
+ ctx = this._getOrReturnCtx(input, ctx);
1760
+ addIssueToContext(ctx, {
1761
+ code: ZodIssueCode.too_small,
1762
+ message: check.message,
1763
+ inclusive: true,
1764
+ exact: false,
1765
+ minimum: check.value,
1766
+ type: "date"
1767
+ });
1768
+ status.dirty();
1769
+ }
1770
+ } else if (check.kind === "max") {
1771
+ if (input.data.getTime() > check.value) {
1772
+ ctx = this._getOrReturnCtx(input, ctx);
1773
+ addIssueToContext(ctx, {
1774
+ code: ZodIssueCode.too_big,
1775
+ message: check.message,
1776
+ inclusive: true,
1777
+ exact: false,
1778
+ maximum: check.value,
1779
+ type: "date"
1780
+ });
1781
+ status.dirty();
1782
+ }
1783
+ } else util.assertNever(check);
1784
+ return {
1785
+ status: status.value,
1786
+ value: new Date(input.data.getTime())
1787
+ };
1788
+ }
1789
+ _addCheck(check) {
1790
+ return new ZodDate({
1791
+ ...this._def,
1792
+ checks: [...this._def.checks, check]
1793
+ });
1794
+ }
1795
+ min(minDate, message) {
1796
+ return this._addCheck({
1797
+ kind: "min",
1798
+ value: minDate.getTime(),
1799
+ message: errorUtil.toString(message)
1800
+ });
1801
+ }
1802
+ max(maxDate, message) {
1803
+ return this._addCheck({
1804
+ kind: "max",
1805
+ value: maxDate.getTime(),
1806
+ message: errorUtil.toString(message)
1807
+ });
1808
+ }
1809
+ get minDate() {
1810
+ let min = null;
1811
+ for (const ch of this._def.checks) if (ch.kind === "min") {
1812
+ if (min === null || ch.value > min) min = ch.value;
1813
+ }
1814
+ return min != null ? new Date(min) : null;
1815
+ }
1816
+ get maxDate() {
1817
+ let max = null;
1818
+ for (const ch of this._def.checks) if (ch.kind === "max") {
1819
+ if (max === null || ch.value < max) max = ch.value;
1820
+ }
1821
+ return max != null ? new Date(max) : null;
1822
+ }
1823
+ };
1824
+ ZodDate.create = (params) => {
1825
+ return new ZodDate({
1826
+ checks: [],
1827
+ coerce: params?.coerce || false,
1828
+ typeName: ZodFirstPartyTypeKind.ZodDate,
1829
+ ...processCreateParams(params)
1830
+ });
1831
+ };
1832
+ var ZodSymbol = class extends ZodType {
1833
+ _parse(input) {
1834
+ if (this._getType(input) !== ZodParsedType.symbol) {
1835
+ const ctx = this._getOrReturnCtx(input);
1836
+ addIssueToContext(ctx, {
1837
+ code: ZodIssueCode.invalid_type,
1838
+ expected: ZodParsedType.symbol,
1839
+ received: ctx.parsedType
1840
+ });
1841
+ return INVALID;
1842
+ }
1843
+ return OK(input.data);
1844
+ }
1845
+ };
1846
+ ZodSymbol.create = (params) => {
1847
+ return new ZodSymbol({
1848
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
1849
+ ...processCreateParams(params)
1850
+ });
1851
+ };
1852
+ var ZodUndefined = class extends ZodType {
1853
+ _parse(input) {
1854
+ if (this._getType(input) !== ZodParsedType.undefined) {
1855
+ const ctx = this._getOrReturnCtx(input);
1856
+ addIssueToContext(ctx, {
1857
+ code: ZodIssueCode.invalid_type,
1858
+ expected: ZodParsedType.undefined,
1859
+ received: ctx.parsedType
1860
+ });
1861
+ return INVALID;
1862
+ }
1863
+ return OK(input.data);
1864
+ }
1865
+ };
1866
+ ZodUndefined.create = (params) => {
1867
+ return new ZodUndefined({
1868
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
1869
+ ...processCreateParams(params)
1870
+ });
1871
+ };
1872
+ var ZodNull = class extends ZodType {
1873
+ _parse(input) {
1874
+ if (this._getType(input) !== ZodParsedType.null) {
1875
+ const ctx = this._getOrReturnCtx(input);
1876
+ addIssueToContext(ctx, {
1877
+ code: ZodIssueCode.invalid_type,
1878
+ expected: ZodParsedType.null,
1879
+ received: ctx.parsedType
1880
+ });
1881
+ return INVALID;
1882
+ }
1883
+ return OK(input.data);
1884
+ }
1885
+ };
1886
+ ZodNull.create = (params) => {
1887
+ return new ZodNull({
1888
+ typeName: ZodFirstPartyTypeKind.ZodNull,
1889
+ ...processCreateParams(params)
1890
+ });
1891
+ };
1892
+ var ZodAny = class extends ZodType {
1893
+ constructor() {
1894
+ super(...arguments);
1895
+ this._any = true;
1896
+ }
1897
+ _parse(input) {
1898
+ return OK(input.data);
1899
+ }
1900
+ };
1901
+ ZodAny.create = (params) => {
1902
+ return new ZodAny({
1903
+ typeName: ZodFirstPartyTypeKind.ZodAny,
1904
+ ...processCreateParams(params)
1905
+ });
1906
+ };
1907
+ var ZodUnknown = class extends ZodType {
1908
+ constructor() {
1909
+ super(...arguments);
1910
+ this._unknown = true;
1911
+ }
1912
+ _parse(input) {
1913
+ return OK(input.data);
1914
+ }
1915
+ };
1916
+ ZodUnknown.create = (params) => {
1917
+ return new ZodUnknown({
1918
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
1919
+ ...processCreateParams(params)
1920
+ });
1921
+ };
1922
+ var ZodNever = class extends ZodType {
1923
+ _parse(input) {
1924
+ const ctx = this._getOrReturnCtx(input);
1925
+ addIssueToContext(ctx, {
1926
+ code: ZodIssueCode.invalid_type,
1927
+ expected: ZodParsedType.never,
1928
+ received: ctx.parsedType
1929
+ });
1930
+ return INVALID;
1931
+ }
1932
+ };
1933
+ ZodNever.create = (params) => {
1934
+ return new ZodNever({
1935
+ typeName: ZodFirstPartyTypeKind.ZodNever,
1936
+ ...processCreateParams(params)
1937
+ });
1938
+ };
1939
+ var ZodVoid = class extends ZodType {
1940
+ _parse(input) {
1941
+ if (this._getType(input) !== ZodParsedType.undefined) {
1942
+ const ctx = this._getOrReturnCtx(input);
1943
+ addIssueToContext(ctx, {
1944
+ code: ZodIssueCode.invalid_type,
1945
+ expected: ZodParsedType.void,
1946
+ received: ctx.parsedType
1947
+ });
1948
+ return INVALID;
1949
+ }
1950
+ return OK(input.data);
1951
+ }
1952
+ };
1953
+ ZodVoid.create = (params) => {
1954
+ return new ZodVoid({
1955
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
1956
+ ...processCreateParams(params)
1957
+ });
1958
+ };
1959
+ var ZodArray = class ZodArray extends ZodType {
1960
+ _parse(input) {
1961
+ const { ctx, status } = this._processInputParams(input);
1962
+ const def = this._def;
1963
+ if (ctx.parsedType !== ZodParsedType.array) {
1964
+ addIssueToContext(ctx, {
1965
+ code: ZodIssueCode.invalid_type,
1966
+ expected: ZodParsedType.array,
1967
+ received: ctx.parsedType
1968
+ });
1969
+ return INVALID;
1970
+ }
1971
+ if (def.exactLength !== null) {
1972
+ const tooBig = ctx.data.length > def.exactLength.value;
1973
+ const tooSmall = ctx.data.length < def.exactLength.value;
1974
+ if (tooBig || tooSmall) {
1975
+ addIssueToContext(ctx, {
1976
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
1977
+ minimum: tooSmall ? def.exactLength.value : void 0,
1978
+ maximum: tooBig ? def.exactLength.value : void 0,
1979
+ type: "array",
1980
+ inclusive: true,
1981
+ exact: true,
1982
+ message: def.exactLength.message
1983
+ });
1984
+ status.dirty();
1985
+ }
1986
+ }
1987
+ if (def.minLength !== null) {
1988
+ if (ctx.data.length < def.minLength.value) {
1989
+ addIssueToContext(ctx, {
1990
+ code: ZodIssueCode.too_small,
1991
+ minimum: def.minLength.value,
1992
+ type: "array",
1993
+ inclusive: true,
1994
+ exact: false,
1995
+ message: def.minLength.message
1996
+ });
1997
+ status.dirty();
1998
+ }
1999
+ }
2000
+ if (def.maxLength !== null) {
2001
+ if (ctx.data.length > def.maxLength.value) {
2002
+ addIssueToContext(ctx, {
2003
+ code: ZodIssueCode.too_big,
2004
+ maximum: def.maxLength.value,
2005
+ type: "array",
2006
+ inclusive: true,
2007
+ exact: false,
2008
+ message: def.maxLength.message
2009
+ });
2010
+ status.dirty();
2011
+ }
2012
+ }
2013
+ if (ctx.common.async) return Promise.all([...ctx.data].map((item, i) => {
2014
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2015
+ })).then((result) => {
2016
+ return ParseStatus.mergeArray(status, result);
2017
+ });
2018
+ const result = [...ctx.data].map((item, i) => {
2019
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2020
+ });
2021
+ return ParseStatus.mergeArray(status, result);
2022
+ }
2023
+ get element() {
2024
+ return this._def.type;
2025
+ }
2026
+ min(minLength, message) {
2027
+ return new ZodArray({
2028
+ ...this._def,
2029
+ minLength: {
2030
+ value: minLength,
2031
+ message: errorUtil.toString(message)
2032
+ }
2033
+ });
2034
+ }
2035
+ max(maxLength, message) {
2036
+ return new ZodArray({
2037
+ ...this._def,
2038
+ maxLength: {
2039
+ value: maxLength,
2040
+ message: errorUtil.toString(message)
2041
+ }
2042
+ });
2043
+ }
2044
+ length(len, message) {
2045
+ return new ZodArray({
2046
+ ...this._def,
2047
+ exactLength: {
2048
+ value: len,
2049
+ message: errorUtil.toString(message)
2050
+ }
2051
+ });
2052
+ }
2053
+ nonempty(message) {
2054
+ return this.min(1, message);
2055
+ }
2056
+ };
2057
+ ZodArray.create = (schema, params) => {
2058
+ return new ZodArray({
2059
+ type: schema,
2060
+ minLength: null,
2061
+ maxLength: null,
2062
+ exactLength: null,
2063
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2064
+ ...processCreateParams(params)
2065
+ });
2066
+ };
2067
+ function deepPartialify(schema) {
2068
+ if (schema instanceof ZodObject) {
2069
+ const newShape = {};
2070
+ for (const key in schema.shape) {
2071
+ const fieldSchema = schema.shape[key];
2072
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2073
+ }
2074
+ return new ZodObject({
2075
+ ...schema._def,
2076
+ shape: () => newShape
2077
+ });
2078
+ } else if (schema instanceof ZodArray) return new ZodArray({
2079
+ ...schema._def,
2080
+ type: deepPartialify(schema.element)
2081
+ });
2082
+ else if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap()));
2083
+ else if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap()));
2084
+ else if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2085
+ else return schema;
2086
+ }
2087
+ var ZodObject = class ZodObject extends ZodType {
2088
+ constructor() {
2089
+ super(...arguments);
2090
+ this._cached = null;
2091
+ /**
2092
+ * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
2093
+ * If you want to pass through unknown properties, use `.passthrough()` instead.
2094
+ */
2095
+ this.nonstrict = this.passthrough;
2096
+ /**
2097
+ * @deprecated Use `.extend` instead
2098
+ * */
2099
+ this.augment = this.extend;
2100
+ }
2101
+ _getCached() {
2102
+ if (this._cached !== null) return this._cached;
2103
+ const shape = this._def.shape();
2104
+ const keys = util.objectKeys(shape);
2105
+ this._cached = {
2106
+ shape,
2107
+ keys
2108
+ };
2109
+ return this._cached;
2110
+ }
2111
+ _parse(input) {
2112
+ if (this._getType(input) !== ZodParsedType.object) {
2113
+ const ctx = this._getOrReturnCtx(input);
2114
+ addIssueToContext(ctx, {
2115
+ code: ZodIssueCode.invalid_type,
2116
+ expected: ZodParsedType.object,
2117
+ received: ctx.parsedType
2118
+ });
2119
+ return INVALID;
2120
+ }
2121
+ const { status, ctx } = this._processInputParams(input);
2122
+ const { shape, keys: shapeKeys } = this._getCached();
2123
+ const extraKeys = [];
2124
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2125
+ for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key);
2126
+ }
2127
+ const pairs = [];
2128
+ for (const key of shapeKeys) {
2129
+ const keyValidator = shape[key];
2130
+ const value = ctx.data[key];
2131
+ pairs.push({
2132
+ key: {
2133
+ status: "valid",
2134
+ value: key
2135
+ },
2136
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2137
+ alwaysSet: key in ctx.data
2138
+ });
2139
+ }
2140
+ if (this._def.catchall instanceof ZodNever) {
2141
+ const unknownKeys = this._def.unknownKeys;
2142
+ if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({
2143
+ key: {
2144
+ status: "valid",
2145
+ value: key
2146
+ },
2147
+ value: {
2148
+ status: "valid",
2149
+ value: ctx.data[key]
2150
+ }
2151
+ });
2152
+ else if (unknownKeys === "strict") {
2153
+ if (extraKeys.length > 0) {
2154
+ addIssueToContext(ctx, {
2155
+ code: ZodIssueCode.unrecognized_keys,
2156
+ keys: extraKeys
2157
+ });
2158
+ status.dirty();
2159
+ }
2160
+ } else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2161
+ } else {
2162
+ const catchall = this._def.catchall;
2163
+ for (const key of extraKeys) {
2164
+ const value = ctx.data[key];
2165
+ pairs.push({
2166
+ key: {
2167
+ status: "valid",
2168
+ value: key
2169
+ },
2170
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2171
+ alwaysSet: key in ctx.data
2172
+ });
2173
+ }
2174
+ }
2175
+ if (ctx.common.async) return Promise.resolve().then(async () => {
2176
+ const syncPairs = [];
2177
+ for (const pair of pairs) {
2178
+ const key = await pair.key;
2179
+ const value = await pair.value;
2180
+ syncPairs.push({
2181
+ key,
2182
+ value,
2183
+ alwaysSet: pair.alwaysSet
2184
+ });
2185
+ }
2186
+ return syncPairs;
2187
+ }).then((syncPairs) => {
2188
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2189
+ });
2190
+ else return ParseStatus.mergeObjectSync(status, pairs);
2191
+ }
2192
+ get shape() {
2193
+ return this._def.shape();
2194
+ }
2195
+ strict(message) {
2196
+ errorUtil.errToObj;
2197
+ return new ZodObject({
2198
+ ...this._def,
2199
+ unknownKeys: "strict",
2200
+ ...message !== void 0 ? { errorMap: (issue, ctx) => {
2201
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2202
+ if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError };
2203
+ return { message: defaultError };
2204
+ } } : {}
2205
+ });
2206
+ }
2207
+ strip() {
2208
+ return new ZodObject({
2209
+ ...this._def,
2210
+ unknownKeys: "strip"
2211
+ });
2212
+ }
2213
+ passthrough() {
2214
+ return new ZodObject({
2215
+ ...this._def,
2216
+ unknownKeys: "passthrough"
2217
+ });
2218
+ }
2219
+ extend(augmentation) {
2220
+ return new ZodObject({
2221
+ ...this._def,
2222
+ shape: () => ({
2223
+ ...this._def.shape(),
2224
+ ...augmentation
2225
+ })
2226
+ });
2227
+ }
2228
+ /**
2229
+ * Prior to zod@1.0.12 there was a bug in the
2230
+ * inferred type of merged objects. Please
2231
+ * upgrade if you are experiencing issues.
2232
+ */
2233
+ merge(merging) {
2234
+ return new ZodObject({
2235
+ unknownKeys: merging._def.unknownKeys,
2236
+ catchall: merging._def.catchall,
2237
+ shape: () => ({
2238
+ ...this._def.shape(),
2239
+ ...merging._def.shape()
2240
+ }),
2241
+ typeName: ZodFirstPartyTypeKind.ZodObject
2242
+ });
2243
+ }
2244
+ setKey(key, schema) {
2245
+ return this.augment({ [key]: schema });
2246
+ }
2247
+ catchall(index) {
2248
+ return new ZodObject({
2249
+ ...this._def,
2250
+ catchall: index
2251
+ });
2252
+ }
2253
+ pick(mask) {
2254
+ const shape = {};
2255
+ for (const key of util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
2256
+ return new ZodObject({
2257
+ ...this._def,
2258
+ shape: () => shape
2259
+ });
2260
+ }
2261
+ omit(mask) {
2262
+ const shape = {};
2263
+ for (const key of util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key];
2264
+ return new ZodObject({
2265
+ ...this._def,
2266
+ shape: () => shape
2267
+ });
2268
+ }
2269
+ /**
2270
+ * @deprecated
2271
+ */
2272
+ deepPartial() {
2273
+ return deepPartialify(this);
2274
+ }
2275
+ partial(mask) {
2276
+ const newShape = {};
2277
+ for (const key of util.objectKeys(this.shape)) {
2278
+ const fieldSchema = this.shape[key];
2279
+ if (mask && !mask[key]) newShape[key] = fieldSchema;
2280
+ else newShape[key] = fieldSchema.optional();
2281
+ }
2282
+ return new ZodObject({
2283
+ ...this._def,
2284
+ shape: () => newShape
2285
+ });
2286
+ }
2287
+ required(mask) {
2288
+ const newShape = {};
2289
+ for (const key of util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key];
2290
+ else {
2291
+ let newField = this.shape[key];
2292
+ while (newField instanceof ZodOptional) newField = newField._def.innerType;
2293
+ newShape[key] = newField;
2294
+ }
2295
+ return new ZodObject({
2296
+ ...this._def,
2297
+ shape: () => newShape
2298
+ });
2299
+ }
2300
+ keyof() {
2301
+ return createZodEnum(util.objectKeys(this.shape));
2302
+ }
2303
+ };
2304
+ ZodObject.create = (shape, params) => {
2305
+ return new ZodObject({
2306
+ shape: () => shape,
2307
+ unknownKeys: "strip",
2308
+ catchall: ZodNever.create(),
2309
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2310
+ ...processCreateParams(params)
2311
+ });
2312
+ };
2313
+ ZodObject.strictCreate = (shape, params) => {
2314
+ return new ZodObject({
2315
+ shape: () => shape,
2316
+ unknownKeys: "strict",
2317
+ catchall: ZodNever.create(),
2318
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2319
+ ...processCreateParams(params)
2320
+ });
2321
+ };
2322
+ ZodObject.lazycreate = (shape, params) => {
2323
+ return new ZodObject({
2324
+ shape,
2325
+ unknownKeys: "strip",
2326
+ catchall: ZodNever.create(),
2327
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2328
+ ...processCreateParams(params)
2329
+ });
2330
+ };
2331
+ var ZodUnion = class extends ZodType {
2332
+ _parse(input) {
2333
+ const { ctx } = this._processInputParams(input);
2334
+ const options = this._def.options;
2335
+ function handleResults(results) {
2336
+ for (const result of results) if (result.result.status === "valid") return result.result;
2337
+ for (const result of results) if (result.result.status === "dirty") {
2338
+ ctx.common.issues.push(...result.ctx.common.issues);
2339
+ return result.result;
2340
+ }
2341
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2342
+ addIssueToContext(ctx, {
2343
+ code: ZodIssueCode.invalid_union,
2344
+ unionErrors
2345
+ });
2346
+ return INVALID;
2347
+ }
2348
+ if (ctx.common.async) return Promise.all(options.map(async (option) => {
2349
+ const childCtx = {
2350
+ ...ctx,
2351
+ common: {
2352
+ ...ctx.common,
2353
+ issues: []
2354
+ },
2355
+ parent: null
2356
+ };
2357
+ return {
2358
+ result: await option._parseAsync({
2359
+ data: ctx.data,
2360
+ path: ctx.path,
2361
+ parent: childCtx
2362
+ }),
2363
+ ctx: childCtx
2364
+ };
2365
+ })).then(handleResults);
2366
+ else {
2367
+ let dirty = void 0;
2368
+ const issues = [];
2369
+ for (const option of options) {
2370
+ const childCtx = {
2371
+ ...ctx,
2372
+ common: {
2373
+ ...ctx.common,
2374
+ issues: []
2375
+ },
2376
+ parent: null
2377
+ };
2378
+ const result = option._parseSync({
2379
+ data: ctx.data,
2380
+ path: ctx.path,
2381
+ parent: childCtx
2382
+ });
2383
+ if (result.status === "valid") return result;
2384
+ else if (result.status === "dirty" && !dirty) dirty = {
2385
+ result,
2386
+ ctx: childCtx
2387
+ };
2388
+ if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
2389
+ }
2390
+ if (dirty) {
2391
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2392
+ return dirty.result;
2393
+ }
2394
+ const unionErrors = issues.map((issues) => new ZodError(issues));
2395
+ addIssueToContext(ctx, {
2396
+ code: ZodIssueCode.invalid_union,
2397
+ unionErrors
2398
+ });
2399
+ return INVALID;
2400
+ }
2401
+ }
2402
+ get options() {
2403
+ return this._def.options;
2404
+ }
2405
+ };
2406
+ ZodUnion.create = (types, params) => {
2407
+ return new ZodUnion({
2408
+ options: types,
2409
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2410
+ ...processCreateParams(params)
2411
+ });
2412
+ };
2413
+ var getDiscriminator = (type) => {
2414
+ if (type instanceof ZodLazy) return getDiscriminator(type.schema);
2415
+ else if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
2416
+ else if (type instanceof ZodLiteral) return [type.value];
2417
+ else if (type instanceof ZodEnum) return type.options;
2418
+ else if (type instanceof ZodNativeEnum) return util.objectValues(type.enum);
2419
+ else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
2420
+ else if (type instanceof ZodUndefined) return [void 0];
2421
+ else if (type instanceof ZodNull) return [null];
2422
+ else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())];
2423
+ else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())];
2424
+ else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
2425
+ else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
2426
+ else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
2427
+ else return [];
2428
+ };
2429
+ var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
2430
+ _parse(input) {
2431
+ const { ctx } = this._processInputParams(input);
2432
+ if (ctx.parsedType !== ZodParsedType.object) {
2433
+ addIssueToContext(ctx, {
2434
+ code: ZodIssueCode.invalid_type,
2435
+ expected: ZodParsedType.object,
2436
+ received: ctx.parsedType
2437
+ });
2438
+ return INVALID;
2439
+ }
2440
+ const discriminator = this.discriminator;
2441
+ const discriminatorValue = ctx.data[discriminator];
2442
+ const option = this.optionsMap.get(discriminatorValue);
2443
+ if (!option) {
2444
+ addIssueToContext(ctx, {
2445
+ code: ZodIssueCode.invalid_union_discriminator,
2446
+ options: Array.from(this.optionsMap.keys()),
2447
+ path: [discriminator]
2448
+ });
2449
+ return INVALID;
2450
+ }
2451
+ if (ctx.common.async) return option._parseAsync({
2452
+ data: ctx.data,
2453
+ path: ctx.path,
2454
+ parent: ctx
2455
+ });
2456
+ else return option._parseSync({
2457
+ data: ctx.data,
2458
+ path: ctx.path,
2459
+ parent: ctx
2460
+ });
2461
+ }
2462
+ get discriminator() {
2463
+ return this._def.discriminator;
2464
+ }
2465
+ get options() {
2466
+ return this._def.options;
2467
+ }
2468
+ get optionsMap() {
2469
+ return this._def.optionsMap;
2470
+ }
2471
+ /**
2472
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2473
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2474
+ * have a different value for each object in the union.
2475
+ * @param discriminator the name of the discriminator property
2476
+ * @param types an array of object schemas
2477
+ * @param params
2478
+ */
2479
+ static create(discriminator, options, params) {
2480
+ const optionsMap = /* @__PURE__ */ new Map();
2481
+ for (const type of options) {
2482
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2483
+ if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2484
+ for (const value of discriminatorValues) {
2485
+ if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2486
+ optionsMap.set(value, type);
2487
+ }
2488
+ }
2489
+ return new ZodDiscriminatedUnion({
2490
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2491
+ discriminator,
2492
+ options,
2493
+ optionsMap,
2494
+ ...processCreateParams(params)
2495
+ });
2496
+ }
2497
+ };
2498
+ function mergeValues(a, b) {
2499
+ const aType = getParsedType(a);
2500
+ const bType = getParsedType(b);
2501
+ if (a === b) return {
2502
+ valid: true,
2503
+ data: a
2504
+ };
2505
+ else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2506
+ const bKeys = util.objectKeys(b);
2507
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2508
+ const newObj = {
2509
+ ...a,
2510
+ ...b
2511
+ };
2512
+ for (const key of sharedKeys) {
2513
+ const sharedValue = mergeValues(a[key], b[key]);
2514
+ if (!sharedValue.valid) return { valid: false };
2515
+ newObj[key] = sharedValue.data;
2516
+ }
2517
+ return {
2518
+ valid: true,
2519
+ data: newObj
2520
+ };
2521
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2522
+ if (a.length !== b.length) return { valid: false };
2523
+ const newArray = [];
2524
+ for (let index = 0; index < a.length; index++) {
2525
+ const itemA = a[index];
2526
+ const itemB = b[index];
2527
+ const sharedValue = mergeValues(itemA, itemB);
2528
+ if (!sharedValue.valid) return { valid: false };
2529
+ newArray.push(sharedValue.data);
2530
+ }
2531
+ return {
2532
+ valid: true,
2533
+ data: newArray
2534
+ };
2535
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return {
2536
+ valid: true,
2537
+ data: a
2538
+ };
2539
+ else return { valid: false };
2540
+ }
2541
+ var ZodIntersection = class extends ZodType {
2542
+ _parse(input) {
2543
+ const { status, ctx } = this._processInputParams(input);
2544
+ const handleParsed = (parsedLeft, parsedRight) => {
2545
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID;
2546
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
2547
+ if (!merged.valid) {
2548
+ addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types });
2549
+ return INVALID;
2550
+ }
2551
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty();
2552
+ return {
2553
+ status: status.value,
2554
+ value: merged.data
2555
+ };
2556
+ };
2557
+ if (ctx.common.async) return Promise.all([this._def.left._parseAsync({
2558
+ data: ctx.data,
2559
+ path: ctx.path,
2560
+ parent: ctx
2561
+ }), this._def.right._parseAsync({
2562
+ data: ctx.data,
2563
+ path: ctx.path,
2564
+ parent: ctx
2565
+ })]).then(([left, right]) => handleParsed(left, right));
2566
+ else return handleParsed(this._def.left._parseSync({
2567
+ data: ctx.data,
2568
+ path: ctx.path,
2569
+ parent: ctx
2570
+ }), this._def.right._parseSync({
2571
+ data: ctx.data,
2572
+ path: ctx.path,
2573
+ parent: ctx
2574
+ }));
2575
+ }
2576
+ };
2577
+ ZodIntersection.create = (left, right, params) => {
2578
+ return new ZodIntersection({
2579
+ left,
2580
+ right,
2581
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
2582
+ ...processCreateParams(params)
2583
+ });
2584
+ };
2585
+ var ZodTuple = class ZodTuple extends ZodType {
2586
+ _parse(input) {
2587
+ const { status, ctx } = this._processInputParams(input);
2588
+ if (ctx.parsedType !== ZodParsedType.array) {
2589
+ addIssueToContext(ctx, {
2590
+ code: ZodIssueCode.invalid_type,
2591
+ expected: ZodParsedType.array,
2592
+ received: ctx.parsedType
2593
+ });
2594
+ return INVALID;
2595
+ }
2596
+ if (ctx.data.length < this._def.items.length) {
2597
+ addIssueToContext(ctx, {
2598
+ code: ZodIssueCode.too_small,
2599
+ minimum: this._def.items.length,
2600
+ inclusive: true,
2601
+ exact: false,
2602
+ type: "array"
2603
+ });
2604
+ return INVALID;
2605
+ }
2606
+ if (!this._def.rest && ctx.data.length > this._def.items.length) {
2607
+ addIssueToContext(ctx, {
2608
+ code: ZodIssueCode.too_big,
2609
+ maximum: this._def.items.length,
2610
+ inclusive: true,
2611
+ exact: false,
2612
+ type: "array"
2613
+ });
2614
+ status.dirty();
2615
+ }
2616
+ const items = [...ctx.data].map((item, itemIndex) => {
2617
+ const schema = this._def.items[itemIndex] || this._def.rest;
2618
+ if (!schema) return null;
2619
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2620
+ }).filter((x) => !!x);
2621
+ if (ctx.common.async) return Promise.all(items).then((results) => {
2622
+ return ParseStatus.mergeArray(status, results);
2623
+ });
2624
+ else return ParseStatus.mergeArray(status, items);
2625
+ }
2626
+ get items() {
2627
+ return this._def.items;
2628
+ }
2629
+ rest(rest) {
2630
+ return new ZodTuple({
2631
+ ...this._def,
2632
+ rest
2633
+ });
2634
+ }
2635
+ };
2636
+ ZodTuple.create = (schemas, params) => {
2637
+ if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2638
+ return new ZodTuple({
2639
+ items: schemas,
2640
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
2641
+ rest: null,
2642
+ ...processCreateParams(params)
2643
+ });
2644
+ };
2645
+ var ZodRecord = class ZodRecord extends ZodType {
2646
+ get keySchema() {
2647
+ return this._def.keyType;
2648
+ }
2649
+ get valueSchema() {
2650
+ return this._def.valueType;
2651
+ }
2652
+ _parse(input) {
2653
+ const { status, ctx } = this._processInputParams(input);
2654
+ if (ctx.parsedType !== ZodParsedType.object) {
2655
+ addIssueToContext(ctx, {
2656
+ code: ZodIssueCode.invalid_type,
2657
+ expected: ZodParsedType.object,
2658
+ received: ctx.parsedType
2659
+ });
2660
+ return INVALID;
2661
+ }
2662
+ const pairs = [];
2663
+ const keyType = this._def.keyType;
2664
+ const valueType = this._def.valueType;
2665
+ for (const key in ctx.data) pairs.push({
2666
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2667
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
2668
+ alwaysSet: key in ctx.data
2669
+ });
2670
+ if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs);
2671
+ else return ParseStatus.mergeObjectSync(status, pairs);
2672
+ }
2673
+ get element() {
2674
+ return this._def.valueType;
2675
+ }
2676
+ static create(first, second, third) {
2677
+ if (second instanceof ZodType) return new ZodRecord({
2678
+ keyType: first,
2679
+ valueType: second,
2680
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
2681
+ ...processCreateParams(third)
2682
+ });
2683
+ return new ZodRecord({
2684
+ keyType: ZodString.create(),
2685
+ valueType: first,
2686
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
2687
+ ...processCreateParams(second)
2688
+ });
2689
+ }
2690
+ };
2691
+ var ZodMap = class extends ZodType {
2692
+ get keySchema() {
2693
+ return this._def.keyType;
2694
+ }
2695
+ get valueSchema() {
2696
+ return this._def.valueType;
2697
+ }
2698
+ _parse(input) {
2699
+ const { status, ctx } = this._processInputParams(input);
2700
+ if (ctx.parsedType !== ZodParsedType.map) {
2701
+ addIssueToContext(ctx, {
2702
+ code: ZodIssueCode.invalid_type,
2703
+ expected: ZodParsedType.map,
2704
+ received: ctx.parsedType
2705
+ });
2706
+ return INVALID;
2707
+ }
2708
+ const keyType = this._def.keyType;
2709
+ const valueType = this._def.valueType;
2710
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
2711
+ return {
2712
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
2713
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
2714
+ };
2715
+ });
2716
+ if (ctx.common.async) {
2717
+ const finalMap = /* @__PURE__ */ new Map();
2718
+ return Promise.resolve().then(async () => {
2719
+ for (const pair of pairs) {
2720
+ const key = await pair.key;
2721
+ const value = await pair.value;
2722
+ if (key.status === "aborted" || value.status === "aborted") return INVALID;
2723
+ if (key.status === "dirty" || value.status === "dirty") status.dirty();
2724
+ finalMap.set(key.value, value.value);
2725
+ }
2726
+ return {
2727
+ status: status.value,
2728
+ value: finalMap
2729
+ };
2730
+ });
2731
+ } else {
2732
+ const finalMap = /* @__PURE__ */ new Map();
2733
+ for (const pair of pairs) {
2734
+ const key = pair.key;
2735
+ const value = pair.value;
2736
+ if (key.status === "aborted" || value.status === "aborted") return INVALID;
2737
+ if (key.status === "dirty" || value.status === "dirty") status.dirty();
2738
+ finalMap.set(key.value, value.value);
2739
+ }
2740
+ return {
2741
+ status: status.value,
2742
+ value: finalMap
2743
+ };
2744
+ }
2745
+ }
2746
+ };
2747
+ ZodMap.create = (keyType, valueType, params) => {
2748
+ return new ZodMap({
2749
+ valueType,
2750
+ keyType,
2751
+ typeName: ZodFirstPartyTypeKind.ZodMap,
2752
+ ...processCreateParams(params)
2753
+ });
2754
+ };
2755
+ var ZodSet = class ZodSet extends ZodType {
2756
+ _parse(input) {
2757
+ const { status, ctx } = this._processInputParams(input);
2758
+ if (ctx.parsedType !== ZodParsedType.set) {
2759
+ addIssueToContext(ctx, {
2760
+ code: ZodIssueCode.invalid_type,
2761
+ expected: ZodParsedType.set,
2762
+ received: ctx.parsedType
2763
+ });
2764
+ return INVALID;
2765
+ }
2766
+ const def = this._def;
2767
+ if (def.minSize !== null) {
2768
+ if (ctx.data.size < def.minSize.value) {
2769
+ addIssueToContext(ctx, {
2770
+ code: ZodIssueCode.too_small,
2771
+ minimum: def.minSize.value,
2772
+ type: "set",
2773
+ inclusive: true,
2774
+ exact: false,
2775
+ message: def.minSize.message
2776
+ });
2777
+ status.dirty();
2778
+ }
2779
+ }
2780
+ if (def.maxSize !== null) {
2781
+ if (ctx.data.size > def.maxSize.value) {
2782
+ addIssueToContext(ctx, {
2783
+ code: ZodIssueCode.too_big,
2784
+ maximum: def.maxSize.value,
2785
+ type: "set",
2786
+ inclusive: true,
2787
+ exact: false,
2788
+ message: def.maxSize.message
2789
+ });
2790
+ status.dirty();
2791
+ }
2792
+ }
2793
+ const valueType = this._def.valueType;
2794
+ function finalizeSet(elements) {
2795
+ const parsedSet = /* @__PURE__ */ new Set();
2796
+ for (const element of elements) {
2797
+ if (element.status === "aborted") return INVALID;
2798
+ if (element.status === "dirty") status.dirty();
2799
+ parsedSet.add(element.value);
2800
+ }
2801
+ return {
2802
+ status: status.value,
2803
+ value: parsedSet
2804
+ };
2805
+ }
2806
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
2807
+ if (ctx.common.async) return Promise.all(elements).then((elements) => finalizeSet(elements));
2808
+ else return finalizeSet(elements);
2809
+ }
2810
+ min(minSize, message) {
2811
+ return new ZodSet({
2812
+ ...this._def,
2813
+ minSize: {
2814
+ value: minSize,
2815
+ message: errorUtil.toString(message)
2816
+ }
2817
+ });
2818
+ }
2819
+ max(maxSize, message) {
2820
+ return new ZodSet({
2821
+ ...this._def,
2822
+ maxSize: {
2823
+ value: maxSize,
2824
+ message: errorUtil.toString(message)
2825
+ }
2826
+ });
2827
+ }
2828
+ size(size, message) {
2829
+ return this.min(size, message).max(size, message);
2830
+ }
2831
+ nonempty(message) {
2832
+ return this.min(1, message);
2833
+ }
2834
+ };
2835
+ ZodSet.create = (valueType, params) => {
2836
+ return new ZodSet({
2837
+ valueType,
2838
+ minSize: null,
2839
+ maxSize: null,
2840
+ typeName: ZodFirstPartyTypeKind.ZodSet,
2841
+ ...processCreateParams(params)
2842
+ });
2843
+ };
2844
+ var ZodFunction = class ZodFunction extends ZodType {
2845
+ constructor() {
2846
+ super(...arguments);
2847
+ this.validate = this.implement;
2848
+ }
2849
+ _parse(input) {
2850
+ const { ctx } = this._processInputParams(input);
2851
+ if (ctx.parsedType !== ZodParsedType.function) {
2852
+ addIssueToContext(ctx, {
2853
+ code: ZodIssueCode.invalid_type,
2854
+ expected: ZodParsedType.function,
2855
+ received: ctx.parsedType
2856
+ });
2857
+ return INVALID;
2858
+ }
2859
+ function makeArgsIssue(args, error) {
2860
+ return makeIssue({
2861
+ data: args,
2862
+ path: ctx.path,
2863
+ errorMaps: [
2864
+ ctx.common.contextualErrorMap,
2865
+ ctx.schemaErrorMap,
2866
+ getErrorMap(),
2867
+ errorMap
2868
+ ].filter((x) => !!x),
2869
+ issueData: {
2870
+ code: ZodIssueCode.invalid_arguments,
2871
+ argumentsError: error
2872
+ }
2873
+ });
2874
+ }
2875
+ function makeReturnsIssue(returns, error) {
2876
+ return makeIssue({
2877
+ data: returns,
2878
+ path: ctx.path,
2879
+ errorMaps: [
2880
+ ctx.common.contextualErrorMap,
2881
+ ctx.schemaErrorMap,
2882
+ getErrorMap(),
2883
+ errorMap
2884
+ ].filter((x) => !!x),
2885
+ issueData: {
2886
+ code: ZodIssueCode.invalid_return_type,
2887
+ returnTypeError: error
2888
+ }
2889
+ });
2890
+ }
2891
+ const params = { errorMap: ctx.common.contextualErrorMap };
2892
+ const fn = ctx.data;
2893
+ if (this._def.returns instanceof ZodPromise) {
2894
+ const me = this;
2895
+ return OK(async function(...args) {
2896
+ const error = new ZodError([]);
2897
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
2898
+ error.addIssue(makeArgsIssue(args, e));
2899
+ throw error;
2900
+ });
2901
+ const result = await Reflect.apply(fn, this, parsedArgs);
2902
+ return await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
2903
+ error.addIssue(makeReturnsIssue(result, e));
2904
+ throw error;
2905
+ });
2906
+ });
2907
+ } else {
2908
+ const me = this;
2909
+ return OK(function(...args) {
2910
+ const parsedArgs = me._def.args.safeParse(args, params);
2911
+ if (!parsedArgs.success) throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
2912
+ const result = Reflect.apply(fn, this, parsedArgs.data);
2913
+ const parsedReturns = me._def.returns.safeParse(result, params);
2914
+ if (!parsedReturns.success) throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
2915
+ return parsedReturns.data;
2916
+ });
2917
+ }
2918
+ }
2919
+ parameters() {
2920
+ return this._def.args;
2921
+ }
2922
+ returnType() {
2923
+ return this._def.returns;
2924
+ }
2925
+ args(...items) {
2926
+ return new ZodFunction({
2927
+ ...this._def,
2928
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
2929
+ });
2930
+ }
2931
+ returns(returnType) {
2932
+ return new ZodFunction({
2933
+ ...this._def,
2934
+ returns: returnType
2935
+ });
2936
+ }
2937
+ implement(func) {
2938
+ return this.parse(func);
2939
+ }
2940
+ strictImplement(func) {
2941
+ return this.parse(func);
2942
+ }
2943
+ static create(args, returns, params) {
2944
+ return new ZodFunction({
2945
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
2946
+ returns: returns || ZodUnknown.create(),
2947
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
2948
+ ...processCreateParams(params)
2949
+ });
2950
+ }
2951
+ };
2952
+ var ZodLazy = class extends ZodType {
2953
+ get schema() {
2954
+ return this._def.getter();
2955
+ }
2956
+ _parse(input) {
2957
+ const { ctx } = this._processInputParams(input);
2958
+ return this._def.getter()._parse({
2959
+ data: ctx.data,
2960
+ path: ctx.path,
2961
+ parent: ctx
2962
+ });
2963
+ }
2964
+ };
2965
+ ZodLazy.create = (getter, params) => {
2966
+ return new ZodLazy({
2967
+ getter,
2968
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
2969
+ ...processCreateParams(params)
2970
+ });
2971
+ };
2972
+ var ZodLiteral = class extends ZodType {
2973
+ _parse(input) {
2974
+ if (input.data !== this._def.value) {
2975
+ const ctx = this._getOrReturnCtx(input);
2976
+ addIssueToContext(ctx, {
2977
+ received: ctx.data,
2978
+ code: ZodIssueCode.invalid_literal,
2979
+ expected: this._def.value
2980
+ });
2981
+ return INVALID;
2982
+ }
2983
+ return {
2984
+ status: "valid",
2985
+ value: input.data
2986
+ };
2987
+ }
2988
+ get value() {
2989
+ return this._def.value;
2990
+ }
2991
+ };
2992
+ ZodLiteral.create = (value, params) => {
2993
+ return new ZodLiteral({
2994
+ value,
2995
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
2996
+ ...processCreateParams(params)
2997
+ });
2998
+ };
2999
+ function createZodEnum(values, params) {
3000
+ return new ZodEnum({
3001
+ values,
3002
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3003
+ ...processCreateParams(params)
3004
+ });
3005
+ }
3006
+ var ZodEnum = class ZodEnum extends ZodType {
3007
+ _parse(input) {
3008
+ if (typeof input.data !== "string") {
3009
+ const ctx = this._getOrReturnCtx(input);
3010
+ const expectedValues = this._def.values;
3011
+ addIssueToContext(ctx, {
3012
+ expected: util.joinValues(expectedValues),
3013
+ received: ctx.parsedType,
3014
+ code: ZodIssueCode.invalid_type
3015
+ });
3016
+ return INVALID;
3017
+ }
3018
+ if (!this._cache) this._cache = new Set(this._def.values);
3019
+ if (!this._cache.has(input.data)) {
3020
+ const ctx = this._getOrReturnCtx(input);
3021
+ const expectedValues = this._def.values;
3022
+ addIssueToContext(ctx, {
3023
+ received: ctx.data,
3024
+ code: ZodIssueCode.invalid_enum_value,
3025
+ options: expectedValues
3026
+ });
3027
+ return INVALID;
3028
+ }
3029
+ return OK(input.data);
3030
+ }
3031
+ get options() {
3032
+ return this._def.values;
3033
+ }
3034
+ get enum() {
3035
+ const enumValues = {};
3036
+ for (const val of this._def.values) enumValues[val] = val;
3037
+ return enumValues;
3038
+ }
3039
+ get Values() {
3040
+ const enumValues = {};
3041
+ for (const val of this._def.values) enumValues[val] = val;
3042
+ return enumValues;
3043
+ }
3044
+ get Enum() {
3045
+ const enumValues = {};
3046
+ for (const val of this._def.values) enumValues[val] = val;
3047
+ return enumValues;
3048
+ }
3049
+ extract(values, newDef = this._def) {
3050
+ return ZodEnum.create(values, {
3051
+ ...this._def,
3052
+ ...newDef
3053
+ });
3054
+ }
3055
+ exclude(values, newDef = this._def) {
3056
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3057
+ ...this._def,
3058
+ ...newDef
3059
+ });
3060
+ }
3061
+ };
3062
+ ZodEnum.create = createZodEnum;
3063
+ var ZodNativeEnum = class extends ZodType {
3064
+ _parse(input) {
3065
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3066
+ const ctx = this._getOrReturnCtx(input);
3067
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3068
+ const expectedValues = util.objectValues(nativeEnumValues);
3069
+ addIssueToContext(ctx, {
3070
+ expected: util.joinValues(expectedValues),
3071
+ received: ctx.parsedType,
3072
+ code: ZodIssueCode.invalid_type
3073
+ });
3074
+ return INVALID;
3075
+ }
3076
+ if (!this._cache) this._cache = new Set(util.getValidEnumValues(this._def.values));
3077
+ if (!this._cache.has(input.data)) {
3078
+ const expectedValues = util.objectValues(nativeEnumValues);
3079
+ addIssueToContext(ctx, {
3080
+ received: ctx.data,
3081
+ code: ZodIssueCode.invalid_enum_value,
3082
+ options: expectedValues
3083
+ });
3084
+ return INVALID;
3085
+ }
3086
+ return OK(input.data);
3087
+ }
3088
+ get enum() {
3089
+ return this._def.values;
3090
+ }
3091
+ };
3092
+ ZodNativeEnum.create = (values, params) => {
3093
+ return new ZodNativeEnum({
3094
+ values,
3095
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3096
+ ...processCreateParams(params)
3097
+ });
3098
+ };
3099
+ var ZodPromise = class extends ZodType {
3100
+ unwrap() {
3101
+ return this._def.type;
3102
+ }
3103
+ _parse(input) {
3104
+ const { ctx } = this._processInputParams(input);
3105
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3106
+ addIssueToContext(ctx, {
3107
+ code: ZodIssueCode.invalid_type,
3108
+ expected: ZodParsedType.promise,
3109
+ received: ctx.parsedType
3110
+ });
3111
+ return INVALID;
3112
+ }
3113
+ return OK((ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data)).then((data) => {
3114
+ return this._def.type.parseAsync(data, {
3115
+ path: ctx.path,
3116
+ errorMap: ctx.common.contextualErrorMap
3117
+ });
3118
+ }));
3119
+ }
3120
+ };
3121
+ ZodPromise.create = (schema, params) => {
3122
+ return new ZodPromise({
3123
+ type: schema,
3124
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3125
+ ...processCreateParams(params)
3126
+ });
3127
+ };
3128
+ var ZodEffects = class extends ZodType {
3129
+ innerType() {
3130
+ return this._def.schema;
3131
+ }
3132
+ sourceType() {
3133
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3134
+ }
3135
+ _parse(input) {
3136
+ const { status, ctx } = this._processInputParams(input);
3137
+ const effect = this._def.effect || null;
3138
+ const checkCtx = {
3139
+ addIssue: (arg) => {
3140
+ addIssueToContext(ctx, arg);
3141
+ if (arg.fatal) status.abort();
3142
+ else status.dirty();
3143
+ },
3144
+ get path() {
3145
+ return ctx.path;
3146
+ }
3147
+ };
3148
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3149
+ if (effect.type === "preprocess") {
3150
+ const processed = effect.transform(ctx.data, checkCtx);
3151
+ if (ctx.common.async) return Promise.resolve(processed).then(async (processed) => {
3152
+ if (status.value === "aborted") return INVALID;
3153
+ const result = await this._def.schema._parseAsync({
3154
+ data: processed,
3155
+ path: ctx.path,
3156
+ parent: ctx
3157
+ });
3158
+ if (result.status === "aborted") return INVALID;
3159
+ if (result.status === "dirty") return DIRTY(result.value);
3160
+ if (status.value === "dirty") return DIRTY(result.value);
3161
+ return result;
3162
+ });
3163
+ else {
3164
+ if (status.value === "aborted") return INVALID;
3165
+ const result = this._def.schema._parseSync({
3166
+ data: processed,
3167
+ path: ctx.path,
3168
+ parent: ctx
3169
+ });
3170
+ if (result.status === "aborted") return INVALID;
3171
+ if (result.status === "dirty") return DIRTY(result.value);
3172
+ if (status.value === "dirty") return DIRTY(result.value);
3173
+ return result;
3174
+ }
3175
+ }
3176
+ if (effect.type === "refinement") {
3177
+ const executeRefinement = (acc) => {
3178
+ const result = effect.refinement(acc, checkCtx);
3179
+ if (ctx.common.async) return Promise.resolve(result);
3180
+ if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3181
+ return acc;
3182
+ };
3183
+ if (ctx.common.async === false) {
3184
+ const inner = this._def.schema._parseSync({
3185
+ data: ctx.data,
3186
+ path: ctx.path,
3187
+ parent: ctx
3188
+ });
3189
+ if (inner.status === "aborted") return INVALID;
3190
+ if (inner.status === "dirty") status.dirty();
3191
+ executeRefinement(inner.value);
3192
+ return {
3193
+ status: status.value,
3194
+ value: inner.value
3195
+ };
3196
+ } else return this._def.schema._parseAsync({
3197
+ data: ctx.data,
3198
+ path: ctx.path,
3199
+ parent: ctx
3200
+ }).then((inner) => {
3201
+ if (inner.status === "aborted") return INVALID;
3202
+ if (inner.status === "dirty") status.dirty();
3203
+ return executeRefinement(inner.value).then(() => {
3204
+ return {
3205
+ status: status.value,
3206
+ value: inner.value
3207
+ };
3208
+ });
3209
+ });
3210
+ }
3211
+ if (effect.type === "transform") {
3212
+ if (ctx.common.async === false) {
3213
+ const base = this._def.schema._parseSync({
3214
+ data: ctx.data,
3215
+ path: ctx.path,
3216
+ parent: ctx
3217
+ });
3218
+ if (!isValid(base)) return INVALID;
3219
+ const result = effect.transform(base.value, checkCtx);
3220
+ if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3221
+ return {
3222
+ status: status.value,
3223
+ value: result
3224
+ };
3225
+ } else return this._def.schema._parseAsync({
3226
+ data: ctx.data,
3227
+ path: ctx.path,
3228
+ parent: ctx
3229
+ }).then((base) => {
3230
+ if (!isValid(base)) return INVALID;
3231
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3232
+ status: status.value,
3233
+ value: result
3234
+ }));
3235
+ });
3236
+ }
3237
+ util.assertNever(effect);
3238
+ }
3239
+ };
3240
+ ZodEffects.create = (schema, effect, params) => {
3241
+ return new ZodEffects({
3242
+ schema,
3243
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3244
+ effect,
3245
+ ...processCreateParams(params)
3246
+ });
3247
+ };
3248
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3249
+ return new ZodEffects({
3250
+ schema,
3251
+ effect: {
3252
+ type: "preprocess",
3253
+ transform: preprocess
3254
+ },
3255
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3256
+ ...processCreateParams(params)
3257
+ });
3258
+ };
3259
+ var ZodOptional = class extends ZodType {
3260
+ _parse(input) {
3261
+ if (this._getType(input) === ZodParsedType.undefined) return OK(void 0);
3262
+ return this._def.innerType._parse(input);
3263
+ }
3264
+ unwrap() {
3265
+ return this._def.innerType;
3266
+ }
3267
+ };
3268
+ ZodOptional.create = (type, params) => {
3269
+ return new ZodOptional({
3270
+ innerType: type,
3271
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3272
+ ...processCreateParams(params)
3273
+ });
3274
+ };
3275
+ var ZodNullable = class extends ZodType {
3276
+ _parse(input) {
3277
+ if (this._getType(input) === ZodParsedType.null) return OK(null);
3278
+ return this._def.innerType._parse(input);
3279
+ }
3280
+ unwrap() {
3281
+ return this._def.innerType;
3282
+ }
3283
+ };
3284
+ ZodNullable.create = (type, params) => {
3285
+ return new ZodNullable({
3286
+ innerType: type,
3287
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3288
+ ...processCreateParams(params)
3289
+ });
3290
+ };
3291
+ var ZodDefault = class extends ZodType {
3292
+ _parse(input) {
3293
+ const { ctx } = this._processInputParams(input);
3294
+ let data = ctx.data;
3295
+ if (ctx.parsedType === ZodParsedType.undefined) data = this._def.defaultValue();
3296
+ return this._def.innerType._parse({
3297
+ data,
3298
+ path: ctx.path,
3299
+ parent: ctx
3300
+ });
3301
+ }
3302
+ removeDefault() {
3303
+ return this._def.innerType;
3304
+ }
3305
+ };
3306
+ ZodDefault.create = (type, params) => {
3307
+ return new ZodDefault({
3308
+ innerType: type,
3309
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3310
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3311
+ ...processCreateParams(params)
3312
+ });
3313
+ };
3314
+ var ZodCatch = class extends ZodType {
3315
+ _parse(input) {
3316
+ const { ctx } = this._processInputParams(input);
3317
+ const newCtx = {
3318
+ ...ctx,
3319
+ common: {
3320
+ ...ctx.common,
3321
+ issues: []
3322
+ }
3323
+ };
3324
+ const result = this._def.innerType._parse({
3325
+ data: newCtx.data,
3326
+ path: newCtx.path,
3327
+ parent: { ...newCtx }
3328
+ });
3329
+ if (isAsync(result)) return result.then((result) => {
3330
+ return {
3331
+ status: "valid",
3332
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3333
+ get error() {
3334
+ return new ZodError(newCtx.common.issues);
3335
+ },
3336
+ input: newCtx.data
3337
+ })
3338
+ };
3339
+ });
3340
+ else return {
3341
+ status: "valid",
3342
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3343
+ get error() {
3344
+ return new ZodError(newCtx.common.issues);
3345
+ },
3346
+ input: newCtx.data
3347
+ })
3348
+ };
3349
+ }
3350
+ removeCatch() {
3351
+ return this._def.innerType;
3352
+ }
3353
+ };
3354
+ ZodCatch.create = (type, params) => {
3355
+ return new ZodCatch({
3356
+ innerType: type,
3357
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3358
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3359
+ ...processCreateParams(params)
3360
+ });
3361
+ };
3362
+ var ZodNaN = class extends ZodType {
3363
+ _parse(input) {
3364
+ if (this._getType(input) !== ZodParsedType.nan) {
3365
+ const ctx = this._getOrReturnCtx(input);
3366
+ addIssueToContext(ctx, {
3367
+ code: ZodIssueCode.invalid_type,
3368
+ expected: ZodParsedType.nan,
3369
+ received: ctx.parsedType
3370
+ });
3371
+ return INVALID;
3372
+ }
3373
+ return {
3374
+ status: "valid",
3375
+ value: input.data
3376
+ };
3377
+ }
3378
+ };
3379
+ ZodNaN.create = (params) => {
3380
+ return new ZodNaN({
3381
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3382
+ ...processCreateParams(params)
3383
+ });
3384
+ };
3385
+ var ZodBranded = class extends ZodType {
3386
+ _parse(input) {
3387
+ const { ctx } = this._processInputParams(input);
3388
+ const data = ctx.data;
3389
+ return this._def.type._parse({
3390
+ data,
3391
+ path: ctx.path,
3392
+ parent: ctx
3393
+ });
3394
+ }
3395
+ unwrap() {
3396
+ return this._def.type;
3397
+ }
3398
+ };
3399
+ var ZodPipeline = class ZodPipeline extends ZodType {
3400
+ _parse(input) {
3401
+ const { status, ctx } = this._processInputParams(input);
3402
+ if (ctx.common.async) {
3403
+ const handleAsync = async () => {
3404
+ const inResult = await this._def.in._parseAsync({
3405
+ data: ctx.data,
3406
+ path: ctx.path,
3407
+ parent: ctx
3408
+ });
3409
+ if (inResult.status === "aborted") return INVALID;
3410
+ if (inResult.status === "dirty") {
3411
+ status.dirty();
3412
+ return DIRTY(inResult.value);
3413
+ } else return this._def.out._parseAsync({
3414
+ data: inResult.value,
3415
+ path: ctx.path,
3416
+ parent: ctx
3417
+ });
3418
+ };
3419
+ return handleAsync();
3420
+ } else {
3421
+ const inResult = this._def.in._parseSync({
3422
+ data: ctx.data,
3423
+ path: ctx.path,
3424
+ parent: ctx
3425
+ });
3426
+ if (inResult.status === "aborted") return INVALID;
3427
+ if (inResult.status === "dirty") {
3428
+ status.dirty();
3429
+ return {
3430
+ status: "dirty",
3431
+ value: inResult.value
3432
+ };
3433
+ } else return this._def.out._parseSync({
3434
+ data: inResult.value,
3435
+ path: ctx.path,
3436
+ parent: ctx
3437
+ });
3438
+ }
3439
+ }
3440
+ static create(a, b) {
3441
+ return new ZodPipeline({
3442
+ in: a,
3443
+ out: b,
3444
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
3445
+ });
3446
+ }
3447
+ };
3448
+ var ZodReadonly = class extends ZodType {
3449
+ _parse(input) {
3450
+ const result = this._def.innerType._parse(input);
3451
+ const freeze = (data) => {
3452
+ if (isValid(data)) data.value = Object.freeze(data.value);
3453
+ return data;
3454
+ };
3455
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3456
+ }
3457
+ unwrap() {
3458
+ return this._def.innerType;
3459
+ }
3460
+ };
3461
+ ZodReadonly.create = (type, params) => {
3462
+ return new ZodReadonly({
3463
+ innerType: type,
3464
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
3465
+ ...processCreateParams(params)
3466
+ });
3467
+ };
3468
+ ZodObject.lazycreate;
3469
+ var ZodFirstPartyTypeKind;
3470
+ (function(ZodFirstPartyTypeKind) {
3471
+ ZodFirstPartyTypeKind["ZodString"] = "ZodString";
3472
+ ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
3473
+ ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
3474
+ ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
3475
+ ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
3476
+ ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
3477
+ ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
3478
+ ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
3479
+ ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
3480
+ ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
3481
+ ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
3482
+ ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
3483
+ ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
3484
+ ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
3485
+ ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
3486
+ ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
3487
+ ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3488
+ ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
3489
+ ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
3490
+ ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
3491
+ ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
3492
+ ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
3493
+ ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
3494
+ ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
3495
+ ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
3496
+ ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
3497
+ ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
3498
+ ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
3499
+ ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
3500
+ ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
3501
+ ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
3502
+ ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
3503
+ ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
3504
+ ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
3505
+ ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
3506
+ ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
3507
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3508
+ var stringType = ZodString.create;
3509
+ var numberType = ZodNumber.create;
3510
+ ZodNaN.create;
3511
+ ZodBigInt.create;
3512
+ var booleanType = ZodBoolean.create;
3513
+ ZodDate.create;
3514
+ ZodSymbol.create;
3515
+ ZodUndefined.create;
3516
+ var nullType = ZodNull.create;
3517
+ ZodAny.create;
3518
+ ZodUnknown.create;
3519
+ ZodNever.create;
3520
+ ZodVoid.create;
3521
+ var arrayType = ZodArray.create;
3522
+ var objectType = ZodObject.create;
3523
+ ZodObject.strictCreate;
3524
+ var unionType = ZodUnion.create;
3525
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
3526
+ ZodIntersection.create;
3527
+ ZodTuple.create;
3528
+ var recordType = ZodRecord.create;
3529
+ ZodMap.create;
3530
+ ZodSet.create;
3531
+ ZodFunction.create;
3532
+ ZodLazy.create;
3533
+ var literalType = ZodLiteral.create;
3534
+ var enumType = ZodEnum.create;
3535
+ ZodNativeEnum.create;
3536
+ ZodPromise.create;
3537
+ ZodEffects.create;
3538
+ ZodOptional.create;
3539
+ ZodNullable.create;
3540
+ ZodEffects.createWithPreprocess;
3541
+ ZodPipeline.create;
3542
+ // ../../packages/schema/src/core.ts
3543
+ /** Occurrences in the trailing 24h window. */
3544
+ var DEFAULT_SEVERITY_THRESHOLDS = {
3545
+ critical: 100,
3546
+ high: 25,
3547
+ medium: 5
3548
+ };
3549
+ function severityFromCount(count, t = DEFAULT_SEVERITY_THRESHOLDS) {
3550
+ if (count >= t.critical) return "critical";
3551
+ if (count >= t.high) return "high";
3552
+ if (count >= t.medium) return "medium";
3553
+ return "low";
3554
+ }
3555
+ var SEVERITY_ORDER = {
3556
+ critical: 3,
3557
+ high: 2,
3558
+ medium: 1,
3559
+ low: 0
3560
+ };
3561
+ var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
3562
+ var GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
3563
+ var NOT_IN_APP = [
3564
+ /node_modules/,
3565
+ /\bnative\b/,
3566
+ /\[native code\]/,
3567
+ /InternalBytecode/
3568
+ ];
3569
+ /**
3570
+ * React Native ships one JS bundle, so every frame points at it: in development a Metro URL
3571
+ * (".../entry.bundle//&platform=ios&dev=true..."), in release "address at index.android.bundle"
3572
+ * or "main.jsbundle". We can't tell app code from library code without source maps, so bundle
3573
+ * frames count as in-app and the function name carries the signal.
3574
+ */
3575
+ var RN_BUNDLE = /\.(?:js)?bundle\b/;
3576
+ function cleanFile(file) {
3577
+ return file.replace(/^address at /, "");
3578
+ }
3579
+ function parseStack(stack) {
3580
+ if (!stack) return [];
3581
+ const frames = [];
3582
+ for (const raw of stack.split("\n")) {
3583
+ const m = V8.exec(raw) ?? GECKO.exec(raw);
3584
+ if (!m) continue;
3585
+ const [, fn, rawFile, line, col] = m;
3586
+ const file = cleanFile(rawFile ?? "");
3587
+ frames.push({
3588
+ fn: fn || void 0,
3589
+ file,
3590
+ line: Number(line),
3591
+ col: Number(col),
3592
+ inApp: RN_BUNDLE.test(file) ? !/^(?:anonymous|eval|global code)$/.test(fn ?? "") : !NOT_IN_APP.some((re) => re.test(file))
3593
+ });
3594
+ if (frames.length >= 100) break;
3595
+ }
3596
+ return frames;
3597
+ }
3598
+ // ../../packages/schema/src/index.ts
3599
+ /** Dotted, lowercase identifier for a part of the app, e.g. "auth.login". */
3600
+ var Flow = stringType().min(1).max(64).regex(/^[a-z0-9_]+(\.[a-z0-9_]+)*$/, "flow must be dotted lowercase, e.g. auth.login");
3601
+ var Tags = recordType(stringType().max(200)).optional();
3602
+ var Iso = stringType().datetime({ offset: true });
3603
+ var Device = objectType({
3604
+ model: stringType().optional(),
3605
+ manufacturer: stringType().optional(),
3606
+ brand: stringType().optional(),
3607
+ type: enumType([
3608
+ "phone",
3609
+ "tablet",
3610
+ "desktop",
3611
+ "tv",
3612
+ "unknown"
3613
+ ]).default("unknown"),
3614
+ isEmulator: booleanType().optional(),
3615
+ memoryMb: numberType().optional(),
3616
+ screen: objectType({
3617
+ width: numberType(),
3618
+ height: numberType(),
3619
+ scale: numberType().optional()
3620
+ }).optional()
3621
+ });
3622
+ var Os = objectType({
3623
+ name: stringType(),
3624
+ version: stringType().optional()
3625
+ });
3626
+ var AppInfo = objectType({
3627
+ id: stringType().min(1),
3628
+ version: stringType().optional(),
3629
+ build: stringType().optional(),
3630
+ environment: stringType().default("production")
3631
+ });
3632
+ var Runtime = objectType({
3633
+ name: stringType(),
3634
+ version: stringType().optional(),
3635
+ engine: stringType().optional()
3636
+ });
3637
+ var Network = objectType({
3638
+ type: enumType([
3639
+ "wifi",
3640
+ "cellular",
3641
+ "ethernet",
3642
+ "none",
3643
+ "unknown"
3644
+ ]).default("unknown"),
3645
+ effectiveType: stringType().optional(),
3646
+ isConnected: booleanType().optional()
3647
+ });
3648
+ var Context = objectType({
3649
+ app: AppInfo,
3650
+ device: Device.default({}),
3651
+ os: Os,
3652
+ runtime: Runtime,
3653
+ network: Network.optional(),
3654
+ locale: stringType().optional(),
3655
+ timezone: stringType().optional()
3656
+ });
3657
+ var Breadcrumb = objectType({
3658
+ ts: Iso,
3659
+ category: enumType([
3660
+ "navigation",
3661
+ "network",
3662
+ "ui",
3663
+ "log",
3664
+ "event",
3665
+ "custom"
3666
+ ]),
3667
+ message: stringType().max(500),
3668
+ level: enumType([
3669
+ "debug",
3670
+ "info",
3671
+ "warning",
3672
+ "error"
3673
+ ]).default("info"),
3674
+ data: recordType(unionType([
3675
+ stringType(),
3676
+ numberType(),
3677
+ booleanType(),
3678
+ nullType()
3679
+ ])).optional()
3680
+ });
3681
+ var StackFrame = objectType({
3682
+ fn: stringType().optional(),
3683
+ file: stringType().optional(),
3684
+ line: numberType().optional(),
3685
+ col: numberType().optional(),
3686
+ inApp: booleanType().optional()
3687
+ });
3688
+ var Severity = enumType([
3689
+ "low",
3690
+ "medium",
3691
+ "high",
3692
+ "critical"
3693
+ ]);
3694
+ var EventBase = objectType({
3695
+ id: stringType().min(8).max(64),
3696
+ ts: Iso,
3697
+ flow: Flow.optional(),
3698
+ step: stringType().max(64).optional(),
3699
+ tags: Tags
3700
+ });
3701
+ var Event = discriminatedUnionType("type", [
3702
+ EventBase.extend({
3703
+ type: literalType("error"),
3704
+ handled: booleanType().default(true),
3705
+ /** Developer's override. Otherwise severity is derived from occurrence counts. */
3706
+ severity: Severity.optional(),
3707
+ error: objectType({
3708
+ name: stringType().max(200).default("Error"),
3709
+ message: stringType().max(2e3),
3710
+ stack: stringType().max(2e4).optional(),
3711
+ frames: arrayType(StackFrame).max(100).optional()
3712
+ }),
3713
+ breadcrumbs: arrayType(Breadcrumb).max(50).optional(),
3714
+ /** Set when the error is a failed HTTP request captured by the SDK's network instrumentation. */
3715
+ request: objectType({
3716
+ method: stringType().max(10),
3717
+ /** Path without query string or fragment, ids replaced with :id, e.g. "/v1/orders/:id". */
3718
+ url: stringType().max(500),
3719
+ status: numberType().int().optional(),
3720
+ durationMs: numberType().optional()
3721
+ }).optional()
3722
+ }),
3723
+ EventBase.extend({
3724
+ type: literalType("event"),
3725
+ name: stringType().min(1).max(100),
3726
+ outcome: enumType([
3727
+ "success",
3728
+ "failure",
3729
+ "abandoned"
3730
+ ]).optional(),
3731
+ props: recordType(unionType([
3732
+ stringType(),
3733
+ numberType(),
3734
+ booleanType(),
3735
+ nullType()
3736
+ ])).optional()
3737
+ }),
3738
+ EventBase.extend({
3739
+ type: literalType("session"),
3740
+ status: enumType([
3741
+ "started",
3742
+ "errored",
3743
+ "crashed"
3744
+ ])
3745
+ })
3746
+ ]);
3747
+ var Envelope = objectType({
3748
+ schema: literalType(1).default(1),
3749
+ sdk: objectType({
3750
+ name: stringType(),
3751
+ version: stringType()
3752
+ }),
3753
+ context: Context,
3754
+ user: objectType({
3755
+ id: stringType().optional(),
3756
+ anonymousId: stringType()
3757
+ }).optional(),
3758
+ session: objectType({
3759
+ id: stringType(),
3760
+ startedAt: Iso
3761
+ }),
3762
+ events: arrayType(Event).min(1).max(100)
3763
+ });
3764
+ // src/server/config.ts
3765
+ var loaded = false;
3766
+ function loadEnv() {
3767
+ if (loaded) return;
3768
+ loaded = true;
3769
+ try {
3770
+ process.loadEnvFile?.(process.env.DEBUG_ENV_FILE ?? ".env");
3771
+ } catch {}
3772
+ }
3773
+ var generatedSecret;
3774
+ function config() {
3775
+ loadEnv();
3776
+ const env = process.env;
3777
+ const store = env.DEBUG_STORE ?? "demo";
3778
+ let secret = env.DEBUG_SESSION_SECRET;
3779
+ if (!secret || secret.length < 32) {
3780
+ if (store !== "demo" && store !== "memory") throw new Error("DEBUG_SESSION_SECRET must be set (≥32 chars) when not in demo mode. Try: openssl rand -hex 32");
3781
+ secret = generatedSecret ??= randomBytes(32).toString("hex");
3782
+ }
3783
+ const num = (v, d) => v && !Number.isNaN(Number(v)) ? Number(v) : d;
3784
+ const severity = {
3785
+ critical: num(env.DEBUG_SEVERITY_CRITICAL, DEFAULT_SEVERITY_THRESHOLDS.critical),
3786
+ high: num(env.DEBUG_SEVERITY_HIGH, DEFAULT_SEVERITY_THRESHOLDS.high),
3787
+ medium: num(env.DEBUG_SEVERITY_MEDIUM, DEFAULT_SEVERITY_THRESHOLDS.medium)
3788
+ };
3789
+ return {
3790
+ store,
3791
+ sessionSecret: secret,
3792
+ users: env.DEBUG_DASHBOARD_USERS ?? "",
3793
+ apiToken: env.DEBUG_API_TOKEN,
3794
+ /** Demo mode: keys accepted by POST /api/ingest. "*" = any app. */
3795
+ localIngestKeys: env.DEBUG_LOCAL_INGEST_KEYS ?? "pk_local:*",
3796
+ firestoreRoot: env.DEBUG_FIRESTORE_ROOT ?? "debug_apps",
3797
+ dynamoTable: env.DEBUG_DYNAMO_TABLE ?? "debug",
3798
+ severity,
3799
+ secureCookies: env.NODE_ENV === "production" && env.DEBUG_INSECURE_COOKIES !== "1"
3800
+ };
3801
+ }
3802
+ // src/server/store.ts
3803
+ var store;
3804
+ /** The dashboard only ever reads. Point it at read-only credentials. */
3805
+ function getStore() {
3806
+ return store ??= create();
3807
+ }
3808
+ /**
3809
+ * Demo mode only: the in-memory store also accepts events, so a local app can send to
3810
+ * http://localhost:4400/api/ingest and see them on the dashboard. Real stores stay read-only.
3811
+ */
3812
+ async function getLocalWriteStore() {
3813
+ const kind = config().store;
3814
+ if (kind !== "demo" && kind !== "memory") return null;
3815
+ return await getStore();
3816
+ }
3817
+ async function create() {
3818
+ const cfg = config();
3819
+ switch (cfg.store) {
3820
+ case "firestore": {
3821
+ const { initializeApp, getApps } = await import("firebase-admin/app");
3822
+ const { getFirestore } = await import("firebase-admin/firestore");
3823
+ const { FirestoreStore } = await import("./firestore-BH-gx9no.js");
3824
+ if (!getApps().length) initializeApp();
3825
+ return new FirestoreStore(getFirestore(), { root: cfg.firestoreRoot });
3826
+ }
3827
+ case "dynamodb": {
3828
+ const { DynamoDBClient } = await import("@aws-sdk/client-dynamodb");
3829
+ const { DynamoDBDocumentClient } = await import("@aws-sdk/lib-dynamodb");
3830
+ const { DynamoStore } = await import("./dynamodb-DejcakaF.js");
3831
+ return new DynamoStore(DynamoDBDocumentClient.from(new DynamoDBClient({})), { table: cfg.dynamoTable });
3832
+ }
3833
+ case "memory": {
3834
+ const { MemoryStore } = await import("./memory-4DwW5cTO.js");
3835
+ return new MemoryStore();
3836
+ }
3837
+ default: {
3838
+ const { seedDemo } = await import("./demo-DTdlXNgj.js");
3839
+ return seedDemo();
3840
+ }
3841
+ }
3842
+ }
3843
+ // src/server/auth.ts
3844
+ var COOKIE = "debug_session";
3845
+ var MAX_AGE_S = 43200;
3846
+ var DEMO_USER = {
3847
+ email: "demo@debug.local",
3848
+ password: "demo-debug"
3849
+ };
3850
+ function users() {
3851
+ const cfg = config();
3852
+ const map = /* @__PURE__ */ new Map();
3853
+ for (const pair of cfg.users.split(",").map((s) => s.trim()).filter(Boolean)) {
3854
+ const i = pair.indexOf("=");
3855
+ if (i > 0) map.set(pair.slice(0, i).toLowerCase(), pair.slice(i + 1));
3856
+ }
3857
+ return map;
3858
+ }
3859
+ function demoLoginEnabled() {
3860
+ return config().store === "demo" && users().size === 0;
3861
+ }
3862
+ function verifyHash(password, stored) {
3863
+ const [algo, saltHex, hashHex] = stored.split(".");
3864
+ if (algo !== "scrypt" || !saltHex || !hashHex) return false;
3865
+ const expected = Buffer.from(hashHex, "hex");
3866
+ const actual = scryptSync(password, Buffer.from(saltHex, "hex"), expected.length);
3867
+ return timingSafeEqual(actual, expected);
3868
+ }
3869
+ function checkCredentials(email, password) {
3870
+ const e = email.trim().toLowerCase();
3871
+ if (demoLoginEnabled()) return e === DEMO_USER.email && password === DEMO_USER.password ? { email: e } : null;
3872
+ const stored = users().get(e);
3873
+ const ok = verifyHash(password, stored ?? "scrypt.00000000000000000000000000000000." + "00".repeat(64));
3874
+ return stored && ok ? { email: e } : null;
3875
+ }
3876
+ var sign = (payload) => createHmac("sha256", config().sessionSecret).update(payload).digest("base64url");
3877
+ function startSession(user) {
3878
+ const payload = Buffer.from(JSON.stringify({
3879
+ email: user.email,
3880
+ exp: Date.now() + MAX_AGE_S * 1e3
3881
+ })).toString("base64url");
3882
+ setCookie(COOKIE, `${payload}.${sign(payload)}`, {
3883
+ httpOnly: true,
3884
+ sameSite: "lax",
3885
+ secure: config().secureCookies,
3886
+ path: "/",
3887
+ maxAge: MAX_AGE_S
3888
+ });
3889
+ }
3890
+ function endSession() {
3891
+ deleteCookie(COOKIE, { path: "/" });
3892
+ }
3893
+ function readSession() {
3894
+ const raw = getCookie(COOKIE);
3895
+ if (!raw) return null;
3896
+ const [payload, sig] = raw.split(".");
3897
+ if (!payload || !sig) return null;
3898
+ const expected = Buffer.from(sign(payload));
3899
+ const given = Buffer.from(sig);
3900
+ if (expected.length !== given.length || !timingSafeEqual(expected, given)) return null;
3901
+ try {
3902
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString());
3903
+ if (Date.now() > data.exp) return null;
3904
+ return { email: data.email };
3905
+ } catch {
3906
+ return null;
3907
+ }
3908
+ }
3909
+ /** For /api/* routes: a browser session or `Authorization: Bearer $DEBUG_API_TOKEN`. */
3910
+ function authorizeApi(request) {
3911
+ if (readSession()) return true;
3912
+ const token = config().apiToken;
3913
+ const header = request.headers.get("authorization") ?? getRequestHeader("authorization") ?? "";
3914
+ if (!token || !header.startsWith("Bearer ")) return false;
3915
+ const a = Buffer.from(header.slice(7));
3916
+ const b = Buffer.from(token);
3917
+ return a.length === b.length && timingSafeEqual(a, b);
3918
+ }
3919
+ // src/server/queries.ts
3920
+ var DAY = 864e5;
3921
+ var HOUR = 36e5;
3922
+ var dayKey = (t) => new Date(t).toISOString().slice(0, 10);
3923
+ var hourKey = (t) => new Date(t).toISOString().slice(0, 13);
3924
+ function days(now, n) {
3925
+ return Array.from({ length: n }, (_, i) => dayKey(now - (n - 1 - i) * DAY));
3926
+ }
3927
+ function hours(now, n) {
3928
+ return Array.from({ length: n }, (_, i) => hourKey(now - (n - 1 - i) * HOUR));
3929
+ }
3930
+ /** Description of every field, shipped with the JSON API so agents can interpret it without docs. */
3931
+ var SUMMARY_FIELDS = {
3932
+ "totals.errors24h": "Error events in the trailing 24 hours (exact, from hourly rollups).",
3933
+ "totals.changePct": "Percent change of errors vs the previous 24h window.",
3934
+ "totals.activeIssues": "Distinct grouped errors (issues) seen in the last 14 days.",
3935
+ "totals.criticalIssues": "Issues whose 24h occurrence count meets the critical threshold.",
3936
+ "flows[]": "Parts of the app as tagged by the developer (e.g. auth.login). Sorted by severity, then errors24h.",
3937
+ "flows[].failureRate": "failures/(failures+successes) from events logged with an outcome. null when the app logs no outcomes for that flow.",
3938
+ "issues[]": "Grouped errors. Sorted by severity, then count24h.",
3939
+ "issues[].severity": "Derived from count24h using thresholds critical/high/medium.",
3940
+ "issues[].culprit": "Top in-app stack frame: function (file:line).",
3941
+ "trend[]": "Errors and non-error events per UTC day for the last 14 days.",
3942
+ "breakdowns": "Errors over the last 14 days split by OS, app version and device model.",
3943
+ narrative: "Plain-language summary of what is going wrong right now.",
3944
+ "health.crashFreeRate": "Share of sessions in 14 days with no fatal crash. Sessions are recorded automatically by the SDK.",
3945
+ "health.errorFreeRate": "Share of sessions in 14 days with no unhandled error.",
3946
+ "health.releases[]": "Crash-free and error-free rates per app version.",
3947
+ "health.endpoints[]": "HTTP endpoints whose requests failed most (5xx, timeouts, network errors), from automatic network capture."
3948
+ };
3949
+ async function counts24hByIssue(store, app, now) {
3950
+ const hs = hours(now, 24);
3951
+ const rows = await store.getRollups(app, "issueHour", hs[0], hs[hs.length - 1]);
3952
+ const map = /* @__PURE__ */ new Map();
3953
+ for (const r of rows) map.set(r.key, (map.get(r.key) ?? 0) + r.errors);
3954
+ return map;
3955
+ }
3956
+ async function buildSummary(store, appParam, thresholds, now = Date.now()) {
3957
+ const apps = await store.listApps();
3958
+ const app = appParam && apps.includes(appParam) ? appParam : apps[0];
3959
+ if (!app) return null;
3960
+ const d14 = days(now, 14);
3961
+ const from = d14[0];
3962
+ const to = d14[d14.length - 1];
3963
+ const [sessionRows, endpointRows, total, flowRows, outcomeRows, os, appVersion, deviceModel, issues, issue24h, hourly] = await Promise.all([
3964
+ store.getRollups(app, "session", from, to),
3965
+ store.getRollups(app, "endpoint", from, to),
3966
+ store.getRollups(app, "total", from, to),
3967
+ store.getRollups(app, "flow", from, to),
3968
+ store.getRollups(app, "flowOutcome", from, to),
3969
+ store.getRollups(app, "os", from, to),
3970
+ store.getRollups(app, "appVersion", from, to),
3971
+ store.getRollups(app, "deviceModel", from, to),
3972
+ store.listIssues(app, { limit: 500 }),
3973
+ counts24hByIssue(store, app, now),
3974
+ store.getRollups(app, "issueHour", hours(now, 48)[0], hourKey(now))
3975
+ ]);
3976
+ const trend = d14.map((day) => {
3977
+ const r = total.find((x) => x.day === day);
3978
+ return {
3979
+ day,
3980
+ errors: r?.errors ?? 0,
3981
+ events: r?.events ?? 0
3982
+ };
3983
+ });
3984
+ const h24 = new Set(hours(now, 24));
3985
+ let errors24h = 0;
3986
+ let errorsPrev24h = 0;
3987
+ for (const r of hourly) h24.has(r.day) ? errors24h += r.errors : errorsPrev24h += r.errors;
3988
+ const since14 = (/* @__PURE__ */ new Date(now - 14 * DAY)).toISOString();
3989
+ const issueRows = issues.filter((i) => i.lastSeen >= since14).map((i) => toIssueRow(i, issue24h.get(i.fingerprint) ?? 0, thresholds)).sort(bySeverityThenCount);
3990
+ const flowMap = /* @__PURE__ */ new Map();
3991
+ const flowOf = (flow) => {
3992
+ let f = flowMap.get(flow);
3993
+ if (!f) flowMap.set(flow, f = {
3994
+ flow,
3995
+ errors24h: 0,
3996
+ errors14d: 0,
3997
+ severity: "low",
3998
+ issues: 0,
3999
+ successes14d: 0,
4000
+ failures14d: 0,
4001
+ failureRate: null
4002
+ });
4003
+ return f;
4004
+ };
4005
+ for (const r of flowRows) if (r.errors > 0) flowOf(r.key).errors14d += r.errors;
4006
+ for (const i of issueRows) {
4007
+ const f = flowOf(i.flow ?? "untagged");
4008
+ f.issues++;
4009
+ f.errors24h += i.count24h;
4010
+ if (SEVERITY_ORDER[i.severity] > SEVERITY_ORDER[f.severity]) f.severity = i.severity;
4011
+ }
4012
+ for (const r of outcomeRows) {
4013
+ const [flow, outcome] = r.key.split("|");
4014
+ const f = flowOf(flow);
4015
+ if (outcome === "success") f.successes14d += r.events;
4016
+ else if (outcome === "failure") f.failures14d += r.events;
4017
+ }
4018
+ const flows = [...flowMap.values()].map((f) => ({
4019
+ ...f,
4020
+ failureRate: f.successes14d + f.failures14d > 0 ? f.failures14d / (f.successes14d + f.failures14d) : null
4021
+ })).filter((f) => f.errors14d > 0 || f.failures14d > 0).sort((a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || b.errors24h - a.errors24h || b.errors14d - a.errors14d);
4022
+ const top = (rows) => {
4023
+ const m = /* @__PURE__ */ new Map();
4024
+ for (const r of rows) m.set(r.key, (m.get(r.key) ?? 0) + r.errors);
4025
+ return [...m.entries()].map(([key, errors]) => ({
4026
+ key,
4027
+ errors
4028
+ })).filter((r) => r.errors > 0).sort((a, b) => b.errors - a.errors).slice(0, 8);
4029
+ };
4030
+ const summary = {
4031
+ app,
4032
+ apps,
4033
+ generatedAt: new Date(now).toISOString(),
4034
+ totals: {
4035
+ errors24h,
4036
+ errorsPrev24h,
4037
+ changePct: errorsPrev24h > 0 ? Math.round((errors24h - errorsPrev24h) / errorsPrev24h * 100) : null,
4038
+ events14d: trend.reduce((a, d) => a + d.events, 0),
4039
+ activeIssues: issueRows.length,
4040
+ criticalIssues: issueRows.filter((i) => i.severity === "critical").length,
4041
+ failingFlows: flows.filter((f) => f.errors24h > 0).length
4042
+ },
4043
+ narrative: [],
4044
+ trend,
4045
+ flows,
4046
+ issues: issueRows,
4047
+ breakdowns: {
4048
+ os: top(os),
4049
+ appVersion: top(appVersion),
4050
+ deviceModel: top(deviceModel)
4051
+ },
4052
+ health: buildHealth(sessionRows, endpointRows, dayKey(now))
4053
+ };
4054
+ summary.narrative = narrate(summary);
4055
+ return summary;
4056
+ }
4057
+ var rate = (bad, total) => total > 0 ? Math.max(0, 1 - bad / total) : null;
4058
+ /** "2.10.0" sorts after "2.9.1". */
4059
+ function compareVersions(a, b) {
4060
+ const pa = a.split(/[.-]/);
4061
+ const pb = b.split(/[.-]/);
4062
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
4063
+ const x = pa[i] ?? "";
4064
+ const y = pb[i] ?? "";
4065
+ const d = /^\d+$/.test(x) && /^\d+$/.test(y) ? Number(x) - Number(y) : x.localeCompare(y);
4066
+ if (d) return d;
4067
+ }
4068
+ return 0;
4069
+ }
4070
+ function buildHealth(sessionRows, endpointRows, today) {
4071
+ const byVersion = /* @__PURE__ */ new Map();
4072
+ for (const r of sessionRows) {
4073
+ const [version = "unknown", status] = r.key.split("|");
4074
+ let v = byVersion.get(version);
4075
+ if (!v) byVersion.set(version, v = {
4076
+ version,
4077
+ sessions: 0,
4078
+ errored: 0,
4079
+ crashed: 0,
4080
+ crashFreeRate: null,
4081
+ errorFreeRate: null
4082
+ });
4083
+ if (status === "started") v.sessions += r.events;
4084
+ else if (status === "errored") v.errored += r.events;
4085
+ else if (status === "crashed") v.crashed += r.events;
4086
+ }
4087
+ const releases = [...byVersion.values()].map((v) => ({
4088
+ ...v,
4089
+ crashFreeRate: rate(v.crashed, v.sessions),
4090
+ errorFreeRate: rate(v.errored, v.sessions)
4091
+ })).filter((v) => v.sessions > 0).sort((a, b) => compareVersions(b.version, a.version)).slice(0, 8);
4092
+ const sum = (k) => [...byVersion.values()].reduce((a, v) => a + v[k], 0);
4093
+ const eps = /* @__PURE__ */ new Map();
4094
+ for (const r of endpointRows) {
4095
+ let e = eps.get(r.key);
4096
+ if (!e) eps.set(r.key, e = {
4097
+ endpoint: r.key,
4098
+ failures14d: 0,
4099
+ failures24h: 0
4100
+ });
4101
+ e.failures14d += r.errors;
4102
+ if (r.day === today) e.failures24h += r.errors;
4103
+ }
4104
+ return {
4105
+ sessions14d: sum("sessions"),
4106
+ crashFreeRate: rate(sum("crashed"), sum("sessions")),
4107
+ errorFreeRate: rate(sum("errored"), sum("sessions")),
4108
+ releases,
4109
+ endpoints: [...eps.values()].sort((a, b) => b.failures14d - a.failures14d).slice(0, 8)
4110
+ };
4111
+ }
4112
+ function toIssueRow(i, count24h, t) {
4113
+ return {
4114
+ fingerprint: i.fingerprint,
4115
+ title: i.title,
4116
+ culprit: i.culprit,
4117
+ flow: i.flow,
4118
+ severity: severityFromCount(count24h, t),
4119
+ count24h,
4120
+ countTotal: i.count,
4121
+ firstSeen: i.firstSeen,
4122
+ lastSeen: i.lastSeen
4123
+ };
4124
+ }
4125
+ var bySeverityThenCount = (a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || b.count24h - a.count24h || b.lastSeen.localeCompare(a.lastSeen);
4126
+ var pct = (n) => `${Math.round(n * 100)}%`;
4127
+ var pctOne = (n) => `${(Math.floor(n * 1e3) / 10).toFixed(1)}%`;
4128
+ function narrate(s) {
4129
+ const out = [];
4130
+ const t = s.totals;
4131
+ if (t.errors24h === 0) {
4132
+ out.push("No errors in the last 24 hours.");
4133
+ return out;
4134
+ }
4135
+ const change = t.changePct === null ? "" : t.changePct === 0 ? ", flat versus the day before" : `, ${t.changePct > 0 ? "up" : "down"} ${Math.abs(t.changePct)}% on the previous 24h`;
4136
+ out.push(`${t.errors24h.toLocaleString()} errors in the last 24 hours${change}, across ${t.failingFlows} part${t.failingFlows === 1 ? "" : "s"} of the app.`);
4137
+ const f = s.flows[0];
4138
+ if (f && f.errors24h > 0) {
4139
+ const rate = f.failureRate !== null ? ` ${pct(f.failureRate)} of attempts fail.` : "";
4140
+ out.push(`${f.flow} is the most affected flow (${f.severity}): ${f.errors24h} errors in 24h from ${f.issues} issue${f.issues === 1 ? "" : "s"}.${rate}`);
4141
+ }
4142
+ const i = s.issues[0];
4143
+ if (i && i.count24h > 0) {
4144
+ const isNew = Date.parse(s.generatedAt) - Date.parse(i.firstSeen) < 3 * DAY;
4145
+ out.push(`Top issue: "${i.title}"${i.culprit ? ` in ${i.culprit}` : ""} — ${i.count24h} time${i.count24h === 1 ? "" : "s"} in 24h${isNew ? `, first seen ${relDays(s.generatedAt, i.firstSeen)}` : ""}.`);
4146
+ }
4147
+ const h = s.health;
4148
+ const latest = h.releases[0];
4149
+ const prev = h.releases[1];
4150
+ if (latest?.crashFreeRate != null && latest.sessions >= 20 && latest.crashFreeRate < .995) {
4151
+ const vs = prev?.crashFreeRate != null && prev.sessions >= 20 ? ` (${prev.version}: ${pctOne(prev.crashFreeRate)})` : "";
4152
+ out.push(`${latest.version} is ${pctOne(latest.crashFreeRate)} crash-free across ${latest.sessions.toLocaleString()} sessions${vs}.`);
4153
+ }
4154
+ const ep = h.endpoints[0];
4155
+ if (ep && ep.failures24h > 0) out.push(`${ep.endpoint} is the most failing endpoint: ${ep.failures24h} failed request${ep.failures24h === 1 ? "" : "s"} today.`);
4156
+ const os = s.breakdowns.os;
4157
+ const osTotal = os.reduce((a, b) => a + b.errors, 0);
4158
+ if (os[0] && osTotal > 20 && os[0].errors / osTotal > .6) out.push(`${pct(os[0].errors / osTotal)} of errors in the last 14 days come from ${os[0].key}.`);
4159
+ return out;
4160
+ }
4161
+ function relDays(now, then) {
4162
+ const d = Math.floor((Date.parse(now) - Date.parse(then)) / DAY);
4163
+ return d === 0 ? "today" : d === 1 ? "yesterday" : `${d} days ago`;
4164
+ }
4165
+ async function buildIssueDetail(store, app, fingerprint, thresholds, now = Date.now()) {
4166
+ const issue = await store.getIssue(app, fingerprint);
4167
+ if (!issue) return null;
4168
+ const hs = hours(now, 48);
4169
+ const d14 = days(now, 14);
4170
+ const [hourRows, dayRows, events] = await Promise.all([
4171
+ store.getRollups(app, "issueHour", hs[0], hs[hs.length - 1]),
4172
+ store.getRollups(app, "issue", d14[0], d14[d14.length - 1]),
4173
+ store.listIssueEvents(app, fingerprint, { limit: 200 })
4174
+ ]);
4175
+ const hourly = hs.map((hour) => ({
4176
+ hour,
4177
+ count: hourRows.filter((r) => r.key === fingerprint && r.day === hour).reduce((a, r) => a + r.errors, 0)
4178
+ }));
4179
+ const daily = d14.map((day) => ({
4180
+ day,
4181
+ count: dayRows.filter((r) => r.key === fingerprint && r.day === day).reduce((a, r) => a + r.errors, 0)
4182
+ }));
4183
+ const count24h = hourly.slice(-24).reduce((a, h) => a + h.count, 0);
4184
+ const split = (pick) => {
4185
+ const m = /* @__PURE__ */ new Map();
4186
+ for (const e of events) {
4187
+ const k = pick(e) || "unknown";
4188
+ m.set(k, (m.get(k) ?? 0) + 1);
4189
+ }
4190
+ return [...m.entries()].map(([key, count]) => ({
4191
+ key,
4192
+ count,
4193
+ share: events.length ? count / events.length : 0
4194
+ })).sort((a, b) => b.count - a.count).slice(0, 6);
4195
+ };
4196
+ const breakdowns = {
4197
+ os: split((e) => `${e.context.os.name} ${e.context.os.version ?? ""}`.trim()),
4198
+ appVersion: split((e) => e.context.app.version),
4199
+ deviceModel: split((e) => e.context.device.model),
4200
+ network: split((e) => e.context.network?.type),
4201
+ runtime: split((e) => [e.context.runtime.name, e.context.runtime.engine].filter(Boolean).join(" / "))
4202
+ };
4203
+ const users = new Set(events.map((e) => e.user?.id ?? e.user?.anonymousId ?? e.sessionId));
4204
+ return {
4205
+ app,
4206
+ issue: toIssueRow(issue, count24h, thresholds),
4207
+ hourly,
4208
+ daily,
4209
+ breakdowns,
4210
+ affectedUsers: users.size,
4211
+ sample: events[0] ?? issue.lastEvent ?? null,
4212
+ recent: events.slice(0, 25).map((e) => ({
4213
+ ts: e.event.ts,
4214
+ os: `${e.context.os.name} ${e.context.os.version ?? ""}`.trim(),
4215
+ appVersion: e.context.app.version,
4216
+ device: e.context.device.model,
4217
+ message: e.event.type === "error" ? e.event.error.message : e.event.type === "event" ? e.event.name : `session ${e.event.status}`,
4218
+ userId: e.user?.id
4219
+ })),
4220
+ hints: hintsFor(issue, breakdowns, events)
4221
+ };
4222
+ }
4223
+ /** Rule-based "what to look at" hints. Phase 2 replaces/augments these with an LLM over the same data. */
4224
+ function hintsFor(issue, b, events) {
4225
+ const hints = [];
4226
+ const text = `${issue.title} ${events[0]?.event.type === "error" ? events[0].event.error.stack ?? "" : ""}`.toLowerCase();
4227
+ const crumbs = events.flatMap((e) => e.event.type === "error" ? e.event.breadcrumbs ?? [] : []);
4228
+ const concentrated = (label, rows) => {
4229
+ const r = rows[0];
4230
+ if (r && r.key !== "unknown" && r.share >= .8 && events.length >= 5 && rows.length >= 1) hints.push({
4231
+ title: `Concentrated on ${label} ${r.key}`,
4232
+ detail: `${Math.round(r.share * 100)}% of recent occurrences. Reproduce on ${r.key} first, and check what changed for it.`
4233
+ });
4234
+ };
4235
+ concentrated("app version", b.appVersion);
4236
+ concentrated("OS", b.os);
4237
+ concentrated("device", b.deviceModel);
4238
+ if (/cannot read propert|undefined is not an object|of undefined|of null|is not a function/.test(text)) hints.push({
4239
+ title: "A value is missing when the code expects it",
4240
+ detail: `Something is null/undefined at ${issue.culprit ?? "the top frame"}. Check the data the previous step returns (API response shape, async state not yet loaded) and add a guard or loading state.`
4241
+ });
4242
+ if (/network request failed|failed to fetch|networkerror|timeout|timed out|econn|socket/.test(text)) hints.push({
4243
+ title: "Network failure",
4244
+ detail: "Check if errors line up with poor connectivity (see the network breakdown), add retries with backoff, and show an offline/timeout state instead of failing."
4245
+ });
4246
+ if (/\b401\b|\b403\b|unauthori[sz]ed|forbidden|token expired|jwt/.test(text)) hints.push({
4247
+ title: "Auth/session problem",
4248
+ detail: "Look for expired or missing tokens. Confirm the token refresh runs before this call, and that the clock/expiry handling is right."
4249
+ });
4250
+ if (/json|unexpected token|syntaxerror/.test(text)) hints.push({
4251
+ title: "Bad response body",
4252
+ detail: "The app tried to parse something that isn't the JSON it expected — often an HTML error page or an empty 204/5xx. Log the status and content-type before parsing."
4253
+ });
4254
+ if (/\b5\d\d\b|internal server error|bad gateway|service unavailable/.test(text)) hints.push({
4255
+ title: "Server-side failure",
4256
+ detail: "The backend returned a 5xx. Correlate the timestamps with your API logs."
4257
+ });
4258
+ const failingRequests = crumbs.filter((c) => c.category === "network" && (c.level === "error" || /\b[45]\d\d\b/.test(c.message)));
4259
+ if (failingRequests.length) {
4260
+ const m = /* @__PURE__ */ new Map();
4261
+ for (const c of failingRequests) m.set(c.message, (m.get(c.message) ?? 0) + 1);
4262
+ const [msg] = [...m.entries()].sort((a, b) => b[1] - a[1])[0];
4263
+ hints.push({
4264
+ title: "A request fails right before the error",
4265
+ detail: `Most common: ${msg}`
4266
+ });
4267
+ }
4268
+ if (hints.length === 0) hints.push({
4269
+ title: "Start at the culprit frame",
4270
+ detail: `Open ${issue.culprit ?? "the top stack frame"} and use the breadcrumbs below to replay what the user did.`
4271
+ });
4272
+ return hints;
4273
+ }
4274
+ export { authorizeApi as a, endSession as c, getLocalWriteStore as d, getStore as f, parseStack as h, DEMO_USER as i, readSession as l, Envelope as m, buildIssueDetail as n, checkCredentials as o, config as p, buildSummary as r, demoLoginEnabled as s, SUMMARY_FIELDS as t, startSession as u };