check-package-boundaries.mjs 3.23 KB
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import { buildKnowledgeGraph } from './knowledge-graph/build-knowledge-graph.mjs'

const NON_RUNTIME_PREFIXES = [
  '.agents/',
  '.superpowers/',
  'docs/',
  'node_modules/',
  'outputs/',
  'scripts/',
  'test/',
  'tests/',
  'typings/',
]

function normalizePath(value) {
  return value?.replaceAll('\\', '/').replace(/^\.\//, '')
}

function packageOwner(filePath, subpackageRoots) {
  const normalized = normalizePath(filePath)
  return (
    subpackageRoots.find(
      root => normalized === root || normalized?.startsWith(`${root}/`),
    ) ?? 'main'
  )
}

function isRuntimePath(node, filePath) {
  const normalized = normalizePath(filePath)
  return (
    Boolean(normalized) &&
    node?.type !== 'test' &&
    !NON_RUNTIME_PREFIXES.some(prefix => normalized.startsWith(prefix))
  )
}

function packageEdges({ graph, subpackageRoots }) {
  const nodeById = new Map(graph.nodes.map(node => [node.id, node]))

  return graph.edges
    .filter(edge => edge.type === 'imports' || edge.type === 'usesComponent')
    .map(edge => ({
      edge,
      fromNode: nodeById.get(edge.from),
      toNode: nodeById.get(edge.to),
      fromPath: normalizePath(
        nodeById.get(edge.from)?.path ?? edge.evidence?.path,
      ),
      toPath: normalizePath(nodeById.get(edge.to)?.path),
    }))
    .filter(
      ({ fromNode, toNode, fromPath, toPath }) =>
        isRuntimePath(fromNode, fromPath) && isRuntimePath(toNode, toPath),
    )
    .map(({ edge, fromPath, toPath }) => ({
      type: edge.type,
      from: edge.from,
      to: edge.to,
      fromPath,
      toPath,
      fromOwner: packageOwner(fromPath, subpackageRoots),
      toOwner: packageOwner(toPath, subpackageRoots),
      evidence: edge.evidence,
    }))
    .sort((left, right) =>
      `${left.fromPath}:${left.toPath}:${left.type}`.localeCompare(
        `${right.fromPath}:${right.toPath}:${right.type}`,
        'en',
      ),
    )
}

export function findIllegalPackageEdges({ graph, subpackageRoots }) {
  return packageEdges({ graph, subpackageRoots }).filter(
    edge =>
      edge.toOwner !== 'main' &&
      edge.fromOwner !== edge.toOwner,
  )
}

export async function checkPackageBoundaries({ rootDir = process.cwd() } = {}) {
  const absoluteRoot = path.resolve(rootDir)
  const appConfig = JSON.parse(
    fs.readFileSync(path.join(absoluteRoot, 'app.json'), 'utf8'),
  )
  const subpackageRoots = (appConfig.subpackages ?? appConfig.subPackages ?? [])
    .map(item => normalizePath(item.root))
    .filter(Boolean)
    .sort()
  const graph = await buildKnowledgeGraph({ rootDir: absoluteRoot })
  const checkedEdges = packageEdges({ graph, subpackageRoots })
  const illegalEdges = checkedEdges.filter(
    edge => edge.toOwner !== 'main' && edge.fromOwner !== edge.toOwner,
  )

  return {
    status: illegalEdges.length ? 'error' : 'ok',
    subpackageRoots,
    checkedEdges: checkedEdges.length,
    illegalEdges,
  }
}

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