All files / packages/sds-customization-compliance/src/theme-layer-validator cli.ts

71.59% Statements 63/88
72.58% Branches 45/62
88.88% Functions 8/9
70.88% Lines 56/79

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                                            5x 5x 4x 1x                     4x 4x       4x 7x 7x 7x 2x 5x 5x 5x 5x                   3x 3x   3x 3x   1x 1x           2x 2x             2x 5x       2x 74x   2x   2x   2x           2x   74x               74x 74x 3x 3x 3x 3x   3x 3x   3x         2x   2x                             3x 3x                                 3x           3x 3x               3x 3x 3x   3x 2x   2x   2x                     50x    
import fsp from 'node:fs/promises';
import path from 'node:path';
import arg from 'arg';
import chalk from 'chalk';
import { flattenCss } from '../audit/extract.js';
import { runChecks } from '../checks/index.js';
import type { ComplianceRow, ComponentSourceFile, ComponentSourceFileRole } from '../types.js';
 
export function usage(): string {
  return [
    'Usage: sds-compliance validate --component <name> [--path <dir> ...] [--json <file>]',
    '',
    'Options:',
    '  --component <name>   Component prefix in --slds-c-{component}-*',
    '  --path <path>        Component directory to scan (repeatable, optional)',
    '                       Defaults to packages/design-system-2/src/slds2/<component>',
    '  --json <file>        Write structured JSON report to file',
    '  --help               Show this help',
  ].join('\n');
}
 
function inferRole(absPath: string, component: string): ComponentSourceFileRole {
  const p = absPath.replace(/\\/g, '/');
  if (/\/themes\/base\.css$/.test(p)) return 'theme-base';
  if (/\/themes\/[^/]+\.css$/.test(p)) return 'theme';
  Eif (p.endsWith(`/${component}.css`)) return 'base';
  return 'aux';
}
 
async function walkDir(
  dir: string,
  component: string,
  baseRef: string,
  out: ComponentSourceFile[],
): Promise<void> {
  let entries: import('node:fs').Dirent[];
  try {
    entries = await fsp.readdir(dir, { withFileTypes: true, encoding: 'utf-8' });
  } catch {
    return;
  }
  for (const entry of entries) {
    Iif (entry.name.startsWith('__')) continue;
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      await walkDir(full, component, baseRef, out);
    } else Eif (entry.isFile() && entry.name.endsWith('.css')) {
      const css = await fsp.readFile(full, 'utf-8');
      const root = await flattenCss(css, full);
      out.push({ path: path.relative(baseRef, full), role: inferRole(full, component), root });
    }
  }
}
 
async function loadSourceFiles(
  inputPaths: string[],
  component: string,
  baseRef: string,
): Promise<ComponentSourceFile[]> {
  const out: ComponentSourceFile[] = [];
  for (const inputPath of inputPaths) {
    let stat;
    try {
      stat = await fsp.stat(inputPath);
    } catch (err) {
      Eif ((err as NodeJS.ErrnoException).code === 'ENOENT') {
        throw new Error(
          `Component directory not found: ${inputPath}. If running outside the repo root, pass --path explicitly.`,
        );
      }
      throw err;
    }
    if (stat.isDirectory()) {
      await walkDir(inputPath, component, baseRef, out);
    } else Eif (inputPath.endsWith('.css')) {
      const css = await fsp.readFile(inputPath, 'utf-8');
      const root = await flattenCss(css, inputPath);
      out.push({ path: path.relative(baseRef, inputPath), role: inferRole(inputPath, component), root });
    }
  }
  const seen = new Set<string>();
  return out.filter((f) => (seen.has(f.path) ? false : seen.add(f.path) && true));
}
 
function printRows(componentName: string, rows: ComplianceRow[]): void {
  const summary = { pass: 0, fail: 0, review: 0, info: 0 };
  for (const r of rows) summary[r.status]++;
 
  const statusStr = summary.fail > 0 ? chalk.red('FAIL') : chalk.green('PASS');
  // eslint-disable-next-line no-console
  console.info(`${statusStr} Theme Layer compliance for ${chalk.cyan(componentName)}`);
  // eslint-disable-next-line no-console
  console.info(
    `Checks: ${rows.length} total, ${chalk.green(String(summary.pass))} passed, ` +
      `${chalk.red(String(summary.fail))} failed, ${chalk.yellow(String(summary.review))} review, ` +
      `${chalk.gray(String(summary.info))} info`,
  );
 
  for (const row of rows) {
    const marker =
      row.status === 'pass'
        ? chalk.green('PASS')
        : row.status === 'fail'
          ? chalk.red('FAIL')
          : row.status === 'review'
            ? chalk.yellow('REVIEW')
            : chalk.gray('INFO');
    // eslint-disable-next-line no-console
    console.info(`\n[${row.id}] ${marker} ${row.label}`);
    for (const off of row.offenders ?? []) {
      const loc = off.location ? ` (${chalk.dim(off.location)})` : '';
      const hook = off.hook ? ` [${chalk.cyan(off.hook)}]` : '';
      const sel = off.selector ? ` {${off.selector}}` : '';
      const note = off.note ?? off.prop ?? '';
      // eslint-disable-next-line no-console
      console.info(`  - ${note}${hook}${sel}${loc}`);
      Eif (off.fix) {
        // eslint-disable-next-line no-console
        console.info(`    ${chalk.dim(`fix: ${off.fix}`)}`);
      }
    }
  }
 
  Eif (summary.info > 0) {
    // eslint-disable-next-line no-console
    console.info(
      chalk.gray(
        `\n${summary.info} check${summary.info === 1 ? '' : 's'} returned info (themeData not supplied; run \`sds-compliance build\` for the full hook-surface results).`,
      ),
    );
  }
}
 
export async function main(argv: string[] = process.argv.slice(2)): Promise<number> {
  let args: {
    '--component'?: string;
    '--path'?: string[];
    '--json'?: string;
    '--help'?: boolean;
  };
  try {
    args = arg(
      {
        '--component': String,
        '--path': [String],
        '--json': String,
        '--help': Boolean,
      },
      { argv },
    );
  } catch (error) {
    // eslint-disable-next-line no-console
    console.error(chalk.red(error instanceof Error ? error.message : String(error)));
    // eslint-disable-next-line no-console
    console.info(usage());
    return 1;
  }
 
  Iif (args['--help']) {
    // eslint-disable-next-line no-console
    console.info(usage());
    return 0;
  }
 
  const component = args['--component'];
  Iif (!component) {
    // eslint-disable-next-line no-console
    console.error(chalk.red('Missing required --component.'));
    // eslint-disable-next-line no-console
    console.info(usage());
    return 1;
  }
 
  const rawPaths = args['--path'] ?? [path.join('packages', 'design-system-2', 'src', 'slds2', component)];
  const scanPaths = rawPaths.map((p) => path.resolve(p));
  const baseRef = process.cwd();
 
  const componentSourceFiles = await loadSourceFiles(scanPaths, component, baseRef);
  const rows = runChecks({ componentName: component, componentSourceFiles });
 
  printRows(component, rows);
 
  Iif (args['--json']) {
    const outPath = path.resolve(args['--json']);
    await fsp.mkdir(path.dirname(outPath), { recursive: true });
    const summary = { pass: 0, fail: 0, review: 0, info: 0 };
    for (const r of rows) summary[r.status]++;
    const report = { componentName: component, generatedAt: new Date().toISOString(), rows, summary };
    await fsp.writeFile(outPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
    // eslint-disable-next-line no-console
    console.info(`\nWrote JSON report: ${outPath}`);
  }
 
  return rows.some((r) => r.status === 'fail') ? 2 : 0;
}