Skip to content

Support patternProperties for z.looseRecord()#5592

Merged
colinhacks merged 1 commit intomainfrom
patternproperties
Dec 31, 2025
Merged

Support patternProperties for z.looseRecord()#5592
colinhacks merged 1 commit intomainfrom
patternproperties

Conversation

@colinhacks
Copy link
Owner

No description provided.

Copy link
Contributor

@pullfrog pullfrog bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a solid improvement for JSON Schema generation. One critical semantic issue identified with multiple regex patterns—see inline comment for details.

Pullfrog  | Fix all ➔Fix 👍s ➔View workflow runpullfrog.com𝕏

});
json.patternProperties = {};
for (const pattern of patterns) {
json.patternProperties[pattern.source] = valueSchema;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical semantic mismatch: When multiple regex patterns are chained (e.g., .regex(/^prefix_/).regex(/_suffix$/)), the zod runtime requires keys to match ALL patterns (AND semantics). However, this implementation outputs separate entries in patternProperties, which in JSON Schema means a key only needs to match ONE pattern (OR semantics). For example, with the test case patterns ^prefix_ and _suffix$, a key like prefix_foo would be valid in JSON Schema (matches first pattern) but invalid in zod runtime (doesn't match second pattern). Consider either: (1) combining multiple patterns into a single pattern with AND semantics (complex), (2) documenting this limitation, or (3) only using the most restrictive pattern.


if (def.mode === "loose" && patterns && patterns.size > 0) {
// Use patternProperties for looseRecord with regex patterns
const valueSchema = process(def.valueType, ctx as any, {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The same valueSchema object is reused for all patterns. If process returns a mutable object, this could cause issues. Consider cloning the schema for each pattern or verify that process returns immutable objects.

@colinhacks colinhacks merged commit e01cd02 into main Dec 31, 2025
8 of 9 checks passed
@colinhacks colinhacks deleted the patternproperties branch December 31, 2025 21:08
@rickosborne
Copy link

Hey, this is awesome. Thanks so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants