marketing-executable-lines.mjs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import ts from "typescript";
  2. import { createInstrumenter } from "istanbul-lib-instrument";
  3. import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
  4. /** 先消除 TS 语法再插桩,避免直接解析 TS 时漏掉运行时 enum。 */
  5. export function executableSourceLines(source, file) {
  6. const compiled = ts.transpileModule(source, {
  7. fileName: file,
  8. reportDiagnostics: true,
  9. compilerOptions: {
  10. target: ts.ScriptTarget.ESNext,
  11. module: ts.ModuleKind.ESNext,
  12. jsx: ts.JsxEmit.Preserve,
  13. sourceMap: true,
  14. inlineSources: true,
  15. },
  16. });
  17. const errors = (compiled.diagnostics ?? []).filter(
  18. (d) => d.category === ts.DiagnosticCategory.Error,
  19. );
  20. if (errors.length || !compiled.sourceMapText)
  21. return {
  22. status: "unknown",
  23. reason: "typescript-transform",
  24. diagnostics: errors.map((d) => d.code),
  25. };
  26. try {
  27. const instrumenter = createInstrumenter({ parserPlugins: ["jsx"], esModules: true });
  28. instrumenter.instrumentSync(compiled.outputText, file);
  29. const map = new TraceMap(JSON.parse(compiled.sourceMapText));
  30. const lines = new Set();
  31. let unmappedStatements = 0;
  32. for (const statement of Object.values(instrumenter.lastFileCoverage().statementMap)) {
  33. const original = originalPositionFor(map, {
  34. line: statement.start.line,
  35. column: statement.start.column,
  36. });
  37. if (original.line === null) unmappedStatements++;
  38. else lines.add(original.line);
  39. }
  40. return { status: "mapped", lines: [...lines].sort((a, b) => a - b), unmappedStatements };
  41. } catch (error) {
  42. return { status: "unknown", reason: "instrumentation", message: error.message };
  43. }
  44. }