@starci/eslint-canon-be 3.18.4 → 3.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/comments.js +1 -1
  3. package/dist/explicit-surface.js +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/jwt-alg.js +1 -1
  6. package/dist/lib/edition.d.ts +1 -1
  7. package/dist/lib/edition.js +1 -1
  8. package/dist/lib/hfs.d.ts +0 -6
  9. package/dist/lib/hfs.js +7 -5
  10. package/dist/lib/runtime-root.d.ts +6 -1
  11. package/dist/lib/runtime-root.js +8 -2
  12. package/dist/lib/subject-values.js +1 -1
  13. package/dist/module-layering.js +2 -2
  14. package/dist/project-graph.js +1 -1
  15. package/dist/third-party-owner.js +1 -1
  16. package/package.json +3 -1
  17. package/runtime/bundle.json +1 -190
  18. package/runtime/scripts/api/git/recorded-lines.mjs +5 -5
  19. package/runtime/scripts/hfs/project-graph.mjs +6 -6
  20. package/runtime/scripts/hfs/project-rule.mjs +3 -3
  21. package/runtime/config.example.yaml +0 -194
  22. package/runtime/engine/by-code-unit.mjs +0 -12
  23. package/runtime/engine/config.mjs +0 -461
  24. package/runtime/engine/invalid-config.mjs +0 -15
  25. package/runtime/engine/model-config.mjs +0 -112
  26. package/runtime/engine/orca-config.mjs +0 -34
  27. package/runtime/engine/plain-object.mjs +0 -5
  28. package/runtime/engine/release-config.mjs +0 -32
  29. package/runtime/engine/removed-vocabulary.mjs +0 -27
  30. package/runtime/engine/resources-config.mjs +0 -59
  31. package/runtime/engine/runtime-root.mjs +0 -138
  32. package/runtime/engine/secrets.mjs +0 -202
  33. package/runtime/engine/sonar-config.mjs +0 -24
  34. package/runtime/engine/temp-root.mjs +0 -26
  35. package/runtime/engine/yaml.mjs +0 -161
  36. package/runtime/knowledge/grammars/index.yaml +0 -114
  37. package/runtime/knowledge/hfs/canon-pins.yaml +0 -720
  38. package/runtime/knowledge/hfs/fe-stack.yaml +0 -272
  39. package/runtime/knowledge/hfs/rules.yaml +0 -6760
  40. package/runtime/knowledge/hfs/slots.yaml +0 -2783
  41. package/runtime/knowledge/patterns/fe/folder.yaml +0 -425
  42. package/runtime/knowledge/sonar-gate.yaml +0 -151
  43. package/runtime/modules/kernel/removed-vocabulary.yaml +0 -458
  44. package/runtime/modules/models/registry.yaml +0 -221
  45. package/runtime/modules/models/runtimes.yaml +0 -556
  46. package/runtime/modules/models/tiers.yaml +0 -66
  47. package/runtime/scripts/api/git/cat-file.mjs +0 -4
  48. package/runtime/scripts/api/git/config-get.mjs +0 -9
  49. package/runtime/scripts/api/git/diff.mjs +0 -4
  50. package/runtime/scripts/api/git/lib.mjs +0 -80
  51. package/runtime/scripts/api/git/ls-files.mjs +0 -5
  52. package/runtime/scripts/api/git/ls-tree.mjs +0 -4
  53. package/runtime/scripts/api/git/merge-base.mjs +0 -8
  54. package/runtime/scripts/api/git/remote.mjs +0 -4
  55. package/runtime/scripts/api/git/rev-parse-query.mjs +0 -4
  56. package/runtime/scripts/api/git/show.mjs +0 -5
  57. package/runtime/scripts/api/git/tag.mjs +0 -4
  58. package/runtime/scripts/hfs/allows.mjs +0 -77
  59. package/runtime/scripts/hfs/architecture/ast-walks.mjs +0 -250
  60. package/runtime/scripts/hfs/architecture/automatic-gates.mjs +0 -103
  61. package/runtime/scripts/hfs/architecture/backend-app-files.mjs +0 -114
  62. package/runtime/scripts/hfs/architecture/backend.mjs +0 -462
  63. package/runtime/scripts/hfs/architecture/background-unowned.mjs +0 -254
  64. package/runtime/scripts/hfs/architecture/canon-clones.mjs +0 -291
  65. package/runtime/scripts/hfs/architecture/canon-jsx-clones.mjs +0 -224
  66. package/runtime/scripts/hfs/architecture/client-reaches-server.mjs +0 -102
  67. package/runtime/scripts/hfs/architecture/clones.mjs +0 -287
  68. package/runtime/scripts/hfs/architecture/component-tiers.mjs +0 -161
  69. package/runtime/scripts/hfs/architecture/config-unread.mjs +0 -16
  70. package/runtime/scripts/hfs/architecture/config.mjs +0 -407
  71. package/runtime/scripts/hfs/architecture/connection-map.mjs +0 -350
  72. package/runtime/scripts/hfs/architecture/constructor-deps.mjs +0 -115
  73. package/runtime/scripts/hfs/architecture/context-coupling.mjs +0 -117
  74. package/runtime/scripts/hfs/architecture/context-map.mjs +0 -355
  75. package/runtime/scripts/hfs/architecture/context-owner.mjs +0 -102
  76. package/runtime/scripts/hfs/architecture/context-platform-tables.mjs +0 -65
  77. package/runtime/scripts/hfs/architecture/context-transaction.mjs +0 -75
  78. package/runtime/scripts/hfs/architecture/contract-bounds.mjs +0 -72
  79. package/runtime/scripts/hfs/architecture/contract-fixture-guard.mjs +0 -177
  80. package/runtime/scripts/hfs/architecture/contracts-readonly.mjs +0 -360
  81. package/runtime/scripts/hfs/architecture/contracts.mjs +0 -489
  82. package/runtime/scripts/hfs/architecture/cross-app-duplicate.mjs +0 -81
  83. package/runtime/scripts/hfs/architecture/dead-exports-bindings.mjs +0 -173
  84. package/runtime/scripts/hfs/architecture/dead-exports.mjs +0 -420
  85. package/runtime/scripts/hfs/architecture/default-deny.mjs +0 -175
  86. package/runtime/scripts/hfs/architecture/doc-language.mjs +0 -45
  87. package/runtime/scripts/hfs/architecture/entity-registry.mjs +0 -51
  88. package/runtime/scripts/hfs/architecture/entrypoint.mjs +0 -75
  89. package/runtime/scripts/hfs/architecture/error-codes.mjs +0 -54
  90. package/runtime/scripts/hfs/architecture/error-masked.mjs +0 -78
  91. package/runtime/scripts/hfs/architecture/fe-slot-allows.mjs +0 -44
  92. package/runtime/scripts/hfs/architecture/feature-shape.mjs +0 -60
  93. package/runtime/scripts/hfs/architecture/framework-pinned.mjs +0 -41
  94. package/runtime/scripts/hfs/architecture/frontend-block-render.mjs +0 -112
  95. package/runtime/scripts/hfs/architecture/frontend-grammar.mjs +0 -193
  96. package/runtime/scripts/hfs/architecture/frontend-routing.mjs +0 -198
  97. package/runtime/scripts/hfs/architecture/frontend-world-render.mjs +0 -368
  98. package/runtime/scripts/hfs/architecture/frontend-world.mjs +0 -374
  99. package/runtime/scripts/hfs/architecture/frontend.mjs +0 -248
  100. package/runtime/scripts/hfs/architecture/function-spec-providers.mjs +0 -185
  101. package/runtime/scripts/hfs/architecture/hfs-graph.mjs +0 -77
  102. package/runtime/scripts/hfs/architecture/hfs.mjs +0 -394
  103. package/runtime/scripts/hfs/architecture/hooks-are-hooks.mjs +0 -118
  104. package/runtime/scripts/hfs/architecture/i18n-keys.mjs +0 -213
  105. package/runtime/scripts/hfs/architecture/identity.mjs +0 -121
  106. package/runtime/scripts/hfs/architecture/index.mjs +0 -402
  107. package/runtime/scripts/hfs/architecture/injection-token-exported.mjs +0 -69
  108. package/runtime/scripts/hfs/architecture/jwt-ast.mjs +0 -231
  109. package/runtime/scripts/hfs/architecture/machine-ast.mjs +0 -232
  110. package/runtime/scripts/hfs/architecture/managed-scripts.mjs +0 -32
  111. package/runtime/scripts/hfs/architecture/module-per-transport.mjs +0 -237
  112. package/runtime/scripts/hfs/architecture/next-data-contract.mjs +0 -126
  113. package/runtime/scripts/hfs/architecture/next-data-inference.mjs +0 -192
  114. package/runtime/scripts/hfs/architecture/next-data-key.mjs +0 -374
  115. package/runtime/scripts/hfs/architecture/next-data-symbols.mjs +0 -26
  116. package/runtime/scripts/hfs/architecture/next-data.mjs +0 -425
  117. package/runtime/scripts/hfs/architecture/operation-contract-roots.mjs +0 -55
  118. package/runtime/scripts/hfs/architecture/owners.mjs +0 -142
  119. package/runtime/scripts/hfs/architecture/package-shape.mjs +0 -92
  120. package/runtime/scripts/hfs/architecture/presentation.mjs +0 -173
  121. package/runtime/scripts/hfs/architecture/reachability.mjs +0 -330
  122. package/runtime/scripts/hfs/architecture/register-once.mjs +0 -212
  123. package/runtime/scripts/hfs/architecture/registration.mjs +0 -372
  124. package/runtime/scripts/hfs/architecture/render-graph.mjs +0 -449
  125. package/runtime/scripts/hfs/architecture/render-prop-across-server.mjs +0 -58
  126. package/runtime/scripts/hfs/architecture/required-files.mjs +0 -237
  127. package/runtime/scripts/hfs/architecture/root-packages.mjs +0 -78
  128. package/runtime/scripts/hfs/architecture/route-files-thin.mjs +0 -133
  129. package/runtime/scripts/hfs/architecture/schema-owner.mjs +0 -288
  130. package/runtime/scripts/hfs/architecture/server-action.mjs +0 -78
  131. package/runtime/scripts/hfs/architecture/side-boundary.mjs +0 -13
  132. package/runtime/scripts/hfs/architecture/source-names-shape.mjs +0 -320
  133. package/runtime/scripts/hfs/architecture/source-names.mjs +0 -393
  134. package/runtime/scripts/hfs/architecture/sql-keys.mjs +0 -344
  135. package/runtime/scripts/hfs/architecture/sql-owner.mjs +0 -291
  136. package/runtime/scripts/hfs/architecture/sql-returning.mjs +0 -76
  137. package/runtime/scripts/hfs/architecture/sql-token-forms.mjs +0 -117
  138. package/runtime/scripts/hfs/architecture/sql-tokens.mjs +0 -587
  139. package/runtime/scripts/hfs/architecture/staged-consumers.mjs +0 -42
  140. package/runtime/scripts/hfs/architecture/surface-nesting.mjs +0 -127
  141. package/runtime/scripts/hfs/architecture/surface.mjs +0 -88
  142. package/runtime/scripts/hfs/architecture/symbols.mjs +0 -273
  143. package/runtime/scripts/hfs/architecture/test-world-files.mjs +0 -263
  144. package/runtime/scripts/hfs/architecture/tiers.mjs +0 -256
  145. package/runtime/scripts/hfs/architecture/transport-owner.mjs +0 -248
  146. package/runtime/scripts/hfs/architecture/type-context.mjs +0 -335
  147. package/runtime/scripts/hfs/architecture/typescript.mjs +0 -477
  148. package/runtime/scripts/hfs/architecture/unit-spec-providers.mjs +0 -165
  149. package/runtime/scripts/hfs/declaration-shape.mjs +0 -196
  150. package/runtime/scripts/hfs/declaration-slots.mjs +0 -89
  151. package/runtime/scripts/hfs/edition-slots.mjs +0 -80
  152. package/runtime/scripts/hfs/explicit-surface-rule.mjs +0 -59
  153. package/runtime/scripts/hfs/linear-text.mjs +0 -30
  154. package/runtime/scripts/hfs/manifest-shape.mjs +0 -474
  155. package/runtime/scripts/hfs/param-names.mjs +0 -13
  156. package/runtime/scripts/hfs/path-findings.mjs +0 -167
  157. package/runtime/scripts/hfs/repo-identity.mjs +0 -89
  158. package/runtime/scripts/hfs/rule-catalog.mjs +0 -458
  159. package/runtime/scripts/hfs/rule-params-shape.mjs +0 -103
  160. package/runtime/scripts/hfs/rules/database-constants.mjs +0 -25
  161. package/runtime/scripts/hfs/rules/database-migrations.mjs +0 -684
  162. package/runtime/scripts/hfs/rules/fe-no-tests.mjs +0 -68
  163. package/runtime/scripts/hfs/rules/read.mjs +0 -45
  164. package/runtime/scripts/hfs/rules/secrets.mjs +0 -79
  165. package/runtime/scripts/hfs/rules/spec-placement.mjs +0 -28
  166. package/runtime/scripts/hfs/slot-app-view.mjs +0 -97
  167. package/runtime/scripts/hfs/slot-classify.mjs +0 -69
  168. package/runtime/scripts/hfs/slot-errors.mjs +0 -12
  169. package/runtime/scripts/hfs/slot-imports.mjs +0 -98
  170. package/runtime/scripts/hfs/slot-manifest-shape.mjs +0 -111
  171. package/runtime/scripts/hfs/slot-match.mjs +0 -164
  172. package/runtime/scripts/hfs/slot-path.mjs +0 -6
  173. package/runtime/scripts/hfs/slot-required.mjs +0 -95
  174. package/runtime/scripts/hfs/slot-semantic-problems.mjs +0 -175
  175. package/runtime/scripts/hfs/slot-side-problems.mjs +0 -32
  176. package/runtime/scripts/hfs/slots.mjs +0 -306
  177. package/runtime/scripts/hfs/test-world-slot.mjs +0 -5
  178. package/runtime/scripts/hfs/trailing-slashes.mjs +0 -8
  179. package/runtime/scripts/hfs/typescript-programs.mjs +0 -95
  180. package/runtime/scripts/hfs/view.mjs +0 -180
  181. package/runtime/scripts/lib/declaration-surface.mjs +0 -166
  182. package/runtime/scripts/lib/dockerfile.mjs +0 -164
  183. package/runtime/scripts/lib/env.mjs +0 -18
  184. package/runtime/scripts/lib/event-contract.mjs +0 -102
  185. package/runtime/scripts/lib/git-hooks-dir.mjs +0 -30
  186. package/runtime/scripts/lib/git.mjs +0 -35
  187. package/runtime/scripts/lib/glob.mjs +0 -32
  188. package/runtime/scripts/lib/grammar-lint.mjs +0 -57
  189. package/runtime/scripts/lib/i18n.mjs +0 -82
  190. package/runtime/scripts/lib/in-order.mjs +0 -90
  191. package/runtime/scripts/lib/json-clone.mjs +0 -70
  192. package/runtime/scripts/lib/json.mjs +0 -44
  193. package/runtime/scripts/lib/language.mjs +0 -233
  194. package/runtime/scripts/lib/list.mjs +0 -26
  195. package/runtime/scripts/lib/mutation-fence.mjs +0 -20
  196. package/runtime/scripts/lib/package-at.mjs +0 -62
  197. package/runtime/scripts/lib/path-key.mjs +0 -124
  198. package/runtime/scripts/lib/read-text.mjs +0 -47
  199. package/runtime/scripts/lib/regex.mjs +0 -3
  200. package/runtime/scripts/lib/rule-packs.mjs +0 -243
  201. package/runtime/scripts/lib/same-text.mjs +0 -4
  202. package/runtime/scripts/lib/secret-patterns.mjs +0 -230
  203. package/runtime/scripts/lib/sops-envelope.mjs +0 -212
  204. package/runtime/scripts/lib/stack-services.mjs +0 -191
  205. package/runtime/scripts/lib/ts-analysis.mjs +0 -39
  206. package/runtime/scripts/lib/ts-ast.mjs +0 -63
  207. package/runtime/scripts/lib/walk.mjs +0 -45
  208. package/runtime/scripts/lib/yaml-cached.mjs +0 -14
@@ -1,350 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { machineKit, pascal, upperSnake } from './machine-ast.mjs';
4
- import { locateDeclaration } from '../slots.mjs';
5
- import { byCodeUnit } from '../../lib/list.mjs';
6
- /**
7
- * R84 `connection-map` (BE_CONNECTION_DUPLICATE), folding RED01 and RED02. One physical database is one connection, one
8
- * `Inject<Conn>EntityManager()` injector, one config; the `hfs.json` connections, the connection files, the injectors, the
9
- * database module registration of every app and the env of every stack correspond one to one.
10
- *
11
- * - per declared connection `<name>`: `src/modules/platform/database/<name>.connection.ts` exports
12
- * `<NAME>_CONNECTION = "<name>"`, `<name>.decorators.ts` exports `Inject<Pascal>EntityManager`, `<name>.config.ts`
13
- * exists and reads only `<ENVPREFIX>_*` keys;
14
- * - a connection file for a name hfs.json does not declare is refused;
15
- * - `getEntityManagerToken(` and `InjectEntityManager(` (from @nestjs/typeorm) resolve their argument through the
16
- * checker to a connection name and may be called only in that connection's decorators file, once; the DataSource
17
- * forms only in platform/database, the cli app and the test fixtures; an exported `Inject*EntityManager`
18
- * anywhere else (a capability-specific injector, a duplicate) is refused;
19
- * - inside one app every connection is passed to the platform/database module registration once;
20
- * - a connection whose hfs.json `isolation` is `schema` reads `<PREFIX>_SCHEMA` in its config (a context is its own database or its own
21
- * schema of a shared one; splitting it out later is an env change only);
22
- * - in every `.starcistacks/<env>/runtime/env` two connections whose `<PREFIX>_HOST`, `<PREFIX>_PORT` and
23
- * `<PREFIX>_NAME` (or `_DATABASE`, whichever the config reads) resolve to one triple are the same database, unless both are
24
- * `isolation: schema` with different `<PREFIX>_SCHEMA` values (two contexts as schemas of one database).
25
- */
26
- export const CONNECTION_RULE_IDS = ['BE_CONNECTION_DUPLICATE'];
27
- const RULE = 'BE_CONNECTION_DUPLICATE';
28
- export const DATABASE_DIR = 'src/modules/platform/database';
29
- const TYPEORM = '@nestjs/typeorm';
30
- const MANAGER_CALLS = new Set(['getEntityManagerToken', 'InjectEntityManager']);
31
- const SOURCE_CALLS = new Set(['getDataSourceToken', 'InjectDataSource']);
32
- const ENV_KEY = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/u;
33
- const INJECTOR_NAME = /^Inject[A-Za-z0-9]*EntityManager$/u;
34
- const exportedInjectorName = (ts, kit, node) => {
35
- const statement = node.parent?.parent;
36
- if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && statement && ts.isVariableStatement(statement) && kit.isExported(statement))
37
- return node.name.text;
38
- if (ts.isFunctionDeclaration(node) && kit.isExported(node) && node.name)
39
- return node.name.text;
40
- return null;
41
- };
42
- const ENV_ASSIGNMENT = /^(?:export\s+)?([A-Za-z_]\w*)\s*=/u;
43
- const LINE_BREAK = /[\n\r\u2028\u2029]/u;
44
- // One `KEY=value` line: a value holding a line break after its first character is not an assignment.
45
- function parseEnvLine(raw) {
46
- const line = raw.trim();
47
- if (!line || line.startsWith('#'))
48
- return null;
49
- const match = ENV_ASSIGNMENT.exec(line);
50
- if (!match)
51
- return null;
52
- const key = match[1];
53
- if (key === undefined)
54
- return null;
55
- let value = line.slice(match[0].length).trim();
56
- if (LINE_BREAK.test(value))
57
- return null;
58
- if (/^(['"]).*\1$/u.test(value))
59
- value = value.slice(1, -1);
60
- return [key, value.trim()];
61
- }
62
- function readEnvFile(file, merged) {
63
- let text;
64
- try {
65
- text = fs.readFileSync(file, 'utf8');
66
- }
67
- catch {
68
- return;
69
- }
70
- for (const raw of text.split(/\r?\n/u)) {
71
- const parsed = parseEnvLine(raw);
72
- if (parsed)
73
- merged.set(parsed[0], parsed[1]);
74
- }
75
- }
76
- function readEnvFiles(target) {
77
- const merged = new Map();
78
- let stat;
79
- try {
80
- stat = fs.statSync(target);
81
- }
82
- catch {
83
- return null;
84
- }
85
- if (stat.isFile())
86
- readEnvFile(target, merged);
87
- else
88
- for (const entry of fs.readdirSync(target, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
89
- if (entry.isFile() && !entry.name.toLowerCase().endsWith('.md'))
90
- readEnvFile(path.join(target, entry.name), merged);
91
- }
92
- return merged;
93
- }
94
- const exportsVariable = (ts, kit, item, name) => ts.isVariableStatement(item) && kit.isExported(item)
95
- && item.declarationList.declarations.some(declaration => ts.isIdentifier(declaration.name) && declaration.name.text === name);
96
- const checkConnectionFile = (connection, kit, ts, report) => {
97
- const connectionRel = `${DATABASE_DIR}/${connection.name}.connection.ts`;
98
- const constant = `${upperSnake(connection.name)}_CONNECTION`;
99
- const connectionFile = kit.graphFile(connectionRel);
100
- if (!connectionFile) {
101
- report(connectionRel, `hfs.json declares connection ${connection.name} but ${connectionRel} does not exist; declare \`export const ${constant} = "${connection.name}"\` there.`, { connection: connection.name });
102
- return;
103
- }
104
- const checker = kit.checkerOf(connectionFile.sourceFile);
105
- const statement = connectionFile.sourceFile.statements.find(item => exportsVariable(ts, kit, item, constant));
106
- const initializer = statement?.declarationList.declarations.find(declaration => ts.isIdentifier(declaration.name) && declaration.name.text === constant)?.initializer;
107
- if (!statement || kit.stringValue(checker, initializer) !== connection.name) {
108
- report(connectionRel, `${connectionRel} must export \`${constant} = "${connection.name}"\` (the connection name declared in hfs.json).`, { connection: connection.name });
109
- }
110
- };
111
- const checkInjectorFile = (connection, kit, ts, report, decoratorsFile) => {
112
- const decorators = kit.graphFile(decoratorsFile(connection.name));
113
- const injector = `Inject${pascal(connection.name)}EntityManager`;
114
- const exported = decorators?.sourceFile.statements.some(item => exportsVariable(ts, kit, item, injector)
115
- || (ts.isFunctionDeclaration(item) && kit.isExported(item) && item.name?.text === injector));
116
- if (!exported)
117
- report(decoratorsFile(connection.name), `Connection ${connection.name} needs ${decoratorsFile(connection.name)} exporting ${injector}, the one injector of its shared EntityManager.`, { connection: connection.name });
118
- };
119
- const isProcessEnvAccess = (ts, node) => ts.isPropertyAccessExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'env'
120
- && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === 'process';
121
- const configEnvKey = (ts, node) => {
122
- if (ts.isStringLiteralLike(node) && ENV_KEY.test(node.text))
123
- return node.text;
124
- if (isProcessEnvAccess(ts, node) && ENV_KEY.test(node.name.text))
125
- return node.name.text;
126
- return null;
127
- };
128
- const checkConfigFile = (connection, declared, kit, ts, report, configRel, configFile) => {
129
- let readsSchema = false;
130
- kit.walk(configFile.sourceFile, node => {
131
- const key = configEnvKey(ts, node);
132
- if (key === null)
133
- return true;
134
- if (key === `${connection.envPrefix}_SCHEMA`)
135
- readsSchema = true;
136
- const own = key.startsWith(`${connection.envPrefix}_`);
137
- const foreign = declared.some(other => other !== connection && key.startsWith(`${other.envPrefix}_`));
138
- if (!own || foreign) {
139
- report(configRel, `${configRel} reads ${key}; the config of connection ${connection.name} reads only ${connection.envPrefix}_* keys.`, { ...kit.at(configRel, configFile.sourceFile, node), connection: connection.name });
140
- }
141
- return false;
142
- });
143
- if (connection.isolation === 'schema' && !readsSchema)
144
- report(configRel, `Connection ${connection.name} is isolated as a schema of a shared database (hfs.json isolation), so ${configRel} must read ${connection.envPrefix}_SCHEMA and hand it to the data source; splitting the context out into its own database is then an env change only.`, { connection: connection.name });
145
- };
146
- const checkDeclaredConnections = (declared, kit, ts, report, decoratorsFile) => {
147
- for (const connection of declared) {
148
- checkConnectionFile(connection, kit, ts, report);
149
- checkInjectorFile(connection, kit, ts, report, decoratorsFile);
150
- const configRel = `${DATABASE_DIR}/${connection.name}.config.ts`;
151
- const configFile = kit.graphFile(configRel);
152
- if (!configFile) {
153
- report(configRel, `Connection ${connection.name} needs ${configRel}, the one place its ${connection.envPrefix}_* keys are read.`, { connection: connection.name });
154
- continue;
155
- }
156
- checkConfigFile(connection, declared, kit, ts, report, configRel, configFile);
157
- }
158
- };
159
- const reportUndeclaredDatabaseFiles = (databaseFiles, byName, report) => {
160
- for (const file of databaseFiles) {
161
- const match = /^(.+)\.(connection|decorators|config)\.ts$/u.exec(path.posix.basename(file.rel));
162
- const name = match?.[1];
163
- if (match && name !== undefined && path.posix.dirname(file.rel) === DATABASE_DIR && !byName.has(name)) {
164
- report(file.rel, `${file.rel} belongs to connection ${name}, which hfs.json does not declare; declare the database in hfs.json connections or delete the file.`, { connection: name });
165
- }
166
- }
167
- };
168
- const inspectManagerToken = (file, checker, node, binding, state) => {
169
- const { kit, byName, decoratorsFile, report, perDecorators } = state;
170
- const value = kit.stringValue(checker, node.arguments[0]);
171
- const home = value === null ? null : decoratorsFile(value);
172
- if (value === null || !byName.has(value)) {
173
- const target = value === null ? 'a connection that cannot be resolved to a constant' : `connection ${value}, which hfs.json does not declare`;
174
- report(file.rel, `${binding.name}() names ${target}; only the declared connections have an entity manager token.`, kit.at(file.rel, file.sourceFile, node));
175
- }
176
- else if (file.rel !== home) {
177
- report(file.rel, `${binding.name}(${value}) belongs in ${home} only; inject the shared manager with Inject${pascal(value)}EntityManager() instead of a second path to connection ${value}.`, { ...kit.at(file.rel, file.sourceFile, node), connection: value });
178
- }
179
- else {
180
- perDecorators.set(value, (perDecorators.get(value) ?? 0) + 1);
181
- if ((perDecorators.get(value) ?? 0) > 1)
182
- report(file.rel, `${home} resolves connection ${value} more than once; one connection has one injector.`, { ...kit.at(file.rel, file.sourceFile, node), connection: value });
183
- }
184
- };
185
- const inspectDataSourceCall = (file, node, binding, state) => {
186
- const allowed = file.rel.startsWith(`${DATABASE_DIR}/`) || state.slotIs(file, 'be.app.cli') || state.slotIs(file, 'be.cli') || state.slotIs(file, 'be.tests.fixtures');
187
- if (!allowed)
188
- state.report(file.rel, `${binding.name}() reaches the DataSource outside platform/database and the cli; inject the shared EntityManager of the connection instead.`, state.kit.at(file.rel, file.sourceFile, node));
189
- };
190
- const inspectTypeormCall = (file, checker, node, state) => {
191
- const binding = state.kit.importBinding(checker, node.expression);
192
- if (binding?.module === TYPEORM && MANAGER_CALLS.has(binding.name))
193
- inspectManagerToken(file, checker, node, binding, state);
194
- else if (binding?.module === TYPEORM && SOURCE_CALLS.has(binding.name))
195
- inspectDataSourceCall(file, node, binding, state);
196
- };
197
- const inspectInjectorExport = (file, node, state) => {
198
- const { ts, kit, byName, decoratorsFile, report } = state;
199
- const exportedName = exportedInjectorName(ts, kit, node);
200
- if (!exportedName || !INJECTOR_NAME.test(exportedName))
201
- return;
202
- const home = [...byName.keys()].find(name => `Inject${pascal(name)}EntityManager` === exportedName);
203
- if (!home || file.rel !== decoratorsFile(home)) {
204
- report(file.rel, `${exportedName} is exported here, but the only injector of an entity manager is Inject<Conn>EntityManager in src/modules/platform/database/<conn>.decorators.ts, one per declared connection.`, kit.at(file.rel, file.sourceFile, node));
205
- }
206
- };
207
- const inspectManagerNode = (file, checker, node, state) => {
208
- if (state.ts.isCallExpression(node))
209
- inspectTypeormCall(file, checker, node, state);
210
- inspectInjectorExport(file, node, state);
211
- return true;
212
- };
213
- const checkManagerCalls = (graph, state) => {
214
- const perDecorators = new Map();
215
- const walkState = { ...state, perDecorators, slotIs: (file, id) => file.slot === id };
216
- for (const file of graph.files.values()) {
217
- const checker = state.kit.checkerOf(file.sourceFile);
218
- state.kit.walk(file.sourceFile, node => inspectManagerNode(file, checker, node, walkState));
219
- }
220
- };
221
- /** The receiver of a `<receiver>.register(...)` call that `node` is, or null. */
222
- const registerReceiver = (ts, node) => {
223
- if (!ts.isCallExpression(node))
224
- return null;
225
- const callee = node.expression;
226
- return ts.isPropertyAccessExpression(callee) && callee.name.text === 'register' ? callee.expression : null;
227
- };
228
- const isPropertyName = (ts, node) => {
229
- const parent = node.parent;
230
- if (!parent)
231
- return false;
232
- return (ts.isPropertyAssignment(parent) || ts.isPropertyAccessExpression(parent)) && parent.name === node;
233
- };
234
- const passConnections = (argument, scope) => {
235
- const { ts, kit, checker, byName, passed, root, app, report } = scope;
236
- kit.walk(argument, inner => {
237
- if (isPropertyName(ts, inner))
238
- return true;
239
- if (!(ts.isIdentifier(inner) || ts.isStringLiteralLike(inner) || ts.isPropertyAccessExpression(inner)))
240
- return true;
241
- const value = kit.stringValue(checker, inner);
242
- if (value === null || !byName.has(value))
243
- return true;
244
- passed.set(value, (passed.get(value) ?? 0) + 1);
245
- if ((passed.get(value) ?? 0) > 1)
246
- report(root.rel, `App ${app.name} passes connection ${value} to the database module registration more than once; one connection is registered once per app.`, { ...kit.at(root.rel, root.sourceFile, inner), connection: value, app: app.name });
247
- return false;
248
- });
249
- };
250
- const checkAppRegistrations = (config, kit, ts, byName, report) => {
251
- let registrations = 0;
252
- for (const app of config.apps) {
253
- // The root and its composition groups (compose/<area>.ts) are one composition: a connection is passed once across them.
254
- const passed = new Map();
255
- for (const root of kit.appCompositionFiles(app.name)) {
256
- const checker = kit.checkerOf(root.sourceFile);
257
- const scope = { ts, kit, checker, byName, passed, root, app, report };
258
- kit.walk(root.sourceFile, node => {
259
- const receiver = registerReceiver(ts, node);
260
- if (!receiver || !ts.isCallExpression(node))
261
- return;
262
- const owner = kit.declarationsOf(checker, receiver).map(kit.ownerOfDeclaration).find(Boolean);
263
- if (owner?.tier !== 'platform' || owner.name !== 'database')
264
- return;
265
- registrations += 1;
266
- for (const argument of node.arguments)
267
- passConnections(argument, scope);
268
- });
269
- }
270
- }
271
- return registrations;
272
- };
273
- const listStackEnvs = (stacksRoot) => {
274
- try {
275
- return fs.readdirSync(stacksRoot, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name).sort(byCodeUnit);
276
- }
277
- catch {
278
- return [];
279
- }
280
- };
281
- // The resolved database of one connection in one stack env, or null while its host, port or name is unset.
282
- const resolveStackConnection = (kit, connection, values) => {
283
- const configFile = kit.graphFile(`${DATABASE_DIR}/${connection.name}.config.ts`);
284
- const nameKey = configFile?.sourceFile.text.includes(`${connection.envPrefix}_DATABASE`) ? `${connection.envPrefix}_DATABASE` : `${connection.envPrefix}_NAME`;
285
- const host = values.get(`${connection.envPrefix}_HOST`);
286
- const port = values.get(`${connection.envPrefix}_PORT`);
287
- const database = values.get(nameKey);
288
- if (!host || !port || !database)
289
- return null;
290
- const schema = connection.isolation === 'schema' ? (values.get(`${connection.envPrefix}_SCHEMA`) ?? '') : null;
291
- return { host, port, database, triple: `${host.toLowerCase()}|${port}|${database}`, schema };
292
- };
293
- // True when the env resolves at least one connection; false when it is skipped.
294
- const checkStackEnv = (config, kit, declared, report, stacksRoot, env) => {
295
- // Relative to the side folder the machine judges (`../.starcistacks/...` for a side): the app-relative path once the side is prefixed.
296
- const rel = path.relative(config.root, path.join(stacksRoot, env, 'runtime', 'env')).split(path.sep).join('/');
297
- const values = readEnvFiles(path.join(stacksRoot, env, 'runtime', 'env'));
298
- if (!values || values.size === 0)
299
- return false;
300
- const seen = new Map(); // host|port|database -> [{name, isolation, schema}]
301
- let resolved = 0;
302
- for (const connection of declared) {
303
- const found = resolveStackConnection(kit, connection, values);
304
- if (!found)
305
- continue;
306
- resolved += 1;
307
- const { host, port, database, triple, schema } = found;
308
- const sharing = seen.get(triple) ?? [];
309
- // Two contexts may share one database only as distinct, named schemas; a context that is its own database shares it with nobody.
310
- const clash = sharing.find(other => schema === null || other.schema === null || other.schema === schema);
311
- if (clash) {
312
- const schemaDetail = schema !== null && clash.schema === schema ? `, schema ${schema || '(none)'}` : '';
313
- report(rel, `Connections ${clash.name} and ${connection.name} resolve to the same database (${host}:${port}/${database}${schemaDetail}) in stack ${env}; contexts share a database only as distinct schemas (isolation schema, a different ${connection.envPrefix}_SCHEMA), otherwise one physical database is one connection.`, { connection: connection.name, env });
314
- }
315
- sharing.push({ name: connection.name, schema });
316
- seen.set(triple, sharing);
317
- }
318
- return resolved > 0;
319
- };
320
- const checkStackConnections = (config, kit, declared, report) => {
321
- let stacksChecked = 0;
322
- let stacksSkipped = 0;
323
- // .starcistacks sits at the app root: the side folder the machine judges reads its app's tree (locateDeclaration).
324
- const stacksRoot = path.join(locateDeclaration(config.root).appRoot, '.starcistacks');
325
- for (const env of listStackEnvs(stacksRoot)) {
326
- if (checkStackEnv(config, kit, declared, report, stacksRoot, env))
327
- stacksChecked += 1;
328
- else
329
- stacksSkipped += 1;
330
- }
331
- return { stacksChecked, stacksSkipped };
332
- };
333
- export function checkConnectionMap(input) {
334
- const { config, graph } = input;
335
- const kit = machineKit(input);
336
- const { ts } = kit;
337
- const declared = config.hfs.repo.connections ?? [];
338
- const byName = new Map(declared.map((connection) => [connection.name, connection]));
339
- const violations = [];
340
- const report = (rel, message, extra = {}) => { violations.push({ ruleId: RULE, path: rel, message, ...extra }); };
341
- const decoratorsFile = name => `${DATABASE_DIR}/${name}.decorators.ts`;
342
- const databaseFiles = [...graph.files.values()].filter(file => file.rel.startsWith(`${DATABASE_DIR}/`));
343
- const state = { config, graph, kit, ts, declared, byName, violations, report, decoratorsFile };
344
- checkDeclaredConnections(declared, kit, ts, report, decoratorsFile);
345
- reportUndeclaredDatabaseFiles(databaseFiles, byName, report);
346
- checkManagerCalls(graph, state);
347
- const registrations = checkAppRegistrations(config, kit, ts, byName, report);
348
- const { stacksChecked, stacksSkipped } = checkStackConnections(config, kit, declared, report);
349
- return { violations, coverage: { status: 'checked', connections: declared.length, registrations, stacksChecked, stacksSkipped } };
350
- }
@@ -1,115 +0,0 @@
1
- import path from 'node:path';
2
- /**
3
- * The constructor dependencies of a service, read the way the injection law (R85) writes them, shared by the unit-spec
4
- * provider check (R48 `unit-spec-providers`) and the token export check (R85 `injection-token-exported`).
5
- *
6
- * A constructor parameter is one of
7
- * - `token`: decorated with a custom `Inject<Thing>()` decorator. The decorator is declared in a `<cap>.decorators.ts`
8
- * as `injector<T>(TOKEN)`; the dependency is the TOKEN it names, identified by the name the token is exported under
9
- * (the declaration's own name), never by the decorator's or the parameter's name. A raw `@Inject(TOKEN)` is read the same way.
10
- * - `class`: no injection decorator and a class type; the dependency is that class.
11
- * - `unresolved`: anything else (a token expression that is not a plain identifier, a decorator the reader cannot follow,
12
- * a type that is not a class).
13
- */
14
- const INJECT_NAME = /^Inject(?:[A-Z][A-Za-z0-9]*)?$/u;
15
- /** The identifier a decorator names: `@InjectFoo()` -> InjectFoo, `@Inject(TOKEN)` -> Inject; null for a non-identifier decorator. */
16
- function decoratorCallee(ts, decorator) {
17
- const expression = decorator.expression;
18
- const callee = ts.isCallExpression(expression) ? expression.expression : expression;
19
- return ts.isIdentifier(callee) ? { callee, call: ts.isCallExpression(expression) ? expression : null } : null;
20
- }
21
- /** The token a `injector(<arg>)` call names, judged where the argument is declared. */
22
- function tokenOfArgument(kit, checker, argument) {
23
- const { ts } = kit;
24
- if (!argument || !ts.isIdentifier(argument))
25
- return { kind: 'unresolved', reason: 'its token is not a plain identifier of an exported const', node: argument ?? null };
26
- const declaration = kit.declarationsOf(checker, argument).find((item) => ts.isVariableDeclaration(item) || ts.isBindingElement(item));
27
- if (declaration) {
28
- const name = ts.isIdentifier(declaration.name) ? declaration.name.text : argument.text;
29
- return { kind: 'token', name, declaration, argument, external: false };
30
- }
31
- const binding = kit.importBinding(checker, argument);
32
- if (binding && !binding.module.startsWith('.'))
33
- return { kind: 'token', name: binding.name, declaration: null, argument, external: true };
34
- return { kind: 'unresolved', reason: `the token ${argument.text} does not resolve to a declaration`, node: argument };
35
- }
36
- /** The first `injector(...)` call under a decorator declaration, or null. */
37
- function injectorCallOf(kit, declaration) {
38
- const { ts } = kit;
39
- let injectorCall = null;
40
- kit.walk(declaration, node => {
41
- if (injectorCall)
42
- return false;
43
- if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
44
- const binding = kit.importBinding(kit.checkerOf(declaration.getSourceFile()), node.expression);
45
- if ((binding?.name ?? node.expression.text) === 'injector')
46
- injectorCall = node;
47
- }
48
- return true;
49
- });
50
- return injectorCall;
51
- }
52
- /** The injector token of a custom `Inject<Thing>()` decorator, or an unresolved reason. */
53
- function tokenOfInjectDecorator(kit, checker, parameter, decorator) {
54
- const { ts } = kit;
55
- const head = decoratorCallee(ts, decorator);
56
- if (!head || !INJECT_NAME.test(head.callee.text))
57
- return null;
58
- if (head.callee.text === 'Inject' && head.call?.arguments.length)
59
- return { ...tokenOfArgument(kit, checker, head.call.arguments[0]), decorator: head.callee.text, decoratorDeclaration: null, decoratorFile: null };
60
- const declaration = kit.declarationsOf(checker, head.callee).find((item) => ts.isVariableDeclaration(item) || ts.isFunctionDeclaration(item));
61
- if (!declaration)
62
- return { kind: 'unresolved', reason: `${head.callee.text}() does not resolve to a declaration`, node: parameter, decorator: head.callee.text };
63
- const injectorCall = injectorCallOf(kit, declaration);
64
- if (!injectorCall)
65
- return { kind: 'unresolved', reason: `${head.callee.text}() is not built with injector<T>(TOKEN)`, node: parameter, decorator: head.callee.text };
66
- const declarationChecker = kit.checkerOf(declaration.getSourceFile());
67
- return { ...tokenOfArgument(kit, declarationChecker, injectorCall.arguments[0]), decorator: head.callee.text, decoratorDeclaration: declaration, injectorCall };
68
- }
69
- /** The class a parameter type names, judged where the type is declared; null when it is not a class type. */
70
- function classOfType(kit, checker, type) {
71
- const { ts } = kit;
72
- if (!type || !ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName))
73
- return null;
74
- const declarations = kit.declarationsOf(checker, type.typeName);
75
- const declared = declarations.find((item) => ts.isClassDeclaration(item) && Boolean(item.name));
76
- if (declared)
77
- return declared.name.text;
78
- if (declarations.length)
79
- return null;
80
- const binding = kit.importBinding(checker, type.typeName);
81
- return binding && binding.name !== 'default' && binding.name !== '*' ? binding.name : null;
82
- }
83
- /** The dependencies of one class, in constructor order: [{kind, name?, node, parameter, ...}]. */
84
- export function constructorDependencies(kit, file, classDeclaration) {
85
- const { ts } = kit;
86
- const checker = kit.checkerOf(file.sourceFile);
87
- const constructor = classDeclaration.members.find((member) => ts.isConstructorDeclaration(member) && member.body !== undefined)
88
- ?? classDeclaration.members.find((member) => ts.isConstructorDeclaration(member));
89
- if (!constructor)
90
- return [];
91
- return constructor.parameters.map((parameter) => {
92
- for (const decorator of kit.decorators(parameter)) {
93
- const token = tokenOfInjectDecorator(kit, checker, parameter, decorator);
94
- if (token)
95
- return { ...token, parameter, node: token.node ?? parameter };
96
- }
97
- const name = classOfType(kit, checker, parameter.type);
98
- if (name)
99
- return { kind: 'class', name, parameter, node: parameter };
100
- return { kind: 'unresolved', reason: 'it has no Inject<Thing>() decorator and its type is not a class', parameter, node: parameter };
101
- });
102
- }
103
- /** Every service class of the program: [{file, declaration}] for each class of a `*.service.ts` file. */
104
- export function serviceClasses(kit, graph) {
105
- const { ts } = kit;
106
- const found = [];
107
- for (const file of graph.files.values()) {
108
- if (!path.posix.basename(file.rel).endsWith('.service.ts'))
109
- continue;
110
- for (const statement of file.sourceFile.statements)
111
- if (ts.isClassDeclaration(statement) && statement.name)
112
- found.push({ file, declaration: statement });
113
- }
114
- return found;
115
- }
@@ -1,117 +0,0 @@
1
- import path from 'node:path';
2
- import { contextModelOf } from './context-map.mjs';
3
- import { machineKit } from './machine-ast.mjs';
4
- import { entitiesOf } from './sql-owner.mjs';
5
- /**
6
- * R175 `context-coupling` (BE_CONTEXT_COUPLING). Bounded contexts are coupled by events only, never by their schema or their code:
7
- * - an entity relation (`OneToOne`, `OneToMany`, `ManyToOne`, `ManyToMany` imported from typeorm) whose target class is an entity of a capability
8
- * of another context is refused;
9
- * - a migration foreign key (`REFERENCES <table>` in a string of a migration file) onto a table whose entity belongs to another context is refused;
10
- * - a domain or projection file imports no file of a capability of another context (its entities, services or SQL).
11
- * A capability's context is the connection its persistence arrays are registered on (context-map.mjs). A file or table with no proven context
12
- * (a platform capability, a capability registered nowhere) is never judged, and the table of a foreign key is looked up through the entities the
13
- * program declares, never guessed from a name.
14
- */
15
- export const CONTEXT_COUPLING_RULE_IDS = ['BE_CONTEXT_COUPLING'];
16
- const RULE = 'BE_CONTEXT_COUPLING';
17
- const TYPEORM = 'typeorm';
18
- const RELATIONS = new Set(['OneToOne', 'OneToMany', 'ManyToOne', 'ManyToMany']);
19
- // The table identifier after the SQL keyword REFERENCES, optionally schema-qualified and quoted.
20
- const REFERENCES = /\bREFERENCES\s+(?:"?\w+"?\s*\.\s*)?"?(\w+)"?/giu;
21
- const checkCrossContextImports = (graph, model, covered, counts, once) => {
22
- for (const edge of graph.edges) {
23
- const from = graph.files.get(edge.from);
24
- const to = graph.files.get(edge.to);
25
- if (!from?.owner || !to?.owner || from.owner.root === to.owner.root)
26
- continue;
27
- const fromContext = model.contextOfFile(edge.from);
28
- const toContext = model.contextOfFile(edge.to);
29
- if (!fromContext || !toContext || fromContext === toContext)
30
- continue;
31
- counts.imports += 1;
32
- if (covered.has(`${edge.from}|${to.owner.root}`))
33
- continue;
34
- once(`${edge.from}|${edge.to}|${edge.line}`, { path: edge.from, line: edge.line, column: edge.column, message: `${from.owner.root} (context ${fromContext}) imports ${to.owner.root} (context ${toContext}); a context never imports another context's entities, services or SQL. Keep a local copy fed by its events, or read a projection.`, context: fromContext, targetContext: toContext });
35
- }
36
- };
37
- const relationTarget = (kit, model, argument) => {
38
- const { ts } = kit;
39
- const isFunction = argument && (ts.isArrowFunction(argument) || ts.isFunctionExpression(argument));
40
- const target = isFunction && !ts.isBlock(argument.body) ? model.unparen(argument.body) : null;
41
- return target && (ts.isIdentifier(target) || ts.isPropertyAccessExpression(target)) ? target : null;
42
- };
43
- // The relation decorator (`@ManyToOne(() => Target)` imported from typeorm) a node is, with the checker that resolves it, else null.
44
- const relationBinding = (kit, checker, node) => {
45
- const { ts } = kit;
46
- if (!ts.isDecorator(node) || !ts.isCallExpression(node.expression))
47
- return null;
48
- const binding = kit.importBinding(checker, node.expression.expression);
49
- return binding?.module === TYPEORM && RELATIONS.has(binding.name) ? binding : null;
50
- };
51
- const checkRelations = (scan, file, ownContext) => {
52
- const { kit, model, counts, covered, once } = scan;
53
- const { ts } = kit;
54
- const checker = kit.checkerOf(file.sourceFile);
55
- kit.walk(file.sourceFile, (node) => {
56
- const binding = relationBinding(kit, checker, node);
57
- if (!binding)
58
- return;
59
- counts.relations += 1;
60
- const target = relationTarget(kit, model, node.expression.arguments[0]);
61
- if (!target)
62
- return;
63
- const home = kit.declarationsOf(checker, ts.isPropertyAccessExpression(target) ? target.name : target).map(kit.ownerOfDeclaration).find(Boolean);
64
- const targetContext = home ? model.contextOfCapability(home.root) : null;
65
- if (!home || !targetContext || targetContext === ownContext)
66
- return;
67
- covered.add(`${file.rel}|${home.root}`);
68
- once(`${file.rel}|${node.getStart()}`, { ...kit.at(file.rel, file.sourceFile, node), message: `A ${binding.name} relation in ${file.owner?.root} (context ${ownContext}) targets an entity of ${home.root} (context ${targetContext}); a relation never crosses a context. Keep the other context's id as a plain column and fill a local copy or a projection from its events.`, context: ownContext, targetContext });
69
- });
70
- };
71
- const stringText = (ts, node) => (ts.isTemplateExpression(node) ? node.head.text + node.templateSpans.map((span) => ` ${span.literal.text}`).join('') : node.text);
72
- const checkForeignKeys = (scan, file, ownContext) => {
73
- const { kit, model, tables, counts, once } = scan;
74
- const { ts } = kit;
75
- kit.walk(file.sourceFile, (node) => {
76
- if (!(ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)))
77
- return;
78
- for (const match of stringText(ts, node).matchAll(REFERENCES)) {
79
- counts.foreignKeys += 1;
80
- const entity = tables.get(match[1].toLowerCase());
81
- const targetContext = entity?.owner ? model.contextOfCapability(entity.owner) : null;
82
- if (!entity || !targetContext || targetContext === ownContext)
83
- continue;
84
- once(`${file.rel}|${node.getStart()}|${match[1]}`, { ...kit.at(file.rel, file.sourceFile, node), message: `A foreign key in ${file.rel} references table ${entity.table} of ${entity.owner} (context ${targetContext}), but this migration belongs to context ${ownContext}; a foreign key never crosses a context. Keep the id as a plain column and validate it through the other context's API or a local copy fed by its events.`, context: ownContext, targetContext, table: entity.table });
85
- }
86
- });
87
- };
88
- const checkPersistenceFile = (scan, file) => {
89
- if (file.slot !== 'be.persistence' || !file.owner)
90
- return;
91
- const ownContext = scan.model.contextOfCapability(file.owner.root);
92
- if (!ownContext)
93
- return;
94
- if (path.posix.basename(file.rel).endsWith('.entity.ts'))
95
- checkRelations(scan, file, ownContext);
96
- if (file.rel.slice(file.owner.root.length + 1).startsWith('persistence/migrations/'))
97
- checkForeignKeys(scan, file, ownContext);
98
- };
99
- export function checkContextCoupling(input) {
100
- const { graph } = input;
101
- const kit = machineKit(input);
102
- const model = contextModelOf(kit, graph);
103
- const { tables } = entitiesOf(kit, graph);
104
- const violations = [];
105
- const seen = new Set();
106
- const once = (key, violation) => { if (!seen.has(key)) {
107
- seen.add(key);
108
- violations.push({ ruleId: RULE, ...violation });
109
- } };
110
- const counts = { relations: 0, foreignKeys: 0, imports: 0 };
111
- const covered = new Set(); // `${fromRel}|${targetRoot}` pairs a relation already reported, so the import edge is not a second finding
112
- const scan = { kit, model, tables, counts, covered, once };
113
- for (const file of graph.files.values())
114
- checkPersistenceFile(scan, file);
115
- checkCrossContextImports(graph, model, covered, counts, once);
116
- return { violations, coverage: { status: 'checked', ...counts } };
117
- }