@starci/eslint-canon-be 3.8.20 → 3.9.2

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 (164) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/runtime/bundle.json +192 -0
  4. package/runtime/engine/by-code-unit.mjs +6 -6
  5. package/runtime/engine/model-config.mjs +98 -76
  6. package/runtime/engine/orca-config.mjs +22 -17
  7. package/runtime/engine/release-config.mjs +22 -18
  8. package/runtime/engine/removed-vocabulary.mjs +21 -20
  9. package/runtime/engine/resources-config.mjs +42 -35
  10. package/runtime/engine/runtime-root.mjs +11 -13
  11. package/runtime/engine/secrets.mjs +170 -102
  12. package/runtime/engine/sonar-config.mjs +16 -13
  13. package/runtime/engine/temp-root.mjs +3 -9
  14. package/runtime/knowledge/hfs/canon-pins.yaml +10 -10
  15. package/runtime/knowledge/hfs/rules.yaml +6 -6
  16. package/runtime/knowledge/hfs/slots.yaml +2 -2
  17. package/runtime/knowledge/sonar-gate.yaml +1 -1
  18. package/runtime/packages/hfs/templates/app/package-scripts/package.json +1 -1
  19. package/runtime/scripts/api/git/cat-file.mjs +0 -1
  20. package/runtime/scripts/api/git/config-get.mjs +1 -2
  21. package/runtime/scripts/api/git/diff.mjs +0 -1
  22. package/runtime/scripts/api/git/lib.mjs +32 -32
  23. package/runtime/scripts/api/git/ls-files.mjs +0 -1
  24. package/runtime/scripts/api/git/ls-tree.mjs +0 -1
  25. package/runtime/scripts/api/git/merge-base.mjs +2 -3
  26. package/runtime/scripts/api/git/remote.mjs +0 -1
  27. package/runtime/scripts/api/git/rev-parse-query.mjs +0 -1
  28. package/runtime/scripts/api/git/show.mjs +0 -1
  29. package/runtime/scripts/hfs/allows.mjs +37 -38
  30. package/runtime/scripts/hfs/architecture/ast-walks.mjs +180 -163
  31. package/runtime/scripts/hfs/architecture/automatic-gates.mjs +80 -73
  32. package/runtime/scripts/hfs/architecture/backend-app-files.mjs +88 -77
  33. package/runtime/scripts/hfs/architecture/backend.mjs +378 -357
  34. package/runtime/scripts/hfs/architecture/background-unowned.mjs +201 -187
  35. package/runtime/scripts/hfs/architecture/canon-clones.mjs +260 -209
  36. package/runtime/scripts/hfs/architecture/canon-jsx-clones.mjs +149 -116
  37. package/runtime/scripts/hfs/architecture/client-reaches-server.mjs +72 -68
  38. package/runtime/scripts/hfs/architecture/clones.mjs +212 -217
  39. package/runtime/scripts/hfs/architecture/config-unread.mjs +7 -9
  40. package/runtime/scripts/hfs/architecture/config.mjs +302 -268
  41. package/runtime/scripts/hfs/architecture/connection-map.mjs +258 -225
  42. package/runtime/scripts/hfs/architecture/constructor-deps.mjs +80 -71
  43. package/runtime/scripts/hfs/architecture/context-coupling.mjs +82 -77
  44. package/runtime/scripts/hfs/architecture/context-map.mjs +267 -234
  45. package/runtime/scripts/hfs/architecture/context-owner.mjs +73 -61
  46. package/runtime/scripts/hfs/architecture/context-platform-tables.mjs +47 -43
  47. package/runtime/scripts/hfs/architecture/context-transaction.mjs +54 -52
  48. package/runtime/scripts/hfs/architecture/contract-fixture-guard.mjs +113 -104
  49. package/runtime/scripts/hfs/architecture/contracts-readonly.mjs +288 -270
  50. package/runtime/scripts/hfs/architecture/contracts.mjs +408 -393
  51. package/runtime/scripts/hfs/architecture/cross-app-duplicate.mjs +50 -51
  52. package/runtime/scripts/hfs/architecture/dead-exports-bindings.mjs +143 -119
  53. package/runtime/scripts/hfs/architecture/dead-exports.mjs +286 -228
  54. package/runtime/scripts/hfs/architecture/default-deny.mjs +129 -110
  55. package/runtime/scripts/hfs/architecture/doc-language.mjs +24 -19
  56. package/runtime/scripts/hfs/architecture/entity-registry.mjs +20 -22
  57. package/runtime/scripts/hfs/architecture/entrypoint.mjs +47 -45
  58. package/runtime/scripts/hfs/architecture/error-codes.mjs +37 -35
  59. package/runtime/scripts/hfs/architecture/error-masked.mjs +55 -59
  60. package/runtime/scripts/hfs/architecture/fe-slot-allows.mjs +24 -23
  61. package/runtime/scripts/hfs/architecture/feature-shape.mjs +40 -38
  62. package/runtime/scripts/hfs/architecture/framework-pinned.mjs +21 -21
  63. package/runtime/scripts/hfs/architecture/frontend-block-render.mjs +106 -98
  64. package/runtime/scripts/hfs/architecture/frontend-grammar.mjs +153 -150
  65. package/runtime/scripts/hfs/architecture/frontend-routing.mjs +161 -149
  66. package/runtime/scripts/hfs/architecture/frontend-world-render.mjs +343 -305
  67. package/runtime/scripts/hfs/architecture/frontend-world.mjs +340 -294
  68. package/runtime/scripts/hfs/architecture/frontend.mjs +174 -184
  69. package/runtime/scripts/hfs/architecture/function-spec-providers.mjs +124 -106
  70. package/runtime/scripts/hfs/architecture/hfs-graph.mjs +52 -48
  71. package/runtime/scripts/hfs/architecture/hooks-are-hooks.mjs +81 -71
  72. package/runtime/scripts/hfs/architecture/i18n-keys.mjs +155 -141
  73. package/runtime/scripts/hfs/architecture/identity.mjs +141 -125
  74. package/runtime/scripts/hfs/architecture/index.mjs +272 -272
  75. package/runtime/scripts/hfs/architecture/injection-token-exported.mjs +45 -43
  76. package/runtime/scripts/hfs/architecture/jwt-ast.mjs +195 -176
  77. package/runtime/scripts/hfs/architecture/machine-ast.mjs +163 -155
  78. package/runtime/scripts/hfs/architecture/managed-scripts.mjs +19 -20
  79. package/runtime/scripts/hfs/architecture/module-per-transport.mjs +177 -172
  80. package/runtime/scripts/hfs/architecture/next-data-contract.mjs +100 -78
  81. package/runtime/scripts/hfs/architecture/next-data-inference.mjs +170 -154
  82. package/runtime/scripts/hfs/architecture/next-data-key.mjs +311 -275
  83. package/runtime/scripts/hfs/architecture/next-data-symbols.mjs +17 -17
  84. package/runtime/scripts/hfs/architecture/next-data.mjs +351 -334
  85. package/runtime/scripts/hfs/architecture/operation-contract-roots.mjs +39 -37
  86. package/runtime/scripts/hfs/architecture/owners.mjs +97 -98
  87. package/runtime/scripts/hfs/architecture/package-shape.mjs +56 -55
  88. package/runtime/scripts/hfs/architecture/presentation.mjs +138 -130
  89. package/runtime/scripts/hfs/architecture/reachability.mjs +258 -241
  90. package/runtime/scripts/hfs/architecture/register-once.mjs +152 -139
  91. package/runtime/scripts/hfs/architecture/registration.mjs +301 -267
  92. package/runtime/scripts/hfs/architecture/required-files.mjs +172 -167
  93. package/runtime/scripts/hfs/architecture/route-files-thin.mjs +85 -77
  94. package/runtime/scripts/hfs/architecture/schema-owner.mjs +206 -181
  95. package/runtime/scripts/hfs/architecture/server-action.mjs +48 -48
  96. package/runtime/scripts/hfs/architecture/side-boundary.mjs +2 -5
  97. package/runtime/scripts/hfs/architecture/source-names-shape.mjs +261 -259
  98. package/runtime/scripts/hfs/architecture/source-names.mjs +304 -278
  99. package/runtime/scripts/hfs/architecture/sql-keys.mjs +277 -194
  100. package/runtime/scripts/hfs/architecture/sql-owner.mjs +236 -194
  101. package/runtime/scripts/hfs/architecture/sql-returning.mjs +46 -45
  102. package/runtime/scripts/hfs/architecture/sql-token-forms.mjs +86 -74
  103. package/runtime/scripts/hfs/architecture/sql-tokens.mjs +456 -341
  104. package/runtime/scripts/hfs/architecture/staged-consumers.mjs +35 -30
  105. package/runtime/scripts/hfs/architecture/surface.mjs +64 -74
  106. package/runtime/scripts/hfs/architecture/symbols.mjs +209 -216
  107. package/runtime/scripts/hfs/architecture/test-world-files.mjs +165 -155
  108. package/runtime/scripts/hfs/architecture/tiers.mjs +161 -154
  109. package/runtime/scripts/hfs/architecture/transport-owner.mjs +155 -149
  110. package/runtime/scripts/hfs/architecture/type-context.mjs +255 -250
  111. package/runtime/scripts/hfs/architecture/typescript.mjs +358 -318
  112. package/runtime/scripts/hfs/architecture/unit-spec-providers.mjs +110 -92
  113. package/runtime/scripts/hfs/declaration-shape.mjs +140 -103
  114. package/runtime/scripts/hfs/declaration-slots.mjs +64 -61
  115. package/runtime/scripts/hfs/edition-slots.mjs +43 -40
  116. package/runtime/scripts/hfs/linear-text.mjs +20 -20
  117. package/runtime/scripts/hfs/param-names.mjs +6 -11
  118. package/runtime/scripts/hfs/path-findings.mjs +120 -100
  119. package/runtime/scripts/hfs/repo-identity.mjs +55 -42
  120. package/runtime/scripts/hfs/rule-catalog.mjs +353 -257
  121. package/runtime/scripts/hfs/rule-params-shape.mjs +60 -47
  122. package/runtime/scripts/hfs/rules/database-migrations.mjs +428 -388
  123. package/runtime/scripts/hfs/rules/fe-no-tests.mjs +37 -36
  124. package/runtime/scripts/hfs/rules/read.mjs +19 -15
  125. package/runtime/scripts/hfs/rules/secrets.mjs +1 -1
  126. package/runtime/scripts/hfs/rules/spec-placement.mjs +12 -13
  127. package/runtime/scripts/hfs/slot-app-view.mjs +69 -74
  128. package/runtime/scripts/hfs/slot-classify.mjs +42 -38
  129. package/runtime/scripts/hfs/slot-errors.mjs +8 -7
  130. package/runtime/scripts/hfs/slot-imports.mjs +70 -63
  131. package/runtime/scripts/hfs/slot-manifest-shape.mjs +74 -52
  132. package/runtime/scripts/hfs/slot-match.mjs +122 -111
  133. package/runtime/scripts/hfs/slot-path.mjs +0 -2
  134. package/runtime/scripts/hfs/slot-required.mjs +65 -59
  135. package/runtime/scripts/hfs/slot-semantic-problems.mjs +138 -112
  136. package/runtime/scripts/hfs/slot-side-problems.mjs +23 -19
  137. package/runtime/scripts/hfs/slots.mjs +175 -152
  138. package/runtime/scripts/hfs/test-world-slot.mjs +0 -1
  139. package/runtime/scripts/hfs/trailing-slashes.mjs +4 -4
  140. package/runtime/scripts/hfs/typescript-programs.mjs +66 -69
  141. package/runtime/scripts/hfs/view.mjs +38 -40
  142. package/runtime/scripts/lib/dockerfile.mjs +131 -114
  143. package/runtime/scripts/lib/env.mjs +3 -6
  144. package/runtime/scripts/lib/event-contract.mjs +73 -78
  145. package/runtime/scripts/lib/git.mjs +15 -16
  146. package/runtime/scripts/lib/glob.mjs +23 -14
  147. package/runtime/scripts/lib/grammar-lint.mjs +33 -37
  148. package/runtime/scripts/lib/i18n.mjs +32 -35
  149. package/runtime/scripts/lib/in-order.mjs +57 -38
  150. package/runtime/scripts/lib/json-clone.mjs +45 -36
  151. package/runtime/scripts/lib/json.mjs +26 -14
  152. package/runtime/scripts/lib/language.mjs +133 -129
  153. package/runtime/scripts/lib/list.mjs +9 -14
  154. package/runtime/scripts/lib/mutation-fence.mjs +10 -5
  155. package/runtime/scripts/lib/path-key.mjs +53 -38
  156. package/runtime/scripts/lib/read-text.mjs +30 -17
  157. package/runtime/scripts/lib/regex.mjs +1 -2
  158. package/runtime/scripts/lib/same-text.mjs +0 -1
  159. package/runtime/scripts/lib/sops-envelope.mjs +148 -120
  160. package/runtime/scripts/lib/stack-services.mjs +128 -129
  161. package/runtime/scripts/lib/ts-analysis.mjs +28 -26
  162. package/runtime/scripts/lib/ts-ast.mjs +36 -42
  163. package/runtime/scripts/lib/walk.mjs +33 -27
  164. package/runtime/scripts/lib/yaml-cached.mjs +4 -4
@@ -3,7 +3,6 @@ import { analyzeSql, HOLE } from './sql-tokens.mjs';
3
3
  import { machineKit } from './machine-ast.mjs';
4
4
  import { contextModelOf } from './context-map.mjs';
5
5
  import { sqlUniqueSetsOf } from './sql-keys.mjs';
6
-
7
6
  /**
8
7
  * R86 `sql-owner` (BE_SQL_TABLE_OWNER). Every `sql` tagged template (the tag declared in platform/database) of a
9
8
  * `<name>.sql.ts` file in a capability's `persistence/` is read with the tokenizer of sql-tokens.mjs and judged against the
@@ -20,230 +19,273 @@ import { sqlUniqueSetsOf } from './sql-keys.mjs';
20
19
  * nobody. A join needs an explicit result bound because key constraints on its first relation do not bound joined rows.
21
20
  */
22
21
  export const SQL_OWNER_RULE_IDS = ['BE_SQL_TABLE_OWNER'];
23
-
24
22
  const RULE = 'BE_SQL_TABLE_OWNER';
25
23
  const TYPEORM = 'typeorm';
26
-
24
+ const hasOwner = (file) => Boolean(file.owner);
27
25
  const literalStrings = (ts, node) => {
28
- if (!node) return null;
29
- if (ts.isStringLiteralLike(node)) return [node.text];
30
- if (ts.isArrayLiteralExpression(node) && node.elements.every(item => ts.isStringLiteralLike(item))) return node.elements.map(item => item.text);
31
- return null;
26
+ if (!node)
27
+ return null;
28
+ if (ts.isStringLiteralLike(node))
29
+ return [node.text];
30
+ if (ts.isArrayLiteralExpression(node)) {
31
+ const literals = node.elements.filter((item) => ts.isStringLiteralLike(item));
32
+ if (literals.length === node.elements.length)
33
+ return literals.map(item => item.text);
34
+ }
35
+ return null;
32
36
  };
33
-
34
37
  function isTypeormDecorator(kit, checker, node, ...names) {
35
- const call = kit.ts.isCallExpression(node.expression) ? node.expression.expression : node.expression;
36
- const binding = kit.importBinding(checker, call);
37
- return binding?.module === TYPEORM && names.includes(binding.name);
38
+ const call = kit.ts.isCallExpression(node.expression) ? node.expression.expression : node.expression;
39
+ const binding = kit.importBinding(checker, call);
40
+ return binding?.module === TYPEORM && names.includes(binding.name);
41
+ }
42
+ /** Whether an object literal carries `unique: true`. */
43
+ function isUniqueTrue(kit, item) {
44
+ if (!kit.ts.isObjectLiteralExpression(item))
45
+ return false;
46
+ const unique = kit.propertyOf(item, 'unique');
47
+ return unique !== undefined && kit.valueOfProperty(unique).kind === kit.ts.SyntaxKind.TrueKeyword;
38
48
  }
39
-
40
49
  function entityTableInfo(kit, checker, statement) {
41
- const { ts } = kit;
42
- const entity = kit.decorators(statement).find(decorator => isTypeormDecorator(kit, checker, decorator, 'Entity'));
43
- if (!entity) return null;
44
- const argument = ts.isCallExpression(entity.expression) ? entity.expression.arguments[0] : null;
45
- let table = argument && ts.isStringLiteralLike(argument) ? argument.text : null;
46
- if (table === null && argument && ts.isObjectLiteralExpression(argument)) {
47
- const property = kit.propertyOf(argument, 'name');
48
- if (property && ts.isStringLiteralLike(kit.valueOfProperty(property))) table = kit.valueOfProperty(property).text;
49
- }
50
- return { table };
51
- }
52
-
50
+ const { ts } = kit;
51
+ const entity = kit.decorators(statement).find(decorator => isTypeormDecorator(kit, checker, decorator, 'Entity'));
52
+ if (!entity)
53
+ return null;
54
+ const argument = ts.isCallExpression(entity.expression) ? entity.expression.arguments[0] ?? null : null;
55
+ let table = argument && ts.isStringLiteralLike(argument) ? argument.text : null;
56
+ if (table === null && argument && ts.isObjectLiteralExpression(argument)) {
57
+ const property = kit.propertyOf(argument, 'name');
58
+ const value = property ? kit.valueOfProperty(property) : null;
59
+ if (value && ts.isStringLiteralLike(value))
60
+ table = value.text;
61
+ }
62
+ return { table };
63
+ }
53
64
  function mappedColumnName(kit, member, property) {
54
- const { ts } = kit;
55
- let column = property;
56
- for (const decorator of kit.decorators(member)) {
57
- const args = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
58
- for (const item of args) if (ts.isObjectLiteralExpression(item)) {
59
- const named = kit.propertyOf(item, 'name');
60
- if (named && ts.isStringLiteralLike(kit.valueOfProperty(named))) column = kit.valueOfProperty(named).text;
65
+ const { ts } = kit;
66
+ let column = property;
67
+ for (const decorator of kit.decorators(member)) {
68
+ const args = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
69
+ for (const item of args)
70
+ if (ts.isObjectLiteralExpression(item)) {
71
+ const named = kit.propertyOf(item, 'name');
72
+ const value = named ? kit.valueOfProperty(named) : null;
73
+ if (value && ts.isStringLiteralLike(value))
74
+ column = value.text;
75
+ }
61
76
  }
62
- }
63
- return column;
77
+ return column;
64
78
  }
65
-
66
79
  function addUniqueColumnSet(kit, checker, decorator, column, primary, sets) {
67
- const { ts } = kit;
68
- const args = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
69
- const uniqueOption = args.some(item => ts.isObjectLiteralExpression(item) && kit.propertyOf(item, 'unique')
70
- && kit.valueOfProperty(kit.propertyOf(item, 'unique')).kind === ts.SyntaxKind.TrueKeyword);
71
- if (isTypeormDecorator(kit, checker, decorator, 'PrimaryColumn', 'PrimaryGeneratedColumn')) primary.push(column.toLowerCase());
72
- else if (isTypeormDecorator(kit, checker, decorator, 'Column', 'Index') && uniqueOption) sets.push([column.toLowerCase()]);
73
- }
74
-
80
+ const { ts } = kit;
81
+ const args = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
82
+ const uniqueOption = args.some(item => isUniqueTrue(kit, item));
83
+ if (isTypeormDecorator(kit, checker, decorator, 'PrimaryColumn', 'PrimaryGeneratedColumn'))
84
+ primary.push(column.toLowerCase());
85
+ else if (isTypeormDecorator(kit, checker, decorator, 'Column', 'Index') && uniqueOption)
86
+ sets.push([column.toLowerCase()]);
87
+ }
88
+ /**
89
+ * The members of an entity class with the checker of the file declaring each: those of every class it extends first (a column base
90
+ * such as UuidAbstractEntity of platform/database maps no table of its own but gives its columns and its primary key to the entity),
91
+ * then its own.
92
+ */
93
+ function entityMembers(kit, checker, statement, seen = new Set()) {
94
+ const { ts } = kit;
95
+ if (seen.has(statement))
96
+ return [];
97
+ seen.add(statement);
98
+ const bases = (statement.heritageClauses ?? []).filter(clause => clause.token === ts.SyntaxKind.ExtendsKeyword)
99
+ .flatMap(clause => clause.types).flatMap(type => kit.declarationsOf(checker, type.expression)).filter((node) => ts.isClassDeclaration(node));
100
+ const inherited = bases.flatMap(base => entityMembers(kit, kit.checkerOf(base.getSourceFile()) ?? checker, base, seen));
101
+ return [...inherited, ...statement.members.map((member) => ({ member, checker }))];
102
+ }
75
103
  function entityColumnSets(kit, checker, statement) {
76
- const { ts } = kit;
77
- const dbName = new Map();
78
- const primary = [];
79
- const sets = [];
80
- for (const member of statement.members) {
81
- if (!ts.isPropertyDeclaration(member) || !member.name || !ts.isIdentifier(member.name)) continue;
82
- const property = member.name.text;
83
- const column = mappedColumnName(kit, member, property);
84
- dbName.set(property, column.toLowerCase());
85
- for (const decorator of kit.decorators(member)) addUniqueColumnSet(kit, checker, decorator, column, primary, sets);
86
- }
87
- if (primary.length) sets.push(primary);
88
- return { dbName, sets };
89
- }
90
-
104
+ const { ts } = kit;
105
+ const dbName = new Map();
106
+ const primary = [];
107
+ const sets = [];
108
+ for (const { member, checker: memberChecker } of entityMembers(kit, checker, statement)) {
109
+ if (!ts.isPropertyDeclaration(member) || !member.name || !ts.isIdentifier(member.name))
110
+ continue;
111
+ const property = member.name.text;
112
+ const column = mappedColumnName(kit, member, property);
113
+ dbName.set(property, column.toLowerCase());
114
+ for (const decorator of kit.decorators(member))
115
+ addUniqueColumnSet(kit, memberChecker, decorator, column, primary, sets);
116
+ }
117
+ if (primary.length)
118
+ sets.push(primary);
119
+ return { dbName, sets };
120
+ }
91
121
  function addEntityUniqueSets(kit, checker, statement, dbName, sets) {
92
- const { ts } = kit;
93
- for (const decorator of kit.decorators(statement)) {
94
- const args = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
95
- const list = args.find(item => ts.isArrayLiteralExpression(item) && literalStrings(ts, item));
96
- const columns = list ? literalStrings(ts, list) : null;
97
- const unique = isTypeormDecorator(kit, checker, decorator, 'Unique') || (isTypeormDecorator(kit, checker, decorator, 'Index') && args.some(item => ts.isObjectLiteralExpression(item) && kit.propertyOf(item, 'unique')
98
- && kit.valueOfProperty(kit.propertyOf(item, 'unique')).kind === ts.SyntaxKind.TrueKeyword));
99
- if (unique && columns) sets.push(columns.map(column => (dbName.get(column) ?? column).toLowerCase()));
100
- }
101
- }
102
-
122
+ const { ts } = kit;
123
+ for (const decorator of kit.decorators(statement)) {
124
+ const args = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
125
+ const list = args.find(item => ts.isArrayLiteralExpression(item) && literalStrings(ts, item));
126
+ const columns = list ? literalStrings(ts, list) : null;
127
+ const unique = isTypeormDecorator(kit, checker, decorator, 'Unique') || (isTypeormDecorator(kit, checker, decorator, 'Index') && args.some(item => isUniqueTrue(kit, item)));
128
+ if (unique && columns)
129
+ sets.push(columns.map(column => (dbName.get(column) ?? column).toLowerCase()));
130
+ }
131
+ }
103
132
  /** Records the entities one `.entity.ts` file declares into `tables`; returns how many of its entities have no readable table name. */
104
133
  function addFileEntities(kit, file, tables) {
105
- const checker = kit.checkerOf(file.sourceFile);
106
- let unreadable = 0;
107
- for (const statement of file.sourceFile.statements) {
108
- if (!kit.ts.isClassDeclaration(statement)) continue;
109
- const entity = entityTableInfo(kit, checker, statement);
110
- if (!entity) continue;
111
- if (entity.table === null) { unreadable += 1; continue; }
112
- const { dbName, sets } = entityColumnSets(kit, checker, statement);
113
- addEntityUniqueSets(kit, checker, statement, dbName, sets);
114
- const key = entity.table.toLowerCase();
115
- if (!tables.has(key)) tables.set(key, { table: entity.table, owner: file.owner.root, rel: file.rel, uniqueSets: sets });
116
- }
117
- return unreadable;
118
- }
119
-
134
+ const checker = kit.checkerOf(file.sourceFile);
135
+ let unreadable = 0;
136
+ for (const statement of file.sourceFile.statements) {
137
+ if (!kit.ts.isClassDeclaration(statement))
138
+ continue;
139
+ const entity = entityTableInfo(kit, checker, statement);
140
+ if (!entity)
141
+ continue;
142
+ if (entity.table === null) {
143
+ unreadable += 1;
144
+ continue;
145
+ }
146
+ const { dbName, sets } = entityColumnSets(kit, checker, statement);
147
+ addEntityUniqueSets(kit, checker, statement, dbName, sets);
148
+ const key = entity.table.toLowerCase();
149
+ if (!tables.has(key))
150
+ tables.set(key, { table: entity.table, owner: file.owner.root, rel: file.rel, uniqueSets: sets });
151
+ }
152
+ return unreadable;
153
+ }
120
154
  export function entitiesOf(kit, graph) {
121
- const tables = new Map();
122
- let unreadable = 0;
123
- for (const file of graph.files.values()) {
124
- if (file.slot !== 'be.persistence' || !path.posix.basename(file.rel).endsWith('.entity.ts') || !file.owner) continue;
125
- unreadable += addFileEntities(kit, file, tables);
126
- }
127
- return { tables, unreadable };
128
- }
129
-
130
- const capabilityTable = root => path.posix.basename(root).replaceAll('-', '_').toLowerCase();
131
-
155
+ const tables = new Map();
156
+ let unreadable = 0;
157
+ for (const file of graph.files.values()) {
158
+ if (file.slot !== 'be.persistence' || !path.posix.basename(file.rel).endsWith('.entity.ts') || !hasOwner(file))
159
+ continue;
160
+ unreadable += addFileEntities(kit, file, tables);
161
+ }
162
+ return { tables, unreadable };
163
+ }
164
+ const capabilityTable = (root) => path.posix.basename(root).replaceAll('-', '_').toLowerCase();
132
165
  /** SQL-authority declarations (the public tables db/migrations create), with an owner when a table name matches a capability's persistence folder. */
133
166
  function sqlDeclarations(graph, appRoot) {
134
- const keys = sqlUniqueSetsOf(appRoot);
135
- const tables = new Map([...keys.keys()].map(table => [table, { table, owner: null, rel: null, uniqueSets: keys.get(table) ?? [] }]));
136
- for (const file of graph.files.values()) {
137
- if (file.slot !== 'be.persistence' || !file.owner) continue;
138
- const key = capabilityTable(file.owner.root);
139
- const declaration = tables.get(key);
140
- if (declaration?.owner === null) tables.set(key, { ...declaration, owner: file.owner.root, rel: file.rel });
141
- }
142
- return tables;
143
- }
144
-
167
+ const keys = sqlUniqueSetsOf(appRoot);
168
+ const tables = new Map([...keys.keys()].map((table) => [table, { table, owner: null, rel: null, uniqueSets: keys.get(table) ?? [] }]));
169
+ for (const file of graph.files.values()) {
170
+ if (file.slot !== 'be.persistence' || !file.owner)
171
+ continue;
172
+ const key = capabilityTable(file.owner.root);
173
+ const declaration = tables.get(key);
174
+ if (declaration?.owner === null)
175
+ tables.set(key, { ...declaration, owner: file.owner.root, rel: file.rel });
176
+ }
177
+ return tables;
178
+ }
145
179
  /** A capability owns the table named for it and the tables that start with its name and an underscore (`realtime`, `realtime_events`). */
146
180
  const isOwnTable = (table, ownTable) => {
147
- const name = table.toLowerCase();
148
- return name === ownTable || name.startsWith(`${ownTable}_`);
181
+ const name = table.toLowerCase();
182
+ return name === ownTable || name.startsWith(`${ownTable}_`);
149
183
  };
150
-
151
184
  function reportSqlWrite({ tables, sqlAuthority, file, ownTable, report }, write) {
152
- const declaration = tables.get(write.table.toLowerCase());
153
- if (!declaration) {
154
- report(sqlAuthority
155
- ? `SQL writes table ${write.table}, which no db/migrations migration creates; add the table in a migration first.`
156
- : `SQL writes table ${write.table}, which no @Entity declares; declare the entity in the owning capability's persistence/entities.`, { table: write.table });
157
- } else if (sqlAuthority) {
158
- if (isOwnTable(write.table, ownTable) && (declaration.owner === null || declaration.owner === file.owner.root)) return;
159
- const ownerNote = declaration.owner ? `, owned by ${declaration.owner}` : '';
160
- report(`SQL in ${file.owner.root} writes table ${write.table}${ownerNote}; under the SQL migration authority a capability writes only its own table (${ownTable}), named for that capability.`, { table: write.table, ...(declaration.owner ? { tableOwner: declaration.owner } : {}) });
161
- } else if (declaration.owner !== file.owner.root) {
162
- report(`SQL in ${file.owner.root} writes table ${write.table}, owned by ${declaration.owner}; a capability writes only the tables of its own entities, call the owner's public API instead.`, { table: write.table, tableOwner: declaration.owner });
163
- }
164
- }
165
-
185
+ const declaration = tables.get(write.table.toLowerCase());
186
+ if (!declaration) {
187
+ report(sqlAuthority
188
+ ? `SQL writes table ${write.table}, which no db/migrations migration creates; add the table in a migration first.`
189
+ : `SQL writes table ${write.table}, which no @Entity declares; declare the entity in the owning capability's persistence/entities.`, { table: write.table });
190
+ }
191
+ else if (sqlAuthority) {
192
+ if (isOwnTable(write.table, ownTable) && (declaration.owner === null || declaration.owner === file.owner.root))
193
+ return;
194
+ const ownerNote = declaration.owner ? `, owned by ${declaration.owner}` : '';
195
+ report(`SQL in ${file.owner.root} writes table ${write.table}${ownerNote}; under the SQL migration authority a capability writes only its own table (${ownTable}), named for that capability.`, { table: write.table, ...(declaration.owner ? { tableOwner: declaration.owner } : {}) });
196
+ }
197
+ else if (declaration.owner !== file.owner.root) {
198
+ report(`SQL in ${file.owner.root} writes table ${write.table}, owned by ${declaration.owner}; a capability writes only the tables of its own entities, call the owner's public API instead.`, { table: write.table, tableOwner: declaration.owner });
199
+ }
200
+ }
166
201
  function reportSqlWrites(input) {
167
- for (const write of input.result.writes) reportSqlWrite(input, write);
202
+ for (const write of input.result.writes)
203
+ reportSqlWrite(input, write);
168
204
  }
169
-
170
205
  function reportSqlRead(tables, sqlAuthority, file, model, resolver, report, read) {
171
- const declaration = tables.get(read.table.toLowerCase());
172
- if (!declaration) {
173
- report(sqlAuthority
174
- ? `SQL reads table ${read.table}, which no db/migrations migration creates; add the table in a migration first.`
175
- : `SQL reads table ${read.table}, which no @Entity declares; declare the entity in the owning capability's persistence/entities.`, { table: read.table });
176
- return;
177
- }
178
- if (!declaration.owner || declaration.owner === file.owner.root) return;
179
- const ownContext = model.contextOfCapability(file.owner.root);
180
- const tableContext = model.contextOfCapability(declaration.owner);
181
- if (ownContext && tableContext && ownContext !== tableContext) {
182
- report(`SQL in ${file.owner.root} (context ${ownContext}) reads table ${read.table}, owned by ${declaration.owner} (context ${tableContext}); a context reads and writes only its own context's tables, so a cross-context JOIN or subquery is refused. Keep a local copy fed by the other context's events (a reactor), or read a projection.`, { table: read.table, tableOwner: declaration.owner, context: ownContext, tableContext });
183
- return;
184
- }
185
- const verdict = resolver.importAllowed(file.rel, `${declaration.owner}/index.ts`);
186
- if (!verdict.allowed) report(`SQL in ${file.owner.root} reads table ${read.table}, owned by ${declaration.owner}, which ${file.owner.root} may not import (${verdict.reason}); read it through the owner's public API.`, { table: read.table, tableOwner: declaration.owner, reason: verdict.reason });
187
- }
188
-
206
+ const declaration = tables.get(read.table.toLowerCase());
207
+ if (!declaration) {
208
+ report(sqlAuthority
209
+ ? `SQL reads table ${read.table}, which no db/migrations migration creates; add the table in a migration first.`
210
+ : `SQL reads table ${read.table}, which no @Entity declares; declare the entity in the owning capability's persistence/entities.`, { table: read.table });
211
+ return;
212
+ }
213
+ if (!declaration.owner || declaration.owner === file.owner.root)
214
+ return;
215
+ const ownContext = model.contextOfCapability(file.owner.root);
216
+ const tableContext = model.contextOfCapability(declaration.owner);
217
+ if (ownContext && tableContext && ownContext !== tableContext) {
218
+ report(`SQL in ${file.owner.root} (context ${ownContext}) reads table ${read.table}, owned by ${declaration.owner} (context ${tableContext}); a context reads and writes only its own context's tables, so a cross-context JOIN or subquery is refused. Keep a local copy fed by the other context's events (a reactor), or read a projection.`, { table: read.table, tableOwner: declaration.owner, context: ownContext, tableContext });
219
+ return;
220
+ }
221
+ const verdict = resolver.importAllowed(file.rel, `${declaration.owner}/index.ts`);
222
+ if (!verdict.allowed)
223
+ report(`SQL in ${file.owner.root} reads table ${read.table}, owned by ${declaration.owner}, which ${file.owner.root} may not import (${verdict.reason}); read it through the owner's public API.`, { table: read.table, tableOwner: declaration.owner, reason: verdict.reason });
224
+ }
189
225
  function reportSqlReads({ result, tables, sqlAuthority, file, model, resolver, report }) {
190
- for (const read of result.reads) reportSqlRead(tables, sqlAuthority, file, model, resolver, report, read);
226
+ for (const read of result.reads)
227
+ reportSqlRead(tables, sqlAuthority, file, model, resolver, report, read);
191
228
  }
192
-
193
229
  function reportSqlSelects({ result, tables, report }) {
194
- for (const select of result.selects) {
195
- if (select.bounded || (select.table && !tables.has(select.table.toLowerCase()))) continue;
196
- const tableNote = select.table ? `on ${select.table} ` : '';
197
- report(`SELECT ${tableNote}has no LIMIT and does not constrain a primary key or unique column with =; bound it with LIMIT (PAGE_SIZE_MAX, LIST_ROWS_MAX or BATCH_ROWS from platform/database), filter by key, or select only aggregates.`, { table: select.table ?? undefined });
198
- }
230
+ for (const select of result.selects) {
231
+ if (select.bounded || (select.table && !tables.has(select.table.toLowerCase())))
232
+ continue;
233
+ const tableNote = select.table ? `on ${select.table} ` : '';
234
+ report(`SELECT ${tableNote}has no LIMIT and does not constrain a primary key or unique column with =; bound it with LIMIT (PAGE_SIZE_MAX, LIST_ROWS_MAX or BATCH_ROWS from platform/database), filter by key, or select only aggregates.`, { table: select.table ?? undefined });
235
+ }
199
236
  }
200
-
201
237
  function inspectSqlTag(input, state, file, checker, node) {
202
- const { kit, ts, tables, sqlAuthority, model, resolver } = input;
203
- if (!ts.isTaggedTemplateExpression(node)) return true;
204
- const home = kit.declarationsOf(checker, node.tag).map(kit.ownerOfDeclaration).find(Boolean);
205
- if (home?.tier !== 'platform' || home?.name !== 'database') { state.foreignTags += 1; return true; }
206
- state.templates += 1;
207
- const template = node.template;
208
- const text = ts.isNoSubstitutionTemplateLiteral(template) ? template.text
209
- : template.head.text + template.templateSpans.map(span => HOLE + span.literal.text).join('');
210
- const seen = new Set();
211
- const report = (message, extra = {}) => {
212
- const key = `${message}`;
213
- if (seen.has(key)) return;
214
- seen.add(key);
215
- state.violations.push({ ruleId: RULE, path: file.rel, ...kit.at(file.rel, file.sourceFile, node), message, ...extra });
216
- };
217
- const result = analyzeSql(text, { uniqueSetsOf: (table, schema) => {
218
- if (sqlAuthority && ((schema && schema !== 'public') || table !== table.toLowerCase())) return null;
219
- return tables.get(table.toLowerCase())?.uniqueSets ?? null;
220
- } });
221
- state.dynamic += result.dynamic;
222
- const ownTable = capabilityTable(file.owner.root);
223
- reportSqlWrites({ result, tables, sqlAuthority, file, ownTable, report });
224
- reportSqlReads({ result, tables, sqlAuthority, file, model, resolver, report });
225
- reportSqlSelects({ result, tables, report });
226
- return true;
227
- }
228
-
238
+ const { kit, ts, tables, sqlAuthority, model, resolver } = input;
239
+ if (!ts.isTaggedTemplateExpression(node))
240
+ return true;
241
+ const home = kit.declarationsOf(checker, node.tag).map(kit.ownerOfDeclaration).find(Boolean);
242
+ if (home?.tier !== 'platform' || home?.name !== 'database') {
243
+ state.foreignTags += 1;
244
+ return true;
245
+ }
246
+ state.templates += 1;
247
+ const template = node.template;
248
+ const text = ts.isNoSubstitutionTemplateLiteral(template) ? template.text
249
+ : template.head.text + template.templateSpans.map(span => HOLE + span.literal.text).join('');
250
+ const seen = new Set();
251
+ const report = (message, extra = {}) => {
252
+ const key = `${message}`;
253
+ if (seen.has(key))
254
+ return;
255
+ seen.add(key);
256
+ state.violations.push({ ruleId: RULE, path: file.rel, ...kit.at(file.rel, file.sourceFile, node), message, ...extra });
257
+ };
258
+ const result = analyzeSql(text, { uniqueSetsOf: (table, schema) => {
259
+ if (sqlAuthority && ((schema && schema !== 'public') || table !== table.toLowerCase()))
260
+ return null;
261
+ return tables.get(table.toLowerCase())?.uniqueSets ?? null;
262
+ } });
263
+ state.dynamic += result.dynamic;
264
+ const ownTable = capabilityTable(file.owner.root);
265
+ reportSqlWrites({ result, tables, sqlAuthority, file, ownTable, report });
266
+ reportSqlReads({ result, tables, sqlAuthority, file, model, resolver, report });
267
+ reportSqlSelects({ result, tables, report });
268
+ return true;
269
+ }
229
270
  function inspectSqlFile(input, state, file) {
230
- const { kit } = input;
231
- if (file.slot !== 'be.persistence' || !path.posix.basename(file.rel).endsWith('.sql.ts') || !file.owner) return;
232
- const checker = kit.checkerOf(file.sourceFile);
233
- kit.walk(file.sourceFile, node => inspectSqlTag(input, state, file, checker, node));
271
+ const { kit } = input;
272
+ if (file.slot !== 'be.persistence' || !path.posix.basename(file.rel).endsWith('.sql.ts') || !hasOwner(file))
273
+ return;
274
+ const checker = kit.checkerOf(file.sourceFile);
275
+ kit.walk(file.sourceFile, (node) => inspectSqlTag(input, state, file, checker, node));
234
276
  }
235
-
236
277
  export function checkSqlOwner(input) {
237
- const { config, graph } = input;
238
- const kit = machineKit(input);
239
- const { ts, resolver } = kit;
240
- const sqlAuthority = resolver.ruleParams().schemaAuthority === 'sql';
241
- const entityDeclarations = sqlAuthority ? { tables: new Map(), unreadable: 0 } : entitiesOf(kit, graph);
242
- const tables = sqlAuthority ? sqlDeclarations(graph, config.packageRoot) : entityDeclarations.tables;
243
- const model = contextModelOf(kit, graph);
244
- const state = { violations: [], templates: 0, dynamic: 0, foreignTags: 0 };
245
- const inspection = { kit, ts, tables, sqlAuthority, model, resolver };
246
- for (const file of graph.files.values()) inspectSqlFile(inspection, state, file);
247
- return { violations: state.violations, coverage: { status: 'checked', entities: entityDeclarations.tables.size, unreadableEntities: entityDeclarations.unreadable,
248
- ...(sqlAuthority ? { sqlTables: tables.size } : {}), templates: state.templates, dynamicIdentifiers: state.dynamic, foreignTags: state.foreignTags } };
278
+ const { config, graph } = input;
279
+ const kit = machineKit(input);
280
+ const { ts, resolver } = kit;
281
+ const sqlAuthority = resolver.ruleParams()?.schemaAuthority === 'sql';
282
+ const entityDeclarations = sqlAuthority ? { tables: new Map(), unreadable: 0 } : entitiesOf(kit, graph);
283
+ const tables = sqlAuthority ? sqlDeclarations(graph, config.packageRoot) : entityDeclarations.tables;
284
+ const model = contextModelOf(kit, graph);
285
+ const state = { violations: [], templates: 0, dynamic: 0, foreignTags: 0 };
286
+ const inspection = { kit, ts, tables, sqlAuthority, model, resolver };
287
+ for (const file of graph.files.values())
288
+ inspectSqlFile(inspection, state, file);
289
+ return { violations: state.violations, coverage: { status: 'checked', entities: entityDeclarations.tables.size, unreadableEntities: entityDeclarations.unreadable,
290
+ ...(sqlAuthority ? { sqlTables: tables.size } : {}), templates: state.templates, dynamicIdentifiers: state.dynamic, foreignTags: state.foreignTags } };
249
291
  }
@@ -1,7 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { HOLE, tokenizeSql } from './sql-tokens.mjs';
3
3
  import { machineKit } from './machine-ast.mjs';
4
-
5
4
  /**
6
5
  * R181 `sql-returning` (BE_SQL_RETURNING_SHAPE). TypeORM's `EntityManager.query` returns an UPDATE or DELETE with RETURNING as
7
6
  * `[rows, affectedCount]`, not as rows (an INSERT ... RETURNING returns rows), so a caller that reads the result as rows silently reads
@@ -12,64 +11,66 @@ import { machineKit } from './machine-ast.mjs';
12
11
  * wrapped form and passes; so does INSERT ... RETURNING and any statement without RETURNING.
13
12
  */
14
13
  export const SQL_RETURNING_RULE_IDS = ['BE_SQL_RETURNING_SHAPE'];
15
-
16
14
  const RULE = 'BE_SQL_RETURNING_SHAPE';
17
-
18
- /** Ends the statement in progress, recording its leading verb when it carried RETURNING. */
19
15
  function closeStatement(state) {
20
- if (state.verb && state.returning) state.found.push(state.verb);
21
- state.verb = null;
22
- state.returning = false;
16
+ if (state.verb && state.returning)
17
+ state.found.push(state.verb);
18
+ state.verb = null;
19
+ state.returning = false;
23
20
  }
24
-
25
21
  /** Folds one token into the statement state: parenthesis depth, statement ends and the top-level words. */
26
22
  function readToken(state, token) {
27
- if (token.t === 'punct') {
28
- if (token.v === '(') state.depth += 1;
29
- else if (token.v === ')') state.depth = Math.max(0, state.depth - 1);
30
- else if (token.v === ';' && state.depth === 0) closeStatement(state);
31
- return;
32
- }
33
- if (state.depth !== 0 || token.t !== 'word') return;
34
- if (state.verb === null) state.verb = token.up;
35
- else if (token.up === 'RETURNING') state.returning = true;
23
+ if (token.t === 'punct') {
24
+ if (token.v === '(')
25
+ state.depth += 1;
26
+ else if (token.v === ')')
27
+ state.depth = Math.max(0, state.depth - 1);
28
+ else if (token.v === ';' && state.depth === 0)
29
+ closeStatement(state);
30
+ return;
31
+ }
32
+ if (state.depth !== 0 || token.t !== 'word')
33
+ return;
34
+ if (state.verb === null)
35
+ state.verb = token.up; // a word token always carries its upper-case spelling
36
+ else if (token.up === 'RETURNING')
37
+ state.returning = true;
36
38
  }
37
-
38
39
  /** The leading verbs of the top-level statements of `text` that RETURN from an UPDATE or DELETE without a wrapping SELECT. */
39
40
  function unwrappedReturning(text) {
40
- const state = { found: [], depth: 0, verb: null, returning: false };
41
- for (const token of tokenizeSql(text)) readToken(state, token);
42
- closeStatement(state);
43
- return state.found.filter(verb => verb === 'UPDATE' || verb === 'DELETE');
41
+ const state = { found: [], depth: 0, verb: null, returning: false };
42
+ for (const token of tokenizeSql(text))
43
+ readToken(state, token);
44
+ closeStatement(state);
45
+ return state.found.filter(verb => verb === 'UPDATE' || verb === 'DELETE');
44
46
  }
45
-
46
47
  /** The SQL text of a tagged template, each substitution replaced by a HOLE marker. */
47
48
  function templateText(ts, template) {
48
- return ts.isNoSubstitutionTemplateLiteral(template) ? template.text
49
- : template.head.text + template.templateSpans.map(span => HOLE + span.literal.text).join('');
49
+ return ts.isNoSubstitutionTemplateLiteral(template) ? template.text
50
+ : template.head.text + template.templateSpans.map(span => HOLE + span.literal.text).join('');
50
51
  }
51
-
52
52
  const isDatabaseTag = (kit, checker, node) => {
53
- const home = kit.declarationsOf(checker, node.tag).map(kit.ownerOfDeclaration).find(Boolean);
54
- return home?.tier === 'platform' && home?.name === 'database';
53
+ const home = kit.declarationsOf(checker, node.tag).map(kit.ownerOfDeclaration).find(Boolean);
54
+ return home?.tier === 'platform' && home?.name === 'database';
55
55
  };
56
-
57
56
  const returningViolation = (kit, file, node, verb) => ({ ruleId: RULE, path: file.rel, ...kit.at(file.rel, file.sourceFile, node), message: `${verb} ... RETURNING in ${file.rel} is returned by EntityManager.query as [rows, affectedCount], not as rows, so a caller reading rows reads the wrong value. Wrap it: WITH changed AS (${verb} ... RETURNING ...) SELECT ... FROM changed.`, verb });
58
-
59
57
  export function checkSqlReturning(input) {
60
- const { graph } = input;
61
- const kit = machineKit(input);
62
- const { ts } = kit;
63
- const violations = [];
64
- let templates = 0;
65
- for (const file of graph.files.values()) {
66
- if (file.slot !== 'be.persistence' || !path.posix.basename(file.rel).endsWith('.sql.ts') || !file.owner) continue;
67
- const checker = kit.checkerOf(file.sourceFile);
68
- kit.walk(file.sourceFile, node => {
69
- if (!ts.isTaggedTemplateExpression(node) || !isDatabaseTag(kit, checker, node)) return;
70
- templates += 1;
71
- for (const verb of unwrappedReturning(templateText(ts, node.template))) violations.push(returningViolation(kit, file, node, verb));
72
- });
73
- }
74
- return { violations, coverage: { status: 'checked', templates } };
58
+ const { graph } = input;
59
+ const kit = machineKit(input);
60
+ const { ts } = kit;
61
+ const violations = [];
62
+ let templates = 0;
63
+ for (const file of graph.files.values()) {
64
+ if (file.slot !== 'be.persistence' || !path.posix.basename(file.rel).endsWith('.sql.ts') || !file.owner)
65
+ continue;
66
+ const checker = kit.checkerOf(file.sourceFile);
67
+ kit.walk(file.sourceFile, node => {
68
+ if (!ts.isTaggedTemplateExpression(node) || !isDatabaseTag(kit, checker, node))
69
+ return;
70
+ templates += 1;
71
+ for (const verb of unwrappedReturning(templateText(ts, node.template)))
72
+ violations.push(returningViolation(kit, file, node, verb));
73
+ });
74
+ }
75
+ return { violations, coverage: { status: 'checked', templates } };
75
76
  }