sync-subpackage-assets.mjs 5.45 KB
/**
 * @file 把被上传配置排除的权威源同步到各分包,并在检查模式下阻止副本漂移。
 */

import {
  copyFileSync,
  cpSync,
  existsSync,
  mkdirSync,
  readFileSync,
  readdirSync,
  rmSync,
  statSync
} from 'node:fs'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { SUBPACKAGE_ASSET_ENTRIES } from './subpackage-assets.manifest.mjs'

const defaultProjectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')

/**
 * 将仓库相对路径解析到指定项目内,避免同步时误删项目外文件。
 * @param {string} projectRoot 项目根目录。
 * @param {string} relativePath 项目相对路径。
 * @returns {string} 解析后的绝对路径。
 */
function resolveInsideProject(projectRoot, relativePath) {
  if (typeof relativePath !== 'string' || !relativePath.trim() || path.isAbsolute(relativePath)) {
    throw new Error(`Subpackage asset path must be a non-empty relative path: ${relativePath}`)
  }
  const absoluteRoot = path.resolve(projectRoot)
  const absolutePath = path.resolve(absoluteRoot, relativePath)
  const relative = path.relative(absoluteRoot, absolutePath)
  if (relative === '' || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
    throw new Error(`Subpackage asset path must stay below the project root: ${relativePath}`)
  }
  return absolutePath
}

/**
 * 递归收集目录中的相对文件路径。
 * @param {string} entryPath 文件或目录绝对路径。
 * @param {string} [basePath] 相对路径计算基准。
 * @returns {string[]} 排序后的文件路径。
 */
function listRelativeFiles(entryPath, basePath = entryPath) {
  if (!existsSync(entryPath)) return []
  if (statSync(entryPath).isFile()) return ['.']
  return readdirSync(entryPath, { withFileTypes: true })
    .sort((left, right) => left.name.localeCompare(right.name))
    .flatMap(entry => {
      const childPath = path.join(entryPath, entry.name)
      if (entry.isDirectory()) return listRelativeFiles(childPath, basePath)
      if (entry.isFile()) return [path.relative(basePath, childPath)]
      throw new Error(`Unsupported subpackage asset entry: ${childPath}`)
    })
}

/**
 * 返回权威源与目标副本的差异。
 * @param {string} sourcePath 权威源绝对路径。
 * @param {string} targetPath 生成目标绝对路径。
 * @returns {string[]} 差异描述。
 */
function compareEntries(sourcePath, targetPath) {
  if (!existsSync(sourcePath)) return [`missing source ${sourcePath}`]
  if (!existsSync(targetPath)) return [`missing target ${targetPath}`]
  if (statSync(sourcePath).isFile() !== statSync(targetPath).isFile()) {
    return [`entry type differs for ${targetPath}`]
  }

  const sourceFiles = listRelativeFiles(sourcePath)
  const targetFiles = listRelativeFiles(targetPath)
  if (sourceFiles.join('\n') !== targetFiles.join('\n')) {
    return [`file set differs for ${targetPath}`]
  }

  return sourceFiles.flatMap(relativeFile => {
    const sourceFile = relativeFile === '.' ? sourcePath : path.join(sourcePath, relativeFile)
    const targetFile = relativeFile === '.' ? targetPath : path.join(targetPath, relativeFile)
    return readFileSync(sourceFile).equals(readFileSync(targetFile))
      ? []
      : [`content differs for ${targetFile}`]
  })
}

/**
 * 同步或检查所有分包资源副本。生成时会先删除明确声明的单个目标,以清理已从权威源删除的旧文件。
 * @param {{projectRoot?: string, entries?: ReadonlyArray<{source: string, targets: readonly string[]}>, checkOnly?: boolean}} [options] 同步选项。
 * @returns {Promise<void>} 检查或同步完成时 resolve,发现漂移时 reject。
 */
export async function syncSubpackageAssets({
  projectRoot = defaultProjectRoot,
  entries = SUBPACKAGE_ASSET_ENTRIES,
  checkOnly = false
} = {}) {
  const differences = []

  for (const entry of entries) {
    const sourcePath = resolveInsideProject(projectRoot, entry.source)
    if (!existsSync(sourcePath)) throw new Error(`Subpackage asset source does not exist: ${entry.source}`)
    for (const target of entry.targets) {
      const targetPath = resolveInsideProject(projectRoot, target)
      if (checkOnly) {
        differences.push(...compareEntries(sourcePath, targetPath))
        continue
      }

      rmSync(targetPath, { recursive: true, force: true })
      mkdirSync(path.dirname(targetPath), { recursive: true })
      if (statSync(sourcePath).isDirectory()) {
        cpSync(sourcePath, targetPath, { recursive: true })
      } else {
        copyFileSync(sourcePath, targetPath)
      }
    }
  }

  if (differences.length > 0) {
    throw new Error(`Subpackage asset copies are out of sync:\n${differences.join('\n')}`)
  }
}

const isCommandLine =
  process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url

if (isCommandLine) {
  const argumentsList = process.argv.slice(2)
  if (argumentsList.length > 1 || (argumentsList.length === 1 && argumentsList[0] !== '--check')) {
    console.error('Usage: node scripts/sync-subpackage-assets.mjs [--check]')
    process.exitCode = 2
  } else {
    syncSubpackageAssets({ checkOnly: argumentsList[0] === '--check' })
      .then(() => {
        console.log(
          argumentsList[0] === '--check'
            ? 'Subpackage asset copies are in sync.'
            : 'Subpackage asset copies synchronized.'
        )
      })
      .catch(error => {
        console.error(error.message)
        process.exitCode = 1
      })
  }
}