schema-dsl 2.0.0 → 2.0.1

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.
Files changed (145) hide show
  1. package/CHANGELOG.md +130 -113
  2. package/LICENSE +21 -21
  3. package/README.md +628 -628
  4. package/dist/{DslBuilder-DkLaOo9Q.d.ts → DslBuilder-BIgQOAXp.d.ts} +2 -0
  5. package/dist/{DslBuilder-DQDN0ZxZ.d.cts → DslBuilder-CjHTucNQ.d.cts} +2 -0
  6. package/dist/{Validator-hFWKGxir.d.ts → Validator-CllRdrY0.d.ts} +1 -1
  7. package/dist/{Validator-C7GsVQOH.d.cts → Validator-D6okG9tr.d.cts} +1 -1
  8. package/dist/index.cjs +75 -29
  9. package/dist/index.d.cts +10 -4
  10. package/dist/index.d.ts +10 -4
  11. package/dist/index.js +75 -29
  12. package/dist/plugins/custom-format.cjs +33 -17
  13. package/dist/plugins/custom-format.d.cts +1 -1
  14. package/dist/plugins/custom-format.d.ts +1 -1
  15. package/dist/plugins/custom-format.js +33 -17
  16. package/dist/plugins/custom-type-example.cjs +33 -17
  17. package/dist/plugins/custom-type-example.d.cts +1 -1
  18. package/dist/plugins/custom-type-example.d.ts +1 -1
  19. package/dist/plugins/custom-type-example.js +33 -17
  20. package/dist/plugins/custom-validator.cjs +0 -2
  21. package/dist/plugins/custom-validator.d.cts +1 -1
  22. package/dist/plugins/custom-validator.d.ts +1 -1
  23. package/dist/plugins/custom-validator.js +0 -2
  24. package/docs/FEATURE-INDEX.md +553 -553
  25. package/docs/add-custom-locale.md +496 -496
  26. package/docs/add-keyword.md +24 -24
  27. package/docs/api-reference.md +1047 -1047
  28. package/docs/api.md +13 -13
  29. package/docs/best-practices-project-structure.md +417 -417
  30. package/docs/best-practices.md +712 -712
  31. package/docs/cache-manager.md +344 -344
  32. package/docs/compile.md +45 -45
  33. package/docs/conditional-api.md +1307 -1307
  34. package/docs/custom-extensions-guide.md +339 -339
  35. package/docs/design-philosophy.md +606 -606
  36. package/docs/doc-index.md +324 -324
  37. package/docs/dsl-syntax.md +714 -714
  38. package/docs/dynamic-locale.md +608 -608
  39. package/docs/enum.md +482 -482
  40. package/docs/error-handling.md +1975 -1975
  41. package/docs/export-guide.md +501 -501
  42. package/docs/export-limitations.md +567 -567
  43. package/docs/faq.md +596 -596
  44. package/docs/frontend-i18n-guide.md +307 -307
  45. package/docs/i18n-user-guide.md +487 -487
  46. package/docs/i18n.md +476 -476
  47. package/docs/index.md +48 -48
  48. package/docs/json-schema-basics.md +40 -40
  49. package/docs/label-vs-description.md +271 -271
  50. package/docs/markdown-exporter.md +406 -406
  51. package/docs/mongodb-exporter.md +302 -302
  52. package/docs/multi-language.md +26 -26
  53. package/docs/multi-type-support.md +322 -322
  54. package/docs/mysql-exporter.md +280 -280
  55. package/docs/number-operators.md +449 -449
  56. package/docs/optional-marker-guide.md +326 -326
  57. package/docs/performance-guide.md +49 -49
  58. package/docs/plugin-system.md +381 -381
  59. package/docs/plugin-type-registration.md +34 -34
  60. package/docs/postgresql-exporter.md +311 -311
  61. package/docs/public/favicon.svg +4 -4
  62. package/docs/quick-start.md +435 -435
  63. package/docs/runtime-locale-support.md +532 -532
  64. package/docs/schema-helper.md +345 -345
  65. package/docs/schema-utils-advanced-issues.md +23 -23
  66. package/docs/schema-utils-best-practices.md +20 -20
  67. package/docs/schema-utils-chaining.md +150 -150
  68. package/docs/schema-utils.md +524 -524
  69. package/docs/security-checklist.md +20 -20
  70. package/docs/string-extensions.md +488 -488
  71. package/docs/troubleshooting.md +486 -486
  72. package/docs/type-converter.md +310 -310
  73. package/docs/type-reference.md +242 -242
  74. package/docs/typescript-guide.md +584 -584
  75. package/docs/union-type-guide.md +157 -157
  76. package/docs/union-types.md +284 -284
  77. package/docs/validate-async.md +491 -491
  78. package/docs/validate-batch.md +49 -49
  79. package/docs/validate-dsl-object-support.md +578 -578
  80. package/docs/validate.md +506 -506
  81. package/docs/validation-guide.md +502 -502
  82. package/docs/validator.md +39 -39
  83. package/package.json +131 -131
  84. package/plugins/custom-format.cjs +8 -8
  85. package/plugins/custom-type-example.cjs +8 -8
  86. package/plugins/custom-validator.cjs +8 -8
  87. package/src/adapters/DslAdapter.ts +111 -111
  88. package/src/adapters/index.ts +1 -1
  89. package/src/config/constants.ts +83 -83
  90. package/src/config/index.ts +2 -2
  91. package/src/config/patterns.ts +77 -77
  92. package/src/core/CacheManager.ts +169 -159
  93. package/src/core/ConditionalBuilder.ts +382 -382
  94. package/src/core/ConditionalRuntime.ts +27 -27
  95. package/src/core/ConditionalValidator.ts +254 -254
  96. package/src/core/DslBuilder.ts +687 -677
  97. package/src/core/ErrorCodes.ts +38 -38
  98. package/src/core/ErrorFormatter.ts +271 -271
  99. package/src/core/JSONSchemaCore.ts +65 -65
  100. package/src/core/Locale.ts +187 -187
  101. package/src/core/MessageTemplate.ts +42 -42
  102. package/src/core/ObjectDslBuilder.ts +64 -64
  103. package/src/core/PluginManager.ts +326 -326
  104. package/src/core/StringExtensions.ts +140 -140
  105. package/src/core/TemplateEngine.ts +44 -44
  106. package/src/core/Validator.ts +448 -448
  107. package/src/errors/I18nError.ts +159 -159
  108. package/src/errors/ValidationError.ts +105 -105
  109. package/src/exporters/BaseExporter.ts +60 -60
  110. package/src/exporters/MarkdownExporter.ts +305 -305
  111. package/src/exporters/MongoDBExporter.ts +126 -126
  112. package/src/exporters/MySQLExporter.ts +156 -155
  113. package/src/exporters/PostgreSQLExporter.ts +222 -222
  114. package/src/exporters/index.ts +18 -18
  115. package/src/index.ts +651 -633
  116. package/src/locales/en-US.ts +160 -160
  117. package/src/locales/es-ES.ts +160 -160
  118. package/src/locales/fr-FR.ts +160 -160
  119. package/src/locales/index.ts +103 -103
  120. package/src/locales/ja-JP.ts +160 -160
  121. package/src/locales/types.ts +156 -156
  122. package/src/locales/zh-CN.ts +160 -160
  123. package/src/parser/ConstraintParser.ts +101 -101
  124. package/src/parser/DslParser.ts +470 -470
  125. package/src/parser/SchemaCompiler.ts +66 -66
  126. package/src/parser/TypeRegistry.ts +250 -250
  127. package/src/parser/index.ts +6 -6
  128. package/src/plugins/custom-format.ts +124 -126
  129. package/src/plugins/custom-type-example.ts +106 -108
  130. package/src/plugins/custom-validator.ts +138 -140
  131. package/src/types/conditional.ts +28 -28
  132. package/src/types/config.ts +59 -59
  133. package/src/types/dsl.ts +131 -131
  134. package/src/types/error.ts +60 -60
  135. package/src/types/index.ts +17 -17
  136. package/src/types/infer.ts +127 -127
  137. package/src/types/plugin.ts +58 -58
  138. package/src/types/safe-regex.d.ts +9 -9
  139. package/src/types/schema.ts +66 -66
  140. package/src/types/validate.ts +71 -71
  141. package/src/utils/SchemaHelper.ts +196 -196
  142. package/src/utils/SchemaUtils.ts +365 -346
  143. package/src/utils/TypeConverter.ts +215 -215
  144. package/src/utils/index.ts +10 -10
  145. package/src/validators/CustomKeywords.ts +477 -477
@@ -1,448 +1,448 @@
1
- import { Ajv } from 'ajv'
2
- import type { ValidateFunction, KeywordDefinition, Format } from 'ajv'
3
- import addFormats from 'ajv-formats'
4
- import type { JSONSchema } from '../types/schema.js'
5
- import type { ValidateOptions, ValidationResult, ValidationErrorItem } from '../types/validate.js'
6
- import type { ErrorMessages } from '../types/error.js'
7
- import { CacheManager } from './CacheManager.js'
8
- import type { CacheStats } from './CacheManager.js'
9
- import { ErrorFormatter } from './ErrorFormatter.js'
10
- import { CustomKeywords } from '../validators/CustomKeywords.js'
11
- import { Locale } from './Locale.js'
12
- import { ConditionalValidator, type ConditionalInternalSchema } from './ConditionalValidator.js'
13
-
14
- // Non-AJV custom option keys (V-Y01 fix: filter before passing to new Ajv())
15
- const NON_AJV_KEYS = new Set([
16
- 'cache', 'smartCoerce', 'locale', 'messages', 'format',
17
- 'strict', // v2 redefines this as strictSchema; do not forward to AJV
18
- ])
19
-
20
- // AJV ValidateFunction type
21
- type AjvValidateFn = ValidateFunction
22
- type KeywordDefinitionInput = KeywordDefinition | ({ keyword?: string;[key: string]: unknown })
23
-
24
- // Schema with _removeAdditional or _isConditional internal markers
25
- type InternalSchema = JSONSchema & {
26
- _removeAdditional?: boolean
27
- _isConditional?: boolean
28
- _runtimeOnlyConditional?: boolean
29
- } & ConditionalInternalSchema
30
-
31
- // Performance: share empty array on valid path to avoid `{ errors: [] }` allocation every time
32
- const EMPTY_ERRORS: ValidationErrorItem[] = []
33
-
34
- /**
35
- * ValidatorOptions — constructor options for Validator (extends AJV base options).
36
- */
37
- export interface ValidatorOptions {
38
- allErrors?: boolean
39
- useDefaults?: boolean
40
- coerceTypes?: boolean | 'array'
41
- removeAdditional?: boolean | 'all' | 'failing'
42
- verbose?: boolean
43
- cache?: boolean | {
44
- maxSize?: number
45
- ttl?: number
46
- enabled?: boolean
47
- statsEnabled?: boolean
48
- }
49
- [key: string]: unknown
50
- }
51
-
52
- /**
53
- * Validator — AJV-backed validator (v2).
54
- *
55
- * Fixes:
56
- * V-Y01: filter non-AJV options before new Ajv() to prevent unknown-option warnings
57
- * V-02: sync cleanSchema.required when conditional fields are removed (v1 missed this)
58
- * V-Y03: _removeAdditional mode reuses cached internal Ajv instance (v1 created new Validator each time)
59
- * V-Y07: static quickValidate reuses a singleton Ajv (v1 created new Ajv each time)
60
- */
61
- export class Validator {
62
- private readonly _ajvOptions: Record<string, unknown>
63
- private readonly _ajv: InstanceType<typeof Ajv>
64
- private readonly _cache: CacheManager
65
- private readonly _errorFormatter: ErrorFormatter
66
-
67
- // WeakMap: schema object → unique cacheKey (avoids JSON.stringify)
68
- private readonly _schemaMap = new WeakMap<object, string>()
69
- private _schemaKeyCounter = 0
70
-
71
- // Performance: cache whether a schema has any conditional fields (avoids traversing properties on every validation)
72
- private readonly _conditionalFlagCache = new WeakMap<object, boolean>()
73
- private readonly _conditionalValidator = new ConditionalValidator({
74
- validateSchema: <T>(schema: JSONSchema, data: T, options: ValidateOptions): ValidationResult<T> => this._validateInternal(schema, data, options),
75
- internalError: <T>(error: unknown, data: T): ValidationResult<T> => this._internalError(error, data),
76
- })
77
-
78
- // V-Y03 fix: cached removeAdditional Ajv instance (no longer new Validator each time)
79
- private _removeAdditionalAjv: InstanceType<typeof Ajv> | null = null
80
-
81
- // V-Y07 fix: static singleton Ajv
82
- private static _quickValidateAjv: InstanceType<typeof Ajv> | null = null
83
-
84
- constructor(options: ValidatorOptions = {}) {
85
- // V-Y01 fix: filter non-AJV options
86
- const ajvOptions: Record<string, unknown> = {
87
- allErrors: options.allErrors !== false,
88
- useDefaults: options.useDefaults !== false,
89
- coerceTypes: options.coerceTypes ?? false,
90
- removeAdditional: options.removeAdditional ?? false,
91
- verbose: true, // verbose mode: enables parentSchema access on error objects
92
- }
93
-
94
- // Forward remaining valid AJV options
95
- for (const [k, v] of Object.entries(options)) {
96
- if (!NON_AJV_KEYS.has(k) && !(k in ajvOptions)) {
97
- ajvOptions[k] = v
98
- }
99
- }
100
-
101
- this._ajvOptions = ajvOptions
102
- this._ajv = new Ajv(ajvOptions)
103
- ; (addFormats as unknown as (a: InstanceType<typeof Ajv>) => void)(this._ajv)
104
- CustomKeywords.registerAll(this._ajv)
105
-
106
- const cacheOpts = options.cache === false
107
- ? { enabled: false }
108
- : options.cache === true || options.cache == null
109
- ? {}
110
- : options.cache
111
-
112
- this._cache = new CacheManager({
113
- ...(cacheOpts.maxSize !== undefined ? { maxSize: cacheOpts.maxSize } : {}),
114
- ...(cacheOpts.ttl !== undefined ? { ttl: cacheOpts.ttl } : {}),
115
- ...(cacheOpts.enabled !== undefined ? { enabled: cacheOpts.enabled } : {}),
116
- ...(cacheOpts.statsEnabled !== undefined ? { statsEnabled: cacheOpts.statsEnabled } : {}),
117
- })
118
-
119
- this._errorFormatter = new ErrorFormatter()
120
- }
121
-
122
- get ajvOptions(): Record<string, unknown> {
123
- return this._ajvOptions
124
- }
125
-
126
- // ─── Public API ────────────────────────────────────────────────────────
127
-
128
- /**
129
- * Compile a schema → AJV validate function (with cache).
130
- */
131
- compile(schema: JSONSchema, cacheKey?: string | null): AjvValidateFn {
132
- const key = cacheKey ?? null
133
-
134
- if (key) {
135
- const cached = this._cache.get(key) as AjvValidateFn | null
136
- if (cached !== null) return cached
137
- }
138
-
139
- try {
140
- const validate = this._ajv.compile(schema)
141
- if (key) this._cache.set(key, validate as unknown as object)
142
- return validate
143
- } catch (error) {
144
- throw new Error(`Schema compilation failed: ${error instanceof Error ? error.message : String(error)}`)
145
- }
146
- }
147
-
148
- /**
149
- * Synchronous validation.
150
- */
151
- validate<T = unknown>(schema: JSONSchema | AjvValidateFn, data: T, options: ValidateOptions = {}): ValidationResult<T> {
152
- return this._validateInternal(schema, data, options)
153
- }
154
-
155
- /**
156
- * Async validation (throws ValidationError on failure).
157
- * V-Y02 fix: v1 validateAsync lacked smartCoerceTypes; v2 routes through _validateInternal uniformly.
158
- * BC-6 fix: validateAsync runs async custom validators (sync AJV pass skips async fn; this method runs the full set).
159
- */
160
- async validateAsync<T = unknown>(schema: JSONSchema | AjvValidateFn, data: T, options: ValidateOptions = {}): Promise<T> {
161
- // Resolve DslBuilder/ObjectDslBuilder duck type to raw schema (mirrors _validateInternal logic)
162
- // so _runCustomValidators can access schema._customValidators
163
- let resolvedSchema = schema as JSONSchema
164
- if (typeof (schema as Record<string, unknown>)['toSchema'] === 'function') {
165
- const obj = schema as Record<string, unknown>
166
- resolvedSchema = (obj['toSchema'] as () => JSONSchema)()
167
- }
168
-
169
- const result = this._validateInternal(schema, data, options)
170
- if (!result.valid) {
171
- const { ValidationError } = await import('../errors/ValidationError.js')
172
- throw new ValidationError(result.errors ?? [], data)
173
- }
174
-
175
- // BC-6: run async custom validators (sync AJV pass skips Promise-returning validators)
176
- const customErr = await this._runCustomValidators(resolvedSchema, data)
177
- if (customErr) {
178
- const { ValidationError } = await import('../errors/ValidationError.js')
179
- throw new ValidationError([customErr], data)
180
- }
181
-
182
- return result.data as T
183
- }
184
-
185
- /**
186
- * BC-6: run all validators in schema._customValidators (including async).
187
- * AJV's sync keyword skips Promise-returning validators; this method runs the complete set in validateAsync.
188
- * Returns the first failing ValidationErrorItem, or null if all pass.
189
- */
190
- private async _runCustomValidators(schema: JSONSchema, data: unknown): Promise<ValidationErrorItem | null> {
191
- const validators = (schema as Record<string, unknown>)['_customValidators'] as Array<(v: unknown) => unknown> | undefined
192
- if (!validators?.length) return null
193
-
194
- for (const fn of validators) {
195
- try {
196
- const result = await Promise.resolve(fn(data))
197
- if (result === false) {
198
- return { message: Locale.getMessageText('CUSTOM_VALIDATION_FAILED'), path: '', keyword: '_customValidators', params: {} }
199
- }
200
- if (typeof result === 'string') {
201
- return { message: result, path: '', keyword: '_customValidators', params: {} }
202
- }
203
- if (result !== null && typeof result === 'object' && (result as Record<string, unknown>)['error']) {
204
- const r = result as { error: unknown; message?: string }
205
- return {
206
- message: r.message ?? Locale.getMessageText('CUSTOM_VALIDATION_FAILED'),
207
- path: '',
208
- keyword: '_customValidators',
209
- params: {},
210
- }
211
- }
212
- } catch (err) {
213
- return {
214
- message: err instanceof Error ? err.message : String(err),
215
- path: '',
216
- keyword: '_customValidators',
217
- params: {},
218
- }
219
- }
220
- }
221
- return null
222
- }
223
-
224
- /**
225
- * Batch validation (compile once, reuse for each item).
226
- */
227
- validateBatch<T = unknown>(schema: JSONSchema, dataArray: T[]): ValidationResult<T>[] {
228
- if (!Array.isArray(dataArray)) throw new Error('Data must be an array')
229
- const cacheKey = this._generateCacheKey(schema)
230
- const validate = this.compile(schema, cacheKey)
231
- return dataArray.map(data => this.validate(validate, data))
232
- }
233
-
234
- /**
235
- * Add a custom keyword.
236
- */
237
- addKeyword(keyword: string, definition: KeywordDefinitionInput): this {
238
- try {
239
- this._ajv.addKeyword({
240
- ...definition,
241
- keyword,
242
- })
243
- return this
244
- } catch (error) {
245
- throw new Error(`Failed to add keyword '${keyword}': ${error instanceof Error ? error.message : String(error)}`)
246
- }
247
- }
248
-
249
- /**
250
- * Add a custom format.
251
- */
252
- addFormat(name: string, validator: Format): this {
253
- this._ajv.addFormat(name, validator)
254
- return this
255
- }
256
-
257
- /**
258
- * Add a schema reference.
259
- */
260
- addSchema(uri: string, schema: JSONSchema): this {
261
- this._ajv.addSchema(schema, uri)
262
- return this
263
- }
264
-
265
- /**
266
- * Remove a schema reference.
267
- */
268
- removeSchema(uri: string): this {
269
- this._ajv.removeSchema(uri)
270
- return this
271
- }
272
-
273
- getAjv(): InstanceType<typeof Ajv> { return this._ajv }
274
- get cache(): CacheManager { return this._cache }
275
- clearCache(): void { this._cache.clear() }
276
- getCacheStats(): CacheStats { return this._cache.getStats() }
277
-
278
- // ─── Static Factory ────────────────────────────────────────────────────
279
-
280
- static create(options?: ValidatorOptions): Validator {
281
- return new Validator(options)
282
- }
283
-
284
- /**
285
- * Quick validate (V-Y07 fix: reuses singleton Ajv instead of creating new Ajv each time).
286
- */
287
- static quickValidate(schema: JSONSchema, data: unknown): boolean {
288
- if (!Validator._quickValidateAjv) {
289
- Validator._quickValidateAjv = new Ajv()
290
- ; (addFormats as unknown as (a: InstanceType<typeof Ajv>) => void)(Validator._quickValidateAjv)
291
- CustomKeywords.registerAll(Validator._quickValidateAjv)
292
- }
293
- try {
294
- return Validator._quickValidateAjv.validate(schema, data) as boolean
295
- } catch {
296
- return false
297
- }
298
- }
299
-
300
- // ─── Internal Implementation ───────────────────────────────────────────
301
-
302
- private _validateInternal<T>(
303
- schema: JSONSchema | AjvValidateFn,
304
- data: T,
305
- options: ValidateOptions = {}
306
- ): ValidationResult<T> {
307
- const shouldFormat = options.format !== false
308
- const locale = options.locale ?? Locale.getLocale()
309
- const messages = (options.messages ?? {}) as ErrorMessages
310
-
311
- // DslBuilder/ObjectDslBuilder/ConditionalBuilder duck type.
312
- // Builders are mutable, so their toSchema() result must be re-materialized on every call.
313
- if (typeof (schema as Record<string, unknown>)['toSchema'] === 'function') {
314
- const obj = schema as Record<string, unknown>
315
- schema = (obj['toSchema'] as () => JSONSchema)()
316
- }
317
-
318
- const internalSchema = schema as InternalSchema
319
-
320
- // ConditionalBuilder (top-level)
321
- if (internalSchema._isConditional) {
322
- return this._conditionalValidator.validateConditional(internalSchema, data as Record<string, unknown>, null, data, options)
323
- }
324
-
325
- // Object schema containing ConditionalBuilder properties (including arbitrary nesting depth)
326
- if (internalSchema.properties) {
327
- // Performance: cache conditional detection result to avoid traversing properties on every validation
328
- let hasConditionals = this._conditionalFlagCache.get(internalSchema as object)
329
- if (hasConditionals === undefined) {
330
- hasConditionals = this._conditionalValidator.hasAnyConditional(internalSchema)
331
- this._conditionalFlagCache.set(internalSchema as object, hasConditionals)
332
- }
333
- if (hasConditionals) {
334
- return this._conditionalValidator.validateWithConditionals(internalSchema, data, options)
335
- }
336
- }
337
-
338
- // V-Y03 fix: _removeAdditional reuses internal Ajv instance
339
- if (internalSchema._removeAdditional) {
340
- if (!this._removeAdditionalAjv) {
341
- this._removeAdditionalAjv = new Ajv({ ...this._ajvOptions, removeAdditional: true })
342
- ; (addFormats as unknown as (a: InstanceType<typeof Ajv>) => void)(this._removeAdditionalAjv)
343
- CustomKeywords.registerAll(this._removeAdditionalAjv)
344
- }
345
-
346
- const cleanSchema: JSONSchema = JSON.parse(JSON.stringify(schema)) as JSONSchema
347
- delete (cleanSchema as InternalSchema)._removeAdditional
348
-
349
- try {
350
- const validate = this._removeAdditionalAjv.compile(cleanSchema)
351
- const valid = validate(data) as boolean
352
- if (valid) return { valid: true, data, errors: EMPTY_ERRORS }
353
- const fmtErrors = this._formatErrors(validate.errors ?? [], messages, locale, shouldFormat)
354
- return { valid: false, data, errors: fmtErrors, errorMessage: fmtErrors[0]?.message }
355
- } catch (error) {
356
- return this._internalError(error, data)
357
- }
358
- }
359
-
360
- try {
361
- let validate: AjvValidateFn
362
- if (typeof schema === 'function') {
363
- validate = schema as AjvValidateFn
364
- } else {
365
- // Performance: merge _generateCacheKey + compile() into a single WeakMap lookup
366
- const schemaObj = schema as object
367
- let cacheKey = this._schemaMap.get(schemaObj)
368
- if (!cacheKey) {
369
- cacheKey = `s${++this._schemaKeyCounter}`
370
- this._schemaMap.set(schemaObj, cacheKey)
371
- }
372
- const cached = this._cache.get(cacheKey) as AjvValidateFn | null
373
- if (cached !== null) {
374
- validate = cached
375
- } else {
376
- try {
377
- validate = this._ajv.compile(schema as JSONSchema)
378
- this._cache.set(cacheKey, validate as unknown as object)
379
- } catch (error) {
380
- throw new Error(`Schema compilation failed: ${error instanceof Error ? error.message : String(error)}`)
381
- }
382
- }
383
- }
384
-
385
- const valid = validate(data) as boolean
386
- if (valid) return { valid: true, data, errors: EMPTY_ERRORS }
387
- const fmtErrors2 = this._formatErrors(validate.errors ?? [], messages, locale, shouldFormat)
388
- return { valid: false, data, errors: fmtErrors2, errorMessage: fmtErrors2[0]?.message }
389
- } catch (error) {
390
- return this._internalError(error, data)
391
- }
392
- }
393
-
394
- // ─── Helper methods ─────────────────────────────────────────────────────
395
-
396
- private _generateCacheKey(schema: object): string {
397
- if (!this._schemaMap.has(schema)) {
398
- this._schemaMap.set(schema, `schema_${++this._schemaKeyCounter}`)
399
- }
400
- return this._schemaMap.get(schema)!
401
- }
402
-
403
- // Performance: cache flattened locale messages (key = locale, value = flat ErrorMessages)
404
- // to avoid re-running Locale.getMessages + Object.entries.map on every validation failure
405
- private readonly _flatLocaleCache = new Map<string, ErrorMessages>()
406
-
407
- private _getFlatLocaleMessages(locale: string): ErrorMessages {
408
- let flat = this._flatLocaleCache.get(locale)
409
- if (!flat) {
410
- const raw = Locale.getMessages(locale)
411
- flat = Object.fromEntries(
412
- Object.entries(raw).map(([k, v]) => [
413
- k,
414
- typeof v === 'string' ? v : (v as { message: string }).message,
415
- ])
416
- ) as ErrorMessages
417
- this._flatLocaleCache.set(locale, flat)
418
- }
419
- return flat
420
- }
421
-
422
- private _formatErrors(
423
- rawErrors: unknown[],
424
- messages: ErrorMessages,
425
- locale: string,
426
- shouldFormat: boolean
427
- ): ValidationErrorItem[] {
428
- if (!shouldFormat) return rawErrors as ValidationErrorItem[]
429
- const localeMessages = this._getFlatLocaleMessages(locale)
430
- // Only merge when there are custom messages (avoid unnecessary object spread)
431
- const mergedMessages: ErrorMessages =
432
- Object.keys(messages).length === 0
433
- ? localeMessages
434
- : { ...localeMessages, ...messages }
435
- // alreadyMerged=true: mergedMessages already contains locale+custom, skip re-expansion inside formatDetailed
436
- return this._errorFormatter.formatDetailed(rawErrors as Parameters<ErrorFormatter['formatDetailed']>[0], locale, mergedMessages, true)
437
- }
438
-
439
- private _internalError<T>(error: unknown, data: T): ValidationResult<T> {
440
- const message = `Validation error: ${error instanceof Error ? error.message : String(error)}`
441
- return {
442
- valid: false,
443
- data,
444
- errors: [{ message, path: '', keyword: 'error', params: {} }],
445
- errorMessage: message,
446
- }
447
- }
448
- }
1
+ import { Ajv } from 'ajv'
2
+ import type { ValidateFunction, KeywordDefinition, Format } from 'ajv'
3
+ import addFormats from 'ajv-formats'
4
+ import type { JSONSchema } from '../types/schema.js'
5
+ import type { ValidateOptions, ValidationResult, ValidationErrorItem } from '../types/validate.js'
6
+ import type { ErrorMessages } from '../types/error.js'
7
+ import { CacheManager } from './CacheManager.js'
8
+ import type { CacheStats } from './CacheManager.js'
9
+ import { ErrorFormatter } from './ErrorFormatter.js'
10
+ import { CustomKeywords } from '../validators/CustomKeywords.js'
11
+ import { Locale } from './Locale.js'
12
+ import { ConditionalValidator, type ConditionalInternalSchema } from './ConditionalValidator.js'
13
+
14
+ // Non-AJV custom option keys (V-Y01 fix: filter before passing to new Ajv())
15
+ const NON_AJV_KEYS = new Set([
16
+ 'cache', 'smartCoerce', 'locale', 'messages', 'format',
17
+ 'strict', // v2 redefines this as strictSchema; do not forward to AJV
18
+ ])
19
+
20
+ // AJV ValidateFunction type
21
+ type AjvValidateFn = ValidateFunction
22
+ type KeywordDefinitionInput = KeywordDefinition | ({ keyword?: string;[key: string]: unknown })
23
+
24
+ // Schema with _removeAdditional or _isConditional internal markers
25
+ type InternalSchema = JSONSchema & {
26
+ _removeAdditional?: boolean
27
+ _isConditional?: boolean
28
+ _runtimeOnlyConditional?: boolean
29
+ } & ConditionalInternalSchema
30
+
31
+ // Performance: share empty array on valid path to avoid `{ errors: [] }` allocation every time
32
+ const EMPTY_ERRORS: ValidationErrorItem[] = []
33
+
34
+ /**
35
+ * ValidatorOptions — constructor options for Validator (extends AJV base options).
36
+ */
37
+ export interface ValidatorOptions {
38
+ allErrors?: boolean
39
+ useDefaults?: boolean
40
+ coerceTypes?: boolean | 'array'
41
+ removeAdditional?: boolean | 'all' | 'failing'
42
+ verbose?: boolean
43
+ cache?: boolean | {
44
+ maxSize?: number
45
+ ttl?: number
46
+ enabled?: boolean
47
+ statsEnabled?: boolean
48
+ }
49
+ [key: string]: unknown
50
+ }
51
+
52
+ /**
53
+ * Validator — AJV-backed validator (v2).
54
+ *
55
+ * Fixes:
56
+ * V-Y01: filter non-AJV options before new Ajv() to prevent unknown-option warnings
57
+ * V-02: sync cleanSchema.required when conditional fields are removed (v1 missed this)
58
+ * V-Y03: _removeAdditional mode reuses cached internal Ajv instance (v1 created new Validator each time)
59
+ * V-Y07: static quickValidate reuses a singleton Ajv (v1 created new Ajv each time)
60
+ */
61
+ export class Validator {
62
+ private readonly _ajvOptions: Record<string, unknown>
63
+ private readonly _ajv: InstanceType<typeof Ajv>
64
+ private readonly _cache: CacheManager
65
+ private readonly _errorFormatter: ErrorFormatter
66
+
67
+ // WeakMap: schema object → unique cacheKey (avoids JSON.stringify)
68
+ private readonly _schemaMap = new WeakMap<object, string>()
69
+ private _schemaKeyCounter = 0
70
+
71
+ // Performance: cache whether a schema has any conditional fields (avoids traversing properties on every validation)
72
+ private readonly _conditionalFlagCache = new WeakMap<object, boolean>()
73
+ private readonly _conditionalValidator = new ConditionalValidator({
74
+ validateSchema: <T>(schema: JSONSchema, data: T, options: ValidateOptions): ValidationResult<T> => this._validateInternal(schema, data, options),
75
+ internalError: <T>(error: unknown, data: T): ValidationResult<T> => this._internalError(error, data),
76
+ })
77
+
78
+ // V-Y03 fix: cached removeAdditional Ajv instance (no longer new Validator each time)
79
+ private _removeAdditionalAjv: InstanceType<typeof Ajv> | null = null
80
+
81
+ // V-Y07 fix: static singleton Ajv
82
+ private static _quickValidateAjv: InstanceType<typeof Ajv> | null = null
83
+
84
+ constructor(options: ValidatorOptions = {}) {
85
+ // V-Y01 fix: filter non-AJV options
86
+ const ajvOptions: Record<string, unknown> = {
87
+ allErrors: options.allErrors !== false,
88
+ useDefaults: options.useDefaults !== false,
89
+ coerceTypes: options.coerceTypes ?? false,
90
+ removeAdditional: options.removeAdditional ?? false,
91
+ verbose: true, // verbose mode: enables parentSchema access on error objects
92
+ }
93
+
94
+ // Forward remaining valid AJV options
95
+ for (const [k, v] of Object.entries(options)) {
96
+ if (!NON_AJV_KEYS.has(k) && !(k in ajvOptions)) {
97
+ ajvOptions[k] = v
98
+ }
99
+ }
100
+
101
+ this._ajvOptions = ajvOptions
102
+ this._ajv = new Ajv(ajvOptions)
103
+ ; (addFormats as unknown as (a: InstanceType<typeof Ajv>) => void)(this._ajv)
104
+ CustomKeywords.registerAll(this._ajv)
105
+
106
+ const cacheOpts = options.cache === false
107
+ ? { enabled: false }
108
+ : options.cache === true || options.cache == null
109
+ ? {}
110
+ : options.cache
111
+
112
+ this._cache = new CacheManager({
113
+ ...(cacheOpts.maxSize !== undefined ? { maxSize: cacheOpts.maxSize } : {}),
114
+ ...(cacheOpts.ttl !== undefined ? { ttl: cacheOpts.ttl } : {}),
115
+ ...(cacheOpts.enabled !== undefined ? { enabled: cacheOpts.enabled } : {}),
116
+ ...(cacheOpts.statsEnabled !== undefined ? { statsEnabled: cacheOpts.statsEnabled } : {}),
117
+ })
118
+
119
+ this._errorFormatter = new ErrorFormatter()
120
+ }
121
+
122
+ get ajvOptions(): Record<string, unknown> {
123
+ return this._ajvOptions
124
+ }
125
+
126
+ // ─── Public API ────────────────────────────────────────────────────────
127
+
128
+ /**
129
+ * Compile a schema → AJV validate function (with cache).
130
+ */
131
+ compile(schema: JSONSchema, cacheKey?: string | null): AjvValidateFn {
132
+ const key = cacheKey ?? null
133
+
134
+ if (key) {
135
+ const cached = this._cache.get(key) as AjvValidateFn | null
136
+ if (cached !== null) return cached
137
+ }
138
+
139
+ try {
140
+ const validate = this._ajv.compile(schema)
141
+ if (key) this._cache.set(key, validate as unknown as object)
142
+ return validate
143
+ } catch (error) {
144
+ throw new Error(`Schema compilation failed: ${error instanceof Error ? error.message : String(error)}`)
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Synchronous validation.
150
+ */
151
+ validate<T = unknown>(schema: JSONSchema | AjvValidateFn, data: T, options: ValidateOptions = {}): ValidationResult<T> {
152
+ return this._validateInternal(schema, data, options)
153
+ }
154
+
155
+ /**
156
+ * Async validation (throws ValidationError on failure).
157
+ * V-Y02 fix: v1 validateAsync lacked smartCoerceTypes; v2 routes through _validateInternal uniformly.
158
+ * BC-6 fix: validateAsync runs async custom validators (sync AJV pass skips async fn; this method runs the full set).
159
+ */
160
+ async validateAsync<T = unknown>(schema: JSONSchema | AjvValidateFn, data: T, options: ValidateOptions = {}): Promise<T> {
161
+ // Resolve DslBuilder/ObjectDslBuilder duck type to raw schema (mirrors _validateInternal logic)
162
+ // so _runCustomValidators can access schema._customValidators
163
+ let resolvedSchema = schema as JSONSchema
164
+ if (typeof (schema as Record<string, unknown>)['toSchema'] === 'function') {
165
+ const obj = schema as Record<string, unknown>
166
+ resolvedSchema = (obj['toSchema'] as () => JSONSchema)()
167
+ }
168
+
169
+ const result = this._validateInternal(schema, data, options)
170
+ if (!result.valid) {
171
+ const { ValidationError } = await import('../errors/ValidationError.js')
172
+ throw new ValidationError(result.errors ?? [], data)
173
+ }
174
+
175
+ // BC-6: run async custom validators (sync AJV pass skips Promise-returning validators)
176
+ const customErr = await this._runCustomValidators(resolvedSchema, data)
177
+ if (customErr) {
178
+ const { ValidationError } = await import('../errors/ValidationError.js')
179
+ throw new ValidationError([customErr], data)
180
+ }
181
+
182
+ return result.data as T
183
+ }
184
+
185
+ /**
186
+ * BC-6: run all validators in schema._customValidators (including async).
187
+ * AJV's sync keyword skips Promise-returning validators; this method runs the complete set in validateAsync.
188
+ * Returns the first failing ValidationErrorItem, or null if all pass.
189
+ */
190
+ private async _runCustomValidators(schema: JSONSchema, data: unknown): Promise<ValidationErrorItem | null> {
191
+ const validators = (schema as Record<string, unknown>)['_customValidators'] as Array<(v: unknown) => unknown> | undefined
192
+ if (!validators?.length) return null
193
+
194
+ for (const fn of validators) {
195
+ try {
196
+ const result = await Promise.resolve(fn(data))
197
+ if (result === false) {
198
+ return { message: Locale.getMessageText('CUSTOM_VALIDATION_FAILED'), path: '', keyword: '_customValidators', params: {} }
199
+ }
200
+ if (typeof result === 'string') {
201
+ return { message: result, path: '', keyword: '_customValidators', params: {} }
202
+ }
203
+ if (result !== null && typeof result === 'object' && (result as Record<string, unknown>)['error']) {
204
+ const r = result as { error: unknown; message?: string }
205
+ return {
206
+ message: r.message ?? Locale.getMessageText('CUSTOM_VALIDATION_FAILED'),
207
+ path: '',
208
+ keyword: '_customValidators',
209
+ params: {},
210
+ }
211
+ }
212
+ } catch (err) {
213
+ return {
214
+ message: err instanceof Error ? err.message : String(err),
215
+ path: '',
216
+ keyword: '_customValidators',
217
+ params: {},
218
+ }
219
+ }
220
+ }
221
+ return null
222
+ }
223
+
224
+ /**
225
+ * Batch validation (compile once, reuse for each item).
226
+ */
227
+ validateBatch<T = unknown>(schema: JSONSchema, dataArray: T[]): ValidationResult<T>[] {
228
+ if (!Array.isArray(dataArray)) throw new Error('Data must be an array')
229
+ const cacheKey = this._generateCacheKey(schema)
230
+ const validate = this.compile(schema, cacheKey)
231
+ return dataArray.map(data => this.validate(validate, data))
232
+ }
233
+
234
+ /**
235
+ * Add a custom keyword.
236
+ */
237
+ addKeyword(keyword: string, definition: KeywordDefinitionInput): this {
238
+ try {
239
+ this._ajv.addKeyword({
240
+ ...definition,
241
+ keyword,
242
+ })
243
+ return this
244
+ } catch (error) {
245
+ throw new Error(`Failed to add keyword '${keyword}': ${error instanceof Error ? error.message : String(error)}`)
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Add a custom format.
251
+ */
252
+ addFormat(name: string, validator: Format): this {
253
+ this._ajv.addFormat(name, validator)
254
+ return this
255
+ }
256
+
257
+ /**
258
+ * Add a schema reference.
259
+ */
260
+ addSchema(uri: string, schema: JSONSchema): this {
261
+ this._ajv.addSchema(schema, uri)
262
+ return this
263
+ }
264
+
265
+ /**
266
+ * Remove a schema reference.
267
+ */
268
+ removeSchema(uri: string): this {
269
+ this._ajv.removeSchema(uri)
270
+ return this
271
+ }
272
+
273
+ getAjv(): InstanceType<typeof Ajv> { return this._ajv }
274
+ get cache(): CacheManager { return this._cache }
275
+ clearCache(): void { this._cache.clear() }
276
+ getCacheStats(): CacheStats { return this._cache.getStats() }
277
+
278
+ // ─── Static Factory ────────────────────────────────────────────────────
279
+
280
+ static create(options?: ValidatorOptions): Validator {
281
+ return new Validator(options)
282
+ }
283
+
284
+ /**
285
+ * Quick validate (V-Y07 fix: reuses singleton Ajv instead of creating new Ajv each time).
286
+ */
287
+ static quickValidate(schema: JSONSchema, data: unknown): boolean {
288
+ if (!Validator._quickValidateAjv) {
289
+ Validator._quickValidateAjv = new Ajv()
290
+ ; (addFormats as unknown as (a: InstanceType<typeof Ajv>) => void)(Validator._quickValidateAjv)
291
+ CustomKeywords.registerAll(Validator._quickValidateAjv)
292
+ }
293
+ try {
294
+ return Validator._quickValidateAjv.validate(schema, data) as boolean
295
+ } catch {
296
+ return false
297
+ }
298
+ }
299
+
300
+ // ─── Internal Implementation ───────────────────────────────────────────
301
+
302
+ private _validateInternal<T>(
303
+ schema: JSONSchema | AjvValidateFn,
304
+ data: T,
305
+ options: ValidateOptions = {}
306
+ ): ValidationResult<T> {
307
+ const shouldFormat = options.format !== false
308
+ const locale = options.locale ?? Locale.getLocale()
309
+ const messages = (options.messages ?? {}) as ErrorMessages
310
+
311
+ // DslBuilder/ObjectDslBuilder/ConditionalBuilder duck type.
312
+ // Builders are mutable, so their toSchema() result must be re-materialized on every call.
313
+ if (typeof (schema as Record<string, unknown>)['toSchema'] === 'function') {
314
+ const obj = schema as Record<string, unknown>
315
+ schema = (obj['toSchema'] as () => JSONSchema)()
316
+ }
317
+
318
+ const internalSchema = schema as InternalSchema
319
+
320
+ // ConditionalBuilder (top-level)
321
+ if (internalSchema._isConditional) {
322
+ return this._conditionalValidator.validateConditional(internalSchema, data as Record<string, unknown>, null, data, options)
323
+ }
324
+
325
+ // Object schema containing ConditionalBuilder properties (including arbitrary nesting depth)
326
+ if (internalSchema.properties) {
327
+ // Performance: cache conditional detection result to avoid traversing properties on every validation
328
+ let hasConditionals = this._conditionalFlagCache.get(internalSchema as object)
329
+ if (hasConditionals === undefined) {
330
+ hasConditionals = this._conditionalValidator.hasAnyConditional(internalSchema)
331
+ this._conditionalFlagCache.set(internalSchema as object, hasConditionals)
332
+ }
333
+ if (hasConditionals) {
334
+ return this._conditionalValidator.validateWithConditionals(internalSchema, data, options)
335
+ }
336
+ }
337
+
338
+ // V-Y03 fix: _removeAdditional reuses internal Ajv instance
339
+ if (internalSchema._removeAdditional) {
340
+ if (!this._removeAdditionalAjv) {
341
+ this._removeAdditionalAjv = new Ajv({ ...this._ajvOptions, removeAdditional: true })
342
+ ; (addFormats as unknown as (a: InstanceType<typeof Ajv>) => void)(this._removeAdditionalAjv)
343
+ CustomKeywords.registerAll(this._removeAdditionalAjv)
344
+ }
345
+
346
+ const cleanSchema: JSONSchema = JSON.parse(JSON.stringify(schema)) as JSONSchema
347
+ delete (cleanSchema as InternalSchema)._removeAdditional
348
+
349
+ try {
350
+ const validate = this._removeAdditionalAjv.compile(cleanSchema)
351
+ const valid = validate(data) as boolean
352
+ if (valid) return { valid: true, data, errors: EMPTY_ERRORS }
353
+ const fmtErrors = this._formatErrors(validate.errors ?? [], messages, locale, shouldFormat)
354
+ return { valid: false, data, errors: fmtErrors, errorMessage: fmtErrors[0]?.message }
355
+ } catch (error) {
356
+ return this._internalError(error, data)
357
+ }
358
+ }
359
+
360
+ try {
361
+ let validate: AjvValidateFn
362
+ if (typeof schema === 'function') {
363
+ validate = schema as AjvValidateFn
364
+ } else {
365
+ // Performance: merge _generateCacheKey + compile() into a single WeakMap lookup
366
+ const schemaObj = schema as object
367
+ let cacheKey = this._schemaMap.get(schemaObj)
368
+ if (!cacheKey) {
369
+ cacheKey = `s${++this._schemaKeyCounter}`
370
+ this._schemaMap.set(schemaObj, cacheKey)
371
+ }
372
+ const cached = this._cache.get(cacheKey) as AjvValidateFn | null
373
+ if (cached !== null) {
374
+ validate = cached
375
+ } else {
376
+ try {
377
+ validate = this._ajv.compile(schema as JSONSchema)
378
+ this._cache.set(cacheKey, validate as unknown as object)
379
+ } catch (error) {
380
+ throw new Error(`Schema compilation failed: ${error instanceof Error ? error.message : String(error)}`)
381
+ }
382
+ }
383
+ }
384
+
385
+ const valid = validate(data) as boolean
386
+ if (valid) return { valid: true, data, errors: EMPTY_ERRORS }
387
+ const fmtErrors2 = this._formatErrors(validate.errors ?? [], messages, locale, shouldFormat)
388
+ return { valid: false, data, errors: fmtErrors2, errorMessage: fmtErrors2[0]?.message }
389
+ } catch (error) {
390
+ return this._internalError(error, data)
391
+ }
392
+ }
393
+
394
+ // ─── Helper methods ─────────────────────────────────────────────────────
395
+
396
+ private _generateCacheKey(schema: object): string {
397
+ if (!this._schemaMap.has(schema)) {
398
+ this._schemaMap.set(schema, `schema_${++this._schemaKeyCounter}`)
399
+ }
400
+ return this._schemaMap.get(schema)!
401
+ }
402
+
403
+ // Performance: cache flattened locale messages (key = locale, value = flat ErrorMessages)
404
+ // to avoid re-running Locale.getMessages + Object.entries.map on every validation failure
405
+ private readonly _flatLocaleCache = new Map<string, ErrorMessages>()
406
+
407
+ private _getFlatLocaleMessages(locale: string): ErrorMessages {
408
+ let flat = this._flatLocaleCache.get(locale)
409
+ if (!flat) {
410
+ const raw = Locale.getMessages(locale)
411
+ flat = Object.fromEntries(
412
+ Object.entries(raw).map(([k, v]) => [
413
+ k,
414
+ typeof v === 'string' ? v : (v as { message: string }).message,
415
+ ])
416
+ ) as ErrorMessages
417
+ this._flatLocaleCache.set(locale, flat)
418
+ }
419
+ return flat
420
+ }
421
+
422
+ private _formatErrors(
423
+ rawErrors: unknown[],
424
+ messages: ErrorMessages,
425
+ locale: string,
426
+ shouldFormat: boolean
427
+ ): ValidationErrorItem[] {
428
+ if (!shouldFormat) return rawErrors as ValidationErrorItem[]
429
+ const localeMessages = this._getFlatLocaleMessages(locale)
430
+ // Only merge when there are custom messages (avoid unnecessary object spread)
431
+ const mergedMessages: ErrorMessages =
432
+ Object.keys(messages).length === 0
433
+ ? localeMessages
434
+ : { ...localeMessages, ...messages }
435
+ // alreadyMerged=true: mergedMessages already contains locale+custom, skip re-expansion inside formatDetailed
436
+ return this._errorFormatter.formatDetailed(rawErrors as Parameters<ErrorFormatter['formatDetailed']>[0], locale, mergedMessages, true)
437
+ }
438
+
439
+ private _internalError<T>(error: unknown, data: T): ValidationResult<T> {
440
+ const message = `Validation error: ${error instanceof Error ? error.message : String(error)}`
441
+ return {
442
+ valid: false,
443
+ data,
444
+ errors: [{ message, path: '', keyword: 'error', params: {} }],
445
+ errorMessage: message,
446
+ }
447
+ }
448
+ }