opencode-codebase-index 0.1.7 → 0.1.8

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
@@ -654,4145 +654,40 @@ var require_ignore = __commonJS({
654
654
  // src/index.ts
655
655
  var index_exports = {};
656
656
  __export(index_exports, {
657
- CodebaseIndexConfigSchema: () => CodebaseIndexConfigSchema,
658
- EMBEDDING_MODELS: () => EMBEDDING_MODELS,
659
- EmbeddingProviderSchema: () => EmbeddingProviderSchema,
660
- FileWatcher: () => FileWatcher,
661
- IndexScopeSchema: () => IndexScopeSchema,
662
- Indexer: () => Indexer,
663
- IndexingConfigSchema: () => IndexingConfigSchema,
664
- SearchConfigSchema: () => SearchConfigSchema,
665
- VectorStore: () => VectorStore,
666
- collectFiles: () => collectFiles,
667
- createCostEstimate: () => createCostEstimate,
668
- createDynamicBatches: () => createDynamicBatches,
669
- createEmbeddingProvider: () => createEmbeddingProvider,
670
- createEmbeddingText: () => createEmbeddingText,
671
- createIgnoreFilter: () => createIgnoreFilter,
672
- default: () => index_default,
673
- detectEmbeddingProvider: () => detectEmbeddingProvider,
674
- estimateChunksFromFiles: () => estimateChunksFromFiles,
675
- estimateCost: () => estimateCost,
676
- estimateTokens: () => estimateTokens,
677
- formatBytes: () => formatBytes,
678
- formatConfirmationPrompt: () => formatConfirmationPrompt,
679
- formatCostEstimate: () => formatCostEstimate,
680
- generateChunkHash: () => generateChunkHash,
681
- generateChunkId: () => generateChunkId,
682
- getDefaultConfig: () => getDefaultConfig,
683
- getDefaultModelForProvider: () => getDefaultModelForProvider,
684
- getProviderDisplayName: () => getProviderDisplayName,
685
- hashContent: () => hashContent,
686
- hashFile: () => hashFile,
687
- parseConfig: () => parseConfig,
688
- parseConfirmationResponse: () => parseConfirmationResponse,
689
- parseFile: () => parseFile,
690
- parseFiles: () => parseFiles,
691
- shouldIncludeFile: () => shouldIncludeFile,
692
- walkDirectory: () => walkDirectory
657
+ default: () => index_default
693
658
  });
694
659
  module.exports = __toCommonJS(index_exports);
695
660
  var import_fs6 = require("fs");
696
661
  var path8 = __toESM(require("path"), 1);
697
662
 
698
- // node_modules/zod/v3/external.js
699
- var external_exports = {};
700
- __export(external_exports, {
701
- BRAND: () => BRAND,
702
- DIRTY: () => DIRTY,
703
- EMPTY_PATH: () => EMPTY_PATH,
704
- INVALID: () => INVALID,
705
- NEVER: () => NEVER,
706
- OK: () => OK,
707
- ParseStatus: () => ParseStatus,
708
- Schema: () => ZodType,
709
- ZodAny: () => ZodAny,
710
- ZodArray: () => ZodArray,
711
- ZodBigInt: () => ZodBigInt,
712
- ZodBoolean: () => ZodBoolean,
713
- ZodBranded: () => ZodBranded,
714
- ZodCatch: () => ZodCatch,
715
- ZodDate: () => ZodDate,
716
- ZodDefault: () => ZodDefault,
717
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
718
- ZodEffects: () => ZodEffects,
719
- ZodEnum: () => ZodEnum,
720
- ZodError: () => ZodError,
721
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
722
- ZodFunction: () => ZodFunction,
723
- ZodIntersection: () => ZodIntersection,
724
- ZodIssueCode: () => ZodIssueCode,
725
- ZodLazy: () => ZodLazy,
726
- ZodLiteral: () => ZodLiteral,
727
- ZodMap: () => ZodMap,
728
- ZodNaN: () => ZodNaN,
729
- ZodNativeEnum: () => ZodNativeEnum,
730
- ZodNever: () => ZodNever,
731
- ZodNull: () => ZodNull,
732
- ZodNullable: () => ZodNullable,
733
- ZodNumber: () => ZodNumber,
734
- ZodObject: () => ZodObject,
735
- ZodOptional: () => ZodOptional,
736
- ZodParsedType: () => ZodParsedType,
737
- ZodPipeline: () => ZodPipeline,
738
- ZodPromise: () => ZodPromise,
739
- ZodReadonly: () => ZodReadonly,
740
- ZodRecord: () => ZodRecord,
741
- ZodSchema: () => ZodType,
742
- ZodSet: () => ZodSet,
743
- ZodString: () => ZodString,
744
- ZodSymbol: () => ZodSymbol,
745
- ZodTransformer: () => ZodEffects,
746
- ZodTuple: () => ZodTuple,
747
- ZodType: () => ZodType,
748
- ZodUndefined: () => ZodUndefined,
749
- ZodUnion: () => ZodUnion,
750
- ZodUnknown: () => ZodUnknown,
751
- ZodVoid: () => ZodVoid,
752
- addIssueToContext: () => addIssueToContext,
753
- any: () => anyType,
754
- array: () => arrayType,
755
- bigint: () => bigIntType,
756
- boolean: () => booleanType,
757
- coerce: () => coerce,
758
- custom: () => custom,
759
- date: () => dateType,
760
- datetimeRegex: () => datetimeRegex,
761
- defaultErrorMap: () => en_default,
762
- discriminatedUnion: () => discriminatedUnionType,
763
- effect: () => effectsType,
764
- enum: () => enumType,
765
- function: () => functionType,
766
- getErrorMap: () => getErrorMap,
767
- getParsedType: () => getParsedType,
768
- instanceof: () => instanceOfType,
769
- intersection: () => intersectionType,
770
- isAborted: () => isAborted,
771
- isAsync: () => isAsync,
772
- isDirty: () => isDirty,
773
- isValid: () => isValid,
774
- late: () => late,
775
- lazy: () => lazyType,
776
- literal: () => literalType,
777
- makeIssue: () => makeIssue,
778
- map: () => mapType,
779
- nan: () => nanType,
780
- nativeEnum: () => nativeEnumType,
781
- never: () => neverType,
782
- null: () => nullType,
783
- nullable: () => nullableType,
784
- number: () => numberType,
785
- object: () => objectType,
786
- objectUtil: () => objectUtil,
787
- oboolean: () => oboolean,
788
- onumber: () => onumber,
789
- optional: () => optionalType,
790
- ostring: () => ostring,
791
- pipeline: () => pipelineType,
792
- preprocess: () => preprocessType,
793
- promise: () => promiseType,
794
- quotelessJson: () => quotelessJson,
795
- record: () => recordType,
796
- set: () => setType,
797
- setErrorMap: () => setErrorMap,
798
- strictObject: () => strictObjectType,
799
- string: () => stringType,
800
- symbol: () => symbolType,
801
- transformer: () => effectsType,
802
- tuple: () => tupleType,
803
- undefined: () => undefinedType,
804
- union: () => unionType,
805
- unknown: () => unknownType,
806
- util: () => util,
807
- void: () => voidType
808
- });
809
-
810
- // node_modules/zod/v3/helpers/util.js
811
- var util;
812
- (function(util2) {
813
- util2.assertEqual = (_) => {
814
- };
815
- function assertIs(_arg) {
816
- }
817
- util2.assertIs = assertIs;
818
- function assertNever(_x) {
819
- throw new Error();
820
- }
821
- util2.assertNever = assertNever;
822
- util2.arrayToEnum = (items) => {
823
- const obj = {};
824
- for (const item of items) {
825
- obj[item] = item;
826
- }
827
- return obj;
828
- };
829
- util2.getValidEnumValues = (obj) => {
830
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
831
- const filtered = {};
832
- for (const k of validKeys) {
833
- filtered[k] = obj[k];
834
- }
835
- return util2.objectValues(filtered);
836
- };
837
- util2.objectValues = (obj) => {
838
- return util2.objectKeys(obj).map(function(e) {
839
- return obj[e];
840
- });
841
- };
842
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
843
- const keys = [];
844
- for (const key in object) {
845
- if (Object.prototype.hasOwnProperty.call(object, key)) {
846
- keys.push(key);
847
- }
848
- }
849
- return keys;
850
- };
851
- util2.find = (arr, checker) => {
852
- for (const item of arr) {
853
- if (checker(item))
854
- return item;
855
- }
856
- return void 0;
857
- };
858
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
859
- function joinValues(array, separator = " | ") {
860
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
861
- }
862
- util2.joinValues = joinValues;
863
- util2.jsonStringifyReplacer = (_, value) => {
864
- if (typeof value === "bigint") {
865
- return value.toString();
866
- }
867
- return value;
868
- };
869
- })(util || (util = {}));
870
- var objectUtil;
871
- (function(objectUtil2) {
872
- objectUtil2.mergeShapes = (first, second) => {
873
- return {
874
- ...first,
875
- ...second
876
- // second overwrites first
877
- };
878
- };
879
- })(objectUtil || (objectUtil = {}));
880
- var ZodParsedType = util.arrayToEnum([
881
- "string",
882
- "nan",
883
- "number",
884
- "integer",
885
- "float",
886
- "boolean",
887
- "date",
888
- "bigint",
889
- "symbol",
890
- "function",
891
- "undefined",
892
- "null",
893
- "array",
894
- "object",
895
- "unknown",
896
- "promise",
897
- "void",
898
- "never",
899
- "map",
900
- "set"
901
- ]);
902
- var getParsedType = (data) => {
903
- const t = typeof data;
904
- switch (t) {
905
- case "undefined":
906
- return ZodParsedType.undefined;
907
- case "string":
908
- return ZodParsedType.string;
909
- case "number":
910
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
911
- case "boolean":
912
- return ZodParsedType.boolean;
913
- case "function":
914
- return ZodParsedType.function;
915
- case "bigint":
916
- return ZodParsedType.bigint;
917
- case "symbol":
918
- return ZodParsedType.symbol;
919
- case "object":
920
- if (Array.isArray(data)) {
921
- return ZodParsedType.array;
922
- }
923
- if (data === null) {
924
- return ZodParsedType.null;
925
- }
926
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
927
- return ZodParsedType.promise;
928
- }
929
- if (typeof Map !== "undefined" && data instanceof Map) {
930
- return ZodParsedType.map;
931
- }
932
- if (typeof Set !== "undefined" && data instanceof Set) {
933
- return ZodParsedType.set;
934
- }
935
- if (typeof Date !== "undefined" && data instanceof Date) {
936
- return ZodParsedType.date;
937
- }
938
- return ZodParsedType.object;
939
- default:
940
- return ZodParsedType.unknown;
941
- }
942
- };
943
-
944
- // node_modules/zod/v3/ZodError.js
945
- var ZodIssueCode = util.arrayToEnum([
946
- "invalid_type",
947
- "invalid_literal",
948
- "custom",
949
- "invalid_union",
950
- "invalid_union_discriminator",
951
- "invalid_enum_value",
952
- "unrecognized_keys",
953
- "invalid_arguments",
954
- "invalid_return_type",
955
- "invalid_date",
956
- "invalid_string",
957
- "too_small",
958
- "too_big",
959
- "invalid_intersection_types",
960
- "not_multiple_of",
961
- "not_finite"
962
- ]);
963
- var quotelessJson = (obj) => {
964
- const json = JSON.stringify(obj, null, 2);
965
- return json.replace(/"([^"]+)":/g, "$1:");
966
- };
967
- var ZodError = class _ZodError extends Error {
968
- get errors() {
969
- return this.issues;
970
- }
971
- constructor(issues) {
972
- super();
973
- this.issues = [];
974
- this.addIssue = (sub) => {
975
- this.issues = [...this.issues, sub];
976
- };
977
- this.addIssues = (subs = []) => {
978
- this.issues = [...this.issues, ...subs];
979
- };
980
- const actualProto = new.target.prototype;
981
- if (Object.setPrototypeOf) {
982
- Object.setPrototypeOf(this, actualProto);
983
- } else {
984
- this.__proto__ = actualProto;
985
- }
986
- this.name = "ZodError";
987
- this.issues = issues;
988
- }
989
- format(_mapper) {
990
- const mapper = _mapper || function(issue) {
991
- return issue.message;
992
- };
993
- const fieldErrors = { _errors: [] };
994
- const processError = (error) => {
995
- for (const issue of error.issues) {
996
- if (issue.code === "invalid_union") {
997
- issue.unionErrors.map(processError);
998
- } else if (issue.code === "invalid_return_type") {
999
- processError(issue.returnTypeError);
1000
- } else if (issue.code === "invalid_arguments") {
1001
- processError(issue.argumentsError);
1002
- } else if (issue.path.length === 0) {
1003
- fieldErrors._errors.push(mapper(issue));
1004
- } else {
1005
- let curr = fieldErrors;
1006
- let i = 0;
1007
- while (i < issue.path.length) {
1008
- const el = issue.path[i];
1009
- const terminal = i === issue.path.length - 1;
1010
- if (!terminal) {
1011
- curr[el] = curr[el] || { _errors: [] };
1012
- } else {
1013
- curr[el] = curr[el] || { _errors: [] };
1014
- curr[el]._errors.push(mapper(issue));
1015
- }
1016
- curr = curr[el];
1017
- i++;
1018
- }
1019
- }
1020
- }
1021
- };
1022
- processError(this);
1023
- return fieldErrors;
1024
- }
1025
- static assert(value) {
1026
- if (!(value instanceof _ZodError)) {
1027
- throw new Error(`Not a ZodError: ${value}`);
1028
- }
1029
- }
1030
- toString() {
1031
- return this.message;
1032
- }
1033
- get message() {
1034
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
1035
- }
1036
- get isEmpty() {
1037
- return this.issues.length === 0;
1038
- }
1039
- flatten(mapper = (issue) => issue.message) {
1040
- const fieldErrors = {};
1041
- const formErrors = [];
1042
- for (const sub of this.issues) {
1043
- if (sub.path.length > 0) {
1044
- const firstEl = sub.path[0];
1045
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
1046
- fieldErrors[firstEl].push(mapper(sub));
1047
- } else {
1048
- formErrors.push(mapper(sub));
1049
- }
1050
- }
1051
- return { formErrors, fieldErrors };
1052
- }
1053
- get formErrors() {
1054
- return this.flatten();
1055
- }
1056
- };
1057
- ZodError.create = (issues) => {
1058
- const error = new ZodError(issues);
1059
- return error;
1060
- };
1061
-
1062
- // node_modules/zod/v3/locales/en.js
1063
- var errorMap = (issue, _ctx) => {
1064
- let message;
1065
- switch (issue.code) {
1066
- case ZodIssueCode.invalid_type:
1067
- if (issue.received === ZodParsedType.undefined) {
1068
- message = "Required";
1069
- } else {
1070
- message = `Expected ${issue.expected}, received ${issue.received}`;
1071
- }
1072
- break;
1073
- case ZodIssueCode.invalid_literal:
1074
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
1075
- break;
1076
- case ZodIssueCode.unrecognized_keys:
1077
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
1078
- break;
1079
- case ZodIssueCode.invalid_union:
1080
- message = `Invalid input`;
1081
- break;
1082
- case ZodIssueCode.invalid_union_discriminator:
1083
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
1084
- break;
1085
- case ZodIssueCode.invalid_enum_value:
1086
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
1087
- break;
1088
- case ZodIssueCode.invalid_arguments:
1089
- message = `Invalid function arguments`;
1090
- break;
1091
- case ZodIssueCode.invalid_return_type:
1092
- message = `Invalid function return type`;
1093
- break;
1094
- case ZodIssueCode.invalid_date:
1095
- message = `Invalid date`;
1096
- break;
1097
- case ZodIssueCode.invalid_string:
1098
- if (typeof issue.validation === "object") {
1099
- if ("includes" in issue.validation) {
1100
- message = `Invalid input: must include "${issue.validation.includes}"`;
1101
- if (typeof issue.validation.position === "number") {
1102
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
1103
- }
1104
- } else if ("startsWith" in issue.validation) {
1105
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
1106
- } else if ("endsWith" in issue.validation) {
1107
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
1108
- } else {
1109
- util.assertNever(issue.validation);
1110
- }
1111
- } else if (issue.validation !== "regex") {
1112
- message = `Invalid ${issue.validation}`;
1113
- } else {
1114
- message = "Invalid";
1115
- }
1116
- break;
1117
- case ZodIssueCode.too_small:
1118
- if (issue.type === "array")
1119
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
1120
- else if (issue.type === "string")
1121
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
1122
- else if (issue.type === "number")
1123
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1124
- else if (issue.type === "bigint")
1125
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1126
- else if (issue.type === "date")
1127
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
1128
- else
1129
- message = "Invalid input";
1130
- break;
1131
- case ZodIssueCode.too_big:
1132
- if (issue.type === "array")
1133
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
1134
- else if (issue.type === "string")
1135
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
1136
- else if (issue.type === "number")
1137
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1138
- else if (issue.type === "bigint")
1139
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1140
- else if (issue.type === "date")
1141
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
1142
- else
1143
- message = "Invalid input";
1144
- break;
1145
- case ZodIssueCode.custom:
1146
- message = `Invalid input`;
1147
- break;
1148
- case ZodIssueCode.invalid_intersection_types:
1149
- message = `Intersection results could not be merged`;
1150
- break;
1151
- case ZodIssueCode.not_multiple_of:
1152
- message = `Number must be a multiple of ${issue.multipleOf}`;
1153
- break;
1154
- case ZodIssueCode.not_finite:
1155
- message = "Number must be finite";
1156
- break;
1157
- default:
1158
- message = _ctx.defaultError;
1159
- util.assertNever(issue);
1160
- }
1161
- return { message };
1162
- };
1163
- var en_default = errorMap;
1164
-
1165
- // node_modules/zod/v3/errors.js
1166
- var overrideErrorMap = en_default;
1167
- function setErrorMap(map) {
1168
- overrideErrorMap = map;
1169
- }
1170
- function getErrorMap() {
1171
- return overrideErrorMap;
1172
- }
1173
-
1174
- // node_modules/zod/v3/helpers/parseUtil.js
1175
- var makeIssue = (params) => {
1176
- const { data, path: path9, errorMaps, issueData } = params;
1177
- const fullPath = [...path9, ...issueData.path || []];
1178
- const fullIssue = {
1179
- ...issueData,
1180
- path: fullPath
1181
- };
1182
- if (issueData.message !== void 0) {
1183
- return {
1184
- ...issueData,
1185
- path: fullPath,
1186
- message: issueData.message
1187
- };
1188
- }
1189
- let errorMessage = "";
1190
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
1191
- for (const map of maps) {
1192
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
1193
- }
1194
- return {
1195
- ...issueData,
1196
- path: fullPath,
1197
- message: errorMessage
1198
- };
1199
- };
1200
- var EMPTY_PATH = [];
1201
- function addIssueToContext(ctx, issueData) {
1202
- const overrideMap = getErrorMap();
1203
- const issue = makeIssue({
1204
- issueData,
1205
- data: ctx.data,
1206
- path: ctx.path,
1207
- errorMaps: [
1208
- ctx.common.contextualErrorMap,
1209
- // contextual error map is first priority
1210
- ctx.schemaErrorMap,
1211
- // then schema-bound map if available
1212
- overrideMap,
1213
- // then global override map
1214
- overrideMap === en_default ? void 0 : en_default
1215
- // then global default map
1216
- ].filter((x) => !!x)
1217
- });
1218
- ctx.common.issues.push(issue);
1219
- }
1220
- var ParseStatus = class _ParseStatus {
1221
- constructor() {
1222
- this.value = "valid";
1223
- }
1224
- dirty() {
1225
- if (this.value === "valid")
1226
- this.value = "dirty";
1227
- }
1228
- abort() {
1229
- if (this.value !== "aborted")
1230
- this.value = "aborted";
1231
- }
1232
- static mergeArray(status, results) {
1233
- const arrayValue = [];
1234
- for (const s of results) {
1235
- if (s.status === "aborted")
1236
- return INVALID;
1237
- if (s.status === "dirty")
1238
- status.dirty();
1239
- arrayValue.push(s.value);
1240
- }
1241
- return { status: status.value, value: arrayValue };
1242
- }
1243
- static async mergeObjectAsync(status, pairs) {
1244
- const syncPairs = [];
1245
- for (const pair of pairs) {
1246
- const key = await pair.key;
1247
- const value = await pair.value;
1248
- syncPairs.push({
1249
- key,
1250
- value
1251
- });
1252
- }
1253
- return _ParseStatus.mergeObjectSync(status, syncPairs);
1254
- }
1255
- static mergeObjectSync(status, pairs) {
1256
- const finalObject = {};
1257
- for (const pair of pairs) {
1258
- const { key, value } = pair;
1259
- if (key.status === "aborted")
1260
- return INVALID;
1261
- if (value.status === "aborted")
1262
- return INVALID;
1263
- if (key.status === "dirty")
1264
- status.dirty();
1265
- if (value.status === "dirty")
1266
- status.dirty();
1267
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1268
- finalObject[key.value] = value.value;
1269
- }
1270
- }
1271
- return { status: status.value, value: finalObject };
1272
- }
1273
- };
1274
- var INVALID = Object.freeze({
1275
- status: "aborted"
1276
- });
1277
- var DIRTY = (value) => ({ status: "dirty", value });
1278
- var OK = (value) => ({ status: "valid", value });
1279
- var isAborted = (x) => x.status === "aborted";
1280
- var isDirty = (x) => x.status === "dirty";
1281
- var isValid = (x) => x.status === "valid";
1282
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1283
-
1284
- // node_modules/zod/v3/helpers/errorUtil.js
1285
- var errorUtil;
1286
- (function(errorUtil2) {
1287
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1288
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
1289
- })(errorUtil || (errorUtil = {}));
1290
-
1291
- // node_modules/zod/v3/types.js
1292
- var ParseInputLazyPath = class {
1293
- constructor(parent, value, path9, key) {
1294
- this._cachedPath = [];
1295
- this.parent = parent;
1296
- this.data = value;
1297
- this._path = path9;
1298
- this._key = key;
1299
- }
1300
- get path() {
1301
- if (!this._cachedPath.length) {
1302
- if (Array.isArray(this._key)) {
1303
- this._cachedPath.push(...this._path, ...this._key);
1304
- } else {
1305
- this._cachedPath.push(...this._path, this._key);
1306
- }
1307
- }
1308
- return this._cachedPath;
1309
- }
1310
- };
1311
- var handleResult = (ctx, result) => {
1312
- if (isValid(result)) {
1313
- return { success: true, data: result.value };
1314
- } else {
1315
- if (!ctx.common.issues.length) {
1316
- throw new Error("Validation failed but no issues detected.");
1317
- }
1318
- return {
1319
- success: false,
1320
- get error() {
1321
- if (this._error)
1322
- return this._error;
1323
- const error = new ZodError(ctx.common.issues);
1324
- this._error = error;
1325
- return this._error;
1326
- }
1327
- };
1328
- }
1329
- };
1330
- function processCreateParams(params) {
1331
- if (!params)
1332
- return {};
1333
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
1334
- if (errorMap2 && (invalid_type_error || required_error)) {
1335
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
1336
- }
1337
- if (errorMap2)
1338
- return { errorMap: errorMap2, description };
1339
- const customMap = (iss, ctx) => {
1340
- const { message } = params;
1341
- if (iss.code === "invalid_enum_value") {
1342
- return { message: message ?? ctx.defaultError };
1343
- }
1344
- if (typeof ctx.data === "undefined") {
1345
- return { message: message ?? required_error ?? ctx.defaultError };
1346
- }
1347
- if (iss.code !== "invalid_type")
1348
- return { message: ctx.defaultError };
1349
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
1350
- };
1351
- return { errorMap: customMap, description };
1352
- }
1353
- var ZodType = class {
1354
- get description() {
1355
- return this._def.description;
1356
- }
1357
- _getType(input) {
1358
- return getParsedType(input.data);
1359
- }
1360
- _getOrReturnCtx(input, ctx) {
1361
- return ctx || {
1362
- common: input.parent.common,
1363
- data: input.data,
1364
- parsedType: getParsedType(input.data),
1365
- schemaErrorMap: this._def.errorMap,
1366
- path: input.path,
1367
- parent: input.parent
1368
- };
1369
- }
1370
- _processInputParams(input) {
1371
- return {
1372
- status: new ParseStatus(),
1373
- ctx: {
1374
- common: input.parent.common,
1375
- data: input.data,
1376
- parsedType: getParsedType(input.data),
1377
- schemaErrorMap: this._def.errorMap,
1378
- path: input.path,
1379
- parent: input.parent
1380
- }
1381
- };
1382
- }
1383
- _parseSync(input) {
1384
- const result = this._parse(input);
1385
- if (isAsync(result)) {
1386
- throw new Error("Synchronous parse encountered promise.");
1387
- }
1388
- return result;
1389
- }
1390
- _parseAsync(input) {
1391
- const result = this._parse(input);
1392
- return Promise.resolve(result);
1393
- }
1394
- parse(data, params) {
1395
- const result = this.safeParse(data, params);
1396
- if (result.success)
1397
- return result.data;
1398
- throw result.error;
1399
- }
1400
- safeParse(data, params) {
1401
- const ctx = {
1402
- common: {
1403
- issues: [],
1404
- async: params?.async ?? false,
1405
- contextualErrorMap: params?.errorMap
1406
- },
1407
- path: params?.path || [],
1408
- schemaErrorMap: this._def.errorMap,
1409
- parent: null,
1410
- data,
1411
- parsedType: getParsedType(data)
1412
- };
1413
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1414
- return handleResult(ctx, result);
1415
- }
1416
- "~validate"(data) {
1417
- const ctx = {
1418
- common: {
1419
- issues: [],
1420
- async: !!this["~standard"].async
1421
- },
1422
- path: [],
1423
- schemaErrorMap: this._def.errorMap,
1424
- parent: null,
1425
- data,
1426
- parsedType: getParsedType(data)
1427
- };
1428
- if (!this["~standard"].async) {
1429
- try {
1430
- const result = this._parseSync({ data, path: [], parent: ctx });
1431
- return isValid(result) ? {
1432
- value: result.value
1433
- } : {
1434
- issues: ctx.common.issues
1435
- };
1436
- } catch (err) {
1437
- if (err?.message?.toLowerCase()?.includes("encountered")) {
1438
- this["~standard"].async = true;
1439
- }
1440
- ctx.common = {
1441
- issues: [],
1442
- async: true
1443
- };
1444
- }
1445
- }
1446
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1447
- value: result.value
1448
- } : {
1449
- issues: ctx.common.issues
1450
- });
1451
- }
1452
- async parseAsync(data, params) {
1453
- const result = await this.safeParseAsync(data, params);
1454
- if (result.success)
1455
- return result.data;
1456
- throw result.error;
1457
- }
1458
- async safeParseAsync(data, params) {
1459
- const ctx = {
1460
- common: {
1461
- issues: [],
1462
- contextualErrorMap: params?.errorMap,
1463
- async: true
1464
- },
1465
- path: params?.path || [],
1466
- schemaErrorMap: this._def.errorMap,
1467
- parent: null,
1468
- data,
1469
- parsedType: getParsedType(data)
1470
- };
1471
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1472
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1473
- return handleResult(ctx, result);
1474
- }
1475
- refine(check, message) {
1476
- const getIssueProperties = (val) => {
1477
- if (typeof message === "string" || typeof message === "undefined") {
1478
- return { message };
1479
- } else if (typeof message === "function") {
1480
- return message(val);
1481
- } else {
1482
- return message;
1483
- }
1484
- };
1485
- return this._refinement((val, ctx) => {
1486
- const result = check(val);
1487
- const setError = () => ctx.addIssue({
1488
- code: ZodIssueCode.custom,
1489
- ...getIssueProperties(val)
1490
- });
1491
- if (typeof Promise !== "undefined" && result instanceof Promise) {
1492
- return result.then((data) => {
1493
- if (!data) {
1494
- setError();
1495
- return false;
1496
- } else {
1497
- return true;
1498
- }
1499
- });
1500
- }
1501
- if (!result) {
1502
- setError();
1503
- return false;
1504
- } else {
1505
- return true;
1506
- }
1507
- });
1508
- }
1509
- refinement(check, refinementData) {
1510
- return this._refinement((val, ctx) => {
1511
- if (!check(val)) {
1512
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1513
- return false;
1514
- } else {
1515
- return true;
1516
- }
1517
- });
1518
- }
1519
- _refinement(refinement) {
1520
- return new ZodEffects({
1521
- schema: this,
1522
- typeName: ZodFirstPartyTypeKind.ZodEffects,
1523
- effect: { type: "refinement", refinement }
1524
- });
1525
- }
1526
- superRefine(refinement) {
1527
- return this._refinement(refinement);
1528
- }
1529
- constructor(def) {
1530
- this.spa = this.safeParseAsync;
1531
- this._def = def;
1532
- this.parse = this.parse.bind(this);
1533
- this.safeParse = this.safeParse.bind(this);
1534
- this.parseAsync = this.parseAsync.bind(this);
1535
- this.safeParseAsync = this.safeParseAsync.bind(this);
1536
- this.spa = this.spa.bind(this);
1537
- this.refine = this.refine.bind(this);
1538
- this.refinement = this.refinement.bind(this);
1539
- this.superRefine = this.superRefine.bind(this);
1540
- this.optional = this.optional.bind(this);
1541
- this.nullable = this.nullable.bind(this);
1542
- this.nullish = this.nullish.bind(this);
1543
- this.array = this.array.bind(this);
1544
- this.promise = this.promise.bind(this);
1545
- this.or = this.or.bind(this);
1546
- this.and = this.and.bind(this);
1547
- this.transform = this.transform.bind(this);
1548
- this.brand = this.brand.bind(this);
1549
- this.default = this.default.bind(this);
1550
- this.catch = this.catch.bind(this);
1551
- this.describe = this.describe.bind(this);
1552
- this.pipe = this.pipe.bind(this);
1553
- this.readonly = this.readonly.bind(this);
1554
- this.isNullable = this.isNullable.bind(this);
1555
- this.isOptional = this.isOptional.bind(this);
1556
- this["~standard"] = {
1557
- version: 1,
1558
- vendor: "zod",
1559
- validate: (data) => this["~validate"](data)
1560
- };
1561
- }
1562
- optional() {
1563
- return ZodOptional.create(this, this._def);
1564
- }
1565
- nullable() {
1566
- return ZodNullable.create(this, this._def);
1567
- }
1568
- nullish() {
1569
- return this.nullable().optional();
1570
- }
1571
- array() {
1572
- return ZodArray.create(this);
1573
- }
1574
- promise() {
1575
- return ZodPromise.create(this, this._def);
1576
- }
1577
- or(option) {
1578
- return ZodUnion.create([this, option], this._def);
1579
- }
1580
- and(incoming) {
1581
- return ZodIntersection.create(this, incoming, this._def);
1582
- }
1583
- transform(transform) {
1584
- return new ZodEffects({
1585
- ...processCreateParams(this._def),
1586
- schema: this,
1587
- typeName: ZodFirstPartyTypeKind.ZodEffects,
1588
- effect: { type: "transform", transform }
1589
- });
1590
- }
1591
- default(def) {
1592
- const defaultValueFunc = typeof def === "function" ? def : () => def;
1593
- return new ZodDefault({
1594
- ...processCreateParams(this._def),
1595
- innerType: this,
1596
- defaultValue: defaultValueFunc,
1597
- typeName: ZodFirstPartyTypeKind.ZodDefault
1598
- });
1599
- }
1600
- brand() {
1601
- return new ZodBranded({
1602
- typeName: ZodFirstPartyTypeKind.ZodBranded,
1603
- type: this,
1604
- ...processCreateParams(this._def)
1605
- });
1606
- }
1607
- catch(def) {
1608
- const catchValueFunc = typeof def === "function" ? def : () => def;
1609
- return new ZodCatch({
1610
- ...processCreateParams(this._def),
1611
- innerType: this,
1612
- catchValue: catchValueFunc,
1613
- typeName: ZodFirstPartyTypeKind.ZodCatch
1614
- });
1615
- }
1616
- describe(description) {
1617
- const This = this.constructor;
1618
- return new This({
1619
- ...this._def,
1620
- description
1621
- });
1622
- }
1623
- pipe(target) {
1624
- return ZodPipeline.create(this, target);
1625
- }
1626
- readonly() {
1627
- return ZodReadonly.create(this);
1628
- }
1629
- isOptional() {
1630
- return this.safeParse(void 0).success;
1631
- }
1632
- isNullable() {
1633
- return this.safeParse(null).success;
1634
- }
1635
- };
1636
- var cuidRegex = /^c[^\s-]{8,}$/i;
1637
- var cuid2Regex = /^[0-9a-z]+$/;
1638
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1639
- 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;
1640
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1641
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1642
- 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)?)??$/;
1643
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1644
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1645
- var emojiRegex;
1646
- 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])$/;
1647
- 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])$/;
1648
- 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]))$/;
1649
- 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])$/;
1650
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1651
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1652
- 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])))`;
1653
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
1654
- function timeRegexSource(args) {
1655
- let secondsRegexSource = `[0-5]\\d`;
1656
- if (args.precision) {
1657
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1658
- } else if (args.precision == null) {
1659
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1660
- }
1661
- const secondsQuantifier = args.precision ? "+" : "?";
1662
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1663
- }
1664
- function timeRegex(args) {
1665
- return new RegExp(`^${timeRegexSource(args)}$`);
1666
- }
1667
- function datetimeRegex(args) {
1668
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1669
- const opts = [];
1670
- opts.push(args.local ? `Z?` : `Z`);
1671
- if (args.offset)
1672
- opts.push(`([+-]\\d{2}:?\\d{2})`);
1673
- regex = `${regex}(${opts.join("|")})`;
1674
- return new RegExp(`^${regex}$`);
1675
- }
1676
- function isValidIP(ip, version) {
1677
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1678
- return true;
1679
- }
1680
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1681
- return true;
1682
- }
1683
- return false;
1684
- }
1685
- function isValidJWT(jwt, alg) {
1686
- if (!jwtRegex.test(jwt))
1687
- return false;
1688
- try {
1689
- const [header] = jwt.split(".");
1690
- if (!header)
1691
- return false;
1692
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1693
- const decoded = JSON.parse(atob(base64));
1694
- if (typeof decoded !== "object" || decoded === null)
1695
- return false;
1696
- if ("typ" in decoded && decoded?.typ !== "JWT")
1697
- return false;
1698
- if (!decoded.alg)
1699
- return false;
1700
- if (alg && decoded.alg !== alg)
1701
- return false;
1702
- return true;
1703
- } catch {
1704
- return false;
1705
- }
1706
- }
1707
- function isValidCidr(ip, version) {
1708
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1709
- return true;
1710
- }
1711
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1712
- return true;
1713
- }
1714
- return false;
1715
- }
1716
- var ZodString = class _ZodString extends ZodType {
1717
- _parse(input) {
1718
- if (this._def.coerce) {
1719
- input.data = String(input.data);
1720
- }
1721
- const parsedType = this._getType(input);
1722
- if (parsedType !== ZodParsedType.string) {
1723
- const ctx2 = this._getOrReturnCtx(input);
1724
- addIssueToContext(ctx2, {
1725
- code: ZodIssueCode.invalid_type,
1726
- expected: ZodParsedType.string,
1727
- received: ctx2.parsedType
1728
- });
1729
- return INVALID;
1730
- }
1731
- const status = new ParseStatus();
1732
- let ctx = void 0;
1733
- for (const check of this._def.checks) {
1734
- if (check.kind === "min") {
1735
- if (input.data.length < check.value) {
1736
- ctx = this._getOrReturnCtx(input, ctx);
1737
- addIssueToContext(ctx, {
1738
- code: ZodIssueCode.too_small,
1739
- minimum: check.value,
1740
- type: "string",
1741
- inclusive: true,
1742
- exact: false,
1743
- message: check.message
1744
- });
1745
- status.dirty();
1746
- }
1747
- } else if (check.kind === "max") {
1748
- if (input.data.length > check.value) {
1749
- ctx = this._getOrReturnCtx(input, ctx);
1750
- addIssueToContext(ctx, {
1751
- code: ZodIssueCode.too_big,
1752
- maximum: check.value,
1753
- type: "string",
1754
- inclusive: true,
1755
- exact: false,
1756
- message: check.message
1757
- });
1758
- status.dirty();
1759
- }
1760
- } else if (check.kind === "length") {
1761
- const tooBig = input.data.length > check.value;
1762
- const tooSmall = input.data.length < check.value;
1763
- if (tooBig || tooSmall) {
1764
- ctx = this._getOrReturnCtx(input, ctx);
1765
- if (tooBig) {
1766
- addIssueToContext(ctx, {
1767
- code: ZodIssueCode.too_big,
1768
- maximum: check.value,
1769
- type: "string",
1770
- inclusive: true,
1771
- exact: true,
1772
- message: check.message
1773
- });
1774
- } else if (tooSmall) {
1775
- addIssueToContext(ctx, {
1776
- code: ZodIssueCode.too_small,
1777
- minimum: check.value,
1778
- type: "string",
1779
- inclusive: true,
1780
- exact: true,
1781
- message: check.message
1782
- });
1783
- }
1784
- status.dirty();
1785
- }
1786
- } else if (check.kind === "email") {
1787
- if (!emailRegex.test(input.data)) {
1788
- ctx = this._getOrReturnCtx(input, ctx);
1789
- addIssueToContext(ctx, {
1790
- validation: "email",
1791
- code: ZodIssueCode.invalid_string,
1792
- message: check.message
1793
- });
1794
- status.dirty();
1795
- }
1796
- } else if (check.kind === "emoji") {
1797
- if (!emojiRegex) {
1798
- emojiRegex = new RegExp(_emojiRegex, "u");
1799
- }
1800
- if (!emojiRegex.test(input.data)) {
1801
- ctx = this._getOrReturnCtx(input, ctx);
1802
- addIssueToContext(ctx, {
1803
- validation: "emoji",
1804
- code: ZodIssueCode.invalid_string,
1805
- message: check.message
1806
- });
1807
- status.dirty();
1808
- }
1809
- } else if (check.kind === "uuid") {
1810
- if (!uuidRegex.test(input.data)) {
1811
- ctx = this._getOrReturnCtx(input, ctx);
1812
- addIssueToContext(ctx, {
1813
- validation: "uuid",
1814
- code: ZodIssueCode.invalid_string,
1815
- message: check.message
1816
- });
1817
- status.dirty();
1818
- }
1819
- } else if (check.kind === "nanoid") {
1820
- if (!nanoidRegex.test(input.data)) {
1821
- ctx = this._getOrReturnCtx(input, ctx);
1822
- addIssueToContext(ctx, {
1823
- validation: "nanoid",
1824
- code: ZodIssueCode.invalid_string,
1825
- message: check.message
1826
- });
1827
- status.dirty();
1828
- }
1829
- } else if (check.kind === "cuid") {
1830
- if (!cuidRegex.test(input.data)) {
1831
- ctx = this._getOrReturnCtx(input, ctx);
1832
- addIssueToContext(ctx, {
1833
- validation: "cuid",
1834
- code: ZodIssueCode.invalid_string,
1835
- message: check.message
1836
- });
1837
- status.dirty();
1838
- }
1839
- } else if (check.kind === "cuid2") {
1840
- if (!cuid2Regex.test(input.data)) {
1841
- ctx = this._getOrReturnCtx(input, ctx);
1842
- addIssueToContext(ctx, {
1843
- validation: "cuid2",
1844
- code: ZodIssueCode.invalid_string,
1845
- message: check.message
1846
- });
1847
- status.dirty();
1848
- }
1849
- } else if (check.kind === "ulid") {
1850
- if (!ulidRegex.test(input.data)) {
1851
- ctx = this._getOrReturnCtx(input, ctx);
1852
- addIssueToContext(ctx, {
1853
- validation: "ulid",
1854
- code: ZodIssueCode.invalid_string,
1855
- message: check.message
1856
- });
1857
- status.dirty();
1858
- }
1859
- } else if (check.kind === "url") {
1860
- try {
1861
- new URL(input.data);
1862
- } catch {
1863
- ctx = this._getOrReturnCtx(input, ctx);
1864
- addIssueToContext(ctx, {
1865
- validation: "url",
1866
- code: ZodIssueCode.invalid_string,
1867
- message: check.message
1868
- });
1869
- status.dirty();
1870
- }
1871
- } else if (check.kind === "regex") {
1872
- check.regex.lastIndex = 0;
1873
- const testResult = check.regex.test(input.data);
1874
- if (!testResult) {
1875
- ctx = this._getOrReturnCtx(input, ctx);
1876
- addIssueToContext(ctx, {
1877
- validation: "regex",
1878
- code: ZodIssueCode.invalid_string,
1879
- message: check.message
1880
- });
1881
- status.dirty();
1882
- }
1883
- } else if (check.kind === "trim") {
1884
- input.data = input.data.trim();
1885
- } else if (check.kind === "includes") {
1886
- if (!input.data.includes(check.value, check.position)) {
1887
- ctx = this._getOrReturnCtx(input, ctx);
1888
- addIssueToContext(ctx, {
1889
- code: ZodIssueCode.invalid_string,
1890
- validation: { includes: check.value, position: check.position },
1891
- message: check.message
1892
- });
1893
- status.dirty();
1894
- }
1895
- } else if (check.kind === "toLowerCase") {
1896
- input.data = input.data.toLowerCase();
1897
- } else if (check.kind === "toUpperCase") {
1898
- input.data = input.data.toUpperCase();
1899
- } else if (check.kind === "startsWith") {
1900
- if (!input.data.startsWith(check.value)) {
1901
- ctx = this._getOrReturnCtx(input, ctx);
1902
- addIssueToContext(ctx, {
1903
- code: ZodIssueCode.invalid_string,
1904
- validation: { startsWith: check.value },
1905
- message: check.message
1906
- });
1907
- status.dirty();
1908
- }
1909
- } else if (check.kind === "endsWith") {
1910
- if (!input.data.endsWith(check.value)) {
1911
- ctx = this._getOrReturnCtx(input, ctx);
1912
- addIssueToContext(ctx, {
1913
- code: ZodIssueCode.invalid_string,
1914
- validation: { endsWith: check.value },
1915
- message: check.message
1916
- });
1917
- status.dirty();
1918
- }
1919
- } else if (check.kind === "datetime") {
1920
- const regex = datetimeRegex(check);
1921
- if (!regex.test(input.data)) {
1922
- ctx = this._getOrReturnCtx(input, ctx);
1923
- addIssueToContext(ctx, {
1924
- code: ZodIssueCode.invalid_string,
1925
- validation: "datetime",
1926
- message: check.message
1927
- });
1928
- status.dirty();
1929
- }
1930
- } else if (check.kind === "date") {
1931
- const regex = dateRegex;
1932
- if (!regex.test(input.data)) {
1933
- ctx = this._getOrReturnCtx(input, ctx);
1934
- addIssueToContext(ctx, {
1935
- code: ZodIssueCode.invalid_string,
1936
- validation: "date",
1937
- message: check.message
1938
- });
1939
- status.dirty();
1940
- }
1941
- } else if (check.kind === "time") {
1942
- const regex = timeRegex(check);
1943
- if (!regex.test(input.data)) {
1944
- ctx = this._getOrReturnCtx(input, ctx);
1945
- addIssueToContext(ctx, {
1946
- code: ZodIssueCode.invalid_string,
1947
- validation: "time",
1948
- message: check.message
1949
- });
1950
- status.dirty();
1951
- }
1952
- } else if (check.kind === "duration") {
1953
- if (!durationRegex.test(input.data)) {
1954
- ctx = this._getOrReturnCtx(input, ctx);
1955
- addIssueToContext(ctx, {
1956
- validation: "duration",
1957
- code: ZodIssueCode.invalid_string,
1958
- message: check.message
1959
- });
1960
- status.dirty();
1961
- }
1962
- } else if (check.kind === "ip") {
1963
- if (!isValidIP(input.data, check.version)) {
1964
- ctx = this._getOrReturnCtx(input, ctx);
1965
- addIssueToContext(ctx, {
1966
- validation: "ip",
1967
- code: ZodIssueCode.invalid_string,
1968
- message: check.message
1969
- });
1970
- status.dirty();
1971
- }
1972
- } else if (check.kind === "jwt") {
1973
- if (!isValidJWT(input.data, check.alg)) {
1974
- ctx = this._getOrReturnCtx(input, ctx);
1975
- addIssueToContext(ctx, {
1976
- validation: "jwt",
1977
- code: ZodIssueCode.invalid_string,
1978
- message: check.message
1979
- });
1980
- status.dirty();
1981
- }
1982
- } else if (check.kind === "cidr") {
1983
- if (!isValidCidr(input.data, check.version)) {
1984
- ctx = this._getOrReturnCtx(input, ctx);
1985
- addIssueToContext(ctx, {
1986
- validation: "cidr",
1987
- code: ZodIssueCode.invalid_string,
1988
- message: check.message
1989
- });
1990
- status.dirty();
1991
- }
1992
- } else if (check.kind === "base64") {
1993
- if (!base64Regex.test(input.data)) {
1994
- ctx = this._getOrReturnCtx(input, ctx);
1995
- addIssueToContext(ctx, {
1996
- validation: "base64",
1997
- code: ZodIssueCode.invalid_string,
1998
- message: check.message
1999
- });
2000
- status.dirty();
2001
- }
2002
- } else if (check.kind === "base64url") {
2003
- if (!base64urlRegex.test(input.data)) {
2004
- ctx = this._getOrReturnCtx(input, ctx);
2005
- addIssueToContext(ctx, {
2006
- validation: "base64url",
2007
- code: ZodIssueCode.invalid_string,
2008
- message: check.message
2009
- });
2010
- status.dirty();
2011
- }
2012
- } else {
2013
- util.assertNever(check);
2014
- }
2015
- }
2016
- return { status: status.value, value: input.data };
2017
- }
2018
- _regex(regex, validation, message) {
2019
- return this.refinement((data) => regex.test(data), {
2020
- validation,
2021
- code: ZodIssueCode.invalid_string,
2022
- ...errorUtil.errToObj(message)
2023
- });
2024
- }
2025
- _addCheck(check) {
2026
- return new _ZodString({
2027
- ...this._def,
2028
- checks: [...this._def.checks, check]
2029
- });
2030
- }
2031
- email(message) {
2032
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
2033
- }
2034
- url(message) {
2035
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
2036
- }
2037
- emoji(message) {
2038
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
2039
- }
2040
- uuid(message) {
2041
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
2042
- }
2043
- nanoid(message) {
2044
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
2045
- }
2046
- cuid(message) {
2047
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
2048
- }
2049
- cuid2(message) {
2050
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
2051
- }
2052
- ulid(message) {
2053
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
2054
- }
2055
- base64(message) {
2056
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
2057
- }
2058
- base64url(message) {
2059
- return this._addCheck({
2060
- kind: "base64url",
2061
- ...errorUtil.errToObj(message)
2062
- });
2063
- }
2064
- jwt(options) {
2065
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
2066
- }
2067
- ip(options) {
2068
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
2069
- }
2070
- cidr(options) {
2071
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
2072
- }
2073
- datetime(options) {
2074
- if (typeof options === "string") {
2075
- return this._addCheck({
2076
- kind: "datetime",
2077
- precision: null,
2078
- offset: false,
2079
- local: false,
2080
- message: options
2081
- });
2082
- }
2083
- return this._addCheck({
2084
- kind: "datetime",
2085
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
2086
- offset: options?.offset ?? false,
2087
- local: options?.local ?? false,
2088
- ...errorUtil.errToObj(options?.message)
2089
- });
2090
- }
2091
- date(message) {
2092
- return this._addCheck({ kind: "date", message });
2093
- }
2094
- time(options) {
2095
- if (typeof options === "string") {
2096
- return this._addCheck({
2097
- kind: "time",
2098
- precision: null,
2099
- message: options
2100
- });
2101
- }
2102
- return this._addCheck({
2103
- kind: "time",
2104
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
2105
- ...errorUtil.errToObj(options?.message)
2106
- });
2107
- }
2108
- duration(message) {
2109
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
2110
- }
2111
- regex(regex, message) {
2112
- return this._addCheck({
2113
- kind: "regex",
2114
- regex,
2115
- ...errorUtil.errToObj(message)
2116
- });
2117
- }
2118
- includes(value, options) {
2119
- return this._addCheck({
2120
- kind: "includes",
2121
- value,
2122
- position: options?.position,
2123
- ...errorUtil.errToObj(options?.message)
2124
- });
2125
- }
2126
- startsWith(value, message) {
2127
- return this._addCheck({
2128
- kind: "startsWith",
2129
- value,
2130
- ...errorUtil.errToObj(message)
2131
- });
2132
- }
2133
- endsWith(value, message) {
2134
- return this._addCheck({
2135
- kind: "endsWith",
2136
- value,
2137
- ...errorUtil.errToObj(message)
2138
- });
2139
- }
2140
- min(minLength, message) {
2141
- return this._addCheck({
2142
- kind: "min",
2143
- value: minLength,
2144
- ...errorUtil.errToObj(message)
2145
- });
2146
- }
2147
- max(maxLength, message) {
2148
- return this._addCheck({
2149
- kind: "max",
2150
- value: maxLength,
2151
- ...errorUtil.errToObj(message)
2152
- });
2153
- }
2154
- length(len, message) {
2155
- return this._addCheck({
2156
- kind: "length",
2157
- value: len,
2158
- ...errorUtil.errToObj(message)
2159
- });
2160
- }
2161
- /**
2162
- * Equivalent to `.min(1)`
2163
- */
2164
- nonempty(message) {
2165
- return this.min(1, errorUtil.errToObj(message));
2166
- }
2167
- trim() {
2168
- return new _ZodString({
2169
- ...this._def,
2170
- checks: [...this._def.checks, { kind: "trim" }]
2171
- });
2172
- }
2173
- toLowerCase() {
2174
- return new _ZodString({
2175
- ...this._def,
2176
- checks: [...this._def.checks, { kind: "toLowerCase" }]
2177
- });
2178
- }
2179
- toUpperCase() {
2180
- return new _ZodString({
2181
- ...this._def,
2182
- checks: [...this._def.checks, { kind: "toUpperCase" }]
2183
- });
2184
- }
2185
- get isDatetime() {
2186
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
2187
- }
2188
- get isDate() {
2189
- return !!this._def.checks.find((ch) => ch.kind === "date");
2190
- }
2191
- get isTime() {
2192
- return !!this._def.checks.find((ch) => ch.kind === "time");
2193
- }
2194
- get isDuration() {
2195
- return !!this._def.checks.find((ch) => ch.kind === "duration");
2196
- }
2197
- get isEmail() {
2198
- return !!this._def.checks.find((ch) => ch.kind === "email");
2199
- }
2200
- get isURL() {
2201
- return !!this._def.checks.find((ch) => ch.kind === "url");
2202
- }
2203
- get isEmoji() {
2204
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
2205
- }
2206
- get isUUID() {
2207
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
2208
- }
2209
- get isNANOID() {
2210
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
2211
- }
2212
- get isCUID() {
2213
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
2214
- }
2215
- get isCUID2() {
2216
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
2217
- }
2218
- get isULID() {
2219
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
2220
- }
2221
- get isIP() {
2222
- return !!this._def.checks.find((ch) => ch.kind === "ip");
2223
- }
2224
- get isCIDR() {
2225
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
2226
- }
2227
- get isBase64() {
2228
- return !!this._def.checks.find((ch) => ch.kind === "base64");
2229
- }
2230
- get isBase64url() {
2231
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
2232
- }
2233
- get minLength() {
2234
- let min = null;
2235
- for (const ch of this._def.checks) {
2236
- if (ch.kind === "min") {
2237
- if (min === null || ch.value > min)
2238
- min = ch.value;
2239
- }
2240
- }
2241
- return min;
2242
- }
2243
- get maxLength() {
2244
- let max = null;
2245
- for (const ch of this._def.checks) {
2246
- if (ch.kind === "max") {
2247
- if (max === null || ch.value < max)
2248
- max = ch.value;
2249
- }
2250
- }
2251
- return max;
2252
- }
2253
- };
2254
- ZodString.create = (params) => {
2255
- return new ZodString({
2256
- checks: [],
2257
- typeName: ZodFirstPartyTypeKind.ZodString,
2258
- coerce: params?.coerce ?? false,
2259
- ...processCreateParams(params)
2260
- });
2261
- };
2262
- function floatSafeRemainder(val, step) {
2263
- const valDecCount = (val.toString().split(".")[1] || "").length;
2264
- const stepDecCount = (step.toString().split(".")[1] || "").length;
2265
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
2266
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
2267
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
2268
- return valInt % stepInt / 10 ** decCount;
2269
- }
2270
- var ZodNumber = class _ZodNumber extends ZodType {
2271
- constructor() {
2272
- super(...arguments);
2273
- this.min = this.gte;
2274
- this.max = this.lte;
2275
- this.step = this.multipleOf;
2276
- }
2277
- _parse(input) {
2278
- if (this._def.coerce) {
2279
- input.data = Number(input.data);
2280
- }
2281
- const parsedType = this._getType(input);
2282
- if (parsedType !== ZodParsedType.number) {
2283
- const ctx2 = this._getOrReturnCtx(input);
2284
- addIssueToContext(ctx2, {
2285
- code: ZodIssueCode.invalid_type,
2286
- expected: ZodParsedType.number,
2287
- received: ctx2.parsedType
2288
- });
2289
- return INVALID;
2290
- }
2291
- let ctx = void 0;
2292
- const status = new ParseStatus();
2293
- for (const check of this._def.checks) {
2294
- if (check.kind === "int") {
2295
- if (!util.isInteger(input.data)) {
2296
- ctx = this._getOrReturnCtx(input, ctx);
2297
- addIssueToContext(ctx, {
2298
- code: ZodIssueCode.invalid_type,
2299
- expected: "integer",
2300
- received: "float",
2301
- message: check.message
2302
- });
2303
- status.dirty();
2304
- }
2305
- } else if (check.kind === "min") {
2306
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2307
- if (tooSmall) {
2308
- ctx = this._getOrReturnCtx(input, ctx);
2309
- addIssueToContext(ctx, {
2310
- code: ZodIssueCode.too_small,
2311
- minimum: check.value,
2312
- type: "number",
2313
- inclusive: check.inclusive,
2314
- exact: false,
2315
- message: check.message
2316
- });
2317
- status.dirty();
2318
- }
2319
- } else if (check.kind === "max") {
2320
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2321
- if (tooBig) {
2322
- ctx = this._getOrReturnCtx(input, ctx);
2323
- addIssueToContext(ctx, {
2324
- code: ZodIssueCode.too_big,
2325
- maximum: check.value,
2326
- type: "number",
2327
- inclusive: check.inclusive,
2328
- exact: false,
2329
- message: check.message
2330
- });
2331
- status.dirty();
2332
- }
2333
- } else if (check.kind === "multipleOf") {
2334
- if (floatSafeRemainder(input.data, check.value) !== 0) {
2335
- ctx = this._getOrReturnCtx(input, ctx);
2336
- addIssueToContext(ctx, {
2337
- code: ZodIssueCode.not_multiple_of,
2338
- multipleOf: check.value,
2339
- message: check.message
2340
- });
2341
- status.dirty();
2342
- }
2343
- } else if (check.kind === "finite") {
2344
- if (!Number.isFinite(input.data)) {
2345
- ctx = this._getOrReturnCtx(input, ctx);
2346
- addIssueToContext(ctx, {
2347
- code: ZodIssueCode.not_finite,
2348
- message: check.message
2349
- });
2350
- status.dirty();
2351
- }
2352
- } else {
2353
- util.assertNever(check);
2354
- }
2355
- }
2356
- return { status: status.value, value: input.data };
2357
- }
2358
- gte(value, message) {
2359
- return this.setLimit("min", value, true, errorUtil.toString(message));
2360
- }
2361
- gt(value, message) {
2362
- return this.setLimit("min", value, false, errorUtil.toString(message));
2363
- }
2364
- lte(value, message) {
2365
- return this.setLimit("max", value, true, errorUtil.toString(message));
2366
- }
2367
- lt(value, message) {
2368
- return this.setLimit("max", value, false, errorUtil.toString(message));
2369
- }
2370
- setLimit(kind, value, inclusive, message) {
2371
- return new _ZodNumber({
2372
- ...this._def,
2373
- checks: [
2374
- ...this._def.checks,
2375
- {
2376
- kind,
2377
- value,
2378
- inclusive,
2379
- message: errorUtil.toString(message)
2380
- }
2381
- ]
2382
- });
2383
- }
2384
- _addCheck(check) {
2385
- return new _ZodNumber({
2386
- ...this._def,
2387
- checks: [...this._def.checks, check]
2388
- });
2389
- }
2390
- int(message) {
2391
- return this._addCheck({
2392
- kind: "int",
2393
- message: errorUtil.toString(message)
2394
- });
2395
- }
2396
- positive(message) {
2397
- return this._addCheck({
2398
- kind: "min",
2399
- value: 0,
2400
- inclusive: false,
2401
- message: errorUtil.toString(message)
2402
- });
2403
- }
2404
- negative(message) {
2405
- return this._addCheck({
2406
- kind: "max",
2407
- value: 0,
2408
- inclusive: false,
2409
- message: errorUtil.toString(message)
2410
- });
2411
- }
2412
- nonpositive(message) {
2413
- return this._addCheck({
2414
- kind: "max",
2415
- value: 0,
2416
- inclusive: true,
2417
- message: errorUtil.toString(message)
2418
- });
2419
- }
2420
- nonnegative(message) {
2421
- return this._addCheck({
2422
- kind: "min",
2423
- value: 0,
2424
- inclusive: true,
2425
- message: errorUtil.toString(message)
2426
- });
2427
- }
2428
- multipleOf(value, message) {
2429
- return this._addCheck({
2430
- kind: "multipleOf",
2431
- value,
2432
- message: errorUtil.toString(message)
2433
- });
2434
- }
2435
- finite(message) {
2436
- return this._addCheck({
2437
- kind: "finite",
2438
- message: errorUtil.toString(message)
2439
- });
2440
- }
2441
- safe(message) {
2442
- return this._addCheck({
2443
- kind: "min",
2444
- inclusive: true,
2445
- value: Number.MIN_SAFE_INTEGER,
2446
- message: errorUtil.toString(message)
2447
- })._addCheck({
2448
- kind: "max",
2449
- inclusive: true,
2450
- value: Number.MAX_SAFE_INTEGER,
2451
- message: errorUtil.toString(message)
2452
- });
2453
- }
2454
- get minValue() {
2455
- let min = null;
2456
- for (const ch of this._def.checks) {
2457
- if (ch.kind === "min") {
2458
- if (min === null || ch.value > min)
2459
- min = ch.value;
2460
- }
2461
- }
2462
- return min;
2463
- }
2464
- get maxValue() {
2465
- let max = null;
2466
- for (const ch of this._def.checks) {
2467
- if (ch.kind === "max") {
2468
- if (max === null || ch.value < max)
2469
- max = ch.value;
2470
- }
2471
- }
2472
- return max;
2473
- }
2474
- get isInt() {
2475
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
2476
- }
2477
- get isFinite() {
2478
- let max = null;
2479
- let min = null;
2480
- for (const ch of this._def.checks) {
2481
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
2482
- return true;
2483
- } else if (ch.kind === "min") {
2484
- if (min === null || ch.value > min)
2485
- min = ch.value;
2486
- } else if (ch.kind === "max") {
2487
- if (max === null || ch.value < max)
2488
- max = ch.value;
2489
- }
2490
- }
2491
- return Number.isFinite(min) && Number.isFinite(max);
2492
- }
2493
- };
2494
- ZodNumber.create = (params) => {
2495
- return new ZodNumber({
2496
- checks: [],
2497
- typeName: ZodFirstPartyTypeKind.ZodNumber,
2498
- coerce: params?.coerce || false,
2499
- ...processCreateParams(params)
2500
- });
2501
- };
2502
- var ZodBigInt = class _ZodBigInt extends ZodType {
2503
- constructor() {
2504
- super(...arguments);
2505
- this.min = this.gte;
2506
- this.max = this.lte;
2507
- }
2508
- _parse(input) {
2509
- if (this._def.coerce) {
2510
- try {
2511
- input.data = BigInt(input.data);
2512
- } catch {
2513
- return this._getInvalidInput(input);
2514
- }
2515
- }
2516
- const parsedType = this._getType(input);
2517
- if (parsedType !== ZodParsedType.bigint) {
2518
- return this._getInvalidInput(input);
2519
- }
2520
- let ctx = void 0;
2521
- const status = new ParseStatus();
2522
- for (const check of this._def.checks) {
2523
- if (check.kind === "min") {
2524
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2525
- if (tooSmall) {
2526
- ctx = this._getOrReturnCtx(input, ctx);
2527
- addIssueToContext(ctx, {
2528
- code: ZodIssueCode.too_small,
2529
- type: "bigint",
2530
- minimum: check.value,
2531
- inclusive: check.inclusive,
2532
- message: check.message
2533
- });
2534
- status.dirty();
2535
- }
2536
- } else if (check.kind === "max") {
2537
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2538
- if (tooBig) {
2539
- ctx = this._getOrReturnCtx(input, ctx);
2540
- addIssueToContext(ctx, {
2541
- code: ZodIssueCode.too_big,
2542
- type: "bigint",
2543
- maximum: check.value,
2544
- inclusive: check.inclusive,
2545
- message: check.message
2546
- });
2547
- status.dirty();
2548
- }
2549
- } else if (check.kind === "multipleOf") {
2550
- if (input.data % check.value !== BigInt(0)) {
2551
- ctx = this._getOrReturnCtx(input, ctx);
2552
- addIssueToContext(ctx, {
2553
- code: ZodIssueCode.not_multiple_of,
2554
- multipleOf: check.value,
2555
- message: check.message
2556
- });
2557
- status.dirty();
2558
- }
2559
- } else {
2560
- util.assertNever(check);
2561
- }
2562
- }
2563
- return { status: status.value, value: input.data };
2564
- }
2565
- _getInvalidInput(input) {
2566
- const ctx = this._getOrReturnCtx(input);
2567
- addIssueToContext(ctx, {
2568
- code: ZodIssueCode.invalid_type,
2569
- expected: ZodParsedType.bigint,
2570
- received: ctx.parsedType
2571
- });
2572
- return INVALID;
2573
- }
2574
- gte(value, message) {
2575
- return this.setLimit("min", value, true, errorUtil.toString(message));
2576
- }
2577
- gt(value, message) {
2578
- return this.setLimit("min", value, false, errorUtil.toString(message));
2579
- }
2580
- lte(value, message) {
2581
- return this.setLimit("max", value, true, errorUtil.toString(message));
2582
- }
2583
- lt(value, message) {
2584
- return this.setLimit("max", value, false, errorUtil.toString(message));
2585
- }
2586
- setLimit(kind, value, inclusive, message) {
2587
- return new _ZodBigInt({
2588
- ...this._def,
2589
- checks: [
2590
- ...this._def.checks,
2591
- {
2592
- kind,
2593
- value,
2594
- inclusive,
2595
- message: errorUtil.toString(message)
2596
- }
2597
- ]
2598
- });
2599
- }
2600
- _addCheck(check) {
2601
- return new _ZodBigInt({
2602
- ...this._def,
2603
- checks: [...this._def.checks, check]
2604
- });
2605
- }
2606
- positive(message) {
2607
- return this._addCheck({
2608
- kind: "min",
2609
- value: BigInt(0),
2610
- inclusive: false,
2611
- message: errorUtil.toString(message)
2612
- });
2613
- }
2614
- negative(message) {
2615
- return this._addCheck({
2616
- kind: "max",
2617
- value: BigInt(0),
2618
- inclusive: false,
2619
- message: errorUtil.toString(message)
2620
- });
2621
- }
2622
- nonpositive(message) {
2623
- return this._addCheck({
2624
- kind: "max",
2625
- value: BigInt(0),
2626
- inclusive: true,
2627
- message: errorUtil.toString(message)
2628
- });
2629
- }
2630
- nonnegative(message) {
2631
- return this._addCheck({
2632
- kind: "min",
2633
- value: BigInt(0),
2634
- inclusive: true,
2635
- message: errorUtil.toString(message)
2636
- });
2637
- }
2638
- multipleOf(value, message) {
2639
- return this._addCheck({
2640
- kind: "multipleOf",
2641
- value,
2642
- message: errorUtil.toString(message)
2643
- });
2644
- }
2645
- get minValue() {
2646
- let min = null;
2647
- for (const ch of this._def.checks) {
2648
- if (ch.kind === "min") {
2649
- if (min === null || ch.value > min)
2650
- min = ch.value;
2651
- }
2652
- }
2653
- return min;
2654
- }
2655
- get maxValue() {
2656
- let max = null;
2657
- for (const ch of this._def.checks) {
2658
- if (ch.kind === "max") {
2659
- if (max === null || ch.value < max)
2660
- max = ch.value;
2661
- }
2662
- }
2663
- return max;
2664
- }
2665
- };
2666
- ZodBigInt.create = (params) => {
2667
- return new ZodBigInt({
2668
- checks: [],
2669
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
2670
- coerce: params?.coerce ?? false,
2671
- ...processCreateParams(params)
2672
- });
2673
- };
2674
- var ZodBoolean = class extends ZodType {
2675
- _parse(input) {
2676
- if (this._def.coerce) {
2677
- input.data = Boolean(input.data);
2678
- }
2679
- const parsedType = this._getType(input);
2680
- if (parsedType !== ZodParsedType.boolean) {
2681
- const ctx = this._getOrReturnCtx(input);
2682
- addIssueToContext(ctx, {
2683
- code: ZodIssueCode.invalid_type,
2684
- expected: ZodParsedType.boolean,
2685
- received: ctx.parsedType
2686
- });
2687
- return INVALID;
2688
- }
2689
- return OK(input.data);
2690
- }
2691
- };
2692
- ZodBoolean.create = (params) => {
2693
- return new ZodBoolean({
2694
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2695
- coerce: params?.coerce || false,
2696
- ...processCreateParams(params)
2697
- });
2698
- };
2699
- var ZodDate = class _ZodDate extends ZodType {
2700
- _parse(input) {
2701
- if (this._def.coerce) {
2702
- input.data = new Date(input.data);
2703
- }
2704
- const parsedType = this._getType(input);
2705
- if (parsedType !== ZodParsedType.date) {
2706
- const ctx2 = this._getOrReturnCtx(input);
2707
- addIssueToContext(ctx2, {
2708
- code: ZodIssueCode.invalid_type,
2709
- expected: ZodParsedType.date,
2710
- received: ctx2.parsedType
2711
- });
2712
- return INVALID;
2713
- }
2714
- if (Number.isNaN(input.data.getTime())) {
2715
- const ctx2 = this._getOrReturnCtx(input);
2716
- addIssueToContext(ctx2, {
2717
- code: ZodIssueCode.invalid_date
2718
- });
2719
- return INVALID;
2720
- }
2721
- const status = new ParseStatus();
2722
- let ctx = void 0;
2723
- for (const check of this._def.checks) {
2724
- if (check.kind === "min") {
2725
- if (input.data.getTime() < check.value) {
2726
- ctx = this._getOrReturnCtx(input, ctx);
2727
- addIssueToContext(ctx, {
2728
- code: ZodIssueCode.too_small,
2729
- message: check.message,
2730
- inclusive: true,
2731
- exact: false,
2732
- minimum: check.value,
2733
- type: "date"
2734
- });
2735
- status.dirty();
2736
- }
2737
- } else if (check.kind === "max") {
2738
- if (input.data.getTime() > check.value) {
2739
- ctx = this._getOrReturnCtx(input, ctx);
2740
- addIssueToContext(ctx, {
2741
- code: ZodIssueCode.too_big,
2742
- message: check.message,
2743
- inclusive: true,
2744
- exact: false,
2745
- maximum: check.value,
2746
- type: "date"
2747
- });
2748
- status.dirty();
2749
- }
2750
- } else {
2751
- util.assertNever(check);
2752
- }
2753
- }
2754
- return {
2755
- status: status.value,
2756
- value: new Date(input.data.getTime())
2757
- };
2758
- }
2759
- _addCheck(check) {
2760
- return new _ZodDate({
2761
- ...this._def,
2762
- checks: [...this._def.checks, check]
2763
- });
2764
- }
2765
- min(minDate, message) {
2766
- return this._addCheck({
2767
- kind: "min",
2768
- value: minDate.getTime(),
2769
- message: errorUtil.toString(message)
2770
- });
2771
- }
2772
- max(maxDate, message) {
2773
- return this._addCheck({
2774
- kind: "max",
2775
- value: maxDate.getTime(),
2776
- message: errorUtil.toString(message)
2777
- });
2778
- }
2779
- get minDate() {
2780
- let min = null;
2781
- for (const ch of this._def.checks) {
2782
- if (ch.kind === "min") {
2783
- if (min === null || ch.value > min)
2784
- min = ch.value;
2785
- }
2786
- }
2787
- return min != null ? new Date(min) : null;
2788
- }
2789
- get maxDate() {
2790
- let max = null;
2791
- for (const ch of this._def.checks) {
2792
- if (ch.kind === "max") {
2793
- if (max === null || ch.value < max)
2794
- max = ch.value;
2795
- }
2796
- }
2797
- return max != null ? new Date(max) : null;
2798
- }
2799
- };
2800
- ZodDate.create = (params) => {
2801
- return new ZodDate({
2802
- checks: [],
2803
- coerce: params?.coerce || false,
2804
- typeName: ZodFirstPartyTypeKind.ZodDate,
2805
- ...processCreateParams(params)
2806
- });
2807
- };
2808
- var ZodSymbol = class extends ZodType {
2809
- _parse(input) {
2810
- const parsedType = this._getType(input);
2811
- if (parsedType !== ZodParsedType.symbol) {
2812
- const ctx = this._getOrReturnCtx(input);
2813
- addIssueToContext(ctx, {
2814
- code: ZodIssueCode.invalid_type,
2815
- expected: ZodParsedType.symbol,
2816
- received: ctx.parsedType
2817
- });
2818
- return INVALID;
2819
- }
2820
- return OK(input.data);
2821
- }
2822
- };
2823
- ZodSymbol.create = (params) => {
2824
- return new ZodSymbol({
2825
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2826
- ...processCreateParams(params)
2827
- });
2828
- };
2829
- var ZodUndefined = class extends ZodType {
2830
- _parse(input) {
2831
- const parsedType = this._getType(input);
2832
- if (parsedType !== ZodParsedType.undefined) {
2833
- const ctx = this._getOrReturnCtx(input);
2834
- addIssueToContext(ctx, {
2835
- code: ZodIssueCode.invalid_type,
2836
- expected: ZodParsedType.undefined,
2837
- received: ctx.parsedType
2838
- });
2839
- return INVALID;
2840
- }
2841
- return OK(input.data);
2842
- }
2843
- };
2844
- ZodUndefined.create = (params) => {
2845
- return new ZodUndefined({
2846
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2847
- ...processCreateParams(params)
2848
- });
2849
- };
2850
- var ZodNull = class extends ZodType {
2851
- _parse(input) {
2852
- const parsedType = this._getType(input);
2853
- if (parsedType !== ZodParsedType.null) {
2854
- const ctx = this._getOrReturnCtx(input);
2855
- addIssueToContext(ctx, {
2856
- code: ZodIssueCode.invalid_type,
2857
- expected: ZodParsedType.null,
2858
- received: ctx.parsedType
2859
- });
2860
- return INVALID;
2861
- }
2862
- return OK(input.data);
2863
- }
2864
- };
2865
- ZodNull.create = (params) => {
2866
- return new ZodNull({
2867
- typeName: ZodFirstPartyTypeKind.ZodNull,
2868
- ...processCreateParams(params)
2869
- });
2870
- };
2871
- var ZodAny = class extends ZodType {
2872
- constructor() {
2873
- super(...arguments);
2874
- this._any = true;
2875
- }
2876
- _parse(input) {
2877
- return OK(input.data);
2878
- }
2879
- };
2880
- ZodAny.create = (params) => {
2881
- return new ZodAny({
2882
- typeName: ZodFirstPartyTypeKind.ZodAny,
2883
- ...processCreateParams(params)
2884
- });
2885
- };
2886
- var ZodUnknown = class extends ZodType {
2887
- constructor() {
2888
- super(...arguments);
2889
- this._unknown = true;
2890
- }
2891
- _parse(input) {
2892
- return OK(input.data);
2893
- }
2894
- };
2895
- ZodUnknown.create = (params) => {
2896
- return new ZodUnknown({
2897
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2898
- ...processCreateParams(params)
2899
- });
2900
- };
2901
- var ZodNever = class extends ZodType {
2902
- _parse(input) {
2903
- const ctx = this._getOrReturnCtx(input);
2904
- addIssueToContext(ctx, {
2905
- code: ZodIssueCode.invalid_type,
2906
- expected: ZodParsedType.never,
2907
- received: ctx.parsedType
2908
- });
2909
- return INVALID;
2910
- }
2911
- };
2912
- ZodNever.create = (params) => {
2913
- return new ZodNever({
2914
- typeName: ZodFirstPartyTypeKind.ZodNever,
2915
- ...processCreateParams(params)
2916
- });
2917
- };
2918
- var ZodVoid = class extends ZodType {
2919
- _parse(input) {
2920
- const parsedType = this._getType(input);
2921
- if (parsedType !== ZodParsedType.undefined) {
2922
- const ctx = this._getOrReturnCtx(input);
2923
- addIssueToContext(ctx, {
2924
- code: ZodIssueCode.invalid_type,
2925
- expected: ZodParsedType.void,
2926
- received: ctx.parsedType
2927
- });
2928
- return INVALID;
2929
- }
2930
- return OK(input.data);
2931
- }
2932
- };
2933
- ZodVoid.create = (params) => {
2934
- return new ZodVoid({
2935
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2936
- ...processCreateParams(params)
2937
- });
2938
- };
2939
- var ZodArray = class _ZodArray extends ZodType {
2940
- _parse(input) {
2941
- const { ctx, status } = this._processInputParams(input);
2942
- const def = this._def;
2943
- if (ctx.parsedType !== ZodParsedType.array) {
2944
- addIssueToContext(ctx, {
2945
- code: ZodIssueCode.invalid_type,
2946
- expected: ZodParsedType.array,
2947
- received: ctx.parsedType
2948
- });
2949
- return INVALID;
2950
- }
2951
- if (def.exactLength !== null) {
2952
- const tooBig = ctx.data.length > def.exactLength.value;
2953
- const tooSmall = ctx.data.length < def.exactLength.value;
2954
- if (tooBig || tooSmall) {
2955
- addIssueToContext(ctx, {
2956
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2957
- minimum: tooSmall ? def.exactLength.value : void 0,
2958
- maximum: tooBig ? def.exactLength.value : void 0,
2959
- type: "array",
2960
- inclusive: true,
2961
- exact: true,
2962
- message: def.exactLength.message
2963
- });
2964
- status.dirty();
2965
- }
2966
- }
2967
- if (def.minLength !== null) {
2968
- if (ctx.data.length < def.minLength.value) {
2969
- addIssueToContext(ctx, {
2970
- code: ZodIssueCode.too_small,
2971
- minimum: def.minLength.value,
2972
- type: "array",
2973
- inclusive: true,
2974
- exact: false,
2975
- message: def.minLength.message
2976
- });
2977
- status.dirty();
2978
- }
2979
- }
2980
- if (def.maxLength !== null) {
2981
- if (ctx.data.length > def.maxLength.value) {
2982
- addIssueToContext(ctx, {
2983
- code: ZodIssueCode.too_big,
2984
- maximum: def.maxLength.value,
2985
- type: "array",
2986
- inclusive: true,
2987
- exact: false,
2988
- message: def.maxLength.message
2989
- });
2990
- status.dirty();
2991
- }
2992
- }
2993
- if (ctx.common.async) {
2994
- return Promise.all([...ctx.data].map((item, i) => {
2995
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2996
- })).then((result2) => {
2997
- return ParseStatus.mergeArray(status, result2);
2998
- });
2999
- }
3000
- const result = [...ctx.data].map((item, i) => {
3001
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3002
- });
3003
- return ParseStatus.mergeArray(status, result);
3004
- }
3005
- get element() {
3006
- return this._def.type;
3007
- }
3008
- min(minLength, message) {
3009
- return new _ZodArray({
3010
- ...this._def,
3011
- minLength: { value: minLength, message: errorUtil.toString(message) }
3012
- });
3013
- }
3014
- max(maxLength, message) {
3015
- return new _ZodArray({
3016
- ...this._def,
3017
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
3018
- });
3019
- }
3020
- length(len, message) {
3021
- return new _ZodArray({
3022
- ...this._def,
3023
- exactLength: { value: len, message: errorUtil.toString(message) }
3024
- });
3025
- }
3026
- nonempty(message) {
3027
- return this.min(1, message);
3028
- }
3029
- };
3030
- ZodArray.create = (schema, params) => {
3031
- return new ZodArray({
3032
- type: schema,
3033
- minLength: null,
3034
- maxLength: null,
3035
- exactLength: null,
3036
- typeName: ZodFirstPartyTypeKind.ZodArray,
3037
- ...processCreateParams(params)
3038
- });
3039
- };
3040
- function deepPartialify(schema) {
3041
- if (schema instanceof ZodObject) {
3042
- const newShape = {};
3043
- for (const key in schema.shape) {
3044
- const fieldSchema = schema.shape[key];
3045
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
3046
- }
3047
- return new ZodObject({
3048
- ...schema._def,
3049
- shape: () => newShape
3050
- });
3051
- } else if (schema instanceof ZodArray) {
3052
- return new ZodArray({
3053
- ...schema._def,
3054
- type: deepPartialify(schema.element)
3055
- });
3056
- } else if (schema instanceof ZodOptional) {
3057
- return ZodOptional.create(deepPartialify(schema.unwrap()));
3058
- } else if (schema instanceof ZodNullable) {
3059
- return ZodNullable.create(deepPartialify(schema.unwrap()));
3060
- } else if (schema instanceof ZodTuple) {
3061
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
3062
- } else {
3063
- return schema;
3064
- }
3065
- }
3066
- var ZodObject = class _ZodObject extends ZodType {
3067
- constructor() {
3068
- super(...arguments);
3069
- this._cached = null;
3070
- this.nonstrict = this.passthrough;
3071
- this.augment = this.extend;
3072
- }
3073
- _getCached() {
3074
- if (this._cached !== null)
3075
- return this._cached;
3076
- const shape = this._def.shape();
3077
- const keys = util.objectKeys(shape);
3078
- this._cached = { shape, keys };
3079
- return this._cached;
3080
- }
3081
- _parse(input) {
3082
- const parsedType = this._getType(input);
3083
- if (parsedType !== ZodParsedType.object) {
3084
- const ctx2 = this._getOrReturnCtx(input);
3085
- addIssueToContext(ctx2, {
3086
- code: ZodIssueCode.invalid_type,
3087
- expected: ZodParsedType.object,
3088
- received: ctx2.parsedType
3089
- });
3090
- return INVALID;
3091
- }
3092
- const { status, ctx } = this._processInputParams(input);
3093
- const { shape, keys: shapeKeys } = this._getCached();
3094
- const extraKeys = [];
3095
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
3096
- for (const key in ctx.data) {
3097
- if (!shapeKeys.includes(key)) {
3098
- extraKeys.push(key);
3099
- }
3100
- }
3101
- }
3102
- const pairs = [];
3103
- for (const key of shapeKeys) {
3104
- const keyValidator = shape[key];
3105
- const value = ctx.data[key];
3106
- pairs.push({
3107
- key: { status: "valid", value: key },
3108
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
3109
- alwaysSet: key in ctx.data
3110
- });
3111
- }
3112
- if (this._def.catchall instanceof ZodNever) {
3113
- const unknownKeys = this._def.unknownKeys;
3114
- if (unknownKeys === "passthrough") {
3115
- for (const key of extraKeys) {
3116
- pairs.push({
3117
- key: { status: "valid", value: key },
3118
- value: { status: "valid", value: ctx.data[key] }
3119
- });
3120
- }
3121
- } else if (unknownKeys === "strict") {
3122
- if (extraKeys.length > 0) {
3123
- addIssueToContext(ctx, {
3124
- code: ZodIssueCode.unrecognized_keys,
3125
- keys: extraKeys
3126
- });
3127
- status.dirty();
3128
- }
3129
- } else if (unknownKeys === "strip") {
3130
- } else {
3131
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
3132
- }
3133
- } else {
3134
- const catchall = this._def.catchall;
3135
- for (const key of extraKeys) {
3136
- const value = ctx.data[key];
3137
- pairs.push({
3138
- key: { status: "valid", value: key },
3139
- value: catchall._parse(
3140
- new ParseInputLazyPath(ctx, value, ctx.path, key)
3141
- //, ctx.child(key), value, getParsedType(value)
3142
- ),
3143
- alwaysSet: key in ctx.data
3144
- });
3145
- }
3146
- }
3147
- if (ctx.common.async) {
3148
- return Promise.resolve().then(async () => {
3149
- const syncPairs = [];
3150
- for (const pair of pairs) {
3151
- const key = await pair.key;
3152
- const value = await pair.value;
3153
- syncPairs.push({
3154
- key,
3155
- value,
3156
- alwaysSet: pair.alwaysSet
3157
- });
3158
- }
3159
- return syncPairs;
3160
- }).then((syncPairs) => {
3161
- return ParseStatus.mergeObjectSync(status, syncPairs);
3162
- });
3163
- } else {
3164
- return ParseStatus.mergeObjectSync(status, pairs);
3165
- }
3166
- }
3167
- get shape() {
3168
- return this._def.shape();
3169
- }
3170
- strict(message) {
3171
- errorUtil.errToObj;
3172
- return new _ZodObject({
3173
- ...this._def,
3174
- unknownKeys: "strict",
3175
- ...message !== void 0 ? {
3176
- errorMap: (issue, ctx) => {
3177
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
3178
- if (issue.code === "unrecognized_keys")
3179
- return {
3180
- message: errorUtil.errToObj(message).message ?? defaultError
3181
- };
3182
- return {
3183
- message: defaultError
3184
- };
3185
- }
3186
- } : {}
3187
- });
3188
- }
3189
- strip() {
3190
- return new _ZodObject({
3191
- ...this._def,
3192
- unknownKeys: "strip"
3193
- });
3194
- }
3195
- passthrough() {
3196
- return new _ZodObject({
3197
- ...this._def,
3198
- unknownKeys: "passthrough"
3199
- });
3200
- }
3201
- // const AugmentFactory =
3202
- // <Def extends ZodObjectDef>(def: Def) =>
3203
- // <Augmentation extends ZodRawShape>(
3204
- // augmentation: Augmentation
3205
- // ): ZodObject<
3206
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
3207
- // Def["unknownKeys"],
3208
- // Def["catchall"]
3209
- // > => {
3210
- // return new ZodObject({
3211
- // ...def,
3212
- // shape: () => ({
3213
- // ...def.shape(),
3214
- // ...augmentation,
3215
- // }),
3216
- // }) as any;
3217
- // };
3218
- extend(augmentation) {
3219
- return new _ZodObject({
3220
- ...this._def,
3221
- shape: () => ({
3222
- ...this._def.shape(),
3223
- ...augmentation
3224
- })
3225
- });
3226
- }
3227
- /**
3228
- * Prior to zod@1.0.12 there was a bug in the
3229
- * inferred type of merged objects. Please
3230
- * upgrade if you are experiencing issues.
3231
- */
3232
- merge(merging) {
3233
- const merged = new _ZodObject({
3234
- unknownKeys: merging._def.unknownKeys,
3235
- catchall: merging._def.catchall,
3236
- shape: () => ({
3237
- ...this._def.shape(),
3238
- ...merging._def.shape()
3239
- }),
3240
- typeName: ZodFirstPartyTypeKind.ZodObject
3241
- });
3242
- return merged;
3243
- }
3244
- // merge<
3245
- // Incoming extends AnyZodObject,
3246
- // Augmentation extends Incoming["shape"],
3247
- // NewOutput extends {
3248
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
3249
- // ? Augmentation[k]["_output"]
3250
- // : k extends keyof Output
3251
- // ? Output[k]
3252
- // : never;
3253
- // },
3254
- // NewInput extends {
3255
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
3256
- // ? Augmentation[k]["_input"]
3257
- // : k extends keyof Input
3258
- // ? Input[k]
3259
- // : never;
3260
- // }
3261
- // >(
3262
- // merging: Incoming
3263
- // ): ZodObject<
3264
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
3265
- // Incoming["_def"]["unknownKeys"],
3266
- // Incoming["_def"]["catchall"],
3267
- // NewOutput,
3268
- // NewInput
3269
- // > {
3270
- // const merged: any = new ZodObject({
3271
- // unknownKeys: merging._def.unknownKeys,
3272
- // catchall: merging._def.catchall,
3273
- // shape: () =>
3274
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
3275
- // typeName: ZodFirstPartyTypeKind.ZodObject,
3276
- // }) as any;
3277
- // return merged;
3278
- // }
3279
- setKey(key, schema) {
3280
- return this.augment({ [key]: schema });
3281
- }
3282
- // merge<Incoming extends AnyZodObject>(
3283
- // merging: Incoming
3284
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
3285
- // ZodObject<
3286
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
3287
- // Incoming["_def"]["unknownKeys"],
3288
- // Incoming["_def"]["catchall"]
3289
- // > {
3290
- // // const mergedShape = objectUtil.mergeShapes(
3291
- // // this._def.shape(),
3292
- // // merging._def.shape()
3293
- // // );
3294
- // const merged: any = new ZodObject({
3295
- // unknownKeys: merging._def.unknownKeys,
3296
- // catchall: merging._def.catchall,
3297
- // shape: () =>
3298
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
3299
- // typeName: ZodFirstPartyTypeKind.ZodObject,
3300
- // }) as any;
3301
- // return merged;
3302
- // }
3303
- catchall(index) {
3304
- return new _ZodObject({
3305
- ...this._def,
3306
- catchall: index
3307
- });
3308
- }
3309
- pick(mask) {
3310
- const shape = {};
3311
- for (const key of util.objectKeys(mask)) {
3312
- if (mask[key] && this.shape[key]) {
3313
- shape[key] = this.shape[key];
3314
- }
3315
- }
3316
- return new _ZodObject({
3317
- ...this._def,
3318
- shape: () => shape
3319
- });
3320
- }
3321
- omit(mask) {
3322
- const shape = {};
3323
- for (const key of util.objectKeys(this.shape)) {
3324
- if (!mask[key]) {
3325
- shape[key] = this.shape[key];
3326
- }
3327
- }
3328
- return new _ZodObject({
3329
- ...this._def,
3330
- shape: () => shape
3331
- });
3332
- }
3333
- /**
3334
- * @deprecated
3335
- */
3336
- deepPartial() {
3337
- return deepPartialify(this);
3338
- }
3339
- partial(mask) {
3340
- const newShape = {};
3341
- for (const key of util.objectKeys(this.shape)) {
3342
- const fieldSchema = this.shape[key];
3343
- if (mask && !mask[key]) {
3344
- newShape[key] = fieldSchema;
3345
- } else {
3346
- newShape[key] = fieldSchema.optional();
3347
- }
3348
- }
3349
- return new _ZodObject({
3350
- ...this._def,
3351
- shape: () => newShape
3352
- });
3353
- }
3354
- required(mask) {
3355
- const newShape = {};
3356
- for (const key of util.objectKeys(this.shape)) {
3357
- if (mask && !mask[key]) {
3358
- newShape[key] = this.shape[key];
3359
- } else {
3360
- const fieldSchema = this.shape[key];
3361
- let newField = fieldSchema;
3362
- while (newField instanceof ZodOptional) {
3363
- newField = newField._def.innerType;
3364
- }
3365
- newShape[key] = newField;
3366
- }
3367
- }
3368
- return new _ZodObject({
3369
- ...this._def,
3370
- shape: () => newShape
3371
- });
3372
- }
3373
- keyof() {
3374
- return createZodEnum(util.objectKeys(this.shape));
3375
- }
3376
- };
3377
- ZodObject.create = (shape, params) => {
3378
- return new ZodObject({
3379
- shape: () => shape,
3380
- unknownKeys: "strip",
3381
- catchall: ZodNever.create(),
3382
- typeName: ZodFirstPartyTypeKind.ZodObject,
3383
- ...processCreateParams(params)
3384
- });
3385
- };
3386
- ZodObject.strictCreate = (shape, params) => {
3387
- return new ZodObject({
3388
- shape: () => shape,
3389
- unknownKeys: "strict",
3390
- catchall: ZodNever.create(),
3391
- typeName: ZodFirstPartyTypeKind.ZodObject,
3392
- ...processCreateParams(params)
3393
- });
3394
- };
3395
- ZodObject.lazycreate = (shape, params) => {
3396
- return new ZodObject({
3397
- shape,
3398
- unknownKeys: "strip",
3399
- catchall: ZodNever.create(),
3400
- typeName: ZodFirstPartyTypeKind.ZodObject,
3401
- ...processCreateParams(params)
3402
- });
3403
- };
3404
- var ZodUnion = class extends ZodType {
3405
- _parse(input) {
3406
- const { ctx } = this._processInputParams(input);
3407
- const options = this._def.options;
3408
- function handleResults(results) {
3409
- for (const result of results) {
3410
- if (result.result.status === "valid") {
3411
- return result.result;
3412
- }
3413
- }
3414
- for (const result of results) {
3415
- if (result.result.status === "dirty") {
3416
- ctx.common.issues.push(...result.ctx.common.issues);
3417
- return result.result;
3418
- }
3419
- }
3420
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
3421
- addIssueToContext(ctx, {
3422
- code: ZodIssueCode.invalid_union,
3423
- unionErrors
3424
- });
3425
- return INVALID;
3426
- }
3427
- if (ctx.common.async) {
3428
- return Promise.all(options.map(async (option) => {
3429
- const childCtx = {
3430
- ...ctx,
3431
- common: {
3432
- ...ctx.common,
3433
- issues: []
3434
- },
3435
- parent: null
3436
- };
3437
- return {
3438
- result: await option._parseAsync({
3439
- data: ctx.data,
3440
- path: ctx.path,
3441
- parent: childCtx
3442
- }),
3443
- ctx: childCtx
3444
- };
3445
- })).then(handleResults);
3446
- } else {
3447
- let dirty = void 0;
3448
- const issues = [];
3449
- for (const option of options) {
3450
- const childCtx = {
3451
- ...ctx,
3452
- common: {
3453
- ...ctx.common,
3454
- issues: []
3455
- },
3456
- parent: null
3457
- };
3458
- const result = option._parseSync({
3459
- data: ctx.data,
3460
- path: ctx.path,
3461
- parent: childCtx
3462
- });
3463
- if (result.status === "valid") {
3464
- return result;
3465
- } else if (result.status === "dirty" && !dirty) {
3466
- dirty = { result, ctx: childCtx };
3467
- }
3468
- if (childCtx.common.issues.length) {
3469
- issues.push(childCtx.common.issues);
3470
- }
3471
- }
3472
- if (dirty) {
3473
- ctx.common.issues.push(...dirty.ctx.common.issues);
3474
- return dirty.result;
3475
- }
3476
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
3477
- addIssueToContext(ctx, {
3478
- code: ZodIssueCode.invalid_union,
3479
- unionErrors
3480
- });
3481
- return INVALID;
3482
- }
3483
- }
3484
- get options() {
3485
- return this._def.options;
3486
- }
3487
- };
3488
- ZodUnion.create = (types, params) => {
3489
- return new ZodUnion({
3490
- options: types,
3491
- typeName: ZodFirstPartyTypeKind.ZodUnion,
3492
- ...processCreateParams(params)
3493
- });
3494
- };
3495
- var getDiscriminator = (type) => {
3496
- if (type instanceof ZodLazy) {
3497
- return getDiscriminator(type.schema);
3498
- } else if (type instanceof ZodEffects) {
3499
- return getDiscriminator(type.innerType());
3500
- } else if (type instanceof ZodLiteral) {
3501
- return [type.value];
3502
- } else if (type instanceof ZodEnum) {
3503
- return type.options;
3504
- } else if (type instanceof ZodNativeEnum) {
3505
- return util.objectValues(type.enum);
3506
- } else if (type instanceof ZodDefault) {
3507
- return getDiscriminator(type._def.innerType);
3508
- } else if (type instanceof ZodUndefined) {
3509
- return [void 0];
3510
- } else if (type instanceof ZodNull) {
3511
- return [null];
3512
- } else if (type instanceof ZodOptional) {
3513
- return [void 0, ...getDiscriminator(type.unwrap())];
3514
- } else if (type instanceof ZodNullable) {
3515
- return [null, ...getDiscriminator(type.unwrap())];
3516
- } else if (type instanceof ZodBranded) {
3517
- return getDiscriminator(type.unwrap());
3518
- } else if (type instanceof ZodReadonly) {
3519
- return getDiscriminator(type.unwrap());
3520
- } else if (type instanceof ZodCatch) {
3521
- return getDiscriminator(type._def.innerType);
3522
- } else {
3523
- return [];
3524
- }
3525
- };
3526
- var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
3527
- _parse(input) {
3528
- const { ctx } = this._processInputParams(input);
3529
- if (ctx.parsedType !== ZodParsedType.object) {
3530
- addIssueToContext(ctx, {
3531
- code: ZodIssueCode.invalid_type,
3532
- expected: ZodParsedType.object,
3533
- received: ctx.parsedType
3534
- });
3535
- return INVALID;
3536
- }
3537
- const discriminator = this.discriminator;
3538
- const discriminatorValue = ctx.data[discriminator];
3539
- const option = this.optionsMap.get(discriminatorValue);
3540
- if (!option) {
3541
- addIssueToContext(ctx, {
3542
- code: ZodIssueCode.invalid_union_discriminator,
3543
- options: Array.from(this.optionsMap.keys()),
3544
- path: [discriminator]
3545
- });
3546
- return INVALID;
3547
- }
3548
- if (ctx.common.async) {
3549
- return option._parseAsync({
3550
- data: ctx.data,
3551
- path: ctx.path,
3552
- parent: ctx
3553
- });
3554
- } else {
3555
- return option._parseSync({
3556
- data: ctx.data,
3557
- path: ctx.path,
3558
- parent: ctx
3559
- });
3560
- }
3561
- }
3562
- get discriminator() {
3563
- return this._def.discriminator;
3564
- }
3565
- get options() {
3566
- return this._def.options;
3567
- }
3568
- get optionsMap() {
3569
- return this._def.optionsMap;
3570
- }
3571
- /**
3572
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
3573
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
3574
- * have a different value for each object in the union.
3575
- * @param discriminator the name of the discriminator property
3576
- * @param types an array of object schemas
3577
- * @param params
3578
- */
3579
- static create(discriminator, options, params) {
3580
- const optionsMap = /* @__PURE__ */ new Map();
3581
- for (const type of options) {
3582
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3583
- if (!discriminatorValues.length) {
3584
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3585
- }
3586
- for (const value of discriminatorValues) {
3587
- if (optionsMap.has(value)) {
3588
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3589
- }
3590
- optionsMap.set(value, type);
3591
- }
3592
- }
3593
- return new _ZodDiscriminatedUnion({
3594
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3595
- discriminator,
3596
- options,
3597
- optionsMap,
3598
- ...processCreateParams(params)
3599
- });
3600
- }
3601
- };
3602
- function mergeValues(a, b) {
3603
- const aType = getParsedType(a);
3604
- const bType = getParsedType(b);
3605
- if (a === b) {
3606
- return { valid: true, data: a };
3607
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3608
- const bKeys = util.objectKeys(b);
3609
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3610
- const newObj = { ...a, ...b };
3611
- for (const key of sharedKeys) {
3612
- const sharedValue = mergeValues(a[key], b[key]);
3613
- if (!sharedValue.valid) {
3614
- return { valid: false };
3615
- }
3616
- newObj[key] = sharedValue.data;
3617
- }
3618
- return { valid: true, data: newObj };
3619
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3620
- if (a.length !== b.length) {
3621
- return { valid: false };
3622
- }
3623
- const newArray = [];
3624
- for (let index = 0; index < a.length; index++) {
3625
- const itemA = a[index];
3626
- const itemB = b[index];
3627
- const sharedValue = mergeValues(itemA, itemB);
3628
- if (!sharedValue.valid) {
3629
- return { valid: false };
3630
- }
3631
- newArray.push(sharedValue.data);
3632
- }
3633
- return { valid: true, data: newArray };
3634
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
3635
- return { valid: true, data: a };
3636
- } else {
3637
- return { valid: false };
3638
- }
3639
- }
3640
- var ZodIntersection = class extends ZodType {
3641
- _parse(input) {
3642
- const { status, ctx } = this._processInputParams(input);
3643
- const handleParsed = (parsedLeft, parsedRight) => {
3644
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3645
- return INVALID;
3646
- }
3647
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
3648
- if (!merged.valid) {
3649
- addIssueToContext(ctx, {
3650
- code: ZodIssueCode.invalid_intersection_types
3651
- });
3652
- return INVALID;
3653
- }
3654
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3655
- status.dirty();
3656
- }
3657
- return { status: status.value, value: merged.data };
3658
- };
3659
- if (ctx.common.async) {
3660
- return Promise.all([
3661
- this._def.left._parseAsync({
3662
- data: ctx.data,
3663
- path: ctx.path,
3664
- parent: ctx
3665
- }),
3666
- this._def.right._parseAsync({
3667
- data: ctx.data,
3668
- path: ctx.path,
3669
- parent: ctx
3670
- })
3671
- ]).then(([left, right]) => handleParsed(left, right));
3672
- } else {
3673
- return handleParsed(this._def.left._parseSync({
3674
- data: ctx.data,
3675
- path: ctx.path,
3676
- parent: ctx
3677
- }), this._def.right._parseSync({
3678
- data: ctx.data,
3679
- path: ctx.path,
3680
- parent: ctx
3681
- }));
3682
- }
3683
- }
3684
- };
3685
- ZodIntersection.create = (left, right, params) => {
3686
- return new ZodIntersection({
3687
- left,
3688
- right,
3689
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
3690
- ...processCreateParams(params)
3691
- });
3692
- };
3693
- var ZodTuple = class _ZodTuple extends ZodType {
3694
- _parse(input) {
3695
- const { status, ctx } = this._processInputParams(input);
3696
- if (ctx.parsedType !== ZodParsedType.array) {
3697
- addIssueToContext(ctx, {
3698
- code: ZodIssueCode.invalid_type,
3699
- expected: ZodParsedType.array,
3700
- received: ctx.parsedType
3701
- });
3702
- return INVALID;
3703
- }
3704
- if (ctx.data.length < this._def.items.length) {
3705
- addIssueToContext(ctx, {
3706
- code: ZodIssueCode.too_small,
3707
- minimum: this._def.items.length,
3708
- inclusive: true,
3709
- exact: false,
3710
- type: "array"
3711
- });
3712
- return INVALID;
3713
- }
3714
- const rest = this._def.rest;
3715
- if (!rest && ctx.data.length > this._def.items.length) {
3716
- addIssueToContext(ctx, {
3717
- code: ZodIssueCode.too_big,
3718
- maximum: this._def.items.length,
3719
- inclusive: true,
3720
- exact: false,
3721
- type: "array"
3722
- });
3723
- status.dirty();
3724
- }
3725
- const items = [...ctx.data].map((item, itemIndex) => {
3726
- const schema = this._def.items[itemIndex] || this._def.rest;
3727
- if (!schema)
3728
- return null;
3729
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3730
- }).filter((x) => !!x);
3731
- if (ctx.common.async) {
3732
- return Promise.all(items).then((results) => {
3733
- return ParseStatus.mergeArray(status, results);
3734
- });
3735
- } else {
3736
- return ParseStatus.mergeArray(status, items);
3737
- }
3738
- }
3739
- get items() {
3740
- return this._def.items;
3741
- }
3742
- rest(rest) {
3743
- return new _ZodTuple({
3744
- ...this._def,
3745
- rest
3746
- });
3747
- }
3748
- };
3749
- ZodTuple.create = (schemas, params) => {
3750
- if (!Array.isArray(schemas)) {
3751
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3752
- }
3753
- return new ZodTuple({
3754
- items: schemas,
3755
- typeName: ZodFirstPartyTypeKind.ZodTuple,
3756
- rest: null,
3757
- ...processCreateParams(params)
3758
- });
3759
- };
3760
- var ZodRecord = class _ZodRecord extends ZodType {
3761
- get keySchema() {
3762
- return this._def.keyType;
3763
- }
3764
- get valueSchema() {
3765
- return this._def.valueType;
3766
- }
3767
- _parse(input) {
3768
- const { status, ctx } = this._processInputParams(input);
3769
- if (ctx.parsedType !== ZodParsedType.object) {
3770
- addIssueToContext(ctx, {
3771
- code: ZodIssueCode.invalid_type,
3772
- expected: ZodParsedType.object,
3773
- received: ctx.parsedType
3774
- });
3775
- return INVALID;
3776
- }
3777
- const pairs = [];
3778
- const keyType = this._def.keyType;
3779
- const valueType = this._def.valueType;
3780
- for (const key in ctx.data) {
3781
- pairs.push({
3782
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3783
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3784
- alwaysSet: key in ctx.data
3785
- });
3786
- }
3787
- if (ctx.common.async) {
3788
- return ParseStatus.mergeObjectAsync(status, pairs);
3789
- } else {
3790
- return ParseStatus.mergeObjectSync(status, pairs);
3791
- }
3792
- }
3793
- get element() {
3794
- return this._def.valueType;
3795
- }
3796
- static create(first, second, third) {
3797
- if (second instanceof ZodType) {
3798
- return new _ZodRecord({
3799
- keyType: first,
3800
- valueType: second,
3801
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3802
- ...processCreateParams(third)
3803
- });
3804
- }
3805
- return new _ZodRecord({
3806
- keyType: ZodString.create(),
3807
- valueType: first,
3808
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3809
- ...processCreateParams(second)
3810
- });
3811
- }
3812
- };
3813
- var ZodMap = class extends ZodType {
3814
- get keySchema() {
3815
- return this._def.keyType;
3816
- }
3817
- get valueSchema() {
3818
- return this._def.valueType;
3819
- }
3820
- _parse(input) {
3821
- const { status, ctx } = this._processInputParams(input);
3822
- if (ctx.parsedType !== ZodParsedType.map) {
3823
- addIssueToContext(ctx, {
3824
- code: ZodIssueCode.invalid_type,
3825
- expected: ZodParsedType.map,
3826
- received: ctx.parsedType
3827
- });
3828
- return INVALID;
3829
- }
3830
- const keyType = this._def.keyType;
3831
- const valueType = this._def.valueType;
3832
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3833
- return {
3834
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3835
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3836
- };
3837
- });
3838
- if (ctx.common.async) {
3839
- const finalMap = /* @__PURE__ */ new Map();
3840
- return Promise.resolve().then(async () => {
3841
- for (const pair of pairs) {
3842
- const key = await pair.key;
3843
- const value = await pair.value;
3844
- if (key.status === "aborted" || value.status === "aborted") {
3845
- return INVALID;
3846
- }
3847
- if (key.status === "dirty" || value.status === "dirty") {
3848
- status.dirty();
3849
- }
3850
- finalMap.set(key.value, value.value);
3851
- }
3852
- return { status: status.value, value: finalMap };
3853
- });
3854
- } else {
3855
- const finalMap = /* @__PURE__ */ new Map();
3856
- for (const pair of pairs) {
3857
- const key = pair.key;
3858
- const value = pair.value;
3859
- if (key.status === "aborted" || value.status === "aborted") {
3860
- return INVALID;
3861
- }
3862
- if (key.status === "dirty" || value.status === "dirty") {
3863
- status.dirty();
3864
- }
3865
- finalMap.set(key.value, value.value);
3866
- }
3867
- return { status: status.value, value: finalMap };
3868
- }
3869
- }
3870
- };
3871
- ZodMap.create = (keyType, valueType, params) => {
3872
- return new ZodMap({
3873
- valueType,
3874
- keyType,
3875
- typeName: ZodFirstPartyTypeKind.ZodMap,
3876
- ...processCreateParams(params)
3877
- });
3878
- };
3879
- var ZodSet = class _ZodSet extends ZodType {
3880
- _parse(input) {
3881
- const { status, ctx } = this._processInputParams(input);
3882
- if (ctx.parsedType !== ZodParsedType.set) {
3883
- addIssueToContext(ctx, {
3884
- code: ZodIssueCode.invalid_type,
3885
- expected: ZodParsedType.set,
3886
- received: ctx.parsedType
3887
- });
3888
- return INVALID;
3889
- }
3890
- const def = this._def;
3891
- if (def.minSize !== null) {
3892
- if (ctx.data.size < def.minSize.value) {
3893
- addIssueToContext(ctx, {
3894
- code: ZodIssueCode.too_small,
3895
- minimum: def.minSize.value,
3896
- type: "set",
3897
- inclusive: true,
3898
- exact: false,
3899
- message: def.minSize.message
3900
- });
3901
- status.dirty();
3902
- }
3903
- }
3904
- if (def.maxSize !== null) {
3905
- if (ctx.data.size > def.maxSize.value) {
3906
- addIssueToContext(ctx, {
3907
- code: ZodIssueCode.too_big,
3908
- maximum: def.maxSize.value,
3909
- type: "set",
3910
- inclusive: true,
3911
- exact: false,
3912
- message: def.maxSize.message
3913
- });
3914
- status.dirty();
3915
- }
3916
- }
3917
- const valueType = this._def.valueType;
3918
- function finalizeSet(elements2) {
3919
- const parsedSet = /* @__PURE__ */ new Set();
3920
- for (const element of elements2) {
3921
- if (element.status === "aborted")
3922
- return INVALID;
3923
- if (element.status === "dirty")
3924
- status.dirty();
3925
- parsedSet.add(element.value);
3926
- }
3927
- return { status: status.value, value: parsedSet };
3928
- }
3929
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3930
- if (ctx.common.async) {
3931
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3932
- } else {
3933
- return finalizeSet(elements);
3934
- }
3935
- }
3936
- min(minSize, message) {
3937
- return new _ZodSet({
3938
- ...this._def,
3939
- minSize: { value: minSize, message: errorUtil.toString(message) }
3940
- });
3941
- }
3942
- max(maxSize, message) {
3943
- return new _ZodSet({
3944
- ...this._def,
3945
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
3946
- });
3947
- }
3948
- size(size, message) {
3949
- return this.min(size, message).max(size, message);
3950
- }
3951
- nonempty(message) {
3952
- return this.min(1, message);
3953
- }
3954
- };
3955
- ZodSet.create = (valueType, params) => {
3956
- return new ZodSet({
3957
- valueType,
3958
- minSize: null,
3959
- maxSize: null,
3960
- typeName: ZodFirstPartyTypeKind.ZodSet,
3961
- ...processCreateParams(params)
3962
- });
3963
- };
3964
- var ZodFunction = class _ZodFunction extends ZodType {
3965
- constructor() {
3966
- super(...arguments);
3967
- this.validate = this.implement;
3968
- }
3969
- _parse(input) {
3970
- const { ctx } = this._processInputParams(input);
3971
- if (ctx.parsedType !== ZodParsedType.function) {
3972
- addIssueToContext(ctx, {
3973
- code: ZodIssueCode.invalid_type,
3974
- expected: ZodParsedType.function,
3975
- received: ctx.parsedType
3976
- });
3977
- return INVALID;
3978
- }
3979
- function makeArgsIssue(args, error) {
3980
- return makeIssue({
3981
- data: args,
3982
- path: ctx.path,
3983
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3984
- issueData: {
3985
- code: ZodIssueCode.invalid_arguments,
3986
- argumentsError: error
3987
- }
3988
- });
3989
- }
3990
- function makeReturnsIssue(returns, error) {
3991
- return makeIssue({
3992
- data: returns,
3993
- path: ctx.path,
3994
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3995
- issueData: {
3996
- code: ZodIssueCode.invalid_return_type,
3997
- returnTypeError: error
3998
- }
3999
- });
4000
- }
4001
- const params = { errorMap: ctx.common.contextualErrorMap };
4002
- const fn = ctx.data;
4003
- if (this._def.returns instanceof ZodPromise) {
4004
- const me = this;
4005
- return OK(async function(...args) {
4006
- const error = new ZodError([]);
4007
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
4008
- error.addIssue(makeArgsIssue(args, e));
4009
- throw error;
4010
- });
4011
- const result = await Reflect.apply(fn, this, parsedArgs);
4012
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
4013
- error.addIssue(makeReturnsIssue(result, e));
4014
- throw error;
4015
- });
4016
- return parsedReturns;
4017
- });
4018
- } else {
4019
- const me = this;
4020
- return OK(function(...args) {
4021
- const parsedArgs = me._def.args.safeParse(args, params);
4022
- if (!parsedArgs.success) {
4023
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
4024
- }
4025
- const result = Reflect.apply(fn, this, parsedArgs.data);
4026
- const parsedReturns = me._def.returns.safeParse(result, params);
4027
- if (!parsedReturns.success) {
4028
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
4029
- }
4030
- return parsedReturns.data;
4031
- });
4032
- }
4033
- }
4034
- parameters() {
4035
- return this._def.args;
4036
- }
4037
- returnType() {
4038
- return this._def.returns;
4039
- }
4040
- args(...items) {
4041
- return new _ZodFunction({
4042
- ...this._def,
4043
- args: ZodTuple.create(items).rest(ZodUnknown.create())
4044
- });
4045
- }
4046
- returns(returnType) {
4047
- return new _ZodFunction({
4048
- ...this._def,
4049
- returns: returnType
4050
- });
4051
- }
4052
- implement(func) {
4053
- const validatedFunc = this.parse(func);
4054
- return validatedFunc;
4055
- }
4056
- strictImplement(func) {
4057
- const validatedFunc = this.parse(func);
4058
- return validatedFunc;
4059
- }
4060
- static create(args, returns, params) {
4061
- return new _ZodFunction({
4062
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
4063
- returns: returns || ZodUnknown.create(),
4064
- typeName: ZodFirstPartyTypeKind.ZodFunction,
4065
- ...processCreateParams(params)
4066
- });
4067
- }
4068
- };
4069
- var ZodLazy = class extends ZodType {
4070
- get schema() {
4071
- return this._def.getter();
4072
- }
4073
- _parse(input) {
4074
- const { ctx } = this._processInputParams(input);
4075
- const lazySchema = this._def.getter();
4076
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
4077
- }
4078
- };
4079
- ZodLazy.create = (getter, params) => {
4080
- return new ZodLazy({
4081
- getter,
4082
- typeName: ZodFirstPartyTypeKind.ZodLazy,
4083
- ...processCreateParams(params)
4084
- });
4085
- };
4086
- var ZodLiteral = class extends ZodType {
4087
- _parse(input) {
4088
- if (input.data !== this._def.value) {
4089
- const ctx = this._getOrReturnCtx(input);
4090
- addIssueToContext(ctx, {
4091
- received: ctx.data,
4092
- code: ZodIssueCode.invalid_literal,
4093
- expected: this._def.value
4094
- });
4095
- return INVALID;
4096
- }
4097
- return { status: "valid", value: input.data };
4098
- }
4099
- get value() {
4100
- return this._def.value;
4101
- }
4102
- };
4103
- ZodLiteral.create = (value, params) => {
4104
- return new ZodLiteral({
4105
- value,
4106
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
4107
- ...processCreateParams(params)
4108
- });
4109
- };
4110
- function createZodEnum(values, params) {
4111
- return new ZodEnum({
4112
- values,
4113
- typeName: ZodFirstPartyTypeKind.ZodEnum,
4114
- ...processCreateParams(params)
4115
- });
4116
- }
4117
- var ZodEnum = class _ZodEnum extends ZodType {
4118
- _parse(input) {
4119
- if (typeof input.data !== "string") {
4120
- const ctx = this._getOrReturnCtx(input);
4121
- const expectedValues = this._def.values;
4122
- addIssueToContext(ctx, {
4123
- expected: util.joinValues(expectedValues),
4124
- received: ctx.parsedType,
4125
- code: ZodIssueCode.invalid_type
4126
- });
4127
- return INVALID;
4128
- }
4129
- if (!this._cache) {
4130
- this._cache = new Set(this._def.values);
4131
- }
4132
- if (!this._cache.has(input.data)) {
4133
- const ctx = this._getOrReturnCtx(input);
4134
- const expectedValues = this._def.values;
4135
- addIssueToContext(ctx, {
4136
- received: ctx.data,
4137
- code: ZodIssueCode.invalid_enum_value,
4138
- options: expectedValues
4139
- });
4140
- return INVALID;
4141
- }
4142
- return OK(input.data);
4143
- }
4144
- get options() {
4145
- return this._def.values;
4146
- }
4147
- get enum() {
4148
- const enumValues = {};
4149
- for (const val of this._def.values) {
4150
- enumValues[val] = val;
4151
- }
4152
- return enumValues;
4153
- }
4154
- get Values() {
4155
- const enumValues = {};
4156
- for (const val of this._def.values) {
4157
- enumValues[val] = val;
4158
- }
4159
- return enumValues;
4160
- }
4161
- get Enum() {
4162
- const enumValues = {};
4163
- for (const val of this._def.values) {
4164
- enumValues[val] = val;
4165
- }
4166
- return enumValues;
4167
- }
4168
- extract(values, newDef = this._def) {
4169
- return _ZodEnum.create(values, {
4170
- ...this._def,
4171
- ...newDef
4172
- });
4173
- }
4174
- exclude(values, newDef = this._def) {
4175
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4176
- ...this._def,
4177
- ...newDef
4178
- });
4179
- }
4180
- };
4181
- ZodEnum.create = createZodEnum;
4182
- var ZodNativeEnum = class extends ZodType {
4183
- _parse(input) {
4184
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
4185
- const ctx = this._getOrReturnCtx(input);
4186
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
4187
- const expectedValues = util.objectValues(nativeEnumValues);
4188
- addIssueToContext(ctx, {
4189
- expected: util.joinValues(expectedValues),
4190
- received: ctx.parsedType,
4191
- code: ZodIssueCode.invalid_type
4192
- });
4193
- return INVALID;
4194
- }
4195
- if (!this._cache) {
4196
- this._cache = new Set(util.getValidEnumValues(this._def.values));
4197
- }
4198
- if (!this._cache.has(input.data)) {
4199
- const expectedValues = util.objectValues(nativeEnumValues);
4200
- addIssueToContext(ctx, {
4201
- received: ctx.data,
4202
- code: ZodIssueCode.invalid_enum_value,
4203
- options: expectedValues
4204
- });
4205
- return INVALID;
4206
- }
4207
- return OK(input.data);
4208
- }
4209
- get enum() {
4210
- return this._def.values;
4211
- }
4212
- };
4213
- ZodNativeEnum.create = (values, params) => {
4214
- return new ZodNativeEnum({
4215
- values,
4216
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
4217
- ...processCreateParams(params)
4218
- });
4219
- };
4220
- var ZodPromise = class extends ZodType {
4221
- unwrap() {
4222
- return this._def.type;
4223
- }
4224
- _parse(input) {
4225
- const { ctx } = this._processInputParams(input);
4226
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
4227
- addIssueToContext(ctx, {
4228
- code: ZodIssueCode.invalid_type,
4229
- expected: ZodParsedType.promise,
4230
- received: ctx.parsedType
4231
- });
4232
- return INVALID;
4233
- }
4234
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
4235
- return OK(promisified.then((data) => {
4236
- return this._def.type.parseAsync(data, {
4237
- path: ctx.path,
4238
- errorMap: ctx.common.contextualErrorMap
4239
- });
4240
- }));
4241
- }
4242
- };
4243
- ZodPromise.create = (schema, params) => {
4244
- return new ZodPromise({
4245
- type: schema,
4246
- typeName: ZodFirstPartyTypeKind.ZodPromise,
4247
- ...processCreateParams(params)
4248
- });
4249
- };
4250
- var ZodEffects = class extends ZodType {
4251
- innerType() {
4252
- return this._def.schema;
4253
- }
4254
- sourceType() {
4255
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
4256
- }
4257
- _parse(input) {
4258
- const { status, ctx } = this._processInputParams(input);
4259
- const effect = this._def.effect || null;
4260
- const checkCtx = {
4261
- addIssue: (arg) => {
4262
- addIssueToContext(ctx, arg);
4263
- if (arg.fatal) {
4264
- status.abort();
4265
- } else {
4266
- status.dirty();
4267
- }
4268
- },
4269
- get path() {
4270
- return ctx.path;
4271
- }
4272
- };
4273
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
4274
- if (effect.type === "preprocess") {
4275
- const processed = effect.transform(ctx.data, checkCtx);
4276
- if (ctx.common.async) {
4277
- return Promise.resolve(processed).then(async (processed2) => {
4278
- if (status.value === "aborted")
4279
- return INVALID;
4280
- const result = await this._def.schema._parseAsync({
4281
- data: processed2,
4282
- path: ctx.path,
4283
- parent: ctx
4284
- });
4285
- if (result.status === "aborted")
4286
- return INVALID;
4287
- if (result.status === "dirty")
4288
- return DIRTY(result.value);
4289
- if (status.value === "dirty")
4290
- return DIRTY(result.value);
4291
- return result;
4292
- });
4293
- } else {
4294
- if (status.value === "aborted")
4295
- return INVALID;
4296
- const result = this._def.schema._parseSync({
4297
- data: processed,
4298
- path: ctx.path,
4299
- parent: ctx
4300
- });
4301
- if (result.status === "aborted")
4302
- return INVALID;
4303
- if (result.status === "dirty")
4304
- return DIRTY(result.value);
4305
- if (status.value === "dirty")
4306
- return DIRTY(result.value);
4307
- return result;
4308
- }
4309
- }
4310
- if (effect.type === "refinement") {
4311
- const executeRefinement = (acc) => {
4312
- const result = effect.refinement(acc, checkCtx);
4313
- if (ctx.common.async) {
4314
- return Promise.resolve(result);
4315
- }
4316
- if (result instanceof Promise) {
4317
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
4318
- }
4319
- return acc;
4320
- };
4321
- if (ctx.common.async === false) {
4322
- const inner = this._def.schema._parseSync({
4323
- data: ctx.data,
4324
- path: ctx.path,
4325
- parent: ctx
4326
- });
4327
- if (inner.status === "aborted")
4328
- return INVALID;
4329
- if (inner.status === "dirty")
4330
- status.dirty();
4331
- executeRefinement(inner.value);
4332
- return { status: status.value, value: inner.value };
4333
- } else {
4334
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
4335
- if (inner.status === "aborted")
4336
- return INVALID;
4337
- if (inner.status === "dirty")
4338
- status.dirty();
4339
- return executeRefinement(inner.value).then(() => {
4340
- return { status: status.value, value: inner.value };
4341
- });
4342
- });
4343
- }
4344
- }
4345
- if (effect.type === "transform") {
4346
- if (ctx.common.async === false) {
4347
- const base = this._def.schema._parseSync({
4348
- data: ctx.data,
4349
- path: ctx.path,
4350
- parent: ctx
4351
- });
4352
- if (!isValid(base))
4353
- return INVALID;
4354
- const result = effect.transform(base.value, checkCtx);
4355
- if (result instanceof Promise) {
4356
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
4357
- }
4358
- return { status: status.value, value: result };
4359
- } else {
4360
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
4361
- if (!isValid(base))
4362
- return INVALID;
4363
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
4364
- status: status.value,
4365
- value: result
4366
- }));
4367
- });
4368
- }
4369
- }
4370
- util.assertNever(effect);
4371
- }
4372
- };
4373
- ZodEffects.create = (schema, effect, params) => {
4374
- return new ZodEffects({
4375
- schema,
4376
- typeName: ZodFirstPartyTypeKind.ZodEffects,
4377
- effect,
4378
- ...processCreateParams(params)
4379
- });
4380
- };
4381
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
4382
- return new ZodEffects({
4383
- schema,
4384
- effect: { type: "preprocess", transform: preprocess },
4385
- typeName: ZodFirstPartyTypeKind.ZodEffects,
4386
- ...processCreateParams(params)
4387
- });
4388
- };
4389
- var ZodOptional = class extends ZodType {
4390
- _parse(input) {
4391
- const parsedType = this._getType(input);
4392
- if (parsedType === ZodParsedType.undefined) {
4393
- return OK(void 0);
4394
- }
4395
- return this._def.innerType._parse(input);
4396
- }
4397
- unwrap() {
4398
- return this._def.innerType;
4399
- }
4400
- };
4401
- ZodOptional.create = (type, params) => {
4402
- return new ZodOptional({
4403
- innerType: type,
4404
- typeName: ZodFirstPartyTypeKind.ZodOptional,
4405
- ...processCreateParams(params)
4406
- });
4407
- };
4408
- var ZodNullable = class extends ZodType {
4409
- _parse(input) {
4410
- const parsedType = this._getType(input);
4411
- if (parsedType === ZodParsedType.null) {
4412
- return OK(null);
4413
- }
4414
- return this._def.innerType._parse(input);
4415
- }
4416
- unwrap() {
4417
- return this._def.innerType;
4418
- }
4419
- };
4420
- ZodNullable.create = (type, params) => {
4421
- return new ZodNullable({
4422
- innerType: type,
4423
- typeName: ZodFirstPartyTypeKind.ZodNullable,
4424
- ...processCreateParams(params)
4425
- });
4426
- };
4427
- var ZodDefault = class extends ZodType {
4428
- _parse(input) {
4429
- const { ctx } = this._processInputParams(input);
4430
- let data = ctx.data;
4431
- if (ctx.parsedType === ZodParsedType.undefined) {
4432
- data = this._def.defaultValue();
4433
- }
4434
- return this._def.innerType._parse({
4435
- data,
4436
- path: ctx.path,
4437
- parent: ctx
4438
- });
4439
- }
4440
- removeDefault() {
4441
- return this._def.innerType;
4442
- }
4443
- };
4444
- ZodDefault.create = (type, params) => {
4445
- return new ZodDefault({
4446
- innerType: type,
4447
- typeName: ZodFirstPartyTypeKind.ZodDefault,
4448
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
4449
- ...processCreateParams(params)
4450
- });
4451
- };
4452
- var ZodCatch = class extends ZodType {
4453
- _parse(input) {
4454
- const { ctx } = this._processInputParams(input);
4455
- const newCtx = {
4456
- ...ctx,
4457
- common: {
4458
- ...ctx.common,
4459
- issues: []
4460
- }
4461
- };
4462
- const result = this._def.innerType._parse({
4463
- data: newCtx.data,
4464
- path: newCtx.path,
4465
- parent: {
4466
- ...newCtx
4467
- }
4468
- });
4469
- if (isAsync(result)) {
4470
- return result.then((result2) => {
4471
- return {
4472
- status: "valid",
4473
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
4474
- get error() {
4475
- return new ZodError(newCtx.common.issues);
4476
- },
4477
- input: newCtx.data
4478
- })
4479
- };
4480
- });
4481
- } else {
4482
- return {
4483
- status: "valid",
4484
- value: result.status === "valid" ? result.value : this._def.catchValue({
4485
- get error() {
4486
- return new ZodError(newCtx.common.issues);
4487
- },
4488
- input: newCtx.data
4489
- })
4490
- };
4491
- }
4492
- }
4493
- removeCatch() {
4494
- return this._def.innerType;
4495
- }
4496
- };
4497
- ZodCatch.create = (type, params) => {
4498
- return new ZodCatch({
4499
- innerType: type,
4500
- typeName: ZodFirstPartyTypeKind.ZodCatch,
4501
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4502
- ...processCreateParams(params)
4503
- });
4504
- };
4505
- var ZodNaN = class extends ZodType {
4506
- _parse(input) {
4507
- const parsedType = this._getType(input);
4508
- if (parsedType !== ZodParsedType.nan) {
4509
- const ctx = this._getOrReturnCtx(input);
4510
- addIssueToContext(ctx, {
4511
- code: ZodIssueCode.invalid_type,
4512
- expected: ZodParsedType.nan,
4513
- received: ctx.parsedType
4514
- });
4515
- return INVALID;
4516
- }
4517
- return { status: "valid", value: input.data };
4518
- }
4519
- };
4520
- ZodNaN.create = (params) => {
4521
- return new ZodNaN({
4522
- typeName: ZodFirstPartyTypeKind.ZodNaN,
4523
- ...processCreateParams(params)
4524
- });
4525
- };
4526
- var BRAND = /* @__PURE__ */ Symbol("zod_brand");
4527
- var ZodBranded = class extends ZodType {
4528
- _parse(input) {
4529
- const { ctx } = this._processInputParams(input);
4530
- const data = ctx.data;
4531
- return this._def.type._parse({
4532
- data,
4533
- path: ctx.path,
4534
- parent: ctx
4535
- });
4536
- }
4537
- unwrap() {
4538
- return this._def.type;
4539
- }
4540
- };
4541
- var ZodPipeline = class _ZodPipeline extends ZodType {
4542
- _parse(input) {
4543
- const { status, ctx } = this._processInputParams(input);
4544
- if (ctx.common.async) {
4545
- const handleAsync = async () => {
4546
- const inResult = await this._def.in._parseAsync({
4547
- data: ctx.data,
4548
- path: ctx.path,
4549
- parent: ctx
4550
- });
4551
- if (inResult.status === "aborted")
4552
- return INVALID;
4553
- if (inResult.status === "dirty") {
4554
- status.dirty();
4555
- return DIRTY(inResult.value);
4556
- } else {
4557
- return this._def.out._parseAsync({
4558
- data: inResult.value,
4559
- path: ctx.path,
4560
- parent: ctx
4561
- });
4562
- }
4563
- };
4564
- return handleAsync();
4565
- } else {
4566
- const inResult = this._def.in._parseSync({
4567
- data: ctx.data,
4568
- path: ctx.path,
4569
- parent: ctx
4570
- });
4571
- if (inResult.status === "aborted")
4572
- return INVALID;
4573
- if (inResult.status === "dirty") {
4574
- status.dirty();
4575
- return {
4576
- status: "dirty",
4577
- value: inResult.value
4578
- };
4579
- } else {
4580
- return this._def.out._parseSync({
4581
- data: inResult.value,
4582
- path: ctx.path,
4583
- parent: ctx
4584
- });
4585
- }
4586
- }
4587
- }
4588
- static create(a, b) {
4589
- return new _ZodPipeline({
4590
- in: a,
4591
- out: b,
4592
- typeName: ZodFirstPartyTypeKind.ZodPipeline
4593
- });
4594
- }
4595
- };
4596
- var ZodReadonly = class extends ZodType {
4597
- _parse(input) {
4598
- const result = this._def.innerType._parse(input);
4599
- const freeze = (data) => {
4600
- if (isValid(data)) {
4601
- data.value = Object.freeze(data.value);
4602
- }
4603
- return data;
4604
- };
4605
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4606
- }
4607
- unwrap() {
4608
- return this._def.innerType;
4609
- }
4610
- };
4611
- ZodReadonly.create = (type, params) => {
4612
- return new ZodReadonly({
4613
- innerType: type,
4614
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
4615
- ...processCreateParams(params)
4616
- });
4617
- };
4618
- function cleanParams(params, data) {
4619
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
4620
- const p2 = typeof p === "string" ? { message: p } : p;
4621
- return p2;
4622
- }
4623
- function custom(check, _params = {}, fatal) {
4624
- if (check)
4625
- return ZodAny.create().superRefine((data, ctx) => {
4626
- const r = check(data);
4627
- if (r instanceof Promise) {
4628
- return r.then((r2) => {
4629
- if (!r2) {
4630
- const params = cleanParams(_params, data);
4631
- const _fatal = params.fatal ?? fatal ?? true;
4632
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4633
- }
4634
- });
4635
- }
4636
- if (!r) {
4637
- const params = cleanParams(_params, data);
4638
- const _fatal = params.fatal ?? fatal ?? true;
4639
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4640
- }
4641
- return;
4642
- });
4643
- return ZodAny.create();
4644
- }
4645
- var late = {
4646
- object: ZodObject.lazycreate
4647
- };
4648
- var ZodFirstPartyTypeKind;
4649
- (function(ZodFirstPartyTypeKind2) {
4650
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
4651
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
4652
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
4653
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
4654
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
4655
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
4656
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
4657
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
4658
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
4659
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
4660
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
4661
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
4662
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
4663
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
4664
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
4665
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
4666
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4667
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
4668
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
4669
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
4670
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
4671
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
4672
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
4673
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
4674
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
4675
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
4676
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
4677
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4678
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4679
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4680
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4681
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4682
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4683
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4684
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4685
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4686
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4687
- var instanceOfType = (cls, params = {
4688
- message: `Input not instance of ${cls.name}`
4689
- }) => custom((data) => data instanceof cls, params);
4690
- var stringType = ZodString.create;
4691
- var numberType = ZodNumber.create;
4692
- var nanType = ZodNaN.create;
4693
- var bigIntType = ZodBigInt.create;
4694
- var booleanType = ZodBoolean.create;
4695
- var dateType = ZodDate.create;
4696
- var symbolType = ZodSymbol.create;
4697
- var undefinedType = ZodUndefined.create;
4698
- var nullType = ZodNull.create;
4699
- var anyType = ZodAny.create;
4700
- var unknownType = ZodUnknown.create;
4701
- var neverType = ZodNever.create;
4702
- var voidType = ZodVoid.create;
4703
- var arrayType = ZodArray.create;
4704
- var objectType = ZodObject.create;
4705
- var strictObjectType = ZodObject.strictCreate;
4706
- var unionType = ZodUnion.create;
4707
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
4708
- var intersectionType = ZodIntersection.create;
4709
- var tupleType = ZodTuple.create;
4710
- var recordType = ZodRecord.create;
4711
- var mapType = ZodMap.create;
4712
- var setType = ZodSet.create;
4713
- var functionType = ZodFunction.create;
4714
- var lazyType = ZodLazy.create;
4715
- var literalType = ZodLiteral.create;
4716
- var enumType = ZodEnum.create;
4717
- var nativeEnumType = ZodNativeEnum.create;
4718
- var promiseType = ZodPromise.create;
4719
- var effectsType = ZodEffects.create;
4720
- var optionalType = ZodOptional.create;
4721
- var nullableType = ZodNullable.create;
4722
- var preprocessType = ZodEffects.createWithPreprocess;
4723
- var pipelineType = ZodPipeline.create;
4724
- var ostring = () => stringType().optional();
4725
- var onumber = () => numberType().optional();
4726
- var oboolean = () => booleanType().optional();
4727
- var coerce = {
4728
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4729
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4730
- boolean: ((arg) => ZodBoolean.create({
4731
- ...arg,
4732
- coerce: true
4733
- })),
4734
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4735
- date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4736
- };
4737
- var NEVER = INVALID;
4738
-
4739
663
  // src/config/schema.ts
4740
- var EmbeddingProviderSchema = external_exports.enum([
4741
- "auto",
4742
- "github-copilot",
4743
- "openai",
4744
- "google",
4745
- "ollama"
4746
- ]);
4747
- var IndexScopeSchema = external_exports.enum(["project", "global"]);
4748
- var IndexingConfigSchema = external_exports.object({
4749
- autoIndex: external_exports.boolean().default(false),
4750
- watchFiles: external_exports.boolean().default(true),
4751
- maxFileSize: external_exports.number().default(1048576),
4752
- retries: external_exports.number().default(3),
4753
- retryDelayMs: external_exports.number().default(1e3)
4754
- });
4755
- var SearchConfigSchema = external_exports.object({
4756
- maxResults: external_exports.number().default(20),
4757
- minScore: external_exports.number().default(0.1),
4758
- includeContext: external_exports.boolean().default(true),
4759
- hybridWeight: external_exports.number().min(0).max(1).default(0.5),
4760
- contextLines: external_exports.number().min(0).max(50).default(0)
4761
- });
4762
- var CodebaseIndexConfigSchema = external_exports.object({
4763
- embeddingProvider: EmbeddingProviderSchema.default("auto"),
4764
- embeddingModel: external_exports.string().default("auto"),
4765
- scope: IndexScopeSchema.default("project"),
4766
- indexing: IndexingConfigSchema.optional(),
4767
- search: SearchConfigSchema.optional(),
4768
- include: external_exports.array(external_exports.string()).default([
4769
- "**/*.{ts,tsx,js,jsx,mjs,cjs}",
4770
- "**/*.{py,pyi}",
4771
- "**/*.{go,rs,java,kt,scala}",
4772
- "**/*.{c,cpp,cc,h,hpp}",
4773
- "**/*.{rb,php,swift}",
4774
- "**/*.{vue,svelte,astro}",
4775
- "**/*.{sql,graphql,proto}",
4776
- "**/*.{yaml,yml,toml}",
4777
- "**/*.{md,mdx}",
4778
- "**/*.{sh,bash,zsh}"
4779
- ]),
4780
- exclude: external_exports.array(external_exports.string()).default([
4781
- "**/node_modules/**",
4782
- "**/.git/**",
4783
- "**/dist/**",
4784
- "**/build/**",
4785
- "**/*.min.js",
4786
- "**/*.bundle.js",
4787
- "**/vendor/**",
4788
- "**/__pycache__/**",
4789
- "**/target/**",
4790
- "**/coverage/**",
4791
- "**/.next/**",
4792
- "**/.nuxt/**",
4793
- "**/.opencode/**"
4794
- ])
4795
- });
664
+ var DEFAULT_INCLUDE = [
665
+ "**/*.{ts,tsx,js,jsx,mjs,cjs}",
666
+ "**/*.{py,pyi}",
667
+ "**/*.{go,rs,java,kt,scala}",
668
+ "**/*.{c,cpp,cc,h,hpp}",
669
+ "**/*.{rb,php,swift}",
670
+ "**/*.{vue,svelte,astro}",
671
+ "**/*.{sql,graphql,proto}",
672
+ "**/*.{yaml,yml,toml}",
673
+ "**/*.{md,mdx}",
674
+ "**/*.{sh,bash,zsh}"
675
+ ];
676
+ var DEFAULT_EXCLUDE = [
677
+ "**/node_modules/**",
678
+ "**/.git/**",
679
+ "**/dist/**",
680
+ "**/build/**",
681
+ "**/*.min.js",
682
+ "**/*.bundle.js",
683
+ "**/vendor/**",
684
+ "**/__pycache__/**",
685
+ "**/target/**",
686
+ "**/coverage/**",
687
+ "**/.next/**",
688
+ "**/.nuxt/**",
689
+ "**/.opencode/**"
690
+ ];
4796
691
  function getDefaultIndexingConfig() {
4797
692
  return {
4798
693
  autoIndex: false,
@@ -4811,17 +706,47 @@ function getDefaultSearchConfig() {
4811
706
  contextLines: 0
4812
707
  };
4813
708
  }
709
+ var VALID_PROVIDERS = ["auto", "github-copilot", "openai", "google", "ollama"];
710
+ var VALID_SCOPES = ["project", "global"];
711
+ function isValidProvider(value) {
712
+ return typeof value === "string" && VALID_PROVIDERS.includes(value);
713
+ }
714
+ function isValidScope(value) {
715
+ return typeof value === "string" && VALID_SCOPES.includes(value);
716
+ }
717
+ function isStringArray(value) {
718
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
719
+ }
4814
720
  function parseConfig(raw) {
4815
- const parsed = CodebaseIndexConfigSchema.parse(raw ?? {});
721
+ const input = raw && typeof raw === "object" ? raw : {};
722
+ const defaultIndexing = getDefaultIndexingConfig();
723
+ const defaultSearch = getDefaultSearchConfig();
724
+ const rawIndexing = input.indexing && typeof input.indexing === "object" ? input.indexing : {};
725
+ const indexing = {
726
+ autoIndex: typeof rawIndexing.autoIndex === "boolean" ? rawIndexing.autoIndex : defaultIndexing.autoIndex,
727
+ watchFiles: typeof rawIndexing.watchFiles === "boolean" ? rawIndexing.watchFiles : defaultIndexing.watchFiles,
728
+ maxFileSize: typeof rawIndexing.maxFileSize === "number" ? rawIndexing.maxFileSize : defaultIndexing.maxFileSize,
729
+ retries: typeof rawIndexing.retries === "number" ? rawIndexing.retries : defaultIndexing.retries,
730
+ retryDelayMs: typeof rawIndexing.retryDelayMs === "number" ? rawIndexing.retryDelayMs : defaultIndexing.retryDelayMs
731
+ };
732
+ const rawSearch = input.search && typeof input.search === "object" ? input.search : {};
733
+ const search = {
734
+ maxResults: typeof rawSearch.maxResults === "number" ? rawSearch.maxResults : defaultSearch.maxResults,
735
+ minScore: typeof rawSearch.minScore === "number" ? rawSearch.minScore : defaultSearch.minScore,
736
+ includeContext: typeof rawSearch.includeContext === "boolean" ? rawSearch.includeContext : defaultSearch.includeContext,
737
+ hybridWeight: typeof rawSearch.hybridWeight === "number" ? Math.min(1, Math.max(0, rawSearch.hybridWeight)) : defaultSearch.hybridWeight,
738
+ contextLines: typeof rawSearch.contextLines === "number" ? Math.min(50, Math.max(0, rawSearch.contextLines)) : defaultSearch.contextLines
739
+ };
4816
740
  return {
4817
- ...parsed,
4818
- indexing: parsed.indexing ?? getDefaultIndexingConfig(),
4819
- search: parsed.search ?? getDefaultSearchConfig()
741
+ embeddingProvider: isValidProvider(input.embeddingProvider) ? input.embeddingProvider : "auto",
742
+ embeddingModel: typeof input.embeddingModel === "string" ? input.embeddingModel : "auto",
743
+ scope: isValidScope(input.scope) ? input.scope : "project",
744
+ include: isStringArray(input.include) ? input.include : DEFAULT_INCLUDE,
745
+ exclude: isStringArray(input.exclude) ? input.exclude : DEFAULT_EXCLUDE,
746
+ indexing,
747
+ search
4820
748
  };
4821
749
  }
4822
- function getDefaultConfig() {
4823
- return CodebaseIndexConfigSchema.parse({});
4824
- }
4825
750
  var EMBEDDING_MODELS = {
4826
751
  "github-copilot/text-embedding-3-small": {
4827
752
  provider: "github-copilot",
@@ -4877,7 +802,7 @@ function getDefaultModelForProvider(provider) {
4877
802
  case "ollama":
4878
803
  return EMBEDDING_MODELS["ollama/nomic-embed-text"];
4879
804
  default:
4880
- return EMBEDDING_MODELS["github/text-embedding-3-small"];
805
+ return EMBEDDING_MODELS["github-copilot/text-embedding-3-small"];
4881
806
  }
4882
807
  }
4883
808
 
@@ -5707,8 +1632,8 @@ var errorMessages = /* @__PURE__ */ new Set([
5707
1632
  // Cloudflare Workers (fetch)
5708
1633
  ]);
5709
1634
  function isNetworkError(error) {
5710
- const isValid2 = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
5711
- if (!isValid2) {
1635
+ const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
1636
+ if (!isValid) {
5712
1637
  return false;
5713
1638
  }
5714
1639
  const { message, stack } = error;
@@ -6375,9 +2300,6 @@ async function collectFiles(projectRoot, includePatterns, excludePatterns, maxFi
6375
2300
  }
6376
2301
 
6377
2302
  // src/utils/cost.ts
6378
- function estimateTokens(text) {
6379
- return Math.ceil(text.length / 4);
6380
- }
6381
2303
  function estimateChunksFromFiles(files) {
6382
2304
  let totalChunks = 0;
6383
2305
  for (const file of files) {
@@ -6438,25 +2360,6 @@ function formatBytes(bytes) {
6438
2360
  function padRight(str, length) {
6439
2361
  return str.padEnd(length);
6440
2362
  }
6441
- function formatConfirmationPrompt() {
6442
- return `
6443
- Proceed with indexing? [Y/n/always]
6444
-
6445
- Y - Index now
6446
- n - Cancel
6447
- always - Index now and don't ask again for this project
6448
- `;
6449
- }
6450
- function parseConfirmationResponse(response) {
6451
- const normalized = response.toLowerCase().trim();
6452
- if (normalized === "" || normalized === "y" || normalized === "yes") {
6453
- return { confirmed: true, rememberChoice: false };
6454
- }
6455
- if (normalized === "always" || normalized === "a") {
6456
- return { confirmed: true, rememberChoice: true };
6457
- }
6458
- return { confirmed: false, rememberChoice: false };
6459
- }
6460
2363
 
6461
2364
  // src/native/index.ts
6462
2365
  var path4 = __toESM(require("path"), 1);
@@ -6494,10 +2397,6 @@ function getNativeBinding() {
6494
2397
  return require(nativePath);
6495
2398
  }
6496
2399
  var native = getNativeBinding();
6497
- function parseFile(filePath, content) {
6498
- const result = native.parseFile(filePath, content);
6499
- return result.map(mapChunk);
6500
- }
6501
2400
  function parseFiles(files) {
6502
2401
  const result = native.parseFiles(files);
6503
2402
  return result.map((f) => ({
@@ -6595,7 +2494,7 @@ var VectorStore = class {
6595
2494
  var CHARS_PER_TOKEN = 4;
6596
2495
  var MAX_BATCH_TOKENS = 7500;
6597
2496
  var MAX_SINGLE_CHUNK_TOKENS = 2e3;
6598
- function estimateTokens2(text) {
2497
+ function estimateTokens(text) {
6599
2498
  return Math.ceil(text.length / CHARS_PER_TOKEN);
6600
2499
  }
6601
2500
  function createEmbeddingText(chunk, filePath) {
@@ -6660,7 +2559,7 @@ function createDynamicBatches(chunks) {
6660
2559
  let currentBatch = [];
6661
2560
  let currentTokens = 0;
6662
2561
  for (const chunk of chunks) {
6663
- const chunkTokens = estimateTokens2(chunk.text);
2562
+ const chunkTokens = estimateTokens(chunk.text);
6664
2563
  if (currentBatch.length > 0 && currentTokens + chunkTokens > MAX_BATCH_TOKENS) {
6665
2564
  batches.push(currentBatch);
6666
2565
  currentBatch = [];
@@ -9216,7 +5115,7 @@ var codebase_search = (0, import_plugin.tool)({
9216
5115
  },
9217
5116
  async execute(args) {
9218
5117
  const indexer = getIndexer();
9219
- const results = await indexer.search(args.query, args.limit, {
5118
+ const results = await indexer.search(args.query, args.limit ?? 10, {
9220
5119
  fileType: args.fileType,
9221
5120
  directory: args.directory,
9222
5121
  chunkType: args.chunkType,
@@ -9254,7 +5153,7 @@ var index_codebase = (0, import_plugin.tool)({
9254
5153
  await indexer.clearIndex();
9255
5154
  }
9256
5155
  const stats = await indexer.index();
9257
- return formatIndexStats(stats, args.verbose);
5156
+ return formatIndexStats(stats, args.verbose ?? false);
9258
5157
  }
9259
5158
  });
9260
5159
  var index_status = (0, import_plugin.tool)({
@@ -9380,44 +5279,6 @@ var plugin = async ({ directory }) => {
9380
5279
  };
9381
5280
  };
9382
5281
  var index_default = plugin;
9383
- // Annotate the CommonJS export names for ESM import in node:
9384
- 0 && (module.exports = {
9385
- CodebaseIndexConfigSchema,
9386
- EMBEDDING_MODELS,
9387
- EmbeddingProviderSchema,
9388
- FileWatcher,
9389
- IndexScopeSchema,
9390
- Indexer,
9391
- IndexingConfigSchema,
9392
- SearchConfigSchema,
9393
- VectorStore,
9394
- collectFiles,
9395
- createCostEstimate,
9396
- createDynamicBatches,
9397
- createEmbeddingProvider,
9398
- createEmbeddingText,
9399
- createIgnoreFilter,
9400
- detectEmbeddingProvider,
9401
- estimateChunksFromFiles,
9402
- estimateCost,
9403
- estimateTokens,
9404
- formatBytes,
9405
- formatConfirmationPrompt,
9406
- formatCostEstimate,
9407
- generateChunkHash,
9408
- generateChunkId,
9409
- getDefaultConfig,
9410
- getDefaultModelForProvider,
9411
- getProviderDisplayName,
9412
- hashContent,
9413
- hashFile,
9414
- parseConfig,
9415
- parseConfirmationResponse,
9416
- parseFile,
9417
- parseFiles,
9418
- shouldIncludeFile,
9419
- walkDirectory
9420
- });
9421
5282
  /*! Bundled license information:
9422
5283
 
9423
5284
  chokidar/index.js: