import { AsyncLocalStorage } from 'node:async_hooks'
import { execFile, execFileSync } from 'node:child_process'
import { createHash, type Hash } from 'node:crypto'
// the node host for every Swift preview: package inputs, one compile and
// immutable artifact addresses. vite and the foreground CLI adapt this host.
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { readPngDimensions } from '../../../src/ios/pngHeader'
import { decodeNativeSdkBinding } from '../../peach-kit/src/nativeSdkBindingContract'
import {
  bundleImageRenditionKey,
  enumerateBundleColors,
  enumerateBundleSymbols,
  enumerateBundleImages,
  enumerateBundleResources,
  resolveSwiftImageResourceUrls,
} from '../../sootsim-swift/src/bundleAssets'
import { compileStringCatalog } from '../../sootsim-swift/src/stringCatalog'
import { coreDataSources } from './core-data-entity-classes'
import { compileCoreDataModel, coreDataModelDirectories } from './core-data-model'
import iosSdk from './ios-sdk-frameworks.json' with { type: 'json' }
import { type NativeAppIdentity } from './native-app-identity'
import { readNativeAppIdentityFromXcodeTarget } from './native-app-identity-project'
import { rustStaticLibrary } from './native-static-libraries'
import { parsePlistSource } from './plist'
import { resolveActiveRuntimeRoot } from './runtime-assets'
import { swiftBinaryModules } from './swift-binary-modules'
import { normalizeSwiftCatalogPng } from './swift-catalog-png'
import {
  brotliCompressQ4,
  compileSwiftProjectUnit,
  compileTargets,
  missingSwiftModules,
  swiftAvailableModules,
  swiftSystemLibrarySurface,
  swiftIcuAddress,
  swiftIcuBundleAsset,
  swiftIcuPacked,
  swiftImportNames,
  swiftPeachModules,
  withNativeSourceGlue,
  swiftModuleInputFiles,
  swiftApplicationEntry,
  swiftCDefinedNames,
  swiftCMainEntry,
  swiftCPredefines,
  swiftDistributionAt,
  swiftOptionalFramework,
  compilerSourceDigest,
  swiftSdkPaths,
  WASM_TRIPLE,
} from './swift-compile'
import {
  assetSymbolText,
  generatePackageAssetSymbols,
  planAssetSymbols,
} from './swift-coverage/xcode-assets'
import { xcodeCxxReachable } from './swift-cxx-reachable'
import { designTimeValues } from './swift-design-time'
import { swiftDistributionRoot, swiftModuleToolchain } from './swift-distribution'
import { splitSwiftDyldTable, swiftDyldTableReference } from './swift-guest-dyld-table'
import { brotliCompressSwiftSdkBinding } from './swift-icu'
import { publishedSwiftSdk } from './swift-native-pin'
import { xcodeNativeFlags, xcodeObjCInputsAsync } from './swift-objc-compile'
import {
  isSwiftCxxTranslationUnit,
  isSwiftNativeTranslationUnit,
  moduleMapModules,
  swiftImplicitResourcePaths,
  swiftManifestSettings,
  swiftMetalSourceFiles,
  swiftResourceBundles,
  swiftResourceBundleForFile,
  swiftResourceBundleInfoPlist,
  SWIFT_NATIVE_SOURCE_EXTENSIONS,
  SWIFT_STANDINS_DIR,
  swiftTargetModuleName,
  swiftPackageIdentity,
  clangMacroSetting,
  clangSettingEntries,
  type SwiftClangSetting,
  type SwiftPackageTarget,
  type SwiftTargetDependency,
} from './swift-package'
import {
  swiftPackageManifest,
  swiftTargetFiles,
  swiftTargetResourceFiles,
} from './swift-package-manifest'
import {
  prefetchSwiftCheckouts,
  readPins as readSwiftPackagePins,
  remoteSwiftCheckouts,
  resolveSwiftPackagesAsync,
  type SwiftPackageBinary,
  type SwiftPackageGap,
  type SwiftPackages,
} from './swift-packages'
import { rasterizePdfFiles } from './swift-pdf-raster'
import { wasmSections } from './swift-sdk-image-wasm'
import { shippedBinaryDiffers } from './swift-shipped-binaries'
import {
  packageInputPath,
  readPackageFile as readSwiftSourceFile,
  replaceRoot,
} from './swift-source-file'
import { readSwiftStandinBehavior } from './swift-standin-config'
import {
  RUST_TARGET,
  standinGenerationInputs,
  standinLibrary,
  standinDependencies,
  swiftBinaryFramework,
  swiftStandins,
  type SwiftStandin,
  type SwiftStandins,
} from './swift-standins'
import {
  MAX_SWIFT_COMPILE_FILES,
  MAX_SWIFT_COMPILE_SOURCE_BYTES,
  MAX_SWIFT_COMPILE_RESOURCES,
  MAX_SWIFT_COMPILE_RESOURCE_BYTES,
  MAX_SWIFT_COMPILE_RESOURCE_TOTAL_BYTES,
  MAX_SWIFT_COMPILE_METAL_FILES,
  MAX_SWIFT_COMPILE_METAL_BYTES,
  MAX_SWIFT_COMPILE_METAL_TOTAL_BYTES,
  MAX_SWIFT_COMPILE_IMAGES,
  MAX_SWIFT_COMPILE_IMAGE_BYTES,
  MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES,
  isSwiftNativeModules,
  isSwiftSdkEntryAssets,
  compileSwiftProject,
  DEFAULT_SWIFT_COMPILE_BUILD_MS,
  httpSwiftCompileSubmit,
  swiftNativeEntry,
  type SwiftImageUpload,
  type SwiftNativeModules,
} from './swift-submit'
import { privateSwiftDistributionRoot, swiftCacheDir } from './swift-toolchain'
import { readArMembers } from './swift-wasm-prune'
import { isDynamicLibrary, simulatorNativeLibrary } from './swift-xcframework'
import { swiftProjectFileProblem } from './swiftContract'
import {
  type SwiftSourceLinkGraph,
  SWIFT_NATIVE_INPUT_ROOT,
  SWIFT_NATIVE_SDK_INCLUDE,
  SWIFT_XCODE_BUILD_CONDITION,
  swiftPackageInputNames,
  swiftPackageInputBytes,
  SWIFT_REMOTE_PACKAGES_DIR,
  SWIFT_LOCAL_PACKAGES_DIR,
} from './swiftContract'
import { swiftWasm64PlatformGates } from './swiftWasm64ConfigContract'
import {
  enclosingXcodeWorkspace,
  expandXcodeBuildSetting,
  readXcodeAppTarget,
  resolveXcodeSwiftPackages,
  xcodeFileListEntries,
  type XcodeAppTarget,
  type XcodeModuleTarget,
} from './xcode-project'
import type {
  AppCatalogColor,
  SfSymbolVector,
  SwiftImageResources,
} from './assetCatalogContract'
import type { PeachConfig } from './config'
import type { SwiftCompileInput, SwiftIcuAsset } from './swift-compile'
import type { SwiftStandinBehaviors } from './swift-standin-emit'
import type { SwiftStartupLaunch } from './swift-startup-split'
import type {
  SwiftEntryModuleArgs,
  SwiftMetalLibrarySource,
  SwiftPackageFiles,
  SwiftNativeTarget,
  SwiftHeaderAliases,
  SwiftResourceBundle,
  SwiftSdkEntryAssets,
} from './swiftContract'
import type { SwiftSdkModuleAsset } from './swiftSdkLinkContract'
import type { ServerResponse } from 'node:http'

const ARTIFACT_PATH = '/__peach/swift/'
const RESOURCE_PATH = '/__peach/swift-res/'
const ICU_PATH = '/__peach/swift-icu/'
const SDK_PATH = '/__peach/swift-sdk/'
const SDK_BINDING_PATH = '/__peach/swift-sdk-bindings/'
// a javascript project around the package keeps its outputs at the root; a
// target compiles every visible file below it, a build or types directory too.
const SKIP_ROOT_DIRS = new Set(['dist', 'types', 'build', 'ios', 'android'])
const NATIVE_DESCRIPTOR = '.one-native-source.json'
const NATIVE_GLUE = '.one-native-source.swift.txt'

// vxrn's `swiftPackageId`: the id One's device registry and typegen name a
// package by.
function swiftPackageId(packagePath: string): string {
  return path
    .basename(packagePath)
    .replace(/[^A-Za-z0-9_]/g, '_')
    .replace(/^(\d)/, '_$1')
}

export function nativeSourceDescriptor(packagePath: string): SwiftNativeModules | null {
  packagePath = fs.realpathSync(packagePath)
  if (sourceEntries().has(packagePath)) return null
  const file = path.join(packagePath, NATIVE_DESCRIPTOR)
  if (!fs.existsSync(file)) return null
  const value: unknown = JSON.parse(
    readPackageFile(packagePath, file, MAX_SWIFT_COMPILE_SOURCE_BYTES).toString('utf8'),
  )
  const invalid = () =>
    new Error(`${file}: invalid One native source descriptor; run one typegen`)
  if (
    !value ||
    typeof value !== 'object' ||
    Reflect.get(value, 'generatedBy') !== 'one typegen' ||
    !fs.existsSync(path.join(packagePath, NATIVE_GLUE))
  ) {
    throw invalid()
  }
  if (!isSwiftNativeModules(value) || value.packageId !== swiftPackageId(packagePath)) {
    throw invalid()
  }
  return value
}

export function nativeSourceFiles(packagePath: string): string[] {
  packagePath = fs.realpathSync(packagePath)
  if (sourceEntries().has(packagePath)) return []
  return [NATIVE_DESCRIPTOR, NATIVE_GLUE]
    .map((name) => path.join(packagePath, name))
    .filter((file) => fs.existsSync(file))
}

export class SwiftMissingModulesError extends Error {}

export interface SwiftArtifact {
  hash: string
  bytes: Buffer
  parts?: ReadonlyMap<string, Buffer>
  /** the dlsym table packs the module's index names, served beside it by range. */
  dyldTable?: { sha256: string; bytes: Buffer }
  sdk?: SwiftSdkModuleAsset
  hostedSdk?: SwiftSdkEntryAssets
  // the icu common data the artifact reserves: built here and served from
  // this server, or already published by the Contrast compile that built it
  icu: SwiftIcuAsset | { url: string }
  // the sources this artifact was built from. a watcher event and a `load`
  // reach the project in either order, so freshness is read from the sources
  // rather than from whichever of them ran first.
  stamp: string
  package: {
    resources: Omit<SwiftResourceTable, 'images' | 'metalUploads'>
    bundleFiles: SwiftBundlePack
    native: SwiftNativeModules | null
  }
  // what a local compile built: its source files, a digest of every other
  // input, and the linked module's stamp. a save that matches outside view
  // builder literals reuses the bytes with the literals' values. a hosted
  // compile's artifact carries none, so each of its saves compiles.
  compiled?: { files: Record<string, string>; inputs: string; module: string }
  // the literal values that bring the compiled sources up to the saved ones
  designTimeValues?: Record<string, string>
}

// cross-request-promise: startup profiling belongs to the node preview host.
const startupImages = new WeakMap<SwiftArtifact, Map<string, Promise<SwiftArtifact>>>()

export interface SwiftProject {
  packagePath: string
  /** one Swift source packages import the dispatch module; native providers do not. */
  oneModule: boolean
  /** native provider loaders consume a self-contained executable. */
  standalone?: boolean
  artifact: SwiftArtifact | null
  // the build in flight and the sources it was started from
  building: {
    stamp: string
    // cross-request-promise: one node host process owns its project builds
    promise: Promise<SwiftArtifact>
    signal?: AbortSignal
  } | null
  // two bounded generations of immutable bytes cover in-flight asset reads.
  resourceFiles: Map<string, { bytes: Buffer; contentType: string }>
  resourcesPrevious: Map<string, { bytes: Buffer; contentType: string }>
  artifacts: SwiftArtifact[]
  hosted?: SwiftHostedCompileOptions
  signal?: AbortSignal
  libraries?: Record<string, string>
  binaryModules?: SwiftCompileInput['binaryModules']
  optimize?: boolean
  unoptimized?: boolean
  staticClangTargets?: string[]
  nativeTargets?: SwiftNativeTarget[]
  headerAliases?: SwiftHeaderAliases
  nativeFiles?: Record<string, string>
  resourceBundles?: SwiftResourceBundle[]
  bundleFiles?: SwiftBundlePack
}

// a project is its swiftpm package: the build, the artifact, and the dev
// server that serves it are shared by every plugin instance in this process.
const sharedProjects = new Map<string, SwiftProject>()
const projectScope = new AsyncLocalStorage<{
  projects: Map<string, SwiftProject>
  xcodeProjects: Map<string, XcodeProjectEntry>
  sourceEntries: Map<string, string>
}>()
const projects = () => projectScope.getStore()?.projects ?? sharedProjects
const sharedSourceEntries = new Map<string, string>()
const sourceEntries = () => projectScope.getStore()?.sourceEntries ?? sharedSourceEntries

// a loose entry compiles alone through the same manifest-free project compiler.
export function openSwiftFile(file: string): string {
  file = fs.realpathSync(file)
  const root = path.dirname(file)
  const existing = sourceEntries().get(root)
  if (existing && existing !== file)
    throw new Error(`Swift input ${root} already owns ${existing}`)
  sourceEntries().set(root, file)
  return root
}

export interface SwiftHostedCompileOptions {
  origin: string
  authorization: string
}

export function projectFor(
  packagePath: string,
  hosted?: SwiftHostedCompileOptions,
  signal?: AbortSignal,
): SwiftProject {
  packagePath = fs.realpathSync(packagePath)
  const existing = projects().get(packagePath)
  if (existing) {
    if (signal && existing.signal !== signal) {
      throw new Error('a Swift package cannot share compile cancellation ownership')
    }
    if (hosted && !existing.hosted) {
      throw new Error('a Swift package cannot share local and hosted compile ownership')
    }
    return existing
  }
  const created: SwiftProject = {
    packagePath,
    oneModule: !xcodeProjects().has(packagePath),
    artifact: null,
    building: null,
    resourceFiles: new Map(),
    resourcesPrevious: new Map(),
    artifacts: [],
    hosted,
    signal,
  }
  projects().set(packagePath, created)
  return created
}

// an xcode project compiles its application target, not its directory: the
// project directory is the package path, and the target's member files, plus
// the local packages it links, are the input tree.
interface XcodeProjectEntry {
  xcodeproj: string
  nativeModules?: readonly string[]
  target?: string
  /** the build configuration a selected scheme runs; xcode's default otherwise. */
  configuration?: string
  /** the selected distribution's modules, including metadata-only native intake. */
  provided: ReadonlySet<string> | null
  /** the module root a local compile links, which builds binary stand-ins. */
  moduleRoot: string | null
  /** the distribution whose generated interface headers an installed pod's declarations come from. */
  interfaceRoot: string | null
  behavior?: SwiftStandinBehaviors
  rustWasm64?: PeachConfig['rustWasm64']
  swiftWasm64?: PeachConfig['swiftWasm64']
  packages?: {
    key: string
    standinKey: string
    /** generation always uses the original closure, before stand-ins replace targets. */
    binaries: SwiftPackageBinary[]
    packages: SwiftPackages
    standins: SwiftStandin[]
    /** the framework name of each stood-in binary target that ships a dynamic library. */
    dynamicFrameworks: Map<string, string>
    /** why a framework the project vendors got no stand-in, by name. */
    projectGaps: Map<string, string>
  }
}

const sharedXcodeProjects = new Map<string, XcodeProjectEntry>()
const xcodeProjects = () => projectScope.getStore()?.xcodeProjects ?? sharedXcodeProjects

// native-module readers select different targets in the same workspace concurrently.
// their temporary registrations and snapshots belong to that read, not the server.
export function withXcodeProject<T>(
  xcodeproj: string,
  options: {
    target?: string
    moduleRoot?: string
    configuration?: string
    interfaceRoot?: string
    nativeModules?: readonly string[]
  },
  run: (root: string) => T | Promise<T>,
): Promise<T> {
  return projectScope.run(
    { projects: new Map(), xcodeProjects: new Map(), sourceEntries: new Map() },
    async () => {
      const root = openXcodeProject(
        xcodeproj,
        options.target,
        options.moduleRoot,
        options.configuration,
        options.interfaceRoot,
        options.nativeModules,
      )
      return run(root)
    },
  )
}

// run script phases read SourcePackages/checkouts from disk, but the pins
// and the checkout root only exist after a first read. read once without
// running scripts, fetch the pins the way xcode's resolution does, link
// each used project's derived-data sibling at them, then read for real.
// once per project per process: the checkouts persist and the link is
// idempotent, and a later re-resolve refetches through the same writer.
const preparedScriptInputs = new Set<string>()

/**
 * writes the project's lock and fetches every pinned checkout, off the event
 * loop, so the synchronous reads that follow find both. a process that
 * serves requests awaits this before opening the project.
 */
export async function prepareXcodeSwiftPackages(
  input: string,
  target?: string,
  configuration?: string,
  signal?: AbortSignal,
): Promise<void> {
  await resolveXcodeSwiftPackages(input, signal, target, configuration)
  const app = readXcodeAppTarget(input, target, configuration, {
    installedPods: true,
    requireSources: false,
  })
  await prefetchSwiftCheckouts(app.rootDir, app.packageResolved, signal)
}
function readXcodeAppTargetPrepared(
  input: string,
  target: string | undefined,
  configuration: string | undefined,
  options: {
    requireSources?: boolean
    prepareGeneratedSources?: boolean
    installedPods?: boolean
    nativeModules?: readonly string[]
  },
): XcodeAppTarget {
  if (options.prepareGeneratedSources !== true)
    return readXcodeAppTarget(input, target, configuration, {
      ...options,
      deferPackageResolution: true,
    })
  const key = JSON.stringify([input, target, configuration, options.nativeModules])
  if (!preparedScriptInputs.has(key)) {
    const probe = readXcodeAppTarget(input, target, configuration, {
      ...options,
      prepareGeneratedSources: false,
      requireSources: false,
      deferPackageResolution: true,
    })
    const checkouts = remoteSwiftCheckouts(probe.rootDir)
    for (const projectDir of probe.projectDirs) {
      const packages = path.join(projectDir, '.build', 'peach-xcode', 'SourcePackages')
      fs.mkdirSync(packages, { recursive: true })
      const link = path.join(packages, 'checkouts')
      let linked: string | null = null
      try {
        linked = fs.lstatSync(link).isSymbolicLink() ? fs.readlinkSync(link) : null
      } catch {
        linked = null
      }
      if (linked !== null) {
        if (path.resolve(packages, linked) === checkouts) continue
        fs.unlinkSync(link)
      } else if (fs.existsSync(link)) continue
      try {
        fs.symlinkSync(checkouts, link)
      } catch (error) {
        // another compiler can prepare the same shared workspace concurrently.
        if (
          !(error instanceof Error && 'code' in error && error.code === 'EEXIST') ||
          path.resolve(packages, fs.readlinkSync(link)) !== checkouts
        )
          throw error
      }
    }
    preparedScriptInputs.add(key)
  }
  return readXcodeAppTarget(input, target, configuration, {
    ...options,
    deferPackageResolution: true,
  })
}

/**
 * registers an xcode project's application target as a compile unit and
 * returns the package path that names it. compiling locally against
 * `moduleRoot`, its remote package products compile from their pinned source;
 * a hosted compile has no local module to tell which products peach provides.
 */
export function openXcodeProject(
  xcodeproj: string,
  target: string | undefined,
  moduleRoot: string | undefined,
  configuration?: string,
  interfaceRoot?: string,
  nativeModules?: readonly string[],
): string {
  const app = readXcodeAppTargetPrepared(xcodeproj, target, configuration, {
    prepareGeneratedSources: true,
    installedPods: true,
    nativeModules,
  })
  const root = app.rootDir
  const distribution = moduleRoot ?? interfaceRoot
  const project = projects().get(root)
  if (project) project.oneModule = false
  xcodeProjects().set(root, {
    xcodeproj,
    nativeModules,
    target: app.name,
    configuration: app.configuration,
    provided: distribution ? new Set(swiftPeachModules(distribution)) : null,
    moduleRoot: moduleRoot ?? null,
    interfaceRoot: interfaceRoot ?? null,
  })
  return root
}

// the compiler reads only literal metadata from configured native modules.
export function configureSwiftProject(
  packagePath: string,
  config: PeachConfig | undefined,
) {
  const entry = xcodeProjects().get(fs.realpathSync(packagePath))
  if (!entry) return
  entry.rustWasm64 = config?.rustWasm64
  entry.swiftWasm64 = config?.swiftWasm64
  const behavior: SwiftStandinBehaviors = {}
  for (const [name, resolution] of Object.entries(config?.nativeModules ?? {})) {
    if (
      resolution &&
      typeof resolution === 'object' &&
      'file' in resolution &&
      typeof resolution.file === 'string'
    ) {
      const members = readSwiftStandinBehavior(fs.readFileSync(resolution.file, 'utf8'))
      if (members.size > 0) behavior[name] = Object.fromEntries(members)
    }
  }
  entry.behavior = behavior
}

// cross-request-promise: the swift host runs only in node (cli, dev server), never a worker
const standinBuilds = new Map<string, Promise<SwiftStandins>>()

// packages resolve once per set of linked products, pins and local manifests.
// assembly guarded to the architectures it was written for preprocesses to
// nothing for wasm32 under the target's own headers and the sdk's c flags, so
// swiftpm builds that target as plain c instead of it standing in. a file that
// fails to preprocess (#error on an unknown platform) keeps the stand-in.
// cross-request-promise: the swift host runs only in node (cli, dev server), never a worker
const emptyWasmAssembly = new Map<string, Promise<boolean>>()
async function wasmPortableAssembly(
  binaries: readonly SwiftPackageBinary[],
  toolchainBin: string,
  moduleRoot: string,
): Promise<Set<string>> {
  const assembly = binaries.filter(
    (binary) =>
      binary.unloweredSources?.length &&
      binary.unloweredSources.every((file) => /\.(s|S)$/.test(file)) &&
      binary.publicHeaders !== undefined,
  )
  if (assembly.length === 0) return new Set()
  const sdk = swiftSdkPaths(moduleRoot, toolchainBin)
  const clang = path.join(toolchainBin, 'clang')
  const empty = (binary: SwiftPackageBinary, file: string) => {
    const source = path.join(binary.dir, file)
    const key = createHash('sha256')
      .update(
        JSON.stringify([
          clang,
          sdk.sysroot,
          sdk.cFlags,
          binary.dir,
          binary.publicHeaders,
        ]),
      )
      .update(fs.readFileSync(source))
      .digest('hex')
    const known = emptyWasmAssembly.get(key)
    if (known) return known
    const result = new Promise<boolean>((resolve) =>
      execFile(
        clang,
        [
          '-target',
          WASM_TRIPLE,
          '--sysroot',
          sdk.sysroot,
          ...sdk.cFlags,
          '-I',
          path.join(binary.dir, binary.publicHeaders!),
          '-I',
          path.dirname(source),
          '-E',
          '-P',
          '-x',
          'assembler-with-cpp',
          source,
        ],
        { maxBuffer: 64 * 1024 * 1024 },
        (error, stdout) => resolve(!error && stdout.trim() === ''),
      ),
    )
    emptyWasmAssembly.set(key, result)
    return result
  }
  const portable = await Promise.all(
    assembly.map(async (binary) =>
      (
        await Promise.all(binary.unloweredSources!.map((file) => empty(binary, file)))
      ).every(Boolean)
        ? [binary.target]
        : [],
    ),
  )
  return new Set(portable.flat())
}

async function swiftPackages(
  entry: XcodeProjectEntry,
  app: XcodeAppTarget,
): Promise<{
  packages: SwiftPackages
  standins: SwiftStandin[]
  dynamicFrameworks: Map<string, string>
  projectGaps: Map<string, string>
  binaries: SwiftPackageBinary[]
}> {
  const stamp = (file: string) =>
    fs.existsSync(file)
      ? createHash('sha256').update(fs.readFileSync(file)).digest('hex')
      : null
  const owners = [...app.frameworks, app].map((target) => ({
    module: target.moduleName,
    products: target.packageProducts ?? [],
  }))
  const key = JSON.stringify([
    app.linkedProducts,
    owners,
    app.packageResolved.map((file) => [file, stamp(file)]),
    app.localPackageDirs.map((dir) => stamp(path.join(dir, 'Package.swift'))),
    app.linkedProducts.map(({ source }) =>
      source.kind === 'local' ? stamp(path.join(source.dir, 'Package.swift')) : 0,
    ),
  ])
  // resolution follows lock and manifest contents even when a checkout restores
  // timestamps. the stand-in key also covers artifacts, peach modules and emitter.
  let cached = entry.packages
  if (cached?.key !== key) {
    const packages = await resolveSwiftPackagesAsync({
      rootDir: app.rootDir,
      resolved: app.packageResolved,
      products: app.linkedProducts,
      localDirs: app.localPackageDirs,
      provided: entry.provided,
      owners,
    })
    cached = {
      key,
      standinKey: '',
      packages,
      binaries: packages.binaries,
      standins: [],
      dynamicFrameworks: new Map(),
      projectGaps: new Map(),
    }
    entry.packages = cached
  }
  // a reached binary target with stand-ins for every module it ships
  // resolves as provided, so what depends on it compiles; the rest keep
  // their reason with why no stand-in was built. surfaces peach already
  // ships are skipped up front, so no generated target overrides a shipped
  // module.
  // a framework the project vendors links straight into its target, so it
  // stands in the same way a package's binary target does.
  const vendored: SwiftPackageBinary[] = app.binaryFrameworks.flatMap(
    ({ name, path: dir, rustCrate, genrule }) =>
      dir
        ? [
            {
              target: name,
              source: 'the project',
              url: null,
              checksum: null,
              dir,
              reached: true,
              rustCrate,
              genrule,
            } satisfies SwiftPackageBinary,
          ]
        : [],
  )
  let reached = [...cached.binaries.filter((binary) => binary.reached), ...vendored]
  // a binary artifact, a source target whose assembly sources keep it from
  // compiling, or a placeholder package's swift target: each stands in from
  // its public surface.
  const standinArtifact = (binary: SwiftPackageBinary) =>
    !binary.rustCrate &&
    (binary.publicHeaders === undefined || binary.unloweredSources !== undefined)
  const artifacts = reached.filter(standinArtifact)
  if (entry.moduleRoot && entry.provided && artifacts.length > 0) {
    const { provided } = entry
    const resolved = swiftModuleToolchain(entry.moduleRoot)
    const toolchain = {
      moduleRoot: entry.moduleRoot,
      toolchainBin: resolved.toolchainBin,
      release: resolved.release,
    }
    // native module readers assemble their original Swift and clang targets
    // after declaration intake. preparing their products here would compile
    // consumers before their binary dependency surfaces exist.
    if (entry.nativeModules === undefined)
      reached = await xcodeCxxReachable(
        app,
        reached,
        entry.moduleRoot,
        path.join(resolved.toolchainBin, 'clang++'),
      )
    const portableAssembly = await wasmPortableAssembly(
      reached,
      resolved.toolchainBin,
      entry.moduleRoot,
    )
    const cxxArtifacts = reached.filter(
      (binary) => standinArtifact(binary) && !portableAssembly.has(binary.target),
    )
    const standinInputs = [
      ...cxxArtifacts,
      ...standinDependencies(cxxArtifacts, cached.packages, provided),
    ]
    const generation = standinGenerationInputs(standinInputs, toolchain, entry.behavior)
    if (cached.standinKey !== generation) {
      // an archive other than the one peach ships a module for stands in itself
      const replaced = new Set(
        cxxArtifacts
          .filter((binary) => shippedBinaryDiffers(binary.target, binary.checksum))
          .map((binary) => binary.target),
      )
      const built = await swiftStandins(
        standinInputs,
        toolchain,
        new Set([...provided].filter((name) => !replaced.has(name))),
        entry.behavior,
      )
      cached.packages = await resolveSwiftPackagesAsync({
        rootDir: app.rootDir,
        resolved: app.packageResolved,
        products: app.linkedProducts,
        localDirs: app.localPackageDirs,
        // an artifact with neither a stand-in nor a gap ships only modules
        // peach provides, so a wrapper target that groups it still compiles
        provided: new Set([
          ...provided,
          ...cxxArtifacts
            .map((binary) => binary.target)
            .filter((target) => !built.gaps.has(target)),
        ]),
        standinTargets: new Set(
          [...replaced].filter((target) => !built.gaps.has(target)),
        ),
        binaryGaps: built.gaps,
        portableAssembly,
        owners,
      })
      for (const target of new Set(
        built.standins
          .filter((standin) => !standin.nativeArchive)
          .map((standin) => standin.target),
      ))
        console.error(`Peach: target ${target} was replaced with a stand-in`)
      cached.standins = built.standins
      // a binary target shipping a dynamic framework is its own image: the app
      // embeds the framework once for every client that links it.
      const stoodIn = new Set(built.standins.map((standin) => standin.target))
      cached.dynamicFrameworks = new Map(
        cxxArtifacts.flatMap((binary) => {
          if (!stoodIn.has(binary.target)) return []
          const native = simulatorNativeLibrary(swiftBinaryFramework(binary).dir)
          return native?.kind === 'framework' && isDynamicLibrary(native.file)
            ? [[binary.target, native.name] as const]
            : []
        }),
      )
      cached.projectGaps = new Map(
        vendored.flatMap(({ target }) => {
          const gap = built.gaps.get(target)
          return gap ? [[target, gap] as const] : []
        }),
      )
      cached.standinKey = generation
    }
  }
  // what only a placeholder imported is no longer linked once it stands in
  const linked = new Set(
    [...cached.packages.binaries.filter((binary) => binary.reached), ...vendored].map(
      (binary) => `${binary.source}\0${binary.target}`,
    ),
  )
  const archiveTargets = new Set(
    cached.standins
      .filter((standin) => standin.nativeArchive)
      .map((standin) => standin.target),
  )
  return {
    ...cached,
    binaries: reached.filter(
      (binary) =>
        linked.has(`${binary.source}\0${binary.target}`) ||
        archiveTargets.has(binary.target),
    ),
  }
}

// the app target's sources compile as one executable target under this
// directory, each at its root-relative path, so a diagnostic still names the
// file; each framework target compiles as one target under its module's
// directory below XCODE_FRAMEWORKS_DIR; local package targets keep their own
// root-relative paths.
export const XCODE_APP_DIR = '__app__'
const XCODE_FRAMEWORKS_DIR = '__frameworks__'
// remote package checkouts compile here: swiftpm owns `.build` in the
// compile's package root as its scratch directory.
const XCODE_PACKAGES_DIR = SWIFT_REMOTE_PACKAGES_DIR

// the compile input key of a root-relative path in an xcode layout.
function xcodeInputKey(
  layout: Pick<XcodeLayout, 'checkouts' | 'targetDirs'>,
  file: string,
  relative: string,
): string {
  const owner = layout.targetDirs.get(file)
  const checkouts = layout.checkouts
  const checkoutPath = file.startsWith(`${checkouts}${path.sep}`)
    ? path.relative(checkouts, file).split(path.sep).join('/')
    : null
  if (owner) {
    // swiftpm ignores sources beneath hidden directories, including pnpm's
    // .pnpm store, even when xcode explicitly includes those files.
    const input = file.endsWith('.swift')
      ? (checkoutPath ?? relative)
          .split('/')
          .map((part) =>
            part === '.' || part === '..'
              ? part
              : part.replaceAll('%', '%25').replace(/^\./, '%2E'),
          )
          .join('/')
      : (checkoutPath ?? relative)
    return path.posix.join(owner, input)
  }
  return checkoutPath !== null
    ? path.posix.join(XCODE_PACKAGES_DIR, checkoutPath)
    : relative === '..' || relative.startsWith('../')
      ? path.posix.join('external', file.split(path.sep).join('/'))
      : relative
}

interface XcodeLayout {
  app: XcodeAppTarget
  appSwiftFlags: string[]
  checkouts: string
  /** framework and package targets, with root-relative paths and the nested target directories they exclude. */
  targets: (SwiftPackageTarget & { exclude: string[] })[]
  packages: SwiftPackages
  packagePaths: Map<string, string>
  packageFiles: Map<string, string>
  standins: SwiftStandin[]
  /** the binary targets the stand-ins come from. */
  binaries: SwiftPackageBinary[]
  /** why a framework the project vendors got no stand-in, by name. */
  projectGaps: Map<string, string>
  /** the input directory each app and framework source compiles under. */
  targetDirs: Map<string, string>
  resourceBundles: SwiftResourceBundle[]
  frameworkInfoPlists: Map<string, string>
  /** the symbol sources xcode generates from package target catalogs, by input key. */
  generatedSources: Record<string, string>
  nativeTargets: SwiftNativeTarget[]
  staticClangTargets: string[]
  sourceLinkGraph: SwiftSourceLinkGraph
  headerAliases: SwiftHeaderAliases
  nativeFiles: Map<string, Buffer>
  files: string[]
}

// package snapshot reads this several times in one synchronous compile. the
// project does not change during that pass.
const layoutScope = new AsyncLocalStorage<Map<string, XcodeLayout | null>>()

// layouts build async because stand-in admission waits on a remote host. a
// pass prepares the project's layout once, then reads it sync in its scope.
export async function withXcodeLayout<T>(
  root: string,
  run: () => T | Promise<T>,
): Promise<T> {
  const scope = new Map<string, XcodeLayout | null>()
  return layoutScope.run(scope, async () => {
    scope.set(root, await buildXcodeLayout(root))
    return run()
  })
}

function xcodeLayout(root: string): XcodeLayout | null {
  if (!xcodeProjects().has(root)) return null
  const cached = layoutScope.getStore()
  if (!cached?.has(root)) throw new Error(`xcode layout for ${root} was not prepared`)
  return cached.get(root) ?? null
}

async function buildXcodeLayout(root: string): Promise<XcodeLayout | null> {
  const registered = xcodeProjects().get(root)
  if (!registered) return null
  const appTarget = readXcodeAppTargetPrepared(
    registered.xcodeproj,
    registered.target,
    registered.configuration,
    {
      prepareGeneratedSources: true,
      installedPods: true,
      nativeModules: registered.nativeModules,
    },
  )
  const { packages, standins, dynamicFrameworks, projectGaps, binaries } =
    await swiftPackages(registered, appTarget)
  for (const { project, prepare } of packages.sourceFrameworks) {
    if (!prepare) continue
    if (!registered.moduleRoot)
      throw new Error(
        `${project}: building its linked libraries needs a local module root`,
      )
    await prepare(path.dirname(project), registered.moduleRoot)
  }
  const sourceFrameworks = new Map(
    packages.sourceFrameworks.map(
      ({
        packageTarget,
        project,
        target,
        module,
        configuration,
        machOType,
        settings,
      }) => {
        const framework = readXcodeAppTarget(project, target, configuration, {
          prepareGeneratedSources: true,
          frameworkMachOType: machOType,
          frameworkBuildSettings: settings,
        })
        if (framework.moduleName !== module || framework.allSources.length === 0)
          throw new Error(`${project}: ${target} did not produce source module ${module}`)
        if (
          framework.linkedProducts.length > 0 ||
          framework.binaryFrameworks.some(({ path }) => path)
        )
          throw new Error(
            `${project}: ${target} has external dependencies outside the source framework build`,
          )
        return [packageTarget, framework] as const
      },
    ),
  )
  const frameworkTargets = [...sourceFrameworks.values()]
  const packageFrameworkSearchPaths = frameworkTargets.flatMap(
    ({ objc }) => objc?.frameworkSearchPaths.slice(0, 1) ?? [],
  )
  const withPackageFrameworks = <T extends XcodeModuleTarget>(target: T): T =>
    target.objc && packageFrameworkSearchPaths.length > 0
      ? {
          ...target,
          objc: {
            ...target.objc,
            frameworkSearchPaths: [
              ...new Set([
                ...target.objc.frameworkSearchPaths,
                ...packageFrameworkSearchPaths,
              ]),
            ],
          },
        }
      : target
  const app = {
    ...withPackageFrameworks(appTarget),
    frameworks: [
      ...appTarget.frameworks.map(withPackageFrameworks),
      ...frameworkTargets.flatMap((framework) => [...framework.frameworks, framework]),
    ],
    projectFiles: [
      ...appTarget.projectFiles,
      ...frameworkTargets.flatMap((framework) => framework.projectFiles),
    ],
    resourceProducts: [
      ...appTarget.resourceProducts,
      ...frameworkTargets.flatMap((framework) => framework.resourceProducts),
    ],
    sdkFrameworks: [
      ...new Set([
        ...appTarget.sdkFrameworks,
        ...frameworkTargets.flatMap((framework) => framework.sdkFrameworks),
      ]),
    ],
  }
  const appSources = app.allSources
  const checkouts = remoteSwiftCheckouts(app.rootDir)
  const files = new Set([
    ...app.projectFiles,
    ...app.packageResolved,
    ...appSources,
    ...app.resources,
  ])
  if (app.infoPlistFile) files.add(app.infoPlistFile)
  const targetDirs = new Map(
    [...appSources, ...app.resources].map((file) => [file, XCODE_APP_DIR]),
  )
  const resourceBundles: SwiftResourceBundle[] = [
    { target: app.moduleName, sourcePath: XCODE_APP_DIR, path: '.' },
  ]
  const frameworkInfoPlists = new Map<string, string>()
  const targets: XcodeLayout['targets'] = []
  const frameworkNames = new Map<XcodeModuleTarget, string>()
  const usedNames = new Set(
    [
      app.moduleName,
      ...app.frameworks.map((item) => item.moduleName),
      ...packages.targets.map((item) => item.name),
    ].map(swiftTargetModuleName),
  )
  const moduleOwners = new Map<string, XcodeModuleTarget>()
  const publishes = (item: XcodeModuleTarget) =>
    item.sources.length > 0 || (item.objc?.publicHeaders.length ?? 0) > 0
  for (const framework of app.frameworks) {
    if (
      framework.allSources.length === 0 &&
      framework.resources.length === 0 &&
      !Object.keys(framework.objc?.productHeaders ?? {}).some((file) =>
        file.endsWith('.modulemap'),
      )
    )
      continue
    const previous = moduleOwners.get(framework.moduleName)
    if (previous && publishes(previous) && publishes(framework))
      throw new Error(
        `${framework.name}: duplicate module ${framework.moduleName} publishes multiple interfaces`,
      )
    if (!previous || publishes(framework))
      moduleOwners.set(framework.moduleName, framework)
  }
  const generatedSources: Record<string, string> = {}
  // xcode generates symbols for each target's own catalogs from its own settings
  // xcode compiles the entity classes of each target's own models into it
  const coreDataClasses = (files: readonly string[], dir: string) => {
    for (const [name, text] of Object.entries(coreDataSources(files)))
      generatedSources[path.posix.join(dir, 'GeneratedCoreData', name)] = text
  }
  const targetAssetSymbols = (module: XcodeModuleTarget, dir: string) => {
    const plan = planAssetSymbols(
      module.resources.map((file) => path.relative(root, file)),
      root,
      module.assetSettings,
    )
    if (plan.status === 'unknown') throw new Error(`${module.name}: ${plan.reason}`)
    if (plan.status === 'plan')
      generatedSources[path.posix.join(dir, 'GeneratedAssetSymbols.swift')] =
        assetSymbolText(plan.plan, root)
  }
  targetAssetSymbols(app, XCODE_APP_DIR)
  coreDataClasses(app.resources, XCODE_APP_DIR)
  for (const framework of app.frameworks) {
    // a framework target that only links products compiles nothing, so it has
    // no module, directory or bundle contents for swiftpm to take as a target;
    // a header-only clang framework still publishes its module map
    if (
      framework.allSources.length === 0 &&
      framework.resources.length === 0 &&
      !Object.keys(framework.objc?.productHeaders ?? {}).some((file) =>
        file.endsWith('.modulemap'),
      )
    )
      continue
    let name = framework.moduleName
    if (moduleOwners.get(name) !== framework) {
      // swiftpm needs distinct target names when native targets share a module.
      if (framework.resources.length > 0)
        throw new Error(
          `${framework.name}: secondary target of shared module ${name} has resources`,
        )
      let suffix = 1
      while (usedNames.has(`${name}__xcode_${suffix}`)) suffix++
      name = `${name}__xcode_${suffix}`
      usedNames.add(name)
    }
    frameworkNames.set(framework, name)
    const dir = path.posix.join(XCODE_FRAMEWORKS_DIR, name)
    if (name === framework.moduleName) {
      const bundlePath = `Frameworks/${framework.moduleName}.framework`
      resourceBundles.push({
        target: name,
        sourcePath: dir,
        path: bundlePath,
      })
      if (framework.frameworkInfoPlist)
        frameworkInfoPlists.set(bundlePath, framework.frameworkInfoPlist)
    }
    for (const file of framework.allSources) {
      if (targetDirs.has(file)) continue
      targetDirs.set(file, dir)
      files.add(file)
    }
    for (const file of framework.resources) {
      if (targetDirs.has(file)) continue
      targetDirs.set(file, dir)
      files.add(file)
    }
    targetAssetSymbols(framework, dir)
    coreDataClasses(framework.resources, dir)
    targets.push({
      name,
      path: dir,
      executable: false,
      resources: false,
      exclude: [],
      languageMode: framework.languageMode,
      mainActorIsolation: framework.mainActorIsolation,
      cxxInterop: framework.swift?.cxxInterop,
      defines: [...framework.defines, SWIFT_XCODE_BUILD_CONDITION],
    })
  }
  for (const framework of app.frameworks) {
    const target = targets.find((target) => target.name === frameworkNames.get(framework))
    if (!target) continue
    const productLinks =
      packages.sourceLinks.owners.find((owner) => owner.module === framework.moduleName)
        ?.products ?? []
    target.dependencies = [
      ...framework.targetDependencies.flatMap((identity) =>
        app.frameworks
          .filter((dependency) => dependency.targetIdentity === identity)
          .flatMap((dependency) => {
            const name = frameworkNames.get(dependency)
            return name ? [{ kind: 'target', name } satisfies SwiftTargetDependency] : []
          }),
      ),
      ...productLinks.flatMap(({ target: productId }) => {
        const product = packages.sourceLinks.targets.find((item) => item.id === productId)
        return (product?.dependencies ?? []).flatMap(({ target: targetId }) => {
          const item = packages.sourceLinks.targets.find((node) => node.id === targetId)
          if (!item) return []
          if (item.sourceTarget)
            return [
              { kind: 'target', name: item.sourceTarget } satisfies SwiftTargetDependency,
            ]
          return item.productType === 'swiftpm.target.binary'
            ? standins
                .filter((standin) => standin.target === item.productName)
                .map(
                  (standin) =>
                    ({
                      kind: 'target',
                      name: standin.module,
                    }) satisfies SwiftTargetDependency,
                )
            : []
        })
      }),
      ...(framework.packageProducts ?? []).flatMap(({ product, source }) => {
        const native = packages.nativeProducts.find(
          ({ name, source: origin }) =>
            name === product &&
            (source.kind === 'unnamed' ||
              origin ===
                (source.kind === 'remote' ? source.url : path.resolve(source.dir))),
        )
        return native
          ? [
              {
                kind: 'product',
                name: native.name,
                package: native.packageDir,
              } satisfies SwiftTargetDependency,
            ]
          : []
      }),
    ]
  }
  const packagePaths = new Map<string, string>()
  const packageFiles = new Map<string, string>()
  let localPackageRoot = root
  for (const { manifest, remote } of packages.nativePackages) {
    if (remote) continue
    let relative = path.relative(localPackageRoot, manifest.dir)
    while (relative === '..' || relative.startsWith(`..${path.sep}`)) {
      localPackageRoot = path.dirname(localPackageRoot)
      relative = path.relative(localPackageRoot, manifest.dir)
    }
  }
  for (const { manifest, remote } of packages.nativePackages) {
    const directory = remote
      ? path.posix.join(
          XCODE_PACKAGES_DIR,
          path
            .relative(remoteSwiftCheckouts(root), manifest.dir)
            .split(path.sep)
            .join('/'),
        )
      : path.posix.join(
          SWIFT_LOCAL_PACKAGES_DIR,
          path.basename(localPackageRoot),
          path.relative(localPackageRoot, manifest.dir).split(path.sep).join('/'),
        )
    packagePaths.set(manifest.dir, directory)
    const manifests = fs
      .readdirSync(manifest.dir)
      .filter((name) => /^Package(@swift-[\d.]+)?\.swift$/.test(name))
      .map((name) => path.join(manifest.dir, name))
    for (const file of new Set([
      ...manifests,
      ...[...manifest.targets.values()].flatMap((target) => [
        ...swiftTargetFiles(manifest, target),
        ...swiftTargetResourceFiles(manifest, target),
      ]),
    ])) {
      packageFiles.set(
        file,
        path.posix.join(
          directory,
          path.relative(manifest.dir, file).split(path.sep).join('/'),
        ),
      )
      files.add(file)
    }
  }
  const standinModules = new Set(standins.map((standin) => standin.module))
  for (const standin of standins)
    targets.push({
      name: standin.module,
      path: path.posix.join(SWIFT_STANDINS_DIR, standin.module),
      publicHeadersPath: standin.publicHeadersPath,
      dependencies: [
        ...new Set([
          ...(standin.dependencies ?? []),
          ...Object.entries(standin.files).flatMap(([file, contents]) =>
            file.endsWith('.swift')
              ? swiftImportNames(contents).filter(
                  (name) => name !== standin.module && standinModules.has(name),
                )
              : [],
          ),
        ]),
      ].map((name) => ({ kind: 'target', name })),
      executable: false,
      resources: false,
      exclude: [],
      languageMode: 5,
      mainActorIsolation: false,
      ...(`${standin.module}.cpp` in standin.files
        ? {
            clangSettings: [
              {
                tool: 'cxx' as const,
                flags: standin.cxxFlags ?? [],
              },
            ],
          }
        : {}),
    })
  // xcode builds packages in swiftpm's debug configuration for Debug, which
  // defines DEBUG, and in release for any other, as its package compiles show;
  // every package swift unit xcode compiles also gets -DXcode
  const packageConfiguration = app.configuration === 'Debug' ? 'debug' : 'release'
  for (const target of packages.targets) {
    const relative = path.relative(
      target.remote ? remoteSwiftCheckouts(root) : root,
      target.dir,
    )
    if (
      relative === '..' ||
      relative.startsWith(`..${path.sep}`) ||
      path.isAbsolute(relative)
    )
      throw new Error(`swift input escapes the selected package: ${target.dir}`)
    const posix = relative.split(path.sep).join(path.posix.sep)
    // swiftpm hands every clang unit of a package SWIFT_PACKAGE=1, and DEBUG=1
    // in its debug configuration
    const packageMacros = [
      'SWIFT_PACKAGE=1',
      ...(packageConfiguration === 'debug' ? ['DEBUG=1'] : []),
    ]
    // objective-c settings travel with the native target. the clang wrapper
    // selects the language standard for each unit in the flattened package.
    const objc = target.files.some((file) => /\.(m|mm)$/.test(file))
    targets.push({
      ...target,
      cDefines: packageMacros,
      cxxDefines: packageMacros,
      path: target.remote ? path.posix.join(XCODE_PACKAGES_DIR, posix) : posix,
      exclude: target.exclude ?? [],
      defines: [
        'Xcode',
        ...(packageConfiguration === 'debug' ? ['DEBUG'] : []),
        ...target.packageDefines
          .filter(
            (define) =>
              define.configuration === null ||
              define.configuration === packageConfiguration,
          )
          .map((define) => define.name),
      ],
      experimentalFeatures: target.packageExperimentalFeatures
        .filter(
          (feature) =>
            feature.configuration === null ||
            feature.configuration === packageConfiguration,
        )
        .map((feature) => feature.name),
      upcomingFeatures: target.packageUpcomingFeatures
        .filter(
          (feature) =>
            feature.configuration === null ||
            feature.configuration === packageConfiguration,
        )
        .map((feature) => feature.name),
      // the flat build gives every module one package; swiftpm names each
      // module for its own package, which `@retroactive` and `package` read.
      // xcode and swiftpm build a debug package testable, so sources may
      // `@testable import` it
      swiftFlags: [
        '-package-name',
        swiftPackageIdentity(target.packageDir),
        ...(packageConfiguration === 'debug' ? ['-enable-testing'] : []),
        ...target.packageSwiftFlags
          .filter(
            (setting) =>
              setting.configuration === null ||
              setting.configuration === packageConfiguration,
          )
          .flatMap((setting) => setting.flags),
      ],
      linkedLibraries: target.packageLibraries
        .filter(
          (library) =>
            library.configuration === null ||
            library.configuration === packageConfiguration,
        )
        .map((library) => library.name),
      clangSettings: objc
        ? []
        : target.packageNativeSettings
            .filter(
              (setting) =>
                setting.configuration === null ||
                setting.configuration === packageConfiguration,
            )
            .map(({ tool, flags }): SwiftClangSetting => {
              const [flag, directory, ...rest] = flags
              return flag === '-I' && directory !== undefined && rest.length === 0
                ? {
                    tool,
                    headerSearchPath:
                      path.relative(target.dir, directory).split(path.sep).join('/') ||
                      '.',
                  }
                : { tool, flags }
            }),
    })
    if (target.resources) {
      resourceBundles.push({
        target: target.name,
        sourcePath: target.remote ? path.posix.join(XCODE_PACKAGES_DIR, posix) : posix,
        path: `${swiftPackageManifest(target.packageDir).name}_${target.name}.bundle`,
      })
    }
    if (!target.remote) files.add(path.join(target.packageDir, 'Package.swift'))
    for (const file of target.files) files.add(file)
    const catalogs = [
      ...new Set(
        target.files.flatMap((file) => {
          const at = file.indexOf(`.xcassets${path.sep}`)
          return at >= 0 ? [file.slice(0, at + '.xcassets'.length)] : []
        }),
      ),
    ].sort()
    if (catalogs.length > 0) {
      if (!target.iosDeployment)
        throw new Error(
          `${target.name}: asset symbols for a package that declares no iOS platform are unproven`,
        )
      generatedSources[
        path.posix.join(
          target.remote ? path.posix.join(XCODE_PACKAGES_DIR, posix) : posix,
          'GeneratedAssetSymbols.swift',
        )
      ] = generatePackageAssetSymbols(catalogs, target.packageDir, target.iosDeployment)
    }
    coreDataClasses(
      target.files,
      target.remote ? path.posix.join(XCODE_PACKAGES_DIR, posix) : posix,
    )
  }
  // swiftpm assigns a file to one target: a target directory nested in
  // another's is that one's exclusion
  for (const target of targets) {
    target.exclude = [
      ...target.exclude,
      ...targets
        .filter((other) => other.path.startsWith(`${target.path}/`))
        .map((other) => other.path.slice(target.path.length + 1)),
    ]
  }
  // a search path some pod xcconfigs stringify from an array embeds the
  // workspace's absolute path, which names the host: key it by the input root
  const relative = (file: string) =>
    xcodeInputKey(
      { checkouts, targetDirs },
      file,
      replaceRoot(
        path.relative(app.rootDir, file).split(path.sep).join('/'),
        app.rootDir,
        SWIFT_NATIVE_INPUT_ROOT,
      ) || '.',
    )
  const nativeInputs = await xcodeObjCInputsAsync(
    app,
    binaries,
    registered.moduleRoot ?? registered.interfaceRoot,
  )
  const nativeFiles = nativeInputs.sources
  const platformGates = registered.swiftWasm64?.platformGates ?? []
  if (platformGates.length > 0) {
    const pins = readSwiftPackagePins(app.packageResolved)
    for (const name of platformGates) {
      const gate = swiftWasm64PlatformGates[name]
      const pin = pins.get(gate.package)
      if (
        pin?.revision !== gate.revision ||
        pin.location.replace(/(?:\.git)?\/?$/, '') !== gate.repository
      )
        throw new Error(`${name} requires ${gate.repository} pinned at ${gate.revision}`)
      const dir = path.join(checkouts, gate.package)
      const target = packages.targets.find(
        (target) => target.packageDir === dir && target.name === gate.target,
      )
      const file = path.join(dir, gate.header)
      const source = target?.files.includes(file)
        ? (
            nativeFiles.get(file) ??
            readPackageFile(root, file, MAX_SWIFT_COMPILE_SOURCE_BYTES)
          ).toString('utf8')
        : null
      if (source === null || source.split(gate.before).length !== 2)
        throw new Error(`${name}: expected one upstream platform gate in ${gate.header}`)
      nativeFiles.set(file, Buffer.from(source.replace(gate.before, gate.after)))
    }
  }
  const headerAliases: SwiftHeaderAliases = {}
  for (const [file, real] of Object.entries(nativeInputs.links)) {
    const bytes = nativeFiles.get(file)!
    if (!nativeFiles.has(real)) nativeFiles.set(real, bytes)
    if (file.endsWith('.modulemap')) continue
    // header aliases retain their bytes and canonical file identity in the
    // product overlay. forwarding imports lose clang module ownership.
    if (/\.(?:h|hh|hpp|hxx|inc|inl|pch)$/.test(file)) {
      const alias = relative(file)
      const canonical = relative(real)
      if (alias !== canonical) headerAliases[alias] = canonical
      continue
    }
    nativeFiles.set(
      file,
      Buffer.from(
        `#include ${JSON.stringify(path.relative(path.dirname(file), real).split(path.sep).join('/'))}\n`,
      ),
    )
  }
  for (const file of nativeFiles.keys()) files.add(file)
  const nativeHeaders = [...nativeFiles.keys()].filter((file) =>
    /\.(?:h|hh|hpp|hxx|pch|inc|inl|modulemap)$/.test(file),
  )
  const nativePath = (file: string, directory = app.rootDir) => {
    const requested = path.resolve(directory, file)
    // module maps resolve relative headers beside the requested symlink.
    const absolute = app.moduleMapSources?.[requested] ?? requested
    return absolute === '/usr/include' || absolute.startsWith('/usr/include/')
      ? SWIFT_NATIVE_SDK_INCLUDE + absolute.slice('/usr/include'.length)
      : `${SWIFT_NATIVE_INPUT_ROOT}/${relative(absolute)}`
  }
  const nativeFlags = (flags: string[], directory = app.rootDir) =>
    xcodeNativeFlags(flags, (file) => nativePath(file, directory), directory)
  for (const target of targets) {
    const original = app.frameworks.find(
      (item) => frameworkNames.get(item) === target.name,
    )
    if (!original?.swift) continue
    const flags: string[] = []
    const ownMap = original.swift.compatibility?.moduleMap
    for (let index = 0; index < original.swift.flags.length; index++) {
      const flag = original.swift.flags[index]!
      // native preparation supplies the staged underlying module and its map.
      if (flag === '-import-underlying-module') continue
      if (
        flag === '-Xfrontend' &&
        original.swift.flags[index + 1] === '-import-underlying-module'
      ) {
        index++
        continue
      }
      if (
        ownMap &&
        flag === '-Xcc' &&
        original.swift.flags[index + 1] === `-fmodule-map-file=${ownMap}`
      ) {
        index++
        continue
      }
      flags.push(flag)
    }
    // xcode names no package unless SWIFT_PACKAGE_NAME asks, so app modules
    // share none; a named package follows among the target's flags and wins
    target.swiftFlags = [
      '-package-name',
      target.name,
      ...nativeFlags(flags),
      ...(original.swift.cxxInterop && original.swift.cxxStandard
        ? ['-Xcc', `-std=${original.swift.cxxStandard}`]
        : []),
    ]
  }
  const nativeTargets = [app, ...app.frameworks].flatMap(
    (target): SwiftNativeTarget[] => {
      if (!target.objc) return []
      const settings = target.objc
      const xcodeIndex =
        target === app ? app.frameworks.length : app.frameworks.indexOf(target)
      return [
        {
          name: frameworkNames.get(target) ?? target.moduleName,
          deploymentTarget: target.iosDeploymentTarget,
          headers: nativeHeaders.map(relative),
          publicHeaders: settings.publicHeaders.map(relative),
          flattensPublicHeaders: settings.flattensPublicHeaders,
          bridgingHeader: settings.bridgingHeader
            ? relative(settings.bridgingHeader)
            : null,
          prefixHeader: settings.prefixHeader ? relative(settings.prefixHeader) : null,
          headerSearchPaths: settings.headerSearchPaths
            .filter(
              (file) => file !== '/usr/include' && !file.startsWith('/usr/include/'),
            )
            .map(relative),
          moduleMaps: nativeInputs.targets
            .find((value) => value.xcodeIndex === xcodeIndex)!
            .moduleMaps.map((map) => ({
              module: map.module,
              headers: relative(map.headers),
            })),
          userHeaderSearchPaths: settings.userHeaderSearchPaths.map(relative),
          frameworkSearchPaths: nativeInputs.targets
            .find((value) => value.xcodeIndex === xcodeIndex)!
            .frameworks.map(relative),
          // the same prepared maps and overlay the implementation compile stages
          headerMaps: settings.headerMaps.map((map) => ({
            flag: map.flag,
            entries: map.entries.flatMap(([key, file]): [string, string][] =>
              !path.isAbsolute(file)
                ? [[key, file]]
                : nativeFiles.has(file)
                  ? [[key, nativePath(file)]]
                  : [],
            ),
          })),
          productHeaders: Object.fromEntries(
            Object.entries(settings.productHeaders).flatMap(([product, file]) =>
              nativeFiles.has(file) ? [[relative(product), relative(file)]] : [],
            ),
          ),
          flags: [
            ...nativeFlags(settings.flags),
            ...settings.headerSearchPaths
              .filter(
                (file) => file === '/usr/include' || file.startsWith('/usr/include/'),
              )
              .flatMap((file) => ['-I', nativePath(file)]),
          ],
          importerFlags: [
            ...nativeFlags(settings.importerFlags),
            ...settings.headerSearchPaths
              .filter(
                (file) => file === '/usr/include' || file.startsWith('/usr/include/'),
              )
              .flatMap((file) => ['-I', nativePath(file)]),
          ],
          cxxFlags: nativeFlags(settings.cxxFlags),
          fileFlags: Object.fromEntries([
            ...Object.entries(settings.fileFlags).map(([file, flags]) => [
              relative(file),
              nativeFlags(flags),
            ]),
            ...(frameworkNames.get(target) &&
            frameworkNames.get(target) !== target.moduleName
              ? target.allSources
                  .filter(isSwiftNativeTranslationUnit)
                  .map((file) => [
                    relative(file),
                    [
                      ...nativeFlags(settings.fileFlags[file] ?? []),
                      `-fmodule-name=${target.moduleName}`,
                    ],
                  ])
              : []),
          ]),
          sourceDirectories: Object.fromEntries(
            target.allSources
              .filter(isSwiftNativeTranslationUnit)
              .map((file) => [relative(file), relative(path.dirname(file))]),
          ),
        },
      ]
    },
  )
  for (const settings of nativeInputs.targets) {
    if (!settings.publicHeaders) continue
    const target = packages.targets.find((value) => value.name === settings.name)
    if (!target) continue
    // a SwiftPM clang target has no prefix header: SwiftPM never injects one.
    nativeTargets.push({
      name: target.name,
      deploymentTarget: settings.deploymentTarget,
      headers: nativeHeaders.map(relative),
      publicHeaders: nativeHeaders
        .filter(
          (file) =>
            file.startsWith(`${settings.publicHeaders}${path.sep}`) &&
            /\.(h|hh|hpp|hxx)$/.test(file),
        )
        .map(relative),
      flattensPublicHeaders: false,
      bridgingHeader: null,
      prefixHeader: null,
      headerSearchPaths: settings.includes.map(relative),
      moduleMaps: settings.moduleMaps.map((map) => ({
        module: map.module,
        headers: relative(map.headers),
      })),
      userHeaderSearchPaths: [],
      // xcode searches the frameworks of the binary targets the app links
      frameworkSearchPaths: settings.frameworks.map(relative),
      headerMaps: [],
      productHeaders: {},
      flags: nativeFlags(settings.flags, target.dir),
      importerFlags: nativeFlags(settings.flags, target.dir),
      cxxFlags: nativeFlags(settings.cxxFlags, target.dir),
      fileFlags: {},
      sourceDirectories: Object.fromEntries(
        settings.files.map((file) => [relative(file), relative(path.dirname(file))]),
      ),
    })
  }
  const graphTargets = [
    ...app.sourceLinkGraph.targets,
    ...frameworkTargets.flatMap((framework) => framework.sourceLinkGraph.targets),
    ...packages.sourceLinks.targets.map((target) => {
      const source = sourceFrameworks.get(target.id)
      return source
        ? { ...target, dependencies: [{ target: source.id, attributes: [] }] }
        : target
    }),
  ]
  const applicationBuildVersion = app.sourceLinkGraph.targets.find(
    (target) => target.id === app.sourceLinkGraph.entry,
  )!.buildVersion
  const binaryTargets = new Set(
    graphTargets.flatMap((target) =>
      target.productType === 'swiftpm.target.binary' ? [target.productName] : [],
    ),
  )
  const vendoredNames = new Set(
    app.binaryFrameworks
      .map((binary) => binary.name)
      .filter((name) => !binaryTargets.has(name)),
  )
  const vendoredModules = new Set(
    standins
      .filter((standin) => vendoredNames.has(standin.target))
      .map((standin) => standin.module),
  )
  for (const binary of binaries) {
    if (!vendoredNames.has(binary.target) || (!binary.rustCrate && !binary.genrule))
      continue
    vendoredModules.add(
      nativeArchiveStandins(binary.target, standins)[0]?.module ??
        swiftTargetModuleName(binary.target),
    )
  }
  return {
    app,
    appSwiftFlags: [
      '-package-name',
      app.moduleName,
      ...nativeFlags(app.swift?.flags ?? []),
    ],
    checkouts,
    targets,
    packages,
    packagePaths,
    packageFiles,
    standins,
    binaries,
    projectGaps,
    targetDirs,
    resourceBundles,
    frameworkInfoPlists,
    generatedSources,
    nativeTargets,
    staticClangTargets: [app, ...app.frameworks].flatMap((target) =>
      target.objc?.alwayslink === false
        ? [frameworkNames.get(target) ?? target.moduleName]
        : [],
    ),
    sourceLinkGraph: {
      entry: relative(app.sourceLinkGraph.entry),
      targets: graphTargets.flatMap((target) => {
        // a binary target builds from the source modules that stand in for
        // its xcframework; the first names the target, the rest link behind it.
        const standinModules =
          target.productType === 'swiftpm.target.binary'
            ? standins
                .filter((standin) => standin.target === target.productName)
                .map((standin) => standin.module)
            : []
        const original =
          target.id === app.id
            ? app
            : app.frameworks.find((framework) => framework.id === target.id)
        const products = original
          ? (packages.sourceLinks.owners.find(
              (owner) => owner.module === original.moduleName,
            )?.products ?? [])
          : []
        const packageTarget = target.productType.startsWith('swiftpm.')
        const binaryFramework =
          target.productType === 'swiftpm.target.binary'
            ? (dynamicFrameworks.get(target.productName) ?? null)
            : null
        const packageFramework =
          target.productType === 'swiftpm.library.dynamic'
            ? target.productName
            : binaryFramework
        const buildVersion = {
          platform: packageTarget
            ? applicationBuildVersion.platform
            : target.buildVersion.platform,
          minimumOS:
            target.buildVersion.minimumOS ??
            (packageTarget ? applicationBuildVersion.minimumOS : null),
          sdk: target.buildVersion.sdk ?? iosSdk.sdk,
        }
        const [first, ...rest] = standinModules
        const standinId = (module: string) => `${target.id}/#standin/${module}`
        // archives vendored by the project link into the app target itself
        const vendoredLinks = target.id === app.id ? [...vendoredModules] : []
        return [
          {
            ...target,
            id: relative(target.id),
            productName:
              packageFramework === null
                ? target.productName
                : `${packageFramework}.framework`,
            installName:
              packageFramework === null
                ? target.installName
                : `@rpath/${packageFramework}.framework/${packageFramework}`,
            machOType: binaryFramework === null ? target.machOType : 'mh_dylib',
            sourceTarget:
              target.sourceTarget === null
                ? (first ?? null)
                : original
                  ? (frameworkNames.get(original) ?? original.moduleName)
                  : target.sourceTarget,
            buildVersion,
            dependencies: [
              ...target.dependencies,
              ...products,
              ...rest.map((module) => ({ target: standinId(module), attributes: [] })),
              ...vendoredLinks.map((module) => ({
                target: standinId(module),
                attributes: [],
              })),
            ].map((link) => ({
              ...link,
              target: relative(link.target),
            })),
          },
          ...[...rest, ...vendoredLinks].map((module) => ({
            ...target,
            id: relative(standinId(module)),
            sourceTarget: module,
            productName: module,
            productType: 'swiftpm.target.binary',
            machOType: null,
            installName: null,
            buildVersion,
            linkerFlags: [],
            dependencies: [],
          })),
        ]
      }),
    },
    headerAliases,
    nativeFiles,
    files: [...files].sort(),
  }
}

// the manifest the compile reads for an xcode app: the app target and each
// framework and package target, in the forms swiftManifestTargets scans.
function xcodeManifest(layout: XcodeLayout): string {
  const nativePaths = new Map(
    [...layout.packagePaths].map(([directory, relative]) => [
      swiftPackageIdentity(directory),
      relative,
    ]),
  )
  const nativeProducts = layout.packages.nativeProducts
  const productDependency = (name: string, packageDir: string | null) => {
    if (packageDir === null) throw new Error(`unresolved package for product ${name}`)
    return `.product(name: ${JSON.stringify(name)}, package: ${JSON.stringify(swiftPackageIdentity(packageDir))})`
  }
  const dependencies = (target: SwiftPackageTarget) =>
    (target.dependencies ?? [])
      .map((dependency) =>
        dependency.kind === 'product'
          ? productDependency(dependency.name, dependency.package)
          : JSON.stringify(dependency.name),
      )
      .join(', ')
  const appProducts = layout.app.linkedProducts.flatMap(({ product, source }) => {
    const native = nativeProducts.find(
      ({ name, source: origin }) =>
        name === product &&
        (source.kind === 'unnamed' ||
          origin === (source.kind === 'remote' ? source.url : path.resolve(source.dir))),
    )
    return native ? [productDependency(native.name, native.packageDir)] : []
  })
  const sdkProducts = layout.app.sdkFrameworks
    .filter(swiftOptionalFramework)
    .map((name) => `.product(name: ${JSON.stringify(name)}, package: "sootsim-swift")`)
  const clangSettings = (target: SwiftPackageTarget) =>
    (
      [
        ['cSettings', 'c', target.cDefines],
        ['cxxSettings', 'cxx', target.cxxDefines],
      ] as const
    )
      .map(([label, tool, macros]) => {
        const entries = [
          ...(macros ?? []).map(clangMacroSetting),
          ...clangSettingEntries(target.clangSettings, tool),
        ]
        return entries.length ? `${label}: [${entries.join(', ')}], ` : ''
      })
      .join('')
  const libraries = (target: SwiftPackageTarget) =>
    target.linkedLibraries?.length
      ? `, linkerSettings: [${target.linkedLibraries.map((name) => `.linkedLibrary(${JSON.stringify(name)})`).join(', ')}]`
      : ''
  const appSwift = layout.app.swift
  const appSettings = swiftManifestSettings({
    ...layout.app,
    defines: [...layout.app.defines, SWIFT_XCODE_BUILD_CONDITION],
    cxxInterop: appSwift?.cxxInterop,
    swiftFlags: [
      ...layout.appSwiftFlags,
      ...(appSwift?.cxxInterop && appSwift.cxxStandard
        ? ['-Xcc', `-std=${appSwift.cxxStandard}`]
        : []),
    ],
  })
  return [
    '// swift-tools-version: 6.2',
    'import PackageDescription',
    `let package = Package(name: "app", platforms: [.iOS(${JSON.stringify(layout.app.iosDeploymentTarget)})], dependencies: [${[...nativePaths].map(([name, directory]) => `.package(name: ${JSON.stringify(name)}, path: ${JSON.stringify(directory)})`).join(', ')}], targets: [`,
    `  .executableTarget(name: "${layout.app.moduleName}", dependencies: [${[...appProducts, ...layout.targets.map((target) => JSON.stringify(target.name)), ...sdkProducts].join(', ')}], path: "${XCODE_APP_DIR}", ${appSettings}),`,
    ...layout.targets.map((target) =>
      target.systemLibrary
        ? `  .systemLibrary(name: "${target.name}", path: "${target.path}"),`
        : `  .target(name: "${target.name}", ${target.dependencies === undefined ? '' : `dependencies: [${dependencies(target)}], `}path: "${target.path}", ${target.exclude.length > 0 ? `exclude: ${JSON.stringify(target.exclude)}, ` : ''}${target.sources === undefined ? '' : `sources: ${JSON.stringify(target.sources)}, `}${target.resources ? 'resources: [], ' : ''}${target.publicHeadersPath === undefined ? '' : `publicHeadersPath: ${JSON.stringify(target.publicHeadersPath)}, `}${clangSettings(target)}${swiftManifestSettings(target)}${libraries(target)}),`,
    ),
    '])',
    '',
  ].join('\n')
}

// preflight the entire input tree before reading any source or resource bytes.
// a nested package is a separate compile unit; ignored build trees never enter it.
function packageFiles(root: string, includeBuildInputs = true): string[] {
  const canonicalRoot = fs.realpathSync(root)
  const source = sourceEntries().get(canonicalRoot)
  if (source) return [source]
  const xcode = xcodeLayout(canonicalRoot)
  if (!xcode) return sourceTreeFiles(canonicalRoot, canonicalRoot)
  if (includeBuildInputs)
    return [
      ...xcode.files,
      ...xcode.sourceLinkGraph.targets.flatMap((target) =>
        target.linkerFlags.flatMap((flag) => {
          const archive = xcodeArchiveSlice(canonicalRoot, flag)
          return archive ? [archive.file] : []
        }),
      ),
    ]
  const buildInputs = new Set(xcode.app.projectFiles)
  return xcode.files.filter(
    (file) =>
      !buildInputs.has(file) ||
      xcode.targetDirs.has(file) ||
      xcode.packages.targets.some((target) => target.files.includes(file)),
  )
}

// remote dependencies are enumerated from peach's checkout cache, while app
// inputs retain their selected-project boundary and all symlink checks.
function readPackageFile(root: string, file: string, maxBytes: number): Buffer {
  return readSwiftSourceFile(
    xcodeProjects().has(root) ? inputPackageRoot(root, file) : root,
    file,
    maxBytes,
  )
}

/** the package whose boundary holds an xcode project's input: its checkout or the app. */
function inputPackageRoot(root: string, file: string): string {
  const checkouts = remoteSwiftCheckouts(root)
  if (!file.startsWith(`${checkouts}${path.sep}`)) return root
  const checkout = path.relative(checkouts, file).split(path.sep)[0]
  if (!checkout || checkout === '..')
    throw new Error(`swift input escapes the selected package: ${file}`)
  return path.join(checkouts, checkout)
}

// every input file under `dir`, which must stay inside `canonicalRoot`.
function sourceTreeFiles(dir: string, canonicalRoot: string): string[] {
  const found: string[] = []
  const ancestors = new Set<string>()
  const walk = (dir: string): void => {
    const realDirectory = packageInputPath(canonicalRoot, dir)
    if (ancestors.has(realDirectory))
      throw new Error(`swift input directory cycle: ${dir}`)
    ancestors.add(realDirectory)
    for (const entry of fs
      .readdirSync(dir, { withFileTypes: true })
      .sort((left, right) => left.name.localeCompare(right.name))) {
      if (
        (entry.name.startsWith('.') &&
          entry.name !== NATIVE_DESCRIPTOR &&
          entry.name !== NATIVE_GLUE) ||
        entry.name === 'node_modules' ||
        // platform project wrappers are excluded only at the package root;
        // native target sources can contain upstream ios/android directories.
        (dir === canonicalRoot && SKIP_ROOT_DIRS.has(entry.name))
      )
        continue
      const full = path.join(dir, entry.name)
      let real: string
      try {
        real = packageInputPath(canonicalRoot, full)
      } catch (error) {
        if (
          entry.isSymbolicLink() &&
          error instanceof Error &&
          'code' in error &&
          error.code === 'ENOENT'
        )
          continue
        throw error
      }
      const stat = fs.statSync(real)
      if (stat.isDirectory()) {
        if (fs.existsSync(path.join(full, 'Package.swift'))) continue
        walk(full)
      } else if (stat.isFile()) {
        found.push(full)
      }
    }
    ancestors.delete(realDirectory)
  }
  if (fs.existsSync(dir)) walk(packageInputPath(canonicalRoot, dir))
  return found
}

function isPackageSource(file: string): boolean {
  return (
    file.endsWith('.swift') ||
    SWIFT_NATIVE_SOURCE_EXTENSIONS.some((extension) => file.endsWith(extension))
  )
}

export function sourceFiles(root: string): string[] {
  return packageFiles(root, false).filter(isPackageSource)
}

// project files and the xcconfigs their settings read are build inputs, never resources
// each target's resources Xcode copies to its bundle root: a folder
// reference keeps its tree and a catalog compiles, so neither is flat
function xcodeFlatResources(app: XcodeLayout['app'] | undefined): ReadonlySet<string> {
  if (!app) return new Set()
  return new Set(
    [app, ...app.frameworks].flatMap((target) =>
      target.resources.filter(
        (file) =>
          !Object.hasOwn(target.resourceNames, file) &&
          !file.split(path.sep).some((segment) => segment.endsWith('.xcassets')),
      ),
    ),
  )
}

// an xcode target declares its resources independently of their source
// directory; the bundle file and image enumerators use Resources as their root marker.
function bundleResourcePath(
  flatResources: ReadonlySet<string>,
  disk: string,
  file: string,
): string {
  return flatResources.has(disk) && !file.split('/').includes('Resources')
    ? `Resources/${file}`
    : file
}

function resourceCandidateFiles(root: string): string[] {
  return packageFiles(root, false).filter(
    (file) =>
      !isPackageSource(file) &&
      !file.endsWith('.xcconfig') &&
      !['project.pbxproj', 'project.xcproj', 'Package.resolved'].includes(
        path.basename(file),
      ),
  )
}

// discovery reads only the app target's catalog, before the first compile.
export function swiftProjectAppInfo(packagePath: string): {
  name: string
  icon: { bytes: Buffer; contentType: string } | null
  identity: NativeAppIdentity | null
} {
  const registered = xcodeProjects().get(packagePath)
  const app = registered
    ? readXcodeAppTargetPrepared(
        registered.xcodeproj,
        registered.target,
        registered.configuration,
        { requireSources: false, prepareGeneratedSources: true, installedPods: true },
      )
    : null
  const files = app?.resources ?? resourceCandidateFiles(packagePath)
  const catalogs = files.filter(
    (file) =>
      file.endsWith('.appiconset/Contents.json') &&
      (!app?.appIconName ||
        path.basename(path.dirname(file)) === `${app.appIconName}.appiconset`),
  )
  let icon: { bytes: Buffer; contentType: string } | null = null
  for (const contents of catalogs) {
    const value: unknown = JSON.parse(fs.readFileSync(contents, 'utf8'))
    if (
      !value ||
      typeof value !== 'object' ||
      !('images' in value) ||
      !Array.isArray(value.images)
    )
      continue
    const images: { filename: string; pixels: number }[] = []
    const entries: readonly unknown[] = value.images
    for (const image of entries) {
      if (
        !image ||
        typeof image !== 'object' ||
        !('filename' in image) ||
        typeof image.filename !== 'string' ||
        path.basename(image.filename) !== image.filename ||
        !/\.(png|jpe?g|webp)$/i.test(image.filename)
      )
        continue
      if (
        'idiom' in image &&
        (typeof image.idiom !== 'string' ||
          !['iphone', 'ios-marketing', 'universal'].includes(image.idiom))
      )
        continue
      if ('appearances' in image) continue
      const size =
        'size' in image && typeof image.size === 'string' ? parseFloat(image.size) : 0
      const scale =
        'scale' in image && typeof image.scale === 'string' ? parseFloat(image.scale) : 1
      images.push({ filename: image.filename, pixels: size * scale })
    }
    const picked = images.sort((a, b) => b.pixels - a.pixels)[0]
    if (!picked) continue
    const file = path.join(path.dirname(contents), picked.filename)
    if (!files.includes(file)) continue
    icon = {
      bytes: fs.readFileSync(file),
      contentType:
        RESOURCE_CONTENT_TYPES[path.extname(file).toLowerCase()] ?? 'image/png',
    }
    break
  }
  return {
    name:
      app?.name ??
      path.basename(sourceEntries().get(packagePath) ?? packagePath, '.swift'),
    icon,
    identity: app ? readNativeAppIdentityFromXcodeTarget(app) : null,
  }
}

// the hosted compile service caps what a project sends it; a local compile
// reads the author's own files, so nothing caps them there.
const HOSTED_LIMITS = {
  sourceBytes: MAX_SWIFT_COMPILE_SOURCE_BYTES,
  resources: MAX_SWIFT_COMPILE_RESOURCES,
  resourceBytes: MAX_SWIFT_COMPILE_RESOURCE_BYTES,
  resourceTotalBytes: MAX_SWIFT_COMPILE_RESOURCE_TOTAL_BYTES,
  images: MAX_SWIFT_COMPILE_IMAGES,
  imageBytes: MAX_SWIFT_COMPILE_IMAGE_BYTES,
  imageTotalBytes: MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES,
}
const LOCAL_LIMITS: typeof HOSTED_LIMITS = {
  sourceBytes: Infinity,
  resources: Infinity,
  resourceBytes: Infinity,
  resourceTotalBytes: Infinity,
  images: Infinity,
  imageBytes: Infinity,
  imageTotalBytes: Infinity,
}
const inputLimits = (hosted: boolean) => (hosted ? HOSTED_LIMITS : LOCAL_LIMITS)

const RESOURCE_CONTENT_TYPES: Record<string, string> = {
  '.avif': 'image/avif',
  '.bmp': 'image/bmp',
  '.gif': 'image/gif',
  '.heic': 'image/heic',
  '.heif': 'image/heif',
  '.ico': 'image/x-icon',
  '.jpeg': 'image/jpeg',
  '.jpg': 'image/jpeg',
  '.png': 'image/png',
  '.svg': 'image/svg+xml',
  '.webp': 'image/webp',
}

export interface SwiftResourceTable {
  /** each bundle's asset names to their serving urls and scales. */
  table: SwiftImageResources
  /** the same rasters as compile-address inputs. */
  images: Record<string, SwiftImageUpload>
  metalSources: Record<string, SwiftMetalLibrarySource>
  metalUploads: Record<string, string>
  /** asset-catalog color name to its value. */
  colors: Record<string, AppCatalogColor>
  symbols: Record<string, SfSymbolVector>
  /** project-relative image and color files this load's table covers (for watching). */
  watched: string[]
}

// the producer for the local vehicle: enumerate the package's bundle images
// through the shared rule both hosts use, hash each raster's bytes into its
// url (an edited photo moves its url, so no stale paint survives a reload),
// and retain immutable bytes for the serving middleware below.
export async function buildSwiftResourceTable(
  project: SwiftProject,
  baseUrl: string,
  inputs: Record<string, string>,
): Promise<SwiftResourceTable> {
  const limits = inputLimits(Boolean(project.hosted))
  const absolute = resourceCandidateFiles(project.packagePath)
  const relative = absolute.map((file) =>
    path.relative(project.packagePath, file).split(path.sep).join(path.posix.sep),
  )
  const byRelative = new Map(absolute.map((file, index) => [relative[index], file]))
  const readContents = (candidate: string): string | null => {
    const file = byRelative.get(candidate)
    // catalog json, and the glyph template a symbolset names
    if (!file || !/(^|\/)Contents\.json$|\.symbolset\/[^/]+\.svg$/.test(candidate))
      return null
    return readPackageFile(project.packagePath, file, limits.resourceBytes).toString(
      'utf8',
    )
  }
  const layout = xcodeLayout(project.packagePath)
  const bundles =
    project.resourceBundles ??
    layout?.resourceBundles ??
    swiftResourceBundles(inputs, relative)
  const catalogFiles = relative.filter((file) => {
    const disk = byRelative.get(file)
    return !disk || !layout?.targetDirs.get(disk)?.startsWith(`${XCODE_FRAMEWORKS_DIR}/`)
  })
  const flatResources = xcodeFlatResources(layout?.app)
  const bundled = new Map(
    relative.map((file) => [
      bundleResourcePath(flatResources, byRelative.get(file)!, file),
      file,
    ]),
  )
  const found = enumerateBundleImages(
    [...bundled.keys()],
    (file) => readContents(bundled.get(file) ?? file),
    (marked) => {
      const file = bundled.get(marked) ?? marked
      const disk = byRelative.get(file)
      if (!disk) throw new Error(`image source ${file} has no input file`)
      const key = layout ? xcodeInputKey(layout, disk, file) : file
      return swiftResourceBundleForFile(bundles, key)?.path ?? '.'
    },
  ).map((image) => ({ ...image, file: bundled.get(image.file) ?? image.file }))
  const catalogBundle = (file: string) => {
    const disk = byRelative.get(file)
    if (!disk) throw new Error(`catalog source ${file} has no input file`)
    const key = layout ? xcodeInputKey(layout, disk, file) : file
    return swiftResourceBundleForFile(bundles, key)?.path ?? '.'
  }
  const colors = enumerateBundleColors(catalogFiles, readContents)
  // embedded frameworks and package bundles publish their own catalog keys.
  const bundleCatalogs = Map.groupBy(relative, catalogBundle)
  bundleCatalogs.delete('.')
  for (const [bundle, files] of bundleCatalogs)
    for (const [name, color] of Object.entries(
      enumerateBundleColors(files, readContents),
    ))
      colors[`${bundle}/${name}`] = color
  const symbols = enumerateBundleSymbols(relative, readContents, catalogBundle)
  const table: SwiftImageResources = Object.create(null)
  const images: Record<string, SwiftImageUpload> = {}
  const metalSources: Record<string, SwiftMetalLibrarySource> = {}
  const metalUploads: Record<string, string> = {}
  const watched: string[] = []
  const registered = new Map<string, { bytes: Buffer; contentType: string }>()
  const shaderFiles = relative.filter((file) => file.endsWith('.metal'))
  const metalCandidates: Record<string, string> = {}
  if (inputs['Package.swift'] !== undefined)
    metalCandidates['Package.swift'] = inputs['Package.swift']
  const metalInputs = new Map<string, { file: string; disk: string }>()
  for (const file of shaderFiles) {
    const disk = byRelative.get(file)
    if (!disk) throw new Error(`metal source ${file} has no input file`)
    const key = layout ? xcodeInputKey(layout, disk, file) : file
    metalCandidates[key] = ''
    metalInputs.set(key, { file, disk })
  }
  const metalFiles = Object.keys(swiftMetalSourceFiles(metalCandidates))
  if (metalFiles.length > MAX_SWIFT_COMPILE_METAL_FILES)
    throw new Error('metal source pack exceeds the compile service file cap')
  let metalBytes = 0
  for (const key of metalFiles) {
    const input = metalInputs.get(key)
    if (!input) throw new Error(`metal source ${key} has no input file`)
    const { file, disk } = input
    const bytes = readPackageFile(
      project.packagePath,
      disk,
      MAX_SWIFT_COMPILE_METAL_BYTES,
    )
    metalBytes += bytes.length
    if (metalBytes > MAX_SWIFT_COMPILE_METAL_TOTAL_BYTES)
      throw new Error('metal source pack exceeds the compile service caps')
    const source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(
      bytes,
    )
    const sha256 = createHash('sha256').update(bytes).digest('hex')
    const bundle = swiftResourceBundleForFile(bundles, key)
    if (!bundle && inputs['Package.swift'])
      throw new Error(`metal source ${key} has no resource target bundle`)
    metalSources[key] = {
      sha256,
      url: `${baseUrl}${RESOURCE_PATH}${sha256}.metal`,
      bundlePath: bundle?.path ?? '.',
    }
    metalUploads[key] = source
    watched.push(file)
    registered.set(`${sha256}.metal`, { bytes, contentType: 'text/plain; charset=utf-8' })
  }
  const pdfs = new Map<string, { file: string; sha256: string }>()
  for (const { file } of found) {
    const disk = byRelative.get(file)
    if (!disk || path.posix.extname(file).toLowerCase() !== '.pdf' || pdfs.has(file))
      continue
    if (pdfs.size >= limits.images)
      throw new Error('swift image pack exceeds the compile service caps')
    const bytes = readPackageFile(project.packagePath, disk, limits.imageBytes)
    pdfs.set(file, {
      file: disk,
      sha256: createHash('sha256').update(bytes).digest('hex'),
    })
  }
  const pdfRasters = rasterizePdfFiles([...pdfs.values()], limits)
  let imageBytes = 0
  for (const {
    name,
    file,
    scale,
    bundlePath,
    appearance,
    renderingMode,
    fileNames,
  } of found) {
    const disk = byRelative.get(file)
    if (!disk) continue
    if (Object.keys(images).length >= limits.images) {
      throw new Error('swift image pack exceeds the compile service caps')
    }
    // a pdf imageset travels as its 3x png (actool's renditions, one file):
    // the bytes, hash, url and upload are the raster's, keyed by the pdf's
    // path so the table still resolves it. a pdf that cannot rasterize
    // throws, like actool failing the build, never a silent blank.
    let bytes: Buffer
    let ext = path.posix.extname(file).toLowerCase()
    let uploadName = path.posix.basename(file)
    const pdf = pdfs.get(file)
    if (pdf) {
      bytes = pdfRasters.get(pdf.sha256)!
      ext = '.png'
      uploadName = `${path.posix.basename(file, path.posix.extname(file))}.png`
    } else {
      if (imageBytes + fs.statSync(disk).size > limits.imageTotalBytes) {
        throw new Error('swift image pack exceeds the compile service caps')
      }
      bytes = readPackageFile(project.packagePath, disk, limits.imageBytes)
      if (ext === '.png') bytes = normalizeSwiftCatalogPng(bytes)
      if (ext === '.svg') {
        const { rasterizeSwiftCatalogSvg } = await import('peachsim/swift-svg-raster')
        bytes = Buffer.from(await rasterizeSwiftCatalogSvg(bytes, scale, file))
        ext = '.png'
        uploadName = `${path.posix.basename(file, path.posix.extname(file))}.png`
      }
    }
    if (bytes.length > limits.imageBytes)
      throw new Error(`swift image ${file} raster exceeds the per-image cap`)
    if (imageBytes + bytes.length > limits.imageTotalBytes) {
      throw new Error('swift image pack exceeds the compile service caps')
    }
    imageBytes += bytes.length
    const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16)
    const bundle = table[bundlePath] ?? Object.create(null)
    const pixelSize = ext === '.png' ? readPngDimensions(bytes) : null
    const variant = {
      uri: `${baseUrl}${RESOURCE_PATH}${hash}${ext}`,
      scale,
      ...(appearance === undefined ? {} : { appearance }),
      ...(renderingMode ? { renderingMode } : {}),
      ...(pixelSize?.width && pixelSize.height ? { pixelSize } : {}),
    }
    for (const lookup of [name, ...(fileNames ?? [])]) {
      const variants = (bundle[lookup] ??= [])
      variants.push(variant)
    }
    table[bundlePath] = bundle
    const key = layout ? xcodeInputKey(layout, disk, file) : file
    images[bundleImageRenditionKey(key, scale)] = {
      file: uploadName,
      data: bytes.toString('base64'),
    }
    watched.push(file)
    // a Contents.json edit (scale swap, file rename) re-resolves the same
    // way a raster edit does, so the catalog rides the watcher too.
    const contents = file.replace(/\/[^/]+$/, '/Contents.json')
    if (byRelative.has(contents)) watched.push(contents)
    registered.set(`${hash}${ext}`, {
      bytes,
      contentType: RESOURCE_CONTENT_TYPES[ext] ?? 'application/octet-stream',
    })
  }
  for (const bundle of Object.values(table))
    for (const variants of Object.values(bundle))
      variants.sort((a, b) => a.scale - b.scale)
  // a colorset or symbolset edit re-resolves like an imageset edit.
  for (const file of relative) {
    if (file.endsWith('.colorset/Contents.json') || file.includes('.symbolset/'))
      watched.push(file)
  }
  if (
    registered.size !== project.resourceFiles.size ||
    [...registered].some(
      ([key, value]) => !project.resourceFiles.get(key)?.bytes.equals(value.bytes),
    )
  ) {
    project.resourcesPrevious = project.resourceFiles
    project.resourceFiles = registered
  }
  return { table, images, metalSources, metalUploads, colors, symbols, watched }
}

// copied resources ride the entry module as base64 in their target bundle.
// each bundle keeps the existing shallow-first basename collision rule.
// bundle caps match the hosted compiler; oversized input refuses before reading.

export interface SwiftBundlePack {
  /** bundle-relative path to base64 bytes for the mount's /res. */
  files: Record<string, string>
  bundles: SwiftResourceBundle[]
  /** project-relative json files this load's pack covers (for watching). */
  watched: string[]
}

// the bare filenames a target's processed Info.plist declares in UIAppFonts.
// xcode copies each into the bundle root; a path spelling resolves by basename.
function declaredAppFonts(infoPlist: string): string[] {
  let parsed: unknown
  try {
    parsed = parsePlistSource(infoPlist)
  } catch {
    return []
  }
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return []
  const declared = Reflect.get(parsed, 'UIAppFonts')
  return Array.isArray(declared)
    ? declared.filter((name): name is string => typeof name === 'string')
    : []
}

export function buildSwiftBundleFiles(
  packagePath: string,
  hosted: boolean,
  inputs?: Record<string, string>,
  resourceBundles?: SwiftResourceBundle[],
): SwiftBundlePack {
  packagePath = fs.realpathSync(packagePath)
  const limits = inputLimits(hosted)
  // resourceCandidateFiles walks every non-ignored file with the nested
  // package exclusion; the shared enumeration decides namespace, order and
  // collisions, identically for every host that packs.
  const relative = resourceCandidateFiles(packagePath).map((file) =>
    path.relative(packagePath, file).split(path.sep).join(path.posix.sep),
  )
  const files: Record<string, string> = {}
  const watched: string[] = []
  let total = 0
  const xcode = xcodeLayout(packagePath)
  const bundles =
    resourceBundles ??
    xcode?.resourceBundles ??
    swiftResourceBundles(inputs ?? packageSources(packagePath, hosted), relative)
  const addFile = (key: string, bytes: Buffer) => {
    if (
      Object.keys(files).length >= limits.resources ||
      bytes.length > limits.resourceBytes ||
      total + bytes.length > limits.resourceTotalBytes
    )
      throw new Error(
        `swift bundle pack exceeds ${limits.resources} files / ${limits.resourceTotalBytes} bytes`,
      )
    files[key] = bytes.toString('base64')
    total += bytes.length
  }
  if (xcode) {
    // xcodeLayout prepares generated sources, so a null plist means the phase produced none
    if (xcode.app.infoPlist === null)
      throw new Error('swift launch Info.plist was not generated by its build phase')
    const bytes = Buffer.from(xcode.app.infoPlist)
    if (bytes.length > limits.resourceBytes || bytes.length > limits.resourceTotalBytes)
      throw new Error('swift launch Info.plist exceeds bundle resource limits')
    addFile('Info.plist', bytes)
    if (xcode.app.infoPlistFile)
      watched.push(
        path.relative(packagePath, xcode.app.infoPlistFile).split(path.sep).join('/'),
      )
    // ios registers UIAppFonts at launch from the app's own bundle. copy the
    // declarations' files wherever the target keeps them, at their bundle
    // basename, so the same bytes reach the mount and the boot runner.
    const resourcesByName = new Map(
      xcode.app.resources.map((file) => [path.basename(file), file]),
    )
    for (const declared of declaredAppFonts(xcode.app.infoPlist)) {
      const file = resourcesByName.get(path.basename(declared))
      if (!file) continue
      const relative = path.relative(packagePath, file)
      if (relative.startsWith('..') || path.isAbsolute(relative)) continue
      const key = path.basename(declared)
      if (Object.hasOwn(files, key)) continue
      addFile(key, readPackageFile(packagePath, file, limits.resourceBytes))
      watched.push(relative.split(path.sep).join('/'))
    }
  }
  const groups = new Map<string, Map<string, string>>()
  const flatResources = xcodeFlatResources(xcode?.app)
  // swiftpm copies a `.copy` resource to its bundle's top level under its own
  // name, its tree intact (isowords' Dictionaries/Words.en.db)
  const copiedRoots = (xcode?.packages.targets ?? []).flatMap(
    (target) => target.copiedResources,
  )
  for (const file of relative) {
    const disk = path.join(packagePath, ...file.split('/'))
    const folderName = xcode?.app.resourceNames[disk]
    if (folderName) {
      watched.push(file)
      addFile(folderName, readPackageFile(packagePath, disk, limits.resourceBytes))
      continue
    }
    const key = xcode ? xcodeInputKey(xcode, disk, file) : file
    const bundle = swiftResourceBundleForFile(bundles, key)
    const copiedRoot = copiedRoots.find(
      (root) => disk === root || disk.startsWith(`${root}${path.sep}`),
    )
    if (copiedRoot && bundle && bundle.path !== '.') {
      watched.push(file)
      const inner = path.relative(copiedRoot, disk).split(path.sep).join('/')
      addFile(
        `${bundle.path}/${path.basename(copiedRoot)}${inner ? `/${inner}` : ''}`,
        readPackageFile(packagePath, disk, limits.resourceBytes),
      )
      continue
    }
    const bundlePath = bundle?.path ?? '.'
    const group = groups.get(bundlePath) ?? new Map<string, string>()
    group.set(bundleResourcePath(flatResources, disk, file), disk)
    groups.set(bundlePath, group)
  }
  for (const bundle of bundles) {
    if (bundle.path === '.') continue
    addFile(
      `${bundle.path}/Info.plist`,
      Buffer.from(
        xcode?.frameworkInfoPlists.get(bundle.path) ??
          swiftResourceBundleInfoPlist(bundle),
      ),
    )
  }
  for (const product of xcode?.app.resourceProducts ?? []) {
    if ('sourceRoot' in product) {
      // cocoapods copies a vendored bundle verbatim, including its original plist.
      for (const file of product.resources) {
        const relative = path.relative(product.sourceRoot, file)
        watched.push(path.relative(packagePath, file).split(path.sep).join('/'))
        addFile(
          `${product.path}/${relative.split(path.sep).join('/')}`,
          readPackageFile(packagePath, file, limits.resourceBytes),
        )
      }
      continue
    }
    addFile(`${product.path}/Info.plist`, Buffer.from(product.infoPlist))
    const group = groups.get(product.path) ?? new Map<string, string>()
    for (const file of product.resources)
      group.set(
        // pod resources may live outside the preview package. the shared
        // enumerator flattens ordinary files and preserves localized folders.
        `Resources/${path.relative(path.parse(file).root, file).split(path.sep).join('/')}`,
        file,
      )
    groups.set(product.path, group)
  }
  for (const [bundlePath, members] of groups) {
    const prefix = bundlePath === '.' ? '' : `${bundlePath}/`
    // a package bundle's target files are its resources; the app's sit under Resources
    const models = [...members]
      .filter(([key]) => bundlePath !== '.' || key.split('/').includes('Resources'))
      .map(([, disk]) => disk)
    for (const model of coreDataModelDirectories(models)) {
      for (const disk of models.filter((file) => file.startsWith(`${model}${path.sep}`)))
        watched.push(path.relative(packagePath, disk).split(path.sep).join('/'))
      for (const [name, bytes] of Object.entries(compileCoreDataModel(model)))
        addFile(`${prefix}${name}`, bytes)
    }
    for (const { base, file } of enumerateBundleResources([...members.keys()], {
      copiedBundle: bundlePath.endsWith('.bundle'),
      copyLooseRasters: !hosted,
    })) {
      const disk = members.get(file)!
      watched.push(path.relative(packagePath, disk).split(path.sep).join('/'))
      const bytes = readPackageFile(packagePath, disk, limits.resourceBytes)
      addFile(`${prefix}${base}`, bytes)
      if (base.endsWith('.xcstrings')) {
        for (const [name, table] of Object.entries(
          compileStringCatalog(bytes.toString('utf8'), base.slice(0, -10)),
        )) {
          addFile(`${prefix}${name}`, Buffer.from(table))
        }
      }
    }
  }
  if (xcode?.app.postBundleScripts.length) {
    const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'peach-xcode-bundle-'))
    const wrapper =
      path.basename(xcode.app.settings('UNLOCALIZED_RESOURCES_FOLDER_PATH')) ||
      `${xcode.app.name}.app`
    const bundle = path.join(dir, wrapper)
    try {
      for (const [name, encoded] of Object.entries(files)) {
        const destination = path.join(bundle, name)
        fs.mkdirSync(path.dirname(destination), { recursive: true })
        fs.writeFileSync(destination, Buffer.from(encoded, 'base64'))
      }
      for (const phase of xcode.app.postBundleScripts) {
        const env: NodeJS.ProcessEnv = {
          ...process.env,
          ...phase.environment,
          BUILT_PRODUCTS_DIR: dir,
          CONFIGURATION_BUILD_DIR: dir,
          TARGET_BUILD_DIR: dir,
          DWARF_DSYM_FOLDER_PATH: dir,
          WRAPPER_NAME: wrapper,
          CONTENTS_FOLDER_PATH: wrapper,
          UNLOCALIZED_RESOURCES_FOLDER_PATH: wrapper,
          INFOPLIST_PATH: `${wrapper}/Info.plist`,
          SCRIPT_INPUT_FILE_COUNT: String(phase.inputPaths.length),
          SCRIPT_INPUT_FILE_LIST_COUNT: String(phase.inputFileListPaths.length),
          SCRIPT_OUTPUT_FILE_COUNT: '0',
          SCRIPT_OUTPUT_FILE_LIST_COUNT: '0',
        }
        const inputPath = (raw: string) => {
          const file = path.resolve(
            phase.directory,
            expandXcodeBuildSetting(raw, (key) => env[key] ?? ''),
          )
          // xcode runs an output-less phase whatever its inputs; a Debug
          // build's dwarf format leaves the dSYM inputs absent.
          if (!file.startsWith(`${dir}${path.sep}`))
            watched.push(path.relative(packagePath, file).split(path.sep).join('/'))
          return file
        }
        phase.inputPaths.forEach((raw, index) => {
          env[`SCRIPT_INPUT_FILE_${index}`] = inputPath(raw)
        })
        phase.inputFileListPaths.forEach((raw, index) => {
          const source = inputPath(raw)
          const entries = xcodeFileListEntries(source, inputPath)
          const expanded = path.join(dir, `Input-${index}.xcfilelist`)
          fs.writeFileSync(expanded, `${entries.join('\n')}\n`)
          env[`SCRIPT_INPUT_FILE_LIST_${index}`] = expanded
        })
        try {
          const [shell, ...args] = phase.command
          execFileSync(shell, args, {
            cwd: phase.directory,
            env,
            stdio: ['ignore', 'pipe', 'pipe'],
            timeout: 10 * 60 * 1000,
            maxBuffer: Infinity,
          })
        } catch (error) {
          const output =
            error instanceof Error
              ? `${error.message}\n${'stdout' in error ? String(error.stdout) : ''}${'stderr' in error ? String(error.stderr) : ''}`
              : String(error)
          throw new Error(
            `${xcode.app.name}: Run Script "${phase.name}" failed:\n${output}`,
            {
              cause: error,
            },
          )
        }
      }
      for (const key of Object.keys(files)) delete files[key]
      total = 0
      for (const entry of fs.readdirSync(bundle, {
        recursive: true,
        withFileTypes: true,
      })) {
        if (!entry.isFile()) continue
        const file = path.join(entry.parentPath, entry.name)
        const name = path.relative(bundle, file).split(path.sep).join('/')
        if (fs.statSync(file).size > limits.resourceBytes)
          throw new Error(
            `swift bundle resource ${name} exceeds ${limits.resourceBytes} bytes`,
          )
        addFile(name, fs.readFileSync(file))
      }
    } finally {
      fs.rmSync(dir, { recursive: true, force: true })
    }
  }
  return { files, bundles, watched }
}

// the middleware's lookup, exported for the producer's own proof: a hit is
// known bytes for a known hash, anything else is null, never a file.
export function serveSwiftResource(
  project: SwiftProject,
  key: string,
): { bytes: Buffer; contentType: string } | null {
  return project.resourceFiles.get(key) ?? project.resourcesPrevious.get(key) ?? null
}

// the SwiftUI module the project links: its manifest names it as a path
// dependency, and `swift build` compiles it with the project, so an edit
// there changes the artifact without moving any of the project's own mtimes.
export function linkedModuleRoots(packagePath: string): string[] {
  // an explicit private distribution wins over a linked checkout, as in resolveSwiftModule
  if (privateSwiftDistributionRoot()) return []
  packagePath = fs.realpathSync(packagePath)
  let manifest: string
  try {
    manifest = readPackageFile(
      packagePath,
      path.join(packagePath, 'Package.swift'),
      MAX_SWIFT_COMPILE_SOURCE_BYTES,
    ).toString('utf8')
  } catch {
    return []
  }
  const roots = new Set<string>()
  const dependency = /\.package\(\s*path:\s*"([^"]+)"\s*\)/g
  for (const match of manifest.replace(/^\s*\/\/.*$/gm, '').matchAll(dependency)) {
    const root = path.resolve(packagePath, match[1])
    if (fs.existsSync(path.join(root, 'Package.swift'))) roots.add(root)
  }
  return [...roots].sort()
}

function updateSwiftConfigStamp(hash: Hash, packagePath: string): void {
  if (projects().get(packagePath)?.standalone) hash.update('standalone')
  const config = xcodeProjects().get(packagePath)
  hash.update(JSON.stringify(config?.behavior ?? {}))
  const gates = config?.swiftWasm64?.platformGates
  if (gates?.length)
    hash.update(JSON.stringify(gates.map((name) => swiftWasm64PlatformGates[name])))
}

// the stamp covers every file that contributes to compileInput plus the
// linked module and toolchain release that the shared artifact hash names. a
// running dev server rebuilds only when this moves, so its input closure must
// stay identical to the artifact address's even though this cheap watcher
// signal hashes mtimes while that stable address hashes content. a checkout
// restoring byte-identical files rebuilds here and reuses the same address
// there, by design.
export function sourceStamp(
  packagePath: string,
  moduleRootOverride?: string,
  hosted = false,
): string {
  const hash = createHash('sha256')
  hash.update(packagePath)
  updateSwiftConfigStamp(hash, packagePath)
  const libraries = projects().get(packagePath)?.libraries
  if (libraries) hash.update(JSON.stringify(libraries))
  hash.update(JSON.stringify(projects().get(packagePath)?.binaryModules ?? {}))
  if (projects().get(packagePath)?.optimize) hash.update('optimize')
  if (projects().get(packagePath)?.unoptimized) hash.update('unoptimized')
  hash.update(JSON.stringify(projects().get(packagePath)?.staticClangTargets ?? []))
  hash.update(
    JSON.stringify(
      projects().get(packagePath)?.oneModule ?? !xcodeProjects().has(packagePath),
    ),
  )
  hash.update(JSON.stringify(projects().get(packagePath)?.nativeTargets ?? []))
  hash.update(JSON.stringify(projects().get(packagePath)?.headerAliases ?? {}))
  hash.update(JSON.stringify(projects().get(packagePath)?.nativeFiles ?? {}))
  hash.update(JSON.stringify(projects().get(packagePath)?.resourceBundles ?? []))
  hash.update(JSON.stringify(projects().get(packagePath)?.bundleFiles ?? null))
  const projectInputs = new Set(packageFiles(packagePath))
  for (const file of [...projectInputs].sort()) {
    hash.update(path.relative(packagePath, file))
    const stat = fs.statSync(file)
    hash.update(`${stat.mtimeMs}/${stat.ctimeMs}/${stat.size}`)
  }
  hash.update(moduleStamp(packagePath, moduleRootOverride, hosted))
  return hash.digest('hex').slice(0, 16)
}

// sourceStamp's inputs read by content and relative to the package, so
// another process's build copy of the same sources stamps the same.
export function sourceContentStamp(
  packagePath: string,
  moduleRootOverride?: string,
): string {
  const hash = createHash('sha256')
  hash.update(compilerSourceDigest)
  updateSwiftConfigStamp(hash, packagePath)
  const libraries = projects().get(packagePath)?.libraries
  if (libraries) hash.update(JSON.stringify(libraries))
  hash.update(JSON.stringify(projects().get(packagePath)?.binaryModules ?? {}))
  if (projects().get(packagePath)?.optimize) hash.update('optimize')
  if (projects().get(packagePath)?.unoptimized) hash.update('unoptimized')
  hash.update(JSON.stringify(projects().get(packagePath)?.staticClangTargets ?? []))
  hash.update(
    JSON.stringify(
      projects().get(packagePath)?.oneModule ?? !xcodeProjects().has(packagePath),
    ),
  )
  hash.update(JSON.stringify(projects().get(packagePath)?.nativeTargets ?? []))
  hash.update(JSON.stringify(projects().get(packagePath)?.headerAliases ?? {}))
  hash.update(JSON.stringify(projects().get(packagePath)?.nativeFiles ?? {}))
  hash.update(JSON.stringify(projects().get(packagePath)?.resourceBundles ?? []))
  hash.update(JSON.stringify(projects().get(packagePath)?.bundleFiles ?? null))
  // packageFiles answers canonical paths; a temporary build copy sits under a
  // linked directory on macOS, and relative to the link its names would carry
  // this process's copy directory.
  const root = fs.realpathSync(packagePath)
  for (const file of [...new Set(packageFiles(packagePath))].sort()) {
    hash.update(path.relative(root, file))
    hash.update(fs.readFileSync(file))
  }
  hash.update(moduleStamp(packagePath, moduleRootOverride, false))
  return hash.digest('hex').slice(0, 16)
}

// the linked module's part of the source stamp
function moduleStamp(
  packagePath: string,
  moduleRootOverride: string | undefined,
  hosted: boolean,
): string {
  const moduleRoot = hosted
    ? undefined
    : (moduleRootOverride ??
      linkedModuleRoots(packagePath).find((root) =>
        fs.existsSync(path.join(root, 'toolchain.json')),
      ))
  if (!moduleRoot) return ''
  const hash = createHash('sha256')
  hash.update(moduleRoot)
  for (const relative of swiftModuleInputFiles(moduleRoot)) {
    hash.update(relative)
    hash.update(String(fs.statSync(path.join(moduleRoot, relative)).mtimeMs))
  }
  return hash.digest('hex')
}

// a compile input's digest outside its source files
function otherInputs(input: SwiftCompileInput, standalone: boolean): string {
  const { files: _files, ...rest } = input
  return createHash('sha256')
    .update(JSON.stringify({ ...rest, standalone }))
    .digest('hex')
}

// the registry slot for an entry: the owning package's own name plus the
// source within it. two packages in one app can hold the same filename, and
// a bare relative path would share one slot, one instance, and its state.
// the name travels instead of the path so identical source in two checkouts
// emits the identical module; two same-named packages sharing one app still
// collide, and take the rootId override for that.
export function entryRootId(packagePath: string, file: string): string {
  const relative = path.relative(packagePath, file).split(path.sep).join(path.posix.sep)
  return `${path.basename(packagePath)}${path.posix.sep}${relative}`
}

export function swiftImageResourceUrls(
  table: Parameters<typeof resolveSwiftImageResourceUrls>[0],
  origin: string,
) {
  return resolveSwiftImageResourceUrls(table, origin)
}

export function icuUrl(origin: string, artifact: SwiftArtifact): string {
  return 'url' in artifact.icu
    ? artifact.icu.url
    : `${origin}${ICU_PATH}${swiftIcuAddress(artifact.icu)}`
}

function nativeArchiveStandins(target: string, standins: readonly SwiftStandin[]) {
  return standins.filter(
    (standin) =>
      standin.target === target &&
      !standin.prebuilt &&
      (`${standin.module}.c` in standin.files ||
        `${standin.module}.cpp` in standin.files),
  )
}

// a framework's WebAssembly library supplies the implementations its
// stand-ins would define. a supplied slice or declared build also links when
// the app's original native targets consume it through their own headers.
export function standinLibraries(
  binaries: readonly SwiftPackageBinary[],
  standins: readonly SwiftStandin[],
  rootDir: string,
  toolchain?: { moduleRoot: string; release: string },
  rustWasm64?: PeachConfig['rustWasm64'],
) {
  const linked = new Map<string, { name: string; standins: SwiftStandin[] }>()
  for (const standin of standins) {
    if (!standin.prebuilt) continue
    const bytes = Buffer.from(standin.prebuilt.library, 'base64')
    const digest = createHash('sha256').update(bytes).digest('hex')
    const dir = path.join(swiftCacheDir(), 'native-archives', digest)
    fs.mkdirSync(dir, { recursive: true })
    const library = path.join(dir, `lib${standin.module}.a`)
    if (!fs.existsSync(library)) fs.writeFileSync(library, bytes)
    linked.set(library, { name: standin.module, standins: [standin] })
  }
  for (const binary of binaries) {
    const modules = nativeArchiveStandins(binary.target, standins)
    const suppliedOnly = modules.length === 0 && !binary.rustCrate && !binary.genrule
    if (binary.placeholder || binary.moduleSources) continue
    const library = standinLibrary(binary, rootDir, toolchain, rustWasm64, suppliedOnly)
    if (!library) continue
    linked.set(library, {
      name: modules[0]?.module ?? swiftTargetModuleName(binary.target),
      standins: modules,
    })
  }
  return linked
}

function xcodeArchiveSlice(root: string, flag: string) {
  if (!path.isAbsolute(flag)) return null
  const filename = path.basename(flag)
  const name = /^lib([A-Za-z_]\w*)\.a$/.exec(filename)?.[1]
  if (!name) return null
  const parts = flag.split(path.sep)
  const target = parts.findLastIndex((part) =>
    /^(?:aarch64|x86_64)-apple-ios(?:-sim)?$/.test(part),
  )
  // a guest archive the target's search paths resolved, such as one its
  // prepare step built; an Apple-architecture archive stays unresolved.
  if (target < 0)
    return fs.existsSync(flag) && readArMembers(fs.readFileSync(flag), true).length > 0
      ? {
          name,
          file: packageInputPath(fs.realpathSync(inputPackageRoot(root, flag)), flag),
        }
      : null
  parts[target] = RUST_TARGET
  const slice = parts.join(path.sep)
  return fs.existsSync(slice) ? { name, file: packageInputPath(root, slice) } : null
}

function xcodeArchiveLinks(layout: XcodeLayout, moduleRoot: string) {
  const root = fs.realpathSync(layout.app.rootDir)
  const libraries = new Map<string, { name: string; standins: SwiftStandin[] }>()
  const names = new Set<string>()
  const targets = layout.sourceLinkGraph.targets.flatMap((target) => {
    const archives = new Map<string, SwiftSourceLinkGraph['targets'][number]>()
    for (const flag of target.linkerFlags) {
      const slice = xcodeArchiveSlice(root, flag)
      if (!slice || archives.has(flag)) continue
      const { name, file } = slice
      if (names.has(name))
        throw new Error(`Xcode archive slice has multiple source link owners: ${name}`)
      names.add(name)
      const standins = layout.app.binaryFrameworks.flatMap((binary) => {
        if (!binary.path) return []
        const map = path.join(binary.path, 'module.modulemap')
        if (!fs.existsSync(map)) return []
        const declared = [...fs.readFileSync(map, 'utf8').matchAll(/\blink\s+"([^"]+)"/g)]
        return declared.some(([, library]) => library === name)
          ? nativeArchiveStandins(binary.name, layout.standins)
          : []
      })
      libraries.set(rustStaticLibrary(file, moduleRoot), { name, standins })
      archives.set(flag, {
        id: `${target.id}/#archive/${name}`,
        sourceTarget: name,
        productName: name,
        productType: 'swiftpm.target.binary',
        installName: null,
        buildVersion: target.buildVersion,
        machOType: null,
        linkerFlags: [],
        dependencies: [],
      })
    }
    if (archives.size === 0) return [target]
    return [
      {
        ...target,
        linkerFlags: target.linkerFlags.filter((flag) => !archives.has(flag)),
        dependencies: [
          ...target.dependencies,
          ...Array.from(archives.values(), (archive) => ({
            target: archive.id,
            attributes: [],
          })),
        ],
      },
      ...archives.values(),
    ]
  })
  return { graph: { entry: layout.sourceLinkGraph.entry, targets }, libraries }
}

function packageSources(
  packagePath: string,
  hosted = false,
  linked: ReadonlySet<SwiftStandin> = new Set(),
): Record<string, string> {
  const xcode = xcodeLayout(packagePath)
  const manifests = new Set(
    xcode?.packages.targets.map((target) =>
      path.join(target.packageDir, 'Package.swift'),
    ),
  )
  const files: Record<string, string> = {}
  const limits = inputLimits(hosted)
  for (const file of sourceFiles(packagePath)) {
    const relative = path.relative(packagePath, file).split(path.sep).join(path.posix.sep)
    if (manifests.has(file) || xcode?.packageFiles.has(file)) continue
    files[xcode ? xcodeInputKey(xcode, file, relative) : relative] = (
      xcode?.nativeFiles.get(file) ??
      readPackageFile(packagePath, file, limits.sourceBytes)
    ).toString('utf8')
  }
  if (xcode) {
    for (const [file, contents] of xcode.nativeFiles)
      files[
        xcodeInputKey(
          xcode,
          file,
          path.relative(packagePath, file).split(path.sep).join('/'),
        )
      ] = contents.toString('utf8')
    files['Package.swift'] = xcodeManifest(xcode)
    Object.assign(files, xcode.generatedSources)
    for (const standin of xcode.standins)
      for (const [file, text] of Object.entries(standin.files))
        files[path.posix.join(SWIFT_STANDINS_DIR, standin.module, file)] =
          linked.has(standin) &&
          (file === `${standin.module}.c` || file === `${standin.module}.cpp`)
            ? `// ${standin.target}'s WebAssembly library defines ${standin.module}'s functions.\n`
            : text
  }
  return files
}

interface SwiftPackageSnapshot {
  nativeModules: string[]
  oneModule: boolean
  standalone: boolean
  packageFiles?: SwiftPackageFiles
  projectFiles?: Record<string, string>
  packageGuestImports?: string[]
  packageHostMacros?: string[]
  files: Record<string, string>
  nativeTargets?: SwiftNativeTarget[]
  sourceLinkGraph?: SwiftSourceLinkGraph
  headerAliases?: SwiftHeaderAliases
  defaultLocalization?: string
  entry: string
  resourcePaths: string[]
  resources: SwiftResourceTable
  bundleFiles: SwiftBundlePack
  native: SwiftNativeModules | null
  glue?: string
  libraries?: Record<string, string>
  binaryModules?: SwiftCompileInput['binaryModules']
  optimize?: boolean
  unoptimized?: boolean
  staticClangTargets?: string[]
}

async function packageSnapshot(
  project: SwiftProject,
  entry: string,
  moduleRoot?: string,
): Promise<SwiftPackageSnapshot> {
  moduleRoot ??=
    xcodeProjects().get(project.packagePath)?.moduleRoot ??
    linkedModuleRoots(project.packagePath).find((root) =>
      fs.existsSync(path.join(root, 'toolchain.json')),
    )
  const layout = xcodeLayout(project.packagePath)
  const pin = moduleRoot
    ? (swiftDistributionAt(moduleRoot) ??
      JSON.parse(fs.readFileSync(path.join(moduleRoot, 'toolchain.json'), 'utf8')))
    : null
  const xcodeArchives =
    layout && moduleRoot ? xcodeArchiveLinks(layout, moduleRoot) : null
  const packageArchives = layout
    ? [
        ...standinLibraries(
          layout.binaries,
          layout.standins,
          layout.app.rootDir,
          pin && moduleRoot ? { moduleRoot, release: pin.release } : undefined,
          xcodeProjects().get(project.packagePath)?.rustWasm64,
        ),
      ]
    : []
  const linked = [...packageArchives, ...(xcodeArchives?.libraries ?? [])]
  const headerOnlyArchives = new Set(
    packageArchives.flatMap(([, { name, standins }]) => (standins.length ? [] : [name])),
  )
  const sourceGraph = xcodeArchives?.graph ?? layout?.sourceLinkGraph
  const files = packageSources(
    project.packagePath,
    Boolean(project.hosted),
    new Set(linked.flatMap(([, { standins }]) => standins)),
  )
  Object.assign(files, project.nativeFiles)
  const native = nativeSourceDescriptor(project.packagePath)
  const limits = inputLimits(Boolean(project.hosted))
  const packageFiles: SwiftPackageFiles = {}
  const headerAliases: SwiftHeaderAliases = {
    ...layout?.headerAliases,
    ...project.headerAliases,
  }
  // checkout headers retain their original bytes and alias identity too.
  const packageReals = new Map<string, string>()
  for (const [file, relative] of layout?.packageFiles ?? [])
    if (!fs.lstatSync(file).isSymbolicLink())
      packageReals.set(fs.realpathSync(file), relative)
  for (const [file, relative] of layout?.packageFiles ?? []) {
    const real = fs.realpathSync(file)
    const target = packageReals.get(real)
    if (target !== undefined && target !== relative && /\.(?:h|hh|hpp|hxx)$/.test(file))
      headerAliases[relative] = target
    packageFiles[relative] = readPackageFile(
      project.packagePath,
      real,
      limits.sourceBytes,
    ).toString('base64')
  }
  // target members that are not sources. the builder hop receives only this
  // request, so the bytes travel at the project-relative path Xcode reads.
  const projectFiles: Record<string, string> = {}
  const packaged = new Set(layout?.packageFiles.keys() ?? [])
  if (layout && !project.hosted) {
    for (const file of layout.files) {
      if (!layout.targetDirs.has(file) || packaged.has(file)) continue
      const relative = path.relative(project.packagePath, file).split(path.sep).join('/')
      if (swiftProjectFileProblem(relative) !== undefined) continue
      const key = xcodeInputKey(layout, file, relative)
      if (files[key] !== undefined) continue
      const absolute = fs.realpathSync(file)
      // documentation catalogs and other directory members carry no
      // compilable bytes; bundled resources travel through the resource table.
      if (!fs.statSync(absolute).isFile()) continue
      projectFiles[relative] = readPackageFile(
        project.packagePath,
        absolute,
        limits.sourceBytes,
      ).toString('base64')
    }
  }
  return {
    files,
    oneModule: project.oneModule,
    standalone: project.standalone === true,
    binaryModules: {
      ...project.binaryModules,
      ...Object.fromEntries(
        (layout?.standins ?? []).flatMap((standin) =>
          standin.prebuilt ? [[standin.module, standin.prebuilt.module]] : [],
        ),
      ),
    },
    ...(Object.keys(headerAliases).length > 0 ? { headerAliases } : {}),
    nativeModules: (layout?.packages.nativePackages ?? []).flatMap(
      ({ guestTargets: targets }) =>
        targets
          .filter((target) => target.type === 'regular' || target.type === 'system')
          .map((target) => swiftTargetModuleName(target.name)),
    ),
    ...(Object.keys(projectFiles).length > 0 ? { projectFiles } : {}),
    ...(Object.keys(packageFiles).length > 0
      ? {
          packageFiles,
          packageHostMacros: [
            ...new Set(
              (layout?.packages.nativePackages ?? []).flatMap(({ manifest }) =>
                [...manifest.targets.values()]
                  .filter((target) => target.type === 'macro')
                  .map((target) => swiftTargetModuleName(target.name)),
              ),
            ),
          ].sort(),
          packageGuestImports: [
            ...new Set(
              (layout?.packages.nativePackages ?? []).flatMap(
                ({ manifest, guestTargets: targets }) =>
                  targets
                    .filter((target) => target.type === 'regular')
                    .flatMap((target) =>
                      swiftTargetFiles(manifest, target)
                        .filter((file) => file.endsWith('.swift'))
                        .flatMap((file) =>
                          swiftImportNames(fs.readFileSync(file, 'utf8')),
                        ),
                    ),
              ),
            ),
          ].sort(),
        }
      : {}),
    ...((project.nativeTargets ?? layout?.nativeTargets)?.length
      ? { nativeTargets: project.nativeTargets ?? layout?.nativeTargets }
      : {}),
    ...(layout && sourceGraph
      ? {
          sourceLinkGraph: {
            entry: sourceGraph.entry,
            targets: sourceGraph.targets.map((target) => {
              if (target.productType !== 'swiftpm.target.binary' || target.sourceTarget)
                return target
              const sourceTarget = swiftTargetModuleName(path.posix.basename(target.id))
              return headerOnlyArchives.has(sourceTarget)
                ? { ...target, sourceTarget }
                : target
            }),
          },
          defaultLocalization: layout.app.developmentRegion,
        }
      : {}),
    entry: layout
      ? xcodeInputKey(layout, path.resolve(project.packagePath, entry), entry)
      : entry,
    resourcePaths: swiftImplicitResourcePaths(
      resourceCandidateFiles(project.packagePath).map((file) => {
        const relative = path
          .relative(project.packagePath, file)
          .split(path.sep)
          .join(path.posix.sep)
        return layout ? xcodeInputKey(layout, file, relative) : relative
      }),
    ),
    resources: await buildSwiftResourceTable(project, '', files),
    bundleFiles:
      project.bundleFiles ??
      buildSwiftBundleFiles(
        project.packagePath,
        Boolean(project.hosted),
        files,
        project.resourceBundles,
      ),
    native,
    ...(project.optimize ? { optimize: true } : {}),
    ...(project.unoptimized ? { unoptimized: true } : {}),
    ...(project.staticClangTargets || layout?.staticClangTargets.length
      ? {
          staticClangTargets: [
            ...new Set([
              ...(project.staticClangTargets ?? []),
              ...(layout?.staticClangTargets ?? []),
            ]),
          ],
        }
      : {}),
    ...(linked.length > 0 || project.libraries
      ? {
          libraries: {
            ...project.libraries,
            ...Object.fromEntries(
              linked.map(([library, { name }]) => [
                name,
                fs.readFileSync(library).toString('base64'),
              ]),
            ),
          },
        }
      : {}),
    ...(native
      ? {
          glue: readPackageFile(
            project.packagePath,
            path.join(project.packagePath, NATIVE_GLUE),
            inputLimits(Boolean(project.hosted)).sourceBytes,
          ).toString('utf8'),
        }
      : {}),
  }
}

function snapshotCompileInput(snapshot: SwiftPackageSnapshot): SwiftCompileInput {
  const input: SwiftCompileInput = {
    files: snapshot.files,
    ...(snapshot.packageFiles
      ? {
          packageFiles: snapshot.packageFiles,
          packageGuestImports: snapshot.packageGuestImports,
          packageHostMacros: snapshot.packageHostMacros,
        }
      : {}),
    ...(snapshot.projectFiles ? { projectFiles: snapshot.projectFiles } : {}),
    ...(snapshot.nativeTargets ? { nativeTargets: snapshot.nativeTargets } : {}),
    ...(snapshot.sourceLinkGraph ? { sourceLinkGraph: snapshot.sourceLinkGraph } : {}),
    ...(snapshot.headerAliases ? { headerAliases: snapshot.headerAliases } : {}),
    ...(snapshot.defaultLocalization
      ? { defaultLocalization: snapshot.defaultLocalization }
      : {}),
    metalSources: snapshot.resources.metalUploads,
    resourcePaths: snapshot.resourcePaths,
    resourceBundles: snapshot.bundleFiles.bundles,
    resources: snapshot.bundleFiles.files,
    images: snapshot.resources.images,
    entry: snapshot.entry,
    oneModule: snapshot.oneModule,
    ...(snapshot.libraries ? { libraries: snapshot.libraries } : {}),
    ...(snapshot.binaryModules ? { binaryModules: snapshot.binaryModules } : {}),
    ...(snapshot.optimize ? { optimize: true } : {}),
    ...(snapshot.unoptimized ? { unoptimized: true } : {}),
    ...(snapshot.staticClangTargets
      ? { staticClangTargets: snapshot.staticClangTargets }
      : {}),
  }
  return snapshot.glue ? withNativeSourceGlue(input, snapshot.glue) : input
}

export function compileInput(
  packagePath: string,
  entry: string,
): Promise<SwiftCompileInput> {
  const project = projectFor(packagePath)
  return withXcodeLayout(project.packagePath, async () =>
    snapshotCompileInput(await packageSnapshot(project, entry)),
  )
}

export function swiftBuildRoot(packagePath: string, moduleRoot: string): string {
  if (process.env.CONTRAST_SWIFT_BUILD_ROOT) return process.env.CONTRAST_SWIFT_BUILD_ROOT
  const distribution = swiftDistributionAt(moduleRoot)
  const compilerKey = distribution
    ? `${distribution.release}\0${distribution.wasmSdkChecksum}`
    : moduleRoot
  const resolvedPath = path.resolve(packagePath)
  const parts = resolvedPath.split(path.sep)
  const scopedAt = Math.max(
    parts.lastIndexOf('peach-expo-swift'),
    parts.lastIndexOf('peach-nitro-swift'),
  )
  const buildKeyPath =
    scopedAt >= 0 && parts.length >= scopedAt + 3
      ? parts.slice(0, scopedAt + 2).join(path.sep)
      : (sourceEntries().get(resolvedPath) ?? resolvedPath)
  return path.join(
    swiftCacheDir(),
    'swift-builds',
    createHash('sha256')
      .update(`${compilerKey}\0${buildKeyPath}`)
      .digest('hex')
      .slice(0, 16),
  )
}

// the compile input of an installed workspace with the binary frameworks its
// pods and project vendor, read from one layout.
export function installedWorkspaceInput(
  packagePath: string,
  entry: string,
  moduleRoot?: string,
): Promise<{
  input: SwiftCompileInput
  binaryFrameworks: string[]
  sourcePaths: Record<string, string>
}> {
  const project = projectFor(packagePath)
  return withXcodeLayout(project.packagePath, async () => {
    const input = snapshotCompileInput(await packageSnapshot(project, entry, moduleRoot))
    const layout = xcodeLayout(fs.realpathSync(packagePath))
    const binaryFrameworks = (layout?.app.binaryFrameworks ?? []).flatMap(
      ({ path: dir }) => (dir ? [dir] : []),
    )
    const sourcePaths = Object.fromEntries(
      layout
        ? [...new Set([...layout.files, ...layout.nativeFiles.keys()])].flatMap(
            (file) => {
              const key = xcodeInputKey(
                layout,
                file,
                path.relative(packagePath, file).split(path.sep).join('/'),
              )
              return input.files[key] === undefined ? [] : [[key, file]]
            },
          )
        : [],
    )
    return { input, binaryFrameworks, sourcePaths }
  })
}

async function compile(
  packagePath: string,
  stamp: string,
  moduleRootOverride: string | undefined,
  hosted: SwiftHostedCompileOptions | undefined,
  snapshot: SwiftPackageSnapshot,
  signal?: AbortSignal,
): Promise<SwiftArtifact> {
  const resources = {
    table: snapshot.resources.table,
    colors: snapshot.resources.colors,
    symbols: snapshot.resources.symbols,
    metalSources: snapshot.resources.metalSources,
    watched: snapshot.resources.watched,
  }
  const content = {
    resources,
    bundleFiles: snapshot.bundleFiles,
    native: snapshot.native,
  }
  if (hosted)
    return {
      ...(await compileRemote(packagePath, snapshot, hosted, signal)),
      stamp,
      package: content,
    }
  // a linked checkout, else the installed distribution
  const moduleRoot =
    moduleRootOverride ??
    linkedModuleRoots(packagePath).find((root) =>
      fs.existsSync(path.join(root, 'toolchain.json')),
    ) ??
    (await swiftDistributionRoot(signal))
  const toolchain = swiftModuleToolchain(moduleRoot)
  const input = snapshotCompileInput(snapshot)
  const compiled = {
    files: input.files,
    inputs: otherInputs(input, snapshot.standalone),
    module: moduleStamp(packagePath, moduleRootOverride, false),
  }
  // targets are imported by their module names
  const parsed = compileTargets(input)
  const targets = parsed.map((target) => swiftTargetModuleName(target.name))
  // the compiler synthesizes Builtin for a file whose own target enables the
  // feature, exactly when its import compiles. longest path first, so a
  // nested target's files read its own settings.
  const byPath = [...parsed].sort((left, right) => right.path.length - left.path.length)
  const clangModulesByTarget = new Map(
    (input.nativeTargets ?? []).map(({ name, headerSearchPaths }) => [
      name,
      headerSearchPaths.flatMap((directory) => {
        const map = input.files[path.posix.join(directory, 'module.modulemap')]
        return map === undefined ? [] : moduleMapModules(map).map(({ name }) => name)
      }),
    ]),
  )
  const providedByFile = (file: string): readonly string[] => {
    const owner = byPath.find((target) =>
      target.path === '.' ? true : file.startsWith(`${target.path}/`),
    )
    if (!owner) return []
    const clangModules = clangModulesByTarget.get(owner.name) ?? []
    return owner.experimentalFeatures?.includes('BuiltinModule')
      ? [...clangModules, 'Builtin']
      : clangModules
  }
  const missing = missingSwiftModules(
    input.files,
    new Set([
      ...swiftAvailableModules(moduleRoot, toolchain.toolchainBin),
      // a project without a manifest compiles as the template's one App target
      ...(targets.length > 0 ? targets : ['App']),
      // a system target's clang module name need not match its target name
      ...swiftSystemLibrarySurface(input.files, parsed).modules,
      ...snapshot.nativeModules,
    ]),
    providedByFile,
  )
  if (missing.size > 0)
    throw new SwiftMissingModulesError(await missingModulesMessage(packagePath, missing))
  const artifact = await compileSwiftProjectUnit(input, {
    // the compile rewrites Sources/App in its root before swiftpm builds, and
    // a root lock orders every process using it, so two vites on one root
    // (a lane's dev server and a capture, or two checkouts) queue instead of
    // building each other's sources. each app and module checkout still gets
    // its own root, so they do not queue and the same app keeps its
    // incremental build across restarts.
    buildRoot: swiftBuildRoot(packagePath, moduleRoot),
    moduleRoot,
    ...toolchain,
    // the preview loads an app module beside the shared sdk image
    sdkModule:
      !snapshot.standalone &&
      (input.sourceLinkGraph !== undefined ||
        swiftApplicationEntry(input.entry, input.files[input.entry] ?? '')),
    signal,
  }).catch((error: unknown) => {
    const report = error instanceof Error ? swiftApiGapReport(error.message) : null
    throw report
      ? new Error(`${error instanceof Error ? error.message : ''}\n\n${report}`, {
          cause: error,
        })
      : error
  })
  const { module, table } = splitSwiftDyldTable(artifact.bytes)
  return {
    ...artifact,
    bytes: module,
    ...(table ? { dyldTable: table } : {}),
    stamp,
    package: content,
    compiled,
  }
}

// the compiler stops a file at its errors, so its output reads one site at a
// time. this groups every error by the api it names, so a project learns
// which symbols Peach lacks, how often and where, from one run. paths are the
// project's own: app sources lose their compile directory, a remote package
// keeps its identity.
const API_GAP_PATTERNS: [RegExp, (match: RegExpExecArray) => string][] = [
  [/^cannot find (?:type )?'([^']+)' in scope/, (match) => match[1]!],
  // a typealias reports its aliased type after `aka`, which is the api's owner
  [
    /^(?:value of )?type '([^']+)'(?: \(aka '([^']+)'\))? has no member '([^']+)'/,
    (match) =>
      `${(match[2] ?? match[1]!).replace(/^Optional<(.+)>$/, '$1').replace(/\?$/, '')}.${match[3]}`,
  ],
  [
    /^module '([^']+)' has no member named '([^']+)'/,
    (match) => `${match[1]}.${match[2]}`,
  ],
  [/^'([^']+)' is unavailable/, (match) => match[1]!],
  // an instance api Peach declares static, or the reverse
  [
    /^(?:static|instance) member '([^']+)' cannot be used on (?:instance of )?type '([^']+)'/,
    (match) => `${match[2]}.${match[1]}`,
  ],
  // an overridable api Peach declares in an extension
  [
    /^(?:non-@objc )?[\w ]+ '([^']+)' is declared in extension of '([^']+)' and cannot be overridden/,
    (match) => `${match[2]}.${match[1]}`,
  ],
  // a form of a macro Peach's expansion does not accept
  [
    /^(@\w+) requires an initial value/,
    (match) => `${match[1]} without an initial value`,
  ],
  [/^no such module '([^']+)'/, (match) => `module ${match[1]}`],
]

export function swiftApiGapReport(output: string): string | null {
  const gaps = new Map<string, { errors: number; files: Set<string> }>()
  const other = new Map<string, { errors: number; files: Set<string> }>()
  const seen = new Set<string>()
  for (const line of output.split('\n')) {
    const diagnostic = /^(\S[^:]*\.swift):(\d+):(\d+): error: (.+)$/.exec(line)
    if (!diagnostic || seen.has(line)) continue
    seen.add(line)
    const file = diagnostic[1]!
      .replace(new RegExp(`^(?:${XCODE_APP_DIR}|${XCODE_FRAMEWORKS_DIR}/[^/]+)/`), '')
      .replace(new RegExp(`^${XCODE_PACKAGES_DIR}/`), '')
    const message = diagnostic[4]!.trim()
    const rule = API_GAP_PATTERNS.find(([pattern]) => pattern.test(message))
    const key = rule ? rule[1](rule[0].exec(message)!) : message
    const table = rule ? gaps : other
    const entry = table.get(key) ?? { errors: 0, files: new Set<string>() }
    entry.errors++
    entry.files.add(file)
    table.set(key, entry)
  }
  if (gaps.size === 0) return null
  const rows = (table: typeof gaps) => {
    const sorted = [...table].sort(
      ([left, a], [right, b]) => b.errors - a.errors || left.localeCompare(right),
    )
    const width = Math.min(48, Math.max(...sorted.map(([key]) => key.length)))
    return sorted.map(
      ([key, entry]) =>
        `  ${key.padEnd(width)}  ${String(entry.errors).padStart(3)} error${entry.errors === 1 ? ' ' : 's'}  ${[...entry.files].sort().join(', ')}`,
    )
  }
  const errors = [...gaps.values()].reduce((sum, entry) => sum + entry.errors, 0)
  return [
    `Peach lacks ${gaps.size} API${gaps.size === 1 ? '' : 's'} this app uses (${errors} error${errors === 1 ? '' : 's'}):`,
    ...rows(gaps),
    ...(other.size > 0
      ? ['other errors, often caused by the ones above:', ...rows(other)]
      : []),
  ].join('\n')
}

// the frameworks the iOS simulator SDK ships, so a report can say which
// missing modules are Apple's on any host, linux included. regenerated by
// scripts/ios-sdk-frameworks.ts.
const IOS_SDK_FRAMEWORKS = new Set(iosSdk.frameworks)

// one report of every module the app imports that Peach lacks, so a project
// learns its whole gap from one run instead of one compile error at a time.
async function missingModulesMessage(
  packagePath: string,
  missing: Map<string, string[]>,
): Promise<string> {
  const layout = xcodeLayout(packagePath)
  const gaps = new Map<string, SwiftPackageGap>([
    ...(layout?.app.binaryFrameworks ?? []).map(({ name }) => {
      const gap = layout?.projectGaps.get(name)
      return [
        name,
        {
          source: 'the project',
          reason: `a vendored binary framework${gap ? `; no stand-in: ${gap}` : ''}`,
        },
      ] as const
    }),
    ...[...missing.keys()].flatMap((name) =>
      IOS_SDK_FRAMEWORKS.has(name)
        ? [
            [
              name,
              { source: 'the iOS SDK', reason: 'a framework Peach does not provide' },
            ] as const,
          ]
        : [],
    ),
    ...(layout?.packages.modules ?? []),
    ...(layout?.packages.unavailable ?? []),
  ])
  // a binary target's archive names the modules it ships, which a target's
  // reason cannot: a wrapper product depends on many binaries, and a module
  // such as FirebaseCore ships inside _FirebaseCore with no target of its
  // own. the archives are read only for a module the sdk does not explain.
  const packaged = new Set(
    [...missing.keys()].filter((name) => !IOS_SDK_FRAMEWORKS.has(name)),
  )
  if (packaged.size > 0)
    await Promise.all(
      (layout?.packages.binaries ?? [])
        .filter((binary) => binary.reached)
        .map(async (binary) => {
          // archive inspection may fail without hiding the selected target's reason.
          const modules = await swiftBinaryModules(binary).catch(() => [])
          for (const name of modules)
            if (packaged.has(name))
              gaps.set(name, {
                source: binary.source,
                reason:
                  layout?.packages.modules.get(binary.target)?.reason ??
                  `${binary.target} is a binary framework`,
              })
        }),
    )
  const width = Math.max(...[...missing.keys()].map((name) => name.length))
  const opened = xcodeProjects().get(packagePath)?.xcodeproj
  const workspace = opened?.endsWith('.xcodeproj')
    ? enclosingXcodeWorkspace(opened)
    : null
  return [
    `Peach does not provide ${missing.size} module${missing.size === 1 ? '' : 's'} this app imports:`,
    ...[...missing].map(([name, files]) => {
      const gap = gaps.get(name)
      return `  ${name.padEnd(width)}  ${files.length} file${files.length === 1 ? '' : 's'}${gap ? `, ${gap.source.includes('://') ? `package ${gap.source}` : gap.source.startsWith('/') ? `package ${path.relative(packagePath, gap.source) || '.'}` : gap.source} (${gap.reason})` : ''}`
    }),
    ...(workspace
      ? [
          `${path.basename(opened!)} is part of ${path.relative(process.cwd(), workspace)}, which holds its local packages and Package.resolved pins; pass the workspace to build what Xcode builds there.`,
        ]
      : []),
  ].join('\n')
}

// a hosted compile (`peach open --upload-source`) compiles the package where
// a Contrast project's compiles: Contrast's compile route, authorized by
// `peach login` or PEACH_API_KEY. the service renders the
// native dispatch glue itself under the package's id and answers the wasm at a
// public content address, which is fetched once and served from this dev
// server like a local build. resource bytes share the compile snapshot and
// immutable local asset addresses.
async function compileRemote(
  packagePath: string,
  snapshot: SwiftPackageSnapshot,
  hosted: SwiftHostedCompileOptions,
  ownerSignal?: AbortSignal,
): Promise<Omit<SwiftArtifact, 'stamp' | 'package'>> {
  const { origin, authorization } = hosted
  const signal = AbortSignal.any([
    ...(ownerSignal ? [ownerSignal] : []),
    AbortSignal.timeout(DEFAULT_SWIFT_COMPILE_BUILD_MS + 60_000),
  ])
  const submit = httpSwiftCompileSubmit({
    endpoint: origin,
    authorization,
    signal,
  })
  if (!submit) throw new Error('swift compile: no credential to submit with')
  const sources = Object.values(snapshot.files)
  const packageSources = Object.values(snapshot.packageFiles ?? {})
  const count = sources.length + packageSources.length
  const bytes =
    sources.reduce((total, text) => total + Buffer.byteLength(text), 0) +
    packageSources.reduce((total, encoded) => total + swiftPackageInputBytes(encoded), 0)
  if (count > MAX_SWIFT_COMPILE_FILES || bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES) {
    throw new Error(
      `${path.basename(packagePath)} has ${count} input files (${bytes} bytes; packages: ${swiftPackageInputNames(snapshot.packageFiles).join(', ') || 'none'}), over Contrast's compile limits of ${MAX_SWIFT_COMPILE_FILES} files and ${MAX_SWIFT_COMPILE_SOURCE_BYTES} bytes; compile it on this machine with the Swift distribution instead`,
    )
  }
  const descriptor = snapshot.native
  const address = await compileSwiftProject(
    submit,
    {
      files: snapshot.files,
      ...(snapshot.packageFiles
        ? {
            packageFiles: snapshot.packageFiles,
            packageGuestImports: snapshot.packageGuestImports,
            packageHostMacros: snapshot.packageHostMacros,
          }
        : {}),
      ...(snapshot.nativeTargets ? { nativeTargets: snapshot.nativeTargets } : {}),
      ...(snapshot.sourceLinkGraph ? { sourceLinkGraph: snapshot.sourceLinkGraph } : {}),
      ...(snapshot.headerAliases ? { headerAliases: snapshot.headerAliases } : {}),
      ...(snapshot.defaultLocalization
        ? { defaultLocalization: snapshot.defaultLocalization }
        : {}),
      metalSources: snapshot.resources.metalUploads,
      resourcePaths: snapshot.resourcePaths,
      resourceBundles: snapshot.bundleFiles.bundles,
      resources: snapshot.bundleFiles.files,
      images: snapshot.resources.images,
      entry: snapshot.entry,
      packageId: descriptor?.packageId ?? swiftPackageId(packagePath),
      sdkModule: !snapshot.standalone,
    },
    origin,
    signal,
    (stage) => console.error(`Peach: compiling ${path.basename(packagePath)}: ${stage}`),
  )
  // the app's JS calls with the hash its own `one typegen` wrote; glue the
  // service rendered from another One would reject every call as stale.
  if (descriptor && address.native?.hash !== descriptor.hash) {
    throw new Error(
      `${path.basename(packagePath)}: Contrast compiled native contract ${address.native?.hash ?? 'none'} but one typegen wrote ${descriptor.hash}; the app's One and the compile host's differ, or the compile host is older than this peachsim`,
    )
  }
  const response = await fetch(address.url, { signal })
  if (!response.ok) {
    throw new Error(`swift compile: ${address.url} answered ${response.status}`)
  }
  const maxArtifactBytes = 64 * 1024 * 1024
  if (
    Number(response.headers.get('content-length')) > maxArtifactBytes ||
    !response.body
  ) {
    throw new Error('swift compile: artifact exceeds 64 MiB or has no body')
  }
  const reader = response.body.getReader()
  const chunks: Uint8Array[] = []
  let total = 0
  for (;;) {
    signal.throwIfAborted()
    const next = await reader.read()
    if (next.done) break
    total += next.value.byteLength
    if (total > maxArtifactBytes) {
      await reader.cancel()
      throw new Error('swift compile: artifact exceeds 64 MiB')
    }
    chunks.push(next.value)
  }
  const module = Buffer.concat(chunks)
  return {
    hash: address.hash,
    bytes: module,
    ...(await fetchSwiftDyldTable(address.url, module, signal)),
    icu: { url: address.icuUrl },
    hostedSdk: isSwiftSdkEntryAssets(address)
      ? { sdkUrl: address.sdkUrl, sdkBindingUrl: address.sdkBindingUrl }
      : undefined,
  }
}

// a published module names its dlsym packs by digest beside it; the host serves both.
async function fetchSwiftDyldTable(
  moduleUrl: string,
  module: Buffer,
  signal: AbortSignal,
): Promise<Pick<SwiftArtifact, 'dyldTable'>> {
  const url = new URL(moduleUrl)
  const table = swiftDyldTableReference(url.pathname, module)
  if (!table) return {}
  const { sha256, byteLength } = table
  url.pathname = table.path
  const response = await fetch(url, { signal })
  if (!response.ok) throw new Error(`swift compile: ${url} answered ${response.status}`)
  const bytes = Buffer.from(await response.arrayBuffer())
  if (
    bytes.length !== byteLength ||
    createHash('sha256').update(bytes).digest('hex') !== sha256
  )
    throw new Error(`swift compile: ${url} does not match its module's index`)
  return { dyldTable: { sha256, bytes } }
}

// the stamp reads the project layout, which builds async.
function currentStamp(project: SwiftProject, moduleRoot: string | undefined) {
  return withXcodeLayout(project.packagePath, () =>
    sourceStamp(project.packagePath, moduleRoot, Boolean(project.hosted)),
  )
}

// one layout scope per call: the build, its stamps and the compile read the
// layout prepared at the start, and a later call prepares its own.
export function artifactFor(
  project: SwiftProject,
  entry: string,
  moduleRoot?: string,
  signal: AbortSignal | undefined = project.signal,
): Promise<SwiftArtifact> {
  return withXcodeLayout(project.packagePath, () =>
    scopedArtifact(project, entry, moduleRoot, signal),
  )
}

function scopedArtifact(
  project: SwiftProject,
  entry: string,
  moduleRoot: string | undefined,
  signal: AbortSignal | undefined,
): Promise<SwiftArtifact> {
  if (project.signal && signal !== project.signal)
    signal = signal ? AbortSignal.any([project.signal, signal]) : project.signal
  signal?.throwIfAborted()
  const stamp = sourceStamp(project.packagePath, moduleRoot, Boolean(project.hosted))
  if (project.artifact?.stamp === stamp) return Promise.resolve(project.artifact)
  if (project.building) {
    // a second edit during a build: the build in flight was started from
    // older sources, so its artifact is not the answer for these. wait it out
    // and ask again, which starts the build these sources need; joining it
    // would emit the older artifact and nothing would trigger another load.
    const running = project.building
    if (running.stamp === stamp && running.signal === signal) return running.promise
    const again = () => artifactFor(project, entry, moduleRoot, signal)
    const queued = running.promise.then(again, again)
    if (!signal) return queued
    return new Promise<SwiftArtifact>((resolve, reject) => {
      const stop = () =>
        reject(
          signal.reason instanceof Error
            ? signal.reason
            : new Error('Swift compilation canceled', { cause: signal.reason }),
        )
      signal.addEventListener('abort', stop, { once: true })
      if (signal.aborted) stop()
      queued
        .then(resolve, reject)
        .finally(() => signal.removeEventListener('abort', stop))
    })
  }
  const promise = packageSnapshot(project, entry, moduleRoot)
    .then((snapshot) => {
      // a save that changed only view builder literals keeps the running bytes
      const compiled = project.artifact?.compiled
      if (
        project.artifact &&
        compiled &&
        compiled.module === moduleStamp(project.packagePath, moduleRoot, false)
      ) {
        const input = snapshotCompileInput(snapshot)
        const values =
          otherInputs(input, snapshot.standalone) === compiled.inputs
            ? designTimeValues(compiled.files, input.files)
            : null
        if (values) return { ...project.artifact, stamp, designTimeValues: values }
      }
      return compile(
        project.packagePath,
        stamp,
        moduleRoot,
        project.hosted,
        snapshot,
        signal,
      )
    })
    .then(
      (artifact) => {
        project.artifact = artifact
        project.artifacts = [
          artifact,
          ...project.artifacts.filter((old) => old.hash !== artifact.hash),
        ].slice(0, 2)
        project.building = null
        return artifact
      },
      (error: unknown) => {
        project.building = null
        throw error
      },
    )
  const fresh = promise.then(async (artifact) =>
    (await currentStamp(project, moduleRoot)) === artifact.stamp
      ? artifact
      : artifactFor(project, entry, moduleRoot, signal),
  )
  project.building = { stamp, promise: fresh, signal }
  return fresh
}

export async function swiftPackageWatchFiles(
  packagePath: string,
  moduleRoot: string | undefined,
): Promise<string[]> {
  packagePath = fs.realpathSync(packagePath)
  return withXcodeLayout(packagePath, () => [
    ...(xcodeProjects().has(packagePath) || sourceEntries().has(packagePath)
      ? []
      : [path.join(packagePath, 'Package.swift')]),
    ...packageFiles(packagePath),
    ...nativeSourceFiles(packagePath),
    ...(moduleRoot
      ? swiftModuleInputFiles(moduleRoot).map((file) => path.join(moduleRoot, file))
      : []),
  ])
}

export async function swiftPackageMetadata(
  packagePath: string,
  packageName: string,
  moduleRoot: string | undefined,
  origin: string,
  hosted?: SwiftHostedCompileOptions,
  signal?: AbortSignal,
  startupEnvironment: readonly string[] = [],
  startupRuntimeUrl?: URL,
  startupGuest?: SwiftStartupLaunch['guest'],
  startupArguments: readonly string[] = [],
): Promise<SwiftEntryModuleArgs> {
  packagePath = fs.realpathSync(packagePath)
  const project = projectFor(packagePath, hosted, signal)
  const limits = inputLimits(Boolean(project.hosted))
  // an xcode project runs its selected application target: the entry is one
  // of the target's own sources, swift or c-family, never a framework,
  // package or sibling target's @main elsewhere in the inputs. a plain
  // package scans its tree.
  const registered = xcodeProjects().get(packagePath)
  const app = registered
    ? readXcodeAppTargetPrepared(
        registered.xcodeproj,
        registered.target,
        registered.configuration,
        { prepareGeneratedSources: true, installedPods: true },
      )
    : null
  const candidates = app
    ? [...app.sources, ...app.allSources.filter(isSwiftNativeTranslationUnit)]
    : sourceFiles(packagePath).filter((file) => file.endsWith('.swift'))
  // the preprocessor names xcode compiles each c-family unit with: the
  // target's -D flags, the c++ ones for c++ units, and the file's own.
  const cDefines = (file: string): Map<string, string | undefined> => {
    const defines = new Map<string, string | undefined>()
    const cxx = isSwiftCxxTranslationUnit(file, app?.objc?.fileFlags[file])
    for (const flag of [
      ...(app?.objc?.flags ?? []),
      ...(cxx ? (app?.objc?.cxxFlags ?? []) : []),
      ...(app?.objc?.fileFlags[file] ?? []),
    ]) {
      const define = /^-D([^=]+)(?:=(.*))?$/.exec(flag)
      if (define) defines.set(define[1]!, define[2])
      const undef = /^-U(.+)$/.exec(flag)
      if (undef) defines.delete(undef[1]!)
    }
    return defines
  }
  // names any of the target's own c-family sources, headers or prefix
  // header defines, read once. like the candidate reads below, a member
  // that cannot be read fails the scan instead of silently deciding false.
  let targetDefined: Set<string> | null = null
  const definedNames = (): Set<string> => {
    if (targetDefined) return targetDefined
    const texts = [
      ...candidates.filter((file) => !file.endsWith('.swift')),
      ...(app?.objc?.headers ?? []),
      ...(app?.objc?.prefixHeader ? [app.objc.prefixHeader] : []),
    ].map((file) =>
      readPackageFile(packagePath, file, limits.sourceBytes).toString('utf8'),
    )
    targetDefined = swiftCDefinedNames(texts)
    return targetDefined
  }
  const cLanguage = (file: string): 'c' | 'c++' | 'objective-c' | 'objective-c++' => {
    const cxx = isSwiftCxxTranslationUnit(file, app?.objc?.fileFlags[file])
    if (/\.mm?$/.test(file)) return cxx ? 'objective-c++' : 'objective-c'
    return cxx ? 'c++' : 'c'
  }
  const mains = candidates.filter((file) => {
    const contents = readPackageFile(packagePath, file, limits.sourceBytes).toString(
      'utf8',
    )
    return file.endsWith('.swift')
      ? swiftApplicationEntry(file, contents)
      : swiftCMainEntry(file, contents, {
          defines: cDefines(file),
          predefines: swiftCPredefines(cLanguage(file)),
          targetDefined: definedNames(),
        })
  })
  const native = nativeSourceDescriptor(packagePath)
  if (mains.length > 1 || (mains.length === 0 && !native)) {
    throw new Error(
      `swift package ${packageName} needs exactly one application entry source or generated native modules; found ${mains.length}`,
    )
  }
  const entry =
    mains.length === 1
      ? path.relative(packagePath, mains[0]).split(path.sep).join(path.posix.sep)
      : Object.entries(native?.files ?? {}).find(
          ([_file, names]) => names.length > 0,
        )?.[0]
  if (!entry) throw new Error(`swift package ${packageName} has no native module source`)
  const artifact = await artifactFor(project, entry, moduleRoot)
  const resources = artifact.package.resources
  const bundleFiles = artifact.package.bundleFiles
  const metadata = (
    origin: string,
    image: SwiftArtifact,
    sdkDigest?: string,
  ): SwiftEntryModuleArgs => ({
    url: `${origin}${ARTIFACT_PATH}${image.hash}.wasm`,
    ...swiftSdkEntryAssets(origin, image, sdkDigest),
    ...swiftCodePartAssets(origin, image.parts, sdkDigest),
    hash: image.hash,
    icuUrl: icuUrl(origin, image),
    rootId: `${packageName}/${entry}`,
    resources: resolveSwiftImageResourceUrls(resources.table, origin),
    bundleFiles: bundleFiles.files,
    ...(Object.keys(resources.metalSources).length === 0
      ? {}
      : {
          metalSources: Object.fromEntries(
            Object.entries(resources.metalSources).map(([file, source]) => [
              file,
              { ...source, url: `${origin}${source.url}` },
            ]),
          ),
        }),
    colors: resources.colors,
    symbols: resources.symbols,
    designTimeValues: artifact.designTimeValues ?? {},
    native: artifact.package.native
      ? {
          packageId: artifact.package.native.packageId,
          contractHash: artifact.package.native.hash,
          modules: artifact.package.native.modules,
          views: Object.keys(artifact.package.native.views),
          defaultView: mains.length === 1,
        }
      : undefined,
  })
  if (mains.length === 0) return metadata(origin, artifact)
  const publishedSdk = artifact.sdk && publishedSwiftSdk(artifact.sdk.sha256)
  const sdkDigest =
    artifact.sdk && !publishedSdk
      ? await swiftSdkStartup(
          artifact.sdk,
          packagePath,
          artifact.hash,
          (profileOrigin) => metadata(profileOrigin, artifact),
          {
            environment: startupEnvironment,
            arguments: startupArguments,
            guest: startupGuest,
          },
          startupRuntimeUrl,
        )
      : undefined
  if (artifact.sdk && sdkDigest) {
    const plan = sdkStartupPlans.get(sdkDigest)
    if (plan) await splitSdkBinding(artifact.sdk, sdkDigest, plan)
  } else if (artifact.sdk && publishedSdk?.dataPlan) {
    const { fetchSwiftSdkDataPlan } = await import('./swift-sdk-later-data')
    const plan = await fetchSwiftSdkDataPlan(publishedSdk)
    if (plan) await splitSdkBinding(artifact.sdk, publishedSdk.dataPlan, plan)
  }
  if (artifact.hostedSdk || publishedSdk || sdkDigest) {
    // the startup splitter moves code; guest image tables can dwarf a small app.
    const code = wasmSections(artifact.bytes).find(({ id }) => id === 10)
    if (code && code.end - code.start < 1024 * 1024)
      return metadata(origin, artifact, sdkDigest)
  }
  let profiles = startupImages.get(artifact)
  if (!profiles) {
    profiles = new Map()
    startupImages.set(artifact, profiles)
  }
  const key = JSON.stringify([
    startupEnvironment,
    startupRuntimeUrl?.origin,
    startupGuest,
    startupArguments,
  ])
  let startup = profiles.get(key)
  if (!startup) {
    startup = (async () => {
      const runtimeRoot = startupRuntimeUrl ?? resolveActiveRuntimeRoot()
      if (!runtimeRoot)
        throw new Error('cannot profile Swift startup without the engine runtime')
      const { splitSwiftApp } = await import('./swift-startup-split')
      const result = await splitSwiftApp(artifact.bytes, {
        runtimeRoot,
        artifactHash: artifact.hash,
        environment: startupEnvironment,
        arguments: startupArguments,
        guest: startupGuest,
        metadata: (profileOrigin) => metadata(profileOrigin, artifact, sdkDigest),
        serveAsset: serveSwiftPackageAsset,
      })
      const image: SwiftArtifact = {
        ...artifact,
        hash: createHash('sha256').update(result.primary).digest('hex'),
        bytes: result.primary,
        parts: result.parts,
      }
      project.artifacts = [
        image,
        ...project.artifacts.filter((old) => old.hash !== image.hash),
      ].slice(0, 3)
      return image
    })()
    const pending = startup
    profiles.set(key, pending)
    pending.catch(() => profiles.delete(key))
  }
  return metadata(origin, await startup, sdkDigest)
}

// cross-request-promise: the swift host runs only in node (cli, dev server), never a worker
const sdkStartups = new Map<string, { artifactHash: string; startup: Promise<string> }>()
const sdkStartupParts = new Map<string, ReadonlyMap<string, Buffer>>()
const sdkStartupPlans = new Map<string, Buffer>()
const sdkPieces = new Map<string, Buffer>()
// an app's binding beside a served split, by binding and primary digest, and the files they name
const sdkSplitBindings = new Map<string, string>()
const sdkBindingFiles = new Map<string, Buffer>()

async function splitSdkBinding(sdk: SwiftSdkModuleAsset, splitKey: string, plan: Buffer) {
  const key = `${sdk.binding.sha256}:${splitKey}`
  if (sdkSplitBindings.has(key)) return
  const [{ splitSwiftSdkLaterData }, { swiftSdkImageFile }] = await Promise.all([
    import('./swift-sdk-later-data'),
    import('./swift-sdk-image'),
  ])
  const split = splitSwiftSdkLaterData(
    path.dirname(swiftSdkImageFile(sdk.key)),
    sdk.binding.bytes,
    plan,
  )
  const digest = createHash('sha256').update(split.binding).digest('hex')
  sdkBindingFiles.set(digest, split.binding)
  for (const later of split.later)
    sdkBindingFiles.set(createHash('sha256').update(later).digest('hex'), later)
  sdkSplitBindings.set(key, digest)
}

const servedSdkBinding = (sdk: SwiftSdkModuleAsset, sdkDigest?: string) =>
  (sdkDigest && sdkSplitBindings.get(`${sdk.binding.sha256}:${sdkDigest}`)) ||
  sdk.binding.sha256

function swiftCodePartAssets(
  origin: string,
  appParts: SwiftArtifact['parts'],
  sdkDigest?: string,
): Pick<SwiftEntryModuleArgs, 'codePartUrls'> {
  const sdkParts = sdkDigest === undefined ? undefined : sdkStartupParts.get(sdkDigest)
  const codePartUrls = [
    ...Array.from(
      appParts?.keys() ?? [],
      (digest) => `${origin}${ARTIFACT_PATH}${digest}.wasm`,
    ),
    ...Array.from(
      sdkParts?.keys() ?? [],
      (digest) => `${origin}${SDK_PATH}${digest}.wasm`,
    ),
  ]
  return codePartUrls.length ? { codePartUrls } : {}
}

export function swiftSdkEntryAssets(
  origin: string,
  image: SwiftArtifact,
  sdkDigest = image.sdk?.sha256,
) {
  if (image.hostedSdk) return image.hostedSdk
  if (!image.sdk) return {}
  const published = publishedSwiftSdk(image.sdk.sha256)
  return {
    sdkUrl: published?.url ?? `${origin}${SDK_PATH}${sdkDigest}.wasm`,
    sdkBindingUrl: `${origin}${SDK_BINDING_PATH}${servedSdkBinding(image.sdk, published?.dataPlan ?? sdkDigest)}.bin`,
  }
}

// each app opened on an sdk image profiles its startup once; the split serves them all
function swiftSdkStartup(
  sdk: SwiftSdkModuleAsset,
  packagePath: string,
  artifactHash: string,
  metadata: SwiftStartupLaunch['metadata'],
  launch: Pick<SwiftStartupLaunch, 'environment' | 'arguments' | 'guest'>,
  runtimeRootOverride?: URL,
) {
  const { key } = sdk
  const app = createHash('sha256')
    .update(
      JSON.stringify([
        packagePath,
        launch.environment,
        runtimeRootOverride?.origin,
        ...(launch.arguments?.length ? [launch.arguments] : []),
      ]),
    )
    .update(launch.guest?.source ?? '')
    .digest('hex')
    .slice(0, 16)
  const cacheKey = `${key}/${app}`
  const cached = sdkStartups.get(cacheKey)
  if (cached?.artifactHash === artifactHash) return cached.startup
  const startup = (async () => {
    const runtimeRoot = runtimeRootOverride ?? resolveActiveRuntimeRoot()
    if (!runtimeRoot)
      throw new Error('cannot profile Swift startup without the engine runtime')
    const [{ splitSwiftSdkImage }, { swiftSdkImageFile }] = await Promise.all([
      import('./swift-startup-split'),
      import('./swift-sdk-image'),
    ])
    const file = swiftSdkImageFile(key)
    const split = await splitSwiftSdkImage(
      await fs.promises.readFile(file),
      path.dirname(file),
      {
        ...launch,
        runtimeRoot,
        artifactHash,
        metadata,
        serveAsset: serveSwiftPackageAsset,
      },
      app,
    )
    const name = createHash('sha256').update(split.primary).digest('hex')
    sdkPieces.set(name, split.primary)
    for (const [digest, bytes] of split.parts) sdkPieces.set(digest, bytes)
    sdkStartupParts.set(name, split.parts)
    if (split.dataPlan) sdkStartupPlans.set(name, split.dataPlan)
    return name
  })()
  startup.catch(() => {
    if (sdkStartups.get(cacheKey)?.startup === startup) sdkStartups.delete(cacheKey)
  })
  sdkStartups.set(cacheKey, { artifactHash, startup })
  return startup
}

// a content-addressed file the tenant reads by range: the index first, then one pack at a time.
function endImmutableRanges(res: ServerResponse, bytes: Buffer) {
  res.setHeader('access-control-allow-origin', '*')
  res.setHeader('cache-control', 'public, max-age=31536000, immutable')
  res.setHeader('content-type', 'application/octet-stream')
  res.setHeader('accept-ranges', 'bytes')
  const range = /^bytes=(\d+)-(\d+)$/.exec(res.req?.headers.range ?? '')
  if (!range) {
    res.end(bytes)
    return
  }
  const start = Number(range[1])
  const end = Math.min(Number(range[2]), bytes.length - 1)
  if (start > end) {
    res.statusCode = 416
    res.setHeader('content-range', `bytes */${bytes.length}`)
    res.end()
    return
  }
  res.statusCode = 206
  res.setHeader('content-range', `bytes ${start}-${end}/${bytes.length}`)
  res.end(bytes.subarray(start, end + 1))
}

export function swiftArtifactIsAvailable(
  origin: string,
  url: string,
  hash: string,
): boolean {
  return (
    !url.startsWith(`${origin}${ARTIFACT_PATH}`) ||
    [...projects().values()].some((project) =>
      project.artifacts.some((artifact) => artifact.hash === hash),
    )
  )
}

export async function serveSwiftPackageAsset(
  pathname: string,
  res: ServerResponse,
): Promise<boolean> {
  const acceptEncoding = res.req?.headers['accept-encoding'] ?? ''
  const acceptsBr = /\bbr\b/.test(
    Array.isArray(acceptEncoding) ? acceptEncoding.join(',') : acceptEncoding,
  )
  if (pathname.startsWith(RESOURCE_PATH)) {
    for (const project of projects().values()) {
      const served = serveSwiftResource(project, pathname.slice(RESOURCE_PATH.length))
      if (!served) continue
      res.setHeader('access-control-allow-origin', '*')
      res.setHeader('content-type', served.contentType)
      res.end(served.bytes)
      return true
    }
    res.statusCode = 404
    res.end('swift resource is stale')
    return true
  }
  if (pathname.startsWith(SDK_PATH)) {
    const name = pathname.slice(SDK_PATH.length).replace(/\.wasm$/, '')
    const piece = sdkPieces.get(name)
    let imageKey: string | undefined
    if (!piece)
      for (const project of projects().values()) {
        imageKey = project.artifacts.find((entry) => entry.sdk?.sha256 === name)?.sdk?.key
        if (imageKey) break
      }
    if ((!piece && !imageKey) || pathname !== `${SDK_PATH}${name}.wasm`) {
      res.statusCode = 404
      res.end('swift sdk image is stale')
      return true
    }
    const bytes =
      piece ??
      (await fs.promises.readFile(
        (await import('./swift-sdk-image')).swiftSdkImageFile(imageKey!),
      ))
    // the address is the content, which every app of this distribution shares
    res.setHeader('access-control-allow-origin', '*')
    res.setHeader('cache-control', 'public, max-age=31536000, immutable')
    res.setHeader('content-type', 'application/wasm')
    res.setHeader('vary', 'accept-encoding')
    if (acceptsBr) {
      res.setHeader('content-encoding', 'br')
      res.end(await brotliCompressQ4(bytes, `sdk-${name}`))
    } else res.end(bytes)
    return true
  }
  if (pathname.startsWith(SDK_BINDING_PATH)) {
    const digest = pathname.slice(SDK_BINDING_PATH.length, -'.bin'.length)
    const split = sdkBindingFiles.get(digest)
    if (split && pathname === `${SDK_BINDING_PATH}${digest}.bin`) {
      res.setHeader('access-control-allow-origin', '*')
      res.setHeader('cache-control', 'public, max-age=31536000, immutable')
      res.setHeader('content-type', 'application/octet-stream')
      res.setHeader('vary', 'accept-encoding')
      if (acceptsBr) {
        res.setHeader('content-encoding', 'br')
        res.end(await brotliCompressSwiftSdkBinding(split, digest))
      } else res.end(split)
      return true
    }
    for (const project of projects().values()) {
      const binding = project.artifacts.find(
        (artifact) =>
          artifact.sdk &&
          pathname === `${SDK_BINDING_PATH}${artifact.sdk.binding.sha256}.bin`,
      )?.sdk?.binding
      if (!binding) continue
      res.setHeader('access-control-allow-origin', '*')
      res.setHeader('cache-control', 'public, max-age=31536000, immutable')
      res.setHeader('content-type', 'application/octet-stream')
      res.setHeader('vary', 'accept-encoding')
      if (acceptsBr) {
        res.setHeader('content-encoding', 'br')
        res.end(await brotliCompressSwiftSdkBinding(binding.bytes, binding.sha256))
      } else res.end(binding.bytes)
      return true
    }
    res.statusCode = 404
    res.end('swift sdk binding is stale')
    return true
  }
  if (pathname.startsWith(ICU_PATH)) {
    for (const project of projects().values()) {
      const icu = project.artifacts.find(
        (artifact) =>
          'sha256' in artifact.icu &&
          pathname === `${ICU_PATH}${swiftIcuAddress(artifact.icu)}`,
      )?.icu
      if (!icu || 'url' in icu) continue
      // the address is the content, so the browser keeps it across reloads,
      // restarts and every app built with this toolchain. the tenant reads
      // the index and then one pack at a time by range.
      endImmutableRanges(res, await swiftIcuPacked(icu))
      return true
    }
    res.statusCode = 404
    res.end('swift icu data is stale')
    return true
  }
  if (!pathname.startsWith(ARTIFACT_PATH)) return false
  if (pathname.endsWith('.dyld')) {
    const digest = pathname.slice(ARTIFACT_PATH.length, -'.dyld'.length)
    for (const project of projects().values()) {
      const table = project.artifacts.find(
        (artifact) => artifact.dyldTable?.sha256 === digest,
      )?.dyldTable
      if (!table) continue
      endImmutableRanges(res, table.bytes)
      return true
    }
    res.statusCode = 404
    res.end('swift dyld table is stale')
    return true
  }
  const address = pathname.slice(ARTIFACT_PATH.length).replace(/\.wasm$/, '')
  for (const project of projects().values()) {
    if (pathname !== `${ARTIFACT_PATH}${address}.wasm`) continue
    const bytes = project.artifacts
      .map((artifact) =>
        artifact.hash === address ? artifact.bytes : artifact.parts?.get(address),
      )
      .find((bytes) => bytes !== undefined)
    if (!bytes) continue
    res.setHeader('access-control-allow-origin', '*')
    res.setHeader('content-type', 'application/wasm')
    res.setHeader('vary', 'accept-encoding')
    if (acceptsBr) {
      res.setHeader('content-encoding', 'br')
      res.end(await brotliCompressQ4(bytes, address))
    } else {
      res.end(bytes)
    }
    return true
  }
  res.statusCode = 404
  res.end('swift artifact is stale')
  return true
}

// packages retain the exact bytes the foreground host serves, including ICU.
export async function swiftPackageAssets(
  packagePath: string,
  {
    hash,
    sdkUrl,
    sdkBindingUrl,
  }: Pick<SwiftEntryModuleArgs, 'hash' | 'sdkUrl' | 'sdkBindingUrl'>,
) {
  const project = projects().get(fs.realpathSync(packagePath))
  const artifact = project?.artifacts.find((candidate) => candidate.hash === hash)
  if (!project || !artifact) throw new Error(`Swift artifact ${hash} was not built`)
  const assets = new Map<string, { bytes: Buffer; contentType: string }>([
    [
      `${ARTIFACT_PATH}${hash}.wasm`,
      { bytes: artifact.bytes, contentType: 'application/wasm' },
    ],
  ])
  if (artifact.dyldTable)
    assets.set(`${ARTIFACT_PATH}${artifact.dyldTable.sha256}.dyld`, {
      bytes: artifact.dyldTable.bytes,
      contentType: 'application/octet-stream',
    })
  for (const [digest, bytes] of artifact.parts ?? [])
    assets.set(`${ARTIFACT_PATH}${digest}.wasm`, {
      bytes,
      contentType: 'application/wasm',
    })
  if (artifact.sdk && sdkUrl) {
    const sdkPath = new URL(sdkUrl, 'http://localhost').pathname
    if (sdkPath.startsWith(SDK_PATH)) {
      const digest = sdkPath.slice(SDK_PATH.length, -'.wasm'.length)
      const primary = sdkPieces.get(digest)
      let bytes: Buffer
      if (primary) {
        bytes = primary
        for (const [name, bytes] of sdkStartupParts.get(digest) ?? [])
          assets.set(`${SDK_PATH}${name}.wasm`, {
            bytes,
            contentType: 'application/wasm',
          })
      } else {
        const { swiftSdkImageFile } = await import('./swift-sdk-image')
        bytes = await fs.promises.readFile(swiftSdkImageFile(artifact.sdk.key))
      }
      assets.set(sdkPath, { bytes, contentType: 'application/wasm' })
    }
    const { binding } = artifact.sdk
    const bindingPath =
      sdkBindingUrl && new URL(sdkBindingUrl, 'http://localhost').pathname
    const served =
      bindingPath && bindingPath.startsWith(SDK_BINDING_PATH)
        ? bindingPath.slice(SDK_BINDING_PATH.length, -'.bin'.length)
        : binding.sha256
    const bytes = sdkBindingFiles.get(served) ?? binding.bytes
    assets.set(`${SDK_BINDING_PATH}${served}.bin`, {
      bytes,
      contentType: 'application/octet-stream',
    })
    const later = decodeNativeSdkBinding(
      bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
    ).later
    for (const { sha256 } of later?.files ?? []) {
      const laterBytes = sdkBindingFiles.get(sha256)
      if (!laterBytes) throw new Error(`swift sdk later data ${sha256} is not served`)
      assets.set(`${SDK_BINDING_PATH}${sha256}.bin`, {
        bytes: laterBytes,
        contentType: 'application/octet-stream',
      })
    }
  }
  for (const [key, resource] of project.resourceFiles)
    assets.set(`${RESOURCE_PATH}${key}`, resource)
  if ('sha256' in artifact.icu) {
    const asset = await swiftIcuBundleAsset(artifact.icu)
    assets.set(`/${asset.path}`, asset)
  }
  return assets
}

export function disposeSwiftProject(packagePath: string, signal?: AbortSignal): void {
  packagePath = fs.realpathSync(packagePath)
  const project = projects().get(packagePath)
  if (signal && project && project.signal !== signal) return
  projects().delete(packagePath)
  xcodeProjects().delete(packagePath)
  sourceEntries().delete(packagePath)
}
