@nestbridge/core 3.0.0 → 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.
@@ -1,7 +1,8 @@
1
- import { SyntaxKind, isArrayLiteralExpression, isArrayTypeNode, isArrowFunction, isBinaryExpression, isBlock, isCallExpression, isClassDeclaration, isClassExpression, isConditionalExpression, isDecorator, isDoStatement, isExportDeclaration, isExpressionStatement, isFalseLiteral, isForInStatement, isForOfStatement, isForStatement, isFunctionDeclaration, isFunctionExpression, isIdentifier, isIfStatement, isImportDeclaration, isLiteralTypeNode, isMethodDeclaration, isNamedExports, isNamedImports, isNewExpression, isNullLiteral, isNumericLiteral, isObjectLiteralExpression, isParenthesizedExpression, isPropertyAccessExpression, isPropertyAssignment, isPropertyDeclaration, isReturnStatement, isShorthandPropertyAssignment, isSpreadElement, isStringLiteral, isStringLiteralLikeNode, isSwitchStatement, isTrueLiteral, isTypeReferenceNode, isUnionTypeNode, isVariableStatement, isWhileStatement } from "typescript/unstable/ast";
2
- import { existsSync } from "node:fs";
3
- import { dirname, extname, relative, resolve } from "node:path";
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";
4
3
  import { API } from "typescript/unstable/sync";
4
+ import { existsSync, realpathSync } from "node:fs";
5
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
5
6
  //#region src/analysis/attach-response-wrappers.ts
6
7
  var attachResponseWrappers = (controller, classDeclaration, interceptors) => {
7
8
  const memberMethods = classDeclaration.members.filter((member) => isMethodDeclaration(member));
@@ -188,6 +189,71 @@ var openSourceFile = (filePath) => {
188
189
  //#region src/analysis/parse-source-file.ts
189
190
  var parseSourceFile = (filePath) => openSourceFile(filePath).sourceFile;
190
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
191
257
  //#region src/analysis/resolve-type-declaration.ts
192
258
  var parsedFilesByPath = /* @__PURE__ */ new Map();
193
259
  /**
@@ -204,15 +270,6 @@ var parseFile = (filePath) => {
204
270
  parsedFilesByPath.set(filePath, sourceFile);
205
271
  return sourceFile;
206
272
  };
207
- var resolveModuleFile = (fromFilePath, moduleSpecifierText) => {
208
- if (!moduleSpecifierText.startsWith(".")) return;
209
- const base = resolve(dirname(fromFilePath), moduleSpecifierText);
210
- return [
211
- `${base}.ts`,
212
- `${base}.tsx`,
213
- resolve(base, "index.ts")
214
- ].find((candidate) => existsSync(candidate));
215
- };
216
273
  var findExportedDeclaration = (sourceFile, name) => sourceFile.statements.find((statement) => isClassDeclaration(statement) && statement.name?.text === name);
217
274
  var findImportSource = (sourceFile, localName) => {
218
275
  for (const statement of sourceFile.statements) {
@@ -233,29 +290,43 @@ var findReExportSource = (sourceFile, name) => {
233
290
  if (isNamedExports(statement.exportClause) && statement.exportClause.elements.some((element) => (element.propertyName?.text ?? element.name.text) === name)) return statement.moduleSpecifier.text;
234
291
  }
235
292
  };
236
- var resolveClassDeclaration = (name, fromSourceFile, fromFilePath, visited = /* @__PURE__ */ new Set()) => {
237
- if (visited.has(fromFilePath)) return;
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" };
238
305
  visited.add(fromFilePath);
239
306
  const direct = findExportedDeclaration(fromSourceFile, name);
240
307
  if (direct !== void 0) return {
241
- classDeclaration: direct,
242
- sourceFile: fromSourceFile,
243
- filePath: fromFilePath
308
+ kind: "source",
309
+ resolved: {
310
+ classDeclaration: direct,
311
+ sourceFile: fromSourceFile,
312
+ filePath: fromFilePath
313
+ }
244
314
  };
245
315
  const importSource = findImportSource(fromSourceFile, name);
246
- if (importSource !== void 0) {
247
- const resolvedPath = resolveModuleFile(fromFilePath, importSource.moduleSpecifierText);
248
- if (resolvedPath !== void 0) {
249
- const nextSourceFile = parseFile(resolvedPath);
250
- const result = resolveClassDeclaration(importSource.importedName, nextSourceFile, resolvedPath, visited);
251
- if (result !== void 0) return result;
252
- }
253
- }
316
+ const imported = importSource === void 0 ? void 0 : resolveImportedClassOrigin(importSource.importedName, importSource.moduleSpecifierText, fromFilePath, visited);
317
+ if (imported !== void 0) return imported;
254
318
  const reExportModuleSpecifierText = findReExportSource(fromSourceFile, name);
255
- if (reExportModuleSpecifierText !== void 0) {
256
- const resolvedPath = resolveModuleFile(fromFilePath, reExportModuleSpecifierText);
257
- if (resolvedPath !== void 0) return resolveClassDeclaration(name, parseFile(resolvedPath), resolvedPath, visited);
258
- }
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;
259
330
  };
260
331
  //#endregion
261
332
  //#region src/analysis/read-pipe-operator.ts
@@ -400,22 +471,51 @@ var analyzeInterceptorClass = (resolved) => {
400
471
  };
401
472
  };
402
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
403
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
+ };
404
488
  /**
405
- * `shapes` run outermost first, so the type is built from the innermost interceptor outward,
406
- * starting at the awaited server result. Returns `undefined` when no interceptor changes the
407
- * shape.
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.
408
493
  */
409
- var composeWrapperTypeSource = (shapes) => {
410
- const operations = [...shapes].reverse().flatMap((shape) => shape.operations);
411
- if (operations.length === 0) return;
494
+ var composeWrapperTypeSource = (links) => {
412
495
  let typeSource = WRAPPED_RESULT_SUBSTITUTION;
413
- for (const operation of operations) {
414
- const synthesis = synthesizeGenericObjectType(operation.returnExpression, operation.parameterName, typeSource);
415
- if (!synthesis.ok) throw new Error(`[nestbridge] An interceptor shape that was validated can no longer be typed: ${synthesis.reason}`);
416
- typeSource = synthesis.typeSource;
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];
417
512
  }
418
- return typeSource;
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
+ };
419
519
  };
420
520
  //#endregion
421
521
  //#region src/analysis/node-location.ts
@@ -428,7 +528,7 @@ var locationOf = (sourceFile, node) => {
428
528
  };
429
529
  //#endregion
430
530
  //#region src/analysis/create-interceptor-diagnostic.ts
431
- var EXPECTED$2 = "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>.";
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>.";
432
532
  var createInterceptorDiagnostic = (source) => {
433
533
  const location = locationOf(source.sourceFile, source.location);
434
534
  return {
@@ -438,7 +538,7 @@ var createInterceptorDiagnostic = (source) => {
438
538
  memberName: source.memberName,
439
539
  detail: source.detail,
440
540
  found: source.found ?? source.location.getText(),
441
- expected: EXPECTED$2,
541
+ expected: EXPECTED$3,
442
542
  filePath: source.filePath,
443
543
  line: location.line,
444
544
  column: location.column
@@ -750,6 +850,14 @@ var findUseInterceptorsRegistrations = (target, sourceFile, filePath) => {
750
850
  return registrations;
751
851
  };
752
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
753
861
  //#region src/analysis/create-interceptor-analysis.ts
754
862
  var REGISTRATION_SUBJECT = "(interceptors)";
755
863
  var INTERCEPT_MEMBER_NAME = "intercept";
@@ -761,6 +869,7 @@ var INTERCEPT_MEMBER_NAME = "intercept";
761
869
  */
762
870
  var createInterceptorAnalysis = (options) => {
763
871
  const { bootstrapFilePath, diagnostics } = options;
872
+ const declarationsByName = new Map((options.declarations ?? []).map((declaration) => [declaration.name, declaration]));
764
873
  const contributingFiles = /* @__PURE__ */ new Set();
765
874
  const shapesByInterceptor = /* @__PURE__ */ new Map();
766
875
  let globalRegistrations;
@@ -785,8 +894,9 @@ var createInterceptorAnalysis = (options) => {
785
894
  }));
786
895
  };
787
896
  const resolveShape = (reference) => {
788
- const resolved = resolveClassDeclaration(reference.className, reference.sourceFile, reference.filePath);
789
- if (resolved === void 0) {
897
+ const origin = resolveClassOrigin(reference.className, reference.sourceFile, reference.filePath);
898
+ if (origin.kind === "package") return PACKAGE_INTERCEPTOR_SHAPE;
899
+ if (origin.kind === "unresolved") {
790
900
  const location = locationOf(reference.sourceFile, reference.node);
791
901
  const referenceKey = `${reference.filePath}:${location.line}:${location.column}`;
792
902
  if (!shapesByInterceptor.has(referenceKey)) {
@@ -795,6 +905,7 @@ var createInterceptorAnalysis = (options) => {
795
905
  }
796
906
  return;
797
907
  }
908
+ const { resolved } = origin;
798
909
  contributingFiles.add(resolved.filePath);
799
910
  const interceptorKey = `${resolved.filePath}#${resolved.classDeclaration.name?.text}`;
800
911
  if (shapesByInterceptor.has(interceptorKey)) return shapesByInterceptor.get(interceptorKey);
@@ -812,6 +923,19 @@ var createInterceptorAnalysis = (options) => {
812
923
  shapesByInterceptor.set(interceptorKey, shape);
813
924
  return shape;
814
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
+ };
815
939
  const readGlobalRegistrations = () => {
816
940
  if (globalRegistrations === void 0) {
817
941
  globalRegistrations = bootstrapFilePath === void 0 ? {
@@ -839,10 +963,9 @@ var createInterceptorAnalysis = (options) => {
839
963
  readControllerRegistrations(),
840
964
  methodRegistrations
841
965
  ];
842
- const shapes = chain.flatMap(({ references }) => references.map(resolveShape));
843
- if (chain.some(({ problems }) => problems.length > 0) || shapes.some((shape) => shape === void 0)) return { wrappedResultTypeSource: UNRESOLVED_WRAPPED_RESULT_TYPE_SOURCE };
844
- const wrappedResultTypeSource = composeWrapperTypeSource(shapes.filter((shape) => shape !== void 0));
845
- return wrappedResultTypeSource === void 0 ? void 0 : { wrappedResultTypeSource };
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);
846
969
  };
847
970
  return { responseWrapperOf };
848
971
  };
@@ -1365,13 +1488,138 @@ var findControllerClasses = (sourceFile) => {
1365
1488
  return sourceFile.statements.filter((statement) => isClassDeclaration(statement) && findDecorator(statement, "Controller") !== void 0);
1366
1489
  };
1367
1490
  //#endregion
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
+ };
1595
+ /**
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.
1599
+ */
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));
1607
+ return {
1608
+ declarations: [...registry.accepted.values()].filter(({ name }) => !registry.conflicted.has(name)),
1609
+ diagnostics
1610
+ };
1611
+ };
1612
+ //#endregion
1368
1613
  //#region src/analysis/analyze-controllers.ts
1369
1614
  var analyzeControllers = (filePaths, options = {}) => {
1370
1615
  const diagnostics = [];
1371
1616
  const controllers = [];
1617
+ const interceptorDeclarations = readInterceptorDeclarations(options.interceptorDeclarationFilePaths);
1618
+ diagnostics.push(...interceptorDeclarations.diagnostics);
1372
1619
  const interceptors = createInterceptorAnalysis({
1373
1620
  bootstrapFilePath: options.bootstrapFilePath,
1374
- diagnostics
1621
+ diagnostics,
1622
+ declarations: interceptorDeclarations.declarations
1375
1623
  });
1376
1624
  clearParsedFileCache();
1377
1625
  for (const filePath of filePaths) {
@@ -1391,7 +1639,8 @@ var analyzeControllers = (filePaths, options = {}) => {
1391
1639
  return {
1392
1640
  controllers,
1393
1641
  diagnostics,
1394
- interceptorFiles: interceptors.contributingFiles()
1642
+ interceptorFiles: interceptors.contributingFiles(),
1643
+ interceptorDeclarations: interceptorDeclarations.declarations
1395
1644
  };
1396
1645
  };
1397
1646
  //#endregion
@@ -2207,6 +2456,15 @@ var detectVersioning = (bootstrapFilePath) => {
2207
2456
  };
2208
2457
  };
2209
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
2210
2468
  //#region src/declarations/generate-controller-declaration.ts
2211
2469
  var REMOTE_RESULT_HELPERS = {
2212
2470
  json: "RemoteResult",
@@ -2217,43 +2475,53 @@ var WRAPPED_RESULT_HELPER = "__NestBridgeWrapped";
2217
2475
  var ABORTABLE_PROMISE = "AbortablePromise";
2218
2476
  var MESSAGE_RESULT_HELPER = "NestBridgeMessageResult";
2219
2477
  var MESSAGE_PAYLOAD_PARAMETER = "payload";
2220
- var toPosixPath = (filePath) => filePath.replace(/\\/g, "/");
2221
- var importSpecifierFor = (sourceFile, outputFilePath) => {
2222
- if (!sourceFile.startsWith(".") && !/^[A-Za-z]:[\\/]/.test(sourceFile) && !sourceFile.startsWith("/")) return sourceFile;
2223
- const relativePath = toPosixPath(relative(dirname(outputFilePath), sourceFile));
2224
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2225
- };
2226
2478
  var stripExtension = (filePath) => {
2227
2479
  const extension = extname(filePath);
2228
2480
  return extension.length > 0 ? filePath.slice(0, -extension.length) : filePath;
2229
2481
  };
2230
- var dependsOnServerResult = (wrapper) => wrapper.wrappedResultTypeSource.includes(WRAPPED_RESULT_SUBSTITUTION);
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);
2231
2485
  var wrapperOf = (method) => (method.responseKind ?? "json") === "json" ? method.responseWrapper : void 0;
2232
2486
  /**
2233
2487
  * Wrappers that depend on the server result get a generic alias, in order of first use, so the
2234
2488
  * first one keeps the name `__NestBridgeWrapped`. A wrapper that does not depend on it, such as
2235
2489
  * `unknown`, is written inline.
2236
2490
  */
2237
- var aliasedWrapperSourcesOf = (methods) => {
2491
+ var aliasedWrapperSourcesOf = (methods, renderSource) => {
2238
2492
  const sources = /* @__PURE__ */ new Set();
2239
2493
  for (const method of methods) {
2240
2494
  const wrapper = wrapperOf(method);
2241
- if (wrapper !== void 0 && dependsOnServerResult(wrapper)) sources.add(wrapper.wrappedResultTypeSource);
2495
+ if (wrapper !== void 0 && dependsOnServerResult(renderSource(wrapper))) sources.add(renderSource(wrapper));
2242
2496
  }
2243
2497
  return [...sources];
2244
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
+ };
2245
2504
  var wrapperHelperName = (aliasIndex) => aliasIndex === 0 ? WRAPPED_RESULT_HELPER : `${WRAPPED_RESULT_HELPER}${aliasIndex + 1}`;
2246
- var generateControllerDeclaration = (controller, outputFilePath) => {
2505
+ var generateControllerDeclaration = (controller, outputFilePath, options = {}) => {
2247
2506
  const sourceFileSpecifier = importSpecifierFor(controller.sourceFile, outputFilePath);
2248
2507
  const importSpecifier = stripExtension(sourceFileSpecifier);
2249
2508
  const serverAlias = `__Server${controller.name}`;
2250
- const aliasedWrapperSources = aliasedWrapperSourcesOf(controller.methods);
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
+ };
2251
2518
  const resultTypeFor = (method) => {
2252
2519
  const serverMethod = `${serverAlias}['${method.name}']`;
2253
2520
  const wrapper = wrapperOf(method);
2254
2521
  if (wrapper === void 0) return `${REMOTE_RESULT_HELPERS[method.responseKind ?? "json"]}<${serverMethod}>`;
2255
- if (!dependsOnServerResult(wrapper)) return `${ABORTABLE_PROMISE}<${wrapper.wrappedResultTypeSource}>`;
2256
- return `${wrapperHelperName(aliasedWrapperSources.indexOf(wrapper.wrappedResultTypeSource))}<${serverMethod}>`;
2522
+ const source = renderSource(wrapper);
2523
+ if (!dependsOnServerResult(source)) return `${ABORTABLE_PROMISE}<${source}>`;
2524
+ return `${wrapperHelperName(aliasedWrapperSources.indexOf(source))}<${serverMethod}>`;
2257
2525
  };
2258
2526
  const importedHelperFor = (method) => wrapperOf(method) === void 0 ? REMOTE_RESULT_HELPERS[method.responseKind ?? "json"] : ABORTABLE_PROMISE;
2259
2527
  const parameterListFor = (method) => {
@@ -2283,6 +2551,7 @@ var generateControllerDeclaration = (controller, outputFilePath) => {
2283
2551
  `import type { ${controller.name} as ${serverAlias} } from '${importSpecifier}';`,
2284
2552
  ...helperImports.length > 0 ? [`import type { ${helperImports.join(", ")} } from 'nestbridge';`] : [],
2285
2553
  ...usesMessageResult ? [`import type { ${MESSAGE_RESULT_HELPER} } from 'nestbridge/microservices';`] : [],
2554
+ ...declaredInterceptorImportLines(),
2286
2555
  "",
2287
2556
  "/**",
2288
2557
  " * Generated by NestBridge — client-facing methods only.",
@@ -2306,6 +2575,29 @@ var generateErrorBodyDeclaration = (errorBodyTypeSource) => [
2306
2575
  ""
2307
2576
  ].join("\n");
2308
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
2309
2601
  //#region src/diagnostics/format-diagnostic.ts
2310
2602
  var formatDiagnostic = (diagnostic) => {
2311
2603
  const subject = diagnostic.memberName.length > 0 ? `${diagnostic.controllerName}.${diagnostic.memberName}` : diagnostic.controllerName;
@@ -2333,8 +2625,8 @@ var NestBridgeDiagnosticError = class extends Error {
2333
2625
  };
2334
2626
  //#endregion
2335
2627
  //#region src/version.ts
2336
- var VERSION = "3.0.0";
2628
+ var VERSION = "3.1.0";
2337
2629
  //#endregion
2338
- export { NestBridgeDiagnosticError, VERSION, analyzeControllers, analyzeResolvers, applyApplicationRouting, detectErrorResponseShape, detectGlobalPrefix, detectVersioning, formatDiagnostic, generateControllerDeclaration, generateErrorBodyDeclaration };
2630
+ export { INTERCEPTOR_DECLARATION_FILE_NAMES, NestBridgeDiagnosticError, VERSION, analyzeControllers, analyzeResolvers, applyApplicationRouting, detectErrorResponseShape, detectGlobalPrefix, detectVersioning, formatDiagnostic, generateControllerDeclaration, generateErrorBodyDeclaration, generateInterceptorsDeclaration };
2339
2631
 
2340
2632
  //# sourceMappingURL=nestbridge.core.js.map