Support patternProperties for z.looseRecord()#5592
Conversation
There was a problem hiding this comment.
This is a solid improvement for JSON Schema generation. One critical semantic issue identified with multiple regex patterns—see inline comment for details.
| }); | ||
| json.patternProperties = {}; | ||
| for (const pattern of patterns) { | ||
| json.patternProperties[pattern.source] = valueSchema; |
There was a problem hiding this comment.
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, { |
There was a problem hiding this comment.
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.
|
Hey, this is awesome. Thanks so much! |

No description provided.