@bymax-one/nest-core 1.3.2 → 1.5.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/CHANGELOG.md +183 -2
- package/README.md +272 -36
- package/dist/index.cjs +335 -161
- package/dist/index.d.cts +242 -16
- package/dist/index.d.ts +242 -16
- package/dist/index.mjs +336 -163
- package/dist/openapi/index.cjs +240 -45
- package/dist/openapi/index.d.cts +147 -2
- package/dist/openapi/index.d.ts +147 -2
- package/dist/openapi/index.mjs +240 -48
- package/package.json +3 -1
package/dist/openapi/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { INestApplication } from '@nestjs/common';
|
|
1
|
+
import { INestApplication, CustomDecorator } from '@nestjs/common';
|
|
2
2
|
|
|
3
3
|
/** Why the document was not mounted. */
|
|
4
4
|
type OpenApiSkipReason =
|
|
@@ -51,4 +51,149 @@ interface OpenApiMountOutcome {
|
|
|
51
51
|
*/
|
|
52
52
|
declare function applyBymaxOpenApi(app: INestApplication): Promise<OpenApiMountOutcome>;
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
/**
|
|
55
|
+
* Addresses one route handler, as `'<ControllerClassName>.<methodName>'`.
|
|
56
|
+
*
|
|
57
|
+
* Controller handlers only. A route the application mounts some other way — raw
|
|
58
|
+
* middleware, a router the framework never scanned — produces no operation in
|
|
59
|
+
* the generated document and therefore no handler to address; a fragment naming
|
|
60
|
+
* one fails the build rather than being quietly dropped.
|
|
61
|
+
*
|
|
62
|
+
* This is the key a library writes its fragments against, and it is a contract:
|
|
63
|
+
* `@nestjs/swagger` hands the same pair to the operation-id factory this package
|
|
64
|
+
* installs, so a fragment can be matched to the operation the scan produced
|
|
65
|
+
* without either side reconstructing a path.
|
|
66
|
+
*
|
|
67
|
+
* Deliberately not the operation id itself. The id is whatever the ecosystem
|
|
68
|
+
* already produces — `AuthController_login` by default — and a library keying on
|
|
69
|
+
* it would break the moment a consumer supplied their own naming, while a
|
|
70
|
+
* consumer changing that naming would silently unmatch every fragment.
|
|
71
|
+
*
|
|
72
|
+
* @example 'AuthController.login'
|
|
73
|
+
* @example 'PasswordResetController.resetPassword'
|
|
74
|
+
*/
|
|
75
|
+
type OpenApiHandlerKey = `${string}.${string}`;
|
|
76
|
+
/**
|
|
77
|
+
* A single OpenAPI object, copied into the document and never interpreted.
|
|
78
|
+
* Modelled as an open record for the same reason the contributed schemas are: a
|
|
79
|
+
* partial local model of the specification would be a second contract to keep in
|
|
80
|
+
* sync with the real one.
|
|
81
|
+
*/
|
|
82
|
+
type OpenApiFragmentObject = Readonly<Record<string, unknown>>;
|
|
83
|
+
/**
|
|
84
|
+
* What a contributor hands over: operation fragments addressed by handler, and
|
|
85
|
+
* the components those fragments reference.
|
|
86
|
+
*
|
|
87
|
+
* The dialect is **OpenAPI 3.0**, which is what `@nestjs/swagger` produces —
|
|
88
|
+
* measured, not assumed: its `DocumentBuilder` writes `openapi: '3.0.0'` and a
|
|
89
|
+
* served document reports the same. A 3.1 fragment merged into a 3.0 document
|
|
90
|
+
* produces one that validates as neither, so nullability belongs in `nullable`
|
|
91
|
+
* rather than in a union type.
|
|
92
|
+
*/
|
|
93
|
+
interface OpenApiFragment {
|
|
94
|
+
/**
|
|
95
|
+
* Which revision of this contract the fragment is written against. Always
|
|
96
|
+
* {@link BYMAX_OPENAPI_CONTRACT_VERSION}.
|
|
97
|
+
*
|
|
98
|
+
* A fragment is data crossing a boundary between independently released
|
|
99
|
+
* packages, and on that boundary compile-time types protect nothing: a
|
|
100
|
+
* library compiled against one revision of this contract runs inside an
|
|
101
|
+
* application that installed another, each having type-checked against its
|
|
102
|
+
* own copy. Only the value travelling at runtime can say which shape it is.
|
|
103
|
+
* So it self-describes, and a revision this package does not know fails the
|
|
104
|
+
* document build naming both — the same reason a Kubernetes object carries
|
|
105
|
+
* `apiVersion` rather than trusting that client and server agree.
|
|
106
|
+
*
|
|
107
|
+
* A plain integer rather than a semver range: this is the shape of the
|
|
108
|
+
* exchange, not the version of any package, and it changes only when the
|
|
109
|
+
* shape does.
|
|
110
|
+
*/
|
|
111
|
+
readonly contractVersion: typeof BYMAX_OPENAPI_CONTRACT_VERSION;
|
|
112
|
+
/**
|
|
113
|
+
* Operation objects to merge, keyed by the handler that produced the
|
|
114
|
+
* operation. A key addressing a handler the document does not contain fails
|
|
115
|
+
* the build naming the contributor: a fragment for a renamed handler is a
|
|
116
|
+
* check that stopped running, which is worse than one that fails.
|
|
117
|
+
*/
|
|
118
|
+
readonly operations?: Readonly<Record<OpenApiHandlerKey, OpenApiFragmentObject>>;
|
|
119
|
+
/**
|
|
120
|
+
* Entries to merge under the document's `components`, keyed by member —
|
|
121
|
+
* `schemas`, `securitySchemes`, `responses`, and so on. Additive: an entry the
|
|
122
|
+
* document already defines under that name is kept.
|
|
123
|
+
*/
|
|
124
|
+
readonly components?: Readonly<Record<string, Readonly<Record<string, OpenApiFragmentObject>>>>;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* A library that describes its own routes in the document.
|
|
128
|
+
*
|
|
129
|
+
* Called once, while the document is being built, and only when the OpenAPI
|
|
130
|
+
* feature is enabled — so a library implementing it costs an application that
|
|
131
|
+
* never builds a document nothing beyond one metadata entry.
|
|
132
|
+
*/
|
|
133
|
+
interface IOpenApiContributor {
|
|
134
|
+
/**
|
|
135
|
+
* Produce this library's fragments.
|
|
136
|
+
*
|
|
137
|
+
* Called after the application's options have resolved, so a contributor may
|
|
138
|
+
* derive its contribution from its own configuration — which is the case that
|
|
139
|
+
* makes this contract necessary rather than convenient. A library whose
|
|
140
|
+
* credential names or transport are configurable cannot state its security
|
|
141
|
+
* statically; only it can say what its resolved options mean.
|
|
142
|
+
*
|
|
143
|
+
* @returns The fragments to merge. Return an empty object to contribute
|
|
144
|
+
* nothing; throwing fails the document build with the contributor named.
|
|
145
|
+
*/
|
|
146
|
+
contributeOpenApi(): OpenApiFragment;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The revision of the fragment exchange this package speaks.
|
|
150
|
+
*
|
|
151
|
+
* Bumped only when the shape of {@link OpenApiFragment} changes in a way a
|
|
152
|
+
* previous revision's fragment would be misread under — not when a member is
|
|
153
|
+
* added, which older fragments simply do not carry.
|
|
154
|
+
*/
|
|
155
|
+
declare const BYMAX_OPENAPI_CONTRACT_VERSION = 1;
|
|
156
|
+
/**
|
|
157
|
+
* Reflect metadata key carrying the contributor marker.
|
|
158
|
+
*
|
|
159
|
+
* A literal string rather than a key from `DiscoveryService.createDecorator()`,
|
|
160
|
+
* which mints a random key per module load: this package ships one bundle per
|
|
161
|
+
* subpath, so a library decorating its class through `./openapi` would get a
|
|
162
|
+
* different key than the scan running from the package root and nothing would
|
|
163
|
+
* ever be discovered. The same reasoning governs the health and metrics markers.
|
|
164
|
+
* Namespaced so it cannot collide with a consumer's own metadata.
|
|
165
|
+
*/
|
|
166
|
+
declare const BYMAX_OPENAPI_CONTRIBUTOR_METADATA = "bymax-one:openapi-contributor";
|
|
167
|
+
/**
|
|
168
|
+
* Mark a provider class as an OpenAPI contributor, so `applyBymaxOpenApi` finds
|
|
169
|
+
* it without the application wiring anything.
|
|
170
|
+
*
|
|
171
|
+
* The class must implement {@link IOpenApiContributor}; a marked provider that
|
|
172
|
+
* does not fails the document build with a message naming it, rather than being
|
|
173
|
+
* skipped silently.
|
|
174
|
+
*
|
|
175
|
+
* @returns The class decorator carrying the marker.
|
|
176
|
+
* @example
|
|
177
|
+
* \@BymaxOpenApiContributor()
|
|
178
|
+
* \@Injectable()
|
|
179
|
+
* export class AuthOpenApi implements IOpenApiContributor {
|
|
180
|
+
* constructor(private readonly options: ResolvedAuthOptions) {}
|
|
181
|
+
* contributeOpenApi(): OpenApiFragment {
|
|
182
|
+
* return {
|
|
183
|
+
* components: {
|
|
184
|
+
* securitySchemes: {
|
|
185
|
+
* authCookie: { type: 'apiKey', in: 'cookie', name: this.options.cookies.accessTokenName },
|
|
186
|
+
* refreshCookie: { type: 'apiKey', in: 'cookie', name: this.options.cookies.refreshTokenName }
|
|
187
|
+
* }
|
|
188
|
+
* },
|
|
189
|
+
* operations: {
|
|
190
|
+
* 'AuthController.login': { security: [] },
|
|
191
|
+
* 'AuthController.refresh': { security: [{ refreshCookie: [] }] }
|
|
192
|
+
* }
|
|
193
|
+
* }
|
|
194
|
+
* }
|
|
195
|
+
* }
|
|
196
|
+
*/
|
|
197
|
+
declare function BymaxOpenApiContributor(): CustomDecorator<string>;
|
|
198
|
+
|
|
199
|
+
export { BYMAX_OPENAPI_CONTRACT_VERSION, BYMAX_OPENAPI_CONTRIBUTOR_METADATA, BymaxOpenApiContributor, type IOpenApiContributor, type OpenApiFragment, type OpenApiFragmentObject, type OpenApiHandlerKey, type OpenApiMountOutcome, type OpenApiSkipReason, applyBymaxOpenApi };
|
package/dist/openapi/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Logger, VersioningType, VERSION_NEUTRAL } from '@nestjs/common';
|
|
2
|
-
import { ApplicationConfig } from '@nestjs/core';
|
|
1
|
+
import { SetMetadata, Logger, VersioningType, VERSION_NEUTRAL } from '@nestjs/common';
|
|
2
|
+
import { DiscoveryService, Reflector, ApplicationConfig } from '@nestjs/core';
|
|
3
3
|
|
|
4
4
|
// src/openapi/openapi.bootstrap.ts
|
|
5
5
|
|
|
@@ -15,10 +15,148 @@ function isProductionRuntime(value = process.env["NODE_ENV"]) {
|
|
|
15
15
|
return !NON_PRODUCTION_ENVIRONMENTS.has(value.trim().toLowerCase());
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
// src/discovery.ts
|
|
19
|
+
function labelFor(className, token) {
|
|
20
|
+
return className === "" ? String(token) : className;
|
|
21
|
+
}
|
|
22
|
+
function findMarkedProviders(discovery, reflector, metadataKey) {
|
|
23
|
+
const marked = [];
|
|
24
|
+
for (const wrapper of discovery.getProviders()) {
|
|
25
|
+
const metatype = wrapper.metatype;
|
|
26
|
+
if (typeof metatype !== "function") {
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (reflector.get(metadataKey, metatype) !== true) {
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
marked.push({ instance: wrapper.instance, label: labelFor(metatype.name, wrapper.name) });
|
|
33
|
+
}
|
|
34
|
+
return marked;
|
|
35
|
+
}
|
|
36
|
+
var BYMAX_OPENAPI_CONTRACT_VERSION = 1;
|
|
37
|
+
var BYMAX_OPENAPI_CONTRIBUTOR_METADATA = "bymax-one:openapi-contributor";
|
|
38
|
+
function BymaxOpenApiContributor() {
|
|
39
|
+
return SetMetadata(BYMAX_OPENAPI_CONTRIBUTOR_METADATA, true);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/openapi/openapi.contribution.ts
|
|
43
|
+
function createHandlerIdMap() {
|
|
44
|
+
const ids = /* @__PURE__ */ new Map();
|
|
45
|
+
const versions = /* @__PURE__ */ new Map();
|
|
46
|
+
return {
|
|
47
|
+
record: (controllerKey, methodKey, version, id) => {
|
|
48
|
+
const handlerKey = `${controllerKey}.${methodKey}`;
|
|
49
|
+
const seen = versions.get(handlerKey) ?? /* @__PURE__ */ new Set();
|
|
50
|
+
if (seen.has(version)) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`[BymaxCoreModule] two route handlers in this application answer to "${handlerKey}", so an OpenAPI fragment addressing it would apply to both. Handler keys are "<ControllerClassName>.<methodName>"; rename one of the controller classes.`
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
seen.add(version);
|
|
56
|
+
versions.set(handlerKey, seen);
|
|
57
|
+
ids.set(handlerKey, [...ids.get(handlerKey) ?? [], id]);
|
|
58
|
+
},
|
|
59
|
+
idsFor: (handlerKey) => ids.get(handlerKey) ?? [],
|
|
60
|
+
keys: () => [...ids.keys()]
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function isContributor(instance) {
|
|
64
|
+
return typeof instance?.contributeOpenApi === "function";
|
|
65
|
+
}
|
|
66
|
+
function callContributor(contributor, label) {
|
|
67
|
+
try {
|
|
68
|
+
return contributor.contributeOpenApi();
|
|
69
|
+
} catch (cause) {
|
|
70
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
71
|
+
throw new Error(
|
|
72
|
+
`[BymaxCoreModule] "${label}" failed to contribute to the OpenAPI document: ${reason}`,
|
|
73
|
+
{
|
|
74
|
+
cause
|
|
75
|
+
}
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function assertContractVersion(fragment, label) {
|
|
80
|
+
if (fragment.contractVersion === BYMAX_OPENAPI_CONTRACT_VERSION) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
throw new Error(
|
|
84
|
+
`[BymaxCoreModule] "${label}" contributed a fragment written against OpenAPI contract version ${String(fragment.contractVersion)}, and this package speaks version ${String(BYMAX_OPENAPI_CONTRACT_VERSION)}. Upgrade whichever of the two is behind; the shapes are not interchangeable.`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
function resolveOperations(fragment, label, handlers) {
|
|
88
|
+
const entries = Object.entries(fragment.operations ?? {});
|
|
89
|
+
const unmatched = entries.filter(([handlerKey]) => handlers.idsFor(handlerKey).length === 0);
|
|
90
|
+
if (unmatched.length > 0) {
|
|
91
|
+
const known = handlers.keys();
|
|
92
|
+
throw new Error(
|
|
93
|
+
`[BymaxCoreModule] "${label}" contributed fragments for ${unmatched.length} handler(s) this application does not have: ${unmatched.map(([key]) => key).join(", ")}. Keys are "<ControllerClassName>.<methodName>". The application has: ${known.length === 0 ? "(none)" : known.join(", ")}.`
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
return Object.fromEntries(
|
|
97
|
+
entries.flatMap(
|
|
98
|
+
([handlerKey, operation]) => handlers.idsFor(handlerKey).map((id) => [id, operation])
|
|
99
|
+
)
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
function collectContributions(discovery, reflector, handlers) {
|
|
103
|
+
const marked = [...findMarkedProviders(discovery, reflector, BYMAX_OPENAPI_CONTRIBUTOR_METADATA)];
|
|
104
|
+
const labels = marked.map(({ label }) => label);
|
|
105
|
+
const duplicated = labels.filter((label, index) => labels.indexOf(label) !== index);
|
|
106
|
+
if (duplicated.length > 0) {
|
|
107
|
+
throw new Error(
|
|
108
|
+
`[BymaxCoreModule] more than one OpenAPI contributor is named "${[...new Set(duplicated)].join('", "')}", so the order they merge in would depend on the container rather than on anything stated. Rename one of the contributor classes.`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
marked.sort((left, right) => left.label.localeCompare(right.label));
|
|
112
|
+
return marked.map(({ instance, label }) => {
|
|
113
|
+
if (!isContributor(instance)) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
`[BymaxCoreModule] "${label}" is marked @BymaxOpenApiContributor() but does not implement IOpenApiContributor: it must expose a "contributeOpenApi" method.`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
const fragment = callContributor(instance, label);
|
|
119
|
+
assertContractVersion(fragment, label);
|
|
120
|
+
return {
|
|
121
|
+
label,
|
|
122
|
+
operations: resolveOperations(fragment, label, handlers),
|
|
123
|
+
components: fragment.components ?? {}
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
18
128
|
// src/route-defaults.ts
|
|
19
129
|
var DEFAULT_HEALTH_PATH = "health";
|
|
20
130
|
var DEFAULT_METRICS_PATH = "metrics";
|
|
21
131
|
|
|
132
|
+
// src/openapi/openapi.routes.ts
|
|
133
|
+
function trimSlashes(segment) {
|
|
134
|
+
return segment.split("/").filter((part) => part !== "").join("/");
|
|
135
|
+
}
|
|
136
|
+
function routePath(prefix, suffix) {
|
|
137
|
+
return prefix === "" ? `/${suffix}` : `/${prefix}/${suffix}`;
|
|
138
|
+
}
|
|
139
|
+
function healthRoutes(options) {
|
|
140
|
+
const bases = /* @__PURE__ */ new Set([trimSlashes(options.health.path), DEFAULT_HEALTH_PATH]);
|
|
141
|
+
return [...bases].flatMap((base) => [`${base}/live`, `${base}/ready`]);
|
|
142
|
+
}
|
|
143
|
+
function metricsRoutes(options) {
|
|
144
|
+
return [.../* @__PURE__ */ new Set([trimSlashes(options.metrics.path), DEFAULT_METRICS_PATH])];
|
|
145
|
+
}
|
|
146
|
+
function indexOwnRoutes(options, prefixes) {
|
|
147
|
+
const normalized = prefixes.map(trimSlashes);
|
|
148
|
+
const expand = (suffixes) => normalized.flatMap((prefix) => suffixes.map((suffix) => routePath(prefix, suffix)));
|
|
149
|
+
const health = expand(healthRoutes(options));
|
|
150
|
+
const metrics = expand(metricsRoutes(options));
|
|
151
|
+
return {
|
|
152
|
+
isHealth: (path) => health.includes(path),
|
|
153
|
+
isMetrics: (path) => metrics.includes(path)
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function isOwnRoute(path, method, routes) {
|
|
157
|
+
return method === "get" && (routes.isHealth(path) || routes.isMetrics(path));
|
|
158
|
+
}
|
|
159
|
+
|
|
22
160
|
// src/envelope/error-codes.ts
|
|
23
161
|
var BYMAX_BAD_REQUEST = "BYMAX_BAD_REQUEST";
|
|
24
162
|
var BYMAX_VALIDATION_FAILED = "BYMAX_VALIDATION_FAILED";
|
|
@@ -207,7 +345,8 @@ function operationsOf(item) {
|
|
|
207
345
|
}
|
|
208
346
|
function mergeResponses(existing, additions) {
|
|
209
347
|
const merged = new Map(Object.entries(existing));
|
|
210
|
-
for (const [status,
|
|
348
|
+
for (const [status, value] of Object.entries(additions)) {
|
|
349
|
+
const contributed = asRecord(value);
|
|
211
350
|
const current = asRecord(merged.get(status));
|
|
212
351
|
if (current["content"] === void 0 && current["$ref"] === void 0) {
|
|
213
352
|
const described = current["description"] === void 0 || current["description"] === "" ? contributed["description"] : current["description"];
|
|
@@ -216,29 +355,6 @@ function mergeResponses(existing, additions) {
|
|
|
216
355
|
}
|
|
217
356
|
return Object.fromEntries(merged);
|
|
218
357
|
}
|
|
219
|
-
function trimSlashes(segment) {
|
|
220
|
-
return segment.split("/").filter((part) => part !== "").join("/");
|
|
221
|
-
}
|
|
222
|
-
function routePath(prefix, suffix) {
|
|
223
|
-
return prefix === "" ? `/${suffix}` : `/${prefix}/${suffix}`;
|
|
224
|
-
}
|
|
225
|
-
function healthRoutes(options) {
|
|
226
|
-
const bases = /* @__PURE__ */ new Set([trimSlashes(options.health.path), DEFAULT_HEALTH_PATH]);
|
|
227
|
-
return [...bases].flatMap((base) => [`${base}/live`, `${base}/ready`]);
|
|
228
|
-
}
|
|
229
|
-
function metricsRoutes(options) {
|
|
230
|
-
return [.../* @__PURE__ */ new Set([trimSlashes(options.metrics.path), DEFAULT_METRICS_PATH])];
|
|
231
|
-
}
|
|
232
|
-
function indexOwnRoutes(options, prefixes) {
|
|
233
|
-
const normalized = prefixes.map(trimSlashes);
|
|
234
|
-
const expand = (suffixes) => normalized.flatMap((prefix) => suffixes.map((suffix) => routePath(prefix, suffix)));
|
|
235
|
-
const health = expand(healthRoutes(options));
|
|
236
|
-
const metrics = expand(metricsRoutes(options));
|
|
237
|
-
return {
|
|
238
|
-
isHealth: (path) => health.includes(path),
|
|
239
|
-
isMetrics: (path) => metrics.includes(path)
|
|
240
|
-
};
|
|
241
|
-
}
|
|
242
358
|
function withoutDisabledRoutes(paths, options, routes) {
|
|
243
359
|
const disabled = (path) => !options.health.enabled && routes.isHealth(path) || !options.metrics.enabled && routes.isMetrics(path);
|
|
244
360
|
const kept = Object.entries(paths).map(([path, item]) => {
|
|
@@ -287,11 +403,29 @@ function coreResponses(path, options, routes) {
|
|
|
287
403
|
}
|
|
288
404
|
return responses;
|
|
289
405
|
}
|
|
290
|
-
function
|
|
291
|
-
|
|
292
|
-
|
|
406
|
+
function fragmentsFor(operationId, contributions) {
|
|
407
|
+
return contributions.flatMap(
|
|
408
|
+
(contribution) => Object.entries(contribution.operations).filter(([id]) => id === operationId).map(([, fragment]) => fragment)
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
function mergeFragment(operation, fragment) {
|
|
412
|
+
const { responses, ...members } = fragment;
|
|
413
|
+
const merged = { ...members, ...operation };
|
|
414
|
+
if (responses !== void 0) {
|
|
415
|
+
merged["responses"] = mergeResponses(asRecord(operation["responses"]), asRecord(responses));
|
|
416
|
+
}
|
|
417
|
+
return merged;
|
|
418
|
+
}
|
|
419
|
+
function augmentOperation(operation, path, method, options, routes, contributions) {
|
|
420
|
+
const declaredByDocument = operation["security"] !== void 0;
|
|
421
|
+
let result = { ...operation };
|
|
422
|
+
for (const fragment of fragmentsFor(result["operationId"], contributions)) {
|
|
423
|
+
result = { ...mergeFragment(result, fragment) };
|
|
424
|
+
}
|
|
425
|
+
if (!declaredByDocument) {
|
|
293
426
|
const override = options.openapi.operationSecurity[operationKey(method, path)];
|
|
294
|
-
const
|
|
427
|
+
const describedByLibrary = result["security"] !== void 0;
|
|
428
|
+
const security = override ?? (describedByLibrary ? void 0 : ownRouteSecurity(path, method, options, routes));
|
|
295
429
|
if (security !== void 0) {
|
|
296
430
|
result["security"] = security;
|
|
297
431
|
}
|
|
@@ -304,6 +438,25 @@ function augmentOperation(operation, path, method, options, routes) {
|
|
|
304
438
|
}
|
|
305
439
|
return result;
|
|
306
440
|
}
|
|
441
|
+
function consumerOperations(paths, routes) {
|
|
442
|
+
return Object.entries(paths).flatMap(
|
|
443
|
+
([path, item]) => operationsOf(item).filter(([method]) => !isOwnRoute(path, method, routes)).map(([method, operation]) => ({
|
|
444
|
+
key: operationKey(method, path),
|
|
445
|
+
operation: asRecord(operation)
|
|
446
|
+
}))
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
function unsecuredOperations(document, options, pathPrefixes = [""]) {
|
|
450
|
+
if (document.security !== void 0) {
|
|
451
|
+
return [];
|
|
452
|
+
}
|
|
453
|
+
const routes = indexOwnRoutes(options, pathPrefixes);
|
|
454
|
+
const candidates = consumerOperations(asRecord(document.paths), routes);
|
|
455
|
+
if (!candidates.some(({ operation }) => operation["security"] !== void 0)) {
|
|
456
|
+
return [];
|
|
457
|
+
}
|
|
458
|
+
return candidates.filter(({ operation }) => operation["security"] === void 0).map(({ key }) => key);
|
|
459
|
+
}
|
|
307
460
|
function assertSchemesDeclared(openapi, schemes) {
|
|
308
461
|
const required = [...openapi.security, ...Object.values(openapi.operationSecurity).flat()];
|
|
309
462
|
const named = [...new Set(required.flatMap((requirement) => Object.keys(requirement)))];
|
|
@@ -347,24 +500,24 @@ function assertOverridesMatch(paths, openapi) {
|
|
|
347
500
|
`[BymaxCoreModule] openapi.operationSecurity addresses ${unmatched.length} operation(s) that the document does not contain: ${unmatched.join(", ")}. Keys are "<METHOD> <path>" with the path exactly as documented, including any global prefix. The document contains: ${documented.length === 0 ? "(none)" : documented.join(", ")}.`
|
|
348
501
|
);
|
|
349
502
|
}
|
|
350
|
-
function augmentPaths(paths, options, routes) {
|
|
503
|
+
function augmentPaths(paths, options, routes, contributions) {
|
|
351
504
|
return Object.fromEntries(
|
|
352
505
|
Object.entries(paths).map(([path, item]) => {
|
|
353
506
|
const augmented = operationsOf(item).map(([method, operation]) => [
|
|
354
507
|
method,
|
|
355
|
-
augmentOperation(asRecord(operation), path, method, options, routes)
|
|
508
|
+
augmentOperation(asRecord(operation), path, method, options, routes, contributions)
|
|
356
509
|
]);
|
|
357
510
|
return [path, { ...asRecord(item), ...Object.fromEntries(augmented) }];
|
|
358
511
|
})
|
|
359
512
|
);
|
|
360
513
|
}
|
|
361
|
-
function augmentDocument(document, options, pathPrefixes = [""]) {
|
|
514
|
+
function augmentDocument(document, options, pathPrefixes = [""], contributions = []) {
|
|
362
515
|
const { openapi } = options;
|
|
363
516
|
const components = asRecord(document.components);
|
|
364
|
-
const merged =
|
|
517
|
+
const merged = new Map(Object.entries(components));
|
|
365
518
|
if (openapi.includeCoreSchemas) {
|
|
366
|
-
merged
|
|
367
|
-
merged
|
|
519
|
+
merged.set("schemas", mergeAbsent(asRecord(components["schemas"]), CORE_SCHEMAS));
|
|
520
|
+
merged.set("parameters", mergeAbsent(asRecord(components["parameters"]), CORE_PARAMETERS));
|
|
368
521
|
}
|
|
369
522
|
const scrapeScheme = options.metrics.authToken === void 0 ? {} : {
|
|
370
523
|
[METRICS_SCHEME_NAME]: {
|
|
@@ -374,20 +527,25 @@ function augmentDocument(document, options, pathPrefixes = [""]) {
|
|
|
374
527
|
}
|
|
375
528
|
};
|
|
376
529
|
assertScrapeSchemeIsOurs(openapi, components, options.metrics.authToken !== void 0);
|
|
377
|
-
const
|
|
530
|
+
const declaredSchemes = mergeAbsent(asRecord(components["securitySchemes"]), {
|
|
378
531
|
...openapi.securitySchemes,
|
|
379
532
|
...scrapeScheme
|
|
380
533
|
});
|
|
381
|
-
if (Object.keys(
|
|
382
|
-
merged
|
|
534
|
+
if (Object.keys(declaredSchemes).length > 0) {
|
|
535
|
+
merged.set("securitySchemes", declaredSchemes);
|
|
536
|
+
}
|
|
537
|
+
for (const contribution of contributions) {
|
|
538
|
+
for (const [member, entries] of Object.entries(contribution.components)) {
|
|
539
|
+
merged.set(member, mergeAbsent(asRecord(merged.get(member)), entries));
|
|
540
|
+
}
|
|
383
541
|
}
|
|
384
|
-
assertSchemesDeclared(openapi,
|
|
542
|
+
assertSchemesDeclared(openapi, asRecord(merged.get("securitySchemes")));
|
|
385
543
|
const routes = indexOwnRoutes(options, pathPrefixes);
|
|
386
544
|
const served = withoutDisabledRoutes(asRecord(document.paths), options, routes);
|
|
387
545
|
assertOverridesMatch(served, openapi);
|
|
388
|
-
const paths = document.paths === void 0 ? {} : { paths: augmentPaths(served, options, routes) };
|
|
546
|
+
const paths = document.paths === void 0 ? {} : { paths: augmentPaths(served, options, routes, contributions) };
|
|
389
547
|
const security = openapi.security.length > 0 && document.security === void 0 ? { security: openapi.security } : {};
|
|
390
|
-
return { ...document, components: merged, ...paths, ...security };
|
|
548
|
+
return { ...document, components: Object.fromEntries(merged), ...paths, ...security };
|
|
391
549
|
}
|
|
392
550
|
|
|
393
551
|
// src/optional-peer.ts
|
|
@@ -413,6 +571,7 @@ async function loadSwagger() {
|
|
|
413
571
|
}
|
|
414
572
|
|
|
415
573
|
// src/openapi/openapi.bootstrap.ts
|
|
574
|
+
var MAX_WARNED_OPERATIONS = 10;
|
|
416
575
|
var OPTIONS_UNRESOLVED_MESSAGE = "[BymaxCoreModule] applyBymaxOpenApi could not resolve BYMAX_CORE_OPTIONS from the application. Register BymaxCoreModule (forRoot or forRootAsync) before calling it, and keep the module global or import it into the module you bootstrap.";
|
|
417
576
|
function resolveCoreOptions(app) {
|
|
418
577
|
try {
|
|
@@ -450,6 +609,37 @@ function readPathPrefixes(app) {
|
|
|
450
609
|
const globalPrefix = config.getGlobalPrefix();
|
|
451
610
|
return versionSegments(config.getVersioning()).map((segment) => `${globalPrefix}/${segment}`);
|
|
452
611
|
}
|
|
612
|
+
function recordingOperationIdFactory(handlers, configured) {
|
|
613
|
+
return (controllerKey, methodKey, version) => {
|
|
614
|
+
const id = configured === void 0 ? defaultOperationId(controllerKey, methodKey, version) : configured(controllerKey, methodKey, version);
|
|
615
|
+
handlers.record(controllerKey, methodKey, version, id);
|
|
616
|
+
return id;
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
function defaultOperationId(controllerKey, methodKey, version) {
|
|
620
|
+
return version === void 0 ? `${controllerKey}_${methodKey}` : `${controllerKey}_${methodKey}_${version}`;
|
|
621
|
+
}
|
|
622
|
+
function readContributions(app, handlers) {
|
|
623
|
+
let discovery;
|
|
624
|
+
let reflector;
|
|
625
|
+
try {
|
|
626
|
+
discovery = app.get(DiscoveryService);
|
|
627
|
+
reflector = app.get(Reflector);
|
|
628
|
+
} catch {
|
|
629
|
+
return [];
|
|
630
|
+
}
|
|
631
|
+
return collectContributions(discovery, reflector, handlers);
|
|
632
|
+
}
|
|
633
|
+
function warnUnsecuredOperations(logger, keys) {
|
|
634
|
+
if (keys.length === 0) {
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
const elided = keys.length - MAX_WARNED_OPERATIONS;
|
|
638
|
+
const listed = keys.slice(0, MAX_WARNED_OPERATIONS).join(", ");
|
|
639
|
+
logger.warn(
|
|
640
|
+
`a client generated from the OpenAPI document will send no credentials to ${keys.length} operation(s): ${listed}${elided > 0 ? `, and ${elided} more` : ""}. They state no security requirement, the document declares no default, and other operations in it do state one \u2014 so this is more often a missing openapi.security default than a public API. Set openapi.security, or state the intent per operation with an explicit [] in openapi.operationSecurity.`
|
|
641
|
+
);
|
|
642
|
+
}
|
|
453
643
|
function buildConfig(builder, options) {
|
|
454
644
|
builder.setTitle(options.title).setDescription(options.description).setVersion(options.version);
|
|
455
645
|
for (const server of options.servers) {
|
|
@@ -474,11 +664,13 @@ async function applyBymaxOpenApi(app) {
|
|
|
474
664
|
}
|
|
475
665
|
const swagger = await loadSwagger();
|
|
476
666
|
const config = buildConfig(new swagger.DocumentBuilder(), options);
|
|
477
|
-
const
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
);
|
|
667
|
+
const handlers = createHandlerIdMap();
|
|
668
|
+
const generated = swagger.SwaggerModule.createDocument(app, config, {
|
|
669
|
+
operationIdFactory: recordingOperationIdFactory(handlers, options.operationIdFactory)
|
|
670
|
+
});
|
|
671
|
+
const prefixes = readPathPrefixes(app);
|
|
672
|
+
const document = augmentDocument(generated, resolved, prefixes, readContributions(app, handlers));
|
|
673
|
+
warnUnsecuredOperations(logger, unsecuredOperations(document, resolved, prefixes));
|
|
482
674
|
swagger.SwaggerModule.setup(options.path, app, document, {
|
|
483
675
|
jsonDocumentUrl: options.jsonPath
|
|
484
676
|
});
|
|
@@ -486,4 +678,4 @@ async function applyBymaxOpenApi(app) {
|
|
|
486
678
|
return { mounted: true, path: options.path };
|
|
487
679
|
}
|
|
488
680
|
|
|
489
|
-
export { applyBymaxOpenApi };
|
|
681
|
+
export { BYMAX_OPENAPI_CONTRACT_VERSION, BYMAX_OPENAPI_CONTRIBUTOR_METADATA, BymaxOpenApiContributor, applyBymaxOpenApi };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bymax-one/nest-core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Zero-dependency NestJS 11 application foundation kit: error-envelope exception filter, request-timing interceptor, pagination helpers, health endpoints with indicator discovery, an optional Prometheus metrics endpoint with a contribution contract, OpenAPI documents in development, and OpenTelemetry trace correlation.",
|
|
5
5
|
"author": "Bymax One <support@bymax.one>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -136,6 +136,7 @@
|
|
|
136
136
|
"@nestjs/common": "^11.1.20",
|
|
137
137
|
"@nestjs/core": "^11.1.20",
|
|
138
138
|
"@nestjs/platform-express": "^11.1.20",
|
|
139
|
+
"@nestjs/platform-fastify": "^11.1.29",
|
|
139
140
|
"@nestjs/swagger": "^11.4.6",
|
|
140
141
|
"@nestjs/testing": "^11.1.20",
|
|
141
142
|
"@opentelemetry/api": "^1.9.1",
|
|
@@ -155,6 +156,7 @@
|
|
|
155
156
|
"eslint-plugin-import": "^2.32.0",
|
|
156
157
|
"eslint-plugin-prettier": "^5.5.5",
|
|
157
158
|
"eslint-plugin-security": "^4.0.0",
|
|
159
|
+
"fastify": "^5.11.3",
|
|
158
160
|
"globals": "^17.6.0",
|
|
159
161
|
"husky": "^9.1.7",
|
|
160
162
|
"jest": "^30.4.2",
|