Skip to content
Open
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
11 changes: 9 additions & 2 deletions src/scorers/json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,15 @@ export function validate(value: unknown, schema: JsonSchema, path = "$"): string
errors.push(`${path}: shorter than minLength ${schema.minLength}`);
if (schema.maxLength !== undefined && value.length > schema.maxLength)
errors.push(`${path}: longer than maxLength ${schema.maxLength}`);
if (schema.pattern && !new RegExp(schema.pattern).test(value))
errors.push(`${path}: does not match pattern ${schema.pattern}`);
if (schema.pattern) {
try {
if (!new RegExp(schema.pattern).test(value))
errors.push(`${path}: does not match pattern ${schema.pattern}`);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
errors.push(`${path}: invalid pattern ${schema.pattern}: ${message}`);
}
}
}

if (isPlainObject(value)) {
Expand Down
23 changes: 23 additions & 0 deletions tests/scorers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,29 @@ describe("json-schema", () => {
);
expect(errs.length).toBe(2);
});
it("returns a path-attributed failure for an invalid nested pattern", async () => {
const r = await run(
jsonSchemaScorer,
{
type: "json-schema",
schema: {
type: "object",
properties: { account: { type: "string", pattern: "[0-9" } },
},
},
ctx('{"account":"123"}'),
);

expect(r.passed).toBe(false);
expect(r.score).toBe(0);
expect(r.reason).toContain("$.account: invalid pattern [0-9");
expect(r.reason).toMatch(/unterminated/i);
});
it("still reports a normal mismatch for a valid pattern", () => {
expect(validate("abc", { type: "string", pattern: "^\\d+$" })).toEqual([
"$: does not match pattern ^\\d+$",
]);
});
});

describe("embedding-similarity", () => {
Expand Down
Loading