Fix: Sanitize whitespace in $ref paths for OpenAI strict mode #1705
+33
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #1679
Problem Statement
When using
zodResponseFormatwith Zod schemas that contain property names with whitespace characters, the generated JSON Schema produces$refvalues and definition keys containing literal spaces. This causes validation failures when submitting the schema to the OpenAI API.Root Cause
In
src/_vendor/zod-to-json-schema/parseDef.tsline 134, theextract-to-rootcase joins path segments with underscores but doesn't sanitize the segments themselves. Path segments like"Thing With Spaces"preserve their internal spaces in the final$refvalue.The
join('_')method only adds separators between array elements - it does not modify the content within individual elements.Solution
Map over each path segment and replace all whitespace characters with underscores before joining:
```typescript
const name = item.path
.slice(refs.basePath.length + 1)
.map((segment) => segment.replace(/\s+/g, ''))
.join('');
```
The regex
/\s+/gmatches all types of whitespace: spaces, tabs, newlines, and Unicode whitespace characters.Testing
Unit tests:
Comprehensive edge cases validated:
No breaking changes:
Changes
Modified files:
src/_vendor/zod-to-json-schema/parseDef.ts(4 lines)tests/helpers/zod.test.ts(added comprehensive test)