jetbridge 0.1.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +237 -0
- package/dist/cli.d.ts +24 -0
- package/dist/cli.js +3426 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +379 -0
- package/dist/index.js +3268 -0
- package/dist/index.js.map +1 -0
- package/dist/variant-Bh99wLZC.d.ts +327 -0
- package/package.json +84 -0
- package/schema/v1.json +351 -0
- package/templates/index-page.html +165 -0
- package/templates/install-page.html +187 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/boundary.ts","../src/errors.ts","../src/asc.ts","../src/project.ts","../src/config.ts","../src/provision.ts","../src/variant.ts","../src/bundles.ts","../src/init.ts","../src/detect.ts","../src/ota.ts","../src/assets.ts","../src/build.ts","../src/signing.ts","../src/entitlements.ts","../src/manifest.ts","../src/storage.ts","../src/wired.ts","../src/devices.ts","../src/prompts.ts","../src/simulator.ts","../src/sim.ts","../src/git.ts"],"sourcesContent":["/**\n * The command line.\n *\n * Argument parsing and printing only — every command delegates immediately.\n * The one piece of real logic here is deciding what a variant is called, which\n * has to be the same answer for every delivery route.\n */\nimport chalk from 'chalk';\nimport { Command, InvalidArgumentError } from 'commander';\nimport { nodeBoundary, type Boundary } from './boundary.js';\nimport { listBundles, provisionBundles, pruneBundles, removeBundles } from './bundles.js';\nimport { runInit } from './init.js';\nimport { otaInstall, reindex } from './ota.js';\nimport { clackPrompter } from './prompts.js';\nimport { JetbridgeError, fail, loadProject, type Project } from './project.js';\nimport { simInstall } from './sim.js';\nimport { assertSingleSegment, displayNameFor, sanitizeName, sanitizeSuffix } from './variant.js';\nimport { branchSuffix } from './git.js';\nimport { wiredInstall } from './wired.js';\n\ninterface VariantOptions {\n suffix?: string | boolean;\n name?: string;\n}\n\ninterface ResolvedVariant {\n suffix: string;\n displayName: string;\n}\n\n/**\n * What this build is called.\n *\n * `--suffix` takes an OPTIONAL value: commander hands back `true` when the flag\n * was given without one, which is the \"name it after the branch\" signal. The\n * RAW string feeds the label, because it still has the word boundaries a bundle\n * id cannot carry (`seeded-feed` → \"Acme Seeded Feed\"); the sanitized slug\n * feeds the bundle id.\n */\nfunction resolveVariant(\n boundary: Boundary,\n project: Project,\n options: VariantOptions,\n): ResolvedVariant {\n const raw =\n options.suffix === true\n ? branchSuffix(boundary, project)\n : typeof options.suffix === 'string'\n ? options.suffix\n : '';\n return {\n suffix: raw ? sanitizeSuffix(raw, project.config) : '',\n displayName: displayNameFor(raw, options.name ?? '', project.config),\n };\n}\n\nconst program = new Command();\n\nprogram\n .name('jetbridge')\n .description('Build, sign and deliver iOS dev builds — to a simulator, a cable, or your bucket.')\n .option('--config-file <path>', 'use this config file instead of the nearest one')\n // Never REQUIRED: behind a pipe the unattended path is already automatic, so\n // an agent needs no flag and no environment variable. This is for a person on\n // a terminal who wants it anyway.\n .option('--non-interactive', 'never prompt, even on a terminal')\n .showHelpAfterError();\n\n/** Resolved per command, so `--config-file` on the root still applies. */\nconst open = (): { boundary: Boundary; project: Project } => {\n const boundary = nodeBoundary({ nonInteractive: Boolean(program.opts().nonInteractive) });\n const configPath = program.opts().configFile as string | undefined;\n return { boundary, project: loadProject(boundary, { configPath }) };\n};\n\nconst parseName = (value: string): string => {\n try {\n return sanitizeName(value);\n } catch {\n throw new InvalidArgumentError('must contain letters or digits');\n }\n};\n\n/** Rejects a pasted bundle id rather than quietly flattening it into one segment. */\nconst parseSuffix = (value: string): string => {\n if (value.includes('.')) {\n throw new InvalidArgumentError('just the last segment — the full bundle id is built for you');\n }\n if (!/[A-Za-z0-9]/.test(value)) {\n throw new InvalidArgumentError('must contain letters or digits');\n }\n return value;\n};\n\nconst SUFFIX_FLAG = '-s, --suffix [slug]';\nconst SUFFIX_HELP = 'variant build; a bare flag names it after the current git branch';\nconst NAME_FLAG = '-n, --name <name>';\nconst NAME_HELP = 'home-screen display name';\n\nprogram\n .command('init')\n .description('write jetbridge.config.json by inspecting this Xcode project')\n .option('-y, --yes', 'accept every detected default and never prompt')\n .option('--ios-dir <dir>', 'directory holding the Xcode project')\n .option('--scheme <name>', 'scheme to build')\n .option('--team-id <id>', 'Apple team id')\n .option('--bundle-id <id>', 'base bundle id')\n .option('--display-name <name>', 'home-screen label for a plain build')\n .option('--ota', 'configure over-the-air delivery')\n .option('--ota-bucket <name>')\n .option('--ota-region <region>')\n .option('--ota-endpoint <url>', 'for an S3-compatible host (R2, MinIO, Backblaze)')\n .option('--ota-public-base-url <url>', 'where uploaded builds are readable (https only)')\n .action(async (options) => {\n const boundary = nodeBoundary({ nonInteractive: Boolean(program.opts().nonInteractive) });\n const result = await runInit(\n boundary,\n {\n yes: Boolean(options.yes),\n iosDir: options.iosDir,\n scheme: options.scheme,\n teamId: options.teamId,\n bundleId: options.bundleId,\n displayName: options.displayName,\n ota: Boolean(options.ota),\n otaBucket: options.otaBucket,\n otaRegion: options.otaRegion,\n otaEndpoint: options.otaEndpoint,\n otaPublicBaseUrl: options.otaPublicBaseUrl,\n },\n { prompts: clackPrompter() },\n );\n if (result.status === 'written') console.error(chalk.green(`wrote ${result.configPath}`));\n else if (result.status === 'unchanged') {\n console.error(chalk.dim(`${result.configPath} is already up to date`));\n } else console.error(chalk.dim('nothing written'));\n });\n\n/**\n * Where the build goes.\n *\n * Both flags take an OPTIONAL value, so one flag answers two questions:\n * `--device` means the cable, and `--device <id>` means that phone. The\n * simulator is the default because it is the only route that needs no\n * credentials, no signing and no paired hardware — a first command on a new\n * machine always works.\n */\nfunction resolveDestination(options: { device?: string | boolean; simulator?: string | boolean }): {\n kind: 'device' | 'simulator';\n id: string;\n} {\n const wantsDevice = options.device !== undefined;\n const wantsSimulator = options.simulator !== undefined;\n // Inside an action handler, so `fail` — a commander parse error here would\n // print a stack instead of the one line an expected failure gets.\n if (wantsDevice && wantsSimulator) fail('pass --device or --simulator, not both');\n const chosen = wantsDevice ? options.device : options.simulator;\n return {\n kind: wantsDevice ? 'device' : 'simulator',\n id: typeof chosen === 'string' ? chosen : '',\n };\n}\n\nprogram\n .command('install')\n .description('build and install — on a simulator by default, or over the cable with --device')\n .option(SUFFIX_FLAG, SUFFIX_HELP, parseSuffix)\n .option(NAME_FLAG, NAME_HELP, parseName)\n .option('-d, --device [id]', 'install over the cable; give an id to pick one device')\n .option('--simulator [name]', 'install on a simulator (the default); give a name or udid')\n // `--configuration`, not `--config`: Xcode's own word, and one keystroke\n // from the root `--config-file` is two meanings of \"config\" too close together.\n .option('-c, --configuration <name>', 'build configuration')\n .option('--clean', 'wipe cached DerivedData first')\n .option('--reprovision', 'bypass the profile cache and provision fresh (--device only)')\n .action(async (options) => {\n const { boundary, project } = open();\n const destination = resolveDestination(options);\n const variant = resolveVariant(boundary, project, options);\n\n if (destination.kind === 'simulator') {\n if (options.reprovision) fail('--reprovision only applies to a --device install');\n await simInstall(boundary, project, {\n ...variant,\n device: destination.id,\n configuration: options.configuration,\n clean: Boolean(options.clean),\n });\n return;\n }\n\n await wiredInstall(boundary, project, {\n ...variant,\n device: destination.id,\n configuration: options.configuration,\n clean: Boolean(options.clean),\n reprovision: Boolean(options.reprovision),\n });\n });\n\nprogram\n .command('link')\n .description('archive, upload to your bucket, and print a link anyone can install from')\n .option(SUFFIX_FLAG, SUFFIX_HELP, parseSuffix)\n .option(NAME_FLAG, NAME_HELP, parseName)\n // `--configuration`, not `--config`: Xcode's own word, and one keystroke\n // from the root `--config-file` is two meanings of \"config\" too close together.\n .option('-c, --configuration <name>', 'build configuration')\n .action(async (options) => {\n const { boundary, project } = open();\n const result = await otaInstall(boundary, project, {\n ...resolveVariant(boundary, project, options),\n configuration: options.configuration,\n });\n console.error('');\n console.error(chalk.green(`install: ${result.installUrl}`));\n console.error(chalk.dim(`builds: ${result.indexUrl}`));\n });\n\nprogram\n .command('reindex')\n .description('rebuild the build index page from what is in the bucket')\n .action(async () => {\n const { boundary, project } = open();\n const url = await reindex(boundary, project, {});\n console.error(chalk.green(`rebuilt: ${url}`));\n });\n\n/**\n * Everything this project has registered with Apple.\n *\n * A noun-first group, in the shape of `docker image ls/rm/prune`: the bare verb\n * that used to live here said nothing about what it acted on, and what it acts\n * on is permanent account state that Apple will not restore.\n */\nconst bundles = program\n .command('bundles')\n .description('variant bundle ids and profiles registered with Apple for this project');\n\nbundles\n .command('ls', { isDefault: true })\n .alias('list')\n .description('what this project has registered')\n .option('--json', 'machine-readable output')\n .action(async (options: { json?: boolean }) => {\n const { boundary, project } = open();\n await listBundles(boundary, project, { json: Boolean(options.json) });\n });\n\nbundles\n .command('provision [slug]')\n .description('register and refresh profiles now, without building')\n .action(async (slug: string | undefined) => {\n const { boundary, project } = open();\n const variant = resolveVariant(boundary, project, { suffix: slug ?? true });\n await provisionBundles(boundary, project, variant);\n });\n\nbundles\n .command('rm <slug...>')\n .description('remove these variants by name')\n .option('-y, --yes', 'actually delete (without this, the plan is printed and nothing changes)')\n .action(async (slugs: string[], options: { yes?: boolean }) => {\n // Validate the arguments BEFORE loading the config: a variadic argument\n // gets no commander parser, and checking afterwards means a typo outside a\n // project is reported as a missing config file — the wrong problem.\n for (const slug of slugs) assertSingleSegmentLoose(slug);\n const { boundary, project } = open();\n await removeBundles(boundary, project, {\n suffixes: slugs.map((value) => sanitizeSuffix(value, project.config)),\n yes: Boolean(options.yes),\n });\n });\n\nbundles\n .command('prune')\n .description('remove variants whose git branch is gone from the remote')\n .option('-y, --yes', 'actually delete (without this, the plan is printed and nothing changes)')\n .action(async (options: { yes?: boolean }) => {\n const { boundary, project } = open();\n await pruneBundles(boundary, project, { yes: Boolean(options.yes) });\n });\n\n/**\n * The config is not loaded yet, so the base bundle id cannot be quoted back —\n * but a pasted bundle id still has to be refused rather than flattened into one\n * absurd segment.\n */\nfunction assertSingleSegmentLoose(value: string): string {\n if (value.includes('.')) {\n fail(`\"${value}\": just the last segment — the full bundle id is built for you (e.g. \"wave\")`);\n }\n return value;\n}\n\n// A `JetbridgeError` is an expected failure that has already explained itself,\n// so it prints as one line. Anything else is a bug, and its stack is the point.\ntry {\n await program.parseAsync(process.argv);\n} catch (error) {\n if (error instanceof JetbridgeError) {\n console.error(chalk.red(`✗ ${error.message}`));\n } else {\n console.error(chalk.red(`✗ ${(error as Error)?.stack ?? String(error)}`));\n }\n process.exit(1);\n}\n\nexport { assertSingleSegment, resolveVariant };\n","/**\n * Everything this tool does to the outside world goes through one object.\n *\n * Nearly every line of jetbridge shells out (`xcodebuild`, `devicectl`,\n * `simctl`, `security`, `git`), calls App Store Connect, or writes to a bucket.\n * Called inline, none of it is exercisable without a Mac, a paired iPhone, an\n * Apple team and a bucket — so it is threaded as one parameter instead, with\n * the real implementation as the default. Tests pass a fake and assert the\n * argv arrays.\n *\n * This is a parameter, not a framework: no container, no registry, no\n * decorators.\n */\nimport { execa, execaSync } from 'execa';\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\nimport { fail } from './errors.js';\n\nexport interface RunOptions {\n cwd?: string;\n env?: Record<string, string>;\n /** Stream the child's output to the terminal instead of capturing it. */\n stdio?: 'pipe' | 'inherit';\n /** Return a failed result instead of throwing. */\n allowFail?: boolean;\n input?: string;\n timeoutMs?: number;\n}\n\nexport interface CommandResult {\n ok: boolean;\n /** null when the process was killed by a signal. */\n code: number | null;\n stdout: string;\n stderr: string;\n}\n\n/** A command as it was invoked — what tests assert against. */\nexport interface CommandCall {\n command: string;\n args: string[];\n options: RunOptions;\n}\n\nexport interface HttpResponse {\n status: number;\n ok: boolean;\n headers: Record<string, string>;\n text: () => Promise<string>;\n json: <T = unknown>() => Promise<T>;\n}\n\nexport interface HttpRequest {\n method: string;\n url: string;\n headers: Record<string, string>;\n body?: string;\n /** Overrides the default. A request that never answers is a hang, so there is always one. */\n timeoutMs?: number;\n}\n\nexport interface FileSystem {\n exists(path: string): boolean;\n read(path: string): string;\n readBytes(path: string): Uint8Array;\n write(path: string, contents: string | Uint8Array): void;\n mkdirp(path: string): void;\n readdir(path: string): string[];\n rm(path: string, opts?: { recursive?: boolean }): void;\n isDirectory(path: string): boolean;\n size(path: string): number;\n}\n\nexport interface Logger {\n info(message: string): void;\n warn(message: string): void;\n error(message: string): void;\n /** Progress that is noise in a log file — suppressed when not a TTY. */\n step(message: string): void;\n}\n\nexport interface Boundary {\n exec: {\n run(command: string, args: string[], options?: RunOptions): Promise<CommandResult>;\n runSync(command: string, args: string[], options?: RunOptions): CommandResult;\n };\n fs: FileSystem;\n http(request: HttpRequest): Promise<HttpResponse>;\n env(name: string): string | undefined;\n /** Unix seconds. Injected because build numbers are derived from it. */\n now(): number;\n homedir(): string;\n cwd(): string;\n log: Logger;\n /** False behind a pipe or in CI: never prompt, never expect a terminal. */\n interactive: boolean;\n}\n\nconst asResult = (r: {\n exitCode?: number | undefined;\n stdout?: unknown;\n stderr?: unknown;\n}): CommandResult => ({\n ok: (r.exitCode ?? 0) === 0,\n code: r.exitCode ?? null,\n stdout: typeof r.stdout === 'string' ? r.stdout : '',\n stderr: typeof r.stderr === 'string' ? r.stderr : '',\n});\n\nexport const nodeFileSystem: FileSystem = {\n exists: (path) => existsSync(path),\n read: (path) => readFileSync(path, 'utf8'),\n readBytes: (path) => new Uint8Array(readFileSync(path)),\n write: (path, contents) => {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n },\n mkdirp: (path) => {\n mkdirSync(path, { recursive: true });\n },\n readdir: (path) => readdirSync(path),\n rm: (path, opts) => {\n rmSync(path, { recursive: opts?.recursive ?? false, force: true });\n },\n isDirectory: (path) => existsSync(path) && statSync(path).isDirectory(),\n size: (path) => statSync(path).size,\n};\n\n/**\n * Is there a person to ask?\n *\n * A TTY that is not CI, and that nobody has explicitly opted out of. All three\n * halves matter: `CI=1` on a developer's machine is the documented way to force\n * the non-interactive path, and `JETBRIDGE_NON_INTERACTIVE` is the same lever\n * for someone who is not in CI and does not want to be prompted.\n *\n * Nothing REQUIRES any of them. No terminal is sufficient on its own — an agent\n * behind a pipe gets the unattended behaviour without setting a variable, which\n * is the whole point.\n */\nexport function isInteractive(env: NodeJS.ProcessEnv = process.env): boolean {\n if (env.CI || env.JETBRIDGE_NON_INTERACTIVE) return false;\n return Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\n/** A request that never answers would hang forever, so one minute is the ceiling. */\nconst HTTP_TIMEOUT_MS = 60_000;\n\n/**\n * How a child process gets its three streams.\n *\n * stdin is the one that hangs, and `stdio: 'pipe'` does NOT protect you: execa\n * leaves the pipe open when there is nothing to write to it, so a child that\n * reads stdin waits for input that never comes and the whole command stalls\n * with no output at all. That is the worst outcome for an unattended run — an\n * agent waits forever and the session dies having printed nothing.\n *\n * So stdin is attached only when there is genuinely something to answer with:\n * the caller's own `input`, or a real terminal with a person at it. Otherwise\n * it is closed, and a tool that decides to ask a question reads EOF and gives\n * up — which surfaces as an error, which is always better than a wait.\n */\nfunction childStreams(\n options: RunOptions,\n interactive: boolean,\n): { stdout: 'pipe' | 'inherit'; stderr: 'pipe' | 'inherit'; stdin?: 'inherit' | 'ignore' } {\n // Output still streams to the terminal when asked; only stdin is withheld.\n const output = options.stdio === 'inherit' ? ('inherit' as const) : ('pipe' as const);\n if (options.input !== undefined) return { stdout: output, stderr: output };\n return {\n stdout: output,\n stderr: output,\n stdin: options.stdio === 'inherit' && interactive ? 'inherit' : 'ignore',\n };\n}\n\nexport interface NodeBoundaryOptions {\n /**\n * Force the unattended path even on a terminal — what `--non-interactive`\n * hands down. Never needed behind a pipe, which is already unattended.\n */\n nonInteractive?: boolean;\n}\n\nexport function nodeBoundary(options: NodeBoundaryOptions = {}): Boundary {\n const interactive = isInteractive() && options.nonInteractive !== true;\n return {\n exec: {\n async run(command, args, runOptions = {}) {\n const result = await execa(command, args, {\n cwd: runOptions.cwd,\n env: runOptions.env,\n extendEnv: true,\n ...childStreams(runOptions, interactive),\n ...(runOptions.input === undefined ? {} : { input: runOptions.input }),\n timeout: runOptions.timeoutMs,\n reject: false,\n });\n return asResult(result);\n },\n runSync(command, args, runOptions = {}) {\n const result = execaSync(command, args, {\n cwd: runOptions.cwd,\n env: runOptions.env,\n extendEnv: true,\n ...childStreams(runOptions, interactive),\n ...(runOptions.input === undefined ? {} : { input: runOptions.input }),\n timeout: runOptions.timeoutMs,\n reject: false,\n });\n return asResult(result);\n },\n },\n fs: nodeFileSystem,\n async http(request) {\n const timeoutMs = request.timeoutMs ?? HTTP_TIMEOUT_MS;\n let response: Response;\n try {\n response = await fetch(request.url, {\n method: request.method,\n headers: request.headers,\n body: request.body,\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n // A blackholed host never answers and fetch never settles without this.\n // Reported as an ordinary failure, because a stalled command is worse.\n const reason =\n (error as Error)?.name === 'TimeoutError'\n ? `timed out after ${timeoutMs}ms`\n : String((error as Error)?.message ?? error);\n return fail(`${request.method} ${request.url} failed — ${reason}`);\n }\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n headers[key.toLowerCase()] = value;\n });\n return {\n status: response.status,\n ok: response.ok,\n headers,\n text: () => response.text(),\n json: <T>() => response.json() as Promise<T>,\n };\n },\n env: (name) => process.env[name],\n now: () => Math.floor(Date.now() / 1000),\n homedir: () => process.env.HOME ?? '',\n cwd: () => process.cwd(),\n log: {\n info: (m) => console.error(m),\n warn: (m) => console.error(m),\n error: (m) => console.error(m),\n step: (m) => {\n if (interactive) console.error(m);\n },\n },\n interactive,\n };\n}\n","/**\n * The failure type, on its own so that everything can throw it.\n *\n * It lived in `project.ts`, which meant the boundary — the lowest layer, which\n * depends on nothing — had to import the layer above it to report a failure.\n * That cycle left modules half-initialized at runtime and surfaced as a\n * `ReferenceError` naming an export that plainly exists.\n */\n\n/** An expected failure that has already explained itself: printed as one line, no stack. */\nexport class JetbridgeError extends Error {\n override readonly name = 'JetbridgeError';\n}\n\n/** A function declaration, not an arrow: TypeScript only narrows control flow through one. */\nexport function fail(message: string): never {\n throw new JetbridgeError(message);\n}\n","/**\n * App Store Connect: credentials, a signed JWT, and one request helper.\n *\n * `xcodebuild -allowProvisioningUpdates` rejects ASC API keys in headless\n * setups (\"Authentication failed: bearer token\") even though the same key works\n * against the REST API directly — so jetbridge registers bundle ids and creates\n * profiles itself, through this client.\n */\nimport { createPrivateKey, sign as cryptoSign } from 'node:crypto';\nimport { join } from 'node:path';\nimport type { Boundary } from './boundary.js';\nimport type { Config } from './config.js';\nimport { fail } from './project.js';\n\nexport const ASC_BASE = 'https://api.appstoreconnect.apple.com';\n\n/** Apple rejects a token older than 20 minutes. */\nconst TOKEN_TTL_SECONDS = 900;\n\nexport interface AscCredentials {\n keyPath: string;\n keyId: string;\n issuerId: string;\n}\n\nexport function missingCredentialsMessage(config: Config): string {\n const { ascKeyId, ascIssuerId, ascKeyPath } = config.credentials;\n return (\n 'App Store Connect credentials are not configured.\\n' +\n ` Set ${ascKeyId} and ${ascIssuerId} in the environment, and place the private key at\\n` +\n ` ~/.appstoreconnect/private_keys/AuthKey_<${ascKeyId}>.p8 (or point ${ascKeyPath} at it).`\n );\n}\n\n/** Apple's own search path for `AuthKey_<keyId>.p8`, in precedence order. */\nexport function keySearchDirs(boundary: Boundary): string[] {\n const home = boundary.homedir();\n return [\n join(boundary.cwd(), 'private_keys'),\n join(home, 'private_keys'),\n join(home, '.private_keys'),\n join(home, '.appstoreconnect', 'private_keys'),\n ];\n}\n\n/**\n * Resolve the key, or null when this machine has none. Null is not an error:\n * a plain build against an already-cached profile needs no credentials at all,\n * and saying so beats failing.\n */\nexport function localCredentials(boundary: Boundary, config: Config): AscCredentials | null {\n const keyId = boundary.env(config.credentials.ascKeyId);\n const issuerId = boundary.env(config.credentials.ascIssuerId);\n if (!keyId || !issuerId) return null;\n\n const explicit = boundary.env(config.credentials.ascKeyPath);\n const keyPath =\n explicit ??\n keySearchDirs(boundary)\n .map((dir) => join(dir, `AuthKey_${keyId}.p8`))\n .find((path) => boundary.fs.exists(path));\n if (!keyPath || !boundary.fs.exists(keyPath)) return null;\n\n return { keyPath, keyId, issuerId };\n}\n\nconst b64url = (value: Buffer): string => value.toString('base64url');\n\n/**\n * A short-lived ES256 JWT. `dsaEncoding: 'ieee-p1363'` produces the raw r||s\n * signature JOSE requires — the DER encoding Node defaults to is rejected.\n */\nexport function mintToken(boundary: Boundary, credentials: AscCredentials): string {\n const now = boundary.now();\n const header = b64url(\n Buffer.from(JSON.stringify({ alg: 'ES256', kid: credentials.keyId, typ: 'JWT' })),\n );\n const payload = b64url(\n Buffer.from(\n JSON.stringify({\n iss: credentials.issuerId,\n iat: now,\n exp: now + TOKEN_TTL_SECONDS,\n aud: 'appstoreconnect-v1',\n }),\n ),\n );\n const input = `${header}.${payload}`;\n const key = createPrivateKey(boundary.fs.read(credentials.keyPath));\n const signature = cryptoSign('sha256', Buffer.from(input), { key, dsaEncoding: 'ieee-p1363' });\n return `${input}.${b64url(signature)}`;\n}\n\nexport interface AscResponse<T = unknown> {\n status: number;\n body: T;\n}\n\nexport interface AscClient {\n request<T = AscDocument>(method: string, path: string, body?: unknown): Promise<AscResponse<T>>;\n}\n\n/** The subset of Apple's JSON:API envelope jetbridge reads. */\nexport interface AscResource {\n id: string;\n type: string;\n attributes: Record<string, unknown>;\n}\n\nexport interface AscDocument {\n data?: AscResource | AscResource[];\n errors?: Array<{ code?: string; title?: string; detail?: string }>;\n}\n\nexport function ascClient(boundary: Boundary, token: string): AscClient {\n return {\n async request(method, path, body) {\n const response = await boundary.http({\n method,\n url: `${ASC_BASE}${path}`,\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const text = await response.text();\n let parsed: unknown = {};\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n // Apple answers some failures with HTML; keep the body for the message.\n parsed = { errors: [{ detail: text.slice(0, 400) }] };\n }\n }\n return { status: response.status, body: parsed } as AscResponse<never>;\n },\n };\n}\n\n/** Apple returns a list of problems; a single readable line is more use. */\nexport function describeAscError(body: unknown): string {\n const errors = (body as AscDocument)?.errors;\n if (!errors?.length) return typeof body === 'string' ? body : JSON.stringify(body);\n return errors.map((e) => [e.title, e.detail].filter(Boolean).join(': ')).join('; ');\n}\n\nexport function requireCredentials(boundary: Boundary, config: Config): AscCredentials {\n const credentials = localCredentials(boundary, config);\n if (!credentials) fail(missingCredentialsMessage(config));\n return credentials;\n}\n\n/** The client every provisioning call runs through. */\nexport function connect(boundary: Boundary, config: Config): AscClient {\n return ascClient(boundary, mintToken(boundary, requireCredentials(boundary, config)));\n}\n\nexport const asArray = (data: AscDocument['data']): AscResource[] =>\n Array.isArray(data) ? data : data ? [data] : [];\n","/**\n * Where the project is, and where everything resolves from.\n *\n * The tool this was extracted from had a `REPO_ROOT` constant, which means\n * nothing in a published CLI. The root is discovered instead: walk up from the\n * working directory until a config file appears. Every other path in jetbridge\n * is resolved against it, so getting this wrong is getting everything wrong.\n */\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport type { Boundary } from './boundary.js';\nimport { CONFIG_FILENAMES, formatConfigErrors, parseConfig, type Config } from './config.js';\nimport { fail } from './errors.js';\n\n// Re-exported so existing importers keep working; defined in errors.ts because\n// the boundary needs to throw without importing the layer above it.\nexport { JetbridgeError, fail } from './errors.js';\n\nexport interface Project {\n /** Directory holding the config file. Everything relative resolves from here. */\n root: string;\n configPath: string;\n config: Config;\n /** Absolute path to a project-relative one. */\n path(...segments: string[]): string;\n /** Absolute path inside the Xcode project directory. */\n iosPath(...segments: string[]): string;\n /** The `-project` or `-workspace` argument pair for xcodebuild. */\n xcodebuildTarget(): [flag: string, path: string];\n}\n\n/** The nearest config file at or above `from`, or null. */\nexport function findConfigFile(boundary: Boundary, from: string): string | null {\n let dir = resolve(from);\n for (;;) {\n for (const name of CONFIG_FILENAMES) {\n const candidate = join(dir, name);\n if (boundary.fs.exists(candidate)) return candidate;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nexport function projectFrom(configPath: string, config: Config): Project {\n const root = dirname(configPath);\n const path = (...segments: string[]): string => resolve(root, ...segments);\n const iosPath = (...segments: string[]): string =>\n resolve(root, config.project.iosDir, ...segments);\n return {\n root,\n configPath,\n config,\n path,\n iosPath,\n xcodebuildTarget: () =>\n config.project.xcworkspace\n ? ['-workspace', iosPath(config.project.xcworkspace)]\n : ['-project', iosPath(config.project.xcodeproj!)],\n };\n}\n\nexport interface LoadOptions {\n /** Start the upward walk here instead of the working directory. */\n from?: string;\n /** Use exactly this file, e.g. from `--config-file`. */\n configPath?: string;\n}\n\nexport function loadProject(boundary: Boundary, options: LoadOptions = {}): Project {\n const explicit = options.configPath;\n const configPath = explicit\n ? isAbsolute(explicit)\n ? explicit\n : resolve(boundary.cwd(), explicit)\n : findConfigFile(boundary, options.from ?? boundary.cwd());\n\n if (!configPath) {\n fail(\n `no ${CONFIG_FILENAMES[0]} found in this directory or any parent.\\n` +\n ' Run `jetbridge init` to create one.',\n );\n }\n if (!boundary.fs.exists(configPath)) {\n fail(`config file not found: ${configPath}`);\n }\n\n let raw: unknown;\n try {\n raw = JSON.parse(boundary.fs.read(configPath));\n } catch (e) {\n return fail(`${configPath} is not valid JSON — ${(e as Error).message}`);\n }\n\n const result = parseConfig(raw);\n if (!result.ok) {\n return fail(\n `${configPath} is not a valid jetbridge config:\\n${formatConfigErrors(result.errors)}`,\n );\n }\n return projectFrom(configPath, result.config);\n}\n","/**\n * `jetbridge.config.json` — one schema, three jobs: the TypeScript types, the\n * runtime validator, and the published JSON Schema editors autocomplete\n * against. Defining it three times is how they drift.\n *\n * Every value here was a hardcoded constant in the tool this package was\n * extracted from. Nothing project-specific is allowed back in as a default.\n */\nimport { z } from 'zod';\n\nexport const CONFIG_FILENAMES = ['jetbridge.config.json', '.jetbridge.json'] as const;\nexport const CONFIG_VERSION = 1;\n\n/** Leading words that carry no meaning in a variant name. */\nexport const COMMIT_TYPE_NOISE = [\n 'feat',\n 'fix',\n 'chore',\n 'refactor',\n 'docs',\n 'perf',\n 'test',\n 'ci',\n 'build',\n 'style',\n 'worktree',\n] as const;\n\nconst identifier = z\n .string()\n .min(1)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, 'must be a plain identifier');\n\nconst relativePath = z\n .string()\n .min(1)\n .refine((p) => !p.startsWith('/'), 'must be relative to the project root')\n .refine((p) => !p.split('/').includes('..'), 'must not escape the project root');\n\n/**\n * An Xcode target that gets its own bundle id — the app, plus any extension\n * that ships inside it. An extension's id is the app's id plus its own segment,\n * which is why a variant has to register more than one.\n */\nconst targetSchema = z.object({\n /** Xcode target name, as the project spells it. */\n name: z.string().min(1),\n /**\n * Appended to the app's variant bundle id. Omit for the app itself; an\n * extension named `uploadwidget` becomes `<base>.<slug>.uploadwidget`.\n */\n bundleIdSuffix: z\n .string()\n .regex(/^[a-z0-9]+$/, 'lowercase alphanumerics — it is one bundle-id segment')\n .optional(),\n /** Shipping entitlements, used by a plain build. */\n entitlements: relativePath.optional(),\n /**\n * Reduced entitlements for a variant. Capabilities the public API cannot\n * grant (app groups, Sign in with Apple) have to be dropped here, or signing\n * fails against a profile that does not carry them.\n */\n variantEntitlements: relativePath.optional(),\n /**\n * Capabilities to enable on the registered bundle id, e.g.\n * `PUSH_NOTIFICATIONS`. Only what the public API can actually deliver.\n */\n capabilities: z\n .array(z.string().regex(/^[A-Z0-9_]+$/, 'an App Store Connect capability type'))\n .default([]),\n /**\n * Build setting carrying this target's profile name. The project's xcconfig\n * has to read it — `PROVISIONING_PROFILE_SPECIFIER = $(JETBRIDGE_PROFILE_APP)`.\n */\n profileSetting: identifier.optional(),\n});\n\n/**\n * Build settings jetbridge passes on the xcodebuild command line. The project\n * decides what to do with them; these are just the names both sides agree on.\n */\nconst buildSettingNamesSchema = z.object({\n /** Appended to the bundle id, e.g. `.wave`. */\n bundleSuffix: identifier.default('JETBRIDGE_BUNDLE_SUFFIX'),\n /** The home-screen label. */\n displayName: identifier.default('JETBRIDGE_DISPLAY_NAME'),\n /** Set to `Manual` for a variant, so the build signs against our profiles. */\n signStyle: identifier.default('JETBRIDGE_SIGN_STYLE'),\n /** Optional provenance stamp, e.g. the short commit SHA. */\n gitSha: identifier.default('JETBRIDGE_GIT_SHA'),\n});\n\nconst projectSchema = z.object({\n /** Directory holding the Xcode project, relative to the config file. */\n iosDir: relativePath.default('.'),\n /** `.xcodeproj` name, relative to `iosDir`. */\n xcodeproj: z.string().min(1).endsWith('.xcodeproj').optional(),\n /** `.xcworkspace` name, relative to `iosDir`. Takes precedence when set. */\n xcworkspace: z.string().min(1).endsWith('.xcworkspace').optional(),\n scheme: z.string().min(1),\n teamId: z.string().regex(/^[A-Z0-9]{10}$/, 'an Apple team id is 10 uppercase alphanumerics'),\n baseBundleId: z\n .string()\n .regex(\n /^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$/,\n 'a reverse-DNS bundle id, e.g. com.example.app.dev',\n ),\n /** XcodeGen spec, relative to `iosDir`. Only set when the project is generated. */\n projectYml: relativePath.optional(),\n /** Re-run XcodeGen before building. Requires `projectYml`. */\n xcodegen: z.boolean().default(false),\n /** Icon shown on the OTA install page, relative to the project root. */\n appIcon: relativePath.optional(),\n /**\n * Device types a cabled install targets. `devicectl` reports an iPad's\n * platform as `iOS` too, so a platform check would sweep a paired iPad into\n * the install set of an iPhone-only app.\n */\n deviceTypes: z\n .array(z.enum(['iPhone', 'iPad']))\n .min(1)\n .default(['iPhone']),\n});\n\nconst configurationsSchema = z.object({\n /** Build configurations that exist in the project. Validated before building. */\n available: z.array(z.string().min(1)).min(1).default(['Debug', 'Release']),\n /** Cabled installs default to a debuggable build — it is the inner loop. */\n wired: z.string().min(1).default('Debug'),\n sim: z.string().min(1).default('Debug'),\n /** Archives default to the optimised build, since they go to other people. */\n archive: z.string().min(1).default('Release'),\n});\n\nconst variantSchema = z.object({\n /** Home-screen label for a plain build, e.g. what the project already sets. */\n displayName: z.string().min(1),\n /** Prefix for a variant label: `<prefix> Seeded Feed`. Defaults to displayName's first word. */\n labelPrefix: z.string().min(1).optional(),\n /** iOS truncates a home-screen label at roughly this many characters. */\n labelBudget: z.number().int().positive().default(14),\n /**\n * Leading words dropped from a variant name. Defaults to conventional-commit\n * types plus the segments of `baseBundleId`, so pasting the bundle id back in\n * does not produce a name that stutters.\n */\n noiseWords: z.array(z.string().min(1)).optional(),\n /** Every target that needs its own registered bundle id. */\n targets: z.array(targetSchema).default([]),\n buildSettings: buildSettingNamesSchema.prefault({}),\n /** Name given to generated provisioning profiles. Defaults to the label prefix. */\n profilePrefix: z.string().min(1).optional(),\n});\n\nconst xcconfigOverrideSchema = z.object({\n /** Git-ignored xcconfig the build already `#include?`s, relative to the project root. */\n file: relativePath,\n /** Build setting to rewrite, e.g. an API base URL. */\n key: identifier,\n /** Named shortcuts, exposed as `--<name>` on the build commands. */\n presets: z.record(z.string(), z.string()).prefault({}),\n});\n\nconst hooksSchema = z.object({\n /**\n * Shell commands run in the project root. JSON cannot hold a function; this\n * is the deliberate cost of a config file a wizard can write and a human can\n * read.\n */\n preBuild: z.string().min(1).optional(),\n postBuild: z.string().min(1).optional(),\n});\n\nconst credentialsSchema = z.object({\n /** Environment variable NAMES. A secret never belongs in this file. */\n ascKeyId: identifier.default('ASC_API_KEY_ID'),\n ascIssuerId: identifier.default('ASC_API_ISSUER_ID'),\n ascKeyPath: identifier.default('ASC_API_KEY_PATH'),\n});\n\nconst otaStorageSchema = z.object({\n bucket: z.string().min(1),\n region: z.string().min(1).default('us-east-1'),\n /** Set for S3-compatible hosts (R2, MinIO, Backblaze). Omit for AWS. */\n endpoint: z.string().url().optional(),\n /**\n * Where the uploaded objects are readable from. `itms-services` refuses\n * anything but HTTPS with a valid certificate, so this is checked, not\n * trusted.\n */\n publicBaseUrl: z\n .string()\n .url()\n .refine((u) => u.startsWith('https://'), 'must be https:// — iOS refuses to install over http'),\n prefix: z.string().default('builds'),\n accessKeyId: identifier.default('JETBRIDGE_S3_ACCESS_KEY_ID'),\n secretAccessKey: identifier.default('JETBRIDGE_S3_SECRET_ACCESS_KEY'),\n});\n\nconst otaSchema = z.object({\n storage: otaStorageSchema,\n exportMethod: z.enum(['ad-hoc', 'enterprise']).default('ad-hoc'),\n /** Builds kept on the index page before the oldest is dropped. */\n maxBuilds: z.number().int().positive().max(500).default(60),\n /** `path` puts an unguessable token in the URL; `none` assumes a private bucket. */\n access: z.enum(['path', 'none']).default('path'),\n branding: z\n .object({\n title: z.string().min(1).optional(),\n accent: z\n .string()\n .regex(/^#[0-9a-fA-F]{6}$/, 'a six-digit hex colour')\n .optional(),\n })\n .prefault({}),\n});\n\nconst gitSchema = z.object({\n /** Repos disagree: main, master, trunk. */\n defaultBranch: z.string().min(1).default('main'),\n /**\n * A plain (non-variant) install overwrites the app every session shares, so\n * its provenance has to be knowable. Off by default — it is a strong\n * convention, not a universal one.\n */\n requireCleanDefaultBranch: z.boolean().default(false),\n});\n\nexport const configSchema = z\n .object({\n $schema: z.string().optional(),\n configVersion: z.literal(CONFIG_VERSION),\n project: projectSchema,\n configurations: configurationsSchema.prefault({}),\n variant: variantSchema,\n xcconfigOverrides: xcconfigOverrideSchema.optional(),\n hooks: hooksSchema.prefault({}),\n credentials: credentialsSchema.prefault({}),\n ota: otaSchema.optional(),\n git: gitSchema.prefault({}),\n })\n .superRefine((config, ctx) => {\n const { available, wired, sim, archive } = config.configurations;\n for (const [field, value] of Object.entries({ wired, sim, archive })) {\n if (!available.includes(value)) {\n ctx.addIssue({\n code: 'custom',\n path: ['configurations', field],\n message: `\"${value}\" is not in configurations.available (${available.join(', ')})`,\n });\n }\n }\n if (config.project.xcodegen && !config.project.projectYml) {\n ctx.addIssue({\n code: 'custom',\n path: ['project', 'projectYml'],\n message:\n 'project.xcodegen is on, so project.projectYml must say which spec to generate from',\n });\n }\n if (!config.project.xcodeproj && !config.project.xcworkspace) {\n ctx.addIssue({\n code: 'custom',\n path: ['project', 'xcodeproj'],\n message: 'set project.xcodeproj or project.xcworkspace',\n });\n }\n // Exactly one target is the app itself. Two would both claim the app's\n // bundle id and silently overwrite each other's profile.\n const appTargets = config.variant.targets.filter((t) => !t.bundleIdSuffix);\n if (config.variant.targets.length > 0 && appTargets.length !== 1) {\n ctx.addIssue({\n code: 'custom',\n path: ['variant', 'targets'],\n message:\n appTargets.length === 0\n ? 'one target must be the app itself — leave its bundleIdSuffix unset'\n : `only one target can be the app itself; ${appTargets\n .map((t) => t.name)\n .join(' and ')} both leave bundleIdSuffix unset`,\n });\n }\n const suffixes = config.variant.targets.map((t) => t.bundleIdSuffix ?? '');\n const duplicate = suffixes.find((s, i) => suffixes.indexOf(s) !== i);\n if (duplicate !== undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['variant', 'targets'],\n message: `two targets share the bundleIdSuffix \"${duplicate}\"`,\n });\n }\n });\n\nexport type Config = z.infer<typeof configSchema>;\nexport type ProjectConfig = Config['project'];\nexport type OtaConfig = NonNullable<Config['ota']>;\nexport type TargetConfig = z.infer<typeof targetSchema>;\n\n/**\n * The noise words actually used: whatever was configured, or the default —\n * commit types plus the segments of the base bundle id.\n */\nexport function noiseWordsFor(config: Config): Set<string> {\n const configured = config.variant.noiseWords;\n if (configured) return new Set(configured.map((w) => w.toLowerCase()));\n return new Set([\n ...COMMIT_TYPE_NOISE,\n ...config.project.baseBundleId.split('.').map((s) => s.toLowerCase()),\n ]);\n}\n\n/** `Acme Dev` → `Acme`, unless a prefix was set explicitly. */\nexport function labelPrefixFor(config: Config): string {\n return config.variant.labelPrefix ?? config.variant.displayName.split(/\\s+/)[0]!;\n}\n\nexport interface ConfigError {\n path: string;\n message: string;\n}\n\nexport type ParseResult = { ok: true; config: Config } | { ok: false; errors: ConfigError[] };\n\n/** Validate an already-parsed object. Separated so the wizard can check its own draft. */\nexport function parseConfig(value: unknown): ParseResult {\n const result = configSchema.safeParse(value);\n if (result.success) return { ok: true, config: result.data };\n return {\n ok: false,\n errors: result.error.issues.map((issue) => ({\n path: issue.path.join('.') || '(root)',\n message: issue.message,\n })),\n };\n}\n\nexport function formatConfigErrors(errors: ConfigError[]): string {\n return errors.map((e) => ` ${e.path}: ${e.message}`).join('\\n');\n}\n\n/** The published JSON Schema, generated from the same definition the runtime uses. */\nexport function jsonSchema(): unknown {\n return z.toJSONSchema(configSchema, { io: 'input', unrepresentable: 'any' });\n}\n","/**\n * Registering a variant's signing, headlessly.\n *\n * For each target that needs its own bundle id: make sure the id exists, make\n * sure its capabilities are on, then create a fresh provisioning profile over\n * the local development certificate and every enabled device, and install it\n * where Xcode looks for it.\n *\n * Idempotent by design. An existing bundle id is success; an existing profile\n * of the same name is deleted and recreated, because its device list and\n * certificate go stale the moment a new phone is registered.\n */\nimport { join } from 'node:path';\nimport {\n asArray,\n connect,\n describeAscError,\n type AscClient,\n type AscDocument,\n type AscResource,\n} from './asc.js';\nimport type { Boundary } from './boundary.js';\nimport { labelPrefixFor, type Config, type TargetConfig } from './config.js';\nimport { fail, type Project } from './project.js';\nimport { ascEntityName, bundleIdFor } from './variant.js';\n\n/** Where Xcode reads installed profiles from. */\nexport const profileDirectory = (boundary: Boundary): string =>\n join(boundary.homedir(), 'Library', 'MobileDevice', 'Provisioning Profiles');\n\nexport interface ProvisionedProfile {\n target: string;\n bundleId: string;\n profileName: string;\n /** Absolute path of the installed `.mobileprovision`. */\n installedAt: string;\n uuid: string;\n}\n\nexport interface ProvisionOptions {\n suffix: string;\n displayName: string;\n /** `IOS_APP_DEVELOPMENT` for a cabled install, `IOS_APP_ADHOC` for OTA. */\n profileType?: string;\n}\n\nconst errorText = (status: number, body: unknown): string => `${status} ${describeAscError(body)}`;\n\n/** Register the bundle id if it is not there already, and return its row id. */\nexport async function ensureBundleId(\n client: AscClient,\n identifier: string,\n name: string,\n): Promise<string> {\n const existing = await client.request<AscDocument>(\n 'GET',\n `/v1/bundleIds?filter[identifier]=${encodeURIComponent(identifier)}&limit=5`,\n );\n if (existing.status === 200) {\n // Apple's filter matches by prefix, so an exact comparison is required —\n // otherwise `…dev.wave` matches when only `…dev.wavelength` exists.\n const match = asArray(existing.body.data).find(\n (row) => row.attributes.identifier === identifier,\n );\n if (match) return match.id;\n }\n\n const created = await client.request<AscDocument>('POST', '/v1/bundleIds', {\n data: {\n type: 'bundleIds',\n attributes: { identifier, name, platform: 'IOS' },\n },\n });\n if (created.status !== 201) {\n fail(\n `could not register the bundle id ${identifier}: ${errorText(created.status, created.body)}`,\n );\n }\n const row = asArray(created.body.data)[0];\n if (!row) fail(`App Store Connect registered ${identifier} but returned no id`);\n return row.id;\n}\n\nexport async function ensureCapabilities(\n client: AscClient,\n bundleRowId: string,\n capabilities: string[],\n): Promise<void> {\n for (const capability of capabilities) {\n const result = await client.request<AscDocument>('POST', '/v1/bundleIdCapabilities', {\n data: {\n type: 'bundleIdCapabilities',\n attributes: { capabilityType: capability },\n relationships: { bundleId: { data: { type: 'bundleIds', id: bundleRowId } } },\n },\n });\n // 409 means it is already enabled, or implied by another capability.\n if (![200, 201, 409].includes(result.status)) {\n fail(`could not enable ${capability}: ${errorText(result.status, result.body)}`);\n }\n }\n}\n\n/**\n * The development certificate whose private key is actually in this keychain.\n * The account may hold certificates belonging to other machines; signing with\n * one of those fails at build time with an error that names nothing useful.\n */\nexport async function localDevelopmentCertificateId(\n boundary: Boundary,\n client: AscClient,\n): Promise<string> {\n const identities = boundary.exec.runSync('security', [\n 'find-identity',\n '-v',\n '-p',\n 'codesigning',\n ]);\n const certificates = await client.request<AscDocument>(\n 'GET',\n '/v1/certificates?filter[certificateType]=DEVELOPMENT&limit=50',\n );\n if (certificates.status !== 200) {\n fail(\n `could not list signing certificates: ${errorText(certificates.status, certificates.body)}`,\n );\n }\n const match = asArray(certificates.body.data).find((certificate) => {\n const displayName = certificate.attributes.displayName;\n return typeof displayName === 'string' && identities.stdout.includes(displayName);\n });\n if (!match) {\n fail(\n 'no App Store Connect development certificate matches a signing identity in this keychain.\\n' +\n ' Create one in Xcode once (Settings › Accounts › Manage Certificates), or import the\\n' +\n \" existing certificate's private key into this keychain.\",\n );\n }\n return match.id;\n}\n\nexport async function enabledDeviceIds(client: AscClient): Promise<string[]> {\n const devices = await client.request<AscDocument>(\n 'GET',\n '/v1/devices?filter[platform]=IOS&filter[status]=ENABLED&limit=200',\n );\n if (devices.status !== 200) {\n fail(`could not list registered devices: ${errorText(devices.status, devices.body)}`);\n }\n return asArray(devices.body.data).map((device) => device.id);\n}\n\n/**\n * A `.mobileprovision` is a CMS envelope wrapping a plist. Only the UUID is\n * needed, and it is the filename Xcode expects — so the embedded plist is\n * sliced out and read rather than pulling in a CMS parser.\n */\nexport function profileUuid(contents: Uint8Array): string {\n const text = Buffer.from(contents).toString('binary');\n const start = text.indexOf('<?xml');\n const end = text.indexOf('</plist>');\n if (start === -1 || end === -1)\n fail('the profile App Store Connect returned has no plist inside');\n const plist = text.slice(start, end + '</plist>'.length);\n const uuid = /<key>UUID<\\/key>\\s*<string>([^<]+)<\\/string>/.exec(plist)?.[1];\n if (!uuid) fail('the profile App Store Connect returned carries no UUID');\n return uuid;\n}\n\nexport async function ensureProfile(\n boundary: Boundary,\n client: AscClient,\n options: {\n name: string;\n bundleRowId: string;\n certificateId: string;\n deviceIds: string[];\n profileType: string;\n },\n): Promise<{ uuid: string; installedAt: string }> {\n const existing = await client.request<AscDocument>(\n 'GET',\n `/v1/profiles?filter[name]=${encodeURIComponent(options.name)}&limit=5`,\n );\n if (existing.status === 200) {\n for (const row of asArray(existing.body.data)) {\n if (row.attributes.name === options.name) {\n await client.request('DELETE', `/v1/profiles/${row.id}`);\n }\n }\n }\n\n const created = await client.request<AscDocument>('POST', '/v1/profiles', {\n data: {\n type: 'profiles',\n attributes: { name: options.name, profileType: options.profileType },\n relationships: {\n bundleId: { data: { type: 'bundleIds', id: options.bundleRowId } },\n certificates: { data: [{ type: 'certificates', id: options.certificateId }] },\n devices: { data: options.deviceIds.map((id) => ({ type: 'devices', id })) },\n },\n },\n });\n if (created.status !== 201) {\n fail(\n `could not create the profile \"${options.name}\": ${errorText(created.status, created.body)}`,\n );\n }\n\n const row = asArray(created.body.data)[0] as AscResource | undefined;\n const encoded = row?.attributes.profileContent;\n if (typeof encoded !== 'string') fail(`the profile \"${options.name}\" came back empty`);\n const contents = Buffer.from(encoded, 'base64');\n const uuid = profileUuid(contents);\n const installedAt = join(profileDirectory(boundary), `${uuid}.mobileprovision`);\n boundary.fs.write(installedAt, new Uint8Array(contents));\n return { uuid, installedAt };\n}\n\n/** `<base>.<slug>` for the app; the app's id plus one segment for an extension. */\nexport function targetBundleId(target: TargetConfig, suffix: string, config: Config): string {\n const appId = bundleIdFor(suffix, config);\n return target.bundleIdSuffix ? `${appId}.${target.bundleIdSuffix}` : appId;\n}\n\n/**\n * The App Store Connect entity name for a target. Derived from the home-screen\n * label so there is one spelling of the convention — the extension gets the\n * app's name plus its own, which is what makes a list of bundle ids readable.\n */\nexport function targetEntityName(target: TargetConfig, displayName: string): string {\n return ascEntityName(target.bundleIdSuffix ? `${displayName} ${target.name}` : displayName);\n}\n\nexport function profileNameFor(target: TargetConfig, suffix: string, config: Config): string {\n const prefix = config.variant.profilePrefix ?? labelPrefixFor(config);\n return `${prefix} ${suffix} ${target.bundleIdSuffix ?? 'app'}`;\n}\n\n/**\n * Register everything a variant needs and install its profiles. Returns one\n * entry per target, in configuration order, for the build to sign against.\n */\nexport async function provisionVariant(\n boundary: Boundary,\n project: Project,\n options: ProvisionOptions,\n): Promise<ProvisionedProfile[]> {\n const { config } = project;\n const targets = config.variant.targets;\n if (targets.length === 0) {\n fail(\n 'a variant build needs at least one entry in variant.targets — the app itself, and any ' +\n 'extension that ships inside it.',\n );\n }\n if (!options.suffix) fail('provisionVariant needs a variant slug');\n\n const client = connect(boundary, config);\n const profileType = options.profileType ?? 'IOS_APP_DEVELOPMENT';\n\n const registered: Array<{ target: TargetConfig; bundleId: string; rowId: string }> = [];\n for (const target of targets) {\n const bundleId = targetBundleId(target, options.suffix, config);\n boundary.log.step(`provisioning ${bundleId}`);\n const rowId = await ensureBundleId(\n client,\n bundleId,\n targetEntityName(target, options.displayName),\n );\n await ensureCapabilities(client, rowId, target.capabilities);\n registered.push({ target, bundleId, rowId });\n }\n\n // One certificate and one device list for every profile in the run: they are\n // the same answer each time, and each lookup is a round trip to Apple.\n const certificateId = await localDevelopmentCertificateId(boundary, client);\n const deviceIds = await enabledDeviceIds(client);\n if (deviceIds.length === 0) {\n fail(\n 'no enabled iOS devices are registered on this team, so a profile would install nowhere.\\n' +\n ' Register the device once (plug it in and build from Xcode), then re-run.',\n );\n }\n\n const profiles: ProvisionedProfile[] = [];\n for (const { target, bundleId, rowId } of registered) {\n const profileName = profileNameFor(target, options.suffix, config);\n const { uuid, installedAt } = await ensureProfile(boundary, client, {\n name: profileName,\n bundleRowId: rowId,\n certificateId,\n deviceIds,\n profileType,\n });\n profiles.push({ target: target.name, bundleId, profileName, installedAt, uuid });\n }\n return profiles;\n}\n","/**\n * Naming a variant build.\n *\n * A variant gets its own bundle id and its own home-screen label, so two\n * branches install side by side as two distinguishable apps instead of\n * overwriting each other. Every name below comes from ONE parse of the raw\n * slug: derive the bundle-id segment and the label separately and they drift\n * (`feat/seeded-feed` became bundle `featseededfeed` but label \"Seeded Feed\").\n */\nimport { type Config, labelPrefixFor, noiseWordsFor } from './config.js';\nimport { fail } from './project.js';\n\n/**\n * The words a variant is named from.\n *\n * Leading noise words are dropped, repeatedly: a conventional-commit type, and\n * the segments of the base bundle id someone might paste back in. So\n * `feat/seeded-feed` and `seeded-feed` name the same app, and\n * `com.example.dev.testtestes` yields `testtestes` rather than the absurd\n * `com.example.app.dev.comexampledevtesttestes`.\n *\n * Guarded on `length > 1` at each step, so an explicit `--suffix fix` still\n * names the variant \"fix\".\n */\nexport function variantWords(raw: string, noiseWords: Set<string>): string[] {\n const words = raw.split(/[^A-Za-z0-9]+/).filter(Boolean);\n while (words.length > 1 && noiseWords.has(words[0]!.toLowerCase())) words.shift();\n if (words.length === 0) fail('a variant slug must contain letters or digits');\n return words;\n}\n\n/** Bundle-id segment and DNS label: lowercase alphanumerics only. */\nexport function sanitizeSuffix(raw: string, config: Config): string {\n return variantWords(raw, noiseWordsFor(config)).join('').toLowerCase();\n}\n\n/**\n * Human words for a variant, from the RAW slug — before `sanitizeSuffix`\n * collapses the separators a bundle id cannot carry. `seeded-feed` → `Seeded\n * Feed`; derive it from the collapsed `seededfeed` instead and you get\n * `Seededfeed`.\n */\nexport function variantTitle(raw: string, config: Config): string {\n return variantWords(raw, noiseWordsFor(config))\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(' ');\n}\n\n/** Interpolated into plist XML and a build setting — keep it boring. */\nexport function sanitizeName(raw: string): string {\n const name = raw.replace(/[^A-Za-z0-9 ._-]/g, '');\n if (!name) fail('a display name must contain letters or digits');\n return name;\n}\n\n/**\n * The name App Store Connect accepts for a bundle-id entity.\n *\n * Not the same string as the home-screen label, though it is derived from it.\n * iOS is happy with `CFBundleDisplayName = \"Acme_Hello_World\"`; the ASC API\n * rejects it outright:\n *\n * 409 ENTITY_ERROR.ATTRIBUTE.INVALID\n * The attribute 'name' is invalid: 'Acme_Hello_World'\n *\n * Apple allows letters, digits and spaces there — not the `._-` a display name\n * permits. Punctuation becomes a space rather than vanishing, so\n * `Acme_Hello_World` reads `Acme Hello World`, not `AcmeHelloWorld`.\n */\nexport function ascEntityName(displayName: string): string {\n const name = displayName\n .replace(/[^A-Za-z0-9 ]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n if (!name) fail(`cannot build an App Store Connect name from \"${displayName}\"`);\n return name;\n}\n\nexport function bundleIdFor(suffix: string, config: Config): string {\n const base = config.project.baseBundleId;\n return suffix ? `${base}.${suffix}` : base;\n}\n\n/**\n * The home-screen label. An explicit name always wins; otherwise a variant gets\n * `<prefix> <Title>`, so two branches are never two identical icons. A plain\n * build keeps the project's own default.\n */\nexport function displayNameFor(rawSuffix: string, explicit: string, config: Config): string {\n if (explicit) return explicit;\n if (!rawSuffix) return config.variant.displayName;\n return `${labelPrefixFor(config)} ${variantTitle(rawSuffix, config)}`;\n}\n\n/** True when iOS will visibly truncate this label on the home screen. */\nexport function exceedsLabelBudget(label: string, config: Config): boolean {\n return label.length > config.variant.labelBudget;\n}\n\n/**\n * A slug is ONE bundle-id segment. A pasted bundle id is rejected rather than\n * quietly flattened: `--suffix com.example.dev.foo` used to build\n * `com.example.app.dev.comexampledevfoo`.\n */\nexport function assertSingleSegment(value: string, config: Config): string {\n if (value.includes('.')) {\n fail(\n `a variant slug is just the last segment — \"${config.project.baseBundleId}.<slug>\" is ` +\n 'built for you (e.g. \"wave\")',\n );\n }\n return value;\n}\n","/**\n * What this project has registered with Apple, and how to get rid of it.\n *\n * Every `--suffix` install mints permanent account state: a bundle id, one more\n * for each extension, and a provisioning profile apiece. Nothing ever removed\n * them, so they accrue — one set per branch anyone ever tested, plus one per\n * typo.\n *\n * DELETION IS IRREVERSIBLE AND APPLE RESTORES NOTHING, so a dry run is the\n * DEFAULT everywhere: the plan is printed, nothing is sent, and the command\n * succeeds. `yes` executes. Nothing here ever prompts — an agent or a piped\n * session has no terminal to answer with, and the absence of `yes` is already\n * an unambiguous answer.\n *\n * The base bundle id is protected twice over: `groupVariants` never classifies\n * it as a variant, and `assertDeletable` checks again immediately before every\n * DELETE. Losing it breaks signing for every build this project ever makes.\n */\nimport { asArray, connect, type AscClient, type AscDocument } from './asc.js';\nimport type { Boundary } from './boundary.js';\nimport { labelPrefixFor, type Config } from './config.js';\nimport { fail, type Project } from './project.js';\nimport { provisionVariant, type ProvisionedProfile } from './provision.js';\nimport { sanitizeSuffix } from './variant.js';\n\nexport interface RegisteredBundleId {\n id: string;\n identifier: string;\n name: string;\n}\n\nexport interface RegisteredProfile {\n id: string;\n name: string;\n /** ISO 8601, as Apple returns it. Empty when the account did not say. */\n createdDate: string;\n}\n\n/** One variant and everything the account holds for it. */\nexport interface RegisteredVariant {\n suffix: string;\n app: RegisteredBundleId;\n extensions: RegisteredBundleId[];\n profiles: RegisteredProfile[];\n}\n\n/**\n * Identifiers this command must never delete, whatever the grouping believes:\n * the project's own bundle id, and the id of each extension that ships inside\n * the plain build. Both are single-segment children of the base — structurally\n * indistinguishable from a variant without this list.\n */\nexport function protectedBundleIds(config: Config): Set<string> {\n const base = config.project.baseBundleId;\n return new Set([\n base,\n ...config.variant.targets\n .filter((target) => target.bundleIdSuffix)\n .map((target) => `${base}.${target.bundleIdSuffix}`),\n ]);\n}\n\n/** Last line of defence: called immediately before every DELETE. */\nexport function assertDeletable(identifier: string, config: Config): void {\n const base = config.project.baseBundleId;\n if (protectedBundleIds(config).has(identifier)) {\n fail(\n `refusing to delete ${identifier} — it is a core identifier, not a variant.\\n` +\n ' This is a bug: it should never have been selected. Nothing further was deleted.',\n );\n }\n if (!identifier.startsWith(`${base}.`)) {\n fail(\n `refusing to delete ${identifier} — it is not a \"${base}.*\" variant of this project.\\n` +\n ' Remove it from the Apple Developer portal by hand if you really mean to.',\n );\n }\n}\n\nexport async function fetchBundleIds(client: AscClient): Promise<RegisteredBundleId[]> {\n const result = await client.request<AscDocument>('GET', '/v1/bundleIds?limit=200');\n if (result.status !== 200) {\n fail(\n `could not list bundle ids (HTTP ${result.status}).\\n` +\n ' Check that the App Store Connect key still has access to this team.',\n );\n }\n return asArray(result.body.data).map((row) => ({\n id: row.id,\n identifier: String(row.attributes.identifier ?? ''),\n name: String(row.attributes.name ?? ''),\n }));\n}\n\nexport async function fetchProfiles(client: AscClient): Promise<RegisteredProfile[]> {\n const result = await client.request<AscDocument>('GET', '/v1/profiles?limit=200');\n if (result.status !== 200) {\n fail(\n `could not list provisioning profiles (HTTP ${result.status}).\\n` +\n ' Check that the App Store Connect key still has access to this team.',\n );\n }\n return asArray(result.body.data).map((row) => ({\n id: row.id,\n name: String(row.attributes.name ?? ''),\n createdDate: String(row.attributes.createdDate ?? ''),\n }));\n}\n\n/**\n * Group the account's flat lists into variants.\n *\n * A variant's app id is `<base>.<slug>` where `<slug>` is ONE segment and is not\n * a configured extension suffix. That second clause is load-bearing:\n * `<base>.uploadwidget` is the extension every plain build ships, a sibling of\n * the base rather than a variant, and it passes the single-segment test. Without\n * the exclusion, pruning deletes it and plain builds stop signing. A variant's\n * OWN extension is `<base>.<slug>.uploadwidget` — two segments, so it is never\n * mistaken for a variant of its own.\n */\nexport function groupVariants(\n bundleIds: RegisteredBundleId[],\n profiles: RegisteredProfile[],\n config: Config,\n): RegisteredVariant[] {\n const prefix = `${config.project.baseBundleId}.`;\n const protectedIds = protectedBundleIds(config);\n const profilePrefix = config.variant.profilePrefix ?? labelPrefixFor(config);\n\n return bundleIds\n .filter((bundle) => {\n if (protectedIds.has(bundle.identifier)) return false;\n if (!bundle.identifier.startsWith(prefix)) return false;\n const slug = bundle.identifier.slice(prefix.length);\n return slug.length > 0 && !slug.includes('.');\n })\n .map((app) => {\n const suffix = app.identifier.slice(prefix.length);\n return {\n suffix,\n app,\n extensions: bundleIds.filter((bundle) =>\n bundle.identifier.startsWith(`${app.identifier}.`),\n ),\n // Matched on the prefix rather than the exact names `profileNameFor`\n // mints, so a profile for a target that has since left the config is\n // still swept up with its bundle id.\n profiles: profiles.filter((profile) =>\n profile.name.startsWith(`${profilePrefix} ${suffix} `),\n ),\n };\n })\n .sort((a, b) => a.suffix.localeCompare(b.suffix));\n}\n\n/** Everything this project has registered, in one round trip pair. */\nexport async function readAccount(\n boundary: Boundary,\n project: Project,\n): Promise<{ client: AscClient; variants: RegisteredVariant[] }> {\n const client = connect(boundary, project.config);\n boundary.log.step('reading the developer account');\n const [bundleIds, profiles] = await Promise.all([fetchBundleIds(client), fetchProfiles(client)]);\n return { client, variants: groupVariants(bundleIds, profiles, project.config) };\n}\n\n/* -------------------------------------------------------------------------- */\n/* ls */\n/* -------------------------------------------------------------------------- */\n\n/**\n * When this variant first appeared.\n *\n * Taken from the earliest profile, because App Store Connect does not date a\n * bundle id at all — the resource carries only its identifier, name, platform\n * and seed id. A variant with no profile left therefore has no date to show.\n */\nexport function firstSeen(variant: RegisteredVariant): string {\n const dates = variant.profiles\n .map((profile) => profile.createdDate)\n .filter(Boolean)\n .sort();\n return dates[0]?.slice(0, 10) ?? '—';\n}\n\nexport interface VariantRecord {\n slug: string;\n bundleId: string;\n name: string;\n extensions: string[];\n profileCount: number;\n /** `YYYY-MM-DD` of the earliest profile, or null when none is left. */\n created: string | null;\n}\n\nexport const toRecords = (variants: RegisteredVariant[]): VariantRecord[] =>\n variants.map((variant) => ({\n slug: variant.suffix,\n bundleId: variant.app.identifier,\n name: variant.app.name,\n extensions: variant.extensions.map((extension) => extension.identifier),\n profileCount: variant.profiles.length,\n created: firstSeen(variant) === '—' ? null : firstSeen(variant),\n }));\n\nconst COLUMNS = ['SLUG', 'BUNDLE ID', 'PROFILES', 'CREATED'] as const;\n\n/**\n * One line per variant, columns padded to the widest cell. The header is always\n * printed, even with nothing to list, so a script can parse the shape of the\n * output without special-casing \"empty\".\n */\nexport function renderTable(variants: RegisteredVariant[]): string {\n const rows = variants.map((variant) => [\n variant.suffix,\n variant.app.identifier,\n String(variant.profiles.length),\n firstSeen(variant),\n ]);\n const widths = COLUMNS.map((heading, column) =>\n Math.max(heading.length, ...rows.map((row) => row[column]!.length), 0),\n );\n const line = (cells: readonly string[]): string =>\n cells\n .map((cell, column) => (column === cells.length - 1 ? cell : cell.padEnd(widths[column]!)))\n .join(' ');\n return [line(COLUMNS), ...rows.map(line)].join('\\n');\n}\n\n/**\n * The listing.\n *\n * The payload goes to STDOUT, not through `boundary.log` — every logger there is\n * stderr, and `bundles ls --json | jq` has to receive something. It is also\n * returned, so a caller can capture it instead and so the shape is testable\n * without scraping a stream.\n */\nexport async function listBundles(\n boundary: Boundary,\n project: Project,\n options: { json?: boolean } = {},\n): Promise<string> {\n const { variants } = await readAccount(boundary, project);\n if (variants.length === 0 && !options.json) {\n boundary.log.info(`no variants of ${project.config.project.baseBundleId} are registered.`);\n }\n const output = options.json\n ? JSON.stringify(toRecords(variants), null, 2)\n : renderTable(variants);\n console.log(output);\n return output;\n}\n\n/* -------------------------------------------------------------------------- */\n/* removal */\n/* -------------------------------------------------------------------------- */\n\nfunction describe(variant: RegisteredVariant, reason?: string): string[] {\n const lines = [\n ` ${variant.app.identifier} \"${variant.app.name}\"${reason ? ` — ${reason}` : ''}`,\n ];\n for (const extension of variant.extensions) lines.push(` ${extension.identifier}`);\n for (const profile of variant.profiles) lines.push(` profile: ${profile.name}`);\n if (variant.extensions.length === 0 && variant.profiles.length === 0) {\n lines.push(' (no extensions or profiles)');\n }\n return lines;\n}\n\n/**\n * Profiles, then extensions, then the app — the reverse of the order they were\n * created in. A bundle id with a live profile cannot be removed, and an app id\n * is the prefix of its extensions' ids.\n */\nasync function deleteVariant(\n boundary: Boundary,\n client: AscClient,\n config: Config,\n variant: RegisteredVariant,\n): Promise<void> {\n // Re-checked here, at the point of no return, rather than trusting whatever\n // selected this variant three functions ago.\n assertDeletable(variant.app.identifier, config);\n for (const extension of variant.extensions) assertDeletable(extension.identifier, config);\n\n for (const profile of variant.profiles) {\n const result = await client.request('DELETE', `/v1/profiles/${profile.id}`);\n if (result.status !== 204) {\n boundary.log.warn(`profile \"${profile.name}\" was not deleted (HTTP ${result.status})`);\n }\n }\n for (const extension of variant.extensions) {\n const result = await client.request('DELETE', `/v1/bundleIds/${extension.id}`);\n if (result.status !== 204) {\n fail(\n `${extension.identifier} was not deleted (HTTP ${result.status}).\\n` +\n ' Delete it in the Apple Developer portal, then re-run.',\n );\n }\n }\n const result = await client.request('DELETE', `/v1/bundleIds/${variant.app.id}`);\n if (result.status !== 204) {\n fail(\n `${variant.app.identifier} was not deleted (HTTP ${result.status}).\\n` +\n ' A profile may still reference it — check the Apple Developer portal.',\n );\n }\n}\n\nexport interface RemovalResult {\n /** Slugs that were, or would have been, removed. */\n slugs: string[];\n /** True when nothing was sent — the default. */\n dryRun: boolean;\n}\n\n/** The shared tail of `rm` and `prune`: print the plan, then stop or delete. */\nasync function removeSelected(\n boundary: Boundary,\n client: AscClient,\n project: Project,\n selected: Array<{ variant: RegisteredVariant; reason?: string }>,\n yes: boolean,\n): Promise<RemovalResult> {\n boundary.log.info(\n yes\n ? 'deleting from the Apple Developer account:'\n : 'would delete from the Apple Developer account:',\n );\n for (const { variant, reason } of selected) {\n boundary.log.info(describe(variant, reason).join('\\n'));\n }\n\n const slugs = selected.map(({ variant }) => variant.suffix);\n if (!yes) {\n boundary.log.warn(\n `dry run — nothing was deleted. Re-run with -y to remove ${slugs.length} variant(s).`,\n );\n return { slugs, dryRun: true };\n }\n\n for (const { variant } of selected) {\n boundary.log.step(`deleting ${variant.app.identifier}`);\n await deleteVariant(boundary, client, project.config, variant);\n boundary.log.info(`removed ${variant.app.identifier}`);\n }\n boundary.log.info(`done — ${slugs.length} variant(s) removed.`);\n return { slugs, dryRun: false };\n}\n\nexport async function removeBundles(\n boundary: Boundary,\n project: Project,\n options: { suffixes: string[]; yes?: boolean },\n): Promise<RemovalResult> {\n if (options.suffixes.length === 0) {\n fail(\n 'name at least one variant to remove.\\n' +\n ' `jetbridge bundles ls` shows what is registered; `bundles prune` removes the stale ones.',\n );\n }\n\n const { client, variants } = await readAccount(boundary, project);\n const selected = options.suffixes.map((slug) => {\n const variant = variants.find((candidate) => candidate.suffix === slug);\n if (!variant) {\n fail(\n `no variant \"${slug}\" is registered — nothing was deleted.\\n` +\n ` Registered: ${variants.map((candidate) => candidate.suffix).join(', ') || '(none)'}`,\n );\n }\n return { variant };\n });\n\n return removeSelected(boundary, client, project, selected, Boolean(options.yes));\n}\n\n/* -------------------------------------------------------------------------- */\n/* prune */\n/* -------------------------------------------------------------------------- */\n\n/**\n * The slug of every branch that still exists on the remote.\n *\n * A slug is derived from a branch name by `sanitizeSuffix`, which is lossy —\n * `feat/seeded-feed` and `seeded_feed` both collapse to `seededfeed`. So the\n * branch names are pushed through the SAME function and compared as slugs,\n * rather than trying to invert a slug back into a branch name, which cannot be\n * done.\n *\n * `ls-remote` rather than a local branch list: a branch nobody on this machine\n * ever fetched is still alive, and reading it as dead would delete a colleague's\n * variant.\n */\nexport async function liveBranchSlugs(boundary: Boundary, project: Project): Promise<Set<string>> {\n const inRepo = await boundary.exec.run('git', ['rev-parse', '--is-inside-work-tree'], {\n cwd: project.root,\n allowFail: true,\n });\n // Exit 0 is not enough: inside a `.git` directory, or with GIT_DIR set, git\n // succeeds and prints `false`.\n if (!inRepo.ok || inRepo.stdout.trim() !== 'true') {\n fail(\n 'prune decides what is stale from the branches on the remote, and this is not a git ' +\n 'checkout.\\n Remove them by name instead: `jetbridge bundles rm <slug>`.',\n );\n }\n\n const remote = await boundary.exec.run('git', ['ls-remote', '--heads', 'origin'], {\n cwd: project.root,\n allowFail: true,\n });\n // Refusing here is the whole safety property. Unreachable must never read as\n // \"every branch is gone\", which would take the entire account with it.\n if (!remote.ok) {\n fail(\n 'could not reach the git remote, so prune cannot tell which branches are gone.\\n' +\n ` ${(remote.stderr || remote.stdout).trim().split('\\n').slice(-3).join('\\n ')}\\n` +\n ' Nothing was deleted. Reconnect and re-run, or name them with `bundles rm <slug>`.',\n );\n }\n\n const branches = remote.stdout\n .split('\\n')\n .map((line) => /\\srefs\\/heads\\/(.+)$/.exec(line.trim())?.[1])\n .filter((branch): branch is string => Boolean(branch));\n // A repository with no branches at all is not a real answer either — far more\n // likely a remote that replied with something this does not understand.\n if (branches.length === 0) {\n fail(\n 'the git remote reported no branches at all, which would mark every variant stale.\\n' +\n ' Nothing was deleted. Check `git ls-remote --heads origin` by hand.',\n );\n }\n\n const slugs = new Set<string>();\n for (const branch of branches) {\n try {\n slugs.add(sanitizeSuffix(branch, project.config));\n } catch {\n // A ref with no letters or digits names no variant; it just is not one.\n }\n }\n return slugs;\n}\n\nexport async function pruneBundles(\n boundary: Boundary,\n project: Project,\n options: { yes?: boolean } = {},\n): Promise<RemovalResult> {\n // Before the account read: being offline is the answer either way, and it\n // costs nothing to find out first.\n const live = await liveBranchSlugs(boundary, project);\n const { client, variants } = await readAccount(boundary, project);\n\n const stale = variants.filter((variant) => !live.has(variant.suffix));\n const kept = variants.length - stale.length;\n boundary.log.info(\n `${variants.length} variant(s) registered, ${kept} with a branch still on the remote.`,\n );\n if (stale.length === 0) {\n boundary.log.info('nothing to prune.');\n return { slugs: [], dryRun: false };\n }\n\n return removeSelected(\n boundary,\n client,\n project,\n stale.map((variant) => ({ variant, reason: 'no branch on the remote maps to this slug' })),\n Boolean(options.yes),\n );\n}\n\n/* -------------------------------------------------------------------------- */\n/* provision */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Register a variant and mint its profiles without building anything.\n *\n * The only route to a refresh after a certificate rotation or a newly registered\n * phone that does not also cost a full build.\n */\nexport async function provisionBundles(\n boundary: Boundary,\n project: Project,\n options: { suffix: string; displayName: string },\n): Promise<ProvisionedProfile[]> {\n const { suffix, displayName } = options;\n if (!suffix) {\n fail(\n 'name the variant to provision, e.g. `jetbridge bundles provision wave`.\\n' +\n ' A plain build signs against the profile the project already has — there is nothing\\n' +\n ' for this command to register.',\n );\n }\n const profiles = await provisionVariant(boundary, project, { suffix, displayName });\n for (const profile of profiles) {\n boundary.log.info(`${profile.bundleId} → \"${profile.profileName}\" (${profile.installedAt})`);\n }\n boundary.log.info(`done — ${profiles.length} profile(s) installed for \"${suffix}\".`);\n return profiles;\n}\n","/**\n * `jetbridge init` — the only thing that should ever write a config file.\n *\n * The order is fixed, and each step exists because of a failure it stops:\n * detect (so the wizard asks as little as possible) → ask what is left → verify\n * what can be verified cheaply (credentials resolve, the bucket round-trips) →\n * dry run (show the file and the commands, confirm) → write → read the file\n * back through `parseConfig`, so what the wizard produced is provably a file\n * the rest of the tool accepts.\n *\n * There is always a flag-driven route through: `--yes` behind a pipe answers\n * nothing and fails loudly, naming the flag that supplies each value it could\n * not infer. A prompt in CI hangs forever, which is worse than any error.\n */\nimport { join, resolve } from 'node:path';\nimport { localCredentials, missingCredentialsMessage } from './asc.js';\nimport type { Boundary } from './boundary.js';\nimport {\n CONFIG_FILENAMES,\n CONFIG_VERSION,\n formatConfigErrors,\n parseConfig,\n type Config,\n} from './config.js';\nimport { detectProject, type Detection, type Suggestion } from './detect.js';\nimport { fail, projectFrom, type Project } from './project.js';\nimport type { Prompter } from './prompts.js';\n\n/** Editors autocomplete against the published schema, not against this file. */\nexport const SCHEMA_URL = 'https://unpkg.com/jetbridge/schema/v1.json';\n\nconst DEFAULT_CONFIGURATIONS = ['Debug', 'Release'];\n\n/* -------------------------------------------------------------------------- */\n/* Assembly */\n/* -------------------------------------------------------------------------- */\n\nexport interface TargetInput {\n name: string;\n bundleIdSuffix?: string;\n entitlements?: string;\n}\n\nexport interface ConfigInput {\n iosDir: string;\n xcodeproj?: string;\n xcworkspace?: string;\n scheme: string;\n teamId: string;\n baseBundleId: string;\n projectYml?: string;\n xcodegen?: boolean;\n configurations: { available: string[]; wired: string; sim: string; archive: string };\n displayName: string;\n targets: TargetInput[];\n credentials: { ascKeyId: string; ascIssuerId: string };\n ota?: { bucket: string; region: string; endpoint?: string; publicBaseUrl: string };\n}\n\n/**\n * The config as an ordinary object, in schema order. Key order is the literal's\n * order, so the written file reads top-down the way the schema is documented\n * rather than the way the wizard happened to ask.\n */\nexport function assembleConfig(input: ConfigInput): Record<string, unknown> {\n return {\n $schema: SCHEMA_URL,\n configVersion: CONFIG_VERSION,\n project: {\n iosDir: input.iosDir,\n ...(input.xcodeproj ? { xcodeproj: input.xcodeproj } : {}),\n ...(input.xcworkspace ? { xcworkspace: input.xcworkspace } : {}),\n scheme: input.scheme,\n teamId: input.teamId,\n baseBundleId: input.baseBundleId,\n ...(input.projectYml ? { projectYml: input.projectYml } : {}),\n ...(input.xcodegen ? { xcodegen: true } : {}),\n },\n configurations: {\n available: input.configurations.available,\n wired: input.configurations.wired,\n sim: input.configurations.sim,\n archive: input.configurations.archive,\n },\n variant: {\n displayName: input.displayName,\n targets: input.targets.map((target) => ({\n name: target.name,\n ...(target.bundleIdSuffix ? { bundleIdSuffix: target.bundleIdSuffix } : {}),\n ...(target.entitlements ? { entitlements: target.entitlements } : {}),\n })),\n },\n credentials: {\n ascKeyId: input.credentials.ascKeyId,\n ascIssuerId: input.credentials.ascIssuerId,\n },\n ...(input.ota\n ? {\n ota: {\n storage: {\n bucket: input.ota.bucket,\n region: input.ota.region,\n ...(input.ota.endpoint ? { endpoint: input.ota.endpoint } : {}),\n publicBaseUrl: input.ota.publicBaseUrl,\n },\n },\n }\n : {}),\n };\n}\n\nexport const serializeConfig = (value: unknown): string => `${JSON.stringify(value, null, 2)}\\n`;\n\n/* -------------------------------------------------------------------------- */\n/* Dry run */\n/* -------------------------------------------------------------------------- */\n\nexport interface CommandPreview {\n mode: 'wired' | 'sim' | 'archive';\n command: string;\n}\n\nconst quote = (value: string): string => (/[\\s]/.test(value) ? `'${value}'` : value);\n\n/**\n * What each mode will run, as the config determines it. Signing flags and the\n * build number are decided at run time and left out — the point of the preview\n * is the scheme, the configuration and the destination, which are exactly what\n * the answers just chose.\n */\nexport function commandPreviews(project: Project): CommandPreview[] {\n const { config } = project;\n const target = project.xcodebuildTarget().map(quote).join(' ');\n const line = (verb: string, configuration: string, destination: string): string =>\n [\n 'xcodebuild',\n verb,\n target,\n '-scheme',\n quote(config.project.scheme),\n '-configuration',\n quote(configuration),\n '-destination',\n quote(destination),\n ].join(' ');\n return [\n { mode: 'wired', command: line('build', config.configurations.wired, 'generic/platform=iOS') },\n { mode: 'sim', command: line('build', config.configurations.sim, 'platform=iOS Simulator') },\n {\n mode: 'archive',\n command: line('archive', config.configurations.archive, 'generic/platform=iOS'),\n },\n ];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Repair */\n/* -------------------------------------------------------------------------- */\n\nexport interface Drift {\n /** Dotted config path, e.g. `project.scheme`. */\n path: string;\n current: unknown;\n detected: unknown;\n /** Why the current value is suspect, when it is more than \"they differ\". */\n note?: string;\n source: string;\n}\n\nconst sameValue = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n/** What the project says that the existing config does not. */\nexport function detectDrift(config: Config, detection: Detection): Drift[] {\n const drift: Drift[] = [];\n const add = (\n path: string,\n current: unknown,\n detected: Suggestion<unknown> | undefined,\n note?: string,\n ): void => {\n if (!detected || sameValue(current, detected.value)) return;\n drift.push({\n path,\n current,\n detected: detected.value,\n source: detected.source,\n ...(note ? { note } : {}),\n });\n };\n\n add('project.iosDir', config.project.iosDir, detection.iosDir);\n add('project.xcodeproj', config.project.xcodeproj, detection.xcodeproj);\n add('project.xcworkspace', config.project.xcworkspace, detection.xcworkspace);\n add('project.teamId', config.project.teamId, detection.teamId);\n add('project.baseBundleId', config.project.baseBundleId, detection.baseBundleId);\n\n // A scheme is only drift when the project no longer has one by that name.\n // Renaming a scheme is the failure this catches; preferring a different one\n // is the developer's business.\n if (detection.schemes.length > 0 && !detection.schemes.includes(config.project.scheme)) {\n const replacement = detection.scheme?.value ?? detection.schemes[0]!;\n drift.push({\n path: 'project.scheme',\n current: config.project.scheme,\n detected: replacement,\n note: `the project has no scheme named \"${config.project.scheme}\" any more`,\n source: detection.scheme?.source ?? detection.iosDir.source,\n });\n }\n\n const available = detection.configurations;\n if (available) {\n add('configurations.available', config.configurations.available, available);\n for (const field of ['wired', 'sim', 'archive'] as const) {\n const current = config.configurations[field];\n if (available.value.includes(current)) continue;\n const fallback = field === 'archive' ? 'Release' : 'Debug';\n drift.push({\n path: `configurations.${field}`,\n current,\n detected: available.value.includes(fallback) ? fallback : available.value[0]!,\n note: `the project has no \"${current}\" build configuration any more`,\n source: available.source,\n });\n }\n }\n return drift;\n}\n\n/** Set one dotted path on the raw JSON, creating nothing that is not already there. */\nfunction setPath(raw: Record<string, unknown>, path: string, value: unknown): void {\n const parts = path.split('.');\n let node = raw;\n for (const part of parts.slice(0, -1)) {\n const next = node[part];\n if (typeof next !== 'object' || next === null) node[part] = {};\n node = node[part] as Record<string, unknown>;\n }\n node[parts.at(-1)!] = value;\n}\n\n/* -------------------------------------------------------------------------- */\n/* The wizard */\n/* -------------------------------------------------------------------------- */\n\nexport interface OtaStorageInput {\n bucket: string;\n region: string;\n endpoint?: string;\n publicBaseUrl: string;\n prefix: string;\n}\n\nexport interface OtaRoundTripResult {\n ok: boolean;\n /** One line, shown either way: what was proved, or what broke. */\n detail: string;\n}\n\n/**\n * Upload a small object, fetch it back over the public base URL, delete it.\n * Injected: a wrong bucket policy is worth ten seconds here instead of a\n * fifteen-minute archive that cannot be installed.\n */\nexport type OtaRoundTrip = (\n boundary: Boundary,\n storage: OtaStorageInput,\n) => Promise<OtaRoundTripResult>;\n\nexport interface InitOptions {\n /** Where the config file goes. Defaults to the working directory. */\n cwd?: string;\n /** Accept every detected default and never prompt. */\n yes?: boolean;\n iosDir?: string;\n xcodeproj?: string;\n xcworkspace?: string;\n scheme?: string;\n teamId?: string;\n bundleId?: string;\n displayName?: string;\n configurations?: string[];\n wired?: string;\n sim?: string;\n archive?: string;\n ascKeyIdEnv?: string;\n ascIssuerIdEnv?: string;\n ota?: boolean;\n otaBucket?: string;\n otaRegion?: string;\n otaEndpoint?: string;\n otaPublicBaseUrl?: string;\n}\n\nexport interface InitDeps {\n prompts: Prompter;\n otaRoundTrip?: OtaRoundTrip;\n}\n\nexport interface InitResult {\n status: 'written' | 'declined' | 'unchanged';\n configPath: string;\n config?: Config;\n /** What a repair pass found, empty on a first run. */\n drift: Drift[];\n}\n\nconst teamIdProblem = (value: string): string | undefined =>\n /^[A-Z0-9]{10}$/.test(value) ? undefined : 'an Apple team id is 10 uppercase alphanumerics';\n\nconst bundleIdProblem = (value: string): string | undefined =>\n /^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$/.test(value)\n ? undefined\n : 'a reverse-DNS bundle id, e.g. io.acme.app.dev';\n\nconst httpsProblem = (value: string): string | undefined => {\n if (!value.startsWith('https://')) return 'must be https:// — iOS refuses to install over http';\n try {\n new URL(value);\n return undefined;\n } catch {\n return 'not a URL';\n }\n};\n\nconst envNameProblem = (value: string): string | undefined =>\n /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value) ? undefined : 'must be a plain identifier';\n\n/**\n * Whether this run answers its own questions.\n *\n * ONE definition, because every prompt site in this file is guarded by it and a\n * site that forgets is a hang. Note which way round it reads: no terminal is\n * sufficient on its own, so an agent needs no flag and no CI variable to get\n * the unattended path. `--yes` is how a person opts into it deliberately.\n */\nconst isAuto = (boundary: Boundary, options: InitOptions): boolean =>\n options.yes === true || !boundary.interactive;\n\nexport async function runInit(\n boundary: Boundary,\n options: InitOptions,\n deps: InitDeps,\n): Promise<InitResult> {\n const root = resolve(options.cwd ?? boundary.cwd());\n const configPath = join(root, CONFIG_FILENAMES[0]);\n // The exact path, never the upward walk: a config in a parent directory is\n // somebody else's project, not this one to repair.\n const existing = boundary.fs.exists(configPath);\n\n const detection = detectProject(boundary, {\n root,\n ...(options.iosDir ? { iosDir: options.iosDir } : {}),\n });\n for (const warning of detection.warnings) boundary.log.warn(`! ${warning}`);\n\n return existing\n ? repair(boundary, options, deps, configPath, detection)\n : create(boundary, options, deps, configPath, detection);\n}\n\nasync function create(\n boundary: Boundary,\n options: InitOptions,\n deps: InitDeps,\n configPath: string,\n detection: Detection,\n): Promise<InitResult> {\n const { prompts } = deps;\n // No terminal means no questions, so the flags have to carry everything.\n const auto = isAuto(boundary, options);\n const missing: Array<{ field: string; flag: string }> = [];\n\n const ask = async (spec: {\n field: string;\n flag: string;\n message: string;\n given?: string;\n detected?: Suggestion<string>;\n validate?: (value: string) => string | undefined;\n }): Promise<string> => {\n if (spec.given !== undefined) {\n const problem = spec.validate?.(spec.given);\n if (problem) fail(`${spec.flag} ${spec.given}: ${problem}`);\n return spec.given;\n }\n if (auto) {\n if (spec.detected) return spec.detected.value;\n missing.push({ field: spec.field, flag: spec.flag });\n return '';\n }\n return prompts.text({\n name: spec.field,\n message: spec.message,\n ...(spec.detected\n ? { initial: spec.detected.value, hint: `from ${spec.detected.source}` }\n : {}),\n ...(spec.validate ? { validate: spec.validate } : {}),\n });\n };\n\n const iosDir = await ask({\n field: 'project.iosDir',\n flag: '--ios-dir',\n message: 'Directory holding the Xcode project',\n given: options.iosDir,\n detected: detection.iosDir,\n });\n const xcodeproj = options.xcodeproj ?? detection.xcodeproj?.value;\n const xcworkspace = options.xcworkspace ?? detection.xcworkspace?.value;\n if (!xcodeproj && !xcworkspace) {\n missing.push({ field: 'project.xcodeproj', flag: '--xcodeproj' });\n }\n\n const scheme = await ask({\n field: 'project.scheme',\n flag: '--scheme',\n message: 'Scheme to build',\n given: options.scheme,\n detected: detection.scheme,\n });\n const teamId = await ask({\n field: 'project.teamId',\n flag: '--team-id',\n message: 'Apple team id',\n given: options.teamId,\n detected: detection.teamId,\n validate: teamIdProblem,\n });\n const baseBundleId = await ask({\n field: 'project.baseBundleId',\n flag: '--bundle-id',\n message: 'Bundle id a variant build extends',\n given: options.bundleId,\n detected: detection.baseBundleId,\n validate: bundleIdProblem,\n });\n const displayName = await ask({\n field: 'variant.displayName',\n flag: '--display-name',\n message: 'Home-screen label for a plain build',\n given: options.displayName,\n detected: detection.displayName,\n });\n\n const available = options.configurations ?? detection.configurations?.value;\n if (!available) {\n boundary.log.warn(\n `! no build configurations were read out of the project, so ${DEFAULT_CONFIGURATIONS.join(\n ' and ',\n )} are assumed.`,\n );\n }\n const configurations = available ?? DEFAULT_CONFIGURATIONS;\n\n const pickConfiguration = async (\n field: 'wired' | 'sim' | 'archive',\n flag: string,\n message: string,\n given: string | undefined,\n preferred: string,\n ): Promise<string> => {\n if (given !== undefined) {\n if (!configurations.includes(given)) {\n fail(`${flag} ${given}: the project has no \"${given}\" build configuration`);\n }\n return given;\n }\n // Naming a configuration the project does not have fails deep inside\n // xcodebuild, so a missing default is asked for, never assumed.\n if (configurations.includes(preferred)) return preferred;\n if (auto) {\n missing.push({ field: `configurations.${field}`, flag });\n return '';\n }\n return prompts.select({\n name: `configurations.${field}`,\n message,\n options: configurations.map((value) => ({ value })),\n });\n };\n\n const wired = await pickConfiguration(\n 'wired',\n '--configuration-wired',\n 'Build configuration for a cabled install',\n options.wired,\n 'Debug',\n );\n const sim = await pickConfiguration(\n 'sim',\n '--configuration-sim',\n 'Build configuration for a simulator install',\n options.sim,\n 'Debug',\n );\n const archive = await pickConfiguration(\n 'archive',\n '--configuration-archive',\n 'Build configuration for an archive',\n options.archive,\n 'Release',\n );\n\n const ascKeyId = await ask({\n field: 'credentials.ascKeyId',\n flag: '--asc-key-id-env',\n message: 'Environment variable holding the App Store Connect key id',\n given: options.ascKeyIdEnv,\n detected: { value: 'ASC_API_KEY_ID', source: 'the jetbridge default' },\n validate: envNameProblem,\n });\n const ascIssuerId = await ask({\n field: 'credentials.ascIssuerId',\n flag: '--asc-issuer-id-env',\n message: 'Environment variable holding the App Store Connect issuer id',\n given: options.ascIssuerIdEnv,\n detected: { value: 'ASC_API_ISSUER_ID', source: 'the jetbridge default' },\n validate: envNameProblem,\n });\n\n let xcodegen = false;\n if (detection.projectYml) {\n xcodegen = auto\n ? true\n : await prompts.confirm({\n name: 'project.xcodegen',\n message: `Run xcodegen from ${detection.projectYml.value} before each build?`,\n initial: true,\n });\n }\n\n const wantsOta =\n options.ota ??\n (auto\n ? false\n : await prompts.confirm({\n name: 'ota.enabled',\n message: 'Deliver builds over the air to your own bucket?',\n initial: false,\n }));\n\n let ota: ConfigInput['ota'];\n if (wantsOta) {\n const bucket = await ask({\n field: 'ota.storage.bucket',\n flag: '--ota-bucket',\n message: 'Bucket builds are uploaded to',\n given: options.otaBucket,\n });\n const region = await ask({\n field: 'ota.storage.region',\n flag: '--ota-region',\n message: 'Bucket region',\n given: options.otaRegion,\n detected: { value: 'us-east-1', source: 'the jetbridge default' },\n });\n const endpoint =\n options.otaEndpoint ??\n (auto\n ? ''\n : await prompts.text({\n name: 'ota.storage.endpoint',\n message: 'S3-compatible endpoint (blank for AWS)',\n }));\n const publicBaseUrl = await ask({\n field: 'ota.storage.publicBaseUrl',\n flag: '--ota-public-base-url',\n message: 'Public https:// base URL the uploads are readable from',\n given: options.otaPublicBaseUrl,\n validate: httpsProblem,\n });\n ota = { bucket, region, publicBaseUrl, ...(endpoint ? { endpoint } : {}) };\n }\n\n if (missing.length > 0) {\n fail(\n 'these could not be worked out from the project, and there is nobody to ask:\\n' +\n missing.map((entry) => ` ${entry.field} — pass ${entry.flag}`).join('\\n'),\n );\n }\n\n if (ota) {\n const kept = await verifyOta(boundary, deps, ota, auto);\n if (!kept) return { status: 'declined', configPath, drift: [] };\n }\n\n const raw = assembleConfig({\n iosDir,\n ...(xcodeproj ? { xcodeproj } : {}),\n ...(xcworkspace ? { xcworkspace } : {}),\n scheme,\n teamId,\n baseBundleId,\n ...(detection.projectYml ? { projectYml: detection.projectYml.value } : {}),\n xcodegen,\n configurations: { available: configurations, wired, sim, archive },\n displayName,\n targets: detection.targets.map((target) => ({\n name: target.name,\n ...(target.bundleIdSuffix ? { bundleIdSuffix: target.bundleIdSuffix } : {}),\n ...(target.entitlements ? { entitlements: target.entitlements.value } : {}),\n })),\n credentials: { ascKeyId, ascIssuerId },\n ...(ota ? { ota } : {}),\n });\n\n return finish(boundary, deps, configPath, raw, auto, options, []);\n}\n\nconst KEEP_OTA = { name: 'ota.continue', message: 'Keep these OTA settings anyway?' };\n\n/** The failed-check path: warn with the reason, then offer to go on. */\nasync function verifyOta(\n boundary: Boundary,\n deps: InitDeps,\n ota: NonNullable<ConfigInput['ota']>,\n auto: boolean,\n): Promise<boolean> {\n if (!deps.otaRoundTrip) {\n // A wiring gap, not a wrong answer: there is nothing to reject.\n boundary.log.warn(\n '! the OTA settings were not verified — the bucket round trip was skipped because no ' +\n 'checker was wired in.',\n );\n return auto ? true : deps.prompts.confirm({ ...KEEP_OTA, initial: false });\n }\n\n const result = await deps.otaRoundTrip(boundary, { ...ota, prefix: 'builds' });\n if (result.ok) {\n boundary.log.info(`✓ ${result.detail}`);\n return true;\n }\n boundary.log.warn(`! the OTA settings could not be verified: ${result.detail}`);\n // Under `--yes` there is nobody to overrule the check, and a config that\n // cannot deliver is worse than a non-zero exit. Leave `--ota` off to skip it.\n if (auto) {\n fail(\n `the OTA round trip failed: ${result.detail}.\\n` +\n ' Fix the bucket, or re-run without --ota to leave over-the-air delivery out.',\n );\n }\n return deps.prompts.confirm({ ...KEEP_OTA, initial: false });\n}\n\n/**\n * The config stores names, so the values behind them are checked here and\n * nowhere else — and a name that does not resolve is a warning, never a\n * failure: the machine that runs `init` is not always the machine that signs.\n */\nfunction warnAboutCredentials(boundary: Boundary, config: Config): void {\n const unresolved = (\n [\n ['credentials.ascKeyId', config.credentials.ascKeyId],\n ['credentials.ascIssuerId', config.credentials.ascIssuerId],\n ] as const\n ).filter(([, name]) => boundary.env(name) === undefined);\n\n for (const [field, name] of unresolved) {\n boundary.log.warn(\n `! ${name} is not set in this environment — ${field} names it, and anything that talks ` +\n 'to App Store Connect will fail until it resolves.',\n );\n }\n // The key file is found by search, so `credentials.ascKeyPath` being unset is\n // normal — the key being nowhere on the search path is not.\n if (unresolved.length === 0 && localCredentials(boundary, config) === null) {\n boundary.log.warn(`! ${missingCredentialsMessage(config)}`);\n }\n}\n\n/** Dry run, confirm, write, and read the file back through the validator. */\nasync function finish(\n boundary: Boundary,\n deps: InitDeps,\n configPath: string,\n raw: Record<string, unknown>,\n auto: boolean,\n options: InitOptions,\n drift: Drift[],\n): Promise<InitResult> {\n const checked = parseConfig(raw);\n if (!checked.ok) {\n fail(`the answers do not make a valid config:\\n${formatConfigErrors(checked.errors)}`);\n }\n\n warnAboutCredentials(boundary, checked.config);\n\n const contents = serializeConfig(raw);\n deps.prompts.note(contents.trimEnd(), configPath);\n for (const preview of commandPreviews(projectFrom(configPath, checked.config))) {\n boundary.log.info(` ${preview.mode.padEnd(7)} ${preview.command}`);\n }\n\n if (auto) {\n // Nothing has been written yet, and there is no way to ask. `--yes` is the\n // consent; without it, a pipe would write a file nobody looked at.\n if (options.yes !== true) {\n fail(`nothing was written — re-run with --yes to accept these values without a terminal.`);\n }\n } else {\n const write = await deps.prompts.confirm({\n name: 'write',\n message: `Write ${configPath}?`,\n initial: true,\n });\n if (!write) {\n boundary.log.info('nothing was written.');\n return { status: 'declined', configPath, drift };\n }\n }\n\n boundary.fs.write(configPath, contents);\n\n // Read it back off disk rather than trusting the object in hand: the file is\n // what every later command loads.\n let written: unknown;\n try {\n written = JSON.parse(boundary.fs.read(configPath));\n } catch (e) {\n return fail(`${configPath} was written but is not valid JSON — ${(e as Error).message}`);\n }\n const reread = parseConfig(written);\n if (!reread.ok) {\n fail(\n `${configPath} was written but jetbridge refuses it:\\n${formatConfigErrors(reread.errors)}`,\n );\n }\n boundary.log.info(`wrote ${configPath}`);\n return { status: 'written', configPath, config: reread.config, drift };\n}\n\n/**\n * A second `init` is a repair pass, not a fresh start: only the fields the\n * project disagrees with are offered, and everything else in the file — hand\n * written sections included — is left exactly as it is.\n */\nasync function repair(\n boundary: Boundary,\n options: InitOptions,\n deps: InitDeps,\n configPath: string,\n detection: Detection,\n): Promise<InitResult> {\n const auto = isAuto(boundary, options);\n let raw: unknown;\n try {\n raw = JSON.parse(boundary.fs.read(configPath));\n } catch (e) {\n return fail(`${configPath} is not valid JSON — ${(e as Error).message}`);\n }\n const parsed = parseConfig(raw);\n if (!parsed.ok) {\n fail(\n `${configPath} already exists but jetbridge refuses it, so there is nothing to compare ` +\n `against:\\n${formatConfigErrors(parsed.errors)}\\n Fix or delete it, then re-run.`,\n );\n }\n\n const drift = detectDrift(parsed.config, detection);\n if (drift.length === 0) {\n boundary.log.info(`${configPath} still matches the project — nothing to change.`);\n return { status: 'unchanged', configPath, drift };\n }\n\n boundary.log.info(`${configPath} and the project disagree:`);\n for (const entry of drift) {\n const reason = entry.note ? ` — ${entry.note}` : '';\n boundary.log.info(\n ` ${entry.path}: ${JSON.stringify(entry.current)} → ${JSON.stringify(entry.detected)}` +\n `${reason} (${entry.source})`,\n );\n }\n\n const merged = raw as Record<string, unknown>;\n const accepted: Drift[] = [];\n for (const entry of drift) {\n const take =\n auto ||\n (await deps.prompts.confirm({\n name: `update:${entry.path}`,\n message: `Update ${entry.path} to ${JSON.stringify(entry.detected)}?`,\n initial: true,\n }));\n if (!take) continue;\n setPath(merged, entry.path, entry.detected);\n accepted.push(entry);\n }\n\n if (accepted.length === 0) {\n boundary.log.info('nothing was changed.');\n return { status: 'unchanged', configPath, drift };\n }\n return finish(boundary, deps, configPath, merged, auto, options, accepted);\n}\n","/**\n * Reading an Xcode project so the wizard has to ask as little as possible.\n *\n * Every answer here is a SUGGESTION carrying the file it came from. A guess\n * that never surfaces costs a whole build to discover it was wrong, so nothing\n * detected is ever accepted silently — the wizard shows it, sourced, as the\n * default.\n *\n * `project.pbxproj` is an OpenStep property list. It is parsed as one instead\n * of grepped, because the interesting values only mean anything in context: a\n * `PRODUCT_BUNDLE_IDENTIFIER` belongs to a build configuration, which belongs\n * to a target, and a project with `Debug`, `Release` and `Staging` has three of\n * them saying different things. Anything unparseable degrades to a partial\n * result with a warning — a strange project must still reach the questions.\n */\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport type { Boundary } from './boundary.js';\n\n/** A detected value and the file that produced it. */\nexport interface Suggestion<T> {\n value: T;\n /** Path relative to the project root, for a message a human can check. */\n source: string;\n}\n\nexport interface DetectedTarget {\n name: string;\n productType?: string;\n isApp: boolean;\n bundleId?: string;\n /** One bundle-id segment for an extension; unset for the app itself. */\n bundleIdSuffix?: string;\n entitlements?: Suggestion<string>;\n}\n\nexport interface Detection {\n root: string;\n iosDir: Suggestion<string>;\n xcodeproj?: Suggestion<string>;\n xcworkspace?: Suggestion<string>;\n projectYml?: Suggestion<string>;\n configurations?: Suggestion<string[]>;\n schemes: string[];\n scheme?: Suggestion<string>;\n teamId?: Suggestion<string>;\n baseBundleId?: Suggestion<string>;\n displayName?: Suggestion<string>;\n targets: DetectedTarget[];\n /** Everything the wizard should say out loud before it starts asking. */\n warnings: string[];\n}\n\n/* -------------------------------------------------------------------------- */\n/* The OpenStep plist subset a pbxproj is written in */\n/* -------------------------------------------------------------------------- */\n\ntype PlistValue = string | PlistValue[] | { [key: string]: PlistValue };\n\nconst isDict = (value: PlistValue | undefined): value is { [key: string]: PlistValue } =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst asString = (value: PlistValue | undefined): string | undefined =>\n typeof value === 'string' ? value : undefined;\n\n/**\n * A hand-written parser rather than a dependency: the grammar is four\n * productions, and every pbxproj library on npm is either abandoned or an order\n * of magnitude more code than this.\n */\nexport function parsePlist(text: string): PlistValue {\n let at = 0;\n\n const skip = (): void => {\n for (;;) {\n while (at < text.length && /\\s/.test(text[at]!)) at += 1;\n if (text.startsWith('//', at)) {\n const end = text.indexOf('\\n', at);\n at = end === -1 ? text.length : end + 1;\n continue;\n }\n if (text.startsWith('/*', at)) {\n const end = text.indexOf('*/', at + 2);\n at = end === -1 ? text.length : end + 2;\n continue;\n }\n return;\n }\n };\n\n const quoted = (): string => {\n at += 1;\n let out = '';\n while (at < text.length && text[at] !== '\"') {\n if (text[at] === '\\\\') {\n out += text[at + 1] ?? '';\n at += 2;\n continue;\n }\n out += text[at];\n at += 1;\n }\n at += 1;\n return out;\n };\n\n const bare = (): string => {\n const start = at;\n while (at < text.length && !/[\\s;,=(){}]/.test(text[at]!)) at += 1;\n if (at === start) throw new Error(`unexpected \"${text[at]}\" at ${at}`);\n return text.slice(start, at);\n };\n\n const value = (): PlistValue => {\n skip();\n const char = text[at];\n if (char === '{') return dict();\n if (char === '(') return array();\n if (char === '\"') return quoted();\n return bare();\n };\n\n const dict = (): { [key: string]: PlistValue } => {\n at += 1;\n const out: { [key: string]: PlistValue } = {};\n for (;;) {\n skip();\n if (text[at] === '}') {\n at += 1;\n return out;\n }\n if (at >= text.length) throw new Error('unterminated {');\n const key = text[at] === '\"' ? quoted() : bare();\n skip();\n if (text[at] !== '=') throw new Error(`expected = after ${key}`);\n at += 1;\n out[key] = value();\n skip();\n if (text[at] === ';') at += 1;\n }\n };\n\n const array = (): PlistValue[] => {\n at += 1;\n const out: PlistValue[] = [];\n for (;;) {\n skip();\n if (text[at] === ')') {\n at += 1;\n return out;\n }\n if (at >= text.length) throw new Error('unterminated (');\n out.push(value());\n skip();\n if (text[at] === ',') at += 1;\n }\n };\n\n skip();\n // A pbxproj starts with a bare `// !$*UTF8*$!` line, already skipped above.\n return value();\n}\n\nexport interface PbxTarget {\n name: string;\n productType?: string;\n /** Build settings for this target, by build-configuration name. */\n settings: Record<string, Record<string, string>>;\n}\n\nexport interface PbxprojFacts {\n /** The project's own build configuration list — what `-configuration` accepts. */\n projectConfigurations: string[];\n /** Every configuration name in the file, target-local ones included. */\n allConfigurations: string[];\n /** Project-level build settings, by configuration name. */\n projectSettings: Record<string, Record<string, string>>;\n targets: PbxTarget[];\n warnings: string[];\n}\n\nconst emptyFacts = (warnings: string[]): PbxprojFacts => ({\n projectConfigurations: [],\n allConfigurations: [],\n projectSettings: {},\n targets: [],\n warnings,\n});\n\n/** Flatten a `buildSettings` dict, dropping the list-valued settings nobody here reads. */\nfunction scalarSettings(value: PlistValue | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!isDict(value)) return out;\n for (const [key, setting] of Object.entries(value)) {\n if (typeof setting === 'string') out[key] = setting;\n }\n return out;\n}\n\nexport function parsePbxproj(text: string): PbxprojFacts {\n let root: PlistValue;\n try {\n root = parsePlist(text);\n } catch (e) {\n return emptyFacts([`project.pbxproj could not be parsed — ${(e as Error).message}`]);\n }\n if (!isDict(root) || !isDict(root.objects)) {\n return emptyFacts(['project.pbxproj has no objects section']);\n }\n\n const warnings: string[] = [];\n const objects = root.objects;\n const object = (id: PlistValue | undefined): { [key: string]: PlistValue } | undefined => {\n const found = typeof id === 'string' ? objects[id] : undefined;\n return isDict(found) ? found : undefined;\n };\n\n /** Configuration name → build settings, for one `XCConfigurationList` id. */\n const settingsFor = (listId: PlistValue | undefined): Record<string, Record<string, string>> => {\n const out: Record<string, Record<string, string>> = {};\n const list = object(listId);\n const ids = list?.buildConfigurations;\n if (!Array.isArray(ids)) return out;\n for (const id of ids) {\n const configuration = object(id);\n const name = asString(configuration?.name);\n if (!name) continue;\n out[name] = scalarSettings(configuration?.buildSettings);\n }\n return out;\n };\n\n const allConfigurations = new Set<string>();\n for (const entry of Object.values(objects)) {\n if (isDict(entry) && entry.isa === 'XCBuildConfiguration') {\n const name = asString(entry.name);\n if (name) allConfigurations.add(name);\n }\n }\n\n const project =\n object(root.rootObject) ??\n Object.values(objects).find((entry) => isDict(entry) && entry.isa === 'PBXProject');\n const projectSettings = settingsFor(isDict(project) ? project.buildConfigurationList : undefined);\n let projectConfigurations = Object.keys(projectSettings);\n if (projectConfigurations.length === 0) {\n // Falling back to every configuration in the file can sweep in a\n // target-local one that `-configuration` will not accept, so say so.\n projectConfigurations = [...allConfigurations];\n if (projectConfigurations.length > 0) {\n warnings.push(\n 'the project-level build configuration list could not be read, so the configuration ' +\n 'names come from every target in the file — check them.',\n );\n }\n }\n\n const targets: PbxTarget[] = [];\n const targetIds = isDict(project) && Array.isArray(project.targets) ? project.targets : [];\n const entries = targetIds.length\n ? targetIds.map((id) => object(id))\n : Object.values(objects).map((entry) => (isDict(entry) ? entry : undefined));\n for (const entry of entries) {\n if (!entry || entry.isa !== 'PBXNativeTarget') continue;\n const name = asString(entry.name);\n if (!name) continue;\n const productType = asString(entry.productType);\n targets.push({\n name,\n ...(productType ? { productType } : {}),\n settings: settingsFor(entry.buildConfigurationList),\n });\n }\n if (targets.length === 0) warnings.push('no native targets were found in project.pbxproj');\n\n return {\n projectConfigurations,\n allConfigurations: [...allConfigurations],\n projectSettings,\n targets,\n warnings,\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* From facts to suggestions */\n/* -------------------------------------------------------------------------- */\n\nconst APP_PRODUCT_TYPE = 'com.apple.product-type.application';\n\nconst isExtension = (productType: string | undefined): boolean =>\n Boolean(productType && /app-extension|watchkit2-app|extensionkit-extension/.test(productType));\n\n/**\n * One setting's value, preferring the configuration a build will actually name.\n * Reports a disagreement instead of picking a winner: `Debug` and `Release`\n * carrying different bundle ids is normal, and the difference is the thing\n * worth showing.\n */\nexport function settingValue(\n settings: Record<string, Record<string, string>>,\n key: string,\n preferred: string[],\n): { value: string; configuration: string; differs: boolean } | undefined {\n const found = Object.entries(settings)\n .map(([configuration, values]) => ({ configuration, value: values[key] }))\n .filter((entry): entry is { configuration: string; value: string } => Boolean(entry.value));\n if (found.length === 0) return undefined;\n const chosen = preferred.map((name) => found.find((e) => e.configuration === name)).find(Boolean);\n const winner = chosen ?? found[0]!;\n return {\n value: winner.value,\n configuration: winner.configuration,\n differs: new Set(found.map((e) => e.value)).size > 1,\n };\n}\n\n/** A path inside the project root, or nothing — the schema refuses the rest. */\nfunction insideRoot(root: string, base: string, value: string): string | undefined {\n if (value.includes('$(') || value.includes('${')) return undefined;\n const absolute = isAbsolute(value) ? value : resolve(base, value);\n const rel = relative(root, absolute);\n if (!rel || rel.startsWith('..') || isAbsolute(rel)) return undefined;\n return rel;\n}\n\n/** `Upload Widget` → `uploadwidget`: one bundle-id segment, or nothing. */\nexport function bundleIdSuffixFrom(value: string): string | undefined {\n const squeezed = value.toLowerCase().replace(/[^a-z0-9]/g, '');\n return squeezed.length > 0 ? squeezed : undefined;\n}\n\nexport interface DetectOptions {\n /** Where the config file will live. Every suggested path is relative to it. */\n root: string;\n /** Skip the search and read this directory, relative to `root`. */\n iosDir?: string;\n}\n\nconst XCODE_PROJECT_SUFFIX = '.xcodeproj';\nconst XCODE_WORKSPACE_SUFFIX = '.xcworkspace';\n\n/** The directory holding an `.xcodeproj` or `.xcworkspace`: the root, or one below it. */\nexport function findProjectDirectory(boundary: Boundary, root: string): string | undefined {\n const holdsProject = (dir: string): boolean => {\n if (!boundary.fs.isDirectory(dir)) return false;\n return boundary.fs\n .readdir(dir)\n .some((name) => name.endsWith(XCODE_PROJECT_SUFFIX) || name.endsWith(XCODE_WORKSPACE_SUFFIX));\n };\n if (holdsProject(root)) return root;\n if (!boundary.fs.isDirectory(root)) return undefined;\n for (const name of boundary.fs.readdir(root)) {\n if (name.startsWith('.') || name === 'node_modules') continue;\n const candidate = join(root, name);\n if (holdsProject(candidate)) return candidate;\n }\n return undefined;\n}\n\nfunction schemeNames(boundary: Boundary, container: string): string[] {\n const directory = join(container, 'xcshareddata', 'xcschemes');\n if (!boundary.fs.isDirectory(directory)) return [];\n return boundary.fs\n .readdir(directory)\n .filter((name) => name.endsWith('.xcscheme'))\n .map((name) => name.slice(0, -'.xcscheme'.length));\n}\n\nexport function detectProject(boundary: Boundary, options: DetectOptions): Detection {\n const root = resolve(options.root);\n const warnings: string[] = [];\n const explicit = options.iosDir ? resolve(root, options.iosDir) : undefined;\n const directory = explicit ?? findProjectDirectory(boundary, root);\n\n if (!directory) {\n return {\n root,\n iosDir: { value: options.iosDir ?? '.', source: '.' },\n schemes: [],\n targets: [],\n warnings: ['no .xcodeproj or .xcworkspace was found here or one directory below.'],\n };\n }\n\n const iosDir = relative(root, directory) || '.';\n const names = boundary.fs.isDirectory(directory) ? boundary.fs.readdir(directory) : [];\n const projectName = names.find((name) => name.endsWith(XCODE_PROJECT_SUFFIX));\n const workspaceName = names.find((name) => name.endsWith(XCODE_WORKSPACE_SUFFIX));\n const specName = names.find((name) => name === 'project.yml' || name === 'project.yaml');\n\n const detection: Detection = {\n root,\n iosDir: { value: iosDir, source: iosDir },\n ...(projectName ? { xcodeproj: { value: projectName, source: iosDir } } : {}),\n ...(workspaceName ? { xcworkspace: { value: workspaceName, source: iosDir } } : {}),\n ...(specName ? { projectYml: { value: specName, source: join(iosDir, specName) } } : {}),\n schemes: [],\n targets: [],\n warnings,\n };\n\n if (!projectName) {\n warnings.push(\n workspaceName\n ? `${workspaceName} has no .xcodeproj beside it, so nothing could be read out of the project.`\n : 'no .xcodeproj was found, so nothing could be read out of the project.',\n );\n return detection;\n }\n\n const projectDir = join(directory, projectName);\n const pbxprojPath = join(projectDir, 'project.pbxproj');\n const sourceOf = (path: string): string => relative(root, path);\n\n detection.schemes = [\n ...new Set([\n ...schemeNames(boundary, projectDir),\n ...(workspaceName ? schemeNames(boundary, join(directory, workspaceName)) : []),\n ]),\n ];\n\n if (!boundary.fs.exists(pbxprojPath)) {\n warnings.push(`${sourceOf(pbxprojPath)} is missing, so nothing could be read out of it.`);\n return detection;\n }\n\n let facts: PbxprojFacts;\n try {\n facts = parsePbxproj(boundary.fs.read(pbxprojPath));\n } catch (e) {\n warnings.push(`${sourceOf(pbxprojPath)} could not be read — ${(e as Error).message}`);\n return detection;\n }\n const pbxSource = sourceOf(pbxprojPath);\n warnings.push(...facts.warnings.map((warning) => `${pbxSource}: ${warning}`));\n\n if (facts.projectConfigurations.length > 0) {\n detection.configurations = { value: facts.projectConfigurations, source: pbxSource };\n }\n\n // `Debug` first: it is what the cabled inner loop builds, so its values are\n // the ones a wrong guess is felt in first.\n const preferred = [\n 'Debug',\n ...facts.projectConfigurations.filter((name) => name !== 'Debug'),\n ] as string[];\n\n const app = facts.targets.find((target) => target.productType === APP_PRODUCT_TYPE);\n if (!app && facts.targets.length > 0) {\n warnings.push(`${pbxSource}: no application target was found — pick one by hand.`);\n }\n\n const readSetting = (\n target: PbxTarget | undefined,\n key: string,\n ): { value: string; configuration: string; differs: boolean } | undefined =>\n (target ? settingValue(target.settings, key, preferred) : undefined) ??\n settingValue(facts.projectSettings, key, preferred);\n\n const teamId = readSetting(app, 'DEVELOPMENT_TEAM');\n if (teamId) {\n if (/^[A-Z0-9]{10}$/.test(teamId.value)) {\n detection.teamId = { value: teamId.value, source: pbxSource };\n } else {\n warnings.push(\n `${pbxSource}: DEVELOPMENT_TEAM is \"${teamId.value}\", which is not a 10-character team id.`,\n );\n }\n }\n\n const bundleId = app\n ? settingValue(app.settings, 'PRODUCT_BUNDLE_IDENTIFIER', preferred)\n : undefined;\n if (bundleId?.value.includes('$(')) {\n warnings.push(\n `${pbxSource}: PRODUCT_BUNDLE_IDENTIFIER is built from other build settings ` +\n `(\"${bundleId.value}\"), so it has to be given by hand.`,\n );\n } else if (bundleId) {\n detection.baseBundleId = { value: bundleId.value, source: pbxSource };\n if (bundleId.differs) {\n warnings.push(\n `${pbxSource}: the bundle id differs between configurations — ${bundleId.configuration} ` +\n `says \"${bundleId.value}\".`,\n );\n }\n }\n\n const displayName = app\n ? settingValue(app.settings, 'INFOPLIST_KEY_CFBundleDisplayName', preferred)\n : undefined;\n if (displayName && !displayName.value.includes('$(')) {\n detection.displayName = { value: displayName.value, source: pbxSource };\n } else if (app) {\n detection.displayName = { value: app.name, source: pbxSource };\n }\n\n if (app) {\n const matching = detection.schemes.find((scheme) => scheme === app.name);\n detection.scheme = matching\n ? { value: matching, source: sourceOf(join(projectDir, 'xcshareddata', 'xcschemes')) }\n : { value: app.name, source: pbxSource };\n } else if (detection.schemes.length === 1) {\n detection.scheme = {\n value: detection.schemes[0]!,\n source: sourceOf(join(projectDir, 'xcshareddata', 'xcschemes')),\n };\n }\n\n for (const target of facts.targets) {\n const isApp = target.productType === APP_PRODUCT_TYPE;\n if (!isApp && !isExtension(target.productType)) continue;\n\n const id = settingValue(target.settings, 'PRODUCT_BUNDLE_IDENTIFIER', preferred)?.value;\n const entitlements = settingValue(target.settings, 'CODE_SIGN_ENTITLEMENTS', preferred)?.value;\n const relativeEntitlements = entitlements\n ? insideRoot(root, directory, entitlements)\n : undefined;\n if (entitlements && !relativeEntitlements) {\n warnings.push(\n `${pbxSource}: ${target.name}'s entitlements path (\"${entitlements}\") is outside the ` +\n 'project root, so it was left out.',\n );\n }\n\n // An extension without a usable id segment would read as a second app\n // target, which the schema refuses. Leave it out and say so.\n const suffix = isApp\n ? undefined\n : bundleIdSuffixFrom(id?.split('.').pop() ?? target.name.split('.').pop() ?? '');\n if (!isApp && !suffix) {\n warnings.push(\n `${pbxSource}: ${target.name} has no usable bundle-id segment — add it by hand.`,\n );\n continue;\n }\n\n detection.targets.push({\n name: target.name,\n ...(target.productType ? { productType: target.productType } : {}),\n isApp,\n ...(id && !id.includes('$(') ? { bundleId: id } : {}),\n ...(suffix ? { bundleIdSuffix: suffix } : {}),\n ...(relativeEntitlements\n ? { entitlements: { value: relativeEntitlements, source: pbxSource } }\n : {}),\n });\n }\n\n return detection;\n}\n","/**\n * Over-the-air delivery: archive, export an .ipa, upload it to a bucket, and\n * print a URL the phone can open in Safari.\n *\n * This is the path for when the phone is not on the desk. Everything it shares\n * with the cabled install — variant naming, provisioning, the entitlement swap\n * — is imported, not repeated. What is genuinely different is here: the archive\n * verb, the export, the metadata read back out of the archive, and the bucket.\n *\n * The order of the last two steps is the load-bearing part. The manifest is\n * fetched over HTTPS BEFORE any URL is printed, because a bucket that accepts\n * the upload and then serves 403 is the common misconfiguration and iOS reports\n * it only as \"Cannot connect\".\n */\nimport { join } from 'node:path';\nimport { fillTemplate, readTemplate } from './assets.js';\nimport type { Boundary } from './boundary.js';\nimport { authArgs, buildNumber, generateProject, requireToolchain, runHook } from './build.js';\nimport type { Config, OtaConfig } from './config.js';\nimport { withEntitlementSwap } from './entitlements.js';\nimport {\n escapeHtml,\n itmsServicesUrl,\n renderExportOptionsPlist,\n renderManifestPlist,\n} from './manifest.js';\nimport { fail, type Project } from './project.js';\nimport { provisionVariant, targetBundleId } from './provision.js';\nimport { signSettings, variantSettings, type SigningProfiles } from './signing.js';\nimport {\n createStore,\n credentials,\n objectKey,\n projectToken,\n publicUrl,\n verifyReachable,\n type ObjectStore,\n type S3Factory,\n} from './storage.js';\nimport { scratchPath } from './wired.js';\n\n/**\n * The profile a signed export needs. An ad hoc profile — not the development\n * one a cabled install uses — is what lets an .ipa install over the air on the\n * devices it names.\n */\nconst PROFILE_TYPES: Record<OtaConfig['exportMethod'], string> = {\n 'ad-hoc': 'IOS_APP_ADHOC',\n enterprise: 'IOS_APP_INHOUSE',\n};\n\nconst IPA_NAME = 'app.ipa';\nconst REGISTRY_NAME = 'builds.json';\n\n// ─── reading a plist ─────────────────────────────────────────────────────────\n\nexport type PlistValue = string | boolean | PlistValue[] | { [key: string]: PlistValue };\n\nconst decodeEntities = (text: string): string =>\n text\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('"', '\"')\n .replaceAll(''', \"'\")\n .replaceAll(''', \"'\")\n .replaceAll('&', '&');\n\n/**\n * A reader for the subset of plist XML Xcode writes.\n *\n * Shelling out to PlistBuddy for each of a dozen keys is a dozen processes, and\n * — the reason that matters here — it makes the metadata step untestable\n * without an archive on disk. Xcode's own output is `<key>`/`<string>` XML, so\n * a scanner over the tags reads it exactly.\n */\nexport function parsePlist(xml: string): Record<string, PlistValue> {\n const tag = /<(\\/?)([A-Za-z]+)[^>]*?(\\/?)>/g;\n const start = xml.indexOf('<plist');\n if (start === -1) fail('that file is not a plist — it has no <plist> element');\n tag.lastIndex = start;\n\n interface Token {\n closing: boolean;\n name: string;\n selfClosing: boolean;\n /** Where the tag starts, so the text before it can be sliced out. */\n start: number;\n end: number;\n }\n\n const next = (): Token => {\n const match = tag.exec(xml);\n if (!match) fail('the plist ended in the middle of a value — it is truncated or malformed');\n return {\n closing: match[1] === '/',\n name: match[2]!,\n selfClosing: match[3] === '/',\n start: match.index,\n end: tag.lastIndex,\n };\n };\n\n /** Everything from here to the next tag — which is this element's close. */\n const textUntilClose = (from: number): string => decodeEntities(xml.slice(from, next().start));\n\n const parseValue = (name: string, selfClosing: boolean, from: number): PlistValue => {\n if (name === 'true' || name === 'false') {\n if (!selfClosing) next();\n return name === 'true';\n }\n if (name === 'dict') {\n const dict: Record<string, PlistValue> = {};\n for (;;) {\n const token = next();\n if (token.closing && token.name === 'dict') return dict;\n if (token.name !== 'key') fail(`unexpected <${token.name}> where a plist key was expected`);\n const key = textUntilClose(token.end);\n const valueToken = next();\n dict[key] = parseValue(valueToken.name, valueToken.selfClosing, valueToken.end);\n }\n }\n if (name === 'array') {\n const array: PlistValue[] = [];\n for (;;) {\n const token = next();\n if (token.closing && token.name === 'array') return array;\n array.push(parseValue(token.name, token.selfClosing, token.end));\n }\n }\n return selfClosing ? '' : textUntilClose(from);\n };\n\n next(); // the <plist> element itself\n const root = next();\n if (root.name !== 'dict') fail('the plist does not hold a dictionary at its root');\n const value = parseValue('dict', false, root.end);\n return value as Record<string, PlistValue>;\n}\n\n/** A dotted path through nested dictionaries; an array yields its first entry. */\nexport function plistString(root: PlistValue, path: string, fallback: string): string {\n let value: PlistValue | undefined = root;\n for (const segment of path.split('.')) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return fallback;\n value = (value as Record<string, PlistValue>)[segment];\n if (value === undefined) return fallback;\n }\n if (Array.isArray(value)) value = value[0];\n if (typeof value === 'boolean') return String(value);\n return typeof value === 'string' && value !== '' ? value : fallback;\n}\n\n// ─── build metadata ──────────────────────────────────────────────────────────\n\nexport interface BuildMetadata {\n appName: string;\n bundleId: string;\n version: string;\n build: string;\n versionTag: string;\n teamId: string;\n /** Certificate type only. The page is URL-gated, not secret — no serial. */\n signedBy: string;\n archs: string;\n minIos: string;\n sdk: string;\n xcodeBuild: string;\n configuration: string;\n branch: string;\n commit: string;\n dirty: boolean;\n variantBadge: string;\n /** `YYYY-MM-DD HH:MM:SS UTC`, from the boundary clock. */\n builtAt: string;\n}\n\n/** `Apple Distribution: Dev Eloper (ABCDE12345)` → `Apple Distribution`. */\nconst certificateType = (identity: string): string => identity.split(':')[0]!.trim() || 'unknown';\n\n/** `YYYY-MM-DD HH:MM:SS UTC`. UTC, not local: a build page is read by other people. */\nexport const utcStamp = (unixSeconds: number): string =>\n new Date(unixSeconds * 1000).toISOString().replace('T', ' ').replace(/\\..+$/, ' UTC');\n\n/** Branch, short SHA and whether the tree was dirty. Absent git is not an error. */\nexport async function gitProvenance(\n boundary: Boundary,\n root: string,\n): Promise<{ branch: string; commit: string; dirty: boolean }> {\n const git = async (...args: string[]): Promise<string> => {\n const result = await boundary.exec.run('git', ['-C', root, ...args], { allowFail: true });\n return result.ok ? result.stdout.trim() : '';\n };\n const branch = await git('rev-parse', '--abbrev-ref', 'HEAD');\n return {\n branch: branch === 'HEAD' || branch === '' ? 'detached HEAD' : branch,\n commit: (await git('rev-parse', '--short', 'HEAD')) || '—',\n // A dirty tree means the .ipa matches no commit. The page says so rather\n // than printing a SHA that quietly misrepresents what is installing.\n dirty: (await git('status', '--porcelain')) !== '',\n };\n}\n\n/**\n * Read a plist that may be in either format.\n *\n * The archive's own Info.plist is XML, but the one inside the built `.app` is a\n * BINARY property list — Xcode converts it at copy time. `plutil` reads both,\n * and is on every Mac that has Xcode, so the text scanner above only ever sees\n * XML. Returns null when neither path works, and the caller decides whether\n * that is fatal.\n */\nexport function readPlistFile(boundary: Boundary, path: string): Record<string, PlistValue> | null {\n const raw = boundary.fs.read(path);\n if (raw.includes('<plist')) return parsePlist(raw);\n const converted = boundary.exec.runSync('plutil', ['-convert', 'xml1', '-o', '-', path], {\n allowFail: true,\n });\n return converted.ok && converted.stdout.includes('<plist') ? parsePlist(converted.stdout) : null;\n}\n\n/**\n * Everything the install page claims, read back out of the archive that\n * produced the .ipa — so the page cannot describe a build that was not made.\n */\nexport async function archiveMetadata(\n boundary: Boundary,\n project: Project,\n options: { archivePath: string; suffix: string; configuration: string },\n): Promise<BuildMetadata> {\n const archivePlist = join(options.archivePath, 'Info.plist');\n if (!boundary.fs.exists(archivePlist)) {\n fail(\n `the archive at ${options.archivePath} has no Info.plist — the archive step did not finish`,\n );\n }\n const archive = readPlistFile(boundary, archivePlist);\n if (!archive) {\n fail(\n `could not read ${archivePlist}.\\n` +\n ' Check it with `plutil -p` — the bundle id and version of the build are read from it.',\n );\n }\n const properties = 'ApplicationProperties';\n\n const applicationPath = plistString(archive, `${properties}.ApplicationPath`, '');\n const appPlist = applicationPath\n ? join(options.archivePath, 'Products', applicationPath, 'Info.plist')\n : '';\n // The app's plist only supplies fields that already have a fallback, so an\n // unreadable one costs a row on the page, never the publish.\n const app =\n (appPlist && boundary.fs.exists(appPlist) ? readPlistFile(boundary, appPlist) : null) ?? {};\n\n const version = plistString(archive, `${properties}.CFBundleShortVersionString`, '0.0.0');\n const build = plistString(archive, `${properties}.CFBundleVersion`, '0');\n const provenance = await gitProvenance(boundary, project.root);\n\n return {\n appName: plistString(\n app,\n 'CFBundleDisplayName',\n plistString(app, 'CFBundleName', project.config.variant.displayName),\n ),\n bundleId: plistString(\n archive,\n `${properties}.CFBundleIdentifier`,\n project.config.project.baseBundleId,\n ),\n version,\n build,\n versionTag: `v${version} · build ${build}`,\n teamId: plistString(archive, `${properties}.Team`, project.config.project.teamId),\n signedBy: certificateType(plistString(archive, `${properties}.SigningIdentity`, 'unknown')),\n archs: plistString(archive, `${properties}.Architectures`, 'arm64'),\n minIos: plistString(app, 'MinimumOSVersion', '—'),\n sdk: plistString(app, 'DTPlatformVersion', '—'),\n xcodeBuild: plistString(app, 'DTXcodeBuild', '—'),\n configuration: options.configuration,\n ...provenance,\n variantBadge: options.suffix ? `variant · ${options.suffix}` : 'plain',\n builtAt: utcStamp(boundary.now()),\n };\n}\n\n// ─── the registry and the pages ──────────────────────────────────────────────\n\n/**\n * One row per uploaded build, kept in the bucket. It is the source of truth for\n * the index page, which is why the page can be rebuilt from bucket state alone\n * without re-archiving anything.\n */\nexport interface BuildRecord {\n /** `<bundleId>-<build>`: unique per variant and version, and a key segment. */\n buildId: string;\n appName: string;\n bundleId: string;\n version: string;\n build: string;\n versionTag: string;\n variantBadge: string;\n branch: string;\n commit: string;\n dirty: boolean;\n ipaSizeLabel: string;\n ipaSizeBytes: number;\n builtAt: string;\n /** ISO instant of the upload — the sort key. */\n uploadedAt: string;\n}\n\nexport const buildIdFor = (meta: BuildMetadata): string => `${meta.bundleId}-${meta.build}`;\n\nexport const megabytes = (bytes: number): string => `${Math.floor(bytes / 1024 / 1024)} MB`;\n\nconst brandTitle = (config: Config, ota: OtaConfig): string =>\n ota.branding.title ?? config.variant.displayName;\n\n/** Six-digit hex, so it drops straight into the template's CSS variable. */\nconst brandAccent = (ota: OtaConfig): string => ota.branding.accent ?? '#f4f0e6';\n\n/** One card. Every developer-controlled value is escaped on the way in. */\nfunction renderRow(record: BuildRecord, manifestUrl: string): string {\n const x = escapeHtml;\n const commit = record.dirty ? `${record.commit} (dirty)` : record.commit;\n return ` <div class=\"build\">\n <div class=\"top\">\n <span class=\"title\">${x(record.appName)}</span>\n <span class=\"badge\">${x(record.variantBadge)}</span>\n </div>\n <dl>\n <dt>Bundle</dt><dd>${x(record.bundleId)}</dd>\n <dt>Version</dt><dd>${x(record.version)} <span class=\"dim\">· build ${x(record.build)}</span></dd>\n <dt>Branch</dt><dd>${x(record.branch)}</dd>\n <dt>Commit</dt><dd>${x(commit)}</dd>\n <dt>Size</dt><dd>${x(record.ipaSizeLabel)}</dd>\n <dt>Built</dt><dd>${x(record.builtAt)}</dd>\n </dl>\n <a class=\"install-btn\" href=\"${x(itmsServicesUrl(manifestUrl))}\">Install ${x(record.versionTag)}</a>\n </div>`;\n}\n\nexport interface IndexOptions {\n config: Config;\n ota: OtaConfig;\n token: string;\n generatedAt: string;\n}\n\n/** The rolling page, newest first. Pure: no bucket, no clock. */\nexport function renderIndexPage(records: BuildRecord[], options: IndexOptions): string {\n const sorted = sortRecords(records);\n const rows = sorted.length\n ? sorted\n .map((record) =>\n renderRow(\n record,\n publicUrl(\n options.ota,\n objectKey(options.ota, options.token, 'builds', record.buildId, 'manifest.plist'),\n ),\n ),\n )\n .join('\\n')\n : ' <p class=\"empty\">No builds uploaded yet.</p>';\n\n return fillTemplate(readTemplate('index-page.html'), {\n BRAND_TITLE: escapeHtml(brandTitle(options.config, options.ota)),\n ACCENT: brandAccent(options.ota),\n BUILD_COUNT: String(sorted.length),\n ROWS: rows,\n GENERATED_AT: escapeHtml(options.generatedAt),\n });\n}\n\n/** The per-build page: the spec sheet plus one install link. Pure. */\nexport function renderInstallPage(\n meta: BuildMetadata,\n options: { config: Config; ota: OtaConfig; manifestUrl: string; ipaSizeLabel: string },\n): string {\n const x = escapeHtml;\n return fillTemplate(readTemplate('install-page.html'), {\n BRAND_TITLE: x(brandTitle(options.config, options.ota)),\n ACCENT: brandAccent(options.ota),\n APP_NAME: x(meta.appName),\n VARIANT_BADGE: x(meta.variantBadge),\n BUNDLE_ID: x(meta.bundleId),\n VERSION: x(meta.version),\n BUILD: x(meta.build),\n GIT_BRANCH: x(meta.branch),\n GIT_COMMIT: x(meta.dirty ? `${meta.commit} (dirty)` : meta.commit),\n CONFIGURATION: x(meta.configuration),\n ARCHS: x(meta.archs),\n IPA_SIZE: x(options.ipaSizeLabel),\n MIN_IOS: x(meta.minIos),\n SDK: x(meta.sdk),\n XCODE_BUILD: x(meta.xcodeBuild),\n SIGNED_BY: x(meta.signedBy),\n TEAM_ID: x(meta.teamId),\n BUILT_AT: x(meta.builtAt),\n INSTALL_HREF: x(itmsServicesUrl(options.manifestUrl)),\n });\n}\n\nconst sortRecords = (records: BuildRecord[]): BuildRecord[] =>\n [...records].sort((a, b) => b.uploadedAt.localeCompare(a.uploadedAt));\n\n/**\n * Fold a build into the registry: a rebuild of the same version replaces its\n * own row rather than appearing twice, then the oldest fall off the end.\n */\nexport function mergeRecords(\n existing: BuildRecord[],\n record: BuildRecord,\n maxBuilds: number,\n): BuildRecord[] {\n const kept = existing.filter((row) => row.buildId !== record.buildId);\n return sortRecords([record, ...kept]).slice(0, maxBuilds);\n}\n\nasync function readRegistry(store: ObjectStore, key: string): Promise<BuildRecord[]> {\n const text = await store.getText(key);\n if (!text) return [];\n try {\n const parsed: unknown = JSON.parse(text);\n return Array.isArray(parsed) ? (parsed as BuildRecord[]) : [];\n } catch {\n // A corrupt registry must not block a publish: the page is rebuilt from\n // what uploads now, and the bad object is overwritten by this run.\n return [];\n }\n}\n\n// ─── archive and export ──────────────────────────────────────────────────────\n\nexport interface ArchiveRequest {\n configuration: string;\n suffix: string;\n displayName: string;\n profiles: SigningProfiles;\n archivePath: string;\n buildNumber: string;\n gitSha?: string;\n}\n\nexport function archiveArgs(\n boundary: Boundary,\n project: Project,\n request: ArchiveRequest,\n): string[] {\n const { config } = project;\n return [\n 'archive',\n ...project.xcodebuildTarget(),\n '-scheme',\n config.project.scheme,\n '-configuration',\n request.configuration,\n '-destination',\n 'generic/platform=iOS',\n '-archivePath',\n request.archivePath,\n `CURRENT_PROJECT_VERSION=${request.buildNumber}`,\n ...(request.gitSha ? [`${config.variant.buildSettings.gitSha}=${request.gitSha}`] : []),\n ...variantSettings(request.suffix, request.displayName, config),\n ...signSettings(request.suffix, request.profiles, config),\n '-allowProvisioningUpdates',\n ...authArgs(boundary, config),\n '-quiet',\n ];\n}\n\n/**\n * `-allowProvisioningUpdates` on the export too, not only the archive: it lets\n * xcodebuild refresh a profile that went stale because a certificate was\n * rotated or a device was registered after it was minted. Without it the export\n * fails with \"profile doesn't include signing certificate\" and the only fix is\n * Xcode's Organizer by hand.\n */\nexport function exportArgs(\n boundary: Boundary,\n config: Config,\n options: { archivePath: string; exportDir: string; optionsPlist: string },\n): string[] {\n return [\n '-exportArchive',\n '-archivePath',\n options.archivePath,\n '-exportOptionsPlist',\n options.optionsPlist,\n '-exportPath',\n options.exportDir,\n '-allowProvisioningUpdates',\n ...authArgs(boundary, config),\n '-quiet',\n ];\n}\n\n/** The bundle id → profile name map an export plist needs for a variant. */\nexport function exportProfileMap(\n config: Config,\n suffix: string,\n profiles: SigningProfiles,\n): Record<string, string> {\n if (!suffix) return {};\n const map: Record<string, string> = {};\n for (const target of config.variant.targets) {\n const profile = profiles.byTarget[target.name];\n if (profile) map[targetBundleId(target, suffix, config)] = profile;\n }\n return map;\n}\n\nasync function runArchive(\n boundary: Boundary,\n project: Project,\n request: ArchiveRequest,\n): Promise<void> {\n boundary.log.step(\n `archiving ${request.configuration}/${project.config.project.scheme} (build ${request.buildNumber})`,\n );\n const result = await boundary.exec.run('xcodebuild', archiveArgs(boundary, project, request), {\n cwd: project.root,\n allowFail: true,\n });\n if (!result.ok) {\n const tail = (result.stderr || result.stdout).trim().split('\\n').slice(-20).join('\\n');\n fail(`xcodebuild archive failed:\\n${tail}`);\n }\n if (!boundary.fs.exists(request.archivePath)) {\n fail(\n `the archive reported success but produced nothing at ${request.archivePath}.\\n` +\n ' Check that the scheme is shared and archives from Xcode.',\n );\n }\n}\n\n/** Export the .ipa and return its path. The filename is the scheme's, not ours. */\nasync function runExport(\n boundary: Boundary,\n project: Project,\n options: { archivePath: string; exportDir: string; optionsPlist: string },\n): Promise<string> {\n boundary.log.step('exporting the .ipa');\n const result = await boundary.exec.run(\n 'xcodebuild',\n exportArgs(boundary, project.config, options),\n { cwd: project.root, allowFail: true },\n );\n if (!result.ok) {\n const tail = (result.stderr || result.stdout).trim().split('\\n').slice(-20).join('\\n');\n fail(`xcodebuild -exportArchive failed:\\n${tail}`);\n }\n const produced = boundary.fs\n .readdir(options.exportDir)\n .filter((name) => name.endsWith('.ipa'))\n .sort();\n const ipa = produced[0];\n if (!ipa) {\n fail(\n `the export produced no .ipa in ${options.exportDir}.\\n` +\n ' Check that ota.exportMethod matches a certificate this machine holds.',\n );\n }\n return join(options.exportDir, ipa);\n}\n\n// ─── the flow ────────────────────────────────────────────────────────────────\n\nexport interface OtaOptions {\n suffix: string;\n displayName: string;\n configuration?: string;\n gitSha?: string;\n /** Injected by tests. Production uses the AWS SDK client. */\n s3?: S3Factory;\n}\n\nexport interface OtaResult {\n installUrl: string;\n indexUrl: string;\n manifestUrl: string;\n record: BuildRecord;\n builds: number;\n}\n\n/** The `ota` block, or a message saying exactly what to add. */\nfunction requireOta(project: Project): OtaConfig {\n const ota = project.config.ota;\n if (!ota) {\n fail(\n 'this project has no \"ota\" block in its config, so there is nowhere to publish to.\\n' +\n ' Add ota.storage (bucket, region, publicBaseUrl) and re-run.',\n );\n }\n return ota;\n}\n\nexport async function otaInstall(\n boundary: Boundary,\n project: Project,\n options: OtaOptions,\n): Promise<OtaResult> {\n const { config } = project;\n const ota = requireOta(project);\n const configuration = options.configuration ?? config.configurations.archive;\n if (!config.configurations.available.includes(configuration)) {\n fail(\n `\"${configuration}\" is not one of this project's build configurations ` +\n `(${config.configurations.available.join(', ')})`,\n );\n }\n\n // Before the slow steps: an unset bucket credential must not cost an archive\n // and an export to discover.\n credentials(boundary, ota);\n\n await requireToolchain(boundary, project, ['xcodebuild']);\n await generateProject(boundary, project);\n await runHook(boundary, project, 'preBuild');\n\n const work = join(scratchPath(boundary, options.suffix), 'ota');\n boundary.fs.rm(work, { recursive: true });\n boundary.fs.mkdirp(work);\n const archivePath = join(work, `${config.project.scheme}.xcarchive`);\n const exportDir = join(work, 'export');\n\n // Ad hoc profiles, not development ones: a development profile signs an app\n // that installs down a cable and refuses to install over the air.\n const profiles: SigningProfiles = options.suffix\n ? {\n byTarget: Object.fromEntries(\n (\n await provisionVariant(boundary, project, {\n suffix: options.suffix,\n displayName: options.displayName,\n profileType: PROFILE_TYPES[ota.exportMethod],\n })\n ).map((profile) => [profile.target, profile.profileName]),\n ),\n }\n : { byTarget: {} };\n\n // The swap is restored the moment the archive returns. The export, the upload\n // and the preflight that follow do not need it, and a hang in any of them\n // would otherwise leave the working tree dirty.\n const request: ArchiveRequest = {\n configuration,\n suffix: options.suffix,\n displayName: options.displayName,\n profiles,\n archivePath,\n buildNumber: buildNumber(boundary),\n ...(options.gitSha ? { gitSha: options.gitSha } : {}),\n };\n await withEntitlementSwap(\n boundary,\n project,\n { suffix: options.suffix, backupPath: join(work, 'project.pbxproj.orig') },\n () => runArchive(boundary, project, request),\n );\n\n const optionsPlist = join(work, 'exportOptions.plist');\n boundary.fs.write(\n optionsPlist,\n renderExportOptionsPlist({\n teamId: config.project.teamId,\n method: ota.exportMethod,\n provisioningProfiles: exportProfileMap(config, options.suffix, profiles),\n }),\n );\n const ipa = await runExport(boundary, project, { archivePath, exportDir, optionsPlist });\n\n const meta = await archiveMetadata(boundary, project, {\n archivePath,\n suffix: options.suffix,\n configuration,\n });\n if (meta.dirty) boundary.log.warn('the working tree is dirty — this .ipa matches no commit');\n\n await runHook(boundary, project, 'postBuild');\n\n return publish(boundary, project, { ota, ipa, meta, s3: options.s3 });\n}\n\n/**\n * Upload the .ipa, its manifest and its page; fold the build into the registry;\n * rebuild the index; and only then confirm the manifest is actually reachable.\n */\nexport async function publish(\n boundary: Boundary,\n project: Project,\n options: { ota: OtaConfig; ipa: string; meta: BuildMetadata; s3?: S3Factory },\n): Promise<OtaResult> {\n const { config } = project;\n const { ota, meta } = options;\n const token = projectToken(boundary, config.project.baseBundleId);\n const store = createStore(boundary, ota, options.s3);\n\n const buildId = buildIdFor(meta);\n const key = (...segments: string[]): string => objectKey(ota, token, ...segments);\n const buildKey = (...segments: string[]): string => key('builds', buildId, ...segments);\n\n const ipaBytes = boundary.fs.size(options.ipa);\n const ipaSizeLabel = megabytes(ipaBytes);\n\n // One icon at the prefix root, referenced by every manifest, so the tile that\n // appears while installing is the app's icon and not a grey placeholder.\n const iconPath = config.project.appIcon ? project.path(config.project.appIcon) : '';\n const iconUrl =\n iconPath && boundary.fs.exists(iconPath) ? publicUrl(ota, key('icon.png')) : undefined;\n if (iconUrl) {\n await store.put(key('icon.png'), boundary.fs.readBytes(iconPath), 'image/png');\n }\n\n boundary.log.step(`uploading ${ipaSizeLabel} .ipa → ${ota.storage.bucket}/${buildKey(IPA_NAME)}`);\n await store.put(\n buildKey(IPA_NAME),\n boundary.fs.readBytes(options.ipa),\n 'application/octet-stream',\n );\n\n const manifestUrl = publicUrl(ota, buildKey('manifest.plist'));\n await store.put(\n buildKey('manifest.plist'),\n renderManifestPlist({\n bundleId: meta.bundleId,\n bundleVersion: meta.version,\n title: meta.appName,\n ipaUrl: publicUrl(ota, buildKey(IPA_NAME)),\n ...(iconUrl ? { displayImageUrl: iconUrl, fullSizeImageUrl: iconUrl } : {}),\n }),\n 'text/xml',\n );\n\n await store.put(\n buildKey('index.html'),\n renderInstallPage(meta, { config, ota, manifestUrl, ipaSizeLabel }),\n 'text/html; charset=utf-8',\n );\n\n const record: BuildRecord = {\n buildId,\n appName: meta.appName,\n bundleId: meta.bundleId,\n version: meta.version,\n build: meta.build,\n versionTag: meta.versionTag,\n variantBadge: meta.variantBadge,\n branch: meta.branch,\n commit: meta.commit,\n dirty: meta.dirty,\n ipaSizeLabel,\n ipaSizeBytes: ipaBytes,\n builtAt: meta.builtAt,\n uploadedAt: new Date(boundary.now() * 1000).toISOString(),\n };\n const merged = mergeRecords(await readRegistry(store, key(REGISTRY_NAME)), record, ota.maxBuilds);\n await store.put(key(REGISTRY_NAME), JSON.stringify(merged, null, 2), 'application/json');\n await store.put(\n key('index.html'),\n renderIndexPage(merged, { config, ota, token, generatedAt: utcStamp(boundary.now()) }),\n 'text/html; charset=utf-8',\n );\n\n // Last, and never earlier: a printed URL that 403s costs a build cycle to\n // diagnose from the phone, where the only symptom is \"Cannot connect\".\n await verifyReachable(boundary, ota, manifestUrl);\n\n const installUrl = publicUrl(ota, buildKey('index.html'));\n const indexUrl = publicUrl(ota, key('index.html'));\n boundary.log.info(\n `published ${meta.versionTag} (${ipaSizeLabel}) — open in Safari: ${installUrl}`,\n );\n boundary.log.info(`${merged.length} build(s) listed at ${indexUrl}`);\n return { installUrl, indexUrl, manifestUrl, record, builds: merged.length };\n}\n\n/**\n * Rebuild the index page from the bucket alone — no build, no archive. For when\n * the page was clobbered, the registry was hand-edited, or the branding\n * changed and every page should say the new thing.\n */\nexport async function reindex(\n boundary: Boundary,\n project: Project,\n options: { s3?: S3Factory } = {},\n): Promise<{ indexUrl: string; builds: number }> {\n const ota = requireOta(project);\n const token = projectToken(boundary, project.config.project.baseBundleId);\n const store = createStore(boundary, ota, options.s3);\n\n const records = await readRegistry(store, objectKey(ota, token, REGISTRY_NAME));\n const page = renderIndexPage(records, {\n config: project.config,\n ota,\n token,\n generatedAt: utcStamp(boundary.now()),\n });\n await store.put(objectKey(ota, token, 'index.html'), page, 'text/html; charset=utf-8');\n\n const indexUrl = publicUrl(ota, objectKey(ota, token, 'index.html'));\n boundary.log.info(`reindexed ${records.length} build(s) → ${indexUrl}`);\n return { indexUrl, builds: records.length };\n}\n","/**\n * Reading the files that ship beside the code.\n *\n * The HTML templates are package assets, not project files, so they are read\n * here rather than through the boundary. Resolving them from\n * `import.meta.dirname` would work in source and break once tsup bundles\n * `src/*.ts` into `dist/` — the chunk's directory is not the package root, and\n * `templates/` sits next to it, not under it. So the package root is found the\n * only way that survives bundling: walk up until `package.json` appears.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nlet cachedRoot: string | undefined;\n\n/** The directory holding this package's `package.json`. */\nexport function packageRoot(): string {\n if (cachedRoot) return cachedRoot;\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n if (existsSync(join(dir, 'package.json'))) {\n cachedRoot = dir;\n return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) {\n throw new Error(\n `could not find the jetbridge package root above ${dirname(fileURLToPath(import.meta.url))}.\\n` +\n ' Reinstall the package — its templates/ directory is missing.',\n );\n }\n dir = parent;\n }\n}\n\nexport function templatePath(name: string): string {\n return join(packageRoot(), 'templates', name);\n}\n\nexport function readTemplate(name: string): string {\n const path = templatePath(name);\n if (!existsSync(path)) {\n throw new Error(`missing template ${path} — reinstall jetbridge, its assets are incomplete`);\n }\n return readFileSync(path, 'utf8');\n}\n\n/**\n * Substitute `{{TOKEN}}` placeholders and refuse to emit a page that still has\n * one. A renamed placeholder is then a loud failure instead of literal braces\n * on a page someone is about to install from.\n *\n * Function replacements, because a string replacement interprets `$&` and `$1`\n * in the REPLACEMENT — and a branch name is allowed to contain them.\n */\nexport function fillTemplate(template: string, values: Record<string, string>): string {\n let page = template;\n for (const [key, value] of Object.entries(values)) {\n page = page.replaceAll(`{{${key}}}`, () => value);\n }\n const missing = [...new Set(page.match(/\\{\\{[A-Z_]+\\}\\}/g) ?? [])];\n if (missing.length > 0) {\n throw new Error(\n `the template has unsubstituted placeholders: ${missing.join(', ')}.\\n` +\n ' Every {{TOKEN}} needs a value — pass it, or drop it from the template.',\n );\n }\n return page;\n}\n","/**\n * Driving xcodebuild.\n *\n * Every argument is assembled here and nowhere else, so what the build actually\n * runs is one readable list — and one thing a test can assert without Xcode\n * installed.\n */\nimport { join } from 'node:path';\nimport { localCredentials } from './asc.js';\nimport type { Boundary, CommandResult } from './boundary.js';\nimport type { Config } from './config.js';\nimport { fail, type Project } from './project.js';\nimport { signSettings, variantSettings, type SigningProfiles } from './signing.js';\n\nexport interface BuildRequest {\n configuration: string;\n suffix: string;\n displayName: string;\n profiles: SigningProfiles;\n derivedDataPath: string;\n /** `generic/platform=iOS` for a device build, or a simulator destination. */\n destination: string;\n /** Unix seconds; a fresh number every run — see `buildNumber`. */\n buildNumber: string;\n gitSha?: string;\n /** Device builds skip the separate dSYM; an archive keeps it. */\n withDsym?: boolean;\n}\n\n/**\n * A build number that always increases.\n *\n * iOS treats \"this CFBundleVersion is already installed\" as nothing to do: it\n * skips the install without a word, and you keep launching the stale app. A\n * fresh number forces the replacement every time.\n */\nexport const buildNumber = (boundary: Boundary): string => String(boundary.now());\n\n/**\n * `-authenticationKey*` flags, which let `-allowProvisioningUpdates` refresh a\n * profile headlessly. Empty when this machine has no credentials — a plain\n * build against a cached profile needs none.\n */\nexport function authArgs(boundary: Boundary, config: Config): string[] {\n const credentials = localCredentials(boundary, config);\n if (!credentials) return [];\n return [\n '-authenticationKeyPath',\n credentials.keyPath,\n '-authenticationKeyID',\n credentials.keyId,\n '-authenticationKeyIssuerID',\n credentials.issuerId,\n ];\n}\n\nexport function buildArgs(boundary: Boundary, project: Project, request: BuildRequest): string[] {\n const { config } = project;\n return [\n 'build',\n ...project.xcodebuildTarget(),\n '-scheme',\n config.project.scheme,\n '-configuration',\n request.configuration,\n '-destination',\n request.destination,\n '-derivedDataPath',\n request.derivedDataPath,\n `CURRENT_PROJECT_VERSION=${request.buildNumber}`,\n // No separate dSYM on the inner loop. Generating one for every target adds\n // seconds to each incremental install, for a debug artifact a dev build\n // never reads: a non-stripped build symbolicates from its own DWARF.\n ...(request.withDsym ? [] : ['DEBUG_INFORMATION_FORMAT=dwarf']),\n ...(request.gitSha ? [`${config.variant.buildSettings.gitSha}=${request.gitSha}`] : []),\n ...variantSettings(request.suffix, request.displayName, config),\n ...signSettings(request.suffix, request.profiles, config),\n '-allowProvisioningUpdates',\n ...authArgs(boundary, config),\n '-quiet',\n ];\n}\n\n/** Where a built `.app` lands for a given configuration and platform. */\nexport function productPath(\n request: Pick<BuildRequest, 'derivedDataPath' | 'configuration'>,\n config: Config,\n platform: 'iphoneos' | 'iphonesimulator',\n): string {\n return join(\n request.derivedDataPath,\n 'Build',\n 'Products',\n `${request.configuration}-${platform}`,\n `${config.project.scheme}.app`,\n );\n}\n\n/** Fail before the slow steps if a required tool or the project is missing. */\nexport async function requireToolchain(\n boundary: Boundary,\n project: Project,\n binaries: string[],\n): Promise<void> {\n for (const binary of binaries) {\n const found = await boundary.exec.run('command', ['-v', binary], { allowFail: true });\n if (!found.ok) fail(`${binary} was not found on PATH`);\n }\n const [, target] = project.xcodebuildTarget();\n if (!boundary.fs.exists(target)) {\n fail(\n `missing ${target}.\\n` +\n (project.config.project.projectYml\n ? ' Generate the project first, then re-run.'\n : ' Check project.xcodeproj in the config.'),\n );\n }\n}\n\n/** Regenerate the project from its spec, when the config says it is generated. */\nexport async function generateProject(boundary: Boundary, project: Project): Promise<void> {\n if (!project.config.project.xcodegen) return;\n boundary.log.step('regenerating the Xcode project');\n const result = await boundary.exec.run('xcodegen', ['generate'], {\n cwd: project.iosPath(),\n allowFail: true,\n });\n if (!result.ok) fail(`xcodegen failed:\\n${(result.stderr || result.stdout).trim()}`);\n}\n\n/** Run a configured shell hook in the project root. */\nexport async function runHook(\n boundary: Boundary,\n project: Project,\n which: 'preBuild' | 'postBuild',\n): Promise<void> {\n const command = project.config.hooks[which];\n if (!command) return;\n boundary.log.step(`${which}: ${command}`);\n const result = await boundary.exec.run('/bin/sh', ['-c', command], {\n cwd: project.root,\n stdio: 'inherit',\n allowFail: true,\n });\n if (!result.ok) fail(`the ${which} hook failed (exit ${result.code}): ${command}`);\n}\n\nexport async function build(\n boundary: Boundary,\n project: Project,\n request: BuildRequest,\n): Promise<CommandResult> {\n const args = buildArgs(boundary, project, request);\n boundary.log.step(\n `building ${request.configuration}/${project.config.project.scheme} (build ${request.buildNumber})`,\n );\n const result = await boundary.exec.run('xcodebuild', args, {\n cwd: project.root,\n allowFail: true,\n });\n if (!result.ok) {\n // xcodebuild's useful lines are at the end; the first hundred are noise.\n const tail = (result.stderr || result.stdout).trim().split('\\n').slice(-20).join('\\n');\n fail(`xcodebuild failed:\\n${tail}`);\n }\n return result;\n}\n","/**\n * Signing: the build settings that point a variant build at its profiles, and\n * the on-disk cache that lets a repeat install skip provisioning entirely.\n */\nimport { createHash } from 'node:crypto';\nimport { join } from 'node:path';\nimport type { Boundary } from './boundary.js';\nimport type { Config, TargetConfig } from './config.js';\nimport { profileDirectory, profileNameFor } from './provision.js';\n\nexport interface SigningProfiles {\n /** Target name → provisioning profile name. */\n byTarget: Record<string, string>;\n}\n\n/** `JETBRIDGE_PROFILE_APP`, or whatever the target configured. */\nexport function profileSettingName(target: TargetConfig): string {\n if (target.profileSetting) return target.profileSetting;\n const key = (target.bundleIdSuffix ?? 'app').toUpperCase().replace(/[^A-Z0-9]/g, '_');\n return `JETBRIDGE_PROFILE_${key}`;\n}\n\n/** Build settings that put the build on manual signing against our profiles. */\nexport function signSettings(suffix: string, profiles: SigningProfiles, config: Config): string[] {\n // No variant means the project's own automatic signing, untouched.\n if (!suffix) return [];\n const settings = [`${config.variant.buildSettings.signStyle}=Manual`];\n for (const target of config.variant.targets) {\n const profile = profiles.byTarget[target.name];\n if (profile) settings.push(`${profileSettingName(target)}=${profile}`);\n }\n return settings;\n}\n\n/** The bundle-id suffix and home-screen label, as build settings. */\nexport function variantSettings(suffix: string, displayName: string, config: Config): string[] {\n const names = config.variant.buildSettings;\n return [\n ...(suffix ? [`${names.bundleSuffix}=.${suffix}`] : []),\n ...(displayName ? [`${names.displayName}=${displayName}`] : []),\n ];\n}\n\ninterface ParsedProfile {\n name: string;\n expiresMs: number;\n devices: Set<string>;\n certificateSha1: Set<string>;\n}\n\n/** The few fields that decide whether a cached profile can still sign. */\nexport function parseProfilePlist(xml: string): ParsedProfile | null {\n const name = /<key>Name<\\/key>\\s*<string>([^<]*)<\\/string>/.exec(xml)?.[1];\n const expires = /<key>ExpirationDate<\\/key>\\s*<date>([^<]*)<\\/date>/.exec(xml)?.[1];\n if (!name || !expires) return null;\n\n const devices = new Set<string>();\n const deviceBlock = /<key>ProvisionedDevices<\\/key>\\s*<array>([\\s\\S]*?)<\\/array>/.exec(xml)?.[1];\n for (const match of (deviceBlock ?? '').matchAll(/<string>([^<]+)<\\/string>/g)) {\n devices.add(match[1]!);\n }\n\n const certificateSha1 = new Set<string>();\n const certificateBlock = /<key>DeveloperCertificates<\\/key>\\s*<array>([\\s\\S]*?)<\\/array>/.exec(\n xml,\n )?.[1];\n for (const match of (certificateBlock ?? '').matchAll(/<data>([\\s\\S]*?)<\\/data>/g)) {\n const der = Buffer.from(match[1]!.replace(/\\s+/g, ''), 'base64');\n certificateSha1.add(createHash('sha1').update(der).digest('hex').toUpperCase());\n }\n return { name, expiresMs: Date.parse(expires), devices, certificateSha1 };\n}\n\n/** SHA-1 thumbprints of every codesigning identity whose key is in this keychain. */\nexport function localSigningThumbprints(boundary: Boundary): Set<string> {\n const output = boundary.exec.runSync('security', [\n 'find-identity',\n '-v',\n '-p',\n 'codesigning',\n ]).stdout;\n const thumbprints = new Set<string>();\n for (const match of output.matchAll(/\\b([0-9A-F]{40})\\b/g)) thumbprints.add(match[1]!);\n return thumbprints;\n}\n\n/** A profile within this long of expiry is treated as already expired. */\nconst EXPIRY_MARGIN_MS = 24 * 60 * 60 * 1000;\n\n/**\n * The fast path around provisioning: if valid profiles for this variant are\n * already installed, skip the round trips to Apple.\n *\n * A profile only counts when every one of these holds, so a stale one never\n * silently signs a build that then refuses to install:\n * - its name is what the provisioner mints, for every target;\n * - it is not within a day of expiring;\n * - it covers every device this install targets (a newly registered phone is\n * a miss, and provisioning adds it);\n * - it embeds a certificate whose private key is in this keychain, which is\n * what closes the certificate-rotation hole.\n *\n * Any parse or tool hiccup returns null: the caller then provisions, which is\n * the correct outcome, just slower.\n */\nexport function cachedSigning(\n boundary: Boundary,\n config: Config,\n options: { suffix: string; deviceUdids: string[]; now: number },\n): SigningProfiles | null {\n try {\n const directory = profileDirectory(boundary);\n if (!boundary.fs.exists(directory)) return null;\n const identities = localSigningThumbprints(boundary);\n if (identities.size === 0) return null;\n\n const wanted = new Map(\n config.variant.targets.map((target) => [\n profileNameFor(target, options.suffix, config),\n target.name,\n ]),\n );\n if (wanted.size === 0) return null;\n if (options.deviceUdids.length === 0 || options.deviceUdids.some((udid) => !udid)) return null;\n\n const found: Record<string, string> = {};\n for (const file of boundary.fs.readdir(directory)) {\n if (!file.endsWith('.mobileprovision')) continue;\n if (Object.keys(found).length === wanted.size) break;\n\n const decoded = boundary.exec.runSync('security', ['cms', '-D', '-i', join(directory, file)]);\n if (!decoded.ok) continue;\n const parsed = parseProfilePlist(decoded.stdout);\n if (!parsed) continue;\n\n const targetName = wanted.get(parsed.name);\n if (!targetName) continue;\n if (Number.isNaN(parsed.expiresMs)) continue;\n if (parsed.expiresMs - options.now * 1000 < EXPIRY_MARGIN_MS) continue;\n if (!options.deviceUdids.every((udid) => parsed.devices.has(udid))) continue;\n if (![...parsed.certificateSha1].some((sha) => identities.has(sha))) continue;\n\n found[targetName] = parsed.name;\n }\n\n return Object.keys(found).length === wanted.size ? { byTarget: found } : null;\n } catch {\n return null;\n }\n}\n","/**\n * The variant entitlement swap.\n *\n * A variant build differs from the committed project in exactly one respect: it\n * signs against reduced entitlements, because capabilities like app groups and\n * Sign in with Apple cannot be granted through the public App Store Connect\n * API. In the project file that is the `CODE_SIGN_ENTITLEMENTS` assignments,\n * and nothing else.\n *\n * So those lines are patched in place rather than the project being\n * regenerated. A regeneration rewrites the whole project; xcodebuild\n * fingerprints it by content, sees a change, and rebuilds — turning every\n * incremental install into a slow one. The targeted patch touches only the\n * lines the build already expects to differ.\n */\nimport type { Boundary } from './boundary.js';\nimport { fail, type Project } from './project.js';\n\n/**\n * Project generators quote a path containing anything a bare token cannot hold\n * (a hyphen, typically). Matching that spelling exactly is what keeps the\n * patched file byte-identical to a regenerated one — and byte-identity is what\n * keeps the build incremental.\n */\nexport const codeSignLine = (path: string): string =>\n `CODE_SIGN_ENTITLEMENTS = ${/[^A-Za-z0-9/._]/.test(path) ? `\"${path}\"` : path};`;\n\n/** Every target that declares both a shipping and a variant entitlements file. */\nexport function swappableTargets(project: Project): Array<{ from: string; to: string }> {\n return project.config.variant.targets\n .filter((target) => target.entitlements && target.variantEntitlements)\n .map((target) => ({ from: target.entitlements!, to: target.variantEntitlements! }));\n}\n\nexport const pbxprojPath = (project: Project): string =>\n project.iosPath(project.config.project.xcodeproj ?? '', 'project.pbxproj');\n\nexport function applySwap(boundary: Boundary, project: Project): void {\n const path = pbxprojPath(project);\n const swaps = swappableTargets(project);\n const before = boundary.fs.read(path);\n let after = before;\n for (const swap of swaps) {\n after = after.replaceAll(codeSignLine(swap.from), codeSignLine(swap.to));\n }\n const applied = swaps.every((swap) => after.includes(codeSignLine(swap.to)));\n if (after === before || !applied) {\n fail(\n 'the entitlement swap matched no CODE_SIGN_ENTITLEMENTS in the project file.\\n' +\n ' Check that variant.targets[].entitlements matches the path the project spells,\\n' +\n ' and regenerate the project if it is stale.',\n );\n }\n boundary.fs.write(path, after);\n}\n\n/**\n * A swap stranded by a killed run. The project file is tracked, so a later\n * `git add -A` would quietly commit the reduced entitlements — and the next\n * build would sign against them without anyone asking for a variant.\n *\n * Only an assignment counts. A clean project already mentions the variant\n * entitlements file in its file references, because the file exists on disk.\n */\nexport function findStrandedSwap(boundary: Boundary, project: Project): string | null {\n const path = pbxprojPath(project);\n if (!boundary.fs.exists(path)) return null;\n const contents = boundary.fs.read(path);\n const stranded = swappableTargets(project).find((swap) =>\n contents.includes(codeSignLine(swap.to)),\n );\n return stranded ? path : null;\n}\n\n/**\n * Run `body` with the swap applied, and restore the original bytes whatever\n * happens.\n *\n * The restore copies the pre-swap bytes back rather than reverting through git,\n * which would also discard unrelated uncommitted edits. `finally` covers a\n * normal exit or a throw; the signal handlers cover the rest.\n *\n * SIGTERM and SIGHUP matter as much as SIGINT here: their default action is to\n * die without unwinding, so a `kill` from another shell or an editor's stop\n * button would otherwise strand the reduced entitlements in the working tree.\n * SIGKILL cannot be caught — that is what the stranded check is for.\n *\n * `body` must not block the event loop, or no handler can run while it does.\n * The restore itself stays synchronous: it has to finish inside the handler,\n * before the process exits.\n *\n * A no-op without a variant slug: a plain build keeps full entitlements.\n */\nconst FATAL_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const;\n\n/** 128 + signal number, the conventional exit code for a signalled death. */\nconst SIGNAL_EXIT_CODES: Record<string, number> = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };\n\nexport async function withEntitlementSwap<T>(\n boundary: Boundary,\n project: Project,\n options: { suffix: string; backupPath: string },\n body: () => Promise<T>,\n): Promise<T> {\n if (!options.suffix || swappableTargets(project).length === 0) return body();\n\n const stranded = findStrandedSwap(boundary, project);\n if (stranded) {\n fail(\n `${stranded} still carries a variant entitlement swap from an interrupted run.\\n` +\n ` Restore it first (\\`git checkout -- ${stranded}\\`), then re-run.`,\n );\n }\n\n const path = pbxprojPath(project);\n let swapped = false;\n const restore = (): void => {\n if (!swapped) return;\n swapped = false;\n boundary.log.info('restoring the project file (variant entitlement swap)');\n boundary.fs.write(path, boundary.fs.read(options.backupPath));\n };\n\n const handlers = FATAL_SIGNALS.map(\n (signal) =>\n [\n signal,\n () => {\n boundary.log.warn(`${signal} — restoring the project file before exit`);\n restore();\n process.exit(SIGNAL_EXIT_CODES[signal] ?? 1);\n },\n ] as const,\n );\n for (const [signal, handler] of handlers) process.on(signal, handler);\n\n try {\n boundary.fs.write(options.backupPath, boundary.fs.read(path));\n boundary.log.step('patching the project file → reduced variant entitlements');\n applySwap(boundary, project);\n swapped = true;\n return await body();\n } finally {\n restore();\n for (const [signal, handler] of handlers) process.removeListener(signal, handler);\n }\n}\n","/**\n * The two plists an over-the-air install needs, and the escaper that guards\n * every value on the way into either.\n *\n * `manifest.plist` is what Apple's itms-services installer reads; the export\n * options plist is what `xcodebuild -exportArchive` reads. Both are generated,\n * never shipped as static files — a static export plist cannot name the\n * per-target provisioning profiles a variant signs against, and the one in the\n * tool this was extracted from had drifted to say `development` under a comment\n * claiming ad hoc.\n */\nimport type { OtaConfig } from './config.js';\n\n/**\n * One escaper for both markup languages. The five entities are the intersection\n * of what XML and HTML need, so a display name containing `&` can neither\n * garble a page nor make the plist unparseable — and an unparseable manifest\n * fails the install with no message on the device.\n */\nexport const escapeHtml = (value: string): string =>\n value\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''');\n\nexport interface ManifestInput {\n /** MUST match the .ipa's CFBundleIdentifier, or iOS refuses the install. */\n bundleId: string;\n /** What iOS compares to decide upgrade against reinstall. */\n bundleVersion: string;\n /** Shown in the system install confirmation sheet. */\n title: string;\n /** Absolute HTTPS URL of the .ipa. Fetched by the device with no auth header. */\n ipaUrl: string;\n /** 57×57 icon shown on the installing tile. Any square PNG works. */\n displayImageUrl?: string;\n /** 512×512 icon shown while the install finishes. */\n fullSizeImageUrl?: string;\n}\n\nconst PLIST_HEADER =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" ' +\n '\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\\n' +\n '<plist version=\"1.0\">\\n';\n\nexport function renderManifestPlist(input: ManifestInput): string {\n const x = escapeHtml;\n const imageAsset = (kind: string, url: string): string =>\n `\\n <dict>\n <key>kind</key>\n <string>${kind}</string>\n <key>url</key>\n <string>${x(url)}</string>\n </dict>`;\n\n const extraAssets =\n (input.displayImageUrl ? imageAsset('display-image', input.displayImageUrl) : '') +\n (input.fullSizeImageUrl ? imageAsset('full-size-image', input.fullSizeImageUrl) : '');\n\n return `${PLIST_HEADER}<dict>\n <key>items</key>\n <array>\n <dict>\n <key>assets</key>\n <array>\n <dict>\n <key>kind</key>\n <string>software-package</string>\n <key>url</key>\n <string>${x(input.ipaUrl)}</string>\n </dict>${extraAssets}\n </array>\n <key>metadata</key>\n <dict>\n <key>bundle-identifier</key>\n <string>${x(input.bundleId)}</string>\n <key>bundle-version</key>\n <string>${x(input.bundleVersion)}</string>\n <key>kind</key>\n <string>software</string>\n <key>title</key>\n <string>${x(input.title)}</string>\n </dict>\n </dict>\n </array>\n</dict>\n</plist>\n`;\n}\n\n/**\n * The Safari-openable link that hands off to the iOS installer. The manifest\n * URL carries `://`, `/` and `?`, so it has to be percent-encoded — unencoded,\n * Safari reads the manifest's own query string as part of the link's.\n */\nexport const itmsServicesUrl = (manifestUrl: string): string =>\n `itms-services://?action=download-manifest&url=${encodeURIComponent(manifestUrl)}`;\n\nexport interface ExportOptionsInput {\n teamId: string;\n method: OtaConfig['exportMethod'];\n /**\n * Bundle id → provisioning profile name, one entry per signed target. Empty\n * for a plain build, which keeps the project's own automatic signing.\n */\n provisioningProfiles?: Record<string, string>;\n}\n\n/**\n * The `-exportOptionsPlist` argument to `xcodebuild -exportArchive`.\n *\n * `method` is written through from the config verbatim. Xcode 16 renamed\n * `ad-hoc` to `release-testing` and still accepts the old spelling with a\n * deprecation warning, so the old one is the value that works on both.\n *\n * A variant signs manually: its profiles were minted minutes ago by the\n * provisioner and automatic signing would pick whatever Xcode already had\n * cached for that bundle id instead.\n */\nexport function renderExportOptionsPlist(input: ExportOptionsInput): string {\n const x = escapeHtml;\n const profiles = Object.entries(input.provisioningProfiles ?? {});\n const manual = profiles.length > 0;\n const profileDict = manual\n ? `\n <key>provisioningProfiles</key>\n <dict>\n${profiles\n .map(\n ([bundleId, profile]) =>\n ` <key>${x(bundleId)}</key>\\n <string>${x(profile)}</string>`,\n )\n .join('\\n')}\n </dict>`\n : '';\n\n return `${PLIST_HEADER}<dict>\n <key>method</key>\n <string>${x(input.method)}</string>\n <key>teamID</key>\n <string>${x(input.teamId)}</string>\n <key>signingStyle</key>\n <string>${manual ? 'manual' : 'automatic'}</string>\n <key>destination</key>\n <string>export</string>\n <key>compileBitcode</key>\n <false/>\n <key>uploadSymbols</key>\n <false/>\n <key>stripSwiftSymbols</key>\n <true/>${profileDict}\n</dict>\n</plist>\n`;\n}\n","/**\n * The bucket half of an over-the-air install: where an object lands, what URL\n * the phone fetches it from, and the check that it can.\n *\n * Nothing here knows what a build is. It knows keys, bytes and one HEAD\n * request — which is what lets the whole upload path be tested without a\n * network, and what keeps the reachability check in one place instead of at\n * every call site that prints a URL.\n */\nimport {\n GetObjectCommand,\n PutObjectCommand,\n S3Client,\n type S3ClientConfig,\n} from '@aws-sdk/client-s3';\nimport { randomBytes } from 'node:crypto';\nimport { join } from 'node:path';\nimport type { Boundary } from './boundary.js';\nimport type { OtaConfig } from './config.js';\nimport { fail } from './project.js';\n\n/** The slice of the S3 client this tool uses. A test supplies its own. */\nexport interface S3Like {\n send(command: PutObjectCommand | GetObjectCommand): Promise<{\n Body?: { transformToString(): Promise<string> };\n }>;\n}\n\nexport type S3Factory = (config: S3ClientConfig) => S3Like;\n\n// The real client's `send` is a union of every command overload; narrowing it to\n// the two commands used here is the whole point of `S3Like`.\nexport const awsS3Factory: S3Factory = (config) => new S3Client(config) as unknown as S3Like;\n\nexport interface ObjectStore {\n put(key: string, body: string | Uint8Array, contentType: string): Promise<void>;\n /** The object's text, or null when it is not there yet. */\n getText(key: string): Promise<string | null>;\n}\n\n/**\n * Credentials come from the environment, named by the config. A bucket secret\n * in a file that lives in the repository is the one mistake this tool must not\n * make easy, so the config carries variable NAMES and never values.\n */\nexport function credentials(\n boundary: Boundary,\n ota: OtaConfig,\n): { accessKeyId: string; secretAccessKey: string } {\n const accessKeyId = boundary.env(ota.storage.accessKeyId)?.trim();\n const secretAccessKey = boundary.env(ota.storage.secretAccessKey)?.trim();\n if (!accessKeyId || !secretAccessKey) {\n const missing = [\n !accessKeyId ? ota.storage.accessKeyId : null,\n !secretAccessKey ? ota.storage.secretAccessKey : null,\n ].filter(Boolean);\n fail(\n `the OTA bucket credentials are not set: ${missing.join(', ')}.\\n` +\n ' Export them in this shell, or point ota.storage.accessKeyId / secretAccessKey at the\\n' +\n ' variable names you already use.',\n );\n }\n return { accessKeyId, secretAccessKey };\n}\n\n/**\n * Which objects may be cached forever.\n *\n * A build's .ipa and manifest are immutable — their key carries the build id.\n * Everything else is rewritten on every publish, including the icon, which\n * lives at the prefix root: cache that for a year and a changed app icon never\n * reaches the install tile again.\n */\nconst MUTABLE = ['.html', '.json', '.png'];\n\nconst cacheControlFor = (key: string): string =>\n MUTABLE.some((suffix) => key.endsWith(suffix))\n ? 'no-cache'\n : 'public, max-age=31536000, immutable';\n\nexport function createStore(\n boundary: Boundary,\n ota: OtaConfig,\n factory: S3Factory = awsS3Factory,\n): ObjectStore {\n const { bucket, region, endpoint } = ota.storage;\n const client = factory({\n region,\n // An S3-compatible host (R2, MinIO, Backblaze) rarely serves virtual-hosted\n // style, and getting it wrong reads as a DNS failure rather than a config one.\n ...(endpoint ? { endpoint, forcePathStyle: true } : {}),\n credentials: credentials(boundary, ota),\n });\n\n return {\n async put(key, body, contentType) {\n await client.send(\n new PutObjectCommand({\n Bucket: bucket,\n Key: key,\n Body: body,\n ContentType: contentType,\n // No `ACL: public-read`: readability comes from the bucket policy on\n // the prefix, which is the only thing that works on a bucket with\n // Block Public ACLs on — which is the default on a new bucket.\n CacheControl: cacheControlFor(key),\n }),\n );\n },\n async getText(key) {\n try {\n const result = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));\n return (await result.Body?.transformToString()) ?? null;\n } catch (error) {\n // A first-ever publish has no registry yet. That is the empty base\n // case, not a failure.\n const code =\n (error as { name?: string; Code?: string }).name ?? (error as { Code?: string }).Code;\n if (code === 'NoSuchKey' || code === 'NotFound') return null;\n throw error;\n }\n },\n };\n}\n\n/**\n * The path segment that gates the install URL.\n *\n * `access: 'path'` puts an unguessable segment in every key, so a visitor at\n * the bucket root has nothing to browse. iOS fetches the manifest and the .ipa\n * with no auth header, so a URL-as-secret is the pattern that fits: a presigned\n * URL expires inside a page that is meant to stay bookmarkable for weeks.\n */\nexport function objectPrefix(ota: OtaConfig, token: string): string {\n const segments = [\n ota.storage.prefix.replace(/^\\/+|\\/+$/g, ''),\n ota.access === 'path' ? token : '',\n ];\n return segments.filter(Boolean).join('/');\n}\n\nexport function objectKey(ota: OtaConfig, token: string, ...segments: string[]): string {\n return [objectPrefix(ota, token), ...segments].filter(Boolean).join('/');\n}\n\nexport function publicUrl(ota: OtaConfig, key: string): string {\n return `${ota.storage.publicBaseUrl.replace(/\\/+$/, '')}/${key}`;\n}\n\n/**\n * Where a project's access token is kept.\n *\n * Keyed by the base bundle id, under the user cache directory — NOT one dotfile\n * in $HOME. Two checkouts on one machine publish two different apps, and a\n * shared file means the second one silently rewrites the first one's install\n * URL. Every variant of one project shares the token deliberately: they publish\n * to one prefix and one index page.\n */\nexport function tokenPath(boundary: Boundary, bundleId: string): string {\n return join(boundary.homedir(), 'Library', 'Caches', 'jetbridge', 'ota', `${bundleId}.token`);\n}\n\n/** ~48 bits — long enough that guessing it is not a strategy. */\nexport function projectToken(boundary: Boundary, bundleId: string): string {\n const path = tokenPath(boundary, bundleId);\n if (boundary.fs.exists(path)) {\n const existing = boundary.fs.read(path).trim();\n if (existing) return existing;\n }\n const token = randomBytes(6).toString('hex');\n boundary.fs.write(path, `${token}\\n`);\n return token;\n}\n\n/**\n * The single most useful check in the whole flow: can the device actually GET\n * the manifest?\n *\n * A bucket that uploads fine but serves 403 is the common misconfiguration, and\n * iOS reports it as \"Cannot connect to <host>\" with nothing else — no status,\n * no URL, no hint that the bytes are there and the policy is wrong. So the\n * manifest is fetched over HTTPS here, before any URL is printed.\n */\nexport async function verifyReachable(\n boundary: Boundary,\n ota: OtaConfig,\n manifestUrl: string,\n): Promise<void> {\n let status: number;\n try {\n const response = await boundary.http({ method: 'HEAD', url: manifestUrl, headers: {} });\n status = response.status;\n } catch (error) {\n fail(\n `could not reach the uploaded manifest at ${manifestUrl} — ${(error as Error).message}.\\n` +\n ` Check that ota.storage.publicBaseUrl points at how bucket \"${ota.storage.bucket}\" is served.`,\n );\n }\n if (status >= 200 && status < 300) return;\n\n const cause =\n status === 403 || status === 401\n ? `the bucket policy on \"${ota.storage.bucket}\" does not allow public reads of this prefix`\n : status === 404\n ? 'the object is not at that URL, so ota.storage.publicBaseUrl or prefix does not match the bucket'\n : 'the bucket returned an unexpected status';\n fail(\n `the manifest is not reachable: HTTP ${status} on ${manifestUrl}.\\n` +\n ` Likely cause: ${cause}.\\n` +\n ` Grant s3:GetObject on \"${ota.storage.prefix}/*\" to everyone (never s3:ListBucket), then\\n` +\n ' re-run. iOS reports this failure only as \"Cannot connect\", so it is checked here instead.',\n );\n}\n","/**\n * The cabled install: build, then push the `.app` straight to every reachable\n * paired device with `xcrun devicectl`. No archive, no export, no upload — the\n * fast inner loop when the phone is on the desk.\n */\nimport { join } from 'node:path';\nimport { localCredentials } from './asc.js';\nimport type { Boundary } from './boundary.js';\nimport {\n build,\n buildNumber,\n generateProject,\n productPath,\n requireToolchain,\n runHook,\n} from './build.js';\nimport { pairedDevices, resolveTargets, type InstallTarget } from './devices.js';\nimport { withEntitlementSwap } from './entitlements.js';\nimport { fail, type Project } from './project.js';\nimport { provisionVariant } from './provision.js';\nimport { cachedSigning, type SigningProfiles } from './signing.js';\nimport { bundleIdFor } from './variant.js';\n\nexport interface WiredOptions {\n suffix: string;\n displayName: string;\n /** Install to one device: identifier, name, UDID or serial. */\n device?: string;\n configuration?: string;\n /** Wipe the cached DerivedData first, for a genuinely corrupt build. */\n clean?: boolean;\n /** Bypass the on-disk profile cache — reach for this after a certificate rotation. */\n reprovision?: boolean;\n}\n\n/**\n * DerivedData that persists per variant, so a repeat install is incremental.\n *\n * This is the inner loop's biggest lever: wiping it turns every install into a\n * clean build of every dependency. It lives under the user cache directory so\n * the OS can reclaim it under disk pressure and the next build repopulates it.\n * Keyed by variant only — xcodebuild namespaces the configuration internally.\n */\nexport function derivedDataPath(boundary: Boundary, suffix: string): string {\n return join(boundary.homedir(), 'Library', 'Caches', 'jetbridge', suffix || 'default');\n}\n\nexport function scratchPath(boundary: Boundary, suffix: string): string {\n return join(\n boundary.homedir(),\n 'Library',\n 'Caches',\n 'jetbridge',\n '.scratch',\n suffix || 'default',\n );\n}\n\n/**\n * Profiles for the build: the on-disk cache when it already covers exactly\n * these devices, otherwise fresh provisioning.\n */\nasync function resolveSigning(\n boundary: Boundary,\n project: Project,\n options: WiredOptions,\n targets: InstallTarget[],\n): Promise<SigningProfiles> {\n if (!options.suffix) return { byTarget: {} };\n\n const deviceUdids = targets.map((target) => target.udid);\n if (!options.reprovision) {\n const cached = cachedSigning(boundary, project.config, {\n suffix: options.suffix,\n deviceUdids,\n now: boundary.now(),\n });\n if (cached) {\n boundary.log.info(\n 'signing: cached profiles already cover these devices — skipping provisioning',\n );\n return cached;\n }\n }\n\n const provisioned = await provisionVariant(boundary, project, {\n suffix: options.suffix,\n displayName: options.displayName,\n });\n return {\n byTarget: Object.fromEntries(provisioned.map((p) => [p.target, p.profileName])),\n };\n}\n\nexport async function wiredInstall(\n boundary: Boundary,\n project: Project,\n options: WiredOptions,\n): Promise<void> {\n const { config } = project;\n const configuration = options.configuration ?? config.configurations.wired;\n if (!config.configurations.available.includes(configuration)) {\n fail(\n `\"${configuration}\" is not one of this project's build configurations ` +\n `(${config.configurations.available.join(', ')})`,\n );\n }\n if (options.suffix && !localCredentials(boundary, config)) {\n fail(\n 'a variant build has to register a new bundle id, which needs App Store Connect ' +\n 'credentials.\\n Drop the variant to build the plain bundle id instead.',\n );\n }\n\n await requireToolchain(boundary, project, ['xcodebuild', 'xcrun']);\n await generateProject(boundary, project);\n await runHook(boundary, project, 'preBuild');\n\n const derivedData = derivedDataPath(boundary, options.suffix);\n if (options.clean) {\n boundary.log.info('--clean: wiping DerivedData for a build from scratch');\n boundary.fs.rm(derivedData, { recursive: true });\n }\n boundary.fs.mkdirp(derivedData);\n\n const scratch = scratchPath(boundary, options.suffix);\n boundary.fs.rm(scratch, { recursive: true });\n boundary.fs.mkdirp(scratch);\n\n // Resolve devices BEFORE the slow build, so an unplugged phone fails in a\n // second instead of after a minute of compiling — and so the signing cache\n // can check that its profiles cover exactly these devices.\n const targets = resolveTargets(\n boundary,\n await pairedDevices(boundary, config, scratch),\n options.device ?? '',\n );\n const profiles = await resolveSigning(boundary, project, options, targets);\n\n // The swap is restored the moment the build returns — before the install runs\n // — so a failed or hung install can never leave the working tree dirty.\n const appPath = await withEntitlementSwap(\n boundary,\n project,\n { suffix: options.suffix, backupPath: join(scratch, 'project.pbxproj.orig') },\n async () => {\n const request = {\n configuration,\n suffix: options.suffix,\n displayName: options.displayName,\n profiles,\n derivedDataPath: derivedData,\n destination: 'generic/platform=iOS',\n buildNumber: buildNumber(boundary),\n };\n await build(boundary, project, request);\n const built = productPath(request, config, 'iphoneos');\n if (!boundary.fs.exists(built)) {\n fail(`the build reported success but produced no app at ${built}`);\n }\n return built;\n },\n );\n boundary.log.info(`built → ${appPath}`);\n\n await runHook(boundary, project, 'postBuild');\n\n const bundleId = bundleIdFor(options.suffix, config);\n const failures: string[] = [];\n for (const target of targets) {\n boundary.log.step(`installing to ${target.name} (${target.id})`);\n const result = await boundary.exec.run(\n 'xcrun',\n ['devicectl', 'device', 'install', 'app', '--device', target.id, appPath],\n { allowFail: true },\n );\n if (result.ok) {\n boundary.log.info(`installed ${bundleId} (\"${options.displayName}\") → ${target.name}`);\n } else {\n boundary.log.warn(`install failed on ${target.name} (${target.id})`);\n failures.push(target.name);\n }\n }\n if (failures.length > 0) {\n fail(`${failures.length} of ${targets.length} installs failed: ${failures.join(', ')}`);\n }\n boundary.log.info(`done — ${targets.length} device(s), ${bundleId} (\"${options.displayName}\")`);\n}\n","/**\n * Paired devices, through `xcrun devicectl`.\n *\n * Lives apart from the install flow because the wizard needs the device list\n * before it can offer a cabled install at all — and it must be the same list\n * the install later pushes to.\n */\nimport { join } from 'node:path';\nimport type { Boundary } from './boundary.js';\nimport type { Config } from './config.js';\nimport { fail } from './project.js';\n\nexport interface DevicectlDevice {\n identifier?: string;\n deviceProperties?: { name?: string };\n hardwareProperties?: {\n platform?: string;\n deviceType?: string;\n serialNumber?: string;\n /** The Apple UDID a provisioning profile lists — NOT `identifier`. */\n udid?: string;\n };\n connectionProperties?: {\n /** `wired` (cable) or `localNetwork` (Wi-Fi). Absent when unreachable. */\n transportType?: string;\n pairingState?: string;\n /** The debug tunnel, opened on demand — not an attachment signal. */\n tunnelState?: string;\n };\n}\n\ninterface DevicectlOutput {\n result?: { devices?: DevicectlDevice[] };\n}\n\nexport const idOf = (device: DevicectlDevice): string => device.identifier ?? '';\nexport const udidOf = (device: DevicectlDevice): string => device.hardwareProperties?.udid ?? '';\nexport const nameOf = (device: DevicectlDevice): string => device.deviceProperties?.name ?? '?';\nexport const transportOf = (device: DevicectlDevice): string =>\n device.connectionProperties?.transportType ?? '';\n\n/**\n * Can devicectl install to this device right now?\n *\n * Deliberately NOT `tunnelState === 'connected'`: that describes the debug\n * tunnel, which stays disconnected until something opens one, and `devicectl\n * device install` opens it on demand. Gating on it hides every device — a\n * cabled iPhone reporting `wired` + `disconnected` installs fine.\n */\nexport const isAvailable = (device: DevicectlDevice): boolean =>\n device.connectionProperties?.pairingState === 'paired' && transportOf(device) !== '';\n\n/** Attached by cable, as opposed to paired over Wi-Fi (`localNetwork`). */\nexport const isCabled = (device: DevicectlDevice): boolean => transportOf(device) === 'wired';\n\nexport const transportLabel = (device: DevicectlDevice): string => {\n if (!isAvailable(device)) return 'unavailable';\n return isCabled(device) ? 'wired' : 'Wi-Fi';\n};\n\n/** Every paired device of a type this project targets. */\nexport async function pairedDevices(\n boundary: Boundary,\n config: Config,\n scratchDir: string,\n): Promise<DevicectlDevice[]> {\n const jsonPath = join(scratchDir, 'devices.json');\n boundary.fs.mkdirp(scratchDir);\n const result = await boundary.exec.run('xcrun', [\n 'devicectl',\n 'list',\n 'devices',\n '--json-output',\n jsonPath,\n ]);\n if (!result.ok || !boundary.fs.exists(jsonPath)) {\n fail(\n '`devicectl list devices` failed — is a device paired?\\n' +\n ' Pair one in Xcode (Window › Devices and Simulators), then re-run.',\n );\n }\n let parsed: DevicectlOutput;\n try {\n parsed = JSON.parse(boundary.fs.read(jsonPath)) as DevicectlOutput;\n } catch {\n return fail('`devicectl list devices` produced output that is not JSON');\n }\n const wanted = new Set<string>(config.project.deviceTypes);\n return (parsed.result?.devices ?? []).filter((device) =>\n wanted.has(device.hardwareProperties?.deviceType ?? ''),\n );\n}\n\nexport interface InstallTarget {\n id: string;\n name: string;\n /** Checked against a cached profile's device list before signing. */\n udid: string;\n}\n\n/**\n * Which devices this install goes to: every reachable one, or the single device\n * asked for.\n *\n * Reachability is the filter, not cabling. Taking cabled devices only sounds\n * right for a mode called \"wired\", but the phone on the desk is sometimes on\n * Wi-Fi — and with a second device cabled, a cabled-only filter is satisfied,\n * so the Wi-Fi one gets dropped without a word and the \"plug something in\" hint\n * never fires. Rounds of device testing then go to a phone that never received\n * the build.\n */\nexport function resolveTargets(\n boundary: Boundary,\n devices: DevicectlDevice[],\n deviceFilter: string,\n): InstallTarget[] {\n boundary.log.info('paired devices:');\n for (const device of devices) {\n boundary.log.info(` ${idOf(device)} ${nameOf(device)} [${transportLabel(device)}]`);\n }\n\n let selected: DevicectlDevice[];\n if (deviceFilter) {\n // Match any identifier a person might reach for.\n selected = devices.filter(\n (device) =>\n idOf(device) === deviceFilter ||\n nameOf(device) === deviceFilter ||\n udidOf(device) === deviceFilter ||\n device.hardwareProperties?.serialNumber === deviceFilter,\n );\n if (selected.length === 0) {\n fail(`--device ${deviceFilter} is not a paired device (see the list above)`);\n }\n const [only] = selected;\n if (only && !isAvailable(only)) {\n fail(`${nameOf(only)} is paired but has no transport — plug it in, or join it to Wi-Fi.`);\n }\n } else {\n selected = devices.filter(isAvailable);\n if (selected.length === 0) {\n fail(\n \"no paired device is reachable — plug one in, or join it to this Mac's Wi-Fi.\\n\" +\n ' (`jetbridge ota` needs no device at all)',\n );\n }\n const overTheAir = selected.filter((device) => !isCabled(device));\n if (overTheAir.length > 0) {\n // Said out loud: a Wi-Fi install takes minutes rather than seconds, and a\n // silent one reads as a hang.\n boundary.log.info(\n `over Wi-Fi (slower): ${overTheAir.map(nameOf).join(', ')} — cable them for the fast loop`,\n );\n }\n }\n return selected.map((device) => ({\n id: idOf(device),\n name: nameOf(device),\n udid: udidOf(device),\n }));\n}\n","/**\n * The one place jetbridge talks to a person.\n *\n * `@clack/prompts` needs a terminal, so every question goes through this seam\n * instead: the wizard asks a `Prompter`, and a test hands it a script. Each\n * question carries a `name`, which is both the scripted answer's key and what\n * an unanswered prompt is reported as — a wizard that grew a question a test\n * never anticipated fails by name instead of hanging.\n */\nimport { confirm, isCancel, note, select, text } from '@clack/prompts';\nimport { isInteractive } from './boundary.js';\nimport { fail } from './project.js';\n\nexport interface Question {\n /** Stable key: the scripted answer's name, and what a missing answer reports. */\n name: string;\n message: string;\n /** Where a suggested value came from, shown next to the default. */\n hint?: string;\n}\n\nexport interface TextQuestion extends Question {\n initial?: string;\n /** Returns a message when the answer is unusable, `undefined` when it is fine. */\n validate?: (value: string) => string | undefined;\n}\n\nexport interface ConfirmQuestion extends Question {\n initial?: boolean;\n}\n\nexport interface SelectQuestion<T extends string> extends Question {\n options: Array<{ value: T; label?: string; hint?: string }>;\n initial?: T;\n}\n\nexport interface Prompter {\n text(question: TextQuestion): Promise<string>;\n confirm(question: ConfirmQuestion): Promise<boolean>;\n select<T extends string>(question: SelectQuestion<T>): Promise<T>;\n /** A block of text, not a question. */\n note(message: string, title?: string): void;\n}\n\n/** Ctrl-C is an answer too — the only correct response is to stop. */\nconst orCancel = <T>(value: T | symbol): T => {\n if (isCancel(value)) fail('cancelled — nothing was written');\n return value as T;\n};\n\nconst withHint = (question: Question): string =>\n question.hint ? `${question.message} (${question.hint})` : question.message;\n\n/**\n * The prompter for a run with nobody at the other end.\n *\n * Every question is a failure that names itself, because the alternatives are\n * both worse: prompting writes escape codes into a pipe and waits forever, and\n * silently defaulting answers a question nobody was asked on the operator's\n * behalf. A caller reaching this has a gap in its own flag handling — the\n * question's `name` is what says which one.\n *\n * `note` is not a question, so it still prints. Suppressing it would break the\n * `--yes` path, whose whole job is to show what it is about to write.\n */\nexport function nonInteractivePrompter(reason: string): Prompter {\n const refuse = (question: Question): never =>\n fail(\n `\"${question.message}\" needs an answer, and ${reason}.\\n` +\n ` Pass the flag that supplies ${question.name}, or re-run on a terminal.`,\n );\n return {\n text: async (question) => refuse(question),\n confirm: async (question) => refuse(question),\n select: async (question) => refuse(question),\n note(message, title) {\n console.error(title ? `${title}\\n${message}` : message);\n },\n };\n}\n\n/**\n * The terminal prompter — and the last line of defence for an unattended run.\n *\n * It reads the real streams rather than the boundary, because it IS the\n * terminal adapter: there is no seam left underneath it. When there is no\n * terminal it hands back the refusing prompter instead, so a code path that\n * forgets its own non-interactive check fails loudly rather than hanging. The\n * callers' checks are the contract; this is the guarantee.\n */\nexport function clackPrompter(): Prompter {\n if (!isInteractive()) {\n return nonInteractivePrompter('this run has no terminal to ask on');\n }\n return {\n async text(question) {\n const answer = orCancel(\n await text({\n message: withHint(question),\n initialValue: question.initial,\n validate: question.validate\n ? (value: string | undefined) => question.validate?.(value ?? '')\n : undefined,\n }),\n );\n return answer;\n },\n async confirm(question) {\n return orCancel(\n await confirm({ message: withHint(question), initialValue: question.initial ?? true }),\n );\n },\n async select(question) {\n // `select` is generic over a conditional option type, which does not\n // resolve for a caller's own type parameter — so it is called as the\n // string prompt it always is here, and the answer is narrowed back.\n const answer = orCancel(\n await select<string>({\n message: withHint(question),\n options: question.options.map((option) => ({\n value: option.value as string,\n label: option.label ?? option.value,\n ...(option.hint ? { hint: option.hint } : {}),\n })),\n initialValue: question.initial,\n }),\n );\n return answer as never;\n },\n note(message, title) {\n note(message, title);\n },\n };\n}\n\nexport interface ScriptedPrompter extends Prompter {\n /** Question names, in the order they were asked. */\n asked: string[];\n notes: string[];\n}\n\n/**\n * The test counterpart. An answer the script does not carry is a failure, not a\n * default: a silently defaulted question is a wizard branch nobody verified.\n */\nexport function scriptedPrompter(answers: Record<string, string | boolean>): ScriptedPrompter {\n const asked: string[] = [];\n const notes: string[] = [];\n\n const answerFor = (question: Question): string | boolean => {\n asked.push(question.name);\n if (!(question.name in answers)) {\n throw new Error(\n `the wizard asked \"${question.name}\" (${question.message}) and the script has no answer`,\n );\n }\n return answers[question.name]!;\n };\n\n return {\n asked,\n notes,\n async text(question) {\n const answer = String(answerFor(question));\n const problem = question.validate?.(answer);\n if (problem) throw new Error(`scripted answer for \"${question.name}\" is invalid: ${problem}`);\n return answer;\n },\n async confirm(question) {\n return Boolean(answerFor(question));\n },\n async select(question) {\n const answer = String(answerFor(question));\n if (!question.options.some((option) => option.value === answer)) {\n throw new Error(\n `scripted answer \"${answer}\" is not one of the options for \"${question.name}\"`,\n );\n }\n return answer as never;\n },\n note(message, title) {\n notes.push(title ? `${title}: ${message}` : message);\n },\n };\n}\n","/**\n * Simulators, through `xcrun simctl`.\n *\n * Only what delivering a build to a simulator needs: find one, boot it, install\n * the `.app`, launch it. Screenshots, permission grants and UI automation are\n * somebody else's tool.\n */\nimport type { Boundary } from './boundary.js';\nimport type { Config } from './config.js';\nimport { fail } from './project.js';\n\nexport interface Simulator {\n udid: string;\n name: string;\n /** `Booted`, `Shutdown`, `Booting`, … — whatever simctl reports. */\n state: string;\n /** False when the runtime behind it is not installed; it cannot be booted. */\n available: boolean;\n /** e.g. `com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro`. */\n deviceTypeIdentifier: string;\n /** The runtime this simulator is listed under. */\n runtime: string;\n}\n\ninterface SimctlDevice {\n udid?: string;\n name?: string;\n state?: string;\n isAvailable?: boolean;\n deviceTypeIdentifier?: string;\n}\n\ninterface SimctlList {\n /** Runtime identifier → the simulators on it. */\n devices?: Record<string, SimctlDevice[]>;\n}\n\nexport const isBooted = (simulator: Simulator): boolean => simulator.state === 'Booted';\n\nexport async function listSimulators(boundary: Boundary): Promise<Simulator[]> {\n const result = await boundary.exec.run('xcrun', ['simctl', 'list', 'devices', '-j'], {\n allowFail: true,\n });\n if (!result.ok) {\n fail(\n '`simctl list devices` failed — are the Xcode command line tools selected?\\n' +\n ' Run `sudo xcode-select -s /Applications/Xcode.app`, then re-run.',\n );\n }\n let parsed: SimctlList;\n try {\n parsed = JSON.parse(result.stdout) as SimctlList;\n } catch {\n return fail('`simctl list devices` produced output that is not JSON');\n }\n const simulators: Simulator[] = [];\n for (const [runtime, devices] of Object.entries(parsed.devices ?? {})) {\n for (const device of devices) {\n if (!device.udid) continue;\n simulators.push({\n udid: device.udid,\n name: device.name ?? '?',\n state: device.state ?? 'Unknown',\n available: device.isAvailable ?? true,\n deviceTypeIdentifier: device.deviceTypeIdentifier ?? '',\n runtime,\n });\n }\n }\n return simulators;\n}\n\n/**\n * Does this simulator model a device type the project targets? Matched against\n * the device-type identifier rather than the display name, so `iPhone 17 Pro`\n * and `iPhone Air` both answer to `iPhone` without a list of model names.\n */\nconst matchesProjectDeviceType = (simulator: Simulator, config: Config): boolean =>\n config.project.deviceTypes.some((type) =>\n simulator.deviceTypeIdentifier.includes(`SimDeviceType.${type}`),\n );\n\n/**\n * The simulator this install goes to: the one named, or a sensible default.\n *\n * A booted simulator wins the default, because it is the one already on screen\n * — installing into a second, invisible simulator looks exactly like an install\n * that silently did nothing.\n */\nexport function resolveSimulator(\n boundary: Boundary,\n simulators: Simulator[],\n config: Config,\n wanted: string,\n): Simulator {\n if (wanted) {\n const match =\n simulators.find((simulator) => simulator.udid === wanted) ??\n simulators.find((simulator) => simulator.name === wanted && simulator.available);\n if (!match) {\n const names = simulators\n .filter((simulator) => simulator.available)\n .map((simulator) => `${simulator.name} (${simulator.udid})`);\n fail(\n `--device ${wanted} is not an available simulator name or udid.\\n` +\n ` Available: ${names.join(', ') || '(none — install a runtime in Xcode › Settings › Components)'}`,\n );\n }\n if (!match.available) {\n fail(\n `simulator ${match.name} (${match.udid}) is unavailable — its runtime is not installed.\\n` +\n ' Install it in Xcode › Settings › Components, or name another simulator.',\n );\n }\n return match;\n }\n\n const candidates = simulators.filter(\n (simulator) => simulator.available && matchesProjectDeviceType(simulator, config),\n );\n const chosen = candidates.find(isBooted) ?? candidates[0];\n if (!chosen) {\n fail(\n `no available ${config.project.deviceTypes.join('/')} simulator is installed.\\n` +\n ' Add one in Xcode › Settings › Components, or name one with --device.',\n );\n }\n boundary.log.info(\n `simulator: ${chosen.name} (${chosen.udid})${isBooted(chosen) ? ' — already booted' : ''}`,\n );\n return chosen;\n}\n\n/** Booting an already-booted simulator is success, not an error. */\nexport async function bootSimulator(boundary: Boundary, simulator: Simulator): Promise<void> {\n if (isBooted(simulator)) return;\n boundary.log.step(`booting ${simulator.name}`);\n const result = await boundary.exec.run('xcrun', ['simctl', 'boot', simulator.udid], {\n allowFail: true,\n });\n // simctl races itself: something else (Xcode, a previous run) can boot the\n // device between the listing and this call, and it says so rather than\n // shrugging.\n if (!result.ok && !/current state: Booted/i.test(result.stderr || result.stdout)) {\n fail(\n `could not boot ${simulator.name} (${simulator.udid}).\\n` +\n ` Try \\`xcrun simctl shutdown ${simulator.udid}\\` and re-run.`,\n );\n }\n}\n\nexport async function installApp(\n boundary: Boundary,\n simulator: Simulator,\n appPath: string,\n): Promise<void> {\n const result = await boundary.exec.run('xcrun', ['simctl', 'install', simulator.udid, appPath], {\n allowFail: true,\n });\n if (!result.ok) {\n fail(\n `could not install ${appPath} on ${simulator.name}:\\n` +\n ` ${(result.stderr || result.stdout).trim()}`,\n );\n }\n}\n\nexport async function launchApp(\n boundary: Boundary,\n simulator: Simulator,\n bundleId: string,\n): Promise<void> {\n // A running app refuses to be launched again, and the copy on screen is the\n // one that was just replaced. Terminating first is what makes the new build\n // the one you see.\n await boundary.exec.run('xcrun', ['simctl', 'terminate', simulator.udid, bundleId], {\n allowFail: true,\n });\n const result = await boundary.exec.run('xcrun', ['simctl', 'launch', simulator.udid, bundleId], {\n allowFail: true,\n });\n if (!result.ok) {\n fail(\n `installed ${bundleId} but could not launch it on ${simulator.name}:\\n` +\n ` ${(result.stderr || result.stdout).trim()}\\n` +\n ' Open it from the simulator home screen to see why.',\n );\n }\n}\n","/**\n * The simulator install: build for `iphonesimulator`, then install and launch on\n * one simulator with `simctl`. The path with no hardware in it.\n *\n * One thing separates it from the cabled install, and it is the whole point: a\n * SIMULATOR VALIDATES NO CODE SIGNATURE. This flow therefore needs no\n * certificate, no provisioning profile, no App Store Connect key and no\n * entitlement swap — `provisionVariant` is never called from here. So a\n * `--suffix` variant runs on a simulator on a machine that has never been near\n * the developer account, where `jetbridge wired` refuses without credentials.\n */\nimport { localCredentials } from './asc.js';\nimport type { Boundary } from './boundary.js';\nimport {\n build,\n buildNumber,\n generateProject,\n productPath,\n requireToolchain,\n runHook,\n} from './build.js';\nimport { fail, type Project } from './project.js';\nimport {\n bootSimulator,\n installApp,\n launchApp,\n listSimulators,\n resolveSimulator,\n} from './simulator.js';\nimport { bundleIdFor } from './variant.js';\nimport { derivedDataPath } from './wired.js';\n\nexport interface SimOptions {\n suffix: string;\n displayName: string;\n /** A simulator name or udid. Empty picks a booted-or-available default. */\n device?: string;\n configuration?: string;\n /** Wipe the cached DerivedData first, for a genuinely corrupt build. */\n clean?: boolean;\n}\n\nexport async function simInstall(\n boundary: Boundary,\n project: Project,\n options: SimOptions,\n): Promise<void> {\n const { config } = project;\n const configuration = options.configuration ?? config.configurations.sim;\n if (!config.configurations.available.includes(configuration)) {\n fail(\n `\"${configuration}\" is not one of this project's build configurations ` +\n `(${config.configurations.available.join(', ')})`,\n );\n }\n\n await requireToolchain(boundary, project, ['xcodebuild', 'xcrun']);\n await generateProject(boundary, project);\n await runHook(boundary, project, 'preBuild');\n\n // Resolve and boot BEFORE the slow build: a simulator name nobody has fails in\n // a second instead of after a minute of compiling, and the boot finishes while\n // xcodebuild works.\n const simulator = resolveSimulator(\n boundary,\n await listSimulators(boundary),\n config,\n options.device ?? '',\n );\n await bootSimulator(boundary, simulator);\n\n const derivedData = derivedDataPath(boundary, options.suffix);\n if (options.clean) {\n boundary.log.info('--clean: wiping DerivedData for a build from scratch');\n boundary.fs.rm(derivedData, { recursive: true });\n }\n boundary.fs.mkdirp(derivedData);\n\n const request = {\n configuration,\n suffix: options.suffix,\n displayName: options.displayName,\n // Empty on purpose: nothing signs a simulator build, so there is no profile\n // to point it at and `provisionVariant` is never called from this flow.\n profiles: { byTarget: {} },\n derivedDataPath: derivedData,\n destination: `platform=iOS Simulator,id=${simulator.udid}`,\n buildNumber: buildNumber(boundary),\n };\n await build(boundary, project, request);\n\n const appPath = productPath(request, config, 'iphonesimulator');\n if (!boundary.fs.exists(appPath)) {\n fail(`the build reported success but produced no app at ${appPath}`);\n }\n boundary.log.info(`built → ${appPath}`);\n\n await runHook(boundary, project, 'postBuild');\n\n const bundleId = bundleIdFor(options.suffix, config);\n boundary.log.step(`installing ${bundleId} → ${simulator.name}`);\n await installApp(boundary, simulator, appPath);\n await launchApp(boundary, simulator, bundleId);\n\n boundary.log.info(\n `installed + launched ${bundleId} (\"${options.displayName}\") → ${simulator.name}`,\n );\n if (options.suffix && !localCredentials(boundary, config)) {\n boundary.log.info(\n 'no App Store Connect credentials here — fine for a simulator, but `jetbridge wired` needs them.',\n );\n }\n}\n","/**\n * Git, only as far as naming a variant needs it.\n *\n * Everything here degrades rather than throws: jetbridge has to work in a\n * checkout that is not a git repository at all, and in a repository whose\n * default branch is not the one this tool happens to assume.\n */\nimport type { Boundary } from './boundary.js';\nimport { fail, type Project } from './project.js';\n\nexport interface GitStamp {\n sha: string;\n shortSha: string;\n /** Tracked files are modified, so the binary would not match the stamped SHA. */\n dirty: boolean;\n}\n\n/** The current branch, or empty outside a repository or on a detached HEAD. */\nexport function currentBranch(boundary: Boundary, cwd: string): string {\n const result = boundary.exec.runSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {\n cwd,\n allowFail: true,\n });\n if (!result.ok) return '';\n const branch = result.stdout.trim();\n return branch === 'HEAD' ? '' : branch;\n}\n\nexport function onDefaultBranch(boundary: Boundary, project: Project): boolean {\n return currentBranch(boundary, project.root) === project.config.git.defaultBranch;\n}\n\n/**\n * What this checkout would build.\n *\n * Untracked files are ignored deliberately: they are not in the project file,\n * so they cannot reach the binary, and a working checkout routinely carries\n * harmless untracked files.\n */\nexport function gitStamp(boundary: Boundary, cwd: string): GitStamp | null {\n const head = boundary.exec.runSync('git', ['rev-parse', 'HEAD'], { cwd, allowFail: true });\n if (!head.ok) return null;\n const sha = head.stdout.trim();\n const status = boundary.exec.runSync('git', ['status', '--porcelain', '--untracked-files=no'], {\n cwd,\n allowFail: true,\n });\n return { sha, shortSha: sha.slice(0, 7), dirty: status.stdout.trim() !== '' };\n}\n\n/** A bare `--suffix` means \"name it after the branch I am on\". */\nexport function branchSuffix(boundary: Boundary, project: Project): string {\n const branch = currentBranch(boundary, project.root);\n if (!branch) {\n fail(\n '--suffix needs a value here: there is no current git branch to derive one from.\\n' +\n ' Pass one explicitly, e.g. --suffix wave.',\n );\n }\n return branch;\n}\n\n/**\n * The provenance gate for a plain install.\n *\n * A plain build overwrites the app every branch shares, so its vintage has to\n * be knowable on the phone. A variant is exempt — a branch build is its whole\n * point, and the branch is on the home screen.\n *\n * Off unless the project asks for it: this is a strong convention, not a\n * universal one.\n */\nexport async function requireCleanDefaultBranch(\n boundary: Boundary,\n project: Project,\n suffix: string,\n): Promise<GitStamp | null> {\n const { config } = project;\n if (suffix || !config.git.requireCleanDefaultBranch) {\n return gitStamp(boundary, project.root);\n }\n\n const stamp = gitStamp(boundary, project.root);\n if (!stamp) return null;\n\n const branch = config.git.defaultBranch;\n // Fetch first, so the comparison is against the remote's branch rather than\n // whatever a stale local ref remembers. Being offline is survivable.\n const fetched = await boundary.exec.run('git', ['fetch', 'origin', branch, '--quiet'], {\n cwd: project.root,\n allowFail: true,\n });\n if (!fetched.ok) {\n boundary.log.warn(`could not fetch origin/${branch} — comparing against the local ref`);\n }\n const remote = boundary.exec.runSync('git', ['rev-parse', `origin/${branch}`], {\n cwd: project.root,\n allowFail: true,\n });\n const remoteSha = remote.stdout.trim();\n\n if (!remote.ok || stamp.sha !== remoteSha || stamp.dirty) {\n const why = !remote.ok\n ? `origin/${branch} could not be resolved`\n : stamp.sha !== remoteSha\n ? `HEAD is ${stamp.shortSha}, origin/${branch} is ${remoteSha.slice(0, 7)}`\n : 'the working tree has uncommitted changes to tracked files';\n fail(\n `a plain install must build exactly origin/${branch} — ${why}.\\n` +\n ' The plain app is shared by every branch, so a branch or dirty build makes its\\n' +\n ` vintage unknowable on the phone. Either merge first and install from ${branch},\\n` +\n ' or install this branch beside it as its own app with --suffix.',\n );\n }\n return stamp;\n}\n\n/** The provenance stamp passed to the build, when there is one. */\nexport const stampSetting = (stamp: GitStamp | null): string | undefined =>\n stamp ? `${stamp.shortSha}${stamp.dirty ? '-dirty' : ''}` : undefined;\n"],"mappings":";;;AAOA,OAAO,WAAW;AAClB,SAAS,SAAS,4BAA4B;;;ACK9C,SAAS,OAAO,iBAAiB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;;;ACbjB,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACtB,OAAO;AAC3B;AAGO,SAAS,KAAK,SAAwB;AAC3C,QAAM,IAAI,eAAe,OAAO;AAClC;;;ADyFA,IAAM,WAAW,CAAC,OAII;AAAA,EACpB,KAAK,EAAE,YAAY,OAAO;AAAA,EAC1B,MAAM,EAAE,YAAY;AAAA,EACpB,QAAQ,OAAO,EAAE,WAAW,WAAW,EAAE,SAAS;AAAA,EAClD,QAAQ,OAAO,EAAE,WAAW,WAAW,EAAE,SAAS;AACpD;AAEO,IAAM,iBAA6B;AAAA,EACxC,QAAQ,CAAC,SAAS,WAAW,IAAI;AAAA,EACjC,MAAM,CAAC,SAAS,aAAa,MAAM,MAAM;AAAA,EACzC,WAAW,CAAC,SAAS,IAAI,WAAW,aAAa,IAAI,CAAC;AAAA,EACtD,OAAO,CAAC,MAAM,aAAa;AACzB,cAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC5C,kBAAc,MAAM,QAAQ;AAAA,EAC9B;AAAA,EACA,Q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BAAiB,gBAAgB;AACnC,YAAQ,MAAM,MAAM,IAAI,UAAK,MAAM,OAAO,EAAE,CAAC;AAAA,EAC/C,OAAO;AACL,YAAQ,MAAM,MAAM,IAAI,UAAM,OAAiB,SAAS,OAAO,KAAK,CAAC,EAAE,CAAC;AAAA,EAC1E;AACA,UAAQ,KAAK,CAAC;AAChB;","names":["join","dirname","dirname","join","credentials","text","join","join","identifier","row","text","identifier","result","join","resolve","isAbsolute","join","resolve","text","pbxprojPath","note","resolve","join","join","existsSync","readFileSync","dirname","join","join","join","join","credentials","join","join","join","join","join","join","join","text","parsePlist","join","build"]}
|