schema-dsl 1.2.4 → 2.0.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/CHANGELOG.md +87 -210
- package/README.md +391 -2249
- package/dist/DslBuilder-DQDN0ZxZ.d.cts +341 -0
- package/dist/DslBuilder-DkLaOo9Q.d.ts +341 -0
- package/dist/Validator-C7GsVQOH.d.cts +192 -0
- package/dist/Validator-hFWKGxir.d.ts +192 -0
- package/dist/index.cjs +6594 -0
- package/dist/index.d.cts +1145 -0
- package/dist/index.d.ts +1145 -0
- package/dist/index.js +6528 -0
- package/dist/plugin-CIKtTMtS.d.cts +246 -0
- package/dist/plugin-CIKtTMtS.d.ts +246 -0
- package/dist/plugins/custom-format.cjs +3802 -0
- package/dist/plugins/custom-format.d.cts +12 -0
- package/dist/plugins/custom-format.d.ts +12 -0
- package/dist/plugins/custom-format.js +3772 -0
- package/dist/plugins/custom-type-example.cjs +3795 -0
- package/dist/plugins/custom-type-example.d.cts +8 -0
- package/dist/plugins/custom-type-example.d.ts +8 -0
- package/dist/plugins/custom-type-example.js +3765 -0
- package/dist/plugins/custom-validator.cjs +146 -0
- package/dist/plugins/custom-validator.d.cts +10 -0
- package/dist/plugins/custom-validator.d.ts +10 -0
- package/dist/plugins/custom-validator.js +121 -0
- package/docs/FEATURE-INDEX.md +102 -68
- package/docs/add-custom-locale.md +48 -35
- package/docs/add-keyword.md +24 -0
- package/docs/api-reference.md +396 -154
- package/docs/api.md +13 -0
- package/docs/best-practices-project-structure.md +19 -10
- package/docs/best-practices.md +93 -53
- package/docs/cache-manager.md +23 -15
- package/docs/compile.md +45 -0
- package/docs/conditional-api.md +40 -11
- package/docs/custom-extensions-guide.md +80 -152
- package/docs/design-philosophy.md +76 -71
- package/docs/doc-index.md +324 -0
- package/docs/dsl-syntax.md +69 -19
- package/docs/dynamic-locale.md +24 -14
- package/docs/enum.md +12 -5
- package/docs/error-handling.md +53 -44
- package/docs/export-guide.md +47 -8
- package/docs/export-limitations.md +27 -11
- package/docs/faq.md +86 -67
- package/docs/frontend-i18n-guide.md +26 -12
- package/docs/i18n-user-guide.md +60 -47
- package/docs/i18n.md +51 -32
- package/docs/index.md +48 -0
- package/docs/json-schema-basics.md +40 -0
- package/docs/label-vs-description.md +12 -3
- package/docs/markdown-exporter.md +15 -6
- package/docs/mongodb-exporter.md +11 -4
- package/docs/multi-language.md +26 -0
- package/docs/multi-type-support.md +26 -33
- package/docs/mysql-exporter.md +9 -2
- package/docs/number-operators.md +12 -5
- package/docs/optional-marker-guide.md +28 -23
- package/docs/performance-guide.md +49 -0
- package/docs/plugin-system.md +205 -366
- package/docs/plugin-type-registration.md +34 -0
- package/docs/postgresql-exporter.md +9 -2
- package/docs/public/favicon.svg +5 -0
- package/docs/quick-start.md +37 -363
- package/docs/runtime-locale-support.md +20 -9
- package/docs/schema-helper.md +10 -5
- package/docs/schema-utils-advanced-issues.md +23 -0
- package/docs/schema-utils-best-practices.md +20 -0
- package/docs/schema-utils-chaining.md +7 -0
- package/docs/schema-utils.md +76 -42
- package/docs/security-checklist.md +20 -0
- package/docs/string-extensions.md +17 -9
- package/docs/troubleshooting.md +36 -21
- package/docs/type-converter.md +41 -50
- package/docs/type-reference.md +38 -15
- package/docs/typescript-guide.md +53 -42
- package/docs/union-type-guide.md +11 -1
- package/docs/union-types.md +10 -3
- package/docs/validate-async.md +36 -25
- package/docs/validate-batch.md +49 -0
- package/docs/validate-dsl-object-support.md +33 -28
- package/docs/validate.md +36 -16
- package/docs/validation-guide.md +25 -7
- package/docs/validator.md +39 -0
- package/package.json +85 -27
- package/plugins/custom-format.cjs +8 -0
- package/plugins/custom-type-example.cjs +8 -0
- package/plugins/custom-validator.cjs +8 -0
- package/src/adapters/DslAdapter.ts +111 -0
- package/src/adapters/index.ts +1 -0
- package/src/config/constants.ts +83 -0
- package/src/config/index.ts +2 -0
- package/src/config/patterns.ts +77 -0
- package/src/core/CacheManager.ts +159 -0
- package/src/core/ConditionalBuilder.ts +382 -0
- package/src/core/ConditionalRuntime.ts +28 -0
- package/src/core/ConditionalValidator.ts +255 -0
- package/src/core/DslBuilder.ts +677 -0
- package/src/core/ErrorCodes.ts +38 -0
- package/src/core/ErrorFormatter.ts +271 -0
- package/src/core/JSONSchemaCore.ts +65 -0
- package/src/core/Locale.ts +187 -0
- package/src/core/MessageTemplate.ts +42 -0
- package/src/core/ObjectDslBuilder.ts +64 -0
- package/src/core/PluginManager.ts +326 -0
- package/src/core/StringExtensions.ts +140 -0
- package/src/core/TemplateEngine.ts +44 -0
- package/src/core/Validator.ts +448 -0
- package/src/errors/I18nError.ts +159 -0
- package/src/errors/ValidationError.ts +105 -0
- package/src/exporters/BaseExporter.ts +60 -0
- package/src/exporters/MarkdownExporter.ts +305 -0
- package/src/exporters/MongoDBExporter.ts +126 -0
- package/src/exporters/MySQLExporter.ts +155 -0
- package/src/exporters/PostgreSQLExporter.ts +222 -0
- package/src/exporters/index.ts +18 -0
- package/src/index.ts +633 -0
- package/{lib/locales/en-US.js → src/locales/en-US.ts} +21 -37
- package/{lib/locales/es-ES.js → src/locales/es-ES.ts} +63 -16
- package/{lib/locales/fr-FR.js → src/locales/fr-FR.ts} +74 -27
- package/src/locales/index.ts +103 -0
- package/{lib/locales/ja-JP.js → src/locales/ja-JP.ts} +59 -17
- package/src/locales/types.ts +156 -0
- package/{lib/locales/zh-CN.js → src/locales/zh-CN.ts} +21 -38
- package/src/parser/ConstraintParser.ts +101 -0
- package/src/parser/DslParser.ts +470 -0
- package/src/parser/SchemaCompiler.ts +66 -0
- package/src/parser/TypeRegistry.ts +250 -0
- package/src/parser/index.ts +6 -0
- package/src/plugins/custom-format.ts +126 -0
- package/src/plugins/custom-type-example.ts +108 -0
- package/src/plugins/custom-validator.ts +140 -0
- package/src/types/conditional.ts +28 -0
- package/src/types/config.ts +59 -0
- package/src/types/dsl.ts +131 -0
- package/src/types/error.ts +60 -0
- package/src/types/index.ts +17 -0
- package/src/types/infer.ts +128 -0
- package/src/types/plugin.ts +58 -0
- package/src/types/safe-regex.d.ts +9 -0
- package/src/types/schema.ts +66 -0
- package/src/types/validate.ts +71 -0
- package/src/utils/SchemaHelper.ts +196 -0
- package/src/utils/SchemaUtils.ts +346 -0
- package/src/utils/TypeConverter.ts +215 -0
- package/src/utils/index.ts +10 -0
- package/src/validators/CustomKeywords.ts +477 -0
- package/.eslintignore +0 -11
- package/.eslintrc.json +0 -27
- package/CONTRIBUTING.md +0 -368
- package/STATUS.md +0 -491
- package/changelogs/v1.0.0.md +0 -328
- package/changelogs/v1.0.9.md +0 -367
- package/changelogs/v1.1.0.md +0 -389
- package/changelogs/v1.1.1.md +0 -308
- package/changelogs/v1.1.2.md +0 -183
- package/changelogs/v1.1.3.md +0 -161
- package/changelogs/v1.1.4.md +0 -432
- package/changelogs/v1.1.5.md +0 -493
- package/changelogs/v1.1.6.md +0 -211
- package/changelogs/v1.1.8.md +0 -376
- package/changelogs/v1.2.3.md +0 -124
- package/docs/INDEX.md +0 -252
- package/docs/issues-resolved-summary.md +0 -196
- package/docs/performance-benchmark-report.md +0 -179
- package/docs/performance-quick-reference.md +0 -123
- package/docs/user-questions-answered.md +0 -353
- package/docs/validation-rules-v1.0.2.md +0 -1608
- package/examples/README.md +0 -81
- package/examples/array-dsl-example.js +0 -227
- package/examples/conditional-example.js +0 -288
- package/examples/conditional-non-object.js +0 -129
- package/examples/conditional-validate-example.js +0 -321
- package/examples/custom-extension.js +0 -85
- package/examples/dsl-match-example.js +0 -74
- package/examples/dsl-style.js +0 -118
- package/examples/dynamic-locale-configuration.js +0 -348
- package/examples/dynamic-locale-example.js +0 -287
- package/examples/enum.examples.js +0 -324
- package/examples/export-demo.js +0 -130
- package/examples/express-integration.js +0 -376
- package/examples/i18n-error-handling-complete.js +0 -381
- package/examples/i18n-error-handling-quickstart.md +0 -0
- package/examples/i18n-error.examples.js +0 -181
- package/examples/i18n-full-demo.js +0 -301
- package/examples/i18n-memory-safety.examples.js +0 -268
- package/examples/markdown-export.js +0 -71
- package/examples/middleware-usage.js +0 -93
- package/examples/new-features-comparison.js +0 -315
- package/examples/password-reset/README.md +0 -153
- package/examples/password-reset/schema.js +0 -26
- package/examples/password-reset/test.js +0 -101
- package/examples/plugin-system.examples.js +0 -205
- package/examples/schema-utils-chaining.examples.js +0 -250
- package/examples/simple-example.js +0 -122
- package/examples/slug.examples.js +0 -179
- package/examples/string-extensions.js +0 -297
- package/examples/union-type-example.js +0 -127
- package/examples/union-types-example.js +0 -77
- package/examples/user-registration/README.md +0 -156
- package/examples/user-registration/routes.js +0 -92
- package/examples/user-registration/schema.js +0 -150
- package/examples/user-registration/server.js +0 -74
- package/index.d.ts +0 -3540
- package/index.js +0 -457
- package/index.mjs +0 -60
- package/lib/adapters/DslAdapter.js +0 -871
- package/lib/adapters/index.js +0 -20
- package/lib/config/constants.js +0 -286
- package/lib/config/patterns/common.js +0 -47
- package/lib/config/patterns/creditCard.js +0 -9
- package/lib/config/patterns/idCard.js +0 -9
- package/lib/config/patterns/index.js +0 -9
- package/lib/config/patterns/licensePlate.js +0 -4
- package/lib/config/patterns/passport.js +0 -4
- package/lib/config/patterns/phone.js +0 -9
- package/lib/config/patterns/postalCode.js +0 -5
- package/lib/core/CacheManager.js +0 -376
- package/lib/core/ConditionalBuilder.js +0 -503
- package/lib/core/DslBuilder.js +0 -1400
- package/lib/core/ErrorCodes.js +0 -233
- package/lib/core/ErrorFormatter.js +0 -445
- package/lib/core/JSONSchemaCore.js +0 -347
- package/lib/core/Locale.js +0 -130
- package/lib/core/MessageTemplate.js +0 -98
- package/lib/core/PluginManager.js +0 -448
- package/lib/core/StringExtensions.js +0 -240
- package/lib/core/Validator.js +0 -654
- package/lib/errors/I18nError.js +0 -328
- package/lib/errors/ValidationError.js +0 -191
- package/lib/exporters/MarkdownExporter.js +0 -420
- package/lib/exporters/MongoDBExporter.js +0 -162
- package/lib/exporters/MySQLExporter.js +0 -212
- package/lib/exporters/PostgreSQLExporter.js +0 -289
- package/lib/exporters/index.js +0 -24
- package/lib/locales/index.js +0 -8
- package/lib/utils/LRUCache.js +0 -174
- package/lib/utils/SchemaHelper.js +0 -240
- package/lib/utils/SchemaUtils.js +0 -445
- package/lib/utils/TypeConverter.js +0 -245
- package/lib/utils/index.js +0 -13
- package/lib/validators/CustomKeywords.js +0 -616
- package/lib/validators/index.js +0 -11
|
@@ -1,871 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* DSL风格适配器 v2.0
|
|
3
|
-
*
|
|
4
|
-
* 统一的DSL Builder Pattern
|
|
5
|
-
* 支持:纯字符串DSL + 链式调用扩展
|
|
6
|
-
*
|
|
7
|
-
* @module lib/adapters/DslAdapter
|
|
8
|
-
* @version 2.0.0
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
const JSONSchemaCore = require('../core/JSONSchemaCore');
|
|
12
|
-
const DslBuilder = require('../core/DslBuilder');
|
|
13
|
-
|
|
14
|
-
// throw new Error('DEBUG FILE LOADED');
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* DSL适配器类
|
|
18
|
-
* @class DslAdapter
|
|
19
|
-
*/
|
|
20
|
-
class DslAdapter {
|
|
21
|
-
/**
|
|
22
|
-
* 解析DSL字符串为JSON Schema(内部使用)
|
|
23
|
-
* @static
|
|
24
|
-
* @param {string} dslString - DSL字符串
|
|
25
|
-
* @returns {Object} JSON Schema对象
|
|
26
|
-
*/
|
|
27
|
-
static parseString(dslString) {
|
|
28
|
-
if (!dslString || typeof dslString !== 'string') {
|
|
29
|
-
throw new Error('DSL must be a string');
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const trimmed = dslString.trim();
|
|
33
|
-
let required = trimmed.endsWith('!');
|
|
34
|
-
let dslWithoutRequired = required ? trimmed.slice(0, -1) : trimmed;
|
|
35
|
-
|
|
36
|
-
// 特殊处理:array!数字范围 → array:数字范围 + 必填
|
|
37
|
-
// 支持: array!1-10, array!1-, array!-10
|
|
38
|
-
if (/^array![\d-]/.test(trimmed)) {
|
|
39
|
-
dslWithoutRequired = trimmed.replace(/^array!/, 'array:');
|
|
40
|
-
required = true;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// 解析基本类型和约束
|
|
44
|
-
const schema = this._parseType(dslWithoutRequired);
|
|
45
|
-
|
|
46
|
-
return schema;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* parse方法别名(向后兼容)
|
|
51
|
-
* @static
|
|
52
|
-
* @param {string} dslString - DSL字符串
|
|
53
|
-
* @returns {Object} JSON Schema对象
|
|
54
|
-
*/
|
|
55
|
-
static parse(dslString) {
|
|
56
|
-
const schema = this.parseString(dslString);
|
|
57
|
-
schema._required = dslString.trim().endsWith('!');
|
|
58
|
-
return schema;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* 解析类型和约束
|
|
63
|
-
* @private
|
|
64
|
-
* @static
|
|
65
|
-
* @param {string} dsl - DSL字符串(不含!)
|
|
66
|
-
* @returns {Object} JSON Schema对象
|
|
67
|
-
*/
|
|
68
|
-
static _parseType(dsl) {
|
|
69
|
-
// 处理数组DSL语法
|
|
70
|
-
if (dsl.startsWith('array')) {
|
|
71
|
-
const schema = { type: 'array' };
|
|
72
|
-
|
|
73
|
-
// 匹配模式: array:min-max<itemType> 或 array:constraint<itemType> 或 array<itemType>
|
|
74
|
-
// 支持: array:1-10, array:1-, array:-10, array:10, array<string>, array:1-10<string>
|
|
75
|
-
const arrayMatch = dsl.match(/^array(?::([^<]+?))?(?:<(.+)>)?$/);
|
|
76
|
-
|
|
77
|
-
if (arrayMatch) {
|
|
78
|
-
const [, constraint, itemType] = arrayMatch;
|
|
79
|
-
|
|
80
|
-
// 解析约束
|
|
81
|
-
if (constraint) {
|
|
82
|
-
const trimmedConstraint = constraint.trim();
|
|
83
|
-
|
|
84
|
-
if (trimmedConstraint.includes('-')) {
|
|
85
|
-
// 范围约束: min-max, min-, -max
|
|
86
|
-
const [min, max] = trimmedConstraint.split('-').map(v => v.trim());
|
|
87
|
-
if (min) schema.minItems = parseInt(min, 10);
|
|
88
|
-
if (max) schema.maxItems = parseInt(max, 10);
|
|
89
|
-
} else {
|
|
90
|
-
// 单个值 = 最大值
|
|
91
|
-
schema.maxItems = parseInt(trimmedConstraint, 10);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// 解析元素类型
|
|
96
|
-
if (itemType) {
|
|
97
|
-
schema.items = this._parseType(itemType.trim());
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
return schema;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
// 检查是否为纯枚举(包含|但没有:且没有数字范围)
|
|
106
|
-
if (dsl.includes('|') && !dsl.includes(':') && !/^\w+\d+-\d+$/.test(dsl)) {
|
|
107
|
-
return {
|
|
108
|
-
type: 'string',
|
|
109
|
-
enum: dsl.split('|').map(v => v.trim())
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// 格式: type:constraint 或 type数字范围
|
|
114
|
-
// 例如: string:3-32, number:0-100
|
|
115
|
-
let type, constraint;
|
|
116
|
-
|
|
117
|
-
// 检查是否有冒号
|
|
118
|
-
const colonIndex = dsl.indexOf(':');
|
|
119
|
-
|
|
120
|
-
if (colonIndex !== -1) {
|
|
121
|
-
// 有冒号:string:3-32
|
|
122
|
-
type = dsl.substring(0, colonIndex);
|
|
123
|
-
constraint = dsl.substring(colonIndex + 1);
|
|
124
|
-
} else {
|
|
125
|
-
// 无冒号:检查是否有数字约束(string3-32)
|
|
126
|
-
const match = dsl.match(/^([a-z]+)(\d.*)$/i);
|
|
127
|
-
if (match) {
|
|
128
|
-
type = match[1];
|
|
129
|
-
constraint = match[2];
|
|
130
|
-
} else {
|
|
131
|
-
type = dsl;
|
|
132
|
-
constraint = '';
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// 特殊处理 phone:country
|
|
137
|
-
if (type === 'phone') {
|
|
138
|
-
const country = constraint || 'cn';
|
|
139
|
-
const config = patterns.phone[country];
|
|
140
|
-
if (!config) throw new Error(`Unsupported country for phone: ${country}`);
|
|
141
|
-
return {
|
|
142
|
-
type: 'string',
|
|
143
|
-
pattern: config.pattern.source,
|
|
144
|
-
minLength: config.min,
|
|
145
|
-
maxLength: config.max,
|
|
146
|
-
_customMessages: { 'pattern': config.key || config.msg }
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// 特殊处理 idCard:country
|
|
151
|
-
if (type === 'idCard') {
|
|
152
|
-
const country = constraint || 'cn';
|
|
153
|
-
const config = patterns.idCard[country.toLowerCase()];
|
|
154
|
-
if (!config) throw new Error(`Unsupported country for idCard: ${country}`);
|
|
155
|
-
return {
|
|
156
|
-
type: 'string',
|
|
157
|
-
pattern: config.pattern.source,
|
|
158
|
-
minLength: config.min,
|
|
159
|
-
maxLength: config.max,
|
|
160
|
-
_customMessages: { 'pattern': config.key || config.msg }
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// 特殊处理 creditCard:type
|
|
165
|
-
if (type === 'creditCard') {
|
|
166
|
-
const cardType = constraint || 'visa';
|
|
167
|
-
const config = patterns.creditCard[cardType.toLowerCase()];
|
|
168
|
-
if (!config) throw new Error(`Unsupported credit card type: ${cardType}`);
|
|
169
|
-
return {
|
|
170
|
-
type: 'string',
|
|
171
|
-
pattern: config.pattern.source,
|
|
172
|
-
_customMessages: { 'pattern': config.key || config.msg }
|
|
173
|
-
};
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// 特殊处理 licensePlate:country
|
|
177
|
-
if (type === 'licensePlate') {
|
|
178
|
-
const country = constraint || 'cn';
|
|
179
|
-
const config = patterns.licensePlate[country.toLowerCase()];
|
|
180
|
-
if (!config) throw new Error(`Unsupported country for licensePlate: ${country}`);
|
|
181
|
-
return {
|
|
182
|
-
type: 'string',
|
|
183
|
-
pattern: config.pattern.source,
|
|
184
|
-
_customMessages: { 'pattern': config.key || config.msg }
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// 特殊处理 postalCode:country
|
|
189
|
-
if (type === 'postalCode') {
|
|
190
|
-
const country = constraint || 'cn';
|
|
191
|
-
const config = patterns.postalCode[country.toLowerCase()];
|
|
192
|
-
if (!config) throw new Error(`Unsupported country for postalCode: ${country}`);
|
|
193
|
-
return {
|
|
194
|
-
type: 'string',
|
|
195
|
-
pattern: config.pattern.source,
|
|
196
|
-
_customMessages: { 'pattern': config.key || config.msg }
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// 特殊处理 passport:country
|
|
201
|
-
if (type === 'passport') {
|
|
202
|
-
const country = constraint || 'cn';
|
|
203
|
-
const config = patterns.passport[country.toLowerCase()];
|
|
204
|
-
if (!config) throw new Error(`Unsupported country for passport: ${country}`);
|
|
205
|
-
return {
|
|
206
|
-
type: 'string',
|
|
207
|
-
pattern: config.pattern.source,
|
|
208
|
-
_customMessages: { 'pattern': config.key || config.msg }
|
|
209
|
-
};
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
// 获取基础类型Schema
|
|
213
|
-
const baseSchema = this._getBaseType(type);
|
|
214
|
-
|
|
215
|
-
// 应用约束
|
|
216
|
-
if (constraint) {
|
|
217
|
-
const constraintSchema = this._parseConstraint(baseSchema.type, constraint);
|
|
218
|
-
Object.assign(baseSchema, constraintSchema);
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
return baseSchema;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
* 获取基本类型Schema
|
|
226
|
-
* @private
|
|
227
|
-
* @static
|
|
228
|
-
* @param {string} type - 类型名称
|
|
229
|
-
* @returns {Object} 基本类型Schema
|
|
230
|
-
*/
|
|
231
|
-
static _getBaseType(type) {
|
|
232
|
-
const typeMap = {
|
|
233
|
-
// 基本类型
|
|
234
|
-
'string': { type: 'string' },
|
|
235
|
-
'number': { type: 'number' },
|
|
236
|
-
'integer': { type: 'integer' },
|
|
237
|
-
'boolean': { type: 'boolean' },
|
|
238
|
-
'object': { type: 'object' },
|
|
239
|
-
'array': { type: 'array' },
|
|
240
|
-
'null': { type: 'null' },
|
|
241
|
-
|
|
242
|
-
// 格式类型
|
|
243
|
-
'date': { type: 'string', format: 'date' },
|
|
244
|
-
'datetime': { type: 'string', format: 'date-time' },
|
|
245
|
-
'time': { type: 'string', format: 'time' },
|
|
246
|
-
'email': { type: 'string', format: 'email' },
|
|
247
|
-
'url': { type: 'string', format: 'uri' },
|
|
248
|
-
'uuid': { type: 'string', format: 'uuid' },
|
|
249
|
-
'ipv4': { type: 'string', format: 'ipv4' },
|
|
250
|
-
'ipv6': { type: 'string', format: 'ipv6' },
|
|
251
|
-
|
|
252
|
-
// 特殊类型(对比 joi 补充)
|
|
253
|
-
'binary': { type: 'string', contentEncoding: 'base64' },
|
|
254
|
-
'objectId': { type: 'string', pattern: '^[0-9a-fA-F]{24}$' },
|
|
255
|
-
'hexColor': { type: 'string', pattern: '^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$' },
|
|
256
|
-
'macAddress': { type: 'string', pattern: '^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$' },
|
|
257
|
-
'cron': { type: 'string', pattern: '^(\\*|([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])|\\*\\/([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])) (\\*|([0-9]|1[0-9]|2[0-3])|\\*\\/([0-9]|1[0-9]|2[0-3])) (\\*|([1-9]|1[0-9]|2[0-9]|3[0-1])|\\*\\/([1-9]|1[0-9]|2[0-9]|3[0-1])) (\\*|([1-9]|1[0-2])|\\*\\/([1-9]|1[0-2])) (\\*|([0-6])|\\*\\/([0-6]))$' },
|
|
258
|
-
'any': {} // 任意类型
|
|
259
|
-
};
|
|
260
|
-
|
|
261
|
-
return typeMap[type] || { type: 'string' };
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/**
|
|
265
|
-
* 解析约束
|
|
266
|
-
* @private
|
|
267
|
-
* @static
|
|
268
|
-
* @param {string} baseType - 基础类型
|
|
269
|
-
* @param {string} constraint - 约束字符串
|
|
270
|
-
* @returns {Object} 约束对象
|
|
271
|
-
*
|
|
272
|
-
* @example
|
|
273
|
-
* // 比较运算符 (v1.2.0+)
|
|
274
|
-
* _parseConstraint('number', '>0') // { exclusiveMinimum: 0 }
|
|
275
|
-
* _parseConstraint('number', '>=18') // { minimum: 18 }
|
|
276
|
-
* _parseConstraint('number', '<100') // { exclusiveMaximum: 100 }
|
|
277
|
-
* _parseConstraint('number', '<=100') // { maximum: 100 }
|
|
278
|
-
* _parseConstraint('number', '=100') // { enum: [100] }
|
|
279
|
-
* _parseConstraint('number', '>0.5') // { exclusiveMinimum: 0.5 } 支持小数
|
|
280
|
-
*/
|
|
281
|
-
static _parseConstraint(baseType, constraint) {
|
|
282
|
-
if (!constraint) return {};
|
|
283
|
-
|
|
284
|
-
const result = {};
|
|
285
|
-
|
|
286
|
-
// ========== 比较运算符(v1.1.2新增,最高优先级)==========
|
|
287
|
-
if (baseType === 'number' || baseType === 'integer') {
|
|
288
|
-
// 1. 大于等于: >=18, >=-10 (支持负数)
|
|
289
|
-
const gteMatch = constraint.match(/^>=(-?\d+(?:\.\d+)?)$/);
|
|
290
|
-
if (gteMatch) {
|
|
291
|
-
result.minimum = parseFloat(gteMatch[1]);
|
|
292
|
-
return result;
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
// 2. 小于等于: <=100, <=-10 (支持负数)
|
|
296
|
-
const lteMatch = constraint.match(/^<=(-?\d+(?:\.\d+)?)$/);
|
|
297
|
-
if (lteMatch) {
|
|
298
|
-
result.maximum = parseFloat(lteMatch[1]);
|
|
299
|
-
return result;
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
// 3. 大于: >0, >-10 (不包括边界值,支持负数)
|
|
303
|
-
const gtMatch = constraint.match(/^>(-?\d+(?:\.\d+)?)$/);
|
|
304
|
-
if (gtMatch) {
|
|
305
|
-
result.exclusiveMinimum = parseFloat(gtMatch[1]);
|
|
306
|
-
return result;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// 4. 小于: <100, <-10 (不包括边界值,支持负数)
|
|
310
|
-
const ltMatch = constraint.match(/^<(-?\d+(?:\.\d+)?)$/);
|
|
311
|
-
if (ltMatch) {
|
|
312
|
-
result.exclusiveMaximum = parseFloat(ltMatch[1]);
|
|
313
|
-
return result;
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// 5. 等于: =100, =-10 (支持负数)
|
|
317
|
-
const eqMatch = constraint.match(/^=(-?\d+(?:\.\d+)?)$/);
|
|
318
|
-
if (eqMatch) {
|
|
319
|
-
result.enum = [parseFloat(eqMatch[1])];
|
|
320
|
-
return result;
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
// 枚举: value1|value2|value3 (优先检查,避免被数字范围误判)
|
|
325
|
-
if (constraint.includes('|') && !/^\d+-\d+$/.test(constraint)) {
|
|
326
|
-
result.enum = constraint.split('|').map(v => v.trim());
|
|
327
|
-
return result;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
// 范围约束: min-max 或 min- 或 -max
|
|
331
|
-
// 支持小数: 0.5-99.9
|
|
332
|
-
const rangeMatch = constraint.match(/^(\d*\.?\d*)-(\d*\.?\d*)$/);
|
|
333
|
-
if (rangeMatch) {
|
|
334
|
-
const [, min, max] = rangeMatch;
|
|
335
|
-
if (baseType === 'string') {
|
|
336
|
-
if (min) result.minLength = parseInt(min, 10);
|
|
337
|
-
if (max) result.maxLength = parseInt(max, 10);
|
|
338
|
-
} else if (baseType === 'array') {
|
|
339
|
-
if (min) result.minItems = parseInt(min, 10);
|
|
340
|
-
if (max) result.maxItems = parseInt(max, 10);
|
|
341
|
-
} else {
|
|
342
|
-
if (min) result.minimum = parseFloat(min);
|
|
343
|
-
if (max) result.maximum = parseFloat(max);
|
|
344
|
-
}
|
|
345
|
-
return result;
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
// 单个约束: min, max
|
|
349
|
-
// 支持小数: 99.99
|
|
350
|
-
const singleMatch = constraint.match(/^(\d+(?:\.\d+)?)$/);
|
|
351
|
-
if (singleMatch) {
|
|
352
|
-
const value = parseFloat(singleMatch[1]);
|
|
353
|
-
if (baseType === 'string') {
|
|
354
|
-
result.maxLength = Math.floor(value);
|
|
355
|
-
} else if (baseType === 'array') {
|
|
356
|
-
result.maxItems = Math.floor(value);
|
|
357
|
-
} else {
|
|
358
|
-
result.maximum = value;
|
|
359
|
-
}
|
|
360
|
-
return result;
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
return constraint;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
/**
|
|
367
|
-
* 解析对象为Schema(支持DslBuilder)
|
|
368
|
-
* @static
|
|
369
|
-
* @param {Object} dslObject - DSL对象定义
|
|
370
|
-
* @returns {Object} JSON Schema对象
|
|
371
|
-
*/
|
|
372
|
-
static parseObject(dslObject) {
|
|
373
|
-
const schema = {
|
|
374
|
-
type: 'object',
|
|
375
|
-
properties: {},
|
|
376
|
-
required: []
|
|
377
|
-
};
|
|
378
|
-
|
|
379
|
-
for (const [key, value] of Object.entries(dslObject)) {
|
|
380
|
-
let fieldKey = key;
|
|
381
|
-
let isFieldRequired = false;
|
|
382
|
-
|
|
383
|
-
// 检查 key 是否带 ! 后缀(表示该字段本身必填)
|
|
384
|
-
if (key.endsWith('!')) {
|
|
385
|
-
fieldKey = key.slice(0, -1);
|
|
386
|
-
isFieldRequired = true;
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
let fieldSchema;
|
|
390
|
-
|
|
391
|
-
// 1. Match 结构 (dsl.match)
|
|
392
|
-
if (value && value._isMatch) {
|
|
393
|
-
const matchSchema = this._buildMatchSchema(value.field, fieldKey, value.map);
|
|
394
|
-
if (matchSchema) {
|
|
395
|
-
if (!schema.allOf) schema.allOf = [];
|
|
396
|
-
schema.allOf.push(matchSchema);
|
|
397
|
-
}
|
|
398
|
-
// 占位Schema,确保字段存在
|
|
399
|
-
fieldSchema = { description: `Depends on ${value.field}` };
|
|
400
|
-
}
|
|
401
|
-
// 2. If 结构 (dsl.if - 旧版本)
|
|
402
|
-
else if (value && value._isIf) {
|
|
403
|
-
const ifSchema = this._buildIfSchema(value.condition, fieldKey, value.then, value.else);
|
|
404
|
-
if (ifSchema) {
|
|
405
|
-
if (!schema.allOf) schema.allOf = [];
|
|
406
|
-
schema.allOf.push(ifSchema);
|
|
407
|
-
}
|
|
408
|
-
fieldSchema = { description: `Conditional field based on ${value.condition}` };
|
|
409
|
-
}
|
|
410
|
-
// 3. ConditionalBuilder 结构 (dsl.if - 新版本)
|
|
411
|
-
else if (value && value._isConditional) {
|
|
412
|
-
// 调用 toSchema() 转换为 Schema 对象
|
|
413
|
-
const conditionalSchema = typeof value.toSchema === 'function'
|
|
414
|
-
? value.toSchema()
|
|
415
|
-
: value;
|
|
416
|
-
// 保存条件链,留待 Validator 执行
|
|
417
|
-
fieldSchema = conditionalSchema;
|
|
418
|
-
}
|
|
419
|
-
// 4. DslBuilder 实例(链式调用结果)
|
|
420
|
-
else if (value instanceof DslBuilder) {
|
|
421
|
-
fieldSchema = value.toSchema();
|
|
422
|
-
}
|
|
423
|
-
// 5. 纯字符串 DSL
|
|
424
|
-
else if (typeof value === 'string') {
|
|
425
|
-
const builder = new DslBuilder(value);
|
|
426
|
-
fieldSchema = builder.toSchema();
|
|
427
|
-
}
|
|
428
|
-
// 6. 嵌套对象
|
|
429
|
-
else if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
|
|
430
|
-
fieldSchema = this.parseObject(value);
|
|
431
|
-
}
|
|
432
|
-
// 7. 其他类型(保留原样)
|
|
433
|
-
else {
|
|
434
|
-
fieldSchema = value;
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
// 处理必填标记(优先级:key! > 字段内部的!)
|
|
438
|
-
if (isFieldRequired) {
|
|
439
|
-
schema.required.push(fieldKey);
|
|
440
|
-
} else if (fieldSchema && fieldSchema._required) {
|
|
441
|
-
schema.required.push(fieldKey);
|
|
442
|
-
delete fieldSchema._required;
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
// 清理所有_required标记(包括嵌套的)
|
|
446
|
-
this._cleanRequiredMarks(fieldSchema);
|
|
447
|
-
|
|
448
|
-
schema.properties[fieldKey] = fieldSchema;
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
if (schema.required.length === 0) {
|
|
452
|
-
delete schema.required;
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
return schema;
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
/**
|
|
459
|
-
* 创建 Match 结构
|
|
460
|
-
* @static
|
|
461
|
-
* @param {string} field - 依赖字段名
|
|
462
|
-
* @param {Object} map - 值映射
|
|
463
|
-
* @returns {Object} Match结构
|
|
464
|
-
*/
|
|
465
|
-
static match(field, map) {
|
|
466
|
-
return {
|
|
467
|
-
_isMatch: true,
|
|
468
|
-
field,
|
|
469
|
-
map
|
|
470
|
-
};
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
/**
|
|
474
|
-
* 创建 If 结构
|
|
475
|
-
* @static
|
|
476
|
-
* @param {string} condition - 条件字段
|
|
477
|
-
* @param {string|Object} thenSchema - 满足条件时的Schema
|
|
478
|
-
* @param {string|Object} elseSchema - 不满足条件时的Schema
|
|
479
|
-
* @returns {Object} If结构
|
|
480
|
-
*/
|
|
481
|
-
static if(condition, thenSchema, elseSchema) {
|
|
482
|
-
return {
|
|
483
|
-
_isIf: true,
|
|
484
|
-
condition,
|
|
485
|
-
then: thenSchema,
|
|
486
|
-
else: elseSchema
|
|
487
|
-
};
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
/**
|
|
491
|
-
* 解析DSL定义(字符串/Builder/对象)
|
|
492
|
-
* @private
|
|
493
|
-
* @static
|
|
494
|
-
*/
|
|
495
|
-
static _resolveDsl(dsl) {
|
|
496
|
-
if (!dsl) return {};
|
|
497
|
-
if (dsl instanceof DslBuilder) return dsl.toSchema();
|
|
498
|
-
if (typeof dsl === 'string') return new DslBuilder(dsl).toSchema();
|
|
499
|
-
if (typeof dsl === 'object' && !Array.isArray(dsl)) return this.parseObject(dsl);
|
|
500
|
-
return dsl;
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
/**
|
|
504
|
-
* 构建 Match 对应的 JSON Schema (if-then-else 链)
|
|
505
|
-
* @private
|
|
506
|
-
* @static
|
|
507
|
-
*/
|
|
508
|
-
static _buildMatchSchema(conditionField, targetField, map) {
|
|
509
|
-
const entries = Object.entries(map).filter(([k]) => k !== '_default');
|
|
510
|
-
const defaultDsl = map._default;
|
|
511
|
-
|
|
512
|
-
const build = (index) => {
|
|
513
|
-
if (index >= entries.length) {
|
|
514
|
-
if (defaultDsl) {
|
|
515
|
-
// 处理 _default 值(可能是 Match、If 或普通 DSL)
|
|
516
|
-
if (defaultDsl._isMatch) {
|
|
517
|
-
return this._buildMatchSchema(defaultDsl.field, targetField, defaultDsl.map);
|
|
518
|
-
} else if (defaultDsl._isIf) {
|
|
519
|
-
return this._buildIfSchema(defaultDsl.condition, targetField, defaultDsl.then, defaultDsl.else);
|
|
520
|
-
} else {
|
|
521
|
-
const s = this._resolveDsl(defaultDsl);
|
|
522
|
-
const isRequired = s._required;
|
|
523
|
-
this._cleanRequiredMarks(s);
|
|
524
|
-
const result = { properties: { [targetField]: s } };
|
|
525
|
-
if (isRequired) result.required = [targetField];
|
|
526
|
-
return result;
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
return {};
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
const [val, dsl] = entries[index];
|
|
533
|
-
|
|
534
|
-
// 处理分支值(可能是 Match、If 或普通 DSL)
|
|
535
|
-
let thenSchema;
|
|
536
|
-
// 先检查 null/undefined
|
|
537
|
-
if (dsl === null || dsl === undefined) {
|
|
538
|
-
// 跳过 null/undefined 分支,继续下一个
|
|
539
|
-
return build(index + 1);
|
|
540
|
-
} else if (dsl._isMatch) {
|
|
541
|
-
thenSchema = this._buildMatchSchema(dsl.field, targetField, dsl.map);
|
|
542
|
-
} else if (dsl._isIf) {
|
|
543
|
-
thenSchema = this._buildIfSchema(dsl.condition, targetField, dsl.then, dsl.else);
|
|
544
|
-
} else {
|
|
545
|
-
const branchSchema = this._resolveDsl(dsl);
|
|
546
|
-
const isRequired = branchSchema._required;
|
|
547
|
-
this._cleanRequiredMarks(branchSchema);
|
|
548
|
-
thenSchema = { properties: { [targetField]: branchSchema } };
|
|
549
|
-
if (isRequired) thenSchema.required = [targetField];
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
return {
|
|
553
|
-
if: { properties: { [conditionField]: { const: val } } },
|
|
554
|
-
then: thenSchema,
|
|
555
|
-
else: build(index + 1)
|
|
556
|
-
};
|
|
557
|
-
};
|
|
558
|
-
|
|
559
|
-
return build(0);
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
/**
|
|
563
|
-
* 构建 If 对应的 JSON Schema
|
|
564
|
-
* @private
|
|
565
|
-
* @static
|
|
566
|
-
*/
|
|
567
|
-
static _buildIfSchema(conditionField, targetField, thenDsl, elseDsl) {
|
|
568
|
-
// 处理 then 分支
|
|
569
|
-
let thenResult;
|
|
570
|
-
if (thenDsl && thenDsl._isMatch) {
|
|
571
|
-
// then 是一个 Match 结构,需要递归构建
|
|
572
|
-
thenResult = this._buildMatchSchema(thenDsl.field, targetField, thenDsl.map);
|
|
573
|
-
} else if (thenDsl && thenDsl._isIf) {
|
|
574
|
-
// then 是一个 If 结构,需要递归构建
|
|
575
|
-
thenResult = this._buildIfSchema(thenDsl.condition, targetField, thenDsl.then, thenDsl.else);
|
|
576
|
-
} else {
|
|
577
|
-
const thenSchema = this._resolveDsl(thenDsl);
|
|
578
|
-
const thenRequired = thenSchema._required;
|
|
579
|
-
this._cleanRequiredMarks(thenSchema);
|
|
580
|
-
thenResult = { properties: { [targetField]: thenSchema } };
|
|
581
|
-
if (thenRequired) thenResult.required = [targetField];
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
// 处理 else 分支
|
|
585
|
-
let elseResult = {};
|
|
586
|
-
if (elseDsl) {
|
|
587
|
-
if (elseDsl._isMatch) {
|
|
588
|
-
// else 也是一个 Match 结构
|
|
589
|
-
elseResult = this._buildMatchSchema(elseDsl.field, targetField, elseDsl.map);
|
|
590
|
-
} else if (elseDsl._isIf) {
|
|
591
|
-
// else 也是一个 If 结构
|
|
592
|
-
elseResult = this._buildIfSchema(elseDsl.condition, targetField, elseDsl.then, elseDsl.else);
|
|
593
|
-
} else {
|
|
594
|
-
const elseSchema = this._resolveDsl(elseDsl);
|
|
595
|
-
const elseRequired = elseSchema._required;
|
|
596
|
-
this._cleanRequiredMarks(elseSchema);
|
|
597
|
-
elseResult = { properties: { [targetField]: elseSchema } };
|
|
598
|
-
if (elseRequired) elseResult.required = [targetField];
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
// 默认行为:检查字段值为 true (适用于 isVip: boolean)
|
|
603
|
-
return {
|
|
604
|
-
if: { properties: { [conditionField]: { const: true } } },
|
|
605
|
-
then: thenResult,
|
|
606
|
-
else: elseResult
|
|
607
|
-
};
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
/**
|
|
611
|
-
* 解析对象为Schema(旧版本,兼容)
|
|
612
|
-
* @static
|
|
613
|
-
* @param {Object} dslObject - DSL对象定义
|
|
614
|
-
* @returns {Object} JSON Schema对象
|
|
615
|
-
*/
|
|
616
|
-
static parseObjectOld(dslObject) {
|
|
617
|
-
if (!dslObject || typeof dslObject !== 'object') {
|
|
618
|
-
throw new Error('DSL object must be an object');
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
const schema = {
|
|
622
|
-
type: 'object',
|
|
623
|
-
properties: {},
|
|
624
|
-
required: []
|
|
625
|
-
};
|
|
626
|
-
|
|
627
|
-
for (const [key, value] of Object.entries(dslObject)) {
|
|
628
|
-
if (typeof value === 'string') {
|
|
629
|
-
const parsed = this.parse(value);
|
|
630
|
-
|
|
631
|
-
// 处理必填标记
|
|
632
|
-
if (parsed._required) {
|
|
633
|
-
schema.required.push(key);
|
|
634
|
-
delete parsed._required; // 清理临时标记
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
// 清理所有_required标记(包括嵌套的)
|
|
638
|
-
this._cleanRequiredMarks(parsed);
|
|
639
|
-
|
|
640
|
-
schema.properties[key] = parsed;
|
|
641
|
-
} else if (typeof value === 'object') {
|
|
642
|
-
// 嵌套对象
|
|
643
|
-
schema.properties[key] = this.parseObject(value);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
if (schema.required.length === 0) {
|
|
648
|
-
delete schema.required;
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
return schema;
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
/**
|
|
655
|
-
* 清理Schema中的临时标记
|
|
656
|
-
* @private
|
|
657
|
-
* @static
|
|
658
|
-
* @param {Object} schema - Schema对象
|
|
659
|
-
*/
|
|
660
|
-
static _cleanRequiredMarks(schema) {
|
|
661
|
-
if (!schema || typeof schema !== 'object') {
|
|
662
|
-
return;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
// 只删除 _required 标记,保留其他扩展属性(如 _customValidators)
|
|
666
|
-
// 这些属性将由自定义关键字处理
|
|
667
|
-
delete schema._required;
|
|
668
|
-
|
|
669
|
-
// 递归处理properties
|
|
670
|
-
if (schema.properties) {
|
|
671
|
-
for (const prop of Object.values(schema.properties)) {
|
|
672
|
-
this._cleanRequiredMarks(prop);
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
// 递归处理items
|
|
677
|
-
if (schema.items) {
|
|
678
|
-
this._cleanRequiredMarks(schema.items);
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
/**
|
|
683
|
-
* 转换为JSONSchemaCore实例
|
|
684
|
-
* @static
|
|
685
|
-
* @param {string|Object} dsl - DSL字符串或对象
|
|
686
|
-
* @returns {JSONSchemaCore} JSONSchemaCore实例
|
|
687
|
-
*/
|
|
688
|
-
static toCore(dsl) {
|
|
689
|
-
let schema;
|
|
690
|
-
if (typeof dsl === 'string') {
|
|
691
|
-
// 创建DslBuilder并转为Schema
|
|
692
|
-
const builder = new DslBuilder(dsl);
|
|
693
|
-
schema = builder.toSchema();
|
|
694
|
-
} else {
|
|
695
|
-
schema = this.parseObject(dsl);
|
|
696
|
-
}
|
|
697
|
-
return new JSONSchemaCore(schema);
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
// ========== 导出统一API ==========
|
|
702
|
-
|
|
703
|
-
/**
|
|
704
|
-
* DSL函数 - 统一入口
|
|
705
|
-
* @param {string|Object} definition - DSL字符串或对象定义
|
|
706
|
-
* @returns {DslBuilder|Object} DslBuilder实例或JSON Schema对象
|
|
707
|
-
*
|
|
708
|
-
* @example
|
|
709
|
-
* // 字符串:返回 DslBuilder(可链式调用)
|
|
710
|
-
* const schema = dsl('email!')
|
|
711
|
-
* .pattern(/custom/)
|
|
712
|
-
* .messages({ 'string.pattern': '格式不正确' });
|
|
713
|
-
*
|
|
714
|
-
* // 对象:返回 JSON Schema
|
|
715
|
-
* const schema = dsl({
|
|
716
|
-
* username: 'string:3-32!',
|
|
717
|
-
* email: dsl('email!').label('邮箱')
|
|
718
|
-
* });
|
|
719
|
-
*/
|
|
720
|
-
function dsl(definition) {
|
|
721
|
-
// 字符串:返回 DslBuilder
|
|
722
|
-
if (typeof definition === 'string') {
|
|
723
|
-
return new DslBuilder(definition);
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
// 对象:解析对象Schema
|
|
727
|
-
if (typeof definition === 'object' && !Array.isArray(definition)) {
|
|
728
|
-
return DslAdapter.parseObject(definition);
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
throw new Error('Invalid DSL definition: must be string or object');
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
/**
|
|
735
|
-
* 便捷验证函数(同步)
|
|
736
|
-
*
|
|
737
|
-
* @param {Object|DslBuilder|string} schema - JSON Schema、DslBuilder实例或DSL对象
|
|
738
|
-
* @param {*} data - 待验证数据
|
|
739
|
-
* @param {Object} options - 验证选项
|
|
740
|
-
* @returns {Object} 验证结果 { valid, errors, data }
|
|
741
|
-
*
|
|
742
|
-
* @example
|
|
743
|
-
* // 方式1:传入 JSON Schema
|
|
744
|
-
* const result1 = validate({ type: 'object', properties: {...} }, data);
|
|
745
|
-
*
|
|
746
|
-
* // 方式2:传入 DslBuilder 实例
|
|
747
|
-
* const result2 = validate(dsl('email!'), data);
|
|
748
|
-
*
|
|
749
|
-
* // 方式3:传入 DSL 对象(自动转换)
|
|
750
|
-
* const result3 = validate({ email: 'email!', age: 'number!' }, data);
|
|
751
|
-
*/
|
|
752
|
-
function validate(schema, data, options = {}) {
|
|
753
|
-
const Validator = require('../core/Validator');
|
|
754
|
-
|
|
755
|
-
// ✅ 自动检测并转换 DSL 对象
|
|
756
|
-
if (_isDslObject(schema)) {
|
|
757
|
-
schema = DslAdapter.parseObject(schema);
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
const validator = new Validator(options);
|
|
761
|
-
return validator.validate(schema, data, options);
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
/**
|
|
765
|
-
* 检测是否为 DSL 对象
|
|
766
|
-
* @private
|
|
767
|
-
* @param {*} obj - 待检测对象
|
|
768
|
-
* @returns {boolean}
|
|
769
|
-
*/
|
|
770
|
-
function _isDslObject(obj) {
|
|
771
|
-
// 不是普通对象,直接返回 false
|
|
772
|
-
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
|
|
773
|
-
return false;
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
// 如果有 toSchema 方法,是 DslBuilder,不是 DSL 对象
|
|
777
|
-
if (typeof obj.toSchema === 'function') {
|
|
778
|
-
return false;
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
// 如果有 _isConditional 标记,是 ConditionalBuilder
|
|
782
|
-
if (obj._isConditional) {
|
|
783
|
-
return false;
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
// 如果有标准 JSON Schema 的 type 字段,认为是 JSON Schema
|
|
787
|
-
if (obj.type && ['string', 'number', 'integer', 'boolean', 'object', 'array', 'null'].includes(obj.type)) {
|
|
788
|
-
return false;
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
// 如果有 properties 但所有属性值都是 JSON Schema 对象(包含 type),认为是 JSON Schema
|
|
792
|
-
if (obj.properties && typeof obj.properties === 'object') {
|
|
793
|
-
const allStandardSchema = Object.values(obj.properties).every(prop =>
|
|
794
|
-
prop && typeof prop === 'object' && prop.type
|
|
795
|
-
);
|
|
796
|
-
if (allStandardSchema) {
|
|
797
|
-
return false;
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
|
|
801
|
-
const values = Object.values(obj);
|
|
802
|
-
|
|
803
|
-
// ✅ 检查是否有 DslBuilder 实例(有 toSchema 方法的对象)
|
|
804
|
-
const hasDslBuilder = values.some(v =>
|
|
805
|
-
v && typeof v === 'object' && typeof v.toSchema === 'function'
|
|
806
|
-
);
|
|
807
|
-
|
|
808
|
-
if (hasDslBuilder) {
|
|
809
|
-
return true;
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
// 检查是否有 DSL 格式的字符串值(如 'email!', 'string:3-32')
|
|
813
|
-
const hasDslString = values.some(v =>
|
|
814
|
-
typeof v === 'string' && (
|
|
815
|
-
v.includes(':') || v.includes('!') || v.includes('|') ||
|
|
816
|
-
['email', 'url', 'uuid', 'date', 'datetime', 'time', 'phone', 'objectId'].includes(v.split(':')[0].replace('!', ''))
|
|
817
|
-
)
|
|
818
|
-
);
|
|
819
|
-
|
|
820
|
-
if (hasDslString) {
|
|
821
|
-
return true;
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
// 检查是否有嵌套的 DSL 对象
|
|
825
|
-
const hasNestedDslObject = values.some(v => _isDslObject(v));
|
|
826
|
-
|
|
827
|
-
return hasNestedDslObject;
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
/**
|
|
831
|
-
* 便捷异步验证函数
|
|
832
|
-
*
|
|
833
|
-
* @param {Object|DslBuilder|string} schema - JSON Schema、DslBuilder实例或DSL对象
|
|
834
|
-
* @param {*} data - 待验证数据
|
|
835
|
-
* @param {Object} options - 验证选项
|
|
836
|
-
* @returns {Promise<*>} 验证通过返回数据
|
|
837
|
-
* @throws {ValidationError} 验证失败抛出异常
|
|
838
|
-
*
|
|
839
|
-
* @example
|
|
840
|
-
* try {
|
|
841
|
-
* // 方式1:传入 JSON Schema
|
|
842
|
-
* const data1 = await validateAsync({ type: 'object', properties: {...} }, inputData);
|
|
843
|
-
*
|
|
844
|
-
* // 方式2:传入 DSL 对象(自动转换)
|
|
845
|
-
* const data2 = await validateAsync({ email: 'email!', age: 'number!' }, inputData);
|
|
846
|
-
*
|
|
847
|
-
* console.log('验证通过:', data);
|
|
848
|
-
* } catch (error) {
|
|
849
|
-
* if (error instanceof ValidationError) {
|
|
850
|
-
* console.error('验证失败:', error.errors);
|
|
851
|
-
* }
|
|
852
|
-
* }
|
|
853
|
-
*/
|
|
854
|
-
async function validateAsync(schema, data, options = {}) {
|
|
855
|
-
const Validator = require('../core/Validator');
|
|
856
|
-
|
|
857
|
-
// ✅ 自动检测并转换 DSL 对象
|
|
858
|
-
if (_isDslObject(schema)) {
|
|
859
|
-
schema = DslAdapter.parseObject(schema);
|
|
860
|
-
}
|
|
861
|
-
|
|
862
|
-
const validator = new Validator(options);
|
|
863
|
-
return validator.validateAsync(schema, data, options);
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
// 导出
|
|
867
|
-
module.exports = dsl;
|
|
868
|
-
module.exports.DslAdapter = DslAdapter;
|
|
869
|
-
module.exports.DslBuilder = DslBuilder;
|
|
870
|
-
module.exports.validate = validate;
|
|
871
|
-
module.exports.validateAsync = validateAsync;
|