zod-nest 3.0.2 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/helpers/fragments.ts","../../src/schema/custom-override.ts","../../src/multipart/file-checks.ts","../../src/multipart/file-marker.ts","../../src/multipart/build-file-schema.ts","../../src/multipart/metadata.ts","../../src/schema/discover-dependents.ts","../../src/schema/constants.ts","../../src/schema/registry.ts","../../src/schema/composition.ts","../../src/schema/errors.ts","../../src/schema/override.ts","../../src/schema/post-process.ts","../../src/schema/engine.ts","../../src/multipart/zod-multipart.decorator.ts","../../src/exceptions/validation.exception.ts","../../src/multipart/param-decorators.ts","../../src/express/index.ts"],"names":["binaryFragment","type","format","binary","opts","customOverrideMap","WeakMap","isWrapper","arg","overrideJSONSchema","schema","overrideSchema","input","output","schemaDescription","description","set","peekRegistration","get","createCustomOverride","io","zodSchema","jsonSchema","record","undefined","fragment","key","Object","keys","Reflect","deleteProperty","assign","normalizeExtension","extension","startsWith","toLowerCase","mimeTypeCheck","accessors","options","allowed","Set","mimeTypes","map","mimeType","payload","value","has","issues","push","code","message","join","extensionCheck","extensions","fileName","matched","some","endsWith","sizeCheck","readSize","size","maxSize","fileSchemas","WeakSet","isZodType","unwrapOnce","def","_zod","innerType","element","markFileSchema","add","isFileSchema","inner","resolveFragment","contentMediaType","singleMimeType","length","collectChecks","params","checks","withId","id","meta","buildFileSchema","base","z","custom","predicate","checked","check","MultipartFilesIn","Request","Body","ZOD_MULTIPART_METADATA_KEY","Symbol","for","INNER_TYPE_WRAPPERS","readId","globalRegistry","resolveLazyTarget","getter","error","ReferenceError","collectChildren","out","shape","values","catchall","opt","left","right","items","it","rest","keyType","valueType","in","discoverDependents","visited","stack","current","pop","child","COMPONENTS_SCHEMAS_PREFIX","DEFS_PREFIX","ZOD_NEST_ERROR_EXTENSION","ZOD_NEST_ERROR_DUPLICATE_ID","createRegistry","seen","Map","forceExposed","anonymous","pendingRoots","recordOnce","flushPendingDiscovery","root","splice","childId","zodRegistry","register","flags","expose","existing","hasCollision","getCollisions","ids","forceExposedIds","anonymousIds","defaultRegistry","registerSchema","registry","explicit","metaId","lineageMap","propsMap","DEFAULT_BUILD_REF","createCompositionOverride","buildRef","ctx","entry","parentCache","parent","parentId","childProps","properties","childRequired","required","parentPropSet","parentReqSet","deltaProps","entries","overriddenKeys","deltaRequired","filter","delta","additionalProperties","allOf","$ref","unevaluatedProperties","ZodNestError","Error","name","ZodNestUnrepresentableError","path","zodType","formatPath","String","primitiveOverride","combine","overrides","list","candidate","o","rewriteRefs","node","rootRef","Array","isArray","item","obj","ref","slice","refsIn","rootDefId","raw","isReferenced","defs","ownRef","referencesRoot","stripEnvelope","$schema","$defs","resolveRoot","refs","liftedId","body","delete","rootId","strict","postProcess","rawDefs","STRICT_REQUIRES_OVERRIDE","ANNOTATION_ONLY_KEYS","isStrictlyUnrepresentable","every","markPipeCoverage","covered","target","traits","buildToJsonSchemaOptions","compositionOverride","uri","customOverride","merged","override","unrepresentableHits","coveredByPipe","wrapped","unrepresentable","metadata","cycles","reused","consumeUnrepresentable","firstHit","find","hit","resolveRootId","toOpenApi","built","toJSONSchema","result","MULTIPART_CONTENT_TYPE","partitionKeys","fileKeys","textKeys","emitInlineBody","object","createZodMultipart","defaultFilesIn","filesIn","propertyKey","descriptor","handler","TypeError","defineMetadata","swaggerDescriptor","ApiConsumes","ApiBody","ZodValidationException","BadRequestException","zodError","argMetadata","statusCode","HttpStatus","BAD_REQUEST","errors","treeifyError","cause","readMetadata","decorator","getMetadata","getHandler","isMultipartMetadata","schemaFor","pick","wanted","picked","validate","argType","safeParseAsync","success","data","metatype","assertFilesOnRequest","resolveUploadedFile","request","switchToHttp","getRequest","file","resolveUploadedFiles","files","resolveMultipartBody","_data","ZodUploadedFile","createParamDecorator","ZodUploadedFiles","ZodMultipartBody","hasCommonFields","isMulterMemoryFile","Buffer","isBuffer","buffer","isMulterDiskFile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MAAAA,GAAY;AAAEqC,IAAAA,OAAAA,EAASvB,OAAAA,CAAQuB;AAAQ,GAAA,GAAI;AACtE,CAAA,CAAA,EAR8B,kBAAA;AAWzB,IAAMkQ,cAAAA,mBAAiB,MAAA,CAAA,CAC5BzR,OAAAA,KAEA8C,eAAAA,CAAoC;EAClCI,SAAAA,EAAWiO,gBAAAA;EACXpR,SAAAA,EAAWwR,aAAAA;AACXvR,EAAAA,OAAAA;EACA,GAAIA,OAAAA,EAASuB,YAAYrC,MAAAA,GAAY;AAAEqC,IAAAA,OAAAA,EAASvB,OAAAA,CAAQuB;AAAQ,GAAA,GAAI;AACtE,CAAA,CAAA,EAR4B,gBAAA;AAWvB,IAAMmQ,yBAAyBF,gBAAAA;AAG/B,IAAMG,uBAAuBF,cAAAA;AAQ7B,IAAMG,YAAAA,GAAehE,kBAAAA,CAAmBvK,gBAAAA,CAAiBC,OAAO","file":"index.js","sourcesContent":["import type { SchemaObject } from '../schema/openapi.types.js';\n\n/**\n * Common JSON Schema fragment catalog — reusable building blocks for assembling\n * fragments by hand: alongside `z.custom<T>()`, in `overrideJSONSchema` calls,\n * in custom override callbacks, in tests that build expected fragments.\n *\n * The catalog overlaps with what Zod constructs already emit (`z.uuid()` →\n * `uuidFragment` shape, `z.email()` → `emailFragment` shape, etc.) — the\n * helpers don't *replace* those Zod constructs; they're a parallel catalog\n * for programmatic fragment assembly.\n *\n * Each fragment is `as const satisfies SchemaObject` so its literal type\n * powers the dispatch in {@link enrich} — passing wrong-family options\n * fails at compile time.\n */\n\n// ---------------------------------------------------------------------------\n// Layer 1 — Fragment catalog\n// ---------------------------------------------------------------------------\n\n// String formats (RFC-defined)\nexport const dateTimeFragment = {\n type: 'string',\n format: 'date-time',\n} as const satisfies SchemaObject;\nexport const dateFragment = { type: 'string', format: 'date' } as const satisfies SchemaObject;\nexport const timeFragment = { type: 'string', format: 'time' } as const satisfies SchemaObject;\nexport const uuidFragment = { type: 'string', format: 'uuid' } as const satisfies SchemaObject;\nexport const emailFragment = { type: 'string', format: 'email' } as const satisfies SchemaObject;\nexport const uriFragment = { type: 'string', format: 'uri' } as const satisfies SchemaObject;\nexport const hostnameFragment = {\n type: 'string',\n format: 'hostname',\n} as const satisfies SchemaObject;\nexport const ipv4Fragment = { type: 'string', format: 'ipv4' } as const satisfies SchemaObject;\nexport const ipv6Fragment = { type: 'string', format: 'ipv6' } as const satisfies SchemaObject;\n\n// Binary / encoded payloads\nexport const binaryFragment = { type: 'string', format: 'binary' } as const satisfies SchemaObject;\nexport const byteFragment = { type: 'string', format: 'byte' } as const satisfies SchemaObject;\n\n// Numeric formats (OpenAPI 3.1)\nexport const int32Fragment = { type: 'integer', format: 'int32' } as const satisfies SchemaObject;\nexport const int64Fragment = { type: 'integer', format: 'int64' } as const satisfies SchemaObject;\nexport const floatFragment = { type: 'number', format: 'float' } as const satisfies SchemaObject;\nexport const doubleFragment = { type: 'number', format: 'double' } as const satisfies SchemaObject;\n\n// Object passthrough\nexport const opaqueFragment = {\n type: 'object',\n additionalProperties: true,\n} as const satisfies SchemaObject;\n\n// ---------------------------------------------------------------------------\n// Layer 2 — Per-family option types\n// ---------------------------------------------------------------------------\n\nexport interface StringFormatOptions {\n description?: string;\n examples?: string[];\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n}\n\nexport interface BinaryFragmentOptions {\n description?: string;\n contentMediaType?: string;\n contentEncoding?: string;\n}\n\nexport interface NumberFormatOptions {\n description?: string;\n examples?: number[];\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n multipleOf?: number;\n}\n\nexport interface OpaqueFragmentOptions {\n description?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Layer 3 — Type-strict generic enrich\n// ---------------------------------------------------------------------------\n\n// `binary` discriminates before the generic string-format branch because its\n// option set diverges (contentMediaType / contentEncoding instead of length\n// constraints). Order matters here.\ntype OptionsFor<T> = T extends { readonly format: 'binary' }\n ? BinaryFragmentOptions\n : T extends {\n readonly format:\n | 'date-time'\n | 'date'\n | 'time'\n | 'uuid'\n | 'email'\n | 'uri'\n | 'hostname'\n | 'ipv4'\n | 'ipv6'\n | 'byte';\n }\n ? StringFormatOptions\n : T extends { readonly format: 'int32' | 'int64' | 'float' | 'double' }\n ? NumberFormatOptions\n : T extends { readonly type: 'object'; readonly additionalProperties: true }\n ? OpaqueFragmentOptions\n : never;\n\n/**\n * Merge a catalog fragment with extras whose shape is dictated by the base\n * fragment's family. Passing wrong-family extras (e.g. a `contentMediaType`\n * onto `uuidFragment`) is a compile-time error.\n *\n * Returns a fresh `SchemaObject` — the original fragment is never mutated.\n */\nexport const enrich = <T extends SchemaObject>(base: T, extras: OptionsFor<T>): SchemaObject => ({\n ...base,\n ...extras,\n});\n\n// ---------------------------------------------------------------------------\n// Layer 3b — Sugar functions\n// ---------------------------------------------------------------------------\n\n/**\n * Binary-content fragment with typed enrichment. Sugar for\n * `enrich(binaryFragment, opts)` — exists because the `binary` option set\n * (`contentMediaType` / `contentEncoding`) is nuanced enough to deserve a\n * dedicated entry point and discoverable via auto-complete.\n *\n * @example\n * overrideJSONSchema(z.instanceof(File), binary());\n * overrideJSONSchema(z.instanceof(File), binary({ contentMediaType: 'application/pdf' }));\n */\nexport const binary = (opts?: BinaryFragmentOptions): SchemaObject => ({\n ...binaryFragment,\n ...opts,\n});\n\n/**\n * Opaque-object fragment with typed enrichment. Sugar for\n * `enrich(opaqueFragment, opts)` — exists for parity with {@link binary}\n * and because opaque passthrough payloads commonly carry a description\n * explaining why the API doesn't introspect them.\n *\n * @example\n * overrideJSONSchema(z.unknown(), opaque({ description: 'JWT passthrough' }));\n */\nexport const opaque = (opts?: OpaqueFragmentOptions): SchemaObject => ({\n ...opaqueFragment,\n ...opts,\n});\n","import type { z } from 'zod';\nimport type { $ZodType } from 'zod/v4/core';\nimport type { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\n\n/**\n * Argument shape for {@link overrideJSONSchema}. Two forms:\n *\n * - A raw `SchemaObject` — applied to both input and output emission.\n * - A `{ input?, output? }` wrapper — distinct fragments per emission side,\n * for coercion shapes where input and output diverge (e.g.\n * `z.union([z.array(item), item.transform((v) => [v])])` accepts\n * `T | T[]` on input but always emits `T[]` on output).\n *\n * The wrapper form is detected by the presence of an `input` or `output`\n * key. Neither is a JSON Schema / OpenAPI 3.1 keyword, so the discriminator\n * is unambiguous in practice.\n */\nexport type OverrideJSONSchemaArg = SchemaObject | { input?: SchemaObject; output?: SchemaObject };\n\nexport interface StoredFragments {\n input?: SchemaObject;\n output?: SchemaObject;\n /**\n * Description captured from the Zod schema at `overrideJSONSchema(...)` call\n * time (`.describe(...)` / `.meta({ description })` both write to\n * `z.globalRegistry`). Applied as a fallback at emission time when the\n * per-direction fragment doesn't supply its own `description`. Fragment-\n * supplied descriptions still win.\n */\n description?: string;\n}\n\n/**\n * Per-instance JSON Schema registration store. Keyed by the Zod core type\n * (`$ZodType`) because that's what the override sees on `ctx.zodSchema`;\n * `z.ZodType` widens to `$ZodType` without a cast at the public API boundary.\n * Same WeakMap pattern as `composition.ts`'s `lineageMap`\n * (CLAUDE.md: \"transient, per-instance → WeakMap\").\n *\n * Value holds the per-direction fragments separately so the override factory\n * can pick the right one without surfacing `io` on `OverrideContext`.\n */\nconst customOverrideMap = new WeakMap<$ZodType, StoredFragments>();\n\nconst isWrapper = (\n arg: OverrideJSONSchemaArg,\n): arg is { input?: SchemaObject; output?: SchemaObject } => 'input' in arg || 'output' in arg;\n\n/**\n * Register a fixed JSON Schema fragment for a specific Zod schema instance.\n *\n * Designed for shapes JSON Schema can't model directly — `z.custom<T>()` and\n * `z.instanceof(...)` (e.g. multipart `File` fields) — which Zod emits as `{}`,\n * tripping `ZodNestUnrepresentableError` in strict mode. Also useful for\n * coercion shapes where input and output diverge (`singleOrArray`-style\n * helpers).\n *\n * Two call shapes:\n *\n * ```ts\n * // 1. Single fragment — applied verbatim to both input and output emission.\n * overrideJSONSchema(FileSchema, { type: 'string', format: 'binary' });\n *\n * // 2. Divergent fragments — separate fragments per emission side. Omit a\n * // side to leave Zod's default emission untouched on that side.\n * overrideJSONSchema(arrayOrItem, {\n * input: { anyOf: [arrFrag, itemFrag] },\n * output: arrFrag,\n * });\n * ```\n *\n * Idempotent: subsequent calls for the same schema overwrite the prior\n * registration (last-write-wins).\n */\nexport const overrideJSONSchema = <T extends z.ZodType>(\n schema: T,\n arg: OverrideJSONSchemaArg,\n): T => {\n const overrideSchema: StoredFragments = isWrapper(arg) ? { ...arg } : { input: arg, output: arg };\n\n const schemaDescription = schema.description;\n if (typeof schemaDescription === 'string') {\n overrideSchema.description = schemaDescription;\n }\n\n customOverrideMap.set(schema, overrideSchema);\n\n return schema;\n};\n\n/**\n * Read-only lookup into the registration store. Used by the engine to detect\n * when a pipe-typed schema covers its inner descent target with a relevant-io\n * fragment — see `buildToJsonSchemaOptions` in `engine.ts`. Returning a\n * possibly-`undefined` `StoredFragments` keeps the engine ignorant of the\n * underlying WeakMap.\n */\nexport const peekRegistration = (schema: $ZodType): StoredFragments | undefined =>\n customOverrideMap.get(schema);\n\n/**\n * Internal override factory consulted by the engine. Closes over the current\n * emission direction so the lookup can pick the right registered fragment\n * without surfacing `io` on the `OverrideContext` public contract. Mirrors\n * `createCompositionOverride` at `engine.ts:98`.\n *\n * Mutates `ctx.jsonSchema` in-place (clears existing keys, then assigns the\n * fragment) because Zod's override pipeline doesn't propagate\n * `ctx.jsonSchema = newObj` reassignments — only mutations on the existing\n * object reach the caller (see `composition.ts` for the same constraint).\n *\n * Falls back to the schema's captured `description` (from `.describe(...)` /\n * `.meta({ description })`) when the per-direction fragment doesn't supply\n * one. Captured at `overrideJSONSchema(...)` call time so the inheritance\n * doesn't depend on Zod's emission-time metadata pass. `title` is\n * deliberately not inherited.\n *\n * No-ops if the schema isn't registered, or if the registered record has no\n * fragment for the current `io` direction.\n */\nexport const createCustomOverride = (io: 'input' | 'output'): Override => {\n return ({ zodSchema, jsonSchema }) => {\n const record = customOverrideMap.get(zodSchema);\n if (record === undefined) {\n return;\n }\n const fragment = record[io];\n if (fragment === undefined) {\n return;\n }\n for (const key of Object.keys(jsonSchema)) {\n Reflect.deleteProperty(jsonSchema, key);\n }\n Object.assign(jsonSchema, fragment);\n if (fragment.description === undefined && record.description !== undefined) {\n jsonSchema.description = record.description;\n }\n };\n};\n","import type { z } from 'zod';\n\n/**\n * Reads the fields a check needs off a platform file object. Multer names the\n * client filename `originalname`, `@fastify/multipart` names it `filename`,\n * and only multer reports a `size` — so each platform supplies its own\n * accessors instead of the library inventing a common shape.\n */\nexport interface FileAccessors<TFile> {\n readonly mimeType: (file: TFile) => string;\n readonly fileName: (file: TFile) => string;\n readonly size?: (file: TFile) => number;\n}\n\nexport interface MimeTypeCheckOptions {\n readonly mimeTypes: readonly string[];\n}\n\nexport interface ExtensionCheckOptions {\n readonly extensions: readonly string[];\n}\n\nexport interface SizeCheckOptions {\n readonly maxSize: number;\n}\n\nexport type FileCheck<TFile> = (payload: z.core.ParsePayload<TFile>) => void;\n\nconst normalizeExtension = (extension: string): string =>\n extension.startsWith('.') ? extension.toLowerCase() : `.${extension.toLowerCase()}`;\n\nexport const mimeTypeCheck = <TFile>(\n accessors: FileAccessors<TFile>,\n options: MimeTypeCheckOptions,\n): FileCheck<TFile> => {\n const allowed = new Set(options.mimeTypes.map((mimeType) => mimeType.toLowerCase()));\n return (payload) => {\n const mimeType = accessors.mimeType(payload.value).toLowerCase();\n if (allowed.has(mimeType)) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected one of ${options.mimeTypes.join(', ')}, received ${mimeType}`,\n });\n };\n};\n\nexport const extensionCheck = <TFile>(\n accessors: FileAccessors<TFile>,\n options: ExtensionCheckOptions,\n): FileCheck<TFile> => {\n const allowed = new Set(options.extensions.map(normalizeExtension));\n return (payload) => {\n const fileName = accessors.fileName(payload.value).toLowerCase();\n const matched = [...allowed].some((extension) => fileName.endsWith(extension));\n if (matched) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected a file ending in ${options.extensions.map(normalizeExtension).join(', ')}, received ${fileName}`,\n });\n };\n};\n\nexport const sizeCheck = <TFile>(\n readSize: (file: TFile) => number,\n options: SizeCheckOptions,\n): FileCheck<TFile> => {\n return (payload) => {\n const size = readSize(payload.value);\n if (size <= options.maxSize) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected at most ${options.maxSize} bytes, received ${size}`,\n });\n };\n};\n","import type { z } from 'zod';\n\n/**\n * Per-instance tag for schemas produced by the platform file factories.\n * WeakSet rather than `z.registry` because this is transient per-instance\n * annotation, not stable id-keyed metadata (CLAUDE.md).\n */\nconst fileSchemas = new WeakSet<z.ZodType>();\n\n// Wrapper defs expose their inner schema as Zod's internal `$ZodType`, which\n// the `in` narrowing widens to `unknown`. Guarding is the cast-free way back\n// to the public type.\nconst isZodType = (value: unknown): value is z.ZodType =>\n value !== null && typeof value === 'object' && '_zod' in value;\n\nconst unwrapOnce = (schema: z.ZodType): z.ZodType | undefined => {\n const def = schema._zod.def;\n if ('innerType' in def) {\n return isZodType(def.innerType) ? def.innerType : undefined;\n }\n if ('element' in def) {\n return isZodType(def.element) ? def.element : undefined;\n }\n return undefined;\n};\n\nexport const markFileSchema = <T extends z.ZodType>(schema: T): T => {\n fileSchemas.add(schema);\n return schema;\n};\n\n/**\n * True for a factory-produced file schema and for `.optional()` / `.array()`\n * wrappers around one — an optional or repeated file field is still a file\n * field for the request-vs-body split.\n */\nexport const isFileSchema = (schema: z.ZodType): boolean => {\n if (fileSchemas.has(schema)) {\n return true;\n }\n const inner = unwrapOnce(schema);\n if (inner === undefined) {\n return false;\n }\n return isFileSchema(inner);\n};\n","import { z } from 'zod';\n\nimport type { SchemaObject } from '../schema/openapi.types.js';\nimport type { FileAccessors, FileCheck } from './file-checks.js';\n\nimport { binary } from '../helpers/fragments.js';\nimport { overrideJSONSchema } from '../schema/custom-override.js';\nimport { extensionCheck, mimeTypeCheck, sizeCheck } from './file-checks.js';\nimport { markFileSchema } from './file-marker.js';\n\nexport interface BaseFileOptions {\n /**\n * Registry id for the schema. Set it to get a reusable\n * `components.schemas` entry that every field `$ref`s, instead of the\n * fragment being inlined at each use site. There is no `title` counterpart\n * — `overrideJSONSchema` replaces the emitted body and does not carry\n * `title` into it, so one would have no effect.\n */\n readonly id?: string;\n /** Allowed MIME types, matched case-insensitively against the client-supplied value. */\n readonly mimeTypes?: readonly string[];\n /** Allowed filename extensions, with or without a leading dot. */\n readonly extensions?: readonly string[];\n /** OpenAPI `description` for the emitted binary property. */\n readonly description?: string;\n /** Overrides the `contentMediaType` derived from a single-entry `mimeTypes`. */\n readonly contentMediaType?: string;\n}\n\nexport interface BuildFileSchemaParams<TFile> {\n readonly predicate: (value: unknown) => boolean;\n readonly accessors: FileAccessors<TFile>;\n readonly options: BaseFileOptions | undefined;\n /** Byte-size ceiling. Only platforms that report a size pass this. */\n readonly maxSize?: number;\n}\n\nconst resolveFragment = (options: BaseFileOptions | undefined): SchemaObject => {\n const contentMediaType = options?.contentMediaType ?? singleMimeType(options?.mimeTypes);\n return binary({\n ...(options?.description !== undefined ? { description: options.description } : {}),\n ...(contentMediaType !== undefined ? { contentMediaType } : {}),\n });\n};\n\nconst singleMimeType = (mimeTypes: readonly string[] | undefined): string | undefined => {\n if (mimeTypes === undefined || mimeTypes.length !== 1) {\n return undefined;\n }\n return mimeTypes[0];\n};\n\nconst collectChecks = <TFile>(params: BuildFileSchemaParams<TFile>): Array<FileCheck<TFile>> => {\n const { accessors, options, maxSize } = params;\n const checks: Array<FileCheck<TFile>> = [];\n if (options?.mimeTypes !== undefined) {\n checks.push(mimeTypeCheck(accessors, { mimeTypes: options.mimeTypes }));\n }\n if (options?.extensions !== undefined) {\n checks.push(extensionCheck(accessors, { extensions: options.extensions }));\n }\n if (maxSize !== undefined && accessors.size !== undefined) {\n checks.push(sizeCheck(accessors.size, { maxSize }));\n }\n return checks;\n};\n\nconst withId = <TFile>(\n schema: z.ZodType<TFile, TFile>,\n options: BaseFileOptions | undefined,\n fragment: SchemaObject,\n): z.ZodType<TFile, TFile> => {\n if (options?.id === undefined) {\n return schema;\n }\n return overrideJSONSchema(schema.meta({ id: options.id }), fragment);\n};\n\n/**\n * Assemble a platform file schema: duck-typing predicate, the option checks,\n * then `.meta({ id })` — re-registering the binary fragment after every step.\n *\n * Each registration is load-bearing. `overrideJSONSchema` keys its fragment on\n * the schema *instance*, and both `.check()` and `.meta()` clone. Emission\n * visits every instance in the chain, so a step left unregistered emits `{}`\n * — as a bare `{}` property in strict mode, or as an empty `components.schemas`\n * entry when the schema is named.\n */\nexport const buildFileSchema = <TFile>(\n params: BuildFileSchemaParams<TFile>,\n): z.ZodType<TFile, TFile> => {\n const fragment = resolveFragment(params.options);\n const base = overrideJSONSchema(z.custom<TFile>(params.predicate), fragment);\n const checks = collectChecks(params);\n const checked = checks.length === 0 ? base : overrideJSONSchema(base.check(...checks), fragment);\n return markFileSchema(withId(checked, params.options, fragment));\n};\n","import type { z } from 'zod';\n\n/**\n * Where the multipart parser puts uploaded files. Multer leaves them on the\n * request (`req.file` / `req.files`) with only text fields in `req.body`;\n * `@fastify/multipart` with `attachFieldsToBody: true` puts everything in\n * `req.body`.\n */\nexport const MultipartFilesIn = {\n Request: 'request',\n Body: 'body',\n} as const;\n\nexport type MultipartFilesIn = (typeof MultipartFilesIn)[keyof typeof MultipartFilesIn];\n\n/** Shape accepted by `@ZodMultipart` — one Zod schema per form field. */\nexport type MultipartShape = Readonly<Record<string, z.ZodType>>;\n\nexport interface MultipartMetadata {\n readonly shape: MultipartShape;\n readonly fileKeys: readonly string[];\n readonly textKeys: readonly string[];\n readonly filesIn: MultipartFilesIn;\n}\n\n/**\n * Metadata key for the shape declared by `@ZodMultipart`. `Symbol.for` so\n * consumers in other realms read the same registry (CLAUDE.md).\n */\nexport const ZOD_MULTIPART_METADATA_KEY = Symbol.for('zod-nest.multipart');\n","import { z } from 'zod';\n\nimport type { $ZodType, $ZodTypes } from 'zod/v4/core';\n\nconst INNER_TYPE_WRAPPERS = new Set([\n 'optional',\n 'nullable',\n 'default',\n 'prefault',\n 'catch',\n 'nonoptional',\n 'success',\n 'readonly',\n 'promise',\n]);\n\nconst readId = (schema: z.ZodType): string | undefined => {\n const meta = z.globalRegistry.get(schema);\n if (meta === undefined) {\n return undefined;\n }\n const id = (meta as { id?: unknown }).id;\n return typeof id === 'string' ? id : undefined;\n};\n\n// A `z.lazy` getter can close over a `const` still in its temporal dead zone\n// (mutual recursion under ESM). Treat that as \"no child yet\" — `toOpenApi`\n// calls the getter again and reports a genuinely broken reference then.\nconst resolveLazyTarget = (getter: () => $ZodType): z.ZodType[] => {\n try {\n return [getter() as unknown as z.ZodType];\n } catch (error) {\n if (error instanceof ReferenceError) {\n return [];\n }\n throw error;\n }\n};\n\nconst collectChildren = (schema: z.ZodType): z.ZodType[] => {\n const def = (schema as unknown as $ZodTypes)._zod.def;\n if (def.type === 'object') {\n const out: z.ZodType[] = [];\n const shape = def.shape as Record<string, z.ZodType> | undefined;\n if (shape !== undefined) {\n for (const value of Object.values(shape)) {\n out.push(value);\n }\n }\n if (def.catchall !== undefined) {\n out.push(def.catchall as unknown as z.ZodType);\n }\n return out;\n }\n if (def.type === 'array') {\n return [def.element as unknown as z.ZodType];\n }\n if (def.type === 'union') {\n return (def.options as readonly $ZodType[]).map((opt) => opt as unknown as z.ZodType);\n }\n if (def.type === 'intersection') {\n return [def.left as unknown as z.ZodType, def.right as unknown as z.ZodType];\n }\n if (def.type === 'tuple') {\n const out: z.ZodType[] = (def.items as readonly $ZodType[]).map(\n (it) => it as unknown as z.ZodType,\n );\n if (def.rest !== null) {\n out.push(def.rest as unknown as z.ZodType);\n }\n return out;\n }\n if (def.type === 'record' || def.type === 'map') {\n return [def.keyType as unknown as z.ZodType, def.valueType as unknown as z.ZodType];\n }\n if (def.type === 'set') {\n return [def.valueType as unknown as z.ZodType];\n }\n if (def.type === 'pipe') {\n return [def.in as unknown as z.ZodType, def.out as unknown as z.ZodType];\n }\n if (def.type === 'lazy') {\n return resolveLazyTarget(() => def.getter());\n }\n if (INNER_TYPE_WRAPPERS.has(def.type)) {\n return [(def as { innerType: $ZodType }).innerType as unknown as z.ZodType];\n }\n return [];\n};\n\n/**\n * Returns every named descendant of `schema` — sub-schemas carrying\n * `.meta({ id })` reachable through the Zod composition tree, at any depth.\n *\n * Cycle-safe via a visited `WeakSet` keyed by Zod schema identity; safe for\n * `z.lazy` schemas that close over themselves. Leaf types (string, number,\n * enum, literal, custom, transform, …) have no children and are skipped.\n */\nexport const discoverDependents = (schema: z.ZodType): ReadonlyArray<[z.ZodType, string]> => {\n const visited = new WeakSet<z.ZodType>();\n const out: [z.ZodType, string][] = [];\n const stack: z.ZodType[] = [schema];\n while (stack.length > 0) {\n const current = stack.pop() as z.ZodType;\n if (visited.has(current)) {\n continue;\n }\n visited.add(current);\n for (const child of collectChildren(current)) {\n // Defensive: a malformed/in-progress schema can yield an undefined slot\n // (sparse object shape, undefined tuple item, etc.). The walker treats\n // such slots as \"no child here\" rather than crashing — the user's\n // schema may still emit fine through `toJSONSchema`.\n if (child === undefined || visited.has(child)) {\n continue;\n }\n const id = readId(child);\n if (id !== undefined) {\n out.push([child, id]);\n }\n stack.push(child);\n }\n }\n return out;\n};\n","/** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */\nexport const COMPONENTS_SCHEMAS_PREFIX = '#/components/schemas/';\n\n/** JSON Schema `$ref` prefix for entries in `$defs` (single-schema emission). */\nexport const DEFS_PREFIX = '#/$defs/';\n\n/** OpenAPI extension key zod-nest uses to surface engine errors inside emitted schemas. */\nexport const ZOD_NEST_ERROR_EXTENSION = 'x-zod-nest-error';\n\n/** Value of `x-zod-nest-error` when a registry id is claimed by more than one schema. */\nexport const ZOD_NEST_ERROR_DUPLICATE_ID = 'duplicate-id';\n\n/**\n * OpenAPI extension key used by `createZodDto` to mark a class for `applyZodNest`.\n * The marker carries `{ __zodNestDto: true, dtoId, io }` so `applyZodNest` can\n * locate every zod-nest DTO in the @nestjs/swagger document and inject the\n * real Zod-derived schema.\n */\nexport const ZOD_NEST_DTO_EXTENSION = 'x-zod-nest-dto';\n","import { z } from 'zod';\n\nimport { discoverDependents } from './discover-dependents.js';\n\n/**\n * Per-registration flags carried alongside the id.\n *\n * - `expose` — force the id into the emitted document even when no endpoint\n * references it. The author deliberately wants it in `components.schemas`\n * (e.g. for out-of-band client codegen). Default exposure is otherwise\n * reachability-scoped, so an unreferenced schema is pruned unless flagged.\n * - `anonymous` — the id is a synthetic placeholder for a schema with no\n * resolvable id (passed inline to `@ZodResponse` / `@ZodBody`). It exists\n * only to carry the body through bulk emission under the document's\n * `strict` / `override` options; `inlineAnonymousBodies` later inlines the\n * body at each `$ref` site and prunes the component, so the synthetic id\n * never reaches the final document.\n *\n * Both flags are sticky — once set for an id they stay set, so a later plain\n * `register` of the same id (e.g. the idempotent re-register inside\n * `createZodDto`) doesn't clear them.\n */\nexport interface RegisterFlags {\n readonly expose?: boolean;\n readonly anonymous?: boolean;\n}\n\nexport interface ZodNestRegistry {\n readonly zodRegistry: typeof z.globalRegistry;\n register(schema: z.ZodType, id: string, flags?: RegisterFlags): void;\n hasCollision(id: string): boolean;\n getCollisions(): ReadonlyMap<string, ReadonlySet<z.ZodType>>;\n /**\n * Snapshot of every id registered through this `ZodNestRegistry`. The\n * underlying Zod registry is `z.globalRegistry`, which may hold third-party\n * entries — bulk emission filters its output against this snapshot to keep\n * only zod-nest-known ids.\n *\n * Includes ids discovered transitively via `.meta({ id })` on descendants\n * of explicitly-registered schemas.\n */\n ids(): readonly string[];\n /** Ids registered with `{ expose: true }` — exposed regardless of usage. */\n forceExposedIds(): readonly string[];\n /** Ids registered with `{ anonymous: true }` — inlined + pruned by `applyZodNest`. */\n anonymousIds(): readonly string[];\n}\n\nexport const createRegistry = (): ZodNestRegistry => {\n const seen = new Map<string, Set<z.ZodType>>();\n const forceExposed = new Set<string>();\n const anonymous = new Set<string>();\n const pendingRoots: z.ZodType[] = [];\n\n const recordOnce = (schema: z.ZodType, id: string): boolean => {\n let set = seen.get(id);\n if (set === undefined) {\n set = new Set<z.ZodType>();\n seen.set(id, set);\n }\n if (set.has(schema)) {\n return false;\n }\n set.add(schema);\n return true;\n };\n\n const flushPendingDiscovery = (): void => {\n for (const root of pendingRoots.splice(0)) {\n for (const [child, childId] of discoverDependents(root)) {\n recordOnce(child, childId);\n }\n }\n };\n\n return {\n zodRegistry: z.globalRegistry,\n register: (schema, id, flags) => {\n // Flags are sticky: a later plain re-register of the same id (e.g. the\n // idempotent call inside `createZodDto`) must not clear an earlier\n // `expose` / `anonymous`.\n if (flags?.expose === true) {\n forceExposed.add(id);\n }\n if (flags?.anonymous === true) {\n anonymous.add(id);\n }\n // `globalRegistry.add` overwrites the schema's entire meta entry; we\n // must merge so user-supplied fields (`title`, `description`,\n // anything else in `.meta({...})`) survive registration. The `has`\n // gate avoids promoting parent-inherited meta into a local entry\n // — `get()` returns parent-merged metadata when the schema has no\n // local entry, and writing that back here would freeze the\n // inherited fields against the schema.\n if (z.globalRegistry.has(schema)) {\n const existing = z.globalRegistry.get(schema);\n if (existing?.id !== id) {\n z.globalRegistry.add(schema, { ...(existing ?? {}), id });\n }\n } else {\n z.globalRegistry.add(schema, { id });\n }\n if (!recordOnce(schema, id)) {\n return;\n }\n // Queue, don't walk: forcing `z.lazy` getters here reads forward\n // references still in their temporal dead zone (throws under ESM,\n // yields `undefined` under CJS). Draining on first read is always safe.\n pendingRoots.push(schema);\n },\n hasCollision: (id) => {\n flushPendingDiscovery();\n const set = seen.get(id);\n return set !== undefined && set.size > 1;\n },\n getCollisions: () => {\n flushPendingDiscovery();\n const out = new Map<string, Set<z.ZodType>>();\n for (const [id, set] of seen) {\n if (set.size <= 1) {\n continue;\n }\n out.set(id, set);\n }\n return out;\n },\n ids: () => {\n flushPendingDiscovery();\n return [...seen.keys()];\n },\n forceExposedIds: () => [...forceExposed],\n anonymousIds: () => [...anonymous],\n };\n};\n\n/** Process-wide default registry, used when no explicit `options.registry` is passed. */\nexport const defaultRegistry: ZodNestRegistry = createRegistry();\n\nexport interface RegisterSchemaOptions {\n /** Forces this id, overriding any `.meta({ id })` already on the schema. */\n readonly id?: string;\n /**\n * Force the schema into the emitted document even when no endpoint\n * references it. Default exposure is reachability-scoped — see\n * {@link RegisterFlags.expose}.\n */\n readonly expose?: boolean;\n /**\n * Mark the resolved id as a synthetic anonymous placeholder — inlined and\n * pruned by `applyZodNest`. See {@link RegisterFlags.anonymous}.\n */\n readonly anonymous?: boolean;\n}\n\n/**\n * Register a schema with the given registry, resolving its id from (in order):\n * an explicit `options.id`, then `.meta({ id })` on the schema. Returns the\n * resolved id, or `undefined` when neither source yields one (the call is then\n * a no-op — callers with their own fallback path handle that case).\n *\n * Shared by `createZodDto` and `extend` so a schema named via `.meta({ id })`\n * gets its body emitted into `components.schemas` even when it never flows\n * through `createZodDto` (e.g. used only as an `extend()` parent — Zod's\n * `.extend()` produces a flat object, so the parent isn't a transitive\n * descendant of the child and would otherwise be missed by `discoverDependents`).\n *\n * Idempotent — `registry.register` already deduplicates repeat calls.\n */\nexport const registerSchema = (\n schema: z.ZodType,\n registry: ZodNestRegistry = defaultRegistry,\n options?: RegisterSchemaOptions,\n): string | undefined => {\n const flags: RegisterFlags = { expose: options?.expose, anonymous: options?.anonymous };\n const explicit = options?.id;\n if (typeof explicit === 'string' && explicit !== '') {\n registry.register(schema, explicit, flags);\n return explicit;\n }\n const meta = registry.zodRegistry.get(schema);\n const metaId = meta === undefined ? undefined : (meta as { id?: unknown }).id;\n if (typeof metaId !== 'string' || metaId === '') {\n return undefined;\n }\n registry.register(schema, metaId, flags);\n return metaId;\n};\n","/**\n * Composition layer — emits OpenAPI `allOf` for schemas derived via `extend`.\n *\n * **EXPERIMENTAL**: output shape may change as edge cases surface.\n */\n\nimport { z } from 'zod';\n\nimport type { $ZodType } from 'zod/v4/core';\nimport type { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\nimport type { ZodNestRegistry } from './registry.js';\n\nimport { DEFS_PREFIX } from './constants.js';\nimport { registerSchema } from './registry.js';\n\n/**\n * Lineage record for a composition-derived schema. Read by the override to\n * emit `allOf` instead of a flat body.\n *\n * @experimental — shape may change.\n */\nexport interface LineageEntry {\n readonly op: 'extend';\n readonly parent: z.ZodObject;\n /**\n * Keys the child redeclared with a *different* schema than the parent's\n * (e.g. narrowing `type: SomeEnum` to `type: z.literal('A')`). Computed by\n * reference comparison at `extend()` time — Zod's `.extend()` keeps the same\n * shape reference for untouched keys and assigns a fresh one for overrides.\n * The composition override keeps these in the delta instead of dropping them\n * as parent-owned, so the narrowing survives in the emitted `allOf`.\n */\n readonly overriddenKeys: ReadonlySet<string>;\n}\n\n// `WeakMap` (not `z.registry`) so transient derived schemas can GC — Zod's\n// own docs warn against long-running registries pinning short-lived schemas.\nconst lineageMap = new WeakMap<$ZodType, LineageEntry>();\n\n// Parent flat-key cache, populated eagerly by `extend()` at registration.\n// `reused: 'inline'` inlines the parent's shape into the child rather than\n// firing the override on the parent as a separate node, so the override\n// can't be relied on to populate this — extend() does it eagerly.\nconst propsMap = new WeakMap<\n $ZodType,\n { properties: readonly string[]; required: readonly string[] }\n>();\n\n/** Zod's wrapper types that make a property optional in JSON Schema's `required` sense. */\nexport const OPTIONAL_WRAPPER_TYPES: ReadonlySet<string> = new Set(['optional', 'default']);\n\nexport const isOptionalProp = (propSchema: z.ZodType): boolean =>\n OPTIONAL_WRAPPER_TYPES.has(propSchema._zod.def.type);\n\nconst computeShapeKeys = (\n schema: z.ZodObject,\n): { properties: readonly string[]; required: readonly string[] } => {\n const { shape } = schema;\n const properties = Object.keys(shape);\n const required = properties.filter((key) => {\n const propSchema = shape[key];\n return propSchema !== undefined && !isOptionalProp(propSchema);\n });\n return { properties, required };\n};\n\n/**\n * Keys the child shares with the parent by name but redeclares with a\n * different schema. Relies on Zod's `.extend()` reference semantics: untouched\n * keys keep the parent's shape reference, overridden keys get a fresh one.\n */\nconst computeOverriddenKeys = (parent: z.ZodObject, child: z.ZodObject): ReadonlySet<string> => {\n const overriddenKeys = new Set<string>();\n for (const key of Object.keys(child.shape)) {\n const parentProp = parent.shape[key];\n if (parentProp !== undefined && parentProp !== child.shape[key]) {\n overriddenKeys.add(key);\n }\n }\n return overriddenKeys;\n};\n\n/**\n * Wraps a derived `z.ZodObject` and records the parent → child link so\n * emission rewrites the body to `allOf: [{ $ref: <parent> }, <delta>]`.\n *\n * @experimental — output shape may change as the surface stabilizes.\n *\n * @example\n * const Base = z.object({ id: z.string() }).meta({ id: 'Base' });\n * const Child = extend(Base, (s) => s.extend({ role: z.string() }).meta({ id: 'Child' }));\n */\nexport const extend = <P extends z.ZodObject, S extends z.ZodObject>(\n parent: P,\n build: (p: P) => S,\n): S => {\n const result = build(parent);\n lineageMap.set(result, {\n op: 'extend',\n parent,\n overriddenKeys: computeOverriddenKeys(parent, result),\n });\n if (!propsMap.has(parent)) {\n propsMap.set(parent, computeShapeKeys(parent));\n }\n // Auto-register named parent/result so their bodies land in\n // `components.schemas`. Zod's `.extend()` produces a flat object, so the\n // parent isn't a transitive descendant of the result — without this, a\n // parent named only via `.meta({ id })` would be referenced by `$ref` but\n // never emitted, yielding `DANGLING_REF`. No-op when the schema is\n // anonymous. The composition override (below) re-registers against the\n // active registry at emit time as a backstop for custom-registry users.\n registerSchema(parent);\n registerSchema(result);\n return result;\n};\n\n/**\n * Read the lineage entry for a composition-derived schema, or `undefined`.\n *\n * @experimental — `LineageEntry` shape may change.\n */\nexport const getLineage = (schema: z.ZodType): LineageEntry | undefined => lineageMap.get(schema);\n\n/**\n * Default ref builder for single-schema mode (`toOpenApi`) — refs land in\n * `#/$defs/<id>` and `post-process` rewrites them to `#/components/schemas/<id>`.\n * Bulk mode passes its own `uri` callback so refs land at the final location.\n */\nexport const DEFAULT_BUILD_REF = (id: string): string => `${DEFS_PREFIX}${id}`;\n\nexport interface CreateCompositionOverrideOptions {\n /** Shape the `$ref` string for a parent id. Defaults to `#/$defs/<id>`. */\n buildRef: (id: string) => string;\n /** Registry to resolve parent ids against. Use the same instance the engine emits with. */\n registry: ZodNestRegistry;\n}\n\n/**\n * Factory for the composition override. Returns an `Override` that rewrites\n * composition-derived schemas to `allOf` form, falling back to Zod's flat\n * emission when no lineage entry exists or the parent has no registered id.\n *\n * Mutation happens in-place — Zod's override doesn't propagate\n * `ctx.jsonSchema = newBody` reassignments; only mutations on the existing\n * object reference reach the caller.\n */\nexport const createCompositionOverride = (opts: CreateCompositionOverrideOptions): Override => {\n const { buildRef, registry } = opts;\n return (ctx) => {\n const { jsonSchema, zodSchema } = ctx;\n const entry = lineageMap.get(zodSchema);\n if (entry === undefined) {\n return;\n }\n\n const parentCache = propsMap.get(entry.parent);\n if (parentCache === undefined) {\n // Defensive: `extend()` pre-caches the parent at registration time, so\n // by the time the child's override fires this should be set.\n return;\n }\n\n const parentId = registry.zodRegistry.get(entry.parent)?.id;\n if (parentId === undefined) {\n // Anonymous parent — fall back to Zod's flat emission.\n return;\n }\n // Backstop the eager `extend()` registration above: that only writes to\n // `defaultRegistry`, so custom-registry users need the parent surfaced\n // here too. Idempotent against the eager call.\n registerSchema(entry.parent, registry);\n\n const childProps = jsonSchema.properties ?? {};\n const childRequired = jsonSchema.required ?? [];\n const parentPropSet = new Set(parentCache.properties);\n const parentReqSet = new Set(parentCache.required);\n\n const deltaProps: NonNullable<SchemaObject['properties']> = {};\n for (const [key, value] of Object.entries(childProps)) {\n // Drop parent-owned keys, but keep any the child overrode with a\n // different schema — otherwise the narrowing (e.g. enum → literal) is\n // lost and `allOf` would only carry the parent's wider constraint.\n if (parentPropSet.has(key) && !entry.overriddenKeys.has(key)) {\n continue;\n }\n deltaProps[key] = value;\n }\n // Mirror the properties logic: drop parent-required keys, but keep any the\n // child overrode and still requires — its narrowed body now lives in the\n // delta, so the `required` marker must travel with it (otherwise the\n // overridden field reads as optional in the delta arm, e.g. breaking a\n // discriminated union whose discriminator must be required on each arm).\n const deltaRequired = childRequired.filter(\n (key) => !parentReqSet.has(key) || entry.overriddenKeys.has(key),\n );\n\n const delta: SchemaObject = { type: 'object', properties: deltaProps };\n if (deltaRequired.length > 0) {\n delta.required = deltaRequired;\n }\n\n delete jsonSchema.properties;\n delete jsonSchema.required;\n delete jsonSchema.additionalProperties;\n // Keep `type: 'object'` on the wrapper rather than deleting it: every arm of\n // the `allOf` is an object, so the wrapper is unambiguously an object, and\n // the explicit `type` is the more correct / tool-friendly emission.\n // `type: 'object'` + `allOf` is valid (the instance must be an object AND\n // satisfy every arm); `unevaluatedProperties: false` still closes the shape.\n jsonSchema.type = 'object';\n jsonSchema.allOf = [{ $ref: buildRef(parentId) }, delta];\n jsonSchema.unevaluatedProperties = false;\n };\n};\n","export class ZodNestError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ZodNestError';\n }\n}\n\nexport class ZodNestUnrepresentableError extends ZodNestError {\n readonly path: ReadonlyArray<string | number>;\n readonly zodType: string;\n\n constructor(path: ReadonlyArray<string | number>, zodType: string) {\n super(\n `Unrepresentable Zod schema \\`${zodType}\\` at ${formatPath(path)}: no override produced ` +\n `a JSON Schema body. Set strict: false to emit \\`{}\\` instead, or supply an \\`override\\` ` +\n `that handles this Zod type.`,\n );\n this.name = 'ZodNestUnrepresentableError';\n this.path = path;\n this.zodType = zodType;\n }\n}\n\nconst formatPath = (path: ReadonlyArray<string | number>): string => {\n if (path.length === 0) {\n return '<root>';\n }\n return '/' + path.map(String).join('/');\n};\n","import type { $ZodTypes } from 'zod/v4/core';\nimport type { SchemaObject } from './openapi.types.js';\n\nexport interface OverrideContext {\n zodSchema: $ZodTypes;\n jsonSchema: SchemaObject;\n path: (string | number)[];\n}\n\nexport type Override = (ctx: OverrideContext) => void;\n\n/**\n * Type-driven override for primitive Zod constructs that JSON Schema can't\n * represent directly (bigint → integer, date → string + date-time format).\n * Composition's `allOf`-form emission lives in `composition.ts`; the engine\n * combines both into the full override chain per call site (since composition\n * needs a uri-aware `buildRef` that differs between single-schema and bulk\n * emission).\n */\nexport const primitiveOverride: Override = ({ zodSchema, jsonSchema }) => {\n const type = zodSchema._zod.def.type;\n if (type === 'bigint') {\n jsonSchema.type = 'integer';\n return;\n }\n if (type === 'date') {\n jsonSchema.type = 'string';\n jsonSchema.format = 'date-time';\n return;\n }\n};\n\nexport const combine = (...overrides: ReadonlyArray<Override | undefined>): Override => {\n const list: Override[] = [];\n for (const candidate of overrides) {\n if (typeof candidate !== 'function') {\n continue;\n }\n list.push(candidate);\n }\n return (ctx) => {\n for (const o of list) {\n o(ctx);\n }\n };\n};\n","import type { SchemaObject } from './openapi.types.js';\n\nimport { COMPONENTS_SCHEMAS_PREFIX, DEFS_PREFIX } from './constants.js';\nimport { ZodNestError } from './errors.js';\n\nexport interface PostProcessResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\nexport interface PostProcessOptions {\n /** Component id of the emitted root, when it has one. Resolves `'#'` refs. */\n rootId?: string;\n strict?: boolean;\n}\n\n// Zod emits '#' for a cycle back to the document root, so it resolves to the\n// root's own component — never to whichever def happens to contain it.\nconst rewriteRefs = (node: unknown, rootRef: string | undefined): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n rewriteRefs(item, rootRef);\n }\n return;\n }\n if (node === null || typeof node !== 'object') {\n return;\n }\n const obj = node as Record<string, unknown>;\n const ref = obj.$ref;\n if (typeof ref === 'string' && ref.startsWith(DEFS_PREFIX)) {\n obj.$ref = COMPONENTS_SCHEMAS_PREFIX + ref.slice(DEFS_PREFIX.length);\n } else if (ref === '#' && rootRef !== undefined) {\n obj.$ref = rootRef;\n }\n for (const value of Object.values(obj)) {\n rewriteRefs(value, rootRef);\n }\n};\n\nconst refsIn = function* (node: unknown): Generator<string> {\n if (Array.isArray(node)) {\n for (const item of node) {\n yield* refsIn(item);\n }\n return;\n }\n if (node === null || typeof node !== 'object') {\n return;\n }\n const obj = node as Record<string, unknown>;\n if (typeof obj.$ref === 'string') {\n yield obj.$ref;\n }\n for (const value of Object.values(obj)) {\n yield* refsIn(value);\n }\n};\n\nconst rootDefId = (raw: SchemaObject): string | undefined => {\n const ref = raw.$ref;\n if (typeof ref !== 'string' || !ref.startsWith(DEFS_PREFIX)) {\n return undefined;\n }\n return ref.slice(DEFS_PREFIX.length);\n};\n\nconst isReferenced = (defs: SchemaObject['$defs'], id: string): boolean => {\n const ownRef = `${DEFS_PREFIX}${id}`;\n for (const ref of refsIn(defs)) {\n if (ref === '#' || ref === ownRef) {\n return true;\n }\n }\n return false;\n};\n\nconst referencesRoot = (raw: SchemaObject): boolean => {\n for (const ref of refsIn(raw)) {\n if (ref === '#') {\n return true;\n }\n }\n return false;\n};\n\nconst stripEnvelope = (raw: SchemaObject): SchemaObject => {\n const root: SchemaObject = { ...raw };\n delete root.$schema;\n delete root.$defs;\n return root;\n};\n\ninterface ResolvedRoot {\n schema: SchemaObject;\n rootRef: string | undefined;\n}\n\n// A referenced root has to be addressable, so it keeps (or gains) a component\n// entry and the caller gets a `$ref`. Inlining an unreferenced one keeps zod\n// 4.4 and 4.5 emitting the same shape.\nconst resolveRoot = (\n raw: SchemaObject,\n refs: Map<string, SchemaObject>,\n options: PostProcessOptions | undefined,\n): ResolvedRoot => {\n const liftedId = rootDefId(raw);\n if (liftedId !== undefined) {\n const body = refs.get(liftedId);\n if (body !== undefined && !isReferenced(raw.$defs, liftedId)) {\n refs.delete(liftedId);\n return { schema: body, rootRef: undefined };\n }\n return { schema: stripEnvelope(raw), rootRef: `${COMPONENTS_SCHEMAS_PREFIX}${liftedId}` };\n }\n\n const root = stripEnvelope(raw);\n if (!referencesRoot(raw)) {\n return { schema: root, rootRef: undefined };\n }\n\n const rootId = options?.rootId;\n if (rootId === undefined) {\n if (options?.strict ?? true) {\n throw new ZodNestError(\n 'A schema referenced from inside its own emission has no id, so the reference ' +\n 'cannot be resolved. Add `.meta({ id: \"…\" })` to the root schema, or set ' +\n 'strict: false to leave the reference unresolved.',\n );\n }\n return { schema: root, rootRef: undefined };\n }\n\n refs.set(rootId, root);\n const rootRef = `${COMPONENTS_SCHEMAS_PREFIX}${rootId}`;\n return { schema: { $ref: rootRef }, rootRef };\n};\n\nexport const postProcess = (raw: SchemaObject, options?: PostProcessOptions): PostProcessResult => {\n const refs = new Map<string, SchemaObject>();\n const rawDefs = raw.$defs;\n if (rawDefs !== undefined) {\n for (const [id, body] of Object.entries(rawDefs)) {\n refs.set(id, body);\n }\n }\n\n const { schema, rootRef } = resolveRoot(raw, refs, options);\n rewriteRefs(schema, rootRef);\n\n for (const body of refs.values()) {\n rewriteRefs(body, rootRef);\n }\n\n return { schema, refs };\n};\n","import { z } from 'zod';\n\nimport type { $ZodType, $ZodTypes } from 'zod/v4/core';\nimport type { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\nimport type { ZodNestRegistry } from './registry.js';\n\nimport { createCompositionOverride, DEFAULT_BUILD_REF } from './composition.js';\nimport { ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION } from './constants.js';\nimport { createCustomOverride, peekRegistration } from './custom-override.js';\nimport { ZodNestUnrepresentableError } from './errors.js';\nimport { combine, primitiveOverride } from './override.js';\nimport { postProcess } from './post-process.js';\n\n/**\n * Zod constructs that JSON Schema can't represent without an override. When\n * one of these shows up and our combined override chain didn't produce any\n * body for it, strict mode collects the hit and surfaces it as a\n * `ZodNestUnrepresentableError`. Bound to `engine.ts` since the strict-hit\n * collection lives here too.\n */\nconst STRICT_REQUIRES_OVERRIDE: ReadonlySet<string> = new Set([\n 'bigint',\n 'date',\n 'symbol',\n 'undefined',\n 'void',\n 'map',\n 'set',\n 'transform',\n 'nan',\n 'custom',\n]);\n\n/**\n * Keywords that annotate a schema without describing its shape. A body made\n * only of these has no type, so it's as unrepresentable as an empty one —\n * `.meta({ title })` on an unregistered schema emits exactly that, and\n * checking emptiness alone let it through as a valid annotation-only body.\n *\n * Deliberately an allow-list of annotations rather than a deny-list of\n * structural keywords: an unrecognised keyword counts as structural, so a\n * future JSON Schema addition can't turn into a spurious build failure.\n */\nconst ANNOTATION_ONLY_KEYS: ReadonlySet<string> = new Set([\n 'title',\n 'description',\n 'deprecated',\n 'examples',\n 'default',\n 'readOnly',\n 'writeOnly',\n '$id',\n '$schema',\n '$comment',\n 'id',\n]);\n\nconst isStrictlyUnrepresentable = (jsonSchema: SchemaObject, zodSchema: $ZodTypes): boolean => {\n if (!STRICT_REQUIRES_OVERRIDE.has(zodSchema._zod.def.type)) {\n return false;\n }\n return Object.keys(jsonSchema).every((key) => ANNOTATION_ONLY_KEYS.has(key));\n};\n\nexport interface ToOpenApiOptions {\n io: 'input' | 'output';\n registry: ZodNestRegistry;\n override?: Override;\n strict?: boolean;\n}\n\nexport interface ToOpenApiResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\ninterface UnrepresentableHit {\n path: (string | number)[];\n zodType: string;\n /**\n * Schema instance that emitted empty. Kept so `consumeUnrepresentable`\n * can drop hits whose outer pipe later marked them covered — pipes process\n * inner before outer in reverse-seen order, so the inner's hit fires\n * before the outer pipe gets to declare coverage.\n */\n zodSchema: $ZodType;\n}\n\n/**\n * Mark a pipe's descent target as covered by an outer registration when\n * the override for the outer pipe fires. Recurses for nested\n * pipe-of-pipe chains (e.g. `pipe(pipe2, transform)`) so the deep inner\n * descent target also has its strict-mode hit suppressed.\n *\n * Mirrors Zod's `pipeProcessor` descent rules (`json-schema-processors.js`):\n * - `io === 'output'` → cover `def.out`\n * - `io === 'input'` → cover `def.out` when `def.in` is a `$ZodTransform`\n * (Zod skips preprocessing on input emission), else `def.in`.\n */\nconst markPipeCoverage = (\n schema: $ZodType,\n io: 'input' | 'output',\n covered: WeakSet<$ZodType>,\n): void => {\n const def = schema._zod.def as { type: string; in?: $ZodType; out?: $ZodType };\n if (def.type !== 'pipe' || def.in === undefined || def.out === undefined) {\n return;\n }\n const target =\n io === 'output' ? def.out : def.in._zod.traits.has('$ZodTransform') ? def.out : def.in;\n if (covered.has(target)) {\n return;\n }\n covered.add(target);\n markPipeCoverage(target, io, covered);\n};\n\n/**\n * Parameters for `buildToJsonSchemaOptions` — the shared option-bag builder\n * used by both `toOpenApi` (single-schema mode) and `bulkEmit` (registry-mode).\n * Centralizes the override chain, unrepresentable detection,\n * metadata wiring, and target/cycles defaults so both paths emit equivalent\n * JSON Schema for the same input.\n */\nexport interface BuildToJsonSchemaOptionsParams {\n registry: ZodNestRegistry;\n io: 'input' | 'output';\n override?: Override;\n strict?: boolean;\n /**\n * Zod's strategy for anonymous reused sub-schemas. Both single-schema and\n * bulk modes use `'inline'` — `'ref'` extracts anonymous reused branches\n * into a virtual `__shared/$defs` table whose refs don't resolve against\n * `components.schemas`, producing dangling refs. Registered schemas\n * (`metadata.id` present) always go through the `uri` callback regardless,\n * so DTO-to-DTO `$ref`s are unaffected.\n */\n reused: 'inline' | 'ref';\n /** Bulk-mode only — shapes internal `$ref`s to `#/components/schemas/<id>`. */\n uri?: (id: string) => string;\n}\n\nexport interface BuiltJsonSchemaOptions {\n options: NonNullable<Parameters<typeof z.toJSONSchema>[1]>;\n /** Throws `ZodNestUnrepresentableError` if any strict-unrepresentable hit was collected during emission. */\n consumeUnrepresentable(): void;\n}\n\nexport const buildToJsonSchemaOptions = (\n params: BuildToJsonSchemaOptionsParams,\n): BuiltJsonSchemaOptions => {\n const strict = params.strict ?? true;\n // Composition's `buildRef` differs between single-schema and bulk modes:\n // single-schema emits `#/$defs/<id>` (post-process rewrites to\n // `#/components/schemas/<id>`); bulk emits `#/components/schemas/<id>`\n // directly via the configured `uri` callback (post-process is skipped).\n const compositionOverride = createCompositionOverride({\n buildRef: params.uri ?? DEFAULT_BUILD_REF,\n registry: params.registry,\n });\n // Chain order matches precedence (left → right, last-write-wins mutation\n // semantics). Caller's `params.override` runs last so per-call overrides\n // remain the ultimate escape hatch; `customOverride` consults the\n // `overrideJSONSchema(...)` registration map (parameterized by `io` so it\n // can pick divergent input/output fragments) and clobbers the built-in\n // primitive/composition mappings for the registered schema instance.\n const customOverride = createCustomOverride(params.io);\n const merged = combine(primitiveOverride, compositionOverride, customOverride, params.override);\n const unrepresentableHits: UnrepresentableHit[] = [];\n // Inner descent targets shadowed by an outer pipe registration. Populated\n // JIT during traversal: Zod processes inner-before-outer in reverse-seen\n // order, but `consumeUnrepresentable` runs only after traversal completes,\n // so by then the outer pipe's coverage declaration has landed.\n const coveredByPipe = new WeakSet<$ZodType>();\n\n const wrapped: Override = (ctx) => {\n merged(ctx);\n if (ctx.zodSchema._zod.def.type === 'pipe') {\n const record = peekRegistration(ctx.zodSchema);\n if (record !== undefined && record[params.io] !== undefined) {\n markPipeCoverage(ctx.zodSchema, params.io, coveredByPipe);\n }\n }\n if (!strict || !isStrictlyUnrepresentable(ctx.jsonSchema, ctx.zodSchema)) {\n return;\n }\n unrepresentableHits.push({\n path: [...ctx.path],\n zodType: ctx.zodSchema._zod.def.type,\n zodSchema: ctx.zodSchema,\n });\n };\n\n const options: NonNullable<Parameters<typeof z.toJSONSchema>[1]> = {\n target: 'draft-2020-12',\n io: params.io,\n unrepresentable: 'any',\n metadata: params.registry.zodRegistry,\n override: wrapped,\n cycles: 'ref',\n reused: params.reused,\n };\n if (params.uri !== undefined) {\n options.uri = params.uri;\n }\n\n return {\n options,\n consumeUnrepresentable: () => {\n const firstHit = unrepresentableHits.find((hit) => !coveredByPipe.has(hit.zodSchema));\n if (firstHit !== undefined) {\n throw new ZodNestUnrepresentableError(firstHit.path, firstHit.zodType);\n }\n },\n };\n};\n\n// Covers both `.meta({ id })` and `registry.register(schema, id)` — the latter\n// writes the id through to the zod registry.\nconst resolveRootId = (schema: z.ZodType, registry: ZodNestRegistry): string | undefined => {\n const id = registry.zodRegistry.get(schema)?.id;\n return typeof id === 'string' && id !== '' ? id : undefined;\n};\n\nexport const toOpenApi = (schema: z.ZodType, opts: ToOpenApiOptions): ToOpenApiResult => {\n const built = buildToJsonSchemaOptions({\n registry: opts.registry,\n io: opts.io,\n override: opts.override,\n strict: opts.strict,\n reused: 'inline',\n });\n const raw = z.toJSONSchema(schema, built.options);\n built.consumeUnrepresentable();\n\n const result = postProcess(raw, {\n rootId: resolveRootId(schema, opts.registry),\n strict: opts.strict,\n });\n\n for (const [id] of opts.registry.getCollisions()) {\n if (!result.refs.has(id)) {\n continue;\n }\n result.refs.set(id, {\n description: `ERROR: duplicate zod-nest id <${id}>`,\n [ZOD_NEST_ERROR_EXTENSION]: ZOD_NEST_ERROR_DUPLICATE_ID,\n });\n }\n\n return result;\n};\n","import { ApiBody, ApiConsumes } from '@nestjs/swagger';\nimport { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../schema/registry.js';\nimport type { MultipartFilesIn, MultipartMetadata, MultipartShape } from './metadata.js';\n\nimport { discoverDependents } from '../schema/discover-dependents.js';\nimport { toOpenApi } from '../schema/engine.js';\nimport { defaultRegistry } from '../schema/registry.js';\nimport { isFileSchema } from './file-marker.js';\nimport { ZOD_MULTIPART_METADATA_KEY } from './metadata.js';\n\nexport const MULTIPART_CONTENT_TYPE = 'multipart/form-data';\n\nexport interface ZodMultipartOptions {\n /**\n * Where the parser puts uploaded files. Defaults to the platform entry\n * point's convention — `'request'` from `zod-nest/express`, `'body'` from\n * `zod-nest/fastify`.\n */\n readonly filesIn?: MultipartFilesIn;\n /** Registry to register named descendants into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n /** OpenAPI `description` for the request body. */\n readonly description?: string;\n /** Whether the body is required. Defaults to `true`. */\n readonly required?: boolean;\n}\n\nconst partitionKeys = (shape: MultipartShape): { fileKeys: string[]; textKeys: string[] } => {\n const fileKeys: string[] = [];\n const textKeys: string[] = [];\n for (const [key, schema] of Object.entries(shape)) {\n if (isFileSchema(schema)) {\n fileKeys.push(key);\n continue;\n }\n textKeys.push(key);\n }\n return { fileKeys, textKeys };\n};\n\n/**\n * Emits the body inline rather than as a `$ref`. Swagger UI's\n * `multipart/form-data` try-it-out form generator doesn't follow `$ref`, so a\n * referenced body renders as a single stub field instead of file pickers.\n * Same trade-off `@ZodBody({ flatten: true })` documents.\n */\nconst emitInlineBody = (\n shape: MultipartShape,\n registry: ZodNestRegistry,\n): Record<string, unknown> => {\n const object = z.object({ ...shape });\n for (const [child, childId] of discoverDependents(object)) {\n registry.register(child, childId);\n }\n const { schema } = toOpenApi(object, { io: 'input', registry });\n return schema;\n};\n\nexport const createZodMultipart = (defaultFilesIn: MultipartFilesIn) => {\n /**\n * Declares an endpoint's whole `multipart/form-data` body — file fields and\n * text fields together — as the single source of truth for both the OpenAPI\n * document and the multipart param decorators.\n */\n return (shape: MultipartShape, options?: ZodMultipartOptions): MethodDecorator => {\n const registry = options?.registry ?? defaultRegistry;\n const { fileKeys, textKeys } = partitionKeys(shape);\n const metadata: MultipartMetadata = {\n shape,\n fileKeys,\n textKeys,\n filesIn: options?.filesIn ?? defaultFilesIn,\n };\n const body = emitInlineBody(shape, registry);\n\n return (target, propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodMultipart can only be applied to methods.');\n }\n Reflect.defineMetadata(ZOD_MULTIPART_METADATA_KEY, metadata, handler);\n\n // `TypedPropertyDescriptor<unknown>` matches what the swagger decorators\n // expect; `MethodDecorator`'s parameter is `TypedPropertyDescriptor<T>`\n // for the inferred return type, structurally compatible at runtime.\n const swaggerDescriptor = descriptor as TypedPropertyDescriptor<unknown>;\n ApiConsumes(MULTIPART_CONTENT_TYPE)(target, propertyKey, swaggerDescriptor);\n ApiBody({\n schema: body,\n ...(options?.description !== undefined ? { description: options.description } : {}),\n required: options?.required ?? true,\n })(target, propertyKey, swaggerDescriptor);\n };\n };\n};\n","import { BadRequestException, HttpStatus } from '@nestjs/common';\nimport { z } from 'zod';\n\nimport type { ArgumentMetadata } from '@nestjs/common';\n\n/**\n * Default exception thrown by `ZodValidationPipe` when input fails to parse.\n *\n * Body shape (returned by `getResponse()`):\n * ```\n * {\n * statusCode: 400,\n * message: 'Validation failed',\n * errors: z.treeifyError(zodError),\n * }\n * ```\n *\n * Carries `zodError` and `argMetadata` so custom exception filters can\n * introspect the original validation failure.\n */\nexport class ZodValidationException extends BadRequestException {\n readonly zodError: z.ZodError;\n readonly argMetadata?: ArgumentMetadata;\n\n constructor(zodError: z.ZodError, argMetadata?: ArgumentMetadata) {\n super(\n {\n statusCode: HttpStatus.BAD_REQUEST,\n message: 'Validation failed',\n errors: z.treeifyError(zodError),\n },\n { cause: zodError },\n );\n this.zodError = zodError;\n this.argMetadata = argMetadata;\n }\n}\n","import { createParamDecorator } from '@nestjs/common';\nimport { z } from 'zod';\n\nimport type { ExecutionContext } from '@nestjs/common';\nimport type { MultipartMetadata, MultipartShape } from './metadata.js';\n\nimport { ZodValidationException } from '../exceptions/validation.exception.js';\nimport { MultipartFilesIn, ZOD_MULTIPART_METADATA_KEY } from './metadata.js';\n\ntype ArgType = 'body' | 'custom';\n\nconst readMetadata = (ctx: ExecutionContext, decorator: string): MultipartMetadata => {\n const metadata: unknown = Reflect.getMetadata(ZOD_MULTIPART_METADATA_KEY, ctx.getHandler());\n if (!isMultipartMetadata(metadata)) {\n throw new Error(\n `[zod-nest] ${decorator} requires @ZodMultipart on the same handler — it reads the declared shape from there.`,\n );\n }\n return metadata;\n};\n\nconst isMultipartMetadata = (value: unknown): value is MultipartMetadata =>\n value !== null && typeof value === 'object' && 'shape' in value && 'filesIn' in value;\n\nconst schemaFor = (metadata: MultipartMetadata, name: string, decorator: string): z.ZodType => {\n const schema = metadata.shape[name];\n if (schema === undefined) {\n throw new Error(\n `[zod-nest] ${decorator}('${name}') has no matching property in the @ZodMultipart shape. Declared: ${Object.keys(metadata.shape).join(', ')}.`,\n );\n }\n return schema;\n};\n\nconst pick = (shape: MultipartShape, keys: readonly string[]): z.ZodType => {\n const wanted = new Set(keys);\n const picked: Record<string, z.ZodType> = {};\n for (const [key, schema] of Object.entries(shape)) {\n if (wanted.has(key)) {\n picked[key] = schema;\n }\n }\n return z.object(picked);\n};\n\nconst validate = async (schema: z.ZodType, value: unknown, argType: ArgType): Promise<unknown> => {\n const result = await schema.safeParseAsync(value);\n if (result.success) {\n return result.data;\n }\n throw new ZodValidationException(result.error, {\n type: argType,\n metatype: undefined,\n data: undefined,\n });\n};\n\nconst assertFilesOnRequest = (metadata: MultipartMetadata, decorator: string): void => {\n if (metadata.filesIn === MultipartFilesIn.Request) {\n return;\n }\n throw new Error(\n `[zod-nest] ${decorator} is unavailable under filesIn: 'body' — the parser puts files in the request body, so read them with @ZodMultipartBody().`,\n );\n};\n\nexport const resolveUploadedFile = async (\n name: string,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodUploadedFile');\n assertFilesOnRequest(metadata, '@ZodUploadedFile');\n const request: { file?: unknown } = ctx.switchToHttp().getRequest();\n return validate(schemaFor(metadata, name, '@ZodUploadedFile'), request.file, 'custom');\n};\n\nexport const resolveUploadedFiles = async (\n name: string | undefined,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodUploadedFiles');\n assertFilesOnRequest(metadata, '@ZodUploadedFiles');\n const request: { files?: unknown } = ctx.switchToHttp().getRequest();\n const schema =\n name === undefined\n ? pick(metadata.shape, metadata.fileKeys)\n : schemaFor(metadata, name, '@ZodUploadedFiles');\n return validate(schema, request.files, 'custom');\n};\n\nexport const resolveMultipartBody = async (\n _data: unknown,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodMultipartBody');\n const request: { body?: unknown } = ctx.switchToHttp().getRequest();\n const keys =\n metadata.filesIn === MultipartFilesIn.Body ? Object.keys(metadata.shape) : metadata.textKeys;\n return validate(pick(metadata.shape, keys), request.body, 'body');\n};\n\n/**\n * Validates `req.file` against the named property of the `@ZodMultipart`\n * shape. The name selects a schema; it never searches the request. Match it\n * to your `FileInterceptor('<name>')` field name, as with plain Nest.\n */\nexport const ZodUploadedFile = createParamDecorator(resolveUploadedFile);\n\n/**\n * Validates `req.files` against the named property of the `@ZodMultipart`\n * shape, or against an object of every declared file property when called\n * with no name — the record shape `FileFieldsInterceptor` produces.\n */\nexport const ZodUploadedFiles = createParamDecorator(resolveUploadedFiles);\n\n/**\n * Validates `req.body` against the `@ZodMultipart` shape — the text fields\n * only under `filesIn: 'request'` (multer keeps files off the body), the\n * whole shape under `filesIn: 'body'`.\n */\nexport const ZodMultipartBody = createParamDecorator(resolveMultipartBody);\n","import type { z } from 'zod';\nimport type { BaseFileOptions } from '../multipart/build-file-schema.js';\nimport type { FileAccessors } from '../multipart/file-checks.js';\n\nimport { buildFileSchema } from '../multipart/build-file-schema.js';\nimport { MultipartFilesIn } from '../multipart/metadata.js';\nimport { createZodMultipart } from '../multipart/zod-multipart.decorator.js';\n\n/**\n * Shape multer hands you under **memory storage** (`FileInterceptor`'s\n * default). `buffer` holds the whole file; there is no `path`.\n */\nexport interface MulterMemoryFileLike {\n fieldname: string;\n originalname: string;\n encoding: string;\n mimetype: string;\n size: number;\n buffer: Buffer;\n}\n\n/**\n * Shape multer hands you under **disk storage**. The bytes are on disk at\n * `path`; there is no `buffer`, so byte-level validation isn't possible.\n */\nexport interface MulterDiskFileLike {\n fieldname: string;\n originalname: string;\n encoding: string;\n mimetype: string;\n size: number;\n destination: string;\n filename: string;\n path: string;\n}\n\n/**\n * Options for the multer file helpers. `maxSize` is checked against multer's\n * reported `size` **after** the file has been read — it documents the limit\n * and adds defence in depth, but the guard that actually stops a large upload\n * is multer's own `limits.fileSize`.\n *\n * `mimeTypes` and `extensions` match the client-supplied values. They are not\n * content sniffing; use `@nestjs/common`'s `FileTypeValidator` when you need\n * magic-number checks.\n */\nexport interface MulterFileOptions extends BaseFileOptions {\n readonly maxSize?: number;\n}\n\nconst hasCommonFields = (value: unknown): value is Record<string, unknown> =>\n value !== null &&\n typeof value === 'object' &&\n 'mimetype' in value &&\n 'originalname' in value &&\n 'size' in value;\n\nconst isMulterMemoryFile = (value: unknown): boolean =>\n hasCommonFields(value) && Buffer.isBuffer(value.buffer);\n\nconst isMulterDiskFile = (value: unknown): boolean =>\n hasCommonFields(value) && typeof value.path === 'string';\n\nconst memoryAccessors: FileAccessors<MulterMemoryFileLike> = {\n mimeType: (file) => file.mimetype,\n fileName: (file) => file.originalname,\n size: (file) => file.size,\n};\n\nconst diskAccessors: FileAccessors<MulterDiskFileLike> = {\n mimeType: (file) => file.mimetype,\n fileName: (file) => file.originalname,\n size: (file) => file.size,\n};\n\n/** Multer memory-storage file, constrained by `options` and emitted as `format: 'binary'`. */\nexport const multerMemoryFile = (\n options?: MulterFileOptions,\n): z.ZodType<MulterMemoryFileLike, MulterMemoryFileLike> =>\n buildFileSchema<MulterMemoryFileLike>({\n predicate: isMulterMemoryFile,\n accessors: memoryAccessors,\n options,\n ...(options?.maxSize !== undefined ? { maxSize: options.maxSize } : {}),\n });\n\n/** Multer disk-storage file, constrained by `options` and emitted as `format: 'binary'`. */\nexport const multerDiskFile = (\n options?: MulterFileOptions,\n): z.ZodType<MulterDiskFileLike, MulterDiskFileLike> =>\n buildFileSchema<MulterDiskFileLike>({\n predicate: isMulterDiskFile,\n accessors: diskAccessors,\n options,\n ...(options?.maxSize !== undefined ? { maxSize: options.maxSize } : {}),\n });\n\n/** Unconstrained {@link multerMemoryFile}, for shapes that need no per-field checks. */\nexport const MulterMemoryFileSchema = multerMemoryFile();\n\n/** Unconstrained {@link multerDiskFile}, for shapes that need no per-field checks. */\nexport const MulterDiskFileSchema = multerDiskFile();\n\n/**\n * Declares an endpoint's whole `multipart/form-data` body. Emits the flat\n * inline `requestBody` Swagger UI's try-it-out form needs, sets\n * `multipart/form-data` as the consumed type, and is the schema source for\n * `@ZodUploadedFile` / `@ZodUploadedFiles` / `@ZodMultipartBody`.\n */\nexport const ZodMultipart = createZodMultipart(MultipartFilesIn.Request);\n\nexport {\n ZodMultipartBody,\n ZodUploadedFile,\n ZodUploadedFiles,\n} from '../multipart/param-decorators.js';\nexport { MULTIPART_CONTENT_TYPE } from '../multipart/zod-multipart.decorator.js';\nexport type { ZodMultipartOptions } from '../multipart/zod-multipart.decorator.js';\nexport type { MultipartShape } from '../multipart/metadata.js';\n"]}