nestjs-docfy 0.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.
package/README.md ADDED
@@ -0,0 +1,226 @@
1
+ # nestjs-docfy
2
+
3
+ Keep your NestJS controllers clean. Swagger documentation lives in a dedicated companion file — by naming convention, zero boilerplate.
4
+
5
+ ```ts
6
+ // users.controller.ts — no Swagger decorators at all
7
+ @WithDocs()
8
+ @Controller('users')
9
+ export class UsersController {
10
+ @Get()
11
+ findAll(): Promise<UserEntity[]> { ... }
12
+
13
+ @Post()
14
+ create(@Body() dto: CreateUserDto): Promise<UserEntity> { ... }
15
+ }
16
+ ```
17
+
18
+ ```ts
19
+ // users.controller.docs.ts — all documentation in one place
20
+ docs(UsersController, {
21
+ classDecorators: [ApiTags('users')],
22
+ methods: {
23
+ findAll: [
24
+ ApiOperation({ summary: 'List all users' }),
25
+ ApiResponse({ status: 200, type: [UserEntity] }),
26
+ ],
27
+ create: [
28
+ ApiOperation({ summary: 'Create a user' }),
29
+ ApiBody({ type: CreateUserDto }),
30
+ ApiResponse({ status: 201, type: UserEntity }),
31
+ ApiResponse({ status: 400, description: 'Invalid input' }),
32
+ ],
33
+ },
34
+ });
35
+ ```
36
+
37
+ ## Why
38
+
39
+ Swagger decorators are documentation. They have nothing to do with routing logic, validation, or business rules — yet they end up mixed into the same file, doubling its length and burying the code that actually matters.
40
+
41
+ `nestjs-docfy` enforces a clean boundary: controllers express behavior, docs files express documentation. The convention (`*.controller.docs.ts`) mirrors how NestJS already organizes specs (`*.controller.spec.ts`), so it feels natural from day one.
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ npm install nestjs-docfy
47
+ ```
48
+
49
+ **Peer dependencies** (already in your project):
50
+
51
+ ```bash
52
+ npm install @nestjs/common @nestjs/swagger reflect-metadata
53
+ ```
54
+
55
+ ## Setup
56
+
57
+ ### 1. Import `DocfyModule` in your root module
58
+
59
+ ```ts
60
+ // app.module.ts
61
+ import { Module } from '@nestjs/common';
62
+ import { DocfyModule } from 'nestjs-docfy';
63
+ import { UsersModule } from './users/users.module';
64
+
65
+ @Module({
66
+ imports: [
67
+ DocfyModule.forRoot(),
68
+ UsersModule,
69
+ ],
70
+ })
71
+ export class AppModule {}
72
+ ```
73
+
74
+ ### 2. Mark your controllers with `@WithDocs()`
75
+
76
+ ```ts
77
+ // users.controller.ts
78
+ import { Controller, Get, Post, Body, Param, Delete } from '@nestjs/common';
79
+ import { WithDocs } from 'nestjs-docfy';
80
+
81
+ @WithDocs()
82
+ @Controller('users')
83
+ export class UsersController {
84
+ // ... your route handlers, nothing else
85
+ }
86
+ ```
87
+
88
+ ### 3. Create the companion docs file
89
+
90
+ Name it exactly like the controller, replacing `.controller.ts` with `.controller.docs.ts`:
91
+
92
+ ```
93
+ src/users/users.controller.ts ← your controller
94
+ src/users/users.controller.docs.ts ← documentation goes here
95
+ ```
96
+
97
+ ```ts
98
+ // users.controller.docs.ts
99
+ import { HttpStatus } from '@nestjs/common';
100
+ import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';
101
+ import { UsersController } from './users.controller';
102
+ import { UserEntity } from './user.entity';
103
+ import { CreateUserDto } from './dto/create-user.dto';
104
+ import { docs } from 'nestjs-docfy';
105
+
106
+ docs(UsersController, {
107
+ classDecorators: [ApiTags('users')],
108
+ methods: {
109
+ findAll: [
110
+ ApiOperation({ summary: 'List all users' }),
111
+ ApiResponse({ status: HttpStatus.OK, type: [UserEntity] }),
112
+ ],
113
+ findOne: [
114
+ ApiOperation({ summary: 'Get a user by ID' }),
115
+ ApiParam({ name: 'id', description: 'User UUID' }),
116
+ ApiResponse({ status: HttpStatus.OK, type: UserEntity }),
117
+ ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'User not found' }),
118
+ ],
119
+ create: [
120
+ ApiOperation({ summary: 'Create a user' }),
121
+ ApiBody({ type: CreateUserDto }),
122
+ ApiResponse({ status: HttpStatus.CREATED, type: UserEntity }),
123
+ ApiResponse({ status: HttpStatus.BAD_REQUEST, description: 'Invalid input' }),
124
+ ],
125
+ },
126
+ });
127
+ ```
128
+
129
+ ### 4. Keep `main.ts` unchanged
130
+
131
+ `DocfyModule` applies documentation metadata synchronously during module initialization, before `SwaggerModule.createDocument` is called. No changes to your bootstrap function are needed.
132
+
133
+ ```ts
134
+ // main.ts — nothing changes here
135
+ async function bootstrap() {
136
+ const app = await NestFactory.create(AppModule);
137
+ const config = new DocumentBuilder().setTitle('My API').build();
138
+ const document = SwaggerModule.createDocument(app, config);
139
+ SwaggerModule.setup('api', app, document);
140
+ await app.listen(3000);
141
+ }
142
+ ```
143
+
144
+ ## API reference
145
+
146
+ ### `DocfyModule.forRoot(options?)`
147
+
148
+ Registers the module and loads all companion docs files for controllers marked with `@WithDocs()`.
149
+
150
+ | Option | Type | Default | Description |
151
+ |---|---|---|---|
152
+ | `strict` | `boolean` | `false` | Throw at startup if a controller has `@WithDocs()` but no companion docs file is found. Recommended for CI. |
153
+
154
+ ```ts
155
+ // Warn on missing docs files (default)
156
+ DocfyModule.forRoot()
157
+
158
+ // Throw on missing docs files — fail fast in CI
159
+ DocfyModule.forRoot({ strict: true })
160
+ ```
161
+
162
+ ---
163
+
164
+ ### `@WithDocs()`
165
+
166
+ Class decorator that marks a controller for companion file discovery. Pair with `@Controller()`.
167
+
168
+ ```ts
169
+ @WithDocs()
170
+ @Controller('products')
171
+ export class ProductsController { ... }
172
+ ```
173
+
174
+ Also sets `DOCFY_MARKER` metadata (`'docfy:with_docs'`) on the class, available for external introspection:
175
+
176
+ ```ts
177
+ import { DOCFY_MARKER } from 'nestjs-docfy';
178
+
179
+ const hasDocs = Reflect.getMetadata(DOCFY_MARKER, ProductsController) === true;
180
+ ```
181
+
182
+ ---
183
+
184
+ ### `docs(controllerClass, config)`
185
+
186
+ Applies Swagger decorators to a controller class from outside its file.
187
+ Call this at the top level of a `*.controller.docs.ts` file — it runs as a side effect on import.
188
+
189
+ **`config.classDecorators`** — `ClassDecorator[]` — decorators applied to the class constructor (e.g. `ApiTags`).
190
+
191
+ **`config.methods`** — `Record<string, MethodDecorator[]>` — decorators per method name. Each decorator is called exactly as TypeScript would call it if it were written inline.
192
+
193
+ If a method name in `config.methods` does not exist on the controller, a warning is logged and that entry is skipped — the rest of the docs file still applies.
194
+
195
+ ## File naming convention
196
+
197
+ | Controller file | Companion docs file |
198
+ |---|---|
199
+ | `users.controller.ts` | `users.controller.docs.ts` |
200
+ | `users.controller.js` (compiled) | `users.controller.docs.js` |
201
+
202
+ Discovery is automatic. `DocfyModule` locates each controller's source file via Node's module cache (`require.cache`) and resolves the companion path. This works identically in both `ts-node` (development) and compiled `dist/` (production).
203
+
204
+ > **Barrel re-exports**: if your controller is exported from an `index.ts` barrel in addition to its own file, `nestjs-docfy` prefers the `.controller.ts` file over the barrel. Make sure the class is exported directly from its own module file.
205
+
206
+ ## Testing
207
+
208
+ When testing application modules that import `DocfyModule`, reset the controller registry between test suites to avoid cross-contamination:
209
+
210
+ ```ts
211
+ import { resetDocfyRegistry } from 'nestjs-docfy/testing';
212
+
213
+ beforeEach(() => resetDocfyRegistry());
214
+ ```
215
+
216
+ ## How it works
217
+
218
+ NestJS calls `NestFactory.create()` to build the dependency graph and module instances, then calls `app.listen()` — which internally calls `app.init()` — to register routes and fire lifecycle hooks. `SwaggerModule.createDocument()` is called between these two steps, in `main.ts`.
219
+
220
+ `DocfyModule.forRoot()` runs synchronously during the `NestFactory.create()` phase (as the module graph is evaluated), which is *before* `SwaggerModule.createDocument()`. At that point, it uses `require()` to load each docs file, which calls `docs()` and writes `Reflect` metadata directly onto the controller methods — exactly as TypeScript decorator syntax would at class-definition time.
221
+
222
+ By the time `SwaggerModule.createDocument()` scans for metadata, all of it is already in place.
223
+
224
+ ## License
225
+
226
+ MIT
@@ -0,0 +1,30 @@
1
+ import { DynamicModule } from '@nestjs/common';
2
+ export interface DocfyModuleOptions {
3
+ /**
4
+ * When true, a controller marked with @WithDocs() that has no companion docs
5
+ * file throws an error at startup instead of emitting a warning.
6
+ * Useful for CI environments to catch missing docs files early.
7
+ * @default false
8
+ */
9
+ strict?: boolean;
10
+ }
11
+ /**
12
+ * Import once in your root AppModule — before any module that declares controllers
13
+ * marked with @WithDocs().
14
+ *
15
+ * @example
16
+ * @Module({
17
+ * imports: [DocfyModule.forRoot(), UsersModule],
18
+ * })
19
+ * export class AppModule {}
20
+ */
21
+ export declare class DocfyModule {
22
+ private static readonly logger;
23
+ static forRoot(options?: DocfyModuleOptions): DynamicModule;
24
+ /**
25
+ * @internal Exposed for unit testing only. Do not call from application code.
26
+ */
27
+ static _loadAllDocs(options?: DocfyModuleOptions, requireFn?: (path: string) => void, cacheReader?: () => Record<string, {
28
+ exports: Record<string, unknown>;
29
+ } | undefined>): void;
30
+ }
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var DocfyModule_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.DocfyModule = void 0;
11
+ const common_1 = require("@nestjs/common");
12
+ const registry_1 = require("./registry");
13
+ const resolve_docs_path_1 = require("./resolve-docs-path");
14
+ /**
15
+ * Import once in your root AppModule — before any module that declares controllers
16
+ * marked with @WithDocs().
17
+ *
18
+ * @example
19
+ * @Module({
20
+ * imports: [DocfyModule.forRoot(), UsersModule],
21
+ * })
22
+ * export class AppModule {}
23
+ */
24
+ let DocfyModule = DocfyModule_1 = class DocfyModule {
25
+ static forRoot(options = {}) {
26
+ DocfyModule_1._loadAllDocs(options);
27
+ return { module: DocfyModule_1 };
28
+ }
29
+ /**
30
+ * @internal Exposed for unit testing only. Do not call from application code.
31
+ */
32
+ static _loadAllDocs(options = {}, requireFn = require, cacheReader) {
33
+ const { strict = false } = options;
34
+ for (const controllerClass of registry_1.DocfyRegistry.getAll()) {
35
+ const docsPath = (0, resolve_docs_path_1.resolveDocsPath)(controllerClass, cacheReader);
36
+ if (!docsPath) {
37
+ const message = `Could not locate source file for ${controllerClass.name}. ` +
38
+ `Make sure the class is exported directly from its own module file ` +
39
+ `(not only via a barrel index.ts).`;
40
+ if (strict)
41
+ throw new Error(`[nestjs-docfy] ${message}`);
42
+ DocfyModule_1.logger.warn(message);
43
+ continue;
44
+ }
45
+ try {
46
+ requireFn(docsPath);
47
+ DocfyModule_1.logger.log(`Loaded docs for ${controllerClass.name} from ${docsPath}`);
48
+ }
49
+ catch (err) {
50
+ if (isMissingDocsFile(err, docsPath)) {
51
+ // The docs file simply doesn't exist — allowed unless strict mode
52
+ const message = `No docs file found for ${controllerClass.name}. Expected: ${docsPath}`;
53
+ if (strict)
54
+ throw new Error(`[nestjs-docfy] ${message}`);
55
+ DocfyModule_1.logger.warn(message);
56
+ }
57
+ else {
58
+ // Unexpected error (syntax error inside the docs file, missing dependency, etc.)
59
+ DocfyModule_1.logger.error(`Failed to load docs file for ${controllerClass.name}: ${docsPath}`, err);
60
+ throw err;
61
+ }
62
+ }
63
+ }
64
+ }
65
+ };
66
+ exports.DocfyModule = DocfyModule;
67
+ DocfyModule.logger = new common_1.Logger(DocfyModule_1.name);
68
+ exports.DocfyModule = DocfyModule = DocfyModule_1 = __decorate([
69
+ (0, common_1.Module)({})
70
+ ], DocfyModule);
71
+ /**
72
+ * Returns true only if the error means the docs file itself does not exist,
73
+ * not if a dependency inside the docs file is missing.
74
+ */
75
+ function isMissingDocsFile(err, docsPath) {
76
+ if (!(err instanceof Error))
77
+ return false;
78
+ if (!('code' in err) || err.code !== 'MODULE_NOT_FOUND')
79
+ return false;
80
+ // Node's error message for a missing top-level module includes its path.
81
+ // If the missing path is the docs file itself, the message contains docsPath.
82
+ // If it's a dependency inside the docs file, the message will contain a different path.
83
+ return err.message.includes(docsPath);
84
+ }
85
+ //# sourceMappingURL=docfy.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docfy.module.js","sourceRoot":"","sources":["../src/docfy.module.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,2CAA+D;AAC/D,yCAA2C;AAC3C,2DAAsD;AAYtD;;;;;;;;;GASG;AAEI,IAAM,WAAW,mBAAjB,MAAM,WAAW;IAGtB,MAAM,CAAC,OAAO,CAAC,UAA8B,EAAE;QAC7C,aAAW,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QAClC,OAAO,EAAE,MAAM,EAAE,aAAW,EAAE,CAAC;IACjC,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,YAAY,CACjB,UAA8B,EAAE,EAChC,YAAoC,OAAO,EAC3C,WAAoF;QAEpF,MAAM,EAAE,MAAM,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC;QAEnC,KAAK,MAAM,eAAe,IAAI,wBAAa,CAAC,MAAM,EAAE,EAAE,CAAC;YACrD,MAAM,QAAQ,GAAG,IAAA,mCAAe,EAAC,eAAe,EAAE,WAAW,CAAC,CAAC;YAE/D,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,MAAM,OAAO,GACX,oCAAoC,eAAe,CAAC,IAAI,IAAI;oBAC5D,oEAAoE;oBACpE,mCAAmC,CAAC;gBACtC,IAAI,MAAM;oBAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,OAAO,EAAE,CAAC,CAAC;gBACzD,aAAW,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBACjC,SAAS;YACX,CAAC;YAED,IAAI,CAAC;gBACH,SAAS,CAAC,QAAQ,CAAC,CAAC;gBACpB,aAAW,CAAC,MAAM,CAAC,GAAG,CAAC,mBAAmB,eAAe,CAAC,IAAI,SAAS,QAAQ,EAAE,CAAC,CAAC;YACrF,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACtB,IAAI,iBAAiB,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,CAAC;oBACrC,kEAAkE;oBAClE,MAAM,OAAO,GACX,0BAA0B,eAAe,CAAC,IAAI,eAAe,QAAQ,EAAE,CAAC;oBAC1E,IAAI,MAAM;wBAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,OAAO,EAAE,CAAC,CAAC;oBACzD,aAAW,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBACnC,CAAC;qBAAM,CAAC;oBACN,iFAAiF;oBACjF,aAAW,CAAC,MAAM,CAAC,KAAK,CACtB,gCAAgC,eAAe,CAAC,IAAI,KAAK,QAAQ,EAAE,EACnE,GAAG,CACJ,CAAC;oBACF,MAAM,GAAG,CAAC;gBACZ,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;;AAnDU,kCAAW;AACE,kBAAM,GAAG,IAAI,eAAM,CAAC,aAAW,CAAC,IAAI,CAAC,AAA/B,CAAgC;sBADnD,WAAW;IADvB,IAAA,eAAM,EAAC,EAAE,CAAC;GACE,WAAW,CAoDvB;AAED;;;GAGG;AACH,SAAS,iBAAiB,CAAC,GAAY,EAAE,QAAgB;IACvD,IAAI,CAAC,CAAC,GAAG,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC1C,IAAI,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,IAAK,GAA6B,CAAC,IAAI,KAAK,kBAAkB;QAAE,OAAO,KAAK,CAAC;IACjG,yEAAyE;IACzE,8EAA8E;IAC9E,wFAAwF;IACxF,OAAO,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AACxC,CAAC"}
package/dist/docs.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ type Constructor = new (...args: any[]) => any;
2
+ export interface DocsConfig {
3
+ /** Class-level decorators (e.g. ApiTags). Applied to the constructor. */
4
+ classDecorators?: ClassDecorator[];
5
+ /** Method-level decorators keyed by method name. */
6
+ methods?: Record<string, MethodDecorator[]>;
7
+ }
8
+ /**
9
+ * Applies Swagger decorators to a controller class from outside the class file.
10
+ * Mirrors exactly what TypeScript decorator syntax does: each decorator factory
11
+ * is called with (prototype, methodName, descriptor) for methods, or (target)
12
+ * for class-level decorators.
13
+ *
14
+ * Call this at the top level of a *.controller.docs.ts file:
15
+ *
16
+ * @example
17
+ * docs(UsersController, {
18
+ * classDecorators: [ApiTags('users')],
19
+ * methods: {
20
+ * findAll: [ApiOperation({ summary: 'List all users' })],
21
+ * },
22
+ * });
23
+ */
24
+ export declare function docs(controllerClass: Constructor, config: DocsConfig): void;
25
+ export {};
package/dist/docs.js ADDED
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.docs = docs;
4
+ /**
5
+ * Applies Swagger decorators to a controller class from outside the class file.
6
+ * Mirrors exactly what TypeScript decorator syntax does: each decorator factory
7
+ * is called with (prototype, methodName, descriptor) for methods, or (target)
8
+ * for class-level decorators.
9
+ *
10
+ * Call this at the top level of a *.controller.docs.ts file:
11
+ *
12
+ * @example
13
+ * docs(UsersController, {
14
+ * classDecorators: [ApiTags('users')],
15
+ * methods: {
16
+ * findAll: [ApiOperation({ summary: 'List all users' })],
17
+ * },
18
+ * });
19
+ */
20
+ function docs(controllerClass, config) {
21
+ if (config.classDecorators) {
22
+ for (const decorator of config.classDecorators) {
23
+ decorator(controllerClass);
24
+ }
25
+ }
26
+ if (!config.methods)
27
+ return;
28
+ for (const [methodName, decorators] of Object.entries(config.methods)) {
29
+ const descriptor = Object.getOwnPropertyDescriptor(controllerClass.prototype, methodName);
30
+ if (!descriptor) {
31
+ console.warn(`[nestjs-docfy] Method "${methodName}" not found on ${controllerClass.name}. ` +
32
+ `Check the spelling in your docs file.`);
33
+ continue;
34
+ }
35
+ for (const decorator of decorators) {
36
+ decorator(controllerClass.prototype, methodName, descriptor);
37
+ }
38
+ }
39
+ }
40
+ //# sourceMappingURL=docs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docs.js","sourceRoot":"","sources":["../src/docs.ts"],"names":[],"mappings":";;AAyBA,oBA2BC;AA3CD;;;;;;;;;;;;;;;GAeG;AACH,SAAgB,IAAI,CAAC,eAA4B,EAAE,MAAkB;IACnE,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;QAC3B,KAAK,MAAM,SAAS,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;YAC/C,SAAS,CAAC,eAAe,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAO;IAE5B,KAAK,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;QACtE,MAAM,UAAU,GAAG,MAAM,CAAC,wBAAwB,CAChD,eAAe,CAAC,SAAS,EACzB,UAAU,CACX,CAAC;QAEF,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,CAAC,IAAI,CACV,0BAA0B,UAAU,kBAAkB,eAAe,CAAC,IAAI,IAAI;gBAC5E,uCAAuC,CAC1C,CAAC;YACF,SAAS;QACX,CAAC;QAED,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACnC,SAAS,CAAC,eAAe,CAAC,SAAS,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { WithDocs, DOCFY_MARKER } from './with-docs.decorator';
2
+ export { docs, DocsConfig } from './docs';
3
+ export { DocfyModule, DocfyModuleOptions } from './docfy.module';
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocfyModule = exports.docs = exports.DOCFY_MARKER = exports.WithDocs = void 0;
4
+ var with_docs_decorator_1 = require("./with-docs.decorator");
5
+ Object.defineProperty(exports, "WithDocs", { enumerable: true, get: function () { return with_docs_decorator_1.WithDocs; } });
6
+ Object.defineProperty(exports, "DOCFY_MARKER", { enumerable: true, get: function () { return with_docs_decorator_1.DOCFY_MARKER; } });
7
+ var docs_1 = require("./docs");
8
+ Object.defineProperty(exports, "docs", { enumerable: true, get: function () { return docs_1.docs; } });
9
+ var docfy_module_1 = require("./docfy.module");
10
+ Object.defineProperty(exports, "DocfyModule", { enumerable: true, get: function () { return docfy_module_1.DocfyModule; } });
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,6DAA+D;AAAtD,+GAAA,QAAQ,OAAA;AAAE,mHAAA,YAAY,OAAA;AAC/B,+BAA0C;AAAjC,4FAAA,IAAI,OAAA;AACb,+CAAiE;AAAxD,2GAAA,WAAW,OAAA"}
@@ -0,0 +1,5 @@
1
+ export declare const DocfyRegistry: {
2
+ add(target: Function): void;
3
+ getAll(): ReadonlySet<Function>;
4
+ _reset(): void;
5
+ };
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocfyRegistry = void 0;
4
+ // Global registry of classes decorated with @WithDocs().
5
+ // Populated at class-definition time; consumed by DocfyModule.forRoot().
6
+ const registry = new Set();
7
+ exports.DocfyRegistry = {
8
+ add(target) {
9
+ registry.add(target);
10
+ },
11
+ getAll() {
12
+ return registry;
13
+ },
14
+ // For testing only — resets the registry between test runs.
15
+ _reset() {
16
+ registry.clear();
17
+ },
18
+ };
19
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":";;;AAAA,yDAAyD;AACzD,yEAAyE;AACzE,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAY,CAAC;AAExB,QAAA,aAAa,GAAG;IAC3B,GAAG,CAAC,MAAgB;QAClB,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC;IAED,MAAM;QACJ,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,4DAA4D;IAC5D,MAAM;QACJ,QAAQ,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;CACF,CAAC"}
@@ -0,0 +1,18 @@
1
+ type CacheSnapshot = Record<string, {
2
+ exports: Record<string, unknown>;
3
+ } | undefined>;
4
+ /**
5
+ * Given a controller class, finds its own source file in require.cache and derives
6
+ * the companion docs file path by replacing the suffix:
7
+ * users.controller.js → users.controller.docs.js
8
+ * users.controller.ts → users.controller.docs.ts (ts-node)
9
+ *
10
+ * Returns null if:
11
+ * - the controller's file cannot be located in the module cache
12
+ * - the file does not follow the *.controller.* naming convention
13
+ * - the class is only found via a barrel re-export (index.ts) rather than its own file
14
+ *
15
+ * @param readCache Injected for testing; defaults to () => require.cache.
16
+ */
17
+ export declare function resolveDocsPath(controllerClass: Function, readCache?: () => CacheSnapshot): string | null;
18
+ export {};
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.resolveDocsPath = resolveDocsPath;
37
+ const path = __importStar(require("path"));
38
+ /**
39
+ * Given a controller class, finds its own source file in require.cache and derives
40
+ * the companion docs file path by replacing the suffix:
41
+ * users.controller.js → users.controller.docs.js
42
+ * users.controller.ts → users.controller.docs.ts (ts-node)
43
+ *
44
+ * Returns null if:
45
+ * - the controller's file cannot be located in the module cache
46
+ * - the file does not follow the *.controller.* naming convention
47
+ * - the class is only found via a barrel re-export (index.ts) rather than its own file
48
+ *
49
+ * @param readCache Injected for testing; defaults to () => require.cache.
50
+ */
51
+ function resolveDocsPath(controllerClass, readCache = () => require.cache) {
52
+ const controllerFile = findFileInCache(controllerClass, readCache());
53
+ if (!controllerFile)
54
+ return null;
55
+ const ext = path.extname(controllerFile); // .ts or .js
56
+ const base = controllerFile.slice(0, -ext.length);
57
+ // Require the .controller suffix so we don't match barrel index files or services
58
+ if (!base.endsWith('.controller'))
59
+ return null;
60
+ return `${base}.docs${ext}`;
61
+ }
62
+ /**
63
+ * Searches require.cache for the file that directly owns the class.
64
+ *
65
+ * Prefers files whose basename contains the class name in kebab/snake/camel form,
66
+ * so that a barrel re-export (index.ts) is ranked below the actual source file.
67
+ * Both are valid cache entries — we want the most specific one.
68
+ */
69
+ function findFileInCache(target, cache) {
70
+ const candidates = [];
71
+ for (const [filename, mod] of Object.entries(cache)) {
72
+ if (!mod?.exports)
73
+ continue;
74
+ for (const key of Object.keys(mod.exports)) {
75
+ if (mod.exports[key] === target) {
76
+ candidates.push(filename);
77
+ break;
78
+ }
79
+ }
80
+ }
81
+ if (candidates.length === 0)
82
+ return null;
83
+ if (candidates.length === 1)
84
+ return candidates[0];
85
+ // Multiple files export the same class (barrel re-exports).
86
+ // Prefer the file whose name matches the .controller. convention,
87
+ // since barrel files (index.ts / index.js) never match that pattern.
88
+ const directFile = candidates.find((f) => {
89
+ const base = path.basename(f, path.extname(f));
90
+ return base.endsWith('.controller') || base.includes('.controller.');
91
+ });
92
+ return directFile ?? candidates[0];
93
+ }
94
+ //# sourceMappingURL=resolve-docs-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-docs-path.js","sourceRoot":"","sources":["../src/resolve-docs-path.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,0CAcC;AA/BD,2CAA6B;AAI7B;;;;;;;;;;;;GAYG;AACH,SAAgB,eAAe,CAC7B,eAAyB,EACzB,YAAiC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAiC;IAEhF,MAAM,cAAc,GAAG,eAAe,CAAC,eAAe,EAAE,SAAS,EAAE,CAAC,CAAC;IACrE,IAAI,CAAC,cAAc;QAAE,OAAO,IAAI,CAAC;IAEjC,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,aAAa;IACvD,MAAM,IAAI,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAElD,kFAAkF;IAClF,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC;QAAE,OAAO,IAAI,CAAC;IAE/C,OAAO,GAAG,IAAI,QAAQ,GAAG,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,SAAS,eAAe,CAAC,MAAgB,EAAE,KAAoB;IAC7D,MAAM,UAAU,GAAa,EAAE,CAAC;IAEhC,KAAK,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACpD,IAAI,CAAC,GAAG,EAAE,OAAO;YAAE,SAAS;QAC5B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;YAC3C,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,MAAM,EAAE,CAAC;gBAChC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;gBAC1B,MAAM;YACR,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC;IAElD,4DAA4D;IAC5D,kEAAkE;IAClE,qEAAqE;IACrE,MAAM,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;QACvC,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/C,OAAO,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IACvE,CAAC,CAAC,CAAC;IAEH,OAAO,UAAU,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;AACrC,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Testing utilities for nestjs-docfy.
3
+ * Import from 'nestjs-docfy/testing' in your test files.
4
+ *
5
+ * @example
6
+ * import { resetDocfyRegistry } from 'nestjs-docfy/testing';
7
+ * beforeEach(() => resetDocfyRegistry());
8
+ */
9
+ import { DocfyRegistry } from './registry';
10
+ export { DocfyRegistry };
11
+ export declare function resetDocfyRegistry(): void;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocfyRegistry = void 0;
4
+ exports.resetDocfyRegistry = resetDocfyRegistry;
5
+ /**
6
+ * Testing utilities for nestjs-docfy.
7
+ * Import from 'nestjs-docfy/testing' in your test files.
8
+ *
9
+ * @example
10
+ * import { resetDocfyRegistry } from 'nestjs-docfy/testing';
11
+ * beforeEach(() => resetDocfyRegistry());
12
+ */
13
+ const registry_1 = require("./registry");
14
+ Object.defineProperty(exports, "DocfyRegistry", { enumerable: true, get: function () { return registry_1.DocfyRegistry; } });
15
+ function resetDocfyRegistry() {
16
+ registry_1.DocfyRegistry._reset();
17
+ }
18
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":";;;AAYA,gDAEC;AAdD;;;;;;;GAOG;AACH,yCAA2C;AAElC,8FAFA,wBAAa,OAEA;AAEtB,SAAgB,kBAAkB;IAChC,wBAAa,CAAC,MAAM,EAAE,CAAC;AACzB,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Metadata key set on every class decorated with @WithDocs().
3
+ * The lib itself uses the global DocfyRegistry (not this metadata) for discovery.
4
+ * Exposed for external introspection — e.g. guards, interceptors, or tooling
5
+ * that need to check whether a controller has a companion docs file:
6
+ *
7
+ * @example
8
+ * const hasDocs = Reflect.getMetadata(DOCFY_MARKER, MyController) === true;
9
+ */
10
+ export declare const DOCFY_MARKER = "docfy:with_docs";
11
+ /**
12
+ * Marks a NestJS controller so that DocfyModule will load its companion
13
+ * docs file (*.controller.docs.ts / *.controller.docs.js) at startup.
14
+ *
15
+ * @example
16
+ * @WithDocs()
17
+ * @Controller('users')
18
+ * export class UsersController { ... }
19
+ */
20
+ export declare function WithDocs(): ClassDecorator;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DOCFY_MARKER = void 0;
4
+ exports.WithDocs = WithDocs;
5
+ const common_1 = require("@nestjs/common");
6
+ const registry_1 = require("./registry");
7
+ /**
8
+ * Metadata key set on every class decorated with @WithDocs().
9
+ * The lib itself uses the global DocfyRegistry (not this metadata) for discovery.
10
+ * Exposed for external introspection — e.g. guards, interceptors, or tooling
11
+ * that need to check whether a controller has a companion docs file:
12
+ *
13
+ * @example
14
+ * const hasDocs = Reflect.getMetadata(DOCFY_MARKER, MyController) === true;
15
+ */
16
+ exports.DOCFY_MARKER = 'docfy:with_docs';
17
+ /**
18
+ * Marks a NestJS controller so that DocfyModule will load its companion
19
+ * docs file (*.controller.docs.ts / *.controller.docs.js) at startup.
20
+ *
21
+ * @example
22
+ * @WithDocs()
23
+ * @Controller('users')
24
+ * export class UsersController { ... }
25
+ */
26
+ function WithDocs() {
27
+ return (target) => {
28
+ (0, common_1.SetMetadata)(exports.DOCFY_MARKER, true)(target);
29
+ registry_1.DocfyRegistry.add(target);
30
+ };
31
+ }
32
+ //# sourceMappingURL=with-docs.decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"with-docs.decorator.js","sourceRoot":"","sources":["../src/with-docs.decorator.ts"],"names":[],"mappings":";;;AAuBA,4BAKC;AA5BD,2CAA6C;AAC7C,yCAA2C;AAE3C;;;;;;;;GAQG;AACU,QAAA,YAAY,GAAG,iBAAiB,CAAC;AAE9C;;;;;;;;GAQG;AACH,SAAgB,QAAQ;IACtB,OAAO,CAAC,MAAgB,EAAE,EAAE;QAC1B,IAAA,oBAAW,EAAC,oBAAY,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC;QACxC,wBAAa,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC5B,CAAC,CAAC;AACJ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "nestjs-docfy",
3
+ "version": "0.1.0",
4
+ "description": "Keep your NestJS controllers clean — Swagger docs live in a separate companion file by naming convention",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "require": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ },
12
+ "./testing": {
13
+ "require": "./dist/testing.js",
14
+ "types": "./dist/testing.d.ts"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "engines": {
21
+ "node": ">=16.0.0"
22
+ },
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.build.json",
25
+ "build:watch": "tsc -p tsconfig.build.json --watch",
26
+ "test": "jest",
27
+ "test:watch": "jest --watch",
28
+ "test:cov": "jest --coverage",
29
+ "prepublishOnly": "npm run build"
30
+ },
31
+ "keywords": [
32
+ "nestjs",
33
+ "swagger",
34
+ "openapi",
35
+ "decorator",
36
+ "documentation",
37
+ "companion"
38
+ ],
39
+ "author": "Marvin Rocha",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/MarvinRF/nest-docfy.git"
43
+ },
44
+ "homepage": "https://github.com/MarvinRF/nest-docfy#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/MarvinRF/nest-docfy/issues"
47
+ },
48
+ "license": "MIT",
49
+ "peerDependencies": {
50
+ "@nestjs/common": ">=9.0.0",
51
+ "@nestjs/swagger": ">=6.0.0",
52
+ "reflect-metadata": "^0.1.13 || ^0.2.0"
53
+ },
54
+ "devDependencies": {
55
+ "@nestjs/common": "^11.0.0",
56
+ "@nestjs/core": "^11.0.0",
57
+ "@nestjs/swagger": "^11.0.0",
58
+ "@types/jest": "^29.5.14",
59
+ "@types/node": "^22.0.0",
60
+ "jest": "^29.7.0",
61
+ "reflect-metadata": "^0.2.2",
62
+ "ts-jest": "^29.2.5",
63
+ "ts-node": "^10.9.2",
64
+ "typescript": "^5.7.3"
65
+ }
66
+ }