@aomex/common-validator 3.30.7 → 3.30.8-alpha.131cf1c.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1564 +1,1623 @@
1
- // src/i18n/index.ts
2
- import { I18n as I18n3 } from "@aomex/internal-tools";
3
-
1
+ import { I18n, createI18n, toArray } from "@aomex/internal-tools";
2
+ import { createHash } from "node:crypto";
3
+ import { DateTime } from "luxon";
4
+ import Decimal from "decimal.js";
5
+ import emailValidator from "email-validator";
6
+ import { isIP, isIPv4, isIPv6 } from "node:net";
7
+ import stream from "node:stream";
8
+ import { URL as URL$1 } from "node:url";
4
9
  // src/i18n/locales/zh-cn.ts
5
- import { I18n } from "@aomex/internal-tools";
6
- var zh = I18n.define({
7
- validator: {
8
- required: "{{label}}\u5FC5\u586B",
9
- array: {
10
- must_be_array: "{{label}}\u5FC5\u987B\u662F\u6570\u7EC4\u7C7B\u578B",
11
- length_not_in_range: "{{label}}\u6570\u7EC4\u957F\u5EA6\u4E0D\u5728\u6307\u5B9A\u8303\u56F4\u5185"
12
- },
13
- boolean: {
14
- must_be_boolean: "{{label}}\u5FC5\u987B\u662F\u5E03\u5C14\u7C7B\u578B"
15
- },
16
- buffer: {
17
- must_be_buffer: "{{label}}\u5FC5\u987B\u662Fbuffer\u7C7B\u578B"
18
- },
19
- stream: {
20
- must_be_stream: "{{label}}\u5FC5\u987B\u662Fstream\u7C7B\u578B"
21
- },
22
- date: {
23
- must_be_date: "{{label}}\u5FC5\u987B\u662F\u65F6\u95F4\u7C7B\u578B",
24
- not_in_range: "{{label}}\u4E0D\u5728\u6307\u5B9A\u65F6\u95F4\u5185"
25
- },
26
- number: {
27
- must_be_number: "{{label}}\u5FC5\u987B\u662F\u6570\u5B57\u7C7B\u578B",
28
- must_be_integer: "{{label}}\u5FC5\u987B\u662F\u6574\u6570",
29
- must_be_bigint: "{{label}}\u5FC5\u987B\u662F\u5927\u6574\u6570\u7C7B\u578B",
30
- not_in_range: "{{label}}\u4E0D\u5728\u6307\u5B9A\u7684\u6570\u5B57\u8303\u56F4"
31
- },
32
- string: {
33
- must_be_string: "{{label}}\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u7C7B\u578B",
34
- must_be_email: "{{label}}\u5FC5\u987B\u662F\u7535\u5B50\u90AE\u4EF6\u683C\u5F0F",
35
- must_be_hash: "{{label}}\u5FC5\u987B\u662F\u54C8\u5E0C\u683C\u5F0F",
36
- must_be_ip: "{{label}}\u5FC5\u987B\u662FIP{{versions}}\u5730\u5740",
37
- must_be_ulid: "{{label}}\u5FC5\u987B\u662FULID\u683C\u5F0F",
38
- must_be_uuid: "{{label}}\u5FC5\u987B\u662FUUID{{versions}}\u683C\u5F0F",
39
- length_not_in_range: "{{label}}\u5B57\u7B26\u4E32\u957F\u5EA6\u4E0D\u5408\u6CD5",
40
- not_match_pattern: "{{label}}\u5B57\u7B26\u4E32\u672A\u5339\u914D\u5230\u89C4\u5219"
41
- },
42
- object: {
43
- must_be_object: "{{label}}\u5FC5\u987B\u662F\u5BF9\u8C61\u7C7B\u578B"
44
- },
45
- enum: {
46
- not_in_range: "{{label}}\u4E0D\u5728\u679A\u4E3E\u8303\u56F4",
47
- only_support_string_number_boolean: "\u679A\u4E3E\u503C\u53EA\u80FD\u662F\u6570\u7EC4\u3001\u5B57\u7B26\u4E32\u548C\u5E03\u5C14\u503C",
48
- can_not_be_empty: '\u679A\u4E3E\u503C\u4E0D\u80FD\u662F\u7A7A\u503C"{{item}}"'
49
- },
50
- one_of: {
51
- not_match_rule: "{{label}}\u672A\u5339\u914D\u89C4\u5219",
52
- match_multiple_rule: "{{label}}\u5339\u914D\u8D85\u8FC71\u4E2A\u89C4\u5219"
53
- },
54
- any_of: {
55
- not_match_rule: "{{label}}\u672A\u5339\u914D\u89C4\u5219"
56
- },
57
- all_of: {
58
- not_match_all: "{{label}}\u672A\u5339\u914D\u6240\u6709\u89C4\u5219"
59
- },
60
- url: {
61
- must_be_url: "{{label}}\u5FC5\u987B\u662FURL\u683C\u5F0F",
62
- unsupported_scheme: "{{label}}\u5305\u542B\u4E0D\u652F\u6301\u7684URL\u534F\u8BAE{{scheme}}"
63
- }
64
- }
65
- });
66
-
10
+ const zh = I18n.define({ validator: {
11
+ required: "{{label}}为必填项",
12
+ array: {
13
+ must_be_array: "{{label}}必须为数组",
14
+ length_not_in_range: "{{label}}数组长度不在指定范围内",
15
+ not_unique: "{{label}}数组元素不能重复"
16
+ },
17
+ boolean: { must_be_boolean: "{{label}}必须为布尔值" },
18
+ buffer: { must_be_buffer: "{{label}}必须为 Buffer" },
19
+ stream: { must_be_stream: "{{label}}必须为 Stream" },
20
+ date: {
21
+ must_be_date: "{{label}}必须为日期",
22
+ not_in_range: "{{label}}不在允许的时间范围内"
23
+ },
24
+ number: {
25
+ must_be_number: "{{label}}必须为数字",
26
+ must_be_integer: "{{label}}必须为整数",
27
+ must_be_bigint: "{{label}}必须为 BigInt",
28
+ must_be_decimal: "{{label}}必须为 Decimal",
29
+ not_in_range: "{{label}}超出允许的数值范围"
30
+ },
31
+ string: {
32
+ must_be_string: "{{label}}必须为字符串",
33
+ must_be_email: "{{label}}必须是电子邮件格式",
34
+ must_be_hash: "{{label}}必须是哈希格式",
35
+ must_be_ip: "{{label}}必须是IP{{versions}}地址",
36
+ must_be_ulid: "{{label}}必须是ULID格式",
37
+ must_be_uuid: "{{label}}必须是UUID{{versions}}格式",
38
+ length_not_in_range: "{{label}}长度不符合要求",
39
+ not_match_pattern: "{{label}}不符合规则"
40
+ },
41
+ object: { must_be_object: "{{label}}必须为对象" },
42
+ enum: {
43
+ not_in_range: "{{label}}不在枚举范围",
44
+ only_support_string_number_boolean: "枚举值只能是字符串、数字和布尔值",
45
+ value_can_not_be_empty: "枚举值不能是空值「{{item}}」",
46
+ ranges_can_not_be_empty: "枚举范围不能为空",
47
+ default_not_in_range: "默认值「{{item}}」不在枚举范围"
48
+ },
49
+ literal: {
50
+ not_match: "{{label}}不是指定的值",
51
+ unsupported_value: "只支持字符串、数字、布尔值和 null"
52
+ },
53
+ one_of: {
54
+ not_match_rule: "{{label}}不符合规则",
55
+ match_multiple_rule: "{{label}}符合了多条规则"
56
+ },
57
+ any_of: { not_match_rule: "{{label}}不符合规则" },
58
+ all_of: { not_match_all: "{{label}}不符合全部规则" },
59
+ url: {
60
+ must_be_url: "{{label}}必须是URL格式",
61
+ unsupported_scheme: "{{label}}包含不支持的 URL 协议:{{scheme}}"
62
+ }
63
+ } });
67
64
  // src/i18n/locales/en-us.ts
68
- import { I18n as I18n2 } from "@aomex/internal-tools";
69
- var en = I18n2.satisfies(zh).define({
70
- validator: {
71
- required: "{{label}} is required",
72
- array: {
73
- must_be_array: "{{label}} must be array",
74
- length_not_in_range: "{{label}} out of array length range"
75
- },
76
- boolean: {
77
- must_be_boolean: "{{label}} must be boolean"
78
- },
79
- buffer: {
80
- must_be_buffer: "{{label}} must be buffer"
81
- },
82
- stream: {
83
- must_be_stream: "{{label}} must be stream"
84
- },
85
- date: {
86
- must_be_date: "{{label}} must be datetime",
87
- not_in_range: "{{label}} is out of datetime range"
88
- },
89
- number: {
90
- must_be_number: "{{label}} must be number",
91
- must_be_integer: "{{label}} must be integer",
92
- must_be_bigint: "{{label}} must be bigint",
93
- not_in_range: "{{label}} is out of number range"
94
- },
95
- string: {
96
- must_be_string: "{{label}} must be string",
97
- must_be_email: "{{label}} must be email",
98
- must_be_hash: "{{label}} must be hash format",
99
- must_be_ip: "{{label}} must be IP{{versions}} address",
100
- must_be_ulid: "{{label}} must be ULID format",
101
- must_be_uuid: "{{label}} must be UUID{{versions}} format",
102
- length_not_in_range: "{{label}} is too long or too short",
103
- not_match_pattern: "{{label}} does not match given pattern"
104
- },
105
- object: {
106
- must_be_object: "{{label}} must be object"
107
- },
108
- enum: {
109
- not_in_range: "{{label}} is not enum value",
110
- only_support_string_number_boolean: "enum values can be only string, number and boolean",
111
- can_not_be_empty: 'enum values can not be empty: "{{item}}"'
112
- },
113
- one_of: {
114
- not_match_rule: "{{label}} does not match rule",
115
- match_multiple_rule: "{{label}} match more than one rule"
116
- },
117
- any_of: {
118
- not_match_rule: "{{label}} does not match rule"
119
- },
120
- all_of: {
121
- not_match_all: "{{label}} does not match all rules"
122
- },
123
- url: {
124
- must_be_url: "{{label}} must be URL format",
125
- unsupported_scheme: "{{label}} contains unsupported URL scheme: {{scheme}}"
126
- }
127
- }
128
- });
129
-
130
- // src/i18n/locales/index.ts
131
- var locales = {
132
- zh_CN: zh,
133
- en_US: en
134
- };
135
-
65
+ const en = I18n.satisfies(zh).define({ validator: {
66
+ required: "{{label}} is required",
67
+ array: {
68
+ must_be_array: "{{label}} must be an array",
69
+ length_not_in_range: "{{label}} out of array length range",
70
+ not_unique: "{{label}} array items must be unique"
71
+ },
72
+ boolean: { must_be_boolean: "{{label}} must be a boolean" },
73
+ buffer: { must_be_buffer: "{{label}} must be a Buffer" },
74
+ stream: { must_be_stream: "{{label}} must be a Stream" },
75
+ date: {
76
+ must_be_date: "{{label}} must be a date",
77
+ not_in_range: "{{label}} is outside the allowed time range"
78
+ },
79
+ number: {
80
+ must_be_number: "{{label}} must be a number",
81
+ must_be_integer: "{{label}} must be an integer",
82
+ must_be_bigint: "{{label}} must be a BigInt",
83
+ must_be_decimal: "{{label}} must be a Decimal",
84
+ not_in_range: "{{label}} is outside the allowed numeric range"
85
+ },
86
+ string: {
87
+ must_be_string: "{{label}} must be a string",
88
+ must_be_email: "{{label}} must be email",
89
+ must_be_hash: "{{label}} must be hash format",
90
+ must_be_ip: "{{label}} must be IP{{versions}} address",
91
+ must_be_ulid: "{{label}} must be ULID format",
92
+ must_be_uuid: "{{label}} must be UUID{{versions}} format",
93
+ length_not_in_range: "{{label}} length does not meet the requirement",
94
+ not_match_pattern: "{{label}} does not conform to the rule"
95
+ },
96
+ object: { must_be_object: "{{label}} must be an object" },
97
+ enum: {
98
+ not_in_range: "{{label}} is not enum value",
99
+ only_support_string_number_boolean: "Enum values can only be strings, numbers, or booleans",
100
+ value_can_not_be_empty: "Enum value cannot be empty: \"{{item}}\"",
101
+ ranges_can_not_be_empty: "enum ranges can not be empty",
102
+ default_not_in_range: "Default value \"{{item}}\" is not in the enum range"
103
+ },
104
+ literal: {
105
+ not_match: "{{label}} is not the specified value",
106
+ unsupported_value: "Only strings, numbers, booleans, and null are supported"
107
+ },
108
+ one_of: {
109
+ not_match_rule: "{{label}} does not conform to the rule",
110
+ match_multiple_rule: "{{label}} matched more than one rule"
111
+ },
112
+ any_of: { not_match_rule: "{{label}} does not conform to the rule" },
113
+ all_of: { not_match_all: "{{label}} does not satisfy all rules" },
114
+ url: {
115
+ must_be_url: "{{label}} must be URL format",
116
+ unsupported_scheme: "{{label}} contains an unsupported URL scheme: {{scheme}}"
117
+ }
118
+ } });
136
119
  // src/i18n/index.ts
137
- var i18n = new I18n3({
138
- resources: locales,
139
- defaultLanguage: "zh_CN"
120
+ const i18n = createI18n({
121
+ zh,
122
+ en,
123
+ load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
140
124
  });
141
-
142
125
  // src/base/validate-result.ts
143
- var ValidateResult = {
144
- accept: (data) => {
145
- return { data };
146
- },
147
- deny: (message) => {
148
- return {
149
- errors: [message]
150
- };
151
- },
152
- noError: (result) => {
153
- return "data" in result;
154
- }
126
+ const ValidateResult = {
127
+ accept: (data) => {
128
+ return { data };
129
+ },
130
+ deny: (message) => {
131
+ return { errors: [message] };
132
+ },
133
+ noError: (result) => {
134
+ return "data" in result;
135
+ }
155
136
  };
156
-
157
137
  // src/base/validator.ts
158
- var Validator = class {
159
- SubClass;
160
- constructor() {
161
- this.SubClass = new.target;
162
- }
163
- config = {
164
- required: true,
165
- nullable: false,
166
- strict: false
167
- };
168
- static toDocument(validator) {
169
- const {
170
- required,
171
- nullable,
172
- docs: { description, deprecated, example, ...schemaProperties } = {},
173
- defaultValue
174
- } = validator.config;
175
- const bothProperties = { description, deprecated, example };
176
- const schema = {
177
- ...schemaProperties,
178
- ...bothProperties,
179
- default: validator.getDefaultValue(defaultValue),
180
- nullable: nullable || void 0,
181
- ...validator.toDocument()
182
- };
183
- const result = {
184
- ...bothProperties,
185
- required: required || void 0,
186
- schema
187
- };
188
- return JSON.parse(JSON.stringify(result));
189
- }
190
- /**
191
- * @param is 是否开启,默认值:`true`
192
- */
193
- strict(is = true) {
194
- const validator = this.copy();
195
- validator.config.strict = is;
196
- return validator;
197
- }
198
- /**
199
- * 扩展openapi的配置
200
- * - **replace:** 本次设置直接覆盖原来的扩展配置
201
- * - **merge:** 本次设置通过`Object.assign`的形式合并到原来的扩展配置
202
- * @param mode 默认值:`merge`
203
- */
204
- docs(docs, mode = "merge") {
205
- const validator = this.copy();
206
- validator.config.docs = mode === "merge" ? { ...validator.config.docs, ...docs } : docs;
207
- return validator;
208
- }
209
- /**
210
- * 值如果是 `undefined, null, ''`或者没传入,以上情况会直接转换成`undefined`
211
- *
212
- * 注意:如果执行了`default(...)`,则无需再执行`optional()`
213
- *
214
- * 注意:如果设置了`nullable()`,则`null`不做处理
215
- */
216
- optional() {
217
- const validator = this.copy();
218
- validator.config.required = false;
219
- return validator;
220
- }
221
- /**
222
- * 把`null`识别成合法的值
223
- * @see optional
224
- */
225
- nullable() {
226
- const validator = this.copy();
227
- validator.config.nullable = true;
228
- return validator;
229
- }
230
- /**
231
- * 数据验证成功最后会触发该方法,你可以把数据转换成任何格式
232
- * ```typescript
233
- * // 最终返回类型:string
234
- * rule.string()
235
- * // 最终返回类型:Array<string>
236
- * rule.string().transform((value) => [value])
237
- * ```
238
- */
239
- transform(fn) {
240
- const validator = this.copy();
241
- validator.config.transform = fn;
242
- return validator;
243
- }
244
- /**
245
- * 如果值为空或者没传入,则使用该默认值,而且无需验证
246
- *
247
- * 注意:如果执行了`default(...)`,则无需再执行`optional()`
248
- */
249
- default(value) {
250
- const validator = this.copy();
251
- validator.config.required = false;
252
- validator.config.defaultValue = value;
253
- return validator;
254
- }
255
- async validate(value, key = "", label = "") {
256
- const { defaultValue, required } = this.config;
257
- if (this.isEmpty(value)) {
258
- value = this.getDefaultValue(defaultValue);
259
- if (this.isEmpty(value)) {
260
- if (!required)
261
- return ValidateResult.accept(
262
- this.config.transform ? await this.config.transform(value) : value
263
- );
264
- return ValidateResult.deny(i18n.t("validator.required", { label }));
265
- }
266
- }
267
- if (this.isValidNull(value)) {
268
- return ValidateResult.accept(
269
- this.config.transform ? await this.config.transform(value) : value
270
- );
271
- }
272
- const result = await this.validateValue(value, key, label);
273
- if (ValidateResult.noError(result) && this.config.transform) {
274
- result.data = await this.config.transform(result.data);
275
- }
276
- return result;
277
- }
278
- isEmpty(value) {
279
- return value === void 0 || !this.config.nullable && value === null || value === "";
280
- }
281
- isValidNull(value) {
282
- return value === null && this.config.nullable;
283
- }
284
- getDefaultValue(value) {
285
- return typeof value === "function" ? value() : value;
286
- }
287
- copy() {
288
- return new this.SubClass().copyConfig(this);
289
- }
290
- copyConfig(prev) {
291
- this.config = { ...prev.config };
292
- return this;
293
- }
294
- toDocument() {
295
- return {};
296
- }
138
+ var Validator = class Validator {
139
+ SubClass;
140
+ constructor() {
141
+ this.SubClass = new.target;
142
+ }
143
+ config = {
144
+ required: true,
145
+ nullable: false,
146
+ strict: false
147
+ };
148
+ /**
149
+ * 判断验证器(含嵌套)中是否包含指定类型
150
+ */
151
+ static has(source, Type) {
152
+ const roots = source instanceof Validator ? [source] : Object.values(source);
153
+ const walk = (validator) => {
154
+ if (validator instanceof Type) return true;
155
+ return validator.nested().some(walk);
156
+ };
157
+ return roots.some(walk);
158
+ }
159
+ /**
160
+ * @param is 是否开启,默认值:`true`
161
+ */
162
+ strict(is = true) {
163
+ const validator = this.copy();
164
+ validator.config.strict = is;
165
+ return validator;
166
+ }
167
+ /**
168
+ * 扩展openapi的配置
169
+ * - **replace:** 本次设置直接覆盖原来的扩展配置
170
+ * - **merge:** 本次设置通过`Object.assign`的形式合并到原来的扩展配置
171
+ * @param mode 默认值:`merge`
172
+ */
173
+ docs(docs, mode = "merge") {
174
+ const validator = this.copy();
175
+ validator.config.docs = mode === "merge" ? {
176
+ ...validator.config.docs,
177
+ ...docs
178
+ } : docs;
179
+ return validator;
180
+ }
181
+ /**
182
+ * 值如果是 `undefined, null, ''`或者没传入,以上情况会直接转换成`undefined`
183
+ *
184
+ * 注意:如果执行了`default(...)`,则无需再执行`optional()`
185
+ *
186
+ * 注意:如果设置了`nullable()`,则`null`不做处理
187
+ */
188
+ optional() {
189
+ const validator = this.copy();
190
+ validator.config.required = false;
191
+ return validator;
192
+ }
193
+ /**
194
+ * 将字段设为必填(`optional()` 的反向)。
195
+ *
196
+ * 若已设置 `default(...)`,则原样返回:缺省仍由默认值补齐,无需也不应清掉 default。
197
+ */
198
+ required() {
199
+ const validator = this.copy();
200
+ if (validator.config.defaultValue !== void 0) return validator;
201
+ validator.config.required = true;
202
+ return validator;
203
+ }
204
+ /**
205
+ * 把`null`识别成合法的值
206
+ * @see optional
207
+ */
208
+ nullable() {
209
+ const validator = this.copy();
210
+ validator.config.nullable = true;
211
+ return validator;
212
+ }
213
+ /**
214
+ * 数据验证成功最后会触发该方法,你可以把数据转换成任何格式
215
+ * ```typescript
216
+ * // 最终返回类型:string
217
+ * rule.string()
218
+ * // 最终返回类型:Array<string>
219
+ * rule.string().transform((value) => [value])
220
+ * ```
221
+ */
222
+ transform(fn) {
223
+ const validator = this.copy();
224
+ validator.config.transform = fn;
225
+ return validator;
226
+ }
227
+ /**
228
+ * 如果值为空或者没传入,则使用该默认值,而且无需验证
229
+ *
230
+ * 注意:如果执行了`default(...)`,则无需再执行`optional()`
231
+ */
232
+ default(value) {
233
+ const validator = this.copy();
234
+ validator.config.required = false;
235
+ validator.config.defaultValue = value;
236
+ return validator;
237
+ }
238
+ async validate(value, key = "", label = "") {
239
+ const { defaultValue, required } = this.config;
240
+ if (this.isEmpty(value)) {
241
+ value = this.getDefaultValue(defaultValue);
242
+ if (this.isEmpty(value)) {
243
+ if (!required) return ValidateResult.accept(this.config.transform ? await this.config.transform(value) : value);
244
+ return ValidateResult.deny(i18n.t("validator.required", { label }));
245
+ }
246
+ }
247
+ if (this.isValidNull(value)) return ValidateResult.accept(this.config.transform ? await this.config.transform(value) : value);
248
+ const result = await this.validateValue(value, key, label);
249
+ if (ValidateResult.noError(result) && this.config.transform) result.data = await this.config.transform(result.data);
250
+ return result;
251
+ }
252
+ isEmpty(value) {
253
+ return value === void 0 || !this.config.nullable && value === null || value === "";
254
+ }
255
+ isValidNull(value) {
256
+ return value === null && this.config.nullable;
257
+ }
258
+ getDefaultValue(value) {
259
+ return typeof value === "function" ? value() : value;
260
+ }
261
+ copy() {
262
+ return new this.SubClass().copyConfig(this);
263
+ }
264
+ copyConfig(prev) {
265
+ this.config = { ...prev.config };
266
+ delete this.config.refName;
267
+ return this;
268
+ }
269
+ /**
270
+ * 直接嵌套的子验证器,供 `Validator.has` 递归探测
271
+ */
272
+ nested() {
273
+ return [];
274
+ }
275
+ toDocument() {
276
+ return {};
277
+ }
297
278
  };
298
-
299
279
  // src/base/base-string.ts
300
280
  var BaseStringValidator = class extends Validator {
301
- /**
302
- * 删除两边空格后再进行验证
303
- */
304
- trim(is = true) {
305
- const validator = this.copy();
306
- validator.config.trim = is;
307
- return validator;
308
- }
309
- length(data) {
310
- const validator = this.copy();
311
- validator.config.lengthRange = typeof data === "number" ? { min: data, max: data } : data;
312
- return validator;
313
- }
314
- match(pattern2) {
315
- const validator = this.copy();
316
- validator.config.pattern = pattern2;
317
- return validator;
318
- }
319
- isEmpty(value) {
320
- if (value !== "" && super.isEmpty(value)) return true;
321
- if (typeof value !== "string") return false;
322
- if (value === "" || this.getTrimValue(value) === "") return true;
323
- return false;
324
- }
325
- getTrimValue(value) {
326
- return this.config.trim ? value.trim() : value;
327
- }
328
- validateValue(value, key, label) {
329
- const { pattern: pattern2, lengthRange } = this.config;
330
- if (typeof value !== "string") {
331
- return ValidateResult.deny(i18n.t("validator.string.must_be_string", { label }));
332
- }
333
- value = this.getTrimValue(value);
334
- if (lengthRange) {
335
- const { min = 0, max = Infinity } = lengthRange;
336
- const length = value.length;
337
- if (length < min || length > max) {
338
- return ValidateResult.deny(
339
- i18n.t("validator.string.length_not_in_range", { label })
340
- );
341
- }
342
- }
343
- if (pattern2 && !pattern2.test(value)) {
344
- return ValidateResult.deny(i18n.t("validator.string.not_match_pattern", { label }));
345
- }
346
- return this.validateString(value, key, label);
347
- }
348
- toDocument() {
349
- const { lengthRange = {}, pattern: pattern2 } = this.config;
350
- return {
351
- type: "string",
352
- // FIXME: openapi没地方放`pattern.flags`
353
- pattern: pattern2 ? pattern2.source : void 0,
354
- minLength: lengthRange.min,
355
- maxLength: lengthRange.max
356
- };
357
- }
281
+ /**
282
+ * 删除两边空格后再进行验证
283
+ */
284
+ trim(is = true) {
285
+ const validator = this.copy();
286
+ validator.config.trim = is;
287
+ return validator;
288
+ }
289
+ length(data) {
290
+ const validator = this.copy();
291
+ validator.config.lengthRange = typeof data === "number" ? {
292
+ min: data,
293
+ max: data
294
+ } : data;
295
+ return validator;
296
+ }
297
+ match(pattern) {
298
+ const validator = this.copy();
299
+ validator.config.pattern = pattern;
300
+ return validator;
301
+ }
302
+ isEmpty(value) {
303
+ if (value !== "" && super.isEmpty(value)) return true;
304
+ if (typeof value !== "string") return false;
305
+ if (value === "" || this.getTrimValue(value) === "") return true;
306
+ return false;
307
+ }
308
+ getTrimValue(value) {
309
+ return this.config.trim ? value.trim() : value;
310
+ }
311
+ validateValue(value, key, label) {
312
+ const { pattern, lengthRange } = this.config;
313
+ if (typeof value !== "string") return ValidateResult.deny(i18n.t("validator.string.must_be_string", { label }));
314
+ value = this.getTrimValue(value);
315
+ if (lengthRange) {
316
+ const { min = 0, max = Infinity } = lengthRange;
317
+ const length = value.length;
318
+ if (length < min || length > max) return ValidateResult.deny(i18n.t("validator.string.length_not_in_range", { label }));
319
+ }
320
+ if (pattern && !pattern.test(value)) return ValidateResult.deny(i18n.t("validator.string.not_match_pattern", { label }));
321
+ return this.validateString(value, key, label);
322
+ }
323
+ toDocument() {
324
+ const { lengthRange = {}, pattern } = this.config;
325
+ return {
326
+ type: "string",
327
+ pattern: pattern ? pattern.source : void 0,
328
+ minLength: lengthRange.min,
329
+ maxLength: lengthRange.max
330
+ };
331
+ }
358
332
  };
359
-
360
333
  // src/base/base-number.ts
361
334
  var BaseNumberValidator = class extends Validator {
362
- /**
363
- * 最小范围限制
364
- * @param min 最小值
365
- * @param inclusive 是否包含最小值,默认值:`true`
366
- */
367
- min(min, inclusive = true) {
368
- const validator = this.copy();
369
- validator.config.min = min;
370
- validator.config.minInclusive = inclusive;
371
- return validator;
372
- }
373
- /**
374
- * 最大范围限制
375
- * @param min 最大值
376
- * @param inclusive 是否包含最大值,默认值:`true`
377
- */
378
- max(max, inclusive = true) {
379
- const validator = this.copy();
380
- validator.config.max = max;
381
- validator.config.maxInclusive = inclusive;
382
- return validator;
383
- }
384
- /**
385
- * 小数点保留位数,使用`.toFixed()`剔除多余的小数
386
- */
387
- precision(decimals) {
388
- const validator = this.copy();
389
- validator.config.precision = decimals;
390
- return validator;
391
- }
392
- validateValue(num, key, label) {
393
- const {
394
- min = -Infinity,
395
- max = Infinity,
396
- minInclusive,
397
- maxInclusive,
398
- strict,
399
- precision
400
- } = this.config;
401
- if (!strict && typeof num === "string") {
402
- num = Number(num);
403
- }
404
- if (!Number.isFinite(num)) {
405
- return ValidateResult.deny(i18n.t("validator.number.must_be_number", { label }));
406
- }
407
- if (precision !== void 0) {
408
- num = Number(num.toFixed(precision));
409
- }
410
- if ((minInclusive ? num < min : num <= min) || (maxInclusive ? num > max : num >= max)) {
411
- return ValidateResult.deny(i18n.t("validator.number.not_in_range", { label }));
412
- }
413
- return this.validateNumber(num, key, label);
414
- }
415
- toDocument() {
416
- const { max, maxInclusive, min, minInclusive } = this.config;
417
- return {
418
- type: "number",
419
- maximum: max,
420
- minimum: min,
421
- exclusiveMaximum: maxInclusive === void 0 ? void 0 : !maxInclusive,
422
- exclusiveMinimum: minInclusive === void 0 ? void 0 : !minInclusive
423
- };
424
- }
335
+ /**
336
+ * 最小范围限制
337
+ * @param min 最小值
338
+ * @param inclusive 是否包含最小值,默认值:`true`
339
+ */
340
+ min(min, inclusive = true) {
341
+ const validator = this.copy();
342
+ validator.config.min = min;
343
+ validator.config.minInclusive = inclusive;
344
+ return validator;
345
+ }
346
+ /**
347
+ * 最大范围限制
348
+ * @param min 最大值
349
+ * @param inclusive 是否包含最大值,默认值:`true`
350
+ */
351
+ max(max, inclusive = true) {
352
+ const validator = this.copy();
353
+ validator.config.max = max;
354
+ validator.config.maxInclusive = inclusive;
355
+ return validator;
356
+ }
357
+ /**
358
+ * 小数点保留位数,使用`.toFixed()`剔除多余的小数
359
+ */
360
+ precision(decimals) {
361
+ const validator = this.copy();
362
+ validator.config.precision = decimals;
363
+ return validator;
364
+ }
365
+ validateValue(num, key, label) {
366
+ const { min = -Infinity, max = Infinity, minInclusive, maxInclusive, strict, precision } = this.config;
367
+ if (!strict && typeof num === "string") num = Number(num);
368
+ if (!Number.isFinite(num)) return ValidateResult.deny(i18n.t("validator.number.must_be_number", { label }));
369
+ if (precision !== void 0) num = Number(num.toFixed(precision));
370
+ if ((minInclusive ? num < min : num <= min) || (maxInclusive ? num > max : num >= max)) return ValidateResult.deny(i18n.t("validator.number.not_in_range", { label }));
371
+ return this.validateNumber(num, key, label);
372
+ }
373
+ toDocument() {
374
+ const { max, maxInclusive, min, minInclusive } = this.config;
375
+ return {
376
+ type: "number",
377
+ maximum: max,
378
+ minimum: min,
379
+ exclusiveMaximum: maxInclusive === void 0 ? void 0 : !maxInclusive,
380
+ exclusiveMinimum: minInclusive === void 0 ? void 0 : !minInclusive
381
+ };
382
+ }
425
383
  };
426
-
427
384
  // src/base/validate-denied-error.ts
428
385
  var ValidateDeniedError = class extends Error {
429
- constructor(message, errors = []) {
430
- super(message);
431
- this.errors = errors;
432
- }
433
- getValidateErrors() {
434
- return this.errors;
435
- }
386
+ errors;
387
+ constructor(message, errors = []) {
388
+ super(message);
389
+ this.errors = errors;
390
+ }
391
+ getValidateErrors() {
392
+ return this.errors;
393
+ }
436
394
  };
437
-
395
+ // src/base/validator-schema.ts
396
+ function normalizeKeys(keys) {
397
+ if (keys.length === 1 && Array.isArray(keys[0])) return [...keys[0]];
398
+ return keys;
399
+ }
400
+ var ValidatorSchema = class ValidatorSchema {
401
+ rules;
402
+ name;
403
+ constructor(rules, name) {
404
+ this.rules = rules;
405
+ this.name = name;
406
+ }
407
+ /**
408
+ * 为 schema 指定 OpenAPI 文档中的具名组件名,字段定义不变。
409
+ * 生成文档时会按该名称引用;未指定则不单独抽成组件。
410
+ * 名称不会传到 `pick` / `omit` 等派生结果;经 `rule.object(schema)` / `toValidator` 转换后写入 `refName`。
411
+ *
412
+ * ```typescript
413
+ * const userSchema = schema({ id: rule.int(), name: rule.string() }).asName('User');
414
+ * ```
415
+ */
416
+ asName(name) {
417
+ return new ValidatorSchema(this.rules, name);
418
+ }
419
+ pick(...keys) {
420
+ const next = {};
421
+ for (const key of normalizeKeys(keys)) {
422
+ const validator = this.rules[key];
423
+ if (validator) next[key] = validator;
424
+ }
425
+ return new ValidatorSchema(next);
426
+ }
427
+ omit(...keys) {
428
+ const excluded = new Set(normalizeKeys(keys));
429
+ const next = {};
430
+ for (const key of Object.keys(this.rules)) {
431
+ if (excluded.has(key)) continue;
432
+ const validator = this.rules[key];
433
+ if (validator) next[key] = validator;
434
+ }
435
+ return new ValidatorSchema(next);
436
+ }
437
+ extend(fieldsOrSchema) {
438
+ const fields = fieldsOrSchema instanceof ValidatorSchema ? fieldsOrSchema["rules"] : normalizeFieldTable(fieldsOrSchema);
439
+ return new ValidatorSchema({
440
+ ...this.rules,
441
+ ...fields
442
+ });
443
+ }
444
+ partial(...keys) {
445
+ return this.mapSelected(keys, (v) => v["optional"]());
446
+ }
447
+ required(...keys) {
448
+ return this.mapSelected(keys, (v) => v["required"]());
449
+ }
450
+ /**
451
+ * 无参(rest 长度为 0)表示全部字段。
452
+ * 必须在 normalizeKeys 之前判断:`fn([])` 的 rest 长度是 1,解包后才变成空数组。
453
+ */
454
+ mapSelected(keys, map) {
455
+ const targets = keys.length === 0 ? Object.keys(this.rules) : normalizeKeys(keys);
456
+ const next = { ...this.rules };
457
+ for (const key of targets) {
458
+ const validator = this.rules[key];
459
+ if (validator) next[key] = map(validator);
460
+ }
461
+ return new ValidatorSchema(next);
462
+ }
463
+ };
464
+ // src/api/to-document.ts
465
+ function toDocument(source) {
466
+ const validator = toValidator(source);
467
+ const { required, nullable, docs: { description, deprecated, example, ...schemaProperties } = {}, defaultValue, refName } = validator["config"];
468
+ const bothProperties = {
469
+ description,
470
+ deprecated,
471
+ example
472
+ };
473
+ const schema = {
474
+ ...schemaProperties,
475
+ ...bothProperties,
476
+ default: validator["getDefaultValue"](defaultValue),
477
+ nullable: nullable || void 0,
478
+ ...validator["toDocument"]()
479
+ };
480
+ if (schema.type === "object" && refName !== void 0) {
481
+ const cleaned = JSON.parse(JSON.stringify(schema));
482
+ Object.assign(schema, { "x-ref": encodeURIComponent(refName === true ? createHash("md5").update(JSON.stringify(cleaned)).digest("hex") : refName) });
483
+ }
484
+ return JSON.parse(JSON.stringify({
485
+ ...bothProperties,
486
+ required: required || void 0,
487
+ schema
488
+ }));
489
+ }
438
490
  // src/validators/all-of.ts
439
491
  var AllOfValidator = class extends Validator {
440
- constructor(validators) {
441
- super();
442
- this.config.validators = validators;
443
- }
444
- isEmpty(_) {
445
- return false;
446
- }
447
- async validateValue(value, key, label) {
448
- const { validators } = this.config;
449
- for (let i = 0; i < validators.length; ++i) {
450
- const validator = validators[i];
451
- const result = await validator.validate(value, key, label);
452
- if (ValidateResult.noError(result)) {
453
- value = result.data;
454
- } else {
455
- return ValidateResult.deny(i18n.t("validator.all_of.not_match_all", { label }));
456
- }
457
- }
458
- return ValidateResult.accept(value);
459
- }
460
- copyConfig(prev) {
461
- super.copyConfig(prev);
462
- this.config.validators = [...prev.config.validators];
463
- return this;
464
- }
465
- toDocument() {
466
- const { validators } = this.config;
467
- return {
468
- allOf: validators.map((validator) => Validator.toDocument(validator).schema)
469
- };
470
- }
492
+ constructor(validators) {
493
+ super();
494
+ this.config.validators = validators;
495
+ }
496
+ isEmpty(_) {
497
+ return false;
498
+ }
499
+ async validateValue(value, key, label) {
500
+ const { validators } = this.config;
501
+ for (let i = 0; i < validators.length; ++i) {
502
+ const result = await validators[i].validate(value, key, label);
503
+ if (ValidateResult.noError(result)) value = result.data;
504
+ else return ValidateResult.deny(i18n.t("validator.all_of.not_match_all", { label }));
505
+ }
506
+ return ValidateResult.accept(value);
507
+ }
508
+ copyConfig(prev) {
509
+ super.copyConfig(prev);
510
+ this.config.validators = [...prev.config.validators];
511
+ return this;
512
+ }
513
+ nested() {
514
+ return this.config.validators;
515
+ }
516
+ toDocument() {
517
+ const { validators } = this.config;
518
+ return { allOf: validators.map((validator) => toDocument(validator).schema) };
519
+ }
471
520
  };
472
-
473
521
  // src/validators/any.ts
474
522
  var AnyValidator = class extends Validator {
475
- validateValue(value) {
476
- return ValidateResult.accept(value);
477
- }
478
- toDocument() {
479
- return {
480
- anyOf: [
481
- { type: "array", items: {} },
482
- { type: "boolean" },
483
- { type: "integer" },
484
- { type: "number" },
485
- { type: "object" },
486
- { type: "string" }
487
- ]
488
- };
489
- }
523
+ validateValue(value) {
524
+ return ValidateResult.accept(value);
525
+ }
526
+ toDocument() {
527
+ return { anyOf: [
528
+ {
529
+ type: "array",
530
+ items: {}
531
+ },
532
+ { type: "boolean" },
533
+ { type: "integer" },
534
+ { type: "number" },
535
+ { type: "object" },
536
+ { type: "string" }
537
+ ] };
538
+ }
490
539
  };
491
-
492
540
  // src/validators/any-of.ts
493
541
  var AnyOfValidator = class extends Validator {
494
- constructor(validators) {
495
- super();
496
- this.config.validators = validators;
497
- }
498
- isEmpty(_) {
499
- return false;
500
- }
501
- async validateValue(value, key, label) {
502
- const { validators } = this.config;
503
- let matched = false;
504
- for (let i = 0; i < validators.length; ++i) {
505
- const validator = validators[i];
506
- const result = await validator.validate(value, key, label);
507
- if (ValidateResult.noError(result)) {
508
- value = result.data;
509
- matched = true;
510
- }
511
- }
512
- return matched ? ValidateResult.accept(value) : ValidateResult.deny(i18n.t("validator.any_of.not_match_rule", { label }));
513
- }
514
- copyConfig(prev) {
515
- super.copyConfig(prev);
516
- this.config.validators = [...prev.config.validators];
517
- return this;
518
- }
519
- toDocument() {
520
- const { validators } = this.config;
521
- return {
522
- anyOf: validators.map((validator) => Validator.toDocument(validator).schema)
523
- };
524
- }
542
+ constructor(validators) {
543
+ super();
544
+ this.config.validators = validators;
545
+ }
546
+ isEmpty(_) {
547
+ return false;
548
+ }
549
+ async validateValue(value, key, label) {
550
+ const { validators } = this.config;
551
+ let matched = false;
552
+ for (let i = 0; i < validators.length; ++i) {
553
+ const result = await validators[i].validate(value, key, label);
554
+ if (ValidateResult.noError(result)) {
555
+ value = result.data;
556
+ matched = true;
557
+ }
558
+ }
559
+ return matched ? ValidateResult.accept(value) : ValidateResult.deny(i18n.t("validator.any_of.not_match_rule", { label }));
560
+ }
561
+ copyConfig(prev) {
562
+ super.copyConfig(prev);
563
+ this.config.validators = [...prev.config.validators];
564
+ return this;
565
+ }
566
+ nested() {
567
+ return this.config.validators;
568
+ }
569
+ toDocument() {
570
+ const { validators } = this.config;
571
+ return { anyOf: validators.map((validator) => toDocument(validator).schema) };
572
+ }
525
573
  };
526
-
527
574
  // src/validators/array.ts
528
575
  var ArrayValidator = class extends Validator {
529
- constructor(validator) {
530
- super();
531
- this.config.itemValidator = validator;
532
- this.config.lengthRange = {};
533
- }
534
- forceToArray(mode, separator) {
535
- const validator = this.copy();
536
- validator.config.force = { mode, separator };
537
- return validator;
538
- }
539
- length(data) {
540
- const validator = this.copy();
541
- validator.config.lengthRange = typeof data === "number" ? { min: data, max: data } : data;
542
- return validator;
543
- }
544
- async validateValue(value, key, label) {
545
- const {
546
- force,
547
- lengthRange: { min = 0, max = Infinity },
548
- itemValidator
549
- } = this.config;
550
- let items;
551
- if (Array.isArray(value)) {
552
- items = value.slice();
553
- } else if (force) {
554
- const { mode, separator = /\s*,\s*/ } = force;
555
- switch (mode) {
556
- case "block":
557
- items = [value];
558
- break;
559
- case "separator":
560
- if (typeof value === "string") {
561
- items = value.split(separator);
562
- }
563
- break;
564
- }
565
- }
566
- if (!Array.isArray(items)) {
567
- return ValidateResult.deny(i18n.t("validator.array.must_be_array", { label }));
568
- }
569
- const length = items.length;
570
- if (length < min || length > max) {
571
- return ValidateResult.deny(
572
- i18n.t("validator.array.length_not_in_range", { label })
573
- );
574
- }
575
- if (itemValidator) {
576
- let error = {
577
- errors: []
578
- };
579
- await Promise.all(
580
- items.map(async (_, index, arr) => {
581
- const result = await itemValidator["validate"](
582
- arr[index],
583
- index.toString(),
584
- label && key ? `${label}.${index}` : index.toString()
585
- );
586
- if (ValidateResult.noError(result)) {
587
- arr[index] = result.data;
588
- } else {
589
- error.errors = error.errors.concat(result.errors);
590
- }
591
- })
592
- );
593
- if (error.errors.length) return error;
594
- }
595
- return ValidateResult.accept(items);
596
- }
597
- toDocument() {
598
- const { itemValidator, lengthRange } = this.config;
599
- return {
600
- type: "array",
601
- items: itemValidator && Validator.toDocument(itemValidator).schema || {},
602
- minItems: lengthRange.min,
603
- maxItems: lengthRange.max
604
- };
605
- }
576
+ constructor(validator) {
577
+ super();
578
+ this.config.itemValidator = validator;
579
+ this.config.lengthRange = {};
580
+ }
581
+ forceToArray(mode, separator) {
582
+ const validator = this.copy();
583
+ validator.config.force = {
584
+ mode,
585
+ separator
586
+ };
587
+ return validator;
588
+ }
589
+ length(data) {
590
+ const validator = this.copy();
591
+ validator.config.lengthRange = typeof data === "number" ? {
592
+ min: data,
593
+ max: data
594
+ } : data;
595
+ return validator;
596
+ }
597
+ unique(by) {
598
+ const validator = this.copy();
599
+ if (arguments.length === 0) validator.config.uniqueBy = true;
600
+ else if (typeof by === "string") {
601
+ const key = by;
602
+ validator.config.uniqueBy = (item) => item?.[key];
603
+ } else validator.config.uniqueBy = by;
604
+ return validator;
605
+ }
606
+ async validateValue(value, key, label) {
607
+ const { force, lengthRange: { min = 0, max = Infinity }, itemValidator, uniqueBy } = this.config;
608
+ let items;
609
+ if (Array.isArray(value)) items = value.slice();
610
+ else if (force) {
611
+ const { mode, separator = /\s*,\s*/ } = force;
612
+ switch (mode) {
613
+ case "block":
614
+ items = [value];
615
+ break;
616
+ case "separator": if (typeof value === "string") items = value.split(separator);
617
+ }
618
+ }
619
+ if (!Array.isArray(items)) return ValidateResult.deny(i18n.t("validator.array.must_be_array", { label }));
620
+ const length = items.length;
621
+ if (length < min || length > max) return ValidateResult.deny(i18n.t("validator.array.length_not_in_range", { label }));
622
+ if (itemValidator) {
623
+ let error = { errors: [] };
624
+ await Promise.all(items.map(async (_, index, arr) => {
625
+ const result = await itemValidator["validate"](arr[index], index.toString(), label && key ? `${label}.${index}` : index.toString());
626
+ if (ValidateResult.noError(result)) arr[index] = result.data;
627
+ else error.errors = error.errors.concat(result.errors);
628
+ }));
629
+ if (error.errors.length) return error;
630
+ }
631
+ if (uniqueBy) {
632
+ const seen = /* @__PURE__ */ new Set();
633
+ const pick = uniqueBy === true ? (item) => item : uniqueBy;
634
+ for (const item of items) {
635
+ const fingerprint = pick(item);
636
+ if (seen.has(fingerprint)) return ValidateResult.deny(i18n.t("validator.array.not_unique", { label }));
637
+ seen.add(fingerprint);
638
+ }
639
+ }
640
+ return ValidateResult.accept(items);
641
+ }
642
+ nested() {
643
+ const { itemValidator } = this.config;
644
+ return itemValidator ? [itemValidator] : [];
645
+ }
646
+ toDocument() {
647
+ const { itemValidator, lengthRange, uniqueBy } = this.config;
648
+ return {
649
+ type: "array",
650
+ items: itemValidator && toDocument(itemValidator).schema || {},
651
+ minItems: lengthRange.min,
652
+ maxItems: lengthRange.max,
653
+ uniqueItems: uniqueBy === true || void 0
654
+ };
655
+ }
606
656
  };
607
-
608
657
  // src/validators/bigInt.ts
609
658
  var BigIntValidator = class extends Validator {
610
- min(min, inclusive = true) {
611
- const validator = this.copy();
612
- validator.config.min = min;
613
- validator.config.minInclusive = inclusive;
614
- return validator;
615
- }
616
- max(max, inclusive = true) {
617
- const validator = this.copy();
618
- validator.config.max = max;
619
- validator.config.maxInclusive = inclusive;
620
- return validator;
621
- }
622
- validateValue(value, _key, label) {
623
- const {
624
- strict,
625
- min = -Infinity,
626
- max = Infinity,
627
- minInclusive,
628
- maxInclusive
629
- } = this.config;
630
- const type = typeof value;
631
- let num;
632
- if (type !== "bigint") {
633
- if (!strict && (type === "number" || type === "string")) {
634
- try {
635
- num = BigInt(value);
636
- } catch {
637
- }
638
- }
639
- if (num === void 0) {
640
- return ValidateResult.deny(i18n.t("validator.number.must_be_bigint", { label }));
641
- }
642
- } else {
643
- num = value;
644
- }
645
- if ((minInclusive ? num < min : num <= min) || (maxInclusive ? num > max : num >= max)) {
646
- return ValidateResult.deny(i18n.t("validator.number.not_in_range", { label }));
647
- }
648
- return ValidateResult.accept(num);
649
- }
650
- toDocument() {
651
- const { min, max, minInclusive, maxInclusive } = this.config;
652
- const defaultValue = this.getDefaultValue(this.config.defaultValue);
653
- return {
654
- type: "integer",
655
- format: "int64",
656
- example: "922337203685475807",
657
- // JSON.stringify 无法处理bigint类型
658
- default: defaultValue === void 0 ? void 0 : Number(defaultValue),
659
- minimum: min === void 0 ? void 0 : Number(min),
660
- maximum: max === void 0 ? void 0 : Number(max),
661
- exclusiveMinimum: minInclusive === void 0 ? void 0 : !minInclusive,
662
- exclusiveMaximum: maxInclusive === void 0 ? void 0 : !maxInclusive
663
- };
664
- }
659
+ min(min, inclusive = true) {
660
+ const validator = this.copy();
661
+ validator.config.min = min;
662
+ validator.config.minInclusive = inclusive;
663
+ return validator;
664
+ }
665
+ max(max, inclusive = true) {
666
+ const validator = this.copy();
667
+ validator.config.max = max;
668
+ validator.config.maxInclusive = inclusive;
669
+ return validator;
670
+ }
671
+ validateValue(value, _key, label) {
672
+ const { strict, min = -Infinity, max = Infinity, minInclusive, maxInclusive } = this.config;
673
+ const type = typeof value;
674
+ let num;
675
+ if (type !== "bigint") {
676
+ if (!strict && (type === "number" || type === "string")) try {
677
+ num = BigInt(value);
678
+ } catch {}
679
+ if (num === void 0) return ValidateResult.deny(i18n.t("validator.number.must_be_bigint", { label }));
680
+ } else num = value;
681
+ if ((minInclusive ? num < min : num <= min) || (maxInclusive ? num > max : num >= max)) return ValidateResult.deny(i18n.t("validator.number.not_in_range", { label }));
682
+ return ValidateResult.accept(num);
683
+ }
684
+ toDocument() {
685
+ const { min, max, minInclusive, maxInclusive } = this.config;
686
+ const defaultValue = this.getDefaultValue(this.config.defaultValue);
687
+ return {
688
+ type: "integer",
689
+ format: "int64",
690
+ example: "922337203685475807",
691
+ default: defaultValue === void 0 ? void 0 : Number(defaultValue),
692
+ minimum: min === void 0 ? void 0 : Number(min),
693
+ maximum: max === void 0 ? void 0 : Number(max),
694
+ exclusiveMinimum: minInclusive === void 0 ? void 0 : !minInclusive,
695
+ exclusiveMaximum: maxInclusive === void 0 ? void 0 : !maxInclusive
696
+ };
697
+ }
665
698
  };
666
-
667
699
  // src/validators/boolean.ts
668
- var BooleanValidator = class _BooleanValidator extends Validator {
669
- static defaultTruthyValues = [1, "1", true, "true"];
670
- static defaultFalsyValues = [0, "0", false, "false"];
671
- /**
672
- * 重新设置真值。默认值:`[1, '1', true, 'true']`
673
- * ```typescript
674
- * boolean.setTruthyValues([true, 'yes']);
675
- * boolean.setTruthyValues(['on', 'good']);
676
- * ```
677
- */
678
- setTruthyValues(values) {
679
- const validator = this.copy();
680
- validator.config.truthyValues = values;
681
- return validator;
682
- }
683
- /**
684
- * 重新设置假值。默认值:`[0, '0', false, 'false']`
685
- * ```typescript
686
- * boolean.setFalsyValues([false, 'no']);
687
- * boolean.setFalsyValues(['off', 'bad']);
688
- * ```
689
- */
690
- setFalsyValues(values) {
691
- const validator = this.copy();
692
- validator.config.falsyValues = values;
693
- return validator;
694
- }
695
- validateValue(value, _key, label) {
696
- const {
697
- truthyValues: trueValues = _BooleanValidator.defaultTruthyValues,
698
- falsyValues: falseValues = _BooleanValidator.defaultFalsyValues
699
- } = this.config;
700
- if (trueValues.includes(value)) {
701
- return ValidateResult.accept(true);
702
- }
703
- if (falseValues.includes(value)) {
704
- return ValidateResult.accept(false);
705
- }
706
- return ValidateResult.deny(i18n.t("validator.boolean.must_be_boolean", { label }));
707
- }
708
- toDocument() {
709
- return {
710
- type: "boolean"
711
- };
712
- }
700
+ var BooleanValidator = class BooleanValidator extends Validator {
701
+ static defaultTruthyValues = [
702
+ 1,
703
+ "1",
704
+ true,
705
+ "true"
706
+ ];
707
+ static defaultFalsyValues = [
708
+ 0,
709
+ "0",
710
+ false,
711
+ "false"
712
+ ];
713
+ /**
714
+ * 重新设置真值。默认值:`[1, '1', true, 'true']`
715
+ * ```typescript
716
+ * boolean.setTruthyValues([true, 'yes']);
717
+ * boolean.setTruthyValues(['on', 'good']);
718
+ * ```
719
+ */
720
+ setTruthyValues(values) {
721
+ const validator = this.copy();
722
+ validator.config.truthyValues = values;
723
+ return validator;
724
+ }
725
+ /**
726
+ * 重新设置假值。默认值:`[0, '0', false, 'false']`
727
+ * ```typescript
728
+ * boolean.setFalsyValues([false, 'no']);
729
+ * boolean.setFalsyValues(['off', 'bad']);
730
+ * ```
731
+ */
732
+ setFalsyValues(values) {
733
+ const validator = this.copy();
734
+ validator.config.falsyValues = values;
735
+ return validator;
736
+ }
737
+ validateValue(value, _key, label) {
738
+ const { truthyValues: trueValues = BooleanValidator.defaultTruthyValues, falsyValues: falseValues = BooleanValidator.defaultFalsyValues } = this.config;
739
+ if (trueValues.includes(value)) return ValidateResult.accept(true);
740
+ if (falseValues.includes(value)) return ValidateResult.accept(false);
741
+ return ValidateResult.deny(i18n.t("validator.boolean.must_be_boolean", { label }));
742
+ }
743
+ toDocument() {
744
+ return { type: "boolean" };
745
+ }
713
746
  };
714
-
715
747
  // src/validators/buffer.ts
716
- var hexReg = /^(?:0x)?[0-9a-f]+$/i;
717
- var base64Reg = /^([a-z0-9+/]{4})*([a-z0-9+/]{3}=|[a-z0-9+/]{2}==)?$/i;
748
+ const hexReg = /^(?:0x)?[0-9a-f]+$/i;
749
+ const base64Reg = /^([a-z0-9+/]{4})*([a-z0-9+/]{3}=|[a-z0-9+/]{2}==)?$/i;
718
750
  var BufferValidator = class extends Validator {
719
- /**
720
- * 尝试从其他类型恢复为buffer类型:
721
- *
722
- * - `hex` 从十六进制字符串恢复
723
- * - `base64` 从base64字符串恢复
724
- */
725
- parseFrom(...encodings) {
726
- const validator = this.copy();
727
- validator.config.fromEncodings = [...new Set(encodings)];
728
- return validator;
729
- }
730
- validateValue(value, _key, label) {
731
- const { fromEncodings = [] } = this.config;
732
- let buffer;
733
- if (!Buffer.isBuffer(value)) {
734
- loop: for (const encoding of fromEncodings) {
735
- switch (encoding) {
736
- case "hex":
737
- if (typeof value === "string" && hexReg.test(value)) {
738
- try {
739
- buffer = Buffer.from(value.replace(/^0x/i, ""), "hex");
740
- break loop;
741
- } catch {
742
- }
743
- }
744
- break;
745
- case "base64":
746
- if (typeof value === "string" && base64Reg.test(value)) {
747
- try {
748
- buffer = Buffer.from(value, "base64");
749
- break loop;
750
- } catch {
751
- }
752
- }
753
- }
754
- }
755
- } else {
756
- buffer = value;
757
- }
758
- if (!buffer) {
759
- return ValidateResult.deny(i18n.t("validator.buffer.must_be_buffer", { label }));
760
- }
761
- return ValidateResult.accept(buffer);
762
- }
763
- toDocument() {
764
- const defaultValue = this.getDefaultValue(
765
- this.config.defaultValue
766
- );
767
- return {
768
- type: "string",
769
- format: "byte",
770
- // JSON 无法处理buffer类型
771
- default: defaultValue && defaultValue.toString("base64")
772
- };
773
- }
751
+ /**
752
+ * 尝试从其他类型恢复为buffer类型:
753
+ *
754
+ * - `hex` 从十六进制字符串恢复
755
+ * - `base64` 从base64字符串恢复
756
+ */
757
+ parseFrom(...encodings) {
758
+ const validator = this.copy();
759
+ validator.config.fromEncodings = [...new Set(encodings)];
760
+ return validator;
761
+ }
762
+ validateValue(value, _key, label) {
763
+ const { fromEncodings = [] } = this.config;
764
+ let buffer;
765
+ if (!Buffer.isBuffer(value)) loop: for (const encoding of fromEncodings) switch (encoding) {
766
+ case "hex":
767
+ if (typeof value === "string" && hexReg.test(value)) try {
768
+ buffer = Buffer.from(value.replace(/^0x/i, ""), "hex");
769
+ break loop;
770
+ } catch {}
771
+ break;
772
+ case "base64": if (typeof value === "string" && base64Reg.test(value)) try {
773
+ buffer = Buffer.from(value, "base64");
774
+ break loop;
775
+ } catch {}
776
+ }
777
+ else buffer = value;
778
+ if (!buffer) return ValidateResult.deny(i18n.t("validator.buffer.must_be_buffer", { label }));
779
+ return ValidateResult.accept(buffer);
780
+ }
781
+ toDocument() {
782
+ const defaultValue = this.getDefaultValue(this.config.defaultValue);
783
+ return {
784
+ type: "string",
785
+ format: "byte",
786
+ default: defaultValue && defaultValue.toString("base64")
787
+ };
788
+ }
774
789
  };
775
-
776
790
  // src/validators/date.ts
777
- import { DateTime } from "luxon";
778
- var regTimestamp = /^[0-9.]+$/;
779
- var regUnixTimeWithMS = /^[0-9]{10}\.[0-9]{3}$/;
791
+ const regTimestamp = /^[0-9.]+$/;
792
+ const regUnixTimeWithMS = /^[0-9]{10}\.[0-9]{3}$/;
780
793
  var DateValidator = class extends Validator {
781
- constructor(formats) {
782
- super();
783
- this.config.formats = formats;
784
- }
785
- min(freshDate, inclusive = true) {
786
- const validator = this.copy();
787
- validator.config.min = freshDate;
788
- validator.config.minInclusive = inclusive;
789
- return validator;
790
- }
791
- max(freshDate, inclusive = true) {
792
- const validator = this.copy();
793
- validator.config.max = freshDate;
794
- validator.config.maxInclusive = inclusive;
795
- return validator;
796
- }
797
- /**
798
- * 尝试把时间戳数字解析成时间对象。默认已开启
799
- *
800
- * 支持如下格式:
801
- * - 13位:1711257956199
802
- * - 14位:1711257956.199
803
- * - 10位:1711257956
804
- */
805
- parseFromTimestamp(is = true) {
806
- const validator = this.copy();
807
- validator.config.parseFromTimestamp = is;
808
- return validator;
809
- }
810
- validateValue(value, _key, label) {
811
- const date = this.toDate(value);
812
- if (date === false || date.toString() === "Invalid Date") {
813
- return ValidateResult.deny(i18n.t("validator.date.must_be_date", { label }));
814
- }
815
- if (!this.compare(date)) {
816
- return ValidateResult.deny(i18n.t("validator.date.not_in_range", { label }));
817
- }
818
- return ValidateResult.accept(date);
819
- }
820
- toDate(value) {
821
- const { parseFromTimestamp = true, formats } = this.config;
822
- if (value instanceof Date) return value;
823
- if (parseFromTimestamp && (typeof value === "number" || typeof value === "string" && regTimestamp.test(value))) {
824
- const timestamp = value.toString();
825
- if (timestamp.length === 10)
826
- return DateTime.fromSeconds(Number(timestamp)).toJSDate();
827
- if (timestamp.length === 13)
828
- return DateTime.fromMillis(Number(timestamp)).toJSDate();
829
- if (timestamp.length === 14 && regUnixTimeWithMS.test(timestamp)) {
830
- return DateTime.fromSeconds(Number(timestamp)).toJSDate();
831
- }
832
- }
833
- if (typeof value === "string") {
834
- if (formats && formats.length) {
835
- for (const format of formats) {
836
- const date = DateTime.fromFormat(value, format, { setZone: true });
837
- if (date.isValid) return date.toJSDate();
838
- }
839
- } else {
840
- return DateTime.fromISO(value).toJSDate();
841
- }
842
- }
843
- return false;
844
- }
845
- compare(date) {
846
- const { min, minInclusive, max, maxInclusive } = this.config;
847
- const timestamp = +date;
848
- if (min !== void 0 && (minInclusive ? timestamp < +min() : timestamp <= +min())) {
849
- return false;
850
- }
851
- if (max !== void 0 && (maxInclusive ? timestamp > +max() : timestamp >= +max())) {
852
- return false;
853
- }
854
- return true;
855
- }
856
- toDocument() {
857
- const defaultValue = this.getDefaultValue(this.config.defaultValue);
858
- return {
859
- type: "string",
860
- format: "date-time",
861
- default: defaultValue?.toISOString()
862
- };
863
- }
794
+ constructor(formats) {
795
+ super();
796
+ this.config.formats = formats;
797
+ }
798
+ min(freshDate, inclusive = true) {
799
+ const validator = this.copy();
800
+ validator.config.min = freshDate;
801
+ validator.config.minInclusive = inclusive;
802
+ return validator;
803
+ }
804
+ max(freshDate, inclusive = true) {
805
+ const validator = this.copy();
806
+ validator.config.max = freshDate;
807
+ validator.config.maxInclusive = inclusive;
808
+ return validator;
809
+ }
810
+ /**
811
+ * 尝试把时间戳数字解析成时间对象。默认已开启
812
+ *
813
+ * 支持如下格式:
814
+ * - 13位:1711257956199
815
+ * - 14位:1711257956.199
816
+ * - 10位:1711257956
817
+ */
818
+ parseFromTimestamp(is = true) {
819
+ const validator = this.copy();
820
+ validator.config.parseFromTimestamp = is;
821
+ return validator;
822
+ }
823
+ validateValue(value, _key, label) {
824
+ const date = this.toDate(value);
825
+ if (date === false || date.toString() === "Invalid Date") return ValidateResult.deny(i18n.t("validator.date.must_be_date", { label }));
826
+ if (!this.compare(date)) return ValidateResult.deny(i18n.t("validator.date.not_in_range", { label }));
827
+ return ValidateResult.accept(date);
828
+ }
829
+ toDate(value) {
830
+ const { parseFromTimestamp = true, formats } = this.config;
831
+ if (value instanceof Date) return value;
832
+ if (parseFromTimestamp && (typeof value === "number" || typeof value === "string" && regTimestamp.test(value))) {
833
+ const timestamp = value.toString();
834
+ if (timestamp.length === 10) return DateTime.fromSeconds(Number(timestamp)).toJSDate();
835
+ if (timestamp.length === 13) return DateTime.fromMillis(Number(timestamp)).toJSDate();
836
+ if (timestamp.length === 14 && regUnixTimeWithMS.test(timestamp)) return DateTime.fromSeconds(Number(timestamp)).toJSDate();
837
+ }
838
+ if (typeof value === "string") {
839
+ if (formats && formats.length) for (const format of formats) {
840
+ const date = DateTime.fromFormat(value, format, { setZone: true });
841
+ if (date.isValid) return date.toJSDate();
842
+ }
843
+ else return DateTime.fromISO(value).toJSDate();
844
+ }
845
+ return false;
846
+ }
847
+ compare(date) {
848
+ const { min, minInclusive, max, maxInclusive } = this.config;
849
+ const timestamp = +date;
850
+ if (min !== void 0 && (minInclusive ? timestamp < +min() : timestamp <= +min())) return false;
851
+ if (max !== void 0 && (maxInclusive ? timestamp > +max() : timestamp >= +max())) return false;
852
+ return true;
853
+ }
854
+ toDocument() {
855
+ return {
856
+ type: "string",
857
+ format: "date-time",
858
+ default: this.getDefaultValue(this.config.defaultValue)?.toISOString()
859
+ };
860
+ }
861
+ };
862
+ // src/validators/decimal.ts
863
+ var DecimalValidator = class extends Validator {
864
+ default(value) {
865
+ return super.default(value instanceof Decimal ? value : new Decimal(value));
866
+ }
867
+ min(min, inclusive = true) {
868
+ const validator = this.copy();
869
+ validator.config.min = min instanceof Decimal ? min : new Decimal(min);
870
+ validator.config.minInclusive = inclusive;
871
+ return validator;
872
+ }
873
+ max(max, inclusive = true) {
874
+ const validator = this.copy();
875
+ validator.config.max = max instanceof Decimal ? max : new Decimal(max);
876
+ validator.config.maxInclusive = inclusive;
877
+ return validator;
878
+ }
879
+ validateValue(value, _key, label) {
880
+ const { strict, min, max, minInclusive, maxInclusive } = this.config;
881
+ let decimal;
882
+ if (value instanceof Decimal) decimal = value;
883
+ else if (!strict && (typeof value === "string" || typeof value === "number")) try {
884
+ decimal = new Decimal(value);
885
+ } catch {}
886
+ if (!decimal || !decimal.isFinite()) return ValidateResult.deny(i18n.t("validator.number.must_be_decimal", { label }));
887
+ if (min !== void 0) {
888
+ const cmp = decimal.comparedTo(min);
889
+ if (minInclusive ? cmp < 0 : cmp <= 0) return ValidateResult.deny(i18n.t("validator.number.not_in_range", { label }));
890
+ }
891
+ if (max !== void 0) {
892
+ const cmp = decimal.comparedTo(max);
893
+ if (maxInclusive ? cmp > 0 : cmp >= 0) return ValidateResult.deny(i18n.t("validator.number.not_in_range", { label }));
894
+ }
895
+ return ValidateResult.accept(decimal);
896
+ }
897
+ toDocument() {
898
+ const { min, max, minInclusive, maxInclusive } = this.config;
899
+ const defaultValue = this.getDefaultValue(this.config.defaultValue);
900
+ return {
901
+ type: "string",
902
+ example: "123.45",
903
+ default: defaultValue === void 0 ? void 0 : defaultValue.toString(),
904
+ minimum: min === void 0 ? void 0 : min.toNumber(),
905
+ maximum: max === void 0 ? void 0 : max.toNumber(),
906
+ exclusiveMinimum: minInclusive === void 0 ? void 0 : !minInclusive,
907
+ exclusiveMaximum: maxInclusive === void 0 ? void 0 : !maxInclusive
908
+ };
909
+ }
864
910
  };
865
-
866
911
  // src/validators/email.ts
867
- import emailValidator from "email-validator";
868
912
  var EmailValidator = class extends BaseStringValidator {
869
- validateString(email, _key, label) {
870
- if (!emailValidator.validate(email)) {
871
- return ValidateResult.deny(i18n.t("validator.string.must_be_email", { label }));
872
- }
873
- return ValidateResult.accept(email);
874
- }
875
- toDocument() {
876
- return {
877
- ...super.toDocument(),
878
- format: "email"
879
- };
880
- }
913
+ validateString(email, _key, label) {
914
+ if (!emailValidator.validate(email)) return ValidateResult.deny(i18n.t("validator.string.must_be_email", { label }));
915
+ return ValidateResult.accept(email);
916
+ }
917
+ toDocument() {
918
+ return {
919
+ ...super.toDocument(),
920
+ format: "email"
921
+ };
922
+ }
881
923
  };
882
-
883
924
  // src/validators/enum.ts
925
+ /**
926
+ * 从 TS enum / 枚举对象抽出可选值;数字 enum 会丢掉反向映射键(`"0"` / `"1"`)
927
+ */
928
+ function enumLikeToRanges(source) {
929
+ return Object.keys(source).filter((key) => Number.isNaN(Number(key))).map((key) => source[key]);
930
+ }
884
931
  var EnumValidator = class extends Validator {
885
- constructor(ranges = []) {
886
- super();
887
- this.config.ranges = ranges;
888
- ranges.forEach((item) => {
889
- if (this.isEmpty(item)) {
890
- throw new Error(i18n.t("validator.enum.can_not_be_empty", { item }));
891
- }
892
- if (typeof item !== "string" && typeof item !== "number" && typeof item !== "boolean") {
893
- throw new Error(i18n.t("validator.enum.only_support_string_number_boolean"));
894
- }
895
- });
896
- }
897
- validateValue(value, _key, label) {
898
- const { strict } = this.config;
899
- const ranges = this.config.ranges;
900
- if (ranges.includes(value)) return ValidateResult.accept(value);
901
- if (!strict) {
902
- if (value === "true" && ranges.includes(true)) {
903
- return ValidateResult.accept(true);
904
- }
905
- if (value === "false" && ranges.includes(false)) {
906
- return ValidateResult.accept(false);
907
- }
908
- if (typeof value === "string") {
909
- const num = Number(value);
910
- if (!Number.isNaN(num)) {
911
- if (ranges.includes(num)) return ValidateResult.accept(num);
912
- }
913
- }
914
- }
915
- return ValidateResult.deny(i18n.t("validator.enum.not_in_range", { label }));
916
- }
917
- toDocument() {
918
- const { ranges } = this.config;
919
- const types = ranges.map((value) => typeof value);
920
- return {
921
- type: new Set(types).size === 1 ? types[0] : void 0,
922
- enum: ranges
923
- };
924
- }
932
+ constructor(ranges = []) {
933
+ super();
934
+ this.config.ranges = ranges;
935
+ ranges.forEach((item) => {
936
+ if (this.isEmpty(item)) throw new Error(i18n.t("validator.enum.value_can_not_be_empty", { item }));
937
+ if (typeof item !== "string" && typeof item !== "number" && typeof item !== "boolean") throw new Error(i18n.t("validator.enum.only_support_string_number_boolean"));
938
+ });
939
+ }
940
+ pick(...values) {
941
+ const list = values.length === 1 && Array.isArray(values[0]) ? values[0] : values;
942
+ const set = new Set(list);
943
+ const validator = this.copy();
944
+ validator.config.ranges = this.config.ranges.filter((item) => set.has(item));
945
+ validator.assertConfigHealthy();
946
+ return validator;
947
+ }
948
+ omit(...values) {
949
+ const list = values.length === 1 && Array.isArray(values[0]) ? values[0] : values;
950
+ const set = new Set(list);
951
+ const validator = this.copy();
952
+ validator.config.ranges = this.config.ranges.filter((item) => !set.has(item));
953
+ validator.assertConfigHealthy();
954
+ return validator;
955
+ }
956
+ /** ranges 为空,或 default 不在 ranges 内时抛错 */
957
+ assertConfigHealthy() {
958
+ const { ranges, defaultValue } = this.config;
959
+ if (ranges.length === 0) throw new Error(i18n.t("validator.enum.ranges_can_not_be_empty"));
960
+ if (defaultValue !== void 0) {
961
+ const resolved = this.getDefaultValue(defaultValue);
962
+ if (!ranges.includes(resolved)) throw new Error(i18n.t("validator.enum.default_not_in_range", { item: String(resolved) }));
963
+ }
964
+ }
965
+ validateValue(value, _key, label) {
966
+ const { strict } = this.config;
967
+ const ranges = this.config.ranges;
968
+ if (ranges.includes(value)) return ValidateResult.accept(value);
969
+ if (!strict) {
970
+ if (value === "true" && ranges.includes(true)) return ValidateResult.accept(true);
971
+ if (value === "false" && ranges.includes(false)) return ValidateResult.accept(false);
972
+ if (typeof value === "string") {
973
+ const num = Number(value);
974
+ if (!Number.isNaN(num)) {
975
+ if (ranges.includes(num)) return ValidateResult.accept(num);
976
+ }
977
+ }
978
+ }
979
+ return ValidateResult.deny(i18n.t("validator.enum.not_in_range", { label }));
980
+ }
981
+ toDocument() {
982
+ const { ranges } = this.config;
983
+ const types = ranges.map((value) => typeof value);
984
+ return {
985
+ type: new Set(types).size === 1 ? types[0] : void 0,
986
+ enum: ranges
987
+ };
988
+ }
925
989
  };
926
-
927
990
  // src/validators/hash.ts
928
- var HashValidator = class _HashValidator extends BaseStringValidator {
929
- /**
930
- * @see https://github.com/validatorjs/validator.js
931
- */
932
- static algorithmLength = {
933
- md5: 32,
934
- md4: 32,
935
- sha1: 40,
936
- sha256: 64,
937
- sha384: 96,
938
- sha512: 128,
939
- ripemd128: 32,
940
- ripemd160: 40,
941
- tiger128: 32,
942
- tiger160: 40,
943
- tiger192: 48,
944
- crc32: 8,
945
- crc32b: 8
946
- };
947
- static algorithmPattern = (() => {
948
- const patterns = {};
949
- Object.values(_HashValidator.algorithmLength).forEach((length) => {
950
- patterns[length] ||= new RegExp(`^[a-f0-9]{${length}}$`, "i");
951
- });
952
- return patterns;
953
- })();
954
- constructor(algorithm) {
955
- super();
956
- this.config.algorithm = algorithm;
957
- if (!Object.hasOwn(_HashValidator.algorithmLength, algorithm)) {
958
- throw new Error("\u672A\u77E5\u7684\u54C8\u5E0C\u7C7B\u578B");
959
- }
960
- }
961
- validateString(hash, _key, label) {
962
- const { algorithm } = this.config;
963
- const length = _HashValidator.algorithmLength[algorithm];
964
- if (!_HashValidator.algorithmPattern[length].test(hash)) {
965
- return ValidateResult.deny(i18n.t("validator.string.must_be_hash", { label }));
966
- }
967
- return ValidateResult.accept(hash);
968
- }
969
- toDocument() {
970
- const { algorithm } = this.config;
971
- const length = _HashValidator.algorithmLength[algorithm];
972
- return {
973
- ...super.toDocument(),
974
- minLength: length,
975
- maxLength: length,
976
- format: this.config.algorithm
977
- };
978
- }
991
+ var HashValidator = class HashValidator extends BaseStringValidator {
992
+ /**
993
+ * @see https://github.com/validatorjs/validator.js
994
+ */
995
+ static algorithmLength = {
996
+ md5: 32,
997
+ md4: 32,
998
+ sha1: 40,
999
+ sha256: 64,
1000
+ sha384: 96,
1001
+ sha512: 128,
1002
+ ripemd128: 32,
1003
+ ripemd160: 40,
1004
+ tiger128: 32,
1005
+ tiger160: 40,
1006
+ tiger192: 48,
1007
+ crc32: 8,
1008
+ crc32b: 8
1009
+ };
1010
+ static algorithmPattern = (() => {
1011
+ const patterns = {};
1012
+ Object.values(HashValidator.algorithmLength).forEach((length) => {
1013
+ patterns[length] ||= new RegExp(`^[a-f0-9]{${length}}$`, "i");
1014
+ });
1015
+ return patterns;
1016
+ })();
1017
+ constructor(algorithm) {
1018
+ super();
1019
+ this.config.algorithm = algorithm;
1020
+ }
1021
+ validateString(hash, _key, label) {
1022
+ const { algorithm } = this.config;
1023
+ const length = HashValidator.algorithmLength[algorithm];
1024
+ if (!HashValidator.algorithmPattern[length].test(hash)) return ValidateResult.deny(i18n.t("validator.string.must_be_hash", { label }));
1025
+ return ValidateResult.accept(hash);
1026
+ }
1027
+ toDocument() {
1028
+ const { algorithm } = this.config;
1029
+ const length = HashValidator.algorithmLength[algorithm];
1030
+ return {
1031
+ ...super.toDocument(),
1032
+ minLength: length,
1033
+ maxLength: length,
1034
+ format: this.config.algorithm
1035
+ };
1036
+ }
979
1037
  };
980
-
981
1038
  // src/validators/int.ts
982
1039
  var IntValidator = class extends BaseNumberValidator {
983
- validateNumber(num, _key, label) {
984
- if (!Number.isInteger(num)) {
985
- return ValidateResult.deny(i18n.t("validator.number.must_be_integer", { label }));
986
- }
987
- return ValidateResult.accept(num);
988
- }
989
- toDocument() {
990
- return {
991
- ...super.toDocument(),
992
- type: "integer"
993
- };
994
- }
1040
+ validateNumber(num, _key, label) {
1041
+ if (!Number.isInteger(num)) return ValidateResult.deny(i18n.t("validator.number.must_be_integer", { label }));
1042
+ return ValidateResult.accept(num);
1043
+ }
1044
+ toDocument() {
1045
+ return {
1046
+ ...super.toDocument(),
1047
+ type: "integer"
1048
+ };
1049
+ }
995
1050
  };
996
-
997
1051
  // src/validators/ip.ts
998
- import { isIP, isIPv4, isIPv6 } from "net";
999
1052
  var IpValidator = class extends BaseStringValidator {
1000
- constructor(version) {
1001
- super();
1002
- this.config.ipVersion = [...new Set(version)];
1003
- }
1004
- validateString(ip, _key, label) {
1005
- const { ipVersion } = this.config;
1006
- let valid = false;
1007
- const hasV4 = ipVersion.includes("v4");
1008
- const hasV6 = ipVersion.includes("v6");
1009
- if (hasV4 && hasV6) {
1010
- valid = isIP(ip) > 0;
1011
- } else if (hasV4) {
1012
- valid = isIPv4(ip);
1013
- } else {
1014
- valid = isIPv6(ip);
1015
- }
1016
- if (!valid) {
1017
- return ValidateResult.deny(
1018
- i18n.t("validator.string.must_be_ip", {
1019
- label,
1020
- versions: ipVersion.toString()
1021
- })
1022
- );
1023
- }
1024
- return ValidateResult.accept(ip);
1025
- }
1026
- toDocument() {
1027
- const { ipVersion } = this.config;
1028
- return {
1029
- ...super.toDocument(),
1030
- format: ipVersion.length === 1 ? `ip${ipVersion[0]}` : "ip"
1031
- };
1032
- }
1053
+ constructor(version) {
1054
+ super();
1055
+ this.config.ipVersion = [...new Set(version)];
1056
+ }
1057
+ validateString(ip, _key, label) {
1058
+ const { ipVersion } = this.config;
1059
+ let valid = false;
1060
+ const hasV4 = ipVersion.includes("v4");
1061
+ const hasV6 = ipVersion.includes("v6");
1062
+ if (hasV4 && hasV6) valid = isIP(ip) > 0;
1063
+ else if (hasV4) valid = isIPv4(ip);
1064
+ else valid = isIPv6(ip);
1065
+ if (!valid) return ValidateResult.deny(i18n.t("validator.string.must_be_ip", {
1066
+ label,
1067
+ versions: ipVersion.toString()
1068
+ }));
1069
+ return ValidateResult.accept(ip);
1070
+ }
1071
+ toDocument() {
1072
+ const { ipVersion } = this.config;
1073
+ return {
1074
+ ...super.toDocument(),
1075
+ format: ipVersion.length === 1 ? `ip${ipVersion[0]}` : "ip"
1076
+ };
1077
+ }
1078
+ };
1079
+ // src/validators/literal.ts
1080
+ var LiteralValidator = class extends Validator {
1081
+ constructor(value) {
1082
+ super();
1083
+ if (value === void 0) return;
1084
+ if (typeof value === "number" && !Number.isFinite(value) || value !== null && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new Error(i18n.t("validator.literal.unsupported_value"));
1085
+ this.config.value = value;
1086
+ if (value === null) this.config.nullable = true;
1087
+ }
1088
+ /**
1089
+ * 字面量为 `''` 时,空字符串是合法取值,不能再被基类当成「空值」吞掉。
1090
+ */
1091
+ isEmpty(value) {
1092
+ if (this.config.value === "" && value === "") return false;
1093
+ return super.isEmpty(value);
1094
+ }
1095
+ validateValue(value, _key, label) {
1096
+ if (Object.is(value, this.config.value)) return ValidateResult.accept(value);
1097
+ return ValidateResult.deny(i18n.t("validator.literal.not_match", { label }));
1098
+ }
1099
+ toDocument() {
1100
+ const { value } = this.config;
1101
+ if (value === null) return { enum: [null] };
1102
+ return {
1103
+ type: typeof value,
1104
+ enum: [value]
1105
+ };
1106
+ }
1033
1107
  };
1034
-
1035
1108
  // src/validators/number.ts
1036
1109
  var NumberValidator = class extends BaseNumberValidator {
1037
- validateNumber(num) {
1038
- return ValidateResult.accept(num);
1039
- }
1040
- toDocument() {
1041
- return {
1042
- ...super.toDocument(),
1043
- type: "number"
1044
- };
1045
- }
1110
+ validateNumber(num) {
1111
+ return ValidateResult.accept(num);
1112
+ }
1113
+ toDocument() {
1114
+ return {
1115
+ ...super.toDocument(),
1116
+ type: "number"
1117
+ };
1118
+ }
1046
1119
  };
1047
-
1048
1120
  // src/validators/object.ts
1049
- import { toArray } from "@aomex/internal-tools";
1050
1121
  var ObjectValidator = class extends Validator {
1051
- constructor(properties) {
1052
- super();
1053
- this.config.properties = properties;
1054
- }
1055
- /**
1056
- * 尝试使用`JSON.parse`把字符串转换为对象,在非严格模式下默认开启
1057
- */
1058
- parseFromString(is = true) {
1059
- const validator = this.copy();
1060
- validator.config.stringToObject = is;
1061
- return validator;
1062
- }
1063
- additional(opts = {}) {
1064
- const validator = this.copy();
1065
- const keys = opts.key ? toArray(opts.key) : [];
1066
- const key = keys.length ? keys : void 0;
1067
- const value = opts.value;
1068
- validator.config.keepAdditional = !value && !key ? true : { key, value };
1069
- return validator;
1070
- }
1071
- isPlainObject(value) {
1072
- return Object.prototype.toString.call(value) === "[object Object]";
1073
- }
1074
- async validateValue(origin, key, label) {
1075
- const { properties, stringToObject, strict, keepAdditional = false } = this.config;
1076
- if (!this.isPlainObject(origin)) {
1077
- let valid = false;
1078
- if ((!strict && stringToObject !== false || strict && stringToObject) && typeof origin === "string") {
1079
- try {
1080
- origin = JSON.parse(origin);
1081
- valid = this.isPlainObject(origin);
1082
- } catch {
1083
- }
1084
- }
1085
- if (!valid) {
1086
- return ValidateResult.deny(i18n.t("validator.object.must_be_object", { label }));
1087
- }
1088
- }
1089
- let obj = {};
1090
- if (properties) {
1091
- const error = {
1092
- errors: []
1093
- };
1094
- await Promise.all(
1095
- Object.entries(properties).map(async ([propKey, validator]) => {
1096
- const result = await validator["validate"](
1097
- origin[propKey],
1098
- propKey,
1099
- label && key ? `${label}.${propKey}` : propKey
1100
- );
1101
- if (ValidateResult.noError(result)) {
1102
- obj[propKey] = result.data;
1103
- } else {
1104
- error.errors = error.errors.concat(result.errors);
1105
- }
1106
- })
1107
- );
1108
- if (error.errors.length) return error;
1109
- }
1110
- if (keepAdditional) {
1111
- const trustedKeys = properties ? Object.keys(properties) : [];
1112
- for (const propKey of Object.keys(origin)) {
1113
- if (trustedKeys.includes(propKey)) continue;
1114
- if (keepAdditional === true) {
1115
- obj[propKey] = origin[propKey];
1116
- continue;
1117
- }
1118
- if (keepAdditional.key) {
1119
- if (keepAdditional.key.every((reg) => !reg.test(propKey))) continue;
1120
- }
1121
- if (keepAdditional.value) {
1122
- const result = await keepAdditional.value["validate"](origin[propKey], propKey);
1123
- if (ValidateResult.noError(result)) {
1124
- obj[propKey] = result.data;
1125
- }
1126
- } else {
1127
- obj[propKey] = origin[propKey];
1128
- }
1129
- }
1130
- }
1131
- if (!properties && !keepAdditional) {
1132
- Object.assign(obj, origin);
1133
- }
1134
- return ValidateResult.accept(obj);
1135
- }
1136
- copyConfig(prev) {
1137
- super.copyConfig(prev);
1138
- this.config.properties = prev.config.properties && {
1139
- ...prev.config.properties
1140
- };
1141
- return this;
1142
- }
1143
- toDocument() {
1144
- const { properties = {}, keepAdditional } = this.config;
1145
- const hasSpecificProperties = !!Object.keys(properties).length;
1146
- const schemas = {};
1147
- const requiredProperties = [];
1148
- if (hasSpecificProperties) {
1149
- Object.entries(properties).forEach(([key, validator]) => {
1150
- const docs = Validator.toDocument(validator);
1151
- schemas[key] = docs.schema;
1152
- docs.required && requiredProperties.push(key);
1153
- });
1154
- }
1155
- let additionalProperties;
1156
- if (keepAdditional === void 0) {
1157
- additionalProperties = !hasSpecificProperties;
1158
- } else if (typeof keepAdditional === "boolean") {
1159
- additionalProperties = keepAdditional;
1160
- } else if (!keepAdditional.value) {
1161
- additionalProperties = true;
1162
- } else {
1163
- additionalProperties = Validator.toDocument(keepAdditional.value).schema;
1164
- }
1165
- return {
1166
- type: "object",
1167
- properties: hasSpecificProperties ? schemas : void 0,
1168
- required: requiredProperties.length ? requiredProperties : void 0,
1169
- additionalProperties
1170
- };
1171
- }
1122
+ constructor(properties) {
1123
+ super();
1124
+ this.config.properties = properties;
1125
+ }
1126
+ /**
1127
+ * 尝试使用`JSON.parse`把字符串转换为对象,在非严格模式下默认开启
1128
+ */
1129
+ parseFromString(is = true) {
1130
+ const validator = this.copy();
1131
+ validator.config.stringToObject = is;
1132
+ return validator;
1133
+ }
1134
+ additional(opts = {}) {
1135
+ const validator = this.copy();
1136
+ const keys = opts.key ? toArray(opts.key) : [];
1137
+ const key = keys.length ? keys : void 0;
1138
+ const value = opts.value === void 0 ? void 0 : toValidator(opts.value);
1139
+ validator.config.keepAdditional = !value && !key ? true : {
1140
+ key,
1141
+ value
1142
+ };
1143
+ return validator;
1144
+ }
1145
+ isPlainObject(value) {
1146
+ return Object.prototype.toString.call(value) === "[object Object]";
1147
+ }
1148
+ async validateValue(origin, key, label) {
1149
+ const { properties, stringToObject, strict, keepAdditional = false } = this.config;
1150
+ if (!this.isPlainObject(origin)) {
1151
+ let valid = false;
1152
+ if ((!strict && stringToObject !== false || strict && stringToObject) && typeof origin === "string") try {
1153
+ origin = JSON.parse(origin);
1154
+ valid = this.isPlainObject(origin);
1155
+ } catch {}
1156
+ if (!valid) return ValidateResult.deny(i18n.t("validator.object.must_be_object", { label }));
1157
+ }
1158
+ let obj = {};
1159
+ if (properties) {
1160
+ const error = { errors: [] };
1161
+ await Promise.all(Object.entries(properties).map(async ([propKey, validator]) => {
1162
+ const result = await validator["validate"](origin[propKey], propKey, label && key ? `${label}.${propKey}` : propKey);
1163
+ if (ValidateResult.noError(result)) obj[propKey] = result.data;
1164
+ else error.errors = error.errors.concat(result.errors);
1165
+ }));
1166
+ if (error.errors.length) return error;
1167
+ }
1168
+ if (keepAdditional) {
1169
+ const trustedKeys = properties ? Object.keys(properties) : [];
1170
+ for (const propKey of Object.keys(origin)) {
1171
+ if (trustedKeys.includes(propKey)) continue;
1172
+ if (keepAdditional === true) {
1173
+ obj[propKey] = origin[propKey];
1174
+ continue;
1175
+ }
1176
+ if (keepAdditional.key) {
1177
+ if (keepAdditional.key.every((reg) => !reg.test(propKey))) continue;
1178
+ }
1179
+ if (keepAdditional.value) {
1180
+ const result = await keepAdditional.value["validate"](origin[propKey], propKey);
1181
+ if (ValidateResult.noError(result)) obj[propKey] = result.data;
1182
+ } else obj[propKey] = origin[propKey];
1183
+ }
1184
+ }
1185
+ if (!properties && !keepAdditional) Object.assign(obj, origin);
1186
+ return ValidateResult.accept(obj);
1187
+ }
1188
+ nested() {
1189
+ const { properties, keepAdditional } = this.config;
1190
+ const nested = properties ? Object.values(properties) : [];
1191
+ if (keepAdditional && typeof keepAdditional === "object" && keepAdditional.value) nested.push(keepAdditional.value);
1192
+ return nested;
1193
+ }
1194
+ copyConfig(prev) {
1195
+ super.copyConfig(prev);
1196
+ this.config.properties = prev.config.properties && { ...prev.config.properties };
1197
+ return this;
1198
+ }
1199
+ toDocument() {
1200
+ const { properties = {}, keepAdditional } = this.config;
1201
+ const hasSpecificProperties = !!Object.keys(properties).length;
1202
+ const schemas = {};
1203
+ const requiredProperties = [];
1204
+ if (hasSpecificProperties) Object.entries(properties).forEach(([key, validator]) => {
1205
+ const docs = toDocument(validator);
1206
+ schemas[key] = docs.schema;
1207
+ docs.required && requiredProperties.push(key);
1208
+ });
1209
+ let additionalProperties;
1210
+ if (keepAdditional === void 0) additionalProperties = !hasSpecificProperties;
1211
+ else if (typeof keepAdditional === "boolean") additionalProperties = keepAdditional;
1212
+ else if (!keepAdditional.value) additionalProperties = true;
1213
+ else additionalProperties = toDocument(keepAdditional.value).schema;
1214
+ return {
1215
+ type: "object",
1216
+ properties: hasSpecificProperties ? schemas : void 0,
1217
+ required: requiredProperties.length ? requiredProperties : void 0,
1218
+ additionalProperties
1219
+ };
1220
+ }
1172
1221
  };
1173
-
1174
1222
  // src/validators/one-of.ts
1175
1223
  var OneOfValidator = class extends Validator {
1176
- constructor(validators) {
1177
- super();
1178
- this.config.validators = validators;
1179
- }
1180
- isEmpty(_) {
1181
- return false;
1182
- }
1183
- async validateValue(value, key, label) {
1184
- const { validators } = this.config;
1185
- let matched;
1186
- for (let i = 0; i < validators.length; ++i) {
1187
- const validator = validators[i];
1188
- const result = await validator.validate(value, key, label);
1189
- if (ValidateResult.noError(result)) {
1190
- if (!matched) {
1191
- matched = result;
1192
- } else {
1193
- return ValidateResult.deny(
1194
- i18n.t("validator.one_of.match_multiple_rule", { label })
1195
- );
1196
- }
1197
- }
1198
- }
1199
- return matched || ValidateResult.deny(i18n.t("validator.one_of.not_match_rule", { label }));
1200
- }
1201
- copyConfig(prev) {
1202
- super.copyConfig(prev);
1203
- this.config.validators = [...prev.config.validators];
1204
- return this;
1205
- }
1206
- toDocument() {
1207
- const { validators } = this.config;
1208
- return {
1209
- oneOf: validators.map((validator) => Validator.toDocument(validator).schema)
1210
- };
1211
- }
1224
+ constructor(validators) {
1225
+ super();
1226
+ this.config.validators = validators;
1227
+ }
1228
+ isEmpty(_) {
1229
+ return false;
1230
+ }
1231
+ async validateValue(value, key, label) {
1232
+ const { validators } = this.config;
1233
+ let matched;
1234
+ for (let i = 0; i < validators.length; ++i) {
1235
+ const result = await validators[i].validate(value, key, label);
1236
+ if (ValidateResult.noError(result)) {
1237
+ if (!matched) matched = result;
1238
+ else return ValidateResult.deny(i18n.t("validator.one_of.match_multiple_rule", { label }));
1239
+ }
1240
+ }
1241
+ return matched || ValidateResult.deny(i18n.t("validator.one_of.not_match_rule", { label }));
1242
+ }
1243
+ copyConfig(prev) {
1244
+ super.copyConfig(prev);
1245
+ this.config.validators = [...prev.config.validators];
1246
+ return this;
1247
+ }
1248
+ nested() {
1249
+ return this.config.validators;
1250
+ }
1251
+ toDocument() {
1252
+ const { validators } = this.config;
1253
+ return { oneOf: validators.map((validator) => toDocument(validator).schema) };
1254
+ }
1212
1255
  };
1213
-
1214
1256
  // src/validators/stream.ts
1215
- import stream from "stream";
1216
1257
  var StreamValidator = class extends Validator {
1217
- validateValue(value, _key, label) {
1218
- if (!(value instanceof stream.Stream)) {
1219
- return ValidateResult.deny(i18n.t("validator.stream.must_be_stream", { label }));
1220
- }
1221
- return ValidateResult.accept(value);
1222
- }
1223
- toDocument() {
1224
- return {
1225
- type: "string",
1226
- format: "binary"
1227
- };
1228
- }
1258
+ validateValue(value, _key, label) {
1259
+ if (!(value instanceof stream.Stream)) return ValidateResult.deny(i18n.t("validator.stream.must_be_stream", { label }));
1260
+ return ValidateResult.accept(value);
1261
+ }
1262
+ toDocument() {
1263
+ return {
1264
+ type: "string",
1265
+ format: "binary"
1266
+ };
1267
+ }
1229
1268
  };
1230
-
1231
1269
  // src/validators/string.ts
1232
1270
  var StringValidator = class extends BaseStringValidator {
1233
- /**
1234
- * 把空字符串`''`设置为合法的值
1235
- */
1236
- allowEmptyString() {
1237
- const validator = this.copy();
1238
- validator.config.allowEmpty = true;
1239
- return validator;
1240
- }
1241
- isEmpty(value) {
1242
- if (value === "" && this.config.allowEmpty) return false;
1243
- return super.isEmpty(value);
1244
- }
1245
- validateString(value) {
1246
- return ValidateResult.accept(value);
1247
- }
1248
- toDocument() {
1249
- return super.toDocument();
1250
- }
1271
+ /**
1272
+ * 把空字符串`''`设置为合法的值
1273
+ */
1274
+ allowEmptyString() {
1275
+ const validator = this.copy();
1276
+ validator.config.allowEmpty = true;
1277
+ return validator;
1278
+ }
1279
+ isEmpty(value) {
1280
+ if (value === "" && this.config.allowEmpty) return false;
1281
+ return super.isEmpty(value);
1282
+ }
1283
+ validateString(value) {
1284
+ return ValidateResult.accept(value);
1285
+ }
1286
+ toDocument() {
1287
+ return super.toDocument();
1288
+ }
1251
1289
  };
1252
-
1253
1290
  // src/validators/ulid.ts
1254
- var pattern = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
1291
+ const pattern = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
1255
1292
  var UlidValidator = class extends BaseStringValidator {
1256
- validateString(ulid, _key, label) {
1257
- if (!pattern.test(ulid)) {
1258
- return ValidateResult.deny(i18n.t("validator.string.must_be_ulid", { label }));
1259
- }
1260
- return ValidateResult.accept(ulid);
1261
- }
1262
- toDocument() {
1263
- return {
1264
- example: "01BJQE4QTHMFP0S5J153XCFSP9",
1265
- ...super.toDocument(),
1266
- format: "ulid"
1267
- };
1268
- }
1293
+ validateString(ulid, _key, label) {
1294
+ if (!pattern.test(ulid)) return ValidateResult.deny(i18n.t("validator.string.must_be_ulid", { label }));
1295
+ return ValidateResult.accept(ulid);
1296
+ }
1297
+ toDocument() {
1298
+ return {
1299
+ example: "01BJQE4QTHMFP0S5J153XCFSP9",
1300
+ ...super.toDocument(),
1301
+ format: "ulid"
1302
+ };
1303
+ }
1269
1304
  };
1270
-
1271
1305
  // src/validators/url.ts
1272
- import { URL } from "url";
1273
1306
  var UrlValidator = class extends BaseStringValidator {
1274
- constructor() {
1275
- super();
1276
- this.config.allowedScheme = ["http", "https"];
1277
- }
1278
- /**
1279
- * 允许使用的协议,不区分大小写。默认配置:`['http', 'https']`
1280
- */
1281
- scheme(scheme) {
1282
- const validator = this.copy();
1283
- validator.config.allowedScheme = scheme.map((item) => item.toLowerCase());
1284
- return validator;
1285
- }
1286
- validateString(url, _key, label) {
1287
- const { allowedScheme } = this.config;
1288
- if (!/^[a-z0-9]+:\/\/.+/.test(url) || !URL.canParse(url)) {
1289
- return ValidateResult.deny(i18n.t("validator.url.must_be_url", { label }));
1290
- }
1291
- const parsedUrl = new URL(url);
1292
- const scheme = parsedUrl.protocol.slice(0, -1);
1293
- if (!allowedScheme.includes(scheme)) {
1294
- return ValidateResult.deny(
1295
- i18n.t("validator.url.unsupported_scheme", { label, scheme })
1296
- );
1297
- }
1298
- return ValidateResult.accept(url);
1299
- }
1300
- toDocument() {
1301
- return {
1302
- example: "https://example.com/path/to?id=1",
1303
- ...super.toDocument(),
1304
- format: "uri"
1305
- };
1306
- }
1307
+ constructor() {
1308
+ super();
1309
+ this.config.allowedScheme = ["http", "https"];
1310
+ }
1311
+ /**
1312
+ * 允许使用的协议,不区分大小写。默认配置:`['http', 'https']`
1313
+ */
1314
+ scheme(scheme) {
1315
+ const validator = this.copy();
1316
+ validator.config.allowedScheme = scheme.map((item) => item.toLowerCase());
1317
+ return validator;
1318
+ }
1319
+ validateString(url, _key, label) {
1320
+ const { allowedScheme } = this.config;
1321
+ if (!/^[a-z0-9]+:\/\/.+/.test(url) || !URL$1.canParse(url)) return ValidateResult.deny(i18n.t("validator.url.must_be_url", { label }));
1322
+ const scheme = new URL$1(url).protocol.slice(0, -1);
1323
+ if (!allowedScheme.includes(scheme)) return ValidateResult.deny(i18n.t("validator.url.unsupported_scheme", {
1324
+ label,
1325
+ scheme
1326
+ }));
1327
+ return ValidateResult.accept(url);
1328
+ }
1329
+ toDocument() {
1330
+ return {
1331
+ example: "https://example.com/path/to?id=1",
1332
+ ...super.toDocument(),
1333
+ format: "uri"
1334
+ };
1335
+ }
1307
1336
  };
1308
-
1309
1337
  // src/validators/uuid.ts
1310
- var createRegexp = (version) => {
1311
- const group = "[0-9a-f]";
1312
- const diff = version === "all" ? `${group}{4}` : `${version}${group}{3}`;
1313
- return new RegExp(
1314
- `^${group}{8}-${group}{4}-${diff}-[89ab]${group}{3}-${group}{12}$`,
1315
- "i"
1316
- );
1338
+ const createRegexp = (version) => {
1339
+ const group = "[0-9a-f]";
1340
+ const diff = version === "all" ? `${group}{4}` : `${version}${group}{3}`;
1341
+ return new RegExp(`^${group}{8}-${group}{4}-${diff}-[89ab]${group}{3}-${group}{12}$`, "i");
1317
1342
  };
1318
- var UuidValidator = class _UuidValidator extends BaseStringValidator {
1319
- static versions = ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8"];
1320
- static patterns = {
1321
- v1: createRegexp(1),
1322
- v2: createRegexp(2),
1323
- v3: createRegexp(3),
1324
- v4: createRegexp(4),
1325
- v5: createRegexp(5),
1326
- v6: createRegexp(6),
1327
- v7: createRegexp(7),
1328
- v8: createRegexp(8),
1329
- all: createRegexp("all")
1330
- };
1331
- constructor(versions) {
1332
- super();
1333
- this.config.uuidVersion = [...new Set(versions)];
1334
- }
1335
- validateString(uuid, _key, label) {
1336
- const { uuidVersion } = this.config;
1337
- let valid = false;
1338
- if (uuidVersion.length === _UuidValidator.versions.length) {
1339
- valid = _UuidValidator.patterns.all.test(uuid);
1340
- } else {
1341
- for (let i = uuidVersion.length; i-- > 0; ) {
1342
- if (_UuidValidator.patterns[uuidVersion[i]].test(uuid)) {
1343
- valid = true;
1344
- break;
1345
- }
1346
- }
1347
- }
1348
- if (!valid) {
1349
- return ValidateResult.deny(
1350
- i18n.t("validator.string.must_be_uuid", {
1351
- label,
1352
- versions: uuidVersion.join(",")
1353
- })
1354
- );
1355
- }
1356
- return ValidateResult.accept(uuid);
1357
- }
1358
- toDocument() {
1359
- return {
1360
- ...super.toDocument(),
1361
- format: "uuid"
1362
- };
1363
- }
1343
+ var UuidValidator = class UuidValidator extends BaseStringValidator {
1344
+ static versions = [
1345
+ "v1",
1346
+ "v2",
1347
+ "v3",
1348
+ "v4",
1349
+ "v5",
1350
+ "v6",
1351
+ "v7",
1352
+ "v8"
1353
+ ];
1354
+ static patterns = {
1355
+ v1: createRegexp(1),
1356
+ v2: createRegexp(2),
1357
+ v3: createRegexp(3),
1358
+ v4: createRegexp(4),
1359
+ v5: createRegexp(5),
1360
+ v6: createRegexp(6),
1361
+ v7: createRegexp(7),
1362
+ v8: createRegexp(8),
1363
+ all: createRegexp("all")
1364
+ };
1365
+ constructor(versions) {
1366
+ super();
1367
+ this.config.uuidVersion = [...new Set(versions)];
1368
+ }
1369
+ validateString(uuid, _key, label) {
1370
+ const { uuidVersion } = this.config;
1371
+ let valid = false;
1372
+ if (uuidVersion.length === UuidValidator.versions.length) valid = UuidValidator.patterns.all.test(uuid);
1373
+ else for (let i = uuidVersion.length; i-- > 0;) if (UuidValidator.patterns[uuidVersion[i]].test(uuid)) {
1374
+ valid = true;
1375
+ break;
1376
+ }
1377
+ if (!valid) return ValidateResult.deny(i18n.t("validator.string.must_be_uuid", {
1378
+ label,
1379
+ versions: uuidVersion.join(",")
1380
+ }));
1381
+ return ValidateResult.accept(uuid);
1382
+ }
1383
+ toDocument() {
1384
+ return {
1385
+ ...super.toDocument(),
1386
+ format: "uuid"
1387
+ };
1388
+ }
1364
1389
  };
1365
-
1366
1390
  // src/api/to-validator.ts
1367
1391
  function toValidator(validator) {
1368
- if (!validator) return;
1369
- if (validator instanceof Validator) return validator;
1370
- return new ObjectValidator(validator);
1392
+ if (!validator) return;
1393
+ if (validator instanceof Validator) return validator;
1394
+ if (validator instanceof ValidatorSchema) {
1395
+ const objectValidator = new ObjectValidator(validator["rules"]);
1396
+ if (validator["name"] !== void 0) objectValidator["config"].refName = validator["name"];
1397
+ return objectValidator;
1398
+ }
1399
+ return new ObjectValidator(normalizeFieldTable(validator));
1400
+ }
1401
+ /**
1402
+ * 逐字段转为 Validator;嵌套裸对象 / schema 经 `toValidator` 转为 `ObjectValidator`
1403
+ */
1404
+ function normalizeFieldTable(fields) {
1405
+ const result = {};
1406
+ for (const key of Object.keys(fields)) result[key] = toValidator(fields[key]);
1407
+ return result;
1371
1408
  }
1372
-
1373
1409
  // src/api/rule.ts
1374
- import { toArray as toArray2 } from "@aomex/internal-tools";
1375
1410
  var Rule = class {
1376
- static register(name, SubValidator) {
1377
- this.prototype[name] = () => new SubValidator();
1378
- }
1379
- /**
1380
- * 规则以管道形式执行,需要匹配所有规则
1381
- * ```typescript
1382
- * rule.allOf([rule.number(), rule.string()]);
1383
- * ```
1384
- */
1385
- allOf(rules) {
1386
- return new AllOfValidator(rules);
1387
- }
1388
- /**
1389
- * 允许任何类型:
1390
- * - string
1391
- * - number
1392
- * - boolean
1393
- * - array
1394
- * - object
1395
- * - buffer
1396
- */
1397
- any() {
1398
- return new AnyValidator();
1399
- }
1400
- /**
1401
- * 规则以管道形式执行,需要至少匹配一个规则
1402
- * ```typescript
1403
- * rule.anyOf([rule.number(), rule.string()]);
1404
- * ```
1405
- */
1406
- anyOf(rules) {
1407
- return new AnyOfValidator(rules);
1408
- }
1409
- array(values) {
1410
- return new ArrayValidator(toValidator(values));
1411
- }
1412
- /**
1413
- * 大整数类型
1414
- *
1415
- * 注意:非严格模式下,`number` 和 `string` 会尝试被转换成 `bigint` 类型
1416
- */
1417
- bigint() {
1418
- return new BigIntValidator();
1419
- }
1420
- /**
1421
- * - 默认真值:`[1, '1', true, 'true']`
1422
- * - 默认假值:`[0, '0', false, 'false']`
1423
- */
1424
- boolean() {
1425
- return new BooleanValidator();
1426
- }
1427
- buffer() {
1428
- return new BufferValidator();
1429
- }
1430
- /**
1431
- * @deprecated 请使用 rule.date()
1432
- */
1433
- dateTime(...formats) {
1434
- return new DateValidator(formats);
1435
- }
1436
- /**
1437
- * @param formats 设置解析字符串的格式,支持同时指定不同的格式并从左到右依次尝试。如果是标准的ISO时间格式或者时间戳则无需指定。
1438
- *
1439
- * @link https://moment.github.io/luxon/#/formatting?id=table-of-tokens
1440
- */
1441
- date(...formats) {
1442
- return new DateValidator(formats);
1443
- }
1444
- email() {
1445
- return new EmailValidator();
1446
- }
1447
- enum(ranges) {
1448
- return new EnumValidator(toArray2(ranges, true));
1449
- }
1450
- hash(algorithm) {
1451
- return new HashValidator(algorithm);
1452
- }
1453
- /**
1454
- * 注意:非严格模式下,`string` 会尝试被转换成 `number` 类型
1455
- */
1456
- int() {
1457
- return new IntValidator();
1458
- }
1459
- /**
1460
- * ```typescript
1461
- * rule.ip('v4');
1462
- * rule.ip('v6');
1463
- * rule.ip(['v4', 'v6']);
1464
- * ```
1465
- */
1466
- ip(version) {
1467
- return new IpValidator(toArray2(version));
1468
- }
1469
- /**
1470
- * 注意:非严格模式下,`string` 会尝试被转换成 `number` 类型
1471
- */
1472
- number() {
1473
- return new NumberValidator();
1474
- }
1475
- /**
1476
- * ```typescript
1477
- * rule.object();
1478
- * rule.object({
1479
- * id: rule.int(),
1480
- * profile: rule.object({
1481
- * sex: rule.enum(['unknown', 'male', 'female']),
1482
- * }),
1483
- * });
1484
- * ```
1485
- */
1486
- object(properties) {
1487
- return new ObjectValidator(properties);
1488
- }
1489
- /**
1490
- * 必须且只能匹配其中一个规则,如果匹配上多个则失败
1491
- * ```typescript
1492
- * rule.oneOf([rule.number(), rule.string()]);
1493
- * ```
1494
- */
1495
- oneOf(rules) {
1496
- return new OneOfValidator(rules);
1497
- }
1498
- /**
1499
- * 数据流
1500
- */
1501
- stream() {
1502
- return new StreamValidator();
1503
- }
1504
- string() {
1505
- return new StringValidator();
1506
- }
1507
- ulid() {
1508
- return new UlidValidator();
1509
- }
1510
- url() {
1511
- return new UrlValidator();
1512
- }
1513
- uuid(versions) {
1514
- return new UuidValidator(toArray2(versions || UuidValidator.versions));
1515
- }
1411
+ static register(name, SubValidator) {
1412
+ this.prototype[name] = () => new SubValidator();
1413
+ }
1414
+ /**
1415
+ * 规则以管道形式执行,需要匹配所有规则
1416
+ * ```typescript
1417
+ * rule.allOf([rule.number(), rule.string()]);
1418
+ * ```
1419
+ */
1420
+ allOf(rules) {
1421
+ return new AllOfValidator(rules.map(toValidator));
1422
+ }
1423
+ /**
1424
+ * 允许任何类型:
1425
+ * - string
1426
+ * - number
1427
+ * - boolean
1428
+ * - array
1429
+ * - object
1430
+ * - buffer
1431
+ */
1432
+ any() {
1433
+ return new AnyValidator();
1434
+ }
1435
+ /**
1436
+ * 规则以管道形式执行,需要至少匹配一个规则
1437
+ * ```typescript
1438
+ * rule.anyOf([rule.number(), rule.string()]);
1439
+ * ```
1440
+ */
1441
+ anyOf(rules) {
1442
+ return new AnyOfValidator(rules.map(toValidator));
1443
+ }
1444
+ array(values) {
1445
+ return new ArrayValidator(toValidator(values));
1446
+ }
1447
+ /**
1448
+ * 大整数类型
1449
+ *
1450
+ * 注意:非严格模式下,`number` 和 `string` 会尝试被转换成 `bigint` 类型
1451
+ */
1452
+ bigint() {
1453
+ return new BigIntValidator();
1454
+ }
1455
+ /**
1456
+ * - 默认真值:`[1, '1', true, 'true']`
1457
+ * - 默认假值:`[0, '0', false, 'false']`
1458
+ */
1459
+ boolean() {
1460
+ return new BooleanValidator();
1461
+ }
1462
+ buffer() {
1463
+ return new BufferValidator();
1464
+ }
1465
+ /**
1466
+ * @deprecated 请使用 rule.date()
1467
+ */
1468
+ dateTime(...formats) {
1469
+ return new DateValidator(formats);
1470
+ }
1471
+ /**
1472
+ * @param formats 设置解析字符串的格式,支持同时指定不同的格式并从左到右依次尝试。如果是标准的ISO时间格式或者时间戳则无需指定。
1473
+ *
1474
+ * @link https://moment.github.io/luxon/#/formatting?id=table-of-tokens
1475
+ */
1476
+ date(...formats) {
1477
+ return new DateValidator(formats);
1478
+ }
1479
+ /**
1480
+ * 高精度小数(decimal.js)
1481
+ *
1482
+ * 注意:非严格模式下,`number` 和 `string` 会尝试被转换成 `Decimal` 类型
1483
+ */
1484
+ decimal() {
1485
+ return new DecimalValidator();
1486
+ }
1487
+ email() {
1488
+ return new EmailValidator();
1489
+ }
1490
+ enum(rangesOrEnum) {
1491
+ if (Array.isArray(rangesOrEnum)) return new EnumValidator(toArray(rangesOrEnum, true));
1492
+ return new EnumValidator(enumLikeToRanges(rangesOrEnum));
1493
+ }
1494
+ hash(algorithm) {
1495
+ return new HashValidator(algorithm);
1496
+ }
1497
+ /**
1498
+ * 注意:非严格模式下,`string` 会尝试被转换成 `number` 类型
1499
+ */
1500
+ int() {
1501
+ return new IntValidator();
1502
+ }
1503
+ /**
1504
+ * ```typescript
1505
+ * rule.ip('v4');
1506
+ * rule.ip('v6');
1507
+ * rule.ip(['v4', 'v6']);
1508
+ * ```
1509
+ */
1510
+ ip(version) {
1511
+ return new IpValidator(toArray(version));
1512
+ }
1513
+ /**
1514
+ * 精确匹配单个字面量(不做类型转换)
1515
+ * ```typescript
1516
+ * rule.literal('ok');
1517
+ * rule.literal(1);
1518
+ * rule.literal(true);
1519
+ * rule.literal(null);
1520
+ * ```
1521
+ */
1522
+ literal(value) {
1523
+ return new LiteralValidator(value);
1524
+ }
1525
+ /**
1526
+ * 注意:非严格模式下,`string` 会尝试被转换成 `number` 类型
1527
+ */
1528
+ number() {
1529
+ return new NumberValidator();
1530
+ }
1531
+ object(properties) {
1532
+ if (!properties) return new ObjectValidator();
1533
+ return toValidator(properties);
1534
+ }
1535
+ /**
1536
+ * 动态键对象(`Record<string, V>`),等价于 `rule.object().additional({ value })`
1537
+ * ```typescript
1538
+ * rule.record(rule.number());
1539
+ * rule.record({ id: rule.int() });
1540
+ * ```
1541
+ */
1542
+ record(value) {
1543
+ return new ObjectValidator().additional({ value });
1544
+ }
1545
+ /**
1546
+ * 必须且只能匹配其中一个规则,如果匹配上多个则失败
1547
+ * ```typescript
1548
+ * rule.oneOf([rule.number(), rule.string()]);
1549
+ * ```
1550
+ */
1551
+ oneOf(rules) {
1552
+ return new OneOfValidator(rules.map(toValidator));
1553
+ }
1554
+ /**
1555
+ * 数据流
1556
+ */
1557
+ stream() {
1558
+ return new StreamValidator();
1559
+ }
1560
+ string() {
1561
+ return new StringValidator();
1562
+ }
1563
+ ulid() {
1564
+ return new UlidValidator();
1565
+ }
1566
+ url() {
1567
+ return new UrlValidator();
1568
+ }
1569
+ uuid(versions) {
1570
+ return new UuidValidator(toArray(versions || UuidValidator.versions));
1571
+ }
1516
1572
  };
1517
- var rule = new Rule();
1518
-
1573
+ const rule = new Rule();
1519
1574
  // src/api/validate.ts
1520
- var validate = async (untrusted, validators, options = {}) => {
1521
- const { errorFormatter = defaultErrorFormatter } = options;
1522
- const validator = toValidator(validators);
1523
- const source = await untrusted;
1524
- const trusted = await validator["validate"](source);
1525
- if (ValidateResult.noError(trusted)) return trusted.data;
1526
- const msg = await errorFormatter(trusted.errors);
1527
- throw new ValidateDeniedError(msg, trusted.errors);
1528
- };
1529
- var defaultErrorFormatter = (errors) => {
1530
- return errors[0];
1531
- };
1532
- export {
1533
- AllOfValidator,
1534
- AnyOfValidator,
1535
- AnyValidator,
1536
- ArrayValidator,
1537
- BaseNumberValidator,
1538
- BaseStringValidator,
1539
- BigIntValidator,
1540
- BooleanValidator,
1541
- BufferValidator,
1542
- DateValidator,
1543
- EmailValidator,
1544
- EnumValidator,
1545
- HashValidator,
1546
- IntValidator,
1547
- IpValidator,
1548
- NumberValidator,
1549
- ObjectValidator,
1550
- OneOfValidator,
1551
- Rule,
1552
- StreamValidator,
1553
- StringValidator,
1554
- UlidValidator,
1555
- UrlValidator,
1556
- UuidValidator,
1557
- ValidateDeniedError,
1558
- ValidateResult,
1559
- Validator,
1560
- rule,
1561
- toValidator,
1562
- validate
1575
+ async function validate(untrusted, validators, options = {}) {
1576
+ const { throwOnError = true, errorFormatter } = options;
1577
+ const validator = toValidator(validators);
1578
+ const source = await untrusted;
1579
+ const trusted = await validator["validate"](source);
1580
+ if (ValidateResult.noError(trusted)) {
1581
+ if (throwOnError) return trusted.data;
1582
+ return {
1583
+ data: trusted.data,
1584
+ errors: null
1585
+ };
1586
+ }
1587
+ const errors = trusted.errors;
1588
+ if (!throwOnError) return {
1589
+ data: null,
1590
+ errors
1591
+ };
1592
+ throw new ValidateDeniedError(errorFormatter ? await errorFormatter(errors) : errors[0], errors);
1593
+ }
1594
+ // src/api/schema.ts
1595
+ /**
1596
+ * 创建可派生的字段集合,可直接或经 pick/omit/extend/partial/required 后用于校验
1597
+ *
1598
+ * 嵌套裸对象会在入库前转为 `rule.object(...)`:
1599
+ * ```typescript
1600
+ * schema({
1601
+ * profile: { bio: rule.string() }, // 等价于 rule.object({ bio: rule.string() })
1602
+ * });
1603
+ * ```
1604
+ *
1605
+ * ```typescript
1606
+ * const userSchema = schema({
1607
+ * id: rule.int(),
1608
+ * name: rule.string(),
1609
+ * email: rule.email(),
1610
+ * });
1611
+ *
1612
+ * const createUserSchema = userSchema.omit('id');
1613
+ * const patchUserSchema = userSchema.pick('name', 'email').partial();
1614
+ * const requiredSchema = patchUserSchema.required();
1615
+ * type User = Validator.Infer<typeof userSchema>;
1616
+ * ```
1617
+ */
1618
+ const schema = (rules) => {
1619
+ return new ValidatorSchema(normalizeFieldTable(rules));
1563
1620
  };
1621
+ export { AllOfValidator, AnyOfValidator, AnyValidator, ArrayValidator, BaseNumberValidator, BaseStringValidator, BigIntValidator, BooleanValidator, BufferValidator, DateValidator, Decimal, DecimalValidator, EmailValidator, EnumValidator, HashValidator, IntValidator, IpValidator, LiteralValidator, NumberValidator, ObjectValidator, OneOfValidator, Rule, StreamValidator, StringValidator, UlidValidator, UrlValidator, UuidValidator, ValidateDeniedError, ValidateResult, Validator, ValidatorSchema, enumLikeToRanges, normalizeFieldTable, rule, schema, toDocument, toValidator, validate };
1622
+
1564
1623
  //# sourceMappingURL=index.js.map