nestjs-docfy 0.5.0 → 0.6.1
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 +130 -90
- package/dist/cli/detect-project.d.ts +8 -0
- package/dist/cli/detect-project.js +27 -0
- package/dist/cli/detect-project.js.map +1 -1
- package/dist/cli/extract-methods.js +58 -8
- package/dist/cli/extract-methods.js.map +1 -1
- package/dist/cli/generate-client.d.ts +15 -0
- package/dist/cli/generate-client.js +62 -0
- package/dist/cli/generate-client.js.map +1 -0
- package/dist/cli/generate-file.js +2 -2
- package/dist/cli/generate-file.js.map +1 -1
- package/dist/cli/index.js +144 -56
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/parse-args.d.ts +2 -0
- package/dist/cli/parse-args.js +1 -0
- package/dist/cli/parse-args.js.map +1 -1
- package/dist/cli/read-spec-source.d.ts +7 -0
- package/dist/cli/read-spec-source.js +74 -0
- package/dist/cli/read-spec-source.js.map +1 -0
- package/dist/cli/register-webpack-plugin.d.ts +16 -0
- package/dist/cli/register-webpack-plugin.js +46 -0
- package/dist/cli/register-webpack-plugin.js.map +1 -0
- package/dist/docfy-ui.module.d.ts +13 -0
- package/dist/docfy-ui.module.js +4 -1
- package/dist/docfy-ui.module.js.map +1 -1
- package/package.json +3 -2
- package/dist/require-ts.d.ts +0 -32
- package/dist/require-ts.js +0 -122
- package/dist/require-ts.js.map +0 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
[](https://github.com/MarvinRF/nest-docfy/issues)
|
|
10
10
|
[](https://github.com/MarvinRF/nest-docfy/blob/main/LICENSE)
|
|
11
11
|
|
|
12
|
-
Keep your NestJS controllers clean. Swagger documentation lives in a dedicated companion file
|
|
12
|
+
Keep your NestJS controllers clean. Swagger documentation lives in a dedicated companion file, by naming convention, with zero boilerplate.
|
|
13
13
|
|
|
14
14
|
📖 **[Full documentation](https://www.nestdocfy.com/)**
|
|
15
15
|
|
|
@@ -22,14 +22,15 @@ Keep your NestJS controllers clean. Swagger documentation lives in a dedicated c
|
|
|
22
22
|
- [2. Mark your controllers](#2-mark-your-controllers)
|
|
23
23
|
- [3. Generate companion docs files](#3-generate-companion-docs-files)
|
|
24
24
|
- [4. Fill in the docs file](#4-fill-in-the-docs-file)
|
|
25
|
-
- [CLI
|
|
25
|
+
- [CLI: generate](#cli-generate)
|
|
26
26
|
- [Options](#options)
|
|
27
27
|
- [Project types](#project-types)
|
|
28
28
|
- [Idempotency and --force](#idempotency-and---force)
|
|
29
|
-
- [CLI
|
|
30
|
-
- [CLI
|
|
31
|
-
- [CLI
|
|
32
|
-
- [CLI
|
|
29
|
+
- [CLI: check](#cli-check)
|
|
30
|
+
- [CLI: coverage](#cli-coverage)
|
|
31
|
+
- [CLI: lint](#cli-lint)
|
|
32
|
+
- [CLI: patch-spec](#cli-patch-spec)
|
|
33
|
+
- [CLI: generate-client](#cli-generate-client)
|
|
33
34
|
- [API reference](#api-reference)
|
|
34
35
|
- [DocfyModule.forRoot()](#docfymoduleforrootoptions)
|
|
35
36
|
- [@WithDocs()](#withdocs)
|
|
@@ -49,9 +50,9 @@ Keep your NestJS controllers clean. Swagger documentation lives in a dedicated c
|
|
|
49
50
|
|
|
50
51
|
## Motivation
|
|
51
52
|
|
|
52
|
-
Swagger decorators are documentation. They have nothing to do with routing logic, validation, or business rules
|
|
53
|
+
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.
|
|
53
54
|
|
|
54
|
-
**Before
|
|
55
|
+
**Before**: Swagger decorators scattered across your controller.
|
|
55
56
|
|
|
56
57
|
```ts
|
|
57
58
|
// users.controller.ts
|
|
@@ -76,7 +77,7 @@ export class UsersController {
|
|
|
76
77
|
}
|
|
77
78
|
```
|
|
78
79
|
|
|
79
|
-
**After
|
|
80
|
+
**After**: the controller expresses only behavior.
|
|
80
81
|
|
|
81
82
|
```ts
|
|
82
83
|
// users.controller.ts
|
|
@@ -94,7 +95,7 @@ export class UsersController {
|
|
|
94
95
|
```
|
|
95
96
|
|
|
96
97
|
```ts
|
|
97
|
-
// users.controller.docs.ts
|
|
98
|
+
// users.controller.docs.ts: all documentation in one place
|
|
98
99
|
docs(UsersController, {
|
|
99
100
|
classDecorators: [ApiTags('users')],
|
|
100
101
|
methods: {
|
|
@@ -141,7 +142,7 @@ import { DocfyModule } from 'nestjs-docfy';
|
|
|
141
142
|
export class AppModule {}
|
|
142
143
|
```
|
|
143
144
|
|
|
144
|
-
Pass `{ strict: true }` to fail fast at startup when a controller has `@WithDocs()` but no companion file is found
|
|
145
|
+
Pass `{ strict: true }` to fail fast at startup when a controller has `@WithDocs()` but no companion file is found. Recommended for CI:
|
|
145
146
|
|
|
146
147
|
```ts
|
|
147
148
|
DocfyModule.forRoot({ strict: true });
|
|
@@ -157,7 +158,7 @@ import { WithDocs } from 'nestjs-docfy';
|
|
|
157
158
|
@WithDocs()
|
|
158
159
|
@Controller('users')
|
|
159
160
|
export class UsersController {
|
|
160
|
-
// route handlers only
|
|
161
|
+
// route handlers only, no Swagger decorators here
|
|
161
162
|
}
|
|
162
163
|
```
|
|
163
164
|
|
|
@@ -169,7 +170,7 @@ Run the CLI to scan your project and generate a pre-filled `*.controller.docs.ts
|
|
|
169
170
|
npx nestjs-docfy generate
|
|
170
171
|
```
|
|
171
172
|
|
|
172
|
-
The CLI uses **static analysis only** (no code execution) and auto-detects your project layout
|
|
173
|
+
The CLI uses **static analysis only** (no code execution) and auto-detects your project layout: monorepos, Nx workspaces, and Nest CLI monorepos are all supported.
|
|
173
174
|
|
|
174
175
|
To preview what would be written without touching the filesystem:
|
|
175
176
|
|
|
@@ -182,7 +183,7 @@ npx nestjs-docfy generate --dry-run
|
|
|
182
183
|
The generated file comes pre-populated with inferred summaries, response types, and common error responses:
|
|
183
184
|
|
|
184
185
|
```ts
|
|
185
|
-
// Generated by nestjs-docfy
|
|
186
|
+
// Generated by nestjs-docfy. Edit freely, use --force to merge new methods
|
|
186
187
|
import { docs } from 'nestjs-docfy';
|
|
187
188
|
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
|
|
188
189
|
import { UsersController } from './users.controller';
|
|
@@ -209,11 +210,11 @@ docs(UsersController, {
|
|
|
209
210
|
});
|
|
210
211
|
```
|
|
211
212
|
|
|
212
|
-
Edit the file freely
|
|
213
|
+
Edit the file freely; your changes are safe. Running `generate` again will skip existing files. Use `--force` to merge only **new** methods without touching existing ones.
|
|
213
214
|
|
|
214
215
|
No changes to `main.ts` are needed. `DocfyModule` applies all metadata before `SwaggerModule.createDocument()` is called.
|
|
215
216
|
|
|
216
|
-
## CLI
|
|
217
|
+
## CLI: generate
|
|
217
218
|
|
|
218
219
|
```bash
|
|
219
220
|
npx nestjs-docfy generate [options]
|
|
@@ -221,20 +222,22 @@ npx nestjs-docfy generate [options]
|
|
|
221
222
|
|
|
222
223
|
### Options
|
|
223
224
|
|
|
224
|
-
| Option | Default | Description
|
|
225
|
-
| ------------------- | ------------------------- |
|
|
226
|
-
| `--root <path>` | `.` | Project root directory
|
|
227
|
-
| `--tsconfig <path>` | auto-detected | Path to `tsconfig.json`
|
|
228
|
-
| `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers
|
|
229
|
-
| `--out <path>` | alongside each controller | Output directory for generated files
|
|
230
|
-
| `--force` | `false` | Merge new methods into existing docs files (preserves user edits)
|
|
231
|
-
| `--dry-run` | `false` | Print what would be generated without writing files
|
|
232
|
-
| `--quiet` | `false` | Suppress all output except errors (CI-friendly)
|
|
233
|
-
| `--format` | `ts` | Output format: `ts` or `js`
|
|
225
|
+
| Option | Default | Description |
|
|
226
|
+
| ------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------- |
|
|
227
|
+
| `--root <path>` | `.` | Project root directory |
|
|
228
|
+
| `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
|
|
229
|
+
| `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
|
|
230
|
+
| `--out <path>` | alongside each controller | Output directory for generated files |
|
|
231
|
+
| `--force` | `false` | Merge new methods into existing docs files (preserves user edits) |
|
|
232
|
+
| `--dry-run` | `false` | Print what would be generated without writing files |
|
|
233
|
+
| `--quiet` | `false` | Suppress all output except errors (CI-friendly) |
|
|
234
|
+
| `--format` | `ts` | Output format: `ts` or `js` |
|
|
235
|
+
| `--watch` | `false` | Re-generate on controller file changes |
|
|
236
|
+
| `--register-plugin` | `false` | If `webpack: true` is set without the CLI plugin, add `nestjs-docfy` to `nest-cli.json`'s `compilerOptions.plugins` |
|
|
234
237
|
|
|
235
238
|
### Project types
|
|
236
239
|
|
|
237
|
-
The CLI auto-detects your project layout
|
|
240
|
+
The CLI auto-detects your project layout, no configuration needed:
|
|
238
241
|
|
|
239
242
|
| Layout | Detected when |
|
|
240
243
|
| ----------------- | ---------------------------------------------------- |
|
|
@@ -248,7 +251,7 @@ The CLI auto-detects your project layout — no configuration needed:
|
|
|
248
251
|
| Scenario | Behavior |
|
|
249
252
|
| ------------------------------------------ | -------------------------------------------------- |
|
|
250
253
|
| Run `generate` on a clean project | Creates all docs files |
|
|
251
|
-
| Run `generate` again (no changes) | Skips all existing files
|
|
254
|
+
| Run `generate` again (no changes) | Skips all existing files, safe to run repeatedly |
|
|
252
255
|
| Add a new endpoint, run `generate --force` | Merges new method block, preserves existing arrays |
|
|
253
256
|
| Edit a method's decorators, run `--force` | Your edits are preserved |
|
|
254
257
|
|
|
@@ -263,21 +266,22 @@ Add to your `package.json` for convenience:
|
|
|
263
266
|
}
|
|
264
267
|
```
|
|
265
268
|
|
|
266
|
-
## CLI
|
|
269
|
+
## CLI: check
|
|
267
270
|
|
|
268
|
-
Verify that every controller is fully documented before merging. Exits with code `1` if any drift is detected
|
|
271
|
+
Verify that every controller is fully documented before merging. Exits with code `1` if any drift is detected, designed for CI pipelines.
|
|
269
272
|
|
|
270
273
|
```bash
|
|
271
274
|
npx nestjs-docfy check [options]
|
|
272
275
|
```
|
|
273
276
|
|
|
274
|
-
| Option | Default | Description
|
|
275
|
-
| ------------------- | -------------------- |
|
|
276
|
-
| `--root <path>` | `.` | Project root directory
|
|
277
|
-
| `--tsconfig <path>` | auto-detected | Path to `tsconfig.json`
|
|
278
|
-
| `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers
|
|
279
|
-
| `--format <format>` | `ts` | Docs file format to look for: `ts` or `js`
|
|
280
|
-
| `--
|
|
277
|
+
| Option | Default | Description |
|
|
278
|
+
| ------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------- |
|
|
279
|
+
| `--root <path>` | `.` | Project root directory |
|
|
280
|
+
| `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
|
|
281
|
+
| `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
|
|
282
|
+
| `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
|
|
283
|
+
| `--json` | `false` | Output a single machine-readable JSON object instead of formatted text: `{ controllersChecked, issues, passed }` |
|
|
284
|
+
| `--quiet` | `false` | Suppress all output except errors |
|
|
281
285
|
|
|
282
286
|
**What it checks:**
|
|
283
287
|
|
|
@@ -287,7 +291,7 @@ npx nestjs-docfy check [options]
|
|
|
287
291
|
**Example output:**
|
|
288
292
|
|
|
289
293
|
```text
|
|
290
|
-
✖ UsersController
|
|
294
|
+
✖ UsersController: undocumented methods: updateProfile, deleteAccount
|
|
291
295
|
→ run nestjs-docfy generate --force to merge new methods
|
|
292
296
|
|
|
293
297
|
✖ 2 controller(s) out of sync.
|
|
@@ -311,7 +315,7 @@ Or as an npm script:
|
|
|
311
315
|
}
|
|
312
316
|
```
|
|
313
317
|
|
|
314
|
-
## CLI
|
|
318
|
+
## CLI: coverage
|
|
315
319
|
|
|
316
320
|
Measure what percentage of your endpoints are documented. Useful as an objective quality metric and as a CI gate.
|
|
317
321
|
|
|
@@ -319,14 +323,15 @@ Measure what percentage of your endpoints are documented. Useful as an objective
|
|
|
319
323
|
npx nestjs-docfy coverage [options]
|
|
320
324
|
```
|
|
321
325
|
|
|
322
|
-
| Option | Default | Description
|
|
323
|
-
| ------------------- | -------------------- |
|
|
324
|
-
| `--root <path>` | `.` | Project root directory
|
|
325
|
-
| `--tsconfig <path>` | auto-detected | Path to `tsconfig.json`
|
|
326
|
-
| `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers
|
|
327
|
-
| `--format <format>` | `ts` | Docs file format to look for: `ts` or `js`
|
|
328
|
-
| `--min <percent>` | none | Minimum coverage required (0-100)
|
|
329
|
-
| `--
|
|
326
|
+
| Option | Default | Description |
|
|
327
|
+
| ------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
|
328
|
+
| `--root <path>` | `.` | Project root directory |
|
|
329
|
+
| `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
|
|
330
|
+
| `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
|
|
331
|
+
| `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
|
|
332
|
+
| `--min <percent>` | none | Minimum coverage required (0-100), exits `1` if below |
|
|
333
|
+
| `--json` | `false` | Output a single machine-readable JSON object instead of formatted text: the `CoverageReport` fields plus `min` and `passed` |
|
|
334
|
+
| `--quiet` | `false` | Suppress all output except errors |
|
|
330
335
|
|
|
331
336
|
**Example output:**
|
|
332
337
|
|
|
@@ -364,9 +369,11 @@ Or as an npm script:
|
|
|
364
369
|
}
|
|
365
370
|
```
|
|
366
371
|
|
|
367
|
-
|
|
372
|
+
**PR bot**: this repo's own [`.github/workflows/pr-check.yml`](.github/workflows/pr-check.yml) is a real example of a GitHub Actions job that runs `check --json` and `coverage --json --min` against a project and posts (and updates, never spams) a single PR comment summarizing the result. See [`.github/scripts/pr-comment.mjs`](.github/scripts/pr-comment.mjs) for the comment logic, built entirely on `--json` output and native `fetch`, no extra dependencies.
|
|
373
|
+
|
|
374
|
+
## CLI: lint
|
|
368
375
|
|
|
369
|
-
Checks documentation **quality**, not just presence
|
|
376
|
+
Checks documentation **quality**, not just presence. Catches incomplete `ApiOperation`, `ApiResponse`, and `ApiBody` decorators that `check` and `coverage` wouldn't flag (the method is documented, just incompletely).
|
|
370
377
|
|
|
371
378
|
```bash
|
|
372
379
|
npx nestjs-docfy lint [options]
|
|
@@ -386,7 +393,7 @@ npx nestjs-docfy lint [options]
|
|
|
386
393
|
- Endpoints with a `@Body()` parameter missing a `400` `ApiResponse`
|
|
387
394
|
- Endpoints with a `@Body()` parameter missing an `ApiBody` `description`
|
|
388
395
|
|
|
389
|
-
Controllers without a companion docs file, or methods not yet documented at all, are left to `check
|
|
396
|
+
Controllers without a companion docs file, or methods not yet documented at all, are left to `check`. `lint` only judges the quality of what's already there.
|
|
390
397
|
|
|
391
398
|
**Example output:**
|
|
392
399
|
|
|
@@ -403,7 +410,7 @@ Controllers without a companion docs file, or methods not yet documented at all,
|
|
|
403
410
|
✖ 3 issue(s) found.
|
|
404
411
|
```
|
|
405
412
|
|
|
406
|
-
Exits with code `1` if any issue is found
|
|
413
|
+
Exits with code `1` if any issue is found, designed for CI pipelines, same as `check`.
|
|
407
414
|
|
|
408
415
|
```yaml
|
|
409
416
|
# GitHub Actions example
|
|
@@ -421,9 +428,9 @@ Or as an npm script:
|
|
|
421
428
|
}
|
|
422
429
|
```
|
|
423
430
|
|
|
424
|
-
## CLI
|
|
431
|
+
## CLI: patch-spec
|
|
425
432
|
|
|
426
|
-
Patches an **already-built** OpenAPI document with every controller's companion docs file, entirely via static analysis (`ts-morph`)
|
|
433
|
+
Patches an **already-built** OpenAPI document with every controller's companion docs file, entirely via static analysis (`ts-morph`). No `require()` of any docs file, no decorators applied to any class, no dependency on a live class reference matching the one the running app actually uses.
|
|
427
434
|
|
|
428
435
|
This is a manual, CI-driven way to work around the one thing `DocfyModule`'s runtime pipeline structurally cannot do: work under NestJS CLI's `webpack: true` build mode (see [`webpack: true` build mode](#webpack-true-build-mode) for why, and for the **CLI plugin**, which does the same analysis automatically on every build instead of a separate step). `patch-spec` sidesteps the webpack wall by matching on **path + HTTP method**, computed the same way `check`/`coverage`/`lint` already do, instead of needing the live controller class.
|
|
429
436
|
|
|
@@ -453,14 +460,47 @@ npx nestjs-docfy patch-spec --spec dist/openapi.json --out dist/openapi.json
|
|
|
453
460
|
|
|
454
461
|
- `ApiTags` → unioned into `tags` (never drops tags the base document already had)
|
|
455
462
|
- `ApiOperation({ summary, description, deprecated })` → overwrites those fields
|
|
456
|
-
- `ApiResponse({ status, description, schema, example, examples })` → merged per status code (other status codes untouched); when no `schema`/`type` is given, falls back to the method's own resolved return type
|
|
457
|
-
- `ApiBody({ schema, examples })` → sets `requestBody`, with the same return-type-style fallback to the `@Body()` parameter's resolved type, including the same union → `oneOf` handling (`example` is intentionally not read here
|
|
463
|
+
- `ApiResponse({ status, description, schema, example, examples })` → merged per status code (other status codes untouched); when no `schema`/`type` is given, falls back to the method's own resolved return type, the same DTO/class-validator/interface inference `generate` already does, including a `oneOf` of `$ref`s when the return type is a union of ≥2 named DTOs/entities (e.g. `Promise<UserDto | AdminDto>`)
|
|
464
|
+
- `ApiBody({ schema, examples })` → sets `requestBody`, with the same return-type-style fallback to the `@Body()` parameter's resolved type, including the same union → `oneOf` handling (`example` is intentionally not read here, since `@nestjs/swagger`'s real `ApiBodyOptions` type only has `examples`, unlike `ApiResponse`, which supports both)
|
|
458
465
|
- `ApiBearerAuth()` → appended to `security`
|
|
459
|
-
- `ApiParam` / `ApiQuery` / `ApiHeader` → merged into `parameters` by name + location: a genuinely new parameter is appended, but one that already exists (e.g. `@nestjs/swagger` auto-generates a bare `required: true` entry from reflection alone for any `@Query()`/`@Param()`-decorated argument, with zero `@Api*` decorators needed) gets its fields overlaid, not discarded
|
|
466
|
+
- `ApiParam` / `ApiQuery` / `ApiHeader` → merged into `parameters` by name + location: a genuinely new parameter is appended, but one that already exists (e.g. `@nestjs/swagger` auto-generates a bare `required: true` entry from reflection alone for any `@Query()`/`@Param()`-decorated argument, with zero `@Api*` decorators needed) gets its fields overlaid, not discarded. An `ApiQuery({ enum, required: false })` in a docs file for a parameter Nest already knew about actually takes effect. `enum` is read from an array literal (`enum: ['a', 'b']`) or a reference to a TS `enum`, including one imported from another file (`enum: Role`), and the schema's `type` is inferred as `number` when every resolved value is numeric, `string` otherwise
|
|
467
|
+
|
|
468
|
+
`example`/`examples` (and `schema`) are only applied when every value inside them is a literal. If even one nested value is a variable, function call, or other non-literal expression, the whole field is left out rather than risk leaking an internal "unresolved" marker into the document as if it were real data.
|
|
469
|
+
|
|
470
|
+
**What this does _not_ do** (yet, since this command is intentionally scoped, not a full reimplementation of `@nestjs/swagger`'s decorator semantics): `anyOf` (no TS construct maps onto "any of" the way a union type naturally maps onto `oneOf`), `links`/`callbacks` (`@nestjs/swagger` itself has no decorator option for either, so there's nothing in a `.docs.ts` file to read), and any decorator argument that isn't a literal (a variable, a function call, a spread) are left alone rather than guessed at. It's better to leave a field as the base document already had it than patch in something wrong. A union return type or `@Body()` payload only becomes a `oneOf` when _every_ branch resolves to a named DTO/entity. A partial guess is avoided by leaving the field alone entirely (falling back to no schema, same as an unresolvable type) if even one branch doesn't resolve. Routes a docs file documents that don't exist in `--spec` are reported as warnings, not silently dropped or errored on.
|
|
471
|
+
|
|
472
|
+
## CLI: generate-client
|
|
473
|
+
|
|
474
|
+
Generates a typed TypeScript client from an OpenAPI document, a thin wrapper over [`openapi-typescript`](https://openapi-ts.dev) (types) and [`openapi-fetch`](https://openapi-ts.dev/openapi-fetch) (the runtime client), not a from-scratch code generator.
|
|
475
|
+
|
|
476
|
+
```bash
|
|
477
|
+
npx nestjs-docfy generate-client --spec <path-or-url> [options]
|
|
478
|
+
```
|
|
460
479
|
|
|
461
|
-
|
|
480
|
+
| Option | Default | Description |
|
|
481
|
+
| -------------------- | -------------------- | ------------------------------------------------------------------- |
|
|
482
|
+
| `--spec <path\|url>` | _(required)_ | A local `openapi.json`, or a URL (e.g. a running app's `/api-json`) |
|
|
483
|
+
| `--out <path>` | `./generated-client` | Output directory for `schema.d.ts` and `client.ts` |
|
|
484
|
+
| `--root <path>` | `.` | Project root directory |
|
|
485
|
+
| `--quiet` | `false` | Suppress all output except errors |
|
|
486
|
+
|
|
487
|
+
```bash
|
|
488
|
+
npx nestjs-docfy generate-client --spec http://localhost:3000/api-json --out src/api-client
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
Writes two files:
|
|
492
|
+
|
|
493
|
+
- **`schema.d.ts`**: the generated types (`paths`, `components`, `operations`), via `openapi-typescript`.
|
|
494
|
+
- **`client.ts`**: a small wrapper exporting `createApiClient(baseUrl)`, typed against `schema.d.ts`.
|
|
495
|
+
|
|
496
|
+
```ts
|
|
497
|
+
import { createApiClient } from './api-client/client';
|
|
498
|
+
|
|
499
|
+
const api = createApiClient('https://api.example.com');
|
|
500
|
+
const { data, error } = await api.GET('/users/{id}', { params: { path: { id: '123' } } });
|
|
501
|
+
```
|
|
462
502
|
|
|
463
|
-
|
|
503
|
+
`openapi-fetch` is **not** a dependency of `nestjs-docfy` itself, since only the generated `client.ts` imports it, so install it in your own project: `npm install openapi-fetch`.
|
|
464
504
|
|
|
465
505
|
## API reference
|
|
466
506
|
|
|
@@ -492,7 +532,7 @@ Reflect.getMetadata(DOCFY_MARKER, ProductsController); // true
|
|
|
492
532
|
|
|
493
533
|
### `docs(controllerClass, config)`
|
|
494
534
|
|
|
495
|
-
Applies Swagger decorators to a controller class from outside its file. Call at the top level of a `*.controller.docs.ts` file
|
|
535
|
+
Applies Swagger decorators to a controller class from outside its file. Call at the top level of a `*.controller.docs.ts` file; runs as a side effect on import.
|
|
496
536
|
|
|
497
537
|
Fully type-safe: `config.methods` only accepts keys that exist on the controller class. Typos are caught at compile time.
|
|
498
538
|
|
|
@@ -506,15 +546,15 @@ docs(UsersController, {
|
|
|
506
546
|
});
|
|
507
547
|
```
|
|
508
548
|
|
|
509
|
-
**`config.classDecorators`**
|
|
549
|
+
**`config.classDecorators`** (`ClassDecorator[]`): applied to the class constructor (e.g. `ApiTags`, `ApiBearerAuth`).
|
|
510
550
|
|
|
511
|
-
**`config.methods`**
|
|
551
|
+
**`config.methods`** (`Partial<Record<keyof T, MethodDecorator[]>>`): decorator arrays per method name, applied in order.
|
|
512
552
|
|
|
513
|
-
**`config.group`**
|
|
553
|
+
**`config.group`** (`string`): logical group name for ReDoc's `x-tagGroups` extension. See [Tag groups](#tag-groups-x-taggroups).
|
|
514
554
|
|
|
515
|
-
**`config.tags`**
|
|
555
|
+
**`config.tags`** (`string[]`): tag names associated with `group`. Should match what you pass to `ApiTags()`.
|
|
516
556
|
|
|
517
|
-
If a method key does not exist on the controller at runtime, a warning is logged and that entry is skipped
|
|
557
|
+
If a method key does not exist on the controller at runtime, a warning is logged and that entry is skipped. The rest of the docs file still applies.
|
|
518
558
|
|
|
519
559
|
### `attachTagGroups(document)`
|
|
520
560
|
|
|
@@ -536,11 +576,11 @@ SwaggerModule.setup('api', app, applyDocfyMetadata(document));
|
|
|
536
576
|
| `metadataPath` | `string` | `docfy-metadata.json` next to the running entry file | Where to read the plugin-generated metadata from. |
|
|
537
577
|
| `strict` | `boolean` | `false` | Throw instead of warning when the metadata file is missing or invalid. |
|
|
538
578
|
|
|
539
|
-
If the metadata file isn't found (e.g. the plugin isn't registered in `nest-cli.json`), it warns and returns the document unchanged
|
|
579
|
+
If the metadata file isn't found (e.g. the plugin isn't registered in `nest-cli.json`), it warns and returns the document unchanged, the same fail-open default as `DocfyModule.forRoot()`.
|
|
540
580
|
|
|
541
581
|
### `DocfyUiModule.setup(mountPath, app, options?)`
|
|
542
582
|
|
|
543
|
-
Serves [`docfy-ui`](https://www.npmjs.com/package/docfy-ui)
|
|
583
|
+
Serves [`docfy-ui`](https://www.npmjs.com/package/docfy-ui) (the AI-first documentation UI companion to this package) at `mountPath`, the same role `SwaggerModule.setup()` + `swagger-ui-express` play for raw Swagger UI. Works on both Express (`@nestjs/platform-express`) and Fastify (`@nestjs/platform-fastify`) apps. On Fastify, static asset serving needs the optional peer dependency [`@fastify/static`](https://www.npmjs.com/package/@fastify/static) (`npm install @fastify/static`), the same package `@nestjs/swagger` itself relies on for Fastify Swagger UI support.
|
|
544
584
|
|
|
545
585
|
```ts
|
|
546
586
|
import { NestFactory } from '@nestjs/core';
|
|
@@ -549,7 +589,7 @@ import { DocfyUiModule } from 'nestjs-docfy';
|
|
|
549
589
|
|
|
550
590
|
const app = await NestFactory.create(AppModule);
|
|
551
591
|
|
|
552
|
-
DocfyUiModule.setup('/docs', app); // before SwaggerModule.setup
|
|
592
|
+
DocfyUiModule.setup('/docs', app); // before SwaggerModule.setup, see staticSpecPath below
|
|
553
593
|
|
|
554
594
|
const document = SwaggerModule.createDocument(app, new DocumentBuilder().build());
|
|
555
595
|
SwaggerModule.setup('api', app, document); // exposes /api-json, which docfy-ui fetches by default
|
|
@@ -557,19 +597,19 @@ SwaggerModule.setup('api', app, document); // exposes /api-json, which docfy-ui
|
|
|
557
597
|
await app.listen(3000);
|
|
558
598
|
```
|
|
559
599
|
|
|
560
|
-
Visit `/docs
|
|
600
|
+
Visit `/docs`: no further configuration needed, since `docfy-ui` fetches `/api-json` same-origin by default.
|
|
561
601
|
|
|
562
602
|
| Option | Type | Default | Description |
|
|
563
603
|
| ---------------- | -------- | ------- | --------------------------------------------------------------------------------------------- |
|
|
564
604
|
| `staticSpecPath` | `string` | — | Path to a pre-built OpenAPI JSON file, served at `/api-json` _instead of_ the app's live one. |
|
|
565
605
|
|
|
566
|
-
**`staticSpecPath
|
|
606
|
+
**`staticSpecPath`: needed if your app builds with `"webpack": true`, and you're not using the [CLI plugin](#webpack-true-build-mode).** `DocfyModule`'s runtime metadata pipeline cannot apply docs files there, so the live `/api-json` will be missing everything docs files would otherwise add. Generate a patched document ahead of time:
|
|
567
607
|
|
|
568
608
|
```bash
|
|
569
609
|
npx nestjs-docfy patch-spec --spec http://localhost:3000/api-json --out openapi.patched.json
|
|
570
610
|
```
|
|
571
611
|
|
|
572
|
-
|
|
612
|
+
Then serve that instead:
|
|
573
613
|
|
|
574
614
|
```ts
|
|
575
615
|
DocfyUiModule.setup('/docs', app, { staticSpecPath: './openapi.patched.json' });
|
|
@@ -577,16 +617,16 @@ DocfyUiModule.setup('/docs', app, { staticSpecPath: './openapi.patched.json' });
|
|
|
577
617
|
|
|
578
618
|
Call this **before** `SwaggerModule.setup()`: Express resolves routes in registration order, so the static, patched document takes precedence over the live one for any request to `/api-json`.
|
|
579
619
|
|
|
580
|
-
> **Fastify caveat**: `SwaggerModule.setup()` also registers its own `/api-json` route by default. On Express, whichever route is registered first silently wins. On Fastify, registering the same exact route twice throws `FST_ERR_DUPLICATED_ROUTE` at startup instead
|
|
620
|
+
> **Fastify caveat**: `SwaggerModule.setup()` also registers its own `/api-json` route by default. On Express, whichever route is registered first silently wins. On Fastify, registering the same exact route twice throws `FST_ERR_DUPLICATED_ROUTE` at startup instead. Registration order does not save you. When using `staticSpecPath` together with Fastify, point `SwaggerModule.setup()` at a different `jsonDocumentUrl`, or pass `{ raw: false }`, so it doesn't also claim `/api-json`.
|
|
581
621
|
>
|
|
582
622
|
> `docfy-ui` reads the mount prefix `DocfyUiModule.setup()` injects (`window.__DOCFY_BASE_PATH__`) and passes it as `BrowserRouter`'s `basename`, so deep client-side routes (e.g. reloading an endpoint's detail page directly) resolve correctly at any `mountPath`, not just `/`.
|
|
583
623
|
|
|
584
624
|
## Interface-typed DTOs
|
|
585
625
|
|
|
586
|
-
When a response or body type is a TypeScript `interface` (not a class), Swagger cannot use it as a `type:` value because interfaces are erased at runtime. `nestjs-docfy` detects this automatically and generates an inline `schema:` object instead
|
|
626
|
+
When a response or body type is a TypeScript `interface` (not a class), Swagger cannot use it as a `type:` value because interfaces are erased at runtime. `nestjs-docfy` detects this automatically and generates an inline `schema:` object instead. **No changes to your code required.**
|
|
587
627
|
|
|
588
628
|
```ts
|
|
589
|
-
// Your existing interface
|
|
629
|
+
// Your existing interface, no need to convert to a class
|
|
590
630
|
export interface RegisterResponseDto {
|
|
591
631
|
success: boolean;
|
|
592
632
|
message: string | null;
|
|
@@ -614,7 +654,7 @@ Supports: primitives, nullable unions (`T | null`), arrays, nested interfaces, a
|
|
|
614
654
|
|
|
615
655
|
## class-validator inference
|
|
616
656
|
|
|
617
|
-
When a DTO class uses `class-validator` decorators and does **not** already have `@ApiProperty` on its properties, `nestjs-docfy` infers a full JSON Schema from the validator decorators
|
|
657
|
+
When a DTO class uses `class-validator` decorators and does **not** already have `@ApiProperty` on its properties, `nestjs-docfy` infers a full JSON Schema from the validator decorators. No manual annotation required.
|
|
618
658
|
|
|
619
659
|
```ts
|
|
620
660
|
// create-user.dto.ts
|
|
@@ -652,7 +692,7 @@ ApiBody({
|
|
|
652
692
|
|
|
653
693
|
Supported decorators: `@IsString`, `@IsEmail`, `@IsUrl`, `@IsUUID`, `@IsDateString`, `@IsNumber`, `@IsInt`, `@IsBoolean`, `@IsArray`, `@Min`, `@Max`, `@MinLength`, `@MaxLength`, `@IsOptional`.
|
|
654
694
|
|
|
655
|
-
> If any property in the class already has `@ApiProperty`, inference is skipped and `type: ClassName` is used instead
|
|
695
|
+
> If any property in the class already has `@ApiProperty`, inference is skipped and `type: ClassName` is used instead. Your existing Swagger annotations are never overwritten.
|
|
656
696
|
|
|
657
697
|
## @HttpCode() support
|
|
658
698
|
|
|
@@ -678,7 +718,7 @@ Without `@HttpCode()`, the default codes apply: `201` for `@Post`, `200` for all
|
|
|
678
718
|
|
|
679
719
|
## Tag groups (x-tagGroups)
|
|
680
720
|
|
|
681
|
-
Pass `group` and `tags` to `docs()` to organize controllers under logical sections in tools that support the `x-tagGroups` OpenAPI extension
|
|
721
|
+
Pass `group` and `tags` to `docs()` to organize controllers under logical sections in tools that support the `x-tagGroups` OpenAPI extension, most notably [ReDoc](https://github.com/Redocly/redoc).
|
|
682
722
|
|
|
683
723
|
```ts
|
|
684
724
|
// users.controller.docs.ts
|
|
@@ -696,7 +736,7 @@ docs(RolesController, {
|
|
|
696
736
|
});
|
|
697
737
|
```
|
|
698
738
|
|
|
699
|
-
`tags` should match what you already pass to `ApiTags()
|
|
739
|
+
`tags` should match what you already pass to `ApiTags()`. `nestjs-docfy` does not call `ApiTags` for you, it only builds the `x-tagGroups` mapping from what you declare.
|
|
700
740
|
|
|
701
741
|
To actually attach the groups to the generated document, call `attachTagGroups()` after `SwaggerModule.createDocument()`:
|
|
702
742
|
|
|
@@ -721,11 +761,11 @@ x-tagGroups:
|
|
|
721
761
|
- roles
|
|
722
762
|
```
|
|
723
763
|
|
|
724
|
-
Multiple `docs()` calls can contribute to the same group
|
|
764
|
+
Multiple `docs()` calls can contribute to the same group; tags are merged and deduplicated. `attachTagGroups()` is a no-op (returns the document unchanged) when no controller declares a `group`.
|
|
725
765
|
|
|
726
766
|
## File naming convention
|
|
727
767
|
|
|
728
|
-
Discovery is automatic. `DocfyModule` locates each controller's source file via Node's module cache and resolves the companion path
|
|
768
|
+
Discovery is automatic. `DocfyModule` locates each controller's source file via Node's module cache and resolves the companion path. This works identically in `ts-node` (development) and compiled `dist/` (production).
|
|
729
769
|
|
|
730
770
|
| Controller file | Companion docs file |
|
|
731
771
|
| --------------------- | -------------------------- |
|
|
@@ -736,15 +776,15 @@ Discovery is automatic. `DocfyModule` locates each controller's source file via
|
|
|
736
776
|
|
|
737
777
|
### `webpack: true` build mode
|
|
738
778
|
|
|
739
|
-
If your `nest-cli.json` has `"webpack": true` under `compilerOptions`
|
|
779
|
+
If your `nest-cli.json` has `"webpack": true` under `compilerOptions` (the documented default for monorepos with multiple apps), `DocfyModule`'s **runtime** pipeline (the `@WithDocs()` + `require.cache` discovery described above) will not work, and there is no configuration that makes it work. This is architectural, not a bug to be patched around:
|
|
740
780
|
|
|
741
781
|
- Webpack inlines every module into one bundle file and never populates Node's `require.cache` with an entry per original source file, which is what the discovery mechanism above depends on. You'll see `Could not locate source file for X` for every `@WithDocs()` controller.
|
|
742
|
-
- Even if that lookup is worked around (e.g. by recovering the original path from the bundle's source map, sidestepping `require.cache` entirely), there's a second, unavoidable wall: a docs file required from outside the bundle creates a structurally different class object than the one the running app actually uses internally. Decorating that fresh copy has no effect on the document `SwaggerModule.createDocument()` actually serves
|
|
743
|
-
- The only way around this would be for the controller's own file to import its `.docs.ts` companion (forcing webpack to bundle them together)
|
|
782
|
+
- Even if that lookup is worked around (e.g. by recovering the original path from the bundle's source map, sidestepping `require.cache` entirely), there's a second, unavoidable wall: a docs file required from outside the bundle creates a structurally different class object than the one the running app actually uses internally. Decorating that fresh copy has no effect on the document `SwaggerModule.createDocument()` actually serves, silently, with no error. This path-recovery layer was built and tested before discovering this; it isn't shipped, because "looks like it loaded, does nothing" is worse than the current loud, accurate warning.
|
|
783
|
+
- The only way around this would be for the controller's own file to import its `.docs.ts` companion (forcing webpack to bundle them together), which defeats the entire point of the convention: zero coupling between a controller and its documentation.
|
|
744
784
|
|
|
745
785
|
There are two ways to get full docs under `webpack: true`, in order of preference:
|
|
746
786
|
|
|
747
|
-
#### 1. The CLI plugin (recommended)
|
|
787
|
+
#### 1. The CLI plugin (recommended): fixes it at the root, automatically, on every build
|
|
748
788
|
|
|
749
789
|
Register `nestjs-docfy` as a NestJS CLI compiler plugin in `nest-cli.json`:
|
|
750
790
|
|
|
@@ -757,7 +797,7 @@ Register `nestjs-docfy` as a NestJS CLI compiler plugin in `nest-cli.json`:
|
|
|
757
797
|
}
|
|
758
798
|
```
|
|
759
799
|
|
|
760
|
-
This is the same mechanism `@nestjs/swagger`'s own CLI plugin uses to work under `webpack: true
|
|
800
|
+
This is the same mechanism `@nestjs/swagger`'s own CLI plugin uses to work under `webpack: true`. That's why `@ApiProperty()` isn't required on every DTO property even in a webpack build. The Nest CLI feeds a TypeScript compiler-plugin hook (`compilerOptions.plugins`) into both the `tsc` and the `webpack` (`ts-loader`) builder identically. `nestjs-docfy`'s plugin doesn't rewrite any decorator syntax or touch the AST at all. On every compilation it re-runs the exact same static analysis `generate`/`check`/`patch-spec` already do (via `ts-morph`, against the source tree, not the bundle) and writes the resulting patch to `docfy-metadata.json` next to your build output. There's no `require.cache` involved and no bundled-class-identity problem, because it never needs the running app to compute anything.
|
|
761
801
|
|
|
762
802
|
Then, right after `SwaggerModule.createDocument()`, merge that file into the document:
|
|
763
803
|
|
|
@@ -768,13 +808,13 @@ const document = SwaggerModule.createDocument(app, config);
|
|
|
768
808
|
SwaggerModule.setup('api', app, applyDocfyMetadata(document));
|
|
769
809
|
```
|
|
770
810
|
|
|
771
|
-
`applyDocfyMetadata()` reads `docfy-metadata.json` from next to your compiled entry file by default
|
|
811
|
+
`applyDocfyMetadata()` reads `docfy-metadata.json` from next to your compiled entry file by default. Pass `{ metadataPath }` to point somewhere else. If the file is missing (e.g. the plugin isn't registered), it warns and returns the document unchanged; pass `{ strict: true }` to throw instead, the same `strict` convention `DocfyModule.forRoot()` already uses.
|
|
772
812
|
|
|
773
|
-
#### 2. `patch-spec` (manual, CI-driven)
|
|
813
|
+
#### 2. `patch-spec` (manual, CI-driven): the same analysis, run as a separate step
|
|
774
814
|
|
|
775
|
-
If you'd rather not add a compiler plugin (e.g. a build pipeline that isn't the Nest CLI, or a stricter policy about what runs during compilation), [`patch-spec`](#cli
|
|
815
|
+
If you'd rather not add a compiler plugin (e.g. a build pipeline that isn't the Nest CLI, or a stricter policy about what runs during compilation), [`patch-spec`](#cli-patch-spec) computes the identical patch by hand against an already-built document. See that section for usage. This was the only option before the CLI plugin existed, and remains useful for one-off patching (e.g. patching a document fetched from a _different_ running instance than the one being built).
|
|
776
816
|
|
|
777
|
-
Disabling webpack entirely (`"webpack": false` or removing the key) also works, if you don't need it for another reason: under `nest build`'s default `tsc`-based compilation, every source file
|
|
817
|
+
Disabling webpack entirely (`"webpack": false` or removing the key) also works, if you don't need it for another reason: under `nest build`'s default `tsc`-based compilation, every source file, including each `*.controller.docs.ts`, gets compiled to its own `.js` file in `dist/`, so `require.cache` naturally has one entry per file and `DocfyModule`'s runtime discovery works exactly as documented above, no special configuration needed.
|
|
778
818
|
|
|
779
819
|
## Testing
|
|
780
820
|
|
|
@@ -788,11 +828,11 @@ beforeEach(() => resetDocfyRegistry());
|
|
|
788
828
|
|
|
789
829
|
## How it works
|
|
790
830
|
|
|
791
|
-
`DocfyModule.forRoot()` runs synchronously during the `NestFactory.create()` phase
|
|
831
|
+
`DocfyModule.forRoot()` runs synchronously during the `NestFactory.create()` phase, before `SwaggerModule.createDocument()` is called. It uses `require()` to load each companion docs file, which executes `docs()` and writes `Reflect` metadata directly onto the controller methods, exactly as TypeScript decorator syntax would at class-definition time.
|
|
792
832
|
|
|
793
833
|
By the time `SwaggerModule.createDocument()` scans for metadata, all of it is already in place. No monkey-patching, no runtime proxies.
|
|
794
834
|
|
|
795
|
-
The `generate` CLI uses `ts-morph` for static analysis
|
|
835
|
+
The `generate` CLI uses `ts-morph` for static analysis. It reads the TypeScript AST without executing any project code. All user-supplied paths and glob patterns are validated and sanitised before use.
|
|
796
836
|
|
|
797
837
|
## License
|
|
798
838
|
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import type { ProjectContext } from './project-types';
|
|
2
|
+
export declare function pluginListHasDocfy(plugins: unknown[]): boolean;
|
|
3
|
+
/**
|
|
4
|
+
* True when the target project's nest-cli.json has `webpack: true` but does
|
|
5
|
+
* not register `nestjs-docfy` under `compilerOptions.plugins` — the runtime
|
|
6
|
+
* discovery mechanism (`@WithDocs()` + `DocfyModule`) silently does not work
|
|
7
|
+
* in that build mode, and the CLI plugin is the sanctioned fix.
|
|
8
|
+
*/
|
|
9
|
+
export declare function hasWebpackWithoutPlugin(root: string): boolean;
|
|
2
10
|
/**
|
|
3
11
|
* Detects the project type and returns a ProjectContext with one entry per
|
|
4
12
|
* compilable unit. All paths in the result are absolute and validated to
|
|
@@ -3,6 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.pluginListHasDocfy = pluginListHasDocfy;
|
|
7
|
+
exports.hasWebpackWithoutPlugin = hasWebpackWithoutPlugin;
|
|
6
8
|
exports.detectProject = detectProject;
|
|
7
9
|
const fs_1 = __importDefault(require("fs"));
|
|
8
10
|
const path_1 = __importDefault(require("path"));
|
|
@@ -269,6 +271,31 @@ function detectGenericMonorepo(root, tsconfigOverride) {
|
|
|
269
271
|
return { kind: 'generic-monorepo', root, apps };
|
|
270
272
|
}
|
|
271
273
|
// ---------------------------------------------------------------------------
|
|
274
|
+
// webpack: true without the CLI plugin registered
|
|
275
|
+
// ---------------------------------------------------------------------------
|
|
276
|
+
function pluginListHasDocfy(plugins) {
|
|
277
|
+
return plugins.some((p) => {
|
|
278
|
+
if (typeof p === 'string')
|
|
279
|
+
return p === 'nestjs-docfy';
|
|
280
|
+
if (p && typeof p === 'object' && 'name' in p)
|
|
281
|
+
return p.name === 'nestjs-docfy';
|
|
282
|
+
return false;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* True when the target project's nest-cli.json has `webpack: true` but does
|
|
287
|
+
* not register `nestjs-docfy` under `compilerOptions.plugins` — the runtime
|
|
288
|
+
* discovery mechanism (`@WithDocs()` + `DocfyModule`) silently does not work
|
|
289
|
+
* in that build mode, and the CLI plugin is the sanctioned fix.
|
|
290
|
+
*/
|
|
291
|
+
function hasWebpackWithoutPlugin(root) {
|
|
292
|
+
const nestCli = safeReadJson(path_1.default.join(root, 'nest-cli.json'), root);
|
|
293
|
+
const compilerOptions = nestCli?.compilerOptions;
|
|
294
|
+
if (!compilerOptions?.webpack)
|
|
295
|
+
return false;
|
|
296
|
+
return !pluginListHasDocfy(compilerOptions.plugins ?? []);
|
|
297
|
+
}
|
|
298
|
+
// ---------------------------------------------------------------------------
|
|
272
299
|
// Public entry point
|
|
273
300
|
// ---------------------------------------------------------------------------
|
|
274
301
|
/**
|