@hy_ong/zod-kit 0.1.1 → 0.1.2
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 +40 -21
- package/dist/index.d.cts +24 -11
- package/dist/index.d.ts +24 -11
- package/dist/index.js +40 -21
- package/package.json +1 -1
- package/src/validators/common/id.ts +108 -41
- package/tests/common/id.test.ts +62 -4
package/dist/index.cjs
CHANGED
|
@@ -1291,35 +1291,31 @@ var validateIdType = (value, type) => {
|
|
|
1291
1291
|
return pattern ? pattern.test(value) : false;
|
|
1292
1292
|
};
|
|
1293
1293
|
function id(required, options) {
|
|
1294
|
-
const {
|
|
1295
|
-
type = "auto",
|
|
1296
|
-
minLength,
|
|
1297
|
-
maxLength,
|
|
1298
|
-
allowedTypes,
|
|
1299
|
-
customRegex,
|
|
1300
|
-
includes,
|
|
1301
|
-
excludes,
|
|
1302
|
-
startsWith,
|
|
1303
|
-
endsWith,
|
|
1304
|
-
caseSensitive = true,
|
|
1305
|
-
transform,
|
|
1306
|
-
defaultValue,
|
|
1307
|
-
i18n
|
|
1308
|
-
} = options ?? {};
|
|
1294
|
+
const { type = "auto", minLength, maxLength, allowedTypes, customRegex, includes, excludes, startsWith, endsWith, caseSensitive = true, transform, defaultValue, i18n } = options ?? {};
|
|
1309
1295
|
const isRequired = required ?? false;
|
|
1310
|
-
const
|
|
1296
|
+
const isNumericType = type === "numeric";
|
|
1297
|
+
const actualDefaultValue = defaultValue !== void 0 ? defaultValue : isRequired ? isNumericType ? NaN : "" : null;
|
|
1311
1298
|
const getMessage = (key, params) => {
|
|
1312
1299
|
if (i18n) {
|
|
1313
1300
|
const currentLocale2 = getLocale();
|
|
1314
1301
|
const customMessages = i18n[currentLocale2];
|
|
1315
1302
|
if (customMessages && customMessages[key]) {
|
|
1316
1303
|
const template = customMessages[key];
|
|
1317
|
-
return template.replace(/\$\{(\w+)}/g, (
|
|
1304
|
+
return template.replace(/\$\{(\w+)}/g, (_match, k) => params?.[k] ?? "");
|
|
1318
1305
|
}
|
|
1319
1306
|
}
|
|
1320
1307
|
return t(`common.id.${key}`, params);
|
|
1321
1308
|
};
|
|
1322
|
-
const
|
|
1309
|
+
const preprocessNumericFn = (val) => {
|
|
1310
|
+
if (val === "" || val === null || val === void 0) {
|
|
1311
|
+
if (isRequired && defaultValue === void 0) {
|
|
1312
|
+
return void 0;
|
|
1313
|
+
}
|
|
1314
|
+
return actualDefaultValue;
|
|
1315
|
+
}
|
|
1316
|
+
return Number(val);
|
|
1317
|
+
};
|
|
1318
|
+
const preprocessStringFn = (val) => {
|
|
1323
1319
|
if (val === "" || val === null || val === void 0) {
|
|
1324
1320
|
return actualDefaultValue;
|
|
1325
1321
|
}
|
|
@@ -1329,7 +1325,30 @@ function id(required, options) {
|
|
|
1329
1325
|
}
|
|
1330
1326
|
return processed;
|
|
1331
1327
|
};
|
|
1332
|
-
|
|
1328
|
+
if (isNumericType) {
|
|
1329
|
+
const numericSchema = import_zod6.z.preprocess(preprocessNumericFn, import_zod6.z.any()).refine((val) => {
|
|
1330
|
+
if (!isRequired && val === null) return true;
|
|
1331
|
+
if (val === void 0 || isRequired && val === null) {
|
|
1332
|
+
throw new import_zod6.z.ZodError([{ code: "custom", message: getMessage("required"), path: [] }]);
|
|
1333
|
+
}
|
|
1334
|
+
if (typeof val !== "number" || isNaN(val)) {
|
|
1335
|
+
throw new import_zod6.z.ZodError([{ code: "custom", message: getMessage("numeric"), path: [] }]);
|
|
1336
|
+
}
|
|
1337
|
+
const strVal = String(val);
|
|
1338
|
+
if (!ID_PATTERNS.numeric.test(strVal)) {
|
|
1339
|
+
throw new import_zod6.z.ZodError([{ code: "custom", message: getMessage("numeric"), path: [] }]);
|
|
1340
|
+
}
|
|
1341
|
+
if (minLength !== void 0 && strVal.length < minLength) {
|
|
1342
|
+
throw new import_zod6.z.ZodError([{ code: "custom", message: getMessage("minLength", { minLength }), path: [] }]);
|
|
1343
|
+
}
|
|
1344
|
+
if (maxLength !== void 0 && strVal.length > maxLength) {
|
|
1345
|
+
throw new import_zod6.z.ZodError([{ code: "custom", message: getMessage("maxLength", { maxLength }), path: [] }]);
|
|
1346
|
+
}
|
|
1347
|
+
return true;
|
|
1348
|
+
});
|
|
1349
|
+
return numericSchema;
|
|
1350
|
+
}
|
|
1351
|
+
const baseSchema = isRequired ? import_zod6.z.preprocess(preprocessStringFn, import_zod6.z.string()) : import_zod6.z.preprocess(preprocessStringFn, import_zod6.z.string().nullable());
|
|
1333
1352
|
const schema = baseSchema.refine((val) => {
|
|
1334
1353
|
if (val === null) return true;
|
|
1335
1354
|
if (isRequired && (val === "" || val === "null" || val === "undefined")) {
|
|
@@ -1355,7 +1374,7 @@ function id(required, options) {
|
|
|
1355
1374
|
const typeNames = allowedTypes.join(", ");
|
|
1356
1375
|
throw new import_zod6.z.ZodError([{ code: "custom", message: getMessage("invalid") + ` (allowed types: ${typeNames})`, path: [] }]);
|
|
1357
1376
|
}
|
|
1358
|
-
} else if (type !== "auto") {
|
|
1377
|
+
} else if (type && type !== "auto") {
|
|
1359
1378
|
isValidId = validateIdType(val, type);
|
|
1360
1379
|
if (!isValidId) {
|
|
1361
1380
|
throw new import_zod6.z.ZodError([{ code: "custom", message: getMessage(type) || getMessage("invalid"), path: [] }]);
|
|
@@ -1366,7 +1385,7 @@ function id(required, options) {
|
|
|
1366
1385
|
throw new import_zod6.z.ZodError([{ code: "custom", message: getMessage("invalid"), path: [] }]);
|
|
1367
1386
|
}
|
|
1368
1387
|
}
|
|
1369
|
-
} else if (val !== null && hasContentValidations && type !== "auto" && !customRegex) {
|
|
1388
|
+
} else if (val !== null && hasContentValidations && type && type !== "auto" && !customRegex) {
|
|
1370
1389
|
if (allowedTypes && allowedTypes.length > 0) {
|
|
1371
1390
|
const isValidType = allowedTypes.some((allowedType) => validateIdType(val, allowedType));
|
|
1372
1391
|
if (!isValidType) {
|
package/dist/index.d.cts
CHANGED
|
@@ -978,10 +978,11 @@ type IdType = "numeric" | "uuid" | "objectId" | "nanoid" | "snowflake" | "cuid"
|
|
|
978
978
|
* Configuration options for ID validation
|
|
979
979
|
*
|
|
980
980
|
* @template IsRequired - Whether the field is required (affects return type)
|
|
981
|
+
* @template Type - The ID type being validated
|
|
981
982
|
*
|
|
982
983
|
* @interface IdOptions
|
|
983
984
|
* @property {IsRequired} [required=true] - Whether the field is required
|
|
984
|
-
* @property {
|
|
985
|
+
* @property {Type} [type="auto"] - Expected ID type or auto-detection
|
|
985
986
|
* @property {number} [minLength] - Minimum length of ID
|
|
986
987
|
* @property {number} [maxLength] - Maximum length of ID
|
|
987
988
|
* @property {IdType[]} [allowedTypes] - Multiple allowed ID types (overrides type)
|
|
@@ -992,11 +993,11 @@ type IdType = "numeric" | "uuid" | "objectId" | "nanoid" | "snowflake" | "cuid"
|
|
|
992
993
|
* @property {string} [endsWith] - String that ID must end with
|
|
993
994
|
* @property {boolean} [caseSensitive=true] - Whether validation is case-sensitive
|
|
994
995
|
* @property {Function} [transform] - Custom transformation function for ID
|
|
995
|
-
* @property {
|
|
996
|
+
* @property {any} [defaultValue] - Default value when input is empty (string for string types, number for numeric)
|
|
996
997
|
* @property {Record<Locale, IdMessages>} [i18n] - Custom error messages for different locales
|
|
997
998
|
*/
|
|
998
|
-
type IdOptions<
|
|
999
|
-
type?:
|
|
999
|
+
type IdOptions<Type extends IdType | undefined = undefined> = {
|
|
1000
|
+
type?: Type;
|
|
1000
1001
|
minLength?: number;
|
|
1001
1002
|
maxLength?: number;
|
|
1002
1003
|
allowedTypes?: IdType[];
|
|
@@ -1007,17 +1008,20 @@ type IdOptions<IsRequired extends boolean = true> = {
|
|
|
1007
1008
|
endsWith?: string;
|
|
1008
1009
|
caseSensitive?: boolean;
|
|
1009
1010
|
transform?: (value: string) => string;
|
|
1010
|
-
defaultValue?:
|
|
1011
|
+
defaultValue?: any;
|
|
1011
1012
|
i18n?: Record<Locale, IdMessages>;
|
|
1012
1013
|
};
|
|
1013
1014
|
/**
|
|
1014
|
-
* Type alias for ID validation schema based on required flag
|
|
1015
|
+
* Type alias for ID validation schema based on required flag and ID type
|
|
1015
1016
|
*
|
|
1016
1017
|
* @template IsRequired - Whether the field is required
|
|
1018
|
+
* @template IdType - The ID type being validated
|
|
1017
1019
|
* @typedef IdSchema
|
|
1018
|
-
* @description Returns
|
|
1020
|
+
* @description Returns appropriate Zod type based on required flag and ID type:
|
|
1021
|
+
* - numeric type: ZodNumber or ZodNullable<ZodNumber>
|
|
1022
|
+
* - other types: ZodString or ZodNullable<ZodString>
|
|
1019
1023
|
*/
|
|
1020
|
-
type IdSchema<IsRequired extends boolean> = IsRequired extends true ? ZodString : ZodNullable<ZodString>;
|
|
1024
|
+
type IdSchema<IsRequired extends boolean, Type extends IdType | undefined = undefined> = Type extends "numeric" ? IsRequired extends true ? ZodNumber : ZodNullable<ZodNumber> : IsRequired extends true ? ZodString : ZodNullable<ZodString>;
|
|
1021
1025
|
/**
|
|
1022
1026
|
* Regular expression patterns for different ID formats
|
|
1023
1027
|
*
|
|
@@ -1079,9 +1083,9 @@ declare const validateIdType: (value: string, type: IdType) => boolean;
|
|
|
1079
1083
|
* Creates a Zod schema for ID validation with comprehensive format support
|
|
1080
1084
|
*
|
|
1081
1085
|
* @template IsRequired - Whether the field is required (affects return type)
|
|
1086
|
+
* @template Type - The ID type being validated (affects return type for numeric)
|
|
1082
1087
|
* @param {IsRequired} [required=false] - Whether the field is required
|
|
1083
|
-
* @
|
|
1084
|
-
* @returns {IdSchema<IsRequired>} Zod schema for ID validation
|
|
1088
|
+
* @returns {IdSchema<IsRequired, Type>} Zod schema for ID validation
|
|
1085
1089
|
*
|
|
1086
1090
|
* @description
|
|
1087
1091
|
* Creates a comprehensive ID validator with support for multiple ID formats,
|
|
@@ -1149,7 +1153,16 @@ declare const validateIdType: (value: string, type: IdType) => boolean;
|
|
|
1149
1153
|
* @see {@link detectIdType} for auto-detection logic
|
|
1150
1154
|
* @see {@link validateIdType} for type-specific validation
|
|
1151
1155
|
*/
|
|
1152
|
-
declare function id<IsRequired extends boolean = false>(required?: IsRequired
|
|
1156
|
+
declare function id<IsRequired extends boolean = false>(required?: IsRequired): IdSchema<IsRequired, undefined>;
|
|
1157
|
+
declare function id<IsRequired extends boolean = false>(required: IsRequired, options: Omit<IdOptions<"numeric">, "required"> & {
|
|
1158
|
+
type: "numeric";
|
|
1159
|
+
}): IdSchema<IsRequired, "numeric">;
|
|
1160
|
+
declare function id<IsRequired extends boolean = false, Type extends Exclude<IdType, "numeric"> = Exclude<IdType, "numeric">>(required: IsRequired, options: Omit<IdOptions<Type>, "required"> & {
|
|
1161
|
+
type: Type;
|
|
1162
|
+
}): IdSchema<IsRequired, Type>;
|
|
1163
|
+
declare function id<IsRequired extends boolean = false>(required: IsRequired, options: Omit<IdOptions, "required"> & {
|
|
1164
|
+
type?: never;
|
|
1165
|
+
}): IdSchema<IsRequired, undefined>;
|
|
1153
1166
|
|
|
1154
1167
|
/**
|
|
1155
1168
|
* @fileoverview Number validator for Zod Kit
|
package/dist/index.d.ts
CHANGED
|
@@ -978,10 +978,11 @@ type IdType = "numeric" | "uuid" | "objectId" | "nanoid" | "snowflake" | "cuid"
|
|
|
978
978
|
* Configuration options for ID validation
|
|
979
979
|
*
|
|
980
980
|
* @template IsRequired - Whether the field is required (affects return type)
|
|
981
|
+
* @template Type - The ID type being validated
|
|
981
982
|
*
|
|
982
983
|
* @interface IdOptions
|
|
983
984
|
* @property {IsRequired} [required=true] - Whether the field is required
|
|
984
|
-
* @property {
|
|
985
|
+
* @property {Type} [type="auto"] - Expected ID type or auto-detection
|
|
985
986
|
* @property {number} [minLength] - Minimum length of ID
|
|
986
987
|
* @property {number} [maxLength] - Maximum length of ID
|
|
987
988
|
* @property {IdType[]} [allowedTypes] - Multiple allowed ID types (overrides type)
|
|
@@ -992,11 +993,11 @@ type IdType = "numeric" | "uuid" | "objectId" | "nanoid" | "snowflake" | "cuid"
|
|
|
992
993
|
* @property {string} [endsWith] - String that ID must end with
|
|
993
994
|
* @property {boolean} [caseSensitive=true] - Whether validation is case-sensitive
|
|
994
995
|
* @property {Function} [transform] - Custom transformation function for ID
|
|
995
|
-
* @property {
|
|
996
|
+
* @property {any} [defaultValue] - Default value when input is empty (string for string types, number for numeric)
|
|
996
997
|
* @property {Record<Locale, IdMessages>} [i18n] - Custom error messages for different locales
|
|
997
998
|
*/
|
|
998
|
-
type IdOptions<
|
|
999
|
-
type?:
|
|
999
|
+
type IdOptions<Type extends IdType | undefined = undefined> = {
|
|
1000
|
+
type?: Type;
|
|
1000
1001
|
minLength?: number;
|
|
1001
1002
|
maxLength?: number;
|
|
1002
1003
|
allowedTypes?: IdType[];
|
|
@@ -1007,17 +1008,20 @@ type IdOptions<IsRequired extends boolean = true> = {
|
|
|
1007
1008
|
endsWith?: string;
|
|
1008
1009
|
caseSensitive?: boolean;
|
|
1009
1010
|
transform?: (value: string) => string;
|
|
1010
|
-
defaultValue?:
|
|
1011
|
+
defaultValue?: any;
|
|
1011
1012
|
i18n?: Record<Locale, IdMessages>;
|
|
1012
1013
|
};
|
|
1013
1014
|
/**
|
|
1014
|
-
* Type alias for ID validation schema based on required flag
|
|
1015
|
+
* Type alias for ID validation schema based on required flag and ID type
|
|
1015
1016
|
*
|
|
1016
1017
|
* @template IsRequired - Whether the field is required
|
|
1018
|
+
* @template IdType - The ID type being validated
|
|
1017
1019
|
* @typedef IdSchema
|
|
1018
|
-
* @description Returns
|
|
1020
|
+
* @description Returns appropriate Zod type based on required flag and ID type:
|
|
1021
|
+
* - numeric type: ZodNumber or ZodNullable<ZodNumber>
|
|
1022
|
+
* - other types: ZodString or ZodNullable<ZodString>
|
|
1019
1023
|
*/
|
|
1020
|
-
type IdSchema<IsRequired extends boolean> = IsRequired extends true ? ZodString : ZodNullable<ZodString>;
|
|
1024
|
+
type IdSchema<IsRequired extends boolean, Type extends IdType | undefined = undefined> = Type extends "numeric" ? IsRequired extends true ? ZodNumber : ZodNullable<ZodNumber> : IsRequired extends true ? ZodString : ZodNullable<ZodString>;
|
|
1021
1025
|
/**
|
|
1022
1026
|
* Regular expression patterns for different ID formats
|
|
1023
1027
|
*
|
|
@@ -1079,9 +1083,9 @@ declare const validateIdType: (value: string, type: IdType) => boolean;
|
|
|
1079
1083
|
* Creates a Zod schema for ID validation with comprehensive format support
|
|
1080
1084
|
*
|
|
1081
1085
|
* @template IsRequired - Whether the field is required (affects return type)
|
|
1086
|
+
* @template Type - The ID type being validated (affects return type for numeric)
|
|
1082
1087
|
* @param {IsRequired} [required=false] - Whether the field is required
|
|
1083
|
-
* @
|
|
1084
|
-
* @returns {IdSchema<IsRequired>} Zod schema for ID validation
|
|
1088
|
+
* @returns {IdSchema<IsRequired, Type>} Zod schema for ID validation
|
|
1085
1089
|
*
|
|
1086
1090
|
* @description
|
|
1087
1091
|
* Creates a comprehensive ID validator with support for multiple ID formats,
|
|
@@ -1149,7 +1153,16 @@ declare const validateIdType: (value: string, type: IdType) => boolean;
|
|
|
1149
1153
|
* @see {@link detectIdType} for auto-detection logic
|
|
1150
1154
|
* @see {@link validateIdType} for type-specific validation
|
|
1151
1155
|
*/
|
|
1152
|
-
declare function id<IsRequired extends boolean = false>(required?: IsRequired
|
|
1156
|
+
declare function id<IsRequired extends boolean = false>(required?: IsRequired): IdSchema<IsRequired, undefined>;
|
|
1157
|
+
declare function id<IsRequired extends boolean = false>(required: IsRequired, options: Omit<IdOptions<"numeric">, "required"> & {
|
|
1158
|
+
type: "numeric";
|
|
1159
|
+
}): IdSchema<IsRequired, "numeric">;
|
|
1160
|
+
declare function id<IsRequired extends boolean = false, Type extends Exclude<IdType, "numeric"> = Exclude<IdType, "numeric">>(required: IsRequired, options: Omit<IdOptions<Type>, "required"> & {
|
|
1161
|
+
type: Type;
|
|
1162
|
+
}): IdSchema<IsRequired, Type>;
|
|
1163
|
+
declare function id<IsRequired extends boolean = false>(required: IsRequired, options: Omit<IdOptions, "required"> & {
|
|
1164
|
+
type?: never;
|
|
1165
|
+
}): IdSchema<IsRequired, undefined>;
|
|
1153
1166
|
|
|
1154
1167
|
/**
|
|
1155
1168
|
* @fileoverview Number validator for Zod Kit
|
package/dist/index.js
CHANGED
|
@@ -1213,35 +1213,31 @@ var validateIdType = (value, type) => {
|
|
|
1213
1213
|
return pattern ? pattern.test(value) : false;
|
|
1214
1214
|
};
|
|
1215
1215
|
function id(required, options) {
|
|
1216
|
-
const {
|
|
1217
|
-
type = "auto",
|
|
1218
|
-
minLength,
|
|
1219
|
-
maxLength,
|
|
1220
|
-
allowedTypes,
|
|
1221
|
-
customRegex,
|
|
1222
|
-
includes,
|
|
1223
|
-
excludes,
|
|
1224
|
-
startsWith,
|
|
1225
|
-
endsWith,
|
|
1226
|
-
caseSensitive = true,
|
|
1227
|
-
transform,
|
|
1228
|
-
defaultValue,
|
|
1229
|
-
i18n
|
|
1230
|
-
} = options ?? {};
|
|
1216
|
+
const { type = "auto", minLength, maxLength, allowedTypes, customRegex, includes, excludes, startsWith, endsWith, caseSensitive = true, transform, defaultValue, i18n } = options ?? {};
|
|
1231
1217
|
const isRequired = required ?? false;
|
|
1232
|
-
const
|
|
1218
|
+
const isNumericType = type === "numeric";
|
|
1219
|
+
const actualDefaultValue = defaultValue !== void 0 ? defaultValue : isRequired ? isNumericType ? NaN : "" : null;
|
|
1233
1220
|
const getMessage = (key, params) => {
|
|
1234
1221
|
if (i18n) {
|
|
1235
1222
|
const currentLocale2 = getLocale();
|
|
1236
1223
|
const customMessages = i18n[currentLocale2];
|
|
1237
1224
|
if (customMessages && customMessages[key]) {
|
|
1238
1225
|
const template = customMessages[key];
|
|
1239
|
-
return template.replace(/\$\{(\w+)}/g, (
|
|
1226
|
+
return template.replace(/\$\{(\w+)}/g, (_match, k) => params?.[k] ?? "");
|
|
1240
1227
|
}
|
|
1241
1228
|
}
|
|
1242
1229
|
return t(`common.id.${key}`, params);
|
|
1243
1230
|
};
|
|
1244
|
-
const
|
|
1231
|
+
const preprocessNumericFn = (val) => {
|
|
1232
|
+
if (val === "" || val === null || val === void 0) {
|
|
1233
|
+
if (isRequired && defaultValue === void 0) {
|
|
1234
|
+
return void 0;
|
|
1235
|
+
}
|
|
1236
|
+
return actualDefaultValue;
|
|
1237
|
+
}
|
|
1238
|
+
return Number(val);
|
|
1239
|
+
};
|
|
1240
|
+
const preprocessStringFn = (val) => {
|
|
1245
1241
|
if (val === "" || val === null || val === void 0) {
|
|
1246
1242
|
return actualDefaultValue;
|
|
1247
1243
|
}
|
|
@@ -1251,7 +1247,30 @@ function id(required, options) {
|
|
|
1251
1247
|
}
|
|
1252
1248
|
return processed;
|
|
1253
1249
|
};
|
|
1254
|
-
|
|
1250
|
+
if (isNumericType) {
|
|
1251
|
+
const numericSchema = z6.preprocess(preprocessNumericFn, z6.any()).refine((val) => {
|
|
1252
|
+
if (!isRequired && val === null) return true;
|
|
1253
|
+
if (val === void 0 || isRequired && val === null) {
|
|
1254
|
+
throw new z6.ZodError([{ code: "custom", message: getMessage("required"), path: [] }]);
|
|
1255
|
+
}
|
|
1256
|
+
if (typeof val !== "number" || isNaN(val)) {
|
|
1257
|
+
throw new z6.ZodError([{ code: "custom", message: getMessage("numeric"), path: [] }]);
|
|
1258
|
+
}
|
|
1259
|
+
const strVal = String(val);
|
|
1260
|
+
if (!ID_PATTERNS.numeric.test(strVal)) {
|
|
1261
|
+
throw new z6.ZodError([{ code: "custom", message: getMessage("numeric"), path: [] }]);
|
|
1262
|
+
}
|
|
1263
|
+
if (minLength !== void 0 && strVal.length < minLength) {
|
|
1264
|
+
throw new z6.ZodError([{ code: "custom", message: getMessage("minLength", { minLength }), path: [] }]);
|
|
1265
|
+
}
|
|
1266
|
+
if (maxLength !== void 0 && strVal.length > maxLength) {
|
|
1267
|
+
throw new z6.ZodError([{ code: "custom", message: getMessage("maxLength", { maxLength }), path: [] }]);
|
|
1268
|
+
}
|
|
1269
|
+
return true;
|
|
1270
|
+
});
|
|
1271
|
+
return numericSchema;
|
|
1272
|
+
}
|
|
1273
|
+
const baseSchema = isRequired ? z6.preprocess(preprocessStringFn, z6.string()) : z6.preprocess(preprocessStringFn, z6.string().nullable());
|
|
1255
1274
|
const schema = baseSchema.refine((val) => {
|
|
1256
1275
|
if (val === null) return true;
|
|
1257
1276
|
if (isRequired && (val === "" || val === "null" || val === "undefined")) {
|
|
@@ -1277,7 +1296,7 @@ function id(required, options) {
|
|
|
1277
1296
|
const typeNames = allowedTypes.join(", ");
|
|
1278
1297
|
throw new z6.ZodError([{ code: "custom", message: getMessage("invalid") + ` (allowed types: ${typeNames})`, path: [] }]);
|
|
1279
1298
|
}
|
|
1280
|
-
} else if (type !== "auto") {
|
|
1299
|
+
} else if (type && type !== "auto") {
|
|
1281
1300
|
isValidId = validateIdType(val, type);
|
|
1282
1301
|
if (!isValidId) {
|
|
1283
1302
|
throw new z6.ZodError([{ code: "custom", message: getMessage(type) || getMessage("invalid"), path: [] }]);
|
|
@@ -1288,7 +1307,7 @@ function id(required, options) {
|
|
|
1288
1307
|
throw new z6.ZodError([{ code: "custom", message: getMessage("invalid"), path: [] }]);
|
|
1289
1308
|
}
|
|
1290
1309
|
}
|
|
1291
|
-
} else if (val !== null && hasContentValidations && type !== "auto" && !customRegex) {
|
|
1310
|
+
} else if (val !== null && hasContentValidations && type && type !== "auto" && !customRegex) {
|
|
1292
1311
|
if (allowedTypes && allowedTypes.length > 0) {
|
|
1293
1312
|
const isValidType = allowedTypes.some((allowedType) => validateIdType(val, allowedType));
|
|
1294
1313
|
if (!isValidType) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hy_ong/zod-kit",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "A comprehensive TypeScript library providing pre-built Zod validation schemas with full internationalization support for common data types and Taiwan-specific formats",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"zod",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* @version 0.0.5
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import { z, ZodNullable, ZodString } from "zod"
|
|
11
|
+
import { z, ZodNullable, ZodString, ZodNumber } from "zod"
|
|
12
12
|
import { t } from "../../i18n"
|
|
13
13
|
import { getLocale, type Locale } from "../../config"
|
|
14
14
|
|
|
@@ -85,10 +85,11 @@ export type IdType =
|
|
|
85
85
|
* Configuration options for ID validation
|
|
86
86
|
*
|
|
87
87
|
* @template IsRequired - Whether the field is required (affects return type)
|
|
88
|
+
* @template Type - The ID type being validated
|
|
88
89
|
*
|
|
89
90
|
* @interface IdOptions
|
|
90
91
|
* @property {IsRequired} [required=true] - Whether the field is required
|
|
91
|
-
* @property {
|
|
92
|
+
* @property {Type} [type="auto"] - Expected ID type or auto-detection
|
|
92
93
|
* @property {number} [minLength] - Minimum length of ID
|
|
93
94
|
* @property {number} [maxLength] - Maximum length of ID
|
|
94
95
|
* @property {IdType[]} [allowedTypes] - Multiple allowed ID types (overrides type)
|
|
@@ -99,11 +100,11 @@ export type IdType =
|
|
|
99
100
|
* @property {string} [endsWith] - String that ID must end with
|
|
100
101
|
* @property {boolean} [caseSensitive=true] - Whether validation is case-sensitive
|
|
101
102
|
* @property {Function} [transform] - Custom transformation function for ID
|
|
102
|
-
* @property {
|
|
103
|
+
* @property {any} [defaultValue] - Default value when input is empty (string for string types, number for numeric)
|
|
103
104
|
* @property {Record<Locale, IdMessages>} [i18n] - Custom error messages for different locales
|
|
104
105
|
*/
|
|
105
|
-
export type IdOptions<
|
|
106
|
-
type?:
|
|
106
|
+
export type IdOptions<Type extends IdType | undefined = undefined> = {
|
|
107
|
+
type?: Type
|
|
107
108
|
minLength?: number
|
|
108
109
|
maxLength?: number
|
|
109
110
|
allowedTypes?: IdType[]
|
|
@@ -114,18 +115,27 @@ export type IdOptions<IsRequired extends boolean = true> = {
|
|
|
114
115
|
endsWith?: string
|
|
115
116
|
caseSensitive?: boolean
|
|
116
117
|
transform?: (value: string) => string
|
|
117
|
-
defaultValue?:
|
|
118
|
+
defaultValue?: any // Simplified to avoid complex conditional types
|
|
118
119
|
i18n?: Record<Locale, IdMessages>
|
|
119
120
|
}
|
|
120
121
|
|
|
121
122
|
/**
|
|
122
|
-
* Type alias for ID validation schema based on required flag
|
|
123
|
+
* Type alias for ID validation schema based on required flag and ID type
|
|
123
124
|
*
|
|
124
125
|
* @template IsRequired - Whether the field is required
|
|
126
|
+
* @template IdType - The ID type being validated
|
|
125
127
|
* @typedef IdSchema
|
|
126
|
-
* @description Returns
|
|
128
|
+
* @description Returns appropriate Zod type based on required flag and ID type:
|
|
129
|
+
* - numeric type: ZodNumber or ZodNullable<ZodNumber>
|
|
130
|
+
* - other types: ZodString or ZodNullable<ZodString>
|
|
127
131
|
*/
|
|
128
|
-
export type IdSchema<IsRequired extends boolean
|
|
132
|
+
export type IdSchema<IsRequired extends boolean, Type extends IdType | undefined = undefined> = Type extends "numeric"
|
|
133
|
+
? IsRequired extends true
|
|
134
|
+
? ZodNumber
|
|
135
|
+
: ZodNullable<ZodNumber>
|
|
136
|
+
: IsRequired extends true
|
|
137
|
+
? ZodString
|
|
138
|
+
: ZodNullable<ZodString>
|
|
129
139
|
|
|
130
140
|
/**
|
|
131
141
|
* Regular expression patterns for different ID formats
|
|
@@ -216,9 +226,9 @@ const validateIdType = (value: string, type: IdType): boolean => {
|
|
|
216
226
|
* Creates a Zod schema for ID validation with comprehensive format support
|
|
217
227
|
*
|
|
218
228
|
* @template IsRequired - Whether the field is required (affects return type)
|
|
229
|
+
* @template Type - The ID type being validated (affects return type for numeric)
|
|
219
230
|
* @param {IsRequired} [required=false] - Whether the field is required
|
|
220
|
-
* @
|
|
221
|
-
* @returns {IdSchema<IsRequired>} Zod schema for ID validation
|
|
231
|
+
* @returns {IdSchema<IsRequired, Type>} Zod schema for ID validation
|
|
222
232
|
*
|
|
223
233
|
* @description
|
|
224
234
|
* Creates a comprehensive ID validator with support for multiple ID formats,
|
|
@@ -286,27 +296,31 @@ const validateIdType = (value: string, type: IdType): boolean => {
|
|
|
286
296
|
* @see {@link detectIdType} for auto-detection logic
|
|
287
297
|
* @see {@link validateIdType} for type-specific validation
|
|
288
298
|
*/
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
const
|
|
299
|
+
// Overload: no options provided
|
|
300
|
+
export function id<IsRequired extends boolean = false>(required?: IsRequired): IdSchema<IsRequired, undefined>
|
|
301
|
+
|
|
302
|
+
// Overload: options with numeric type
|
|
303
|
+
export function id<IsRequired extends boolean = false>(required: IsRequired, options: Omit<IdOptions<"numeric">, "required"> & { type: "numeric" }): IdSchema<IsRequired, "numeric">
|
|
304
|
+
|
|
305
|
+
// Overload: options with other specific type
|
|
306
|
+
export function id<IsRequired extends boolean = false, Type extends Exclude<IdType, "numeric"> = Exclude<IdType, "numeric">>(
|
|
307
|
+
required: IsRequired,
|
|
308
|
+
options: Omit<IdOptions<Type>, "required"> & { type: Type }
|
|
309
|
+
): IdSchema<IsRequired, Type>
|
|
310
|
+
|
|
311
|
+
// Overload: options without type specified
|
|
312
|
+
export function id<IsRequired extends boolean = false>(required: IsRequired, options: Omit<IdOptions, "required"> & { type?: never }): IdSchema<IsRequired, undefined>
|
|
313
|
+
|
|
314
|
+
// Implementation
|
|
315
|
+
export function id<IsRequired extends boolean = false, Type extends IdType | undefined = undefined>(required?: IsRequired, options?: any): any {
|
|
316
|
+
const { type = "auto" as Type, minLength, maxLength, allowedTypes, customRegex, includes, excludes, startsWith, endsWith, caseSensitive = true, transform, defaultValue, i18n } = options ?? {}
|
|
317
|
+
|
|
318
|
+
const isRequired = (required ?? false) as IsRequired
|
|
319
|
+
const isNumericType = type === "numeric"
|
|
320
|
+
|
|
321
|
+
// Set appropriate default value based on required flag and type
|
|
322
|
+
// For required fields, we don't set a default unless explicitly provided
|
|
323
|
+
const actualDefaultValue = defaultValue !== undefined ? defaultValue : isRequired ? (isNumericType ? NaN : "") : null
|
|
310
324
|
|
|
311
325
|
// Helper function to get custom message or fallback to default i18n
|
|
312
326
|
const getMessage = (key: keyof IdMessages, params?: Record<string, any>) => {
|
|
@@ -315,14 +329,30 @@ export function id<IsRequired extends boolean = false>(required?: IsRequired, op
|
|
|
315
329
|
const customMessages = i18n[currentLocale]
|
|
316
330
|
if (customMessages && customMessages[key]) {
|
|
317
331
|
const template = customMessages[key]!
|
|
318
|
-
return template.replace(/\$\{(\w+)}/g, (
|
|
332
|
+
return template.replace(/\$\{(\w+)}/g, (_match: string, k: string) => params?.[k] ?? "")
|
|
319
333
|
}
|
|
320
334
|
}
|
|
321
335
|
return t(`common.id.${key}`, params)
|
|
322
336
|
}
|
|
323
337
|
|
|
324
|
-
// Preprocessing function
|
|
325
|
-
const
|
|
338
|
+
// Preprocessing function for numeric type
|
|
339
|
+
const preprocessNumericFn = (val: unknown) => {
|
|
340
|
+
// Handle empty/null values
|
|
341
|
+
if (val === "" || val === null || val === undefined) {
|
|
342
|
+
// If required and no default, return a special marker that will fail validation
|
|
343
|
+
if (isRequired && defaultValue === undefined) {
|
|
344
|
+
// Return undefined to trigger required error in refine
|
|
345
|
+
return undefined as any
|
|
346
|
+
}
|
|
347
|
+
return actualDefaultValue
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Try to convert to number and return (even if NaN) so it can be validated by the schema
|
|
351
|
+
return Number(val)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Preprocessing function for string type
|
|
355
|
+
const preprocessStringFn = (val: unknown) => {
|
|
326
356
|
if (val === "" || val === null || val === undefined) {
|
|
327
357
|
return actualDefaultValue
|
|
328
358
|
}
|
|
@@ -336,7 +366,44 @@ export function id<IsRequired extends boolean = false>(required?: IsRequired, op
|
|
|
336
366
|
return processed
|
|
337
367
|
}
|
|
338
368
|
|
|
339
|
-
|
|
369
|
+
// Create base schema based on type
|
|
370
|
+
if (isNumericType) {
|
|
371
|
+
// Use z.any() to avoid Zod's built-in type checking, then validate manually
|
|
372
|
+
const numericSchema = z.preprocess(preprocessNumericFn, z.any()).refine((val) => {
|
|
373
|
+
// Allow null for optional fields
|
|
374
|
+
if (!isRequired && val === null) return true
|
|
375
|
+
|
|
376
|
+
// Required check for undefined/null/empty (empty string when required)
|
|
377
|
+
if (val === undefined || (isRequired && val === null)) {
|
|
378
|
+
throw new z.ZodError([{ code: "custom", message: getMessage("required"), path: [] }])
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Numeric validation - check if it's an actual number (not NaN)
|
|
382
|
+
if (typeof val !== "number" || isNaN(val)) {
|
|
383
|
+
throw new z.ZodError([{ code: "custom", message: getMessage("numeric"), path: [] }])
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Length checks on string representation
|
|
387
|
+
const strVal = String(val)
|
|
388
|
+
if (!ID_PATTERNS.numeric.test(strVal)) {
|
|
389
|
+
throw new z.ZodError([{ code: "custom", message: getMessage("numeric"), path: [] }])
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
if (minLength !== undefined && strVal.length < minLength) {
|
|
393
|
+
throw new z.ZodError([{ code: "custom", message: getMessage("minLength", { minLength }), path: [] }])
|
|
394
|
+
}
|
|
395
|
+
if (maxLength !== undefined && strVal.length > maxLength) {
|
|
396
|
+
throw new z.ZodError([{ code: "custom", message: getMessage("maxLength", { maxLength }), path: [] }])
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
return true
|
|
400
|
+
})
|
|
401
|
+
|
|
402
|
+
return numericSchema as unknown as IdSchema<IsRequired, Type>
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// String-based ID validation
|
|
406
|
+
const baseSchema = isRequired ? z.preprocess(preprocessStringFn, z.string()) : z.preprocess(preprocessStringFn, z.string().nullable())
|
|
340
407
|
|
|
341
408
|
const schema = baseSchema
|
|
342
409
|
.refine((val) => {
|
|
@@ -372,12 +439,12 @@ export function id<IsRequired extends boolean = false>(required?: IsRequired, op
|
|
|
372
439
|
|
|
373
440
|
if (allowedTypes && allowedTypes.length > 0) {
|
|
374
441
|
// Check if ID matches any of the allowed types
|
|
375
|
-
isValidId = allowedTypes.some((allowedType) => validateIdType(val, allowedType))
|
|
442
|
+
isValidId = allowedTypes.some((allowedType: IdType) => validateIdType(val, allowedType))
|
|
376
443
|
if (!isValidId) {
|
|
377
444
|
const typeNames = allowedTypes.join(", ")
|
|
378
445
|
throw new z.ZodError([{ code: "custom", message: getMessage("invalid") + ` (allowed types: ${typeNames})`, path: [] }])
|
|
379
446
|
}
|
|
380
|
-
} else if (type !== "auto") {
|
|
447
|
+
} else if (type && type !== "auto") {
|
|
381
448
|
// Validate specific type
|
|
382
449
|
isValidId = validateIdType(val, type)
|
|
383
450
|
if (!isValidId) {
|
|
@@ -390,10 +457,10 @@ export function id<IsRequired extends boolean = false>(required?: IsRequired, op
|
|
|
390
457
|
throw new z.ZodError([{ code: "custom", message: getMessage("invalid"), path: [] }])
|
|
391
458
|
}
|
|
392
459
|
}
|
|
393
|
-
} else if (val !== null && hasContentValidations && type !== "auto" && !customRegex) {
|
|
460
|
+
} else if (val !== null && hasContentValidations && type && type !== "auto" && !customRegex) {
|
|
394
461
|
// Still validate specific types even with content validations (but not auto)
|
|
395
462
|
if (allowedTypes && allowedTypes.length > 0) {
|
|
396
|
-
const isValidType = allowedTypes.some((allowedType) => validateIdType(val, allowedType))
|
|
463
|
+
const isValidType = allowedTypes.some((allowedType: IdType) => validateIdType(val, allowedType))
|
|
397
464
|
if (!isValidType) {
|
|
398
465
|
const typeNames = allowedTypes.join(", ")
|
|
399
466
|
throw new z.ZodError([{ code: "custom", message: getMessage("invalid") + ` (allowed types: ${typeNames})`, path: [] }])
|
|
@@ -444,7 +511,7 @@ export function id<IsRequired extends boolean = false>(required?: IsRequired, op
|
|
|
444
511
|
return val // preserve the original case for UUID/ObjectId or when case-sensitive
|
|
445
512
|
})
|
|
446
513
|
|
|
447
|
-
return schema as unknown as IdSchema<IsRequired>
|
|
514
|
+
return schema as unknown as IdSchema<IsRequired, Type>
|
|
448
515
|
}
|
|
449
516
|
|
|
450
517
|
/**
|
package/tests/common/id.test.ts
CHANGED
|
@@ -135,8 +135,8 @@ describe.each(locales)("id(true) locale: $locale", ({ locale, messages }) => {
|
|
|
135
135
|
})
|
|
136
136
|
|
|
137
137
|
it("should apply transform function", () => {
|
|
138
|
-
const schema = id(true, { type: "
|
|
139
|
-
expect(schema.parse("
|
|
138
|
+
const schema = id(true, { type: "uuid", transform: (val) => val.toUpperCase() })
|
|
139
|
+
expect(schema.parse("550e8400-e29b-41d4-a716-446655440000")).toBe("550E8400-E29B-41D4-A716-446655440000")
|
|
140
140
|
})
|
|
141
141
|
})
|
|
142
142
|
|
|
@@ -162,7 +162,9 @@ describe.each(locales)("id(true) locale: $locale", ({ locale, messages }) => {
|
|
|
162
162
|
it("should accept valid numeric IDs", () => {
|
|
163
163
|
const schema = id(true, { type: "numeric" })
|
|
164
164
|
validIds.numeric.forEach((validId) => {
|
|
165
|
-
|
|
165
|
+
const result = schema.parse(validId)
|
|
166
|
+
expect(typeof result).toBe("number")
|
|
167
|
+
expect(result).toBe(Number(validId))
|
|
166
168
|
})
|
|
167
169
|
})
|
|
168
170
|
|
|
@@ -461,7 +463,8 @@ describe.each(locales)("id(true) locale: $locale", ({ locale, messages }) => {
|
|
|
461
463
|
expect(schema.parse("")).toBe(null)
|
|
462
464
|
expect(() => schema.parse("ab")).toThrow() // not numeric
|
|
463
465
|
expect(() => schema.parse("12")).toThrow() // too short
|
|
464
|
-
expect(schema.parse("12345")).toBe(
|
|
466
|
+
expect(schema.parse("12345")).toBe(12345) // Returns number for numeric type
|
|
467
|
+
expect(typeof schema.parse("12345")).toBe("number")
|
|
465
468
|
})
|
|
466
469
|
|
|
467
470
|
it("should handle multiple allowed types with constraints", () => {
|
|
@@ -499,4 +502,59 @@ describe.each(locales)("id(true) locale: $locale", ({ locale, messages }) => {
|
|
|
499
502
|
expect(ID_PATTERNS.objectId.test("507f1f77bcf86cd799439011")).toBe(true)
|
|
500
503
|
})
|
|
501
504
|
})
|
|
505
|
+
|
|
506
|
+
describe("numeric type returns number", () => {
|
|
507
|
+
it("should return number type when type is numeric and required is true", () => {
|
|
508
|
+
const schema = id(true, { type: "numeric" })
|
|
509
|
+
const result = schema.parse("123")
|
|
510
|
+
expect(result).toBe(123)
|
|
511
|
+
expect(typeof result).toBe("number")
|
|
512
|
+
})
|
|
513
|
+
|
|
514
|
+
it("should return number | null when type is numeric and required is false", () => {
|
|
515
|
+
const schema = id(false, { type: "numeric" })
|
|
516
|
+
const result = schema.parse("456")
|
|
517
|
+
expect(result).toBe(456)
|
|
518
|
+
expect(typeof result).toBe("number")
|
|
519
|
+
|
|
520
|
+
const nullResult = schema.parse(null)
|
|
521
|
+
expect(nullResult).toBe(null)
|
|
522
|
+
|
|
523
|
+
const emptyResult = schema.parse("")
|
|
524
|
+
expect(emptyResult).toBe(null)
|
|
525
|
+
})
|
|
526
|
+
|
|
527
|
+
it("should use numeric default value for numeric type", () => {
|
|
528
|
+
const schema = id(true, { type: "numeric", defaultValue: 999 })
|
|
529
|
+
const result = schema.parse("")
|
|
530
|
+
expect(result).toBe(999)
|
|
531
|
+
expect(typeof result).toBe("number")
|
|
532
|
+
})
|
|
533
|
+
|
|
534
|
+
it("should validate numeric ID constraints", () => {
|
|
535
|
+
const schema = id(true, { type: "numeric", minLength: 3, maxLength: 5 })
|
|
536
|
+
|
|
537
|
+
expect(schema.parse("123")).toBe(123)
|
|
538
|
+
expect(schema.parse("12345")).toBe(12345)
|
|
539
|
+
|
|
540
|
+
// Too short
|
|
541
|
+
expect(() => schema.parse("12")).toThrow()
|
|
542
|
+
|
|
543
|
+
// Too long
|
|
544
|
+
expect(() => schema.parse("123456")).toThrow()
|
|
545
|
+
|
|
546
|
+
// Not numeric
|
|
547
|
+
expect(() => schema.parse("abc")).toThrow()
|
|
548
|
+
})
|
|
549
|
+
|
|
550
|
+
it("should convert string numbers to number type", () => {
|
|
551
|
+
const schema = id(true, { type: "numeric" })
|
|
552
|
+
|
|
553
|
+
expect(schema.parse("0")).toBe(0)
|
|
554
|
+
expect(schema.parse("999999")).toBe(999999)
|
|
555
|
+
expect(schema.parse(123)).toBe(123)
|
|
556
|
+
|
|
557
|
+
expect(typeof schema.parse("123")).toBe("number")
|
|
558
|
+
})
|
|
559
|
+
})
|
|
502
560
|
})
|