nestjs-docfy 0.7.0 → 0.9.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 +39 -24
- package/dist/cli/index.js +0 -0
- package/dist/docfy-ui.module.d.ts +18 -0
- package/dist/docfy-ui.module.js +23 -2
- package/dist/docfy-ui.module.js.map +1 -1
- package/dist/proxy-handler.d.ts +40 -0
- package/dist/proxy-handler.js +213 -0
- package/dist/proxy-handler.js.map +1 -0
- package/dist/require-ts.d.ts +32 -0
- package/dist/require-ts.js +122 -0
- package/dist/require-ts.js.map +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -274,14 +274,14 @@ Verify that every controller is fully documented before merging. Exits with code
|
|
|
274
274
|
npx nestjs-docfy check [options]
|
|
275
275
|
```
|
|
276
276
|
|
|
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
|
|
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 |
|
|
285
285
|
|
|
286
286
|
**What it checks:**
|
|
287
287
|
|
|
@@ -323,15 +323,15 @@ Measure what percentage of your endpoints are documented. Useful as an objective
|
|
|
323
323
|
npx nestjs-docfy coverage [options]
|
|
324
324
|
```
|
|
325
325
|
|
|
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`
|
|
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
332
|
| `--min <percent>` | none | Minimum coverage required (0-100), exits `1` if below |
|
|
333
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
|
|
334
|
+
| `--quiet` | `false` | Suppress all output except errors |
|
|
335
335
|
|
|
336
336
|
**Example output:**
|
|
337
337
|
|
|
@@ -495,12 +495,12 @@ export default async function () {
|
|
|
495
495
|
npx nestjs-docfy export --entry docfy-export.ts --out openapi.json
|
|
496
496
|
```
|
|
497
497
|
|
|
498
|
-
| Option | Default | Description
|
|
499
|
-
| ---------------- | ------------ |
|
|
500
|
-
| `--entry <path>` | _(required)_ | `.ts`/`.js` file whose default export returns `{ app, document }`
|
|
501
|
-
| `--out <path>` | stdout | Where to write the document
|
|
502
|
-
| `--root <path>` | `.` | Project root — where `ts-node`/`tsconfig-paths` are resolved from
|
|
503
|
-
| `--quiet` | `false` | Suppress informational output (errors still go to stderr)
|
|
498
|
+
| Option | Default | Description |
|
|
499
|
+
| ---------------- | ------------ | ----------------------------------------------------------------- |
|
|
500
|
+
| `--entry <path>` | _(required)_ | `.ts`/`.js` file whose default export returns `{ app, document }` |
|
|
501
|
+
| `--out <path>` | stdout | Where to write the document |
|
|
502
|
+
| `--root <path>` | `.` | Project root — where `ts-node`/`tsconfig-paths` are resolved from |
|
|
503
|
+
| `--quiet` | `false` | Suppress informational output (errors still go to stderr) |
|
|
504
504
|
|
|
505
505
|
A `.ts` entry file needs `ts-node` as a devDependency of your project (for `tsconfig-paths` support too, if your project uses path aliases like `@app/common`). Informational output always goes to stderr, never stdout — safe to pipe: `npx nestjs-docfy export --entry docfy-export.ts > openapi.json`.
|
|
506
506
|
|
|
@@ -634,9 +634,12 @@ await app.listen(3000);
|
|
|
634
634
|
|
|
635
635
|
Visit `/docs`: no further configuration needed, since `docfy-ui` fetches `/api-json` same-origin by default.
|
|
636
636
|
|
|
637
|
-
| Option
|
|
638
|
-
|
|
|
639
|
-
| `staticSpecPath`
|
|
637
|
+
| Option | Type | Default | Description |
|
|
638
|
+
| ------------------------ | --------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
639
|
+
| `staticSpecPath` | `string` | — | Path to a pre-built OpenAPI JSON file, served at `/api-json` _instead of_ the app's live one. |
|
|
640
|
+
| `specs` | `{ name: string; url: string }[]` | — | Extra OpenAPI specs to offer in `docfy-ui`'s spec switcher, so one deployed instance can browse more than one service's documentation. |
|
|
641
|
+
| `openApiDocument` | `{ servers?: { url: string }[] }` | — | Enables the "Try it out" same-origin proxy — pass the same object you already have from `SwaggerModule.createDocument()`. See below. |
|
|
642
|
+
| `additionalProxyOrigins` | `string[]` | — | Extra origins the proxy is allowed to forward requests to, beyond what `openApiDocument.servers` declares. |
|
|
640
643
|
|
|
641
644
|
**`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:
|
|
642
645
|
|
|
@@ -656,6 +659,18 @@ Call this **before** `SwaggerModule.setup()`: Express resolves routes in registr
|
|
|
656
659
|
>
|
|
657
660
|
> `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 `/`.
|
|
658
661
|
|
|
662
|
+
**`openApiDocument` / `additionalProxyOrigins`: enables `docfy-ui`'s "Try it out" same-origin proxy.** Without it, "Try it out" does a direct `fetch()` from the browser to the target API, subject to that API's own CORS policy. With it, the browser instead calls a same-origin route this module registers (`POST {mountPath}/__docfy_proxy`), and the proxy makes the real request server-to-server — CORS never applies.
|
|
663
|
+
|
|
664
|
+
```ts
|
|
665
|
+
const document = SwaggerModule.createDocument(app, new DocumentBuilder().build());
|
|
666
|
+
SwaggerModule.setup('api', app, document);
|
|
667
|
+
DocfyUiModule.setup('/docs', app, { openApiDocument: document });
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
The proxy's allowlist is built **only** from absolute URLs in the OpenAPI document's `servers[]` array (plus anything in `additionalProxyOrigins`) — a request for any other origin gets rejected with `403` and an `X-Docfy-Proxy-Error: origin_not_allowed` response header. There is deliberately no implicit "same origin as this request" fallback: that would have to be derived from client-controlled request headers (`Host`), which is a classic SSRF vector — someone hitting the proxy endpoint directly (not through a browser, no CORS involved) could forge it to reach an internal-only origin. Declare `servers[]` in your `DocumentBuilder` config to opt an origin in; without any absolute `servers[]` entry, the route exists but always returns `403`.
|
|
671
|
+
|
|
672
|
+
Every other proxy failure (target unreachable, timeout) also sets `X-Docfy-Proxy-Error`, so `docfy-ui` can tell a proxy-level failure apart from a real `4xx`/`5xx` response coming from your API — those pass through untouched, with their real status/headers/body.
|
|
673
|
+
|
|
659
674
|
## Interface-typed DTOs
|
|
660
675
|
|
|
661
676
|
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.**
|
package/dist/cli/index.js
CHANGED
|
File without changes
|
|
@@ -8,6 +8,7 @@ export interface DocfyUiHttpAdapter {
|
|
|
8
8
|
getType(): string;
|
|
9
9
|
getInstance(): unknown;
|
|
10
10
|
get(path: string, handler: (req: unknown, res: unknown) => unknown): unknown;
|
|
11
|
+
post(path: string, handler: (req: unknown, res: unknown) => unknown): unknown;
|
|
11
12
|
}
|
|
12
13
|
/**
|
|
13
14
|
* Minimal structural shape of what `DocfyUiModule.setup()` needs from a
|
|
@@ -56,6 +57,23 @@ export interface DocfyUiSetupOptions {
|
|
|
56
57
|
name: string;
|
|
57
58
|
url: string;
|
|
58
59
|
}[];
|
|
60
|
+
/**
|
|
61
|
+
* Enables the "Try it out" server-side proxy: docfy-ui's browser calls a same-origin
|
|
62
|
+
* route on this app instead of the target API directly, sidestepping CORS entirely.
|
|
63
|
+
* Requires explicit opt-in — pass the same `OpenAPIObject` you already have from
|
|
64
|
+
* `SwaggerModule.createDocument()`. Its `servers[]` becomes the proxy's allowlist;
|
|
65
|
+
* there is deliberately no implicit "same origin as this request" fallback (that would
|
|
66
|
+
* be derived from client-controlled headers, an SSRF risk — see docfy-ui.module.ts).
|
|
67
|
+
* Only absolute server URLs count. Omit entirely to leave the proxy disabled (no new
|
|
68
|
+
* route registered at all).
|
|
69
|
+
*/
|
|
70
|
+
openApiDocument?: {
|
|
71
|
+
servers?: {
|
|
72
|
+
url: string;
|
|
73
|
+
}[];
|
|
74
|
+
};
|
|
75
|
+
/** Extra allowed origins for the proxy, beyond what `openApiDocument.servers` declares. */
|
|
76
|
+
additionalProxyOrigins?: string[];
|
|
59
77
|
}
|
|
60
78
|
/**
|
|
61
79
|
* Serves the published `docfy-ui` package's static build at `mountPath`,
|
package/dist/docfy-ui.module.js
CHANGED
|
@@ -37,6 +37,7 @@ exports.DocfyUiModule = void 0;
|
|
|
37
37
|
const fs = __importStar(require("fs"));
|
|
38
38
|
const path = __importStar(require("path"));
|
|
39
39
|
const express = __importStar(require("express"));
|
|
40
|
+
const proxy_handler_1 = require("./proxy-handler");
|
|
40
41
|
function loadFastifyStatic() {
|
|
41
42
|
try {
|
|
42
43
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
@@ -72,15 +73,35 @@ class DocfyUiModule {
|
|
|
72
73
|
res.send(specJson);
|
|
73
74
|
});
|
|
74
75
|
}
|
|
76
|
+
const basePath = mountPath === '/' ? '/' : `${mountPath.replace(/\/+$/, '')}/`;
|
|
77
|
+
let proxyPath;
|
|
78
|
+
if (options.openApiDocument || options.additionalProxyOrigins) {
|
|
79
|
+
const allowedOrigins = (0, proxy_handler_1.buildAllowedOrigins)(options.openApiDocument?.servers, options.additionalProxyOrigins);
|
|
80
|
+
if (allowedOrigins.size === 0) {
|
|
81
|
+
console.warn('DocfyUiModule.setup(): "Try it out" proxy enabled but no absolute server URLs were found — ' +
|
|
82
|
+
'every request will be rejected. Declare an absolute URL in your OpenAPI "servers" array ' +
|
|
83
|
+
'(or pass `additionalProxyOrigins`) to allow it.');
|
|
84
|
+
}
|
|
85
|
+
proxyPath = `${basePath}__docfy_proxy`.replace(/\/+/g, '/');
|
|
86
|
+
httpAdapter.post(proxyPath, (req, res) => {
|
|
87
|
+
(0, proxy_handler_1.readJsonBody)(req)
|
|
88
|
+
.then((body) => (0, proxy_handler_1.handleProxyRequest)(body, allowedOrigins, res))
|
|
89
|
+
.catch((err) => {
|
|
90
|
+
console.error('DocfyUiModule: "Try it out" proxy handler failed unexpectedly:', err);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
75
94
|
const indexHtmlPath = require.resolve('docfy-ui/dist/index.html');
|
|
76
95
|
const uiDir = path.dirname(indexHtmlPath);
|
|
77
|
-
const basePath = mountPath === '/' ? '/' : `${mountPath.replace(/\/+$/, '')}/`;
|
|
78
96
|
const specsScript = options.specs
|
|
79
97
|
? `\n <script>window.__DOCFY_SPECS__ = ${JSON.stringify(options.specs)};</script>`
|
|
80
98
|
: '';
|
|
99
|
+
const proxyScript = proxyPath
|
|
100
|
+
? `\n <script>window.__DOCFY_PROXY_PATH__ = ${JSON.stringify(proxyPath)};</script>`
|
|
101
|
+
: '';
|
|
81
102
|
const indexHtml = fs
|
|
82
103
|
.readFileSync(indexHtmlPath, 'utf8')
|
|
83
|
-
.replace('<head>', `<head>\n <base href="${basePath}" />\n <script>window.__DOCFY_BASE_PATH__ = ${JSON.stringify(basePath)};</script>${specsScript}`);
|
|
104
|
+
.replace('<head>', `<head>\n <base href="${basePath}" />\n <script>window.__DOCFY_BASE_PATH__ = ${JSON.stringify(basePath)};</script>${specsScript}${proxyScript}`);
|
|
84
105
|
if (isFastify) {
|
|
85
106
|
const fastifyStatic = loadFastifyStatic();
|
|
86
107
|
const instance = httpAdapter.getInstance();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docfy-ui.module.js","sourceRoot":"","sources":["../src/docfy-ui.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAC7B,iDAAmC;
|
|
1
|
+
{"version":3,"file":"docfy-ui.module.js","sourceRoot":"","sources":["../src/docfy-ui.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAC7B,iDAAmC;AACnC,mDAA4G;AAkF5G,SAAS,iBAAiB;IACxB,IAAI,CAAC;QACH,iEAAiE;QACjE,OAAO,OAAO,CAAC,iBAAiB,CAAC,CAAC;IACpC,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CACb,+EA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,EAAE;gBACtB,MAAM,CAAC,QAAQ,CAAC,aAAa,EAAE;oBAC7B,IAAI,EAAE,KAAK;oBACX,gEAAgE;oBAChE,+DAA+D;oBAC/D,QAAQ,EAAE,KAAK;oBACf,gEAAgE;oBAChE,oDAAoD;oBACpD,6DAA6D;oBAC7D,YAAY;oBACZ,KAAK,EAAE,KAAK;oBACZ,aAAa,EAAE,KAAK;iBACrB,CAAC,CAAC;gBACH,MAAM,CAAC,kBAAkB,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;oBACxC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBAC1C,CAAC,CAAC,CAAC;gBACH,IAAI,EAAE,CAAC;YACT,CAAC,EACD,EAAE,MAAM,EAAE,SAAS,EAAE,CACtB,CAAC;YACF,OAAO;QACT,CAAC;QAED,wEAAwE;QACxE,+DAA+D;QAC/D,2CAA2C;QAC3C,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QAC5D,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,IAAqB,EAAE,GAAqB,EAAE,EAAE;YAClE,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACtB,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAtFD,sCAsFC"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export declare const PROXY_ERROR_HEADER = "x-docfy-proxy-error";
|
|
2
|
+
interface RawRequestLike {
|
|
3
|
+
body?: unknown;
|
|
4
|
+
on(event: 'data' | 'end' | 'error', listener: (arg?: unknown) => void): unknown;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Reads the proxy envelope from the request. Prefers an already-parsed `req.body` (Fastify
|
|
8
|
+
* parses JSON bodies unconditionally as a core feature, so this is always populated there;
|
|
9
|
+
* Express only populates it if a JSON body-parser middleware happened to run *before* this
|
|
10
|
+
* route in the stack — not something `DocfyUiModule.setup()` can guarantee, since it's called
|
|
11
|
+
* directly against the app's HTTP adapter, outside Nest's own route pipeline). Falls back to
|
|
12
|
+
* reading and parsing the raw stream itself so Express works with no assumptions either way.
|
|
13
|
+
*/
|
|
14
|
+
export declare function readJsonBody(req: RawRequestLike): Promise<unknown>;
|
|
15
|
+
export interface ProxyRequestBody {
|
|
16
|
+
method?: string;
|
|
17
|
+
url?: string;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
body?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface ProxyResponderLike {
|
|
22
|
+
status(code: number): this;
|
|
23
|
+
header(name: string, value: string): this;
|
|
24
|
+
send(body: string): unknown;
|
|
25
|
+
}
|
|
26
|
+
/** Builds the allowlist of origins the proxy is permitted to forward requests to.
|
|
27
|
+
* Only absolute server URLs count — see docfy-ui.module.ts for why there's no
|
|
28
|
+
* implicit "same origin as this request" fallback. */
|
|
29
|
+
export declare function buildAllowedOrigins(servers: {
|
|
30
|
+
url: string;
|
|
31
|
+
}[] | undefined, additional: string[] | undefined): Set<string>;
|
|
32
|
+
/**
|
|
33
|
+
* Validates and forwards a "Try it out" request to its real target, server-to-server —
|
|
34
|
+
* the browser only ever talks to this same-origin endpoint, so CORS never applies.
|
|
35
|
+
* Success responses are passed through transparently (real status/headers/body from the
|
|
36
|
+
* target); only proxy-level failures set `X-Docfy-Proxy-Error` so the client can tell the
|
|
37
|
+
* two apart.
|
|
38
|
+
*/
|
|
39
|
+
export declare function handleProxyRequest(requestBody: unknown, allowedOrigins: Set<string>, res: ProxyResponderLike): Promise<void>;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,213 @@
|
|
|
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.PROXY_ERROR_HEADER = void 0;
|
|
37
|
+
exports.readJsonBody = readJsonBody;
|
|
38
|
+
exports.buildAllowedOrigins = buildAllowedOrigins;
|
|
39
|
+
exports.handleProxyRequest = handleProxyRequest;
|
|
40
|
+
const http = __importStar(require("http"));
|
|
41
|
+
const https = __importStar(require("https"));
|
|
42
|
+
const MAX_BODY_BYTES = 10 * 1024 * 1024; // 10MB
|
|
43
|
+
const TIMEOUT_MS = 20000;
|
|
44
|
+
const ALLOWED_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
45
|
+
// Stripped in both directions — connection-management headers make no sense relayed
|
|
46
|
+
// through a second hop, `transfer-encoding`/`content-length` would corrupt a buffered
|
|
47
|
+
// body relayed as a fresh single write, and `content-encoding` is dropped because the
|
|
48
|
+
// response is buffered/decoded as raw bytes here (no zlib re-encoding) — forwarding a
|
|
49
|
+
// compressed body labeled with its original encoding would make the browser fail to
|
|
50
|
+
// (or wrongly) decode it.
|
|
51
|
+
const HOP_BY_HOP_HEADERS = new Set([
|
|
52
|
+
'connection',
|
|
53
|
+
'keep-alive',
|
|
54
|
+
'transfer-encoding',
|
|
55
|
+
'content-length',
|
|
56
|
+
'content-encoding',
|
|
57
|
+
'upgrade',
|
|
58
|
+
'proxy-authorization',
|
|
59
|
+
'proxy-authenticate',
|
|
60
|
+
'te',
|
|
61
|
+
'trailer',
|
|
62
|
+
]);
|
|
63
|
+
exports.PROXY_ERROR_HEADER = 'x-docfy-proxy-error';
|
|
64
|
+
/**
|
|
65
|
+
* Reads the proxy envelope from the request. Prefers an already-parsed `req.body` (Fastify
|
|
66
|
+
* parses JSON bodies unconditionally as a core feature, so this is always populated there;
|
|
67
|
+
* Express only populates it if a JSON body-parser middleware happened to run *before* this
|
|
68
|
+
* route in the stack — not something `DocfyUiModule.setup()` can guarantee, since it's called
|
|
69
|
+
* directly against the app's HTTP adapter, outside Nest's own route pipeline). Falls back to
|
|
70
|
+
* reading and parsing the raw stream itself so Express works with no assumptions either way.
|
|
71
|
+
*/
|
|
72
|
+
function readJsonBody(req) {
|
|
73
|
+
if (req.body !== undefined)
|
|
74
|
+
return Promise.resolve(req.body);
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
let raw = '';
|
|
77
|
+
req.on('data', (chunk) => {
|
|
78
|
+
raw += chunk;
|
|
79
|
+
});
|
|
80
|
+
req.on('end', () => {
|
|
81
|
+
try {
|
|
82
|
+
resolve(raw ? JSON.parse(raw) : undefined);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
resolve(undefined);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
req.on('error', () => resolve(undefined));
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** Builds the allowlist of origins the proxy is permitted to forward requests to.
|
|
92
|
+
* Only absolute server URLs count — see docfy-ui.module.ts for why there's no
|
|
93
|
+
* implicit "same origin as this request" fallback. */
|
|
94
|
+
function buildAllowedOrigins(servers, additional) {
|
|
95
|
+
const origins = new Set();
|
|
96
|
+
for (const url of [...(servers ?? []).map((s) => s.url), ...(additional ?? [])]) {
|
|
97
|
+
try {
|
|
98
|
+
origins.add(new URL(url).origin);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// Relative or malformed server URL — no safe base to resolve it against, skip.
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return origins;
|
|
105
|
+
}
|
|
106
|
+
function sendProxyError(res, status, error, message) {
|
|
107
|
+
res
|
|
108
|
+
.status(status)
|
|
109
|
+
.header(exports.PROXY_ERROR_HEADER, error)
|
|
110
|
+
.header('Content-Type', 'application/json')
|
|
111
|
+
.send(JSON.stringify({ error, message }));
|
|
112
|
+
}
|
|
113
|
+
function filterHeaders(headers) {
|
|
114
|
+
const result = {};
|
|
115
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
116
|
+
if (value === undefined || HOP_BY_HOP_HEADERS.has(name.toLowerCase()))
|
|
117
|
+
continue;
|
|
118
|
+
result[name] = Array.isArray(value) ? value.join(', ') : value;
|
|
119
|
+
}
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
function forward(target, method, headers, body) {
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
const transport = target.protocol === 'https:' ? https : http;
|
|
125
|
+
// Force uncompressed responses — the body is buffered as raw bytes below with no
|
|
126
|
+
// zlib decoding, so a compressed response would otherwise come through corrupted.
|
|
127
|
+
const outgoingHeaders = { ...headers, 'accept-encoding': 'identity' };
|
|
128
|
+
const req = transport.request(target, { method, headers: outgoingHeaders, timeout: TIMEOUT_MS }, (res) => {
|
|
129
|
+
const chunks = [];
|
|
130
|
+
let receivedBytes = 0;
|
|
131
|
+
let truncated = false;
|
|
132
|
+
res.on('data', (chunk) => {
|
|
133
|
+
receivedBytes += chunk.length;
|
|
134
|
+
if (receivedBytes > MAX_BODY_BYTES) {
|
|
135
|
+
truncated = true;
|
|
136
|
+
res.destroy();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
chunks.push(chunk);
|
|
140
|
+
});
|
|
141
|
+
res.on('end', () => {
|
|
142
|
+
if (truncated) {
|
|
143
|
+
reject(new Error('Response body exceeded the proxy size limit.'));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
resolve({
|
|
147
|
+
status: res.statusCode ?? 502,
|
|
148
|
+
headers: res.headers,
|
|
149
|
+
bodyText: Buffer.concat(chunks).toString('utf8'),
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
res.on('error', reject);
|
|
153
|
+
});
|
|
154
|
+
req.on('timeout', () => req.destroy(new Error('Request to the target API timed out.')));
|
|
155
|
+
req.on('error', reject);
|
|
156
|
+
if (body)
|
|
157
|
+
req.write(body);
|
|
158
|
+
req.end();
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Validates and forwards a "Try it out" request to its real target, server-to-server —
|
|
163
|
+
* the browser only ever talks to this same-origin endpoint, so CORS never applies.
|
|
164
|
+
* Success responses are passed through transparently (real status/headers/body from the
|
|
165
|
+
* target); only proxy-level failures set `X-Docfy-Proxy-Error` so the client can tell the
|
|
166
|
+
* two apart.
|
|
167
|
+
*/
|
|
168
|
+
async function handleProxyRequest(requestBody, allowedOrigins, res) {
|
|
169
|
+
if (!requestBody || typeof requestBody !== 'object') {
|
|
170
|
+
sendProxyError(res, 400, 'bad_request', 'Missing or malformed JSON body.');
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const { method, url, headers, body } = requestBody;
|
|
174
|
+
if (!method || !url) {
|
|
175
|
+
sendProxyError(res, 400, 'bad_request', 'Both "method" and "url" are required.');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const upperMethod = method.toUpperCase();
|
|
179
|
+
if (!ALLOWED_METHODS.has(upperMethod)) {
|
|
180
|
+
sendProxyError(res, 400, 'bad_request', `Unsupported method "${method}".`);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
let target;
|
|
184
|
+
try {
|
|
185
|
+
target = new URL(url);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
sendProxyError(res, 400, 'invalid_url', `"${url}" is not a valid URL.`);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (target.protocol !== 'http:' && target.protocol !== 'https:') {
|
|
192
|
+
sendProxyError(res, 400, 'invalid_url', `Unsupported protocol "${target.protocol}".`);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (!allowedOrigins.has(target.origin)) {
|
|
196
|
+
sendProxyError(res, 403, 'origin_not_allowed', `"${target.origin}" is not in the allowed server list for this API. Declare it in your OpenAPI "servers" array to allow it.`);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
const result = await forward(target, upperMethod, filterHeaders(headers ?? {}), body);
|
|
201
|
+
res.status(result.status);
|
|
202
|
+
for (const [name, value] of Object.entries(filterHeaders(result.headers))) {
|
|
203
|
+
res.header(name, value);
|
|
204
|
+
}
|
|
205
|
+
res.send(result.bodyText);
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
const message = err instanceof Error ? err.message : 'Unknown error reaching the target API.';
|
|
209
|
+
const isTimeout = message.includes('timed out');
|
|
210
|
+
sendProxyError(res, isTimeout ? 504 : 502, isTimeout ? 'timeout' : 'network_error', message);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
//# sourceMappingURL=proxy-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy-handler.js","sourceRoot":"","sources":["../src/proxy-handler.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,oCAiBC;AAkBD,kDAaC;AA+ED,gDAwDC;AAhOD,2CAA6B;AAC7B,6CAA+B;AAE/B,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC,OAAO;AAChD,MAAM,UAAU,GAAG,KAAM,CAAC;AAC1B,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAE9F,oFAAoF;AACpF,sFAAsF;AACtF,sFAAsF;AACtF,sFAAsF;AACtF,oFAAoF;AACpF,0BAA0B;AAC1B,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACjC,YAAY;IACZ,YAAY;IACZ,mBAAmB;IACnB,gBAAgB;IAChB,kBAAkB;IAClB,SAAS;IACT,qBAAqB;IACrB,oBAAoB;IACpB,IAAI;IACJ,SAAS;CACV,CAAC,CAAC;AAEU,QAAA,kBAAkB,GAAG,qBAAqB,CAAC;AAOxD;;;;;;;GAOG;AACH,SAAgB,YAAY,CAAC,GAAmB;IAC9C,IAAI,GAAG,CAAC,IAAI,KAAK,SAAS;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAE7D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,IAAI,GAAG,GAAG,EAAE,CAAC;QACb,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,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CAAC;QACH,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,aAAa,CAAC,OAAO,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;QACtF,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC1B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;YAC1E,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC1B,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC5B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,wCAAwC,CAAC;QAC9F,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;QAChD,cAAc,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;IAC/F,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads a .ts companion docs file at runtime without relying on a
|
|
3
|
+
* pre-registered TypeScript loader (ts-node, tsx, etc.).
|
|
4
|
+
*
|
|
5
|
+
* Why this is needed: docs files are intentionally never imported by
|
|
6
|
+
* application code (that's the whole point of the *.controller.docs.ts
|
|
7
|
+
* convention — they attach metadata from outside the controller). Under
|
|
8
|
+
* NestJS CLI's `webpack: true` build mode, that means they're never part
|
|
9
|
+
* of the bundle's reachable module graph, so they never get compiled to
|
|
10
|
+
* .js even when the rest of the app is — there's nothing for a plain
|
|
11
|
+
* `require()` to load. resolveDocsPath can correctly locate the original
|
|
12
|
+
* .ts file (see resolve-source-from-stack.ts), but loading it still needs
|
|
13
|
+
* this.
|
|
14
|
+
*
|
|
15
|
+
* Registers `require.extensions['.ts']` — exactly the mechanism ts-node's
|
|
16
|
+
* own `register()` uses — rather than manually constructing a `Module`
|
|
17
|
+
* instance and calling `_compile()` directly. That distinction matters for
|
|
18
|
+
* correctness, not just style: Node's module *resolution* (not just
|
|
19
|
+
* compilation) only tries an extension if it's a registered key of
|
|
20
|
+
* `require.extensions`. A docs file importing a sibling relative path
|
|
21
|
+
* (`import { UsersController } from './users.controller'`) needs Node to
|
|
22
|
+
* try `./users.controller.ts` while resolving — manually compiling just
|
|
23
|
+
* the entry file doesn't make Node try `.ts` for anything *it* requires
|
|
24
|
+
* in turn, so any relative import inside the docs file would still throw
|
|
25
|
+
* "Cannot find module" one level down.
|
|
26
|
+
*
|
|
27
|
+
* Transpiles with esbuild — type-stripping only, since docs files call
|
|
28
|
+
* decorator factories as plain functions (`docs(Controller, { classDecorators:
|
|
29
|
+
* [ApiTags('x')] })`) rather than using TypeScript decorator syntax
|
|
30
|
+
* themselves, so no decorator-metadata emulation is needed.
|
|
31
|
+
*/
|
|
32
|
+
export declare function requireTypeScriptFile(absPath: string): unknown;
|
|
@@ -0,0 +1,122 @@
|
|
|
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.requireTypeScriptFile = requireTypeScriptFile;
|
|
37
|
+
const fs = __importStar(require("fs"));
|
|
38
|
+
/**
|
|
39
|
+
* Loads a .ts companion docs file at runtime without relying on a
|
|
40
|
+
* pre-registered TypeScript loader (ts-node, tsx, etc.).
|
|
41
|
+
*
|
|
42
|
+
* Why this is needed: docs files are intentionally never imported by
|
|
43
|
+
* application code (that's the whole point of the *.controller.docs.ts
|
|
44
|
+
* convention — they attach metadata from outside the controller). Under
|
|
45
|
+
* NestJS CLI's `webpack: true` build mode, that means they're never part
|
|
46
|
+
* of the bundle's reachable module graph, so they never get compiled to
|
|
47
|
+
* .js even when the rest of the app is — there's nothing for a plain
|
|
48
|
+
* `require()` to load. resolveDocsPath can correctly locate the original
|
|
49
|
+
* .ts file (see resolve-source-from-stack.ts), but loading it still needs
|
|
50
|
+
* this.
|
|
51
|
+
*
|
|
52
|
+
* Registers `require.extensions['.ts']` — exactly the mechanism ts-node's
|
|
53
|
+
* own `register()` uses — rather than manually constructing a `Module`
|
|
54
|
+
* instance and calling `_compile()` directly. That distinction matters for
|
|
55
|
+
* correctness, not just style: Node's module *resolution* (not just
|
|
56
|
+
* compilation) only tries an extension if it's a registered key of
|
|
57
|
+
* `require.extensions`. A docs file importing a sibling relative path
|
|
58
|
+
* (`import { UsersController } from './users.controller'`) needs Node to
|
|
59
|
+
* try `./users.controller.ts` while resolving — manually compiling just
|
|
60
|
+
* the entry file doesn't make Node try `.ts` for anything *it* requires
|
|
61
|
+
* in turn, so any relative import inside the docs file would still throw
|
|
62
|
+
* "Cannot find module" one level down.
|
|
63
|
+
*
|
|
64
|
+
* Transpiles with esbuild — type-stripping only, since docs files call
|
|
65
|
+
* decorator factories as plain functions (`docs(Controller, { classDecorators:
|
|
66
|
+
* [ApiTags('x')] })`) rather than using TypeScript decorator syntax
|
|
67
|
+
* themselves, so no decorator-metadata emulation is needed.
|
|
68
|
+
*/
|
|
69
|
+
function requireTypeScriptFile(absPath) {
|
|
70
|
+
console.error('[DEBUG requireTypeScriptFile]', JSON.stringify(absPath), 'exists=', fs.existsSync(absPath));
|
|
71
|
+
if (!fs.existsSync(absPath)) {
|
|
72
|
+
// Matches the shape of Node's own require() MODULE_NOT_FOUND error, so
|
|
73
|
+
// callers that distinguish "file doesn't exist" from "file threw while
|
|
74
|
+
// loading" (DocfyModule's isMissingDocsFile) work the same regardless
|
|
75
|
+
// of which loader actually handled the path.
|
|
76
|
+
throw Object.assign(new Error(`Cannot find module '${absPath}'`), {
|
|
77
|
+
code: 'MODULE_NOT_FOUND',
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
registerTsExtension();
|
|
81
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
82
|
+
return require(absPath);
|
|
83
|
+
}
|
|
84
|
+
let registered = false;
|
|
85
|
+
function registerTsExtension() {
|
|
86
|
+
if (registered || require.extensions['.ts'])
|
|
87
|
+
return;
|
|
88
|
+
const esbuild = loadEsbuild();
|
|
89
|
+
if (!esbuild) {
|
|
90
|
+
throw new Error(`[nestjs-docfy] Cannot load a .ts docs file: no TypeScript loader is registered ` +
|
|
91
|
+
`(e.g. ts-node) and the "esbuild" dependency isn't available. Install esbuild ` +
|
|
92
|
+
`(it's a direct dependency of nestjs-docfy and should already be present — ` +
|
|
93
|
+
`check your install), or disable webpack bundling ("webpack": false in ` +
|
|
94
|
+
`nest-cli.json) so docs files get compiled to .js like everything else.`);
|
|
95
|
+
}
|
|
96
|
+
require.extensions['.ts'] = (mod, filename) => {
|
|
97
|
+
const source = fs.readFileSync(filename, 'utf8');
|
|
98
|
+
const { code } = esbuild.transformSync(source, {
|
|
99
|
+
loader: 'ts',
|
|
100
|
+
format: 'cjs',
|
|
101
|
+
target: 'es2019',
|
|
102
|
+
sourcefile: filename,
|
|
103
|
+
// A docs file's own relative imports can pull in real application
|
|
104
|
+
// source (e.g. the controller it documents), which legitimately uses
|
|
105
|
+
// NestJS's decorator syntax — without this, esbuild rejects parameter
|
|
106
|
+
// decorators like `@Body()` outright.
|
|
107
|
+
tsconfigRaw: { compilerOptions: { experimentalDecorators: true, emitDecoratorMetadata: true } },
|
|
108
|
+
});
|
|
109
|
+
mod._compile(code, filename);
|
|
110
|
+
};
|
|
111
|
+
registered = true;
|
|
112
|
+
}
|
|
113
|
+
function loadEsbuild() {
|
|
114
|
+
try {
|
|
115
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
116
|
+
return require('esbuild');
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=require-ts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"require-ts.js","sourceRoot":"","sources":["../src/require-ts.ts"],"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,MAAM,EAAE;YAC7C,MAAM,EAAE,IAAI;YACZ,MAAM,EAAE,KAAK;YACb,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,kEAAkE;YAClE,qEAAqE;YACrE,sEAAsE;YACtE,sCAAsC;YACtC,WAAW,EAAE,EAAE,eAAe,EAAE,EAAE,sBAAsB,EAAE,IAAI,EAAE,qBAAqB,EAAE,IAAI,EAAE,EAAE;SAChG,CAAC,CAAC;QACF,GAAqC,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAClE,CAAC,CAAC;IACF,UAAU,GAAG,IAAI,CAAC;AACpB,CAAC;AAED,SAAS,WAAW;IAClB,IAAI,CAAC;QACH,iEAAiE;QACjE,OAAO,OAAO,CAAC,SAAS,CAAkB,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nestjs-docfy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Keep your NestJS controllers clean — Swagger docs live in a separate companion file by naming convention",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -116,7 +116,7 @@
|
|
|
116
116
|
},
|
|
117
117
|
"dependencies": {
|
|
118
118
|
"commander": "^15.0.0",
|
|
119
|
-
"docfy-ui": "^0.
|
|
119
|
+
"docfy-ui": "^0.5.0",
|
|
120
120
|
"express": "^5.0.0",
|
|
121
121
|
"openapi-typescript": "^7.13.0",
|
|
122
122
|
"picocolors": "^1.1.1",
|