main-package-size.mjs 3.46 KB
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

export const DEFAULT_MAIN_PACKAGE_BUDGET_BYTES = 2_000_000

function normalizeRelative(value) {
  return value.replaceAll('\\', '/').replace(/^\.\//, '').replace(/^\/+|\/+$/g, '')
}

function readJson(filePath) {
  return JSON.parse(fs.readFileSync(filePath, 'utf8'))
}

function isInside(relativePath, rootPath) {
  return relativePath === rootPath || relativePath.startsWith(`${rootPath}/`)
}

function collectUploadExclusions(projectConfig) {
  const ignoredFolders = new Set(['node_modules'])
  const ignoredFiles = new Set()

  for (const item of projectConfig.packOptions?.ignore ?? []) {
    const value = normalizeRelative(item.value ?? '')
    if (!value) continue
    if (item.type === 'folder') ignoredFolders.add(value)
    if (item.type === 'file') ignoredFiles.add(value)
  }

  return {
    ignoredFolders: [...ignoredFolders].sort(),
    ignoredFiles: [...ignoredFiles].sort(),
  }
}

function walkFiles(rootDir, shouldExclude) {
  const files = []

  function visit(relativeDir = '') {
    const absoluteDir = path.join(rootDir, relativeDir)
    const entries = fs.readdirSync(absoluteDir, { withFileTypes: true }).sort((a, b) =>
      a.name.localeCompare(b.name, 'en'),
    )

    for (const entry of entries) {
      const relativePath = normalizeRelative(path.join(relativeDir, entry.name))
      if (shouldExclude(relativePath)) continue
      if (entry.isDirectory()) visit(relativePath)
      else if (entry.isFile()) files.push(relativePath)
    }
  }

  visit()
  return files
}

export function analyzeMainPackage({
  rootDir = process.cwd(),
  budgetBytes = DEFAULT_MAIN_PACKAGE_BUDGET_BYTES,
} = {}) {
  const absoluteRoot = path.resolve(rootDir)
  const appConfig = readJson(path.join(absoluteRoot, 'app.json'))
  const projectConfig = readJson(path.join(absoluteRoot, 'project.config.json'))
  const subpackageRoots = (appConfig.subpackages ?? appConfig.subPackages ?? [])
    .map(item => normalizeRelative(item.root ?? ''))
    .filter(Boolean)
    .sort()
  const { ignoredFolders, ignoredFiles } = collectUploadExclusions(projectConfig)

  const shouldExclude = relativePath =>
    subpackageRoots.some(root => isInside(relativePath, root)) ||
    ignoredFolders.some(root => isInside(relativePath, root)) ||
    ignoredFiles.includes(relativePath)

  const files = walkFiles(absoluteRoot, shouldExclude)
  const sizes = files.map(relativePath => ({
    path: relativePath,
    bytes: fs.statSync(path.join(absoluteRoot, relativePath)).size,
  }))
  const totalBytes = sizes.reduce((sum, item) => sum + item.bytes, 0)
  const rootTotals = new Map()

  for (const item of sizes) {
    const root = item.path.includes('/') ? item.path.slice(0, item.path.indexOf('/')) : '(root)'
    rootTotals.set(root, (rootTotals.get(root) ?? 0) + item.bytes)
  }

  const largestRoots = [...rootTotals.entries()]
    .map(([root, bytes]) => ({ root, bytes }))
    .sort((a, b) => b.bytes - a.bytes || a.root.localeCompare(b.root, 'en'))

  return {
    budgetBytes,
    totalBytes,
    totalFiles: files.length,
    remainingBytes: budgetBytes - totalBytes,
    withinBudget: totalBytes <= budgetBytes,
    subpackageRoots,
    largestRoots,
  }
}

const currentFile = fileURLToPath(import.meta.url)
if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(currentFile)) {
  const report = analyzeMainPackage()
  console.log(JSON.stringify(report, null, 2))
  if (!report.withinBudget) process.exitCode = 1
}