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