@stlmpp/nestjs-zod 1.0.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,518 @@
1
+ import { _ as assert, a as convertToOpenApi3Point0, c as EMPTY_TYPE_KEY, d as PARENT_ID_KEY, f as PARENT_METADATA_KEY, g as configureZodDto, h as USES_THREE_POINT_ONE_SYNTAX_KEY, i as zodV3ToOpenAPI, l as PARENT_ADDITIONAL_PROPERTIES_KEY, m as UNWRAP_ROOT_KEY, n as isZodDto, o as fixAllRefs, p as SELF_REQUIRED_KEY, r as ioSymbol, s as DEFS_KEY, t as createZodDto, u as PARENT_HAS_REFS_KEY } from "./dto-D6WPyGHI.mjs";
2
+ import { createRequire } from "node:module";
3
+ import deepmerge from "deepmerge";
4
+ import { BadRequestException, HttpCode, HttpStatus, Inject, Injectable, InternalServerErrorException, Optional, SetMetadata, StreamableFile, UseGuards, applyDecorators } from "@nestjs/common";
5
+ import { map } from "rxjs";
6
+ import { isDeepStrictEqual } from "node:util";
7
+ //#region \0rolldown/runtime.js
8
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
9
+ //#endregion
10
+ //#region src/exception.ts
11
+ var ZodValidationException = class extends BadRequestException {
12
+ constructor(error) {
13
+ super({
14
+ statusCode: HttpStatus.BAD_REQUEST,
15
+ message: "Validation failed",
16
+ errors: error && typeof error === "object" && "issues" in error ? error.issues : void 0
17
+ });
18
+ this.error = error;
19
+ }
20
+ getZodError() {
21
+ return this.error;
22
+ }
23
+ };
24
+ var ZodSerializationException = class extends InternalServerErrorException {
25
+ constructor(error) {
26
+ super();
27
+ this.error = error;
28
+ }
29
+ getZodError() {
30
+ return this.error;
31
+ }
32
+ };
33
+ const createZodValidationException = (error) => {
34
+ return new ZodValidationException(error);
35
+ };
36
+ const createZodSerializationException = (error) => {
37
+ return new ZodSerializationException(error);
38
+ };
39
+ //#endregion
40
+ //#region src/validate.ts
41
+ /**
42
+ * @deprecated `validate` will be removed in a future version. It is
43
+ * recommended to use `.parse` directly
44
+ */
45
+ function validate(value, schemaOrDto, createValidationException = createZodValidationException) {
46
+ const schema = isZodDto(schemaOrDto) ? schemaOrDto.schema : schemaOrDto;
47
+ try {
48
+ return schema.parse(value);
49
+ } catch (error) {
50
+ throw createValidationException(error);
51
+ }
52
+ }
53
+ //#endregion
54
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorateMetadata.js
55
+ function __decorateMetadata(k, v) {
56
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
57
+ }
58
+ //#endregion
59
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorate.js
60
+ function __decorate(decorators, target, key, desc) {
61
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
62
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
63
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
64
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
65
+ }
66
+ //#endregion
67
+ //#region src/guard.ts
68
+ /**
69
+ * @deprecated `createZodGuard` will be removed in a future version, since
70
+ * guards are not intended for validation purposes.
71
+ */
72
+ function createZodGuard({ createValidationException } = {}) {
73
+ let ZodGuard = class ZodGuard {
74
+ constructor(source, schemaOrDto) {
75
+ this.source = source;
76
+ this.schemaOrDto = schemaOrDto;
77
+ }
78
+ canActivate(context) {
79
+ const data = context.switchToHttp().getRequest()[this.source];
80
+ validate(data, this.schemaOrDto, createValidationException);
81
+ return true;
82
+ }
83
+ };
84
+ ZodGuard = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [Object, Object])], ZodGuard);
85
+ return ZodGuard;
86
+ }
87
+ /**
88
+ * @deprecated `ZodGuard` will be removed in a future version, since guards
89
+ * are not intended for validation purposes.
90
+ */
91
+ const ZodGuard = createZodGuard();
92
+ /**
93
+ * @deprecated `UseZodGuard` will be removed in a future version, since guards
94
+ * are not intended for validation purposes.
95
+ */
96
+ const UseZodGuard = (source, schemaOrDto) => UseGuards(new ZodGuard(source, schemaOrDto));
97
+ //#endregion
98
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorateParam.js
99
+ function __decorateParam(paramIndex, decorator) {
100
+ return function(target, key) {
101
+ decorator(target, key, paramIndex);
102
+ };
103
+ }
104
+ //#endregion
105
+ //#region src/pipe.ts
106
+ var ZodSchemaDeclarationException = class extends InternalServerErrorException {
107
+ constructor() {
108
+ super();
109
+ }
110
+ };
111
+ function createZodValidationPipe({ createValidationException, strictSchemaDeclaration = false } = {}) {
112
+ let ZodValidationPipe = class ZodValidationPipe {
113
+ constructor(schemaOrDto) {
114
+ this.schemaOrDto = schemaOrDto;
115
+ }
116
+ transform(value, metadata) {
117
+ if (this.schemaOrDto) return validate(value, this.schemaOrDto, createValidationException);
118
+ const { metatype } = metadata;
119
+ if (!isZodDto(metatype)) {
120
+ if (strictSchemaDeclaration) throw new ZodSchemaDeclarationException();
121
+ return value;
122
+ }
123
+ return validate(value, metatype.schema, createValidationException);
124
+ }
125
+ };
126
+ ZodValidationPipe = __decorate([
127
+ Injectable(),
128
+ __decorateParam(0, Optional()),
129
+ __decorateMetadata("design:paramtypes", [Object])
130
+ ], ZodValidationPipe);
131
+ return ZodValidationPipe;
132
+ }
133
+ const ZodValidationPipe = createZodValidationPipe();
134
+ //#endregion
135
+ //#region src/serializer.ts
136
+ const REFLECTOR = "Reflector";
137
+ const ZodSerializerDtoOptions = "ZOD_SERIALIZER_DTO_OPTIONS";
138
+ function ZodSerializerDto(dto) {
139
+ if (Array.isArray(dto)) {
140
+ const schema = "schema" in dto[0] ? dto[0].schema : dto[0];
141
+ assert("array" in schema && typeof schema.array === "function", "ZodSerializerDto was used with array syntax (e.g. `ZodSerializerDto([MyDto])`) but the DTO schema does not have an array method");
142
+ }
143
+ return SetMetadata(ZodSerializerDtoOptions, dto);
144
+ }
145
+ function createZodSerializerInterceptor({ reportInput } = {}) {
146
+ let ZodSerializerInterceptor = class ZodSerializerInterceptor {
147
+ constructor(reflector) {
148
+ this.reflector = reflector;
149
+ }
150
+ intercept(context, next) {
151
+ const responseSchema = this.getContextResponseSchema(context);
152
+ return next.handle().pipe(map((res) => {
153
+ if (!responseSchema) return res;
154
+ if (res instanceof StreamableFile) return res;
155
+ if (Array.isArray(responseSchema)) {
156
+ const schemaOrDto = responseSchema[0];
157
+ const schema = "schema" in schemaOrDto ? schemaOrDto.schema : schemaOrDto;
158
+ assert("array" in schema && typeof schema.array === "function", "ZodSerializerDto was used with array syntax (e.g. `ZodSerializerDto([MyDto])`) but the DTO schema does not have an array method");
159
+ const arrSchema = schema.array();
160
+ if (isZodDto(schemaOrDto)) {
161
+ if (schemaOrDto.codec) {
162
+ assert(arrSchema.encode, "Schema does not have an encode method");
163
+ try {
164
+ return arrSchema.encode(res, reportInput !== void 0 ? { reportInput } : void 0);
165
+ } catch (error) {
166
+ throw createZodSerializationException(error);
167
+ }
168
+ }
169
+ try {
170
+ return arrSchema.parse(res, reportInput !== void 0 ? { reportInput } : void 0);
171
+ } catch (error) {
172
+ throw createZodSerializationException(error);
173
+ }
174
+ }
175
+ try {
176
+ return arrSchema.parse(res, reportInput !== void 0 ? { reportInput } : void 0);
177
+ } catch (error) {
178
+ throw createZodSerializationException(error);
179
+ }
180
+ }
181
+ if (isZodDto(responseSchema)) {
182
+ if (responseSchema.codec) {
183
+ assert(responseSchema.schema.encode, "Schema does not have an encode method");
184
+ try {
185
+ return responseSchema.schema.encode(res, reportInput !== void 0 ? { reportInput } : void 0);
186
+ } catch (error) {
187
+ throw createZodSerializationException(error);
188
+ }
189
+ }
190
+ try {
191
+ return responseSchema.schema.parse(res, reportInput !== void 0 ? { reportInput } : void 0);
192
+ } catch (error) {
193
+ throw createZodSerializationException(error);
194
+ }
195
+ }
196
+ try {
197
+ return responseSchema.parse(res, reportInput !== void 0 ? { reportInput } : void 0);
198
+ } catch (error) {
199
+ throw createZodSerializationException(error);
200
+ }
201
+ }));
202
+ }
203
+ getContextResponseSchema(context) {
204
+ return this.reflector.getAllAndOverride(ZodSerializerDtoOptions, [context.getHandler(), context.getClass()]);
205
+ }
206
+ };
207
+ ZodSerializerInterceptor = __decorate([
208
+ Injectable(),
209
+ __decorateParam(0, Inject(REFLECTOR)),
210
+ __decorateMetadata("design:paramtypes", [Object])
211
+ ], ZodSerializerInterceptor);
212
+ return ZodSerializerInterceptor;
213
+ }
214
+ const ZodSerializerInterceptor = createZodSerializerInterceptor();
215
+ //#endregion
216
+ //#region src/cleanupOpenApiDoc.ts
217
+ /**
218
+ * This function performs some post-processing on the OpenAPI document. It
219
+ * should only touch parts of the document that were generated from nestjs-zod
220
+ * DTOs.
221
+ *
222
+ * Specifically, this function:
223
+ * 1. Removes empty `type` fields
224
+ * 2. Renames OpenAPI schemas that have an explicit `id` field to match that
225
+ * `id`, instead of using the DTO class name
226
+ * 3. If the DTO's schema references another zod schema, it adds that zod
227
+ * schema's OpenAPI representation to `components.schemas`
228
+ * 4. If a DTO is created directly with an array zod schema, it ensures the
229
+ * OpenAPI schema is generated properly
230
+ * 5. Handles recursive zod schemas
231
+ * 6. Handles `null` properly based on the OpenAPI version
232
+ *
233
+ * @param doc - The OpenAPI document that is generated by `SwaggerModule.createDocument`
234
+ * @param options.version - The version of OpenAPI to use. Defaults to `auto`,
235
+ * which will use the version of the OpenAPI object passed in. Note if the
236
+ * version is `3.1` then it impacts how `null` is handled. In `3.0`, `nullable:
237
+ * true` is used, while in `3.1` `anyOf: [..., { type: 'null' }]` is used
238
+ * instead
239
+ * @returns A cleaned up OpenAPI document
240
+ */
241
+ function cleanupOpenApiDoc(doc, { version: versionParam = "auto" } = {}) {
242
+ const schemas = {};
243
+ const renames = {};
244
+ const version = versionParam === "auto" ? doc.openapi.startsWith("3.1") ? "3.1" : "3.0" : versionParam;
245
+ for (const [oldSchemaName, oldOpenapiSchema] of Object.entries(doc.components?.schemas || {})) {
246
+ const { newSchema, newSchemaName, additionalNewSchemas } = cleanupSchema({
247
+ oldSchemaName,
248
+ oldOpenapiSchema,
249
+ version
250
+ });
251
+ for (const [additionalSchemaName, additionalSchema] of Object.entries(additionalNewSchemas)) registerSchema(schemas, additionalSchemaName, additionalSchema);
252
+ if (oldSchemaName !== newSchemaName) renames[oldSchemaName] = newSchemaName;
253
+ registerSchema(schemas, newSchemaName, newSchema);
254
+ }
255
+ const paths = deepmerge(doc.paths, {});
256
+ for (const { get, patch, post, delete: del, put, head } of Object.values(paths)) for (const methodObject of Object.values({
257
+ get,
258
+ patch,
259
+ post,
260
+ del,
261
+ put,
262
+ head
263
+ })) {
264
+ fixRefsInBodies({
265
+ methodObject,
266
+ renames
267
+ });
268
+ for (let i = 0; i < (methodObject?.parameters || []).length; i++) {
269
+ assert(methodObject?.parameters, "parameters is required");
270
+ let parameter = methodObject.parameters[i];
271
+ parameter = fixParameter(parameter, version);
272
+ if (SELF_REQUIRED_KEY in parameter) {
273
+ if ("schema" in parameter && parameter.in === "query" && typeof parameter.style === "undefined" && parameter.schema && "type" in parameter.schema && parameter.schema.type === "object") parameter.style = "deepObject";
274
+ if ("schema" in parameter) {
275
+ if (Array.isArray(parameter.required) && parameter.schema && "type" in parameter.schema && parameter.schema.type === "object" && typeof parameter.schema.required === "undefined") parameter.schema.required = parameter.required;
276
+ parameter.required = Boolean(parameter[SELF_REQUIRED_KEY]);
277
+ }
278
+ delete parameter[SELF_REQUIRED_KEY];
279
+ }
280
+ if (DEFS_KEY in parameter) {
281
+ const defs = parameter[DEFS_KEY];
282
+ delete parameter[DEFS_KEY];
283
+ for (const [defSchemaId, defSchema] of Object.entries(defs)) {
284
+ let fixedDef;
285
+ try {
286
+ fixedDef = fixAllRefs({ schema: defSchema });
287
+ } catch (err) {
288
+ if (err instanceof Error && err.message.startsWith("[fixAllRefs]")) throw new Error(`[cleanupOpenApiDoc] Recursive schemas are not supported for parameters`, { cause: err });
289
+ throw err;
290
+ }
291
+ if (version === "3.0") fixedDef = convertToOpenApi3Point0(fixedDef);
292
+ registerSchema(schemas, defSchemaId, fixedDef);
293
+ }
294
+ }
295
+ methodObject.parameters[i] = parameter;
296
+ }
297
+ }
298
+ return {
299
+ ...doc,
300
+ paths,
301
+ components: {
302
+ ...doc.components,
303
+ schemas
304
+ }
305
+ };
306
+ }
307
+ /**
308
+ * Registers a schema in the schema registry.
309
+ *
310
+ * Mutates `schemaRegistry`
311
+ */
312
+ function registerSchema(schemaRegistry, schemaName, schema) {
313
+ if (schemaRegistry[schemaName] && !isDeepStrictEqual(schemaRegistry[schemaName], schema)) throw new Error(`[cleanupOpenApiDoc] Found multiple schemas with name \`${schemaName}\`. Please review your schemas to ensure that you are not using the same schema name for different schemas`);
314
+ schemaRegistry[schemaName] = schema;
315
+ }
316
+ /**
317
+ * In the process of cleaning up the OpenAPI document, we may rename schemas.
318
+ *
319
+ * This function fixes the `$ref` fields in the request body and responses to
320
+ * point to the correct schema names.
321
+ *
322
+ * Mutates `methodObject`
323
+ */
324
+ function fixRefsInBodies({ methodObject, renames }) {
325
+ const content = methodObject?.requestBody && "content" in methodObject.requestBody && methodObject.requestBody.content || {};
326
+ for (const requestBodyObject of Object.values(content)) if (requestBodyObject.schema && "$ref" in requestBodyObject.schema) {
327
+ const oldSchemaName = getSchemaNameFromRef(requestBodyObject.schema.$ref);
328
+ if (renames[oldSchemaName]) {
329
+ const newSchemaName = renames[oldSchemaName];
330
+ requestBodyObject.schema.$ref = requestBodyObject.schema.$ref.replace(`/${oldSchemaName}`, `/${newSchemaName}`);
331
+ }
332
+ }
333
+ for (const statusCodeObject of Object.values(methodObject?.responses || {})) {
334
+ const content = statusCodeObject && "content" in statusCodeObject && statusCodeObject.content || {};
335
+ for (const responseBodyObject of Object.values(content)) if (responseBodyObject.schema && "$ref" in responseBodyObject.schema) {
336
+ const oldSchemaName = getSchemaNameFromRef(responseBodyObject.schema.$ref);
337
+ if (renames[oldSchemaName]) {
338
+ const newSchemaName = renames[oldSchemaName];
339
+ responseBodyObject.schema.$ref = responseBodyObject.schema.$ref.replace(`/${oldSchemaName}`, `/${newSchemaName}`);
340
+ }
341
+ }
342
+ }
343
+ }
344
+ /**
345
+ * Cleans up a schema.
346
+ */
347
+ function cleanupSchema({ oldSchemaName, oldOpenapiSchema, version }) {
348
+ const additionalNewSchemas = {};
349
+ if (!("type" in oldOpenapiSchema) || oldOpenapiSchema.type !== "object") return {
350
+ newSchema: oldOpenapiSchema,
351
+ newSchemaName: oldSchemaName,
352
+ additionalNewSchemas
353
+ };
354
+ let newSchemaName = oldSchemaName;
355
+ let addedDefs = false;
356
+ let hasRefs = false;
357
+ let usesThreePointOneSyntax = false;
358
+ const defRenames = {};
359
+ let newOpenapiSchema = deepmerge({}, oldOpenapiSchema);
360
+ for (const [propertyName, propertySchema] of Object.entries(newOpenapiSchema.properties || {})) {
361
+ if (SELF_REQUIRED_KEY in propertySchema) {
362
+ if (!propertySchema[SELF_REQUIRED_KEY] && Array.isArray(newOpenapiSchema.required)) {
363
+ const idx = newOpenapiSchema.required.indexOf(propertyName);
364
+ if (idx !== -1) newOpenapiSchema.required.splice(idx, 1);
365
+ if (newOpenapiSchema.required.length === 0) delete newOpenapiSchema.required;
366
+ }
367
+ delete propertySchema[SELF_REQUIRED_KEY];
368
+ if ("selfRequired" in propertySchema) delete propertySchema.selfRequired;
369
+ }
370
+ if (USES_THREE_POINT_ONE_SYNTAX_KEY in propertySchema) {
371
+ usesThreePointOneSyntax = Boolean(propertySchema[USES_THREE_POINT_ONE_SYNTAX_KEY]);
372
+ delete propertySchema[USES_THREE_POINT_ONE_SYNTAX_KEY];
373
+ }
374
+ if (PARENT_HAS_REFS_KEY in propertySchema) {
375
+ hasRefs = Boolean(propertySchema[PARENT_HAS_REFS_KEY]);
376
+ delete propertySchema[PARENT_HAS_REFS_KEY];
377
+ }
378
+ if (EMPTY_TYPE_KEY in propertySchema && propertySchema[EMPTY_TYPE_KEY]) {
379
+ delete propertySchema[EMPTY_TYPE_KEY];
380
+ if ("type" in propertySchema && propertySchema.type === "") delete propertySchema.type;
381
+ }
382
+ if (PARENT_ID_KEY in propertySchema && typeof propertySchema[PARENT_ID_KEY] === "string") {
383
+ newSchemaName = propertySchema[PARENT_ID_KEY];
384
+ delete propertySchema[PARENT_ID_KEY];
385
+ }
386
+ if (PARENT_METADATA_KEY in propertySchema && typeof propertySchema[PARENT_METADATA_KEY] === "object") {
387
+ Object.assign(newOpenapiSchema, propertySchema[PARENT_METADATA_KEY]);
388
+ delete propertySchema[PARENT_METADATA_KEY];
389
+ }
390
+ if (PARENT_ADDITIONAL_PROPERTIES_KEY in propertySchema && typeof propertySchema[PARENT_ADDITIONAL_PROPERTIES_KEY] === "boolean") {
391
+ newOpenapiSchema.additionalProperties = propertySchema[PARENT_ADDITIONAL_PROPERTIES_KEY];
392
+ delete propertySchema[PARENT_ADDITIONAL_PROPERTIES_KEY];
393
+ }
394
+ if (DEFS_KEY in propertySchema) {
395
+ const defs = propertySchema[DEFS_KEY];
396
+ delete propertySchema[DEFS_KEY];
397
+ if (!addedDefs) {
398
+ for (const defSchemaId of Object.keys(defs)) if (defSchemaId.startsWith("__schema")) defRenames[defSchemaId] = `${newSchemaName}${defSchemaId}`;
399
+ for (const [defSchemaId, defSchema] of Object.entries(defs)) {
400
+ let fixedDef = fixAllRefs({
401
+ schema: defSchema,
402
+ rootSchemaName: newSchemaName,
403
+ defRenames
404
+ });
405
+ if (version === "3.0") fixedDef = convertToOpenApi3Point0(fixedDef);
406
+ registerSchema(additionalNewSchemas, defRenames[defSchemaId] || defSchemaId, fixedDef);
407
+ }
408
+ addedDefs = true;
409
+ }
410
+ }
411
+ }
412
+ if (newSchemaName !== oldSchemaName && "id" in newOpenapiSchema) newOpenapiSchema["id"] = newSchemaName;
413
+ if (hasRefs) newOpenapiSchema = fixAllRefs({
414
+ schema: newOpenapiSchema,
415
+ rootSchemaName: newSchemaName,
416
+ defRenames
417
+ });
418
+ if (usesThreePointOneSyntax && version === "3.0") newOpenapiSchema = convertToOpenApi3Point0(newOpenapiSchema);
419
+ if (newOpenapiSchema.properties && "root" in newOpenapiSchema.properties && UNWRAP_ROOT_KEY in newOpenapiSchema.properties.root) {
420
+ const replaceRoot = newOpenapiSchema.properties.root[UNWRAP_ROOT_KEY];
421
+ delete newOpenapiSchema.properties.root[UNWRAP_ROOT_KEY];
422
+ if (replaceRoot) newOpenapiSchema = newOpenapiSchema.properties.root;
423
+ }
424
+ if (additionalNewSchemas[newSchemaName] && !isDeepStrictEqual(additionalNewSchemas[newSchemaName], newOpenapiSchema)) throw new Error(`[cleanupOpenApiDoc] Found multiple schemas with name \`${newSchemaName}\`. Please review your schemas to ensure that you are not using the same schema name for different schemas`);
425
+ return {
426
+ newSchema: newOpenapiSchema,
427
+ newSchemaName,
428
+ additionalNewSchemas
429
+ };
430
+ }
431
+ /**
432
+ * Fixes various issues with parameters:
433
+ * 1. Removes empty `type` fields
434
+ * 2. Moves `const` from the root level of the parameter object to the schema
435
+ * 3. Fixes refs to point to components.schemas
436
+ * 4. Removes some nestjs-zod markers
437
+ */
438
+ function fixParameter(parameterInput, version) {
439
+ const parameter = deepmerge({}, parameterInput);
440
+ let usesThreePointOneSyntax = false;
441
+ if (EMPTY_TYPE_KEY in parameter) {
442
+ delete parameter[EMPTY_TYPE_KEY];
443
+ if ("schema" in parameter && parameter.schema && "type" in parameter.schema) delete parameter.schema.type;
444
+ }
445
+ if (UNWRAP_ROOT_KEY in parameter) throw new Error(`[cleanupOpenApiDoc] Query or url parameters must be an object type`);
446
+ if ("const" in parameter && "schema" in parameter && parameter.schema) {
447
+ Object.assign(parameter.schema, { const: parameter.const });
448
+ delete parameter.const;
449
+ }
450
+ if (PARENT_ID_KEY in parameter) delete parameter[PARENT_ID_KEY];
451
+ if (PARENT_METADATA_KEY in parameter) delete parameter[PARENT_METADATA_KEY];
452
+ if (PARENT_ADDITIONAL_PROPERTIES_KEY in parameter) delete parameter[PARENT_ADDITIONAL_PROPERTIES_KEY];
453
+ if (PARENT_HAS_REFS_KEY in parameter) {
454
+ delete parameter[PARENT_HAS_REFS_KEY];
455
+ if ("schema" in parameter) try {
456
+ parameter.schema = fixAllRefs({ schema: parameter.schema });
457
+ } catch (err) {
458
+ if (err instanceof Error && err.message.startsWith("[fixAllRefs]")) throw new Error(`[cleanupOpenApiDoc] Recursive schemas are not supported for parameters`, { cause: err });
459
+ throw err;
460
+ }
461
+ }
462
+ if (USES_THREE_POINT_ONE_SYNTAX_KEY in parameter) {
463
+ usesThreePointOneSyntax = Boolean(parameter[USES_THREE_POINT_ONE_SYNTAX_KEY]);
464
+ delete parameter[USES_THREE_POINT_ONE_SYNTAX_KEY];
465
+ }
466
+ if (PARENT_ADDITIONAL_PROPERTIES_KEY in parameter) delete parameter[PARENT_ADDITIONAL_PROPERTIES_KEY];
467
+ if (version === "3.0" && "schema" in parameter && parameter.schema && usesThreePointOneSyntax) parameter.schema = convertToOpenApi3Point0(parameter.schema);
468
+ return parameter;
469
+ }
470
+ function getSchemaNameFromRef(ref) {
471
+ const lastSlash = ref.lastIndexOf("/");
472
+ return ref.slice(lastSlash + 1);
473
+ }
474
+ //#endregion
475
+ //#region src/response.ts
476
+ let ApiResponse;
477
+ try {
478
+ ApiResponse = __require("@nestjs/swagger").ApiResponse;
479
+ } catch {}
480
+ function ZodResponse({ status, description, type }) {
481
+ assert(ApiResponse, "ZodResponse requires @nestjs/swagger to be installed");
482
+ if (Array.isArray(type)) {
483
+ assert(type[0][ioSymbol] !== "output", "There is no need to use Dto.Output with ZodResponse");
484
+ return applyDecorators(...[
485
+ ...status ? [HttpCode(status)] : [],
486
+ ZodSerializerDto(type),
487
+ ApiResponse({
488
+ status,
489
+ description,
490
+ type: [!type[0].codec && "_zod" in type[0].schema ? type[0].Output : type[0]]
491
+ }),
492
+ RequirePassthrough()
493
+ ]);
494
+ } else {
495
+ assert(type[ioSymbol] !== "output", "There is no need to use Dto.Output with ZodResponse");
496
+ return applyDecorators(...[
497
+ ...status ? [HttpCode(status)] : [],
498
+ ZodSerializerDto(type),
499
+ ApiResponse({
500
+ status,
501
+ description,
502
+ type: !type.codec && "_zod" in type.schema ? type.Output : type
503
+ }),
504
+ RequirePassthrough()
505
+ ]);
506
+ }
507
+ }
508
+ const ROUTE_ARGS_METADATA = "__routeArguments__";
509
+ const RESPONSE_PASSTHROUGH_METADATA = "__responsePassthrough__";
510
+ const RESPONSE_PARAMTYPE = "1";
511
+ function RequirePassthrough() {
512
+ return (target, propertyKey) => {
513
+ const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, target.constructor, propertyKey) || {};
514
+ if (Object.keys(args).some((key) => key.startsWith(`${RESPONSE_PARAMTYPE}:`))) assert(Reflect.getMetadata(RESPONSE_PASSTHROUGH_METADATA, target.constructor, propertyKey) === true, "@ZodResponse requires the passthrough option to be set (e.g. @Res({ passthrough: true })) when using @Res(). Using @Res() without passthrough bypasses the serialization interceptor.");
515
+ };
516
+ }
517
+ //#endregion
518
+ export { UseZodGuard, ZodGuard, ZodResponse, ZodSchemaDeclarationException, ZodSerializationException, ZodSerializerDto, ZodSerializerInterceptor, ZodValidationException, ZodValidationPipe, cleanupOpenApiDoc, configureZodDto, createZodDto, createZodGuard, createZodSerializerInterceptor, createZodValidationPipe, validate, zodV3ToOpenAPI };
Binary file
Binary file