repometry 0.6.2 → 0.7.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 (91) hide show
  1. package/package.json +1 -1
  2. package/target/main/resources/config/process-plugins-v1.schema.json +75 -0
  3. package/target/main/resources/report/json/report-v2.schema.json +21 -1
  4. package/target/main/resources/report/json/repository-summary-v1.schema.json +9 -0
  5. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +11 -3
  6. package/target/main/resources/viewer/files.css +6 -0
  7. package/target/main/resources/viewer/index.html +1 -1
  8. package/target/main/resources/viewer/styles.css +1 -0
  9. package/target/main/ts/cli/config.d.ts +1 -0
  10. package/target/main/ts/cli/config.js +3 -2
  11. package/target/main/ts/cli/main.js +37 -19
  12. package/target/main/ts/cli/reporting.js +3 -3
  13. package/target/main/ts/compose/analysis-files.d.ts +1 -0
  14. package/target/main/ts/compose/analysis-files.js +27 -7
  15. package/target/main/ts/compose/analysis-imports.js +2 -1
  16. package/target/main/ts/compose/analysis-report.js +7 -3
  17. package/target/main/ts/compose/analysis-results.d.ts +4 -1
  18. package/target/main/ts/compose/analysis-results.js +3 -0
  19. package/target/main/ts/compose/analysis-sources.js +2 -1
  20. package/target/main/ts/compose/languages.js +4 -1
  21. package/target/main/ts/compose/plugin-list.d.ts +11 -2
  22. package/target/main/ts/compose/plugin-list.js +4 -1
  23. package/target/main/ts/compose/process-plugins.d.ts +2 -0
  24. package/target/main/ts/compose/process-plugins.js +63 -0
  25. package/target/main/ts/compose/structure-measures.d.ts +5 -0
  26. package/target/main/ts/compose/structure-measures.js +57 -0
  27. package/target/main/ts/core/engine/manifest.js +5 -1
  28. package/target/main/ts/core/model/clone-source.js +0 -1
  29. package/target/main/ts/core/model/code-structure.d.ts +14 -9
  30. package/target/main/ts/core/model/code-structure.js +23 -10
  31. package/target/main/ts/core/model/language.d.ts +2 -0
  32. package/target/main/ts/core/model/plugin-data.d.ts +2 -0
  33. package/target/main/ts/core/model/quality-summary.d.ts +4 -0
  34. package/target/main/ts/core/model/quality-summary.js +53 -29
  35. package/target/main/ts/core/model/report.d.ts +6 -0
  36. package/target/main/ts/plugin.d.ts +1 -1
  37. package/target/main/ts/plugins/coverage/coverage.d.ts +2 -1
  38. package/target/main/ts/plugins/coverage/coverage.js +40 -30
  39. package/target/main/ts/plugins/language-js/function-facts.d.ts +1 -1
  40. package/target/main/ts/plugins/language-js/function-facts.js +0 -1
  41. package/target/main/ts/plugins/language-js/js-security.js +25 -37
  42. package/target/main/ts/plugins/language-js/structural-observations.js +5 -4
  43. package/target/main/ts/plugins/maintainability/maintainability.d.ts +1 -1
  44. package/target/main/ts/plugins/maintainability/maintainability.js +9 -8
  45. package/target/main/ts/plugins/security/dockerfile.js +45 -37
  46. package/target/main/ts/plugins/structure/structure.js +2 -2
  47. package/target/main/ts/report/html/app/viewer-code-map.js +6 -5
  48. package/target/main/ts/report/html/app/viewer-columns.d.ts +2 -0
  49. package/target/main/ts/report/html/app/viewer-columns.js +9 -4
  50. package/target/main/ts/report/html/app/viewer-data.d.ts +2 -1
  51. package/target/main/ts/report/html/app/viewer-data.js +1 -1
  52. package/target/main/ts/report/html/app/viewer-file-aside.d.ts +5 -9
  53. package/target/main/ts/report/html/app/viewer-file-aside.js +18 -8
  54. package/target/main/ts/report/html/app/viewer-file-figures.d.ts +2 -0
  55. package/target/main/ts/report/html/app/viewer-file-figures.js +6 -1
  56. package/target/main/ts/report/html/app/viewer-hotspots.js +7 -5
  57. package/target/main/ts/report/html/app/viewer-inspection.js +1 -1
  58. package/target/main/ts/report/html/app/viewer-issue-group.js +2 -2
  59. package/target/main/ts/report/html/app/viewer-languages.d.ts +3 -2
  60. package/target/main/ts/report/html/app/viewer-languages.js +14 -7
  61. package/target/main/ts/report/html/app/viewer-line-coverage.d.ts +4 -4
  62. package/target/main/ts/report/html/app/viewer-line-coverage.js +11 -24
  63. package/target/main/ts/report/html/app/viewer-map-scale.d.ts +1 -1
  64. package/target/main/ts/report/html/app/viewer-map-scale.js +1 -1
  65. package/target/main/ts/report/html/app/viewer-map-shape.d.ts +2 -2
  66. package/target/main/ts/report/html/app/viewer-metric-registry.d.ts +0 -3
  67. package/target/main/ts/report/html/app/viewer-metric-registry.js +0 -9
  68. package/target/main/ts/report/html/app/viewer-metrics-view.js +1 -4
  69. package/target/main/ts/report/html/app/viewer-metrics.d.ts +2 -0
  70. package/target/main/ts/report/html/app/viewer-metrics.js +5 -0
  71. package/target/main/ts/report/html/app/viewer-overview-cards.js +4 -1
  72. package/target/main/ts/report/html/app/viewer-overview-hotspots.js +2 -2
  73. package/target/main/ts/report/html/app/viewer-profile.js +15 -1
  74. package/target/main/ts/report/html/app/viewer-source-view.js +7 -6
  75. package/target/main/ts/report/html/app/viewer-table-cells.js +8 -2
  76. package/target/main/ts/report/html/app/viewer-table-rows.d.ts +2 -0
  77. package/target/main/ts/report/html/app/viewer-table-rows.js +7 -5
  78. package/target/main/ts/report/html/app/viewer-tokenizer.d.ts +2 -5
  79. package/target/main/ts/report/html/app/viewer-tokenizer.js +9 -12
  80. package/target/main/ts/report/html/app/viewer-totals.d.ts +6 -0
  81. package/target/main/ts/report/html/app/viewer-totals.js +11 -0
  82. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +1 -1
  83. package/target/main/ts/report/html/app/viewer-trend-data.js +1 -1
  84. package/target/main/ts/report/html/app/viewer-trend-nav.js +3 -2
  85. package/target/main/ts/report/html/app/viewer.js +1 -7
  86. package/target/main/ts/report/json/projections/commit-summary.js +5 -0
  87. package/target/main/ts/report/json/projections/file-metrics.js +20 -4
  88. package/target/main/ts/report/json/projections/inspection-details.js +32 -14
  89. package/target/main/ts/report/json/projections/metric-values.d.ts +1 -0
  90. package/target/main/ts/report/json/projections/metric-values.js +36 -3
  91. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +8 -1
@@ -154,7 +154,7 @@ function scan(path, ast) {
154
154
  }
155
155
  return;
156
156
  }
157
- const imported = resolve(target);
157
+ const imported = resolveImport(target, bindings);
158
158
  if (imported?.module === 'child_process' && shellCalls.has(imported.name)) {
159
159
  if (first !== undefined && isBuiltString(first)) {
160
160
  report('child-process-injection', node, `${imported.name}() passes a command built from interpolated values to a shell, `
@@ -173,7 +173,7 @@ function scan(path, ast) {
173
173
  inspectFunctionConstructor(args, node);
174
174
  return;
175
175
  }
176
- const imported = resolve(target);
176
+ const imported = resolveImport(target, bindings);
177
177
  const [code] = args;
178
178
  if (imported?.module === 'vm' && imported.name === 'Script' && code !== undefined && !isStatic(code)) {
179
179
  report('vm-code-execution', node, 'new vm.Script() compiles code that is not a literal, and the vm module '
@@ -216,16 +216,6 @@ function scan(path, ast) {
216
216
  return;
217
217
  report('http-url', node, `The plain HTTP URL to ${host} sends data unencrypted, so it can be read or altered in transit; use https.`);
218
218
  }
219
- function resolve(node) {
220
- if (node.type === 'Identifier')
221
- return bindings.named.get(node.name);
222
- const name = memberName(node);
223
- if (name === undefined || (node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression'))
224
- return undefined;
225
- const object = unwrap(node.object);
226
- const module = object.type === 'Identifier' ? bindings.namespaces.get(object.name) : requiredModule(object);
227
- return module === undefined ? undefined : { module, name };
228
- }
229
219
  function report(rule, node, message) {
230
220
  const line = node.loc?.start.line ?? 1;
231
221
  findings.push({ tool: 'js-security', rule, category: 'security', level: catalog[rule].level, message, path,
@@ -281,31 +271,29 @@ function bindDeclarator(id, init, bindings) {
281
271
  }
282
272
  if (id.type !== 'Identifier')
283
273
  return;
284
- // const exec = require('child_process').exec; const run = promisify(exec);
285
- const member = memberName(init);
286
- if (member !== undefined && (init.type === 'MemberExpression' || init.type === 'OptionalMemberExpression')) {
287
- const object = unwrap(init.object);
288
- const owner = object.type === 'Identifier' ? bindings.namespaces.get(object.name) : requiredModule(object);
289
- if (owner !== undefined)
290
- bindings.named.set(id.name, { module: owner, name: member });
291
- return;
292
- }
293
- if (init.type === 'CallExpression' && init.arguments[0] !== undefined) {
294
- const callee = unwrap(init.callee);
295
- if ((callee.type === 'Identifier' && callee.name === 'promisify') || memberName(callee) === 'promisify') {
296
- const wrapped = unwrap(init.arguments[0]);
297
- const original = wrapped.type === 'Identifier' ? bindings.named.get(wrapped.name) : undefined;
298
- if (original !== undefined)
299
- bindings.named.set(id.name, original);
300
- else if (wrapped.type === 'MemberExpression') {
301
- const object = unwrap(wrapped.object);
302
- const owner = object.type === 'Identifier' ? bindings.namespaces.get(object.name) : requiredModule(object);
303
- const name = memberName(wrapped);
304
- if (owner !== undefined && name !== undefined)
305
- bindings.named.set(id.name, { module: owner, name });
306
- }
307
- }
308
- }
274
+ const imported = init.type === 'CallExpression' ? resolvePromisified(init, bindings)
275
+ : init.type === 'Identifier' ? undefined : resolveImport(init, bindings);
276
+ if (imported)
277
+ bindings.named.set(id.name, imported);
278
+ }
279
+ function resolvePromisified(call, bindings) {
280
+ const [argument] = call.arguments;
281
+ const callee = unwrap(call.callee);
282
+ const name = callee.type === 'Identifier' ? callee.name : memberName(callee);
283
+ if (argument === undefined || name !== 'promisify')
284
+ return undefined;
285
+ const target = unwrap(argument);
286
+ return target.type === 'OptionalMemberExpression' ? undefined : resolveImport(target, bindings);
287
+ }
288
+ function resolveImport(node, bindings) {
289
+ if (node.type === 'Identifier')
290
+ return bindings.named.get(node.name);
291
+ const name = memberName(node);
292
+ if (name === undefined || (node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression'))
293
+ return undefined;
294
+ const object = unwrap(node.object);
295
+ const module = object.type === 'Identifier' ? bindings.namespaces.get(object.name) : requiredModule(object);
296
+ return module === undefined ? undefined : { module, name };
309
297
  }
310
298
  /** The tracked module that `require('x')` or `await import('x')` loads, if any. */
311
299
  function requiredModule(node) {
@@ -28,12 +28,13 @@ export function structuralObservations(ast) {
28
28
  const start = node.loc?.start;
29
29
  cognitiveFunctions.push({ line: start?.line,
30
30
  column: start === undefined ? undefined : start.column + 1, name, value: own.cognitive });
31
+ const label = name ?? '(anonymous)';
31
32
  cognitive += own.cognitive;
32
- observe('function-parameters', node.params.length, `${name} · Parameters`, node);
33
- observe('return-statements', own.returns, `${name} · Return statements`, node);
34
- observe('function-complexity', own.cognitive, `${name} · Cognitive complexity`, node);
33
+ observe('function-parameters', node.params.length, `${label} · Parameters`, node);
34
+ observe('return-statements', own.returns, `${label} · Return statements`, node);
35
+ observe('function-complexity', own.cognitive, `${label} · Cognitive complexity`, node);
35
36
  if (own.nestedRange !== undefined)
36
- observe('nested-control-flow', own.maxNesting, `${name} · Control-flow depth`, own.nestedRange);
37
+ observe('nested-control-flow', own.maxNesting, `${label} · Control-flow depth`, own.nestedRange);
37
38
  return;
38
39
  }
39
40
  if (node.type === 'ReturnStatement')
@@ -2,7 +2,7 @@ import type { DataContract, Plugin } from '../../core/engine/plugin.js';
2
2
  import type { CloneSource } from '../../core/model/clone-source.js';
3
3
  import type { FindingResult } from '../../core/model/finding.js';
4
4
  interface FileQuality extends FindingResult {
5
- readonly cloneSource: CloneSource;
5
+ readonly cloneSource?: CloneSource;
6
6
  }
7
7
  export declare const fileQuality: DataContract<FileQuality>;
8
8
  export declare const maintainability: Plugin;
@@ -1,6 +1,6 @@
1
1
  import { isRecord, pluginApi } from '../../core/engine/plugin.js';
2
2
  import { isCloneSource } from '../../core/model/clone-source.js';
3
- import { codeStructure } from '../../core/model/code-structure.js';
3
+ import { codeStructure, structureCodeLines } from '../../core/model/code-structure.js';
4
4
  import { findingResult } from '../../core/model/finding.js';
5
5
  import { definitions } from '../../core/model/measurement.js';
6
6
  import { sourceFile } from '../../core/model/snapshot.js';
@@ -8,7 +8,7 @@ import { structuralRules } from '../../core/profile/maintainability.js';
8
8
  import { structuralSmells } from './structural-smells.js';
9
9
  export const fileQuality = {
10
10
  id: 'repometry.maintainability-file/v1',
11
- accepts: (value) => isRecord(value) && isCloneSource(value.cloneSource) && findingResult.accepts(value),
11
+ accepts: (value) => isRecord(value) && (value.cloneSource === undefined || isCloneSource(value.cloneSource)) && findingResult.accepts(value),
12
12
  };
13
13
  export const maintainability = {
14
14
  id: 'maintainability', version: '1.0.0', api: pluginApi,
@@ -25,17 +25,18 @@ export const maintainability = {
25
25
  operations: [{
26
26
  id: 'file', role: 'inspection', inputs: { syntax: codeStructure, source: sourceFile }, output: fileQuality,
27
27
  execute(inputs) {
28
- const { path, observations, cognitiveFunctions, cognitiveComplexity, classes, commentLines, clones } = inputs.read('syntax', codeStructure);
28
+ const facts = inputs.read('syntax', codeStructure);
29
+ const { path, observations = [], cognitiveFunctions = [], cognitiveComplexity, classes, commentLines, clones } = facts;
30
+ const codeLines = structureCodeLines(facts);
31
+ const counts = [[definitions.cognitiveComplexity, cognitiveComplexity], [definitions.classes, classes],
32
+ [definitions.codeLines, codeLines?.length], [definitions.comments, commentLines]];
29
33
  return {
30
34
  findings: structuralSmells(path, observations),
31
35
  measurements: [
32
36
  ...cognitiveFunctions.map(({ line, column, name, value }) => ({ definition: definitions.cognitiveComplexity, target: 'function', path, line, column, name, value })),
33
- { definition: definitions.cognitiveComplexity, target: 'file', path, value: cognitiveComplexity },
34
- { definition: definitions.classes, target: 'file', path, value: classes },
35
- { definition: definitions.codeLines, target: 'file', path, value: clones.codeLines.length },
36
- { definition: definitions.comments, target: 'file', path, value: commentLines },
37
+ ...counts.flatMap(([definition, value]) => value === undefined ? [] : [{ definition, target: 'file', path, value }]),
37
38
  ],
38
- cloneSource: clones,
39
+ ...(clones === undefined ? {} : { cloneSource: clones }),
39
40
  };
40
41
  },
41
42
  }],
@@ -59,22 +59,7 @@ function scan(path, text) {
59
59
  for (const instruction of instructions) {
60
60
  const { keyword } = instruction;
61
61
  if (keyword === 'FROM') {
62
- const [reference = '', as, name] = words(instruction.args, escape).filter(item => !item.startsWith('--'));
63
- const image = expand(reference, globals);
64
- const parent = names.get((image ?? reference).toLowerCase());
65
- const external = parent === undefined && image !== undefined && image.toLowerCase() !== 'scratch';
66
- if (external) {
67
- const pinning = pinningOf(image);
68
- if (pinning === 'none') {
69
- report('unpinned-base-image', instruction, `Base image ${image} has no tag or digest, so every build pulls whatever latest points to; pin a version tag or a digest.`);
70
- }
71
- else if (pinning === 'latest') {
72
- report('unpinned-base-image', instruction, `Base image ${image} uses the mutable latest tag; pin a version tag or a digest.`);
73
- }
74
- }
75
- stages.push({ from: instruction, image: parent === undefined ? image : undefined, parent, users: [] });
76
- if (as?.toUpperCase() === 'AS' && name)
77
- names.set(name.toLowerCase(), stages.length - 1);
62
+ startStage(instruction);
78
63
  }
79
64
  else if (keyword === 'USER') {
80
65
  stages.at(-1)?.users.push(instruction);
@@ -96,34 +81,57 @@ function scan(path, text) {
96
81
  }
97
82
  }
98
83
  else if (keyword === 'RUN') {
99
- const script = runScript(instruction);
100
- const commands = pipelines(script);
101
- if (substitutedDownload.test(script) || commands.some(pipesDownloadToShell)) {
102
- report('pipe-to-shell', instruction, 'RUN pipes a curl or wget download straight into a shell; download to a file and verify its checksum before running it.');
103
- }
104
- if (commands.flat().some(upgradesAllPackages)) {
105
- report('apt-unpinned-upgrade', instruction, 'RUN upgrades every installed package with apt, which makes the build unreproducible; use a newer base image or pin packages.');
84
+ checkRun(instruction);
85
+ }
86
+ }
87
+ checkFinalStage();
88
+ return findings.sort((left, right) => left.line - right.line || left.endLine - right.endLine
89
+ || left.rule.localeCompare(right.rule));
90
+ function startStage(instruction) {
91
+ const [reference = '', as, name] = words(instruction.args, escape).filter(item => !item.startsWith('--'));
92
+ const image = expand(reference, globals);
93
+ const parent = names.get((image ?? reference).toLowerCase());
94
+ if (parent === undefined && image !== undefined && image.toLowerCase() !== 'scratch') {
95
+ const pinning = pinningOf(image);
96
+ if (pinning === 'none') {
97
+ report('unpinned-base-image', instruction, `Base image ${image} has no tag or digest, so every build pulls whatever latest points to; pin a version tag or a digest.`);
106
98
  }
107
- if (commands.flat().some(item => command(item).sudo)) {
108
- report('sudo-usage', instruction, 'RUN uses sudo, which behaves unpredictably in containers; run the step before switching USER or use gosu instead.');
99
+ else if (pinning === 'latest') {
100
+ report('unpinned-base-image', instruction, `Base image ${image} uses the mutable latest tag; pin a version tag or a digest.`);
109
101
  }
110
102
  }
103
+ stages.push({ from: instruction, image: parent === undefined ? image : undefined, parent, users: [] });
104
+ if (as?.toUpperCase() === 'AS' && name)
105
+ names.set(name.toLowerCase(), stages.length - 1);
111
106
  }
112
- const final = stages.length - 1;
113
- if (final >= 0) {
114
- const { user, image } = effectiveUser(stages, final);
115
- if (user !== undefined) {
116
- const account = (words(user.args, escape)[0] ?? '').split(':')[0];
117
- if (account === 'root' || account === '0') {
118
- report('runs-as-root', user, 'The final stage runs as root because its last USER is root; switch to an unprivileged user.');
119
- }
107
+ function checkRun(instruction) {
108
+ const script = runScript(instruction);
109
+ const commands = pipelines(script);
110
+ const steps = commands.flat();
111
+ if (substitutedDownload.test(script) || commands.some(pipesDownloadToShell)) {
112
+ report('pipe-to-shell', instruction, 'RUN pipes a curl or wget download straight into a shell; download to a file and verify its checksum before running it.');
120
113
  }
121
- else if (image === undefined || !/nonroot/i.test(image)) {
122
- report('runs-as-root', stages[final].from, 'The final stage never sets USER, so the container runs as root; add a USER with an unprivileged account.');
114
+ if (steps.some(upgradesAllPackages)) {
115
+ report('apt-unpinned-upgrade', instruction, 'RUN upgrades every installed package with apt, which makes the build unreproducible; use a newer base image or pin packages.');
116
+ }
117
+ if (steps.some(item => command(item).sudo)) {
118
+ report('sudo-usage', instruction, 'RUN uses sudo, which behaves unpredictably in containers; run the step before switching USER or use gosu instead.');
123
119
  }
124
120
  }
125
- return findings.sort((left, right) => left.line - right.line || left.endLine - right.endLine
126
- || left.rule.localeCompare(right.rule));
121
+ function checkFinalStage() {
122
+ const final = stages.at(-1);
123
+ if (final === undefined)
124
+ return;
125
+ const { user, image } = effectiveUser(stages, stages.length - 1);
126
+ if (user === undefined) {
127
+ if (image === undefined || !/nonroot/i.test(image))
128
+ report('runs-as-root', final.from, 'The final stage never sets USER, so the container runs as root; add a USER with an unprivileged account.');
129
+ return;
130
+ }
131
+ const account = (words(user.args, escape)[0] ?? '').split(':')[0];
132
+ if (account === 'root' || account === '0')
133
+ report('runs-as-root', user, 'The final stage runs as root because its last USER is root; switch to an unprivileged user.');
134
+ }
127
135
  }
128
136
  function parseDockerfile(text) {
129
137
  const lines = text.split(/\r\n|\r|\n/);
@@ -21,7 +21,7 @@ export const structure = {
21
21
  const { path, lines, functions } = inputs.read('syntax', codeStructure);
22
22
  return [
23
23
  { definition: definitions.lines, target: 'file', path, value: lines },
24
- { definition: definitions.functions, target: 'file', path, value: functions },
24
+ ...(functions === undefined ? [] : [{ definition: definitions.functions, target: 'file', path, value: functions }]),
25
25
  ];
26
26
  },
27
27
  }, {
@@ -30,7 +30,7 @@ export const structure = {
30
30
  inputs: { syntax: codeStructure },
31
31
  output: measurements,
32
32
  execute(inputs) {
33
- const { path, cyclomaticFunctions } = inputs.read('syntax', codeStructure);
33
+ const { path, cyclomaticFunctions = [] } = inputs.read('syntax', codeStructure);
34
34
  return cyclomaticFunctions.map(({ line, column, name, value }) => ({ definition: definitions.complexity, target: 'function', path, line, column, name, value }));
35
35
  },
36
36
  }],
@@ -16,8 +16,8 @@ function mapTree(metrics, directory, metric, useCodeLines, levels) {
16
16
  return;
17
17
  const value = hotspotScore(entry, metric);
18
18
  measured ||= value !== null;
19
- // Nothing measured is nothing to count: a file without functions has no complexity, not an unknown one.
20
- const branch = { entry, folder, area, score: levels ? levels.get(entry.path) ?? 0 : value ?? 0 };
19
+ // Security levels cover every file; any other score is unknown where the file was not measured.
20
+ const branch = { entry, folder, area, score: levels ? levels.get(entry.path) ?? 0 : value };
21
21
  const parent = parentPath(entry.path);
22
22
  const siblings = byParent.get(parent);
23
23
  if (siblings)
@@ -52,8 +52,8 @@ function shading(metrics, tree, metric, limits, levels) {
52
52
  return branch => branch.score;
53
53
  const unread = unreadFolders(metrics.files);
54
54
  const peakOf = relativePeaks([...tree.byParent.values()].flat().map(branch => ({ path: branch.entry.path, folder: branch.folder, score: branch.score })));
55
- return branch => branch.entry.analysed === false || unread.has(branch.entry.path) ? 'none'
56
- : band(branch.entry, metric, branch.score, peakOf(branch.entry.path, branch.folder), limits);
55
+ const grey = (branch) => branch.score === null || branch.entry.analysed === false || unread.has(branch.entry.path);
56
+ return branch => grey(branch) ? 'none' : band(branch.entry, metric, branch.score, peakOf(branch.entry.path, branch.folder), limits);
57
57
  }
58
58
  /** The scale runs the panel's width under the title row: the key to the whole map. */
59
59
  function mapLegend(metric, limits, levels, grey) {
@@ -151,7 +151,8 @@ export function renderSunburst(details, options) {
151
151
  // Grey marks no data: a metric this inspection did not measure at all (no coverage report) is not a map of zeros.
152
152
  const grey = options.muted === true || !tree.measured;
153
153
  panel.dataset.palette = palette(metric, security, grey);
154
- const reading = (branch) => security ? securityRisks[branch.score] : `${count(branch.score)} ${scoreLabel(metric)}`;
154
+ const reading = (branch) => security ? securityRisks[branch.score]
155
+ : branch.score === null ? 'Not measured' : `${count(branch.score)} ${scoreLabel(metric)}`;
155
156
  // What the map encodes is said to assistive technology; on screen the legend's scale carries it.
156
157
  const meaning = security ? 'Colour shows the worst security finding.' : meaningOf(metric);
157
158
  const description = `${shape === 'tiles' ? 'Tile' : 'Wedge'} size shows ${units}. ${meaning}`;
@@ -13,6 +13,8 @@ export interface MetricColumn {
13
13
  defaultVisible?(directory: Directory | undefined, scope: ColumnScope): boolean;
14
14
  /** The first click sorts this way: worst first. Repometry's own columns open descending. */
15
15
  readonly ascending?: boolean;
16
+ /** Whether a file carries the measure, so a total over files that do not all carry it reads as partial. */
17
+ present?(entry: Metrics): boolean;
16
18
  }
17
19
  export type Columns = readonly [MetricColumn, ...MetricColumn[]];
18
20
  /**
@@ -7,7 +7,7 @@ import { firstSortAscending, format } from './viewer-metric-format.js';
7
7
  import { labelOf, pluginMetrics, size } from './viewer-metrics.js';
8
8
  /** A column of counts, shown with a dash where the file has none. */
9
9
  function counted(label, read, extra = {}) {
10
- return { label, value: entry => read(entry) ?? null, display: entry => count(read(entry)), ...extra };
10
+ return { label, value: entry => read(entry) ?? null, display: entry => count(read(entry)), present: entry => read(entry) != null, ...extra };
11
11
  }
12
12
  /** Offered where the folder's totals have this quality measure. */
13
13
  function hasQuality(key) {
@@ -23,12 +23,15 @@ const builtinColumns = [
23
23
  { label: 'Size', value: entry => entry.bytes ?? null, display: entry => size(entry.bytes),
24
24
  available: directory => directory?.bytes !== undefined, defaultVisible: (_, scope) => scope.sized },
25
25
  counted('Functions', entry => entry.functions, { defaultVisible: hidden }),
26
- counted(labelOf('complexity'), entry => entry.complexity?.maximum),
26
+ // A file measured without functions has no peak, and is measured all the same.
27
+ counted(labelOf('complexity'), entry => entry.complexity?.maximum, { present: entry => entry.complexity != null }),
27
28
  counted(labelOf('cognitive'), entry => entry.quality?.cognitiveComplexity, { available: hasQuality('cognitiveComplexity') }),
28
29
  { label: labelOf('coverage'), value: coverageRatio, display: coverageText, available: directory => !directory || coverageRatio(directory) !== null },
29
- { label: 'Duplication', value: duplicationRatio, display: duplicationText, available: hasQuality('duplication') },
30
+ { label: 'Duplication', value: duplicationRatio, display: duplicationText, available: hasQuality('duplication'),
31
+ present: entry => entry.quality?.duplication !== undefined },
30
32
  { label: labelOf('effort'), value: entry => entry.quality?.maintainability?.effortMinutes ?? null,
31
- display: entry => effortText(entry.quality?.maintainability?.effortMinutes), available: hasQuality('maintainability') },
33
+ display: entry => effortText(entry.quality?.maintainability?.effortMinutes), available: hasQuality('maintainability'),
34
+ present: entry => entry.quality?.maintainability !== undefined },
32
35
  counted('Git changes', entry => entry.quality?.churn, { available: hasQuality('churn'), defaultVisible: hidden }),
33
36
  counted('Diagnostics', entry => entry.diagnosticCount, { defaultVisible: hidden }),
34
37
  ];
@@ -41,6 +44,8 @@ function pluginColumns(specs) {
41
44
  available: () => measured(spec.descriptor),
42
45
  defaultVisible: () => spec.column,
43
46
  ascending: firstSortAscending(spec),
47
+ // A ratio is no sum: a file without branches has no branch coverage, and the folder's ratio is complete.
48
+ ...spec.descriptor.unit === 'ratio' ? {} : { present: (entry) => localValue(entry, spec) !== null },
44
49
  }));
45
50
  }
46
51
  /**
@@ -8,7 +8,8 @@ export interface ViewerData {
8
8
  readonly quality: QualityHistory['reports'];
9
9
  readonly context: Record<string, InspectionContext>;
10
10
  readonly counts: Record<string, InspectionCounts | undefined>;
11
- readonly pullReviewCount?: number;
11
+ /** How many pull request reviews are saved; the summary counts them, so no page loads them to find out. */
12
+ readonly pullReviewCount: number;
12
13
  /** The branch whose first-parent history the commits are, when the configuration names it. */
13
14
  readonly branch?: string;
14
15
  /** The metrics the history's plugins declare; each commit's values are indexed by it. */
@@ -20,7 +20,7 @@ export async function loadViewerData(mode) {
20
20
  exclusions: null, boundary: commit.profileBoundary ?? null, security: commit.counts?.security,
21
21
  }])),
22
22
  counts,
23
- pullReviewCount: summary.pullReviewCount,
23
+ pullReviewCount: summary.pullReviewCount ?? 0,
24
24
  ...(Array.isArray(summary.metrics) ? { metrics: summary.metrics } : {}),
25
25
  ...(() => {
26
26
  const sources = sourceLocator(summary.sources);
@@ -1,14 +1,10 @@
1
1
  import type { InspectionDetails } from '../../json/wire/inspection-details-model.js';
2
2
  import type { Directory, Metrics, Navigation } from './viewer-inspection.js';
3
- export interface SelectionCounts {
4
- /** Files a plugin read, and lockfiles, among the selected ones. */
5
- readonly analysed: number;
6
- readonly lockfiles: number;
7
- /** How the selection reads against its folder, where a query narrowed it. */
8
- readonly selection?: string | undefined;
9
- }
10
- /** The totals of a folder, or of the files a query selected in it. */
11
- export declare function directorySummary(entry: Directory, { analysed, lockfiles, selection }: SelectionCounts): HTMLElement;
3
+ /**
4
+ * The totals of a folder, or of the files a query selected in it, with how the selection reads against its folder. A
5
+ * total some of the files a plugin read do not carry says in how many it was measured.
6
+ */
7
+ export declare function directorySummary(entry: Directory, files: readonly Metrics[], selection?: string): HTMLElement;
12
8
  export interface SourceHooks {
13
9
  /** Brings a line of the open source into view. */
14
10
  readonly reveal?: (line: number) => void;
@@ -1,12 +1,14 @@
1
1
  import { basename, count, element, fact, link, parentPath, quantity } from './viewer-dom.js';
2
2
  import { coverageContext, coverageRatio, coverageText, duplicationContext, duplicationText, effortText } from './viewer-file-figures.js';
3
- import { lockfilesLabel } from './viewer-languages.js';
3
+ import { isLockfile, lockfilesLabel } from './viewer-languages.js';
4
+ import { tableColumns } from './viewer-columns.js';
5
+ import { partialNote } from './viewer-totals.js';
4
6
  import { coverageKinds, localValue, measured, measuredFileMetrics } from './viewer-inspection.js';
5
7
  import { atPath } from './viewer-locations.js';
6
8
  import { format } from './viewer-metric-format.js';
7
9
  import { labelOf, size } from './viewer-metrics.js';
8
10
  import { lineSnippet } from './viewer-source-view.js';
9
- import { highlightCode } from './viewer-tokenizer.js';
11
+ import { highlighter } from './viewer-tokenizer.js';
10
12
  /** A fact where the inspection took the measurement; a measurement it did not take leaves no row behind. */
11
13
  function factIf(shown, label, value, context) {
12
14
  return shown ? [fact(label, value, context)] : [];
@@ -18,24 +20,32 @@ function panel(label, title, className = 'fx-aside') {
18
20
  heading.append(element('h2', '', title));
19
21
  return { panel: aside, heading };
20
22
  }
21
- /** The totals of a folder, or of the files a query selected in it. */
22
- export function directorySummary(entry, { analysed, lockfiles, selection }) {
23
+ /**
24
+ * The totals of a folder, or of the files a query selected in it, with how the selection reads against its folder. A
25
+ * total some of the files a plugin read do not carry says in how many it was measured.
26
+ */
27
+ export function directorySummary(entry, files, selection) {
23
28
  const { panel: aside, heading } = panel(selection ? 'Selection totals' : 'Folder totals', selection ? 'Selection' : basename(entry.path) || 'All files');
24
29
  // The breadcrumbs above name the folder; only a selection needs its words here.
25
30
  if (selection)
26
31
  heading.append(element('p', 'fx-aside-path fx-aside-selection', selection));
27
32
  const facts = element('dl', 'fx-kv');
28
33
  const quality = entry.quality;
34
+ const analysed = files.filter(file => file.analysed !== false).length;
35
+ const lockfiles = files.filter(file => isLockfile(file.path)).length;
29
36
  const partial = analysed !== entry.files;
37
+ // A total is partial as its table column is: the column says which files carry the measure.
38
+ const presence = new Map(tableColumns().map(column => [column.label, column.present]));
39
+ const note = (label) => presence.get(label) && partialNote(files, presence.get(label));
30
40
  facts.append(
31
41
  // Every tracked file counts here; Trends counts the analysed ones, so both say which they are.
32
- fact('Tracked files', count(entry.files)), ...factIf(partial, labelOf('files'), count(analysed)), ...factIf(lockfiles > 0, lockfilesLabel, count(lockfiles)), ...factIf(quality?.codeLines !== undefined, labelOf('code-lines'), count(quality?.codeLines)),
42
+ fact('Tracked files', count(entry.files)), ...factIf(partial, labelOf('files'), count(analysed)), ...factIf(lockfiles > 0, lockfilesLabel, count(lockfiles)), ...factIf(quality?.codeLines !== undefined, labelOf('code-lines'), count(quality?.codeLines), note(labelOf('code-lines'))),
33
43
  // Physical lines are what the language bar weighs once some files are ignored, so its total stands here too.
34
- ...factIf(quality?.codeLines === undefined || partial, labelOf('lines'), count(entry.lines)), ...factIf(entry.bytes !== undefined, 'Size', size(entry.bytes)), ...factIf(entry.functions !== null, labelOf('functions'), count(entry.functions)), fact(labelOf('complexity'), count(entry.complexity?.maximum)), ...factIf(quality?.cognitiveComplexity !== undefined, labelOf('cognitive'), count(quality?.cognitiveComplexity)), ...factIf(quality?.duplication !== undefined, labelOf('duplication'), duplicationText(entry)), ...factIf(quality?.maintainability !== undefined, labelOf('effort'), effortText(quality?.maintainability?.effortMinutes)), ...factIf(coverageRatio(entry) !== null, labelOf('coverage'), coverageText(entry)),
44
+ ...factIf(quality?.codeLines === undefined || partial, labelOf('lines'), count(entry.lines)), ...factIf(entry.bytes !== undefined, 'Size', size(entry.bytes)), ...factIf(entry.functions !== null, labelOf('functions'), count(entry.functions)), fact(labelOf('complexity'), count(entry.complexity?.maximum), note(labelOf('complexity'))), ...factIf(quality?.cognitiveComplexity !== undefined, labelOf('cognitive'), count(quality?.cognitiveComplexity), note(labelOf('cognitive'))), ...factIf(quality?.duplication !== undefined, labelOf('duplication'), duplicationText(entry), note(labelOf('duplication'))), ...factIf(quality?.maintainability !== undefined, labelOf('effort'), effortText(quality?.maintainability?.effortMinutes), note(labelOf('effort'))), ...factIf(coverageRatio(entry) !== null, labelOf('coverage'), coverageText(entry)),
35
45
  // Other plugins' totals follow Repometry's own, where this inspection ran them and they roll up; the counts behind
36
46
  // a ratio read through it.
37
47
  ...measuredFileMetrics().filter(spec => spec.descriptor.aggregate !== 'none' && !spec.ratioPart)
38
- .map(spec => fact(spec.short, format(spec, localValue(entry, spec)))));
48
+ .map(spec => fact(spec.short, format(spec, localValue(entry, spec)), note(spec.short))));
39
49
  aside.append(heading, facts);
40
50
  return aside;
41
51
  }
@@ -98,7 +108,7 @@ function sourceFunctionList(functions, reveal, text) {
98
108
  button.disabled = record.line === null;
99
109
  const name = element(snippet ? 'code' : 'span', 'fx-function-name');
100
110
  if (snippet)
101
- name.append(...highlightCode(record.path, snippet));
111
+ name.append(...highlighter(record.path)(snippet));
102
112
  else
103
113
  name.textContent = record.name;
104
114
  button.append(name);
@@ -10,6 +10,8 @@ export declare function duplicationContext(entry: Metrics): string | undefined;
10
10
  export declare function effortText(minutes: number | null | undefined): string;
11
11
  /** What a file scores on the metric the code map and the ranking show; null where it was not measured. */
12
12
  export declare function hotspotScore(entry: Metrics, metric: HotspotMetric): number | null;
13
+ /** The top of a ranking's bars: its highest measured score, and 1 where none is above zero. */
14
+ export declare function scorePeak(scores: readonly (number | null)[]): number;
13
15
  /** Orders two entries by a column, unmeasured last whichever way the column sorts, and by path between equals. */
14
16
  export declare function compareEntries(a: Metrics, b: Metrics, measurement: (row: Metrics) => string | number | null, ascending: boolean): number;
15
17
  export declare function fileHref(navigation: Pick<Navigation, 'href'>, file: string): string;
@@ -32,7 +32,8 @@ export function effortText(minutes) {
32
32
  return minutes == null ? '—' : duration(minutes);
33
33
  }
34
34
  const builtinScores = {
35
- complexity: entry => entry.complexity?.maximum,
35
+ // A file measured without functions has nothing to score; one with no record was not measured.
36
+ complexity: entry => entry.complexity && (entry.complexity.maximum ?? 0),
36
37
  cognitive: entry => entry.quality?.cognitiveComplexity,
37
38
  duplication: entry => entry.quality?.duplication?.duplicatedLines,
38
39
  churn: entry => entry.quality?.churn,
@@ -46,6 +47,10 @@ export function hotspotScore(entry, metric) {
46
47
  // A name that is neither a plugin's nor one of the rankings reads as uncovered lines, the last of them.
47
48
  return (builtinScores[metric] ?? builtinScores.missedLines)(entry) ?? null;
48
49
  }
50
+ /** The top of a ranking's bars: its highest measured score, and 1 where none is above zero. */
51
+ export function scorePeak(scores) {
52
+ return scores.reduce((max, score) => score === null ? max : Math.max(max, score), 0) || 1;
53
+ }
49
54
  /** Orders two entries by a column, unmeasured last whichever way the column sorts, and by path between equals. */
50
55
  export function compareEntries(a, b, measurement, ascending) {
51
56
  const left = measurement(a);
@@ -1,7 +1,7 @@
1
1
  import { renderSunburst } from './viewer-code-map.js';
2
2
  import { choice, navigationButtons } from './viewer-controls.js';
3
3
  import { basename, collator, count, element, inside, link, parentPath } from './viewer-dom.js';
4
- import { fileHref, hotspotScore } from './viewer-file-figures.js';
4
+ import { fileHref, hotspotScore, scorePeak } from './viewer-file-figures.js';
5
5
  import { localValue, measured } from './viewer-inspection.js';
6
6
  import { breadcrumbs, liftToTitle } from './viewer-layout.js';
7
7
  import { band, bandLimits, rankTitle } from './viewer-map-scale.js';
@@ -56,10 +56,12 @@ function rankRow(entry, metric, navigation, peak, limits) {
56
56
  const row = element('li');
57
57
  const title = link(fileHref(navigation, entry.path), basename(entry.path), 'fx-rank-link');
58
58
  title.append(element('span', 'fx-rank-path', parentPath(entry.path) || '/'));
59
- const value = hotspotScore(entry, metric) ?? 0;
59
+ const value = hotspotScore(entry, metric);
60
60
  const mark = element('span', 'fx-rank-mark');
61
- mark.style.setProperty('--length', `${value / peak * 100}%`);
62
- mark.dataset.band = String(band(entry, metric, value, peak, limits));
61
+ // An unmeasured file has no bar and no band: a zero-length bar would read as a measured zero.
62
+ mark.style.setProperty('--length', `${(value ?? 0) / peak * 100}%`);
63
+ if (value !== null)
64
+ mark.dataset.band = String(band(entry, metric, value, peak, limits));
63
65
  mark.setAttribute('aria-hidden', 'true');
64
66
  row.append(title, mark, element('strong', 'fx-rank-score', count(value)));
65
67
  return row;
@@ -81,7 +83,7 @@ function rankFiles(entries, metric, navigation, hasMeasures, limits) {
81
83
  const pages = navigationButtons('Ranking pages', () => { page--; render(); }, () => { page++; render(); });
82
84
  pages.section.hidden = entries.length <= maxRanked;
83
85
  // The longest bar is the highest value, whichever end of the scale the list starts from.
84
- const peak = entries.reduce((max, entry) => Math.max(max, hotspotScore(entry, metric) ?? 0), 0) || 1;
86
+ const peak = scorePeak(entries.map(entry => hotspotScore(entry, metric)));
85
87
  let page = 0;
86
88
  function render() {
87
89
  const offset = page * maxRanked;
@@ -9,7 +9,7 @@ let local = { catalog: undefined, index: new Map() };
9
9
  export function useDetails(details) {
10
10
  const catalog = details.metrics.catalog;
11
11
  extendCatalog(catalog);
12
- useLanguages(details.metrics.languages);
12
+ useLanguages(details.metrics);
13
13
  local = { catalog, index: catalogIndex(catalog) };
14
14
  usePluginMeasures(pluginMetrics().filter(spec => spec.descriptor.scope === 'file' && measured(spec.descriptor)).map(spec => [spec.key, {
15
15
  label: spec.label, percent: spec.descriptor.unit === 'ratio', minutes: spec.descriptor.unit === 'minutes',
@@ -3,7 +3,7 @@ import { element, externalLink, link, parentPath, quantity } from './viewer-dom.
3
3
  import { allLocations, formatLocation } from './viewer-locations.js';
4
4
  import { duration } from './viewer-metrics.js';
5
5
  import { lineSnippet, renderExcerpt } from './viewer-source-view.js';
6
- import { highlightCode } from './viewer-tokenizer.js';
6
+ import { highlighter } from './viewer-tokenizer.js';
7
7
  export const issueCategories = {
8
8
  structure: 'Structure', duplication: 'Duplication', lint: 'Lint', security: 'Security',
9
9
  dependency: 'Dependencies', secret: 'Secrets', infrastructure: 'Infrastructure',
@@ -108,7 +108,7 @@ function excerpt(finding, place, message, context, source) {
108
108
  if (!snippet || !finding.message.startsWith('(anonymous)'))
109
109
  return;
110
110
  const name = element('code', 'fx-occurrence-name');
111
- name.append(...highlightCode(place.path, snippet));
111
+ name.append(...highlighter(place.path)(snippet));
112
112
  message.replaceChildren(name, finding.message.slice('(anonymous)'.length));
113
113
  });
114
114
  return slot;
@@ -1,8 +1,9 @@
1
1
  import type { FileMetricsReport } from '../../json/wire/file-metrics-model.js';
2
2
  type FileEntry = FileMetricsReport['files'][number];
3
- type Language = NonNullable<FileMetricsReport['languages']>[number];
4
3
  /** Takes the languages of the inspection on screen: their names, and the colours the plugins and the catalog give them. */
5
- export declare function useLanguages(list: readonly Language[] | undefined): void;
4
+ export declare function useLanguages(metrics: Pick<FileMetricsReport, 'languages' | 'files'>): void;
5
+ /** The id of a file's language, as the inspection gives it: what decides how its source is read. */
6
+ export declare function languageIdOf(path: string): string | undefined;
6
7
  /**
7
8
  * Dependency lockfiles, by exact file name. They are generated, often the largest files in a repository, and no
8
9
  * plugin reads them: the language bar and the Metrics list give them a category of their own beside the ignored files.