code-gauge 10.2.3 → 10.2.4

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 (42) hide show
  1. package/README.md +2 -2
  2. package/THIRD-PARTY-NOTICES.txt +12 -12
  3. package/dist/checkCommand.cjs.map +1 -1
  4. package/dist/checkCommand.js.map +1 -1
  5. package/dist/cli.cjs.map +1 -1
  6. package/dist/cli.js.map +1 -1
  7. package/dist/cliConfig.cjs.map +1 -1
  8. package/dist/cliConfig.js.map +1 -1
  9. package/dist/crossFileDuplication.cjs.map +1 -1
  10. package/dist/crossFileDuplication.js.map +1 -1
  11. package/dist/crossFileNearMiss.cjs.map +1 -1
  12. package/dist/crossFileNearMiss.js.map +1 -1
  13. package/dist/duplicateSelection.cjs.map +1 -1
  14. package/dist/duplicateSelection.js.map +1 -1
  15. package/dist/duplication.cjs.map +1 -1
  16. package/dist/duplication.js.map +1 -1
  17. package/dist/exclusion.cjs.map +1 -1
  18. package/dist/exclusion.js.map +1 -1
  19. package/dist/git.cjs.map +1 -1
  20. package/dist/git.js.map +1 -1
  21. package/dist/languages.cjs.map +1 -1
  22. package/dist/languages.js.map +1 -1
  23. package/dist/metrics.cjs.map +1 -1
  24. package/dist/metrics.js.map +1 -1
  25. package/dist/nativeMetrics.cjs.map +1 -1
  26. package/dist/nativeMetrics.js.map +1 -1
  27. package/dist/scan.cjs.map +1 -1
  28. package/dist/scan.js.map +1 -1
  29. package/dist/thresholdCheck.cjs.map +1 -1
  30. package/dist/thresholdCheck.js.map +1 -1
  31. package/dist/thresholds.cjs.map +1 -1
  32. package/dist/thresholds.js.map +1 -1
  33. package/dist/wasmBinding.cjs +1 -1
  34. package/dist/wasmBinding.cjs.map +1 -1
  35. package/dist/wasmBinding.js +1 -1
  36. package/dist/wasmBinding.js.map +1 -1
  37. package/dist/worker.cjs.map +1 -1
  38. package/dist/worker.js.map +1 -1
  39. package/native/Cargo.lock +24 -24
  40. package/native/Cargo.toml +12 -12
  41. package/native/code-gauge.wasm +0 -0
  42. package/package.json +14 -14
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command, InvalidArgumentError } from 'commander';\nimport { getErrorMessage, parsePositiveInteger } from '@willbooster/shared-lib';\nimport { type CliOptions, configFileName, loadConfig, type ResolvedOptions, resolveOptions } from './cliConfig.js';\nimport type { CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport { runCheckCommand, type CheckCliOptions } from './checkCommand.js';\nimport { loadExclusion } from './exclusion.js';\nimport {\n addCrossFileDuplication,\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatPath,\n resolveTarget,\n scanTarget,\n writeStderr,\n writeStdout,\n type FileMetrics,\n type ScanResult,\n} from './scan.js';\nimport {\n duplicationThreshold,\n fileThresholds,\n functionThresholds,\n levels,\n thresholds,\n type Level,\n type Limits,\n} from './thresholds.js';\nimport { qualifyFunctionName } from './thresholdCheck.js';\nimport type { FunctionMetrics } from './types.js';\n\n/** The worst (highest-cognitive-complexity) function of a file, reported as the ranking evidence. */\ninterface WorstFunction {\n name: string;\n startLine: number;\n endLine: number;\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n}\n\n/**\n * One ranked refactoring candidate. The score is the sum of the file's repo-relative percentile\n * ranks (each in [0, 1)) over three dimensions: worst-function cognitive complexity, duplicated\n * lines (within-file and cross-file combined), and file NCSS. Ranking is relative to the scanned\n * project, so no absolute threshold is involved.\n */\ninterface RankedFile {\n file: string;\n score: number;\n worstFunction?: WorstFunction;\n /** Distinct lines covered by within-file duplicate blocks or cross-file duplicate occurrences. */\n duplicatedLineCount: number;\n /** duplicatedLineCount / code lines (0 when the file has no code). */\n duplicatedLineRatio: number;\n /** Other files sharing cross-file duplicate blocks; filled only for the reported top files. */\n crossFilePartners: string[];\n ncss: number;\n codeLines: number;\n}\n\n/** Caps how many cross-file partners a ranked file lists so the report stays scannable. */\nconst maxCrossFilePartners = 3;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${getErrorMessage(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics: rank refactoring candidates (the default command) or check thresholds.');\n\n addSharedOptions(\n program\n .command('rank', { isDefault: true })\n .description('Rank the files of a project by refactoring priority')\n .argument('[target]', 'file or directory to measure', '.')\n )\n .option('--top <number>', 'number of top-ranked files to report (default: 10)', parsePositiveIntegerOption)\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .action(runRankCommand);\n\n const check = addSharedOptions(\n program\n .command('check')\n .description(\n 'Report every exceeded threshold as a warning or an error (exit 1 on errors, 2 when files cannot be measured); with --base, only in what the change touches'\n )\n .argument('[target]', 'file or directory to check', '.')\n ).option('--base <ref>', 'check only what the working tree changed since the merge-base of this git ref and HEAD');\n for (const level of levels) {\n for (const { key, defaultLimits } of thresholds) {\n const defaultLimit = defaultLimits[level];\n check.option(\n `--${level}-${toKebabCase(key)} <number>`,\n `${describeLimit(key, level)} (default ${Number.isFinite(defaultLimit) ? defaultLimit : 'off'}); \"off\" disables it`,\n parseLimit\n );\n }\n }\n // Exit code 1 means error-level violations, so a rejected command line must not use it.\n check.exitOverride((error) => process.exit(error.exitCode === 0 ? 0 : 2));\n check.action(async (target: string, cliOptions: CheckCliOptions & Record<string, unknown>) => {\n const readLimits = (level: Level): Limits =>\n Object.fromEntries(\n thresholds.flatMap(({ key }) => {\n const limit = cliOptions[`${level}${key.charAt(0).toUpperCase()}${key.slice(1)}`];\n return limit === undefined ? [] : [[key, limit as number]];\n })\n );\n await runCheckCommand(target, cliOptions, { warning: readLimits('warning'), error: readLimits('error') });\n });\n\n await program.parseAsync();\n}\n\n/** Registers the options shared by the ranking and check commands. */\nfunction addSharedOptions(command: Command): Command {\n return command\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveIntegerOption\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--duplication-min-similarity-percent <number>',\n 'minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)',\n parsePercentInteger\n )\n .option('--include-tests', 'include test files and test directories')\n .option('--json', 'print JSON output');\n}\n\nfunction describeLimit(key: string, level: Level): string {\n if (key === duplicationThreshold.key) {\n return `code-line count from which a duplicated block is ${level === 'error' ? 'an error' : 'a warning'}`;\n }\n const fileThreshold = fileThresholds.find((threshold) => threshold.key === key);\n const subject = fileThreshold\n ? fileThreshold.label\n : `${functionThresholds.find((threshold) => threshold.key === key)?.label} of a function`;\n return `maximum ${subject} without ${level === 'error' ? 'an error' : 'a warning'}`;\n}\n\nfunction toKebabCase(key: string): string {\n return key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);\n}\n\nasync function runRankCommand(target: string, cliOptions: CliOptions): Promise<void> {\n const resolvedTarget = resolveTarget(target);\n const searchDirectory = await configSearchDirectory(resolvedTarget);\n const config = await loadConfig(cliOptions.config, searchDirectory);\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, {\n ...options,\n loadExclusion: (absolutePaths) => loadExclusion(searchDirectory, options.exclude, absolutePaths),\n });\n addCrossFileDuplication(result, options);\n const rankedFiles = rankFiles(result, options.top);\n\n if (options.json) {\n printJson(result, rankedFiles, options);\n } else {\n printTextReport(resolvedTarget, result, rankedFiles, options);\n }\n\n if (result.fatalError || (options.failOnError && result.errors.length > 0)) {\n process.exitCode = 1;\n }\n}\n\nfunction rankFiles(result: ScanResult, top: number): RankedFile[] {\n const candidates = result.files.map(({ file, metrics }) => {\n const formattedFile = formatPath(file, result.displayRoot);\n const duplicatedLines = collectDuplicatedLineNumbers(metrics, result.crossFileDuplication, formattedFile);\n return {\n file: formattedFile,\n worstFunction: findWorstFunction(metrics.functions),\n duplicatedLineCount: duplicatedLines.size,\n duplicatedLineRatio: metrics.lines.code === 0 ? 0 : duplicatedLines.size / metrics.lines.code,\n crossFilePartners: [] as string[],\n ncss: metrics.ncssCount,\n codeLines: metrics.lines.code,\n };\n });\n\n const cognitivePercentile = makePercentile(candidates.map((c) => c.worstFunction?.cognitiveComplexity ?? 0));\n const duplicationPercentile = makePercentile(candidates.map((c) => c.duplicatedLineCount));\n const ncssPercentile = makePercentile(candidates.map((c) => c.ncss));\n\n const ranked = candidates\n .map((candidate) => ({\n ...candidate,\n score:\n cognitivePercentile(candidate.worstFunction?.cognitiveComplexity ?? 0) +\n duplicationPercentile(candidate.duplicatedLineCount) +\n ncssPercentile(candidate.ncss),\n }))\n .toSorted(\n (left, right) => right.score - left.score || right.ncss - left.ncss || left.file.localeCompare(right.file)\n );\n // Partner evidence is attached only to the files that will be reported: expanding partners for\n // every scanned file first would retain TH(F^2) strings when one clone group spans F files, and\n // rescanning all groups per file would be O(files x groups) on the post-scan ranking step.\n attachCrossFilePartners(ranked.slice(0, top), result.crossFileDuplication);\n return ranked;\n}\n\n/** One pass over the groups fills the reported files' partner lists (other files sharing a group). */\nfunction attachCrossFilePartners(\n reportedFiles: RankedFile[],\n crossFileDuplication: CrossFileDuplicationMetrics | undefined\n): void {\n if (!crossFileDuplication) {\n return;\n }\n const partnersByFile = new Map(reportedFiles.map((ranked) => [ranked.file, new Set<string>()]));\n for (const group of crossFileDuplication.groups) {\n for (const file of group.files) {\n const partners = partnersByFile.get(file);\n if (!partners) {\n continue;\n }\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n for (const ranked of reportedFiles) {\n ranked.crossFilePartners = [...(partnersByFile.get(ranked.file) ?? [])].toSorted();\n }\n}\n\n/**\n * Percentile rank within the scanned project: the fraction of files with a strictly smaller\n * value, in [0, 1). Relative ranking needs no absolute threshold, which sidesteps the metric\n * calibration problem entirely — the top of the list is worth refactoring first regardless of\n * where any cutoff would sit.\n */\nfunction makePercentile(values: number[]): (value: number) => number {\n const sorted = values.toSorted((left, right) => left - right);\n return (value: number) => {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if ((sorted[middle] as number) < value) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return sorted.length === 0 ? 0 : low / sorted.length;\n };\n}\n\n/** The highest-cognitive-complexity function; NCSS breaks ties so the larger body is reported. */\nfunction findWorstFunction(functions: FunctionMetrics[]): WorstFunction | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (\n !worst ||\n fn.cognitiveComplexity > worst.cognitiveComplexity ||\n (fn.cognitiveComplexity === worst.cognitiveComplexity && fn.ncss > worst.ncss)\n ) {\n worst = fn;\n }\n }\n if (!worst) {\n return undefined;\n }\n return {\n name: qualifyFunctionName(worst),\n startLine: worst.startLine,\n endLine: worst.endLine,\n cognitiveComplexity: worst.cognitiveComplexity,\n ncss: worst.ncss,\n nestingDepth: worst.nestingDepth,\n };\n}\n\nfunction printJson(result: ScanResult, rankedFiles: RankedFile[], options: ResolvedOptions): void {\n const reportedFiles = rankedFiles.slice(0, options.top);\n writeStdout(\n JSON.stringify(\n {\n summary: summarize(result.files),\n totalRankedFiles: rankedFiles.length,\n truncated: reportedFiles.length < rankedFiles.length,\n files: reportedFiles,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(\n target: string,\n result: ScanResult,\n rankedFiles: RankedFile[],\n options: ResolvedOptions\n): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const summary = summarize(result.files);\n writeStdout(\n `Measured ${summary.fileCount} files under ${target} (code LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount})\\n`\n );\n\n if (rankedFiles.length === 0) {\n writeStdout('No measurable files found.\\n');\n } else {\n const reportedFiles = rankedFiles.slice(0, options.top);\n const totalSuffix = rankedFiles.length > reportedFiles.length ? ` of ${rankedFiles.length}` : '';\n writeStdout(`\\nRefactoring candidates (top ${reportedFiles.length}${totalSuffix}):\\n`);\n for (const [index, ranked] of reportedFiles.entries()) {\n writeStdout(`${index + 1}. ${formatRankedFile(ranked)}\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\n/** One ranked file as a single line: the location, the evidence, and where the duplication points. */\nfunction formatRankedFile(ranked: RankedFile): string {\n const reasons: string[] = [];\n if (ranked.worstFunction) {\n const fn = ranked.worstFunction;\n reasons.push(\n `worst function ${fn.name} (L${fn.startLine}-${fn.endLine}) cognitive ${fn.cognitiveComplexity}, NCSS ${fn.ncss}, nesting ${fn.nestingDepth}`\n );\n }\n if (ranked.duplicatedLineCount > 0) {\n const partnersSuffix =\n ranked.crossFilePartners.length > 0\n ? `, shared with ${ranked.crossFilePartners.slice(0, maxCrossFilePartners).join(', ')}${ranked.crossFilePartners.length > maxCrossFilePartners ? ', ...' : ''}`\n : '';\n reasons.push(\n `duplicated lines ${ranked.duplicatedLineCount} (${Math.round(ranked.duplicatedLineRatio * 100)}%${partnersSuffix})`\n );\n }\n reasons.push(`file NCSS ${ranked.ncss}`);\n return `${ranked.file} (score ${ranked.score.toFixed(2)}): ${reasons.join('; ')}`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n ncssCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functions.length;\n linesOfCode += file.metrics.lines.code;\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n }\n\n return { fileCount: files.length, functionCount, linesOfCode, maxCognitiveComplexity, ncssCount };\n}\n\nfunction parseLimit(value: string): number {\n if (value === 'off') {\n return Infinity;\n }\n const parsed = value.trim() === '' ? Number.NaN : Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative number or \"off\".');\n }\n return parsed;\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveIntegerOption(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveIntegerOption(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed === undefined) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n"],"mappings":";wsBAkEK,EAAK,CAAC,CAAC,MAAO,GAAmB,CACpC,EAAY,UAAU,EAAgB,CAAK,EAAE,GAAG,EAChD,QAAQ,SAAW,CACrB,CAAC,EAED,eAAe,GAAsB,CACnC,IAAM,EAAU,IAAI,EAAQ,CAAC,CAC1B,KAAK,YAAY,CAAC,CAClB,YAAY,8FAA8F,EAE7G,EACE,EACG,QA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aAAa,EAAO,MAAM,EAChC,GAAG,EAAO,KAAK,UAAU,EAAO,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAQ,KAAK,IAAI,GAChF,CAEA,SAAS,EAAU,EAMjB,CACA,IAAI,EAAgB,EAChB,EAAc,EACd,EAAyB,EACzB,EAAY,EAEhB,IAAK,IAAM,KAAQ,EACjB,GAAiB,EAAK,QAAQ,UAAU,OACxC,GAAe,EAAK,QAAQ,MAAM,KAClC,EAAyB,KAAK,IAAI,EAAwB,EAAK,QAAQ,sBAAsB,EAC7F,GAAa,EAAK,QAAQ,UAG5B,MAAO,CAAE,UAAW,EAAM,OAAQ,gBAAe,cAAa,yBAAwB,WAAU,CAClG,CAEA,SAAS,EAAW,EAAuB,CACzC,GAAI,IAAU,MACZ,MAAO,KAET,IAAM,EAAS,EAAM,KAAK,IAAM,GAAK,IAAa,OAAO,CAAK,EAC9D,GAAI,CAAC,OAAO,SAAS,CAAM,GAAK,EAAS,EACvC,MAAM,IAAI,EAAqB,0CAA0C,EAE3E,OAAO,CACT,CAEA,SAAS,EAAoB,EAAuB,CAClD,IAAM,EAAS,EAA2B,CAAK,EAC/C,GAAI,EAAS,IACX,MAAM,IAAI,EAAqB,wCAAwC,EAEzE,OAAO,CACT,CAEA,SAAS,EAAwB,EAAuB,CACtD,GAAI,CAAC,SAAS,KAAK,CAAK,EACtB,MAAM,IAAI,EAAqB,kCAAkC,EAGnE,IAAM,EAAS,OAAO,CAAK,EAC3B,GAAI,CAAC,OAAO,cAAc,CAAM,GAAK,EAAS,EAC5C,MAAM,IAAI,EAAqB,kCAAkC,EAEnE,OAAO,CACT,CAEA,SAAS,EAA2B,EAAuB,CACzD,IAAM,EAAS,EAAqB,CAAK,EACzC,GAAI,IAAW,IAAA,GACb,MAAM,IAAI,EAAqB,8BAA8B,EAE/D,OAAO,CACT"}
1
+ {"version":3,"file":"cli.js","names":["main","writeStderr","getErrorMessage","error","program","Command","addSharedOptions","parsePositiveIntegerOption","runRankCommand","check","level","levels","thresholds","defaultLimit","defaultLimits","toKebabCase","key","describeLimit","parseLimit","readLimits","limit","cliOptions","runCheckCommand","target","command","configFileName","parseNonNegativeInteger","parsePercentInteger","duplicationThreshold","fileThreshold","fileThresholds","threshold","functionThresholds","letter","resolvedTarget","resolveTarget","searchDirectory","configSearchDirectory","config","loadConfig","options","resolveOptions","result","scanTarget","loadExclusion","absolutePaths","addCrossFileDuplication","rankedFiles","rankFiles","printJson","printTextReport","candidates","formattedFile","formatPath","file","duplicatedLines","collectDuplicatedLineNumbers","metrics","findWorstFunction","cognitivePercentile","makePercentile","c","duplicationPercentile","ncssPercentile","ranked","candidate","right","left","attachCrossFilePartners","top","crossFileDuplication","partnersByFile","reportedFiles","group","partners","partner","sorted","values","low","high","middle","value","worst","fn","functions","qualifyFunctionName","writeStdout","summarize","summary","totalSuffix","index","formatRankedFile","warning","reasons","partnersSuffix","functionCount","linesOfCode","maxCognitiveComplexity","ncssCount","files","parsed","InvalidArgumentError","parsePositiveInteger"],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command, InvalidArgumentError } from 'commander';\nimport { getErrorMessage, parsePositiveInteger } from '@willbooster/shared-lib';\nimport { type CliOptions, configFileName, loadConfig, type ResolvedOptions, resolveOptions } from './cliConfig.js';\nimport type { CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport { runCheckCommand, type CheckCliOptions } from './checkCommand.js';\nimport { loadExclusion } from './exclusion.js';\nimport {\n addCrossFileDuplication,\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatPath,\n resolveTarget,\n scanTarget,\n writeStderr,\n writeStdout,\n type FileMetrics,\n type ScanResult,\n} from './scan.js';\nimport {\n duplicationThreshold,\n fileThresholds,\n functionThresholds,\n levels,\n thresholds,\n type Level,\n type Limits,\n} from './thresholds.js';\nimport { qualifyFunctionName } from './thresholdCheck.js';\nimport type { FunctionMetrics } from './types.js';\n\n/** The worst (highest-cognitive-complexity) function of a file, reported as the ranking evidence. */\ninterface WorstFunction {\n name: string;\n startLine: number;\n endLine: number;\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n}\n\n/**\n * One ranked refactoring candidate. The score is the sum of the file's repo-relative percentile\n * ranks (each in [0, 1)) over three dimensions: worst-function cognitive complexity, duplicated\n * lines (within-file and cross-file combined), and file NCSS. Ranking is relative to the scanned\n * project, so no absolute threshold is involved.\n */\ninterface RankedFile {\n file: string;\n score: number;\n worstFunction?: WorstFunction;\n /** Distinct lines covered by within-file duplicate blocks or cross-file duplicate occurrences. */\n duplicatedLineCount: number;\n /** duplicatedLineCount / code lines (0 when the file has no code). */\n duplicatedLineRatio: number;\n /** Other files sharing cross-file duplicate blocks; filled only for the reported top files. */\n crossFilePartners: string[];\n ncss: number;\n codeLines: number;\n}\n\n/** Caps how many cross-file partners a ranked file lists so the report stays scannable. */\nconst maxCrossFilePartners = 3;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${getErrorMessage(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics: rank refactoring candidates (the default command) or check thresholds.');\n\n addSharedOptions(\n program\n .command('rank', { isDefault: true })\n .description('Rank the files of a project by refactoring priority')\n .argument('[target]', 'file or directory to measure', '.')\n )\n .option('--top <number>', 'number of top-ranked files to report (default: 10)', parsePositiveIntegerOption)\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .action(runRankCommand);\n\n const check = addSharedOptions(\n program\n .command('check')\n .description(\n 'Report every exceeded threshold as a warning or an error (exit 1 on errors, 2 when files cannot be measured); with --base, only in what the change touches'\n )\n .argument('[target]', 'file or directory to check', '.')\n ).option('--base <ref>', 'check only what the working tree changed since the merge-base of this git ref and HEAD');\n for (const level of levels) {\n for (const { key, defaultLimits } of thresholds) {\n const defaultLimit = defaultLimits[level];\n check.option(\n `--${level}-${toKebabCase(key)} <number>`,\n `${describeLimit(key, level)} (default ${Number.isFinite(defaultLimit) ? defaultLimit : 'off'}); \"off\" disables it`,\n parseLimit\n );\n }\n }\n // Exit code 1 means error-level violations, so a rejected command line must not use it.\n check.exitOverride((error) => process.exit(error.exitCode === 0 ? 0 : 2));\n check.action(async (target: string, cliOptions: CheckCliOptions & Record<string, unknown>) => {\n const readLimits = (level: Level): Limits =>\n Object.fromEntries(\n thresholds.flatMap(({ key }) => {\n const limit = cliOptions[`${level}${key.charAt(0).toUpperCase()}${key.slice(1)}`];\n return limit === undefined ? [] : [[key, limit as number]];\n })\n );\n await runCheckCommand(target, cliOptions, { warning: readLimits('warning'), error: readLimits('error') });\n });\n\n await program.parseAsync();\n}\n\n/** Registers the options shared by the ranking and check commands. */\nfunction addSharedOptions(command: Command): Command {\n return command\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveIntegerOption\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--duplication-min-similarity-percent <number>',\n 'minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)',\n parsePercentInteger\n )\n .option('--include-tests', 'include test files and test directories')\n .option('--json', 'print JSON output');\n}\n\nfunction describeLimit(key: string, level: Level): string {\n if (key === duplicationThreshold.key) {\n return `code-line count from which a duplicated block is ${level === 'error' ? 'an error' : 'a warning'}`;\n }\n const fileThreshold = fileThresholds.find((threshold) => threshold.key === key);\n const subject = fileThreshold\n ? fileThreshold.label\n : `${functionThresholds.find((threshold) => threshold.key === key)?.label} of a function`;\n return `maximum ${subject} without ${level === 'error' ? 'an error' : 'a warning'}`;\n}\n\nfunction toKebabCase(key: string): string {\n return key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);\n}\n\nasync function runRankCommand(target: string, cliOptions: CliOptions): Promise<void> {\n const resolvedTarget = resolveTarget(target);\n const searchDirectory = await configSearchDirectory(resolvedTarget);\n const config = await loadConfig(cliOptions.config, searchDirectory);\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, {\n ...options,\n loadExclusion: (absolutePaths) => loadExclusion(searchDirectory, options.exclude, absolutePaths),\n });\n addCrossFileDuplication(result, options);\n const rankedFiles = rankFiles(result, options.top);\n\n if (options.json) {\n printJson(result, rankedFiles, options);\n } else {\n printTextReport(resolvedTarget, result, rankedFiles, options);\n }\n\n if (result.fatalError || (options.failOnError && result.errors.length > 0)) {\n process.exitCode = 1;\n }\n}\n\nfunction rankFiles(result: ScanResult, top: number): RankedFile[] {\n const candidates = result.files.map(({ file, metrics }) => {\n const formattedFile = formatPath(file, result.displayRoot);\n const duplicatedLines = collectDuplicatedLineNumbers(metrics, result.crossFileDuplication, formattedFile);\n return {\n file: formattedFile,\n worstFunction: findWorstFunction(metrics.functions),\n duplicatedLineCount: duplicatedLines.size,\n duplicatedLineRatio: metrics.lines.code === 0 ? 0 : duplicatedLines.size / metrics.lines.code,\n crossFilePartners: [] as string[],\n ncss: metrics.ncssCount,\n codeLines: metrics.lines.code,\n };\n });\n\n const cognitivePercentile = makePercentile(candidates.map((c) => c.worstFunction?.cognitiveComplexity ?? 0));\n const duplicationPercentile = makePercentile(candidates.map((c) => c.duplicatedLineCount));\n const ncssPercentile = makePercentile(candidates.map((c) => c.ncss));\n\n const ranked = candidates\n .map((candidate) => ({\n ...candidate,\n score:\n cognitivePercentile(candidate.worstFunction?.cognitiveComplexity ?? 0) +\n duplicationPercentile(candidate.duplicatedLineCount) +\n ncssPercentile(candidate.ncss),\n }))\n .toSorted(\n (left, right) => right.score - left.score || right.ncss - left.ncss || left.file.localeCompare(right.file)\n );\n // Partner evidence is attached only to the files that will be reported: expanding partners for\n // every scanned file first would retain TH(F^2) strings when one clone group spans F files, and\n // rescanning all groups per file would be O(files x groups) on the post-scan ranking step.\n attachCrossFilePartners(ranked.slice(0, top), result.crossFileDuplication);\n return ranked;\n}\n\n/** One pass over the groups fills the reported files' partner lists (other files sharing a group). */\nfunction attachCrossFilePartners(\n reportedFiles: RankedFile[],\n crossFileDuplication: CrossFileDuplicationMetrics | undefined\n): void {\n if (!crossFileDuplication) {\n return;\n }\n const partnersByFile = new Map(reportedFiles.map((ranked) => [ranked.file, new Set<string>()]));\n for (const group of crossFileDuplication.groups) {\n for (const file of group.files) {\n const partners = partnersByFile.get(file);\n if (!partners) {\n continue;\n }\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n for (const ranked of reportedFiles) {\n ranked.crossFilePartners = [...(partnersByFile.get(ranked.file) ?? [])].toSorted();\n }\n}\n\n/**\n * Percentile rank within the scanned project: the fraction of files with a strictly smaller\n * value, in [0, 1). Relative ranking needs no absolute threshold, which sidesteps the metric\n * calibration problem entirely — the top of the list is worth refactoring first regardless of\n * where any cutoff would sit.\n */\nfunction makePercentile(values: number[]): (value: number) => number {\n const sorted = values.toSorted((left, right) => left - right);\n return (value: number) => {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if ((sorted[middle] as number) < value) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return sorted.length === 0 ? 0 : low / sorted.length;\n };\n}\n\n/** The highest-cognitive-complexity function; NCSS breaks ties so the larger body is reported. */\nfunction findWorstFunction(functions: FunctionMetrics[]): WorstFunction | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (\n !worst ||\n fn.cognitiveComplexity > worst.cognitiveComplexity ||\n (fn.cognitiveComplexity === worst.cognitiveComplexity && fn.ncss > worst.ncss)\n ) {\n worst = fn;\n }\n }\n if (!worst) {\n return undefined;\n }\n return {\n name: qualifyFunctionName(worst),\n startLine: worst.startLine,\n endLine: worst.endLine,\n cognitiveComplexity: worst.cognitiveComplexity,\n ncss: worst.ncss,\n nestingDepth: worst.nestingDepth,\n };\n}\n\nfunction printJson(result: ScanResult, rankedFiles: RankedFile[], options: ResolvedOptions): void {\n const reportedFiles = rankedFiles.slice(0, options.top);\n writeStdout(\n JSON.stringify(\n {\n summary: summarize(result.files),\n totalRankedFiles: rankedFiles.length,\n truncated: reportedFiles.length < rankedFiles.length,\n files: reportedFiles,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(\n target: string,\n result: ScanResult,\n rankedFiles: RankedFile[],\n options: ResolvedOptions\n): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const summary = summarize(result.files);\n writeStdout(\n `Measured ${summary.fileCount} files under ${target} (code LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount})\\n`\n );\n\n if (rankedFiles.length === 0) {\n writeStdout('No measurable files found.\\n');\n } else {\n const reportedFiles = rankedFiles.slice(0, options.top);\n const totalSuffix = rankedFiles.length > reportedFiles.length ? ` of ${rankedFiles.length}` : '';\n writeStdout(`\\nRefactoring candidates (top ${reportedFiles.length}${totalSuffix}):\\n`);\n for (const [index, ranked] of reportedFiles.entries()) {\n writeStdout(`${index + 1}. ${formatRankedFile(ranked)}\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\n/** One ranked file as a single line: the location, the evidence, and where the duplication points. */\nfunction formatRankedFile(ranked: RankedFile): string {\n const reasons: string[] = [];\n if (ranked.worstFunction) {\n const fn = ranked.worstFunction;\n reasons.push(\n `worst function ${fn.name} (L${fn.startLine}-${fn.endLine}) cognitive ${fn.cognitiveComplexity}, NCSS ${fn.ncss}, nesting ${fn.nestingDepth}`\n );\n }\n if (ranked.duplicatedLineCount > 0) {\n const partnersSuffix =\n ranked.crossFilePartners.length > 0\n ? `, shared with ${ranked.crossFilePartners.slice(0, maxCrossFilePartners).join(', ')}${ranked.crossFilePartners.length > maxCrossFilePartners ? ', ...' : ''}`\n : '';\n reasons.push(\n `duplicated lines ${ranked.duplicatedLineCount} (${Math.round(ranked.duplicatedLineRatio * 100)}%${partnersSuffix})`\n );\n }\n reasons.push(`file NCSS ${ranked.ncss}`);\n return `${ranked.file} (score ${ranked.score.toFixed(2)}): ${reasons.join('; ')}`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n ncssCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functions.length;\n linesOfCode += file.metrics.lines.code;\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n }\n\n return { fileCount: files.length, functionCount, linesOfCode, maxCognitiveComplexity, ncssCount };\n}\n\nfunction parseLimit(value: string): number {\n if (value === 'off') {\n return Infinity;\n }\n const parsed = value.trim() === '' ? Number.NaN : Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative number or \"off\".');\n }\n return parsed;\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveIntegerOption(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveIntegerOption(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed === undefined) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n"],"mappings":";wsBAkEKA,EAAK,CAAC,CAAC,MAAO,GAAmB,CACpCC,EAAY,UAAUC,EAAgBC,CAAK,EAAE,GAAG,EAChD,QAAQ,SAAW,CACrB,CAAC,EAED,eAAeH,GAAsB,CACnC,IAAMI,EAAU,IAAIC,EAAQ,CAAC,CAC1B,KAAK,YAAY,CAAC,CAClB,YAAY,8FAA8F,EAE7GC,EACEF,EACG,QAAQ,OAAQ,CAAE,UAAW,EAAK,CAAC,CAAC,CACpC,YAAY,qDAAqD,CAAC,CAClE,SAAS,WAAY,+BAAgC,GAAG,CAC7D,CAAC,CACE,OAAO,iBAAkB,qDAAsDG,CAA0B,CAAC,CAC1G,OAAO,kBAAmB,8DAA8D,CAAC,CACzF,OAAOC,CAAc,EAExB,IAAMC,EAAQH,EACZF,EACG,QAAQ,OAAO,CAAC,CAChB,YACC,4JACF,CAAC,CACA,SAAS,WAAY,6BAA8B,GAAG,CAC3D,CAAC,CAAC,OAAO,eAAgB,wFAAwF,EACjH,IAAK,IAAMM,KAASC,EAClB,IAAK,GAAM,CAAE,MAAK,mBAAmBC,EAAY,CAC/C,IAAMC,EAAeC,EAAcJ,GACnCD,EAAM,OACJ,KAAKC,EAAM,GAAGK,EAAYC,CAAG,EAAE,WAC/B,GAAGC,EAAcD,EAAKN,CAAK,EAAE,YAAY,OAAO,SAASG,CAAY,EAAIA,EAAe,MAAM,sBAC9FK,CACF,CACF,CAGFT,EAAM,aAAc,GAAU,QAAQ,KAAKN,EAAM,WAAa,EAAI,EAAI,CAAC,CAAC,EACxEM,EAAM,OA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AAQ,MAAM,KAClC,EAAyB,KAAK,IAAI2C,EAAwB3C,EAAK,QAAQ,sBAAsB,EAC7F,GAAaA,EAAK,QAAQ,UAG5B,MAAO,CAAE,UAAW6C,EAAM,OAAQ,gBAAe,cAAa,yBAAwB,WAAU,CAClG,CAEA,SAASjF,EAAW,EAAuB,CACzC,GAAI+D,IAAU,MACZ,MAAO,KAET,IAAMmB,EAASnB,EAAM,KAAK,IAAM,GAAK,IAAa,OAAOA,CAAK,EAC9D,GAAI,CAAC,OAAO,SAASmB,CAAM,GAAKA,EAAS,EACvC,MAAM,IAAIC,EAAqB,0CAA0C,EAE3E,OAAOD,CACT,CAEA,SAASzE,EAAoB,EAAuB,CAClD,IAAMyE,EAAS7F,EAA2B0E,CAAK,EAC/C,GAAImB,EAAS,IACX,MAAM,IAAIC,EAAqB,wCAAwC,EAEzE,OAAOD,CACT,CAEA,SAAS1E,EAAwB,EAAuB,CACtD,GAAI,CAAC,SAAS,KAAKuD,CAAK,EACtB,MAAM,IAAIoB,EAAqB,kCAAkC,EAGnE,IAAMD,EAAS,OAAOnB,CAAK,EAC3B,GAAI,CAAC,OAAO,cAAcmB,CAAM,GAAKA,EAAS,EAC5C,MAAM,IAAIC,EAAqB,kCAAkC,EAEnE,OAAOD,CACT,CAEA,SAAS7F,EAA2B,EAAuB,CACzD,IAAM6F,EAASE,EAAqBrB,CAAK,EACzC,GAAImB,IAAW,IAAA,GACb,MAAM,IAAIC,EAAqB,8BAA8B,EAE/D,OAAOD,CACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"cliConfig.cjs","names":["defaultDuplicationOptions","readFile","getErrorMessage","path","stat","isRecord","levels","supportedLanguages","thresholds"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { getErrorMessage, isRecord } from '@willbooster/shared-lib';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { ExcludePatterns } from './exclusion.js';\nimport { supportedLanguages } from './languages.js';\nimport {\n levels,\n thresholds,\n type Level,\n type LevelThresholdsConfig,\n type Limits,\n type ThresholdsConfig,\n} from './thresholds.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Limits of `code-gauge check`. */\n thresholds?: ThresholdsConfig;\n /** Glob patterns, relative to the config file's directory, of files left out of every command. */\n exclude?: string[];\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** A parsed configuration file and the directory its relative settings resolve against. */\nexport interface LoadedConfig {\n config: CodeGaugeConfig;\n /** The config file's directory; the search start directory when no config file was found. */\n directory: string;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n exclude: ExcludePatterns;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, { config, directory }: LoadedConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n exclude: { patterns: config.exclude ?? [], root: directory },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<LoadedConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return { config: {}, directory: targetDirectory };\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n return { config: {}, directory: targetDirectory };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n\n return { config: validateConfig(parsed, configFile), directory: path.dirname(path.resolve(configFile)) };\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const knownKeys = new Set(['duplication', 'rank', 'thresholds', 'exclude', 'includeTests', 'failOnError']);\n for (const key of Object.keys(value)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (value.duplication !== undefined) {\n config.duplication = validateDuplicationObject(value.duplication, configFile);\n }\n\n if (value.rank !== undefined) {\n config.rank = validateRankObject(value.rank, configFile);\n }\n\n if (value.thresholds !== undefined) {\n config.thresholds = validateThresholdsObject(value.thresholds, configFile);\n }\n\n if (value.exclude !== undefined) {\n config.exclude = validateExcludePatterns(value.exclude, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (value[key] !== undefined) {\n config[key] = requireBoolean(value[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateExcludePatterns(value: unknown, configFile: string): string[] {\n if (!Array.isArray(value) || !value.every((pattern) => typeof pattern === 'string' && pattern !== '')) {\n throw new TypeError(`Config file \"${configFile}\": \"exclude\" must be an array of non-empty glob patterns.`);\n }\n return value as string[];\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateThresholdsObject(value: unknown, configFile: string): ThresholdsConfig {\n return Object.fromEntries(\n Object.entries(requireRecord(value, 'thresholds', configFile)).map(([level, levelThresholds]) => {\n if (!levels.includes(level as Level)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${level}\" in \"thresholds\" (expected ${levels.join(', ')}).`\n );\n }\n return [level, validateLevelThresholds(levelThresholds, `thresholds.${level}`, configFile)];\n })\n );\n}\n\nfunction validateLevelThresholds(value: unknown, settingName: string, configFile: string): LevelThresholdsConfig {\n const { languages, ...limits } = requireRecord(value, settingName, configFile);\n const languagesName = `${settingName}.languages`;\n return {\n limits: validateLimits(limits, settingName, ['languages'], configFile),\n languages: Object.fromEntries(\n Object.entries(languages === undefined ? {} : requireRecord(languages, languagesName, configFile)).map(\n ([language, overrides]) => {\n if (!supportedLanguages.includes(language)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language \"${language}\" in \"${languagesName}\" (expected ${supportedLanguages.join(', ')}).`\n );\n }\n const languageName = `${languagesName}.${language}`;\n return [\n language,\n validateLimits(requireRecord(overrides, languageName, configFile), languageName, [], configFile),\n ];\n }\n )\n ),\n };\n}\n\n/** Limits as written in the config file, where `null` disables one. */\nfunction validateLimits(\n value: Record<string, unknown>,\n settingName: string,\n otherKeys: string[],\n configFile: string\n): Limits {\n const knownKeys = thresholds.map(({ key }) => key);\n return Object.fromEntries(\n Object.entries(value).map(([key, limit]) => {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${[...knownKeys, ...otherKeys].join(', ')}).`\n );\n }\n if (limit !== null && (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}.${key}\" must be a non-negative number or null.`);\n }\n return [key, limit ?? Infinity];\n })\n );\n}\n\nfunction requireRecord(value: unknown, settingName: string, configFile: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n return value;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n"],"mappings":"0QAgBA,MAAa,EAAiB,yBAgD9B,SAAgB,EAAe,EAAiB,CAAE,SAAQ,aAA4C,CACpG,MAAO,CACL,YAAa,CACX,UAAW,EAAI,sBAAwB,EAAO,aAAa,WAAaA,EAAAA,0BAA0B,UAClG,aACE,EAAI,yBAA2B,EAAO,aAAa,cAAgBA,EAAAA,0BAA0B,aAC/F,qBACE,EAAI,iCACJ,EAAO,aAAa,sBACpBA,EAAAA,0BAA0B,oBAC9B,EACA,QAAS,CAAE,SAAU,EAAO,SAAW,CAAC,EAAG,KAAM,CAAU,EAC3D,IAAK,EAAI,KAAO,EAAO,MAAM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AC7F,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,IAAM,EAAS,EAAc,EAAO,EAAK,EAAY,OAAO,cAAe,oBAAoB,EAC/F,GAAI,EAAS,EACX,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAGA,SAAS,EACP,EACA,EACA,EACA,EACA,EACQ,CACR,GAAI,OAAO,GAAU,UAAY,CAAC,EAAY,CAAK,GAAK,EAAQ,EAC9D,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,YAAY,EAAY,EAAE,EAEjF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT"}
1
+ {"version":3,"file":"cliConfig.cjs","names":["defaultDuplicationOptions","readFile","getErrorMessage","path","stat","isRecord","levels","supportedLanguages","thresholds","require_runtime","require_duplication","require_languages","require_thresholds","_willbooster_shared_lib","node_fs_promises","node_path","configFileName","resolveOptions","cli","config","directory","loadConfig","configFile","explicitPath","findNearestConfig","targetDirectory","content","error","parsed","validateConfig","currentDirectory","fileExists","parentDirectory","file","value","knownKeys","key","validateDuplicationObject","validateRankObject","validateThresholdsObject","validateExcludePatterns","requireBoolean","pattern","rank","setting","requirePositiveInteger","requireRecord","level","levelThresholds","validateLevelThresholds","limits","settingName","languagesName","validateLimits","languages","language","overrides","languageName","limit","otherKeys","duplication","requireNonNegativeInteger","requireNumber","isValidKind","description"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { getErrorMessage, isRecord } from '@willbooster/shared-lib';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { ExcludePatterns } from './exclusion.js';\nimport { supportedLanguages } from './languages.js';\nimport {\n levels,\n thresholds,\n type Level,\n type LevelThresholdsConfig,\n type Limits,\n type ThresholdsConfig,\n} from './thresholds.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Limits of `code-gauge check`. */\n thresholds?: ThresholdsConfig;\n /** Glob patterns, relative to the config file's directory, of files left out of every command. */\n exclude?: string[];\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** A parsed configuration file and the directory its relative settings resolve against. */\nexport interface LoadedConfig {\n config: CodeGaugeConfig;\n /** The config file's directory; the search start directory when no config file was found. */\n directory: string;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n exclude: ExcludePatterns;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, { config, directory }: LoadedConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n exclude: { patterns: config.exclude ?? [], root: directory },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<LoadedConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return { config: {}, directory: targetDirectory };\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n return { config: {}, directory: targetDirectory };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n\n return { config: validateConfig(parsed, configFile), directory: path.dirname(path.resolve(configFile)) };\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const knownKeys = new Set(['duplication', 'rank', 'thresholds', 'exclude', 'includeTests', 'failOnError']);\n for (const key of Object.keys(value)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (value.duplication !== undefined) {\n config.duplication = validateDuplicationObject(value.duplication, configFile);\n }\n\n if (value.rank !== undefined) {\n config.rank = validateRankObject(value.rank, configFile);\n }\n\n if (value.thresholds !== undefined) {\n config.thresholds = validateThresholdsObject(value.thresholds, configFile);\n }\n\n if (value.exclude !== undefined) {\n config.exclude = validateExcludePatterns(value.exclude, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (value[key] !== undefined) {\n config[key] = requireBoolean(value[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateExcludePatterns(value: unknown, configFile: string): string[] {\n if (!Array.isArray(value) || !value.every((pattern) => typeof pattern === 'string' && pattern !== '')) {\n throw new TypeError(`Config file \"${configFile}\": \"exclude\" must be an array of non-empty glob patterns.`);\n }\n return value as string[];\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateThresholdsObject(value: unknown, configFile: string): ThresholdsConfig {\n return Object.fromEntries(\n Object.entries(requireRecord(value, 'thresholds', configFile)).map(([level, levelThresholds]) => {\n if (!levels.includes(level as Level)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${level}\" in \"thresholds\" (expected ${levels.join(', ')}).`\n );\n }\n return [level, validateLevelThresholds(levelThresholds, `thresholds.${level}`, configFile)];\n })\n );\n}\n\nfunction validateLevelThresholds(value: unknown, settingName: string, configFile: string): LevelThresholdsConfig {\n const { languages, ...limits } = requireRecord(value, settingName, configFile);\n const languagesName = `${settingName}.languages`;\n return {\n limits: validateLimits(limits, settingName, ['languages'], configFile),\n languages: Object.fromEntries(\n Object.entries(languages === undefined ? {} : requireRecord(languages, languagesName, configFile)).map(\n ([language, overrides]) => {\n if (!supportedLanguages.includes(language)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language \"${language}\" in \"${languagesName}\" (expected ${supportedLanguages.join(', ')}).`\n );\n }\n const languageName = `${languagesName}.${language}`;\n return [\n language,\n validateLimits(requireRecord(overrides, languageName, configFile), languageName, [], configFile),\n ];\n }\n )\n ),\n };\n}\n\n/** Limits as written in the config file, where `null` disables one. */\nfunction validateLimits(\n value: Record<string, unknown>,\n settingName: string,\n otherKeys: string[],\n configFile: string\n): Limits {\n const knownKeys = thresholds.map(({ key }) => key);\n return Object.fromEntries(\n Object.entries(value).map(([key, limit]) => {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${[...knownKeys, ...otherKeys].join(', ')}).`\n );\n }\n if (limit !== null && (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}.${key}\" must be a non-negative number or null.`);\n }\n return [key, limit ?? Infinity];\n })\n );\n}\n\nfunction requireRecord(value: unknown, settingName: string, configFile: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n return value;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n"],"mappings":"0QAgBA,MAAagB,EAAiB,yBAgD9B,SAAgBC,EAAe,EAAiB,CAAE,SAAQ,aAA4C,CACpG,MAAO,CACL,YAAa,CACX,UAAWC,EAAI,sBAAwBC,EAAO,aAAa,WAAanB,EAAAA,0BAA0B,UAClG,aACEkB,EAAI,yBAA2BC,EAAO,aAAa,cAAgBnB,EAAAA,0BAA0B,aAC/F,qBACEkB,EAAI,iCACJC,EAAO,aAAa,sBACpBnB,EAAAA,0BAA0B,oBAC9B,EACA,QAAS,CAAE,SAAUmB,EAAO,SAAW,CAAC,EAAG,KAAMC,CAAU,EAC3D,IAAKF,EAAI,KAAOC,EAAO,MAAM,KAAA,GAC7B,aAAcD,EAAI,cAAgBC,EAAO,cAAg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F,GAAIM,EAAS,IACX,MAAU,MAAM,gBAAgBN,EAAW,iEAAiE,EAE9G,EAAY,qBAAuBM,CACrC,MACE,MAAU,MACR,gBAAgBN,EAAW,sBAAsBc,EAAI,gFACvD,EAGJ,OAAOwB,CACT,CAEA,SAASC,EAA0B,EAAgB,EAAa,EAA4B,CAC1F,OAAOC,EAAc5B,EAAOE,EAAKd,EAAY,OAAO,cAAe,wBAAwB,CAC7F,CAEA,SAASuB,EAAuB,EAAgB,EAAa,EAA4B,CACvF,IAAMjB,EAASkC,EAAc5B,EAAOE,EAAKd,EAAY,OAAO,cAAe,oBAAoB,EAC/F,GAAIM,EAAS,EACX,MAAU,MAAM,gBAAgBN,EAAW,MAAMc,EAAI,8BAA8B,EAErF,OAAOR,CACT,CAGA,SAASkC,EACP,EACA,EACA,EACA,EACA,EACQ,CACR,GAAI,OAAO5B,GAAU,UAAY,CAAC6B,EAAY7B,CAAK,GAAKA,EAAQ,EAC9D,MAAU,MAAM,gBAAgBZ,EAAW,MAAMc,EAAI,YAAY4B,EAAY,EAAE,EAEjF,OAAO9B,CACT,CAEA,SAASO,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAOP,GAAU,UACnB,MAAU,UAAU,gBAAgBZ,EAAW,MAAMc,EAAI,qBAAqB,EAEhF,OAAOF,CACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"cliConfig.js","names":[],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { getErrorMessage, isRecord } from '@willbooster/shared-lib';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { ExcludePatterns } from './exclusion.js';\nimport { supportedLanguages } from './languages.js';\nimport {\n levels,\n thresholds,\n type Level,\n type LevelThresholdsConfig,\n type Limits,\n type ThresholdsConfig,\n} from './thresholds.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Limits of `code-gauge check`. */\n thresholds?: ThresholdsConfig;\n /** Glob patterns, relative to the config file's directory, of files left out of every command. */\n exclude?: string[];\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** A parsed configuration file and the directory its relative settings resolve against. */\nexport interface LoadedConfig {\n config: CodeGaugeConfig;\n /** The config file's directory; the search start directory when no config file was found. */\n directory: string;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n exclude: ExcludePatterns;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, { config, directory }: LoadedConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n exclude: { patterns: config.exclude ?? [], root: directory },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<LoadedConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return { config: {}, directory: targetDirectory };\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n return { config: {}, directory: targetDirectory };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n\n return { config: validateConfig(parsed, configFile), directory: path.dirname(path.resolve(configFile)) };\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const knownKeys = new Set(['duplication', 'rank', 'thresholds', 'exclude', 'includeTests', 'failOnError']);\n for (const key of Object.keys(value)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (value.duplication !== undefined) {\n config.duplication = validateDuplicationObject(value.duplication, configFile);\n }\n\n if (value.rank !== undefined) {\n config.rank = validateRankObject(value.rank, configFile);\n }\n\n if (value.thresholds !== undefined) {\n config.thresholds = validateThresholdsObject(value.thresholds, configFile);\n }\n\n if (value.exclude !== undefined) {\n config.exclude = validateExcludePatterns(value.exclude, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (value[key] !== undefined) {\n config[key] = requireBoolean(value[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateExcludePatterns(value: unknown, configFile: string): string[] {\n if (!Array.isArray(value) || !value.every((pattern) => typeof pattern === 'string' && pattern !== '')) {\n throw new TypeError(`Config file \"${configFile}\": \"exclude\" must be an array of non-empty glob patterns.`);\n }\n return value as string[];\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateThresholdsObject(value: unknown, configFile: string): ThresholdsConfig {\n return Object.fromEntries(\n Object.entries(requireRecord(value, 'thresholds', configFile)).map(([level, levelThresholds]) => {\n if (!levels.includes(level as Level)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${level}\" in \"thresholds\" (expected ${levels.join(', ')}).`\n );\n }\n return [level, validateLevelThresholds(levelThresholds, `thresholds.${level}`, configFile)];\n })\n );\n}\n\nfunction validateLevelThresholds(value: unknown, settingName: string, configFile: string): LevelThresholdsConfig {\n const { languages, ...limits } = requireRecord(value, settingName, configFile);\n const languagesName = `${settingName}.languages`;\n return {\n limits: validateLimits(limits, settingName, ['languages'], configFile),\n languages: Object.fromEntries(\n Object.entries(languages === undefined ? {} : requireRecord(languages, languagesName, configFile)).map(\n ([language, overrides]) => {\n if (!supportedLanguages.includes(language)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language \"${language}\" in \"${languagesName}\" (expected ${supportedLanguages.join(', ')}).`\n );\n }\n const languageName = `${languagesName}.${language}`;\n return [\n language,\n validateLimits(requireRecord(overrides, languageName, configFile), languageName, [], configFile),\n ];\n }\n )\n ),\n };\n}\n\n/** Limits as written in the config file, where `null` disables one. */\nfunction validateLimits(\n value: Record<string, unknown>,\n settingName: string,\n otherKeys: string[],\n configFile: string\n): Limits {\n const knownKeys = thresholds.map(({ key }) => key);\n return Object.fromEntries(\n Object.entries(value).map(([key, limit]) => {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${[...knownKeys, ...otherKeys].join(', ')}).`\n );\n }\n if (limit !== null && (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}.${key}\" must be a non-negative number or null.`);\n }\n return [key, limit ?? Infinity];\n })\n );\n}\n\nfunction requireRecord(value: unknown, settingName: string, configFile: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n return value;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n"],"mappings":"iUAgBA,MAAa,EAAiB,yBAgD9B,SAAgB,EAAe,EAAiB,CAAE,SAAQ,aAA4C,CACpG,MAAO,CACL,YAAa,CACX,UAAW,EAAI,sBAAwB,EAAO,aAAa,WAAa,EAA0B,UAClG,aACE,EAAI,yBAA2B,EAAO,aAAa,cAAgB,EAA0B,aAC/F,qBACE,EAAI,iCACJ,EAAO,aAAa,sBACpB,EAA0B,oBAC9B,EACA,QAAS,CAAE,SAAU,EAAO,SAAW,CAAC,EAAG,KAAM,CAAU,EAC3D,IAAK,EAAI,KAAO,EAAO,MAAM,KAAA,GAC7B,aAAc,EAAI,cAAgB,EAAO,cAAgB,GACzD,YAAa,EAAI,aAAe,EAAO,aAAe,GACtD,KAAM,EAAI,MAAQ,EACpB,CACF,CAMA,eAAsB,EAAW,EAAkC,EAAgD,CACjH,IAAM,EAAa,GAAiB,MAAM,EAAkB,CAAe,EAC3E,G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AU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT"}
1
+ {"version":3,"file":"cliConfig.js","names":["path","configFileName","resolveOptions","cli","config","defaultDuplicationOptions","directory","loadConfig","configFile","explicitPath","findNearestConfig","targetDirectory","content","readFile","error","getErrorMessage","parsed","validateConfig","currentDirectory","fileExists","parentDirectory","stat","file","isRecord","value","knownKeys","key","validateDuplicationObject","validateRankObject","validateThresholdsObject","validateExcludePatterns","requireBoolean","pattern","rank","setting","requirePositiveInteger","requireRecord","level","levelThresholds","levels","validateLevelThresholds","limits","settingName","languagesName","validateLimits","languages","language","overrides","supportedLanguages","languageName","thresholds","limit","otherKeys","duplication","requireNonNegativeInteger","requireNumber","isValidKind","description"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { getErrorMessage, isRecord } from '@willbooster/shared-lib';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { ExcludePatterns } from './exclusion.js';\nimport { supportedLanguages } from './languages.js';\nimport {\n levels,\n thresholds,\n type Level,\n type LevelThresholdsConfig,\n type Limits,\n type ThresholdsConfig,\n} from './thresholds.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Limits of `code-gauge check`. */\n thresholds?: ThresholdsConfig;\n /** Glob patterns, relative to the config file's directory, of files left out of every command. */\n exclude?: string[];\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** A parsed configuration file and the directory its relative settings resolve against. */\nexport interface LoadedConfig {\n config: CodeGaugeConfig;\n /** The config file's directory; the search start directory when no config file was found. */\n directory: string;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n exclude: ExcludePatterns;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, { config, directory }: LoadedConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n exclude: { patterns: config.exclude ?? [], root: directory },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<LoadedConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return { config: {}, directory: targetDirectory };\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n return { config: {}, directory: targetDirectory };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n\n return { config: validateConfig(parsed, configFile), directory: path.dirname(path.resolve(configFile)) };\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const knownKeys = new Set(['duplication', 'rank', 'thresholds', 'exclude', 'includeTests', 'failOnError']);\n for (const key of Object.keys(value)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (value.duplication !== undefined) {\n config.duplication = validateDuplicationObject(value.duplication, configFile);\n }\n\n if (value.rank !== undefined) {\n config.rank = validateRankObject(value.rank, configFile);\n }\n\n if (value.thresholds !== undefined) {\n config.thresholds = validateThresholdsObject(value.thresholds, configFile);\n }\n\n if (value.exclude !== undefined) {\n config.exclude = validateExcludePatterns(value.exclude, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (value[key] !== undefined) {\n config[key] = requireBoolean(value[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateExcludePatterns(value: unknown, configFile: string): string[] {\n if (!Array.isArray(value) || !value.every((pattern) => typeof pattern === 'string' && pattern !== '')) {\n throw new TypeError(`Config file \"${configFile}\": \"exclude\" must be an array of non-empty glob patterns.`);\n }\n return value as string[];\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateThresholdsObject(value: unknown, configFile: string): ThresholdsConfig {\n return Object.fromEntries(\n Object.entries(requireRecord(value, 'thresholds', configFile)).map(([level, levelThresholds]) => {\n if (!levels.includes(level as Level)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${level}\" in \"thresholds\" (expected ${levels.join(', ')}).`\n );\n }\n return [level, validateLevelThresholds(levelThresholds, `thresholds.${level}`, configFile)];\n })\n );\n}\n\nfunction validateLevelThresholds(value: unknown, settingName: string, configFile: string): LevelThresholdsConfig {\n const { languages, ...limits } = requireRecord(value, settingName, configFile);\n const languagesName = `${settingName}.languages`;\n return {\n limits: validateLimits(limits, settingName, ['languages'], configFile),\n languages: Object.fromEntries(\n Object.entries(languages === undefined ? {} : requireRecord(languages, languagesName, configFile)).map(\n ([language, overrides]) => {\n if (!supportedLanguages.includes(language)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language \"${language}\" in \"${languagesName}\" (expected ${supportedLanguages.join(', ')}).`\n );\n }\n const languageName = `${languagesName}.${language}`;\n return [\n language,\n validateLimits(requireRecord(overrides, languageName, configFile), languageName, [], configFile),\n ];\n }\n )\n ),\n };\n}\n\n/** Limits as written in the config file, where `null` disables one. */\nfunction validateLimits(\n value: Record<string, unknown>,\n settingName: string,\n otherKeys: string[],\n configFile: string\n): Limits {\n const knownKeys = thresholds.map(({ key }) => key);\n return Object.fromEntries(\n Object.entries(value).map(([key, limit]) => {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${[...knownKeys, ...otherKeys].join(', ')}).`\n );\n }\n if (limit !== null && (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}.${key}\" must be a non-negative number or null.`);\n }\n return [key, limit ?? Infinity];\n })\n );\n}\n\nfunction requireRecord(value: unknown, settingName: string, configFile: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n return value;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n"],"mappings":"iUAgBA,MAAaC,EAAiB,yBAgD9B,SAAgBC,EAAe,EAAiB,CAAE,SAAQ,aAA4C,CACpG,MAAO,CACL,YAAa,CACX,UAAWC,EAAI,sBAAwBC,EAAO,aAAa,WAAaC,EAA0B,UAClG,aACEF,EAAI,yBAA2BC,EAAO,aAAa,cAAgBC,EAA0B,aAC/F,qBACEF,EAAI,iCACJC,EAAO,aAAa,sBACpBC,EAA0B,oBAC9B,EACA,QAAS,CAAE,SAAUD,EAAO,SAAW,CAAC,EAAG,KAAME,CAAU,EAC3D,IAAKH,EAAI,KAAOC,EAAO,MAAM,KAAA,GAC7B,aAAcD,EAAI,cAAgBC,EAAO,cAAgB,GACzD,YAAaD,EAAI,aAAeC,EAAO,aAAe,GACtD,KAAMD,EAAI,MAAQ,EACpB,CACF,CAMA,eAAsBI,EAAW,EAAkC,EAAgD,CACjH,IAAMC,EAAaC,GAAiB,MAAMC,EAAkBC,CAAe,EAC3E,GAAI,CAACH,EACH,MAAO,CAAE,OAAQ,CAAC,EAAG,UAAWG,CAAgB,EAGlD,IAAIC,EACJ,GAAI,CACF,EAAU,MAAMC,EAASL,EAAY,MAAM,CAC7C,OAASM,EAAO,CACd,GAAIL,EACF,MAAU,MAAM,4BAA4BD,EAAW,KAAKO,EAAgBD,CAAK,GAAG,EAEtF,MAAO,CAAE,OAAQ,CAAC,EAAG,UAAWH,CAAgB,CAClD,CAEA,IAAIK,EACJ,GAAI,CACF,EAAS,KAAK,MAAMJ,CAAO,CAC7B,OAASE,EAAO,CACd,MAAU,MAAM,gCAAg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kB,EAAI,qBAAqB,EAEhF,OAAOF,CACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"crossFileDuplication.cjs","names":["resolveDuplicationOptions","selectMaximalGroups","collectCrossFileNearMissGroups","buildLiteralCountPrefix","collectSequenceWindowCandidates","mergeAdjacentGroups","countRedundantFragments","collectMatchedLines"],"sources":["../src/crossFileDuplication.ts"],"sourcesContent":["import { collectCrossFileNearMissGroups } from './crossFileNearMiss.js';\nimport { selectMaximalGroups, type SelectableRegion } from './duplicateSelection.js';\nimport {\n buildLiteralCountPrefix,\n collectMatchedLines,\n collectSequenceWindowCandidates,\n countRedundantFragments,\n mergeAdjacentGroups,\n resolveDuplicationOptions,\n type CountedOccurrence,\n type CrossFileDuplicateCandidate,\n type CrossFileDuplicationFileData,\n type SequenceWindowContext,\n type TokenSegment,\n} from './duplication.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport interface CrossFileDuplicationSourceFile extends Partial<CrossFileDuplicationFileData> {\n file: string;\n candidates: CrossFileDuplicateCandidate[];\n}\n\nexport interface CrossFileDuplicateOccurrence {\n endLine: number;\n file: string;\n /**\n * The code lines carrying the occurrence's matched tokens (see\n * DuplicateBlockOccurrence.lineNumbers). Absent for a file that supplied only candidates (no\n * `tokens`), whose matched lines are unknowable.\n */\n lineNumbers?: number[];\n startLine: number;\n /**\n * The tokens of its matched runs, or of a near-miss block or its matched cores with the edited\n * tokens among them; the group's `tokenCount` is the smallest of its occurrences'.\n */\n tokenCount: number;\n}\n\nexport interface CrossFileDuplicateBlockGroup {\n files: string[];\n occurrences: CrossFileDuplicateOccurrence[];\n /**\n * Token count of the smallest occurrence. For exact and gapped groups it is the matched token\n * count every occurrence shares (gaps are not counted); for near-miss (Type-3) groups it is the\n * token count of the smallest whole block or set of matched cores, edited tokens included.\n */\n tokenCount: number;\n}\n\nexport interface CrossFileDuplicationMetrics {\n /** Number of redundant copies across all groups, counted per matched fragment like within-file. */\n duplicateBlockCount: number;\n /** Groups the file participates in, keyed by the file name passed in. */\n duplicateBlockGroupCountByFile: Record<string, number>;\n /**\n * Per file, the 1-based code lines covered by the tokens of its cross-file occurrences, sorted\n * ascending: the matched tokens of exact and gapped occurrences, and the lines of a near-miss\n * block or its matched cores more than half of whose tokens its partners match or which a part of it\n * matched exactly reaches (like within-file near-miss coverage). The unmatched gap of a merged\n * clone and comment/blank lines inside an occurrence's bounding range are excluded (blank rows\n * inside multi-row tokens only when the file supplied codeLineNumbers). A file that supplied\n * only candidates (no `tokens`) has no entry — without its token stream the covered lines are\n * unknowable, and an approximate bounding range would break this field's exactness.\n */\n duplicateLineNumbersByFile: Record<string, number[]>;\n groups: CrossFileDuplicateBlockGroup[];\n}\n\ninterface SelectableCandidate extends CrossFileDuplicateCandidate, SelectableRegion {\n regionBucket: number;\n file: string;\n}\n\n/** A cross-file occurrence: a within-file occurrence in the project-wide token index space. */\ninterface CrossFileOccurrence extends CountedOccurrence {\n file: string;\n fileIndex: number;\n}\n\n/**\n * Detects code regions duplicated across files. Per-file candidates (whole block subtrees and full\n * container runs, fingerprinted with the same normalization as within-file duplication) are joined\n * by a project-level window index over per-statement fingerprint sequences (CPD-style), so a\n * copy-pasted partial statement run embedded in different surrounding code is matched even though\n * no single file can know it repeats elsewhere. Candidates are grouped by fingerprint, and only\n * maximal, non-overlapping regions whose group spans at least two files are counted. Groups that\n * shrink to a single file during selection are shed — a within-file repeat is already reported by\n * that file's own duplication metrics. A copy nested inside a larger group's region (two files share\n * a whole function, a third file only a block of it) is reported with its group, so the third\n * file's copy still shows what it duplicates. Groups separated by a small token gap within each file then\n * merge into gapped (Type-3) clone groups under `maxGapTokens`, exactly like within-file merging.\n * Finally, blocks of files that supplied `nearMissBlocks` are compared across files for near-miss\n * (Type-3) clones under `minSimilarityPercent` (see crossFileNearMiss.ts).\n */\nexport function measureCrossFileDuplication(\n files: CrossFileDuplicationSourceFile[],\n options?: DuplicationOptions\n): CrossFileDuplicationMetrics {\n const { minTokens, maxGapTokens, minSimilarityPercent } = resolveDuplicationOptions(options);\n const candidates: SelectableCandidate[] = files.flatMap(({ file, candidates }, fileIndex) =>\n candidates.map((candidate) => ({ ...candidate, regionBucket: fileIndex, file }))\n );\n // Pushed one by one: spreading the project-scale window-candidate array as call arguments\n // overflows V8's argument limit (~124k) and crashes on Node, though Bun/JSC tolerates it.\n for (const candidate of collectWindowCandidates(files, minTokens)) {\n candidates.push(candidate);\n }\n const counted = selectMaximalGroups(\n candidates,\n spansMultipleFiles,\n // File index and position break coverage ties deterministically.\n (left, right) => left.regionBucket - right.regionBucket || left.startIndex - right.startIndex\n );\n const tokenOffsets = computeTokenOffsets(files, maxGapTokens);\n const exactGroups = mergeGapAdjacentGroups([...counted.values()], tokenOffsets, maxGapTokens);\n const nearMissGroups = collectNearMissGroups(files, exactGroups, tokenOffsets, minTokens, minSimilarityPercent);\n return summarize(takeOverExactGroups(exactGroups, nearMissGroups, minTokens), files, tokenOffsets);\n}\n\n/**\n * Lets a near-miss group take over the exact groups standing for the same copies, as within a\n * file (collect_near_miss_groups in native/src/duplication.rs): every occurrence of such a group\n * overlaps exactly one copy of the near-miss group (one overlapping none reports content the copies\n * do not share, and one reaching into two would make one copy take over lines of the next), exceeds\n * its span by less than `minTokens` (a copy is listed at the size it matched, not at that of a\n * clone larger by a reportable part, which may run into code no copy matched), and no two overlap\n * the same copy (those repeat within the copy, not between the copies).\n * Each copy then becomes one occurrence with the exact fragments it holds, so the copies are\n * listed once.\n */\nfunction takeOverExactGroups(\n exactGroups: CrossFileOccurrence[][],\n nearMissGroups: CrossFileOccurrence[][],\n minTokens: number\n): CrossFileOccurrence[][] {\n const exactGroupIndexesByFile = new Map<number, Set<number>>();\n for (const [groupIndex, group] of exactGroups.entries()) {\n for (const { fileIndex } of group) {\n const indexes = exactGroupIndexesByFile.get(fileIndex) ?? new Set();\n indexes.add(groupIndex);\n exactGroupIndexesByFile.set(fileIndex, indexes);\n }\n }\n const taken = new Set<number>();\n const coalesced = new Set<CrossFileOccurrence>();\n const merged = nearMissGroups.map((copies) => {\n const copyOf = (occurrence: CrossFileOccurrence): CrossFileOccurrence | undefined => {\n const overlapped = copies.filter((copy) =>\n copy.segments.some((segment) => occurrence.segments.some((matched) => overlap(matched, segment)))\n );\n const [copy] = overlapped;\n if (overlapped.length !== 1 || !copy) {\n return undefined;\n }\n const excess =\n Math.max(0, copy.startTokenIndex - occurrence.startTokenIndex) +\n Math.max(0, occurrence.endTokenIndex - copy.endTokenIndex);\n return excess < minTokens ? copy : undefined;\n };\n const fragmentsByCopy = new Map<CrossFileOccurrence, CrossFileOccurrence[]>();\n const candidateIndexes = new Set<number>();\n for (const copy of copies) {\n for (const groupIndex of copy.spanCountedElsewhere ? (exactGroupIndexesByFile.get(copy.fileIndex) ?? []) : []) {\n candidateIndexes.add(groupIndex);\n }\n }\n for (const groupIndex of [...candidateIndexes].toSorted((left, right) => left - right)) {\n const group = exactGroups[groupIndex] ?? [];\n const owners = group.map(copyOf);\n if (taken.has(groupIndex) || owners.includes(undefined) || new Set(owners).size !== owners.length) {\n continue;\n }\n taken.add(groupIndex);\n for (const [index, owner] of owners.entries()) {\n const fragment = group[index];\n if (owner && fragment) {\n const fragments = fragmentsByCopy.get(owner) ?? [];\n fragments.push(fragment);\n fragmentsByCopy.set(owner, fragments);\n }\n }\n }\n return copies.map((copy): CrossFileOccurrence => {\n const fragments = fragmentsByCopy.get(copy);\n if (!fragments) {\n return copy;\n }\n const whole = coalesceOccurrences([copy, ...fragments]);\n coalesced.add(whole);\n return whole;\n });\n });\n // A copy that took its fragments over counts them itself, unless a group left in place still\n // counts all of it: a larger clone whose matched segments enclose those of the copy, which its\n // fragments were nested in. A smaller run left in place inside the copy counts its own repeats,\n // not the copy.\n for (const copy of coalesced) {\n for (const groupIndex of exactGroupIndexesByFile.get(copy.fileIndex) ?? []) {\n const enclosed =\n !taken.has(groupIndex) &&\n exactGroups[groupIndex]?.some(\n (occurrence) =>\n !occurrence.spanCountedElsewhere &&\n copy.segments.every((segment) =>\n occurrence.segments.some(\n (matched) =>\n matched.startTokenIndex <= segment.startTokenIndex && segment.endTokenIndex <= matched.endTokenIndex\n )\n )\n );\n if (enclosed) {\n copy.spanCountedElsewhere = true;\n break;\n }\n }\n }\n return [...exactGroups.filter((_, groupIndex) => !taken.has(groupIndex)), ...merged];\n}\n\nfunction overlap(left: TokenSegment, right: TokenSegment): boolean {\n return left.startTokenIndex < right.endTokenIndex && right.startTokenIndex < left.endTokenIndex;\n}\n\n/** The parts of one copy as one occurrence: an exact part is matched throughout, a near-miss part where its partners match it. */\nfunction coalesceOccurrences(parts: [CrossFileOccurrence, ...CrossFileOccurrence[]]): CrossFileOccurrence {\n const segments = mergeSegments(parts.flatMap((part) => part.segments));\n return {\n ...parts[0],\n spanCountedElsewhere: undefined,\n nestedInLargerGroup: undefined,\n segments,\n matchedRuns: mergeSegments(parts.flatMap((part) => part.matchedRuns ?? part.segments)),\n exactSegments: mergeSegments(\n parts.flatMap((part) => (part.matchedRuns ? (part.exactSegments ?? []) : part.segments))\n ),\n tokenCount: segments.reduce((sum, segment) => sum + segment.endTokenIndex - segment.startTokenIndex, 0),\n startTokenIndex: Math.min(...parts.map((part) => part.startTokenIndex)),\n endTokenIndex: Math.max(...parts.map((part) => part.endTokenIndex)),\n startIndex: Math.min(...parts.map((part) => part.startIndex)),\n endIndex: Math.max(...parts.map((part) => part.endIndex)),\n startLine: Math.min(...parts.map((part) => part.startLine)),\n endLine: Math.max(...parts.map((part) => part.endLine)),\n };\n}\n\n/** The unions of overlapping segments, in position order. */\nfunction mergeSegments(segments: TokenSegment[]): TokenSegment[] {\n const merged: TokenSegment[] = [];\n for (const segment of segments.toSorted((left, right) => left.startTokenIndex - right.startTokenIndex)) {\n const last = merged.at(-1);\n if (last && segment.startTokenIndex < last.endTokenIndex) {\n last.endTokenIndex = Math.max(last.endTokenIndex, segment.endTokenIndex);\n } else {\n merged.push({ ...segment });\n }\n }\n return merged;\n}\n\n/** Near-miss groups among the blocks the exact groups leave unreported, in the project token space. */\nfunction collectNearMissGroups(\n files: CrossFileDuplicationSourceFile[],\n exactGroups: CrossFileOccurrence[][],\n tokenOffsets: number[],\n minTokens: number,\n minSimilarityPercent: number\n): CrossFileOccurrence[][] {\n // Segment by segment: the gap of a gapped clone is not reported content.\n const spansByFile = (groups: CrossFileOccurrence[][]): TokenSegment[][] => {\n const spans: TokenSegment[][] = files.map(() => []);\n for (const { fileIndex, segments } of groups.flat()) {\n const offset = tokenOffsets[fileIndex] ?? 0;\n for (const segment of segments) {\n spans[fileIndex]?.push(shift(segment, -offset));\n }\n }\n return spans;\n };\n return collectCrossFileNearMissGroups(\n files,\n spansByFile(exactGroups),\n spansByFile(exactGroups.filter((group) => !group.some((occurrence) => occurrence.nestedInLargerGroup))),\n minTokens,\n minSimilarityPercent\n ).map((group) =>\n group.map((occurrence) => {\n const offset = tokenOffsets[occurrence.fileIndex] ?? 0;\n return {\n ...occurrence,\n file: files[occurrence.fileIndex]?.file ?? '',\n segments: occurrence.segments.map((segment) => shift(segment, offset)),\n matchedRuns: occurrence.matchedRuns?.map((run) => shift(run, offset)),\n startTokenIndex: occurrence.startTokenIndex + offset,\n endTokenIndex: occurrence.endTokenIndex + offset,\n };\n })\n );\n}\n\nfunction shift({ startTokenIndex, endTokenIndex }: TokenSegment, offset: number): TokenSegment {\n return { startTokenIndex: startTokenIndex + offset, endTokenIndex: endTokenIndex + offset };\n}\n\n/** Repeated sub-windows of sibling statements matched across the whole project's files. */\nfunction collectWindowCandidates(files: CrossFileDuplicationSourceFile[], minTokens: number): SelectableCandidate[] {\n const fileIndexByContext: number[] = [];\n const contexts: SequenceWindowContext[] = [];\n for (const [fileIndex, { tokens, containerStatements }] of files.entries()) {\n if (tokens && containerStatements) {\n fileIndexByContext.push(fileIndex);\n contexts.push({ tokens, literalCountPrefix: buildLiteralCountPrefix(tokens), containers: containerStatements });\n }\n }\n if (contexts.length < 2) {\n return [];\n }\n return collectSequenceWindowCandidates(contexts, minTokens, true).flatMap(({ candidate, contextIndex }) => {\n const fileIndex = fileIndexByContext[contextIndex];\n const file = fileIndex === undefined ? undefined : files[fileIndex];\n return fileIndex === undefined || file === undefined\n ? []\n : [{ ...candidate, regionBucket: fileIndex, file: file.file }];\n });\n}\n\n/** A merged group is reported only while it still covers more than one file. */\nfunction spansMultipleFilesAfterMerge(group: CrossFileOccurrence[]): boolean {\n return new Set(group.map((occurrence) => occurrence.file)).size >= 2;\n}\n\nfunction spansMultipleFiles(group: SelectableCandidate[]): boolean {\n return group.length >= 2 && new Set(group.map((candidate) => candidate.regionBucket)).size >= 2;\n}\n\n/**\n * Per-file token offsets that map every file into one project-wide token index space: each file's\n * tokens are offset by more than `maxGapTokens` past the previous file's, so occurrences in\n * different files are never gap-adjacent and merged pairs always stay within one file.\n */\nfunction computeTokenOffsets(files: CrossFileDuplicationSourceFile[], maxGapTokens: number): number[] {\n const tokenOffsets: number[] = [];\n let offset = 0;\n for (const { tokens, candidates } of files) {\n tokenOffsets.push(offset);\n // Accumulated in a loop: spreading a project-scale candidate array as call arguments would\n // overflow V8's argument limit (~124k) and crash on Node.\n let tokenCount = tokens?.length ?? 0;\n if (!tokens) {\n for (const candidate of candidates) {\n tokenCount = Math.max(tokenCount, candidate.endTokenIndex);\n }\n }\n offset += tokenCount + maxGapTokens + 1;\n }\n return tokenOffsets;\n}\n\n/** Reuses the within-file gapped (Type-3) merging in the project-wide token index space. */\nfunction mergeGapAdjacentGroups(\n groups: SelectableCandidate[][],\n tokenOffsets: number[],\n maxGapTokens: number\n): CrossFileOccurrence[][] {\n const occurrenceGroups = groups.map((group) =>\n group\n .map((candidate): CrossFileOccurrence => {\n const start = candidate.startTokenIndex + (tokenOffsets[candidate.regionBucket] ?? 0);\n const end = candidate.endTokenIndex + (tokenOffsets[candidate.regionBucket] ?? 0);\n return {\n file: candidate.file,\n fileIndex: candidate.regionBucket,\n spanCountedElsewhere: candidate.nestedInLargerGroup,\n nestedInLargerGroup: candidate.nestedInLargerGroup,\n segments: [{ startTokenIndex: start, endTokenIndex: end }],\n tokenCount: candidate.tokenCount,\n startTokenIndex: start,\n endTokenIndex: end,\n startIndex: candidate.startIndex,\n endIndex: candidate.endIndex,\n startLine: candidate.startLine,\n endLine: candidate.endLine,\n };\n })\n .toSorted((left, right) => left.startTokenIndex - right.startTokenIndex)\n );\n return mergeAdjacentGroups(occurrenceGroups, maxGapTokens, spansMultipleFilesAfterMerge);\n}\n\nfunction summarize(\n groups: CrossFileOccurrence[][],\n files: CrossFileDuplicationSourceFile[],\n tokenOffsets: number[]\n): CrossFileDuplicationMetrics {\n const reported: CrossFileDuplicateBlockGroup[] = [];\n // Accumulated in Maps: file names are arbitrary strings, and a plain object would read\n // inherited properties for names like \"constructor\".\n const groupCountByFile = new Map<string, number>();\n const fileDataByName = new Map(\n files.map((file, index) => [\n file.file,\n { tokens: file.tokens, codeLineNumbers: file.codeLineNumbers, offset: tokenOffsets[index] ?? 0 },\n ])\n );\n const lineNumbersByFile = new Map<string, Set<number>>();\n let duplicateBlockCount = 0;\n for (const group of groups) {\n // Mirrors within-file counting: each redundant occurrence contributes one count per matched\n // fragment, gapped merging consolidates the grouping without halving the count, and spans a\n // partial merge shares between a retained group and the merged group count once.\n duplicateBlockCount += countRedundantFragments(group);\n const occurrences = group\n .map((occurrence) => {\n const { file, startLine, endLine, tokenCount } = occurrence;\n const lineNumbers = collectOccurrenceLines(occurrence, fileDataByName, lineNumbersByFile);\n return { file, startLine, endLine, ...(lineNumbers && { lineNumbers }), tokenCount };\n })\n .toSorted((left, right) => left.file.localeCompare(right.file) || left.startLine - right.startLine);\n const files = [...new Set(occurrences.map(({ file }) => file))];\n for (const file of files) {\n groupCountByFile.set(file, (groupCountByFile.get(file) ?? 0) + 1);\n }\n reported.push({ files, occurrences, tokenCount: Math.min(...group.map(({ tokenCount }) => tokenCount)) });\n }\n reported.sort(\n (left, right) =>\n right.tokenCount - left.tokenCount ||\n (left.occurrences[0]?.file ?? '').localeCompare(right.occurrences[0]?.file ?? '') ||\n (left.occurrences[0]?.startLine ?? 0) - (right.occurrences[0]?.startLine ?? 0)\n );\n return {\n duplicateBlockCount,\n duplicateBlockGroupCountByFile: Object.fromEntries(groupCountByFile),\n duplicateLineNumbersByFile: Object.fromEntries(\n [...lineNumbersByFile].map(([file, lines]) => [file, [...lines].toSorted((left, right) => left - right)])\n ),\n groups: reported,\n };\n}\n\n/**\n * Adds the code lines an occurrence's matched tokens cover (see collectMatchedLines) to its file's\n * line set, mapping the project-wide token segments back into the file's own token stream, and\n * returns them in order.\n * A file that supplied only candidates (no token stream) is skipped rather than approximated from\n * the bounding line range, which would include gap and comment/blank lines and break the field's\n * exactness contract.\n */\nfunction collectOccurrenceLines(\n occurrence: CrossFileOccurrence,\n fileDataByName: Map<\n string,\n { tokens?: CrossFileDuplicationSourceFile['tokens']; codeLineNumbers?: Set<number>; offset: number }\n >,\n lineNumbersByFile: Map<string, Set<number>>\n): number[] | undefined {\n const fileData = fileDataByName.get(occurrence.file);\n if (!fileData?.tokens) {\n return undefined;\n }\n let fileLines = lineNumbersByFile.get(occurrence.file);\n if (!fileLines) {\n fileLines = new Set();\n lineNumbersByFile.set(occurrence.file, fileLines);\n }\n const lines = collectMatchedLines(\n occurrence.segments.map((segment) => shift(segment, -fileData.offset)),\n occurrence.matchedRuns?.map((run) => shift(run, -fileData.offset)),\n fileData.tokens,\n fileData.codeLineNumbers,\n occurrence.exactSegments?.map((segment) => shift(segment, -fileData.offset))\n );\n for (const line of lines) {\n fileLines.add(line);\n }\n return [...lines].toSorted((left, right) => left - right);\n}\n"],"mappings":"6HA+FA,SAAgB,EACd,EACA,EAC6B,CAC7B,GAAM,CAAE,YAAW,eAAc,wBAAyBA,EAAAA,0BAA0B,CAAO,EACrF,EAAoC,EAAM,SAAS,CAAE,OAAM,cAAc,IAC7E,EAAW,IAAK,IAAe,CAAE,GAAG,EAAW,aAAc,EAAW,MAAK,EAAE,CACjF,EAGA,IAAK,IAAM,KAAa,EAAwB,EAAO,CAAS,EAC9D,EAAW,KAAK,CAAS,EAE3B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4B,OAAO,YACjC,CAAC,GAAG,CAAiB,CAAC,CAAC,KAAK,CAAC,EAAM,KAAW,CAAC,EAAM,CAAC,GAAG,CAAK,CAAC,CAAC,UAAU,EAAM,IAAU,EAAO,CAAK,CAAC,CAAC,CAC1G,EACA,OAAQ,CACV,CACF,CAUA,SAAS,EACP,EACA,EAIA,EACsB,CACtB,IAAM,EAAW,EAAe,IAAI,EAAW,IAAI,EACnD,GAAI,CAAC,GAAU,OACb,OAEF,IAAI,EAAY,EAAkB,IAAI,EAAW,IAAI,EAChD,IACH,kBAAY,IAAI,IAChB,EAAkB,IAAI,EAAW,KAAM,CAAS,GAElD,IAAM,EAAQC,EAAAA,oBACZ,EAAW,SAAS,IAAK,GAAY,EAAM,EAAS,CAAC,EAAS,MAAM,CAAC,EACrE,EAAW,aAAa,IAAK,GAAQ,EAAM,EAAK,CAAC,EAAS,MAAM,CAAC,EACjE,EAAS,OACT,EAAS,gBACT,EAAW,eAAe,IAAK,GAAY,EAAM,EAAS,CAAC,EAAS,MAAM,CAAC,CAC7E,EACA,IAAK,IAAM,KAAQ,EACjB,EAAU,IAAI,CAAI,EAEpB,MAAO,CAAC,GAAG,CAAK,CAAC,CAAC,UAAU,EAAM,IAAU,EAAO,CAAK,CAC1D"}
1
+ {"version":3,"file":"crossFileDuplication.cjs","names":["resolveDuplicationOptions","selectMaximalGroups","collectCrossFileNearMissGroups","buildLiteralCountPrefix","collectSequenceWindowCandidates","mergeAdjacentGroups","countRedundantFragments","collectMatchedLines","require_duplication","require_crossFileNearMiss","require_duplicateSelection","measureCrossFileDuplication","options","candidates","files","candidate","fileIndex","collectWindowCandidates","minTokens","counted","spansMultipleFiles","left","right","tokenOffsets","computeTokenOffsets","maxGapTokens","exactGroups","mergeGapAdjacentGroups","summarize","takeOverExactGroups","collectNearMissGroups","minSimilarityPercent","exactGroupIndexesByFile","groupIndex","group","indexes","taken","coalesced","merged","nearMissGroups","copyOf","overlapped","copies","copy","occurrence","overlap","matched","segment","fragmentsByCopy","candidateIndexes","owners","index","owner","fragment","fragments","whole","coalesceOccurrences","segments","mergeSegments","parts","part","sum","last","spansByFile","spans","groups","offset","shift","run","startTokenIndex","endTokenIndex","fileIndexByContext","contexts","tokens","containerStatements","contextIndex","file","spansMultipleFilesAfterMerge","tokenCount","occurrenceGroups","start","end","reported","groupCountByFile","fileDataByName","lineNumbersByFile","duplicateBlockCount","occurrences","lineNumbers","collectOccurrenceLines","lines","fileData","fileLines","line"],"sources":["../src/crossFileDuplication.ts"],"sourcesContent":["import { collectCrossFileNearMissGroups } from './crossFileNearMiss.js';\nimport { selectMaximalGroups, type SelectableRegion } from './duplicateSelection.js';\nimport {\n buildLiteralCountPrefix,\n collectMatchedLines,\n collectSequenceWindowCandidates,\n countRedundantFragments,\n mergeAdjacentGroups,\n resolveDuplicationOptions,\n type CountedOccurrence,\n type CrossFileDuplicateCandidate,\n type CrossFileDuplicationFileData,\n type SequenceWindowContext,\n type TokenSegment,\n} from './duplication.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport interface CrossFileDuplicationSourceFile extends Partial<CrossFileDuplicationFileData> {\n file: string;\n candidates: CrossFileDuplicateCandidate[];\n}\n\nexport interface CrossFileDuplicateOccurrence {\n endLine: number;\n file: string;\n /**\n * The code lines carrying the occurrence's matched tokens (see\n * DuplicateBlockOccurrence.lineNumbers). Absent for a file that supplied only candidates (no\n * `tokens`), whose matched lines are unknowable.\n */\n lineNumbers?: number[];\n startLine: number;\n /**\n * The tokens of its matched runs, or of a near-miss block or its matched cores with the edited\n * tokens among them; the group's `tokenCount` is the smallest of its occurrences'.\n */\n tokenCount: number;\n}\n\nexport interface CrossFileDuplicateBlockGroup {\n files: string[];\n occurrences: CrossFileDuplicateOccurrence[];\n /**\n * Token count of the smallest occurrence. For exact and gapped groups it is the matched token\n * count every occurrence shares (gaps are not counted); for near-miss (Type-3) groups it is the\n * token count of the smallest whole block or set of matched cores, edited tokens included.\n */\n tokenCount: number;\n}\n\nexport interface CrossFileDuplicationMetrics {\n /** Number of redundant copies across all groups, counted per matched fragment like within-file. */\n duplicateBlockCount: number;\n /** Groups the file participates in, keyed by the file name passed in. */\n duplicateBlockGroupCountByFile: Record<string, number>;\n /**\n * Per file, the 1-based code lines covered by the tokens of its cross-file occurrences, sorted\n * ascending: the matched tokens of exact and gapped occurrences, and the lines of a near-miss\n * block or its matched cores more than half of whose tokens its partners match or which a part of it\n * matched exactly reaches (like within-file near-miss coverage). The unmatched gap of a merged\n * clone and comment/blank lines inside an occurrence's bounding range are excluded (blank rows\n * inside multi-row tokens only when the file supplied codeLineNumbers). A file that supplied\n * only candidates (no `tokens`) has no entry — without its token stream the covered lines are\n * unknowable, and an approximate bounding range would break this field's exactness.\n */\n duplicateLineNumbersByFile: Record<string, number[]>;\n groups: CrossFileDuplicateBlockGroup[];\n}\n\ninterface SelectableCandidate extends CrossFileDuplicateCandidate, SelectableRegion {\n regionBucket: number;\n file: string;\n}\n\n/** A cross-file occurrence: a within-file occurrence in the project-wide token index space. */\ninterface CrossFileOccurrence extends CountedOccurrence {\n file: string;\n fileIndex: number;\n}\n\n/**\n * Detects code regions duplicated across files. Per-file candidates (whole block subtrees and full\n * container runs, fingerprinted with the same normalization as within-file duplication) are joined\n * by a project-level window index over per-statement fingerprint sequences (CPD-style), so a\n * copy-pasted partial statement run embedded in different surrounding code is matched even though\n * no single file can know it repeats elsewhere. Candidates are grouped by fingerprint, and only\n * maximal, non-overlapping regions whose group spans at least two files are counted. Groups that\n * shrink to a single file during selection are shed — a within-file repeat is already reported by\n * that file's own duplication metrics. A copy nested inside a larger group's region (two files share\n * a whole function, a third file only a block of it) is reported with its group, so the third\n * file's copy still shows what it duplicates. Groups separated by a small token gap within each file then\n * merge into gapped (Type-3) clone groups under `maxGapTokens`, exactly like within-file merging.\n * Finally, blocks of files that supplied `nearMissBlocks` are compared across files for near-miss\n * (Type-3) clones under `minSimilarityPercent` (see crossFileNearMiss.ts).\n */\nexport function measureCrossFileDuplication(\n files: CrossFileDuplicationSourceFile[],\n options?: DuplicationOptions\n): CrossFileDuplicationMetrics {\n const { minTokens, maxGapTokens, minSimilarityPercent } = resolveDuplicationOptions(options);\n const candidates: SelectableCandidate[] = files.flatMap(({ file, candidates }, fileIndex) =>\n candidates.map((candidate) => ({ ...candidate, regionBucket: fileIndex, file }))\n );\n // Pushed one by one: spreading the project-scale window-candidate array as call arguments\n // overflows V8's argument limit (~124k) and crashes on Node, though Bun/JSC tolerates it.\n for (const candidate of collectWindowCandidates(files, minTokens)) {\n candidates.push(candidate);\n }\n const counted = selectMaximalGroups(\n candidates,\n spansMultipleFiles,\n // File index and position break coverage ties deterministically.\n (left, right) => left.regionBucket - right.regionBucket || left.startIndex - right.startIndex\n );\n const tokenOffsets = computeTokenOffsets(files, maxGapTokens);\n const exactGroups = mergeGapAdjacentGroups([...counted.values()], tokenOffsets, maxGapTokens);\n const nearMissGroups = collectNearMissGroups(files, exactGroups, tokenOffsets, minTokens, minSimilarityPercent);\n return summarize(takeOverExactGroups(exactGroups, nearMissGroups, minTokens), files, tokenOffsets);\n}\n\n/**\n * Lets a near-miss group take over the exact groups standing for the same copies, as within a\n * file (collect_near_miss_groups in native/src/duplication.rs): every occurrence of such a group\n * overlaps exactly one copy of the near-miss group (one overlapping none reports content the copies\n * do not share, and one reaching into two would make one copy take over lines of the next), exceeds\n * its span by less than `minTokens` (a copy is listed at the size it matched, not at that of a\n * clone larger by a reportable part, which may run into code no copy matched), and no two overlap\n * the same copy (those repeat within the copy, not between the copies).\n * Each copy then becomes one occurrence with the exact fragments it holds, so the copies are\n * listed once.\n */\nfunction takeOverExactGroups(\n exactGroups: CrossFileOccurrence[][],\n nearMissGroups: CrossFileOccurrence[][],\n minTokens: number\n): CrossFileOccurrence[][] {\n const exactGroupIndexesByFile = new Map<number, Set<number>>();\n for (const [groupIndex, group] of exactGroups.entries()) {\n for (const { fileIndex } of group) {\n const indexes = exactGroupIndexesByFile.get(fileIndex) ?? new Set();\n indexes.add(groupIndex);\n exactGroupIndexesByFile.set(fileIndex, indexes);\n }\n }\n const taken = new Set<number>();\n const coalesced = new Set<CrossFileOccurrence>();\n const merged = nearMissGroups.map((copies) => {\n const copyOf = (occurrence: CrossFileOccurrence): CrossFileOccurrence | undefined => {\n const overlapped = copies.filter((copy) =>\n copy.segments.some((segment) => occurrence.segments.some((matched) => overlap(matched, segment)))\n );\n const [copy] = overlapped;\n if (overlapped.length !== 1 || !copy) {\n return undefined;\n }\n const excess =\n Math.max(0, copy.startTokenIndex - occurrence.startTokenIndex) +\n Math.max(0, occurrence.endTokenIndex - copy.endTokenIndex);\n return excess < minTokens ? copy : undefined;\n };\n const fragmentsByCopy = new Map<CrossFileOccurrence, CrossFileOccurrence[]>();\n const candidateIndexes = new Set<number>();\n for (const copy of copies) {\n for (const groupIndex of copy.spanCountedElsewhere ? (exactGroupIndexesByFile.get(copy.fileIndex) ?? []) : []) {\n candidateIndexes.add(groupIndex);\n }\n }\n for (const groupIndex of [...candidateIndexes].toSorted((left, right) => left - right)) {\n const group = exactGroups[groupIndex] ?? [];\n const owners = group.map(copyOf);\n if (taken.has(groupIndex) || owners.includes(undefined) || new Set(owners).size !== owners.length) {\n continue;\n }\n taken.add(groupIndex);\n for (const [index, owner] of owners.entries()) {\n const fragment = group[index];\n if (owner && fragment) {\n const fragments = fragmentsByCopy.get(owner) ?? [];\n fragments.push(fragment);\n fragmentsByCopy.set(owner, fragments);\n }\n }\n }\n return copies.map((copy): CrossFileOccurrence => {\n const fragments = fragmentsByCopy.get(copy);\n if (!fragments) {\n return copy;\n }\n const whole = coalesceOccurrences([copy, ...fragments]);\n coalesced.add(whole);\n return whole;\n });\n });\n // A copy that took its fragments over counts them itself, unless a group left in place still\n // counts all of it: a larger clone whose matched segments enclose those of the copy, which its\n // fragments were nested in. A smaller run left in place inside the copy counts its own repeats,\n // not the copy.\n for (const copy of coalesced) {\n for (const groupIndex of exactGroupIndexesByFile.get(copy.fileIndex) ?? []) {\n const enclosed =\n !taken.has(groupIndex) &&\n exactGroups[groupIndex]?.some(\n (occurrence) =>\n !occurrence.spanCountedElsewhere &&\n copy.segments.every((segment) =>\n occurrence.segments.some(\n (matched) =>\n matched.startTokenIndex <= segment.startTokenIndex && segment.endTokenIndex <= matched.endTokenIndex\n )\n )\n );\n if (enclosed) {\n copy.spanCountedElsewhere = true;\n break;\n }\n }\n }\n return [...exactGroups.filter((_, groupIndex) => !taken.has(groupIndex)), ...merged];\n}\n\nfunction overlap(left: TokenSegment, right: TokenSegment): boolean {\n return left.startTokenIndex < right.endTokenIndex && right.startTokenIndex < left.endTokenIndex;\n}\n\n/** The parts of one copy as one occurrence: an exact part is matched throughout, a near-miss part where its partners match it. */\nfunction coalesceOccurrences(parts: [CrossFileOccurrence, ...CrossFileOccurrence[]]): CrossFileOccurrence {\n const segments = mergeSegments(parts.flatMap((part) => part.segments));\n return {\n ...parts[0],\n spanCountedElsewhere: undefined,\n nestedInLargerGroup: undefined,\n segments,\n matchedRuns: mergeSegments(parts.flatMap((part) => part.matchedRuns ?? part.segments)),\n exactSegments: mergeSegments(\n parts.flatMap((part) => (part.matchedRuns ? (part.exactSegments ?? []) : part.segments))\n ),\n tokenCount: segments.reduce((sum, segment) => sum + segment.endTokenIndex - segment.startTokenIndex, 0),\n startTokenIndex: Math.min(...parts.map((part) => part.startTokenIndex)),\n endTokenIndex: Math.max(...parts.map((part) => part.endTokenIndex)),\n startIndex: Math.min(...parts.map((part) => part.startIndex)),\n endIndex: Math.max(...parts.map((part) => part.endIndex)),\n startLine: Math.min(...parts.map((part) => part.startLine)),\n endLine: Math.max(...parts.map((part) => part.endLine)),\n };\n}\n\n/** The unions of overlapping segments, in position order. */\nfunction mergeSegments(segments: TokenSegment[]): TokenSegment[] {\n const merged: TokenSegment[] = [];\n for (const segment of segments.toSorted((left, right) => left.startTokenIndex - right.startTokenIndex)) {\n const last = merged.at(-1);\n if (last && segment.startTokenIndex < last.endTokenIndex) {\n last.endTokenIndex = Math.max(last.endTokenIndex, segment.endTokenIndex);\n } else {\n merged.push({ ...segment });\n }\n }\n return merged;\n}\n\n/** Near-miss groups among the blocks the exact groups leave unreported, in the project token space. */\nfunction collectNearMissGroups(\n files: CrossFileDuplicationSourceFile[],\n exactGroups: CrossFileOccurrence[][],\n tokenOffsets: number[],\n minTokens: number,\n minSimilarityPercent: number\n): CrossFileOccurrence[][] {\n // Segment by segment: the gap of a gapped clone is not reported content.\n const spansByFile = (groups: CrossFileOccurrence[][]): TokenSegment[][] => {\n const spans: TokenSegment[][] = files.map(() => []);\n for (const { fileIndex, segments } of groups.flat()) {\n const offset = tokenOffsets[fileIndex] ?? 0;\n for (const segment of segments) {\n spans[fileIndex]?.push(shift(segment, -offset));\n }\n }\n return spans;\n };\n return collectCrossFileNearMissGroups(\n files,\n spansByFile(exactGroups),\n spansByFile(exactGroups.filter((group) => !group.some((occurrence) => occurrence.nestedInLargerGroup))),\n minTokens,\n minSimilarityPercent\n ).map((group) =>\n group.map((occurrence) => {\n const offset = tokenOffsets[occurrence.fileIndex] ?? 0;\n return {\n ...occurrence,\n file: files[occurrence.fileIndex]?.file ?? '',\n segments: occurrence.segments.map((segment) => shift(segment, offset)),\n matchedRuns: occurrence.matchedRuns?.map((run) => shift(run, offset)),\n startTokenIndex: occurrence.startTokenIndex + offset,\n endTokenIndex: occurrence.endTokenIndex + offset,\n };\n })\n );\n}\n\nfunction shift({ startTokenIndex, endTokenIndex }: TokenSegment, offset: number): TokenSegment {\n return { startTokenIndex: startTokenIndex + offset, endTokenIndex: endTokenIndex + offset };\n}\n\n/** Repeated sub-windows of sibling statements matched across the whole project's files. */\nfunction collectWindowCandidates(files: CrossFileDuplicationSourceFile[], minTokens: number): SelectableCandidate[] {\n const fileIndexByContext: number[] = [];\n const contexts: SequenceWindowContext[] = [];\n for (const [fileIndex, { tokens, containerStatements }] of files.entries()) {\n if (tokens && containerStatements) {\n fileIndexByContext.push(fileIndex);\n contexts.push({ tokens, literalCountPrefix: buildLiteralCountPrefix(tokens), containers: containerStatements });\n }\n }\n if (contexts.length < 2) {\n return [];\n }\n return collectSequenceWindowCandidates(contexts, minTokens, true).flatMap(({ candidate, contextIndex }) => {\n const fileIndex = fileIndexByContext[contextIndex];\n const file = fileIndex === undefined ? undefined : files[fileIndex];\n return fileIndex === undefined || file === undefined\n ? []\n : [{ ...candidate, regionBucket: fileIndex, file: file.file }];\n });\n}\n\n/** A merged group is reported only while it still covers more than one file. */\nfunction spansMultipleFilesAfterMerge(group: CrossFileOccurrence[]): boolean {\n return new Set(group.map((occurrence) => occurrence.file)).size >= 2;\n}\n\nfunction spansMultipleFiles(group: SelectableCandidate[]): boolean {\n return group.length >= 2 && new Set(group.map((candidate) => candidate.regionBucket)).size >= 2;\n}\n\n/**\n * Per-file token offsets that map every file into one project-wide token index space: each file's\n * tokens are offset by more than `maxGapTokens` past the previous file's, so occurrences in\n * different files are never gap-adjacent and merged pairs always stay within one file.\n */\nfunction computeTokenOffsets(files: CrossFileDuplicationSourceFile[], maxGapTokens: number): number[] {\n const tokenOffsets: number[] = [];\n let offset = 0;\n for (const { tokens, candidates } of files) {\n tokenOffsets.push(offset);\n // Accumulated in a loop: spreading a project-scale candidate array as call arguments would\n // overflow V8's argument limit (~124k) and crash on Node.\n let tokenCount = tokens?.length ?? 0;\n if (!tokens) {\n for (const candidate of candidates) {\n tokenCount = Math.max(tokenCount, candidate.endTokenIndex);\n }\n }\n offset += tokenCount + maxGapTokens + 1;\n }\n return tokenOffsets;\n}\n\n/** Reuses the within-file gapped (Type-3) merging in the project-wide token index space. */\nfunction mergeGapAdjacentGroups(\n groups: SelectableCandidate[][],\n tokenOffsets: number[],\n maxGapTokens: number\n): CrossFileOccurrence[][] {\n const occurrenceGroups = groups.map((group) =>\n group\n .map((candidate): CrossFileOccurrence => {\n const start = candidate.startTokenIndex + (tokenOffsets[candidate.regionBucket] ?? 0);\n const end = candidate.endTokenIndex + (tokenOffsets[candidate.regionBucket] ?? 0);\n return {\n file: candidate.file,\n fileIndex: candidate.regionBucket,\n spanCountedElsewhere: candidate.nestedInLargerGroup,\n nestedInLargerGroup: candidate.nestedInLargerGroup,\n segments: [{ startTokenIndex: start, endTokenIndex: end }],\n tokenCount: candidate.tokenCount,\n startTokenIndex: start,\n endTokenIndex: end,\n startIndex: candidate.startIndex,\n endIndex: candidate.endIndex,\n startLine: candidate.startLine,\n endLine: candidate.endLine,\n };\n })\n .toSorted((left, right) => left.startTokenIndex - right.startTokenIndex)\n );\n return mergeAdjacentGroups(occurrenceGroups, maxGapTokens, spansMultipleFilesAfterMerge);\n}\n\nfunction summarize(\n groups: CrossFileOccurrence[][],\n files: CrossFileDuplicationSourceFile[],\n tokenOffsets: number[]\n): CrossFileDuplicationMetrics {\n const reported: CrossFileDuplicateBlockGroup[] = [];\n // Accumulated in Maps: file names are arbitrary strings, and a plain object would read\n // inherited properties for names like \"constructor\".\n const groupCountByFile = new Map<string, number>();\n const fileDataByName = new Map(\n files.map((file, index) => [\n file.file,\n { tokens: file.tokens, codeLineNumbers: file.codeLineNumbers, offset: tokenOffsets[index] ?? 0 },\n ])\n );\n const lineNumbersByFile = new Map<string, Set<number>>();\n let duplicateBlockCount = 0;\n for (const group of groups) {\n // Mirrors within-file counting: each redundant occurrence contributes one count per matched\n // fragment, gapped merging consolidates the grouping without halving the count, and spans a\n // partial merge shares between a retained group and the merged group count once.\n duplicateBlockCount += countRedundantFragments(group);\n const occurrences = group\n .map((occurrence) => {\n const { file, startLine, endLine, tokenCount } = occurrence;\n const lineNumbers = collectOccurrenceLines(occurrence, fileDataByName, lineNumbersByFile);\n return { file, startLine, endLine, ...(lineNumbers && { lineNumbers }), tokenCount };\n })\n .toSorted((left, right) => left.file.localeCompare(right.file) || left.startLine - right.startLine);\n const files = [...new Set(occurrences.map(({ file }) => file))];\n for (const file of files) {\n groupCountByFile.set(file, (groupCountByFile.get(file) ?? 0) + 1);\n }\n reported.push({ files, occurrences, tokenCount: Math.min(...group.map(({ tokenCount }) => tokenCount)) });\n }\n reported.sort(\n (left, right) =>\n right.tokenCount - left.tokenCount ||\n (left.occurrences[0]?.file ?? '').localeCompare(right.occurrences[0]?.file ?? '') ||\n (left.occurrences[0]?.startLine ?? 0) - (right.occurrences[0]?.startLine ?? 0)\n );\n return {\n duplicateBlockCount,\n duplicateBlockGroupCountByFile: Object.fromEntries(groupCountByFile),\n duplicateLineNumbersByFile: Object.fromEntries(\n [...lineNumbersByFile].map(([file, lines]) => [file, [...lines].toSorted((left, right) => left - right)])\n ),\n groups: reported,\n };\n}\n\n/**\n * Adds the code lines an occurrence's matched tokens cover (see collectMatchedLines) to its file's\n * line set, mapping the project-wide token segments back into the file's own token stream, and\n * returns them in order.\n * A file that supplied only candidates (no token stream) is skipped rather than approximated from\n * the bounding line range, which would include gap and comment/blank lines and break the field's\n * exactness contract.\n */\nfunction collectOccurrenceLines(\n occurrence: CrossFileOccurrence,\n fileDataByName: Map<\n string,\n { tokens?: CrossFileDuplicationSourceFile['tokens']; codeLineNumbers?: Set<number>; offset: number }\n >,\n lineNumbersByFile: Map<string, Set<number>>\n): number[] | undefined {\n const fileData = fileDataByName.get(occurrence.file);\n if (!fileData?.tokens) {\n return undefined;\n }\n let fileLines = lineNumbersByFile.get(occurrence.file);\n if (!fileLines) {\n fileLines = new Set();\n lineNumbersByFile.set(occurrence.file, fileLines);\n }\n const lines = collectMatchedLines(\n occurrence.segments.map((segment) => shift(segment, -fileData.offset)),\n occurrence.matchedRuns?.map((run) => shift(run, -fileData.offset)),\n fileData.tokens,\n fileData.codeLineNumbers,\n occurrence.exactSegments?.map((segment) => shift(segment, -fileData.offset))\n );\n for (const line of lines) {\n fileLines.add(line);\n }\n return [...lines].toSorted((left, right) => left - right);\n}\n"],"mappings":"6HA+FA,SAAgBW,EACd,EACA,EAC6B,CAC7B,GAAM,CAAE,YAAW,eAAc,wBAAyBX,EAAAA,0BAA0BY,CAAO,EACrFC,EAAoCC,EAAM,SAAS,CAAE,OAAM,cAAc,IAC7ED,EAAW,IAAK,IAAe,CAAE,GAAGE,EAAW,aAAcC,EAAW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