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: 26 additions & 8 deletions packages/zod/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1335,13 +1335,27 @@ 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)
// 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 contentEntries = Object.entries(resolvedRef.content ?? {});

const jsonContent = contentEntries.find(
isMediaType(
// application/json
// application/geo+json
// application/ld+json
// application/manifest+json
// application/vnd.api+json (and other valid vendor subtypes)
String.raw`^application\/([^/;]+\+)?json$`,
),
);
const formDataContent = contentEntries.find(
isMediaType(String.raw`^multipart\/form-data$`),
);
Comment thread
melloware 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 +1366,6 @@ const parseBodyAndResponse = ({
isArray: false,
};
}

const encoding = mediaType.encoding;

const resolvedJsonSchema = dereference(schema, context);
Expand Down Expand Up @@ -1420,6 +1433,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 Down
130 changes: 130 additions & 0 deletions packages/zod/src/zod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6273,6 +6273,136 @@ 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' },
},
},
},
},
},
},
},
},
},
},
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({
"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()
})

`);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const getSearchPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -80,7 +80,7 @@ export const getListPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -121,7 +121,7 @@ export const getListPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand All @@ -144,17 +144,17 @@ export const getShowPetByIdResponseMock = () =>
(() => ({
id: faker.number.int({ min: 1, max: 99 }),
name: faker.person.firstName(),
tag: faker.helpers.arrayElement([faker.word.sample(), undefined]),
tag: faker.helpers.arrayElement([faker.word.sample(), void 0]),
status: faker.helpers.arrayElement(['available', 'pending', 'sold']),
requiredNullableString: null,
optionalNullableString: faker.helpers.arrayElement([
faker.word.sample(),
null,
undefined,
void 0,
]),
phone: faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]),
}))();

Expand Down Expand Up @@ -183,7 +183,7 @@ export const getUpdatePetByIdResponseMock = (
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -229,7 +229,7 @@ export const getPatchPetByIdResponseMock = (
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down
16 changes: 8 additions & 8 deletions samples/angular-app/__snapshots__/api/http-both/pets/pets.msw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const getSearchPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -80,7 +80,7 @@ export const getListPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -121,7 +121,7 @@ export const getListPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand All @@ -144,17 +144,17 @@ export const getShowPetByIdResponseMock = () =>
(() => ({
id: faker.number.int({ min: 1, max: 99 }),
name: faker.person.firstName(),
tag: faker.helpers.arrayElement([faker.word.sample(), undefined]),
tag: faker.helpers.arrayElement([faker.word.sample(), void 0]),
status: faker.helpers.arrayElement(['available', 'pending', 'sold']),
requiredNullableString: null,
optionalNullableString: faker.helpers.arrayElement([
faker.word.sample(),
null,
undefined,
void 0,
]),
phone: faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]),
}))();

Expand Down Expand Up @@ -183,7 +183,7 @@ export const getUpdatePetByIdResponseMock = (
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -229,7 +229,7 @@ export const getPatchPetByIdResponseMock = (
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const getSearchPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -80,7 +80,7 @@ export const getListPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -121,7 +121,7 @@ export const getListPetsResponseMock = (): Pets =>
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand All @@ -144,17 +144,17 @@ export const getShowPetByIdResponseMock = () =>
(() => ({
id: faker.number.int({ min: 1, max: 99 }),
name: faker.person.firstName(),
tag: faker.helpers.arrayElement([faker.word.sample(), undefined]),
tag: faker.helpers.arrayElement([faker.word.sample(), void 0]),
status: faker.helpers.arrayElement(['available', 'pending', 'sold']),
requiredNullableString: null,
optionalNullableString: faker.helpers.arrayElement([
faker.word.sample(),
null,
undefined,
void 0,
]),
phone: faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]),
}))();

Expand Down Expand Up @@ -183,7 +183,7 @@ export const getUpdatePetByIdResponseMock = (
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down Expand Up @@ -229,7 +229,7 @@ export const getPatchPetByIdResponseMock = (
phone: (() =>
faker.helpers.arrayElement([
`+1${faker.string.numeric({ length: 10 })}`,
undefined,
void 0,
]))(),
requiredNullableString: faker.helpers.arrayElement([
faker.helpers.arrayElement([
Expand Down
Loading
Loading