Skip to content
Closed
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
10 changes: 8 additions & 2 deletions src/scorers/json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,14 @@ 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) {
errors.push(`${path}: invalid pattern ${schema.pattern}: ${(err as Error).message}`);
}
}
}

if (isPlainObject(value)) {
Expand Down
9 changes: 9 additions & 0 deletions tests/scorers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,15 @@ describe("json-schema", () => {
);
expect(errs.length).toBe(2);
});
it("fails cleanly when a schema pattern is invalid", async () => {
const r = await run(
jsonSchemaScorer,
{ type: "json-schema", schema: { type: "string", pattern: "[a-z" } },
ctx('"abc"'),
);
expect(r.passed).toBe(false);
expect(r.reason).toContain("invalid pattern");
});
});

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