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
34 changes: 24 additions & 10 deletions packages/zod/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1335,13 +1335,25 @@ const parseBodyAndResponse = ({
| OpenApiRequestBodyObject;

// Only handle JSON and form-data; other content types (e.g., application/octet-stream)
// are skipped - unclear if this is correct behavior for root-level binary/text bodies
const jsonMedia = resolvedRef.content?.['application/json'];
const formDataMedia = resolvedRef.content?.['multipart/form-data'];
const [contentType, mediaType] = jsonMedia
? (['application/json', jsonMedia] as const)
: formDataMedia
? (['multipart/form-data', formDataMedia] as const)
// are skipped - unclear if this is correct behavior for root-level binary/text bodies.
const contentEntries = Object.entries(resolvedRef.content ?? {});

const jsonContent = contentEntries.find(
isMediaType(
// application/json
// application/geo+json
// application/ld+json
// application/manifest+json
String.raw`^application\/([\w-]+\+)?json$`,
),
Comment on lines +1341 to +1348

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

JSON media-type matcher still misses valid vendor subtypes.

The current pattern rejects valid JSON media types like application/vnd.api+json (dot in subtype), so schema generation can still be skipped for legitimate responses/requests.

Suggested fix
   const jsonContent = contentEntries.find(
     isMediaType(
       // application/json
       // application/geo+json
       // application/ld+json
       // application/manifest+json
-      String.raw`^application\/([\w-]+\+)?json$`,
+      // application/vnd.api+json (and other valid vendor subtypes)
+      String.raw`^application\/([^/;]+\+)?json$`,
     ),
   );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/zod/src/index.ts` around lines 1341 - 1348, The media-type regex
used when computing jsonContent (contentEntries.find(... isMediaType(...)))
disallows dots in vendor subtype names (so types like application/vnd.api+json
are rejected); update the pattern passed to isMediaType (the
String.raw`^application\/([\w-]+\+)?json$` literal) to allow dots (and keep
existing word, plus and hyphen chars) in the subtype token (e.g. use a character
class that includes '.' such as [\w.-] or [\w.+-]) so vendor subtypes like
vnd.api+json are accepted.

);
const formDataContent = contentEntries.find(
isMediaType('multipart/form-data'),
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const [contentType, mediaType] = jsonContent
? (['application/json', jsonContent[1]] as const)
: formDataContent
? (['multipart/form-data', formDataContent[1]] as const)
: [undefined, undefined];

const schema = mediaType?.schema;
Expand All @@ -1352,7 +1364,6 @@ const parseBodyAndResponse = ({
isArray: false,
};
}

const encoding = mediaType.encoding;

const resolvedJsonSchema = dereference(schema, context);
Expand Down Expand Up @@ -1390,7 +1401,6 @@ const parseBodyAndResponse = ({
},
};
}

const effectiveSchema =
parseType === 'body'
? removeReadOnlyProperties(resolvedJsonSchema)
Expand Down Expand Up @@ -1420,6 +1430,11 @@ const parseBodyAndResponse = ({
};
};

const isMediaType =
(pattern: string) =>
([contentType]: [string, object]): boolean =>
new RegExp(pattern).test(contentType.split(';')[0].trim().toLowerCase());

const getSingleResponse = (
responses:
| Record<string, OpenApiResponseObject | OpenApiReferenceObject | undefined>
Expand All @@ -1431,7 +1446,6 @@ const getSingleResponse = (

return responses['200'] ?? responses['2XX'] ?? responses['2xx'];
};

/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */

export const parseParameters = ({
Expand Down
213 changes: 213 additions & 0 deletions packages/zod/src/zod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6273,6 +6273,219 @@ describe('generateZod (content type handling - parity with res-req-types.test.ts
})
})

`);
});

it('content type with charset precision: comprehensive content type handling', async () => {
// Matches type gen test structure in res-req-types.test.ts
const schema = {
pathRoute: '/upload-form',
context: {
spec: {
paths: {
'/upload-form': {
post: {
operationId: 'uploadForm',
requestBody: {
required: true,
content: {
'multipart/form-data; charset=utf-8': {
schema: {
type: 'object',
properties: {
encBinary: { type: 'string' },
encText: { type: 'string' },
cmtBinary: {
type: 'string',
contentMediaType: 'image/png',
},
cmtText: {
type: 'string',
contentMediaType: 'application/xml',
},
encOverride: {
type: 'string',
contentMediaType: 'image/png',
},
formatBinary: { type: 'string', format: 'binary' },
base64Field: {
type: 'string',
contentMediaType: 'image/png',
contentEncoding: 'base64',
},
metadata: {
type: 'object',
properties: { name: { type: 'string' } },
},
},
required: [
'encBinary',
'encText',
'cmtBinary',
'cmtText',
'encOverride',
'formatBinary',
'base64Field',
'metadata',
],
},
encoding: {
encBinary: { contentType: 'image/png' },
encText: { contentType: 'text/plain' },
encOverride: { contentType: 'text/csv' },
metadata: { contentType: 'application/json' },
},
},
},
},
responses: {
'200': {
content: {
'application/json; charset=utf-8': {
schema: {
type: 'object',
properties: {
success: { type: 'boolean' },
uploaded: { type: 'number' },
},
},
},
},
},
},
Comment thread
melloware marked this conversation as resolved.
},
},
},
},
output: { override: { zod: { generateEachHttpStatus: false } } },
},
} as unknown as GeneratorOptions;
const result = await generateZod(
{
pathRoute: '/upload-form',
verb: 'post',
operationName: 'uploadForm',
override: {
...zodOverride,
zod: {
...zodOverride.zod,
generate: { ...zodOverride.zod.generate, response: true },
},
},
} as unknown as Parameters<typeof generateZod>[0],
schema,
testOutput,
);
// encBinary: encoding image/png → File
// encText: encoding text/plain → File | string
// cmtBinary: contentMediaType image/png → File
// cmtText: contentMediaType application/xml → File | string
// encOverride: encoding text/csv overrides contentMediaType image/png → File | string
// formatBinary: format: binary → File (same as instanceof check)
// base64Field: contentEncoding base64 → stays string
// metadata: object → object schema
expect(result.implementation)
.toBe(`export const UploadFormBody = zod.object({
Comment thread
melloware marked this conversation as resolved.
"encBinary": zod.instanceof(File),
"encText": zod.instanceof(File).or(zod.string()),
"cmtBinary": zod.instanceof(File),
"cmtText": zod.instanceof(File).or(zod.string()),
"encOverride": zod.instanceof(File).or(zod.string()),
"formatBinary": zod.instanceof(File),
"base64Field": zod.string(),
"metadata": zod.object({
"name": zod.string().optional()
})
})

export const UploadFormResponse = zod.object({
"success": zod.boolean().optional(),
"uploaded": zod.number().optional()
})

`);
});

it('json exotic content type: comprehensive content type handling', async () => {
const schema = {
pathRoute: '/upload-form',
context: {
spec: {
paths: {
'/upload-form': {
post: {
operationId: 'uploadForm',
requestBody: {
required: true,
content: {
'application/geo+json': {
schema: {
type: 'object',
properties: {
success: { type: 'boolean' },
uploaded: { type: 'number' },
},
},
},
},
},
responses: {
'200': {
content: {
'application/manifest+json': {
schema: {
type: 'object',
properties: {
success: { type: 'boolean' },
uploaded: { type: 'number' },
},
},
},
},
},
},
},
},
},
},
output: { override: { zod: { generateEachHttpStatus: false } } },
},
} as unknown as GeneratorOptions;
const result = await generateZod(
{
pathRoute: '/upload-form',
verb: 'post',
operationName: 'uploadForm',
override: {
...zodOverride,
zod: {
...zodOverride.zod,
generate: { ...zodOverride.zod.generate, response: true },
},
},
} as unknown as Parameters<typeof generateZod>[0],
schema,
testOutput,
);
// encBinary: encoding image/png → File
// encText: encoding text/plain → File | string
// cmtBinary: contentMediaType image/png → File
// cmtText: contentMediaType application/xml → File | string
// encOverride: encoding text/csv overrides contentMediaType image/png → File | string
// formatBinary: format: binary → File (same as instanceof check)
// base64Field: contentEncoding base64 → stays string
// metadata: object → object schema
expect(result.implementation)
.toBe(`export const UploadFormBody = zod.object({
"success": zod.boolean().optional(),
"uploaded": zod.number().optional()
})

export const UploadFormResponse = zod.object({
"success": zod.boolean().optional(),
"uploaded": zod.number().optional()
})

`);
});
});
Expand Down
Loading