@starci/eslint-canon-be 3.18.4 → 3.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/comments.js +1 -1
  4. package/dist/explicit-surface.js +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/jwt-alg.js +1 -1
  7. package/dist/lib/edition.d.ts +1 -1
  8. package/dist/lib/edition.js +1 -1
  9. package/dist/lib/hfs-view.d.ts +5 -0
  10. package/dist/lib/hfs.d.ts +0 -6
  11. package/dist/lib/hfs.js +7 -5
  12. package/dist/lib/runtime-root.d.ts +6 -1
  13. package/dist/lib/runtime-root.js +8 -2
  14. package/dist/lib/subject-values.js +1 -1
  15. package/dist/module-layering.js +2 -2
  16. package/dist/project-graph.js +1 -1
  17. package/dist/schema-authority.js +66 -2
  18. package/dist/third-party-owner.js +1 -1
  19. package/package.json +3 -1
  20. package/runtime/bundle.json +1 -190
  21. package/runtime/scripts/api/git/recorded-lines.mjs +5 -5
  22. package/runtime/scripts/hfs/project-graph.mjs +6 -6
  23. package/runtime/scripts/hfs/project-rule.mjs +3 -3
  24. package/runtime/config.example.yaml +0 -194
  25. package/runtime/engine/by-code-unit.mjs +0 -12
  26. package/runtime/engine/config.mjs +0 -461
  27. package/runtime/engine/invalid-config.mjs +0 -15
  28. package/runtime/engine/model-config.mjs +0 -112
  29. package/runtime/engine/orca-config.mjs +0 -34
  30. package/runtime/engine/plain-object.mjs +0 -5
  31. package/runtime/engine/release-config.mjs +0 -32
  32. package/runtime/engine/removed-vocabulary.mjs +0 -27
  33. package/runtime/engine/resources-config.mjs +0 -59
  34. package/runtime/engine/runtime-root.mjs +0 -138
  35. package/runtime/engine/secrets.mjs +0 -202
  36. package/runtime/engine/sonar-config.mjs +0 -24
  37. package/runtime/engine/temp-root.mjs +0 -26
  38. package/runtime/engine/yaml.mjs +0 -161
  39. package/runtime/knowledge/grammars/index.yaml +0 -114
  40. package/runtime/knowledge/hfs/canon-pins.yaml +0 -720
  41. package/runtime/knowledge/hfs/fe-stack.yaml +0 -272
  42. package/runtime/knowledge/hfs/rules.yaml +0 -6760
  43. package/runtime/knowledge/hfs/slots.yaml +0 -2783
  44. package/runtime/knowledge/patterns/fe/folder.yaml +0 -425
  45. package/runtime/knowledge/sonar-gate.yaml +0 -151
  46. package/runtime/modules/kernel/removed-vocabulary.yaml +0 -458
  47. package/runtime/modules/models/registry.yaml +0 -221
  48. package/runtime/modules/models/runtimes.yaml +0 -556
  49. package/runtime/modules/models/tiers.yaml +0 -66
  50. package/runtime/scripts/api/git/cat-file.mjs +0 -4
  51. package/runtime/scripts/api/git/config-get.mjs +0 -9
  52. package/runtime/scripts/api/git/diff.mjs +0 -4
  53. package/runtime/scripts/api/git/lib.mjs +0 -80
  54. package/runtime/scripts/api/git/ls-files.mjs +0 -5
  55. package/runtime/scripts/api/git/ls-tree.mjs +0 -4
  56. package/runtime/scripts/api/git/merge-base.mjs +0 -8
  57. package/runtime/scripts/api/git/remote.mjs +0 -4
  58. package/runtime/scripts/api/git/rev-parse-query.mjs +0 -4
  59. package/runtime/scripts/api/git/show.mjs +0 -5
  60. package/runtime/scripts/api/git/tag.mjs +0 -4
  61. package/runtime/scripts/hfs/allows.mjs +0 -77
  62. package/runtime/scripts/hfs/architecture/ast-walks.mjs +0 -250
  63. package/runtime/scripts/hfs/architecture/automatic-gates.mjs +0 -103
  64. package/runtime/scripts/hfs/architecture/backend-app-files.mjs +0 -114
  65. package/runtime/scripts/hfs/architecture/backend.mjs +0 -462
  66. package/runtime/scripts/hfs/architecture/background-unowned.mjs +0 -254
  67. package/runtime/scripts/hfs/architecture/canon-clones.mjs +0 -291
  68. package/runtime/scripts/hfs/architecture/canon-jsx-clones.mjs +0 -224
  69. package/runtime/scripts/hfs/architecture/client-reaches-server.mjs +0 -102
  70. package/runtime/scripts/hfs/architecture/clones.mjs +0 -287
  71. package/runtime/scripts/hfs/architecture/component-tiers.mjs +0 -161
  72. package/runtime/scripts/hfs/architecture/config-unread.mjs +0 -16
  73. package/runtime/scripts/hfs/architecture/config.mjs +0 -407
  74. package/runtime/scripts/hfs/architecture/connection-map.mjs +0 -350
  75. package/runtime/scripts/hfs/architecture/constructor-deps.mjs +0 -115
  76. package/runtime/scripts/hfs/architecture/context-coupling.mjs +0 -117
  77. package/runtime/scripts/hfs/architecture/context-map.mjs +0 -355
  78. package/runtime/scripts/hfs/architecture/context-owner.mjs +0 -102
  79. package/runtime/scripts/hfs/architecture/context-platform-tables.mjs +0 -65
  80. package/runtime/scripts/hfs/architecture/context-transaction.mjs +0 -75
  81. package/runtime/scripts/hfs/architecture/contract-bounds.mjs +0 -72
  82. package/runtime/scripts/hfs/architecture/contract-fixture-guard.mjs +0 -177
  83. package/runtime/scripts/hfs/architecture/contracts-readonly.mjs +0 -360
  84. package/runtime/scripts/hfs/architecture/contracts.mjs +0 -489
  85. package/runtime/scripts/hfs/architecture/cross-app-duplicate.mjs +0 -81
  86. package/runtime/scripts/hfs/architecture/dead-exports-bindings.mjs +0 -173
  87. package/runtime/scripts/hfs/architecture/dead-exports.mjs +0 -420
  88. package/runtime/scripts/hfs/architecture/default-deny.mjs +0 -175
  89. package/runtime/scripts/hfs/architecture/doc-language.mjs +0 -45
  90. package/runtime/scripts/hfs/architecture/entity-registry.mjs +0 -51
  91. package/runtime/scripts/hfs/architecture/entrypoint.mjs +0 -75
  92. package/runtime/scripts/hfs/architecture/error-codes.mjs +0 -54
  93. package/runtime/scripts/hfs/architecture/error-masked.mjs +0 -78
  94. package/runtime/scripts/hfs/architecture/fe-slot-allows.mjs +0 -44
  95. package/runtime/scripts/hfs/architecture/feature-shape.mjs +0 -60
  96. package/runtime/scripts/hfs/architecture/framework-pinned.mjs +0 -41
  97. package/runtime/scripts/hfs/architecture/frontend-block-render.mjs +0 -112
  98. package/runtime/scripts/hfs/architecture/frontend-grammar.mjs +0 -193
  99. package/runtime/scripts/hfs/architecture/frontend-routing.mjs +0 -198
  100. package/runtime/scripts/hfs/architecture/frontend-world-render.mjs +0 -368
  101. package/runtime/scripts/hfs/architecture/frontend-world.mjs +0 -374
  102. package/runtime/scripts/hfs/architecture/frontend.mjs +0 -248
  103. package/runtime/scripts/hfs/architecture/function-spec-providers.mjs +0 -185
  104. package/runtime/scripts/hfs/architecture/hfs-graph.mjs +0 -77
  105. package/runtime/scripts/hfs/architecture/hfs.mjs +0 -394
  106. package/runtime/scripts/hfs/architecture/hooks-are-hooks.mjs +0 -118
  107. package/runtime/scripts/hfs/architecture/i18n-keys.mjs +0 -213
  108. package/runtime/scripts/hfs/architecture/identity.mjs +0 -121
  109. package/runtime/scripts/hfs/architecture/index.mjs +0 -402
  110. package/runtime/scripts/hfs/architecture/injection-token-exported.mjs +0 -69
  111. package/runtime/scripts/hfs/architecture/jwt-ast.mjs +0 -231
  112. package/runtime/scripts/hfs/architecture/machine-ast.mjs +0 -232
  113. package/runtime/scripts/hfs/architecture/managed-scripts.mjs +0 -32
  114. package/runtime/scripts/hfs/architecture/module-per-transport.mjs +0 -237
  115. package/runtime/scripts/hfs/architecture/next-data-contract.mjs +0 -126
  116. package/runtime/scripts/hfs/architecture/next-data-inference.mjs +0 -192
  117. package/runtime/scripts/hfs/architecture/next-data-key.mjs +0 -374
  118. package/runtime/scripts/hfs/architecture/next-data-symbols.mjs +0 -26
  119. package/runtime/scripts/hfs/architecture/next-data.mjs +0 -425
  120. package/runtime/scripts/hfs/architecture/operation-contract-roots.mjs +0 -55
  121. package/runtime/scripts/hfs/architecture/owners.mjs +0 -142
  122. package/runtime/scripts/hfs/architecture/package-shape.mjs +0 -92
  123. package/runtime/scripts/hfs/architecture/presentation.mjs +0 -173
  124. package/runtime/scripts/hfs/architecture/reachability.mjs +0 -330
  125. package/runtime/scripts/hfs/architecture/register-once.mjs +0 -212
  126. package/runtime/scripts/hfs/architecture/registration.mjs +0 -372
  127. package/runtime/scripts/hfs/architecture/render-graph.mjs +0 -449
  128. package/runtime/scripts/hfs/architecture/render-prop-across-server.mjs +0 -58
  129. package/runtime/scripts/hfs/architecture/required-files.mjs +0 -237
  130. package/runtime/scripts/hfs/architecture/root-packages.mjs +0 -78
  131. package/runtime/scripts/hfs/architecture/route-files-thin.mjs +0 -133
  132. package/runtime/scripts/hfs/architecture/schema-owner.mjs +0 -288
  133. package/runtime/scripts/hfs/architecture/server-action.mjs +0 -78
  134. package/runtime/scripts/hfs/architecture/side-boundary.mjs +0 -13
  135. package/runtime/scripts/hfs/architecture/source-names-shape.mjs +0 -320
  136. package/runtime/scripts/hfs/architecture/source-names.mjs +0 -393
  137. package/runtime/scripts/hfs/architecture/sql-keys.mjs +0 -344
  138. package/runtime/scripts/hfs/architecture/sql-owner.mjs +0 -291
  139. package/runtime/scripts/hfs/architecture/sql-returning.mjs +0 -76
  140. package/runtime/scripts/hfs/architecture/sql-token-forms.mjs +0 -117
  141. package/runtime/scripts/hfs/architecture/sql-tokens.mjs +0 -587
  142. package/runtime/scripts/hfs/architecture/staged-consumers.mjs +0 -42
  143. package/runtime/scripts/hfs/architecture/surface-nesting.mjs +0 -127
  144. package/runtime/scripts/hfs/architecture/surface.mjs +0 -88
  145. package/runtime/scripts/hfs/architecture/symbols.mjs +0 -273
  146. package/runtime/scripts/hfs/architecture/test-world-files.mjs +0 -263
  147. package/runtime/scripts/hfs/architecture/tiers.mjs +0 -256
  148. package/runtime/scripts/hfs/architecture/transport-owner.mjs +0 -248
  149. package/runtime/scripts/hfs/architecture/type-context.mjs +0 -335
  150. package/runtime/scripts/hfs/architecture/typescript.mjs +0 -477
  151. package/runtime/scripts/hfs/architecture/unit-spec-providers.mjs +0 -165
  152. package/runtime/scripts/hfs/declaration-shape.mjs +0 -196
  153. package/runtime/scripts/hfs/declaration-slots.mjs +0 -89
  154. package/runtime/scripts/hfs/edition-slots.mjs +0 -80
  155. package/runtime/scripts/hfs/explicit-surface-rule.mjs +0 -59
  156. package/runtime/scripts/hfs/linear-text.mjs +0 -30
  157. package/runtime/scripts/hfs/manifest-shape.mjs +0 -474
  158. package/runtime/scripts/hfs/param-names.mjs +0 -13
  159. package/runtime/scripts/hfs/path-findings.mjs +0 -167
  160. package/runtime/scripts/hfs/repo-identity.mjs +0 -89
  161. package/runtime/scripts/hfs/rule-catalog.mjs +0 -458
  162. package/runtime/scripts/hfs/rule-params-shape.mjs +0 -103
  163. package/runtime/scripts/hfs/rules/database-constants.mjs +0 -25
  164. package/runtime/scripts/hfs/rules/database-migrations.mjs +0 -684
  165. package/runtime/scripts/hfs/rules/fe-no-tests.mjs +0 -68
  166. package/runtime/scripts/hfs/rules/read.mjs +0 -45
  167. package/runtime/scripts/hfs/rules/secrets.mjs +0 -79
  168. package/runtime/scripts/hfs/rules/spec-placement.mjs +0 -28
  169. package/runtime/scripts/hfs/slot-app-view.mjs +0 -97
  170. package/runtime/scripts/hfs/slot-classify.mjs +0 -69
  171. package/runtime/scripts/hfs/slot-errors.mjs +0 -12
  172. package/runtime/scripts/hfs/slot-imports.mjs +0 -98
  173. package/runtime/scripts/hfs/slot-manifest-shape.mjs +0 -111
  174. package/runtime/scripts/hfs/slot-match.mjs +0 -164
  175. package/runtime/scripts/hfs/slot-path.mjs +0 -6
  176. package/runtime/scripts/hfs/slot-required.mjs +0 -95
  177. package/runtime/scripts/hfs/slot-semantic-problems.mjs +0 -175
  178. package/runtime/scripts/hfs/slot-side-problems.mjs +0 -32
  179. package/runtime/scripts/hfs/slots.mjs +0 -306
  180. package/runtime/scripts/hfs/test-world-slot.mjs +0 -5
  181. package/runtime/scripts/hfs/trailing-slashes.mjs +0 -8
  182. package/runtime/scripts/hfs/typescript-programs.mjs +0 -95
  183. package/runtime/scripts/hfs/view.mjs +0 -180
  184. package/runtime/scripts/lib/declaration-surface.mjs +0 -166
  185. package/runtime/scripts/lib/dockerfile.mjs +0 -164
  186. package/runtime/scripts/lib/env.mjs +0 -18
  187. package/runtime/scripts/lib/event-contract.mjs +0 -102
  188. package/runtime/scripts/lib/git-hooks-dir.mjs +0 -30
  189. package/runtime/scripts/lib/git.mjs +0 -35
  190. package/runtime/scripts/lib/glob.mjs +0 -32
  191. package/runtime/scripts/lib/grammar-lint.mjs +0 -57
  192. package/runtime/scripts/lib/i18n.mjs +0 -82
  193. package/runtime/scripts/lib/in-order.mjs +0 -90
  194. package/runtime/scripts/lib/json-clone.mjs +0 -70
  195. package/runtime/scripts/lib/json.mjs +0 -44
  196. package/runtime/scripts/lib/language.mjs +0 -233
  197. package/runtime/scripts/lib/list.mjs +0 -26
  198. package/runtime/scripts/lib/mutation-fence.mjs +0 -20
  199. package/runtime/scripts/lib/package-at.mjs +0 -62
  200. package/runtime/scripts/lib/path-key.mjs +0 -124
  201. package/runtime/scripts/lib/read-text.mjs +0 -47
  202. package/runtime/scripts/lib/regex.mjs +0 -3
  203. package/runtime/scripts/lib/rule-packs.mjs +0 -243
  204. package/runtime/scripts/lib/same-text.mjs +0 -4
  205. package/runtime/scripts/lib/secret-patterns.mjs +0 -230
  206. package/runtime/scripts/lib/sops-envelope.mjs +0 -212
  207. package/runtime/scripts/lib/stack-services.mjs +0 -191
  208. package/runtime/scripts/lib/ts-analysis.mjs +0 -39
  209. package/runtime/scripts/lib/ts-ast.mjs +0 -63
  210. package/runtime/scripts/lib/walk.mjs +0 -45
  211. package/runtime/scripts/lib/yaml-cached.mjs +0 -14
@@ -1,489 +0,0 @@
1
- import path from 'node:path';
2
- import { isInside } from './config.mjs';
3
- import { referencedExports, relativePath, unwrapExpression } from './typescript.mjs';
4
- import { commonJsRequireReasons, constructedDecoratorKind as sharedConstructedDecoratorKind, decoratorCallee, moduleExportsOf, nodeDecorators, normalizedSymbol, normalizedSymbolValue, programSourcesOf, selectedNode, valueSymbol, violation } from './ast-walks.mjs';
5
- import { byCodeUnit } from '../../lib/list.mjs';
6
- import { hasAnyFlag } from '../../lib/ts-ast.mjs';
7
- import { canonical, checkInjectedClass, checkMessageReadonly, isPublicMember, messageClass } from './contracts-readonly.mjs';
8
- export const PUBLIC_CONTRACT_RULE_ID = 'BE_PUBLIC_CONTRACT_FORM';
9
- export { READONLY_BOUNDARY_RULE_ID } from './contracts-readonly.mjs';
10
- const FRAMEWORK_EXPORTS = new Map([
11
- ['@nestjs/common', new Set(['Controller', 'Inject', 'Injectable', 'Module'])],
12
- ['@nestjs/cqrs', new Set(['CommandHandler', 'QueryHandler'])],
13
- ['@nestjs/graphql', new Set(['Resolver'])],
14
- ]);
15
- const NEST_CREATED = new Set(['CommandHandler', 'Controller', 'Injectable', 'QueryHandler', 'Resolver']);
16
- const MESSAGE_HANDLERS = new Set(['CommandHandler', 'QueryHandler']);
17
- const NON_API_SOURCE_ROLES = new Set(['config', 'configuration', 'constants', 'main', 'module', 'module-definition', 'providers']);
18
- const SOURCE_EXTENSION = /\.[cm]?[jt]sx?$/i;
19
- /** The checker of a file in the program; every file the contexts hand in belongs to one. */
20
- const checkerFor = (context, fileName) => context.checkerFor(fileName);
21
- function frameworkKindForSymbol(symbol, targets) {
22
- const selected = symbol ? targets.get(symbol) : undefined;
23
- if (selected)
24
- return selected;
25
- const name = symbol?.getName?.();
26
- if (!name)
27
- return null;
28
- for (const [packageName, exports] of FRAMEWORK_EXPORTS) {
29
- if (!exports.has(name))
30
- continue;
31
- const marker = `/node_modules/${packageName}/`;
32
- if ((symbol?.getDeclarations?.() ?? []).some((declaration) => declaration.getSourceFile().fileName.replaceAll('\\', '/').includes(marker)))
33
- return name;
34
- }
35
- return null;
36
- }
37
- /* This module's trace through frameworkKindForSymbol (name lookup and node_modules marker) instead of the
38
- * default symbol->kind map, plus the shorthand/property-assignment descent. */
39
- const FRAMEWORK_TRACE = {
40
- directOf: (ts, checker, { selected, targets }) => frameworkKindForSymbol(valueSymbol(ts, checker, selected), targets),
41
- shorthandOf: (_ts, _checker, target, targets) => frameworkKindForSymbol(target, targets),
42
- };
43
- function addFrameworkTargets(config, context, checker, sourceFile, statement, bySymbol, reasons) {
44
- const bound = moduleExportsOf(context.ts, checker, statement);
45
- if (!bound || !FRAMEWORK_EXPORTS.has(bound.specifier))
46
- return;
47
- if (!bound.symbol) {
48
- reasons.push(`${relativePath(config.root, sourceFile.fileName)} cannot resolve ${bound.specifier}`);
49
- return;
50
- }
51
- for (const name of referencedExports(context.ts, statement, FRAMEWORK_EXPORTS.get(bound.specifier))) {
52
- const target = bound.exports.get(name);
53
- if (target)
54
- bySymbol.set(target, name);
55
- else
56
- reasons.push(`${relativePath(config.root, sourceFile.fileName)} cannot resolve ${name} from ${bound.specifier}`);
57
- }
58
- }
59
- function frameworkTargets(config, context, checker, localFiles) {
60
- const bySymbol = new Map();
61
- const reasons = [];
62
- const files = programSourcesOf(context, checker, localFiles, { root: config.root });
63
- if (!files)
64
- return { bySymbol, reasons: ['a TypeScript program checker could not be associated with its source'] };
65
- for (const sourceFile of files) {
66
- for (const statement of sourceFile.statements)
67
- addFrameworkTargets(config, context, checker, sourceFile, statement, bySymbol, reasons);
68
- commonJsRequireReasons(context.ts, checker, sourceFile, (specifier) => FRAMEWORK_EXPORTS.has(specifier), reasons, relativePath(config.root, sourceFile.fileName), 'binding whose contract role cannot be proved');
69
- }
70
- return { bySymbol, reasons };
71
- }
72
- function decoratorKind(ts, checker, decorator, targets) {
73
- const selected = selectedNode(ts, decoratorCallee(ts, decorator));
74
- return selected ? frameworkKindForSymbol(valueSymbol(ts, checker, selected), targets) : null;
75
- }
76
- const constructedDecoratorKind = (ts, checker, decorator, targets) => sharedConstructedDecoratorKind(ts, checker, decorator, targets, FRAMEWORK_TRACE);
77
- function sourceRole(sourceFile) {
78
- const normalized = sourceFile.fileName.replaceAll('\\', '/');
79
- const base = path.basename(sourceFile.fileName).replace(SOURCE_EXTENSION, '').toLowerCase();
80
- const segments = base.split('.');
81
- const role = segments.length > 1 ? segments.at(-1) : ((base === 'use-case' || base.endsWith('-use-case')) && 'use-case') || null;
82
- return { base, role, transport: normalized.includes('/transport/') };
83
- }
84
- function isFrameworkHelper(sourceFile, declaration, framework) {
85
- const role = sourceRole(sourceFile);
86
- if (role.transport || NON_API_SOURCE_ROLES.has(role.role ?? '') || NON_API_SOURCE_ROLES.has(role.base))
87
- return true;
88
- if (declaration?.name && (declaration.name.text ?? '').endsWith('Module')) {
89
- return nodeDecorators(framework.ts, declaration).some((decorator) => decoratorKind(framework.ts, framework.checker, decorator, framework.targets) === 'Module');
90
- }
91
- return false;
92
- }
93
- function builtinSymbol(_ts, symbol, name) {
94
- if (!symbol || symbol.getName?.() !== name)
95
- return false;
96
- const declarations = symbol.getDeclarations?.() ?? [];
97
- return declarations.length > 0 && declarations.every((declaration) => declaration.getSourceFile().isDeclarationFile
98
- && /(?:^|[/\\])lib\.[^/\\]+\.d\.ts$/i.test(declaration.getSourceFile().fileName));
99
- }
100
- function typeReferenceStatus(ts, checker, node, seen, depth) {
101
- const symbol = normalizedSymbol(ts, checker, node.typeName);
102
- if (!symbol)
103
- return 'unavailable';
104
- if (builtinSymbol(ts, symbol, 'Promise') || builtinSymbol(ts, symbol, 'Readonly') || builtinSymbol(ts, symbol, 'Awaited')
105
- || builtinSymbol(ts, symbol, 'Array') || builtinSymbol(ts, symbol, 'ReadonlyArray')) {
106
- return node.typeArguments?.length === 1 ? contractTypeStatus(ts, checker, node.typeArguments[0], seen, depth + 1) : 'unavailable';
107
- }
108
- if (builtinSymbol(ts, symbol, 'Record') || builtinSymbol(ts, symbol, 'Partial') || builtinSymbol(ts, symbol, 'Pick')
109
- || builtinSymbol(ts, symbol, 'Omit') || builtinSymbol(ts, symbol, 'Required'))
110
- return 'inline';
111
- const declarations = symbol.getDeclarations?.() ?? [];
112
- if (!declarations.length)
113
- return 'unavailable';
114
- return declarations.every((declaration) => ts.isTypeParameterDeclaration(declaration)
115
- || ts.isInterfaceDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration)
116
- || ts.isClassDeclaration(declaration) || ts.isEnumDeclaration(declaration)) ? 'named' : 'unavailable';
117
- }
118
- function isInlineContractType(ts, node) {
119
- return ts.isTypeLiteralNode(node) || ts.isMappedTypeNode(node) || ts.isUnionTypeNode(node)
120
- || ts.isIntersectionTypeNode(node) || ts.isTupleTypeNode(node) || ts.isFunctionTypeNode(node);
121
- }
122
- function isUnavailableContractType(ts, node) {
123
- return ts.isConditionalTypeNode(node) || ts.isIndexedAccessTypeNode(node) || ts.isInferTypeNode(node)
124
- || ts.isTypeQueryNode(node) || ts.isImportTypeNode(node);
125
- }
126
- function contractTypeStatus(ts, checker, node, seen = new Set(), depth = 0) {
127
- if (!node || depth > 12)
128
- return 'unavailable';
129
- if (ts.isParenthesizedTypeNode(node))
130
- return contractTypeStatus(ts, checker, node.type, seen, depth + 1);
131
- if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.ReadonlyKeyword) {
132
- return contractTypeStatus(ts, checker, node.type, seen, depth + 1);
133
- }
134
- if (ts.isTypeReferenceNode(node))
135
- return typeReferenceStatus(ts, checker, node, seen, depth);
136
- if (ts.isArrayTypeNode(node))
137
- return contractTypeStatus(ts, checker, node.elementType, seen, depth + 1);
138
- if (isInlineContractType(ts, node))
139
- return 'inline';
140
- if (isUnavailableContractType(ts, node))
141
- return 'unavailable';
142
- return 'scalar';
143
- }
144
- function wrappedTypeStatus(ts, checker, type, named, nextSeen, depth) {
145
- for (const wrapper of ['Promise', 'Readonly', 'Awaited', 'Array', 'ReadonlyArray'])
146
- if (builtinSymbol(ts, named, wrapper)) {
147
- const argumentsList = type.aliasTypeArguments ?? (typeof checker.getTypeArguments === 'function' && hasAnyFlag(type.objectFlags, ts.ObjectFlags.Reference)
148
- ? checker.getTypeArguments(type) : type.typeArguments) ?? [];
149
- return argumentsList.length === 1 ? contractTypeStatusFromType(ts, checker, argumentsList[0], nextSeen, depth + 1) : 'unavailable';
150
- }
151
- for (const anonymous of ['Record', 'Partial', 'Pick', 'Omit', 'Required'])
152
- if (builtinSymbol(ts, named, anonymous))
153
- return 'inline';
154
- return null;
155
- }
156
- function objectContractTypeStatus(ts, checker, type, nextSeen, depth) {
157
- if (checker.isTupleType?.(type))
158
- return 'inline';
159
- if (checker.isArrayType?.(type)) {
160
- const argumentsList = checker.getTypeArguments?.(type) ?? [];
161
- return argumentsList.length === 1 ? contractTypeStatusFromType(ts, checker, argumentsList[0], nextSeen, depth + 1) : 'unavailable';
162
- }
163
- const declarations = type.symbol?.getDeclarations?.() ?? [];
164
- if (type.symbol?.getName().startsWith('__') === false && declarations.some((declaration) => ts.isInterfaceDeclaration(declaration)
165
- || ts.isClassDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration) || ts.isEnumDeclaration(declaration)))
166
- return 'named';
167
- return 'inline';
168
- }
169
- function contractTypeStatusFromType(ts, checker, type, seen = new Set(), depth = 0) {
170
- if (!type || depth > 12 || seen.has(type))
171
- return 'unavailable';
172
- if (hasAnyFlag(type.flags, ts.TypeFlags.Any | ts.TypeFlags.Unknown))
173
- return 'unavailable';
174
- const nextSeen = new Set(seen).add(type);
175
- const named = type.aliasSymbol ?? type.symbol ?? null;
176
- const wrapperStatus = wrappedTypeStatus(ts, checker, type, named, nextSeen, depth);
177
- if (wrapperStatus !== null)
178
- return wrapperStatus;
179
- if (type.aliasSymbol)
180
- return 'named';
181
- if ((type.symbol?.getDeclarations?.() ?? []).some((declaration) => ts.isEnumDeclaration(declaration)))
182
- return 'named';
183
- if (hasAnyFlag(type.flags, ts.TypeFlags.TypeParameter))
184
- return 'named';
185
- if (hasAnyFlag(type.flags, ts.TypeFlags.Boolean))
186
- return 'scalar';
187
- if (hasAnyFlag(type.flags, ts.TypeFlags.Union | ts.TypeFlags.Intersection))
188
- return 'inline';
189
- if (hasAnyFlag(type.flags, ts.TypeFlags.Object))
190
- return objectContractTypeStatus(ts, checker, type, nextSeen, depth);
191
- if (hasAnyFlag(type.flags, ts.TypeFlags.Conditional | ts.TypeFlags.IndexedAccess | ts.TypeFlags.Substitution))
192
- return 'unavailable';
193
- return 'scalar';
194
- }
195
- function callableSignatures(ts, symbol, checker, location) {
196
- const type = checker.getTypeOfSymbolAtLocation(symbol, location);
197
- const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call);
198
- const bodyless = signatures.filter((signature) => signature.getDeclaration() && !signature.getDeclaration().body);
199
- return bodyless.length ? bodyless : signatures.filter((signature) => signature.getDeclaration());
200
- }
201
- function signatureParameterStatus(ts, checker, signature, location, parameter, signatureIndex) {
202
- const parameterSymbol = signature.getParameters()[signatureIndex];
203
- const actual = parameterSymbol ? checker.getTypeOfSymbolAtLocation(parameterSymbol, location) : null;
204
- if (actual && parameter.questionToken && !ts.isUnionTypeNode(parameter.type) && hasAnyFlag(actual.flags, ts.TypeFlags.Union)) {
205
- const selected = actual.types.filter((type) => !hasAnyFlag(type.flags, ts.TypeFlags.Undefined));
206
- // An optional boolean is represented as true | false | undefined, not one Boolean member.
207
- if (selected.length > 0 && selected.every((type) => hasAnyFlag(type.flags, ts.TypeFlags.BooleanLike)))
208
- return 'scalar';
209
- return selected.length === 1 ? contractTypeStatusFromType(ts, checker, selected[0]) : 'inline';
210
- }
211
- return actual ? contractTypeStatusFromType(ts, checker, actual) : contractTypeStatus(ts, checker, parameter.type);
212
- }
213
- function checkSignatureInputs(state, declaration) {
214
- const { config, context, checker, signature, location, reportSource, reportNode, displayName, violations, reasons } = state;
215
- const ts = context.ts;
216
- let signatureIndex = 0;
217
- for (let index = 0; index < (declaration.parameters?.length ?? 0); index += 1) {
218
- const parameter = declaration.parameters[index];
219
- if (parameter.name && ts.isIdentifier(parameter.name) && parameter.name.text === 'this')
220
- continue;
221
- if (!parameter.type) {
222
- violations.push(violation(config, reportSource, reportNode ?? parameter, PUBLIC_CONTRACT_RULE_ID, `${displayName} must declare the type of each public input.`));
223
- signatureIndex += 1;
224
- continue;
225
- }
226
- const status = signatureParameterStatus(ts, checker, signature, location, parameter, signatureIndex);
227
- signatureIndex += 1;
228
- if (status === 'inline')
229
- violations.push(violation(config, reportSource, reportNode ?? parameter.type, PUBLIC_CONTRACT_RULE_ID, `${displayName} uses an inline object/union input; expose a named contract or a positional primitive.`));
230
- else if (status === 'unavailable')
231
- reasons.push(`${relativePath(config.root, reportSource.fileName)} cannot prove the public input type of ${displayName}`);
232
- }
233
- }
234
- function checkSignatureOutput(state, declaration) {
235
- const { config, context, checker, signature, reportSource, reportNode, displayName, violations, reasons } = state;
236
- const ts = context.ts;
237
- if (!declaration.type) {
238
- violations.push(violation(config, reportSource, reportNode ?? declaration, PUBLIC_CONTRACT_RULE_ID, `${displayName} must declare an explicit public output type.`));
239
- return;
240
- }
241
- const actual = checker.getReturnTypeOfSignature(signature);
242
- const status = actual ? contractTypeStatusFromType(ts, checker, actual) : contractTypeStatus(ts, checker, declaration.type);
243
- if (status === 'inline')
244
- violations.push(violation(config, reportSource, reportNode ?? declaration.type, PUBLIC_CONTRACT_RULE_ID, `${displayName} uses an inline object/union output; expose a named result contract or a primitive.`));
245
- else if (status === 'unavailable')
246
- reasons.push(`${relativePath(config.root, reportSource.fileName)} cannot prove the public output type of ${displayName}`);
247
- }
248
- function checkSignature(state) {
249
- const declaration = state.signature.getDeclaration();
250
- checkSignatureInputs(state, declaration);
251
- checkSignatureOutput(state, declaration);
252
- }
253
- function symbolName(symbol) {
254
- const name = symbol.getName?.() ?? '(anonymous)';
255
- return name === '__call' ? '(callable)' : name;
256
- }
257
- function isRepositoryDeclaration(declaration, localFiles) {
258
- return localFiles.has(canonical(declaration.getSourceFile().fileName));
259
- }
260
- const isPublicCallableDeclaration = (ts, declaration) => ts.isMethodDeclaration(declaration) || ts.isMethodSignature(declaration)
261
- || ts.isPropertyDeclaration(declaration) || ts.isPropertySignature(declaration) || ts.isGetAccessorDeclaration(declaration);
262
- function isCallableMember(ts, checker, member, location, localFiles) {
263
- if (member.getName() === 'prototype')
264
- return false;
265
- const selected = member.getDeclarations?.() ?? [];
266
- return Boolean(selected.some((declaration) => isPublicCallableDeclaration(ts, declaration)
267
- && isPublicMember(ts, declaration) && isRepositoryDeclaration(declaration, localFiles))
268
- && checker.getSignaturesOfType(checker.getTypeOfSymbolAtLocation(member, location), ts.SignatureKind.Call).length);
269
- }
270
- function callableMembers(ts, checker, symbol, location, localFiles) {
271
- const declarations = symbol.getDeclarations?.() ?? [];
272
- const classExpressions = declarations.flatMap((declaration) => ts.isVariableDeclaration(declaration)
273
- && declaration.initializer && ts.isClassExpression(unwrapExpression(ts, declaration.initializer))
274
- ? [unwrapExpression(ts, declaration.initializer)] : []);
275
- const valueType = checker.getTypeOfSymbolAtLocation(symbol, location);
276
- const declaredClassLike = declarations.some(declaration => ts.isClassDeclaration(declaration) || ts.isInterfaceDeclaration(declaration));
277
- const primary = declaredClassLike ? checker.getDeclaredTypeOfSymbol(symbol) : valueType;
278
- const types = [primary];
279
- if (declaredClassLike || classExpressions.length)
280
- types.push(valueType);
281
- for (const signature of checker.getSignaturesOfType(valueType, ts.SignatureKind.Construct))
282
- types.push(checker.getReturnTypeOfSignature(signature));
283
- const direct = checker.getSignaturesOfType(primary, ts.SignatureKind.Call).length ? [symbol] : [];
284
- const members = types.flatMap((type) => checker.getPropertiesOfType(type)).filter((member) => isCallableMember(ts, checker, member, location, localFiles));
285
- return [...new Set([...direct, ...members])];
286
- }
287
- function exportedSymbols(ts, checker, sourceFile) {
288
- const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
289
- return moduleSymbol ? checker.getExportsOfModule(moduleSymbol).map((symbol) => normalizedSymbolValue(ts, checker, symbol)).filter((symbol) => Boolean(symbol)) : [];
290
- }
291
- function checkCallableSymbol({ config, context, checker, symbol, location, reportSource, reportNode, violations, reasons, seen, localFiles }) {
292
- if (seen.has(symbol))
293
- return 0;
294
- seen.add(symbol);
295
- let checked = 0;
296
- for (const callable of callableMembers(context.ts, checker, symbol, location, localFiles)) {
297
- if (callable !== symbol && seen.has(callable))
298
- continue;
299
- seen.add(callable);
300
- const signatures = callableSignatures(context.ts, callable, checker, location);
301
- if (!signatures.length) {
302
- reasons.push(`${relativePath(config.root, reportSource.fileName)} cannot resolve the callable signature of ${symbolName(callable)}`);
303
- continue;
304
- }
305
- for (const signature of signatures) {
306
- checked += 1;
307
- checkSignature({ config, context, checker, signature, location, reportSource, reportNode,
308
- displayName: callable === symbol ? symbolName(symbol) : `${symbolName(symbol)}.${symbolName(callable)}`,
309
- violations, reasons });
310
- }
311
- }
312
- return checked;
313
- }
314
- function frameworkFor(state, checker) {
315
- if (!state.frameworkByChecker.has(checker)) {
316
- const selected = frameworkTargets(state.config, state.context, checker, state.localFiles);
317
- state.frameworkByChecker.set(checker, { ...selected, ts: state.ts, checker, targets: selected.bySymbol });
318
- state.readonlyReasons.push(...selected.reasons);
319
- }
320
- return state.frameworkByChecker.get(checker);
321
- }
322
- function checkOwnerCoverage(state) {
323
- const { config, context, publicReasons } = state;
324
- if (!config.owners?.length)
325
- publicReasons.push('no slot owner with an entry file exists, so capability API discovery has no owners to list');
326
- const ownerRoots = (config.owners ?? []).map((owner) => path.resolve(config.root, ...owner.root.split('/')));
327
- const publicSourceRoots = [...config.backend.features, ...config.backend.modules].map((root) => path.resolve(config.root, ...root.split('/')));
328
- for (const sourceFile of context.files)
329
- if (publicSourceRoots.some((root) => isInside(root, sourceFile.fileName))
330
- && !ownerRoots.some((root) => isInside(root, sourceFile.fileName))) {
331
- publicReasons.push(`${relativePath(config.root, sourceFile.fileName)} is outside every declared owner root`);
332
- }
333
- }
334
- function checkExportedSymbol(state, checker, framework, symbol) {
335
- const { context, localFiles, publicReasons, violations, publicSeen } = state;
336
- const declarations = (symbol.getDeclarations?.() ?? []).filter((declaration) => localFiles.has(canonical(declaration.getSourceFile().fileName))) ?? [];
337
- if (!declarations.length)
338
- return;
339
- const representative = declarations[0];
340
- if (isFrameworkHelper(representative.getSourceFile(), representative, framework))
341
- return;
342
- state.callableSignatures += checkCallableSymbol({ config: state.config, context, checker, symbol, location: representative,
343
- reportSource: representative.getSourceFile(), reportNode: representative.name ?? representative,
344
- violations, reasons: publicReasons, seen: publicSeen, localFiles });
345
- }
346
- function checkOwnerEntry(state, owner) {
347
- const { config, context, ts, sourceFiles, publicReasons } = state;
348
- const entry = sourceFiles.get(canonical(path.resolve(config.root, ...owner.entry.split('/'))));
349
- if (!entry) {
350
- publicReasons.push(`${owner.entry} is outside the checked production program`);
351
- return;
352
- }
353
- const checker = checkerFor(context, entry.fileName);
354
- const framework = frameworkFor(state, checker);
355
- if (entry.statements.some((statement) => ts.isExportAssignment(statement) && statement.isExportEquals)) {
356
- publicReasons.push(`${owner.entry} uses export =, so named capability API discovery is unavailable`);
357
- }
358
- for (const symbol of exportedSymbols(ts, checker, entry))
359
- checkExportedSymbol(state, checker, framework, symbol);
360
- }
361
- function checkPublicOwners(state) {
362
- for (const owner of state.config.owners ?? [])
363
- checkOwnerEntry(state, owner);
364
- }
365
- function classesInSource(ts, sourceFile) {
366
- const classes = [];
367
- const collect = (node) => {
368
- if (ts.isClassDeclaration(node) || ts.isClassExpression(node))
369
- classes.push(node);
370
- ts.forEachChild(node, collect);
371
- };
372
- collect(sourceFile);
373
- return classes;
374
- }
375
- function checkConstructedClassDecorators(state, sourceFile, checker, decorators, kinds, targets) {
376
- for (const [index, decorator] of decorators.entries())
377
- if (!kinds[index]) {
378
- const constructed = constructedDecoratorKind(state.ts, checker, decorator, targets);
379
- if (constructed && (NEST_CREATED.has(constructed) || MESSAGE_HANDLERS.has(constructed) || constructed.includes('framework'))) {
380
- state.readonlyReasons.push(`${relativePath(state.config.root, sourceFile.fileName)} has a constructed ${constructed} decorator identity`);
381
- }
382
- }
383
- }
384
- function checkConstructedMemberDecorator(state, sourceFile, checker, decorator, targets) {
385
- const { ts, config, readonlyReasons } = state;
386
- if (decoratorKind(ts, checker, decorator, targets))
387
- return;
388
- const constructed = constructedDecoratorKind(ts, checker, decorator, targets);
389
- if (constructed === 'Inject' || constructed === 'unproven framework') {
390
- readonlyReasons.push(`${relativePath(config.root, sourceFile.fileName)} has a constructed ${constructed} injection decorator identity`);
391
- }
392
- }
393
- function checkConstructedMemberDecorators(state, sourceFile, declaration, checker, targets) {
394
- const { ts } = state;
395
- for (const member of declaration.members)
396
- for (const decorated of [member, ...(ts.isConstructorDeclaration(member) ? member.parameters : [])]) {
397
- for (const decorator of nodeDecorators(ts, decorated))
398
- checkConstructedMemberDecorator(state, sourceFile, checker, decorator, targets);
399
- }
400
- }
401
- function hasInjectedMember(ts, checker, declaration, targets) {
402
- return declaration.members.some((member) => nodeDecorators(ts, member).some((decorator) => decoratorKind(ts, checker, decorator, targets) === 'Inject')
403
- || (ts.isConstructorDeclaration(member) && member.parameters.some((parameter) => nodeDecorators(ts, parameter)
404
- .some((decorator) => decoratorKind(ts, checker, decorator, targets) === 'Inject'))));
405
- }
406
- function checkMessageHandlers(state, checker, decorators, kinds) {
407
- for (const [index, decorator] of decorators.entries()) {
408
- const kind = kinds[index];
409
- if (!kind || !MESSAGE_HANDLERS.has(kind))
410
- continue;
411
- const message = messageClass(state.config, state.context, checker, decorator, state.localFiles, state.readonlyReasons);
412
- if (!message)
413
- continue;
414
- const key = `${message.getSourceFile().fileName}:${message.pos}`;
415
- if (state.messageSeen.has(key))
416
- continue;
417
- state.messageSeen.add(key);
418
- state.messages += 1;
419
- checkMessageReadonly(state.config, state.context, checkerFor(state.context, message.getSourceFile().fileName), message, state.localFiles, state.violations, state.readonlyReasons);
420
- }
421
- }
422
- function checkUseCase(state, role, sourceFile, checker, declaration) {
423
- const { ts, config, context, publicReasons, publicSeen, localFiles, violations } = state;
424
- if (!(role.role === 'use-case' && !role.transport && ts.isClassDeclaration(declaration) && declaration.name))
425
- return;
426
- const exported = exportedSymbols(ts, checker, sourceFile).some((symbol) => (symbol.getDeclarations?.() ?? []).includes(declaration));
427
- if (!exported)
428
- return;
429
- const classSymbol = normalizedSymbol(ts, checker, declaration.name);
430
- const instanceType = classSymbol ? checker.getDeclaredTypeOfSymbol(classSymbol) : null;
431
- const execute = instanceType ? checker.getPropertyOfType(instanceType, 'execute') : null;
432
- if (!execute)
433
- publicReasons.push(`${relativePath(config.root, sourceFile.fileName)} exports a use-case class without a statically resolved execute contract`);
434
- else
435
- state.callableSignatures += checkCallableSymbol({ config, context, checker, symbol: execute, location: declaration,
436
- reportSource: sourceFile, reportNode: declaration.name, violations, reasons: publicReasons, seen: publicSeen, localFiles });
437
- }
438
- function checkClassContracts(state, sourceFile, checker, role, declaration, framework) {
439
- const { ts, config, context, violations, readonlyReasons, localFiles } = state;
440
- const decorators = nodeDecorators(ts, declaration);
441
- const kinds = decorators.map((decorator) => decoratorKind(ts, checker, decorator, framework.targets));
442
- const directKinds = kinds.filter((kind) => Boolean(kind));
443
- checkConstructedClassDecorators(state, sourceFile, checker, decorators, kinds, framework.targets);
444
- const classKind = directKinds.find((kind) => NEST_CREATED.has(kind)) ?? null;
445
- const targets = framework.targets;
446
- checkConstructedMemberDecorators(state, sourceFile, declaration, checker, targets);
447
- if (classKind || hasInjectedMember(ts, checker, declaration, targets)) {
448
- state.injectedClasses += 1;
449
- checkInjectedClass({ config, context, checker, declaration, classKind, targets, decoratorKind,
450
- localFiles, violations, reasons: readonlyReasons });
451
- }
452
- checkMessageHandlers(state, checker, decorators, kinds);
453
- checkUseCase(state, role, sourceFile, checker, declaration);
454
- }
455
- function checkSourceFile(state, sourceFile) {
456
- const checker = checkerFor(state.context, sourceFile.fileName);
457
- const framework = frameworkFor(state, checker);
458
- const role = sourceRole(sourceFile);
459
- for (const declaration of classesInSource(state.ts, sourceFile))
460
- checkClassContracts(state, sourceFile, checker, role, declaration, framework);
461
- }
462
- function contractCoverage(state) {
463
- const publicDetails = [...new Set(state.publicReasons)].sort(byCodeUnit);
464
- const readonlyDetails = [...new Set(state.readonlyReasons)].sort(byCodeUnit);
465
- return {
466
- violations: state.violations,
467
- coverage: {
468
- publicContracts: publicDetails.length ? { status: 'unavailable', callableSignatures: state.callableSignatures, details: publicDetails }
469
- : { status: 'checked', callableSignatures: state.callableSignatures },
470
- readonlyBoundaries: readonlyDetails.length ? { status: 'unavailable', injectedClasses: state.injectedClasses, messages: state.messages, details: readonlyDetails }
471
- : { status: 'checked', injectedClasses: state.injectedClasses, messages: state.messages },
472
- },
473
- };
474
- }
475
- /** Enforce mechanically selected public contract and readonly boundaries without treating DTOs or arbitrary interfaces as APIs. */
476
- export function checkBackendContracts(config, context) {
477
- const state = {
478
- config, context, ts: context.ts,
479
- localFiles: new Set(context.files.map((file) => canonical(file.fileName))),
480
- sourceFiles: new Map(context.files.map((file) => [canonical(file.fileName), file])),
481
- frameworkByChecker: new Map(), violations: [], publicReasons: [], readonlyReasons: [],
482
- publicSeen: new Set(), messageSeen: new Set(), callableSignatures: 0, injectedClasses: 0, messages: 0,
483
- };
484
- checkOwnerCoverage(state);
485
- checkPublicOwners(state);
486
- for (const sourceFile of context.files)
487
- checkSourceFile(state, sourceFile);
488
- return contractCoverage(state);
489
- }
@@ -1,81 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import path from 'node:path';
3
- /**
4
- * R21 `cross-app-duplicate` (FE_CROSS_APP_DUPLICATE): the slot manifest's `crossApp` law says apps never import each other and
5
- * shared code is a `packages/<pkg>` slot. `HFS_DUPLICATE_CODE` sees blocks of a size inside the owner graph; this sees whole
6
- * files of any size, route-tree files included: two TypeScript files under different apps whose token-normalised content is
7
- * equal (comments and whitespace do not exist in the token sequence; identifiers and literals are kept) are one file copied
8
- * instead of moved to a package.
9
- *
10
- * Exempt: a file made only of import and export statements. It is the sanctioned shape of a Next route file that must exist
11
- * per app and re-exports one package symbol (`export { default } from "@family/ui/global-error"`), and it holds nothing to move.
12
- * Not source, so not judged: declaration files and everything that is not .ts/.tsx (JSON catalogs, CSS).
13
- */
14
- export const CROSS_APP_DUPLICATE_RULE_IDS = ['FE_CROSS_APP_DUPLICATE'];
15
- const RULE = 'FE_CROSS_APP_DUPLICATE';
16
- const SOURCE = /\.[cm]?tsx?$/u;
17
- /** The app a file belongs to: the slot binding when a slot owns it, else the declared app whose directory holds it. */
18
- const appOf = (resolver, declaredApps, rel) => resolver.classifyPath(rel).bindings?.app ?? declaredApps.find(name => rel.startsWith(`apps/${name}/`)) ?? null;
19
- const onlyModuleEdges = (ts, file) => file.sourceFile.statements.every(statement => ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)
20
- || (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)));
21
- const leafText = (SyntaxKind, node, sourceFile) => (node.kind === SyntaxKind.JsxText ? node.getText(sourceFile).replace(/\s+/gu, ' ').trim() : node.getText(sourceFile));
22
- function collectTokens(SyntaxKind, sourceFile, node, parts) {
23
- if (node.kind >= SyntaxKind.FirstJSDocNode && node.kind <= SyntaxKind.LastJSDocNode)
24
- return;
25
- if (node.kind === SyntaxKind.JsxText && node.containsOnlyTriviaWhiteSpaces)
26
- return;
27
- const children = node.getChildren(sourceFile);
28
- if (!children.length) {
29
- if (node.kind !== SyntaxKind.EndOfFileToken)
30
- parts.push(leafText(SyntaxKind, node, sourceFile));
31
- return;
32
- }
33
- for (const child of children)
34
- collectTokens(SyntaxKind, sourceFile, child, parts);
35
- }
36
- const tokenText = (SyntaxKind, sourceFile) => {
37
- const parts = [];
38
- collectTokens(SyntaxKind, sourceFile, sourceFile, parts);
39
- return parts.join('\u0000');
40
- };
41
- /** Groups the comparable files by the hash of their token text; returns the groups and the number of files compared. */
42
- function groupByContent(graph, ts, declaredApps) {
43
- const groups = new Map();
44
- let files = 0;
45
- for (const file of graph.files.values()) {
46
- if (!SOURCE.test(file.rel) || /\.d\.[cm]?tsx?$/u.test(file.rel))
47
- continue;
48
- const app = appOf(graph.resolver, declaredApps, file.rel);
49
- if (!app || onlyModuleEdges(ts, file) || !file.sourceFile.statements.length)
50
- continue;
51
- files += 1;
52
- const key = createHash('sha256').update(tokenText(ts.SyntaxKind, file.sourceFile)).digest('hex');
53
- if (!groups.has(key))
54
- groups.set(key, []);
55
- groups.get(key)?.push({ rel: file.rel, app });
56
- }
57
- return { groups, files };
58
- }
59
- const duplicateViolation = (group, item) => {
60
- const twins = group.filter(other => other.app !== item.app).map(other => other.rel);
61
- return {
62
- ruleId: RULE, path: item.rel, line: 1, column: 1, twins,
63
- message: `${item.rel} is token-for-token the same file as ${twins.join(', ')} in another app (comments and whitespace ignored); shared code is a packages/<pkg> slot. Move it to a package (packages/<pkg>) and let each app re-export it (${path.posix.basename(item.rel)} keeps only an import or export statement).`,
64
- };
65
- };
66
- export function checkCrossAppDuplicate({ graph, context }) {
67
- const ts = context.ts;
68
- const declaredApps = graph.resolver.repo.apps.map((app) => app.name);
69
- const { groups, files } = groupByContent(graph, ts, declaredApps);
70
- const violations = [];
71
- let duplicated = 0;
72
- for (const group of groups.values()) {
73
- if (new Set(group.map(item => item.app)).size < 2)
74
- continue;
75
- duplicated += 1;
76
- group.sort((a, b) => a.rel.localeCompare(b.rel));
77
- for (const item of group)
78
- violations.push(duplicateViolation(group, item));
79
- }
80
- return { violations, coverage: { status: 'checked', files, duplicatedGroups: duplicated } };
81
- }