All files / packages/sds-styling-hooks/scripts validateDist.js

86.88% Statements 106/122
89.47% Branches 51/57
94.44% Functions 17/18
86.2% Lines 100/116

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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269                    1x 1x 24x         1x   1x 1x 1x                                                                       1x 25x 25x 1x 1x           25x               1x 24x 24x 24x   24x 1x 1x     23x 23x 22x 2x   22x 1x   22x 4x       22x 2x         1x     23x               1x 24x 24x 24x 72x 72x 57x     24x               1x 24x 24x   24x 15x     9x   11x 10x   9x 1x 1x     8x 1x     8x 10x 10x 10x 10x 10x   10x 3x       8x                 1x 48x 42x   6x 6x 2x   4x               1x 24x 5x 5x     24x 23x 70x     24x 1x                 1x 25x 25x 25x     25x 25x 25x 1x       24x 24x 24x     24x     24x     24x 24x 1x       24x 24x 1x       24x   24x                       1x            
import path from 'node:path';
import fs from 'fs-extra';
import { fileURLToPath } from 'url';
 
/**
 * Calculate the default dist path. This function handles both native ES modules
 * and Babel-transformed code (used in Jest tests).
 * We check for __dirname first (provided by Babel in CommonJS mode) to avoid
 * issues with Babel's import.meta.url transformation.
 */
let _defaultDist = null;
const getDefaultDist = () => {
  if (_defaultDist) return _defaultDist;
 
  // Check if we're in a Babel-transformed environment (Jest tests)
  // Babel provides __dirname in CommonJS mode, and we can check for it
  // @ts-ignore - __dirname is provided by Babel in CommonJS mode
  Eif (typeof __dirname !== 'undefined') {
    // @ts-ignore - __dirname is provided by Babel in CommonJS mode
    const packageRoot = path.resolve(__dirname, '../');
    _defaultDist = path.resolve(packageRoot, 'dist');
    return _defaultDist;
  }
 
  // In native ES module environment, use import.meta.url
  // We access it inside the function to minimize Babel transformation issues
  try {
    // Access import.meta.url inside try-catch to handle transformation issues
    const metaUrl = (() => {
      try {
        return import.meta.url;
      } catch {
        return undefined;
      }
    })();
 
    if (metaUrl) {
      const __filename = fileURLToPath(metaUrl);
      const scriptDir = path.dirname(__filename);
      const packageRoot = path.resolve(scriptDir, '../');
      _defaultDist = path.resolve(packageRoot, 'dist');
      return _defaultDist;
    }
  } catch (error) {
    // Continue to fallback
  }
 
  // Final fallback: use process.cwd() which should be the package root when run via yarn workspace
  _defaultDist = path.resolve(process.cwd(), 'dist');
  return _defaultDist;
};
 
/**
 * Validates that the dist directory exists.
 * @param {string} dist - Path to dist directory
 * @returns {object} - Object with errors array and isValid boolean
 */
const validateDistExists = (dist) => {
  const errors = [];
  if (!fs.existsSync(dist)) {
    const packageRoot = path.resolve(dist, '..');
    errors.push(
      `Dist directory does not exist: ${dist}\n` +
        `  (Looking relative to package root: ${packageRoot})\n` +
        `  (Current working directory: ${process.cwd()})`,
    );
  }
  return { errors, isValid: errors.length === 0 };
};
 
/**
 * Validates package.json structure and content.
 * @param {string} dist - Path to dist directory
 * @returns {object} - Object with errors and warnings arrays
 */
const validatePackageJson = (dist) => {
  const errors = [];
  const warnings = [];
  const packageJsonPath = path.resolve(dist, 'package.json');
 
  if (!fs.existsSync(packageJsonPath)) {
    errors.push(`Required file missing: dist/package.json`);
    return { errors, warnings };
  }
 
  try {
    const packageJson = fs.readJsonSync(packageJsonPath);
    if (!packageJson.name) {
      errors.push(`package.json is missing required field: name`);
    }
    if (!packageJson.version) {
      errors.push(`package.json is missing required field: version`);
    }
    if (packageJson.scripts) {
      warnings.push(
        `package.json still contains 'scripts' field. These should be stripped before publishing.`,
      );
    }
    if (packageJson.devDependencies) {
      warnings.push(
        `package.json still contains 'devDependencies' field. These should be stripped before publishing.`,
      );
    }
  } catch (error) {
    errors.push(`Failed to parse package.json: ${error.message}`);
  }
 
  return { errors, warnings };
};
 
/**
 * Validates that expected output directories exist.
 * @param {string} dist - Path to dist directory
 * @returns {string[]} - Array of warning messages
 */
const validateOutputDirectories = (dist) => {
  const warnings = [];
  const expectedDirs = ['config', 'defaults', 'themes'];
  expectedDirs.forEach((dir) => {
    const dirPath = path.resolve(dist, dir);
    if (!fs.existsSync(dirPath)) {
      warnings.push(`Expected directory missing: dist/${dir}/`);
    }
  });
  return warnings;
};
 
/**
 * Validates theme-specific output files.
 * @param {string} dist - Path to dist directory
 * @returns {string[]} - Array of warning messages
 */
const validateThemes = (dist) => {
  const warnings = [];
  const themesDir = path.resolve(dist, 'themes');
 
  if (!fs.existsSync(themesDir)) {
    return warnings;
  }
 
  const themes = fs
    .readdirSync(themesDir, { withFileTypes: true })
    .filter((dirent) => dirent.isDirectory())
    .map((dirent) => dirent.name);
 
  if (themes.length === 0) {
    warnings.push(`No theme directories found in dist/themes/`);
    return warnings;
  }
 
  if (!themes.includes('slds')) {
    warnings.push(`Expected theme 'slds' not found in dist/themes/. Found: ${themes.join(', ')}`);
  }
 
  themes.forEach((theme) => {
    const themeDir = path.resolve(themesDir, theme);
    const files = fs.readdirSync(themeDir);
    const hasHooks = files.some((f) => f.includes('.hooks.'));
    const hasCss = files.some((f) => f.endsWith('.css'));
    const hasJson = files.some((f) => f.endsWith('.json'));
 
    if (!hasHooks && !hasCss && !hasJson) {
      warnings.push(`Theme directory '${theme}' appears to be empty or missing output files`);
    }
  });
 
  return warnings;
};
 
/**
 * Validates that a directory is not empty.
 * @param {string} dirPath - Path to directory
 * @param {string} dirName - Name of directory for error message
 * @returns {string|null} - Warning message or null if directory is not empty
 */
const validateDirectoryNotEmpty = (dirPath, dirName) => {
  if (!fs.existsSync(dirPath)) {
    return null;
  }
  const files = fs.readdirSync(dirPath);
  if (files.length === 0) {
    return `${dirName} directory exists but is empty`;
  }
  return null;
};
 
/**
 * Prints validation results to console.
 * @param {string[]} errors - Array of error messages
 * @param {string[]} warnings - Array of warning messages
 */
const printValidationResults = (errors, warnings) => {
  if (errors.length > 0) {
    console.error('❌ Dist validation failed with errors:');
    errors.forEach((error) => console.error(`   - ${error}`));
  }
 
  if (warnings.length > 0) {
    console.warn('⚠️  Dist validation warnings:');
    warnings.forEach((warning) => console.warn(`   - ${warning}`));
  }
 
  if (errors.length === 0 && warnings.length === 0) {
    console.log('✅ Dist folder validation passed');
  }
};
 
/**
 * Validates that the dist folder exists and contains the expected files for publishing.
 * This ensures the package stage has successfully built the distribution artifacts.
 * @param {string} distPath - Optional path to dist directory. Defaults to calculated path.
 */
const validateDist = (distPath) => {
  const dist = distPath || getDefaultDist();
  const errors = [];
  const warnings = [];
 
  // Check if dist directory exists (early return if not)
  const distCheck = validateDistExists(dist);
  errors.push(...distCheck.errors);
  if (!distCheck.isValid) {
    return { errors, warnings, isValid: false };
  }
 
  // Validate package.json
  const packageJsonCheck = validatePackageJson(dist);
  errors.push(...packageJsonCheck.errors);
  warnings.push(...packageJsonCheck.warnings);
 
  // Validate output directories
  warnings.push(...validateOutputDirectories(dist));
 
  // Validate themes
  warnings.push(...validateThemes(dist));
 
  // Validate defaults directory
  const defaultsWarning = validateDirectoryNotEmpty(path.resolve(dist, 'defaults'), 'Defaults');
  if (defaultsWarning) {
    warnings.push(defaultsWarning);
  }
 
  // Validate config directory
  const configWarning = validateDirectoryNotEmpty(path.resolve(dist, 'config'), 'Config');
  if (configWarning) {
    warnings.push(configWarning);
  }
 
  // Print results
  printValidationResults(errors, warnings);
 
  return {
    errors,
    warnings,
    isValid: errors.length === 0,
  };
};
 
// Export for testing
export { validateDist };
 
// Run validation when executed directly (not when imported in tests)
// Skip execution if running in Jest test environment
Iif (!process.env.JEST_WORKER_ID && process.argv[1]?.endsWith('validateDist.js')) {
  const result = validateDist();
  if (!result.isValid) {
    process.exit(1);
  }
}