Skip to content

An open source design system that's fully customizable and agent ready

TypeScript
64.8 KB
Raw Blame
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
 * @file `astryx integration verify` — verify an integration package is
 * ready to publish by cross-referencing its declared contributions against the
 * real npm tarball.
 *
 * Three phases:
 *   1. Structure validation — reuses `validateLocalIntegration`.
 *   2. Pack-list cross-reference — computes the static file inventory and
 *      compares it against the lifecycle-produced `npm pack --json` artifact.
 *   3. Extracted-tarball validation — extracts the tarball into a scratch
 *      consumer under the author's node_modules and runs the same discovery
 *      functions a consumer uses, then compares identities (slugs, names,
 *      topic ids) exactly.
 *
 * Contract: every contribution visible in the author's package, and every
 * file required to make it visible, must survive the real npm tarball and
 * be equally visible from an extracted node_modules consumer view.
 */

import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import {fileURLToPath} from 'node:url';
import {spawnSync} from 'node:child_process';
import {assertWithin} from '../../foundation/fs/path-safety.mjs';
import {npmCommand} from '../../foundation/release/cache.mjs';
import {commandTokensIn} from '../../foundation/doc-compiler/doc-syntax.mjs';
import {resolvePackageDir} from '../../foundation/integrations/integrations.mjs';
import {
  literalThemeName,
  rootProblem,
  symlinkedFolder,
} from '../../foundation/integrations/validate-contributions.mjs';
import {
  componentReplacesCliProblem,
  docsTreeCliProblem,
  keywordsCliProblem,
  replacesCliProblem,
  sectionIdsCliProblem,
  docTokensCliProblem,
  sectionPositionCliProblem,
  themesCliProblem,
} from '../../foundation/integrations/cli-requirement.mjs';
import {
  discoverIntegrationDocs,
  loadTopicModule,
} from '../../foundation/discovery/docs-discovery.mjs';
import {discoverIntegrationThemes} from '../../foundation/discovery/theme-discovery.mjs';
import {inspectPackageExport} from '../../foundation/discovery/package-exports.mjs';
import {parse as parseModule} from '@babel/parser';
import {moduleExportsName} from '../../foundation/discovery/module-exports.mjs';
import {
  ThemeImportError,
  resolveThemeImports,
} from '../../foundation/discovery/theme-imports.mjs';
import {
  normalizeThemeBuildForCompare,
  themeBuild,
} from '../theme/build/build.mjs';
import {
  discoverIntegrationComponents,
  docStem,
  familyImports,
  isIntegrationMember,
  resolveIntegrationImportPath,
} from '../../foundation/discovery/component-discovery.mjs';
import {loadComponentReplacements} from '../component/_adapter.mjs';
import {loadComponentDoc} from '../../foundation/discovery/component-loader.mjs';
import {discoverIntegrationTemplatesForOne} from '../../foundation/discovery/template-adapter.mjs';
import {
  validateLocalIntegration,
  validateInstalledIntegration,
} from './validate-integration.mjs';
import {
  computeRequiredFiles,
  collectIdentities,
  compareIdentities,
} from '../../foundation/integrations/contribution-inventory.mjs';
import {formatCliCommand} from '../../foundation/env/package-manager.mjs';

/**
 * @typedef {import('../../foundation/integrations/issue').AstryxIntegrationIssue} Issue
 */

/** @param {string} code @param {string} message @returns {Issue} */
function error(code, message) {
  return {code, severity: 'error', message};
}

/** @param {string} code @param {string} message @returns {Issue} */
function warning(code, message) {
  return {code, severity: 'warning', message};
}

const GENERATED_HEADER_LINE =
  ' * @generated by `astryx theme build` — do not edit manually.';
const SOURCE_LINE = /^( \* Source: )(\S(?:.*\S)?)(\s*)$/u;
const CLI_VERSION_LINE = /^( \* CLI: @astryxdesign\/cli@)(\S+)(\s*)$/u;
const CORE_VERSION_LINE = /^( \* Core: @astryxdesign\/core@)(\S+)(\s*)$/u;
// The built module's own doc comment names the command that built it, which
// depends on the package manager and host that ran the build.
const BUILT_BY_LINE =
  /^( \* \S(?:.*\S)? theme — built by `)(\S(?:.*\S)?)( theme build`)(\s*)$/u;

/**
 * Compare generated theme outputs without making their build directory,
 * CLI/Core version, or build command look like source drift. Normalization
 * applies only to a file whose first comment is the generated header with
 * exactly one well-formed Source, CLI, and Core line; it covers those lines
 * and, in a built module, the one `built by` line that names the command
 * (`yarn astryx`, `pnpm exec astryx`, or a host's own). Missing, duplicate,
 * malformed, reordered, or any other bytes stay significant. `theme build
 * --check` deliberately stays strict.
 * @param {string} content
 */
export function normalizeThemeVerifyForCompare(content) {
  const normalized = normalizeThemeBuildForCompare(content);
  const lines = normalized.split('\n');
  if (lines[0] !== '/*' && lines[0] !== '/**') return normalized;
  const close = lines.indexOf(' */', 1);
  if (close === -1) return normalized;
  const header = lines.slice(1, close);
  if (header.filter(line => line === GENERATED_HEADER_LINE).length !== 1) {
    return normalized;
  }
  const source = header.filter(line => SOURCE_LINE.test(line));
  const cli = header.filter(line => CLI_VERSION_LINE.test(line));
  const core = header.filter(line => CORE_VERSION_LINE.test(line));
  if (source.length !== 1 || cli.length !== 1 || core.length !== 1) {
    return normalized;
  }
  const builtBy = lines.filter(line => BUILT_BY_LINE.test(line)).length;
  return lines
    .map((line, index) => {
      if (builtBy === 1 && BUILT_BY_LINE.test(line)) {
        return line.replace(BUILT_BY_LINE, '$1<command>$3$4');
      }
      if (index >= close) return line;
      if (SOURCE_LINE.test(line)) {
        return line.replace(SOURCE_LINE, '$1<source>$3');
      }
      if (CLI_VERSION_LINE.test(line)) {
        return line.replace(CLI_VERSION_LINE, '$1<version>$3');
      }
      if (CORE_VERSION_LINE.test(line)) {
        return line.replace(CORE_VERSION_LINE, '$1<version>$3');
      }
      return line;
    })
    .join('\n');
}

/**
 * Cleanup must never hide the check result or prevent the other temporary tree
 * from being removed.
 * @param {string|null} dir
 * @param {string} label
 * @param {Issue[]} issues
 */
function removeTreeBestEffort(dir, label, issues) {
  if (dir == null) return;
  try {
    fs.rmSync(dir, {recursive: true, force: true});
  } catch (err) {
    issues.push(
      warning(
        'cleanup_failed',
        `Could not remove ${label} ${dir}: ${err instanceof Error ? err.message : String(err)}`,
      ),
    );
  }
}

/**
 * Find the nearest package.json starting from `cwd` and walking up.
 * @param {string} cwd
 * @returns {{packageDir: string, pkg: Record<string, unknown>}|null}
 */
function findPackage(cwd) {
  let dir = path.resolve(cwd);
  for (let depth = 0; depth < 50; depth++) {
    const file = path.join(dir, 'package.json');
    if (fs.existsSync(file)) {
      try {
        return {
          packageDir: dir,
          pkg: JSON.parse(fs.readFileSync(file, 'utf-8')),
        };
      } catch (err) {
        throw new Error(
          `Could not parse ${file}: ${err instanceof Error ? err.message : String(err)}`,
          {cause: err},
        );
      }
    }
    const parent = path.dirname(dir);
    if (parent === dir) break;
    dir = parent;
  }
  return null;
}

/**
 * Build the empty receipt returned when no integration manifest is found.
 * @param {string|null} name
 * @param {Issue[]} issues
 * @returns {import('./pack-check.type.mjs').IntegrationPackCheckResponse}
 */
function emptyReceipt(name, issues) {
  return {
    type: 'integration.pack-check',
    data: {
      name,
      version: null,
      packable: !issues.some(i => i.severity === 'error'),
      tarball: null,
      inventory: {manifest: null, roots: [], expectedFiles: 0, packedFiles: 0},
      contributions: {local: null, packed: null},
      issues,
    },
  };
}

/**
 * Parse npm's JSON pack result into the facts the checker needs.
 * @param {string} output
 * @returns {{filename: string, fileCount: number, size: number, unpackedSize: number, packedPaths: Set<string>}}
 */
export function parseNpmPackOutput(output) {
  /** @type {Array<{filename: string, entryCount: number, size: number, unpackedSize: number, files?: Array<{path: string}>}>} */
  let parsed;
  try {
    parsed = JSON.parse(output);
  } catch {
    throw new Error('npm pack produced unparseable JSON output.');
  }
  if (!Array.isArray(parsed) || parsed.length === 0) {
    throw new Error('npm pack returned an empty result.');
  }
  const info = parsed[0];
  if (!info || !Array.isArray(info.files)) {
    throw new Error('npm pack returned a result without a files array.');
  }
  return {
    // npm 8 names a scoped package's tarball `@scope/name-1.0.0.tgz` in its
    // JSON but writes `scope-name-1.0.0.tgz`, as every later npm reports.
    filename:
      typeof info.filename === 'string' && /^@[^/]+\//.test(info.filename)
        ? info.filename.slice(1).replace('/', '-')
        : info.filename,
    fileCount: info.entryCount,
    size: info.size,
    unpackedSize: info.unpackedSize,
    packedPaths: new Set(info.files.map(file => file.path)),
  };
}

/**
 * Summarize the JSON error npm prints on stdout when `--json` pack fails.
 * @param {string} output
 * @returns {string}
 */
function npmPackErrorDetail(output) {
  try {
    const error = JSON.parse(output)?.error;
    return [error?.summary, error?.detail]
      .filter(part => typeof part === 'string' && part.trim() !== '')
      .join(': ');
  } catch {
    return (output || '').trim();
  }
}

/**
 * Run `npm pack --json` with output directed to `destDir` so no preexisting
 * tgz is overwritten. This intentionally runs the package lifecycle, matching
 * the artifact `npm publish` would produce. npm starts the way the CLI starts
 * it everywhere else (`npmCommand`): npm's own entry file run with this Node
 * when one is found, so an `npm` earlier on the PATH that is not npm itself
 * cannot answer for it. Uses spawnSync with an args array — no shell — so
 * paths with metacharacters cannot inject.
 *
 * @param {string} packageDir
 * @param {string} destDir
 * @returns {{filename: string, fileCount: number, size: number, unpackedSize: number, packedPaths: Set<string>}}
 */
function runNpmPack(packageDir, destDir) {
  const npm = npmCommand();
  const result = spawnSync(
    npm.command,
    [
      ...npm.prefix,
      'pack',
      '--json',
      '--silent',
      // Lifecycle scripts still run; background mode keeps their output off
      // the stdout that carries the JSON result.
      '--foreground-scripts=false',
      `--pack-destination=${destDir}`,
    ],
    {cwd: packageDir, encoding: 'utf-8', shell: false, timeout: 60_000},
  );
  if (result.error) {
    throw new Error(`Could not start npm pack: ${result.error.message}`);
  }
  if (result.status !== 0) {
    const detail =
      (result.stderr || '').trim() || npmPackErrorDetail(result.stdout);
    throw new Error(
      `npm pack failed (exit ${result.status})${detail ? `: ${detail}` : ''}.`,
    );
  }
  return parseNpmPackOutput(result.stdout);
}

/**
 * Extract a tarball into `extractDir`, stripping the leading `package/`
 * directory that npm tarballs wrap files in. Uses spawnSync with an args
 * array — no shell.
 *
 * @param {string} tgzPath
 * @param {string} extractDir
 */
function extractTarball(tgzPath, extractDir) {
  fs.mkdirSync(extractDir, {recursive: true});
  const result = spawnSync(
    'tar',
    ['xzf', tgzPath, '-C', extractDir, '--strip-components=1'],
    {encoding: 'utf-8', timeout: 30_000},
  );
  if (result.error) {
    throw new Error(`Could not start tar extraction: ${result.error.message}`);
  }
  if (result.status !== 0) {
    const stderr = (result.stderr || '').trim();
    throw new Error(
      `tar extraction failed (exit ${result.status})${stderr ? `: ${stderr}` : ''}.`,
    );
  }
}

/**
 * Whether any of these doc files writes a doc token (`{@command …}`, `{@pm …}`
 * or `{@pm-only …}`; an escaped `{@@…}` is not one).
 * @param {unknown[]} files
 * @returns {boolean}
 */
function writesDocTokens(files) {
  return files.some(file => {
    if (typeof file !== 'string') return false;
    try {
      return commandTokensIn(fs.readFileSync(file, 'utf8')).length > 0;
    } catch {
      return false;
    }
  });
}

/**
 * Whether any of these doc files has a section that sets `id`.
 * @param {string[]} files
 * @returns {Promise<boolean>}
 */
async function setsSectionIds(files) {
  return setsSectionField(files, ['id']);
}

/**
 * Whether any of these doc files has a section that sets one of `fields`.
 * @param {string[]} files
 * @param {string[]} fields
 * @returns {Promise<boolean>}
 */
async function setsSectionField(files, fields) {
  for (const file of files) {
    if (typeof file !== 'string') continue;
    const doc = /** @type {any} */ (
      await loadTopicModule(file).catch(() => null)
    );
    const sections = Array.isArray(doc?.sections) ? doc.sections : [];
    if (
      sections.some((/** @type {any} */ section) =>
        fields.some(field => section?.[field] != null),
      )
    ) {
      return true;
    }
  }
  return false;
}

/**
 * Resolve package specifiers through Node's real ESM resolver from the scratch
 * consumer. Resolution does not execute the target module, so source `.tsx`
 * exports and built `.mjs` exports are both safe to inspect.
 *
 * @param {string[]} specifiers
 * @param {string} scratchBase
 * @returns {Map<string, {url?: string, error?: string}>}
 */
function resolveConsumerSpecifiers(specifiers, scratchBase) {
  const resolver = path.join(scratchBase, '.astryx-resolve-imports.mjs');
  const source = `const specs = JSON.parse(process.argv[2]);\nconst out = {};\nfor (const specifier of specs) {\n  try { out[specifier] = {url: import.meta.resolve(specifier)}; }\n  catch (error) { out[specifier] = {error: error instanceof Error ? error.message : String(error)}; }\n}\nconsole.log(JSON.stringify(out));\n`;
  fs.writeFileSync(resolver, source, {flag: 'wx'});
  try {
    const result = spawnSync(
      process.execPath,
      [resolver, JSON.stringify([...new Set(specifiers)])],
      {cwd: scratchBase, encoding: 'utf-8', timeout: 30_000},
    );
    if (result.error || result.status !== 0) {
      const message = result.error?.message ?? result.stderr.trim();
      return new Map(
        specifiers.map(specifier => [
          specifier,
          {error: message || `resolver exited ${result.status}`},
        ]),
      );
    }
    const parsed = JSON.parse(result.stdout);
    return new Map(
      /** @type {Array<[string, {url?: string, error?: string}]>} */ (
        Object.entries(parsed)
      ),
    );
  } finally {
    fs.rmSync(resolver, {force: true});
  }
}

/**
 * Verify that every packed component is reachable through the exact import
 * specifier the component API gives consumers, and that the resolved module
 * statically exports the component name.
 *
 * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} integration
 * @param {string} scratchBase
 * @returns {Promise<Issue[]>}
 */
async function validatePackedComponentExports(integration, scratchBase) {
  const records = discoverIntegrationComponents(integration);
  /** @type {Issue[]} */
  const issues = [];
  /** @type {Array<{name: string, specifier: string}>} */
  const components = [];
  // A family doc backs several records: load it, and report it, once.
  const loads = new Map();
  for (const record of records) {
    const first = !loads.has(record.docPath);
    if (first) loads.set(record.docPath, loadComponentDoc(record.docPath));
    let docs;
    try {
      docs = await loads.get(record.docPath);
    } catch (err) {
      if (!first) continue;
      issues.push(
        error(
          'component_doc_unloadable',
          `Component "${docStem(record.docPath)}" doc at "${record.docPath}" could not be loaded: ${err instanceof Error ? err.message : String(err)}`,
        ),
      );
      continue;
    }
    const specifier =
      /** @type {{import?: string}} */ (docs).import ??
      resolveIntegrationImportPath(
        {
          exportsMap: integration.__packageExports,
          packageDir: integration.__packageDir,
          docPath: record.docPath,
          packageName: integration.name,
        },
        record.name,
      );
    components.push({name: record.name, specifier});
  }

  const resolved = resolveConsumerSpecifiers(
    components.map(component => component.specifier),
    scratchBase,
  );
  issues.push(
    ...validateSpecifierExtensions(
      components.map(({name, specifier}) => ({
        label: `Component "${name}"`,
        specifier,
      })),
    ),
  );
  for (const {name, specifier} of components) {
    const result = resolved.get(specifier);
    if (!result?.url || result.error) {
      issues.push(
        error(
          'component_import_unresolvable',
          `Component "${name}" advertises import "${specifier}", but a consumer cannot resolve it${result?.error ? `: ${result.error}` : '.'}`,
        ),
      );
      continue;
    }
    let target;
    try {
      target = fileURLToPath(result.url);
    } catch {
      target = null;
    }
    if (!target || !moduleExportsName(target, name)) {
      issues.push(
        error(
          'component_export_missing',
          `Component "${name}" advertises import "${specifier}", but that packed module does not export "${name}". Add or correct the package export before publishing.`,
        ),
      );
    }
  }
  return issues;
}

/** @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} integration */
function integrationPackageMetadata(integration) {
  try {
    return JSON.parse(
      fs.readFileSync(
        path.join(integration.__packageDir, 'package.json'),
        'utf-8',
      ),
    );
  } catch {
    return {name: integration.name};
  }
}

/**
 * The exported output group selected for one theme. A complete per-theme or
 * single-theme pair wins; otherwise return the incomplete group so each path
 * can still be checked without making source-only packages fail.
 * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} integration
 * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
 * @param {number} themeCount
 */
function declaredThemeBuildOutputs(integration, theme, themeCount) {
  const pkg = integrationPackageMetadata(integration);
  if (pkg.exports === undefined) return [];
  const groups = [
    [
      {kind: 'module', subpath: `./themes/${theme.slug}`},
      {kind: 'stylesheet', subpath: `./themes/${theme.slug}.css`},
      {kind: 'font stylesheet', subpath: `./themes/${theme.slug}.fonts.css`},
    ],
    ...(themeCount === 1
      ? [
          [
            {kind: 'module', subpath: './built'},
            {kind: 'stylesheet', subpath: './theme.css'},
            {kind: 'font stylesheet', subpath: './fonts.css'},
          ],
        ]
      : []),
  ].map(group =>
    group.map(output => ({
      ...output,
      inspected: inspectPackageExport(
        pkg,
        integration.__packageDir,
        output.subpath,
      ),
    })),
  );
  const declared = groups.map(group =>
    group.filter(output => output.inspected.exported),
  );
  return (
    declared.find(
      group =>
        group.some(output => output.kind === 'module') &&
        group.some(output => output.kind === 'stylesheet'),
    ) ??
    declared.find(group => group.length > 0) ??
    []
  );
}

/**
 * Check every declared path in an incomplete export pair without making the
 * missing partner a publication error.
 * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} localTheme
 * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} packedIntegration
 * @param {Array<{kind: string, subpath: string, inspected: import('../../foundation/discovery/package-exports.mjs').PackageExportResult}>} declared
 * @param {string} source
 * @param {string} sourceRelative
 * @param {string} packageDir
 */
async function validateIncompleteThemeExports(
  localTheme,
  packedIntegration,
  declared,
  source,
  sourceRelative,
  packageDir,
) {
  /** @type {Issue[]} */
  const issues = [
    warning(
      'theme_exports_incomplete',
      `Theme "${localTheme.slug}" exports ${declared.map(output => output.inspected.specifier).join(', ')} without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.`,
    ),
  ];
  const packedPkg = integrationPackageMetadata(packedIntegration);
  const outputs = declared.map(output => ({
    ...output,
    packed: inspectPackageExport(
      packedPkg,
      packedIntegration.__packageDir,
      output.subpath,
    ),
  }));
  for (const output of outputs) {
    if (
      !output.inspected.target ||
      !output.packed.exported ||
      !output.packed.target
    ) {
      issues.push(
        error(
          'theme_import_unresolvable',
          `Theme "${localTheme.slug}" declares ${output.inspected.specifier}, but that ${output.kind} does not resolve from both the source package and packed tarball.`,
        ),
      );
    }
  }
  if (issues.some(issue => issue.severity === 'error')) return issues;

  const expectedDir = fs.mkdtempSync(
    path.join(os.tmpdir(), `astryx-theme-${localTheme.slug}-`),
  );
  const expectedCss = path.join(expectedDir, `${localTheme.slug}.css`);
  let expectedModule = path.join(expectedDir, `${localTheme.slug}.js`);
  try {
    if (outputs.some(output => output.kind !== 'font stylesheet')) {
      // The scratch directory is the write root; the package stays the cwd,
      // so the build selects the package's Core and its paths as before.
      const scratchBuild = {out: expectedCss, __writeRoot: expectedDir};
      const receipt = await themeBuild(source, scratchBuild, {cwd: packageDir});
      if (receipt == null || receipt.type !== 'theme.build') {
        throw new Error('the theme build produced no complete receipt');
      }
      expectedModule = builtModuleFile(
        receipt,
        packageDir,
        expectedDir,
        localTheme.slug,
      );
    }
    for (const output of outputs) {
      const localFile = /** @type {string} */ (output.inspected.target);
      const packedFile = /** @type {string} */ (output.packed.target);
      if (output.kind === 'font stylesheet') {
        if (!fs.readFileSync(localFile).equals(fs.readFileSync(packedFile))) {
          issues.push(
            error(
              'packed_theme_font_stylesheet_changed',
              `Theme "${localTheme.slug}" font stylesheet changed during packing. Keep its export and bytes unchanged in the tarball.`,
            ),
          );
        }
        continue;
      }
      const expectedFile =
        output.kind === 'module' ? expectedModule : expectedCss;
      const expected = normalizeThemeVerifyForCompare(
        fs.readFileSync(expectedFile, 'utf-8'),
      );
      const local = normalizeThemeVerifyForCompare(
        fs.readFileSync(localFile, 'utf-8'),
      );
      const packed = normalizeThemeVerifyForCompare(
        fs.readFileSync(packedFile, 'utf-8'),
      );
      if (expected !== local) {
        issues.push(
          warning(
            output.kind === 'module'
              ? 'theme_module_stale'
              : 'theme_stylesheet_stale',
            `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. This incomplete export remains packable, but run \`${formatCliCommand(`theme build ${sourceRelative}`, packageDir)}\` before adding its matching export.`,
          ),
        );
      }
      if (local !== packed) {
        issues.push(
          error(
            output.kind === 'module'
              ? 'packed_theme_module_changed'
              : 'packed_theme_stylesheet_changed',
            `Theme "${localTheme.slug}" ${output.kind} changed during packing. Keep the built output unchanged in the tarball.`,
          ),
        );
      }
    }
  } catch (err) {
    issues.push(
      error(
        'theme_build_failed',
        `Theme "${localTheme.slug}" could not be rebuilt from ${sourceRelative}: ${err instanceof Error ? err.message : String(err)} Run \`${formatCliCommand(`theme build ${sourceRelative}`, packageDir)}\` before packing.`,
      ),
    );
  } finally {
    fs.rmSync(expectedDir, {recursive: true, force: true});
  }
  return issues;
}

/**
 * The module a scratch `theme build` wrote. Its file is named by the theme's
 * own name, which can differ from the slug the package exports it under. A
 * receipt that names no file inside the scratch directory falls back to the
 * slug.
 * @param {any} receipt
 * @param {string} cwd the directory the build ran in
 * @param {string} expectedDir
 * @param {string} slug
 * @returns {string}
 */
function builtModuleFile(receipt, cwd, expectedDir, slug) {
  const written = receipt?.data?.outputs?.js;
  if (typeof written === 'string') {
    const file = path.resolve(cwd, written);
    const relative = path.relative(expectedDir, file);
    if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) {
      return file;
    }
  }
  return path.join(expectedDir, `${slug}.js`);
}

/**
 * The `.js` file a relative module specifier names from `fromFile`, the
 * extension `theme build` gives the built module: the exact path, the path
 * with `.js`, or its `index.js`.
 * @param {string} specifier
 * @param {string} fromFile
 * @returns {string | null}
 */
function resolveRelativeJsModule(specifier, fromFile) {
  if (!specifier.startsWith('./') && !specifier.startsWith('../')) return null;
  const base = path.resolve(path.dirname(fromFile), specifier);
  const candidates = [base, `${base}.js`, path.join(base, 'index.js')];
  return (
    candidates.find(candidate => {
      try {
        return candidate.endsWith('.js') && fs.statSync(candidate).isFile();
      } catch {
        return false;
      }
    }) ?? null
  );
}

/** @param {string} file */
function realFile(file) {
  try {
    return fs.realpathSync(file);
  } catch {
    return null;
  }
}

/**
 * The file a stylesheet import names: a relative path from the module, or a
 * subpath of the package itself, resolved through its own exports.
 * @param {string} specifier
 * @param {string} moduleFile
 * @param {{name?: string}} pkg
 * @param {string} packageDir
 * @returns {string | null}
 */
function resolveStylesheetImport(specifier, moduleFile, pkg, packageDir) {
  if (specifier.startsWith('./') || specifier.startsWith('../')) {
    const file = path.resolve(path.dirname(moduleFile), specifier);
    try {
      return fs.statSync(file).isFile() ? realFile(file) : null;
    } catch {
      return null;
    }
  }
  if (typeof pkg.name !== 'string' || !specifier.startsWith(`${pkg.name}/`)) {
    return null;
  }
  const exported = inspectPackageExport(
    pkg,
    packageDir,
    `.${specifier.slice(pkg.name.length)}`,
  );
  return exported.exported && exported.target
    ? realFile(exported.target)
    : null;
}

/**
 * The theme binding of a built module: the name of its `export const`.
 * @param {string} file
 * @returns {string | null}
 */
function builtThemeBinding(file) {
  try {
    const ast = parseModule(fs.readFileSync(file, 'utf-8'), {
      sourceType: 'module',
      plugins: ['importAttributes'],
    });
    for (const node of ast.program.body) {
      if (
        node.type === 'ExportNamedDeclaration' &&
        node.declaration?.type === 'VariableDeclaration'
      ) {
        const id = node.declaration.declarations[0]?.id;
        return id?.type === 'Identifier' ? id.name : null;
      }
    }
  } catch {
    // An unreadable module has no binding to match.
  }
  return null;
}

/** @param {any} node */
function exportedName(node) {
  return node?.name ?? node?.value;
}

/**
 * Check a `.js` or `.mjs` theme module that is not the built module itself.
 * It is accepted when it only loads the theme's own styles and re-exports the
 * built module: each statement imports the theme's exported stylesheet or font
 * stylesheet for its side effects, except one, which re-exports from a `.js`
 * file that matches the built module either everything or only its theme,
 * under the theme's export name. Returns null for any other file and for a module that
 * re-exports nothing, and otherwise whether it is accepted. A
 * rejection gives the reason, or, when only the re-exported module is stale,
 * that module's specifier with `rebuild` set.
 *
 * @param {string} moduleFile
 * @param {string} expected the built module, normalized for comparison
 * @param {{exportName: string, stylesheetFile: string, fontStylesheetFile?: string, pkg: {name?: string}, packageDir: string}} theme
 * @returns {{ok: true} | {ok: false, reason: string, rebuild: boolean} | null}
 */
function ownStylesEntry(moduleFile, expected, theme) {
  if (!/\.m?js$/u.test(moduleFile)) return null;
  let ast;
  try {
    ast = parseModule(fs.readFileSync(moduleFile, 'utf-8'), {
      sourceType: 'module',
      plugins: ['importAttributes'],
    });
  } catch {
    return null;
  }
  const body = ast.program.body;
  const reexports = body.filter(
    (/** @type {any} */ node) =>
      node.type === 'ExportAllDeclaration' ||
      (node.type === 'ExportNamedDeclaration' && node.source != null),
  );
  if (reexports.length === 0) return null;
  /** @param {string} reason @param {boolean} [rebuild] */
  const reject = (reason, rebuild = false) => ({
    ok: /** @type {const} */ (false),
    reason,
    rebuild,
  });
  if (reexports.length > 1) return reject('it has more than one re-export');
  if ((ast.program.directives ?? []).length > 0) {
    return reject('it has a directive');
  }
  const ownStylesheets = new Set(
    [theme.stylesheetFile, theme.fontStylesheetFile]
      .filter(file => file != null)
      .map(file => realFile(/** @type {string} */ (file))),
  );
  const imported = new Set();
  for (const node of body) {
    if (node === reexports[0]) continue;
    const line = node.loc?.start.line;
    if (node.type !== 'ImportDeclaration') {
      return reject(
        `line ${line} is neither a stylesheet import nor the re-export`,
      );
    }
    const specifier = node.source.value;
    if (
      node.importKind === 'type' ||
      node.specifiers.length > 0 ||
      (node.attributes ?? []).length > 0 ||
      node.phase != null
    ) {
      return reject(`its import of ${specifier} is not a side-effect import`);
    }
    const file = resolveStylesheetImport(
      specifier,
      moduleFile,
      theme.pkg,
      theme.packageDir,
    );
    if (!file || !ownStylesheets.has(file)) {
      return reject(
        `${specifier} is not the theme's own stylesheet or font stylesheet`,
      );
    }
    if (imported.has(file)) return reject(`it imports ${specifier} twice`);
    imported.add(file);
  }
  const reexport = /** @type {any} */ (reexports[0]);
  const from = reexport.source.value;
  /** @type {string | null} */
  let reexported = null;
  if (
    reexport.exportKind === 'type' ||
    (reexport.attributes ?? []).length > 0
  ) {
    return reject(`its re-export from ${from} is not a plain re-export`);
  }
  if (reexport.type === 'ExportAllDeclaration') {
    if (reexport.exported != null) {
      return reject(`it re-exports ${from} as a namespace`);
    }
  } else {
    const specifiers = reexport.specifiers ?? [];
    if (
      specifiers.length !== 1 ||
      specifiers[0].type !== 'ExportSpecifier' ||
      specifiers[0].exportKind === 'type' ||
      exportedName(specifiers[0].exported) !== theme.exportName
    ) {
      return reject(`it re-exports names other than ${theme.exportName}`);
    }
    reexported = exportedName(specifiers[0].local);
  }
  const target = resolveRelativeJsModule(from, moduleFile);
  if (!target) {
    return reject(`its re-export from ${from} does not name a .js module`);
  }
  if (
    normalizeThemeVerifyForCompare(fs.readFileSync(target, 'utf-8')) !==
    expected
  ) {
    return reject(from, true);
  }
  // `theme build` names the theme's export after the theme's own name, which
  // can differ from its slug, so a named re-export may give that export the
  // slug's export name. It must be the theme, not another export of the built
  // module, such as its icon registry.
  if (reexported != null && reexported !== builtThemeBinding(target)) {
    return reject(`it re-exports ${reexported}, which is not the built theme`);
  }
  return {ok: /** @type {const} */ (true)};
}

/**
 * Prove local theme exports are fresh, prove the same exports resolve from the
 * tarball, and reject lifecycle changes to source or built output bytes.
 *
 * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} localIntegration
 * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} packedIntegration
 * @param {string} scratchBase
 * @returns {Promise<Issue[]>}
 */
async function validatePackedThemeExports(
  localIntegration,
  packedIntegration,
  scratchBase,
) {
  /** @type {Issue[]} */
  const issues = [];
  let localThemes;
  let packedThemes;
  try {
    localThemes = await discoverIntegrationThemes(localIntegration);
  } catch (err) {
    issues.push(
      error(
        'theme_discovery_failed',
        `Local themes could not be validated: ${err instanceof Error ? err.message : String(err)}`,
      ),
    );
    return issues;
  }
  try {
    packedThemes = await discoverIntegrationThemes(packedIntegration);
  } catch (err) {
    issues.push(
      error(
        'packed_theme_discovery_failed',
        `Packed themes could not be validated: ${err instanceof Error ? err.message : String(err)}`,
      ),
    );
    return issues;
  }
  const packedBySlug = new Map(packedThemes.map(theme => [theme.slug, theme]));
  for (const localTheme of localThemes) {
    const packedTheme = packedBySlug.get(localTheme.slug);
    if (!packedTheme) continue;
    const source = path.join(localTheme.sourceDir, localTheme.entry);
    const packedSource = path.join(packedTheme.sourceDir, packedTheme.entry);
    const sourceRelative = path.relative(localIntegration.__packageDir, source);

    if (!fs.readFileSync(source).equals(fs.readFileSync(packedSource))) {
      issues.push(
        error(
          'packed_theme_source_changed',
          `Theme "${localTheme.slug}" source changed during packing. Keep ${sourceRelative} unchanged in the tarball.`,
        ),
      );
    }

    // The name the source gives defineTheme, when the file says it: the
    // build names its files after it.
    const builtName = literalThemeName(source, localTheme.exportName);

    const declaredOutputs = declaredThemeBuildOutputs(
      localIntegration,
      localTheme,
      localThemes.length,
    );
    if (declaredOutputs.length === 0) {
      issues.push(
        warning(
          'theme_exports_missing',
          `Theme "${localTheme.slug}" has no declared built exports. The package remains source-compatible. To make it importable, run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` and export "./themes/${localTheme.slug}" plus "./themes/${localTheme.slug}.css" from package.json; \`${formatCliCommand(`integration add theme ${localTheme.slug}`, localIntegration.__packageDir)}\` creates those exports for a new theme.`,
        ),
      );
      continue;
    }
    if (
      !declaredOutputs.some(output => output.kind === 'module') ||
      !declaredOutputs.some(output => output.kind === 'stylesheet')
    ) {
      issues.push(
        ...(await validateIncompleteThemeExports(
          localTheme,
          packedIntegration,
          declaredOutputs,
          source,
          sourceRelative,
          localIntegration.__packageDir,
        )),
      );
      continue;
    }

    let localImports;
    let packedImports;
    try {
      localImports = resolveThemeImports(localTheme, {
        cwd: localIntegration.__packageDir,
        ownerThemeCount: localThemes.length,
      });
      packedImports = resolveThemeImports(packedTheme, {
        cwd: scratchBase,
        ownerThemeCount: packedThemes.length,
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      issues.push(
        error(
          err instanceof ThemeImportError
            ? 'theme_import_unresolvable'
            : 'theme_import_invalid',
          `${message} Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`,
        ),
      );
      continue;
    }

    const expectedDir = fs.mkdtempSync(
      path.join(os.tmpdir(), `astryx-theme-${localTheme.slug}-`),
    );
    const expectedCss = path.join(expectedDir, `${localTheme.slug}.css`);
    try {
      // The scratch directory is the write root; the package stays the cwd,
      // so the build selects the package's Core and its paths as before.
      const scratchBuild = {out: expectedCss, __writeRoot: expectedDir};
      const receipt = await themeBuild(source, scratchBuild, {
        cwd: localIntegration.__packageDir,
      });
      if (receipt == null || receipt.type !== 'theme.build') {
        issues.push(
          error(
            'theme_build_failed',
            `Theme "${localTheme.slug}" did not produce a complete build. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`,
          ),
        );
        continue;
      }
      const expectedModule = builtModuleFile(
        receipt,
        localIntegration.__packageDir,
        expectedDir,
        localTheme.slug,
      );
      /** @type {Array<{kind: string, expected: string, local: string, packed: string, staleCode: string, packedCode: string}>} */
      const buildOutputs = [
        {
          kind: 'module',
          expected: expectedModule,
          local: localImports.moduleFile,
          packed: packedImports.moduleFile,
          staleCode: 'theme_module_stale',
          packedCode: 'packed_theme_module_changed',
        },
        {
          kind: 'stylesheet',
          expected: expectedCss,
          local: localImports.stylesheetFile,
          packed: packedImports.stylesheetFile,
          staleCode: 'theme_stylesheet_stale',
          packedCode: 'packed_theme_stylesheet_changed',
        },
      ];
      const localEntry = {
        exportName: localTheme.exportName,
        stylesheetFile: localImports.stylesheetFile,
        fontStylesheetFile: localImports.fontStylesheetFile,
        pkg: integrationPackageMetadata(localIntegration),
        packageDir: localIntegration.__packageDir,
      };
      const packedEntry = {
        exportName: packedTheme.exportName,
        stylesheetFile: packedImports.stylesheetFile,
        fontStylesheetFile: packedImports.fontStylesheetFile,
        pkg: integrationPackageMetadata(packedIntegration),
        packageDir: packedIntegration.__packageDir,
      };
      for (const output of buildOutputs) {
        const expected = normalizeThemeVerifyForCompare(
          fs.readFileSync(output.expected, 'utf-8'),
        );
        const local = normalizeThemeVerifyForCompare(
          fs.readFileSync(output.local, 'utf-8'),
        );
        const packed = normalizeThemeVerifyForCompare(
          fs.readFileSync(output.packed, 'utf-8'),
        );
        // A module that is not the built module may still be an entry that
        // loads the theme's own styles and re-exports the built module.
        const localWrapper =
          output.kind === 'module' && expected !== local
            ? ownStylesEntry(output.local, expected, localEntry)
            : null;
        const packedWrapper =
          output.kind === 'module' && expected !== packed
            ? ownStylesEntry(output.packed, expected, packedEntry)
            : null;
        const localMatches = expected === local || localWrapper?.ok === true;
        const packedMatches = expected === packed || packedWrapper?.ok === true;
        if (!localMatches) {
          issues.push(
            error(
              output.staleCode,
              localWrapper && !localWrapper.ok && !localWrapper.rebuild
                ? `Theme "${localTheme.slug}" module is not the module \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` writes and does not only wrap it: ${localWrapper.reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as ${localTheme.exportName}.`
                : localWrapper && !localWrapper.ok
                  ? `Theme "${localTheme.slug}" module re-exports ${localWrapper.reason}, which does not match ${sourceRelative}. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`
                  : (renamedOutputMessage(
                      localTheme,
                      output.kind,
                      output.local,
                      source,
                      builtName,
                      localIntegration.__packageDir,
                    ) ??
                    `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`),
            ),
          );
        }
        if (local !== packed || (localMatches && !packedMatches)) {
          issues.push(
            error(
              output.packedCode,
              `Theme "${localTheme.slug}" ${output.kind} changed during packing. Keep the built output unchanged in the tarball.`,
            ),
          );
        }
      }
      if (
        localImports.fontStylesheet !== packedImports.fontStylesheet ||
        (localImports.fontStylesheetFile &&
          packedImports.fontStylesheetFile &&
          !fs
            .readFileSync(localImports.fontStylesheetFile)
            .equals(fs.readFileSync(packedImports.fontStylesheetFile)))
      ) {
        issues.push(
          error(
            'packed_theme_font_stylesheet_changed',
            `Theme "${localTheme.slug}" font stylesheet changed during packing. Keep its export and bytes unchanged in the tarball.`,
          ),
        );
      }
    } catch (err) {
      issues.push(
        error(
          'theme_build_failed',
          `Theme "${localTheme.slug}" could not be rebuilt from ${sourceRelative}: ${err instanceof Error ? err.message : String(err)} Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`,
        ),
      );
    } finally {
      fs.rmSync(expectedDir, {recursive: true, force: true});
    }
  }
  return issues;
}

/**
 * Verify that every packed template source can be imported through its exact
 * package subpath and still has a default export.
 *
 * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} integration
 * @param {string} scratchBase
 * @returns {Promise<Issue[]>}
 */
async function validatePackedTemplateExports(integration, scratchBase) {
  const {templates} = await discoverIntegrationTemplatesForOne(integration);
  const entries = templates.map(template => {
    const relPath = path
      .relative(integration.__packageDir, template.filePath)
      .split(path.sep)
      .join('/');
    const extensionless = relPath.replace(/\.tsx?$/u, '');
    return {
      id: template.dirName,
      specifier: `${integration.name}/${extensionless}`,
    };
  });
  const resolved = resolveConsumerSpecifiers(
    entries.map(entry => entry.specifier),
    scratchBase,
  );
  const issues = validateSpecifierExtensions(
    entries.map(({id, specifier}) => ({
      label: `Template "${id}"`,
      specifier,
    })),
  );
  for (const {id, specifier} of entries) {
    const result = resolved.get(specifier);
    if (!result?.url || result.error) {
      issues.push(
        error(
          'template_import_unresolvable',
          `Template "${id}" source is packed but its public import "${specifier}" cannot be resolved${result?.error ? `: ${result.error}` : '.'}`,
        ),
      );
      continue;
    }
    let target;
    try {
      target = fileURLToPath(result.url);
    } catch {
      target = null;
    }
    if (!target || !moduleExportsName(target, 'default')) {
      issues.push(
        error(
          'template_export_missing',
          `Template "${id}" public import "${specifier}" does not have a default export.`,
        ),
      );
    }
  }
  return issues;
}

const TS_EXTENSION_RE = /\.tsx?$/u;

/**
 * Reject specifiers that end in a TypeScript extension — they fail under
 * default `moduleResolution` with TS5097/TS2307 unless the consumer enables
 * `allowImportingTsExtensions`.
 *
 * @param {Array<{label: string, specifier: string}>} entries
 * @returns {Issue[]}
 */
function validateSpecifierExtensions(entries) {
  /** @type {Issue[]} */
  const issues = [];
  for (const {label, specifier} of entries) {
    if (TS_EXTENSION_RE.test(specifier)) {
      issues.push(
        error(
          'typescript_extension_in_specifier',
          `${label} advertises import "${specifier}", which ends in a TypeScript extension. A consumer with default moduleResolution will reject it (TS5097). Use an extensionless specifier mapped through the package exports.`,
        ),
      );
    }
  }
  return issues;
}

/**
 * Verify an integration package is ready to publish.
 *
 * Validates the local structure, cross-references every declared contribution
 * file against the real `npm pack` file list, extracts the tarball into a
 * scratch consumer, and compares local vs packed discovery results exactly.
 *
 * @param {import('./pack-check.type.mjs').IntegrationPackCheckOptions} [options]
 * @returns {Promise<import('./pack-check.type.mjs').IntegrationPackCheckResponse>}
 */
export async function integrationPackCheck(options = {}) {
  const {cwd = process.cwd()} = options;

  // ── Locate the package ──
  let found;
  try {
    found = findPackage(cwd);
  } catch (err) {
    return emptyReceipt(null, [
      error(
        'invalid_package_json',
        err instanceof Error ? err.message : String(err),
      ),
    ]);
  }
  if (!found) {
    return emptyReceipt(null, [
      error(
        'no_package',
        'No package.json found. Run this command inside an integration package.',
      ),
    ]);
  }
  const {packageDir, pkg} = found;
  const pkgName = typeof pkg.name === 'string' ? pkg.name : '(unnamed package)';
  const pkgVersion = typeof pkg.version === 'string' ? pkg.version : null;

  // ── Phase 1: structure validation ──
  const localResult = await validateLocalIntegration(cwd);
  /** @type {Issue[]} */
  const issues = [
    ...localResult.issues,
    // Validate lists these layout findings without counting them. A
    // package.json npm cannot pack is what fails the pack here, as it did
    // before they were named; the rest stay warnings, which fail nothing.
    ...(localResult.found ? (localResult.listed ?? []) : []).map(issue =>
      issue.code === 'invalid_package_json'
        ? {...issue, severity: /** @type {const} */ ('error')}
        : issue,
    ),
  ];

  if (!localResult.found || !localResult.integration) {
    return emptyReceipt(pkgName, [
      ...issues,
      ...(localResult.found
        ? []
        : [
            error(
              'missing_manifest',
              'No astryx.integration.{ts,mjs,js} found next to package.json.',
            ),
          ]),
    ]);
  }

  const loaded = localResult.integration;

  // ── Phase 2: file inventory + npm pack ──
  const fileInv = computeRequiredFiles(loaded);
  const {identities: localIdentities, errors: localDiscoveryErrors} =
    await collectIdentities(loaded);
  // A family lists its members from the module its import names, which the
  // pack lifecycle may build or rebuild, so they are compared as local
  // discovery lists them after the pack.
  const familiesBefore = familyImports(loaded).map(family => family.docPath);
  /**
   * @param {Array<{name: string, docPath: string|null}>} records
   * @param {Set<string>} families
   */
  const membersOf = (records, families) =>
    records
      .filter(
        r =>
          r.docPath != null &&
          families.has(r.docPath) &&
          isIntegrationMember(r),
      )
      .map(r => r.name);
  const recordsBefore = discoverIntegrationComponents(loaded);
  for (const discoveryError of localDiscoveryErrors) {
    issues.push(
      error(
        'local_discovery_failed',
        `${discoveryError.kind}: ${discoveryError.message}`,
      ),
    );
  }
  for (const root of fileInv.roots) {
    // A root that is not a readable folder has its own issue.
    if (rootProblem(/** @type {string} */ (loaded[root.kind]))) continue;
    if (root.files.length === 0) {
      issues.push(
        error(
          'empty_contribution_root',
          `Declared ${root.kind} root "${root.path}" contains no discoverable contribution files.`,
        ),
      );
    }
  }
  // A namespace doc or a placed guide needs a CLI that reads the docs tree
  // (spec:AST-046 FR11): an older CLI can hide every doc topic the package
  // ships, so the declared CLI range must admit only CLIs that read it.
  if (loaded.docs) {
    const {records, namespaces, guides} = await discoverIntegrationDocs(
      loaded,
    ).catch(() => ({records: [], namespaces: [], guides: []}));
    const problem =
      namespaces.length > 0 || guides.length > 0
        ? docsTreeCliProblem(pkg)
        : null;
    if (problem != null) {
      issues.push(error('docs_tree_needs_cli', problem));
    } else if (
      await setsSectionIds([
        ...records.map(record => record.path),
        ...guides.map(guide => /** @type {any} */ (guide.ref).topicFile),
      ])
    ) {
      // A section `id` is also a field an older CLI rejects, hiding the
      // package's doc topics. It needs an older CLI than the docs tree does.
      const idProblem = sectionIdsCliProblem(pkg);
      if (idProblem != null) {
        issues.push(error('section_ids_need_cli', idProblem));
      }
    }
    // `before` and `after` need a newer CLI than any field above. Added in a
    // patch release, it warns and never fails the check (INV35).
    if (
      await setsSectionField(
        [
          ...records.map(record => record.path),
          ...guides.map(guide => /** @type {any} */ (guide.ref).topicFile),
        ],
        ['before', 'after'],
      )
    ) {
      const positionProblem = sectionPositionCliProblem(pkg);
      if (positionProblem != null) {
        issues.push(warning('section_position_needs_cli', positionProblem));
      }
    }
    // A doc token shows as written on a CLI before the one that renders
    // them. Added in a patch release, it warns and never fails (INV35).
    if (
      problem == null &&
      writesDocTokens([
        ...records.map(record => record.path),
        ...guides.map(guide => /** @type {any} */ (guide.ref).topicFile),
      ])
    ) {
      const tokenProblem = docTokensCliProblem(pkg);
      if (tokenProblem != null) {
        issues.push(warning('doc_tokens_need_cli', tokenProblem));
      }
    }
  }
  // A template that sets `replaces` (spec:AST-035) or `keywords` needs a CLI
  // that reads the field: an older CLI drops that template and can hide the
  // package's docs. Each field has its own floor.
  if (loaded.templates) {
    const found = await discoverIntegrationTemplatesForOne(loaded).catch(
      () => ({templates: [], errors: []}),
    );
    const setsReplaces =
      found.templates.some(template => template.replaces != null) ||
      found.errors.some(
        (/** @type {any} */ issue) => issue.replacementTarget != null,
      );
    const problem = setsReplaces ? replacesCliProblem(pkg) : null;
    if (problem != null) issues.push(error('replaces_needs_cli', problem));
    const setsKeywords = found.templates.some(
      template => template.keywords != null && template.keywords.length > 0,
    );
    const keywordsProblem = setsKeywords ? keywordsCliProblem(pkg) : null;
    if (keywordsProblem != null) {
      issues.push(error('keywords_needs_cli', keywordsProblem));
    }
  }
  // A component that sets `replaces` (spec:AST-035 FR10) is applied only when
  // the package's CLI range starts at the release that applies it. Without
  // that range the component keeps its own name and Core stays selected, so
  // this warns and never fails the check.
  if (loaded.components) {
    const found = await loadComponentReplacements(null, [loaded]).catch(() => ({
      findings: [],
    }));
    // Every declaration from a package without the range is reported as
    // inactive, whatever else is wrong with it.
    const setsReplaces = found.findings.some(
      finding => finding.code === 'inactive_component_replacement',
    );
    const problem = setsReplaces ? componentReplacesCliProblem(pkg) : null;
    if (problem != null) {
      issues.push(warning('component_replaces_needs_cli', problem));
    }
  }
  // A theme needs a CLI that reads typed theme descriptors: an older CLI
  // rejects the themes root and withholds the package's themes and docs.
  if (localIdentities.themes.length > 0) {
    const problem = themesCliProblem(pkg);
    if (problem != null) issues.push(error('themes_need_cli', problem));
  }

  // Temp resources — always cleaned up
  const tgzTmpDir = fs.mkdtempSync(
    path.join(os.tmpdir(), 'astryx-pack-check-'),
  );
  /** @type {string|null} */
  let scratchBase = null;
  /** @type {string|undefined} the packed copy of the package */
  let extractDir;
  const issuesBeforePack = issues.length;

  try {
    // npm pack
    /** @type {ReturnType<typeof runNpmPack>} */
    let packResult;
    try {
      packResult = runNpmPack(packageDir, tgzTmpDir);
    } catch (err) {
      issues.push(error('pack_failed', /** @type {Error} */ (err).message));
      return buildReceipt(
        pkgName,
        pkgVersion,
        fileInv,
        null,
        localIdentities,
        null,
        issues,
      );
    }

    // Create the repo-local consumer AFTER packing, so it cannot enter the
    // tarball. Keeping it beside the package lets packed metadata resolve the
    // package's already-installed dependencies. The unique suffix makes
    // concurrent checks independent.
    scratchBase = fs.mkdtempSync(path.join(packageDir, '.astryx-pack-check-'));
    // The consumer's own package.json makes it the package scope for its
    // imports. Without one, Node resolves the package's name through the
    // SOURCE package.json (self-reference), so an export target left out of
    // the tarball would still resolve.
    fs.writeFileSync(
      path.join(scratchBase, 'package.json'),
      `${JSON.stringify({name: 'astryx-verify-consumer', private: true})}\n`,
    );

    // Cross-reference file inventory vs pack list
    if (!packResult.packedPaths.has(fileInv.manifest)) {
      issues.push(
        error(
          'manifest_not_packed',
          `Integration manifest "${fileInv.manifest}" is not in the npm pack list. ` +
            'Add it to "files" in package.json.',
        ),
      );
    }

    for (const root of fileInv.roots) {
      const missing = root.files.filter(f => !packResult.packedPaths.has(f));
      if (missing.length === root.files.length && root.files.length > 0) {
        const absolute = /** @type {string} */ (loaded[root.kind]);
        const link = symlinkedFolder(absolute, packageDir);
        issues.push(
          error(
            'root_not_packed',
            `Declared ${root.kind} root "${root.path}" has 0 of ${root.files.length} expected ` +
              `files in the pack list. ` +
              (link
                ? `It is reached through the symlink "${path.relative(packageDir, link.path).split(path.sep).join('/')}", and npm pack does not follow a symlinked folder. Fix: replace the link with the folder itself, or point "${root.kind}" at the folder it links to.`
                : `Add "${root.path.replace(/^\.\//, '')}" to "files" in package.json.`),
          ),
        );
      } else {
        for (const file of missing) {
          issues.push(
            error(
              'file_not_packed',
              `${root.kind} file "${file}" is not in the pack list.`,
            ),
          );
        }
      }
    }

    let tgzPath;
    try {
      tgzPath = assertWithin(packResult.filename, tgzTmpDir, {
        label: 'npm pack filename',
      });
    } catch (err) {
      issues.push(
        error(
          'invalid_pack_result',
          err instanceof Error ? err.message : String(err),
        ),
      );
      return buildReceipt(
        pkgName,
        pkgVersion,
        fileInv,
        packResult,
        localIdentities,
        null,
        issues,
      );
    }

    // ── Phase 3: extract + identity comparison ──
    try {
      extractDir = resolvePackageDir(pkgName, scratchBase);
    } catch (err) {
      issues.push(
        error(
          'invalid_package_name',
          err instanceof Error ? err.message : String(err),
        ),
      );
      return buildReceipt(
        pkgName,
        pkgVersion,
        fileInv,
        packResult,
        localIdentities,
        null,
        issues,
      );
    }
    try {
      extractTarball(tgzPath, extractDir);
    } catch (err) {
      issues.push(error('extract_failed', /** @type {Error} */ (err).message));
      return buildReceipt(
        pkgName,
        pkgVersion,
        fileInv,
        packResult,
        localIdentities,
        null,
        issues,
      );
    }

    // Validate the extracted tree as an installed integration
    // The packed tree is the package being authored: its icon sets are
    // checked whatever the scratch folder's config says.
    const packedResult = await validateInstalledIntegration(
      pkgName,
      scratchBase,
      {iconSets: true},
    );

    for (const issue of packedResult.issues) {
      issues.push({
        code: `packed_${issue.code}`,
        severity: issue.severity,
        message: `Packed: ${issue.message}`,
        // The packed tree keeps the package's own paths.
        ...(issue.fix != null ? {fix: issue.fix} : {}),
        ...(issue.file != null ? {file: issue.file} : {}),
        ...(issue.line != null ? {line: issue.line} : {}),
      });
    }

    if (!packedResult.integration) {
      return buildReceipt(
        pkgName,
        pkgVersion,
        fileInv,
        packResult,
        localIdentities,
        null,
        issues,
      );
    }

    // Collect packed identities and compare
    const {identities: packedIdentities, errors: discoveryErrors} =
      await collectIdentities(packedResult.integration);

    for (const de of discoveryErrors) {
      issues.push(
        error('packed_discovery_failed', `${de.kind}: ${de.message}`),
      );
    }

    const families = new Set([
      ...familiesBefore,
      ...familyImports(loaded).map(family => family.docPath),
    ]);
    let localComponents = localIdentities.components;
    if (families.size > 0) {
      const stale = new Set(membersOf(recordsBefore, families));
      const built = new Set(
        membersOf(discoverIntegrationComponents(loaded), families),
      );
      const {identities: afterPack} = await collectIdentities(loaded);
      localComponents = [
        ...new Set([
          ...localComponents.filter(name => !stale.has(name)),
          ...afterPack.components.filter(name => built.has(name)),
        ]),
      ].sort();
    }
    // The receipt reports the local inventory that was compared.
    const comparedLocal = {...localIdentities, components: localComponents};
    issues.push(...compareIdentities(comparedLocal, packedIdentities));
    issues.push(
      ...(await validatePackedThemeExports(
        loaded,
        packedResult.integration,
        scratchBase,
      )),
      ...(await validatePackedComponentExports(
        packedResult.integration,
        scratchBase,
      )),
      ...(await validatePackedTemplateExports(
        packedResult.integration,
        scratchBase,
      )),
    );

    return buildReceipt(
      pkgName,
      pkgVersion,
      fileInv,
      packResult,
      comparedLocal,
      packedIdentities,
      issues,
    );
  } finally {
    // The packed copy lives in a scratch folder that is gone once this
    // returns: name its files the way the package does.
    if (extractDir && scratchBase) {
      packageRelative(issues.slice(issuesBeforePack), extractDir, scratchBase);
    }
    removeTreeBestEffort(tgzTmpDir, 'temporary tarball directory', issues);
    removeTreeBestEffort(scratchBase, 'scratch consumer', issues);
  }
}

/**
 * When a theme's source names it something other than the file the package
 * exports for it, a rebuild writes new files under that name and leaves the
 * exported one stale forever: say so, with both ways out. Null otherwise.
 * @param {{slug: string}} theme
 * @param {string} kind 'module' or 'stylesheet'
 * @param {string} exported the file the package exports for it
 * @param {string} source the theme's source
 * @param {string | null} builtName the literal defineTheme name, if any
 * @param {string} packageDir
 * @returns {string | null}
 */
function renamedOutputMessage(
  theme,
  kind,
  exported,
  source,
  builtName,
  packageDir,
) {
  if (builtName == null || builtName === theme.slug) return null;
  const extension = kind === 'module' ? '.js' : '.css';
  if (path.basename(exported) === `${builtName}${extension}`) return null;
  const rel = (/** @type {string} */ file) =>
    path.relative(packageDir, file).split(path.sep).join('/');
  const built = rel(
    path.join(path.dirname(source), `${builtName}${extension}`),
  );
  return `Theme "${theme.slug}" ${kind} is ${rel(exported)}, but ${path.basename(source)} calls defineTheme with name: '${builtName}', so \`${formatCliCommand(`theme build ${rel(source)}`, packageDir)}\` writes ${built} instead and rebuilding never updates ${path.basename(exported)}. Fix: point the package export that serves it at ${built} after building, or set name: '${theme.slug}' in ${path.basename(source)} and rebuild.`;
}

/**
 * Rewrite the scratch copy's absolute paths in each issue's message: a file
 * of the packed package as its path in the package, and any other path in the
 * scratch consumer (such as the module that resolved an import) as that
 * consumer. Both folders are gone once verify returns.
 * @param {Issue[]} issues
 * @param {string} packedDir the packed package inside the scratch consumer
 * @param {string} consumerDir the scratch consumer
 */
function packageRelative(issues, packedDir, consumerDir) {
  /** @param {string} dir */
  const spellings = dir => {
    const out = [dir];
    try {
      const real = fs.realpathSync(dir);
      if (real !== dir) out.push(real);
    } catch {
      // Already removed: the plain path is all there is.
    }
    return out;
  };
  /** @param {string} text */
  const escape = text => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
  const packed = spellings(packedDir);
  const consumer = spellings(consumerDir);
  for (const issue of issues) {
    if (typeof issue.message !== 'string') continue;
    let message = issue.message;
    for (const prefix of packed) {
      message = message
        .split(`${prefix}${path.sep}`)
        .join('')
        .replace(
          new RegExp(`${escape(prefix)}(?![\\w-]|\\.\\w)`, 'gu'),
          'the package root',
        );
    }
    for (const prefix of consumer) {
      message = message.replace(
        new RegExp(`${escape(prefix)}[^\\s"'\`]*`, 'gu'),
        'a consumer project',
      );
    }
    issue.message = message;
  }
}

/**
 * Assemble the receipt.
 * @param {string} name
 * @param {string|null} version
 * @param {import('../../foundation/integrations/contribution-inventory.mjs').FileInventory} fileInv
 * @param {ReturnType<typeof runNpmPack>|null} packResult
 * @param {import('../../foundation/integrations/contribution-inventory.mjs').ContributionIdentities|null} localIdentities
 * @param {import('../../foundation/integrations/contribution-inventory.mjs').ContributionIdentities|null} packedIdentities
 * @param {Issue[]} issues
 * @returns {import('./pack-check.type.mjs').IntegrationPackCheckResponse}
 */
function buildReceipt(
  name,
  version,
  fileInv,
  packResult,
  localIdentities,
  packedIdentities,
  issues,
) {
  const packedPaths = packResult?.packedPaths ?? new Set();

  /** @type {import('./pack-check.type.mjs').PackCheckInventoryRoot[]} */
  const roots = fileInv.roots.map(root => {
    const missing = root.files.filter(f => !packedPaths.has(f));
    return {
      kind: root.kind,
      path: root.path,
      expectedFiles: root.files.length,
      missingFiles: missing,
      complete: missing.length === 0,
    };
  });

  const expectedFiles = fileInv.allFiles.length;
  const packedFiles = fileInv.allFiles.filter(f => packedPaths.has(f)).length;

  return {
    type: 'integration.pack-check',
    data: {
      name,
      version,
      packable: !issues.some(i => i.severity === 'error'),
      tarball: packResult
        ? {
            filename: packResult.filename,
            fileCount: packResult.fileCount,
            size: packResult.size,
            unpackedSize: packResult.unpackedSize,
          }
        : null,
      inventory: {
        manifest: fileInv.manifest,
        roots,
        expectedFiles,
        packedFiles,
      },
      contributions: {local: localIdentities, packed: packedIdentities},
      issues,
    },
  };
}