scan-broken-imports.mjs 3.71 KB
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const skipDirs = new Set(['node_modules', 'miniprogram_npm', '.git', 'dist'])
const importRe = /(?:import\s+[^'"]+from\s+|require\s*\(\s*)['"](\.[^'"]+)['"]/g

const exts = ['', '.js', '.mjs', '.ts', '.json', '/index.js', '/index.mjs']

function stripQuery(spec) {
  return spec.split('?')[0]
}

function resolveImport(fromFile, spec) {
  spec = stripQuery(spec)
  if (!spec.startsWith('.')) return { resolved: null, target: null }
  let target = path.resolve(path.dirname(fromFile), spec)
  if (path.extname(target)) {
    return { resolved: fs.existsSync(target) ? target : null, target }
  }
  for (const ext of exts) {
    const p = ext.startsWith('/') ? target + ext : target + ext
    if (fs.existsSync(p) && fs.statSync(p).isFile()) return { resolved: p, target: p }
  }
  if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
    for (const ext of ['/index.js', '/index.mjs']) {
      const p = target + ext
      if (fs.existsSync(p)) return { resolved: p, target: p }
    }
  }
  return { resolved: null, target }
}

function walk(dir, files = []) {
  let entries
  try {
    entries = fs.readdirSync(dir, { withFileTypes: true })
  } catch {
    return files
  }
  for (const e of entries) {
    if (skipDirs.has(e.name)) continue
    const full = path.join(dir, e.name)
    if (e.isDirectory()) walk(full, files)
    else if (/\.(js|mjs|ts)$/.test(e.name)) files.push(full)
  }
  return files
}

const subpackages = ['packageEquity', 'packageDynamicForm', 'packageUsedCar', 'packageStudyCenter', 'packageCrowdFunding', 'tabWorkOrder', 'tabRepairOrder', 'tabDate', 'tabIndex', 'tabMine', 'tabOperating', 'integration', 'subvehicleConversion']
const rootOnlyPrefixes = ['utils/', 'api/', 'mixins/', 'store/', 'router/']

const issues = []
const seen = new Set()

for (const file of walk(root)) {
  const relFile = path.relative(root, file).replace(/\\/g, '/')
  const content = fs.readFileSync(file, 'utf8')
  let m
  while ((m = importRe.exec(content)) !== null) {
    const spec = m[1]
    const { resolved, target } = resolveImport(file, spec)
    if (resolved) continue

    const key = `${relFile}|${spec}`
    if (seen.has(key)) continue
    seen.add(key)

    // Cross-subpackage wrong-depth: resolved inside subpackage but exists at project root
    let crossRoot = null
    for (const sp of subpackages) {
      const idx = relFile.indexOf(sp + '/')
      if (idx === -1) continue
      const subRoot = path.join(root, sp)
      const inSub = target && target.startsWith(subRoot)
      if (!inSub) break
      const relTarget = path.relative(subRoot, target).replace(/\\/g, '/')
      for (const prefix of rootOnlyPrefixes) {
        if (!relTarget.startsWith(prefix)) continue
        const rootCandidate = path.join(root, relTarget)
        if (fs.existsSync(rootCandidate) || exts.some((ext) => fs.existsSync(rootCandidate + ext))) {
          crossRoot = path.relative(root, rootCandidate).replace(/\\/g, '/')
        }
      }
    }

    issues.push({ file: relFile, spec, crossRoot })
  }
}

issues.sort((a, b) => {
  if (a.crossRoot && !b.crossRoot) return -1
  if (!a.crossRoot && b.crossRoot) return 1
  return a.file.localeCompare(b.file)
})

const critical = issues.filter((i) => i.crossRoot)
const other = issues.filter((i) => !i.crossRoot)

console.log(`CRITICAL_CROSS_ROOT=${critical.length}`)
for (const i of critical) {
  console.log(`${i.file} -> ${i.spec} | should be ~/${i.crossRoot}`)
}

console.log(`\nOTHER_BROKEN=${other.length}`)
for (const i of other.slice(0, 80)) {
  console.log(`${i.file} -> ${i.spec}`)
}
if (other.length > 80) console.log(`... and ${other.length - 80} more`)