// the swift packages an app links, local and remote, compiled from source.
// each linked product resolves through swiftpm's own reading of its package
// (swift-package-manifest.ts) to the source targets that build it; remote
// packages are fetched at the revision the app's Package.resolved pins, into
// PEACH_HOME/cache/swift-packages, isolated by the app root. swift and c-family source
// targets, including objective-c, use the common compiler backend. assembly
// a target's own wasi-conditioned c settings support compiles with them as
// swiftpm builds it; other assembly and binary targets the host built no
// stand-in for stay missing with their reason; the targets beside them still
// compile.

import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
import { promisify } from 'node:util'
import { cacheDir } from './home-paths'
import { requireNativeGit } from './native-git'
import { tryAcquireNumberedLock } from './numbered-lock'
import { preparedSwiftCheckouts, preparedSwiftPin } from './prepared-xcode-phases'
import { swiftCTakesReturnAddress } from './swift-compile'
import {
  isSwiftNativeTranslationUnit,
  swiftImplicitResourcePaths,
  swiftPackageIdentity,
  type SwiftPackageTarget,
  type SwiftTargetDependency,
} from './swift-package'
import {
  prepareSwiftPackageManifest,
  SwiftManifestPreparationRequired,
  swiftPackageManifest,
  swiftProductDependency,
  swiftTargetFiles,
  type SwiftManifestSetting,
  type SwiftManifestTarget,
  type SwiftPackageManifest,
} from './swift-package-manifest'
import { shippedBinaryDiffers } from './swift-shipped-binaries'
import type { SwiftSourceLinkGraph } from './swiftContract'

// which machine a package target is built for
type BuildSide = 'guest' | 'host'

/** where a linked product comes from, as the project names it. */
export type SwiftPackageSource =
  | { kind: 'local'; dir: string }
  | { kind: 'remote'; url: string }
  /** a product xcode finds by name among the packages the workspace references. */
  | { kind: 'unnamed'; remoteUrls: string[] }

export interface SwiftLinkedProduct {
  /** attributes of the original frameworks-phase product edge. */
  attributes?: string[]
  product: string
  source: SwiftPackageSource
}

/** a source target that compiles, its directory and files absolute. */
export interface SwiftPackageSourceTarget extends SwiftPackageTarget {
  dir: string
  files: string[]
  /** the package directory, so a manifest edit reaches the compile. */
  packageDir: string
  remote: boolean
  /** the iOS version its package declares, which actool compiles the target's catalogs for. */
  iosDeployment: string | null
  /** the conditions its manifest defines, before a build configuration picks them. */
  packageDefines: SwiftManifestSetting[]
  packageLibraries: SwiftManifestSetting[]
  packageExperimentalFeatures: SwiftManifestSetting[]
  packageUpcomingFeatures: SwiftManifestSetting[]
  packageSwiftFlags: SwiftManifestTarget['swiftFlags']
  packageNativeSettings: SwiftManifestTarget['nativeSettings']
}

/** why a product or module does not compile, and where it comes from. */
export interface SwiftPackageGap {
  source: string
  reason: string
}

export interface SwiftPackages {
  sourceLinks: {
    targets: SwiftSourceLinkGraph['targets']
    owners: { module: string; products: { target: string; attributes: string[] }[] }[]
  }
  targets: SwiftPackageSourceTarget[]
  /** packages whose original graph builds both guest libraries and host macros. */
  nativePackages: {
    manifest: SwiftPackageManifest
    remote: boolean
    guestTargets: SwiftManifestTarget[]
  }[]
  nativeProducts: { name: string; packageDir: string; source: string }[]
  /** linked products peach cannot compile. */
  unavailable: Map<string, SwiftPackageGap>
  /** every module a reached package declares that does not compile. */
  modules: Map<string, SwiftPackageGap>
  /** binary targets of reached packages, whose archives name the modules
   *  they ship under other names than the target's (_FirebaseCore vends
   *  FirebaseCore). */
  binaries: SwiftPackageBinary[]
}

export interface SwiftPackageBinary {
  target: string
  source: string
  /** the archive url, or null for a local artifact at `dir`. */
  url: string | null
  /** the Package.swift SHA-256, required for a remote archive. */
  checksum: string | null
  dir: string
  /** a linked product's closure reaches it, so the app links it. */
  reached: boolean
  /** a source Objective-C target: public headers relative to dir. */
  publicHeaders?: string
  /** sources, relative to the package, with no wasm lowering that keep a
   *  source target from compiling; its public headers stand in for it. */
  unloweredSources?: string[]
  /** dependency module public headers, relative to dir. */
  headerDependencies?: { module: string; path: string }[]
  /** xcode modules whose linked package products reach this clang target. */
  clients?: string[]
  /** simulator library headers actually included by original C++ units. */
  cxxHeaders?: { roots: string[]; reached: string[]; flags: string[]; error?: string }
  /** a swift target of a placeholder package: the compiler gap that forces
   *  it, its sources relative to dir, and the swiftc flags its settings give
   *  them. it stands in from its own sources' public interface. */
  placeholder?: { gap: string; sources: string[]; flags: string[] }
}

export const swiftBinaryOnDisk = (binary: SwiftPackageBinary): boolean =>
  binary.url !== null || fs.existsSync(binary.dir)

// sdks that send telemetry, by package identity, that peach's swift cannot
// compile yet, each with the compiler gap that forces it. their swift targets
// stand in from their own public interface with inert bodies, so an app's
// calls compile and run and nothing is sent. an entry goes once the real sdk
// compiles.
export const SWIFT_PLACEHOLDER_PACKAGES: ReadonlyMap<string, string> = new Map<
  string,
  string
>()
const placeholderPackage = (pkg: LoadedPackage) =>
  SWIFT_PLACEHOLDER_PACKAGES.get(swiftPackageIdentity(pkg.manifest.dir))

/** dependency checkouts belong to peach, isolated by the canonical app root. */
export function remoteSwiftCheckouts(root: string): string {
  const prepared = preparedSwiftCheckouts(root)
  if (prepared) return prepared
  const key = createHash('sha256')
    .update(fs.realpathSync(root))
    .digest('hex')
    .slice(0, 32)
  fs.mkdirSync(cacheDir(), { recursive: true })
  return path.join(fs.realpathSync(cacheDir()), 'swift-packages', key, 'checkouts')
}

// assembly requires its own target lowering; objective-c keeps its original bodies.
const UNSUPPORTED_NATIVE = /\.(s|S)$/

// a clang source target whose sources include assembly, or take their own
// return address, cannot lower to wasm, unless upstream declares
// wasi-conditioned c settings for it: that is the package's own supported
// portable path (boringssl's guarded assembly with OPENSSL_NO_ASM), which
// compiles with those flags exactly as swiftpm builds it. assembly that
// preprocesses to nothing for wasm32 (guarded to the architectures it was
// written for) is the same portable path without the signal: swiftpm compiles
// it as plain c. otherwise the target keeps the refusal below. when a refused
// target also ships public headers, those headers stand in for it and every
// declaration they spell traps by name. this is the assembly rule above,
// widened only where the target has a header surface to stand in from.
function unlowerableSources(
  files: readonly string[],
  target: SwiftManifestTarget,
  portable: ReadonlySet<string>,
): string[] {
  if (target.declaresWasiNativeSettings) return []
  return [
    ...(portable.has(target.name)
      ? []
      : files.filter((file) => UNSUPPORTED_NATIVE.test(file))),
    ...files
      .filter(isSwiftNativeTranslationUnit)
      .filter((file) => swiftCTakesReturnAddress(fs.readFileSync(file, 'utf8'))),
  ]
}

function unloweredSources(
  files: readonly string[],
  target: SwiftManifestTarget,
  portable: ReadonlySet<string>,
): string[] | null {
  if (target.type !== 'regular') return null
  if (!files.some(isSwiftNativeTranslationUnit)) return null
  const unlowered = unlowerableSources(files, target, portable)
  if (unlowered.length === 0) return null
  const headers = path.resolve(target.dir, target.publicHeadersPath)
  if (
    !files.some((file) => file.startsWith(`${headers}${path.sep}`) && file.endsWith('.h'))
  )
    return null
  return unlowered
}

const BINARY = 'is a binary framework'
// retain every independent blocker in dependency order. a product can reach
// several unsupported targets, and fixing one must not reveal a hidden next one.
const blockers = (reasons: readonly string[][]): string[] => [...new Set(reasons.flat())]

export interface Pin {
  location: string
  revision: string
}

interface ResolvedPin extends Pin {
  identity: string
}

// a Package.resolved's pins in any of swiftpm's three lockfile generations:
// v1 nests them under `object` with the package name and repository url, and
// the identity is derived from the url as swiftpm derives it; v2 and v3 list
// them at the top level with their explicit identity and location. entries
// without a usable revision are skipped, as today.
function resolvedPins(data: unknown): ResolvedPin[] | null {
  if (!data || typeof data !== 'object') return null
  const version =
    'version' in data && typeof data.version === 'number' ? data.version : null
  // swiftpm fails a lockfile with no version or one it does not know, and
  // each generation decodes its own pin shape: v1 carries repositoryURL,
  // v2 and v3 carry location.
  if (version !== 1 && version !== 2 && version !== 3) return null
  const top = 'pins' in data && Array.isArray(data.pins) ? data.pins : null
  const nested =
    'object' in data &&
    data.object &&
    typeof data.object === 'object' &&
    'pins' in data.object &&
    Array.isArray(data.object.pins)
      ? data.object.pins
      : null
  const v1 = version === 1
  const pins = v1 ? nested : top
  if (!pins) return null
  const out: ResolvedPin[] = []
  for (const pin of pins) {
    const location = v1 ? pin?.repositoryURL : pin?.location
    const identity =
      v1 && typeof location === 'string' ? swiftPackageIdentity(location) : pin?.identity
    const revision = pin?.state?.revision
    if (
      typeof identity === 'string' &&
      typeof location === 'string' &&
      typeof revision === 'string'
    )
      out.push({ identity, location, revision })
  }
  return out
}

export function readPins(resolved: readonly string[]): Map<string, Pin> {
  const out = new Map<string, Pin>()
  const owners = new Map<string, string>()
  for (const file of resolved) {
    const data: unknown = JSON.parse(fs.readFileSync(file, 'utf8'))
    const pins = resolvedPins(data)
    if (!pins) throw new Error(`${file} has no pins; resolve packages in a current Xcode`)
    for (const { identity, location, revision } of pins) {
      const previous = out.get(identity)
      const repository = (url: string) => url.replace(/(?:\.git)?\/?$/, '')
      if (
        previous &&
        (previous.revision !== revision ||
          repository(previous.location) !== repository(location))
      )
        throw new Error(
          `conflicting Package.resolved pins for ${identity}: ${owners.get(identity)} pins ${previous.location} at ${previous.revision}; ${file} pins ${location} at ${revision}`,
        )
      out.set(identity, { location, revision })
      owners.set(identity, file)
    }
  }
  return out
}

const verified = new Set<string>()
const execFileAsync = promisify(execFile)

type Git = (cwd: string, ...args: string[]) => Promise<string>

// submodule paths that name a url in .gitmodules. a gitlink without an entry
// cannot resolve, so it is left out instead of failing the fetch.
async function resolvableSubmodulePaths(dir: string, git: Git): Promise<string[]> {
  if (!fs.existsSync(path.join(dir, '.gitmodules'))) return []
  let raw: string
  try {
    raw = await git(
      dir,
      'config',
      '--file',
      '.gitmodules',
      '--get-regexp',
      '^submodule\\.',
    )
  } catch {
    return []
  }
  const entries = new Map<string, { path?: string; url?: string }>()
  for (const line of raw.split('\n')) {
    const match = /^submodule\.(.+)\.(path|url)\s+(.+)$/.exec(line.trim())
    if (!match || (match[2] !== 'path' && match[2] !== 'url')) continue
    const entry = entries.get(match[1]!) ?? {}
    if (match[2] === 'path') entry.path = match[3]
    else entry.url = match[3]
    entries.set(match[1]!, entry)
  }
  const named = [...entries.values()]
    .filter((entry) => entry.path !== undefined && entry.url !== undefined)
    .map((entry) => entry.path!)
  if (named.length === 0) return []
  const gitlinks = new Set(
    (await git(dir, 'ls-files', '--stage', '--', ...named))
      .split('\n')
      .filter((line) => line.startsWith('160000 '))
      .map((line) => line.slice(line.indexOf('\t') + 1)),
  )
  return named.filter((submodule) => gitlinks.has(submodule))
}

// a shallow checkout of exactly the pinned revision, reused while HEAD is it.
// submodules check out at the commits the pinned revision records, as xcode
// does; without this a package like secp256k1.swift leaves its C sources empty.
// git runs off the event loop and never prompts for credentials.
async function fetchCheckout(
  checkouts: string,
  identity: string,
  pin: Pin,
  signal: AbortSignal | undefined,
): Promise<void> {
  const dir = path.join(checkouts, identity)
  if (preparedSwiftPin(checkouts, identity, pin.location, pin.revision)) return
  requireNativeGit()
  const key = checkoutKey(dir, pin)
  const git: Git = async (cwd, ...args) =>
    (
      await execFileAsync('git', ['-C', cwd, ...args], {
        encoding: 'utf8',
        env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
        signal,
      })
    ).stdout.trim()
  const lock = async () => {
    let release = tryAcquireNumberedLock(`${dir}.lock`)
    while (!release) {
      await sleep(25, undefined, { signal })
      release = tryAcquireNumberedLock(`${dir}.lock`)
    }
    return release
  }
  // an interrupted clone leaves a .git without a HEAD commit, which counts as no checkout
  const head = async (at = dir) => {
    if (!fs.existsSync(path.join(at, '.git'))) return ''
    try {
      return await git(at, 'rev-parse', 'HEAD')
    } catch {
      return ''
    }
  }
  // a verified pin stays verified only while HEAD is still it: requesting
  // revisions A then B then A must refetch A, not return the B checkout.
  if (verified.has(key) && (await head()) === pin.revision) return
  if ((await head()) !== pin.revision) {
    // staging dirs of killed runs are never reused
    for (const name of fs.readdirSync(checkouts)) {
      if (!name.startsWith(`${identity}.tmp-`)) continue
      const stale = path.join(checkouts, name)
      try {
        if (Date.now() - fs.statSync(stale).mtimeMs > 24 * 3600_000)
          fs.rmSync(stale, { recursive: true, force: true })
      } catch {}
    }
    // fetch beside the final path and rename, so a killed run never leaves a partial dir
    const staging = `${dir}.tmp-${process.pid}-${Date.now()}`
    fs.rmSync(staging, { recursive: true, force: true })
    fs.mkdirSync(staging, { recursive: true })
    try {
      await git(staging, 'init', '-q')
      await git(staging, 'fetch', '-q', '--depth', '1', pin.location, pin.revision)
      await git(staging, 'checkout', '-q', 'FETCH_HEAD')
      // the final dir changes only under a per-package lock, so the head check
      // and the replacement are one step: a tree published by another run is
      // kept as is and a stale publisher never removes it
      const release = await lock()
      try {
        if ((await head()) !== pin.revision) {
          const aside = `${dir}.tmp-old-${process.pid}-${Date.now()}`
          if (fs.existsSync(dir)) fs.renameSync(dir, aside)
          fs.renameSync(staging, dir)
          fs.rmSync(aside, { recursive: true, force: true })
        }
      } finally {
        release()
      }
    } catch (error) {
      const stderr =
        error instanceof Error && 'stderr' in error ? String(error.stderr).trim() : ''
      throw new Error(
        `could not fetch ${pin.location} at ${pin.revision}${stderr ? `: ${stderr}` : ''}`,
      )
    } finally {
      fs.rmSync(staging, { recursive: true, force: true })
    }
  }
  // a reused checkout from before submodules were fetched has the right HEAD
  // but empty submodule dirs, so this runs for fresh and reused trees alike.
  // the per-package lock orders concurrent initializations of one checkout.
  // relative submodule urls resolve against origin, which a fetch-by-url
  // never configures, so the pinned location is named as origin and sync
  // repairs urls recorded against a missing origin before update checks out
  // the gitlink pins. only gitlinks the tree records whose .gitmodules entry
  // names a url resolve, as swiftpm's bare `submodule update` selects them: a
  // stale gitlink without a .gitmodules entry (gifu's GifuDocs) stays an empty
  // dir, and a .gitmodules entry whose path the tree has no gitlink for
  // (apollo-ios's docs/renderer) is skipped, instead of failing the fetch.
  const submoduleRelease = await lock()
  try {
    try {
      await git(dir, 'remote', 'set-url', 'origin', pin.location)
    } catch {
      await git(dir, 'remote', 'add', 'origin', pin.location)
    }
    const submodules = await resolvableSubmodulePaths(dir, git)
    if (submodules.length > 0) {
      await git(dir, 'submodule', 'sync', '--recursive', '-q')
      await git(
        dir,
        'submodule',
        'update',
        '--init',
        '--recursive',
        '--depth',
        '1',
        '-q',
        '--',
        ...submodules,
      )
    }
  } catch (error) {
    const stderr =
      error instanceof Error && 'stderr' in error ? String(error.stderr).trim() : ''
    throw new Error(
      `could not fetch submodules of ${pin.location} at ${pin.revision}${stderr ? `: ${stderr}` : ''}`,
    )
  } finally {
    submoduleRelease()
  }
  verified.add(key)
}

const checkoutKey = (dir: string, pin: Pin) => `${dir}\0${pin.revision}`

// the checkout prefetch fetched: resolution reads manifests synchronously, so
// a pin that was never fetched is a caller that skipped the prefetch. the
// verified set is per process and another run may have replaced the shared
// dir with another revision since, so the detached HEAD (the pinned sha after
// `checkout FETCH_HEAD`) must still be the pin.
function fetchedCheckout(checkouts: string, identity: string, pin: Pin): string {
  const dir = path.join(checkouts, identity)
  const head = path.join(dir, '.git', 'HEAD')
  if (
    !verified.has(checkoutKey(dir, pin)) ||
    !fs.existsSync(head) ||
    fs.readFileSync(head, 'utf8').trim() !== pin.revision
  )
    throw new Error(
      `${identity} at ${pin.revision} was not fetched; await prefetchSwiftCheckouts first`,
    )
  return dir
}

interface LoadedPackage {
  /** the url, or the local directory. */
  source: string
  remote: boolean
  manifest: SwiftPackageManifest
}

/**
 * fetch every pinned checkout, as xcode's package resolution does before a
 * build. run script phases read checkouts from disk, so they need them
 * before the resolver runs for the compile.
 */
export async function prefetchSwiftCheckouts(
  rootDir: string,
  resolved: readonly string[],
  signal?: AbortSignal,
): Promise<void> {
  const pins = resolved.length > 0 ? readPins(resolved) : null
  if (!pins) return
  const checkouts = remoteSwiftCheckouts(rootDir)
  fs.mkdirSync(checkouts, { recursive: true })
  for (const [identity, pin] of pins)
    await fetchCheckout(checkouts, identity, pin, signal)
}

export async function resolveSwiftPackagesAsync(
  options: Parameters<typeof resolveSwiftPackages>[0],
): Promise<SwiftPackages> {
  // evaluate only manifests reached by the graph; an unused broken package
  // must not stop a build. restart with each newly cached manifest.
  for (;;) {
    try {
      return resolveSwiftPackages({ ...options, requirePrepared: true })
    } catch (error) {
      if (!(error instanceof SwiftManifestPreparationRequired)) throw error
      await prepareSwiftPackageManifest(error.dir)
    }
  }
}

/**
 * resolves `products` to the source targets that build them. products named
 * in `provided` link as peach modules unless explicitly linked source owns
 * their target closure. without
 * `provided` (a hosted compile has no local module list) remote products
 * stay unresolved and only local packages compile.
 */
export function resolveSwiftPackages(options: {
  rootDir: string
  /** the selected workspace or local Package.resolved files. */
  resolved: readonly string[]
  products: readonly SwiftLinkedProduct[]
  /** local package directories the workspace or a project references. */
  localDirs: readonly string[]
  provided: ReadonlySet<string> | null
  /** binary targets whose stand-in is built; one pinning another archive than peach's shipped module compiles through it. */
  standinTargets?: ReadonlySet<string>
  /** why a binary target has no stand-in, added to its reason. */
  binaryGaps?: ReadonlyMap<string, string>
  /** assembly targets whose sources preprocess to nothing for wasm32. */
  portableAssembly?: ReadonlySet<string>
  /**
   * each compiling module and the package products it links. a clang target
   * in that product's closure records the module as a client.
   */
  owners?: readonly { module: string; products: readonly SwiftLinkedProduct[] }[]
  requirePrepared?: boolean
}): SwiftPackages {
  const { rootDir, resolved, products, localDirs } = options
  const providedTargets = new Set(options.provided ?? [])
  const portableAssembly = options.portableAssembly ?? new Set<string>()
  const providedProducts = new Set(options.provided ?? [])
  const result: SwiftPackages = {
    sourceLinks: { targets: [], owners: [] },
    targets: [],
    nativePackages: [],
    nativeProducts: [],
    unavailable: new Map(),
    modules: new Map(),
    binaries: [],
  }
  const pins = resolved.length > 0 ? readPins(resolved) : null
  const checkouts = remoteSwiftCheckouts(rootDir)

  const packages = new Map<string, LoadedPackage | string>()
  // swiftpm identifies a remote package by its identity (the url's last path
  // component, case-insensitive and without `.git`) and a local package by its
  // directory. two spellings of one repository are one package, with one
  // checkout and one set of targets.
  const packageKey = (source: string) =>
    path.isAbsolute(source) ? source : swiftPackageIdentity(source)
  const sourceKey = (source: SwiftPackageSource & { kind: 'local' | 'remote' }) =>
    packageKey(source.kind === 'local' ? path.resolve(source.dir) : source.url)
  // a package by local directory or remote url, or why it cannot load
  const load = (source: SwiftPackageSource & { kind: 'local' | 'remote' }) => {
    const key = sourceKey(source)
    const cached = packages.get(key)
    if (cached !== undefined) return cached
    let loaded: LoadedPackage | string
    if (source.kind === 'local') {
      loaded = {
        source: key,
        remote: false,
        manifest: swiftPackageManifest(key, undefined, options.requirePrepared),
      }
    } else {
      const identity = swiftPackageIdentity(source.url)
      const pin = pins?.get(identity)
      if (!pin) {
        loaded = pins
          ? `package ${identity} is not pinned in Package.resolved`
          : 'no Package.resolved pins it; resolve packages in Xcode once'
      } else {
        fs.mkdirSync(checkouts, { recursive: true })
        loaded = {
          source: source.url,
          remote: true,
          manifest: swiftPackageManifest(
            fetchedCheckout(checkouts, identity, pin),
            undefined,
            options.requirePrepared,
          ),
        }
      }
    }
    packages.set(key, loaded)
    return loaded
  }

  const dependencyPackage = (
    pkg: LoadedPackage,
    dependency: Extract<SwiftTargetDependency, { kind: 'product' }>,
    manifest = pkg.manifest,
  ) =>
    swiftProductDependency(manifest, dependency, (source) =>
      'dir' in source
        ? load({ kind: 'local', dir: source.dir })
        : options.provided
          ? load({ kind: 'remote', url: source.url })
          : undefined,
    )

  const targets = new Map<string, SwiftPackageSourceTarget>()
  const nativePackages = new Map<string, LoadedPackage>()
  const nativeTargets = new Set<string>()
  const hostPlatform = process.platform === 'darwin' ? 'macos' : 'linux'
  // guest targets build for the simulated device from the declared manifest;
  // host targets (macros) build for the machine running the compiler.
  const manifestFor = (pkg: LoadedPackage, side: BuildSide) =>
    side === 'guest'
      ? pkg.manifest
      : swiftPackageManifest(pkg.manifest.dir, hostPlatform, options.requirePrepared)
  const preservePackage = (
    pkg: LoadedPackage,
    roots: readonly string[],
    side: BuildSide,
  ): string[] => {
    nativePackages.set(pkg.manifest.dir, pkg)
    const manifest = manifestFor(pkg, side)
    return blockers(
      roots.map((name) => {
        const key = `${manifest.dir}\0${name}\0${side}`
        if (nativeTargets.has(key)) return []
        nativeTargets.add(key)
        const target = manifest.targets.get(name)
        if (!target) return [`${manifest.name} declares no target ${name}`]
        if (target.type === 'macro' && side === 'guest')
          return preservePackage(pkg, [name], 'host')
        return blockers(
          target.dependencies.map((dependency) => {
            if (dependency.kind === 'target')
              return preservePackage(pkg, [dependency.name], side)
            const nested = dependencyPackage(pkg, dependency, manifest)
            if (!nested) return []
            if (typeof nested === 'string') return [nested]
            const nestedManifest = manifestFor(nested, side)
            const roots = nestedManifest.products.get(dependency.name)?.targets
            return roots
              ? preservePackage(nested, roots, side)
              : [`${nestedManifest.name} has no library ${dependency.name}`]
          }),
        )
      }),
    )
  }
  // every reason each target cannot compile; empty once it can
  const targetOutcomes = new Map<string, string[]>()
  const resolveTarget = (pkg: LoadedPackage, name: string): string[] => {
    const key = `${pkg.manifest.dir}\0${name}`
    if (targetOutcomes.has(key)) return targetOutcomes.get(key)!
    // a dependency cycle resolves as compiling; swiftpm rejects real cycles
    targetOutcomes.set(key, [])
    const outcome = ((): string[] => {
      if (providedTargets.has(name)) return []
      const target = pkg.manifest.targets.get(name)
      if (!target)
        return [`${path.basename(pkg.manifest.dir)} declares no target ${name}`]
      if (target.type === 'macro') return preservePackage(pkg, [name], 'host')
      const files =
        target.type === 'regular' || target.type === 'system'
          ? swiftTargetFiles(pkg.manifest, target)
          : []
      const gap = options.binaryGaps?.get(name)
      const unlowerable = unlowerableSources(files, target, portableAssembly)
      const placeholder = placeholderPackage(pkg)
      const ownReason =
        target.type === 'binary'
          ? `${name} ${BINARY}${gap ? `; ${gap}` : ''}`
          : placeholder && gap
            ? `${name} stands in as a placeholder (${placeholder}), and ${gap}`
            : target.type !== 'regular' && target.type !== 'system'
              ? `${name} is a ${target.type} target`
              : unlowerable.length > 0
                ? `${name} has native sources with no wasm lowering: ${unlowerable.map((file) => path.relative(pkg.manifest.dir, file)).join(', ')}${gap ? `; ${gap}` : ''}`
                : null
      // every dependency resolves, so a failing one never hides the rest
      // of the closure from the compile or from the report
      const reasons = target.dependencies.map((dependency) => {
        if (dependency.kind === 'target') return resolveTarget(pkg, dependency.name)
        const nested = resolveDependencyProduct(pkg, dependency)
        return nested.map((reason) => `${dependency.name}: ${reason}`)
      })
      const blocked = blockers([ownReason ? [ownReason] : [], ...reasons])
      if (blocked.length > 0) return blocked
      const relative = files.map((file) => path.relative(target.dir, file))
      targets.set(`${pkg.manifest.dir}\0${name}`, {
        name,
        path: '',
        dir: target.dir,
        files,
        exclude: target.exclude,
        ...(target.sources ? { sources: target.sources } : {}),
        packageDir: pkg.manifest.dir,
        remote: pkg.remote,
        iosDeployment: pkg.manifest.iosDeployment,
        packageDefines: target.defines,
        packageLibraries: target.libraries,
        packageExperimentalFeatures: target.experimentalFeatures,
        packageUpcomingFeatures: target.upcomingFeatures,
        packageSwiftFlags: target.swiftFlags,
        packageNativeSettings: target.nativeSettings,
        dependencies: target.dependencies,
        executable: false,
        publicHeadersPath: target.publicHeadersPath,
        ...(target.type === 'system' ? { systemLibrary: true } : {}),
        languageMode: target.languageMode,
        mainActorIsolation: target.mainActorIsolation,
        resources:
          target.declaresResources || swiftImplicitResourcePaths(relative).length > 0,
      })
      return []
    })()
    targetOutcomes.set(key, outcome)
    return outcome
  }
  // products resolved anywhere in the closure, by package, with why one
  // cannot compile: a wrapper package's product is often the module name
  const productOutcomes = new Map<string, { pkg: LoadedPackage; reason: string[] }>()
  const resolveProduct = (pkg: LoadedPackage, product: string): string[] => {
    if (providedProducts.has(product)) return []
    const roots = pkg.manifest.products.get(product)?.targets
    const reason = !roots
      ? [`${path.basename(pkg.manifest.dir)} has no library ${product}`]
      : blockers(roots.map((name) => resolveTarget(pkg, name)))
    productOutcomes.set(`${pkg.manifest.dir}\0${product}`, { pkg, reason })
    return reason
  }
  const resolveDependencyProduct = (
    pkg: LoadedPackage,
    dependency: Extract<SwiftTargetDependency, { kind: 'product' }>,
  ): string[] => {
    if (providedProducts.has(dependency.name)) return []
    const loaded = dependencyPackage(pkg, dependency)
    return typeof loaded === 'string'
      ? [loaded]
      : loaded
        ? resolveProduct(loaded, dependency.name)
        : []
  }

  const unnamedProducts = new Map<string, LoadedPackage | string | undefined>()
  const unnamed = (
    source: Extract<SwiftPackageSource, { kind: 'unnamed' }>,
    product: string,
  ): LoadedPackage | string | undefined => {
    const key = JSON.stringify([source, product])
    if (unnamedProducts.has(key)) return unnamedProducts.get(key)
    const candidates = [
      ...localDirs.map((dir) => load({ kind: 'local', dir })),
      ...(options.provided ? source.remoteUrls : []).map((url) =>
        load({ kind: 'remote', url }),
      ),
    ]
      .filter((pkg) => typeof pkg !== 'string')
      .filter((pkg) => pkg.manifest.products.has(product))
    const matches = [
      ...new Map(candidates.map((pkg) => [pkg.manifest.dir, pkg])).values(),
    ]
    const pkg =
      matches.length > 1
        ? `ambiguous library product ${product} is vended by ${matches.map((match) => match.source).join(', ')}`
        : matches[0]
    unnamedProducts.set(key, pkg)
    return pkg
  }
  // linked source owns its regular targets and their source dependencies.
  // binary and placeholder targets retain their existing providers.
  const claimed = new Set<string>()
  const claimTarget = (pkg: LoadedPackage, name: string): boolean => {
    const key = `${pkg.manifest.dir}\0${name}`
    if (claimed.has(key)) return true
    const target = pkg.manifest.targets.get(name)
    if (!target || target.type !== 'regular' || placeholderPackage(pkg)) return false
    // a wrapper target with empty sources only groups binary dependencies,
    // which the module peach ships already covers
    const files = swiftTargetFiles(pkg.manifest, target)
    if (
      files.every(
        (file) => file.endsWith('.swift') && fs.readFileSync(file, 'utf8').trim() === '',
      )
    )
      return false
    // a target whose headers stand in for its unlowered sources stays with the stand-in
    if (unloweredSources(files, target, portableAssembly)) return false
    claimed.add(key)
    providedTargets.delete(name)
    for (const dependency of target.dependencies) {
      if (dependency.kind === 'target') claimTarget(pkg, dependency.name)
      else {
        const nested = dependencyPackage(pkg, dependency)
        if (nested && typeof nested !== 'string') claimProduct(nested, dependency.name)
      }
    }
    return true
  }
  const claimProduct = (pkg: LoadedPackage, product: string): void => {
    const roots = pkg.manifest.products.get(product)?.targets ?? []
    for (const root of roots) {
      const target = pkg.manifest.targets.get(root)
      if (
        target?.type === 'binary' &&
        !options.standinTargets?.has(root) &&
        shippedBinaryDiffers(root, target.checksum)
      ) {
        providedTargets.delete(root)
        providedProducts.delete(product)
      }
    }
    if (roots.map((name) => claimTarget(pkg, name)).some(Boolean))
      providedProducts.delete(product)
  }
  for (const { product, source } of products) {
    if (source.kind === 'remote' && !options.provided) continue
    const pkg = source.kind === 'unnamed' ? unnamed(source, product) : load(source)
    if (pkg && typeof pkg !== 'string') claimProduct(pkg, product)
  }
  for (const { product, source } of products) {
    if (providedProducts.has(product)) continue
    if (source.kind === 'remote' && !options.provided) continue
    const pkg = source.kind === 'unnamed' ? unnamed(source, product) : load(source)
    const reason =
      pkg === undefined
        ? ['no package the workspace references vends it']
        : typeof pkg === 'string'
          ? [pkg]
          : resolveProduct(pkg, product)
    if (reason.length > 0)
      result.unavailable.set(product, {
        source:
          source.kind === 'remote'
            ? source.url
            : typeof pkg === 'object'
              ? pkg.source
              : source.kind === 'local'
                ? source.dir
                : 'the workspace',
        reason: reason.join('; '),
      })
  }

  // every module a reached package declares, so an import of one that does
  // not compile says why even when the app links it through another product
  for (const pkg of packages.values()) {
    if (typeof pkg === 'string') continue
    for (const [name, target] of pkg.manifest.targets) {
      if (target.type === 'test' || target.type === 'plugin' || target.type === 'macro')
        continue
      if (target.type === 'executable') continue
      const files =
        target.type === 'regular' || target.type === 'system'
          ? swiftTargetFiles(pkg.manifest, target)
          : []
      const objc =
        target.type === 'regular' && files.some((file) => /\.(m|mm)$/.test(file))
      const unlowered = unloweredSources(files, target, portableAssembly)
      const gap = placeholderPackage(pkg)
      const sources = files.filter((file) => file.endsWith('.swift'))
      // swiftpm's release settings, as xcode builds a package for any
      // configuration other than Debug
      const release = (setting: SwiftManifestSetting) => setting.configuration !== 'debug'
      if (gap && target.type === 'regular' && !objc && sources.length > 0)
        result.binaries.push({
          target: name,
          source: pkg.source,
          url: null,
          checksum: null,
          dir: pkg.manifest.dir,
          reached: false,
          placeholder: {
            gap,
            sources: sources.map((file) => path.relative(pkg.manifest.dir, file)),
            flags: [
              '-swift-version',
              String(target.languageMode),
              '-package-name',
              swiftPackageIdentity(pkg.manifest.dir),
              '-DSWIFT_PACKAGE',
              ...target.defines.filter(release).flatMap(({ name }) => ['-D', name]),
              ...target.experimentalFeatures
                .filter(release)
                .flatMap(({ name }) => ['-enable-experimental-feature', name]),
              ...target.upcomingFeatures
                .filter(release)
                .flatMap(({ name }) => ['-enable-upcoming-feature', name]),
            ],
          },
        })
      else if (target.type === 'binary' || objc || unlowered)
        result.binaries.push({
          target: name,
          source: pkg.source,
          url: target.url,
          checksum: target.checksum,
          dir: target.type === 'binary' ? target.dir : pkg.manifest.dir,
          reached: false,
          ...(target.type === 'binary'
            ? {}
            : {
                publicHeaders: path.relative(
                  pkg.manifest.dir,
                  path.join(target.dir, target.publicHeadersPath),
                ),
              }),
          ...(unlowered
            ? {
                unloweredSources: unlowered.map((file) =>
                  path.relative(pkg.manifest.dir, file),
                ),
              }
            : {}),
        })
      const reason = resolveTarget(pkg, name)
      if (reason.length > 0 && !result.modules.has(name))
        result.modules.set(name, { source: pkg.source, reason: reason.join('; ') })
    }
  }
  for (const [key, { pkg, reason }] of productOutcomes) {
    const product = key.slice(key.indexOf('\0') + 1)
    if (reason.length > 0 && !result.modules.has(product))
      result.modules.set(product, { source: pkg.source, reason: reason.join('; ') })
  }
  // what compiles is every buildable target in a linked product's closure,
  // decided per target: a product with one target behind a binary still
  // builds its other targets and their dependencies, which the app may
  // import directly. the module sweep above resolved the rest only to learn
  // their reasons.
  const productClosure = (listed: readonly SwiftLinkedProduct[]): Set<string> => {
    const found = new Set<string>()
    const visit = (pkg: LoadedPackage, name: string) => {
      const key = `${pkg.manifest.dir}\0${name}`
      if (found.has(key)) return
      found.add(key)
      if (pkg.manifest.targets.get(name)?.type === 'macro') return
      // a placeholder standing in needs none of what its sources import
      if (providedTargets.has(name) && placeholderPackage(pkg)) return
      for (const dependency of pkg.manifest.targets.get(name)?.dependencies ?? []) {
        if (dependency.kind === 'target') visit(pkg, dependency.name)
        else if (!providedProducts.has(dependency.name)) {
          const nested = dependencyPackage(pkg, dependency)
          if (nested && typeof nested !== 'string')
            for (const root of nested.manifest.products.get(dependency.name)?.targets ??
              [])
              visit(nested, root)
        }
      }
    }
    // a product peach ships links as its module, so its wrapper targets and
    // their binary dependencies are not part of what compiles
    for (const { product, source } of listed) {
      if (providedProducts.has(product)) continue
      const pkg =
        source.kind === 'unnamed'
          ? unnamed(source, product)
          : packages.get(sourceKey(source))
      if (!pkg || typeof pkg === 'string') continue
      for (const root of pkg.manifest.products.get(product)?.targets ?? [])
        visit(pkg, root)
    }
    return found
  }
  const reached = productClosure(products)
  // a package's source is its key among the loaded packages
  for (const binary of result.binaries) {
    const pkg = packages.get(packageKey(binary.source))
    if (pkg && typeof pkg !== 'string')
      binary.reached = reached.has(`${pkg.manifest.dir}\0${binary.target}`)
  }
  for (const binary of result.binaries) {
    if (binary.publicHeaders === undefined) continue
    const pkg = packages.get(packageKey(binary.source))
    if (!pkg || typeof pkg === 'string') continue
    const headers = new Map<string, string>()
    const visited = new Set<string>()
    const visit = (owner: LoadedPackage, name: string) => {
      const key = `${owner.manifest.dir}\0${name}`
      if (visited.has(key)) return
      visited.add(key)
      const target = owner.manifest.targets.get(name)
      if (!target) return
      const dir = path.join(target.dir, target.publicHeadersPath)
      for (const dependency of target.dependencies) {
        if (dependency.kind === 'target') visit(owner, dependency.name)
        else {
          const nested = dependencyPackage(owner, dependency)
          if (nested && typeof nested !== 'string')
            for (const root of nested.manifest.products.get(dependency.name)?.targets ??
              [])
              visit(nested, root)
        }
      }
      if (name !== binary.target && fs.existsSync(dir))
        headers.set(name, path.relative(binary.dir, dir))
    }
    visit(pkg, binary.target)
    binary.headerDependencies = [...headers].map(([module, path]) => ({ module, path }))
  }
  for (const owner of options.owners ?? []) {
    const found = productClosure(owner.products)
    for (const binary of result.binaries) {
      if (binary.publicHeaders === undefined) continue
      const pkg = packages.get(packageKey(binary.source))
      if (
        !pkg ||
        typeof pkg === 'string' ||
        !found.has(`${pkg.manifest.dir}\0${binary.target}`) ||
        binary.clients?.includes(owner.module)
      )
        continue
      binary.clients = [...(binary.clients ?? []), owner.module]
    }
  }
  const macroOwners = [...nativePackages.values()].filter(({ manifest }) =>
    [...manifest.targets.values()].some(
      (target) =>
        target.type === 'macro' && reached.has(`${manifest.dir}\0${target.name}`),
    ),
  )
  nativePackages.clear()
  nativeTargets.clear()
  for (const pkg of macroOwners)
    preservePackage(
      pkg,
      [...pkg.manifest.targets.keys()].filter((name) =>
        reached.has(`${pkg.manifest.dir}\0${name}`),
      ),
      'guest',
    )
  result.targets = [...targets.entries()]
    .filter(([key, target]) => reached.has(key) && !nativePackages.has(target.packageDir))
    .map(([, target]) => target)
  const byDirectory = new Map<string, LoadedPackage>()
  for (const pkg of packages.values())
    if (typeof pkg !== 'string') byDirectory.set(pkg.manifest.dir, pkg)
  for (const target of result.targets) {
    const pkg = byDirectory.get(target.packageDir)
    if (!pkg) throw new Error(`missing resolved package ${target.packageDir}`)
    target.dependencies = (target.dependencies ?? []).flatMap(
      (dependency): SwiftTargetDependency[] => {
        if (dependency.kind === 'target') return [dependency]
        if (providedProducts.has(dependency.name)) return []
        const nested = dependencyPackage(pkg, dependency)
        if (!nested || typeof nested === 'string') return []
        if (nativePackages.has(nested.manifest.dir))
          return [
            {
              kind: 'product',
              name: dependency.name,
              package: swiftPackageIdentity(nested.manifest.dir),
            },
          ]
        return (nested.manifest.products.get(dependency.name)?.targets ?? []).map(
          (name) => ({
            kind: 'target',
            name,
          }),
        )
      },
    )
  }
  // retain the evaluated product boundary before targets are flattened into
  // the generated package. automatic products remain automatic here.
  const targetId = (pkg: LoadedPackage, name: string) =>
    path.join(pkg.manifest.dir, '#target', name)
  const productId = (pkg: LoadedPackage, name: string) =>
    path.join(pkg.manifest.dir, '#product', name)
  const emitted = new Set<string>()
  const addProduct = (pkg: LoadedPackage, name: string): string => {
    const id = productId(pkg, name)
    if (emitted.has(id)) return id
    emitted.add(id)
    const product = pkg.manifest.products.get(name)
    if (!product) throw new Error(`missing resolved library product ${name}`)
    result.sourceLinks.targets.push({
      id,
      sourceTarget: null,
      productName: name,
      productType: `swiftpm.library.${product.linkage}`,
      machOType: product.linkage === 'dynamic' ? 'mh_dylib' : 'staticlib',
      installName: null,
      buildVersion: { platform: null, minimumOS: pkg.manifest.iosDeployment, sdk: null },
      linkerFlags: [],
      dependencies: product.targets.map((name) => ({
        target: addTarget(pkg, name),
        attributes: [],
      })),
    })
    return id
  }
  const addTarget = (pkg: LoadedPackage, name: string): string => {
    const id = targetId(pkg, name)
    if (emitted.has(id)) return id
    emitted.add(id)
    const target = pkg.manifest.targets.get(name)
    if (!target) throw new Error(`missing resolved package target ${name}`)
    const dependencies =
      target.type === 'macro'
        ? []
        : target.dependencies.flatMap((dependency) => {
            if (dependency.kind === 'target')
              return pkg.manifest.targets.get(dependency.name)?.type === 'macro'
                ? []
                : [{ target: addTarget(pkg, dependency.name), attributes: [] }]
            const provider = dependencyPackage(pkg, dependency)
            if (!provider || typeof provider === 'string') return []
            return [{ target: addProduct(provider, dependency.name), attributes: [] }]
          })
    result.sourceLinks.targets.push({
      id,
      sourceTarget: target.type === 'regular' && !providedTargets.has(name) ? name : null,
      productName: name,
      productType: `swiftpm.target.${target.type}`,
      machOType: null,
      installName: null,
      buildVersion: { platform: null, minimumOS: pkg.manifest.iosDeployment, sdk: null },
      linkerFlags: [
        ...target.libraries
          .filter((setting) => setting.configuration !== 'debug')
          .map((setting) => `-l${setting.name}`),
        ...target.frameworks
          .filter((setting) => setting.configuration !== 'debug')
          .flatMap((setting) => ['-framework', setting.name]),
      ],
      dependencies,
    })
    return id
  }
  for (const owner of options.owners ?? []) {
    const links: { target: string; attributes: string[] }[] = []
    for (const { product, source, attributes } of owner.products) {
      const pkg =
        source.kind === 'unnamed'
          ? unnamed(source, product)
          : packages.get(sourceKey(source))
      if (pkg && typeof pkg !== 'string' && pkg.manifest.products.has(product))
        links.push({ target: addProduct(pkg, product), attributes: attributes ?? [] })
    }
    result.sourceLinks.owners.push({ module: owner.module, products: links })
  }
  result.nativePackages = [...nativePackages.values()].map(({ manifest, remote }) => ({
    manifest,
    remote,
    guestTargets: [...manifest.targets.values()].filter((target) =>
      nativeTargets.has(`${manifest.dir}\0${target.name}\0guest`),
    ),
  }))
  for (const { manifest, source } of nativePackages.values())
    for (const name of manifest.products.keys())
      result.nativeProducts.push({ name, packageDir: manifest.dir, source })
  return result
}
