@nestbridge/core 2.6.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +23 -23
- package/build/nestbridge.core.d.ts +74 -16
- package/build/nestbridge.core.js +1158 -279
- package/build/nestbridge.core.js.map +1 -1
- package/package.json +1 -1
package/build/nestbridge.core.js
CHANGED
|
@@ -1,7 +1,550 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { ModifierFlags, SyntaxKind, isArrayLiteralExpression, isArrayTypeNode, isArrowFunction, isBinaryExpression, isBlock, isCallExpression, isClassDeclaration, isClassExpression, isConditionalExpression, isDecorator, isDoStatement, isEnumDeclaration, isExportAssignment, isExportDeclaration, isExpressionStatement, isFalseLiteral, isForInStatement, isForOfStatement, isForStatement, isFunctionDeclaration, isFunctionExpression, isIdentifier, isIfStatement, isImportDeclaration, isInterfaceDeclaration, isLiteralTypeNode, isMethodDeclaration, isModuleDeclaration, isNamedExports, isNamedImports, isNewExpression, isNullLiteral, isNumericLiteral, isObjectLiteralExpression, isParenthesizedExpression, isPropertyAccessExpression, isPropertyAssignment, isPropertyDeclaration, isReturnStatement, isShorthandPropertyAssignment, isSpreadElement, isStringLiteral, isStringLiteralLikeNode, isSwitchStatement, isTrueLiteral, isTypeAliasDeclaration, isTypeReferenceNode, isUnionTypeNode, isVariableStatement, isWhileStatement } from "typescript/unstable/ast";
|
|
2
3
|
import { API } from "typescript/unstable/sync";
|
|
3
|
-
import { existsSync } from "node:fs";
|
|
4
|
-
import { dirname, extname, relative, resolve } from "node:path";
|
|
4
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
5
|
+
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
6
|
+
//#region src/analysis/attach-response-wrappers.ts
|
|
7
|
+
var attachResponseWrappers = (controller, classDeclaration, interceptors) => {
|
|
8
|
+
const memberMethods = classDeclaration.members.filter((member) => isMethodDeclaration(member));
|
|
9
|
+
const methods = controller.methods.map((method) => {
|
|
10
|
+
const declaration = memberMethods.find((candidate) => candidate.name.getText() === method.name);
|
|
11
|
+
const responseWrapper = method.responseKind === "json" && declaration !== void 0 ? interceptors.responseWrapperOf(declaration) : void 0;
|
|
12
|
+
return responseWrapper === void 0 ? method : {
|
|
13
|
+
...method,
|
|
14
|
+
responseWrapper
|
|
15
|
+
};
|
|
16
|
+
});
|
|
17
|
+
return {
|
|
18
|
+
...controller,
|
|
19
|
+
methods
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/models/response-wrapper-substitution.ts
|
|
24
|
+
var WRAPPED_RESULT_SUBSTITUTION = "Awaited<Result>";
|
|
25
|
+
var UNRESOLVED_WRAPPED_RESULT_TYPE_SOURCE = "unknown";
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/analysis/unwrap-parenthesized-expression.ts
|
|
28
|
+
var unwrapParenthesizedExpression = (expression) => {
|
|
29
|
+
let unwrapped = expression;
|
|
30
|
+
while (isParenthesizedExpression(unwrapped)) unwrapped = unwrapped.expression;
|
|
31
|
+
return unwrapped;
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/analysis/resolve-sole-return-expression.ts
|
|
35
|
+
/**
|
|
36
|
+
* Accepts an expression body, or a block that holds nothing but simple `const` declarations and
|
|
37
|
+
* a single trailing `return`. A returned identifier resolves to its declared initializer.
|
|
38
|
+
*/
|
|
39
|
+
var resolveSoleReturnExpression = (body) => {
|
|
40
|
+
if (!isBlock(body)) return unwrapParenthesizedExpression(body);
|
|
41
|
+
const localDeclarations = /* @__PURE__ */ new Map();
|
|
42
|
+
let returnExpression;
|
|
43
|
+
let sawReturn = false;
|
|
44
|
+
for (const statement of body.statements) {
|
|
45
|
+
if (sawReturn) return;
|
|
46
|
+
if (isVariableStatement(statement)) {
|
|
47
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
48
|
+
if (!isIdentifier(declaration.name) || declaration.initializer === void 0) return;
|
|
49
|
+
localDeclarations.set(declaration.name.text, declaration.initializer);
|
|
50
|
+
}
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (isReturnStatement(statement)) {
|
|
54
|
+
sawReturn = true;
|
|
55
|
+
returnExpression = statement.expression;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (returnExpression === void 0) return;
|
|
61
|
+
return isIdentifier(returnExpression) ? localDeclarations.get(returnExpression.text) : returnExpression;
|
|
62
|
+
};
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/analysis/synthesize-generic-object-type.ts
|
|
65
|
+
var NUMERIC_OPERATOR_KINDS = [
|
|
66
|
+
SyntaxKind.MinusToken,
|
|
67
|
+
SyntaxKind.AsteriskToken,
|
|
68
|
+
SyntaxKind.SlashToken,
|
|
69
|
+
SyntaxKind.PercentToken
|
|
70
|
+
];
|
|
71
|
+
var fail = (state, node, reason) => {
|
|
72
|
+
state.failure ??= {
|
|
73
|
+
node,
|
|
74
|
+
reason
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
var describeUntypedExpression = (expression) => isBinaryExpression(expression) && expression.operatorToken.kind === SyntaxKind.PlusToken ? `\`${expression.getText()}\` can be a string or a number, so its type is not guessed.` : `The type of \`${expression.getText()}\` cannot be determined statically.`;
|
|
78
|
+
var synthesizeExpressionType = (expression, parameterName, substitution, state) => {
|
|
79
|
+
if (isParenthesizedExpression(expression)) return synthesizeExpressionType(expression.expression, parameterName, substitution, state);
|
|
80
|
+
if (isIdentifier(expression) && expression.text === parameterName) {
|
|
81
|
+
state.substitutionCount += 1;
|
|
82
|
+
return substitution;
|
|
83
|
+
}
|
|
84
|
+
if (isObjectLiteralExpression(expression)) {
|
|
85
|
+
const memberTypes = [];
|
|
86
|
+
for (const property of expression.properties) {
|
|
87
|
+
if (isShorthandPropertyAssignment(property)) {
|
|
88
|
+
const shorthandName = property.name.getText();
|
|
89
|
+
if (shorthandName !== parameterName) return fail(state, property, `The type of \`${shorthandName}\` cannot be determined statically.`);
|
|
90
|
+
state.substitutionCount += 1;
|
|
91
|
+
memberTypes.push(`${shorthandName}: ${substitution}`);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (!isPropertyAssignment(property) || !(isIdentifier(property.name) || isStringLiteral(property.name))) return fail(state, property, `\`${property.getText()}\` is not a plain \`name: value\` property.`);
|
|
95
|
+
const valueType = synthesizeExpressionType(property.initializer, parameterName, substitution, state);
|
|
96
|
+
if (valueType === void 0) return;
|
|
97
|
+
memberTypes.push(`${property.name.text}: ${valueType}`);
|
|
98
|
+
}
|
|
99
|
+
return `{ ${memberTypes.join("; ")} }`;
|
|
100
|
+
}
|
|
101
|
+
if (isStringLiteral(expression)) return "string";
|
|
102
|
+
if (isNumericLiteral(expression)) return "number";
|
|
103
|
+
if (isTrueLiteral(expression) || isFalseLiteral(expression)) return "boolean";
|
|
104
|
+
if (isNullLiteral(expression)) return "null";
|
|
105
|
+
if (isBinaryExpression(expression) && NUMERIC_OPERATOR_KINDS.includes(expression.operatorToken.kind)) return "number";
|
|
106
|
+
return fail(state, expression, describeUntypedExpression(expression));
|
|
107
|
+
};
|
|
108
|
+
var synthesizeGenericObjectType = (objectLiteral, parameterName, substitution) => {
|
|
109
|
+
const state = { substitutionCount: 0 };
|
|
110
|
+
const objectType = synthesizeExpressionType(objectLiteral, parameterName, substitution, state);
|
|
111
|
+
if (objectType === void 0) {
|
|
112
|
+
const failure = state.failure ?? {
|
|
113
|
+
node: objectLiteral,
|
|
114
|
+
reason: `The type of \`${objectLiteral.getText()}\` cannot be determined statically.`
|
|
115
|
+
};
|
|
116
|
+
return {
|
|
117
|
+
ok: false,
|
|
118
|
+
node: failure.node,
|
|
119
|
+
reason: failure.reason
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
if (state.substitutionCount !== 1) return {
|
|
123
|
+
ok: false,
|
|
124
|
+
node: objectLiteral,
|
|
125
|
+
reason: `The payload parameter \`${parameterName}\` must appear exactly once in the returned object, but appears ${state.substitutionCount} times.`
|
|
126
|
+
};
|
|
127
|
+
return {
|
|
128
|
+
ok: true,
|
|
129
|
+
typeSource: objectType
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/analysis/read-map-operation.ts
|
|
134
|
+
var readMapOperation = (operator) => {
|
|
135
|
+
const [callback] = operator.arguments;
|
|
136
|
+
if (operator.arguments.length !== 1 || callback === void 0 || !(isArrowFunction(callback) || isFunctionExpression(callback))) return {
|
|
137
|
+
ok: false,
|
|
138
|
+
node: operator,
|
|
139
|
+
reason: "The `map` operator must take a single arrow or function expression."
|
|
140
|
+
};
|
|
141
|
+
const [parameter] = callback.parameters;
|
|
142
|
+
if (callback.parameters.length !== 1 || parameter === void 0 || !isIdentifier(parameter.name)) return {
|
|
143
|
+
ok: false,
|
|
144
|
+
node: callback,
|
|
145
|
+
reason: "The `map` callback must take exactly one plain parameter."
|
|
146
|
+
};
|
|
147
|
+
const returnExpression = resolveSoleReturnExpression(callback.body);
|
|
148
|
+
if (returnExpression === void 0 || !isObjectLiteralExpression(returnExpression)) return {
|
|
149
|
+
ok: false,
|
|
150
|
+
node: callback,
|
|
151
|
+
reason: "The `map` callback must return an object literal."
|
|
152
|
+
};
|
|
153
|
+
const synthesis = synthesizeGenericObjectType(returnExpression, parameter.name.text, WRAPPED_RESULT_SUBSTITUTION);
|
|
154
|
+
if (!synthesis.ok) return {
|
|
155
|
+
ok: false,
|
|
156
|
+
node: synthesis.node,
|
|
157
|
+
reason: synthesis.reason
|
|
158
|
+
};
|
|
159
|
+
return {
|
|
160
|
+
ok: true,
|
|
161
|
+
operation: {
|
|
162
|
+
parameterName: parameter.name.text,
|
|
163
|
+
returnExpression
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/analysis/open-source-file.ts
|
|
169
|
+
var sharedApi;
|
|
170
|
+
/**
|
|
171
|
+
* The returned checker belongs to the snapshot opened for this file. Opening the next file
|
|
172
|
+
* replaces that snapshot, so finish every checker query before calling this again.
|
|
173
|
+
*/
|
|
174
|
+
var openSourceFile = (filePath) => {
|
|
175
|
+
sharedApi ??= new API();
|
|
176
|
+
sharedApi.updateSnapshot({ closeFiles: [filePath] });
|
|
177
|
+
const project = sharedApi.updateSnapshot({
|
|
178
|
+
openFiles: [filePath],
|
|
179
|
+
fileChanges: { changed: [filePath] }
|
|
180
|
+
}).getDefaultProjectForFile(filePath);
|
|
181
|
+
const sourceFile = project?.program.getSourceFile(filePath);
|
|
182
|
+
if (project === void 0 || sourceFile === void 0) throw new Error(`Unable to parse source file: ${filePath}`);
|
|
183
|
+
return {
|
|
184
|
+
sourceFile,
|
|
185
|
+
checker: project.checker
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
//#endregion
|
|
189
|
+
//#region src/analysis/parse-source-file.ts
|
|
190
|
+
var parseSourceFile = (filePath) => openSourceFile(filePath).sourceFile;
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region src/analysis/resolve-module-origin.ts
|
|
193
|
+
var NODE_MODULES_DIRECTORY_NAME = "node_modules";
|
|
194
|
+
var TYPESCRIPT_SOURCE_EXTENSIONS = [".ts", ".tsx"];
|
|
195
|
+
var UNRESOLVED_ENTRY_ERROR_CODES = /* @__PURE__ */ new Set(["MODULE_NOT_FOUND", "ERR_PACKAGE_PATH_NOT_EXPORTED"]);
|
|
196
|
+
var DECLARATION_FILE_EXTENSIONS = [
|
|
197
|
+
".d.ts",
|
|
198
|
+
".d.mts",
|
|
199
|
+
".d.cts"
|
|
200
|
+
];
|
|
201
|
+
var isTypeScriptSourceFile = (filePath) => TYPESCRIPT_SOURCE_EXTENSIONS.some((extension) => filePath.endsWith(extension)) && !DECLARATION_FILE_EXTENSIONS.some((extension) => filePath.endsWith(extension));
|
|
202
|
+
var isInsideNodeModules = (filePath) => filePath.split(/[/]/).includes(NODE_MODULES_DIRECTORY_NAME);
|
|
203
|
+
var readPackageName = (moduleSpecifierText) => {
|
|
204
|
+
const segments = moduleSpecifierText.split("/");
|
|
205
|
+
return moduleSpecifierText.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
|
|
206
|
+
};
|
|
207
|
+
var findInstalledPackageDirectory = (fromFilePath, packageName) => {
|
|
208
|
+
let directory = dirname(fromFilePath);
|
|
209
|
+
for (;;) {
|
|
210
|
+
const candidate = join(directory, NODE_MODULES_DIRECTORY_NAME, packageName);
|
|
211
|
+
if (existsSync(candidate)) return candidate;
|
|
212
|
+
const parent = dirname(directory);
|
|
213
|
+
if (parent === directory) return;
|
|
214
|
+
directory = parent;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
var resolveRelativeModule = (fromFilePath, moduleSpecifierText) => {
|
|
218
|
+
const base = resolve(dirname(fromFilePath), moduleSpecifierText);
|
|
219
|
+
const filePath = [
|
|
220
|
+
`${base}.ts`,
|
|
221
|
+
`${base}.tsx`,
|
|
222
|
+
resolve(base, "index.ts")
|
|
223
|
+
].find((candidate) => existsSync(candidate));
|
|
224
|
+
return filePath === void 0 ? void 0 : {
|
|
225
|
+
kind: "source-file",
|
|
226
|
+
filePath
|
|
227
|
+
};
|
|
228
|
+
};
|
|
229
|
+
var resolveWorkspacePackageEntry = (fromFilePath, moduleSpecifierText) => {
|
|
230
|
+
try {
|
|
231
|
+
return createRequire(fromFilePath).resolve(moduleSpecifierText);
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (error instanceof Error && "code" in error && UNRESOLVED_ENTRY_ERROR_CODES.has(error.code)) return;
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
/**
|
|
238
|
+
* A bare specifier is a package when the installed copy lives in a `node_modules` directory once
|
|
239
|
+
* symlinks are followed, or when its entry point is a declaration or JavaScript file. Only a
|
|
240
|
+
* workspace library whose entry point is TypeScript source (a symlinked workspace package) can be
|
|
241
|
+
* read, so it resolves to that source file. Anything that does not resolve at all is `undefined`.
|
|
242
|
+
*/
|
|
243
|
+
var resolveBareModule = (fromFilePath, moduleSpecifierText) => {
|
|
244
|
+
const packageName = readPackageName(moduleSpecifierText);
|
|
245
|
+
const packageDirectory = packageName === void 0 ? void 0 : findInstalledPackageDirectory(fromFilePath, packageName);
|
|
246
|
+
if (packageDirectory === void 0) return;
|
|
247
|
+
if (isInsideNodeModules(realpathSync(packageDirectory))) return { kind: "package" };
|
|
248
|
+
const entryPath = resolveWorkspacePackageEntry(fromFilePath, moduleSpecifierText);
|
|
249
|
+
if (entryPath === void 0) return;
|
|
250
|
+
return isTypeScriptSourceFile(entryPath) && !isInsideNodeModules(entryPath) ? {
|
|
251
|
+
kind: "source-file",
|
|
252
|
+
filePath: entryPath
|
|
253
|
+
} : { kind: "package" };
|
|
254
|
+
};
|
|
255
|
+
var resolveModuleOrigin = (fromFilePath, moduleSpecifierText) => moduleSpecifierText.startsWith(".") ? resolveRelativeModule(fromFilePath, moduleSpecifierText) : resolveBareModule(fromFilePath, moduleSpecifierText);
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region src/analysis/resolve-type-declaration.ts
|
|
258
|
+
var parsedFilesByPath = /* @__PURE__ */ new Map();
|
|
259
|
+
/**
|
|
260
|
+
* Each analysis entry point starts from an empty cache, so a long-running watch session never
|
|
261
|
+
* resolves a class from a file version that has since changed.
|
|
262
|
+
*/
|
|
263
|
+
var clearParsedFileCache = () => {
|
|
264
|
+
parsedFilesByPath.clear();
|
|
265
|
+
};
|
|
266
|
+
var parseFile = (filePath) => {
|
|
267
|
+
const cached = parsedFilesByPath.get(filePath);
|
|
268
|
+
if (cached !== void 0) return cached;
|
|
269
|
+
const sourceFile = parseSourceFile(filePath);
|
|
270
|
+
parsedFilesByPath.set(filePath, sourceFile);
|
|
271
|
+
return sourceFile;
|
|
272
|
+
};
|
|
273
|
+
var findExportedDeclaration = (sourceFile, name) => sourceFile.statements.find((statement) => isClassDeclaration(statement) && statement.name?.text === name);
|
|
274
|
+
var findImportSource = (sourceFile, localName) => {
|
|
275
|
+
for (const statement of sourceFile.statements) {
|
|
276
|
+
if (!isImportDeclaration(statement) || !isStringLiteralLikeNode(statement.moduleSpecifier)) continue;
|
|
277
|
+
const namedBindings = statement.importClause?.namedBindings;
|
|
278
|
+
if (namedBindings === void 0 || !isNamedImports(namedBindings)) continue;
|
|
279
|
+
const element = namedBindings.elements.find((candidate) => candidate.name.text === localName);
|
|
280
|
+
if (element !== void 0) return {
|
|
281
|
+
moduleSpecifierText: statement.moduleSpecifier.text,
|
|
282
|
+
importedName: element.propertyName?.text ?? element.name.text
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
var findReExportSource = (sourceFile, name) => {
|
|
287
|
+
for (const statement of sourceFile.statements) {
|
|
288
|
+
if (!isExportDeclaration(statement) || statement.moduleSpecifier === void 0 || !isStringLiteralLikeNode(statement.moduleSpecifier)) continue;
|
|
289
|
+
if (statement.exportClause === void 0) return statement.moduleSpecifier.text;
|
|
290
|
+
if (isNamedExports(statement.exportClause) && statement.exportClause.elements.some((element) => (element.propertyName?.text ?? element.name.text) === name)) return statement.moduleSpecifier.text;
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
var resolveImportedClassOrigin = (name, moduleSpecifierText, fromFilePath, visited) => {
|
|
294
|
+
const moduleOrigin = resolveModuleOrigin(fromFilePath, moduleSpecifierText);
|
|
295
|
+
if (moduleOrigin === void 0) return;
|
|
296
|
+
if (moduleOrigin.kind === "package") return {
|
|
297
|
+
kind: "package",
|
|
298
|
+
moduleSpecifierText
|
|
299
|
+
};
|
|
300
|
+
const origin = resolveOrigin(name, parseFile(moduleOrigin.filePath), moduleOrigin.filePath, visited);
|
|
301
|
+
return origin.kind === "unresolved" ? void 0 : origin;
|
|
302
|
+
};
|
|
303
|
+
var resolveOrigin = (name, fromSourceFile, fromFilePath, visited) => {
|
|
304
|
+
if (visited.has(fromFilePath)) return { kind: "unresolved" };
|
|
305
|
+
visited.add(fromFilePath);
|
|
306
|
+
const direct = findExportedDeclaration(fromSourceFile, name);
|
|
307
|
+
if (direct !== void 0) return {
|
|
308
|
+
kind: "source",
|
|
309
|
+
resolved: {
|
|
310
|
+
classDeclaration: direct,
|
|
311
|
+
sourceFile: fromSourceFile,
|
|
312
|
+
filePath: fromFilePath
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
const importSource = findImportSource(fromSourceFile, name);
|
|
316
|
+
const imported = importSource === void 0 ? void 0 : resolveImportedClassOrigin(importSource.importedName, importSource.moduleSpecifierText, fromFilePath, visited);
|
|
317
|
+
if (imported !== void 0) return imported;
|
|
318
|
+
const reExportModuleSpecifierText = findReExportSource(fromSourceFile, name);
|
|
319
|
+
return (reExportModuleSpecifierText === void 0 ? void 0 : resolveImportedClassOrigin(name, reExportModuleSpecifierText, fromFilePath, visited)) ?? { kind: "unresolved" };
|
|
320
|
+
};
|
|
321
|
+
/**
|
|
322
|
+
* Follows imports and re-exports from `fromSourceFile` to where the class named `name` comes
|
|
323
|
+
* from: a TypeScript class declaration that can be read, a package that has no readable source,
|
|
324
|
+
* or nowhere (the import does not resolve, or the name is not declared there).
|
|
325
|
+
*/
|
|
326
|
+
var resolveClassOrigin = (name, fromSourceFile, fromFilePath) => resolveOrigin(name, fromSourceFile, fromFilePath, /* @__PURE__ */ new Set());
|
|
327
|
+
var resolveClassDeclaration = (name, fromSourceFile, fromFilePath) => {
|
|
328
|
+
const origin = resolveClassOrigin(name, fromSourceFile, fromFilePath);
|
|
329
|
+
return origin.kind === "source" ? origin.resolved : void 0;
|
|
330
|
+
};
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/analysis/read-pipe-operator.ts
|
|
333
|
+
var RXJS_MODULE_SPECIFIERS = ["rxjs", "rxjs/operators"];
|
|
334
|
+
var MAP_OPERATOR_NAME = "map";
|
|
335
|
+
var SHAPE_NEUTRAL_OPERATOR_NAMES = [
|
|
336
|
+
"tap",
|
|
337
|
+
"timeout",
|
|
338
|
+
"finalize"
|
|
339
|
+
];
|
|
340
|
+
var readPipeOperator = (operator, sourceFile) => {
|
|
341
|
+
if (!isCallExpression(operator) || !isIdentifier(operator.expression)) return {
|
|
342
|
+
ok: false,
|
|
343
|
+
node: operator,
|
|
344
|
+
reason: "Pipe operators must be calls of operators imported by name from rxjs."
|
|
345
|
+
};
|
|
346
|
+
const importSource = findImportSource(sourceFile, operator.expression.text);
|
|
347
|
+
if (importSource === void 0 || !RXJS_MODULE_SPECIFIERS.includes(importSource.moduleSpecifierText)) return {
|
|
348
|
+
ok: false,
|
|
349
|
+
node: operator,
|
|
350
|
+
reason: `Operator \`${operator.expression.text}\` is not imported from rxjs, so its effect on the response shape is unknown.`
|
|
351
|
+
};
|
|
352
|
+
if (importSource.importedName === MAP_OPERATOR_NAME) return readMapOperation(operator);
|
|
353
|
+
if (SHAPE_NEUTRAL_OPERATOR_NAMES.includes(importSource.importedName)) return {
|
|
354
|
+
ok: true,
|
|
355
|
+
operation: void 0
|
|
356
|
+
};
|
|
357
|
+
return {
|
|
358
|
+
ok: false,
|
|
359
|
+
node: operator,
|
|
360
|
+
reason: `Operator \`${importSource.importedName}\` changes or hides the response shape.`
|
|
361
|
+
};
|
|
362
|
+
};
|
|
363
|
+
//#endregion
|
|
364
|
+
//#region src/analysis/contains-return-statement.ts
|
|
365
|
+
var isNestedFunctionScope = (node) => isArrowFunction(node) || isFunctionExpression(node) || isFunctionDeclaration(node) || isMethodDeclaration(node) || isClassDeclaration(node) || isClassExpression(node);
|
|
366
|
+
var containsReturnStatement = (node) => {
|
|
367
|
+
if (isReturnStatement(node)) return true;
|
|
368
|
+
if (isNestedFunctionScope(node)) return false;
|
|
369
|
+
let found = false;
|
|
370
|
+
node.forEachChild((child) => {
|
|
371
|
+
if (containsReturnStatement(child)) found = true;
|
|
372
|
+
});
|
|
373
|
+
return found;
|
|
374
|
+
};
|
|
375
|
+
//#endregion
|
|
376
|
+
//#region src/analysis/resolve-intercept-return-expression.ts
|
|
377
|
+
/**
|
|
378
|
+
* Any statements may precede the final `return` (logger setup, `const startedAt = Date.now()`),
|
|
379
|
+
* but none of them may return early, since the response shape would then depend on the branch.
|
|
380
|
+
* A returned identifier resolves to the initializer of the `const` declared with that name.
|
|
381
|
+
*/
|
|
382
|
+
var resolveInterceptReturnExpression = (body) => {
|
|
383
|
+
const finalStatement = body.statements[body.statements.length - 1];
|
|
384
|
+
if (finalStatement === void 0 || !isReturnStatement(finalStatement) || finalStatement.expression === void 0) return {
|
|
385
|
+
ok: false,
|
|
386
|
+
node: finalStatement ?? body,
|
|
387
|
+
reason: "The last statement of intercept() must be a `return` statement with a value."
|
|
388
|
+
};
|
|
389
|
+
const localDeclarations = /* @__PURE__ */ new Map();
|
|
390
|
+
for (const statement of body.statements) {
|
|
391
|
+
if (statement === finalStatement) continue;
|
|
392
|
+
if (containsReturnStatement(statement)) return {
|
|
393
|
+
ok: false,
|
|
394
|
+
node: statement,
|
|
395
|
+
reason: "intercept() returns before its last statement, so the response shape is ambiguous."
|
|
396
|
+
};
|
|
397
|
+
if (isVariableStatement(statement)) {
|
|
398
|
+
for (const declaration of statement.declarationList.declarations) if (isIdentifier(declaration.name) && declaration.initializer !== void 0) localDeclarations.set(declaration.name.text, declaration.initializer);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
const returned = unwrapParenthesizedExpression(finalStatement.expression);
|
|
402
|
+
if (!isIdentifier(returned)) return {
|
|
403
|
+
ok: true,
|
|
404
|
+
expression: returned
|
|
405
|
+
};
|
|
406
|
+
const initializer = localDeclarations.get(returned.text);
|
|
407
|
+
return initializer === void 0 ? {
|
|
408
|
+
ok: false,
|
|
409
|
+
node: returned,
|
|
410
|
+
reason: `\`${returned.text}\` is not a local \`const\` initialized inside intercept().`
|
|
411
|
+
} : {
|
|
412
|
+
ok: true,
|
|
413
|
+
expression: unwrapParenthesizedExpression(initializer)
|
|
414
|
+
};
|
|
415
|
+
};
|
|
416
|
+
//#endregion
|
|
417
|
+
//#region src/analysis/analyze-intercept-method.ts
|
|
418
|
+
var HANDLE_MEMBER_NAME = "handle";
|
|
419
|
+
var PIPE_MEMBER_NAME = "pipe";
|
|
420
|
+
var CALL_HANDLER_PARAMETER_INDEX = 1;
|
|
421
|
+
var isHandleCall = (expression, callHandlerName) => isCallExpression(expression) && expression.arguments.length === 0 && isPropertyAccessExpression(expression.expression) && expression.expression.name.text === HANDLE_MEMBER_NAME && isIdentifier(expression.expression.expression) && expression.expression.expression.text === callHandlerName;
|
|
422
|
+
var analyzeInterceptMethod = (method, sourceFile) => {
|
|
423
|
+
const callHandler = method.parameters[CALL_HANDLER_PARAMETER_INDEX];
|
|
424
|
+
if (method.body === void 0 || callHandler === void 0 || !isIdentifier(callHandler.name)) return {
|
|
425
|
+
ok: false,
|
|
426
|
+
node: method,
|
|
427
|
+
reason: "intercept() must have a body and name its CallHandler parameter."
|
|
428
|
+
};
|
|
429
|
+
const returned = resolveInterceptReturnExpression(method.body);
|
|
430
|
+
if (!returned.ok) return returned;
|
|
431
|
+
const callHandlerName = callHandler.name.text;
|
|
432
|
+
const expression = returned.expression;
|
|
433
|
+
if (isHandleCall(expression, callHandlerName)) return {
|
|
434
|
+
ok: true,
|
|
435
|
+
shape: { operations: [] }
|
|
436
|
+
};
|
|
437
|
+
if (!isCallExpression(expression) || !isPropertyAccessExpression(expression.expression) || expression.expression.name.text !== PIPE_MEMBER_NAME || !isHandleCall(expression.expression.expression, callHandlerName)) return {
|
|
438
|
+
ok: false,
|
|
439
|
+
node: expression,
|
|
440
|
+
reason: `intercept() must return \`${callHandlerName}.handle()\`, optionally piped through rxjs operators.`
|
|
441
|
+
};
|
|
442
|
+
const operations = [];
|
|
443
|
+
for (const operator of expression.arguments) {
|
|
444
|
+
const read = readPipeOperator(operator, sourceFile);
|
|
445
|
+
if (!read.ok) return read;
|
|
446
|
+
if (read.operation !== void 0) operations.push(read.operation);
|
|
447
|
+
}
|
|
448
|
+
return {
|
|
449
|
+
ok: true,
|
|
450
|
+
shape: { operations }
|
|
451
|
+
};
|
|
452
|
+
};
|
|
453
|
+
//#endregion
|
|
454
|
+
//#region src/analysis/analyze-interceptor-class.ts
|
|
455
|
+
var INTERCEPT_METHOD_NAME = "intercept";
|
|
456
|
+
var findInterceptMethod = (members) => members.find((member) => isMethodDeclaration(member) && isIdentifier(member.name) && member.name.text === INTERCEPT_METHOD_NAME);
|
|
457
|
+
var analyzeInterceptorClass = (resolved) => {
|
|
458
|
+
const interceptMethod = findInterceptMethod(resolved.classDeclaration.members);
|
|
459
|
+
if (interceptMethod === void 0) return {
|
|
460
|
+
ok: false,
|
|
461
|
+
location: resolved.classDeclaration,
|
|
462
|
+
found: void 0,
|
|
463
|
+
reason: "The class declares no intercept() method of its own."
|
|
464
|
+
};
|
|
465
|
+
const analysis = analyzeInterceptMethod(interceptMethod, resolved.sourceFile);
|
|
466
|
+
return analysis.ok ? analysis : {
|
|
467
|
+
ok: false,
|
|
468
|
+
location: interceptMethod,
|
|
469
|
+
found: analysis.node.getText(),
|
|
470
|
+
reason: analysis.reason
|
|
471
|
+
};
|
|
472
|
+
};
|
|
473
|
+
//#endregion
|
|
474
|
+
//#region src/models/declared-interceptor-reference.ts
|
|
475
|
+
var DECLARED_INTERCEPTOR_PREFIX = "__DeclaredInterceptor_";
|
|
476
|
+
var declaredInterceptorReference = (interceptorName) => `${DECLARED_INTERCEPTOR_PREFIX}${interceptorName}`;
|
|
477
|
+
//#endregion
|
|
478
|
+
//#region src/analysis/compose-wrapper-type-source.ts
|
|
479
|
+
var applyShape = (typeSource, link) => {
|
|
480
|
+
let composed = typeSource;
|
|
481
|
+
for (const operation of link.shape.operations) {
|
|
482
|
+
const synthesis = synthesizeGenericObjectType(operation.returnExpression, operation.parameterName, composed);
|
|
483
|
+
if (!synthesis.ok) throw new Error(`[nestbridge] An interceptor shape that was validated can no longer be typed: ${synthesis.reason}`);
|
|
484
|
+
composed = synthesis.typeSource;
|
|
485
|
+
}
|
|
486
|
+
return composed;
|
|
487
|
+
};
|
|
488
|
+
/**
|
|
489
|
+
* `links` run outermost first, so the type is built from the innermost interceptor outward,
|
|
490
|
+
* starting at the awaited server result. A declared alias with one type parameter wraps what is
|
|
491
|
+
* inside it, one with none replaces it, and an interceptor nobody can read turns what is inside
|
|
492
|
+
* it into `unknown`. Returns `undefined` when no interceptor changes the shape.
|
|
493
|
+
*/
|
|
494
|
+
var composeWrapperTypeSource = (links) => {
|
|
495
|
+
let typeSource = WRAPPED_RESULT_SUBSTITUTION;
|
|
496
|
+
let declaredInterceptors = [];
|
|
497
|
+
for (const link of [...links].reverse()) {
|
|
498
|
+
if (link.kind === "shape") {
|
|
499
|
+
typeSource = applyShape(typeSource, link);
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
if (link.kind === "unknown") {
|
|
503
|
+
typeSource = UNRESOLVED_WRAPPED_RESULT_TYPE_SOURCE;
|
|
504
|
+
declaredInterceptors = [];
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
const { name, typeParameterCount } = link.declaration;
|
|
508
|
+
const reference = declaredInterceptorReference(name);
|
|
509
|
+
if (typeParameterCount === 0) declaredInterceptors = [];
|
|
510
|
+
typeSource = typeParameterCount === 0 ? reference : `${reference}<${typeSource}>`;
|
|
511
|
+
declaredInterceptors = [name, ...declaredInterceptors];
|
|
512
|
+
}
|
|
513
|
+
if (typeSource === "Awaited<Result>") return;
|
|
514
|
+
const uniqueDeclaredInterceptors = [...new Set(declaredInterceptors)];
|
|
515
|
+
return uniqueDeclaredInterceptors.length === 0 ? { wrappedResultTypeSource: typeSource } : {
|
|
516
|
+
wrappedResultTypeSource: typeSource,
|
|
517
|
+
declaredInterceptors: uniqueDeclaredInterceptors
|
|
518
|
+
};
|
|
519
|
+
};
|
|
520
|
+
//#endregion
|
|
521
|
+
//#region src/analysis/node-location.ts
|
|
522
|
+
var locationOf = (sourceFile, node) => {
|
|
523
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
|
|
524
|
+
return {
|
|
525
|
+
line: line + 1,
|
|
526
|
+
column: character + 1
|
|
527
|
+
};
|
|
528
|
+
};
|
|
529
|
+
//#endregion
|
|
530
|
+
//#region src/analysis/create-interceptor-diagnostic.ts
|
|
531
|
+
var EXPECTED$3 = "An intercept() method that returns next.handle(), optionally piped through rxjs `map` operators that return object literals and the shape-neutral `tap`, `timeout` and `finalize` operators, registered as a class or `new Class()`. Routes under an interceptor that cannot be analyzed are declared as AbortablePromise<unknown>.";
|
|
532
|
+
var createInterceptorDiagnostic = (source) => {
|
|
533
|
+
const location = locationOf(source.sourceFile, source.location);
|
|
534
|
+
return {
|
|
535
|
+
code: "unsupported-interceptor",
|
|
536
|
+
title: "Unsupported interceptor.",
|
|
537
|
+
controllerName: source.controllerName,
|
|
538
|
+
memberName: source.memberName,
|
|
539
|
+
detail: source.detail,
|
|
540
|
+
found: source.found ?? source.location.getText(),
|
|
541
|
+
expected: EXPECTED$3,
|
|
542
|
+
filePath: source.filePath,
|
|
543
|
+
line: location.line,
|
|
544
|
+
column: location.column
|
|
545
|
+
};
|
|
546
|
+
};
|
|
547
|
+
//#endregion
|
|
5
548
|
//#region src/analysis/decorator-inspection.ts
|
|
6
549
|
var getDecorators = (node) => {
|
|
7
550
|
const decorators = node.modifiers?.filter(isDecorator);
|
|
@@ -12,6 +555,7 @@ var findDecorator = (node, decoratorName) => {
|
|
|
12
555
|
if (decorators === void 0) return;
|
|
13
556
|
return decorators.find((decorator) => decoratorNameOf(decorator) === decoratorName);
|
|
14
557
|
};
|
|
558
|
+
var findDecorators = (node, decoratorName) => (getDecorators(node) ?? []).filter((decorator) => decoratorNameOf(decorator) === decoratorName);
|
|
15
559
|
var hasAnyDecorator = (node) => getDecorators(node) !== void 0;
|
|
16
560
|
var findAnyDecorator = (node, decoratorNames) => {
|
|
17
561
|
const decorators = getDecorators(node);
|
|
@@ -44,6 +588,393 @@ var readStaticStringArgument = (decorator) => {
|
|
|
44
588
|
};
|
|
45
589
|
};
|
|
46
590
|
//#endregion
|
|
591
|
+
//#region src/analysis/read-module-option.ts
|
|
592
|
+
var MODULE_DECORATOR_NAME$1 = "Module";
|
|
593
|
+
var hasModuleDecorator = (classDeclaration) => findDecorator(classDeclaration, MODULE_DECORATOR_NAME$1) !== void 0;
|
|
594
|
+
var readModuleOption = (classDeclaration, optionName) => {
|
|
595
|
+
const moduleDecorator = findDecorator(classDeclaration, MODULE_DECORATOR_NAME$1);
|
|
596
|
+
if (moduleDecorator === void 0 || !isCallExpression(moduleDecorator.expression)) return;
|
|
597
|
+
const [moduleOptions] = moduleDecorator.expression.arguments;
|
|
598
|
+
if (moduleOptions === void 0 || !isObjectLiteralExpression(moduleOptions)) return;
|
|
599
|
+
return moduleOptions.properties.find((property) => isPropertyAssignment(property) && isIdentifier(property.name) && property.name.text === optionName);
|
|
600
|
+
};
|
|
601
|
+
//#endregion
|
|
602
|
+
//#region src/analysis/find-app-interceptor-provider-registrations.ts
|
|
603
|
+
var PROVIDERS_OPTION_NAME = "providers";
|
|
604
|
+
var PROVIDE_PROPERTY_NAME$1 = "provide";
|
|
605
|
+
var USE_CLASS_PROPERTY_NAME$1 = "useClass";
|
|
606
|
+
var APP_INTERCEPTOR_LOCAL_NAME = "APP_INTERCEPTOR";
|
|
607
|
+
var NEST_CORE_MODULE_SPECIFIER$2 = "@nestjs/core";
|
|
608
|
+
var UNSUPPORTED_PROVIDER_PROPERTY_NAMES = [
|
|
609
|
+
"useFactory",
|
|
610
|
+
"useValue",
|
|
611
|
+
"useExisting"
|
|
612
|
+
];
|
|
613
|
+
var findProperty = (provider, name) => provider.properties.find((property) => isPropertyAssignment(property) && isIdentifier(property.name) && property.name.text === name);
|
|
614
|
+
var findUnsupportedProviderPropertyName = (provider) => UNSUPPORTED_PROVIDER_PROPERTY_NAMES.find((name) => findProperty(provider, name) !== void 0);
|
|
615
|
+
/**
|
|
616
|
+
* Reads the `{ provide: APP_INTERCEPTOR, useClass: X }` providers of one module, in the order
|
|
617
|
+
* they are declared. Only `useClass` can be analyzed: `useFactory`, `useValue`, `useExisting` and
|
|
618
|
+
* spread providers are reported as problems because the interceptor behind them is unknown.
|
|
619
|
+
*/
|
|
620
|
+
var findAppInterceptorProviderRegistrations = (moduleClassDeclaration, moduleSourceFile, moduleFilePath) => {
|
|
621
|
+
const registrations = {
|
|
622
|
+
references: [],
|
|
623
|
+
problems: []
|
|
624
|
+
};
|
|
625
|
+
const providersProperty = readModuleOption(moduleClassDeclaration, PROVIDERS_OPTION_NAME);
|
|
626
|
+
const appInterceptorImportSource = findImportSource(moduleSourceFile, APP_INTERCEPTOR_LOCAL_NAME);
|
|
627
|
+
if (providersProperty === void 0 || appInterceptorImportSource === void 0 || appInterceptorImportSource.moduleSpecifierText !== NEST_CORE_MODULE_SPECIFIER$2) return registrations;
|
|
628
|
+
const reportProblem = (node, detail) => {
|
|
629
|
+
registrations.problems.push({
|
|
630
|
+
node,
|
|
631
|
+
sourceFile: moduleSourceFile,
|
|
632
|
+
filePath: moduleFilePath,
|
|
633
|
+
detail
|
|
634
|
+
});
|
|
635
|
+
};
|
|
636
|
+
if (!isArrayLiteralExpression(providersProperty.initializer)) {
|
|
637
|
+
reportProblem(providersProperty.initializer, "The `providers` of a module registering APP_INTERCEPTOR must be an array literal.");
|
|
638
|
+
return registrations;
|
|
639
|
+
}
|
|
640
|
+
for (const element of providersProperty.initializer.elements) {
|
|
641
|
+
if (isSpreadElement(element)) {
|
|
642
|
+
reportProblem(element, "Spread providers cannot be analyzed, so an APP_INTERCEPTOR provider inside them would be missed.");
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
if (!isObjectLiteralExpression(element)) continue;
|
|
646
|
+
const provideProperty = findProperty(element, PROVIDE_PROPERTY_NAME$1);
|
|
647
|
+
if (provideProperty === void 0 || !isIdentifier(provideProperty.initializer) || provideProperty.initializer.text !== APP_INTERCEPTOR_LOCAL_NAME) continue;
|
|
648
|
+
const unsupportedPropertyName = findUnsupportedProviderPropertyName(element);
|
|
649
|
+
if (unsupportedPropertyName !== void 0) {
|
|
650
|
+
reportProblem(element, `\`${unsupportedPropertyName}\` interceptor providers can't be analysed; use \`useClass\`.`);
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
const useClassProperty = findProperty(element, USE_CLASS_PROPERTY_NAME$1);
|
|
654
|
+
if (useClassProperty === void 0 || !isIdentifier(useClassProperty.initializer)) {
|
|
655
|
+
reportProblem(element, "An APP_INTERCEPTOR provider must state its interceptor as `useClass: InterceptorClass`.");
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
registrations.references.push({
|
|
659
|
+
className: useClassProperty.initializer.text,
|
|
660
|
+
node: useClassProperty.initializer,
|
|
661
|
+
sourceFile: moduleSourceFile,
|
|
662
|
+
filePath: moduleFilePath
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
return registrations;
|
|
666
|
+
};
|
|
667
|
+
//#endregion
|
|
668
|
+
//#region src/analysis/read-imported-modules.ts
|
|
669
|
+
var IMPORTS_OPTION_NAME = "imports";
|
|
670
|
+
/**
|
|
671
|
+
* Only plain class identifiers that resolve to a local `@Module()` class are followed. Dynamic
|
|
672
|
+
* modules such as `FooModule.forRoot()`, `forwardRef()` calls, spreads and package imports are
|
|
673
|
+
* skipped because their providers cannot be read statically.
|
|
674
|
+
*/
|
|
675
|
+
var readImportedModules = (module) => {
|
|
676
|
+
const importsProperty = readModuleOption(module.classDeclaration, IMPORTS_OPTION_NAME);
|
|
677
|
+
if (importsProperty === void 0 || !isArrayLiteralExpression(importsProperty.initializer)) return [];
|
|
678
|
+
const importedModules = [];
|
|
679
|
+
for (const element of importsProperty.initializer.elements) {
|
|
680
|
+
if (!isIdentifier(element)) continue;
|
|
681
|
+
const resolved = resolveClassDeclaration(element.text, module.sourceFile, module.filePath);
|
|
682
|
+
if (resolved !== void 0 && hasModuleDecorator(resolved.classDeclaration)) importedModules.push(resolved);
|
|
683
|
+
}
|
|
684
|
+
return importedModules;
|
|
685
|
+
};
|
|
686
|
+
//#endregion
|
|
687
|
+
//#region src/analysis/collect-module-interceptor-registrations.ts
|
|
688
|
+
/**
|
|
689
|
+
* Nest scans modules depth-first starting at the root module, inserting a module before the
|
|
690
|
+
* modules it imports, and a module reached twice keeps its first position. Registering the
|
|
691
|
+
* `APP_INTERCEPTOR` providers module by module, each module's providers before its imports,
|
|
692
|
+
* reproduces the order in which Nest adds them to the global interceptor list.
|
|
693
|
+
*/
|
|
694
|
+
var collectModuleInterceptorRegistrations = (rootModule, contributingFiles) => {
|
|
695
|
+
const registrations = {
|
|
696
|
+
references: [],
|
|
697
|
+
problems: []
|
|
698
|
+
};
|
|
699
|
+
const visitedModules = /* @__PURE__ */ new Set();
|
|
700
|
+
const visit = (module) => {
|
|
701
|
+
const moduleKey = `${module.filePath}#${module.classDeclaration.name?.text}`;
|
|
702
|
+
if (visitedModules.has(moduleKey)) return;
|
|
703
|
+
visitedModules.add(moduleKey);
|
|
704
|
+
contributingFiles.add(module.filePath);
|
|
705
|
+
const moduleRegistrations = findAppInterceptorProviderRegistrations(module.classDeclaration, module.sourceFile, module.filePath);
|
|
706
|
+
registrations.references.push(...moduleRegistrations.references);
|
|
707
|
+
registrations.problems.push(...moduleRegistrations.problems);
|
|
708
|
+
for (const importedModule of readImportedModules(module)) visit(importedModule);
|
|
709
|
+
};
|
|
710
|
+
visit(rootModule);
|
|
711
|
+
return registrations;
|
|
712
|
+
};
|
|
713
|
+
//#endregion
|
|
714
|
+
//#region src/analysis/find-bootstrap-interceptor-registrations.ts
|
|
715
|
+
var USE_GLOBAL_INTERCEPTORS_METHOD_NAME = "useGlobalInterceptors";
|
|
716
|
+
var collectUseGlobalInterceptorsCalls = (node, calls) => {
|
|
717
|
+
if (isCallExpression(node) && isPropertyAccessExpression(node.expression) && node.expression.name.text === USE_GLOBAL_INTERCEPTORS_METHOD_NAME) calls.push(node);
|
|
718
|
+
node.forEachChild((child) => {
|
|
719
|
+
collectUseGlobalInterceptorsCalls(child, calls);
|
|
720
|
+
});
|
|
721
|
+
};
|
|
722
|
+
/**
|
|
723
|
+
* Returned in registration order: `useGlobalInterceptors` concatenates onto a single global
|
|
724
|
+
* list, so a later call (or a later argument within one call) registers an interceptor that wraps
|
|
725
|
+
* closer to the raw handler result.
|
|
726
|
+
*/
|
|
727
|
+
var findBootstrapInterceptorRegistrations = (sourceFile, filePath) => {
|
|
728
|
+
const calls = [];
|
|
729
|
+
collectUseGlobalInterceptorsCalls(sourceFile, calls);
|
|
730
|
+
const registrations = {
|
|
731
|
+
references: [],
|
|
732
|
+
problems: []
|
|
733
|
+
};
|
|
734
|
+
for (const call of calls) for (const argument of call.arguments) {
|
|
735
|
+
if (isNewExpression(argument) && isIdentifier(argument.expression)) {
|
|
736
|
+
registrations.references.push({
|
|
737
|
+
className: argument.expression.text,
|
|
738
|
+
node: argument,
|
|
739
|
+
sourceFile,
|
|
740
|
+
filePath
|
|
741
|
+
});
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
744
|
+
registrations.problems.push({
|
|
745
|
+
node: argument,
|
|
746
|
+
sourceFile,
|
|
747
|
+
filePath,
|
|
748
|
+
detail: "Global interceptors must be registered as `new InterceptorClass()` to be analyzed."
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
return registrations;
|
|
752
|
+
};
|
|
753
|
+
//#endregion
|
|
754
|
+
//#region src/analysis/find-root-module-class-name.ts
|
|
755
|
+
var NEST_FACTORY_LOCAL_NAME = "NestFactory";
|
|
756
|
+
var NEST_FACTORY_CREATE_METHOD_NAME = "create";
|
|
757
|
+
var NEST_CORE_MODULE_SPECIFIER$1 = "@nestjs/core";
|
|
758
|
+
var collectNestFactoryCreateCalls = (node, calls) => {
|
|
759
|
+
if (isCallExpression(node) && isPropertyAccessExpression(node.expression) && isIdentifier(node.expression.expression) && node.expression.expression.text === NEST_FACTORY_LOCAL_NAME && node.expression.name.text === NEST_FACTORY_CREATE_METHOD_NAME) calls.push(node);
|
|
760
|
+
node.forEachChild((child) => {
|
|
761
|
+
collectNestFactoryCreateCalls(child, calls);
|
|
762
|
+
});
|
|
763
|
+
};
|
|
764
|
+
var findRootModuleClassName = (sourceFile) => {
|
|
765
|
+
const nestFactoryImportSource = findImportSource(sourceFile, NEST_FACTORY_LOCAL_NAME);
|
|
766
|
+
if (nestFactoryImportSource === void 0 || nestFactoryImportSource.moduleSpecifierText !== NEST_CORE_MODULE_SPECIFIER$1) return;
|
|
767
|
+
const calls = [];
|
|
768
|
+
collectNestFactoryCreateCalls(sourceFile, calls);
|
|
769
|
+
if (calls.length !== 1) return;
|
|
770
|
+
const [call] = calls;
|
|
771
|
+
if (call === void 0) return;
|
|
772
|
+
const [moduleArgument] = call.arguments;
|
|
773
|
+
return moduleArgument !== void 0 && isIdentifier(moduleArgument) ? moduleArgument.text : void 0;
|
|
774
|
+
};
|
|
775
|
+
//#endregion
|
|
776
|
+
//#region src/analysis/find-global-interceptor-registrations.ts
|
|
777
|
+
/**
|
|
778
|
+
* The global interceptors in the order Nest runs them, outermost first: the `APP_INTERCEPTOR`
|
|
779
|
+
* providers of the root module and of the local modules it imports, then the interceptors passed
|
|
780
|
+
* to `useGlobalInterceptors()`.
|
|
781
|
+
*
|
|
782
|
+
* Verified against @nestjs/core 12.3.1: `NestFactory.create()` awaits `initialize()`, which calls
|
|
783
|
+
* `DependenciesScanner.applyApplicationProviders()` (nest-factory.js line 108) and pushes every
|
|
784
|
+
* `APP_INTERCEPTOR` instance onto the global list (scanner.js line 386,
|
|
785
|
+
* application-config.js line 60). `useGlobalInterceptors()` can only run once `create()` has
|
|
786
|
+
* returned, and it appends to the same list (application-config.js line 63). The first entry of
|
|
787
|
+
* the list is the outermost interceptor. Request- and transient-scoped `APP_INTERCEPTOR`
|
|
788
|
+
* providers are appended after all of them at request time and are not distinguished here.
|
|
789
|
+
*/
|
|
790
|
+
var findGlobalInterceptorRegistrations = (bootstrapFilePath, contributingFiles) => {
|
|
791
|
+
const bootstrapSourceFile = parseSourceFile(bootstrapFilePath);
|
|
792
|
+
contributingFiles.add(bootstrapFilePath);
|
|
793
|
+
const rootModuleClassName = findRootModuleClassName(bootstrapSourceFile);
|
|
794
|
+
const rootModule = rootModuleClassName === void 0 ? void 0 : resolveClassDeclaration(rootModuleClassName, bootstrapSourceFile, bootstrapFilePath);
|
|
795
|
+
const moduleRegistrations = rootModule === void 0 ? {
|
|
796
|
+
references: [],
|
|
797
|
+
problems: []
|
|
798
|
+
} : collectModuleInterceptorRegistrations(rootModule, contributingFiles);
|
|
799
|
+
const bootstrapRegistrations = findBootstrapInterceptorRegistrations(bootstrapSourceFile, bootstrapFilePath);
|
|
800
|
+
return {
|
|
801
|
+
references: [...moduleRegistrations.references, ...bootstrapRegistrations.references],
|
|
802
|
+
problems: [...moduleRegistrations.problems, ...bootstrapRegistrations.problems]
|
|
803
|
+
};
|
|
804
|
+
};
|
|
805
|
+
//#endregion
|
|
806
|
+
//#region src/analysis/find-use-interceptors-registrations.ts
|
|
807
|
+
var USE_INTERCEPTORS_DECORATOR_NAME = "UseInterceptors";
|
|
808
|
+
var NEST_COMMON_MODULE_SPECIFIER = "@nestjs/common";
|
|
809
|
+
/**
|
|
810
|
+
* Decorators are applied bottom-up and each one appends to the target's interceptor metadata, so
|
|
811
|
+
* stacked `@UseInterceptors()` decorators contribute in reverse source order.
|
|
812
|
+
*/
|
|
813
|
+
var findUseInterceptorsRegistrations = (target, sourceFile, filePath) => {
|
|
814
|
+
const registrations = {
|
|
815
|
+
references: [],
|
|
816
|
+
problems: []
|
|
817
|
+
};
|
|
818
|
+
const importSource = findImportSource(sourceFile, USE_INTERCEPTORS_DECORATOR_NAME);
|
|
819
|
+
if (importSource === void 0 || importSource.moduleSpecifierText !== NEST_COMMON_MODULE_SPECIFIER || importSource.importedName !== USE_INTERCEPTORS_DECORATOR_NAME) return registrations;
|
|
820
|
+
const decorators = findDecorators(target, USE_INTERCEPTORS_DECORATOR_NAME).reverse();
|
|
821
|
+
for (const decorator of decorators) {
|
|
822
|
+
if (!isCallExpression(decorator.expression)) continue;
|
|
823
|
+
for (const argument of decorator.expression.arguments) {
|
|
824
|
+
if (isIdentifier(argument)) {
|
|
825
|
+
registrations.references.push({
|
|
826
|
+
className: argument.text,
|
|
827
|
+
node: argument,
|
|
828
|
+
sourceFile,
|
|
829
|
+
filePath
|
|
830
|
+
});
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
if (isNewExpression(argument) && isIdentifier(argument.expression)) {
|
|
834
|
+
registrations.references.push({
|
|
835
|
+
className: argument.expression.text,
|
|
836
|
+
node: argument,
|
|
837
|
+
sourceFile,
|
|
838
|
+
filePath
|
|
839
|
+
});
|
|
840
|
+
continue;
|
|
841
|
+
}
|
|
842
|
+
registrations.problems.push({
|
|
843
|
+
node: argument,
|
|
844
|
+
sourceFile,
|
|
845
|
+
filePath,
|
|
846
|
+
detail: "@UseInterceptors() arguments must be interceptor classes or `new InterceptorClass()` to be analyzed."
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
return registrations;
|
|
851
|
+
};
|
|
852
|
+
//#endregion
|
|
853
|
+
//#region src/analysis/package-interceptor-shape.ts
|
|
854
|
+
/**
|
|
855
|
+
* An interceptor class that comes from a package has no TypeScript source to read, so it is
|
|
856
|
+
* assumed not to change the response shape. A package interceptor that does change it, such as
|
|
857
|
+
* `ClassSerializerInterceptor` with `@Exclude`, is not reflected in the generated types.
|
|
858
|
+
*/
|
|
859
|
+
var PACKAGE_INTERCEPTOR_SHAPE = { operations: [] };
|
|
860
|
+
//#endregion
|
|
861
|
+
//#region src/analysis/create-interceptor-analysis.ts
|
|
862
|
+
var REGISTRATION_SUBJECT = "(interceptors)";
|
|
863
|
+
var INTERCEPT_MEMBER_NAME = "intercept";
|
|
864
|
+
/**
|
|
865
|
+
* Resolves, for each JSON route, the interceptors that apply to it (global, then controller, then
|
|
866
|
+
* route, outermost first) and the response shape they give it. Every interceptor class is
|
|
867
|
+
* analyzed once and every problem is reported once, however many routes the interceptor reaches.
|
|
868
|
+
* Global interceptors are only read when the first JSON route asks for them.
|
|
869
|
+
*/
|
|
870
|
+
var createInterceptorAnalysis = (options) => {
|
|
871
|
+
const { bootstrapFilePath, diagnostics } = options;
|
|
872
|
+
const declarationsByName = new Map((options.declarations ?? []).map((declaration) => [declaration.name, declaration]));
|
|
873
|
+
const contributingFiles = /* @__PURE__ */ new Set();
|
|
874
|
+
const shapesByInterceptor = /* @__PURE__ */ new Map();
|
|
875
|
+
let globalRegistrations;
|
|
876
|
+
const reportRegistrationProblem = (problem) => {
|
|
877
|
+
diagnostics.push(createInterceptorDiagnostic({
|
|
878
|
+
controllerName: REGISTRATION_SUBJECT,
|
|
879
|
+
memberName: "",
|
|
880
|
+
detail: problem.detail,
|
|
881
|
+
location: problem.node,
|
|
882
|
+
sourceFile: problem.sourceFile,
|
|
883
|
+
filePath: problem.filePath
|
|
884
|
+
}));
|
|
885
|
+
};
|
|
886
|
+
const reportUnresolvedReference = (reference) => {
|
|
887
|
+
diagnostics.push(createInterceptorDiagnostic({
|
|
888
|
+
controllerName: reference.className,
|
|
889
|
+
memberName: "",
|
|
890
|
+
detail: `Interceptor \`${reference.className}\` does not resolve to a class declared in a local source file, so its effect on the response shape is unknown.`,
|
|
891
|
+
location: reference.node,
|
|
892
|
+
sourceFile: reference.sourceFile,
|
|
893
|
+
filePath: reference.filePath
|
|
894
|
+
}));
|
|
895
|
+
};
|
|
896
|
+
const resolveShape = (reference) => {
|
|
897
|
+
const origin = resolveClassOrigin(reference.className, reference.sourceFile, reference.filePath);
|
|
898
|
+
if (origin.kind === "package") return PACKAGE_INTERCEPTOR_SHAPE;
|
|
899
|
+
if (origin.kind === "unresolved") {
|
|
900
|
+
const location = locationOf(reference.sourceFile, reference.node);
|
|
901
|
+
const referenceKey = `${reference.filePath}:${location.line}:${location.column}`;
|
|
902
|
+
if (!shapesByInterceptor.has(referenceKey)) {
|
|
903
|
+
shapesByInterceptor.set(referenceKey, void 0);
|
|
904
|
+
reportUnresolvedReference(reference);
|
|
905
|
+
}
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
const { resolved } = origin;
|
|
909
|
+
contributingFiles.add(resolved.filePath);
|
|
910
|
+
const interceptorKey = `${resolved.filePath}#${resolved.classDeclaration.name?.text}`;
|
|
911
|
+
if (shapesByInterceptor.has(interceptorKey)) return shapesByInterceptor.get(interceptorKey);
|
|
912
|
+
const analysis = analyzeInterceptorClass(resolved);
|
|
913
|
+
if (!analysis.ok) diagnostics.push(createInterceptorDiagnostic({
|
|
914
|
+
controllerName: resolved.classDeclaration.name?.text ?? reference.className,
|
|
915
|
+
memberName: INTERCEPT_MEMBER_NAME,
|
|
916
|
+
detail: analysis.reason,
|
|
917
|
+
found: analysis.found,
|
|
918
|
+
location: analysis.location,
|
|
919
|
+
sourceFile: resolved.sourceFile,
|
|
920
|
+
filePath: resolved.filePath
|
|
921
|
+
}));
|
|
922
|
+
const shape = analysis.ok ? analysis.shape : void 0;
|
|
923
|
+
shapesByInterceptor.set(interceptorKey, shape);
|
|
924
|
+
return shape;
|
|
925
|
+
};
|
|
926
|
+
const exportedNameOf = (reference) => findImportSource(reference.sourceFile, reference.className)?.importedName ?? reference.className;
|
|
927
|
+
const resolveLink = (reference) => {
|
|
928
|
+
const declaration = declarationsByName.get(exportedNameOf(reference));
|
|
929
|
+
if (declaration !== void 0) return {
|
|
930
|
+
kind: "declared",
|
|
931
|
+
declaration
|
|
932
|
+
};
|
|
933
|
+
const shape = resolveShape(reference);
|
|
934
|
+
return shape === void 0 ? { kind: "unknown" } : {
|
|
935
|
+
kind: "shape",
|
|
936
|
+
shape
|
|
937
|
+
};
|
|
938
|
+
};
|
|
939
|
+
const readGlobalRegistrations = () => {
|
|
940
|
+
if (globalRegistrations === void 0) {
|
|
941
|
+
globalRegistrations = bootstrapFilePath === void 0 ? {
|
|
942
|
+
references: [],
|
|
943
|
+
problems: []
|
|
944
|
+
} : findGlobalInterceptorRegistrations(bootstrapFilePath, contributingFiles);
|
|
945
|
+
globalRegistrations.problems.forEach(reportRegistrationProblem);
|
|
946
|
+
}
|
|
947
|
+
return globalRegistrations;
|
|
948
|
+
};
|
|
949
|
+
const forController = (classDeclaration, sourceFile, filePath) => {
|
|
950
|
+
let controllerRegistrations;
|
|
951
|
+
const readControllerRegistrations = () => {
|
|
952
|
+
if (controllerRegistrations === void 0) {
|
|
953
|
+
controllerRegistrations = findUseInterceptorsRegistrations(classDeclaration, sourceFile, filePath);
|
|
954
|
+
controllerRegistrations.problems.forEach(reportRegistrationProblem);
|
|
955
|
+
}
|
|
956
|
+
return controllerRegistrations;
|
|
957
|
+
};
|
|
958
|
+
const responseWrapperOf = (method) => {
|
|
959
|
+
const methodRegistrations = findUseInterceptorsRegistrations(method, sourceFile, filePath);
|
|
960
|
+
methodRegistrations.problems.forEach(reportRegistrationProblem);
|
|
961
|
+
const chain = [
|
|
962
|
+
readGlobalRegistrations(),
|
|
963
|
+
readControllerRegistrations(),
|
|
964
|
+
methodRegistrations
|
|
965
|
+
];
|
|
966
|
+
const links = chain.flatMap(({ references }) => references.map(resolveLink));
|
|
967
|
+
if (chain.some(({ problems }) => problems.length > 0)) return { wrappedResultTypeSource: UNRESOLVED_WRAPPED_RESULT_TYPE_SOURCE };
|
|
968
|
+
return composeWrapperTypeSource(links);
|
|
969
|
+
};
|
|
970
|
+
return { responseWrapperOf };
|
|
971
|
+
};
|
|
972
|
+
return {
|
|
973
|
+
forController,
|
|
974
|
+
contributingFiles: () => [...contributingFiles]
|
|
975
|
+
};
|
|
976
|
+
};
|
|
977
|
+
//#endregion
|
|
47
978
|
//#region src/models/graphql-operation-kind.ts
|
|
48
979
|
var GRAPHQL_OPERATION_DECORATOR_NAMES = {
|
|
49
980
|
Query: "query",
|
|
@@ -69,23 +1000,14 @@ var MESSAGE_PATTERN_DECORATOR_NAMES = {
|
|
|
69
1000
|
var PAYLOAD_DECORATOR_NAME = "Payload";
|
|
70
1001
|
/**
|
|
71
1002
|
* Nest passes the payload to the `@Payload()` parameter. Without decorators it passes it as the
|
|
72
|
-
* first argument; once any parameter is decorated (`@Ctx()`, a custom decorator), undecorated
|
|
73
|
-
* parameters receive nothing, so the handler takes no payload.
|
|
74
|
-
*/
|
|
75
|
-
var findPayloadParameterIndex = (method) => {
|
|
76
|
-
const payloadIndex = method.parameters.findIndex((parameter) => findDecorator(parameter, PAYLOAD_DECORATOR_NAME) !== void 0);
|
|
77
|
-
if (payloadIndex !== -1) return payloadIndex;
|
|
78
|
-
if (method.parameters.length === 0 || method.parameters.some(hasAnyDecorator)) return null;
|
|
79
|
-
return 0;
|
|
80
|
-
};
|
|
81
|
-
//#endregion
|
|
82
|
-
//#region src/analysis/node-location.ts
|
|
83
|
-
var locationOf = (sourceFile, node) => {
|
|
84
|
-
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
|
|
85
|
-
return {
|
|
86
|
-
line: line + 1,
|
|
87
|
-
column: character + 1
|
|
88
|
-
};
|
|
1003
|
+
* first argument; once any parameter is decorated (`@Ctx()`, a custom decorator), undecorated
|
|
1004
|
+
* parameters receive nothing, so the handler takes no payload.
|
|
1005
|
+
*/
|
|
1006
|
+
var findPayloadParameterIndex = (method) => {
|
|
1007
|
+
const payloadIndex = method.parameters.findIndex((parameter) => findDecorator(parameter, PAYLOAD_DECORATOR_NAME) !== void 0);
|
|
1008
|
+
if (payloadIndex !== -1) return payloadIndex;
|
|
1009
|
+
if (method.parameters.length === 0 || method.parameters.some(hasAnyDecorator)) return null;
|
|
1010
|
+
return 0;
|
|
89
1011
|
};
|
|
90
1012
|
//#endregion
|
|
91
1013
|
//#region src/analysis/read-literal-type.ts
|
|
@@ -566,24 +1488,125 @@ var findControllerClasses = (sourceFile) => {
|
|
|
566
1488
|
return sourceFile.statements.filter((statement) => isClassDeclaration(statement) && findDecorator(statement, "Controller") !== void 0);
|
|
567
1489
|
};
|
|
568
1490
|
//#endregion
|
|
569
|
-
//#region src/analysis/
|
|
570
|
-
var
|
|
1491
|
+
//#region src/analysis/interceptor-declaration-file-names.ts
|
|
1492
|
+
var INTERCEPTOR_DECLARATION_FILE_NAMES = ["nestbridge.d.ts", "nestbridge-env.d.ts"];
|
|
1493
|
+
//#endregion
|
|
1494
|
+
//#region src/analysis/create-interceptor-declaration-diagnostic.ts
|
|
1495
|
+
var EXPECTED$2 = `Only exported \`type\` aliases with zero or one type parameter, named after an interceptor class, in ${INTERCEPTOR_DECLARATION_FILE_NAMES.join(" or ")}. Imports and declarations that are not exported are allowed as helpers.`;
|
|
1496
|
+
var createInterceptorDeclarationDiagnostic = (source) => {
|
|
1497
|
+
const location = locationOf(source.sourceFile, source.location);
|
|
1498
|
+
return {
|
|
1499
|
+
code: "invalid-interceptor-declaration",
|
|
1500
|
+
title: "Invalid interceptor declaration.",
|
|
1501
|
+
controllerName: source.subject,
|
|
1502
|
+
memberName: "",
|
|
1503
|
+
detail: source.detail,
|
|
1504
|
+
found: source.location.getText(),
|
|
1505
|
+
expected: EXPECTED$2,
|
|
1506
|
+
filePath: source.filePath,
|
|
1507
|
+
line: location.line,
|
|
1508
|
+
column: location.column
|
|
1509
|
+
};
|
|
1510
|
+
};
|
|
1511
|
+
//#endregion
|
|
1512
|
+
//#region src/analysis/read-interceptor-declarations.ts
|
|
1513
|
+
var ONLY_TYPE_ALIASES_DETAIL = "Only `type` aliases can be exported from an interceptor declarations file.";
|
|
1514
|
+
var isExported = (statement) => (statement.modifierFlags & ModifierFlags.Export) !== 0;
|
|
1515
|
+
var findUnsupportedStatement = (statement, fileName) => {
|
|
1516
|
+
if (isModuleDeclaration(statement)) {
|
|
1517
|
+
const subject = isIdentifier(statement.name) ? statement.name.text : statement.name.getText();
|
|
1518
|
+
if (isIdentifier(statement.name) && statement.name.text === "global") return {
|
|
1519
|
+
subject,
|
|
1520
|
+
detail: "`declare global` cannot be used in an interceptor declarations file."
|
|
1521
|
+
};
|
|
1522
|
+
if (!isIdentifier(statement.name)) return {
|
|
1523
|
+
subject,
|
|
1524
|
+
detail: "`declare module` cannot be used in an interceptor declarations file."
|
|
1525
|
+
};
|
|
1526
|
+
return isExported(statement) ? {
|
|
1527
|
+
subject,
|
|
1528
|
+
detail: "An exported namespace cannot be used as an interceptor declaration."
|
|
1529
|
+
} : void 0;
|
|
1530
|
+
}
|
|
1531
|
+
if (isExportAssignment(statement)) return {
|
|
1532
|
+
subject: fileName,
|
|
1533
|
+
detail: "`export =` and `export default` cannot declare an interceptor."
|
|
1534
|
+
};
|
|
1535
|
+
if (isExportDeclaration(statement)) return statement.moduleSpecifier === void 0 && statement.exportClause !== void 0 && isNamedExports(statement.exportClause) && statement.exportClause.elements.length === 0 ? void 0 : {
|
|
1536
|
+
subject: fileName,
|
|
1537
|
+
detail: "Re-exports and export lists cannot declare an interceptor; declare the alias with `export type Name = ...`."
|
|
1538
|
+
};
|
|
1539
|
+
if (isInterfaceDeclaration(statement) && isExported(statement)) return {
|
|
1540
|
+
subject: statement.name.text,
|
|
1541
|
+
detail: "An exported interface cannot be used as an interceptor declaration; use a `type` alias."
|
|
1542
|
+
};
|
|
1543
|
+
if ((isClassDeclaration(statement) || isEnumDeclaration(statement)) && isExported(statement)) return {
|
|
1544
|
+
subject: statement.name?.text ?? fileName,
|
|
1545
|
+
detail: ONLY_TYPE_ALIASES_DETAIL
|
|
1546
|
+
};
|
|
1547
|
+
if (isFunctionDeclaration(statement) && isExported(statement)) return {
|
|
1548
|
+
subject: statement.name?.text ?? fileName,
|
|
1549
|
+
detail: ONLY_TYPE_ALIASES_DETAIL
|
|
1550
|
+
};
|
|
1551
|
+
if (isVariableStatement(statement) && isExported(statement)) return {
|
|
1552
|
+
subject: fileName,
|
|
1553
|
+
detail: ONLY_TYPE_ALIASES_DETAIL
|
|
1554
|
+
};
|
|
1555
|
+
};
|
|
1556
|
+
var typeParameterCountOf = (alias) => alias.typeParameters?.length ?? 0;
|
|
1557
|
+
var readStatements = (sourceFile, filePath, registry) => {
|
|
1558
|
+
const diagnostics = [];
|
|
1559
|
+
const fileName = basename(filePath);
|
|
1560
|
+
const report = (statement, subject, detail) => {
|
|
1561
|
+
diagnostics.push(createInterceptorDeclarationDiagnostic({
|
|
1562
|
+
subject,
|
|
1563
|
+
detail,
|
|
1564
|
+
location: statement,
|
|
1565
|
+
sourceFile,
|
|
1566
|
+
filePath
|
|
1567
|
+
}));
|
|
1568
|
+
};
|
|
1569
|
+
for (const statement of sourceFile.statements) {
|
|
1570
|
+
if (isTypeAliasDeclaration(statement) && isExported(statement)) {
|
|
1571
|
+
const name = statement.name.text;
|
|
1572
|
+
const typeParameterCount = typeParameterCountOf(statement);
|
|
1573
|
+
if (typeParameterCount > 1) {
|
|
1574
|
+
report(statement, name, `\`${name}\` declares ${typeParameterCount} type parameters; an interceptor declaration takes none (a fixed shape) or one (the shape from inside).`);
|
|
1575
|
+
continue;
|
|
1576
|
+
}
|
|
1577
|
+
const earlier = registry.accepted.get(name);
|
|
1578
|
+
if (earlier !== void 0) {
|
|
1579
|
+
registry.conflicted.add(name);
|
|
1580
|
+
report(statement, name, `\`${name}\` is already declared in ${basename(earlier.filePath)}. Neither declaration is used; declare each interceptor in one file only.`);
|
|
1581
|
+
continue;
|
|
1582
|
+
}
|
|
1583
|
+
registry.accepted.set(name, {
|
|
1584
|
+
name,
|
|
1585
|
+
filePath,
|
|
1586
|
+
typeParameterCount: typeParameterCount === 0 ? 0 : 1
|
|
1587
|
+
});
|
|
1588
|
+
continue;
|
|
1589
|
+
}
|
|
1590
|
+
const unsupported = findUnsupportedStatement(statement, fileName);
|
|
1591
|
+
if (unsupported !== void 0) report(statement, unsupported.subject, unsupported.detail);
|
|
1592
|
+
}
|
|
1593
|
+
return diagnostics;
|
|
1594
|
+
};
|
|
571
1595
|
/**
|
|
572
|
-
*
|
|
573
|
-
*
|
|
1596
|
+
* Reads the exported type aliases of the given declaration files, in order; a missing file
|
|
1597
|
+
* declares nothing. Aliases that break the rules are reported and left out, and so is a name that
|
|
1598
|
+
* two files declare, so the interceptor they name is analyzed as if it had no declaration.
|
|
574
1599
|
*/
|
|
575
|
-
var
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
const sourceFile = project?.program.getSourceFile(filePath);
|
|
583
|
-
if (project === void 0 || sourceFile === void 0) throw new Error(`Unable to parse source file: ${filePath}`);
|
|
1600
|
+
var readInterceptorDeclarations = (filePaths) => {
|
|
1601
|
+
const registry = {
|
|
1602
|
+
accepted: /* @__PURE__ */ new Map(),
|
|
1603
|
+
conflicted: /* @__PURE__ */ new Set()
|
|
1604
|
+
};
|
|
1605
|
+
const diagnostics = [];
|
|
1606
|
+
for (const filePath of filePaths ?? []) if (existsSync(filePath)) diagnostics.push(...readStatements(parseSourceFile(filePath), filePath, registry));
|
|
584
1607
|
return {
|
|
585
|
-
|
|
586
|
-
|
|
1608
|
+
declarations: [...registry.accepted.values()].filter(({ name }) => !registry.conflicted.has(name)),
|
|
1609
|
+
diagnostics
|
|
587
1610
|
};
|
|
588
1611
|
};
|
|
589
1612
|
//#endregion
|
|
@@ -591,22 +1614,33 @@ var openSourceFile = (filePath) => {
|
|
|
591
1614
|
var analyzeControllers = (filePaths, options = {}) => {
|
|
592
1615
|
const diagnostics = [];
|
|
593
1616
|
const controllers = [];
|
|
1617
|
+
const interceptorDeclarations = readInterceptorDeclarations(options.interceptorDeclarationFilePaths);
|
|
1618
|
+
diagnostics.push(...interceptorDeclarations.diagnostics);
|
|
1619
|
+
const interceptors = createInterceptorAnalysis({
|
|
1620
|
+
bootstrapFilePath: options.bootstrapFilePath,
|
|
1621
|
+
diagnostics,
|
|
1622
|
+
declarations: interceptorDeclarations.declarations
|
|
1623
|
+
});
|
|
1624
|
+
clearParsedFileCache();
|
|
594
1625
|
for (const filePath of filePaths) {
|
|
595
1626
|
const { sourceFile, checker } = openSourceFile(filePath);
|
|
596
|
-
|
|
597
|
-
|
|
1627
|
+
const extractedControllers = findControllerClasses(sourceFile).map((classDeclaration) => ({
|
|
1628
|
+
classDeclaration,
|
|
1629
|
+
controller: extractControllerDefinition(classDeclaration, {
|
|
598
1630
|
sourceFile,
|
|
599
1631
|
filePath,
|
|
600
1632
|
checker,
|
|
601
1633
|
messagePatterns: options.messagePatterns ?? false,
|
|
602
1634
|
diagnostics
|
|
603
|
-
})
|
|
604
|
-
|
|
605
|
-
}
|
|
1635
|
+
})
|
|
1636
|
+
}));
|
|
1637
|
+
for (const { classDeclaration, controller } of extractedControllers) if (controller !== void 0) controllers.push(attachResponseWrappers(controller, classDeclaration, interceptors.forController(classDeclaration, sourceFile, filePath)));
|
|
606
1638
|
}
|
|
607
1639
|
return {
|
|
608
1640
|
controllers,
|
|
609
|
-
diagnostics
|
|
1641
|
+
diagnostics,
|
|
1642
|
+
interceptorFiles: interceptors.contributingFiles(),
|
|
1643
|
+
interceptorDeclarations: interceptorDeclarations.declarations
|
|
610
1644
|
};
|
|
611
1645
|
};
|
|
612
1646
|
//#endregion
|
|
@@ -745,72 +1779,6 @@ var extractResolverArgumentDefinition = (parameter, index, context) => {
|
|
|
745
1779
|
};
|
|
746
1780
|
};
|
|
747
1781
|
//#endregion
|
|
748
|
-
//#region src/analysis/parse-source-file.ts
|
|
749
|
-
var parseSourceFile = (filePath) => openSourceFile(filePath).sourceFile;
|
|
750
|
-
//#endregion
|
|
751
|
-
//#region src/analysis/resolve-type-declaration.ts
|
|
752
|
-
var parsedFilesByPath = /* @__PURE__ */ new Map();
|
|
753
|
-
var parseFile = (filePath) => {
|
|
754
|
-
const cached = parsedFilesByPath.get(filePath);
|
|
755
|
-
if (cached !== void 0) return cached;
|
|
756
|
-
const sourceFile = parseSourceFile(filePath);
|
|
757
|
-
parsedFilesByPath.set(filePath, sourceFile);
|
|
758
|
-
return sourceFile;
|
|
759
|
-
};
|
|
760
|
-
var resolveModuleFile = (fromFilePath, moduleSpecifierText) => {
|
|
761
|
-
if (!moduleSpecifierText.startsWith(".")) return;
|
|
762
|
-
const base = resolve(dirname(fromFilePath), moduleSpecifierText);
|
|
763
|
-
return [
|
|
764
|
-
`${base}.ts`,
|
|
765
|
-
`${base}.tsx`,
|
|
766
|
-
resolve(base, "index.ts")
|
|
767
|
-
].find((candidate) => existsSync(candidate));
|
|
768
|
-
};
|
|
769
|
-
var findExportedDeclaration = (sourceFile, name) => sourceFile.statements.find((statement) => isClassDeclaration(statement) && statement.name?.text === name);
|
|
770
|
-
var findImportSource = (sourceFile, localName) => {
|
|
771
|
-
for (const statement of sourceFile.statements) {
|
|
772
|
-
if (!isImportDeclaration(statement) || !isStringLiteralLikeNode(statement.moduleSpecifier)) continue;
|
|
773
|
-
const namedBindings = statement.importClause?.namedBindings;
|
|
774
|
-
if (namedBindings === void 0 || !isNamedImports(namedBindings)) continue;
|
|
775
|
-
const element = namedBindings.elements.find((candidate) => candidate.name.text === localName);
|
|
776
|
-
if (element !== void 0) return {
|
|
777
|
-
moduleSpecifierText: statement.moduleSpecifier.text,
|
|
778
|
-
importedName: element.propertyName?.text ?? element.name.text
|
|
779
|
-
};
|
|
780
|
-
}
|
|
781
|
-
};
|
|
782
|
-
var findReExportSource = (sourceFile, name) => {
|
|
783
|
-
for (const statement of sourceFile.statements) {
|
|
784
|
-
if (!isExportDeclaration(statement) || statement.moduleSpecifier === void 0 || !isStringLiteralLikeNode(statement.moduleSpecifier)) continue;
|
|
785
|
-
if (statement.exportClause === void 0) return statement.moduleSpecifier.text;
|
|
786
|
-
if (isNamedExports(statement.exportClause) && statement.exportClause.elements.some((element) => (element.propertyName?.text ?? element.name.text) === name)) return statement.moduleSpecifier.text;
|
|
787
|
-
}
|
|
788
|
-
};
|
|
789
|
-
var resolveClassDeclaration = (name, fromSourceFile, fromFilePath, visited = /* @__PURE__ */ new Set()) => {
|
|
790
|
-
if (visited.has(fromFilePath)) return;
|
|
791
|
-
visited.add(fromFilePath);
|
|
792
|
-
const direct = findExportedDeclaration(fromSourceFile, name);
|
|
793
|
-
if (direct !== void 0) return {
|
|
794
|
-
classDeclaration: direct,
|
|
795
|
-
sourceFile: fromSourceFile,
|
|
796
|
-
filePath: fromFilePath
|
|
797
|
-
};
|
|
798
|
-
const importSource = findImportSource(fromSourceFile, name);
|
|
799
|
-
if (importSource !== void 0) {
|
|
800
|
-
const resolvedPath = resolveModuleFile(fromFilePath, importSource.moduleSpecifierText);
|
|
801
|
-
if (resolvedPath !== void 0) {
|
|
802
|
-
const nextSourceFile = parseFile(resolvedPath);
|
|
803
|
-
const result = resolveClassDeclaration(importSource.importedName, nextSourceFile, resolvedPath, visited);
|
|
804
|
-
if (result !== void 0) return result;
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
const reExportModuleSpecifierText = findReExportSource(fromSourceFile, name);
|
|
808
|
-
if (reExportModuleSpecifierText !== void 0) {
|
|
809
|
-
const resolvedPath = resolveModuleFile(fromFilePath, reExportModuleSpecifierText);
|
|
810
|
-
if (resolvedPath !== void 0) return resolveClassDeclaration(name, parseFile(resolvedPath), resolvedPath, visited);
|
|
811
|
-
}
|
|
812
|
-
};
|
|
813
|
-
//#endregion
|
|
814
1782
|
//#region src/analysis/extract-selection-fields.ts
|
|
815
1783
|
var PRIMITIVE_SCALAR_NAMES$1 = /* @__PURE__ */ new Set([
|
|
816
1784
|
"string",
|
|
@@ -1119,7 +2087,7 @@ var PROVIDERS_PROPERTY_NAME = "providers";
|
|
|
1119
2087
|
var PROVIDE_PROPERTY_NAME = "provide";
|
|
1120
2088
|
var USE_CLASS_PROPERTY_NAME = "useClass";
|
|
1121
2089
|
var APP_FILTER_LOCAL_NAME = "APP_FILTER";
|
|
1122
|
-
var NEST_CORE_MODULE_SPECIFIER
|
|
2090
|
+
var NEST_CORE_MODULE_SPECIFIER = "@nestjs/core";
|
|
1123
2091
|
var findAppFilterProviderClassName = (moduleClassDeclaration, moduleSourceFile) => {
|
|
1124
2092
|
const moduleDecorator = findDecorator(moduleClassDeclaration, MODULE_DECORATOR_NAME);
|
|
1125
2093
|
if (moduleDecorator === void 0 || !isCallExpression(moduleDecorator.expression)) return;
|
|
@@ -1128,7 +2096,7 @@ var findAppFilterProviderClassName = (moduleClassDeclaration, moduleSourceFile)
|
|
|
1128
2096
|
const providersProperty = moduleOptions.properties.find((property) => isPropertyAssignment(property) && isIdentifier(property.name) && property.name.text === PROVIDERS_PROPERTY_NAME);
|
|
1129
2097
|
if (providersProperty === void 0 || !isArrayLiteralExpression(providersProperty.initializer)) return;
|
|
1130
2098
|
const appFilterImportSource = findImportSource(moduleSourceFile, APP_FILTER_LOCAL_NAME);
|
|
1131
|
-
if (appFilterImportSource === void 0 || appFilterImportSource.moduleSpecifierText !== NEST_CORE_MODULE_SPECIFIER
|
|
2099
|
+
if (appFilterImportSource === void 0 || appFilterImportSource.moduleSpecifierText !== NEST_CORE_MODULE_SPECIFIER) return;
|
|
1132
2100
|
const classNames = /* @__PURE__ */ new Set();
|
|
1133
2101
|
for (const element of providersProperty.initializer.elements) {
|
|
1134
2102
|
if (isSpreadElement(element)) return;
|
|
@@ -1162,28 +2130,6 @@ var findGlobalFilterClassName = (sourceFile) => {
|
|
|
1162
2130
|
return classNames.size === 1 ? [...classNames][0] : void 0;
|
|
1163
2131
|
};
|
|
1164
2132
|
//#endregion
|
|
1165
|
-
//#region src/analysis/find-root-module-class-name.ts
|
|
1166
|
-
var NEST_FACTORY_LOCAL_NAME = "NestFactory";
|
|
1167
|
-
var NEST_FACTORY_CREATE_METHOD_NAME = "create";
|
|
1168
|
-
var NEST_CORE_MODULE_SPECIFIER = "@nestjs/core";
|
|
1169
|
-
var collectNestFactoryCreateCalls = (node, calls) => {
|
|
1170
|
-
if (isCallExpression(node) && isPropertyAccessExpression(node.expression) && isIdentifier(node.expression.expression) && node.expression.expression.text === NEST_FACTORY_LOCAL_NAME && node.expression.name.text === NEST_FACTORY_CREATE_METHOD_NAME) calls.push(node);
|
|
1171
|
-
node.forEachChild((child) => {
|
|
1172
|
-
collectNestFactoryCreateCalls(child, calls);
|
|
1173
|
-
});
|
|
1174
|
-
};
|
|
1175
|
-
var findRootModuleClassName = (sourceFile) => {
|
|
1176
|
-
const nestFactoryImportSource = findImportSource(sourceFile, NEST_FACTORY_LOCAL_NAME);
|
|
1177
|
-
if (nestFactoryImportSource === void 0 || nestFactoryImportSource.moduleSpecifierText !== NEST_CORE_MODULE_SPECIFIER) return;
|
|
1178
|
-
const calls = [];
|
|
1179
|
-
collectNestFactoryCreateCalls(sourceFile, calls);
|
|
1180
|
-
if (calls.length !== 1) return;
|
|
1181
|
-
const [call] = calls;
|
|
1182
|
-
if (call === void 0) return;
|
|
1183
|
-
const [moduleArgument] = call.arguments;
|
|
1184
|
-
return moduleArgument !== void 0 && isIdentifier(moduleArgument) ? moduleArgument.text : void 0;
|
|
1185
|
-
};
|
|
1186
|
-
//#endregion
|
|
1187
2133
|
//#region src/analysis/resolve-catch-method-body.ts
|
|
1188
2134
|
var RESPONSE_BODY_CALL_NAMES = /* @__PURE__ */ new Set(["json", "send"]);
|
|
1189
2135
|
var matchResponseBodyArgument = (expression) => {
|
|
@@ -1287,6 +2233,7 @@ var reconcileResolvedFilter = (viaGlobalFilters, viaAppFilterProvider) => {
|
|
|
1287
2233
|
return viaGlobalFilters ?? viaAppFilterProvider;
|
|
1288
2234
|
};
|
|
1289
2235
|
var detectErrorResponseShape = (bootstrapFilePath) => {
|
|
2236
|
+
clearParsedFileCache();
|
|
1290
2237
|
const bootstrapSourceFile = parseSourceFile(bootstrapFilePath);
|
|
1291
2238
|
const resolved = reconcileResolvedFilter(resolveViaGlobalFilters(bootstrapSourceFile, bootstrapFilePath), resolveViaAppFilterProvider(bootstrapSourceFile, bootstrapFilePath));
|
|
1292
2239
|
if (resolved === void 0 || findDecorator(resolved.classDeclaration, CATCH_DECORATOR_NAME) === void 0) return;
|
|
@@ -1444,136 +2391,6 @@ var detectGlobalPrefix = (bootstrapFilePath) => {
|
|
|
1444
2391
|
};
|
|
1445
2392
|
};
|
|
1446
2393
|
//#endregion
|
|
1447
|
-
//#region src/analysis/find-global-interceptor-class-names.ts
|
|
1448
|
-
var USE_GLOBAL_INTERCEPTORS_METHOD_NAME = "useGlobalInterceptors";
|
|
1449
|
-
var collectUseGlobalInterceptorsCalls = (node, calls) => {
|
|
1450
|
-
if (isCallExpression(node) && isPropertyAccessExpression(node.expression) && node.expression.name.text === USE_GLOBAL_INTERCEPTORS_METHOD_NAME) calls.push(node);
|
|
1451
|
-
node.forEachChild((child) => {
|
|
1452
|
-
collectUseGlobalInterceptorsCalls(child, calls);
|
|
1453
|
-
});
|
|
1454
|
-
};
|
|
1455
|
-
/**
|
|
1456
|
-
* Returned in registration order: `useGlobalInterceptors` concatenates onto a
|
|
1457
|
-
* single global list, so a later call (or a later argument within one call)
|
|
1458
|
-
* always registers an interceptor that wraps closer to the raw handler result.
|
|
1459
|
-
*/
|
|
1460
|
-
var findGlobalInterceptorClassNames = (sourceFile) => {
|
|
1461
|
-
const calls = [];
|
|
1462
|
-
collectUseGlobalInterceptorsCalls(sourceFile, calls);
|
|
1463
|
-
if (calls.length === 0) return;
|
|
1464
|
-
const classNames = [];
|
|
1465
|
-
for (const call of calls) for (const argument of call.arguments) {
|
|
1466
|
-
if (!isNewExpression(argument) || !isIdentifier(argument.expression)) return;
|
|
1467
|
-
classNames.push(argument.expression.text);
|
|
1468
|
-
}
|
|
1469
|
-
return classNames.length === 0 ? void 0 : classNames;
|
|
1470
|
-
};
|
|
1471
|
-
//#endregion
|
|
1472
|
-
//#region src/analysis/synthesize-generic-object-type.ts
|
|
1473
|
-
var synthesizeExpressionType = (expression, parameterName, substitution, state) => {
|
|
1474
|
-
if (isIdentifier(expression) && expression.text === parameterName) {
|
|
1475
|
-
state.substitutionCount += 1;
|
|
1476
|
-
return substitution;
|
|
1477
|
-
}
|
|
1478
|
-
if (isObjectLiteralExpression(expression)) {
|
|
1479
|
-
const memberTypes = [];
|
|
1480
|
-
for (const property of expression.properties) {
|
|
1481
|
-
if (!isPropertyAssignment(property) || !(isIdentifier(property.name) || isStringLiteral(property.name))) return;
|
|
1482
|
-
const valueType = synthesizeExpressionType(property.initializer, parameterName, substitution, state);
|
|
1483
|
-
if (valueType === void 0) return;
|
|
1484
|
-
memberTypes.push(`${property.name.text}: ${valueType}`);
|
|
1485
|
-
}
|
|
1486
|
-
return `{ ${memberTypes.join("; ")} }`;
|
|
1487
|
-
}
|
|
1488
|
-
if (isStringLiteral(expression)) return "string";
|
|
1489
|
-
if (isNumericLiteral(expression)) return "number";
|
|
1490
|
-
if (isTrueLiteral(expression) || isFalseLiteral(expression)) return "boolean";
|
|
1491
|
-
if (isNullLiteral(expression)) return "null";
|
|
1492
|
-
};
|
|
1493
|
-
var synthesizeGenericObjectType = (objectLiteral, parameterName, substitution) => {
|
|
1494
|
-
const state = { substitutionCount: 0 };
|
|
1495
|
-
const objectType = synthesizeExpressionType(objectLiteral, parameterName, substitution, state);
|
|
1496
|
-
return objectType !== void 0 && state.substitutionCount === 1 ? objectType : void 0;
|
|
1497
|
-
};
|
|
1498
|
-
//#endregion
|
|
1499
|
-
//#region src/analysis/detect-response-wrapper.ts
|
|
1500
|
-
var INTERCEPT_METHOD_NAME = "intercept";
|
|
1501
|
-
var PIPE_MEMBER_NAME = "pipe";
|
|
1502
|
-
var MAP_OPERATOR_NAME = "map";
|
|
1503
|
-
var RXJS_MODULE_SPECIFIER = "rxjs";
|
|
1504
|
-
var WRAPPED_RESULT_SUBSTITUTION = "Awaited<Result>";
|
|
1505
|
-
var unwrapParenthesizedExpression = (expression) => {
|
|
1506
|
-
let unwrapped = expression;
|
|
1507
|
-
while (isParenthesizedExpression(unwrapped)) unwrapped = unwrapped.expression;
|
|
1508
|
-
return unwrapped;
|
|
1509
|
-
};
|
|
1510
|
-
var resolveSoleReturnExpression = (body) => {
|
|
1511
|
-
if (!isBlock(body)) return unwrapParenthesizedExpression(body);
|
|
1512
|
-
const localDeclarations = /* @__PURE__ */ new Map();
|
|
1513
|
-
let returnExpression;
|
|
1514
|
-
let sawReturn = false;
|
|
1515
|
-
for (const statement of body.statements) {
|
|
1516
|
-
if (sawReturn) return;
|
|
1517
|
-
if (isVariableStatement(statement)) {
|
|
1518
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
1519
|
-
if (!isIdentifier(declaration.name) || declaration.initializer === void 0) return;
|
|
1520
|
-
localDeclarations.set(declaration.name.text, declaration.initializer);
|
|
1521
|
-
}
|
|
1522
|
-
continue;
|
|
1523
|
-
}
|
|
1524
|
-
if (isReturnStatement(statement)) {
|
|
1525
|
-
sawReturn = true;
|
|
1526
|
-
returnExpression = statement.expression;
|
|
1527
|
-
continue;
|
|
1528
|
-
}
|
|
1529
|
-
return;
|
|
1530
|
-
}
|
|
1531
|
-
if (returnExpression === void 0) return;
|
|
1532
|
-
return isIdentifier(returnExpression) ? localDeclarations.get(returnExpression.text) : returnExpression;
|
|
1533
|
-
};
|
|
1534
|
-
var matchPipedMapCallback = (expression, interceptorSourceFile) => {
|
|
1535
|
-
if (!isCallExpression(expression) || !isPropertyAccessExpression(expression.expression) || expression.expression.name.text !== PIPE_MEMBER_NAME || expression.arguments.length !== 1) return;
|
|
1536
|
-
const [operator] = expression.arguments;
|
|
1537
|
-
if (operator === void 0 || !isCallExpression(operator) || !isIdentifier(operator.expression) || operator.expression.text !== MAP_OPERATOR_NAME || operator.arguments.length !== 1) return;
|
|
1538
|
-
const mapImportSource = findImportSource(interceptorSourceFile, operator.expression.text);
|
|
1539
|
-
if (mapImportSource === void 0 || mapImportSource.moduleSpecifierText !== RXJS_MODULE_SPECIFIER) return;
|
|
1540
|
-
const [callback] = operator.arguments;
|
|
1541
|
-
return callback !== void 0 && (isArrowFunction(callback) || isFunctionExpression(callback)) ? callback : void 0;
|
|
1542
|
-
};
|
|
1543
|
-
var findInterceptMethod = (members) => members.find((member) => isMethodDeclaration(member) && isIdentifier(member.name) && member.name.text === INTERCEPT_METHOD_NAME);
|
|
1544
|
-
var synthesizeInterceptorWrapperType = (interceptorClassName, bootstrapSourceFile, bootstrapFilePath, innerTypeSource) => {
|
|
1545
|
-
const resolved = resolveClassDeclaration(interceptorClassName, bootstrapSourceFile, bootstrapFilePath);
|
|
1546
|
-
if (resolved === void 0) return;
|
|
1547
|
-
const interceptMethod = findInterceptMethod(resolved.classDeclaration.members);
|
|
1548
|
-
if (interceptMethod?.body === void 0) return;
|
|
1549
|
-
const returnExpression = resolveSoleReturnExpression(interceptMethod.body);
|
|
1550
|
-
if (returnExpression === void 0) return;
|
|
1551
|
-
const mapCallback = matchPipedMapCallback(returnExpression, resolved.sourceFile);
|
|
1552
|
-
if (mapCallback === void 0 || mapCallback.parameters.length !== 1) return;
|
|
1553
|
-
const [callbackParameter] = mapCallback.parameters;
|
|
1554
|
-
if (callbackParameter === void 0 || !isIdentifier(callbackParameter.name)) return;
|
|
1555
|
-
const callbackReturnExpression = resolveSoleReturnExpression(mapCallback.body);
|
|
1556
|
-
if (callbackReturnExpression === void 0 || !isObjectLiteralExpression(callbackReturnExpression)) return;
|
|
1557
|
-
return synthesizeGenericObjectType(callbackReturnExpression, callbackParameter.name.text, innerTypeSource);
|
|
1558
|
-
};
|
|
1559
|
-
/**
|
|
1560
|
-
* Interceptors registered first wrap those registered after them, so the
|
|
1561
|
-
* composed type is built from the last-registered interceptor (closest to the
|
|
1562
|
-
* raw handler result) outward to the first-registered one.
|
|
1563
|
-
*/
|
|
1564
|
-
var detectResponseWrapper = (bootstrapFilePath) => {
|
|
1565
|
-
const bootstrapSourceFile = parseSourceFile(bootstrapFilePath);
|
|
1566
|
-
const interceptorClassNames = findGlobalInterceptorClassNames(bootstrapSourceFile);
|
|
1567
|
-
if (interceptorClassNames === void 0) return;
|
|
1568
|
-
let composedTypeSource = WRAPPED_RESULT_SUBSTITUTION;
|
|
1569
|
-
for (const interceptorClassName of [...interceptorClassNames].reverse()) {
|
|
1570
|
-
const wrapperTypeSource = synthesizeInterceptorWrapperType(interceptorClassName, bootstrapSourceFile, bootstrapFilePath, composedTypeSource);
|
|
1571
|
-
if (wrapperTypeSource === void 0) return;
|
|
1572
|
-
composedTypeSource = wrapperTypeSource;
|
|
1573
|
-
}
|
|
1574
|
-
return { wrappedResultTypeSource: composedTypeSource };
|
|
1575
|
-
};
|
|
1576
|
-
//#endregion
|
|
1577
2394
|
//#region src/analysis/detect-versioning.ts
|
|
1578
2395
|
var ENABLE_VERSIONING_METHOD_NAME = "enableVersioning";
|
|
1579
2396
|
var VERSIONING_TYPE_ENUM_NAME = "VersioningType";
|
|
@@ -1639,6 +2456,15 @@ var detectVersioning = (bootstrapFilePath) => {
|
|
|
1639
2456
|
};
|
|
1640
2457
|
};
|
|
1641
2458
|
//#endregion
|
|
2459
|
+
//#region src/declarations/import-specifier-for.ts
|
|
2460
|
+
var toPosixPath = (filePath) => filePath.replace(/\\/g, "/");
|
|
2461
|
+
var importSpecifierFor = (sourceFile, outputFilePath) => {
|
|
2462
|
+
if (!sourceFile.startsWith(".") && !/^[A-Za-z]:[\\/]/.test(sourceFile) && !sourceFile.startsWith("/")) return sourceFile;
|
|
2463
|
+
const relativePath = toPosixPath(relative(dirname(outputFilePath), sourceFile));
|
|
2464
|
+
return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
|
|
2465
|
+
};
|
|
2466
|
+
var stripDeclarationExtension = (filePath) => filePath.replace(/\.d\.ts$/, "");
|
|
2467
|
+
//#endregion
|
|
1642
2468
|
//#region src/declarations/generate-controller-declaration.ts
|
|
1643
2469
|
var REMOTE_RESULT_HELPERS = {
|
|
1644
2470
|
json: "RemoteResult",
|
|
@@ -1649,30 +2475,61 @@ var WRAPPED_RESULT_HELPER = "__NestBridgeWrapped";
|
|
|
1649
2475
|
var ABORTABLE_PROMISE = "AbortablePromise";
|
|
1650
2476
|
var MESSAGE_RESULT_HELPER = "NestBridgeMessageResult";
|
|
1651
2477
|
var MESSAGE_PAYLOAD_PARAMETER = "payload";
|
|
1652
|
-
var toPosixPath = (filePath) => filePath.replace(/\\/g, "/");
|
|
1653
|
-
var importSpecifierFor = (sourceFile, outputFilePath) => {
|
|
1654
|
-
if (!sourceFile.startsWith(".") && !/^[A-Za-z]:[\\/]/.test(sourceFile) && !sourceFile.startsWith("/")) return sourceFile;
|
|
1655
|
-
const relativePath = toPosixPath(relative(dirname(outputFilePath), sourceFile));
|
|
1656
|
-
return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
|
|
1657
|
-
};
|
|
1658
2478
|
var stripExtension = (filePath) => {
|
|
1659
2479
|
const extension = extname(filePath);
|
|
1660
2480
|
return extension.length > 0 ? filePath.slice(0, -extension.length) : filePath;
|
|
1661
2481
|
};
|
|
1662
|
-
var
|
|
2482
|
+
var DECLARED_INTERCEPTOR_ALIAS_PREFIX = "__I";
|
|
2483
|
+
var DECLARED_INTERCEPTOR_REFERENCE_PATTERN = new RegExp(`${DECLARED_INTERCEPTOR_PREFIX}([A-Za-z0-9_$]+)`, "g");
|
|
2484
|
+
var dependsOnServerResult = (source) => source.includes(WRAPPED_RESULT_SUBSTITUTION);
|
|
2485
|
+
var wrapperOf = (method) => (method.responseKind ?? "json") === "json" ? method.responseWrapper : void 0;
|
|
2486
|
+
/**
|
|
2487
|
+
* Wrappers that depend on the server result get a generic alias, in order of first use, so the
|
|
2488
|
+
* first one keeps the name `__NestBridgeWrapped`. A wrapper that does not depend on it, such as
|
|
2489
|
+
* `unknown`, is written inline.
|
|
2490
|
+
*/
|
|
2491
|
+
var aliasedWrapperSourcesOf = (methods, renderSource) => {
|
|
2492
|
+
const sources = /* @__PURE__ */ new Set();
|
|
2493
|
+
for (const method of methods) {
|
|
2494
|
+
const wrapper = wrapperOf(method);
|
|
2495
|
+
if (wrapper !== void 0 && dependsOnServerResult(renderSource(wrapper))) sources.add(renderSource(wrapper));
|
|
2496
|
+
}
|
|
2497
|
+
return [...sources];
|
|
2498
|
+
};
|
|
2499
|
+
var declaredInterceptorNamesOf = (methods) => {
|
|
2500
|
+
const names = /* @__PURE__ */ new Set();
|
|
2501
|
+
for (const method of methods) for (const name of wrapperOf(method)?.declaredInterceptors ?? []) names.add(name);
|
|
2502
|
+
return [...names];
|
|
2503
|
+
};
|
|
2504
|
+
var wrapperHelperName = (aliasIndex) => aliasIndex === 0 ? WRAPPED_RESULT_HELPER : `${WRAPPED_RESULT_HELPER}${aliasIndex + 1}`;
|
|
2505
|
+
var generateControllerDeclaration = (controller, outputFilePath, options = {}) => {
|
|
1663
2506
|
const sourceFileSpecifier = importSpecifierFor(controller.sourceFile, outputFilePath);
|
|
1664
2507
|
const importSpecifier = stripExtension(sourceFileSpecifier);
|
|
1665
2508
|
const serverAlias = `__Server${controller.name}`;
|
|
1666
|
-
const
|
|
2509
|
+
const declaredInterceptorNames = declaredInterceptorNamesOf(controller.methods);
|
|
2510
|
+
const renderSource = (wrapper) => wrapper.wrappedResultTypeSource.replace(DECLARED_INTERCEPTOR_REFERENCE_PATTERN, (_reference, name) => `${DECLARED_INTERCEPTOR_ALIAS_PREFIX}${declaredInterceptorNames.indexOf(name)}`);
|
|
2511
|
+
const aliasedWrapperSources = aliasedWrapperSourcesOf(controller.methods, renderSource);
|
|
2512
|
+
const declaredInterceptorImportLines = () => {
|
|
2513
|
+
if (declaredInterceptorNames.length === 0) return [];
|
|
2514
|
+
if (options.interceptorsDeclarationFilePath === void 0) throw new Error(`[nestbridge] ${controller.name} uses declared interceptors (${declaredInterceptorNames.join(", ")}) but no interceptors declaration file was given.`);
|
|
2515
|
+
const specifier = importSpecifierFor(stripDeclarationExtension(options.interceptorsDeclarationFilePath), outputFilePath);
|
|
2516
|
+
return [`import type { ${declaredInterceptorNames.map((name, index) => `${name} as ${DECLARED_INTERCEPTOR_ALIAS_PREFIX}${index}`).join(", ")} } from '${specifier}';`];
|
|
2517
|
+
};
|
|
2518
|
+
const resultTypeFor = (method) => {
|
|
2519
|
+
const serverMethod = `${serverAlias}['${method.name}']`;
|
|
2520
|
+
const wrapper = wrapperOf(method);
|
|
2521
|
+
if (wrapper === void 0) return `${REMOTE_RESULT_HELPERS[method.responseKind ?? "json"]}<${serverMethod}>`;
|
|
2522
|
+
const source = renderSource(wrapper);
|
|
2523
|
+
if (!dependsOnServerResult(source)) return `${ABORTABLE_PROMISE}<${source}>`;
|
|
2524
|
+
return `${wrapperHelperName(aliasedWrapperSources.indexOf(source))}<${serverMethod}>`;
|
|
2525
|
+
};
|
|
2526
|
+
const importedHelperFor = (method) => wrapperOf(method) === void 0 ? REMOTE_RESULT_HELPERS[method.responseKind ?? "json"] : ABORTABLE_PROMISE;
|
|
1667
2527
|
const parameterListFor = (method) => {
|
|
1668
2528
|
const serverParameters = `Parameters<${serverAlias}['${method.name}']>`;
|
|
1669
2529
|
if ((method.serverOnlyParameterIndexes ?? []).length === 0) return `...args: ${serverParameters}`;
|
|
1670
2530
|
return [...method.parameters ?? []].sort((a, b) => a.index - b.index).map((parameter) => `${parameter.parameterName}: ${serverParameters}[${parameter.index}]`).join(", ");
|
|
1671
2531
|
};
|
|
1672
|
-
const methodDeclarations = controller.methods.map((method) => {
|
|
1673
|
-
const helperName = helperNameFor(method);
|
|
1674
|
-
return ` ${method.name}(${parameterListFor(method)}): ${helperName}<${serverAlias}['${method.name}']>;`;
|
|
1675
|
-
});
|
|
2532
|
+
const methodDeclarations = controller.methods.map((method) => ` ${method.name}(${parameterListFor(method)}): ${resultTypeFor(method)};`);
|
|
1676
2533
|
const messageHandlers = controller.messageHandlers ?? [];
|
|
1677
2534
|
const messageHandlerDeclarations = messageHandlers.map((handler) => {
|
|
1678
2535
|
const serverMethod = `${serverAlias}['${handler.name}']`;
|
|
@@ -1686,16 +2543,15 @@ var generateControllerDeclaration = (controller, outputFilePath, responseWrapper
|
|
|
1686
2543
|
...methodDeclarations,
|
|
1687
2544
|
...messageHandlerDeclarations
|
|
1688
2545
|
].join("\n");
|
|
1689
|
-
const
|
|
1690
|
-
const hasWrappedMethod = rawHelperNames.includes(WRAPPED_RESULT_HELPER);
|
|
1691
|
-
const remoteHelperImports = Array.from(new Set(rawHelperNames.map((name) => name === WRAPPED_RESULT_HELPER ? ABORTABLE_PROMISE : name))).sort();
|
|
2546
|
+
const remoteHelperImports = Array.from(new Set(controller.methods.map((method) => importedHelperFor(method)))).sort();
|
|
1692
2547
|
const helperImports = remoteHelperImports.length === 0 && messageHandlers.length === 0 ? ["RemoteResult"] : remoteHelperImports;
|
|
1693
2548
|
const usesMessageResult = messageHandlers.some((handler) => handler.kind === "message");
|
|
1694
|
-
const wrappedResultTypeAliasLines =
|
|
2549
|
+
const wrappedResultTypeAliasLines = aliasedWrapperSources.length === 0 ? [] : [...aliasedWrapperSources.map((source, aliasIndex) => `type ${wrapperHelperName(aliasIndex)}<T> = T extends (...args: never[]) => infer Result ? ${ABORTABLE_PROMISE}<${source}> : never;`), ""];
|
|
1695
2550
|
return [
|
|
1696
2551
|
`import type { ${controller.name} as ${serverAlias} } from '${importSpecifier}';`,
|
|
1697
2552
|
...helperImports.length > 0 ? [`import type { ${helperImports.join(", ")} } from 'nestbridge';`] : [],
|
|
1698
2553
|
...usesMessageResult ? [`import type { ${MESSAGE_RESULT_HELPER} } from 'nestbridge/microservices';`] : [],
|
|
2554
|
+
...declaredInterceptorImportLines(),
|
|
1699
2555
|
"",
|
|
1700
2556
|
"/**",
|
|
1701
2557
|
" * Generated by NestBridge — client-facing methods only.",
|
|
@@ -1719,6 +2575,29 @@ var generateErrorBodyDeclaration = (errorBodyTypeSource) => [
|
|
|
1719
2575
|
""
|
|
1720
2576
|
].join("\n");
|
|
1721
2577
|
//#endregion
|
|
2578
|
+
//#region src/declarations/generate-interceptors-declaration.ts
|
|
2579
|
+
var namesByFilePath = (declarations) => {
|
|
2580
|
+
const names = /* @__PURE__ */ new Map();
|
|
2581
|
+
for (const { filePath, name } of declarations) names.set(filePath, [...names.get(filePath) ?? [], name]);
|
|
2582
|
+
return names;
|
|
2583
|
+
};
|
|
2584
|
+
/**
|
|
2585
|
+
* One re-export line per declaration file, in the order the files were read. A file that
|
|
2586
|
+
* contributes no alias gets no line.
|
|
2587
|
+
*/
|
|
2588
|
+
var generateInterceptorsDeclaration = (declarations, outputFilePath) => {
|
|
2589
|
+
return [
|
|
2590
|
+
"/**",
|
|
2591
|
+
" * Generated by NestBridge — the interceptor types declared in the server interceptor declaration files.",
|
|
2592
|
+
" */",
|
|
2593
|
+
...[...namesByFilePath(declarations)].map(([filePath, names]) => {
|
|
2594
|
+
const specifier = importSpecifierFor(stripDeclarationExtension(filePath), outputFilePath);
|
|
2595
|
+
return `export type { ${names.join(", ")} } from '${specifier}';`;
|
|
2596
|
+
}),
|
|
2597
|
+
""
|
|
2598
|
+
].join("\n");
|
|
2599
|
+
};
|
|
2600
|
+
//#endregion
|
|
1722
2601
|
//#region src/diagnostics/format-diagnostic.ts
|
|
1723
2602
|
var formatDiagnostic = (diagnostic) => {
|
|
1724
2603
|
const subject = diagnostic.memberName.length > 0 ? `${diagnostic.controllerName}.${diagnostic.memberName}` : diagnostic.controllerName;
|
|
@@ -1746,8 +2625,8 @@ var NestBridgeDiagnosticError = class extends Error {
|
|
|
1746
2625
|
};
|
|
1747
2626
|
//#endregion
|
|
1748
2627
|
//#region src/version.ts
|
|
1749
|
-
var VERSION = "
|
|
2628
|
+
var VERSION = "3.1.0";
|
|
1750
2629
|
//#endregion
|
|
1751
|
-
export { NestBridgeDiagnosticError, VERSION, analyzeControllers, analyzeResolvers, applyApplicationRouting, detectErrorResponseShape, detectGlobalPrefix,
|
|
2630
|
+
export { INTERCEPTOR_DECLARATION_FILE_NAMES, NestBridgeDiagnosticError, VERSION, analyzeControllers, analyzeResolvers, applyApplicationRouting, detectErrorResponseShape, detectGlobalPrefix, detectVersioning, formatDiagnostic, generateControllerDeclaration, generateErrorBodyDeclaration, generateInterceptorsDeclaration };
|
|
1752
2631
|
|
|
1753
2632
|
//# sourceMappingURL=nestbridge.core.js.map
|