@ovh-ux/manager-static-analysis-kit 0.8.0 → 0.10.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 (86) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +59 -69
  3. package/bin/cli-path-config.js +31 -0
  4. package/bin/code-duplication-cli.js +96 -0
  5. package/bin/code-duplication-tests-cli.js +68 -0
  6. package/bin/lint-cli.js +1 -1
  7. package/bin/perf-budgets-cli.js +58 -297
  8. package/bin/perf-budgets-tests-cli.js +1 -3
  9. package/bin/static-dynamic-quality-checks.js +138 -0
  10. package/bin/tests-coverage-cli-tests.js +67 -0
  11. package/bin/tests-coverage-cli.js +137 -0
  12. package/bin/types-coverage-cli.js +195 -0
  13. package/bin/types-coverage-tests-cli.js +68 -0
  14. package/bin/utils/apps-utils.js +64 -0
  15. package/bin/utils/args-parse-utils.js +229 -0
  16. package/bin/utils/file-utils.js +52 -0
  17. package/bin/utils/log-utils.js +29 -0
  18. package/bin/utils/runner-utils.js +85 -0
  19. package/bin/utils/turbo-utils.js +150 -0
  20. package/dist/adapters/code-duplication/helpers/code-duplication-analysis-helper.d.ts +9 -0
  21. package/dist/adapters/code-duplication/helpers/code-duplication-analysis-helper.d.ts.map +1 -0
  22. package/dist/adapters/code-duplication/helpers/code-duplication-analysis-helper.js +294 -0
  23. package/dist/adapters/code-duplication/types/CodeDuplication.d.ts +63 -0
  24. package/dist/adapters/code-duplication/types/CodeDuplication.d.ts.map +1 -0
  25. package/dist/adapters/code-duplication/types/CodeDuplication.js +1 -0
  26. package/dist/adapters/eslint/rules/eslint-prettier.js +1 -1
  27. package/dist/adapters/html-a11y-validation/helpers/html-a11y-tests-setup.d.ts +62 -0
  28. package/dist/adapters/html-a11y-validation/helpers/html-a11y-tests-setup.d.ts.map +1 -0
  29. package/dist/adapters/html-a11y-validation/helpers/html-a11y-tests-setup.js +73 -0
  30. package/dist/adapters/html-w3c-validation/helpers/html-w3c-tests-setup.d.ts +19 -0
  31. package/dist/adapters/html-w3c-validation/helpers/html-w3c-tests-setup.d.ts.map +1 -0
  32. package/dist/adapters/html-w3c-validation/helpers/html-w3c-tests-setup.js +32 -0
  33. package/dist/adapters/html-w3c-validation/helpers/html-w3c-validator.d.ts +4 -0
  34. package/dist/adapters/html-w3c-validation/helpers/html-w3c-validator.d.ts.map +1 -0
  35. package/dist/adapters/html-w3c-validation/helpers/html-w3c-validator.js +89 -0
  36. package/dist/adapters/html-w3c-validation/types/HtmlW3CValidator.d.ts +6 -0
  37. package/dist/adapters/html-w3c-validation/types/HtmlW3CValidator.d.ts.map +1 -0
  38. package/dist/adapters/html-w3c-validation/types/HtmlW3CValidator.js +1 -0
  39. package/dist/adapters/html-w3c-validation/types/globals/vnu-jar.d.ts +5 -0
  40. package/dist/adapters/perf-budgets/helpers/perfs-bundle-analysis-helper.d.ts +1 -1
  41. package/dist/adapters/perf-budgets/helpers/perfs-bundle-analysis-helper.d.ts.map +1 -1
  42. package/dist/adapters/perf-budgets/helpers/perfs-bundle-analysis-helper.js +2 -3
  43. package/dist/adapters/tests-coverage/helpers/tests-coverage-analysis-helper.d.ts +4 -0
  44. package/dist/adapters/tests-coverage/helpers/tests-coverage-analysis-helper.d.ts.map +1 -0
  45. package/dist/adapters/tests-coverage/helpers/tests-coverage-analysis-helper.js +215 -0
  46. package/dist/adapters/tests-coverage/types/TestsCoverage.d.ts +36 -0
  47. package/dist/adapters/tests-coverage/types/TestsCoverage.d.ts.map +1 -0
  48. package/dist/adapters/tests-coverage/types/TestsCoverage.js +6 -0
  49. package/dist/adapters/types-coverage/helpers/types-coverage-analysis-helper.d.ts +4 -0
  50. package/dist/adapters/types-coverage/helpers/types-coverage-analysis-helper.d.ts.map +1 -0
  51. package/dist/adapters/types-coverage/helpers/types-coverage-analysis-helper.js +231 -0
  52. package/dist/adapters/types-coverage/types/TypesCoverage.d.ts +38 -0
  53. package/dist/adapters/types-coverage/types/TypesCoverage.d.ts.map +1 -0
  54. package/dist/adapters/types-coverage/types/TypesCoverage.js +1 -0
  55. package/dist/configs/architecture-analysis-config.d.ts +5 -0
  56. package/dist/configs/architecture-analysis-config.d.ts.map +1 -0
  57. package/dist/configs/{madge-config.js → architecture-analysis-config.js} +1 -1
  58. package/dist/configs/code-duplication-config.d.ts +22 -0
  59. package/dist/configs/code-duplication-config.d.ts.map +1 -0
  60. package/dist/configs/code-duplication-config.js +22 -0
  61. package/dist/configs/{prettier-config.d.ts → code-formatter-config.d.ts} +1 -1
  62. package/dist/configs/code-formatter-config.d.ts.map +1 -0
  63. package/dist/configs/file-globs-config.d.ts +0 -3
  64. package/dist/configs/file-globs-config.d.ts.map +1 -1
  65. package/dist/configs/file-globs-config.js +0 -3
  66. package/dist/configs/naming-conventions-config.d.ts.map +1 -1
  67. package/dist/configs/naming-conventions-config.js +2 -0
  68. package/dist/configs/shared-exclusion-patterns.d.ts +1 -0
  69. package/dist/configs/shared-exclusion-patterns.d.ts.map +1 -1
  70. package/dist/configs/shared-exclusion-patterns.js +23 -1
  71. package/dist/configs/tests-coverage-config.d.ts +12 -0
  72. package/dist/configs/tests-coverage-config.d.ts.map +1 -0
  73. package/dist/configs/tests-coverage-config.js +11 -0
  74. package/dist/configs/types-coverage-config.d.ts +33 -0
  75. package/dist/configs/types-coverage-config.d.ts.map +1 -0
  76. package/dist/configs/types-coverage-config.js +24 -0
  77. package/dist/tsconfig.tsbuildinfo +1 -1
  78. package/package.json +32 -7
  79. package/bin/cli-utils.js +0 -56
  80. package/dist/configs/jscpd-config.d.ts +0 -7
  81. package/dist/configs/jscpd-config.d.ts.map +0 -1
  82. package/dist/configs/jscpd-config.js +0 -7
  83. package/dist/configs/madge-config.d.ts +0 -5
  84. package/dist/configs/madge-config.d.ts.map +0 -1
  85. package/dist/configs/prettier-config.d.ts.map +0 -1
  86. /package/dist/configs/{prettier-config.js → code-formatter-config.js} +0 -0
@@ -0,0 +1,52 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { logError, logInfo } from './log-utils.js';
5
+
6
+ /**
7
+ * Safe JSON read.
8
+ */
9
+ export function readJsonSafe(file) {
10
+ try {
11
+ return JSON.parse(fs.readFileSync(file, 'utf-8'));
12
+ } catch {
13
+ return null;
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Remove old combined report files (JSON & HTML).
19
+ */
20
+ export function removeOldCombinedReports(root, dirName, jsonFile, htmlFile) {
21
+ const combinedJson = path.join(root, dirName, jsonFile);
22
+ const combinedHtml = path.join(root, dirName, htmlFile);
23
+
24
+ [combinedJson, combinedHtml].forEach((file) => {
25
+ if (fs.existsSync(file)) {
26
+ fs.rmSync(file, { force: true });
27
+ logInfo(`🧹 Removed old combined report ${file}`);
28
+ }
29
+ });
30
+ }
31
+
32
+ /**
33
+ * Generate combined JSON & HTML reports.
34
+ * @param {string} reportRoot - output root
35
+ * @param {string} jsonFile - filename for combined JSON
36
+ * @param {string} htmlFile - filename for combined HTML
37
+ * @param {Function} collectorFn - e.g., collectTsTypesCoverage or collectPerfBudgets
38
+ * @param {Function} htmlGenFn - e.g., generateTsTypesCoverageHtml or generatePerfBudgetsHtml
39
+ */
40
+ // eslint-disable-next-line max-params
41
+ export function generateCombinedReports(reportRoot, jsonFile, htmlFile, collectorFn, htmlGenFn) {
42
+ try {
43
+ const combinedJsonPath = path.join(reportRoot, jsonFile);
44
+ const combinedHtmlPath = path.join(reportRoot, htmlFile);
45
+
46
+ const summary = collectorFn(reportRoot);
47
+ fs.writeFileSync(combinedJsonPath, JSON.stringify(summary, null, 2));
48
+ fs.writeFileSync(combinedHtmlPath, htmlGenFn(summary));
49
+ } catch (err) {
50
+ logError(`❌ Failed to generate combined reports: ${err.message}`);
51
+ }
52
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Log an informational message with a standard prefix.
3
+ *
4
+ * @param {string} msg - The message to log.
5
+ * @returns {void}
6
+ */
7
+ export function logInfo(msg) {
8
+ console.log(`[manager-static-analysis-kit] ${msg}`);
9
+ }
10
+
11
+ /**
12
+ * Log a warning message with a standard prefix.
13
+ *
14
+ * @param {string} msg - The message to log.
15
+ * @returns {void}
16
+ */
17
+ export function logWarn(msg) {
18
+ console.warn(`⚠️ [manager-static-analysis-kit] ${msg}`);
19
+ }
20
+
21
+ /**
22
+ * Log an error message with a standard prefix.
23
+ *
24
+ * @param {string} msg - The message to log.
25
+ * @returns {void}
26
+ */
27
+ export function logError(msg) {
28
+ console.error(`❌ [manager-static-analysis-kit] ${msg}`);
29
+ }
@@ -0,0 +1,85 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import process from 'node:process';
5
+
6
+ import { resolveAppInfo } from './apps-utils.js';
7
+ import { generateCombinedReports } from './file-utils.js';
8
+ import { logError, logInfo } from './log-utils.js';
9
+
10
+ /**
11
+ * Ensure the given binary exists.
12
+ */
13
+ export function ensureBinExists(binPath, label) {
14
+ if (!fs.existsSync(binPath)) {
15
+ logError(`❌ ${label} binary not found at ${binPath}`);
16
+ process.exit(1);
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Run a child process with consistent defaults.
22
+ */
23
+ export function runCommand(bin, args, cwd) {
24
+ const result = spawnSync(bin, args, {
25
+ cwd,
26
+ stdio: 'inherit',
27
+ shell: true,
28
+ });
29
+ return result.status === 0;
30
+ }
31
+
32
+ /**
33
+ * Generic per-app analysis runner with safety.
34
+ */
35
+ export function runAppsAnalysis({
36
+ appsDir,
37
+ appFolders,
38
+ requireReact = false,
39
+ binaryLabel,
40
+ appRunner, // (appDir, appShortName, appInfo) => boolean
41
+ reportsRootDirName,
42
+ combinedJson,
43
+ combinedHtml,
44
+ collectFn,
45
+ generateHtmlFn,
46
+ outputRootDir,
47
+ }) {
48
+ const analyzed = [];
49
+
50
+ for (const appFolder of appFolders) {
51
+ const appInfo = resolveAppInfo(appsDir, appFolder, { requireReact });
52
+ if (!appInfo) continue;
53
+
54
+ let ok = false;
55
+ try {
56
+ ok = appRunner(appInfo.appDir, appInfo.appShortName, appInfo);
57
+ } catch (err) {
58
+ logError(
59
+ `❌ Fatal error while analyzing ${appInfo.appShortName}: ${err.stack || err.message}`,
60
+ );
61
+ }
62
+ if (ok) analyzed.push(appInfo.appShortName);
63
+ }
64
+
65
+ if (analyzed.length > 0) {
66
+ if (typeof collectFn !== 'function' || typeof generateHtmlFn !== 'function') {
67
+ logError(`❌ Invalid collector or HTML generator passed to ${binaryLabel} analysis`);
68
+ process.exit(1);
69
+ }
70
+
71
+ generateCombinedReports(
72
+ path.join(outputRootDir, reportsRootDirName),
73
+ combinedJson,
74
+ combinedHtml,
75
+ collectFn,
76
+ generateHtmlFn,
77
+ );
78
+ logInfo(`✅ ${binaryLabel} reports generated (per-app + combined).`);
79
+ } else {
80
+ logError('❌ No apps successfully analyzed. Exiting.');
81
+ process.exit(1);
82
+ }
83
+
84
+ return analyzed;
85
+ }
@@ -0,0 +1,150 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ import { logError, logInfo, logWarn } from './log-utils.js';
6
+
7
+ /**
8
+ * Convert app folder names into Turbo filters by resolving their package.json names.
9
+ *
10
+ * Each app folder must contain a valid `package.json`. If not found, the app is skipped.
11
+ *
12
+ * @param {string} appsDir - Absolute path to the apps root directory.
13
+ * @param {string[]} appFolders - List of app folder names inside the apps directory.
14
+ * @returns {string[]} Array of package names to be used as Turbo filters.
15
+ *
16
+ * @example
17
+ * // appsDir = "/workspace/manager/apps"
18
+ * // appFolders = ["zimbra", "web"]
19
+ * // Returns: ["@ovh-ux/manager-zimbra-app", "@ovh-ux/manager-web-app"]
20
+ */
21
+ function resolveTurboFiltersFromAppFolders(appsDir, appFolders) {
22
+ return appFolders
23
+ .map((appFolder) => {
24
+ const pkgPath = path.join(appsDir, appFolder, 'package.json');
25
+ if (!fs.existsSync(pkgPath)) {
26
+ logError(`❌ No package.json for app folder ${appFolder}, skipping`);
27
+ return null;
28
+ }
29
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
30
+ return pkg.name;
31
+ })
32
+ .filter(Boolean);
33
+ }
34
+
35
+ /**
36
+ * Resolve Turbo filters (package names) based on input mode.
37
+ *
38
+ * - If only `appFolders` are provided, resolves their corresponding package names.
39
+ * - If `packageNames` are provided, they are used directly as filters.
40
+ *
41
+ * @param {Object} options
42
+ * @param {string} options.appsDir - Absolute path to the apps root directory.
43
+ * @param {string[]} options.appFolders - List of app folders to analyze.
44
+ * @param {string[]} options.packageNames - List of package names (overrides appFolders).
45
+ * @returns {string[]} List of resolved Turbo filters (package names).
46
+ *
47
+ * @example
48
+ * resolveTurboFilters({
49
+ * appsDir: "/workspace/manager/apps",
50
+ * appFolders: ["zimbra"],
51
+ * packageNames: []
52
+ * });
53
+ * // → ["@ovh-ux/manager-zimbra-app"]
54
+ *
55
+ * @example
56
+ * resolveTurboFilters({
57
+ * appsDir: "/workspace/manager/apps",
58
+ * appFolders: [],
59
+ * packageNames: ["@ovh-ux/manager-web-app"]
60
+ * });
61
+ * // → ["@ovh-ux/manager-web-app"]
62
+ */
63
+ export function resolveTurboFilters({ appsDir, appFolders, packageNames }) {
64
+ let filters = [];
65
+
66
+ if (appFolders.length > 0 && packageNames.length === 0) {
67
+ filters = resolveTurboFiltersFromAppFolders(appsDir, appFolders);
68
+ } else if (packageNames.length > 0) {
69
+ filters = packageNames;
70
+ }
71
+
72
+ return filters;
73
+ }
74
+
75
+ /**
76
+ * Run a Turbo build for the provided filters.
77
+ *
78
+ * - Executes `turbo run build` with `--filter` for each package name.
79
+ * - Runs in the specified root directory.
80
+ * - If no filters are provided, the build step is skipped with a warning.
81
+ *
82
+ * @param {string} rootDir - Root directory where Turbo should be executed.
83
+ * @param {string[]} filters - List of Turbo build filters (package names).
84
+ * @param {string[]} [extraArgs=[]] - Additional arguments to forward to Turbo.
85
+ * @returns {void}
86
+ *
87
+ * @example
88
+ * runTurboBuild("/workspace", ["@ovh-ux/manager-zimbra-app"]);
89
+ * // Executes: turbo run build --filter @ovh-ux/manager-zimbra-app
90
+ */
91
+ export function runTurboBuild(rootDir, filters, extraArgs = []) {
92
+ if (filters.length === 0) {
93
+ logWarn('⚠️ No Turbo build filters provided, skipping build step.');
94
+ return;
95
+ }
96
+
97
+ const turboArgs = [
98
+ 'run',
99
+ 'build',
100
+ ...filters.flatMap((pkgName) => ['--filter', pkgName]),
101
+ ...extraArgs,
102
+ ];
103
+ logInfo(`Building with Turbo (filters: ${filters.join(', ')})`);
104
+
105
+ const buildResult = spawnSync('turbo', turboArgs, {
106
+ cwd: rootDir,
107
+ stdio: 'inherit',
108
+ shell: true,
109
+ });
110
+
111
+ if (buildResult.status !== 0) {
112
+ logWarn('⚠️ Turbo build failed for one or more targets. Will still try to analyze apps.');
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Run Turbo tests with optional filters and extra arguments.
118
+ *
119
+ * This function spawns a synchronous Turbo process to run tests,
120
+ * applying filters for specific packages if provided. It logs
121
+ * progress and warns if any tests fail, but does not throw.
122
+ *
123
+ * @param {string} rootDir - Root directory to run Turbo in (typically the monorepo root).
124
+ * @param {string[]} filters - List of package filters (Turbo `--filter` flags).
125
+ * @param {string[]} [extraArgs=[]] - Additional arguments to forward to Turbo.
126
+ * @returns {void}
127
+ *
128
+ * @example
129
+ * // Run tests for "web" and "zimbra" apps with coverage
130
+ * runTurboTests(process.cwd(), ['web', 'zimbra'], ['--', '--coverage']);
131
+ */
132
+ export function runTurboTests(rootDir, filters, extraArgs = []) {
133
+ const args = [
134
+ 'run',
135
+ 'test',
136
+ ...filters.flatMap((pkgName) => ['--filter', pkgName]),
137
+ ...extraArgs,
138
+ ];
139
+ logInfo(`Testing with Turbo (filters: ${filters.join(', ')})`);
140
+
141
+ const res = spawnSync('turbo', args, {
142
+ cwd: rootDir,
143
+ stdio: 'inherit',
144
+ shell: true,
145
+ });
146
+
147
+ if (res.status !== 0) {
148
+ logWarn('⚠️ Turbo tests failed for one or more targets. Will still harvest coverage if any.');
149
+ }
150
+ }
@@ -0,0 +1,9 @@
1
+ import { CombinedCodeDuplicationSummary, JscpdReportV4, WorstCodeDuplicationFile } from '../types/CodeDuplication.js';
2
+ export declare const extPriority: (file: string) => number;
3
+ export declare function extractWorstFiles(report: JscpdReportV4): {
4
+ files: WorstCodeDuplicationFile[];
5
+ fileCount: number;
6
+ };
7
+ export declare function collectCodeDuplication(reportOutputDir: string): CombinedCodeDuplicationSummary;
8
+ export declare function generateCodeDuplicationHtml(summary: CombinedCodeDuplicationSummary): string;
9
+ //# sourceMappingURL=code-duplication-analysis-helper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-duplication-analysis-helper.d.ts","sourceRoot":"","sources":["../../../../src/adapters/code-duplication/helpers/code-duplication-analysis-helper.ts"],"names":[],"mappings":"AAIA,OAAO,EAEL,8BAA8B,EAC9B,aAAa,EACb,wBAAwB,EAEzB,MAAM,0BAA0B,CAAC;AAUlC,eAAO,MAAM,WAAW,GAAI,MAAM,MAAM,KAAG,MAc1C,CAAC;AAmEF,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,aAAa,GAAG;IACxD,KAAK,EAAE,wBAAwB,EAAE,CAAC;IAClC,SAAS,EAAE,MAAM,CAAC;CACnB,CAwEA;AA4ED,wBAAgB,sBAAsB,CAAC,eAAe,EAAE,MAAM,GAAG,8BAA8B,CA+B9F;AAsGD,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,8BAA8B,GAAG,MAAM,CAyD3F"}
@@ -0,0 +1,294 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { codeDuplicationConfig } from '../../../configs/code-duplication-config.js';
4
+ export const extPriority = (file) => {
5
+ const f = file.toLowerCase();
6
+ if (/\.(d\.ts)$/.test(f))
7
+ return 2;
8
+ if (/\.(tsx?|mts|cts)$/.test(f))
9
+ return 0;
10
+ if (/\.(jsx?|mjs|cjs)$/.test(f))
11
+ return 1;
12
+ return 2;
13
+ };
14
+ const safeCountLines = (file) => {
15
+ try {
16
+ const txt = fs.readFileSync(file, 'utf8');
17
+ return txt.split(/\r?\n/).length;
18
+ }
19
+ catch {
20
+ return 0;
21
+ }
22
+ };
23
+ function shortPathFromAppsRoot(filePath, app) {
24
+ const norm = filePath.replace(/\\/g, '/');
25
+ const appsIdx = norm.indexOf('/apps/');
26
+ if (appsIdx >= 0) {
27
+ return norm.slice(appsIdx + 1);
28
+ }
29
+ const parts = norm.split('/');
30
+ return parts.slice(Math.max(0, parts.length - 5)).join('/');
31
+ }
32
+ export function extractWorstFiles(report) {
33
+ const dups = Array.isArray(report?.duplicates) ? report.duplicates : [];
34
+ if (dups.length === 0)
35
+ return { files: [], fileCount: 0 };
36
+ const { threshold, count } = codeDuplicationConfig.worstFiles;
37
+ const fileMap = {};
38
+ for (const dup of dups) {
39
+ const lines = Number(dup?.lines ?? 0);
40
+ if (!lines)
41
+ continue;
42
+ for (const side of [dup.firstFile, dup.secondFile]) {
43
+ const file = side?.name;
44
+ if (!file)
45
+ continue;
46
+ const endLine = Number(side?.endLoc?.line ?? 0);
47
+ const entry = fileMap[file] ?? { dup: 0, estimatedTotal: 0 };
48
+ entry.dup += lines;
49
+ if (endLine > entry.estimatedTotal)
50
+ entry.estimatedTotal = endLine;
51
+ fileMap[file] = entry;
52
+ }
53
+ }
54
+ for (const file of Object.keys(fileMap)) {
55
+ const realTotal = safeCountLines(file);
56
+ const estTotal = fileMap[file].estimatedTotal;
57
+ fileMap[file].total = Math.max(realTotal || estTotal || 0, fileMap[file].dup);
58
+ }
59
+ const files = Object.entries(fileMap)
60
+ .map(([file, { dup, total = 0 }]) => {
61
+ const percentage = total > 0 ? (dup / total) * 100 : 0;
62
+ const stats = {
63
+ duplicatedLines: dup,
64
+ totalLines: total,
65
+ percentage,
66
+ };
67
+ return [file, stats];
68
+ })
69
+ .filter(([, s]) => s.percentage >= threshold)
70
+ .sort((a, b) => {
71
+ const pa = extPriority(a[0]);
72
+ const pb = extPriority(b[0]);
73
+ if (pa !== pb)
74
+ return pa - pb;
75
+ const pct = b[1].percentage - a[1].percentage;
76
+ if (pct !== 0)
77
+ return pct;
78
+ if (b[1].duplicatedLines !== a[1].duplicatedLines) {
79
+ return b[1].duplicatedLines - a[1].duplicatedLines;
80
+ }
81
+ if (b[1].totalLines !== a[1].totalLines) {
82
+ return b[1].totalLines - a[1].totalLines;
83
+ }
84
+ return a[0].localeCompare(b[0]);
85
+ })
86
+ .slice(0, count);
87
+ return { files, fileCount: Object.keys(fileMap).length };
88
+ }
89
+ function parseAppCodeDuplicationReport(jsonPath) {
90
+ try {
91
+ const report = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
92
+ const total = report.statistics?.total ?? {};
93
+ const totalLines = total.lines ?? 0;
94
+ const duplicateLines = total.duplicatedLines ?? 0;
95
+ const percentage = total.percentage ?? (totalLines > 0 ? (duplicateLines / totalLines) * 100 : 0);
96
+ const { files: worstFiles, fileCount } = extractWorstFiles(report);
97
+ const perFilePercentages = worstFiles.map(([, f]) => f.percentage);
98
+ const minPercentage = perFilePercentages.length ? Math.min(...perFilePercentages) : percentage;
99
+ const maxPercentage = perFilePercentages.length ? Math.max(...perFilePercentages) : percentage;
100
+ return {
101
+ totalLines,
102
+ totalTokens: total.tokens ?? 0,
103
+ duplicateLines,
104
+ duplicateTokens: total.duplicatedTokens ?? 0,
105
+ clonesCount: total.clones ?? 0,
106
+ percentage,
107
+ minPercentage,
108
+ maxPercentage,
109
+ worstFiles,
110
+ filesWithDuplication: fileCount,
111
+ };
112
+ }
113
+ catch (err) {
114
+ return {
115
+ totalLines: 0,
116
+ totalTokens: 0,
117
+ duplicateLines: 0,
118
+ duplicateTokens: 0,
119
+ clonesCount: 0,
120
+ percentage: 0,
121
+ minPercentage: 0,
122
+ maxPercentage: 0,
123
+ error: err.message,
124
+ worstFiles: [],
125
+ filesWithDuplication: 0,
126
+ };
127
+ }
128
+ }
129
+ function aggregateTotals(apps) {
130
+ return Object.values(apps).reduce((acc, app) => {
131
+ acc.totalLines += app.totalLines;
132
+ acc.totalTokens += app.totalTokens;
133
+ acc.totalDuplicateLines += app.duplicateLines;
134
+ acc.totalDuplicateTokens += app.duplicateTokens;
135
+ return acc;
136
+ }, { totalLines: 0, totalTokens: 0, totalDuplicateLines: 0, totalDuplicateTokens: 0 });
137
+ }
138
+ export function collectCodeDuplication(reportOutputDir) {
139
+ if (!fs.existsSync(reportOutputDir)) {
140
+ return {
141
+ apps: {},
142
+ totalLines: 0,
143
+ totalTokens: 0,
144
+ totalDuplicateLines: 0,
145
+ totalDuplicateTokens: 0,
146
+ percentage: 0,
147
+ };
148
+ }
149
+ const apps = {};
150
+ const appDirs = fs
151
+ .readdirSync(reportOutputDir)
152
+ .filter((entry) => fs.statSync(path.join(reportOutputDir, entry)).isDirectory());
153
+ for (const appDirName of appDirs) {
154
+ const jsonPath = path.join(reportOutputDir, appDirName, 'jscpd-report.json');
155
+ if (fs.existsSync(jsonPath)) {
156
+ apps[appDirName] = parseAppCodeDuplicationReport(jsonPath);
157
+ }
158
+ }
159
+ const totals = aggregateTotals(apps);
160
+ return {
161
+ apps,
162
+ ...totals,
163
+ percentage: totals.totalLines > 0 ? (totals.totalDuplicateLines / totals.totalLines) * 100 : 0,
164
+ };
165
+ }
166
+ const getColorForDuplicationStatus = (pct) => {
167
+ const green = codeDuplicationConfig.thresholds?.green ?? 10;
168
+ const orange = codeDuplicationConfig.thresholds?.orange ?? 20;
169
+ return pct < green ? 'green' : pct < orange ? 'orange' : 'red';
170
+ };
171
+ function renderWorstFiles(app, worstFiles = []) {
172
+ const threshold = codeDuplicationConfig.worstFiles.threshold;
173
+ if (!worstFiles.length) {
174
+ return `
175
+ <details class="coverage-details">
176
+ <summary>📊 Duplication Overview for <strong>${app}</strong></summary>
177
+ <p class="coverage-empty">No files above threshold 🎉</p>
178
+ </details>`;
179
+ }
180
+ const rows = worstFiles
181
+ .map(([file, f]) => {
182
+ const short = shortPathFromAppsRoot(file, app);
183
+ const color = getColorForDuplicationStatus(f.percentage);
184
+ return `
185
+ <tr>
186
+ <td colspan="2" title="${file}">${short}</td>
187
+ <td>${f.duplicatedLines}/${f.totalLines}</td>
188
+ <td style="color:${color}">${f.percentage.toFixed(2)}%</td>
189
+ </tr>`;
190
+ })
191
+ .join('');
192
+ return `
193
+ <details class="coverage-details">
194
+ <summary>📊 Duplication Overview for <strong>${app}</strong> (≥ ${threshold}%)</summary>
195
+ <table class="coverage-subtable">
196
+ <tbody>${rows}</tbody>
197
+ </table>
198
+ </details>`;
199
+ }
200
+ function renderDuplicationCell(stats) {
201
+ const min = stats.minPercentage ?? stats.percentage;
202
+ const max = stats.maxPercentage ?? stats.percentage;
203
+ if (stats.duplicateLines === 0) {
204
+ return `<span style="color:${getColorForDuplicationStatus(0)}">0.00%</span>`;
205
+ }
206
+ if (min.toFixed(2) === max.toFixed(2)) {
207
+ return `
208
+ ${stats.percentage.toFixed(2)}% (${stats.filesWithDuplication} files cluster at
209
+ <span style="color:${getColorForDuplicationStatus(min)}">${min.toFixed(2)}%</span>)
210
+ `;
211
+ }
212
+ return `
213
+ ${stats.percentage.toFixed(2)}% (range:
214
+ <span style="color:${getColorForDuplicationStatus(min)}">${min.toFixed(2)}%</span> –
215
+ <span style="color:${getColorForDuplicationStatus(max)}">${max.toFixed(2)}%</span>)
216
+ `;
217
+ }
218
+ function buildAppRow(app, stats) {
219
+ if (stats.error) {
220
+ return `<tr style="background:#ffe0e0">
221
+ <td>${app}</td>
222
+ <td colspan="5" style="color:red">${stats.error}</td>
223
+ </tr>`;
224
+ }
225
+ const max = stats.maxPercentage ?? stats.percentage;
226
+ const rowColor = getColorForDuplicationStatus(max);
227
+ const bg = rowColor === 'green' ? '#e6ffed' : rowColor === 'orange' ? '#fff8e1' : '#ffe6e6';
228
+ return `
229
+ <tr style="background:${bg}">
230
+ <td>${app}</td>
231
+ <td>${stats.totalLines}</td>
232
+ <td>${stats.duplicateLines}</td>
233
+ <td>${stats.clonesCount}</td>
234
+ <td style="font-weight:bold;">${renderDuplicationCell(stats)}</td>
235
+ </tr>
236
+ <tr><td colspan="5">${renderWorstFiles(app, stats.worstFiles)}</td></tr>`;
237
+ }
238
+ export function generateCodeDuplicationHtml(summary) {
239
+ const rows = Object.entries(summary.apps)
240
+ .map(([app, stats]) => buildAppRow(app, stats))
241
+ .join('');
242
+ return `<!DOCTYPE html>
243
+ <html lang="en">
244
+ <head>
245
+ <meta charset="UTF-8"/>
246
+ <title>Code Duplication Report</title>
247
+ <style>
248
+ body { font-family: Arial, sans-serif; margin: 2rem; }
249
+ table { border-collapse: collapse; width: 100%; }
250
+ th, td { border: 1px solid #ccc; padding: 0.5rem; text-align: left; }
251
+ th { background: #f0f0f0; }
252
+ .coverage-details {
253
+ margin: 0.3rem 0 0.8rem 1.5rem;
254
+ padding: 0.5rem;
255
+ border-left: 3px solid #ccc;
256
+ background: #fafafa;
257
+ border-radius: 4px;
258
+ }
259
+ .coverage-details summary {
260
+ font-weight: bold;
261
+ cursor: pointer;
262
+ }
263
+ .coverage-subtable {
264
+ margin-top: 0.5rem;
265
+ border: 1px solid #ddd;
266
+ width: 95%;
267
+ font-size: 0.9em;
268
+ }
269
+ .coverage-empty {
270
+ margin: 0.5rem 0;
271
+ color: #888;
272
+ font-style: italic;
273
+ }
274
+ </style>
275
+ </head>
276
+ <body>
277
+ <h1>Code Duplication Report</h1>
278
+ <p>Total lines: ${summary.totalLines}, Duplicate lines: ${summary.totalDuplicateLines},
279
+ Percentage: ${summary.percentage.toFixed(2)}%</p>
280
+ <table>
281
+ <thead>
282
+ <tr>
283
+ <th>App</th>
284
+ <th>Total lines</th>
285
+ <th>Duplicate lines</th>
286
+ <th>Clones</th>
287
+ <th>Duplication %</th>
288
+ </tr>
289
+ </thead>
290
+ <tbody>${rows}</tbody>
291
+ </table>
292
+ </body>
293
+ </html>`;
294
+ }
@@ -0,0 +1,63 @@
1
+ export interface AppCodeDuplicationSummary {
2
+ totalLines: number;
3
+ totalTokens: number;
4
+ duplicateLines: number;
5
+ duplicateTokens: number;
6
+ percentage: number;
7
+ minPercentage: number;
8
+ maxPercentage: number;
9
+ clonesCount: number;
10
+ filesWithDuplication: number;
11
+ error?: string;
12
+ worstFiles?: WorstCodeDuplicationFile[];
13
+ }
14
+ export interface CombinedCodeDuplicationSummary {
15
+ apps: Record<string, AppCodeDuplicationSummary>;
16
+ totalLines: number;
17
+ totalTokens: number;
18
+ totalDuplicateLines: number;
19
+ totalDuplicateTokens: number;
20
+ percentage: number;
21
+ }
22
+ export type WorstCodeDuplicationFile = [
23
+ string,
24
+ {
25
+ duplicatedLines: number;
26
+ totalLines: number;
27
+ percentage: number;
28
+ }
29
+ ];
30
+ export interface WorstFileStats {
31
+ duplicatedLines: number;
32
+ totalLines: number;
33
+ percentage: number;
34
+ }
35
+ interface JscpdDuplicateSide {
36
+ name: string;
37
+ startLoc?: {
38
+ line?: number;
39
+ };
40
+ endLoc?: {
41
+ line?: number;
42
+ };
43
+ }
44
+ interface JscpdDuplicate {
45
+ lines: number;
46
+ firstFile: JscpdDuplicateSide;
47
+ secondFile: JscpdDuplicateSide;
48
+ }
49
+ export interface JscpdReportV4 {
50
+ statistics?: {
51
+ total?: {
52
+ lines?: number;
53
+ tokens?: number;
54
+ duplicatedLines?: number;
55
+ duplicatedTokens?: number;
56
+ clones?: number;
57
+ percentage?: number;
58
+ };
59
+ };
60
+ duplicates?: JscpdDuplicate[];
61
+ }
62
+ export {};
63
+ //# sourceMappingURL=CodeDuplication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CodeDuplication.d.ts","sourceRoot":"","sources":["../../../../src/adapters/code-duplication/types/CodeDuplication.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,yBAAyB;IAExC,UAAU,EAAE,MAAM,CAAC;IAGnB,WAAW,EAAE,MAAM,CAAC;IAGpB,cAAc,EAAE,MAAM,CAAC;IAGvB,eAAe,EAAE,MAAM,CAAC;IAMxB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IAMtB,WAAW,EAAE,MAAM,CAAC;IAMpB,oBAAoB,EAAE,MAAM,CAAC;IAM7B,KAAK,CAAC,EAAE,MAAM,CAAC;IAMf,UAAU,CAAC,EAAE,wBAAwB,EAAE,CAAC;CACzC;AAKD,MAAM,WAAW,8BAA8B;IAK7C,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,yBAAyB,CAAC,CAAC;IAGhD,UAAU,EAAE,MAAM,CAAC;IAGnB,WAAW,EAAE,MAAM,CAAC;IAGpB,mBAAmB,EAAE,MAAM,CAAC;IAG5B,oBAAoB,EAAE,MAAM,CAAC;IAM7B,UAAU,EAAE,MAAM,CAAC;CACpB;AAcD,MAAM,MAAM,wBAAwB,GAAG;IACrC,MAAM;IACN;QAEE,eAAe,EAAE,MAAM,CAAC;QAGxB,UAAU,EAAE,MAAM,CAAC;QAGnB,UAAU,EAAE,MAAM,CAAC;KACpB;CACF,CAAC;AAKF,MAAM,WAAW,cAAc;IAE7B,eAAe,EAAE,MAAM,CAAC;IAGxB,UAAU,EAAE,MAAM,CAAC;IAGnB,UAAU,EAAE,MAAM,CAAC;CACpB;AAKD,UAAU,kBAAkB;IAE1B,IAAI,EAAE,MAAM,CAAC;IAMb,QAAQ,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAM7B,MAAM,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC5B;AAKD,UAAU,cAAc;IAKtB,KAAK,EAAE,MAAM,CAAC;IAGd,SAAS,EAAE,kBAAkB,CAAC;IAG9B,UAAU,EAAE,kBAAkB,CAAC;CAChC;AAMD,MAAM,WAAW,aAAa;IAK5B,UAAU,CAAC,EAAE;QACX,KAAK,CAAC,EAAE;YAEN,KAAK,CAAC,EAAE,MAAM,CAAC;YAGf,MAAM,CAAC,EAAE,MAAM,CAAC;YAGhB,eAAe,CAAC,EAAE,MAAM,CAAC;YAGzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;YAG1B,MAAM,CAAC,EAAE,MAAM,CAAC;YAMhB,UAAU,CAAC,EAAE,MAAM,CAAC;SACrB,CAAC;KACH,CAAC;IAMF,UAAU,CAAC,EAAE,cAAc,EAAE,CAAC;CAC/B"}