All files / packages/design-tokens/src/validators validator-runner-utils.js

89.43% Statements 110/123
63.63% Branches 49/77
92.85% Functions 26/28
90.29% Lines 93/103

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 203 204 205 206 207 208 209              12x 12x   20x           90x     200x         88x 88x 88x 88x 88x 88x   88x 88x   88x 88x 88x 88x 88x                       6x 6x   5x 5x 5x 5x 5x   5x 5x   5x 5x 5x             5x 5x 5x 5x 5x     5x         20x 27x 96x             20x 20x 20x   20x 50x 50x 7x 7x 7x   7x 7x 7x     13x     96x 96x 96x   20x 20x 20x     13x 12x     2x 1x 1x 1x 1x                         14x 14x 14x     84x         14x   14x 14x             14x 14x 14x 14x   43x 14x 5x 46x 5x 5x     14x         14x   14x 84x 84x     14x   14x 14x         14x 14x         23x                
/**
 * Shared utilities for validator runners
 */
import { spawn } from 'child_process';
import readline from 'readline';
import chalk from 'chalk';
 
const SEPARATOR = '='.repeat(80);
const DASH_SEP = '─'.repeat(80);
 
export const parseArgs = (argv = process.argv) => ({
  isVerbose: argv.includes('--verbose') || argv.includes('-v'),
  isInteractive: argv.includes('--interactive') || argv.includes('-i'),
});
 
/** Create a validator config object */
export const v = (name, script, description, extraArgs = []) => ({
  name,
  command: 'node',
  args: (verboseFlag) => [`src/validators/${script}`, ...extraArgs, verboseFlag].filter(Boolean),
  description,
});
 
export function runValidator(validator, spawnFn = spawn) {
  return new Promise((resolve) => {
    console.log(chalk.bold.blue(`\n${SEPARATOR}`));
    console.log(chalk.bold.blue(`Running: ${validator.name}`));
    console.log(chalk.bold.blue(`Description: ${validator.description}`));
    if (validator.category) console.log(chalk.bold.blue(`Category: ${validator.category}`));
    console.log(chalk.bold.blue(SEPARATOR));
 
    const startTime = Date.now();
    const args = typeof validator.args === 'function' ? validator.args('') : validator.args;
 
    spawnFn(validator.command, args, { stdio: 'inherit', shell: false }).on('close', (code) => {
      const duration = ((Date.now() - startTime) / 1000).toFixed(2);
      const status = code === 0 ? 'PASS' : 'FAIL';
      console.log((code === 0 ? chalk.green : chalk.red)(`\n${status}: ${validator.name} (${duration}s)`));
      resolve({
        name: validator.name,
        status,
        code,
        duration,
        ...(validator.category && { category: validator.category }),
      });
    });
  });
}
 
export function promptContinue(nextValidator, { isRlClosed = false } = {}) {
  return new Promise((resolve) => {
    if (isRlClosed) return resolve(true);
 
    const categoryInfo = nextValidator.category ? ` (${nextValidator.category})` : '';
    console.log(chalk.bold.yellow(`\n${DASH_SEP}`));
    console.log(chalk.bold.yellow(`Next: ${nextValidator.name}${categoryInfo}`));
    console.log(chalk.yellow('Press Enter or Space to continue (or Ctrl+C to exit)...'));
    console.log(chalk.bold.yellow(DASH_SEP));
 
    process.stdin.setRawMode(true);
    process.stdin.resume();
 
    const onKeyPress = (chunk) => {
      const key = chunk.toString();
      Eif (
        key === '\r' ||
        key === '\n' ||
        key === ' ' ||
        key.charCodeAt(0) === 13 ||
        key.charCodeAt(0) === 32
      ) {
        process.stdin.setRawMode(false);
        process.stdin.pause();
        process.stdin.removeListener('data', onKeyPress);
        console.log('');
        resolve(true);
      }
    };
    process.stdin.on('data', onKeyPress);
  });
}
 
function printResults(results, grouped = false) {
  const print = (items, indent = '') =>
    items.forEach((r) => {
      console.log(
        (r.status === 'PASS' ? chalk.green : chalk.red)(
          `${indent}${r.status.padEnd(6)} ${r.name.padEnd(50 - indent.length)} ${r.duration}s`,
        ),
      );
    });
 
  console.log(chalk.bold.blue(`\n\n${SEPARATOR}`));
  console.log(chalk.bold.blue('SUMMARY'));
  console.log(chalk.bold.blue(SEPARATOR));
 
  if (grouped) {
    const permanent = results.filter((r) => r.category === 'permanent');
    const temporary = results.filter((r) => r.category === 'temporary');
    Eif (permanent.length) {
      console.log(chalk.bold.cyan('\nPermanent Validators:'));
      print(permanent, '  ');
    }
    Eif (temporary.length) {
      console.log(chalk.bold.cyan('\nTemporary Validators:'));
      print(temporary, '  ');
    }
  } else {
    print(results);
  }
 
  const passed = results.filter((r) => r.status === 'PASS').length;
  const failed = results.filter((r) => r.status === 'FAIL').length;
  const totalTime = results.reduce((sum, r) => sum + parseFloat(r.duration), 0).toFixed(2);
 
  console.log(chalk.bold.blue(`\n${SEPARATOR}`));
  console.log(chalk.bold(`Total: ${passed} passed, ${failed} failed (${totalTime}s)`));
  return { passed, failed, totalTime };
}
 
export const printBasicSummary = (results) => printResults(results, false);
export const printCategorizedSummary = (results) => printResults(results, true);
 
export function setupSigintHandler(exitFn = process.exit) {
  process.on('SIGINT', () => {
    console.log(chalk.yellow('\n\n⚠️  Interrupted by user'));
    Iif (process.stdin.isRaw) process.stdin.setRawMode(false);
    process.stdin.pause();
    exitFn(130);
  });
}
 
export async function createRunner(config) {
  const {
    title,
    description,
    getValidators,
    printSummary = printBasicSummary,
    argv = process.argv,
    spawnFn = spawn,
    exitFn = process.exit,
  } = config;
  const { isVerbose, isInteractive } = parseArgs(argv);
  const verboseFlag = isVerbose ? '--verbose' : '';
 
  // Resolve validator args with verboseFlag
  const validators = getValidators(verboseFlag).map((val) => ({
    ...val,
    args: typeof val.args === 'function' ? val.args(verboseFlag) : val.args,
  }));
 
  const results = [];
  let rl,
    isRlClosed = false;
  const closeReadline = () => {
    if (rl && !isRlClosed) {
      rl.close();
      isRlClosed = true;
    }
  };
 
  console.log(chalk.bold.blue(`\n🔍 ${title}`));
  console.log(SEPARATOR);
  console.log(chalk.gray(`${description}\n`));
  console.log(`Total validators to run: ${validators.length}`);
 
  const hasCategories = validators.some((val) => val.category);
  if (hasCategories) {
    const counts = { permanent: 0, temporary: 0 };
    validators.forEach((val) => val.category && counts[val.category]++);
    Eif (counts.permanent) console.log(`  - Permanent: ${counts.permanent}`);
    Eif (counts.temporary) console.log(`  - Temporary: ${counts.temporary}`);
  }
 
  Iif (isInteractive) {
    console.log(chalk.gray('\nInteractive mode: Press Enter or Space to continue between validators'));
    console.log(chalk.gray('Press Ctrl+C at any time to exit'));
    rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  }
  console.log('');
 
  for (let i = 0; i < validators.length; i++) {
    results.push(await runValidator(validators[i], spawnFn));
    Iif (isInteractive && i < validators.length - 1) await promptContinue(validators[i + 1], { isRlClosed });
  }
 
  Iif (isInteractive) closeReadline();
 
  const { passed, failed } = printSummary(results);
  console.log(
    failed === 0
      ? chalk.green('\n✅ All validators passed!\n')
      : chalk.red(`\n❌ ${failed} validator(s) failed\n`),
  );
  exitFn(failed === 0 ? 0 : 1);
  return { passed, failed };
}
 
/** Standard entry point for runner scripts - call with import.meta.url */
export function runMain(main, importMetaUrl) {
  Iif (importMetaUrl === `file://${process.argv[1]}`) {
    setupSigintHandler();
    main().catch((err) => {
      console.error('\n❌ Error running validators:', err);
      process.exit(1);
    });
  }
}