@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
@@ -19,63 +19,57 @@
19
19
  * What a receiver is comes from its TYPE, what a decorator is from the import that binds it, and where a parameter comes
20
20
  * from from the declaration its name resolves to. No rule here tests a path pattern or a variable name.
21
21
  */
22
- import { walk } from "./lib/ast.mjs"
23
- import { aliasTarget, callsOf, hasClassDecorator, injectedMembers, methodsDecoratedBy, parametersOf } from "./lib/doors.mjs"
24
- import { hfsOf } from "./lib/hfs.mjs"
25
- import { decoratorCallee } from "./lib/import-source.mjs"
26
- import { baseName, isOwnedType, ownerNameOf } from "./lib/ports.mjs"
27
-
22
+ import { walk } from "./lib/ast.js";
23
+ import { aliasTarget, callsOf, hasClassDecorator, injectedMembers, methodsDecoratedBy, parametersOf } from "./lib/doors.js";
24
+ import { hfsOf } from "./lib/hfs.js";
25
+ import { decoratorCallee } from "./lib/import-source.js";
26
+ import { baseName, isOwnedType, ownerNameOf } from "./lib/ports.js";
28
27
  /** The slot of realtime doors. */
29
- const DOOR_SLOTS = new Set(["be.feature.realtime.graphql", "be.feature.realtime.websocket", "be.feature.realtime.sse"])
30
-
28
+ const DOOR_SLOTS = new Set(["be.feature.realtime.graphql", "be.feature.realtime.websocket", "be.feature.realtime.sse"]);
31
29
  /** The `RealtimeHub` port of `platform/realtime`. */
32
- const isHubType = (context, node) => isOwnedType(context, node, { name: "RealtimeHub", capability: "realtime", tier: "platform" })
33
-
30
+ const isHubType = (context, node) => isOwnedType(context, node, { name: "RealtimeHub", capability: "realtime", tier: "platform" });
34
31
  /** The plain HTTP route decorators of `@nestjs/common`: an SSE controller carries none of them, its one route is `@Sse`. */
35
- const HTTP_ROUTES = ["Get", "Post", "Put", "Patch", "Delete", "All", "Options", "Head"]
36
-
32
+ const HTTP_ROUTES = ["Get", "Post", "Put", "Patch", "Delete", "All", "Options", "Head"];
37
33
  /** The decorators that make a class a door of one kind of realtime file, by file role. */
38
34
  const ROLES = {
39
35
  gateway: { classDecorator: ["@nestjs/websockets", "WebSocketGateway"], operation: ["@nestjs/websockets", "SubscribeMessage"], foreign: [["@nestjs/graphql", ["Query", "Mutation", "ResolveField", "Subscription"]], ["@nestjs/common", ["Controller"]]] },
40
36
  subscription: { classDecorator: ["@nestjs/graphql", "Resolver"], operation: ["@nestjs/graphql", "Subscription"], foreign: [["@nestjs/graphql", ["Query", "Mutation", "ResolveField"]], ["@nestjs/websockets", ["WebSocketGateway", "SubscribeMessage"]], ["@nestjs/common", ["Controller"]]] },
41
37
  controller: { classDecorator: ["@nestjs/common", "Controller"], operation: ["@nestjs/common", "Sse"], foreign: [["@nestjs/graphql", ["Query", "Mutation", "ResolveField", "Subscription", "Resolver"]], ["@nestjs/websockets", ["WebSocketGateway", "SubscribeMessage"]], ["@nestjs/common", HTTP_ROUTES]] },
42
- }
43
-
38
+ };
39
+ /** Whether a captured file role is one of `ROLES`. */
40
+ const isRole = (value) => value === "gateway" || value === "subscription" || value === "controller";
44
41
  /** The role (`gateway`, `subscription` or `controller`) a realtime file name carries, or null. */
45
- const roleOf = (filename) => /\.(gateway|subscription|controller)\.ts$/.exec(baseName(filename))?.[1] ?? null
46
-
42
+ const roleOf = (filename) => {
43
+ const found = /\.(gateway|subscription|controller)\.ts$/.exec(baseName(filename))?.[1];
44
+ return isRole(found) ? found : null;
45
+ };
47
46
  /** The door classes of a file: every class with a class-level door decorator of the role. */
48
47
  const doorClasses = (context, program, role) => {
49
- const found = []
48
+ const found = [];
49
+ const [source, name] = ROLES[role].classDecorator;
50
50
  walk(program, (node) => {
51
- if (node.type === "ClassDeclaration" && hasClassDecorator(context, node, ...ROLES[role].classDecorator)) found.push(node)
52
- })
53
- return found
54
- }
55
-
51
+ if (node.type === "ClassDeclaration" && hasClassDecorator(context, node, source, name))
52
+ found.push(node);
53
+ });
54
+ return found;
55
+ };
56
56
  /** The framework supplies this server property; no inbound message supplies a stream's principal. */
57
- const hasSocketServer = (context, node) => node.body.body.some((member) =>
58
- member.type === "PropertyDefinition" && hasClassDecorator(context, member, "@nestjs/websockets", "WebSocketServer"))
59
-
57
+ const hasSocketServer = (context, node) => node.body.body.some((member) => member.type === "PropertyDefinition" && hasClassDecorator(context, member, "@nestjs/websockets", "WebSocketServer"));
60
58
  /** The authenticated principal port the socket middleware passes to a push-only stream. */
61
- const isStreamPrincipal = (context, param) => isOwnedType(context, param, { name: "Principal", capability: "cqrs", tier: "platform" })
62
-
59
+ const isStreamPrincipal = (context, param) => isOwnedType(context, param, { name: "Principal", capability: "cqrs", tier: "platform" });
63
60
  /** The hub calls that open a client's stream: `subscribe` (an async iterable of frames) and `stream` (server-sent events), including those inside closures. */
64
- const OPENING_CALLS = new Set(["subscribe", "stream"])
65
- const hubSubscriptions = (context, method) => callsOf(method).filter(({ receiver, method: called }) =>
66
- OPENING_CALLS.has(called) && receiver !== null && isHubType(context, receiver))
67
-
61
+ const OPENING_CALLS = new Set(["subscribe", "stream"]);
62
+ const hubSubscriptions = (context, method) => callsOf(method).filter(({ receiver, method: called }) => called !== null && OPENING_CALLS.has(called) && receiver !== null && isHubType(context, receiver));
68
63
  /** The nonstatic methods a push-only gateway uses to feed its socket server. */
69
64
  const streamMethods = (context, node) => {
70
- if (!hasSocketServer(context, node)) return []
65
+ if (!hasSocketServer(context, node))
66
+ return [];
71
67
  return node.body.body.filter((member) => member.type === "MethodDefinition" && member.kind === "method" && !member.static
72
- && hubSubscriptions(context, member).length > 0)
73
- }
74
-
68
+ && hubSubscriptions(context, member).length > 0);
69
+ };
75
70
  /** An inbound handler or a push-only stream taking the server's authenticated principal. */
76
- const hasOperation = (context, node, role) => methodsDecoratedBy(context, node, ...ROLES[role].operation).length > 0
77
- || (role === "gateway" && streamMethods(context, node).some((method) => parametersOf(method).some((param) => isStreamPrincipal(context, param))))
78
-
71
+ const hasOperation = (context, node, role) => methodsDecoratedBy(context, node, ROLES[role].operation[0], ROLES[role].operation[1]).length > 0
72
+ || (role === "gateway" && streamMethods(context, node).some((method) => parametersOf(method).some((param) => isStreamPrincipal(context, param))));
79
73
  /** A realtime file is the one door its role names, and nothing else. */
80
74
  export const realtimeShape = {
81
75
  meta: {
@@ -90,35 +84,39 @@ export const realtimeShape = {
90
84
  },
91
85
  },
92
86
  create(context) {
93
- const hfs = hfsOf(context)
94
- const role = roleOf(context.filename)
95
- if (!DOOR_SLOTS.has(hfs.slotOf(context.filename) ?? "") || role === null) return {}
96
- const spec = ROLES[role]
87
+ const hfs = hfsOf(context);
88
+ const role = roleOf(context.filename);
89
+ if (!DOOR_SLOTS.has(hfs.slotOf(context.filename) ?? "") || role === null)
90
+ return {};
91
+ const spec = ROLES[role];
97
92
  return {
98
93
  "Program:exit"(program) {
99
- const doors = doorClasses(context, program, role)
100
- if (doors.length !== 1) {
101
- context.report({ node: program, messageId: "door", data: { role, decorator: `@${spec.classDecorator[1]}`, count: String(doors.length) } })
102
- return
94
+ const doors = doorClasses(context, program, role);
95
+ const [door] = doors;
96
+ if (doors.length !== 1 || !door) {
97
+ context.report({ node: program, messageId: "door", data: { role, decorator: `@${spec.classDecorator[1]}`, count: String(doors.length) } });
98
+ return;
103
99
  }
104
- if (!hasOperation(context, doors[0], role)) context.report({ node: doors[0], messageId: "operations", data: { role, operation: spec.operation[1] } })
105
- const streams = role === "controller" ? methodsDecoratedBy(context, doors[0], ...spec.operation).length : 1
106
- if (streams > 1) context.report({ node: doors[0], messageId: "single", data: { count: String(streams) } })
100
+ if (!hasOperation(context, door, role))
101
+ context.report({ node: door, messageId: "operations", data: { role, operation: spec.operation[1] } });
102
+ const streams = role === "controller" ? methodsDecoratedBy(context, door, spec.operation[0], spec.operation[1]).length : 1;
103
+ if (streams > 1)
104
+ context.report({ node: door, messageId: "single", data: { count: String(streams) } });
107
105
  walk(program, (node) => {
108
- if (node.type !== "Decorator") return
106
+ if (node.type !== "Decorator")
107
+ return;
109
108
  for (const [source, names] of spec.foreign) {
110
- const hit = names.find((name) => hasDecorator(context, node, source, name))
111
- if (hit !== undefined) context.report({ node, messageId: "foreign", data: { name: hit, role } })
109
+ const hit = names.find((name) => hasDecorator(context, node, source, name));
110
+ if (hit !== undefined)
111
+ context.report({ node, messageId: "foreign", data: { name: hit, role } });
112
112
  }
113
- })
113
+ });
114
114
  },
115
- }
115
+ };
116
116
  },
117
- }
118
-
117
+ };
119
118
  /** True when one decorator node is `name` exported by `source`. */
120
- const hasDecorator = (context, decorator, source, name) => hasClassDecorator(context, { decorators: [decorator] }, source, name)
121
-
119
+ const hasDecorator = (context, decorator, source, name) => hasClassDecorator(context, { decorators: [decorator] }, source, name);
122
120
  /** A realtime door injects the hub and nothing else: it reads and pushes, it never writes. */
123
121
  export const realtimeReadOnly = {
124
122
  meta: {
@@ -130,60 +128,62 @@ export const realtimeReadOnly = {
130
128
  },
131
129
  },
132
130
  create(context) {
133
- const hfs = hfsOf(context)
134
- if (!DOOR_SLOTS.has(hfs.slotOf(context.filename) ?? "") || roleOf(context.filename) === null) return {}
131
+ const hfs = hfsOf(context);
132
+ if (!DOOR_SLOTS.has(hfs.slotOf(context.filename) ?? "") || roleOf(context.filename) === null)
133
+ return {};
135
134
  return {
136
135
  ClassDeclaration(node) {
137
136
  for (const { node: member, annotation } of injectedMembers(context, node)) {
138
- if (!annotation || !isHubType(context, annotation)) context.report({ node: member, messageId: "injects", data: { what: context.sourceCode.getText(member) } })
137
+ if (!annotation || !isHubType(context, annotation))
138
+ context.report({ node: member, messageId: "injects", data: { what: context.sourceCode.getText(member) } });
139
139
  }
140
140
  },
141
- }
141
+ };
142
142
  },
143
- }
144
-
143
+ };
145
144
  /** True when the parameter carries `@CurrentPrincipal()` declared by `domain/identity`, judged by the declaration the decorator resolves to. */
146
- const isPrincipalParameter = (context, hfs, param) =>
147
- (param.decorators ?? []).some((decorator) => {
148
- const callee = decoratorCallee(decorator)
149
- if (callee?.type !== "Identifier") return false
150
- const symbol = aliasTarget(context, callee)
151
- return symbol?.getName() === "CurrentPrincipal" && (symbol.getDeclarations() ?? []).some((declaration) => ownerNameOf(hfs, declaration.getSourceFile().fileName) === "identity" && hfs.tierOf(declaration.getSourceFile().fileName) === "domain")
152
- })
153
-
145
+ const isPrincipalParameter = (context, hfs, param) => (param.decorators ?? []).some((decorator) => {
146
+ const callee = decoratorCallee(decorator);
147
+ if (callee?.type !== "Identifier")
148
+ return false;
149
+ const symbol = aliasTarget(context, callee);
150
+ return symbol?.getName() === "CurrentPrincipal" && (symbol.getDeclarations() ?? []).some((declaration) => ownerNameOf(hfs, declaration.getSourceFile().fileName) === "identity" && hfs.tierOf(declaration.getSourceFile().fileName) === "domain");
151
+ });
154
152
  /** True when the identifier resolves to one of the `names` (parameters of the handler). */
155
153
  const resolvesTo = (context, identifier, parameters) => {
156
154
  for (let scope = context.sourceCode.getScope(identifier); scope; scope = scope.upper) {
157
- const variable = scope.set.get(identifier.name)
158
- if (!variable) continue
159
- return variable.defs.some((definition) => definition.type === "Parameter" && parameters.has(definition.name))
155
+ const variable = scope.set.get(identifier.name);
156
+ if (!variable)
157
+ continue;
158
+ return variable.defs.some((definition) => definition.type === "Parameter" && parameters.has(definition.name));
160
159
  }
161
- return false
162
- }
163
-
160
+ return false;
161
+ };
164
162
  /** A method's principal parameters, declared by the identity decorator or the push stream's platform type. */
165
163
  const principalParameters = (context, hfs, method, push) => {
166
- const principals = new Set()
164
+ const principals = new Set();
167
165
  for (const param of parametersOf(method)) {
168
- if (!isPrincipalParameter(context, hfs, param) && !(push && isStreamPrincipal(context, param))) continue
169
- const target = param.type === "AssignmentPattern" ? param.left : param
170
- if (target.type === "Identifier") principals.add(target)
166
+ if (!isPrincipalParameter(context, hfs, param) && !(push && isStreamPrincipal(context, param)))
167
+ continue;
168
+ const target = param.type === "AssignmentPattern" ? param.left : param;
169
+ if (target.type === "Identifier")
170
+ principals.add(target);
171
171
  }
172
- return principals
173
- }
174
-
172
+ return principals;
173
+ };
175
174
  /** The hub topic must use the method's principal declaration rather than a shadowing identifier. */
176
175
  const checkMethodTopics = (context, hfs, method, push) => {
177
- const principals = principalParameters(context, hfs, method, push)
176
+ const principals = principalParameters(context, hfs, method, push);
178
177
  for (const { call } of hubSubscriptions(context, method)) {
179
- let scoped = false
178
+ let scoped = false;
180
179
  walk(call.arguments[0], (child) => {
181
- if (child.type === "Identifier" && resolvesTo(context, child, principals)) scoped = true
182
- })
183
- if (!scoped) context.report({ node: call, messageId: "scope" })
180
+ if (child.type === "Identifier" && resolvesTo(context, child, principals))
181
+ scoped = true;
182
+ });
183
+ if (!scoped)
184
+ context.report({ node: call, messageId: "scope" });
184
185
  }
185
- }
186
-
186
+ };
187
187
  /** The topic a client subscribes to is built from the principal the handler receives. */
188
188
  export const realtimeTopicScope = {
189
189
  meta: {
@@ -195,33 +195,35 @@ export const realtimeTopicScope = {
195
195
  },
196
196
  },
197
197
  create(context) {
198
- const hfs = hfsOf(context)
199
- const role = roleOf(context.filename)
200
- if (!DOOR_SLOTS.has(hfs.slotOf(context.filename) ?? "") || role === null) return {}
201
- const [source, name] = ROLES[role].operation
198
+ const hfs = hfsOf(context);
199
+ const role = roleOf(context.filename);
200
+ if (!DOOR_SLOTS.has(hfs.slotOf(context.filename) ?? "") || role === null)
201
+ return {};
202
+ const [source, name] = ROLES[role].operation;
202
203
  return {
203
204
  ClassDeclaration(node) {
204
- const handlers = methodsDecoratedBy(context, node, source, name)
205
- for (const method of handlers) checkMethodTopics(context, hfs, method, false)
206
- if (role !== "gateway") return
205
+ const handlers = methodsDecoratedBy(context, node, source, name);
206
+ for (const method of handlers)
207
+ checkMethodTopics(context, hfs, method, false);
208
+ if (role !== "gateway")
209
+ return;
207
210
  for (const method of streamMethods(context, node)) {
208
- if (!handlers.includes(method)) checkMethodTopics(context, hfs, method, true)
211
+ if (!handlers.includes(method))
212
+ checkMethodTopics(context, hfs, method, true);
209
213
  }
210
214
  },
211
- }
215
+ };
212
216
  },
213
- }
214
-
217
+ };
215
218
  /** The rules this law contributes to the plugin. */
216
219
  export const rules = {
217
220
  "realtime-shape": realtimeShape,
218
221
  "realtime-read-only": realtimeReadOnly,
219
222
  "realtime-topic-scope": realtimeTopicScope,
220
- }
221
-
223
+ };
222
224
  /** Every rule of this law at `error`. */
223
225
  export const recommended = {
224
226
  "starci-be/realtime-shape": "error",
225
227
  "starci-be/realtime-read-only": "error",
226
228
  "starci-be/realtime-topic-scope": "error",
227
- }
229
+ };
@@ -0,0 +1,15 @@
1
+ import type { Recommended, RuleModule } from "./lib/rule.js";
2
+ /** Every outbound HTTP call carries a deadline. */
3
+ export declare const httpNeedsTimeout: RuleModule;
4
+ /** `JSON.parse` of outside text fails inside a guard. */
5
+ export declare const jsonParseNeedsGuard: RuleModule;
6
+ /** A loop that both catches an error and waits is retrying by hand. */
7
+ export declare const noHandRolledRetry: RuleModule;
8
+ /** The rules this law contributes to the plugin. */
9
+ export declare const rules: {
10
+ "http-needs-timeout": RuleModule;
11
+ "json-parse-needs-guard": RuleModule;
12
+ "no-hand-rolled-retry": RuleModule;
13
+ };
14
+ /** All three start at error: no baseline exists, and the repositories' fix lanes clear the debt. */
15
+ export declare const recommended: Recommended;
@@ -0,0 +1,319 @@
1
+ /**
2
+ * The rules that keep one slow or malformed dependency from taking a process down.
3
+ *
4
+ * - `http-needs-timeout` (R70 `BE_HTTP_TIMEOUT`): an outbound HTTP call states how long it may take. A socket
5
+ * with no deadline holds a request, a connection and a worker slot for as long as the far side sleeps.
6
+ * - `json-parse-needs-guard` (R76 `BE_JSON_PARSE_UNGUARDED`): `JSON.parse` of text that came from outside the
7
+ * function sits inside a `try`. A corrupt row or a hostile payload then becomes a typed outcome instead of a 500.
8
+ * - `no-hand-rolled-retry` (R81 `BE_HAND_ROLLED_RETRY`): a loop that catches an error and waits before trying
9
+ * again re-implements retry by hand, outside `platform/retry`'s bounded, jittered, abortable helper.
10
+ *
11
+ * A config held in a variable or returned by a helper proves its deadline through its type.
12
+ */
13
+ import ts from "typescript";
14
+ import { keyName, staticText, walk } from "./lib/ast.js";
15
+ import { hfsOf } from "./lib/hfs.js";
16
+ import { isOwnedBy } from "./lib/ports.js";
17
+ import { isPackageType, isTypeNamed, typed, childNode } from "./lib/types.js";
18
+ import { isDeclarationFile } from "./lib/path.js";
19
+ const HTTP_METHODS = new Set(["get", "post", "put", "patch", "delete", "head", "request"]);
20
+ /** The outbound HTTP client types a call may be made on, by the package that declares each. */
21
+ const HTTP_CLIENT_TYPES = Object.freeze([["AxiosInstance", "axios"], ["AxiosStatic", "axios"], ["HttpService", "@nestjs/axios"]]);
22
+ /** Whether the node's TYPE is an outbound HTTP client (an axios instance or the Nest `HttpService`), whatever it is called. */
23
+ const isHttpClient = (context, node) => HTTP_CLIENT_TYPES.some(([name, pkg]) => isPackageType(context, node, name, pkg));
24
+ const hasSpread = (objectNode) => objectNode.properties.some((property) => property.type === "SpreadElement");
25
+ /** A deadline value cannot be absent in any branch of its type. */
26
+ const mayBeAbsent = (type) => type.isUnion()
27
+ ? type.types.some(mayBeAbsent)
28
+ : (type.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void)) !== 0;
29
+ /** A non-literal config promises a present deadline in every possible branch, including a generic's constraint. */
30
+ const typeHasDeadline = (checker, type, atNode, names) => {
31
+ if ((type.flags & ts.TypeFlags.TypeParameter) !== 0) {
32
+ const constraint = checker.getBaseConstraintOfType(type);
33
+ return constraint !== undefined && constraint !== type && typeHasDeadline(checker, constraint, atNode, names);
34
+ }
35
+ if (type.isUnion())
36
+ return type.types.every((part) => typeHasDeadline(checker, part, atNode, names));
37
+ if ((type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) !== 0 || mayBeAbsent(type))
38
+ return false;
39
+ return names.some((name) => {
40
+ const property = checker.getPropertyOfType(type, name);
41
+ if (!property || (property.flags & ts.SymbolFlags.Optional) !== 0)
42
+ return false;
43
+ const valueType = checker.getTypeOfSymbolAtLocation(property, atNode);
44
+ return !mayBeAbsent(valueType) && (valueType.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) === 0;
45
+ });
46
+ };
47
+ /** Literal keys state a deadline directly; other configs must prove it with a required, present typed member. */
48
+ const hasDeadline = (context, config, names) => {
49
+ if (!config)
50
+ return false;
51
+ const { checker, toTs } = typed(context);
52
+ if (config.type === "ObjectExpression" && !hasSpread(config)) {
53
+ return names.some((name) => {
54
+ const property = config.properties.findLast((entry) => entry.type === "Property"
55
+ && (entry.computed ? staticText(entry.key) : keyName(entry.key)) === name);
56
+ if (!property)
57
+ return false;
58
+ let expression = property.value;
59
+ while (expression.type === "TSAsExpression" || expression.type === "TSTypeAssertion" || expression.type === "TSNonNullExpression" || expression.type === "TSSatisfiesExpression")
60
+ expression = expression.expression;
61
+ const value = toTs(expression);
62
+ return Boolean(value) && !mayBeAbsent(checker.getTypeAtLocation(value));
63
+ });
64
+ }
65
+ const configNode = toTs(config);
66
+ return Boolean(configNode) && typeHasDeadline(checker, checker.getTypeAtLocation(configNode), configNode, names);
67
+ };
68
+ /** Every outbound HTTP call carries a deadline. */
69
+ export const httpNeedsTimeout = {
70
+ meta: {
71
+ type: "problem",
72
+ docs: { description: "`fetch`, axios and HttpService calls state a `timeout` or an abort `signal`." },
73
+ schema: [],
74
+ messages: {
75
+ fetchNoSignal: "`fetch` without a `signal`. A peer that accepts the connection and then goes quiet holds this request for as long as it likes. Pass `{ signal: AbortSignal.timeout(<named ms>) }`.",
76
+ clientNoTimeout: "`{{call}}` states no `timeout` or `signal`. A peer that goes quiet holds this request, its socket and a worker slot indefinitely. Pass `{ timeout: <named ms> }` (or an abort `signal`) in the request config, or set it once on `axios.create({ timeout })`.",
77
+ createNoTimeout: "`axios.create` without a `timeout`. Every call through this instance inherits no deadline. Set `timeout: <named ms>` here.",
78
+ },
79
+ },
80
+ create(context) {
81
+ const filename = context.filename || context.getFilename();
82
+ if (isDeclarationFile(filename))
83
+ return {};
84
+ return {
85
+ CallExpression(node) {
86
+ const { callee } = node;
87
+ if (callee.type === "Identifier" && callee.name === "fetch") {
88
+ const init = node.arguments[1];
89
+ if (!hasDeadline(context, init, ["signal"]))
90
+ context.report({ node, messageId: "fetchNoSignal" });
91
+ return;
92
+ }
93
+ if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier")
94
+ return;
95
+ const method = callee.property.name;
96
+ if (!isHttpClient(context, callee.object))
97
+ return;
98
+ const receiver = callee.object.type === "Identifier" ? callee.object.name : "client";
99
+ if (method === "create" && isPackageType(context, callee.object, "AxiosStatic", "axios")) {
100
+ const config = node.arguments[0];
101
+ if (!hasDeadline(context, config, ["timeout", "signal"])) {
102
+ context.report({ node, messageId: "createNoTimeout" });
103
+ }
104
+ return;
105
+ }
106
+ if (!HTTP_METHODS.has(method))
107
+ return;
108
+ const configAt = method === "request" ? 0 : ["post", "put", "patch"].includes(method) ? 2 : 1;
109
+ const config = node.arguments[configAt];
110
+ if (!hasDeadline(context, config, ["timeout", "signal"])) {
111
+ context.report({ node, messageId: "clientNoTimeout", data: { call: `${receiver}.${method}` } });
112
+ }
113
+ },
114
+ };
115
+ },
116
+ };
117
+ /** Whether `node` sits inside a `try` block of its own function. */
118
+ const insideTry = (node) => {
119
+ let child = node;
120
+ let current = node.parent;
121
+ while (current) {
122
+ if (current.type === "TryStatement" && current.block === child)
123
+ return true;
124
+ if (current.type === "FunctionDeclaration" || current.type === "FunctionExpression" || current.type === "ArrowFunctionExpression")
125
+ return false;
126
+ child = current;
127
+ current = current.parent;
128
+ }
129
+ return false;
130
+ };
131
+ /** `JSON.parse` of outside text fails inside a guard. */
132
+ export const jsonParseNeedsGuard = {
133
+ meta: {
134
+ type: "problem",
135
+ docs: { description: "`JSON.parse` sits inside a `try` in its own function." },
136
+ schema: [],
137
+ messages: {
138
+ unguarded: "`JSON.parse` outside a `try`. Stored text, a webhook body and a provider reply can all be malformed, and the throw surfaces far from here as an unmasked 500. Wrap it and return a typed outcome (or a `DomainError`) naming what was being parsed.",
139
+ },
140
+ },
141
+ create(context) {
142
+ const filename = context.filename || context.getFilename();
143
+ if (isDeclarationFile(filename))
144
+ return {};
145
+ return {
146
+ CallExpression(node) {
147
+ const { callee } = node;
148
+ if (callee.type !== "MemberExpression" || callee.computed)
149
+ return;
150
+ if (callee.object.type !== "Identifier" || callee.object.name !== "JSON")
151
+ return;
152
+ if (callee.property.type !== "Identifier" || callee.property.name !== "parse")
153
+ return;
154
+ if (insideTry(node))
155
+ return;
156
+ context.report({ node, messageId: "unguarded" });
157
+ },
158
+ };
159
+ },
160
+ };
161
+ /** Modules whose functions wait: `node:timers/promises` `setTimeout` and `scheduler.wait`, and the callback timers. */
162
+ const TIMER_MODULES = new Set(["node:timers/promises", "timers/promises", "node:timers", "timers"]);
163
+ const LOOP_TYPES = ["ForStatement", "WhileStatement", "DoWhileStatement", "ForOfStatement", "ForInStatement"];
164
+ /** The variable a name resolves to from `node`'s scope, or null when it is a global. */
165
+ const variableOf = (context, node, name) => {
166
+ let scope = (context.sourceCode || context.getSourceCode()).getScope(node);
167
+ while (scope) {
168
+ const found = scope.set.get(name);
169
+ if (found)
170
+ return found;
171
+ scope = scope.upper;
172
+ }
173
+ return null;
174
+ };
175
+ /** Whether an identifier is the global timer function of that name, not a local one. */
176
+ const isGlobalTimer = (context, identifier) => identifier.name === "setTimeout" && (variableOf(context, identifier, identifier.name)?.defs.length ?? 0) === 0;
177
+ /** The module specifier of an import binding's declaration; an `import x = require()` has no `source` and throws, as reading `source.value` off it did. */
178
+ const importSourceValue = (parent) => {
179
+ if (parent.type === "ImportDeclaration")
180
+ return parent.source.value;
181
+ throw new TypeError("Cannot read properties of undefined (reading 'value')");
182
+ };
183
+ /** Whether an identifier is bound by an import of a timers module (`import { setTimeout as pause } from "node:timers/promises"`). */
184
+ const isTimerImport = (context, identifier) => variableOf(context, identifier, identifier.name)?.defs.some((def) => def.type === "ImportBinding" && TIMER_MODULES.has(importSourceValue(def.parent))) ?? false;
185
+ /** The leftmost identifier of `a.b.c`, else null. */
186
+ const rootOf = (node) => {
187
+ let current = node;
188
+ while (current.type === "MemberExpression")
189
+ current = current.object;
190
+ return current.type === "Identifier" ? current : null;
191
+ };
192
+ /** The import a TypeScript identifier resolves to, when it is an import of a timers module. */
193
+ const isTimerImportTs = (checker, identifier) => {
194
+ const declarations = checker.getSymbolAtLocation(identifier)?.declarations ?? [];
195
+ return declarations.some((declaration) => {
196
+ const importDeclaration = ts.findAncestor(declaration, ts.isImportDeclaration);
197
+ return importDeclaration !== undefined && ts.isStringLiteral(importDeclaration.moduleSpecifier) && TIMER_MODULES.has(importDeclaration.moduleSpecifier.text);
198
+ });
199
+ };
200
+ /** Whether a TypeScript identifier named `setTimeout` is the ambient timer (declared by a `.d.ts`, or by nothing), not a function of the repository. */
201
+ const isGlobalTimerTs = (checker, identifier) => (checker.getSymbolAtLocation(identifier)?.declarations ?? []).every((declaration) => declaration.getSourceFile().isDeclarationFile);
202
+ /** The functions a TypeScript declaration is or holds (`function f`, `const f = () => ...`, a method, a property arrow). */
203
+ const bodiesOf = (declaration) => {
204
+ if (ts.isFunctionLike(declaration)) {
205
+ const body = childNode(declaration, "body");
206
+ if (body)
207
+ return [body];
208
+ }
209
+ if ((ts.isVariableDeclaration(declaration) || ts.isPropertyDeclaration(declaration) || ts.isPropertyAssignment(declaration)) && declaration.initializer) {
210
+ const body = ts.isFunctionLike(declaration.initializer) ? childNode(declaration.initializer, "body") : undefined;
211
+ return body ? [body] : [];
212
+ }
213
+ return [];
214
+ };
215
+ /**
216
+ * Whether calling the function a TypeScript call resolves to WAITS: its body calls the global `setTimeout`, a
217
+ * `node:timers` function, or another function that does (followed up to three levels deep). A function declared by
218
+ * the `platform/retry` owner is the sanctioned helper and never counts. A function whose body is not in the program
219
+ * (a package declaration file) cannot be judged and does not count; the timer-import ban (R90) closes that door.
220
+ */
221
+ const waitsThrough = (context, checker, call, depth, seen) => {
222
+ const hfs = hfsOf(context);
223
+ const target = ts.isPropertyAccessExpression(call.expression) ? call.expression.name : call.expression;
224
+ let symbol = checker.getSymbolAtLocation(target);
225
+ if (symbol && (symbol.flags & ts.SymbolFlags.Alias) !== 0)
226
+ symbol = checker.getAliasedSymbol(symbol);
227
+ for (const declaration of symbol?.declarations ?? []) {
228
+ if (seen.has(declaration))
229
+ continue;
230
+ seen.add(declaration);
231
+ if (isOwnedBy(hfs, declaration.getSourceFile().fileName, "platform", "retry"))
232
+ continue;
233
+ for (const body of bodiesOf(declaration))
234
+ if (waitsIn(context, checker, body, depth, seen))
235
+ return true;
236
+ }
237
+ return false;
238
+ };
239
+ /** Whether a TypeScript subtree waits: it calls a timer, or a function that waits. */
240
+ const waitsIn = (context, checker, root, depth, seen) => {
241
+ let found = false;
242
+ const visit = (node) => {
243
+ if (found)
244
+ return;
245
+ if (ts.isCallExpression(node)) {
246
+ let base = node.expression;
247
+ while (ts.isPropertyAccessExpression(base))
248
+ base = base.expression;
249
+ if (ts.isIdentifier(base) && ((base.text === "setTimeout" && isGlobalTimerTs(checker, base)) || isTimerImportTs(checker, base)))
250
+ found = true;
251
+ else if (depth > 0 && waitsThrough(context, checker, node, depth - 1, seen))
252
+ found = true;
253
+ }
254
+ if (!found)
255
+ ts.forEachChild(node, visit);
256
+ };
257
+ visit(root);
258
+ return found;
259
+ };
260
+ /** Whether an ESTree call waits: a global or imported timer, or a function declared outside `platform/retry` whose body waits. */
261
+ const isWaitCall = (context, node) => {
262
+ const { callee } = node;
263
+ const root = rootOf(callee);
264
+ if (root && (isGlobalTimer(context, root) || isTimerImport(context, root)))
265
+ return true;
266
+ const { checker, toTs } = typed(context);
267
+ const tsCall = toTs(node);
268
+ return Boolean(tsCall) && waitsThrough(context, checker, tsCall, 3, new Set());
269
+ };
270
+ /** Whether a call catches: a `.catch(...)` on a Promise. */
271
+ const isPromiseCatch = (context, node) => node.type === "CallExpression" && node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier"
272
+ && node.callee.property.name === "catch" && isTypeNamed(context, node.callee.object, "Promise");
273
+ /** A loop that both catches an error and waits is retrying by hand. */
274
+ export const noHandRolledRetry = {
275
+ meta: {
276
+ type: "problem",
277
+ docs: { description: "A loop that catches an error and waits before trying again goes through `platform/retry`, not a hand-written loop." },
278
+ schema: [],
279
+ messages: {
280
+ handRolled: "This loop catches an error and waits before trying again - a hand-rolled retry with no attempt bound visible here, no jitter and no way to honor an abort signal. Retry through `retry(work, { maxAttempts, baseDelayMs, maxDelayMs, signal })` from `platform/retry` (or the queue's declared `attempts`/`backoff`) instead of a loop written at the call site.",
281
+ },
282
+ },
283
+ create(context) {
284
+ const filename = context.filename || context.getFilename();
285
+ if (isDeclarationFile(filename) || isOwnedBy(hfsOf(context), filename, "platform", "retry"))
286
+ return {};
287
+ const check = (node) => {
288
+ let hasCatch = false;
289
+ walk(node.body, (child) => {
290
+ if (child.type === "CatchClause" || isPromiseCatch(context, child))
291
+ hasCatch = true;
292
+ }, { intoFunctions: false });
293
+ if (!hasCatch)
294
+ return;
295
+ // a wait is often a `new Promise((resolve) => setTimeout(resolve, ms))` executor, so the wait search enters functions
296
+ let hasWait = false;
297
+ walk(node.body, (child) => {
298
+ if (!hasWait && child.type === "CallExpression" && isWaitCall(context, child))
299
+ hasWait = true;
300
+ });
301
+ if (hasWait)
302
+ context.report({ node, messageId: "handRolled" });
303
+ };
304
+ const listener = Object.fromEntries(LOOP_TYPES.map((type) => [type, check]));
305
+ return listener;
306
+ },
307
+ };
308
+ /** The rules this law contributes to the plugin. */
309
+ export const rules = {
310
+ "http-needs-timeout": httpNeedsTimeout,
311
+ "json-parse-needs-guard": jsonParseNeedsGuard,
312
+ "no-hand-rolled-retry": noHandRolledRetry,
313
+ };
314
+ /** All three start at error: no baseline exists, and the repositories' fix lanes clear the debt. */
315
+ export const recommended = {
316
+ "starci-be/http-needs-timeout": "error",
317
+ "starci-be/json-parse-needs-guard": "error",
318
+ "starci-be/no-hand-rolled-retry": "error",
319
+ };