diff --git a/src/analyzer.ts b/src/analyzer.ts index cb5889d..03642aa 100644 --- a/src/analyzer.ts +++ b/src/analyzer.ts @@ -22,7 +22,7 @@ import { parse, } from "./parser"; import { - assertNoConditionalSchema, + findConditionalSchemaLocations, resolveArrayItems, resolveSchemaPath, simplifySchema, @@ -137,13 +137,22 @@ export interface AnalyzeOptions { function coerceTextValue( text: string, targetType: "string" | "number" | "integer" | "boolean" | "null", -): string | number | boolean | null { +): string | number | boolean | null | undefined { switch (targetType) { case "number": - case "integer": - return Number(text); - case "boolean": - return text === "true"; + case "integer": { + if (text === "") return undefined; + const num = Number(text); + if (Number.isNaN(num)) return undefined; + if (targetType === "integer" && !Number.isInteger(num)) return undefined; + return num; + } + case "boolean": { + const lower = text.toLowerCase(); + if (lower === "true") return true; + if (lower === "false") return false; + return undefined; + } case "null": return null; default: @@ -213,18 +222,7 @@ export function analyzeFromAst( coerceSchema?: JSONSchema7; }, ): AnalysisResult { - // ── Reject unsupported schema features before analysis ──────────── - // Conditional schemas (if/then/else) are non-resolvable without runtime - // data. Fail fast with a clear error rather than producing silently - // incorrect results. - assertNoConditionalSchema(inputSchema); - - if (options?.identifierSchemas) { - for (const [id, idSchema] of Object.entries(options.identifierSchemas)) { - assertNoConditionalSchema(idSchema, `/identifierSchemas/${id}`); - } - } - + // ── Initialize the diagnostic context FIRST ──────────────────────── const ctx: AnalysisContext = { root: inputSchema, current: inputSchema, @@ -235,6 +233,54 @@ export function analyzeFromAst( coerceSchema: options?.coerceSchema, }; + // ── Detect unsupported schema features as diagnostics ────────────── + // Conditional schemas (if/then/else) are non-resolvable without runtime + // data. Instead of throwing, we collect structured diagnostics so the + // caller receives a standard AnalysisResult. + const conditionalLocations = findConditionalSchemaLocations(inputSchema); + for (const loc of conditionalLocations) { + addDiagnostic( + ctx, + "UNSUPPORTED_SCHEMA", + "error", + `Unsupported JSON Schema feature: "${loc.keyword}" at "${loc.schemaPath}". ` + + "Conditional schemas (if/then/else) cannot be resolved during static analysis " + + "because they depend on runtime data. Consider using oneOf/anyOf combinators instead.", + undefined, + { path: loc.schemaPath }, + ); + } + + if (options?.identifierSchemas) { + for (const [id, idSchema] of Object.entries(options.identifierSchemas)) { + const idLocations = findConditionalSchemaLocations( + idSchema, + `/identifierSchemas/${id}`, + ); + for (const loc of idLocations) { + addDiagnostic( + ctx, + "UNSUPPORTED_SCHEMA", + "error", + `Unsupported JSON Schema feature: "${loc.keyword}" at "${loc.schemaPath}". ` + + "Conditional schemas (if/then/else) cannot be resolved during static analysis " + + "because they depend on runtime data. Consider using oneOf/anyOf combinators instead.", + undefined, + { path: loc.schemaPath }, + ); + } + } + } + + // If unsupported schemas were found, return early with valid: false + if (ctx.diagnostics.length > 0) { + return { + valid: false, + diagnostics: ctx.diagnostics, + outputSchema: {}, + }; + } + // Single pass: type inference + validation in one traversal. const outputSchema = inferProgramType(ast, ctx); diff --git a/src/executor.ts b/src/executor.ts index d40838f..eb6ce2e 100644 --- a/src/executor.ts +++ b/src/executor.ts @@ -234,9 +234,21 @@ function coerceValue(raw: string, coerceSchema?: JSONSchema7): unknown { const targetType = coerceSchema.type; if (typeof targetType === "string") { if (targetType === "string") return raw; - if (targetType === "number" || targetType === "integer") - return Number(raw.trim()); - if (targetType === "boolean") return raw.trim() === "true"; + if (targetType === "number" || targetType === "integer") { + const trimmed = raw.trim(); + if (trimmed === "") return undefined; + const num = Number(trimmed); + if (Number.isNaN(num)) return undefined; + if (targetType === "integer" && !Number.isInteger(num)) + return undefined; + return num; + } + if (targetType === "boolean") { + const lower = raw.trim().toLowerCase(); + if (lower === "true") return true; + if (lower === "false") return false; + return undefined; + } if (targetType === "null") return null; } } diff --git a/src/schema-resolver.ts b/src/schema-resolver.ts index af6fc51..2a6ebd3 100644 --- a/src/schema-resolver.ts +++ b/src/schema-resolver.ts @@ -24,10 +24,11 @@ import { deepEqual } from "./utils.ts"; // we fail fast with a clear error pointing to the exact location in the schema. /** - * Recursively validates that a JSON Schema does not contain `if/then/else` - * conditional keywords. Throws an `UnsupportedSchemaError` if any are found. + * Recursively scans a JSON Schema tree for `if/then/else` conditional keywords + * and returns their locations as an array of `{ keyword, schemaPath }` objects. * - * This check traverses the entire schema tree, including: + * This is the non-throwing counterpart of `assertNoConditionalSchema`. + * It traverses the entire schema tree, including: * - `properties` values * - `additionalProperties` (when it's a schema) * - `items` (single schema or tuple) @@ -38,54 +39,59 @@ import { deepEqual } from "./utils.ts"; * A `Set` is used to track visited schemas and prevent infinite loops * from circular structures. * - * @param schema - The JSON Schema to validate - * @param path - The current JSON pointer path (for error reporting) + * @param schema - The JSON Schema to scan + * @param path - The current JSON pointer path (for location reporting) * @param visited - Set of already-visited schema objects (cycle protection) - * - * @throws {UnsupportedSchemaError} if `if`, `then`, or `else` is found + * @returns Array of locations where `if/then/else` keywords were found * * @example * ``` - * // Throws UnsupportedSchemaError: - * assertNoConditionalSchema({ + * // Returns [{ keyword: "if/then/else", schemaPath: "/" }]: + * findConditionalSchemaLocations({ * type: "object", * if: { properties: { kind: { const: "a" } } }, * then: { properties: { a: { type: "string" } } }, * }); * - * // OK — no conditional keywords: - * assertNoConditionalSchema({ + * // Returns []: + * findConditionalSchemaLocations({ * type: "object", * properties: { name: { type: "string" } }, * }); * ``` */ -export function assertNoConditionalSchema( +export function findConditionalSchemaLocations( schema: JSONSchema7, path = "", visited: Set = new Set(), -): void { +): Array<{ keyword: string; schemaPath: string }> { + const locations: Array<{ keyword: string; schemaPath: string }> = []; + // Cycle protection — avoid infinite loops on circular schema structures - if (visited.has(schema)) return; + if (visited.has(schema)) return locations; visited.add(schema); // ── Detect if/then/else at the current level ───────────────────────── - if (schema.if !== undefined) { - throw new UnsupportedSchemaError("if/then/else", path || "/"); - } - // `then` or `else` without `if` is unusual but still unsupported - if (schema.then !== undefined) { - throw new UnsupportedSchemaError("if/then/else", path || "/"); - } - if (schema.else !== undefined) { - throw new UnsupportedSchemaError("if/then/else", path || "/"); + // One diagnostic per schema node is enough — no need to report `then` + // and `else` separately if `if` is already present. + for (const kw of ["if", "then", "else"] as const) { + if (schema[kw] !== undefined) { + locations.push({ keyword: "if/then/else", schemaPath: path || "/" }); + break; + } } // ── Recurse into properties ────────────────────────────────────────── if (schema.properties) { for (const [key, prop] of Object.entries(schema.properties)) { if (prop && typeof prop !== "boolean") { - assertNoConditionalSchema(prop, `${path}/properties/${key}`, visited); + locations.push( + ...findConditionalSchemaLocations( + prop, + `${path}/properties/${key}`, + visited, + ), + ); } } } @@ -95,10 +101,12 @@ export function assertNoConditionalSchema( schema.additionalProperties && typeof schema.additionalProperties === "object" ) { - assertNoConditionalSchema( - schema.additionalProperties, - `${path}/additionalProperties`, - visited, + locations.push( + ...findConditionalSchemaLocations( + schema.additionalProperties, + `${path}/additionalProperties`, + visited, + ), ); } @@ -108,11 +116,23 @@ export function assertNoConditionalSchema( for (let i = 0; i < schema.items.length; i++) { const item = schema.items[i]; if (item && typeof item !== "boolean") { - assertNoConditionalSchema(item, `${path}/items/${i}`, visited); + locations.push( + ...findConditionalSchemaLocations( + item, + `${path}/items/${i}`, + visited, + ), + ); } } } else if (typeof schema.items !== "boolean") { - assertNoConditionalSchema(schema.items, `${path}/items`, visited); + locations.push( + ...findConditionalSchemaLocations( + schema.items, + `${path}/items`, + visited, + ), + ); } } @@ -123,7 +143,13 @@ export function assertNoConditionalSchema( for (let i = 0; i < branches.length; i++) { const branch = branches[i]; if (branch && typeof branch !== "boolean") { - assertNoConditionalSchema(branch, `${path}/${keyword}/${i}`, visited); + locations.push( + ...findConditionalSchemaLocations( + branch, + `${path}/${keyword}/${i}`, + visited, + ), + ); } } } @@ -131,7 +157,9 @@ export function assertNoConditionalSchema( // ── Recurse into not ───────────────────────────────────────────────── if (schema.not && typeof schema.not !== "boolean") { - assertNoConditionalSchema(schema.not, `${path}/not`, visited); + locations.push( + ...findConditionalSchemaLocations(schema.not, `${path}/not`, visited), + ); } // ── Recurse into definitions / $defs ───────────────────────────────── @@ -140,11 +168,61 @@ export function assertNoConditionalSchema( if (defs) { for (const [name, def] of Object.entries(defs)) { if (def && typeof def !== "boolean") { - assertNoConditionalSchema(def, `${path}/${defsKey}/${name}`, visited); + locations.push( + ...findConditionalSchemaLocations( + def, + `${path}/${defsKey}/${name}`, + visited, + ), + ); } } } } + + return locations; +} + +/** + * Recursively validates that a JSON Schema does not contain `if/then/else` + * conditional keywords. Throws an `UnsupportedSchemaError` if any are found. + * + * @deprecated Use `findConditionalSchemaLocations` for diagnostic-based reporting. + * This function is preserved for backward compatibility. + * + * @param schema - The JSON Schema to validate + * @param path - The current JSON pointer path (for error reporting) + * @param visited - Set of already-visited schema objects (cycle protection) + * + * @throws {UnsupportedSchemaError} if `if`, `then`, or `else` is found + * + * @example + * ``` + * // Throws UnsupportedSchemaError: + * assertNoConditionalSchema({ + * type: "object", + * if: { properties: { kind: { const: "a" } } }, + * then: { properties: { a: { type: "string" } } }, + * }); + * + * // OK — no conditional keywords: + * assertNoConditionalSchema({ + * type: "object", + * properties: { name: { type: "string" } }, + * }); + * ``` + */ +export function assertNoConditionalSchema( + schema: JSONSchema7, + path = "", + visited: Set = new Set(), +): void { + const locations = findConditionalSchemaLocations(schema, path, visited); + if (locations.length > 0) { + // biome-ignore lint: length check guarantees defined + const first = locations[0]!; + throw new UnsupportedSchemaError(first.keyword, first.schemaPath); + } } // ─── $ref Resolution ───────────────────────────────────────────────────────── diff --git a/src/types.ts b/src/types.ts index 69b5cd6..8bee81f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -164,7 +164,9 @@ export type DiagnosticCode = /** Syntax error in the template */ | "PARSE_ERROR" /** The $root token is used with path traversal (e.g. $root.name) */ - | "ROOT_PATH_TRAVERSAL"; + | "ROOT_PATH_TRAVERSAL" + /** Unsupported JSON Schema feature (e.g. if/then/else conditional schemas) */ + | "UNSUPPORTED_SCHEMA"; // ─── Diagnostic Details ────────────────────────────────────────────────────── // Supplementary information to understand the exact cause of the error. diff --git a/tests/coerce-execution.spec.ts b/tests/coerce-execution.spec.ts index c3372d6..053a6c3 100644 --- a/tests/coerce-execution.spec.ts +++ b/tests/coerce-execution.spec.ts @@ -330,7 +330,7 @@ describe("coerceSchema at execution time", () => { ).toBe("hello"); }); - test("static 'hello' + coerceSchema number → NaN (expected — analysis should catch this)", () => { + test("static 'hello' + coerceSchema number → undefined (non-numeric string)", () => { const result = engine.execute( "hello", {}, @@ -338,7 +338,7 @@ describe("coerceSchema at execution time", () => { coerceSchema: { type: "number" }, }, ); - expect(result).toBeNaN(); + expect(result).toBeUndefined(); }); test("Handlebars expression is NOT affected by coerceSchema", () => { @@ -1054,4 +1054,237 @@ describe("coerceSchema at execution time", () => { expect(typeof value).toBe("string"); }); }); + + // ─── Boolean Coercion Case-Insensitivity ───────────────────────────── + + describe("boolean coercion case-insensitivity", () => { + test("'true' → true", () => { + const result = engine.execute( + "true", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBe(true); + }); + + test("'false' → false", () => { + const result = engine.execute( + "false", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBe(false); + }); + + test("'True' → true (case-insensitive)", () => { + const result = engine.execute( + "True", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBe(true); + }); + + test("'TRUE' → true (case-insensitive)", () => { + const result = engine.execute( + "TRUE", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBe(true); + }); + + test("'False' → false (case-insensitive)", () => { + const result = engine.execute( + "False", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBe(false); + }); + + test("'FALSE' → false (case-insensitive)", () => { + const result = engine.execute( + "FALSE", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBe(false); + }); + + test("'' → undefined (empty string is not a boolean)", () => { + const result = engine.execute( + "", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBeUndefined(); + }); + + test("' true ' → true (whitespace trimmed)", () => { + const result = engine.execute( + " true ", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBe(true); + }); + + test("' FALSE ' → false (whitespace trimmed + case-insensitive)", () => { + const result = engine.execute( + " FALSE ", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBe(false); + }); + + test("'yes' → undefined (not a valid boolean string)", () => { + const result = engine.execute( + "yes", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBeUndefined(); + }); + + test("'1' → undefined (not a valid boolean string)", () => { + const result = engine.execute( + "1", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBeUndefined(); + }); + + test("'0' → undefined (not a valid boolean string)", () => { + const result = engine.execute( + "0", + {}, + { coerceSchema: { type: "boolean" } }, + ); + expect(result).toBeUndefined(); + }); + }); + + // ─── Number Coercion Edge Cases ────────────────────────────────────── + + describe("number coercion edge cases", () => { + test("'42' → 42", () => { + const result = engine.execute( + "42", + {}, + { coerceSchema: { type: "number" } }, + ); + expect(result).toBe(42); + }); + + test("'3.14' → 3.14", () => { + const result = engine.execute( + "3.14", + {}, + { coerceSchema: { type: "number" } }, + ); + expect(result).toBe(3.14); + }); + + test("'-7' → -7", () => { + const result = engine.execute( + "-7", + {}, + { coerceSchema: { type: "number" } }, + ); + expect(result).toBe(-7); + }); + + test("'' → undefined (not 0)", () => { + const result = engine.execute( + "", + {}, + { coerceSchema: { type: "number" } }, + ); + expect(result).toBeUndefined(); + }); + + test("' ' → undefined (not 0)", () => { + const result = engine.execute( + " ", + {}, + { coerceSchema: { type: "number" } }, + ); + expect(result).toBeUndefined(); + }); + + test("'hello' → undefined (not NaN)", () => { + const result = engine.execute( + "hello", + {}, + { coerceSchema: { type: "number" } }, + ); + expect(result).toBeUndefined(); + }); + + test("'3.14' with integer schema → undefined (not an integer)", () => { + const result = engine.execute( + "3.14", + {}, + { coerceSchema: { type: "integer" } }, + ); + expect(result).toBeUndefined(); + }); + + test("'-7' with integer schema → -7", () => { + const result = engine.execute( + "-7", + {}, + { coerceSchema: { type: "integer" } }, + ); + expect(result).toBe(-7); + }); + + test("'42' with integer schema → 42", () => { + const result = engine.execute( + "42", + {}, + { coerceSchema: { type: "integer" } }, + ); + expect(result).toBe(42); + }); + + test("'0' with number schema → 0", () => { + const result = engine.execute( + "0", + {}, + { coerceSchema: { type: "number" } }, + ); + expect(result).toBe(0); + }); + + test("' 42 ' with number schema → 42 (whitespace trimmed)", () => { + const result = engine.execute( + " 42 ", + {}, + { coerceSchema: { type: "number" } }, + ); + expect(result).toBe(42); + }); + + test("'' with integer schema → undefined (not 0)", () => { + const result = engine.execute( + "", + {}, + { coerceSchema: { type: "integer" } }, + ); + expect(result).toBeUndefined(); + }); + + test("'abc' with integer schema → undefined", () => { + const result = engine.execute( + "abc", + {}, + { coerceSchema: { type: "integer" } }, + ); + expect(result).toBeUndefined(); + }); + }); }); diff --git a/tests/conditional-schema.spec.ts b/tests/conditional-schema.spec.ts index e30e3ab..23acdd4 100644 --- a/tests/conditional-schema.spec.ts +++ b/tests/conditional-schema.spec.ts @@ -1,8 +1,14 @@ import { beforeEach, describe, expect, test } from "bun:test"; import type { JSONSchema7 } from "json-schema"; import { analyze } from "../src/analyzer.ts"; -import { UnsupportedSchemaError } from "../src/errors.ts"; -import { assertNoConditionalSchema } from "../src/schema-resolver.ts"; +import { + TemplateAnalysisError, + UnsupportedSchemaError, +} from "../src/errors.ts"; +import { + assertNoConditionalSchema, + findConditionalSchemaLocations, +} from "../src/schema-resolver.ts"; import { Typebars } from "../src/typebars.ts"; import { userSchema } from "./fixtures.ts"; @@ -410,17 +416,26 @@ describe("conditional schema detection (if/then/else)", () => { // ─── Integration with analyze() ──────────────────────────────────────── describe("integration with analyze()", () => { - test("analyze throws UnsupportedSchemaError for schema with if/then/else", () => { + test("analyze returns valid: false with UNSUPPORTED_SCHEMA diagnostic for schema with if/then/else", () => { const schema: JSONSchema7 = { type: "object", if: { properties: { kind: { const: "a" } } }, then: { properties: { a: { type: "string" } } }, else: { properties: { b: { type: "number" } } }, }; - expect(() => analyze("{{a}}", schema)).toThrow(UnsupportedSchemaError); + const result = analyze("{{a}}", schema); + expect(result.valid).toBe(false); + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), + ); }); - test("analyze throws for nested if/then/else in properties", () => { + test("analyze returns valid: false for nested if/then/else in properties", () => { const schema: JSONSchema7 = { type: "object", properties: { @@ -432,7 +447,16 @@ describe("conditional schema detection (if/then/else)", () => { }, }, }; - expect(() => analyze("{{name}}", schema)).toThrow(UnsupportedSchemaError); + const result = analyze("{{name}}", schema); + expect(result.valid).toBe(false); + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), + ); }); test("analyze works normally for schemas without conditionals", () => { @@ -450,47 +474,70 @@ describe("conditional schema detection (if/then/else)", () => { engine = new Typebars(); }); - test("engine.analyze throws UnsupportedSchemaError", () => { + test("engine.analyze returns valid: false with UNSUPPORTED_SCHEMA diagnostic", () => { const schema: JSONSchema7 = { type: "object", if: { properties: { kind: { const: "a" } } }, then: { properties: { a: { type: "string" } } }, }; - expect(() => engine.analyze("{{a}}", schema)).toThrow( - UnsupportedSchemaError, + const result = engine.analyze("{{a}}", schema); + expect(result.valid).toBe(false); + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), ); }); - test("engine.validate throws UnsupportedSchemaError", () => { + test("engine.validate returns valid: false with UNSUPPORTED_SCHEMA diagnostic", () => { const schema: JSONSchema7 = { type: "object", if: { properties: { kind: { const: "a" } } }, then: { properties: { a: { type: "string" } } }, }; - expect(() => engine.validate("{{a}}", schema)).toThrow( - UnsupportedSchemaError, + const result = engine.validate("{{a}}", schema); + expect(result.valid).toBe(false); + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), ); }); - test("engine.analyzeAndExecute throws UnsupportedSchemaError", () => { + test("engine.analyzeAndExecute returns valid: false with UNSUPPORTED_SCHEMA diagnostic", () => { const schema: JSONSchema7 = { type: "object", if: { properties: { kind: { const: "a" } } }, then: { properties: { a: { type: "string" } } }, }; - expect(() => - engine.analyzeAndExecute("{{a}}", schema, { a: "hello" }), - ).toThrow(UnsupportedSchemaError); + const result = engine.analyzeAndExecute("{{a}}", schema, { + a: "hello", + }); + expect(result.analysis.valid).toBe(false); + expect(result.analysis.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), + ); }); - test("engine.execute with schema option throws UnsupportedSchemaError", () => { + test("engine.execute with schema option throws TemplateAnalysisError", () => { const schema: JSONSchema7 = { type: "object", if: { properties: { kind: { const: "a" } } }, then: { properties: { a: { type: "string" } } }, }; expect(() => engine.execute("{{a}}", { a: "hello" }, { schema })).toThrow( - UnsupportedSchemaError, + TemplateAnalysisError, ); }); @@ -499,14 +546,23 @@ describe("conditional schema detection (if/then/else)", () => { expect(result).toBe("hello"); }); - test("compiled template analyze throws UnsupportedSchemaError", () => { + test("compiled template analyze returns valid: false with UNSUPPORTED_SCHEMA diagnostic", () => { const tpl = engine.compile("{{a}}"); const schema: JSONSchema7 = { type: "object", if: { properties: { kind: { const: "a" } } }, then: { properties: { a: { type: "string" } } }, }; - expect(() => tpl.analyze(schema)).toThrow(UnsupportedSchemaError); + const result = tpl.analyze(schema); + expect(result.valid).toBe(false); + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), + ); }); }); @@ -519,7 +575,7 @@ describe("conditional schema detection (if/then/else)", () => { engine = new Typebars(); }); - test("throws for if/then/else in an identifierSchema", () => { + test("returns valid: false for if/then/else in an identifierSchema", () => { const inputSchema: JSONSchema7 = { type: "object", properties: { name: { type: "string" } }, @@ -531,12 +587,21 @@ describe("conditional schema detection (if/then/else)", () => { then: { properties: { value: { type: "string" } } }, }, }; - expect(() => - engine.analyze("{{value:1}}", inputSchema, { identifierSchemas }), - ).toThrow(UnsupportedSchemaError); + const result = engine.analyze("{{value:1}}", inputSchema, { + identifierSchemas, + }); + expect(result.valid).toBe(false); + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), + ); }); - test("throws for nested if/then/else in identifierSchema properties", () => { + test("returns valid: false for nested if/then/else in identifierSchema properties", () => { const inputSchema: JSONSchema7 = { type: "object", properties: { name: { type: "string" } }, @@ -553,11 +618,18 @@ describe("conditional schema detection (if/then/else)", () => { }, }, }; - expect(() => - engine.analyze("{{config.extra:1}}", inputSchema, { - identifierSchemas, - }), - ).toThrow(UnsupportedSchemaError); + const result = engine.analyze("{{config.extra:1}}", inputSchema, { + identifierSchemas, + }); + expect(result.valid).toBe(false); + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), + ); }); test("does not throw when identifierSchemas are clean", () => { @@ -577,35 +649,42 @@ describe("conditional schema detection (if/then/else)", () => { expect(result.valid).toBe(true); }); - test("analyzeAndExecute throws for conditional identifierSchema", () => { + test("analyzeAndExecute returns valid: false for conditional identifierSchema", () => { const inputSchema: JSONSchema7 = { type: "object", properties: { name: { type: "string" } }, }; - expect(() => - engine.analyzeAndExecute( - "{{value:1}}", - inputSchema, - { name: "test" }, - { - identifierSchemas: { - 1: { - type: "object", - if: { properties: { x: { const: 1 } } }, - then: { properties: { value: { type: "string" } } }, - }, + const result = engine.analyzeAndExecute( + "{{value:1}}", + inputSchema, + { name: "test" }, + { + identifierSchemas: { + 1: { + type: "object", + if: { properties: { x: { const: 1 } } }, + then: { properties: { value: { type: "string" } } }, }, - identifierData: { 1: { value: "hello" } }, }, - ), - ).toThrow(UnsupportedSchemaError); + identifierData: { 1: { value: "hello" } }, + }, + ); + expect(result.analysis.valid).toBe(false); + expect(result.analysis.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), + ); }); }); // ─── Object templates ────────────────────────────────────────────────── describe("object templates", () => { - test("throws for if/then/else in schema even with object template", () => { + test("returns valid: false for if/then/else in schema even with object template", () => { const engine = new Typebars(); const schema: JSONSchema7 = { type: "object", @@ -613,7 +692,86 @@ describe("conditional schema detection (if/then/else)", () => { then: { properties: { a: { type: "string" } } }, else: { properties: { b: { type: "number" } } }, }; - expect(() => engine.analyze({ result: "{{a}}" }, schema)).toThrow( + const result = engine.analyze({ result: "{{a}}" }, schema); + expect(result.valid).toBe(false); + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "UNSUPPORTED_SCHEMA", + severity: "error", + }), + ]), + ); + }); + }); + + // ─── findConditionalSchemaLocations ───────────────────────────────────── + + describe("findConditionalSchemaLocations", () => { + test("returns locations for root-level if/then/else", () => { + const schema: JSONSchema7 = { + type: "object", + if: { properties: { kind: { const: "a" } } }, + then: { properties: { a: { type: "string" } } }, + }; + const locations = findConditionalSchemaLocations(schema); + expect(locations).toEqual([{ keyword: "if/then/else", schemaPath: "/" }]); + }); + + test("returns empty array for clean schemas", () => { + const schema: JSONSchema7 = { + type: "object", + properties: { name: { type: "string" } }, + }; + const locations = findConditionalSchemaLocations(schema); + expect(locations).toEqual([]); + }); + + test("returns locations for nested if/then/else", () => { + const schema: JSONSchema7 = { + type: "object", + properties: { + config: { + type: "object", + if: { properties: { mode: { const: "x" } } }, + then: { properties: { extra: { type: "string" } } }, + }, + }, + }; + const locations = findConditionalSchemaLocations(schema); + expect(locations).toEqual([ + { keyword: "if/then/else", schemaPath: "/properties/config" }, + ]); + }); + + test("returns locations for if/then/else inside allOf branches", () => { + const schema: JSONSchema7 = { + type: "object", + properties: { role: { type: "string" } }, + allOf: [ + { + if: { properties: { role: { const: "admin" } } }, + then: { required: ["permissions"] }, + }, + ], + }; + const locations = findConditionalSchemaLocations(schema); + expect(locations).toEqual([ + { keyword: "if/then/else", schemaPath: "/allOf/0" }, + ]); + }); + }); + + // ─── assertNoConditionalSchema (deprecated, backward compat) ─────────── + + describe("assertNoConditionalSchema (deprecated)", () => { + test("still throws UnsupportedSchemaError for backward compatibility", () => { + const schema: JSONSchema7 = { + type: "object", + if: { properties: { kind: { const: "a" } } }, + then: { properties: { a: { type: "string" } } }, + }; + expect(() => assertNoConditionalSchema(schema)).toThrow( UnsupportedSchemaError, ); });