All files / src/test sourceScan.ts

93.87% Statements 92/98
86.53% Branches 45/52
76.92% Functions 10/13
93.97% Lines 78/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202                        2x                   1x 1x 184x 1052x 184x 184x   868x 850x 634x 632x 632x 625x 625x             1x 1x                       1x 1x 184x 1052x 184x 184x   868x 216x 216x 216x             1x 1x         7786x                                 12x 12x 7087x     1449412x     7087x 1515514x 1515514x 15x         12x     2x                                   1251x 1251x 1251x     1251x 9840x 9840x 9840x   9840x 1168x 1168x 135368x 133483x 1885x 1885x 1168x 1168x       8672x 8670x   2x     9838x 9838x 9838x   1251x                         625x 625x 625x   625x 626x 626x 626x 192504x 192504x 191097x 189690x   626x 626x 626x 626x           625x    
import path from "node:path";
 
import { readdirSyncRetry, readFileSyncRetry } from "../../../vitest.fsRetry";
 
/** One source file, read once, for the static-analysis suites. */
export interface SourceFile {
  /** Path relative to the package root, e.g. `src/pages/Error.tsx`. */
  path: string;
  text: string;
  lines: string[];
}
 
const SKIP_DIRS = new Set(["node_modules", "dist", "coverage", "assets"]);
 
/**
 * Every `.ts`/`.tsx` file under `src`, excluding tests and test helpers.
 *
 * These suites assert things the type system and the runtime tests cannot:
 * that we are not shipping debug logging, and that we are not building
 * Tailwind class names in ways the compiler cannot see.
 */
export function readSourceFiles(root: string): SourceFile[] {
  const out: SourceFile[] = [];
  const walk = (dir: string) => {
    for (const entry of readdirSyncRetry(dir)) {
      if (entry.isDirectory()) {
        if (!SKIP_DIRS.has(entry.name)) walk(path.join(dir, entry.name));
        continue;
      }
      if (!/\.tsx?$/.test(entry.name)) continue;
      if (/\.test\.tsx?$/.test(entry.name)) continue;
      if (entry.name.endsWith(".d.ts")) continue;
      const full = path.join(dir, entry.name);
      if (full.includes(`${path.sep}test${path.sep}`)) continue;
      const text = readFileSyncRetry(full);
      out.push({
        path: path.relative(root, full).split(path.sep).join("/"),
        text,
        lines: text.split("\n"),
      });
    }
  };
  walk(path.join(root, "src"));
  return out;
}
 
/**
 * Every `.test.ts`/`.test.tsx` file under `src` — the complement of
 * {@link readSourceFiles}, which deliberately excludes them.
 *
 * Checks about *test* code need this. Scanning `readSourceFiles` for a
 * focused test can never find one, because a focused test only ever lives in
 * a file that function filters out.
 */
export function readTestFiles(root: string): SourceFile[] {
  const out: SourceFile[] = [];
  const walk = (dir: string) => {
    for (const entry of readdirSyncRetry(dir)) {
      if (entry.isDirectory()) {
        if (!SKIP_DIRS.has(entry.name)) walk(path.join(dir, entry.name));
        continue;
      }
      if (!/\.test\.tsx?$/.test(entry.name)) continue;
      const full = path.join(dir, entry.name);
      const text = readFileSyncRetry(full);
      out.push({
        path: path.relative(root, full).split(path.sep).join("/"),
        text,
        lines: text.split("\n"),
      });
    }
  };
  walk(path.join(root, "src"));
  return out;
}
 
/** Strip `//` and `/* *\/` comments so a scan does not fire on commented code. */
export function stripComments(text: string): string {
  return text
    .replace(/\/\*[\s\S]*?\*\//g, "")
    .replace(/(^|[^:])\/\/.*$/gm, "$1");
}
 
export interface Finding {
  file: string;
  line: number;
  text: string;
}
 
/** Report every line matching `pattern`, ignoring commented-out code. */
export function scan(
  files: SourceFile[],
  pattern: RegExp,
  isExempt: (f: SourceFile, line: string) => boolean = () => false,
): Finding[] {
  const findings: Finding[] = [];
  for (const file of files) {
    const live = new Set(
      stripComments(file.text)
        .split("\n")
        .map((l) => l.trim())
        .filter(Boolean),
    );
    file.lines.forEach((line, i) => {
      const trimmed = line.trim();
      if (!pattern.test(line)) return;
      Eif (!live.has(trimmed)) return; // commented out
      if (isExempt(file, line)) return;
      findings.push({ file: file.path, line: i + 1, text: trimmed });
    });
  }
  return findings;
}
 
export const formatFindings = (findings: Finding[], limit = 25): string =>
  findings
    .slice(0, limit)
    .map((f) => `  ${f.file}:${f.line}  ${f.text}`)
    .join("\n") +
  (findings.length > limit ? `\n  …and ${findings.length - limit} more` : "");
 
/**
 * Every `className={...}` / `class="..."` expression in a file, flattened to
 * one line each so a multi-line template literal can be matched in one go.
 *
 * Scanning whole files for `bg-${` produces false positives — SVG gradient
 * ids look identical (`id={\`fill-${widget.id}\`}`) and are perfectly fine.
 * Only what actually reaches a `class` attribute matters.
 */
export function classNameExpressions(
  file: SourceFile,
): { value: string; line: number }[] {
  const out: { value: string; line: number }[] = [];
  const text = file.text;
  const re = /className\s*=\s*/g;
  let m: RegExpExecArray | null;
 
  while ((m = re.exec(text))) {
    const start = m.index + m[0].length;
    const open = text[start];
    let end = start;
 
    if (open === "{") {
      let depth = 0;
      for (let i = start; i < text.length; i++) {
        if (text[i] === "{") depth++;
        else if (text[i] === "}") {
          depth--;
          if (depth === 0) {
            end = i + 1;
            break;
          }
        }
      }
    } else if (open === '"' || open === "'") {
      end = text.indexOf(open, start + 1) + 1;
    } else {
      continue;
    }
 
    const value = text.slice(start, end);
    const line = text.slice(0, start).split("\n").length;
    out.push({ value: value.replace(/\s+/g, " "), line });
  }
  return out;
}
 
/**
 * Every JSX `<button>` in a file: its own `className` (flattened, or "" when
 * it has none), what lies between it and its `</button>`, and its line.
 *
 * The opening tag is read to its closing `>` by brace depth, so an arrow
 * function in `onClick={() => …}` does not end it early.
 */
export function buttonElements(
  file: SourceFile,
): { className: string; body: string; line: number }[] {
  const out: { className: string; body: string; line: number }[] = [];
  const text = stripComments(file.text);
  const re = /<button\b/g;
  let m: RegExpExecArray | null;
  while ((m = re.exec(text))) {
    let i = m.index + m[0].length;
    let depth = 0;
    for (; i < text.length; i++) {
      const c = text[i];
      if (c === "{") depth++;
      else if (c === "}") depth--;
      else if (c === ">" && depth === 0) break;
    }
    const tag = text.slice(m.index, i + 1);
    const close = text.indexOf("</button>", i);
    const own = classNameExpressions({ path: file.path, text: tag, lines: [] })[0];
    out.push({
      className: own?.value ?? "",
      body: close === -1 ? "" : text.slice(i + 1, close),
      line: text.slice(0, m.index).split("\n").length,
    });
  }
  return out;
}