@prefactor/openclaw 0.0.5 → 0.0.7

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