repometry 0.6.0 → 0.6.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 (43) hide show
  1. package/package.json +1 -1
  2. package/target/main/ts/cli/main.js +1 -1
  3. package/target/main/ts/cli/reporting.js +3 -2
  4. package/target/main/ts/compose/analysis-files.js +1 -1
  5. package/target/main/ts/compose/analysis-report.js +4 -4
  6. package/target/main/ts/compose/analysis-sources.d.ts +2 -32
  7. package/target/main/ts/compose/analysis-sources.js +2 -3
  8. package/target/main/ts/compose/languages.d.ts +2 -2
  9. package/target/main/ts/compose/languages.js +3 -23
  10. package/target/main/ts/compose/plugin-list.js +2 -2
  11. package/target/main/ts/core/engine/execute.js +40 -39
  12. package/target/main/ts/core/engine/manifest.js +40 -37
  13. package/target/main/ts/core/model/file-types.d.ts +19 -0
  14. package/target/main/ts/core/model/file-types.js +39 -0
  15. package/target/main/ts/core/model/language.d.ts +4 -0
  16. package/target/main/ts/core/model/report.d.ts +2 -0
  17. package/target/main/ts/core/model/report.js +20 -0
  18. package/target/main/ts/core/usecases/compare.js +3 -4
  19. package/target/main/ts/index.d.ts +3 -2
  20. package/target/main/ts/index.js +2 -1
  21. package/target/main/ts/plugins/coverage/coverage.js +69 -81
  22. package/target/main/ts/plugins/duplication/duplication.js +2 -3
  23. package/target/main/ts/plugins/language-js/babel-provider.js +5 -7
  24. package/target/main/ts/plugins/language-js/extensions.d.ts +0 -2
  25. package/target/main/ts/plugins/language-js/extensions.js +2 -3
  26. package/target/main/ts/report/html/app/viewer-file-source.js +1 -1
  27. package/target/main/ts/report/html/app/viewer-filter.js +1 -1
  28. package/target/main/ts/report/html/app/viewer-inspection.js +2 -0
  29. package/target/main/ts/report/html/app/viewer-languages.d.ts +7 -2
  30. package/target/main/ts/report/html/app/viewer-languages.js +18 -31
  31. package/target/main/ts/report/html/app/viewer-suggest.js +1 -1
  32. package/target/main/ts/report/html/app/viewer-table-cells.js +1 -1
  33. package/target/main/ts/report/html/site/export-site.d.ts +2 -3
  34. package/target/main/ts/report/html/site/export-site.js +1 -1
  35. package/target/main/ts/report/html/site/local-server.js +1 -1
  36. package/target/main/ts/report/json/projections/commit-summary.js +4 -1
  37. package/target/main/ts/report/json/projections/components.d.ts +1 -1
  38. package/target/main/ts/report/json/projections/file-metrics.d.ts +2 -3
  39. package/target/main/ts/report/json/projections/file-metrics.js +75 -78
  40. package/target/main/ts/report/json/projections/inspection-context.d.ts +1 -3
  41. package/target/main/ts/report/json/projections/inspection-context.js +10 -24
  42. package/target/main/ts/report/json/projections/inspection-details.d.ts +7 -4
  43. package/target/main/ts/report/json/projections/inspection-details.js +5 -5
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repometry",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Track repository metrics without SaaS",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -267,7 +267,7 @@ async function show(input) {
267
267
  throw error;
268
268
  report = await store.reader.read({ kind: 'working-tree', id: ref });
269
269
  }
270
- print(input.flag('files') ? fileMetrics(report) : report);
270
+ print(input.flag('files') ? fileMetrics(report, defaultLanguages) : report);
271
271
  }
272
272
  async function compare(input) {
273
273
  const { directory, root, store } = await context(input);
@@ -3,6 +3,7 @@ import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import { basename, dirname, resolve } from 'node:path';
4
4
  import { commitMetadataReader } from '../api/git/commit-metadata.js';
5
5
  import { readLocalSources, sourceRemotes } from '../api/git/local-sources.js';
6
+ import { defaultLanguages } from '../compose/languages.js';
6
7
  import { resolveSourceLocator } from '../compose/sources.js';
7
8
  import { commitSummary, withCommitMetadata } from '../report/json/projections/commit-summary.js';
8
9
  import { exportSite, siteSummary } from '../report/html/site/export-site.js';
@@ -41,7 +42,7 @@ export async function outputReports(root, store, requested, input, config) {
41
42
  readComponents(componentsPath(root, input), input.text('components') === undefined),
42
43
  store.path ? listPullReviews(store.path) : [],
43
44
  ]);
44
- const options = { sources, components, pulls, readCommitMetadata, branch: input.text('branch') ?? config.branch,
45
+ const options = { languages: defaultLanguages, sources, components, pulls, readCommitMetadata, branch: input.text('branch') ?? config.branch,
45
46
  title: input.text('title') ?? (input.text('repo') ? basename(root) : undefined),
46
47
  footer: !input.flag('no-footer') };
47
48
  for (const request of requests) {
@@ -92,7 +93,7 @@ export async function viewTarget(input, port) {
92
93
  readConfig(root, input),
93
94
  ]);
94
95
  const local = repository ? readLocalSources(repository) : undefined;
95
- const server = await serveSite(store.reader, port, { title: input.text('title') ?? basename(root), components, pulls,
96
+ const server = await serveSite(store.reader, port, { languages: defaultLanguages, title: input.text('title') ?? basename(root), components, pulls,
96
97
  branch: input.text('branch') ?? config.branch, readCommitMetadata: repository ? commitMetadataReader(repository) : undefined,
97
98
  sources: local ? resolveSourceLocator('local', { remotes: [], env: {} }) : undefined, footer: !input.flag('no-footer') }, local);
98
99
  return { ...server, label: `${basename(root)} (live from ${store.path ?? input.text('store')})` };
@@ -90,6 +90,6 @@ function cloneSource(outcome, provider) {
90
90
  if (outcome.state !== 'completed' || outcome.product.contract !== fileQuality.id || !fileQuality.accepts(outcome.product.value))
91
91
  return;
92
92
  const source = outcome.product.value.cloneSource;
93
- return provider && provider !== defaultProvider && source.scheme === undefined ? { ...source, scheme: provider.plugin.id } : source;
93
+ return provider && source.scheme === undefined ? { ...source, scheme: provider.plugin.id } : source;
94
94
  }
95
95
  //# sourceMappingURL=analysis-files.js.map
@@ -4,8 +4,8 @@ import { reportSchema } from '../core/model/report.js';
4
4
  import { comparePaths, digest, sourceDirectoriesExcluded, textLineCount } from '../core/model/snapshot.js';
5
5
  import { defaultSourceExclusions, generatedSourcePolicy } from '../core/profile/exclusions.js';
6
6
  import { duplicationSettings, structuralRules } from '../core/profile/maintainability.js';
7
- import { parserDefaults } from '../plugins/language-js/babel-provider.js';
8
- import { languageId } from './languages.js';
7
+ import { defaultProvider } from './analysis-sources.js';
8
+ import { fileTypeId } from '../core/model/file-types.js';
9
9
  const measurementDefinitions = {
10
10
  [definitions.lines]: 'Physical lines including blank lines and comments. A final line terminator does not add a line.',
11
11
  [definitions.functions]: 'Babel function nodes with bodies, including nested functions and methods.',
@@ -44,7 +44,7 @@ function appliedConfiguration({ snapshot, excludedOutput, excludedPaths = [], co
44
44
  source: { extensions: languages.extensions, ...(languages.globs.length ? { globs: languages.globs } : {}),
45
45
  excludedDirectories: sourceDirectoriesExcluded, excludedOutput, excludedPaths,
46
46
  defaultExclusions: defaultSourceExclusions, generatedSourcePolicy, generatedExcluded: snapshot.generatedExcluded ?? [] },
47
- parser: parserDefaults,
47
+ parser: defaultProvider.plugin.settings,
48
48
  maintainability: { structuralRules, duplication: duplicationSettings, debtModel, remediation: 'nonoverlapping-complexity/v1' },
49
49
  coverage: coverage === undefined ? null : { inputDigest: digest(coverage.text), pathBase: coverage.sourceRoot,
50
50
  merge: 'any-hit', hitCounts: 'sum', lines: 'code-only' },
@@ -71,7 +71,7 @@ function reportInventory(snapshot, sources, results) {
71
71
  }
72
72
  return [...inventory].sort(([left], [right]) => comparePaths(left, right)).map(([path, { lines, bytes }]) => {
73
73
  const provider = sources.providersByPath.get(path);
74
- return { path, lines, ...(bytes === undefined ? {} : { bytes }), language: provider?.language(path) ?? languageId(path),
74
+ return { path, lines, ...(bytes === undefined ? {} : { bytes }), language: provider?.language(path) ?? fileTypeId(path),
75
75
  analysed: results.parsed.has(path) || results.inspected.has(path), ...(provider === undefined ? {} : { provider: provider.key }) };
76
76
  });
77
77
  }
@@ -1,22 +1,7 @@
1
1
  import type { Operation, Plugin } from '../core/engine/plugin.js';
2
2
  import type { SourceFile, SourceSnapshot } from '../core/model/source.js';
3
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
- }[];
4
+ export declare const structuralInspections: Plugin[];
20
5
  export declare const defaultProvider: LanguageProvider;
21
6
  export interface SelectedSource {
22
7
  readonly file: SourceFile;
@@ -48,22 +33,7 @@ export declare function selectAnalysisSources(snapshot: SourceSnapshot, addition
48
33
  sources: SelectedSource[];
49
34
  sourceFiles: SourceFile[];
50
35
  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
- })[];
36
+ plugins: Plugin[];
67
37
  claimedPlugins: Plugin[];
68
38
  perFile: ClaimedPlugin[];
69
39
  repository: ClaimedPlugin[];
@@ -1,12 +1,11 @@
1
1
  import { plan } from '../core/engine/plan.js';
2
2
  import { coverage } from '../plugins/coverage/coverage.js';
3
3
  import { duplication } from '../plugins/duplication/duplication.js';
4
- import { babelProvider, babelTypes } from '../plugins/language-js/babel-provider.js';
5
4
  import { maintainability } from '../plugins/maintainability/maintainability.js';
6
5
  import { structure } from '../plugins/structure/structure.js';
7
6
  import { claimMatcher, defaultLanguages, languageRegistry } from './languages.js';
8
7
  import { securityPlugins } from './security-plugins.js';
9
- export const structuralInspections = [{ ...structure, tools: babelTypes }, { ...maintainability, tools: babelTypes }];
8
+ export const structuralInspections = [structure, maintainability];
10
9
  export const defaultProvider = defaultLanguages.providers[0];
11
10
  export function inspectionFileMatcher(additional, languages = defaultLanguages) {
12
11
  const matches = [...securityPlugins, ...additional].filter(plugin => !plugin.kinds.includes('language'))
@@ -19,7 +18,7 @@ export function selectAnalysisSources(snapshot, additional, withCoverage) {
19
18
  const providersByPath = new Map(sources.flatMap(({ file, provider }) => provider ? [[file.path, provider]] : []));
20
19
  const sourceFiles = sources.flatMap(({ file, provider }) => provider ? [file] : []);
21
20
  const claimedPlugins = [...securityPlugins.filter(plugin => !additional.includes(plugin)), ...additional];
22
- const plugins = [babelProvider, ...structuralInspections, duplication, ...(withCoverage ? [coverage] : []), ...claimedPlugins];
21
+ const plugins = [defaultProvider.plugin, ...structuralInspections, duplication, ...(withCoverage ? [coverage] : []), ...claimedPlugins];
23
22
  validateRegistration(plugins, additional, withCoverage);
24
23
  const claims = claimedPlugins.map(plugin => ({ plugin, matches: plugin.kinds.includes('language')
25
24
  ? path => providersByPath.get(path)?.plugin.id === plugin.id : claimMatcher(plugin.claims, languages.id) }));
@@ -1,4 +1,5 @@
1
1
  import type { FileClaims, Operation, Plugin } from '../core/engine/plugin.js';
2
+ import { fileTypeId } from '../core/model/file-types.js';
2
3
  import type { LanguageDisplay } from '../core/model/language.js';
3
4
  export interface LanguageProvider {
4
5
  readonly plugin: Plugin;
@@ -25,5 +26,4 @@ export declare function languageRegistry(plugins: readonly Plugin[]): {
25
26
  readonly catalog: readonly LanguageDisplay[];
26
27
  readonly providers: readonly LanguageProvider[];
27
28
  };
28
- export declare function languageId(path: string): string;
29
- export declare function claimMatcher(claims: FileClaims | undefined, identify?: typeof languageId): (path: string) => boolean;
29
+ export declare function claimMatcher(claims: FileClaims | undefined, identify?: typeof fileTypeId): (path: string) => boolean;
@@ -1,9 +1,9 @@
1
1
  import { extname } from 'node:path';
2
+ import { fileTypeId } from '../core/model/file-types.js';
2
3
  import { codeStructure, codeStructures } from '../core/model/code-structure.js';
3
4
  import { isExcludedDirectory } from '../core/model/snapshot.js';
4
5
  import { exclusionMatcher } from '../core/profile/exclusions.js';
5
6
  import { babelProvider } from '../plugins/language-js/babel-provider.js';
6
- import { javaScriptExtensions, typeScriptExtensions } from '../plugins/language-js/extensions.js';
7
7
  export const defaultLanguages = languageRegistry([]);
8
8
  export function languageRegistry(plugins) {
9
9
  const entries = [babelProvider, ...plugins.filter(plugin => plugin.kinds?.includes('language'))].map(plugin => {
@@ -39,7 +39,7 @@ export function languageRegistry(plugins) {
39
39
  })));
40
40
  if (new Set(catalog.map(({ id }) => id)).size !== catalog.length)
41
41
  throw new Error('Duplicate provided language ID');
42
- return { select, isSource: path => select(path) !== undefined, id: path => select(path)?.language(path) ?? languageId(path), extensions, globs,
42
+ return { select, isSource: path => select(path) !== undefined, id: path => select(path)?.language(path) ?? fileTypeId(path), extensions, globs,
43
43
  catalog, providers };
44
44
  function select(path) {
45
45
  let selected;
@@ -55,27 +55,7 @@ export function languageRegistry(plugins) {
55
55
  return selected;
56
56
  }
57
57
  }
58
- const js = new Set(javaScriptExtensions);
59
- const ts = new Set(typeScriptExtensions);
60
- export function languageId(path) {
61
- const suffix = extname(path).toLowerCase();
62
- if (js.has(suffix))
63
- return 'javascript';
64
- if (ts.has(suffix))
65
- return 'typescript';
66
- if (suffix === '.md' || suffix === '.mdx')
67
- return 'markdown';
68
- if (suffix === '.yml')
69
- return 'yaml';
70
- if (suffix === '.py')
71
- return 'python';
72
- if (suffix === '.rs')
73
- return 'rust';
74
- if (suffix === '.kt' || suffix === '.kts')
75
- return 'kotlin';
76
- return suffix.slice(1) || 'other';
77
- }
78
- export function claimMatcher(claims, identify = languageId) {
58
+ export function claimMatcher(claims, identify = fileTypeId) {
79
59
  const { extensions = [], globs = [], languages = [] } = claims ?? {};
80
60
  if (extensions.length === 0 && globs.length === 0 && languages.length === 0)
81
61
  return () => true;
@@ -1,11 +1,11 @@
1
1
  import { coverage } from '../plugins/coverage/coverage.js';
2
2
  import { diffCoverage } from '../plugins/coverage/diff-coverage.js';
3
3
  import { duplication } from '../plugins/duplication/duplication.js';
4
- import { babelProvider } from '../plugins/language-js/babel-provider.js';
5
4
  import { maintainability } from '../plugins/maintainability/maintainability.js';
6
5
  import { structure } from '../plugins/structure/structure.js';
6
+ import { defaultLanguages } from './languages.js';
7
7
  import { sourceProviders } from './sources.js';
8
8
  import { securityPlugins } from './security-plugins.js';
9
- export const builtInPlugins = [babelProvider, structure, maintainability, duplication, coverage, diffCoverage, ...securityPlugins, ...sourceProviders]
9
+ export const builtInPlugins = [...defaultLanguages.providers.map(({ plugin }) => plugin), structure, maintainability, duplication, coverage, diffCoverage, ...securityPlugins, ...sourceProviders]
10
10
  .map(({ id, version, kinds, claims }) => ({ id, version, kinds, ...(claims ? { claims } : {}) }));
11
11
  //# sourceMappingURL=plugin-list.js.map
@@ -3,55 +3,56 @@ export async function execute(plan, external, cache) {
3
3
  const results = new Map();
4
4
  for (const task of plan) {
5
5
  const inputs = new Map();
6
+ const missing = [];
6
7
  for (const [name, binding] of task.inputs) {
7
8
  const producer = 'operation' in binding ? results.get(binding.operation) : undefined;
8
9
  const product = 'external' in binding ? external.get(binding.external)
9
10
  : producer?.state === 'completed' ? producer.product : undefined;
10
11
  if (product)
11
12
  inputs.set(name, product);
13
+ else
14
+ missing.push(name);
12
15
  }
13
- const missing = [...task.inputs.keys()].filter(name => !inputs.has(name));
14
- if (missing.length > 0) {
15
- results.set(task.key, { state: 'blocked', reason: `Unavailable inputs: ${missing.join(', ')}` });
16
- continue;
17
- }
18
- try {
19
- for (const [name, contract] of Object.entries(task.operation.inputs)) {
20
- readInput(inputs, name, contract);
21
- }
22
- const key = cache && operationCacheKey(task, inputs, cache.configurationDigest);
23
- const hit = key && cache ? await readCachedOperation(cache.store, key, task) : undefined;
24
- if (hit) {
25
- results.set(task.key, { state: 'completed', product: hit });
26
- continue;
27
- }
28
- const diagnostics = [];
29
- const context = {
30
- read: (port, contract) => {
31
- if (!Object.hasOwn(task.operation.inputs, port) || task.operation.inputs[port]?.id !== contract.id) {
32
- throw new Error(`Undeclared input contract: ${port} (${contract.id})`);
33
- }
34
- return readInput(inputs, port, contract);
35
- },
36
- emitDiagnostic: message => diagnostics.push(message),
37
- };
38
- const value = await task.operation.execute(context);
39
- const { output } = task.operation;
40
- if (!output.accepts(value))
41
- throw new Error(`Invalid output for ${output.id}`);
42
- if (task.validateOutput && !task.validateOutput(value))
43
- throw new Error(`Output violates the schema for ${output.id}`);
44
- const product = { contract: output.id, value };
45
- if (key && cache && diagnostics.length === 0)
46
- await writeCachedOperation(cache.store, key, product);
47
- results.set(task.key, { state: 'completed', product, ...(diagnostics.length ? { diagnostics } : {}) });
48
- }
49
- catch (error) {
50
- results.set(task.key, { state: 'failed', reason: error instanceof Error ? error.message : String(error) });
51
- }
16
+ results.set(task.key, missing.length
17
+ ? { state: 'blocked', reason: `Unavailable inputs: ${missing.join(', ')}` }
18
+ : await runTask(task, inputs, cache));
52
19
  }
53
20
  return results;
54
21
  }
22
+ async function runTask(task, inputs, cache) {
23
+ try {
24
+ const { operation, validateOutput } = task;
25
+ for (const [name, contract] of Object.entries(operation.inputs))
26
+ readInput(inputs, name, contract);
27
+ const key = cache && operationCacheKey(task, inputs, cache.configurationDigest);
28
+ const hit = key && cache ? await readCachedOperation(cache.store, key, task) : undefined;
29
+ if (hit)
30
+ return { state: 'completed', product: hit };
31
+ const diagnostics = [];
32
+ const context = {
33
+ read: (port, contract) => {
34
+ if (!Object.hasOwn(operation.inputs, port) || operation.inputs[port]?.id !== contract.id) {
35
+ throw new Error(`Undeclared input contract: ${port} (${contract.id})`);
36
+ }
37
+ return readInput(inputs, port, contract);
38
+ },
39
+ emitDiagnostic: message => diagnostics.push(message),
40
+ };
41
+ const value = await operation.execute(context);
42
+ const { output } = operation;
43
+ if (!output.accepts(value))
44
+ throw new Error(`Invalid output for ${output.id}`);
45
+ if (validateOutput && !validateOutput(value))
46
+ throw new Error(`Output violates the schema for ${output.id}`);
47
+ const product = { contract: output.id, value };
48
+ if (key && cache && diagnostics.length === 0)
49
+ await writeCachedOperation(cache.store, key, product);
50
+ return { state: 'completed', product, ...(diagnostics.length ? { diagnostics } : {}) };
51
+ }
52
+ catch (error) {
53
+ return { state: 'failed', reason: error instanceof Error ? error.message : String(error) };
54
+ }
55
+ }
55
56
  function readInput(inputs, port, contract) {
56
57
  const product = inputs.get(port);
57
58
  if (!product || product.contract !== contract.id || !contract.accepts(product.value)) {
@@ -17,30 +17,7 @@ export function isCoreReportProduct(contract) {
17
17
  return coreProducts.has(contract);
18
18
  }
19
19
  export function manifestProducts(plugin) {
20
- const { id, kinds: declaredKinds, claims, providesLanguages, produces, rules, config } = plugin;
21
- if (declaredKinds === undefined && claims === undefined && providesLanguages === undefined && produces === undefined) {
22
- throw new Error(`Missing plugin manifest for ${id}. Declare kinds and produces.`);
23
- }
24
- if (Object.hasOwn(plugin, 'languages'))
25
- throw new Error(`Plugin ${id} must declare languages in claims.languages`);
26
- if (!strings(declaredKinds) || declaredKinds.length === 0 || declaredKinds.some(kind => !kinds.has(kind))) {
27
- throw new Error(`Invalid kinds for plugin ${id}`);
28
- }
29
- if (claims !== undefined && (!isRecord(claims) || Object.entries(claims).some(([key, values]) => key === 'scanOnly' ? typeof values !== 'boolean'
30
- : !['extensions', 'globs', 'languages'].includes(key) || !strings(values)
31
- || (key === 'extensions' && values.some(extension => !/^\.[\w-]+$/.test(extension)))))) {
32
- throw new Error(`Invalid file claims for plugin ${id}`);
33
- }
34
- if (providesLanguages !== undefined && (!declaredKinds.includes('language') || !validLanguages(providesLanguages))) {
35
- throw new Error(`Invalid provided languages for plugin ${id}`);
36
- }
37
- if (!Array.isArray(produces))
38
- throw new Error(`Plugin ${id} must declare its products`);
39
- if (rules !== undefined && (!Array.isArray(rules) || !rules.every(isRuleDescriptor)
40
- || new Set(rules.map(rule => rule.id)).size !== rules.length))
41
- throw new Error(`Invalid or duplicate rules for plugin ${id}`);
42
- if (config !== undefined && typeof config !== 'boolean' && !isRecord(config))
43
- throw new Error(`Invalid configuration schema for plugin ${id}`);
20
+ const { id, produces, rules } = manifestDeclarations(plugin);
44
21
  const products = new Map();
45
22
  const catalog = new Map();
46
23
  for (const product of produces) {
@@ -48,8 +25,8 @@ export function manifestProducts(plugin) {
48
25
  || products.has(product.contract))
49
26
  throw new Error(`Invalid or duplicate product for plugin ${id}`);
50
27
  const { contract, schema, metrics } = product;
51
- if ((schema === undefined && product.persistence !== 'transient' && !isCoreReportProduct(contract))
52
- || (schema !== undefined && typeof schema !== 'boolean' && !isRecord(schema))) {
28
+ if (schema === undefined ? product.persistence !== 'transient' && !isCoreReportProduct(contract)
29
+ : typeof schema !== 'boolean' && !isRecord(schema)) {
53
30
  throw new Error(`Missing or invalid product schema for ${contract} in plugin ${id}`);
54
31
  }
55
32
  if (metrics !== undefined && (!Array.isArray(metrics) || !metrics.every(isMetricDescriptor))) {
@@ -63,22 +40,45 @@ export function manifestProducts(plugin) {
63
40
  }
64
41
  products.set(contract, declaration);
65
42
  }
66
- for (const rule of rules ?? []) {
67
- if (rule.measure !== undefined && !catalog.has(rule.measure)) {
68
- throw new Error(`Rule ${rule.id} in plugin ${id} references undeclared metric ${rule.measure}`);
69
- }
70
- }
43
+ const undeclared = rules?.find(rule => rule.measure !== undefined && !catalog.has(rule.measure));
44
+ if (undeclared)
45
+ throw new Error(`Rule ${undeclared.id} in plugin ${id} references undeclared metric ${undeclared.measure}`);
71
46
  for (const metric of catalog.values()) {
72
47
  if (!metric.ratio)
73
48
  continue;
74
- for (const component of [metric.ratio.of, metric.ratio.over]) {
75
- if (component === metric.id || (!catalog.has(component) && !coreMetrics.has(component))) {
76
- throw new Error(`Ratio ${metric.id} in plugin ${id} references invalid component ${component}`);
77
- }
78
- }
49
+ const invalid = [metric.ratio.of, metric.ratio.over].find(component => component === metric.id || (!catalog.has(component) && !coreMetrics.has(component)));
50
+ if (invalid !== undefined)
51
+ throw new Error(`Ratio ${metric.id} in plugin ${id} references invalid component ${invalid}`);
79
52
  }
80
53
  return products;
81
54
  }
55
+ function manifestDeclarations(plugin) {
56
+ const { id, kinds: declaredKinds, claims, providesLanguages, produces, rules, config } = plugin;
57
+ if (declaredKinds === undefined && claims === undefined && providesLanguages === undefined && produces === undefined) {
58
+ throw new Error(`Missing plugin manifest for ${id}. Declare kinds and produces.`);
59
+ }
60
+ if (Object.hasOwn(plugin, 'languages'))
61
+ throw new Error(`Plugin ${id} must declare languages in claims.languages`);
62
+ if (!strings(declaredKinds) || declaredKinds.length === 0 || declaredKinds.some(kind => !kinds.has(kind))) {
63
+ throw new Error(`Invalid kinds for plugin ${id}`);
64
+ }
65
+ if (claims !== undefined && (!isRecord(claims) || Object.entries(claims).some(([key, values]) => key === 'scanOnly' ? typeof values !== 'boolean'
66
+ : !['extensions', 'globs', 'languages'].includes(key) || !strings(values)
67
+ || (key === 'extensions' && !values.every(isExtension))))) {
68
+ throw new Error(`Invalid file claims for plugin ${id}`);
69
+ }
70
+ if (providesLanguages !== undefined && (!declaredKinds.includes('language') || !validLanguages(providesLanguages))) {
71
+ throw new Error(`Invalid provided languages for plugin ${id}`);
72
+ }
73
+ if (!Array.isArray(produces))
74
+ throw new Error(`Plugin ${id} must declare its products`);
75
+ if (rules !== undefined && (!Array.isArray(rules) || !rules.every(isRuleDescriptor)
76
+ || new Set(rules.map(rule => rule.id)).size !== rules.length))
77
+ throw new Error(`Invalid or duplicate rules for plugin ${id}`);
78
+ if (config !== undefined && typeof config !== 'boolean' && !isRecord(config))
79
+ throw new Error(`Invalid configuration schema for plugin ${id}`);
80
+ return { id, produces, rules };
81
+ }
82
82
  function validLanguages(values) {
83
83
  if (!Array.isArray(values) || values.length === 0)
84
84
  return false;
@@ -87,7 +87,7 @@ function validLanguages(values) {
87
87
  if (!isRecord(value) || !isLanguageDisplay(value) || ids.has(value.id))
88
88
  return false;
89
89
  const { extensions, globs } = value;
90
- if (extensions !== undefined && (!strings(extensions) || extensions.some(extension => !/^\.[\w-]+$/.test(extension))))
90
+ if (extensions !== undefined && (!strings(extensions) || !extensions.every(isExtension)))
91
91
  return false;
92
92
  if (globs !== undefined && !strings(globs))
93
93
  return false;
@@ -114,6 +114,9 @@ export function isMetricDescriptor(value) {
114
114
  && value.bands.every((limit, index, array) => typeof limit === 'number' && Number.isFinite(limit)
115
115
  && (index === 0 || limit > array[index - 1]))));
116
116
  }
117
+ function isExtension(value) {
118
+ return /^\.[\w-]+$/.test(value);
119
+ }
117
120
  function strings(value) {
118
121
  return Array.isArray(value) && value.every(text) && new Set(value).size === value.length;
119
122
  }
@@ -0,0 +1,19 @@
1
+ import type { ProvidedLanguage } from './language.js';
2
+ interface FileType extends ProvidedLanguage {
3
+ readonly names?: readonly string[];
4
+ }
5
+ export declare const javascriptType: {
6
+ readonly id: 'javascript';
7
+ readonly label: 'JavaScript';
8
+ readonly color: '#f1e05a';
9
+ readonly extensions: readonly ['.js', '.mjs', '.cjs', '.jsx'];
10
+ };
11
+ export declare const typescriptType: {
12
+ readonly id: 'typescript';
13
+ readonly label: 'TypeScript';
14
+ readonly color: '#3178c6';
15
+ readonly extensions: readonly ['.ts', '.mts', '.cts', '.tsx'];
16
+ };
17
+ export declare const fileTypes: readonly FileType[];
18
+ export declare function fileTypeId(path: string, fallback?: string): string;
19
+ export {};
@@ -0,0 +1,39 @@
1
+ import { posix } from 'node:path';
2
+ export const javascriptType = { id: 'javascript', label: 'JavaScript', color: '#f1e05a', extensions: ['.js', '.mjs', '.cjs', '.jsx'] };
3
+ export const typescriptType = { id: 'typescript', label: 'TypeScript', color: '#3178c6', extensions: ['.ts', '.mts', '.cts', '.tsx'] };
4
+ export const fileTypes = [
5
+ javascriptType, typescriptType,
6
+ { id: 'markdown', label: 'Markdown', color: '#768390', extensions: ['.md', '.mdx', '.markdown'] },
7
+ { id: 'yaml', label: 'YAML', color: '#c47d84', extensions: ['.yaml', '.yml'] },
8
+ { id: 'json', label: 'JSON', color: '#9b86b5', extensions: ['.json'] },
9
+ { id: 'css', label: 'CSS', color: '#663399', extensions: ['.css'] },
10
+ { id: 'scss', label: 'SCSS', color: '#c6538c', extensions: ['.scss'] },
11
+ { id: 'less', label: 'Less', color: '#1d365d', extensions: ['.less'] },
12
+ { id: 'html', label: 'HTML', color: '#e34c26', extensions: ['.html', '.htm'] },
13
+ { id: 'shell', label: 'Shell', color: '#89e051', extensions: ['.sh', '.bash'], names: ['.bashrc', '.bash_profile'] },
14
+ { id: 'dockerfile', label: 'Dockerfile', color: '#4f9a94', names: ['dockerfile', 'containerfile'], extensions: ['.dockerfile'] },
15
+ { id: 'python', label: 'Python', color: '#3572a5', extensions: ['.py'] },
16
+ { id: 'go', label: 'Go', color: '#00add8', extensions: ['.go'] },
17
+ { id: 'rust', label: 'Rust', color: '#dea584', extensions: ['.rs'] },
18
+ { id: 'java', label: 'Java', color: '#b07219', extensions: ['.java'] },
19
+ { id: 'kotlin', label: 'Kotlin', color: '#a97bff', extensions: ['.kt', '.kts'] },
20
+ { id: 'ruby', label: 'Ruby', color: '#701516', extensions: ['.rb'] },
21
+ { id: 'php', label: 'PHP', color: '#4f5d95', extensions: ['.php'] },
22
+ { id: 'c-sharp', label: 'C#', color: '#178600', extensions: ['.cs'] },
23
+ { id: 'c', label: 'C', color: '#555555', extensions: ['.c', '.h'] },
24
+ { id: 'cpp', label: 'C++', color: '#f34b7d', extensions: ['.cc', '.cpp', '.cxx', '.hpp', '.hh'] },
25
+ { id: 'swift', label: 'Swift', color: '#f05138', extensions: ['.swift'] },
26
+ { id: 'scala', label: 'Scala', color: '#c22d40', extensions: ['.scala'] },
27
+ { id: 'vue', label: 'Vue', color: '#41b883', extensions: ['.vue'] },
28
+ { id: 'svelte', label: 'Svelte', color: '#ff3e00', extensions: ['.svelte'] },
29
+ { id: 'text', label: 'Plain text', color: '#7b8794', extensions: ['.txt'] },
30
+ ];
31
+ const extensions = new Map(fileTypes.flatMap(({ id, extensions }) => extensions?.map(ext => [ext, id]) ?? []));
32
+ const names = new Map(fileTypes.flatMap(({ id, names }) => names?.map(name => [name, id]) ?? []));
33
+ export function fileTypeId(path, fallback) {
34
+ const name = posix.basename(path).toLowerCase();
35
+ const extension = posix.extname(name);
36
+ return names.get(name) ?? names.get(name.split('.', 1)[0]) ?? extensions.get(extension)
37
+ ?? fallback ?? (extension.slice(1) || 'other');
38
+ }
39
+ //# sourceMappingURL=file-types.js.map
@@ -3,6 +3,10 @@ export interface LanguageDisplay {
3
3
  readonly label: string;
4
4
  readonly color?: string;
5
5
  }
6
+ export interface LanguageLookup {
7
+ readonly catalog: readonly LanguageDisplay[];
8
+ id(path: string): string;
9
+ }
6
10
  export interface ProvidedLanguage extends LanguageDisplay {
7
11
  readonly extensions?: readonly string[];
8
12
  readonly globs?: readonly string[];
@@ -37,3 +37,5 @@ export interface Report {
37
37
  readonly pluginData?: PluginData;
38
38
  }
39
39
  export declare function validSubjectId(kind: Subject['kind'], id: string): boolean;
40
+ export declare const legacySyntaxPlugin = "babel-syntax";
41
+ export declare function historicalPluginTools(plugins: unknown): unknown;
@@ -1,4 +1,24 @@
1
+ import { isRecord } from './plugin-data.js';
1
2
  export const reportSchema = 'urn:repometry:schema:report:2';
2
3
  export function validSubjectId(kind, id) {
3
4
  return /^[a-f0-9]{64}$/.test(id) || (kind === 'commit' && /^[a-f0-9]{40}$/.test(id));
4
5
  }
6
+ export const legacySyntaxPlugin = 'babel-syntax';
7
+ // Keep history comparable when the parser starts recording its own tool versions.
8
+ export function historicalPluginTools(plugins) {
9
+ if (!Array.isArray(plugins))
10
+ return plugins;
11
+ const syntax = plugins.find(entry => isRecord(entry) && entry.id === legacySyntaxPlugin);
12
+ if (!isRecord(syntax?.tools))
13
+ return plugins;
14
+ const { '@babel/types': types, ...native } = syntax.tools;
15
+ if (typeof types !== 'string')
16
+ return plugins;
17
+ return plugins.map(entry => {
18
+ if (entry === syntax)
19
+ return { ...syntax, tools: native };
20
+ if (!isRecord(entry) || (entry.id !== 'structure' && entry.id !== 'maintainability') || !isRecord(entry.tools))
21
+ return entry;
22
+ return { ...entry, tools: { '@babel/types': types, ...entry.tools } };
23
+ });
24
+ }
@@ -1,6 +1,7 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
2
  import { isRecord } from '../engine/plugin.js';
3
3
  import { canonicalMetricId, definitions } from '../model/measurement.js';
4
+ import { historicalPluginTools, legacySyntaxPlugin } from '../model/report.js';
4
5
  import { comparePaths } from '../model/snapshot.js';
5
6
  import { comparisonSchema } from '../model/comparison.js';
6
7
  export { comparisonSchema } from '../model/comparison.js';
@@ -92,8 +93,6 @@ function hasDiagnostic(report, ...operations) {
92
93
  }
93
94
  function hasParserDiagnostic(report) {
94
95
  const references = parserReferences(report);
95
- if (references.size === 0)
96
- return hasDiagnostic(report, 'babel-syntax/parse');
97
96
  const operations = new Set(references.values());
98
97
  return report.diagnostics.some(({ path, operation }) => path === undefined
99
98
  ? operations.has(operation) : references.get(path) === operation);
@@ -162,12 +161,12 @@ function structureMethod(report, operation) {
162
161
  return null;
163
162
  const providerBindings = recordedEntries(operations, 'key', [...providerKeys].sort(comparePaths));
164
163
  const pluginIds = [...new Set([operation, ...providerKeys].map(key => key.slice(0, key.indexOf('/'))))].sort(comparePaths);
165
- const toolchain = recordedEntries(plugins, 'id', pluginIds);
164
+ const toolchain = recordedEntries(historicalPluginTools(plugins), 'id', pluginIds);
166
165
  if (!providerBindings || !toolchain)
167
166
  return null;
168
167
  // The original reports carried the Babel configuration at report level.
169
168
  const configured = toolchain.map(({ id, version, api, tools, settings }) => ({
170
- id, version, api, tools, settings: id === 'babel-syntax' && isRecord(parser) ? parser : settings ?? null,
169
+ id, version, api, tools, settings: id === legacySyntaxPlugin && isRecord(parser) ? parser : settings ?? null,
171
170
  }));
172
171
  return { toolchain: configured, bindings: [...providerBindings, ...bindings.sort((a, b) => comparePaths(JSON.stringify(a), JSON.stringify(b)))] };
173
172
  }
@@ -17,8 +17,9 @@ export { compareInspections as compare } from './core/usecases/compare.js';
17
17
  export { measureDiffCoverage as diffCoverage } from './compose/diff-coverage.js';
18
18
  export { review } from './compose/review.js';
19
19
  export type { InspectionComparison } from './core/usecases/compare.js';
20
- export { fileMetrics, fileMetricsSchema } from './report/json/projections/file-metrics.js';
21
- export type { FileMetricsReport } from './report/json/projections/file-metrics.js';
20
+ export { fileMetrics } from './report/json/projections/file-metrics.js';
21
+ export { fileMetricsSchema } from './report/json/wire/file-metrics-model.js';
22
+ export type { FileMetricsReport } from './report/json/wire/file-metrics-model.js';
22
23
  export { LocalReportStore } from './report/json/store/local-store.js';
23
24
  export { GitReportReader } from './api/git/git-reader.js';
24
25
  export { readReport, reportSchema } from './report/json/validation/report.js';
@@ -8,7 +8,8 @@ export { compareInspections, comparisonSchema } from './core/usecases/compare.js
8
8
  export { compareInspections as compare } from './core/usecases/compare.js';
9
9
  export { measureDiffCoverage as diffCoverage } from './compose/diff-coverage.js';
10
10
  export { review } from './compose/review.js';
11
- export { fileMetrics, fileMetricsSchema } from './report/json/projections/file-metrics.js';
11
+ export { fileMetrics } from './report/json/projections/file-metrics.js';
12
+ export { fileMetricsSchema } from './report/json/wire/file-metrics-model.js';
12
13
  export { LocalReportStore } from './report/json/store/local-store.js';
13
14
  export { GitReportReader } from './api/git/git-reader.js';
14
15
  export { readReport, reportSchema } from './report/json/validation/report.js';