diff --git a/src/lib/ajv-validate.ts b/src/lib/ajv-validate.ts index 7ee86967..4266e3f1 100644 --- a/src/lib/ajv-validate.ts +++ b/src/lib/ajv-validate.ts @@ -152,6 +152,77 @@ function deduplicateUnionErrors (errors: ValidationError[]): ValidationError[] { ) } +interface SchemaNode { + type?: string | string[] + const?: unknown + enum?: unknown[] + anyOf?: SchemaNode[] + oneOf?: SchemaNode[] + $ref?: string +} + +/** Follows same-document `$ref`s. External refs are left as-is. */ +function derefNode (root: Record, node: SchemaNode, seen: Set): SchemaNode { + const ref = node.$ref + if (typeof ref !== 'string' || !ref.startsWith('#/$defs/')) return node + if (seen.has(ref)) return node + const defs = root['$defs'] + if (defs == null || typeof defs !== 'object') return node + const target = (defs as Record)[ref.slice('#/$defs/'.length)] + if (target == null || typeof target !== 'object') return node + seen.add(ref) + return derefNode(root, target, seen) +} + +/** What a schema node (and its union branches) accepts. */ +function unionKinds ( + root: Record, + node: SchemaNode, + seen: Set, +): { number: boolean, enum: boolean, freeString: boolean } { + const resolved = derefNode(root, node, seen) + const variants = resolved.anyOf ?? resolved.oneOf + if (variants != null && variants.length > 0) { + const acc = { number: false, enum: false, freeString: false } + for (const variant of variants) { + const part = unionKinds(root, variant, seen) + acc.number = acc.number || part.number + acc.enum = acc.enum || part.enum + acc.freeString = acc.freeString || part.freeString + } + return acc + } + const rawType = Array.isArray(resolved.type) ? resolved.type[0] : resolved.type + if (rawType === 'number' || rawType === 'integer' || typeof resolved.const === 'number') { + return { number: true, enum: false, freeString: false } + } + if (Array.isArray(resolved.enum) && resolved.enum.length > 0) { + return { number: false, enum: true, freeString: false } + } + if (rawType === 'string') return { number: false, enum: false, freeString: true } + return { number: false, enum: false, freeString: false } +} + +// No leading zeros, no exponent. "01" and "1e2" stay strings. +const CANONICAL_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/ + +/** + * Turns a numeric string into a number when the property is a number-or-enum + * union (`slices`, `wait_for_active_shards`). A free string branch is left + * alone, so an index named "5" stays a string. + */ +function coerceNumericEnumUnions (schema: Record, data: Record): void { + const props = schema['properties'] + if (props == null || typeof props !== 'object') return + for (const [key, prop] of Object.entries(props as Record)) { + const value = data[key] + if (typeof value !== 'string' || !CANONICAL_NUMBER.test(value)) continue + if (prop == null || typeof prop !== 'object') continue + const kinds = unionKinds(schema, prop, new Set()) + if (kinds.number && kinds.enum && !kinds.freeString) data[key] = Number(value) + } +} + /** * Validates `input` against a JSON Schema object. * @@ -172,6 +243,9 @@ export function validateWithJsonSchema ( // deep-clone input so defaults don't mutate the original object const data = JSON.parse(JSON.stringify(input ?? {})) as Record + if (data != null && typeof data === 'object' && !Array.isArray(data)) { + coerceNumericEnumUnions(compilable, data) + } const ajv = getAjv() let validate: ValidateFunction diff --git a/test/factory.test.ts b/test/factory.test.ts index 65b1cb77..b8d81f0d 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -1878,6 +1878,25 @@ describe('defineCommand', () => { assert.equal(input.size, 5) }) + it('coerces a numeric flag when the schema is a number or an enum', async () => { + const schema = jsonSchema({ + slices: { anyOf: [{ type: 'number' }, { enum: ['auto'] }], 'x-found-in': 'query' }, + }) + const received: unknown[] = [] + const cmd = defineCommand({ + name: 'reindex', + description: 'Reindex', + input: schema, + handler: (parsed) => { received.push(parsed.input); return {} }, + }) + await invokeAsync(cmd, ['--slices', '5']) + assert.equal((received[0] as Record).slices, 5) + await invokeAsync(cmd, ['--slices', 'auto']) + assert.equal((received[1] as Record).slices, 'auto') + const err = await captureErrAsync(cmd, ['--slices', '../']) + assert.match(err, /input validation failed/) + }) + it('accepts array-typed body fields with any valid JSON', async () => { const schema = jsonSchema({ operations: { type: 'array', 'x-found-in': 'body' }, diff --git a/test/lib/ajv-validate.test.ts b/test/lib/ajv-validate.test.ts index 8d07b2ce..3bbd1b6f 100644 --- a/test/lib/ajv-validate.test.ts +++ b/test/lib/ajv-validate.test.ts @@ -304,3 +304,66 @@ describe('validateWithJsonSchema (ajv6 compile robustness) (#fix5)', () => { } }) }) + +describe('numeric string or enum unions', () => { + const slices = { + type: 'object', + properties: { + slices: { + anyOf: [{ type: 'number' }, { enum: ['auto'] }], + }, + }, + } + + it('coerces a numeric string when the union is a number or an enum', () => { + const result = validateWithJsonSchema(slices, { slices: '5' }) + assert.equal(result.success, true) + if (result.success) assert.equal(result.data['slices'], 5) + }) + + it('keeps the enum string', () => { + const result = validateWithJsonSchema(slices, { slices: 'auto' }) + assert.equal(result.success, true) + if (result.success) assert.equal(result.data['slices'], 'auto') + }) + + it('follows a same-document $ref to the enum branch', () => { + const schema = { + type: 'object', + $defs: { Slices: { anyOf: [{ type: 'number' }, { $ref: '#/$defs/Auto' }] }, Auto: { enum: ['auto'] } }, + properties: { slices: { $ref: '#/$defs/Slices' } }, + } + const result = validateWithJsonSchema(schema, { slices: '5' }) + assert.equal(result.success, true) + if (result.success) assert.equal(result.data['slices'], 5) + }) + + it('rejects a numeric string that is not a plain decimal', () => { + for (const value of ['5abc', '01', '1e2', '', '../', '?#']) { + const result = validateWithJsonSchema(slices, { slices: value }) + assert.equal(result.success, false, value) + } + }) + + it('does not coerce a free string, including a numeric one', () => { + const schema = { type: 'object', properties: { index: { type: 'string' } } } + const result = validateWithJsonSchema(schema, { index: '5' }) + assert.equal(result.success, true) + if (result.success) assert.equal(result.data['index'], '5') + }) + + it('does not coerce a duration string that also allows numeric consts', () => { + const schema = { + type: 'object', + properties: { + keep_alive: { anyOf: [{ type: 'string' }, { const: -1 }, { const: 0 }] }, + }, + } + const text = validateWithJsonSchema(schema, { keep_alive: '10s' }) + assert.equal(text.success, true) + if (text.success) assert.equal(text.data['keep_alive'], '10s') + const numeric = validateWithJsonSchema(schema, { keep_alive: '-1' }) + assert.equal(numeric.success, true) + if (numeric.success) assert.equal(numeric.data['keep_alive'], '-1') + }) +})