Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 64 additions & 18 deletions src/analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
parse,
} from "./parser";
import {
assertNoConditionalSchema,
findConditionalSchemaLocations,
resolveArrayItems,
resolveSchemaPath,
simplifySchema,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -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);

Expand Down
18 changes: 15 additions & 3 deletions src/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
144 changes: 111 additions & 33 deletions src/schema-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -38,54 +39,59 @@ import { deepEqual } from "./utils.ts";
* A `Set<object>` 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<object> = 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,
),
);
}
}
}
Expand All @@ -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,
),
);
}

Expand All @@ -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,
),
);
}
}

Expand All @@ -123,15 +143,23 @@ 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,
),
);
}
}
}
}

// ── 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 ─────────────────────────────────
Expand All @@ -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<object> = 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 ─────────────────────────────────────────────────────────
Expand Down
4 changes: 3 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading