repometry 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +35 -17
  2. package/package.json +1 -1
  3. package/target/main/resources/report/json/comparison-v1.schema.json +6 -6
  4. package/target/main/resources/report/json/file-metrics-v1.schema.json +7 -6
  5. package/target/main/resources/report/json/pull-review-v1.schema.json +5 -5
  6. package/target/main/resources/report/json/report-v2.schema.json +197 -10
  7. package/target/main/resources/report/json/repository-summary-v1.schema.json +161 -14
  8. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +518 -6
  9. package/target/main/resources/viewer/styles.css +5 -0
  10. package/target/main/ts/api/git/changes.d.ts +1 -1
  11. package/target/main/ts/api/git/changes.js +3 -3
  12. package/target/main/ts/api/git/commit-metadata.js +6 -4
  13. package/target/main/ts/api/git/git.d.ts +1 -1
  14. package/target/main/ts/api/git/git.js +4 -4
  15. package/target/main/ts/api/git/inspection-source.d.ts +1 -1
  16. package/target/main/ts/api/git/inspection-source.js +3 -3
  17. package/target/main/ts/api/git/local.d.ts +1 -1
  18. package/target/main/ts/api/git/local.js +4 -4
  19. package/target/main/ts/api/worker/remote-executor.d.ts +1 -1
  20. package/target/main/ts/api/worker/remote-executor.js +2 -2
  21. package/target/main/ts/api/worker/worker-protocol.d.ts +2 -2
  22. package/target/main/ts/api/worker/worker-protocol.js +8 -8
  23. package/target/main/ts/api/worker/worker.d.ts +1 -1
  24. package/target/main/ts/api/worker/worker.js +4 -4
  25. package/target/main/ts/cli/main.js +4 -3
  26. package/target/main/ts/cli/reporting.d.ts +1 -1
  27. package/target/main/ts/cli/reporting.js +1 -1
  28. package/target/main/ts/compose/analysis-files.d.ts +13 -0
  29. package/target/main/ts/compose/analysis-files.js +95 -0
  30. package/target/main/ts/compose/analysis-imports.d.ts +7 -0
  31. package/target/main/ts/compose/analysis-imports.js +34 -0
  32. package/target/main/ts/compose/analysis-report.d.ts +5 -0
  33. package/target/main/ts/compose/analysis-report.js +78 -0
  34. package/target/main/ts/compose/analysis-repository.d.ts +6 -0
  35. package/target/main/ts/compose/analysis-repository.js +61 -0
  36. package/target/main/ts/compose/analysis-results.d.ts +38 -0
  37. package/target/main/ts/compose/analysis-results.js +78 -0
  38. package/target/main/ts/compose/analysis-sources.d.ts +73 -0
  39. package/target/main/ts/compose/analysis-sources.js +47 -0
  40. package/target/main/ts/compose/analyze-snapshot.d.ts +2 -2
  41. package/target/main/ts/compose/analyze-snapshot.js +19 -250
  42. package/target/main/ts/compose/diff-coverage.d.ts +2 -0
  43. package/target/main/ts/compose/diff-coverage.js +6 -4
  44. package/target/main/ts/compose/inspect.js +8 -5
  45. package/target/main/ts/compose/languages.d.ts +29 -0
  46. package/target/main/ts/compose/languages.js +87 -0
  47. package/target/main/ts/compose/sources.js +14 -12
  48. package/target/main/ts/core/engine/manifest.d.ts +2 -2
  49. package/target/main/ts/core/engine/manifest.js +25 -5
  50. package/target/main/ts/core/engine/plan.d.ts +2 -4
  51. package/target/main/ts/core/engine/plan.js +13 -15
  52. package/target/main/ts/core/engine/plugin.d.ts +2 -1
  53. package/target/main/ts/core/model/clone-source.d.ts +1 -0
  54. package/target/main/ts/core/model/clone-source.js +1 -0
  55. package/target/main/ts/core/model/code-structure.d.ts +2 -0
  56. package/target/main/ts/core/model/code-structure.js +6 -0
  57. package/target/main/ts/core/model/language.d.ts +10 -0
  58. package/target/main/ts/core/model/language.js +6 -0
  59. package/target/main/ts/core/model/measurement.d.ts +7 -6
  60. package/target/main/ts/core/model/measurement.js +17 -6
  61. package/target/main/ts/core/model/plugin-data.d.ts +3 -0
  62. package/target/main/ts/core/model/quality-summary.js +5 -4
  63. package/target/main/ts/core/model/report.d.ts +1 -2
  64. package/target/main/ts/core/model/report.js +0 -1
  65. package/target/main/ts/core/model/snapshot.d.ts +0 -2
  66. package/target/main/ts/core/model/snapshot.js +0 -6
  67. package/target/main/ts/core/usecases/compare.js +61 -17
  68. package/target/main/ts/core/usecases/inspect.js +2 -2
  69. package/target/main/ts/plugin.d.ts +3 -2
  70. package/target/main/ts/plugin.js +1 -1
  71. package/target/main/ts/plugins/duplication/duplication.js +10 -4
  72. package/target/main/ts/plugins/language-js/babel-provider.js +8 -2
  73. package/target/main/ts/plugins/language-js/extensions.d.ts +3 -0
  74. package/target/main/ts/plugins/language-js/extensions.js +4 -0
  75. package/target/main/ts/plugins/language-js/js-security.js +3 -2
  76. package/target/main/ts/report/html/app/viewer-data.d.ts +1 -1
  77. package/target/main/ts/report/html/app/viewer-data.js +2 -29
  78. package/target/main/ts/report/html/app/viewer-metric-registry.js +7 -7
  79. package/target/main/ts/report/html/app/viewer-overview-cards.js +8 -2
  80. package/target/main/ts/report/html/app/viewer-route.d.ts +2 -2
  81. package/target/main/ts/report/html/app/viewer-route.js +3 -3
  82. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +6 -1
  83. package/target/main/ts/report/html/app/viewer-trend-data.js +6 -2
  84. package/target/main/ts/report/html/app/viewer.js +3 -3
  85. package/target/main/ts/report/html/site/export-site.d.ts +3 -4
  86. package/target/main/ts/report/html/site/export-site.js +24 -41
  87. package/target/main/ts/report/html/site/exported-server.js +2 -1
  88. package/target/main/ts/report/html/site/local-server.d.ts +1 -1
  89. package/target/main/ts/report/html/site/local-server.js +13 -19
  90. package/target/main/ts/report/html/site/projects.js +8 -17
  91. package/target/main/ts/report/json/projections/commit-summary.d.ts +2 -2
  92. package/target/main/ts/report/json/projections/commit-summary.js +18 -19
  93. package/target/main/ts/report/json/projections/file-metrics.js +31 -24
  94. package/target/main/ts/report/json/projections/inspection-context.js +10 -1
  95. package/target/main/ts/report/json/projections/inspection-details.d.ts +1 -1
  96. package/target/main/ts/report/json/projections/inspection-details.js +2 -2
  97. package/target/main/ts/report/json/projections/metric-values.d.ts +1 -0
  98. package/target/main/ts/report/json/projections/metric-values.js +15 -5
  99. package/target/main/ts/report/json/store/pull-review-store.js +1 -2
  100. package/target/main/ts/report/json/validation/report.d.ts +1 -1
  101. package/target/main/ts/report/json/validation/report.js +10 -8
  102. package/target/main/ts/report/json/validation/summary-validation.js +1 -3
  103. package/target/main/ts/report/json/wire/file-metrics-model.d.ts +2 -0
  104. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +0 -5
  105. package/target/main/ts/report/json/wire/public-history-model.d.ts +0 -6
  106. package/target/main/ts/report/json/wire/public-history-model.js +0 -1
  107. package/target/main/ts/report.d.ts +2 -3
  108. package/target/main/ts/report.js +1 -2
  109. package/target/main/resources/report/json/inspection-context-v1.schema.json +0 -172
  110. package/target/main/resources/report/json/public-history-v1.schema.json +0 -50
  111. package/target/main/resources/report/json/quality-history-v1.schema.json +0 -51
  112. package/target/main/resources/report/json/report-v1.schema.json +0 -65
  113. package/target/main/resources/report/json/viewer-details-v1.schema.json +0 -346
  114. package/target/main/ts/report/json/projections/public-history.d.ts +0 -4
  115. package/target/main/ts/report/json/projections/public-history.js +0 -17
@@ -0,0 +1,78 @@
1
+ import { ReportProducts } from '../core/engine/report-products.js';
2
+ import { inspectionKeys } from './analysis-sources.js';
3
+ export class AnalysisResults {
4
+ measurements = [];
5
+ findings = [];
6
+ diagnostics;
7
+ parsed = new Set();
8
+ inspected = new Set();
9
+ completedInspection = false;
10
+ products;
11
+ scanned = new Set();
12
+ scanOnly;
13
+ securityOperations;
14
+ usedPlans = new Map();
15
+ constructor(plugins, claimed, oversized) {
16
+ this.products = new ReportProducts(plugins);
17
+ this.diagnostics = oversized.map(oversizedClaim);
18
+ this.scanOnly = new Set(plugins.filter(plugin => plugin.claims?.scanOnly).flatMap(({ id, operations }) => operations.map(operation => `${id}/${operation.id}`)));
19
+ this.securityOperations = new Map(claimed.filter(plugin => plugin.kinds.includes('security')).flatMap(plugin => inspectionKeys(plugin).map(key => [key, plugin.id])));
20
+ }
21
+ remember(task, syntaxProvider) {
22
+ this.usedPlans.set(JSON.stringify([task.key, [...task.inputs], syntaxProvider]), operationProvenance(task, syntaxProvider));
23
+ }
24
+ operationRecords() {
25
+ return [...this.usedPlans.values()];
26
+ }
27
+ pluginData() {
28
+ return this.products.result();
29
+ }
30
+ securityScanners(plugins) {
31
+ return plugins.filter(plugin => this.scanned.has(plugin.id)).map(({ id, version }) => ({ name: id, version }));
32
+ }
33
+ record(task, outcome, path, paths) {
34
+ if (outcome.state !== 'completed') {
35
+ this.diagnostics.push({ operation: task.key, state: outcome.state, message: outcome.reason,
36
+ ...(path === undefined ? {} : { path }) });
37
+ return;
38
+ }
39
+ try {
40
+ const stored = this.products.record(task, outcome.product, path);
41
+ this.recordInspection(task, outcome.diagnostics ?? [], path, paths);
42
+ if (stored) {
43
+ this.measurements.push(...stored.measurements);
44
+ this.findings.push(...stored.findings);
45
+ }
46
+ }
47
+ catch (error) {
48
+ this.diagnostics.push({ operation: task.key, state: 'failed', path, message: error instanceof Error ? error.message : String(error) });
49
+ }
50
+ }
51
+ recordInspection(task, messages, path, paths) {
52
+ for (const message of messages)
53
+ this.diagnostics.push({ operation: task.key, state: 'partial', message,
54
+ ...(path === undefined ? {} : { path }) });
55
+ const scanner = this.securityOperations.get(task.key);
56
+ if (scanner)
57
+ this.scanned.add(scanner);
58
+ if (task.operation.role !== 'inspection' || (path === undefined && !paths?.length))
59
+ return;
60
+ this.completedInspection = true;
61
+ if (this.scanOnly.has(task.key))
62
+ return;
63
+ if (path !== undefined)
64
+ this.inspected.add(path);
65
+ else
66
+ for (const file of paths ?? [])
67
+ this.inspected.add(file);
68
+ }
69
+ }
70
+ export function operationProvenance(task, syntaxProvider) {
71
+ return { key: task.key, inputs: Object.fromEntries(task.inputs),
72
+ ...(task.operation.scope === 'repository' ? { scope: task.operation.scope } : {}),
73
+ ...(syntaxProvider === undefined ? {} : { syntaxProvider }) };
74
+ }
75
+ export function oversizedClaim(path) {
76
+ return { operation: 'source/claims', state: 'partial', path, message: 'Plugin inspection skipped a file larger than 1 MiB' };
77
+ }
78
+ //# sourceMappingURL=analysis-results.js.map
@@ -0,0 +1,73 @@
1
+ import type { Operation, Plugin } from '../core/engine/plugin.js';
2
+ import type { SourceFile, SourceSnapshot } from '../core/model/source.js';
3
+ import type { LanguageProvider } from './languages.js';
4
+ export declare const structuralInspections: {
5
+ id: string;
6
+ version: string;
7
+ api: string;
8
+ operations: readonly Operation[];
9
+ rules?: readonly import("../core/engine/plugin.js").RuleDescriptor[];
10
+ config?: import("../core/engine/plugin.js").PluginConfigSchema;
11
+ settings?: import("../core/model/plugin-data.js").JsonValue;
12
+ kinds: readonly import("../core/engine/plugin.js").PluginKind[];
13
+ claims?: import("../core/engine/plugin.js").FileClaims;
14
+ providesLanguages?: readonly import("../plugin.js").ProvidedLanguage[];
15
+ produces: readonly import("../core/engine/plugin.js").ProductDeclaration[];
16
+ tools: {
17
+ '@babel/types': string;
18
+ };
19
+ }[];
20
+ export declare const defaultProvider: LanguageProvider;
21
+ export interface SelectedSource {
22
+ readonly file: SourceFile;
23
+ readonly provider: LanguageProvider | undefined;
24
+ }
25
+ export interface ClaimedPlugin {
26
+ readonly plugin: Plugin;
27
+ readonly matches: (path: string) => boolean;
28
+ }
29
+ export declare function inspectionFileMatcher(additional: readonly Plugin[], languages?: {
30
+ select(path: string): LanguageProvider | undefined;
31
+ isSource(path: string): boolean;
32
+ id(path: string): string;
33
+ readonly extensions: readonly string[];
34
+ readonly globs: readonly string[];
35
+ readonly catalog: readonly import("../plugin.js").LanguageDisplay[];
36
+ readonly providers: readonly LanguageProvider[];
37
+ }): (path: string) => boolean;
38
+ export declare function selectAnalysisSources(snapshot: SourceSnapshot, additional: readonly Plugin[], withCoverage: boolean): {
39
+ languages: {
40
+ select(path: string): LanguageProvider | undefined;
41
+ isSource(path: string): boolean;
42
+ id(path: string): string;
43
+ readonly extensions: readonly string[];
44
+ readonly globs: readonly string[];
45
+ readonly catalog: readonly import("../plugin.js").LanguageDisplay[];
46
+ readonly providers: readonly LanguageProvider[];
47
+ };
48
+ sources: SelectedSource[];
49
+ sourceFiles: SourceFile[];
50
+ providersByPath: Map<string, LanguageProvider>;
51
+ plugins: (Plugin | {
52
+ id: string;
53
+ version: string;
54
+ api: string;
55
+ operations: readonly Operation[];
56
+ rules?: readonly import("../core/engine/plugin.js").RuleDescriptor[];
57
+ config?: import("../core/engine/plugin.js").PluginConfigSchema;
58
+ settings?: import("../core/model/plugin-data.js").JsonValue;
59
+ kinds: readonly import("../core/engine/plugin.js").PluginKind[];
60
+ claims?: import("../core/engine/plugin.js").FileClaims;
61
+ providesLanguages?: readonly import("../plugin.js").ProvidedLanguage[];
62
+ produces: readonly import("../core/engine/plugin.js").ProductDeclaration[];
63
+ tools: {
64
+ '@babel/types': string;
65
+ };
66
+ })[];
67
+ claimedPlugins: Plugin[];
68
+ perFile: ClaimedPlugin[];
69
+ repository: ClaimedPlugin[];
70
+ };
71
+ export type AnalysisSources = ReturnType<typeof selectAnalysisSources>;
72
+ export declare function pluginForScope(plugin: Plugin, scope: NonNullable<Operation['scope']>): Plugin;
73
+ export declare function inspectionKeys(plugin: Plugin): string[];
@@ -0,0 +1,47 @@
1
+ import { plan } from '../core/engine/plan.js';
2
+ import { coverage } from '../plugins/coverage/coverage.js';
3
+ import { duplication } from '../plugins/duplication/duplication.js';
4
+ import { babelProvider, babelTypes } from '../plugins/language-js/babel-provider.js';
5
+ import { maintainability } from '../plugins/maintainability/maintainability.js';
6
+ import { structure } from '../plugins/structure/structure.js';
7
+ import { claimMatcher, defaultLanguages, languageRegistry } from './languages.js';
8
+ import { securityPlugins } from './security-plugins.js';
9
+ export const structuralInspections = [{ ...structure, tools: babelTypes }, { ...maintainability, tools: babelTypes }];
10
+ export const defaultProvider = defaultLanguages.providers[0];
11
+ export function inspectionFileMatcher(additional, languages = defaultLanguages) {
12
+ const matches = [...securityPlugins, ...additional].filter(plugin => !plugin.kinds.includes('language'))
13
+ .map(plugin => claimMatcher(plugin.claims, languages.id));
14
+ return path => matches.some(match => match(path));
15
+ }
16
+ export function selectAnalysisSources(snapshot, additional, withCoverage) {
17
+ const languages = additional.length ? languageRegistry(additional) : defaultLanguages;
18
+ const sources = snapshot.files.map(file => ({ file, provider: languages.select(file.path) }));
19
+ const providersByPath = new Map(sources.flatMap(({ file, provider }) => provider ? [[file.path, provider]] : []));
20
+ const sourceFiles = sources.flatMap(({ file, provider }) => provider ? [file] : []);
21
+ const claimedPlugins = [...securityPlugins.filter(plugin => !additional.includes(plugin)), ...additional];
22
+ const plugins = [babelProvider, ...structuralInspections, duplication, ...(withCoverage ? [coverage] : []), ...claimedPlugins];
23
+ validateRegistration(plugins, additional, withCoverage);
24
+ const claims = claimedPlugins.map(plugin => ({ plugin, matches: plugin.kinds.includes('language')
25
+ ? path => providersByPath.get(path)?.plugin.id === plugin.id : claimMatcher(plugin.claims, languages.id) }));
26
+ return { languages, sources, sourceFiles, providersByPath, plugins, claimedPlugins,
27
+ perFile: claimsForScope(claims, 'file'), repository: claimsForScope(claims, 'repository') };
28
+ }
29
+ function validateRegistration(plugins, additional, withCoverage) {
30
+ if (additional.length)
31
+ plan({ plugins, select: [], inputs: new Map() });
32
+ if (!withCoverage && additional.some(plugin => plugin.id === coverage.id)) {
33
+ throw new Error('An additional plugin uses a built-in plugin ID');
34
+ }
35
+ }
36
+ function claimsForScope(claims, scope) {
37
+ return claims.map(({ plugin, matches }) => ({ plugin: pluginForScope(plugin, scope), matches }))
38
+ .filter(({ plugin }) => plugin.operations.length > 0);
39
+ }
40
+ export function pluginForScope(plugin, scope) {
41
+ const operations = plugin.operations.filter(operation => (operation.scope ?? 'file') === scope);
42
+ return operations.length === plugin.operations.length ? plugin : { ...plugin, operations };
43
+ }
44
+ export function inspectionKeys(plugin) {
45
+ return plugin.operations.filter(operation => operation.role === 'inspection').map(operation => `${plugin.id}/${operation.id}`);
46
+ }
47
+ //# sourceMappingURL=analysis-sources.js.map
@@ -2,5 +2,5 @@ import type { OperationCacheOptions } from '../core/engine/operation-cache.js';
2
2
  import type { Plugin } from '../core/engine/plugin.js';
3
3
  import type { Report } from '../core/model/report.js';
4
4
  import type { AnalysisInput } from '../core/usecases/inspect.js';
5
- export declare function inspectionFileMatcher(additional: readonly Plugin[]): (path: string) => boolean;
6
- export declare function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths, coverage: inputCoverage }: AnalysisInput, additional?: readonly Plugin[], cache?: OperationCacheOptions): Promise<Report>;
5
+ export { inspectionFileMatcher } from './analysis-sources.js';
6
+ export declare function analyzeSnapshot(input: AnalysisInput, additional?: readonly Plugin[], cache?: OperationCacheOptions): Promise<Report>;
@@ -1,252 +1,21 @@
1
- import { extname } from 'node:path';
2
- import { execute } from '../core/engine/execute.js';
3
- import { plan } from '../core/engine/plan.js';
4
- import { ReportProducts } from '../core/engine/report-products.js';
5
- import { codeStructure } from '../core/model/code-structure.js';
6
- import { definitions } from '../core/model/measurement.js';
7
- import { debtModel } from '../core/model/quality-summary.js';
8
- import { reportSchema } from '../core/model/report.js';
9
- import { comparePaths, digest, isSourcePath, sourceDirectoriesExcluded, sourceExtensions, sourceFile, sourceFiles as sourceFileSet, sourceLineCounts, textLineCount } from '../core/model/snapshot.js';
10
- import { isClaimedText, maxClaimedFileBytes } from '../core/model/source.js';
11
- import { defaultSourceExclusions, exclusionMatcher, generatedSourcePolicy, sourceExclusionMatcher } from '../core/profile/exclusions.js';
12
- import { duplicationSettings, structuralRules } from '../core/profile/maintainability.js';
13
- import { coverage, coverageResult, lcovInput } from '../plugins/coverage/coverage.js';
14
- import { duplication, duplicationInput } from '../plugins/duplication/duplication.js';
15
- import { babelProvider, babelTypes, parserDefaults } from '../plugins/language-js/babel-provider.js';
16
- import { fileQuality, maintainability } from '../plugins/maintainability/maintainability.js';
17
- import { structure } from '../plugins/structure/structure.js';
18
- import { securityPlugins } from './security-plugins.js';
19
- const sourcePlugins = [babelProvider, { ...structure, tools: babelTypes }, { ...maintainability, tools: babelTypes }];
20
- const selected = ['structure/size', 'structure/complexity', 'maintainability/file'];
21
- const bindings = new Map(selected.map(operation => [operation, { syntax: { operation: 'babel-syntax/parse' } }]));
22
- const sourcePlan = plan({ plugins: sourcePlugins, select: selected, inputs: new Map([['file', sourceFile.id]]), bindings });
23
- const duplicationPlan = plan({ plugins: [duplication], select: ['duplication/detect'], inputs: new Map([['sources', duplicationInput.id]]) });
24
- const coveragePlan = plan({ plugins: [coverage], select: ['lcov/import', 'lcov/lines'], inputs: new Map([['lcov', lcovInput.id]]) });
25
- const securityClaims = securityPlugins.map(plugin => claimMatcher(plugin.claims));
26
- export function inspectionFileMatcher(additional) {
27
- const matches = [...securityClaims, ...additional.map(plugin => claimMatcher(plugin.claims))];
28
- return path => matches.some(match => match(path));
29
- }
30
- const measurementDefinitions = {
31
- [definitions.lines]: 'Physical lines including blank lines and comments. A final line terminator does not add a line.',
32
- [definitions.functions]: 'Babel function nodes with bodies, including nested functions and methods.',
33
- [definitions.complexity]: 'One plus branches in the function body: if, ternary, loops, catch, non-default switch cases and logical operators. Nested functions are measured separately. Line and column are 1-based and columns count UTF-16 units.',
34
- [definitions.coverage]: 'Distinct covered code lines divided by the distinct code lines listed in LCOV DA records. Hit counts are summed across records. A zero denominator has no ratio.',
35
- [definitions.codeLines]: 'Nonblank physical lines after removing Babel comment spans and the interpreter directive. A line containing both code and a comment counts as code.',
36
- [definitions.comments]: 'Physical lines containing only a Babel comment or interpreter directive.',
37
- [definitions.classes]: 'Babel class declaration and expression nodes.',
38
- [definitions.cognitiveComplexity]: 'Flow breaks plus nesting weight and logical operator sequences. Nested functions are measured separately. File complexity sums functions and module-level flow breaks.',
39
- [definitions.duplicatedLines]: 'Distinct code lines inside repeated Babel syntax subtrees, including original and repeated occurrences. Identifier and literal spellings are ignored for similar-code matches.',
40
- };
41
- export async function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths = [], coverage: inputCoverage }, additional = [], cache) {
42
- const rows = [];
43
- const diagnostics = (snapshot.oversizedClaims ?? []).map(oversizedClaim);
44
- const findings = [];
45
- const cloneSources = [];
46
- const functionBodies = new Map();
47
- const sourceFiles = snapshot.files.filter(file => isSourcePath(file.path));
48
- const claimedPlugins = [...securityPlugins.filter(plugin => !additional.includes(plugin)), ...additional];
49
- const enabled = [...sourcePlugins, duplication, ...(inputCoverage === undefined ? [] : [coverage])];
50
- const plugins = [...enabled, ...claimedPlugins];
51
- if (additional.length)
52
- plan({ plugins, select: [], inputs: new Map() });
53
- if (inputCoverage === undefined && additional.some(plugin => plugin.id === coverage.id))
54
- throw new Error('An additional plugin uses a built-in plugin ID');
55
- const reportProducts = new ReportProducts(plugins);
56
- const sourcePlans = new Map([['[true]', sourcePlan]]);
57
- const usedPlans = new Map(sourcePlan.map(task => [operationBindingKey(task), task]));
58
- const matches = claimedPlugins.map(plugin => claimMatcher(plugin.claims));
59
- const repositoryPlugins = claimedPlugins.flatMap((plugin, index) => {
60
- if (!plugin.operations.some(operation => operation.scope === 'repository'))
61
- return [];
62
- return [{ plugin: pluginForScope(plugin, 'repository'), matches: matches[index] }];
63
- });
64
- const filePlugins = repositoryPlugins.length ? claimedPlugins.map(plugin => pluginForScope(plugin, 'file')) : claimedPlugins;
65
- const parsed = new Set();
66
- const inspected = new Set();
67
- const scanned = new Set();
68
- let completedInspection = false;
69
- const scanOnlyOperations = new Set(plugins.filter(plugin => plugin.claims?.scanOnly).flatMap(({ id, operations }) => operations.map(operation => `${id}/${operation.id}`)));
70
- const securityOperations = new Map(claimedPlugins.filter(plugin => plugin.kinds.includes('security')).flatMap(plugin => plugin.operations.filter(operation => operation.role === 'inspection').map(operation => [`${plugin.id}/${operation.id}`, plugin.id])));
71
- for (const file of snapshot.files) {
72
- const source = isSourcePath(file.path);
73
- const matching = filePlugins.filter((_, index) => matches[index](file.path));
74
- const selectedPlugins = isClaimedText(file.bytes) ? matching : [];
75
- if (matching.length && file.bytes.byteLength > maxClaimedFileBytes)
76
- diagnostics.push(oversizedClaim(file.path));
77
- if (!source && !selectedPlugins.length)
78
- continue;
79
- const groupKey = JSON.stringify([source, ...selectedPlugins.map(plugin => plugin.id)]);
80
- let tasks = sourcePlans.get(groupKey);
81
- if (!tasks) {
82
- tasks = plan({
83
- plugins: source ? [...sourcePlugins, ...selectedPlugins] : selectedPlugins,
84
- select: [...(source ? selected : []), ...selectedPlugins.flatMap(inspectionKeys)],
85
- inputs: new Map([['file', sourceFile.id]]), ...(source ? { bindings } : {}),
86
- });
87
- sourcePlans.set(groupKey, tasks);
88
- for (const task of tasks)
89
- usedPlans.set(operationBindingKey(task), task);
90
- }
91
- const results = await execute(tasks, new Map([['file', { contract: sourceFile.id, value: file }]]), cache);
92
- const syntax = results.get('babel-syntax/parse');
93
- if (syntax?.state === 'completed') {
94
- parsed.add(file.path);
95
- if (inputCoverage !== undefined && codeStructure.accepts(syntax.product.value) && syntax.product.value.functionBodies !== undefined) {
96
- functionBodies.set(file.path, syntax.product.value.functionBodies);
97
- }
98
- }
99
- for (const task of tasks) {
100
- const outcome = results.get(task.key);
101
- record(task, outcome, file.path);
102
- if (outcome.state === 'completed' && outcome.product.contract === fileQuality.id && fileQuality.accepts(outcome.product.value)) {
103
- cloneSources.push(outcome.product.value.cloneSource);
104
- }
105
- }
106
- }
107
- for (const { plugin, matches } of repositoryPlugins) {
108
- const select = inspectionKeys(plugin);
109
- if (!select.length)
110
- continue;
111
- const files = snapshot.files.filter(file => matches(file.path) && isClaimedText(file.bytes));
112
- if (!files.length)
113
- continue;
114
- const tasks = plan({ plugins: [plugin], select, inputs: new Map([['files', sourceFileSet.id]]) });
115
- const results = await execute(tasks, new Map([['files', { contract: sourceFileSet.id, value: files }]]), cache);
116
- const paths = files.map(({ path }) => path);
117
- for (const task of tasks) {
118
- usedPlans.set(operationBindingKey(task), task);
119
- record(task, results.get(task.key), undefined, paths);
120
- }
121
- }
122
- const copies = (await execute(duplicationPlan, new Map([['sources', { contract: duplicationInput.id, value: cloneSources }]]), cache))
123
- .get('duplication/detect');
124
- record(duplicationPlan[0], copies);
125
- if (inputCoverage !== undefined) {
126
- const value = { text: inputCoverage.text, root: inputCoverage.sourceRoot, sourceLines: sourceLineCounts(sourceFiles),
127
- codeLines: new Map(cloneSources.map(({ path, codeLines }) => [path, new Set(codeLines)])),
128
- functionBodies,
129
- excludes: sourceExclusionMatcher(excludedPaths, snapshot.generatedExcluded) };
130
- const outcomes = await execute(coveragePlan, new Map([['lcov', { contract: lcovInput.id, value }]]), cache);
131
- for (const task of coveragePlan)
132
- record(task, outcomes.get(task.key));
133
- const result = outcomes.get('lcov/import');
134
- if (result.state === 'completed' && coverageResult.accepts(result.product.value)) {
135
- for (const { path, reason } of result.product.value.gaps) {
136
- diagnostics.push({ operation: 'lcov/import', state: 'partial', path, message: reason });
137
- }
138
- }
139
- }
140
- const pluginData = reportProducts.result();
141
- const securityScanners = claimedPlugins.filter(plugin => scanned.has(plugin.id)).map(({ id, version }) => ({ name: id, version }));
142
- const inventory = new Map((snapshot.inventory ?? []).map(({ path, lines, bytes }) => [path, { lines, bytes }]));
143
- for (const { path, bytes } of snapshot.files) {
144
- if (!inventory.has(path))
145
- inventory.set(path, { lines: textLineCount(bytes), bytes: bytes.length });
146
- }
147
- return {
148
- schema: reportSchema,
149
- subject: snapshot.subject,
150
- generatedAt: new Date().toISOString(),
151
- appliedConfig: {
152
- profile: 'js-ts/v2', mode: snapshot.subject.kind,
153
- source: { extensions: sourceExtensions, excludedDirectories: sourceDirectoriesExcluded, excludedOutput, excludedPaths,
154
- defaultExclusions: defaultSourceExclusions, generatedSourcePolicy, generatedExcluded: snapshot.generatedExcluded ?? [] },
155
- parser: parserDefaults,
156
- maintainability: { structuralRules, duplication: duplicationSettings, debtModel, remediation: 'nonoverlapping-complexity/v1' },
157
- coverage: inputCoverage === undefined ? null : { inputDigest: digest(inputCoverage.text), pathBase: inputCoverage.sourceRoot,
158
- merge: 'any-hit', hitCounts: 'sum', lines: 'code-only' },
159
- ...(securityScanners.length ? { securityScanners } : {}),
160
- plugins: plugins.map(({ id, version, api, tools, kinds, claims, settings }) => ({ id, version, api, tools: tools ?? {},
161
- ...(kinds === undefined ? {} : { kinds }), ...(claims === undefined ? {} : { claims }), ...(settings === undefined ? {} : { settings }) })),
162
- operations: [...usedPlans.values(), ...duplicationPlan, ...(inputCoverage === undefined ? [] : coveragePlan)]
163
- .map(task => ({ key: task.key, inputs: Object.fromEntries(task.inputs),
164
- ...(task.operation.scope === 'repository' ? { scope: task.operation.scope } : {}) })),
165
- },
166
- definitions: { ...Object.fromEntries((pluginData?.metrics ?? []).map(metric => [metric.id, metric.description ?? metric.label])),
167
- ...measurementDefinitions },
168
- scope: { files: sourceFiles.length, parsed: parsed.size },
169
- status: diagnostics.length > 0 ? 'partial' : sourceFiles.length === 0 && !completedInspection ? 'not-applicable' : 'complete',
170
- measurements: rows,
171
- diagnostics,
172
- findings,
173
- ...(pluginData === undefined ? {} : { pluginData: { ...pluginData,
174
- inventory: [...inventory].sort(([left], [right]) => comparePaths(left, right)).map(([path, { lines, bytes }]) => ({ path, lines, ...(bytes === undefined ? {} : { bytes }), language: languageId(path), analysed: parsed.has(path) || inspected.has(path) })) } }),
175
- };
176
- function record(task, outcome, path, paths) {
177
- if (outcome.state !== 'completed') {
178
- diagnostics.push(diagnostic(task.key, outcome, path));
179
- return;
180
- }
181
- try {
182
- const stored = reportProducts.record(task, outcome.product, path);
183
- for (const message of outcome.diagnostics ?? [])
184
- diagnostics.push({ operation: task.key, state: 'partial', message,
185
- ...(path === undefined ? {} : { path }) });
186
- if (task.operation.role === 'inspection' && (path !== undefined || paths?.length)) {
187
- completedInspection = true;
188
- if (!scanOnlyOperations.has(task.key)) {
189
- if (path !== undefined)
190
- inspected.add(path);
191
- else
192
- for (const file of paths ?? [])
193
- inspected.add(file);
194
- }
195
- }
196
- const scanner = securityOperations.get(task.key);
197
- if (scanner)
198
- scanned.add(scanner);
199
- if (stored) {
200
- rows.push(...stored.measurements);
201
- findings.push(...stored.findings);
202
- }
203
- }
204
- catch (error) {
205
- diagnostics.push({ operation: task.key, state: 'failed', path, message: error instanceof Error ? error.message : String(error) });
206
- }
207
- }
208
- }
209
- function pluginForScope(plugin, scope) {
210
- const operations = plugin.operations.filter(operation => (operation.scope ?? 'file') === scope);
211
- return operations.length === plugin.operations.length ? plugin : { ...plugin, operations };
212
- }
213
- function inspectionKeys(plugin) {
214
- return plugin.operations.filter(operation => operation.role === 'inspection').map(operation => `${plugin.id}/${operation.id}`);
215
- }
216
- function operationBindingKey(task) {
217
- return JSON.stringify([task.key, [...task.inputs]]);
218
- }
219
- function oversizedClaim(path) {
220
- return { operation: 'source/claims', state: 'partial', path, message: 'Plugin inspection skipped a file larger than 1 MiB' };
221
- }
222
- function languageId(path) {
223
- const suffix = extname(path).toLowerCase();
224
- if (['.js', '.mjs', '.cjs', '.jsx'].includes(suffix))
225
- return 'javascript';
226
- if (['.ts', '.mts', '.cts', '.tsx'].includes(suffix))
227
- return 'typescript';
228
- if (suffix === '.md' || suffix === '.mdx')
229
- return 'markdown';
230
- if (suffix === '.yml')
231
- return 'yaml';
232
- if (suffix === '.py')
233
- return 'python';
234
- if (suffix === '.rs')
235
- return 'rust';
236
- if (suffix === '.kt' || suffix === '.kts')
237
- return 'kotlin';
238
- return suffix.slice(1) || 'other';
239
- }
240
- function claimMatcher(claims) {
241
- const { extensions = [], globs = [], languages = [] } = claims ?? {};
242
- if (extensions.length === 0 && globs.length === 0 && languages.length === 0)
243
- return () => true;
244
- const glob = exclusionMatcher(globs);
245
- const suffixes = new Set(extensions);
246
- const languageSet = new Set(languages);
247
- return path => suffixes.has(extname(path)) || glob(path) || languageSet.has(languageId(path));
248
- }
249
- function diagnostic(operation, outcome, path) {
250
- return { operation, state: outcome.state, message: outcome.reason, ...(path === undefined ? {} : { path }) };
1
+ import { defaultFilePlan, inspectFiles } from './analysis-files.js';
2
+ import { importAnalysisCoverage, inspectDuplication } from './analysis-imports.js';
3
+ import { collectRepositorySyntax, inspectRepositories } from './analysis-repository.js';
4
+ import { assembleAnalysisReport } from './analysis-report.js';
5
+ import { AnalysisResults } from './analysis-results.js';
6
+ import { selectAnalysisSources } from './analysis-sources.js';
7
+ export { inspectionFileMatcher } from './analysis-sources.js';
8
+ export async function analyzeSnapshot(input, additional = [], cache) {
9
+ const withCoverage = input.coverage !== undefined;
10
+ const sources = selectAnalysisSources(input.snapshot, additional, withCoverage);
11
+ const results = new AnalysisResults(sources.plugins, sources.claimedPlugins, input.snapshot.oversizedClaims ?? []);
12
+ for (const task of defaultFilePlan)
13
+ results.remember(task);
14
+ const batchFacts = await collectRepositorySyntax(sources, results, cache);
15
+ const files = await inspectFiles(sources, batchFacts, results, withCoverage, cache);
16
+ await inspectRepositories(sources, results, cache);
17
+ await inspectDuplication(files, results, cache);
18
+ await importAnalysisCoverage(input, sources, files, results, cache);
19
+ return assembleAnalysisReport(input, sources, results);
251
20
  }
252
21
  //# sourceMappingURL=analyze-snapshot.js.map
@@ -1,3 +1,4 @@
1
+ import type { Plugin } from '../core/engine/plugin.js';
1
2
  import type { DiffCoveragePorts, DiffCoverageReport } from '../core/usecases/diff-coverage.js';
2
3
  import type { LcovFiles } from '../api/import/lcov-files.js';
3
4
  export { diffCoverageSchema } from '../core/usecases/diff-coverage.js';
@@ -9,6 +10,7 @@ export interface DiffCoverageRequest {
9
10
  readonly lcov: LcovFiles;
10
11
  readonly exclude?: readonly string[];
11
12
  readonly minimumPercent?: number;
13
+ readonly plugins?: readonly Plugin[];
12
14
  }
13
15
  export declare function measureDiffCoverage(request: DiffCoverageRequest, overrides?: Partial<DiffCoveragePorts>): Promise<DiffCoverageReport>;
14
16
  export declare function measureChangedLines(request: DiffCoverageRequest, overrides?: Partial<DiffCoveragePorts>): Promise<{
@@ -1,6 +1,6 @@
1
1
  import { execute } from '../core/engine/execute.js';
2
2
  import { plan } from '../core/engine/plan.js';
3
- import { digest, sourceDirectoriesExcluded, sourceExtensions, sourceLineCounts } from '../core/model/snapshot.js';
3
+ import { digest, sourceDirectoriesExcluded, sourceLineCounts } from '../core/model/snapshot.js';
4
4
  import { executeDiffCoverage } from '../core/usecases/diff-coverage.js';
5
5
  import { defaultSourceExclusions, generatedSourcePolicy, sourceExclusionMatcher } from '../core/profile/exclusions.js';
6
6
  import { coverage, lcovInput } from '../plugins/coverage/coverage.js';
@@ -8,6 +8,7 @@ import { changesInput, diffCoverage, diffCoverageResult } from '../plugins/cover
8
8
  import { diffMethod, findMergeBase, readChanges } from '../api/git/changes.js';
9
9
  import { gitText, physicalGitRoot, readGitCommit, resolveGitCommit } from '../api/git/git.js';
10
10
  import { readLcovFiles } from '../api/import/lcov-files.js';
11
+ import { defaultLanguages, languageRegistry } from './languages.js';
11
12
  export { diffCoverageSchema } from '../core/usecases/diff-coverage.js';
12
13
  const operation = 'diff-coverage/measure';
13
14
  const steps = plan({ plugins: [diffCoverage], select: [operation],
@@ -43,10 +44,11 @@ async function readInputs(request, excludedPaths, excludes) {
43
44
  gitText(root, ['--version']).then(text => text.trim()),
44
45
  ]);
45
46
  const base = await findMergeBase(root, requestedBase, head);
46
- const snapshot = await readGitCommit(root, head, excludes);
47
- const changes = await readChanges(root, base, snapshot, sourceExclusionMatcher(excludedPaths, snapshot.generatedExcluded));
47
+ const { isSource, extensions, globs } = request.plugins?.length ? languageRegistry(request.plugins) : defaultLanguages;
48
+ const snapshot = await readGitCommit(root, head, excludes, isSource);
49
+ const changes = await readChanges(root, base, snapshot, sourceExclusionMatcher(excludedPaths, snapshot.generatedExcluded), isSource);
48
50
  return { requestedBase, base, head, snapshot, changes, root, lcovText: lcov.text, appliedConfig: {
49
- source: { extensions: sourceExtensions, excludedDirectories: sourceDirectoriesExcluded, excludedPaths,
51
+ source: { extensions, ...(globs.length ? { globs } : {}), excludedDirectories: sourceDirectoriesExcluded, excludedPaths,
50
52
  defaultExclusions: defaultSourceExclusions, generatedSourcePolicy, generatedExcluded: snapshot.generatedExcluded ?? [] },
51
53
  gitDiff: { ...diffMethod, version: gitVersion },
52
54
  lcov: { inputDigest: digest(lcov.text), pathBase: root, merge: 'any-hit', importerVersion: coverage.version,
@@ -9,25 +9,28 @@ import { executeInspection } from '../core/usecases/inspect.js';
9
9
  import { LocalReportStore } from '../report/json/store/local-store.js';
10
10
  import { analyzeSnapshot, inspectionFileMatcher } from './analyze-snapshot.js';
11
11
  import { attachChurn } from './attach-churn.js';
12
+ import { defaultLanguages, languageRegistry } from './languages.js';
12
13
  export { analyzeSnapshot } from './analyze-snapshot.js';
13
14
  export async function inspect(request, overrides) {
14
15
  const { lcov, findingInputs = [], plugins = [], operationCache } = request;
15
16
  if ((plugins.length || operationCache) && (typeof overrides === 'function' || overrides?.analyze)) {
16
17
  throw new Error('Configure plugins and the operation cache on the custom executor');
17
18
  }
18
- const claims = inspectionFileMatcher(plugins);
19
+ const languages = plugins.length ? languageRegistry(plugins) : defaultLanguages;
20
+ const claims = inspectionFileMatcher(plugins, languages);
21
+ const { isSource } = languages;
19
22
  const ports = {
20
- readSource: excludes => readSource(request, excludes, claims),
23
+ readSource: excludes => readSource(request, excludes, isSource, claims),
21
24
  analyze: input => analyzeSnapshot(input, plugins, operationCache),
22
25
  ...(lcov === undefined ? {} : { readCoverage: () => readLcovFiles(lcov) }),
23
26
  ...(findingInputs.length === 0 ? {} : { importFindings: (report, root, excludes) => attachFindings(report, findingInputs, root, request.findingRoot === undefined ? root : resolve(request.findingRoot), excludes) }),
24
- recordChurn: attachChurn,
27
+ recordChurn: (report, root, paths) => attachChurn(report, root, paths.filter(isSource)),
25
28
  ...(typeof overrides === 'function' ? { analyze: overrides } : overrides),
26
29
  };
27
30
  return executeInspection(request, ports);
28
31
  }
29
- async function readSource(request, excludes, claims) {
30
- const source = await readInspectionSource(request, excludes, claims);
32
+ async function readSource(request, excludes, isSource, claims) {
33
+ const source = await readInspectionSource(request, excludes, isSource, claims);
31
34
  const store = new LocalReportStore(source.output);
32
35
  return { ...source, save: (report) => store.save(report) };
33
36
  }
@@ -0,0 +1,29 @@
1
+ import type { FileClaims, Operation, Plugin } from '../core/engine/plugin.js';
2
+ import type { LanguageDisplay } from '../core/model/language.js';
3
+ export interface LanguageProvider {
4
+ readonly plugin: Plugin;
5
+ readonly operation: Operation;
6
+ readonly key: string;
7
+ readonly batch: boolean;
8
+ readonly language: (path: string) => string | undefined;
9
+ }
10
+ export declare const defaultLanguages: {
11
+ select(path: string): LanguageProvider | undefined;
12
+ isSource(path: string): boolean;
13
+ id(path: string): string;
14
+ readonly extensions: readonly string[];
15
+ readonly globs: readonly string[];
16
+ readonly catalog: readonly LanguageDisplay[];
17
+ readonly providers: readonly LanguageProvider[];
18
+ };
19
+ export declare function languageRegistry(plugins: readonly Plugin[]): {
20
+ select(path: string): LanguageProvider | undefined;
21
+ isSource(path: string): boolean;
22
+ id(path: string): string;
23
+ readonly extensions: readonly string[];
24
+ readonly globs: readonly string[];
25
+ readonly catalog: readonly LanguageDisplay[];
26
+ readonly providers: readonly LanguageProvider[];
27
+ };
28
+ export declare function languageId(path: string): string;
29
+ export declare function claimMatcher(claims: FileClaims | undefined, identify?: typeof languageId): (path: string) => boolean;