Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const fs = require("fs/promises");
const path = require("path");
 
const v8toIstanbul = require("v8-to-istanbul");
const covDir = "./output/coverage";
const resDir = "../coverage";
const basePath = path.resolve("../");
const basePathRegExp = new RegExp(`${basePath}\\LabelStudio`.replace(/\\/g, "\\\\"), "g");
 
const fixBasePath = (path) => {
  return path.replace(basePathRegExp, basePath);
};
 
async function loadSource(fileName) {
  const source = await fs.readFile(`../build/static/js/${fileName}`);
 
  return source.toString();
}
 
async function loadSourceMap(fileName) {
  const sourceMap = await fs.readFile(`../build/static/js/${fileName}.map`);
 
  return JSON.parse(sourceMap.toString().replace(/\/\.\//g, "/"));
}
 
const convertCoverage = async (fileName) => {
  if (fileName.match("_final.coverage")) return;
 
  const coverage = require(`${covDir}/${fileName}`);
  const basename = path.basename(fileName).replace(".coverage.json", "");
  const finalName = path.resolve(`${resDir}/${basename}_final.coverage.json`);
 
  for (const entry of coverage) {
    // Used to get file name
    const sourceFileName = entry.url.match(/(?:http(s)*:\/\/.*\/)(?<file>.*)/).groups.file;
 
    if (!sourceFileName) continue;
 
    const scriptSource = await loadSource(sourceFileName);
    const scriptSourceMap = await loadSourceMap(sourceFileName);
 
    const filePath = path.resolve(`../${sourceFileName}`);
 
    const converter = new v8toIstanbul(filePath, 0, {
      source: scriptSource.toString(),
      sourceMap: {
        sourcemap: scriptSourceMap,
      },
    });
 
    await converter.load();
    converter.applyCoverage(entry.functions);
 
    const result = JSON.stringify(
      converter.toIstanbul(),
      (key, value) => {
        if (key === "") {
          return Object.fromEntries(
            Object.entries(value).reduce((res, [key, val]) => {
              res.push([fixBasePath(key), val]);
              return res;
            }, []),
          );
        }
        if (key === "path") {
          return fixBasePath(value);
        }
        return value;
      },
      2,
    );
 
    // Store converted coverage file which can later be used to generate report
    await fs.writeFile(finalName, result);
    console.log(`Processed ${basename}`);
  }
 
  await fs.unlink(`${covDir}/${fileName}`);
};
 
// read all the coverage file from output/coverage folder
fs.readdir(covDir).then(async (files) => {
  for (const file of files) {
    await convertCoverage(file);
  }
});