@starci/eslint-canon-be 3.5.0 → 3.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +13 -2
  3. package/dist/ambient-id.d.ts +9 -0
  4. package/{ambient-id.mjs → dist/ambient-id.js} +43 -39
  5. package/dist/app-composition.d.ts +21 -0
  6. package/{app-composition.mjs → dist/app-composition.js} +396 -300
  7. package/dist/async-discipline.d.ts +9 -0
  8. package/dist/async-discipline.js +77 -0
  9. package/dist/authorization.d.ts +12 -0
  10. package/{authorization.mjs → dist/authorization.js} +53 -59
  11. package/dist/boundary-schema.d.ts +15 -0
  12. package/{boundary-schema.mjs → dist/boundary-schema.js} +120 -105
  13. package/dist/builders.d.ts +21 -0
  14. package/{builders.mjs → dist/builders.js} +162 -146
  15. package/dist/cli.d.ts +15 -0
  16. package/{cli.mjs → dist/cli.js} +97 -82
  17. package/dist/comments.d.ts +52 -0
  18. package/dist/comments.js +412 -0
  19. package/dist/config-owner.d.ts +24 -0
  20. package/{config-owner.mjs → dist/config-owner.js} +256 -219
  21. package/dist/connections.d.ts +12 -0
  22. package/{connections.mjs → dist/connections.js} +138 -140
  23. package/dist/cookies.d.ts +9 -0
  24. package/{cookies.mjs → dist/cookies.js} +58 -58
  25. package/dist/cqrs.d.ts +27 -0
  26. package/{cqrs.mjs → dist/cqrs.js} +341 -282
  27. package/dist/data-access.d.ts +50 -0
  28. package/{data-access.mjs → dist/data-access.js} +238 -243
  29. package/dist/default-deny.d.ts +15 -0
  30. package/{default-deny.mjs → dist/default-deny.js} +103 -88
  31. package/dist/e2e-flow.d.ts +25 -0
  32. package/{e2e-flow.mjs → dist/e2e-flow.js} +113 -112
  33. package/dist/edge-hardening.d.ts +10 -0
  34. package/dist/edge-hardening.js +173 -0
  35. package/dist/error-handling.d.ts +21 -0
  36. package/{error-handling.mjs → dist/error-handling.js} +289 -239
  37. package/dist/event-bus.d.ts +14 -0
  38. package/{event-bus.mjs → dist/event-bus.js} +146 -129
  39. package/dist/feature-thin.d.ts +12 -0
  40. package/{feature-thin.mjs → dist/feature-thin.js} +208 -191
  41. package/dist/function-budget.d.ts +7 -0
  42. package/{function-budget.mjs → dist/function-budget.js} +24 -27
  43. package/dist/health-ready.d.ts +10 -0
  44. package/dist/health-ready.js +703 -0
  45. package/dist/idempotency.d.ts +10 -0
  46. package/{idempotency.mjs → dist/idempotency.js} +296 -226
  47. package/dist/index.d.ts +54 -0
  48. package/{index.mjs → dist/index.js} +91 -109
  49. package/dist/infra-owner.d.ts +18 -0
  50. package/{infra-owner.mjs → dist/infra-owner.js} +58 -51
  51. package/dist/injection.d.ts +30 -0
  52. package/{injection.mjs → dist/injection.js} +397 -344
  53. package/dist/input-bounds.d.ts +15 -0
  54. package/{input-bounds.mjs → dist/input-bounds.js} +143 -132
  55. package/dist/jobs.d.ts +17 -0
  56. package/{jobs.mjs → dist/jobs.js} +116 -99
  57. package/dist/jwt-alg.d.ts +6 -0
  58. package/dist/jwt-alg.js +49 -0
  59. package/dist/lib/app-roles.d.ts +25 -0
  60. package/{lib/app-roles.mjs → dist/lib/app-roles.js} +15 -17
  61. package/dist/lib/ast.d.ts +40 -0
  62. package/dist/lib/ast.js +100 -0
  63. package/dist/lib/client-idempotency.d.ts +3 -0
  64. package/{lib/client-idempotency.mjs → dist/lib/client-idempotency.js} +316 -268
  65. package/dist/lib/config.d.ts +36 -0
  66. package/{lib/config.mjs → dist/lib/config.js} +24 -27
  67. package/dist/lib/db-writes.d.ts +29 -0
  68. package/{lib/db-writes.mjs → dist/lib/db-writes.js} +27 -27
  69. package/dist/lib/declared.d.ts +77 -0
  70. package/{lib/declared.mjs → dist/lib/declared.js} +83 -78
  71. package/dist/lib/doors.d.ts +50 -0
  72. package/{lib/doors.mjs → dist/lib/doors.js} +45 -50
  73. package/dist/lib/edition.d.ts +25 -0
  74. package/{lib/edition.mjs → dist/lib/edition.js} +15 -20
  75. package/dist/lib/entity-writes.d.ts +7 -0
  76. package/{lib/entity-writes.mjs → dist/lib/entity-writes.js} +31 -22
  77. package/dist/lib/hfs-view.d.ts +127 -0
  78. package/dist/lib/hfs-view.js +1 -0
  79. package/dist/lib/hfs.d.ts +34 -0
  80. package/{lib/hfs.mjs → dist/lib/hfs.js} +31 -29
  81. package/dist/lib/import-source.d.ts +63 -0
  82. package/dist/lib/import-source.js +134 -0
  83. package/dist/lib/path.d.ts +8 -0
  84. package/{lib/path.mjs → dist/lib/path.js} +4 -7
  85. package/dist/lib/persistence.d.ts +115 -0
  86. package/{lib/persistence.mjs → dist/lib/persistence.js} +55 -66
  87. package/dist/lib/ports.d.ts +70 -0
  88. package/{lib/ports.mjs → dist/lib/ports.js} +62 -66
  89. package/dist/lib/rule.d.ts +31 -0
  90. package/dist/lib/rule.js +2 -0
  91. package/dist/lib/runtime-root.d.ts +4 -0
  92. package/dist/lib/runtime-root.js +10 -0
  93. package/dist/lib/schema-values.d.ts +13 -0
  94. package/{lib/schema-values.mjs → dist/lib/schema-values.js} +67 -59
  95. package/dist/lib/specifier.d.ts +12 -0
  96. package/dist/lib/specifier.js +29 -0
  97. package/dist/lib/subject-values.d.ts +4 -0
  98. package/dist/lib/subject-values.js +61 -0
  99. package/dist/lib/transactions.d.ts +18 -0
  100. package/{lib/transactions.mjs → dist/lib/transactions.js} +17 -15
  101. package/dist/lib/transport-slots.d.ts +17 -0
  102. package/{lib/transport-slots.mjs → dist/lib/transport-slots.js} +2 -4
  103. package/dist/lib/types.d.ts +96 -0
  104. package/dist/lib/types.js +150 -0
  105. package/dist/lib/unit-spec.d.ts +48 -0
  106. package/{lib/unit-spec.mjs → dist/lib/unit-spec.js} +35 -44
  107. package/dist/lib/webhook-ack.d.ts +4 -0
  108. package/{lib/webhook-ack.mjs → dist/lib/webhook-ack.js} +78 -62
  109. package/dist/lib/webhook-handoff-inbox.d.ts +3 -0
  110. package/{lib/webhook-handoff-inbox.mjs → dist/lib/webhook-handoff-inbox.js} +195 -167
  111. package/dist/lib/webhook-handoff-intake.d.ts +4 -0
  112. package/{lib/webhook-handoff-intake.mjs → dist/lib/webhook-handoff-intake.js} +125 -102
  113. package/dist/lib/webhook-handoff.d.ts +15 -0
  114. package/{lib/webhook-handoff.mjs → dist/lib/webhook-handoff.js} +107 -100
  115. package/dist/lib/webhook-verifiers.d.ts +20 -0
  116. package/{lib/webhook-verifiers.mjs → dist/lib/webhook-verifiers.js} +108 -104
  117. package/dist/lib/why.d.ts +9 -0
  118. package/{lib/why.mjs → dist/lib/why.js} +6 -6
  119. package/dist/log-safety.d.ts +20 -0
  120. package/dist/log-safety.js +308 -0
  121. package/dist/module-layering.d.ts +42 -0
  122. package/dist/module-layering.js +257 -0
  123. package/dist/module-shape.d.ts +47 -0
  124. package/{module-shape.mjs → dist/module-shape.js} +278 -236
  125. package/dist/naming.d.ts +49 -0
  126. package/dist/naming.js +246 -0
  127. package/dist/observability.d.ts +25 -0
  128. package/dist/observability.js +245 -0
  129. package/dist/operations.d.ts +23 -0
  130. package/{operations.mjs → dist/operations.js} +410 -332
  131. package/dist/project-graph.d.ts +9 -0
  132. package/{project-graph.mjs → dist/project-graph.js} +8 -13
  133. package/dist/projections.d.ts +11 -0
  134. package/{projections.mjs → dist/projections.js} +60 -57
  135. package/dist/query-safety.d.ts +21 -0
  136. package/{query-safety.mjs → dist/query-safety.js} +92 -108
  137. package/dist/realtime.d.ts +15 -0
  138. package/{realtime.mjs → dist/realtime.js} +108 -106
  139. package/dist/resilience.d.ts +15 -0
  140. package/dist/resilience.js +319 -0
  141. package/dist/schema-authority.d.ts +15 -0
  142. package/{schema-authority.mjs → dist/schema-authority.js} +256 -220
  143. package/dist/service-deps.d.ts +17 -0
  144. package/{service-deps.mjs → dist/service-deps.js} +133 -130
  145. package/dist/service-isolation.d.ts +8 -0
  146. package/dist/service-isolation.js +76 -0
  147. package/dist/size-budget.d.ts +9 -0
  148. package/{size-budget.mjs → dist/size-budget.js} +27 -27
  149. package/dist/sonar-parity.d.ts +5 -0
  150. package/{sonar-parity.mjs → dist/sonar-parity.js} +7 -7
  151. package/dist/spec-no-skip.d.ts +9 -0
  152. package/dist/spec-no-skip.js +81 -0
  153. package/dist/spec-quality.d.ts +10 -0
  154. package/{spec-quality.mjs → dist/spec-quality.js} +103 -87
  155. package/dist/suppression.d.ts +26 -0
  156. package/{suppression.mjs → dist/suppression.js} +30 -45
  157. package/dist/temporal.d.ts +9 -0
  158. package/{temporal.mjs → dist/temporal.js} +75 -65
  159. package/dist/test-world.d.ts +28 -0
  160. package/{test-world.mjs → dist/test-world.js} +102 -83
  161. package/dist/testing.d.ts +51 -0
  162. package/dist/testing.js +368 -0
  163. package/dist/third-party-owner.d.ts +8 -0
  164. package/{third-party-owner.mjs → dist/third-party-owner.js} +105 -91
  165. package/dist/transport.d.ts +24 -0
  166. package/{transport.mjs → dist/transport.js} +279 -240
  167. package/dist/type-safety.d.ts +25 -0
  168. package/dist/type-safety.js +297 -0
  169. package/dist/unit-spec.d.ts +30 -0
  170. package/{unit-spec.mjs → dist/unit-spec.js} +473 -399
  171. package/dist/uploads.d.ts +9 -0
  172. package/{uploads.mjs → dist/uploads.js} +62 -54
  173. package/dist/user-copy.d.ts +9 -0
  174. package/{user-copy.mjs → dist/user-copy.js} +76 -67
  175. package/dist/webhooks.d.ts +16 -0
  176. package/{webhooks.mjs → dist/webhooks.js} +243 -231
  177. package/package.json +23 -8
  178. package/runtime/knowledge/hfs/canon-pins.yaml +18 -11
  179. package/runtime/scripts/hfs/repo-identity.mjs +5 -4
  180. package/async-discipline.mjs +0 -83
  181. package/comments.mjs +0 -416
  182. package/edge-hardening.mjs +0 -139
  183. package/health-ready.mjs +0 -539
  184. package/jwt-alg.mjs +0 -45
  185. package/lib/ast.mjs +0 -88
  186. package/lib/import-source.mjs +0 -104
  187. package/lib/specifier.mjs +0 -27
  188. package/lib/subject-values.mjs +0 -55
  189. package/lib/types.mjs +0 -133
  190. package/log-safety.mjs +0 -303
  191. package/module-layering.mjs +0 -270
  192. package/naming.mjs +0 -251
  193. package/observability.mjs +0 -241
  194. package/resilience.mjs +0 -304
  195. package/service-isolation.mjs +0 -75
  196. package/spec-no-skip.mjs +0 -85
  197. package/testing.mjs +0 -384
  198. package/type-safety.mjs +0 -323
@@ -10,119 +10,145 @@
10
10
  * What the table IS comes from where its types are declared (the `operations` capability of the platform slot), never from a name in
11
11
  * a path pattern.
12
12
  */
13
- import ts from "typescript"
14
- import { keyName, walk } from "./lib/ast.mjs"
15
- import { hfsOf } from "./lib/hfs.mjs"
16
- import { decoratorArguments, decoratorCallee, isImportedFrom } from "./lib/import-source.mjs"
17
- import { isTransportSlot } from "./lib/transport-slots.mjs"
18
- import { typed } from "./lib/types.mjs"
19
-
13
+ import ts from "typescript";
14
+ import { keyName, walk } from "./lib/ast.js";
15
+ import { hfsOf } from "./lib/hfs.js";
16
+ import { decoratorArguments, decoratorCallee, isImportedFrom } from "./lib/import-source.js";
17
+ import { isTransportSlot } from "./lib/transport-slots.js";
18
+ import { isTsNode, typed } from "./lib/types.js";
20
19
  /** The HTTP route decorators of `@nestjs/common` (`Sse` is a route too: a `text/event-stream` GET that needs its own evidence). */
21
- const HTTP_ROUTES = ["Get", "Post", "Put", "Patch", "Delete", "All", "Options", "Head", "Sse"]
22
-
20
+ const HTTP_ROUTES = ["Get", "Post", "Put", "Patch", "Delete", "All", "Options", "Head", "Sse"];
23
21
  /** The slot of server-sent-events doors: the one place an `@Sse` route is evidence of itself. */
24
- const SSE_SLOT = "be.feature.realtime.sse"
25
-
22
+ const SSE_SLOT = "be.feature.realtime.sse";
26
23
  /** True when a declaration file is owned by the capability `operations` of a platform slot. */
27
- const declaredByOperations = (hfs, file) => hfs.slotOf(file) === "be.platform" && hfs.ownerOf(file)?.split("/").pop() === "operations"
28
-
24
+ const declaredByOperations = (hfs, file) => hfs.slotOf(file) === "be.platform" && hfs.ownerOf(file)?.split("/").pop() === "operations";
29
25
  /** The declarations of a symbol after alias resolution. */
30
26
  const declarationsOfSymbol = (checker, symbol) => {
31
- if (!symbol) return []
32
- const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol
33
- return target.getDeclarations?.() ?? []
34
- }
35
-
27
+ if (!symbol)
28
+ return [];
29
+ const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
30
+ return target.getDeclarations?.() ?? [];
31
+ };
32
+ /** `declaration.name?.text` of a declaration whose kind is not known: the text of its name node, or undefined. */
33
+ const nameTextOf = (declaration) => {
34
+ const name = "name" in declaration ? declaration.name : undefined;
35
+ return isTsNode(name) && "text" in name && typeof name.text === "string" ? name.text : undefined;
36
+ };
37
+ /** Whether a type carries the reference object flag (`Array<T>`, a tuple, a generic instantiation), so it has type arguments. */
38
+ const isTypeReference = (type) => "objectFlags" in type && typeof type.objectFlags === "number" && (type.objectFlags & ts.ObjectFlags.Reference) !== 0;
39
+ /** The type annotation a parameter carries: its own, or that of the parameter a `TSParameterProperty` wraps. */
40
+ const paramAnnotation = (param) => ("typeAnnotation" in param ? param.typeAnnotation : undefined) ?? (param.type === "TSParameterProperty" ? param.parameter.typeAnnotation : undefined);
36
41
  /** True when the symbol is the canon type `name` of the operations capability. */
37
- const isCanonType = (hfs, checker, symbol, name) => declarationsOfSymbol(checker, symbol).some((declaration) => declaration.name?.text === name && declaredByOperations(hfs, String(declaration.getSourceFile().fileName).replace(/\\/g, "/")))
38
-
39
- const F = ts.TypeFlags
40
-
42
+ const isCanonType = (hfs, checker, symbol, name) => declarationsOfSymbol(checker, symbol).some((declaration) => nameTextOf(declaration) === name && declaredByOperations(hfs, String(declaration.getSourceFile().fileName).replace(/\\/g, "/")));
43
+ const F = ts.TypeFlags;
41
44
  /** Optional object fields can be absent; an operation's root input/value must itself be a JSON value. */
42
- const rootMayBeAbsent = (type) => Boolean(type.flags & (F.Undefined | F.Void)) || (type.isUnion() && type.types.some(rootMayBeAbsent))
43
-
45
+ const rootMayBeAbsent = (type) => Boolean(type.flags & (F.Undefined | F.Void)) || (type.isUnion() && type.types.some(rootMayBeAbsent));
44
46
  /** Follow constant aliases and declaration wrappers without trusting an asserted type. */
45
47
  const expressionOf = (checker, node, seen = new Set()) => {
46
- if (!node || seen.has(node)) return node
47
- seen.add(node)
48
- if (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node) || ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node)) return expressionOf(checker, node.expression, seen)
48
+ if (!node || seen.has(node))
49
+ return node;
50
+ seen.add(node);
51
+ if (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node) || ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node))
52
+ return expressionOf(checker, node.expression, seen);
49
53
  if (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isQualifiedName(node)) {
50
54
  for (const declaration of declarationsOfSymbol(checker, checker.getSymbolAtLocation(node))) {
51
55
  if (ts.isShorthandPropertyAssignment(declaration)) {
52
- const value = checker.getShorthandAssignmentValueSymbol(declaration)
53
- const home = declarationsOfSymbol(checker, value).find((candidate) => ts.isVariableDeclaration(candidate) && candidate.initializer)
54
- if (home) return expressionOf(checker, home.initializer, seen)
56
+ const value = checker.getShorthandAssignmentValueSymbol(declaration);
57
+ const home = declarationsOfSymbol(checker, value).find((candidate) => ts.isVariableDeclaration(candidate) && Boolean(candidate.initializer));
58
+ if (home)
59
+ return expressionOf(checker, home.initializer, seen);
55
60
  }
56
- if ((ts.isVariableDeclaration(declaration) || ts.isPropertyAssignment(declaration)) && declaration.initializer) return expressionOf(checker, declaration.initializer, seen)
61
+ if ((ts.isVariableDeclaration(declaration) || ts.isPropertyAssignment(declaration)) && declaration.initializer)
62
+ return expressionOf(checker, declaration.initializer, seen);
57
63
  }
58
64
  }
59
- return node
60
- }
61
-
65
+ return node;
66
+ };
62
67
  /** A schema is a named declaration of its boundary owner, including re-exports and local aliases. */
63
68
  const ownerSchema = (hfs, checker, node, seen = new Set()) => {
64
- if (!node || seen.has(node)) return false
65
- seen.add(node)
66
- if (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node) || ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node)) return ownerSchema(hfs, checker, node.expression, seen)
67
- if (!ts.isIdentifier(node) && !ts.isPropertyAccessExpression(node)) return false
68
- const type = checker.getTypeAtLocation(node)
69
- const parser = type.getProperty("safeParse")
70
- if (!(parser?.getDeclarations() ?? []).some((declaration) => /\/node_modules\/zod\//.test(declaration.getSourceFile().fileName.replace(/\\/g, "/")))) return false
69
+ if (!node || seen.has(node))
70
+ return false;
71
+ seen.add(node);
72
+ if (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node) || ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node))
73
+ return ownerSchema(hfs, checker, node.expression, seen);
74
+ if (!ts.isIdentifier(node) && !ts.isPropertyAccessExpression(node))
75
+ return false;
76
+ const type = checker.getTypeAtLocation(node);
77
+ const parser = type.getProperty("safeParse");
78
+ if (!(parser?.getDeclarations() ?? []).some((declaration) => /\/node_modules\/zod\//.test(declaration.getSourceFile().fileName.replace(/\\/g, "/"))))
79
+ return false;
71
80
  for (const declaration of declarationsOfSymbol(checker, checker.getSymbolAtLocation(node))) {
72
- const source = declaration.getSourceFile()
73
- const file = source.fileName
74
- const module = checker.getSymbolAtLocation(source)
75
- const exported = module && checker.getExportsOfModule(module).some((symbol) => declarationsOfSymbol(checker, symbol).includes(declaration))
76
- if (/\.schema\.ts$/.test(file) && ["domain", "platform", "integrations"].includes(hfs.tierOf(file)) && exported) return true
77
- if (ts.isVariableDeclaration(declaration) && declaration.initializer && ownerSchema(hfs, checker, declaration.initializer, seen)) return true
81
+ const source = declaration.getSourceFile();
82
+ const file = source.fileName;
83
+ const module = checker.getSymbolAtLocation(source);
84
+ const exported = module && checker.getExportsOfModule(module).some((symbol) => declarationsOfSymbol(checker, symbol).includes(declaration));
85
+ const tier = hfs.tierOf(file);
86
+ if (/\.schema\.ts$/.test(file) && tier !== null && ["domain", "platform", "integrations"].includes(tier) && exported)
87
+ return true;
88
+ if (ts.isVariableDeclaration(declaration) && declaration.initializer && ownerSchema(hfs, checker, declaration.initializer, seen))
89
+ return true;
78
90
  if (ts.isShorthandPropertyAssignment(declaration)) {
79
91
  for (const home of declarationsOfSymbol(checker, checker.getShorthandAssignmentValueSymbol(declaration))) {
80
- if (ts.isVariableDeclaration(home) && home.initializer && ownerSchema(hfs, checker, home.initializer, seen)) return true
92
+ if (ts.isVariableDeclaration(home) && home.initializer && ownerSchema(hfs, checker, home.initializer, seen))
93
+ return true;
81
94
  }
82
95
  }
83
96
  }
84
- return false
85
- }
86
-
97
+ return false;
98
+ };
87
99
  /** Read a property initializer from a closed declaration object, following an alias of that object. */
88
100
  const propertyValue = (checker, expression, name) => {
89
- const object = expressionOf(checker, expression)
90
- if (!object) return null
91
- const property = checker.getTypeAtLocation(object).getProperty(name)
101
+ const object = expressionOf(checker, expression);
102
+ if (!object)
103
+ return null;
104
+ const property = checker.getTypeAtLocation(object).getProperty(name);
92
105
  for (const declaration of property?.getDeclarations() ?? []) {
93
- if (ts.isPropertyAssignment(declaration)) return declaration.initializer
94
- if (ts.isShorthandPropertyAssignment(declaration)) return declaration.name
106
+ if (ts.isPropertyAssignment(declaration))
107
+ return declaration.initializer;
108
+ if (ts.isShorthandPropertyAssignment(declaration))
109
+ return declaration.name;
95
110
  }
96
- return null
97
- }
98
-
111
+ return null;
112
+ };
99
113
  /** A spec registers tables to test the platform capability; such a table is local to the spec and serves no operation. */
100
- const isSpecFile = (filename) => /\.(?:spec|e2e-spec|integration-spec|contract-spec)\.ts$/.test(filename.replaceAll("\\", "/"))
101
-
102
- const TS_WRAPPERS = new Set(["TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "TSTypeAssertion"])
103
-
114
+ const isSpecFile = (filename) => /\.(?:spec|e2e-spec|integration-spec|contract-spec)\.ts$/.test(filename.replaceAll("\\", "/"));
115
+ /** The root a node hangs from: its Program. */
116
+ const rootOf = (node) => {
117
+ let current = node;
118
+ while (current.parent)
119
+ current = current.parent;
120
+ return current;
121
+ };
122
+ const TS_WRAPPERS = new Set(["TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "TSTypeAssertion"]);
104
123
  /**
105
124
  * Whether the table a `defineOperations` call makes leaves its file: `export const X = ...`, `export { X }` or `export default X`.
106
125
  * A spec may keep a stub table to itself; one it exports can be imported by production code, so it is judged like any table.
107
126
  *
108
- * @param {object} node - The CallExpression (ESTree).
109
- * @returns {boolean} True when the registered table is exported.
127
+ * @param node - The CallExpression (ESTree).
128
+ * @returns True when the registered table is exported.
110
129
  */
111
130
  const tableLeavesFile = (node) => {
112
- let value = node
113
- while (TS_WRAPPERS.has(value.parent?.type)) value = value.parent
114
- const parent = value.parent
115
- if (parent?.type === "ExportDefaultDeclaration") return true
116
- if (parent?.type !== "VariableDeclarator" || parent.init !== value || parent.id.type !== "Identifier") return false
117
- if (parent.parent?.parent?.type === "ExportNamedDeclaration") return true
118
- let program = parent
119
- while (program.parent) program = program.parent
131
+ let value = node;
132
+ for (let wrapper = value.parent; wrapper && TS_WRAPPERS.has(wrapper.type); wrapper = value.parent)
133
+ value = wrapper;
134
+ const parent = value.parent;
135
+ if (parent?.type === "ExportDefaultDeclaration")
136
+ return true;
137
+ if (parent?.type !== "VariableDeclarator" || parent.init !== value || parent.id.type !== "Identifier")
138
+ return false;
139
+ if (parent.parent?.parent?.type === "ExportNamedDeclaration")
140
+ return true;
141
+ const idName = parent.id.name;
142
+ const program = rootOf(parent);
143
+ // The root of every linted tree is its Program.
144
+ if (program.type !== "Program")
145
+ return false;
120
146
  return program.body.some((statement) => {
121
- if (statement.type === "ExportDefaultDeclaration") return statement.declaration?.type === "Identifier" && statement.declaration.name === parent.id.name
122
- return statement.type === "ExportNamedDeclaration" && statement.specifiers.some((specifier) => specifier.local.name === parent.id.name)
123
- })
124
- }
125
-
147
+ if (statement.type === "ExportDefaultDeclaration")
148
+ return statement.declaration?.type === "Identifier" && statement.declaration.name === idName;
149
+ return statement.type === "ExportNamedDeclaration" && statement.specifiers.some((specifier) => specifier.local.type === "Identifier" && specifier.local.name === idName);
150
+ });
151
+ };
126
152
  /** The operation table must supply the runtime schemas that a generic request type cannot validate. */
127
153
  export const operationTableSchemas = {
128
154
  meta: {
@@ -135,88 +161,104 @@ export const operationTableSchemas = {
135
161
  },
136
162
  },
137
163
  create(context) {
138
- const inSpec = isSpecFile(context.filename)
139
- const hfs = hfsOf(context)
140
- const { checker, toTs } = typed(context)
164
+ const inSpec = isSpecFile(context.filename);
165
+ const hfs = hfsOf(context);
166
+ const { checker, toTs } = typed(context);
141
167
  return {
142
168
  CallExpression(node) {
143
- const call = toTs(node)
144
- if (!isCanonType(hfs, checker, checker.getSymbolAtLocation(call.expression), "defineOperations")) return
145
- if (inSpec && !tableLeavesFile(node)) return
146
- const argument = expressionOf(checker, call.arguments[0])
147
- const entries = argument ? checker.getPropertiesOfType(checker.getTypeAtLocation(argument)) : []
169
+ const call = toTs(node);
170
+ if (!isCanonType(hfs, checker, checker.getSymbolAtLocation(call.expression), "defineOperations"))
171
+ return;
172
+ if (inSpec && !tableLeavesFile(node))
173
+ return;
174
+ const argument = expressionOf(checker, call.arguments[0]);
175
+ const entries = argument ? checker.getPropertiesOfType(checker.getTypeAtLocation(argument)) : [];
148
176
  if (entries.length === 0) {
149
- context.report({ node, messageId: "table" })
150
- return
177
+ context.report({ node, messageId: "table" });
178
+ return;
151
179
  }
152
180
  for (const entry of entries) {
153
- const declaration = entry.getDeclarations()?.find((candidate) => ts.isPropertyAssignment(candidate) || ts.isShorthandPropertyAssignment(candidate))
154
- const value = declaration && expressionOf(checker, ts.isShorthandPropertyAssignment(declaration) ? declaration.name : declaration.initializer)
155
- const helper = value && ts.isCallExpression(value) && ["query", "mutation"].some((name) => isCanonType(hfs, checker, checker.getSymbolAtLocation(value.expression), name))
156
- const options = helper ? value.arguments[0] : null
157
- if (!["input", "output"].every((name) => ownerSchema(hfs, checker, propertyValue(checker, options, name)))) context.report({ node, messageId: "schemas", data: { operation: entry.getName() } })
181
+ const declaration = entry.getDeclarations()?.find((candidate) => ts.isPropertyAssignment(candidate) || ts.isShorthandPropertyAssignment(candidate));
182
+ const value = declaration && expressionOf(checker, ts.isShorthandPropertyAssignment(declaration) ? declaration.name : declaration.initializer);
183
+ const options = value && ts.isCallExpression(value) && ["query", "mutation"].some((name) => isCanonType(hfs, checker, checker.getSymbolAtLocation(value.expression), name)) ? value.arguments[0] : null;
184
+ if (!["input", "output"].every((name) => ownerSchema(hfs, checker, propertyValue(checker, options, name))))
185
+ context.report({ node, messageId: "schemas", data: { operation: entry.getName() } });
158
186
  }
159
187
  },
160
- }
188
+ };
161
189
  },
162
- }
163
-
190
+ };
164
191
  /**
165
192
  * Why a type says nothing on the wire, or null when the checker can express it.
166
193
  *
167
- * @param {object} checker - The program's type checker.
168
- * @param {object} type - A TypeScript type.
169
- * @param {Set<object>} seen - The types already judged (recursive types).
170
- * @returns {string | null} The reason, or null.
194
+ * @param checker - The program's type checker.
195
+ * @param type - A TypeScript type.
196
+ * @param seen - The types already judged (recursive types).
197
+ * @returns The reason, or null.
171
198
  */
172
199
  const whyUndecidable = (checker, type, seen = new Set(), schemaBacked = false) => {
173
- if (seen.has(type)) return null
174
- seen.add(type)
175
- const flags = type.flags
176
- if (flags & F.Any) return "any"
177
- if (flags & F.Unknown) return "unknown"
178
- if (flags & F.Never) return "never"
179
- if (flags & F.TypeParameter) return "an unbound generic"
180
- if (flags & F.NonPrimitive) return "object with no declared members"
181
- if (flags & (F.BigInt | F.BigIntLiteral | F.ESSymbol | F.UniqueESSymbol)) return "bigint or symbol"
200
+ if (seen.has(type))
201
+ return null;
202
+ seen.add(type);
203
+ const flags = type.flags;
204
+ if (flags & F.Any)
205
+ return "any";
206
+ if (flags & F.Unknown)
207
+ return "unknown";
208
+ if (flags & F.Never)
209
+ return "never";
210
+ if (flags & F.TypeParameter)
211
+ return "an unbound generic";
212
+ if (flags & F.NonPrimitive)
213
+ return "object with no declared members";
214
+ if (flags & (F.BigInt | F.BigIntLiteral | F.ESSymbol | F.UniqueESSymbol))
215
+ return "bigint or symbol";
182
216
  if (type.isUnion() || type.isIntersection()) {
183
217
  for (const member of type.types) {
184
- if (member.flags & (F.Undefined | F.Void)) continue
185
- const why = whyUndecidable(checker, member, seen, schemaBacked)
186
- if (why) return why
218
+ if (member.flags & (F.Undefined | F.Void))
219
+ continue;
220
+ const why = whyUndecidable(checker, member, seen, schemaBacked);
221
+ if (why)
222
+ return why;
187
223
  }
188
- return null
224
+ return null;
189
225
  }
190
226
  if (flags & F.Object) {
191
- if (type.getCallSignatures().length || type.getConstructSignatures().length) return "a function"
227
+ if (type.getCallSignatures().length || type.getConstructSignatures().length)
228
+ return "a function";
192
229
  if (checker.isArrayType(type) || checker.isTupleType(type)) {
193
- for (const item of checker.getTypeArguments(type)) {
194
- const why = whyUndecidable(checker, item, seen, schemaBacked)
195
- if (why) return why
230
+ // An array or tuple type is always a type reference.
231
+ for (const item of isTypeReference(type) ? checker.getTypeArguments(type) : []) {
232
+ const why = whyUndecidable(checker, item, seen, schemaBacked);
233
+ if (why)
234
+ return why;
196
235
  }
197
- return null
236
+ return null;
198
237
  }
199
- const own = type.getSymbol()
200
- if (own && !own.getName().startsWith("__") && (own.getDeclarations() ?? []).some((declaration) => /[\\/]typescript[\\/]lib[\\/]lib\./.test(declaration.getSourceFile().fileName))) return `${own.getName()}, which is not a JSON value`
201
- const props = checker.getPropertiesOfType(type)
202
- const index = checker.getIndexInfosOfType(type)
203
- if (props.length === 0 && index.length === 0 && !schemaBacked) return "an object type with no members"
238
+ const own = type.getSymbol();
239
+ if (own && !own.getName().startsWith("__") && (own.getDeclarations() ?? []).some((declaration) => /[\\/]typescript[\\/]lib[\\/]lib\./.test(declaration.getSourceFile().fileName)))
240
+ return `${own.getName()}, which is not a JSON value`;
241
+ const props = checker.getPropertiesOfType(type);
242
+ const index = checker.getIndexInfosOfType(type);
243
+ if (props.length === 0 && index.length === 0 && !schemaBacked)
244
+ return "an object type with no members";
204
245
  for (const info of index) {
205
246
  // Zod's strict empty object infers Record<string, never>: no key is permitted, rather than an unknown value.
206
- if (schemaBacked && (info.type.flags & F.Never)) continue
207
- const why = whyUndecidable(checker, info.type, seen, schemaBacked)
208
- if (why) return `a record of ${why}`
247
+ if (schemaBacked && (info.type.flags & F.Never))
248
+ continue;
249
+ const why = whyUndecidable(checker, info.type, seen, schemaBacked);
250
+ if (why)
251
+ return `a record of ${why}`;
209
252
  }
210
253
  for (const prop of props) {
211
- const why = whyUndecidable(checker, checker.getTypeOfSymbol(prop), seen, schemaBacked)
212
- if (why) return `${prop.getName()}: ${why}`
254
+ const why = whyUndecidable(checker, checker.getTypeOfSymbol(prop), seen, schemaBacked);
255
+ if (why)
256
+ return `${prop.getName()}: ${why}`;
213
257
  }
214
258
  }
215
- return null
216
- }
217
-
259
+ return null;
260
+ };
218
261
  // -- operation-contract-decidable --------------------------------------------------------------------------------
219
-
220
262
  /** No operation contract with an input, an output or a refusal set the contract emit cannot express. */
221
263
  export const operationContractDecidable = {
222
264
  meta: {
@@ -229,243 +271,267 @@ export const operationContractDecidable = {
229
271
  },
230
272
  },
231
273
  create(context) {
232
- const inSpec = isSpecFile(context.filename)
233
- const hfs = hfsOf(context)
234
- const { checker, toTs } = typed(context)
235
- const inOwner = declaredByOperations(hfs, context.filename.replace(/\\/g, "/"))
274
+ const inSpec = isSpecFile(context.filename);
275
+ const hfs = hfsOf(context);
276
+ const { checker, toTs } = typed(context);
277
+ const inOwner = declaredByOperations(hfs, context.filename.replace(/\\/g, "/"));
236
278
  const judge = (node, contract, schemaCall = null) => {
237
- const symbol = contract.aliasSymbol ?? contract.getSymbol()
238
- if (!isCanonType(hfs, checker, symbol, "OperationContract")) return
239
- const call = schemaCall ?? (node.type === "CallExpression" ? toTs(node) : null)
240
- const schemaBacked = call && ["query", "mutation"].some((name) => isCanonType(hfs, checker, checker.getSymbolAtLocation(call.expression), name)) && ["input", "output"].every((name) => ownerSchema(hfs, checker, propertyValue(checker, call.arguments[0], name)))
241
- const [input, output, refusal] = (contract.objectFlags & ts.ObjectFlags.Reference) !== 0 ? checker.getTypeArguments(contract) : (contract.aliasTypeArguments ?? [])
279
+ const symbol = contract.aliasSymbol ?? contract.getSymbol();
280
+ if (!isCanonType(hfs, checker, symbol, "OperationContract"))
281
+ return;
282
+ const call = schemaCall ?? (node.type === "CallExpression" ? toTs(node) : null);
283
+ const schemaBacked = Boolean(call && ["query", "mutation"].some((name) => isCanonType(hfs, checker, checker.getSymbolAtLocation(call.expression), name)) && ["input", "output"].every((name) => ownerSchema(hfs, checker, propertyValue(checker, call.arguments[0], name))));
284
+ const [input, output, refusal] = isTypeReference(contract) ? checker.getTypeArguments(contract) : (contract.aliasTypeArguments ?? []);
242
285
  for (const [label, type] of [["input", input], ["output", output]]) {
243
- const why = type ? rootMayBeAbsent(type) ? "undefined or void at the root" : whyUndecidable(checker, type, new Set(), schemaBacked) : null
244
- if (why) context.report({ node, messageId: "type", data: { label, why } })
286
+ const why = type ? rootMayBeAbsent(type) ? "undefined or void at the root" : whyUndecidable(checker, type, new Set(), schemaBacked) : null;
287
+ if (why)
288
+ context.report({ node, messageId: "type", data: { label, why } });
245
289
  }
246
290
  if (refusal && !(refusal.flags & F.Never)) {
247
- const members = refusal.isUnion() ? refusal.types : [refusal]
248
- if (!members.every((member) => member.isStringLiteral())) context.report({ node, messageId: "refusal", data: { found: checker.typeToString(refusal) } })
291
+ const members = refusal.isUnion() ? refusal.types : [refusal];
292
+ if (!members.every((member) => member.isStringLiteral()))
293
+ context.report({ node, messageId: "refusal", data: { found: checker.typeToString(refusal) } });
249
294
  }
250
- }
295
+ };
251
296
  return {
252
297
  TSTypeReference(node) {
253
298
  // The capability declares generic OperationContract/OperationTable bounds here; concrete registrations below
254
299
  // still owe the same closed parsed types as operations declared anywhere else.
255
- if (inOwner || inSpec) return
256
- const tsNode = toTs(node)
257
- const type = checker.getTypeFromTypeNode(tsNode)
258
- if (type.getSymbol() || type.aliasSymbol) judge(node, type)
300
+ if (inOwner || inSpec)
301
+ return;
302
+ const tsNode = toTs(node);
303
+ const type = checker.getTypeFromTypeNode(tsNode);
304
+ if (type.getSymbol() || type.aliasSymbol)
305
+ judge(node, type);
259
306
  },
260
307
  CallExpression(node) {
261
- const call = toTs(node)
308
+ const call = toTs(node);
262
309
  if ((inOwner || inSpec) && isCanonType(hfs, checker, checker.getSymbolAtLocation(call.expression), "defineOperations")) {
263
- if (inSpec && !tableLeavesFile(node)) return
264
- const argument = call.arguments[0]
265
- const source = expressionOf(checker, argument)
266
- const entries = argument ? checker.getPropertiesOfType(checker.getTypeAtLocation(argument)) : []
310
+ if (inSpec && !tableLeavesFile(node))
311
+ return;
312
+ const argument = call.arguments[0];
313
+ const source = expressionOf(checker, argument);
314
+ const entries = argument ? checker.getPropertiesOfType(checker.getTypeAtLocation(argument)) : [];
267
315
  for (const entry of entries) {
268
- const contract = checker.getTypeOfSymbol(entry)
269
- const actual = source ? propertyValue(checker, source, entry.getName()) : null
270
- const value = expressionOf(checker, actual)
316
+ const contract = checker.getTypeOfSymbol(entry);
317
+ const actual = source ? propertyValue(checker, source, entry.getName()) : null;
318
+ const value = expressionOf(checker, actual);
271
319
  // Plain helper calls are judged once by their own CallExpression. A declaration annotation can widen
272
320
  // that result before registration, so its served type also needs a check.
273
- const helper = value && ts.isCallExpression(value) && ["query", "mutation"].some((name) => isCanonType(hfs, checker, checker.getSymbolAtLocation(value.expression), name)) ? value : null
274
- if (inSpec || !helper || contract !== checker.getTypeAtLocation(helper)) judge(node, contract, helper)
321
+ const helper = value && ts.isCallExpression(value) && ["query", "mutation"].some((name) => isCanonType(hfs, checker, checker.getSymbolAtLocation(value.expression), name)) ? value : null;
322
+ if (inSpec || !helper || contract !== checker.getTypeAtLocation(helper))
323
+ judge(node, contract, helper);
275
324
  }
276
- return
325
+ return;
277
326
  }
278
- if (inSpec) return
279
- if (inOwner &&!["query", "mutation"].some((name) => isCanonType(hfs, checker, checker.getSymbolAtLocation(call.expression), name))) return
280
- const type = checker.getTypeAtLocation(call)
281
- if (type.getSymbol()) judge(node, type)
327
+ if (inSpec)
328
+ return;
329
+ if (inOwner && !["query", "mutation"].some((name) => isCanonType(hfs, checker, checker.getSymbolAtLocation(call.expression), name)))
330
+ return;
331
+ const type = checker.getTypeAtLocation(call);
332
+ if (type.getSymbol())
333
+ judge(node, type);
282
334
  },
283
- }
335
+ };
284
336
  },
285
- }
286
-
337
+ };
287
338
  // -- operation-route-driven-by-table -----------------------------------------------------------------------------
288
-
289
339
  /** The runtime table named by a `typeof OPERATIONS` type argument, including named aliases of that type. */
290
340
  const tableExpressionOf = (checker, type, seen = new Set()) => {
291
- if (!type || seen.has(type)) return null
292
- seen.add(type)
293
- if (ts.isTypeQueryNode(type)) return expressionOf(checker, type.exprName)
294
- if (ts.isParenthesizedTypeNode(type)) return tableExpressionOf(checker, type.type, seen)
295
- if (!ts.isTypeReferenceNode(type)) return null
341
+ if (!type || seen.has(type))
342
+ return null;
343
+ seen.add(type);
344
+ if (ts.isTypeQueryNode(type))
345
+ return expressionOf(checker, type.exprName);
346
+ if (ts.isParenthesizedTypeNode(type))
347
+ return tableExpressionOf(checker, type.type, seen);
348
+ if (!ts.isTypeReferenceNode(type))
349
+ return null;
296
350
  for (const declaration of declarationsOfSymbol(checker, checker.getSymbolAtLocation(type.typeName))) {
297
- if (ts.isTypeAliasDeclaration(declaration)) return tableExpressionOf(checker, declaration.type, seen)
351
+ if (ts.isTypeAliasDeclaration(declaration))
352
+ return tableExpressionOf(checker, declaration.type, seen);
298
353
  }
299
- return null
300
- }
301
-
302
- /** The canon alias a type annotation node names (`OperationRequest`, `OperationReply`), with its table type argument. */
354
+ return null;
355
+ };
303
356
  const canonReference = (hfs, checker, toTs, annotation) => {
304
- let node = annotation
305
- if (node?.type === "TSTypeAnnotation") node = node.typeAnnotation
306
- if (node?.type !== "TSTypeReference") return null
307
- const tsNode = toTs(node)
308
- const symbol = checker.getSymbolAtLocation(tsNode.typeName)
357
+ let node = annotation;
358
+ if (node?.type === "TSTypeAnnotation")
359
+ node = node.typeAnnotation;
360
+ if (node?.type !== "TSTypeReference")
361
+ return null;
362
+ const tsNode = toTs(node);
363
+ const symbol = checker.getSymbolAtLocation(tsNode.typeName);
309
364
  for (const name of ["OperationRequest", "OperationReply"]) {
310
365
  if (isCanonType(hfs, checker, symbol, name)) {
311
- const argument = tsNode.typeArguments?.[0]
312
- return { name, table: argument ? checker.getTypeFromTypeNode(argument) : null, expression: tableExpressionOf(checker, argument) }
366
+ const argument = tsNode.typeArguments?.[0];
367
+ return { name, table: argument ? checker.getTypeFromTypeNode(argument) : null, expression: tableExpressionOf(checker, argument) };
313
368
  }
314
369
  }
315
- return null
316
- }
317
-
370
+ return null;
371
+ };
318
372
  /** The type annotation a return type wraps: `Promise<X>` gives `X`. */
319
373
  const unwrapPromise = (annotation) => {
320
- const node = annotation?.type === "TSTypeAnnotation" ? annotation.typeAnnotation : annotation
321
- if (node?.type === "TSTypeReference" && node.typeName?.type === "Identifier" && node.typeName.name === "Promise") return node.typeArguments?.params?.[0] ?? node.typeParameters?.params?.[0] ?? null
322
- return node ?? null
323
- }
324
-
374
+ const node = annotation?.type === "TSTypeAnnotation" ? annotation.typeAnnotation : annotation;
375
+ if (node?.type === "TSTypeReference" && node.typeName?.type === "Identifier" && node.typeName.name === "Promise")
376
+ return node.typeArguments?.params?.[0] ?? null;
377
+ return node ?? null;
378
+ };
325
379
  /** The canon request and reply annotations of one HTTP method. */
326
380
  const operationReferences = (context, method) => {
327
- const hfs = hfsOf(context)
328
- const { checker, toTs } = typed(context)
329
- const params = method.value.params.filter((param) => (param.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Body")))
381
+ const hfs = hfsOf(context);
382
+ const { checker, toTs } = typed(context);
383
+ const params = method.value.params.filter((param) => (param.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Body")));
330
384
  return {
331
- request: params.map((param) => canonReference(hfs, checker, toTs, param.typeAnnotation ?? param.parameter?.typeAnnotation)).find((reference) => reference?.name === "OperationRequest") ?? null,
385
+ request: params.map((param) => canonReference(hfs, checker, toTs, paramAnnotation(param))).find((reference) => reference?.name === "OperationRequest") ?? null,
332
386
  reply: canonReference(hfs, checker, toTs, unwrapPromise(method.value.returnType)),
333
- }
334
- }
335
-
387
+ };
388
+ };
336
389
  /** A route's table must be the nonempty result of the canon defineOperations, including an imported app table. */
337
390
  export const operationRouteEvidence = (context) => {
338
- const hfs = hfsOf(context)
339
- const { program, checker } = typed(context)
340
- let tables
391
+ const hfs = hfsOf(context);
392
+ const { program, checker } = typed(context);
393
+ let tables;
341
394
  const declaredTables = () => {
342
- if (tables) return tables
343
- tables = new Set()
395
+ if (tables)
396
+ return tables;
397
+ const found = new Set();
398
+ tables = found;
344
399
  const visit = (node) => {
345
400
  if (ts.isCallExpression(node) && isCanonType(hfs, checker, checker.getSymbolAtLocation(node.expression), "defineOperations")) {
346
- const table = checker.getTypeAtLocation(node)
347
- if (checker.getPropertiesOfType(table).length > 0) tables.add(table)
401
+ const table = checker.getTypeAtLocation(node);
402
+ if (checker.getPropertiesOfType(table).length > 0)
403
+ found.add(table);
348
404
  }
349
- ts.forEachChild(node, visit)
350
- }
405
+ ts.forEachChild(node, visit);
406
+ };
351
407
  for (const source of program.getSourceFiles()) {
352
408
  // A table made in a spec is never an app's declared table, even when the spec exports it.
353
- if (!source.isDeclarationFile && !isSpecFile(source.fileName) && hfs.slotOf(source.fileName)) visit(source)
409
+ if (!source.isDeclarationFile && !isSpecFile(source.fileName) && hfs.slotOf(source.fileName))
410
+ visit(source);
354
411
  }
355
- return tables
356
- }
412
+ return found;
413
+ };
357
414
  return (method) => {
358
- const { request, reply } = operationReferences(context, method)
359
- return request?.table != null && reply?.name === "OperationReply" && request.table === reply.table && declaredTables().has(request.table)
360
- }
361
- }
362
-
415
+ const { request, reply } = operationReferences(context, method);
416
+ return request?.table != null && reply?.name === "OperationReply" && request.table === reply.table && declaredTables().has(request.table);
417
+ };
418
+ };
363
419
  /** A symbol declared by the app's domain identity capability, rather than a same-named local decorator or enum. */
364
420
  const identityExport = (context, node, name) => {
365
- if (!node) return false
366
- const hfs = hfsOf(context)
367
- const { checker, toTs } = typed(context)
368
- const target = toTs(node)
369
- if (!target) return false
421
+ if (!node)
422
+ return false;
423
+ const hfs = hfsOf(context);
424
+ const { checker, toTs } = typed(context);
425
+ const target = toTs(node);
426
+ if (!target)
427
+ return false;
370
428
  return declarationsOfSymbol(checker, checker.getSymbolAtLocation(target)).some((declaration) => {
371
- const file = declaration.getSourceFile().fileName
372
- return declaration.name?.text === name && hfs.tierOf(file) === "domain" && hfs.ownerOf(file)?.split("/").pop() === "identity"
373
- })
374
- }
375
-
376
- const REST_REASONS = new Set(["Health", "AuthHandshake", "SignedWebhook"])
377
- const FILE_INTERCEPTORS = ["FileInterceptor", "FilesInterceptor", "AnyFilesInterceptor", "FileFieldsInterceptor"]
378
-
429
+ const file = declaration.getSourceFile().fileName;
430
+ return nameTextOf(declaration) === name && hfs.tierOf(file) === "domain" && hfs.ownerOf(file)?.split("/").pop() === "identity";
431
+ });
432
+ };
433
+ const REST_REASONS = new Set(["Health", "AuthHandshake", "SignedWebhook"]);
434
+ const FILE_INTERCEPTORS = ["FileInterceptor", "FilesInterceptor", "AnyFilesInterceptor", "FileFieldsInterceptor"];
379
435
  /** A stream actually returned by this method; importing or mentioning a stream constructor proves nothing. */
380
436
  const returnsBytes = (context, method) => {
381
- const seen = new Set()
437
+ const seen = new Set();
382
438
  const isBytes = (expression) => {
383
- if (!expression || seen.has(expression)) return false
384
- seen.add(expression)
385
- if (["AwaitExpression", "TSAsExpression", "TSTypeAssertion", "TSNonNullExpression"].includes(expression.type)) return isBytes(expression.argument ?? expression.expression)
386
- if (expression.type === "NewExpression" && isImportedFrom(context, expression.callee, "@nestjs/common", "StreamableFile")) return true
387
- if (expression.type === "CallExpression" && isImportedFrom(context, expression.callee, ["node:fs", "fs"], "createReadStream")) return true
388
- if (expression.type !== "Identifier") return false
439
+ if (!expression || seen.has(expression))
440
+ return false;
441
+ seen.add(expression);
442
+ if (expression.type === "AwaitExpression")
443
+ return isBytes(expression.argument);
444
+ if (expression.type === "TSAsExpression" || expression.type === "TSTypeAssertion" || expression.type === "TSNonNullExpression")
445
+ return isBytes(expression.expression);
446
+ if (expression.type === "NewExpression" && isImportedFrom(context, expression.callee, "@nestjs/common", "StreamableFile"))
447
+ return true;
448
+ if (expression.type === "CallExpression" && isImportedFrom(context, expression.callee, ["node:fs", "fs"], "createReadStream"))
449
+ return true;
450
+ if (expression.type !== "Identifier")
451
+ return false;
389
452
  for (let scope = context.sourceCode.getScope(expression); scope; scope = scope.upper) {
390
- const variable = scope.set.get(expression.name)
391
- if (variable) return variable.defs.some((definition) => definition.type === "Variable" && isBytes(definition.node.init))
453
+ const variable = scope.set.get(expression.name);
454
+ if (variable)
455
+ return variable.defs.some((definition) => definition.type === "Variable" && isBytes(definition.node.init));
392
456
  }
393
- return false
394
- }
395
- let found = false
457
+ return false;
458
+ };
459
+ let found = false;
396
460
  walk(method.value.body, (node) => {
397
- if (node.type === "ReturnStatement" && isBytes(node.argument)) found = true
398
- }, { intoFunctions: false })
399
- return found
400
- }
401
-
461
+ if (node.type === "ReturnStatement" && isBytes(node.argument))
462
+ found = true;
463
+ }, { intoFunctions: false });
464
+ return found;
465
+ };
402
466
  /** True when a class declaration implements the `CanActivate` of `@nestjs/common` (resolved by symbol, not by spelling). */
403
- const implementsCanActivate = (checker, declaration) =>
404
- (declaration.heritageClauses ?? []).some((clause) => clause.token === ts.SyntaxKind.ImplementsKeyword && clause.types.some((type) => {
405
- const symbol = checker.getSymbolAtLocation(type.expression)
406
- return declarationsOfSymbol(checker, symbol).some((found) => found.name?.text === "CanActivate" && /[\/]@nestjs[\/]common[\/]/.test(String(found.getSourceFile().fileName)))
407
- }))
408
-
467
+ const implementsCanActivate = (checker, declaration) => (declaration.heritageClauses ?? []).some((clause) => clause.token === ts.SyntaxKind.ImplementsKeyword && clause.types.some((type) => {
468
+ const symbol = checker.getSymbolAtLocation(type.expression);
469
+ return declarationsOfSymbol(checker, symbol).some((found) => nameTextOf(found) === "CanActivate" && /[\/]@nestjs[\/]common[\/]/.test(String(found.getSourceFile().fileName)));
470
+ }));
409
471
  /**
410
472
  * True when the identity capability that declares `Credential` also declares the canon `CredentialGuard`, a class implementing
411
473
  * `CanActivate`. The decorator only selects the credential kind; this guard is what authenticates it.
412
474
  */
413
475
  const credentialGuardDeclared = (context, decoratorCallee_) => {
414
- const hfs = hfsOf(context)
415
- const { program, checker, toTs } = typed(context)
416
- const target = toTs(decoratorCallee_)
417
- const home = declarationsOfSymbol(checker, target ? checker.getSymbolAtLocation(target) : undefined).find((declaration) => declaration.name?.text === "Credential")
418
- const owner = home && hfs.ownerOf(home.getSourceFile().fileName)
419
- if (!owner) return false
476
+ const hfs = hfsOf(context);
477
+ const { program, checker, toTs } = typed(context);
478
+ const target = toTs(decoratorCallee_);
479
+ const home = declarationsOfSymbol(checker, target ? checker.getSymbolAtLocation(target) : undefined).find((declaration) => nameTextOf(declaration) === "Credential");
480
+ const owner = home && hfs.ownerOf(home.getSourceFile().fileName);
481
+ if (!owner)
482
+ return false;
420
483
  for (const source of program.getSourceFiles()) {
421
- if (source.isDeclarationFile || hfs.ownerOf(source.fileName) !== owner) continue
422
- const found = source.statements.some((statement) => ts.isClassDeclaration(statement) && statement.name?.text === "CredentialGuard" && implementsCanActivate(checker, statement))
423
- if (found) return true
484
+ if (source.isDeclarationFile || hfs.ownerOf(source.fileName) !== owner)
485
+ continue;
486
+ const found = source.statements.some((statement) => ts.isClassDeclaration(statement) && statement.name?.text === "CredentialGuard" && implementsCanActivate(checker, statement));
487
+ if (found)
488
+ return true;
424
489
  }
425
- return false
426
- }
427
-
490
+ return false;
491
+ };
428
492
  /**
429
493
  * Credential-guarded route (BE_REST_DOOR_EVIDENCE, owner delegation 2026-10-16): the route, or its controller class, carries
430
494
  * `@Credential({ kind: "<literal>" })` imported from the domain identity capability, and that capability declares a
431
495
  * `CredentialGuard implements CanActivate`. A same-named local decorator, a `@UseGuards` of any other guard and a non-literal kind prove nothing.
432
496
  */
433
497
  const credentialGuardEvidence = (context, method) => {
434
- const carriers = [...(method.decorators ?? []), ...(method.parent?.parent?.decorators ?? [])]
498
+ const carriers = [...(method.decorators ?? []), ...(method.parent?.parent?.decorators ?? [])];
435
499
  for (const decorator of carriers) {
436
- const callee = decoratorCallee(decorator)
437
- if (!identityExport(context, callee, "Credential")) continue
438
- const options = decoratorArguments(decorator)[0]
439
- const kind = options?.type === "ObjectExpression" ? options.properties.find((property) => property.type === "Property" && keyName(property.key) === "kind")?.value : null
440
- if (kind?.type === "Literal" && typeof kind.value === "string" && kind.value !== "" && credentialGuardDeclared(context, callee)) return true
500
+ const callee = decoratorCallee(decorator);
501
+ if (!callee || !identityExport(context, callee, "Credential"))
502
+ continue;
503
+ const options = decoratorArguments(decorator)[0];
504
+ const kind = options?.type === "ObjectExpression" ? options.properties.find((property) => property.type === "Property" && keyName(property.key) === "kind")?.value : null;
505
+ if (kind?.type === "Literal" && typeof kind.value === "string" && kind.value !== "" && credentialGuardDeclared(context, callee))
506
+ return true;
441
507
  }
442
- return false
443
- }
444
-
508
+ return false;
509
+ };
445
510
  /**
446
511
  * Event-stream evidence (BE_REST_DOOR_EVIDENCE, owner:lite-sse-door): the route is an `@Sse` method of `@nestjs/common` inside the sse slot of a
447
512
  * realtime channel. It is structural, not a name list: the same `@Sse` anywhere else, or any other route inside the sse slot, proves nothing.
448
513
  */
449
- const eventStreamEvidence = (context, method) =>
450
- hfsOf(context).slotOf(context.filename) === SSE_SLOT
451
- && (method.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Sse"))
452
-
514
+ const eventStreamEvidence = (context, method) => hfsOf(context).slotOf(context.filename) === SSE_SLOT
515
+ && (method.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Sse"));
453
516
  /** Route-level evidence for probes, auth handshakes, signed webhooks, redirects, byte transfers, event streams and credential-guarded routes. */
454
517
  export const restExceptionEvidence = (context, method) => {
455
- if (credentialGuardEvidence(context, method) || eventStreamEvidence(context, method)) return true
518
+ if (credentialGuardEvidence(context, method) || eventStreamEvidence(context, method))
519
+ return true;
456
520
  for (const decorator of method.decorators ?? []) {
457
- const callee = decoratorCallee(decorator)
458
- if (isImportedFrom(context, callee, "@nestjs/common", "Redirect")) return true
521
+ const callee = decoratorCallee(decorator);
522
+ if (isImportedFrom(context, callee, "@nestjs/common", "Redirect"))
523
+ return true;
459
524
  if (identityExport(context, callee, "Public")) {
460
- const options = decoratorArguments(decorator)[0]
461
- const reason = options?.type === "ObjectExpression" ? options.properties.find((property) => property.type === "Property" && keyName(property.key) === "reason")?.value : null
462
- if (reason?.type === "MemberExpression" && !reason.computed && REST_REASONS.has(keyName(reason.property)) && identityExport(context, reason.object, "PublicReason")) return true
525
+ const options = decoratorArguments(decorator)[0];
526
+ const reason = options?.type === "ObjectExpression" ? options.properties.find((property) => property.type === "Property" && keyName(property.key) === "reason")?.value : null;
527
+ if (reason?.type === "MemberExpression" && !reason.computed && REST_REASONS.has(keyName(reason.property)) && identityExport(context, reason.object, "PublicReason"))
528
+ return true;
463
529
  }
464
- if (isImportedFrom(context, callee, "@nestjs/common", "UseInterceptors") && decoratorArguments(decorator).some((argument) => argument.type === "CallExpression" && isImportedFrom(context, argument.callee, "@nestjs/platform-express", FILE_INTERCEPTORS))) return true
530
+ if (isImportedFrom(context, callee, "@nestjs/common", "UseInterceptors") && decoratorArguments(decorator).some((argument) => argument.type === "CallExpression" && isImportedFrom(context, argument.callee, "@nestjs/platform-express", FILE_INTERCEPTORS)))
531
+ return true;
465
532
  }
466
- return returnsBytes(context, method)
467
- }
468
-
533
+ return returnsBytes(context, method);
534
+ };
469
535
  /** Public REST JSON is exposed through the app's declared operation table. */
470
536
  export const restRouteDeclared = {
471
537
  meta: {
@@ -477,21 +543,25 @@ export const restRouteDeclared = {
477
543
  },
478
544
  },
479
545
  create(context) {
480
- const hfs = hfsOf(context)
481
- if (!isTransportSlot(hfs.slotOf(context.filename))) return {}
482
- const declared = operationRouteEvidence(context)
546
+ const hfs = hfsOf(context);
547
+ if (!isTransportSlot(hfs.slotOf(context.filename)))
548
+ return {};
549
+ const declared = operationRouteEvidence(context);
483
550
  return {
484
551
  MethodDefinition(node) {
485
- if (node.kind !== "method" || node.static) return
486
- if (!(node.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", HTTP_ROUTES))) return
487
- const controller = node.parent?.parent
488
- if (!(controller?.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Controller"))) return
489
- if (!restExceptionEvidence(context, node) && !declared(node)) context.report({ node: node.key, messageId: "undeclared" })
552
+ if (node.kind !== "method" || node.static)
553
+ return;
554
+ if (!(node.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", HTTP_ROUTES)))
555
+ return;
556
+ const controller = node.parent?.parent;
557
+ if (!(controller?.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Controller")))
558
+ return;
559
+ if (!restExceptionEvidence(context, node) && !declared(node))
560
+ context.report({ node: node.key, messageId: "undeclared" });
490
561
  },
491
- }
562
+ };
492
563
  },
493
- }
494
-
564
+ };
495
565
  /** An operation route takes the table's `OperationRequest` and answers its `OperationReply`, of one table, and validates the body it takes. */
496
566
  export const operationRouteDrivenByTable = {
497
567
  meta: {
@@ -505,57 +575,65 @@ export const operationRouteDrivenByTable = {
505
575
  },
506
576
  },
507
577
  create(context) {
508
- const hfs = hfsOf(context)
509
- if (!isTransportSlot(hfs.slotOf(context.filename))) return {}
510
- const { checker, toTs } = typed(context)
578
+ const hfs = hfsOf(context);
579
+ if (!isTransportSlot(hfs.slotOf(context.filename)))
580
+ return {};
581
+ const { checker, toTs } = typed(context);
511
582
  return {
512
583
  MethodDefinition(node) {
513
- if (node.kind !== "method" || node.static) return
514
- if (!(node.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", HTTP_ROUTES))) return
515
- const params = node.value.params.filter((param) => (param.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Body")))
516
- const references = params.map((param) => canonReference(hfs, checker, toTs, param.typeAnnotation ?? param.parameter?.typeAnnotation))
517
- const request = references.find(Boolean) ?? null
518
- const reply = canonReference(hfs, checker, toTs, unwrapPromise(node.value.returnType))
519
- if (!request && !reply) return
584
+ if (node.kind !== "method" || node.static)
585
+ return;
586
+ if (!(node.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", HTTP_ROUTES)))
587
+ return;
588
+ const params = node.value.params.filter((param) => (param.decorators ?? []).some((decorator) => isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Body")));
589
+ const references = params.map((param) => canonReference(hfs, checker, toTs, paramAnnotation(param)));
590
+ const request = references.find(Boolean) ?? null;
591
+ const reply = canonReference(hfs, checker, toTs, unwrapPromise(node.value.returnType));
592
+ if (!request && !reply)
593
+ return;
520
594
  if (!request || !reply) {
521
- context.report({ node: node.key, messageId: "half", data: request ? { one: "OperationRequest", other: "OperationReply" } : { one: "OperationReply", other: "OperationRequest" } })
522
- return
595
+ context.report({ node: node.key, messageId: "half", data: request ? { one: "OperationRequest", other: "OperationReply" } : { one: "OperationReply", other: "OperationRequest" } });
596
+ return;
523
597
  }
524
598
  if (request.table !== reply.table) {
525
- context.report({ node: node.key, messageId: "table" })
526
- return
599
+ context.report({ node: node.key, messageId: "table" });
600
+ return;
527
601
  }
528
602
  const validated = params.some((param) => {
529
- const reference = canonReference(hfs, checker, toTs, param.typeAnnotation ?? param.parameter?.typeAnnotation)
530
- if (reference?.name !== "OperationRequest") return false
603
+ const reference = canonReference(hfs, checker, toTs, paramAnnotation(param));
604
+ if (reference?.name !== "OperationRequest")
605
+ return false;
531
606
  return (param.decorators ?? []).some((decorator) => {
532
- if (!isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Body")) return false
533
- const args = decoratorArguments(decorator)
534
- if (args.length !== 1) return false
535
- const pipe = expressionOf(checker, toTs(args[0]))
536
- if (!pipe || !ts.isNewExpression(pipe) || !isCanonType(hfs, checker, checker.getSymbolAtLocation(pipe.expression), "OperationValidationPolicy")) return false
537
- const table = expressionOf(checker, pipe.arguments?.[0])
538
- return pipe.arguments?.length === 1 && table && request.expression && table === request.expression
539
- })
540
- })
541
- if (!validated) context.report({ node: node.key, messageId: "validation" })
607
+ if (!isImportedFrom(context, decoratorCallee(decorator), "@nestjs/common", "Body"))
608
+ return false;
609
+ const args = decoratorArguments(decorator);
610
+ const [first] = args;
611
+ if (args.length !== 1 || first === undefined)
612
+ return false;
613
+ const pipe = expressionOf(checker, toTs(first));
614
+ if (!pipe || !ts.isNewExpression(pipe) || !isCanonType(hfs, checker, checker.getSymbolAtLocation(pipe.expression), "OperationValidationPolicy"))
615
+ return false;
616
+ const table = expressionOf(checker, pipe.arguments?.[0]);
617
+ return pipe.arguments?.length === 1 && table && request.expression && table === request.expression;
618
+ });
619
+ });
620
+ if (!validated)
621
+ context.report({ node: node.key, messageId: "validation" });
542
622
  },
543
- }
623
+ };
544
624
  },
545
- }
546
-
625
+ };
547
626
  /** Every rule of this law. */
548
627
  export const rules = {
549
628
  "operation-contract-decidable": operationContractDecidable,
550
629
  "operation-table-schemas": operationTableSchemas,
551
630
  "operation-route-driven-by-table": operationRouteDrivenByTable,
552
631
  "rest-route-declared": restRouteDeclared,
553
- }
554
-
632
+ };
555
633
  /** Every rule of this law at `error`. */
556
634
  export const recommended = {
557
635
  "starci-be/operation-contract-decidable": "error",
558
636
  "starci-be/operation-table-schemas": "error",
559
637
  "starci-be/operation-route-driven-by-table": "error",
560
638
  "starci-be/rest-route-declared": "error",
561
- }
639
+ };