All files / src/utils file-size-stats.ts

96.85% Statements 123/127
92.3% Branches 24/26
85.71% Functions 6/7
96.85% Lines 123/127

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 1901x 1x 1x                                                       6x 6x 6x 6x 6x 6x     6x   4x 4x 4x 4x   4x 4x 4x 4x   1x 6x 6x 6x 6x 1x 1x   5x 6x 1x 1x   4x 4x 4x                 4x   4x 4x   6x 6x 6x 6x 6x 6x   6x 6x 6x 6x 6x 6x 6x   6x 6x 6x   6x 5x 5x 5x 5x 5x 5x 5x 5x   6x 6x 6x 6x   4x 5x 5x 4x   4x   4x 6x   6x 6x 6x 6x 6x 6x 6x 6x 6x   1x 20x 20x 20x   20x 10x 10x 10x   20x 20x   1x 3x   3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x   3x 4x 4x 4x 4x 4x   3x 3x 3x 3x   3x 3x   1x       1x 2x   2x 2x 2x 2x 2x  
import fs, { globSync } from 'node:fs';
import path from 'node:path';
import { gzipSync } from 'node:zlib';
 
export interface FileInfo {
    path: string;
    relativePath: string;
    size: number;
    gzipSize: number;
    ext: string;
}
 
export interface SizeStatsReport {
    totalFiles: number;
    totalSize: number;
    totalGzipSize: number;
    compressionRatio: number;
    files: FileInfo[];
    byExtension: Record<
        string,
        {
            count: number;
            totalSize: number;
            totalGzipSize: number;
            avgSize: number;
            avgGzipSize: number;
        }
    >;
}
 
function getGzipSize(filePath: string): number {
    try {
        const content = fs.readFileSync(filePath);
        const compressed = gzipSync(content, { level: 9 });
        return compressed.length;
    } catch (error) {
        return fs.statSync(filePath).size;
    }
}
 
function getAllFiles(dirPath: string, pattern = '**/!(.*)'): string[] {
    const files = globSync(pattern, {
        cwd: dirPath
    });
 
    return files
        .map((relativePath) => path.resolve(dirPath, relativePath))
        .filter((filePath) => fs.statSync(filePath).isFile());
}
 
export function analyzeDirectory(
    dirPath: string,
    pattern?: string
): SizeStatsReport {
    if (!fs.existsSync(dirPath)) {
        throw new Error(`Directory does not exist: ${dirPath}`);
    }
 
    const stat = fs.statSync(dirPath);
    if (!stat.isDirectory()) {
        throw new Error(`Path is not a directory: ${dirPath}`);
    }
 
    const files = getAllFiles(dirPath, pattern);
    const fileInfos: FileInfo[] = [];
    const byExtension: Record<
        string,
        {
            count: number;
            totalSize: number;
            totalGzipSize: number;
            avgSize: number;
            avgGzipSize: number;
        }
    > = {};
 
    let totalSize = 0;
    let totalGzipSize = 0;
 
    for (const filePath of files) {
        const fileStat = fs.statSync(filePath);
        const size = fileStat.size;
        const gzipSize = getGzipSize(filePath);
        const relativePath = path.relative(process.cwd(), filePath);
        const ext = path.extname(filePath).toLowerCase() || '(no ext)';
 
        const fileInfo: FileInfo = {
            path: filePath,
            relativePath,
            size,
            gzipSize,
            ext
        };
 
        fileInfos.push(fileInfo);
        totalSize += size;
        totalGzipSize += gzipSize;
 
        if (!byExtension[ext]) {
            byExtension[ext] = {
                count: 0,
                totalSize: 0,
                totalGzipSize: 0,
                avgSize: 0,
                avgGzipSize: 0
            };
        }
 
        byExtension[ext].count++;
        byExtension[ext].totalSize += size;
        byExtension[ext].totalGzipSize += gzipSize;
    }
 
    Object.values(byExtension).forEach((group) => {
        group.avgSize = Math.round(group.totalSize / group.count);
        group.avgGzipSize = Math.round(group.totalGzipSize / group.count);
    });
 
    fileInfos.sort((a, b) => b.size - a.size);
 
    const compressionRatio =
        totalSize > 0 ? ((totalSize - totalGzipSize) / totalSize) * 100 : 0;
 
    return {
        totalFiles: files.length,
        totalSize,
        totalGzipSize,
        compressionRatio: Math.round(compressionRatio * 100) / 100,
        files: fileInfos,
        byExtension
    };
}
 
export function formatSize(bytes: number): string {
    const units = ['B', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;
 
    while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024;
        unitIndex++;
    }
 
    return `${size.toFixed(unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`;
}
 
export function generateTextReport(report: SizeStatsReport): string {
    const lines: string[] = [];
 
    lines.push('📊 Bundle Analysis');
    lines.push('='.repeat(50));
    lines.push('');
 
    const maxPathLength = Math.max(
        ...report.files.map((f) => f.relativePath.length)
    );
    const sizeHeader = 'Size'.padStart(10);
    const gzippedHeader = 'Gzipped'.padStart(10);
    const header = `File${' '.repeat(maxPathLength - 4)}  ${sizeHeader}  ${gzippedHeader}`;
    lines.push(header);
    lines.push('-'.repeat(header.length));
 
    for (const file of report.files) {
        const paddedPath = file.relativePath.padEnd(maxPathLength);
        const sizeStr = formatSize(file.size).padStart(10);
        const gzipStr = formatSize(file.gzipSize).padStart(10);
        lines.push(`${paddedPath}  ${sizeStr}  ${gzipStr}`);
    }
 
    lines.push('');
    lines.push(
        `Total: ${report.totalFiles} files, ${formatSize(report.totalSize)} (gzipped: ${formatSize(report.totalGzipSize)})`
    );
 
    return lines.join('\n');
}
 
export function generateJsonReport(report: SizeStatsReport): string {
    return JSON.stringify(report, null, 2);
}
 
export function generateSizeReport(dirPath: string, pattern?: string) {
    const json = analyzeDirectory(dirPath, pattern);
 
    return {
        text: generateTextReport(json),
        json
    };
}