@hot-updater/apple-helper 1.2.0-rc.2 → 1.2.0-rc.21

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/dist/index.mjs CHANGED
@@ -1,199 +1,567 @@
1
1
  import crypto from "node:crypto";
2
- import { createReadStream, rmSync } from "node:fs";
3
- import fs, { mkdtemp, rm } from "node:fs/promises";
4
- import net from "node:net";
5
- import os, { tmpdir } from "node:os";
6
- import path, { join } from "node:path";
2
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
7
3
  import { BuildFailedError, BuildLogger, colors, createCredentialResolver, createMinBundleId, getCwd, getReactNativeMetadatas, isCI, p, parseSecretReference, registerSecretValue } from "@hot-updater/cli-tools";
4
+ import { SANDBOX_INFO_PLIST_KEY, normalizeIosUdid, sandboxChannelOf, sandboxUrlSchemeOf } from "@hot-updater/protocol/native-artifact";
5
+ import crypto$1 from "crypto";
6
+ import fs from "fs";
7
+ import path from "path";
8
8
  import { ExecaError, execa } from "execa";
9
- import fs$1 from "fs";
10
- import path$1 from "path";
9
+ import { rmSync } from "node:fs";
10
+ import { mkdtemp, rm } from "node:fs/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
11
13
  import { spawn, spawnSync } from "child_process";
12
- import crypto$1 from "crypto";
13
- import os$1 from "os";
14
- //#region src/asc/ascCli.ts
14
+ import os from "os";
15
+ //#region src/asc/appleSrp.ts
15
16
  /**
16
- * The release of asc, the open-source App Store Connect CLI
17
- * (https://github.com/rorkai/App-Store-Connect-CLI, MIT), that signs in with
18
- * an Apple Account and issues App Store Connect API keys for Hot Updater. An
19
- * `asc` on PATH is used when it is at least this version.
17
+ * Apple's sign-in proof: SRP-6a over the RFC 5054 2048-bit group with
18
+ * SHA-256, the password stretched with PBKDF2, as Apple's sign-in page and
19
+ * asc, the open-source App Store Connect CLI
20
+ * (https://github.com/rorkai/App-Store-Connect-CLI, MIT), compute it.
20
21
  */
21
- const ASC_CLI_VERSION = "5.16.1";
22
+ /** RFC 5054, Appendix A, the 2048-bit group. */
23
+ const N = BigInt("0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73");
24
+ const G = 2n;
25
+ /** The hex length every padded value has: N's byte length, twice. */
26
+ const PADDED_HEX_LENGTH = 512;
27
+ const modPow = (base, exponent, modulus) => {
28
+ let result = 1n;
29
+ let b = (base % modulus + modulus) % modulus;
30
+ let e = exponent;
31
+ while (e > 0n) {
32
+ if (e & 1n) result = result * b % modulus;
33
+ b = b * b % modulus;
34
+ e >>= 1n;
35
+ }
36
+ return result;
37
+ };
38
+ /** An even-length lowercase hex of `value`, as the proof hashes it. */
39
+ const toHex = (value) => {
40
+ const hex = value.toString(16);
41
+ return hex.length % 2 === 1 ? `0${hex}` : hex;
42
+ };
43
+ const fromBytes = (bytes) => bytes.length === 0 ? 0n : BigInt(`0x${Buffer.from(bytes).toString("hex")}`);
44
+ const sha256Hex = (hex) => crypto.createHash("sha256").update(Buffer.from(hex, "hex")).digest("hex");
45
+ /** SHA-256 of each value left-padded to N's length, as a number mod N. */
46
+ const paddedHash = (...values) => BigInt(`0x${sha256Hex(values.map((value) => value.padStart(PADDED_HEX_LENGTH, "0")).join(""))}`) % N;
47
+ /** The password as the protocol Apple named feeds it to PBKDF2. */
48
+ const preparePassword = (password, protocol) => {
49
+ const digest = crypto.createHash("sha256").update(password).digest();
50
+ if (protocol === "s2k") return digest;
51
+ if (protocol === "s2k_fo") return Buffer.from(digest.toString("hex"));
52
+ throw new Error(`Apple asked for the sign-in protocol ${protocol}.`);
53
+ };
54
+ /** A new SRP client; `secret` is the private value a, random unless set. */
55
+ const createSrpClient = (secret = fromBytes(crypto.randomBytes(256))) => {
56
+ const A = modPow(G, secret, N);
57
+ const aHex = toHex(A);
58
+ return {
59
+ a: Buffer.from(aHex, "hex").toString("base64"),
60
+ proof: ({ accountName, password, protocol, iterations, salt, b }) => {
61
+ const saltBytes = Buffer.from(salt, "base64");
62
+ const saltHex = saltBytes.toString("hex");
63
+ const bHex = Buffer.from(b, "base64").toString("hex");
64
+ const B = BigInt(`0x${bHex || "0"}`);
65
+ if (B % N === 0n) throw new Error("Apple answered an invalid SRP value.");
66
+ const derived = crypto.pbkdf2Sync(preparePassword(password, protocol), saltBytes, iterations, 32, "sha256");
67
+ const x = BigInt(`0x${sha256Hex(saltHex + sha256Hex(`3a${derived.toString("hex")}`))}`);
68
+ const k = paddedHash(toHex(N), toHex(G));
69
+ const u = paddedHash(aHex, bHex);
70
+ if (u === 0n) throw new Error("Apple answered an invalid SRP value.");
71
+ const S = modPow(B - k * modPow(G, x, N) % N, secret + u * x, N);
72
+ const K = sha256Hex(toHex(S));
73
+ const m1 = sha256Hex(toHex(paddedHash(toHex(N)) ^ paddedHash(toHex(G))) + crypto.createHash("sha256").update(accountName).digest("hex") + saltHex + aHex + bHex + K);
74
+ const m2 = toHex(BigInt(`0x${sha256Hex(aHex + m1 + K)}`));
75
+ return {
76
+ m1: Buffer.from(m1, "hex").toString("base64"),
77
+ m2: Buffer.from(m2, "hex").toString("base64")
78
+ };
79
+ }
80
+ };
81
+ };
82
+ const hasLeadingZeroBits = (digest, bits) => {
83
+ const full = Math.floor(bits / 8);
84
+ for (let index = 0; index < full; index++) if (digest[index] !== 0) return false;
85
+ const rest = bits % 8;
86
+ return rest === 0 || (digest[full] & 255 << 8 - rest & 255) === 0;
87
+ };
22
88
  /**
23
- * The SHA-256 of each macOS binary of the release, from its
24
- * asc_5.16.1_checksums.txt. Pinned here, so a download is trusted only when
25
- * it is the exact binary this version of Hot Updater was written against.
89
+ * The hashcash stamp Apple's sign-in asks for in `X-Apple-HC`: the first
90
+ * `1:<bits>:<date>:<challenge>::<counter>` whose SHA-1 starts with `bits`
91
+ * zero bits.
26
92
  */
27
- const ASC_CLI_SHA256 = {
28
- arm64: "85a848ef33fe3490adc4f0348af30b7bbf95209a258dac06c735318f62495707",
29
- x64: "5a978732e0c2f2b673da601568c489dfaa232ae32c93dcfa63b95f0b892a2580"
30
- };
31
- const ASC_RELEASE_ASSET = {
32
- arm64: `asc_${ASC_CLI_VERSION}_macOS_arm64`,
33
- x64: `asc_${ASC_CLI_VERSION}_macOS_amd64`
93
+ const makeHashcash = (bits, challenge, now = /* @__PURE__ */ new Date()) => {
94
+ const date = now.toISOString().replace(/\.\d+Z$/u, "").replaceAll(/[-:T]/gu, "");
95
+ for (let counter = 0;; counter++) {
96
+ const stamp = `1:${bits}:${date}:${challenge}::${counter}`;
97
+ const digest = crypto.createHash("sha1").update(stamp).digest();
98
+ if (hasLeadingZeroBits(digest, bits)) return stamp;
99
+ }
34
100
  };
35
- const ASC_RELEASE_URL = `https://github.com/rorkai/App-Store-Connect-CLI/releases/download/${ASC_CLI_VERSION}`;
36
- const INSTALL_HINT = `Install asc ${ASC_CLI_VERSION} or later with \`brew install asc\` (https://github.com/rorkai/App-Store-Connect-CLI), then run the command again.`;
37
- /** asc could not be found, downloaded, or verified. */
38
- var AscCliUnavailableError = class extends Error {
101
+ //#endregion
102
+ //#region src/asc/appleSignIn.ts
103
+ /**
104
+ * Signing in to App Store Connect with an Apple Account, as its web page
105
+ * does: Apple's SRP sign-in at idmsa.apple.com, its two-factor check, then
106
+ * App Store Connect's session. The endpoints and their headers follow asc,
107
+ * the open-source App Store Connect CLI
108
+ * (https://github.com/rorkai/App-Store-Connect-CLI, MIT), 5.16.1, whose
109
+ * internal/web/auth.go has signed in this way against Apple.
110
+ */
111
+ const AUTH_URL = "https://idmsa.apple.com/appleauth/auth";
112
+ const ASC_URL = "https://appstoreconnect.apple.com";
113
+ const SESSION_URL = `${ASC_URL}/olympus/v1/session`;
114
+ /**
115
+ * The public widget key App Store Connect's sign-in page ships, used when
116
+ * neither place Apple publishes the current one answers. Not a credential.
117
+ */
118
+ const ASC_WIDGET_KEY = "e0b80c3bf78523bfe80974d320935bfa30add02e1bff88ec2166c6bd5a706c42";
119
+ /** Signing in, or a request in the signed-in session, failed. */
120
+ var AppleSignInError = class extends Error {
121
+ status;
122
+ /** The response body, for messages that depend on what Apple said. */
123
+ body;
39
124
  constructor(message, options) {
40
- super(message, options);
41
- this.name = "AscCliUnavailableError";
125
+ super(message, options?.cause ? { cause: options.cause } : void 0);
126
+ this.name = "AppleSignInError";
127
+ this.status = options?.status;
128
+ this.body = options?.body;
42
129
  }
43
130
  };
44
- const parseVersion = (output) => {
45
- const match = /(\d+)\.(\d+)\.(\d+)/u.exec(output);
46
- return match ? match.slice(1, 4).map(Number) : void 0;
131
+ /**
132
+ * A cookie jar for the sign-in's requests, as a browser keeps one: `fetch`
133
+ * keeps none, and Apple's session is its cookies.
134
+ */
135
+ const createCookieJar = () => {
136
+ let cookies = [];
137
+ const live = () => {
138
+ const now = Date.now();
139
+ cookies = cookies.filter((cookie) => cookie.expires === void 0 || cookie.expires > now);
140
+ return cookies;
141
+ };
142
+ return {
143
+ store(url, response) {
144
+ for (const header of response.headers.getSetCookie()) {
145
+ const [pair = "", ...attributes] = header.split(";");
146
+ const separator = pair.indexOf("=");
147
+ if (separator <= 0) continue;
148
+ const name = pair.slice(0, separator).trim();
149
+ const value = pair.slice(separator + 1).trim();
150
+ let domain = url.hostname;
151
+ let hostOnly = true;
152
+ let path = "/";
153
+ let expires;
154
+ let maxAge;
155
+ for (const attribute of attributes) {
156
+ const index = attribute.indexOf("=");
157
+ const key = (index === -1 ? attribute : attribute.slice(0, index)).trim().toLowerCase();
158
+ const raw = index === -1 ? "" : attribute.slice(index + 1).trim();
159
+ if (key === "domain" && raw) {
160
+ const candidate = raw.replace(/^\./u, "").toLowerCase();
161
+ if (url.hostname !== candidate && !url.hostname.endsWith(`.${candidate}`)) {
162
+ domain = "";
163
+ break;
164
+ }
165
+ domain = candidate;
166
+ hostOnly = false;
167
+ } else if (key === "path" && raw.startsWith("/")) path = raw;
168
+ else if (key === "expires") {
169
+ const time = Date.parse(raw);
170
+ if (!Number.isNaN(time)) expires = time;
171
+ } else if (key === "max-age" && /^-?\d+$/u.test(raw)) maxAge = Number(raw);
172
+ }
173
+ if (!domain) continue;
174
+ if (maxAge !== void 0) expires = Date.now() + maxAge * 1e3;
175
+ cookies = cookies.filter((cookie) => !(cookie.name === name && cookie.domain === domain && cookie.path === path));
176
+ if (expires === void 0 || expires > Date.now()) cookies.push({
177
+ name,
178
+ value,
179
+ domain,
180
+ hostOnly,
181
+ path,
182
+ expires
183
+ });
184
+ }
185
+ },
186
+ header(url) {
187
+ const matching = live().filter((cookie) => (cookie.hostOnly ? url.hostname === cookie.domain : url.hostname === cookie.domain || url.hostname.endsWith(`.${cookie.domain}`)) && (url.pathname === cookie.path || url.pathname.startsWith(cookie.path.endsWith("/") ? cookie.path : `${cookie.path}/`)));
188
+ return matching.length === 0 ? void 0 : matching.map((cookie) => `${cookie.name}=${cookie.value}`).join("; ");
189
+ },
190
+ clear() {
191
+ cookies = [];
192
+ }
193
+ };
194
+ };
195
+ const REDIRECTS = /* @__PURE__ */ new Set([
196
+ 301,
197
+ 302,
198
+ 303,
199
+ 307,
200
+ 308
201
+ ]);
202
+ /** `fetch` with the jar's cookies, following redirects itself to keep them. */
203
+ const createClient = (fetch) => {
204
+ const jar = createCookieJar();
205
+ const request = async (url, init = {}) => {
206
+ let current = new URL(url);
207
+ let method = init.method ?? "GET";
208
+ let body = init.body;
209
+ for (let hop = 0; hop < 10; hop++) {
210
+ const headers = new Headers(init.headers);
211
+ const cookie = jar.header(current);
212
+ if (cookie) headers.set("Cookie", cookie);
213
+ const response = await fetch(current, {
214
+ method,
215
+ headers,
216
+ ...body === void 0 ? {} : { body },
217
+ redirect: "manual"
218
+ });
219
+ jar.store(current, response);
220
+ const location = response.headers.get("location");
221
+ if (!REDIRECTS.has(response.status) || !location) return response;
222
+ await response.text();
223
+ current = new URL(location, current);
224
+ if (response.status === 303 || response.status !== 307 && response.status !== 308 && method === "POST") {
225
+ method = "GET";
226
+ body = void 0;
227
+ }
228
+ }
229
+ throw new AppleSignInError(`${url} redirected too many times.`);
230
+ };
231
+ return {
232
+ request,
233
+ clear: jar.clear
234
+ };
47
235
  };
48
- const isAtLeast = (version, minimum) => {
49
- for (let index = 0; index < minimum.length; index++) {
50
- const part = version[index] ?? 0;
51
- if (part !== minimum[index]) return part > minimum[index];
236
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
237
+ const text$1 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
238
+ const parseJson = (body) => {
239
+ try {
240
+ return JSON.parse(body);
241
+ } catch {
242
+ return;
52
243
  }
53
- return true;
54
244
  };
55
- const sha256Of = (file) => new Promise((resolve, reject) => {
56
- const hash = crypto.createHash("sha256");
57
- createReadStream(file).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve(hash.digest("hex")));
245
+ /** What Apple's sign-in said went wrong, from its `serviceErrors`. */
246
+ const serviceErrors = (body) => {
247
+ const parsed = parseJson(body);
248
+ const errors = isRecord$1(parsed) && Array.isArray(parsed.serviceErrors) ? parsed.serviceErrors.filter(isRecord$1) : [];
249
+ return {
250
+ codes: errors.map((error) => text$1(error.code)).filter(Boolean),
251
+ message: errors.map((error) => text$1(error.message)).find(Boolean)
252
+ };
253
+ };
254
+ const failure = (step, response, body) => new AppleSignInError(`${step} failed (HTTP ${response.status}).${serviceErrors(body).message ? `\n${serviceErrors(body).message}` : ""}`, {
255
+ status: response.status,
256
+ body
58
257
  });
59
- /** Where a downloaded asc is kept, per user, so every project shares it. */
60
- const defaultAscCacheDir = () => path.join(os.homedir(), "Library", "Caches", "hot-updater");
61
- /**
62
- * Finds asc: the `asc` on PATH when it is at least `ASC_CLI_VERSION`, else
63
- * the pinned release in `cacheDir`, downloaded from GitHub on first use and
64
- * verified against its pinned SHA-256 each time it is used. Only macOS has
65
- * one: TestFlight builds need Xcode.
66
- */
67
- const findAscCli = async ({ cacheDir = defaultAscCacheDir(), fetch = globalThis.fetch, platform = process.platform, arch = process.arch, pathCommand = "asc" } = {}) => {
68
- if (platform !== "darwin") throw new AscCliUnavailableError("Signing in with an Apple Account to issue an App Store Connect API key runs on macOS, where iOS builds run.");
69
- const minimum = parseVersion(ASC_CLI_VERSION);
70
- const onPath = await execa(pathCommand, ["--version"], {
71
- reject: false,
72
- env: { ASC_TELEMETRY_DISABLED: "1" },
73
- timeout: 15e3
258
+ /**
259
+ * The widget key Apple's sign-in wants: from the sign-out redirect App Store
260
+ * Connect answers without cookies, else its config, else the one its page
261
+ * ships.
262
+ */
263
+ const findWidgetKey = async (fetch, client) => {
264
+ const signOut = await fetch(`${ASC_URL}/logout`, {
265
+ method: "HEAD",
266
+ redirect: "manual"
74
267
  }).catch(() => void 0);
75
- const pathVersion = onPath?.exitCode === 0 ? parseVersion(onPath.stdout) : void 0;
76
- if (pathVersion && isAtLeast(pathVersion, minimum)) return {
77
- path: pathCommand,
78
- version: pathVersion.join("."),
79
- source: "path"
268
+ const location = signOut?.headers.get("location");
269
+ if (signOut && REDIRECTS.has(signOut.status) && location) {
270
+ const url = (() => {
271
+ try {
272
+ return new URL(location);
273
+ } catch {
274
+ return;
275
+ }
276
+ })();
277
+ const keys = url?.searchParams.getAll("widgetKey") ?? [];
278
+ if (url?.protocol === "https:" && url.hostname === "idmsa.apple.com" && url.pathname === "/appleauth/signout" && keys.length === 1 && keys[0].trim()) return keys[0].trim();
279
+ }
280
+ const config = await client.request(`${ASC_URL}/olympus/v1/app/config?hostname=itunesconnect.apple.com`);
281
+ const body = await config.text();
282
+ if (config.status === 404) return ASC_WIDGET_KEY;
283
+ const parsed = parseJson(body);
284
+ const key = isRecord$1(parsed) ? text$1(parsed.authServiceKey) ?? text$1(parsed.serviceKey) : void 0;
285
+ if (!config.ok || !key) throw new AppleSignInError(`Couldn't load Apple's sign-in configuration (HTTP ${config.status}).`, { status: config.status });
286
+ return key;
287
+ };
288
+ const hashcash = async (client, widgetKey) => {
289
+ const response = await client.request(`${AUTH_URL}/signin?widgetKey=${encodeURIComponent(widgetKey)}`, { headers: { Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } });
290
+ await response.text();
291
+ if (!response.ok) throw new AppleSignInError(`Loading Apple's sign-in page failed (HTTP ${response.status}).`, { status: response.status });
292
+ const bits = response.headers.get("x-apple-hc-bits")?.trim();
293
+ const challenge = response.headers.get("x-apple-hc-challenge")?.trim();
294
+ if (!bits || !challenge) return void 0;
295
+ if (!/^\d+$/u.test(bits) || Number(bits) > 32) throw new AppleSignInError(`Apple asked for a hashcash of ${bits} bits.`);
296
+ return makeHashcash(Number(bits), challenge);
297
+ };
298
+ const pendingHeaders = (pending) => ({
299
+ "X-Apple-ID-Session-Id": pending.sessionId,
300
+ "X-Apple-Widget-Key": pending.widgetKey,
301
+ scnt: pending.scnt,
302
+ Accept: "application/json"
303
+ });
304
+ /** Apple rotates `scnt` and the session ID; each request sends the latest. */
305
+ const track = (pending, response) => {
306
+ const scnt = response.headers.get("scnt")?.trim();
307
+ const sessionId = response.headers.get("x-apple-id-session-id")?.trim();
308
+ if (scnt) pending.scnt = scnt;
309
+ if (sessionId) pending.sessionId = sessionId;
310
+ };
311
+ const CANCELLED = "Signing in was cancelled.";
312
+ const twoFactor = async (client, pending, prompts) => {
313
+ const send = async (url, method, payload) => {
314
+ const response = await client.request(url, {
315
+ method,
316
+ headers: {
317
+ ...pendingHeaders(pending),
318
+ ...payload === void 0 ? {} : { "Content-Type": "application/json" }
319
+ },
320
+ ...payload === void 0 ? {} : { body: JSON.stringify(payload) }
321
+ });
322
+ track(pending, response);
323
+ return {
324
+ response,
325
+ body: await response.text()
326
+ };
80
327
  };
81
- const asset = ASC_RELEASE_ASSET[arch];
82
- const expected = ASC_CLI_SHA256[arch];
83
- if (!asset || !expected) throw new AscCliUnavailableError(`asc publishes no macOS binary for ${arch}. ${INSTALL_HINT}`);
84
- const binary = path.join(cacheDir, "asc", ASC_CLI_VERSION, asset);
85
- if (await sha256Of(binary).catch(() => void 0) === expected) return {
86
- path: binary,
87
- version: ASC_CLI_VERSION,
88
- source: "cache"
328
+ const options = await send(AUTH_URL, "GET");
329
+ if (!options.response.ok) throw failure("Loading the two-factor options", options.response, options.body);
330
+ const parsed = parseJson(options.body);
331
+ const phone = (isRecord$1(parsed) && Array.isArray(parsed.trustedPhoneNumbers) ? parsed.trustedPhoneNumbers.filter(isRecord$1) : []).filter((phone) => typeof phone.id === "number")[0];
332
+ const noDevices = isRecord$1(parsed) && parsed.noTrustedDevices === true;
333
+ if (noDevices && !phone) throw new AppleSignInError("The Apple Account has no trusted device or phone number for two-factor codes.");
334
+ const phoneMode = text$1(phone?.pushMode) ?? "sms";
335
+ const destination = text$1(phone?.numberWithDialCode);
336
+ const securityCode = isRecord$1(parsed) && isRecord$1(parsed.securityCode) ? parsed.securityCode.length : void 0;
337
+ const length = typeof securityCode === "number" && securityCode > 0 ? securityCode : 6;
338
+ const textCode = async () => {
339
+ const requested = await send(`${AUTH_URL}/verify/phone`, "PUT", {
340
+ phoneNumber: { id: phone.id },
341
+ mode: phoneMode
342
+ });
343
+ if (!requested.response.ok) throw failure("Texting a two-factor code", requested.response, requested.body);
89
344
  };
90
- await fs.mkdir(path.dirname(binary), { recursive: true });
91
- const partial = `${binary}.${process.pid}.download`;
92
- try {
93
- let response;
94
- try {
95
- response = await fetch(`${ASC_RELEASE_URL}/${asset}`, { redirect: "follow" });
96
- } catch (error) {
97
- throw new AscCliUnavailableError(`Could not download asc ${ASC_CLI_VERSION} from GitHub (${error instanceof Error ? error.message : String(error)}). ${INSTALL_HINT}`, { cause: error });
345
+ const verify = async (via, code) => {
346
+ const verified = via === "device" ? await send(`${AUTH_URL}/verify/trusteddevice/securitycode`, "POST", { securityCode: { code } }) : await send(`${AUTH_URL}/verify/phone/securitycode`, "POST", {
347
+ securityCode: { code },
348
+ phoneNumber: { id: phone.id },
349
+ mode: phoneMode
350
+ });
351
+ if (verified.response.ok) return true;
352
+ if ([
353
+ 400,
354
+ 401,
355
+ 403
356
+ ].includes(verified.response.status)) return false;
357
+ throw failure("Checking the two-factor code", verified.response, verified.body);
358
+ };
359
+ const ask = async (via, afterWrongCode) => {
360
+ const code = await prompts.twoFactorCode({
361
+ via,
362
+ destination,
363
+ textsOnWrongCode: via === "device" && phone !== void 0,
364
+ afterWrongCode,
365
+ length
366
+ });
367
+ if (code === void 0) throw new AppleSignInError(CANCELLED);
368
+ return code;
369
+ };
370
+ let accepted;
371
+ if (noDevices) {
372
+ await textCode();
373
+ accepted = await verify("sms", await ask("sms", false));
374
+ } else {
375
+ accepted = await verify("device", await ask("device", false));
376
+ if (!accepted && phone) {
377
+ await textCode();
378
+ accepted = await verify("sms", await ask("sms", true));
98
379
  }
99
- if (!response.ok || !response.body) throw new AscCliUnavailableError(`Could not download asc ${ASC_CLI_VERSION} from GitHub (HTTP ${response.status}). ${INSTALL_HINT}`);
100
- await fs.writeFile(partial, Buffer.from(await response.arrayBuffer()), { mode: 448 });
101
- const actual = await sha256Of(partial);
102
- if (actual !== expected) throw new AscCliUnavailableError(`The downloaded asc ${ASC_CLI_VERSION} does not match its published SHA-256 (expected ${expected}, got ${actual}), so it was deleted and not run. ${INSTALL_HINT}`);
103
- await fs.chmod(partial, 493);
104
- await fs.rename(partial, binary);
105
- } finally {
106
- await fs.rm(partial, { force: true });
107
380
  }
381
+ if (!accepted) throw new AppleSignInError("Apple rejected the verification code.");
382
+ const trust = await send(`${AUTH_URL}/2sv/trust`, "GET");
383
+ if (!trust.response.ok) throw failure("Finishing the two-factor check", trust.response, trust.body);
384
+ };
385
+ const parseProvider = (value) => {
386
+ if (!isRecord$1(value) || typeof value.providerId !== "number") return void 0;
387
+ const publicProviderId = text$1(value.publicProviderId);
388
+ if (!publicProviderId) return void 0;
108
389
  return {
109
- path: binary,
110
- version: ASC_CLI_VERSION,
111
- source: "download"
390
+ providerId: value.providerId,
391
+ publicProviderId,
392
+ name: text$1(value.name)
112
393
  };
113
394
  };
114
- //#endregion
115
- //#region src/asc/ascCliKeyIssuer.ts
116
- /** An asc command failed; its message is asc's own, which it printed too. */
117
- var AscCommandError = class extends Error {
118
- exitCode;
119
- constructor(message, exitCode, options) {
120
- super(message, options);
121
- this.name = "AscCommandError";
122
- this.exitCode = exitCode;
123
- }
395
+ const readSession = async (client) => {
396
+ const response = await client.request(SESSION_URL, { headers: { Accept: "application/json" } });
397
+ const body = await response.text();
398
+ if (!response.ok) throw new AppleSignInError(response.status === 401 || response.status === 403 ? "App Store Connect didn't accept the sign-in. Check that the Apple Account is in an Apple Developer team." : `Loading the App Store Connect session failed (HTTP ${response.status}).`, {
399
+ status: response.status,
400
+ body
401
+ });
402
+ const parsed = parseJson(body);
403
+ const provider = isRecord$1(parsed) ? parseProvider(parsed.provider) : void 0;
404
+ if (!isRecord$1(parsed) || !provider) throw new AppleSignInError("App Store Connect's session names no team for the Apple Account.");
405
+ const providers = (Array.isArray(parsed.availableProviders) ? parsed.availableProviders : []).map(parseProvider).filter((value) => value !== void 0);
406
+ return {
407
+ provider,
408
+ providers: providers.some((value) => value.providerId === provider.providerId) ? providers : [provider, ...providers]
409
+ };
124
410
  };
125
- const TERMINATION_SIGNALS$3 = [
126
- "SIGHUP",
127
- "SIGINT",
128
- "SIGTERM"
129
- ];
130
411
  /**
131
- * A 0700 directory holding asc's whole state for one sign-in (its web
132
- * session, config, and the downloaded `.p8`), removed by `dispose`, on
133
- * `exit`, or on a termination signal, so nothing outlives the sign-in.
412
+ * Signs in to App Store Connect with `appleId` and `password`, asking
413
+ * `prompts` for the two-factor code. The session lives only in the returned
414
+ * object's memory.
134
415
  */
135
- const createWorkDirectory = async () => {
136
- const root = await fs.mkdtemp(path.join(os.tmpdir(), "hot-updater-asc-"));
137
- await fs.chmod(root, 448);
138
- const remove = () => rmSync(root, {
139
- force: true,
140
- recursive: true
141
- });
142
- const onSignal = (signal) => {
143
- stop();
144
- remove();
145
- if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
146
- };
147
- const stop = () => {
148
- process.off("exit", remove);
149
- for (const signal of TERMINATION_SIGNALS$3) process.off(signal, onSignal);
150
- };
151
- process.on("exit", remove);
152
- for (const signal of TERMINATION_SIGNALS$3) process.on(signal, onSignal);
153
- for (const directory of [
154
- "home",
155
- "session",
156
- "keys"
157
- ]) await fs.mkdir(path.join(root, directory), { mode: 448 });
158
- let disposal;
159
- return {
160
- root,
161
- dispose: () => {
162
- disposal ??= (async () => {
163
- stop();
164
- await fs.rm(root, {
165
- force: true,
166
- recursive: true
167
- });
416
+ const signInToAppStoreConnect = async ({ appleId, password, prompts, fetch = globalThis.fetch }) => {
417
+ const client = createClient(fetch);
418
+ try {
419
+ const widgetKey = await findWidgetKey(fetch, client);
420
+ const json = {
421
+ "Content-Type": "application/json",
422
+ "X-Apple-Widget-Key": widgetKey,
423
+ "X-Requested-With": "XMLHttpRequest",
424
+ Accept: "application/json, text/javascript"
425
+ };
426
+ const srp = createSrpClient();
427
+ const init = await client.request(`${AUTH_URL}/signin/init`, {
428
+ method: "POST",
429
+ headers: json,
430
+ body: JSON.stringify({
431
+ accountName: appleId,
432
+ protocols: ["s2k", "s2k_fo"],
433
+ a: srp.a
434
+ })
435
+ });
436
+ const initBody = await init.text();
437
+ if (!init.ok) throw failure("Starting the sign-in", init, initBody);
438
+ const started = parseJson(initBody);
439
+ if (!isRecord$1(started) || typeof started.iteration !== "number" || !text$1(started.salt) || !text$1(started.b) || !text$1(started.protocol)) throw new AppleSignInError("Apple's sign-in answered no SRP challenge.");
440
+ const { m1, m2 } = srp.proof({
441
+ accountName: appleId,
442
+ password,
443
+ protocol: text$1(started.protocol),
444
+ iterations: started.iteration,
445
+ salt: text$1(started.salt),
446
+ b: text$1(started.b)
447
+ });
448
+ const stamp = await hashcash(client, widgetKey);
449
+ const complete = await client.request(`${AUTH_URL}/signin/complete?isRememberMeEnabled=false`, {
450
+ method: "POST",
451
+ headers: {
452
+ ...json,
453
+ ...stamp ? { "X-Apple-HC": stamp } : {}
454
+ },
455
+ body: JSON.stringify({
456
+ accountName: appleId,
457
+ rememberMe: false,
458
+ m1,
459
+ m2,
460
+ c: started.c
461
+ })
462
+ });
463
+ const completeBody = await complete.text();
464
+ if (complete.status === 409) {
465
+ const sessionId = complete.headers.get("x-apple-id-session-id")?.trim();
466
+ const scnt = complete.headers.get("scnt")?.trim();
467
+ if (!sessionId || !scnt) throw new AppleSignInError("Apple asked for a two-factor code without a sign-in session.");
468
+ await twoFactor(client, {
469
+ widgetKey,
470
+ sessionId,
471
+ scnt
472
+ }, prompts);
473
+ } else if (!complete.ok) {
474
+ const { codes } = serviceErrors(completeBody);
475
+ const authType = (() => {
476
+ const parsed = parseJson(completeBody);
477
+ return isRecord$1(parsed) ? text$1(parsed.authType) : void 0;
168
478
  })();
169
- return disposal;
479
+ if (complete.status === 401 && codes.includes("-20101")) throw new AppleSignInError("Apple rejected the email or password.", { status: 401 });
480
+ if (complete.status === 412 && authType && [
481
+ "sa",
482
+ "hsa",
483
+ "non-sa",
484
+ "hsa2"
485
+ ].includes(authType)) throw new AppleSignInError("The Apple Account has a pending prompt. Sign in at https://appstoreconnect.apple.com once, then run this again.", { status: 412 });
486
+ throw failure("Signing in", complete, completeBody);
170
487
  }
171
- };
488
+ let { provider, providers } = await readSession(client);
489
+ return {
490
+ appleId,
491
+ get provider() {
492
+ return provider;
493
+ },
494
+ get providers() {
495
+ return providers;
496
+ },
497
+ selectProvider: async (publicProviderId) => {
498
+ if (provider.publicProviderId === publicProviderId) return provider;
499
+ const selected = providers.find((value) => value.publicProviderId === publicProviderId);
500
+ if (!selected) throw new AppleSignInError(`The Apple Account is in no team ${publicProviderId}.`);
501
+ const response = await client.request(SESSION_URL, {
502
+ method: "POST",
503
+ headers: {
504
+ "Content-Type": "application/json",
505
+ "X-Requested-With": "olympus-ui"
506
+ },
507
+ body: JSON.stringify({ provider: { providerId: selected.providerId } })
508
+ });
509
+ const body = await response.text();
510
+ if (!response.ok) throw new AppleSignInError(`Switching to the team ${selected.name ?? publicProviderId} failed (HTTP ${response.status}).`, {
511
+ status: response.status,
512
+ body
513
+ });
514
+ ({provider, providers} = await readSession(client));
515
+ if (provider.providerId !== selected.providerId) throw new AppleSignInError(`App Store Connect stayed in the team ${provider.name ?? provider.publicProviderId}.`);
516
+ return provider;
517
+ },
518
+ request: client.request,
519
+ clear: client.clear
520
+ };
521
+ } catch (error) {
522
+ client.clear();
523
+ throw error;
524
+ }
172
525
  };
526
+ //#endregion
527
+ //#region src/asc/programLicenseAgreement.ts
173
528
  /**
174
- * asc's environment: the caller's, without any `ASC_*` variable (such as a
175
- * saved password, a 2FA code command, or another API key), and with every
176
- * file asc keeps (home, config, web session) in `root`. Passwords are never
177
- * stored, the keychain is bypassed, and telemetry is off.
529
+ * What to do when Apple holds a team's requests until the Account Holder
530
+ * accepts the latest Apple Developer Program License Agreement: App Store
531
+ * Connect answers 403, and xcodebuild prints "PLA Update available".
178
532
  */
179
- const ascEnvironment = (root, base = process.env) => {
180
- const env = {};
181
- for (const [name, value] of Object.entries(base)) if (!name.startsWith("ASC_") && name !== "DO_NOT_TRACK") env[name] = value;
182
- return {
183
- ...env,
184
- HOME: path.join(root, "home"),
185
- XDG_CONFIG_HOME: path.join(root, "home", ".config"),
186
- XDG_CACHE_HOME: path.join(root, "home", ".cache"),
187
- ASC_CONFIG_PATH: path.join(root, "home", "config.json"),
188
- ASC_WEB_SESSION_CACHE_DIR: path.join(root, "session"),
189
- ASC_WEB_SESSION_CACHE_BACKEND: "file",
190
- ASC_WEB_DONT_STORE_PASSWORD: "1",
191
- ASC_BYPASS_KEYCHAIN: "1",
192
- ASC_TELEMETRY_DISABLED: "1",
193
- ASC_SPINNER_DISABLED: "1"
194
- };
195
- };
533
+ const PROGRAM_LICENSE_AGREEMENT_HINT = ["The Account Holder must accept the latest Program License Agreement:", "https://developer.apple.com/account"].join("\n");
534
+ /** The code App Store Connect answers a team with a pending agreement. */
535
+ const AGREEMENT_ERROR_CODE = "FORBIDDEN.REQUIRED_AGREEMENTS_MISSING_OR_EXPIRED";
536
+ /**
537
+ * Whether App Store Connect's JSON:API errors say the team has a Program
538
+ * License Agreement to accept, by its code or its detail.
539
+ */
540
+ const isProgramLicenseAgreementError = (errors) => errors.some(({ code, detail, title }) => code === AGREEMENT_ERROR_CODE || /Program License Agreement/iu.test(`${detail ?? ""} ${title ?? ""}`));
541
+ /** Whether xcodebuild's output says the team has an agreement to accept. */
542
+ const mentionsProgramLicenseAgreement = (output) => output.includes("PLA Update available");
543
+ //#endregion
544
+ //#region src/asc/ascKeyIssuer.ts
545
+ const IRIS_URL = "https://appstoreconnect.apple.com/iris/v1";
546
+ /**
547
+ * The headers App Store Connect's Integrations page sends its API with. A
548
+ * function: `ascApiKey` imports this module, so its constants aren't set
549
+ * yet when this module loads.
550
+ */
551
+ const irisHeaders = () => ({
552
+ Accept: "application/vnd.api+json, application/json, text/csv",
553
+ "Content-Type": "application/json",
554
+ "X-CSRF-ITC": "[asc-ui]",
555
+ Origin: "https://appstoreconnect.apple.com",
556
+ Referer: ASC_INTEGRATIONS_URL
557
+ });
196
558
  const answer = (value) => p.isCancel(value) ? void 0 : value;
559
+ /** One line: where the code went, and where a wrong one sends the next. */
560
+ const twoFactorMessage = (request) => {
561
+ const phone = request.destination ?? "your trusted phone";
562
+ if (request.via === "sms") return `${request.afterWrongCode ? "Wrong code. " : ""}Code texted to ${phone}`;
563
+ return request.textsOnWrongCode ? `Code on your Apple device (wrong code texts ${phone})` : "Code on your Apple device";
564
+ };
197
565
  /** Hot Updater's own prompts, so the sign-in looks like the rest of the CLI. */
198
566
  const cliPrompts = {
199
567
  password: async (appleId) => answer(await p.password({
@@ -201,65 +569,53 @@ const cliPrompts = {
201
569
  mask: "•",
202
570
  validate: (value) => value ? void 0 : "Enter the password."
203
571
  })),
204
- twoFactorCode: async (attempt) => answer(await p.text({
205
- message: attempt === 1 ? "Two-factor code from your trusted device (no device at hand? enter any wrong code once, and Apple texts one to your phone)" : "Verification code Apple sent to your phone",
206
- validate: (value) => /^\d{6}$/u.test(value?.trim() ?? "") ? void 0 : "Enter the 6-digit code."
572
+ twoFactorCode: async (request) => answer(await p.text({
573
+ message: twoFactorMessage(request),
574
+ validate: (value) => new RegExp(`^\\d{${request.length}}$`, "u").test(value?.trim() ?? "") ? void 0 : `Enter the ${request.length}-digit code.`
207
575
  }))?.trim()
208
576
  };
209
- /** `value` as one word for `sh`. */
210
- const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
211
- /**
212
- * A two-factor code command for asc that asks `prompts` in this process:
213
- * asc runs it when Apple wants a code, and it prints what the developer
214
- * typed, which it gets over a socket in the 0700 work directory. A
215
- * cancelled prompt makes it print nothing and fail, which stops the sign-in.
216
- */
217
- const listenForTwoFactorCodes = async (root, prompts) => {
218
- const socketPath = path.join(root, "2fa.sock");
219
- const scriptPath = path.join(root, "two-factor-code.cjs");
220
- await fs.writeFile(scriptPath, [
221
- "const socket = require(\"node:net\").connect(" + JSON.stringify(socketPath) + ");",
222
- "let code = \"\";",
223
- "socket.on(\"data\", (chunk) => { code += chunk; });",
224
- "socket.on(\"end\", () => {",
225
- " code = code.trim();",
226
- " if (!code) process.exit(1);",
227
- " process.stdout.write(code + \"\\n\");",
228
- "});",
229
- "socket.on(\"error\", () => process.exit(1));",
230
- ""
231
- ].join("\n"), { mode: 384 });
232
- let attempts = 0;
233
- let cancelled = false;
234
- const server = net.createServer((socket) => {
235
- attempts += 1;
236
- prompts.twoFactorCode(attempts).then((code) => {
237
- if (!code) cancelled = true;
238
- socket.end(code ? `${code}\n` : "");
239
- }, () => {
240
- cancelled = true;
241
- socket.destroy();
242
- });
243
- });
244
- await new Promise((resolve, reject) => {
245
- server.once("error", reject);
246
- server.listen(socketPath, resolve);
247
- });
248
- return {
249
- command: `${shellQuote(process.execPath)} ${shellQuote(scriptPath)}`,
250
- cancelled: () => cancelled,
251
- close: () => new Promise((resolve) => server.close(() => resolve()))
252
- };
253
- };
254
577
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
255
578
  const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
256
- /** The last line of asc's error output, which names what failed. */
257
- const lastLine = (stderr) => stderr.split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
258
- /** What to do about a key asc could not create, by what App Store Connect said. */
259
- const createFailureHint = (stderr) => {
260
- if (/agreement/iu.test(stderr)) return "The Apple Developer Program License Agreement has changed: the Account Holder accepts it at https://developer.apple.com/account, then run this again.";
261
- if (/limit|maximum/iu.test(stderr)) return `The team has as many active API keys as App Store Connect allows: revoke one you no longer use at ${ASC_INTEGRATIONS_URL}, then run this again.`;
262
- if (/account holder|admin|permission|forbidden|not allowed|403/iu.test(stderr)) return "Creating an App Store Connect API key needs the Account Holder or Admin role in the team: sign in with such an Apple Account, or ask one to run this.";
579
+ const toTeam = (appleId, provider) => ({
580
+ appleId,
581
+ teamId: provider.publicProviderId,
582
+ ...provider.name ? { name: provider.name } : {}
583
+ });
584
+ /** What App Store Connect's API said went wrong, from its JSON:API errors. */
585
+ const irisDetail = (body) => {
586
+ try {
587
+ const parsed = JSON.parse(body);
588
+ if (!isRecord(parsed) || !Array.isArray(parsed.errors)) return void 0;
589
+ return parsed.errors.filter(isRecord).map((error) => text(error.detail) ?? text(error.title)).find(Boolean);
590
+ } catch {
591
+ return;
592
+ }
593
+ };
594
+ /** What to do about a key App Store Connect would not create. */
595
+ const createFailureHint = (status, body) => {
596
+ if (/agreement/iu.test(body)) return PROGRAM_LICENSE_AGREEMENT_HINT;
597
+ if (/limit|maximum/iu.test(body)) return `The team has the most API keys App Store Connect allows. Revoke one at:\n${ASC_INTEGRATIONS_URL}`;
598
+ if (status === 403 || /account holder|admin|permission/iu.test(body)) return "Creating an API key needs the Account Holder or Admin role in the team.";
599
+ };
600
+ const irisRequest = async (session, step, method, path, payload) => {
601
+ const response = await session.request(`${IRIS_URL}${path}`, {
602
+ method,
603
+ headers: irisHeaders(),
604
+ ...payload === void 0 ? {} : { body: JSON.stringify(payload) }
605
+ });
606
+ const body = await response.text();
607
+ if (!response.ok) {
608
+ const detail = irisDetail(body);
609
+ throw new AppleSignInError(`${step} failed (HTTP ${response.status}).${detail ? `\n${detail}` : ""}`, {
610
+ status: response.status,
611
+ body
612
+ });
613
+ }
614
+ try {
615
+ const parsed = JSON.parse(body);
616
+ if (isRecord(parsed) && isRecord(parsed.data)) return parsed.data;
617
+ } catch {}
618
+ throw new AppleSignInError(`${step} answered no API key.`, { status: response.status });
263
619
  };
264
620
  /** A P-256 private key, as App Store Connect issues one, or a thrown error. */
265
621
  const assertP8 = (p8) => {
@@ -267,144 +623,108 @@ const assertP8 = (p8) => {
267
623
  try {
268
624
  key = crypto.createPrivateKey(p8);
269
625
  } catch {
270
- throw new Error("asc saved a .p8 that is not a private key.");
626
+ throw new Error("App Store Connect sent a .p8 that is not a private key.");
627
+ }
628
+ if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") throw new Error("App Store Connect sent a .p8 that is not a P-256 private key.");
629
+ };
630
+ /** The one-time `.p8`; a key App Store Connect hasn't settled yet is retried. */
631
+ const downloadP8 = async (session, keyId, wait) => {
632
+ for (let attempt = 1;; attempt++) try {
633
+ const data = await irisRequest(session, "Downloading the key's .p8", "GET", `/apiKeys/${encodeURIComponent(keyId)}?${new URLSearchParams({ "fields[apiKeys]": "privateKey" })}`);
634
+ const encoded = isRecord(data.attributes) ? text(data.attributes.privateKey) : void 0;
635
+ if (text(data.id) !== keyId || !encoded) throw new Error("App Store Connect sent no .p8 for the key.");
636
+ return Buffer.from(encoded, "base64").toString("utf-8").trim();
637
+ } catch (error) {
638
+ if (!(error instanceof AppleSignInError && error.status !== void 0 && (error.status === 404 || error.status === 409 || error.status === 429 || error.status >= 500)) || attempt === 3) throw error;
639
+ await wait(attempt * 1e3);
271
640
  }
272
- if (key.asymmetricKeyType !== "ec") throw new Error("asc saved a .p8 that is not an EC private key.");
641
+ };
642
+ const issuerOf = (data) => {
643
+ const attributes = isRecord(data.attributes) ? data.attributes : {};
644
+ const relationships = isRecord(data.relationships) ? data.relationships : {};
645
+ const related = isRecord(relationships.provider) ? relationships.provider.data : void 0;
646
+ return (isRecord(attributes.provider) ? text(attributes.provider.id) : void 0) ?? (isRecord(related) ? text(related.id) : void 0);
273
647
  };
274
648
  /**
275
- * `IssueAscApiKey` with asc, the open-source App Store Connect CLI
276
- * (https://github.com/rorkai/App-Store-Connect-CLI, MIT):
649
+ * `IssueAscApiKey` by signing in as App Store Connect's web page does
650
+ * (`signInToAppStoreConnect`) and creating the key with the API its
651
+ * Integrations page uses:
277
652
  *
278
- * 1. `asc web auth login` signs in with the password and the two-factor
279
- * codes typed into Hot Updater's prompts. The password reaches only that
280
- * asc process, in its environment (never an argument), each code only
281
- * asc's two-factor code command, and neither is kept or printed.
282
- * 2. `chooseTeam` sees the team asc signed in to, unless `teamId` is set.
283
- * 3. `asc web api-keys create` issues the key and saves its one-time `.p8`,
284
- * which is checked before it is handed out; a key that fails the check is
285
- * revoked at once.
286
- * 4. `revoke` runs `asc web api-keys revoke` in the same session.
653
+ * 1. The password typed into Hot Updater's prompt goes only to Apple's SRP
654
+ * sign-in, which sends a proof of it, never the password; the two-factor
655
+ * code goes only to Apple's check. Neither is kept or printed.
656
+ * 2. `chooseTeam` sees the teams the Apple Account is in, unless `teamId`
657
+ * is set.
658
+ * 3. The key is created, its one-time `.p8` downloaded and checked; a key
659
+ * that fails the check is revoked at once.
660
+ * 4. `revoke` deactivates the key in the same session.
287
661
  *
288
- * asc's whole state (its web session, config, and the `.p8`) lives in a
289
- * temporary 0700 directory, which `dispose` deletes, as does the process
290
- * exiting first.
662
+ * The session is cookies in this process's memory, which `dispose` drops.
291
663
  *
292
- * @param asc The asc binary; found or downloaded with `findAscCli` unless set.
293
- * @param env The environment asc's own is derived from.
664
+ * @param fetch Where requests go, Apple unless set.
294
665
  * @param prompts Where the password and two-factor codes are asked.
666
+ * @param wait How a retried download waits.
295
667
  */
296
- const createAscCliKeyIssuer = ({ asc, env = process.env, prompts = cliPrompts } = {}) => async ({ name, role, appleId, teamId, chooseTeam }) => {
297
- const cli = asc ?? await findAscCli();
298
- p.log.info("Hot Updater signs in with asc, the open-source App Store Connect CLI. It keeps only the API key it issues: neither the password nor the session.");
668
+ const createAscKeyIssuer = ({ fetch = globalThis.fetch, prompts = cliPrompts, wait = setTimeout$1 } = {}) => async ({ name, role, appleId, teamId, chooseTeam }) => {
669
+ if (!appleId) throw new AppleSignInError("Signing in needs the Apple Account's email.");
670
+ p.log.info("Signing in to App Store Connect. Only the issued key is kept.");
299
671
  const password = await prompts.password(appleId);
300
- if (password === void 0) throw new AscCommandError("Signing in was cancelled.", void 0);
672
+ if (password === void 0) throw new AppleSignInError("Signing in was cancelled.");
301
673
  registerSecretValue(password);
302
- const work = await createWorkDirectory();
303
- const ascEnv = ascEnvironment(work.root, env);
304
- const run = async (step, args, extraEnv = {}) => {
305
- const result = await execa(cli.path, args, {
306
- env: {
307
- ...ascEnv,
308
- ...extraEnv
309
- },
310
- extendEnv: false,
311
- stdin: "ignore",
312
- stdout: "pipe",
313
- stderr: "pipe",
314
- reject: false
315
- });
316
- const stderr = String(result.stderr ?? "");
317
- if (result.exitCode !== 0 || result.failed) throw new AscCommandError(`${step} failed: ${lastLine(stderr) ?? (result.signal ? `stopped by ${result.signal}` : void 0) ?? `exit code ${result.exitCode}`}`, result.exitCode, { cause: { stderr } });
318
- let parsed;
319
- try {
320
- parsed = JSON.parse(String(result.stdout));
321
- } catch {
322
- parsed = void 0;
323
- }
324
- if (!isRecord(parsed)) throw new AscCommandError(`${step} printed no JSON this version of Hot Updater reads.`, result.exitCode);
325
- return parsed;
674
+ const session = await signInToAppStoreConnect({
675
+ appleId,
676
+ password,
677
+ prompts,
678
+ fetch
679
+ });
680
+ let disposed = false;
681
+ const dispose = async () => {
682
+ disposed = true;
683
+ session.clear();
326
684
  };
327
685
  try {
328
- const twoFactor = await listenForTwoFactorCodes(work.root, prompts);
329
- let login;
686
+ const teams = session.providers.map((provider) => toTeam(appleId, provider));
687
+ const chosen = teamId ?? await chooseTeam?.(teams, toTeam(appleId, session.provider));
688
+ const provider = chosen === void 0 ? session.provider : await session.selectProvider(chosen);
689
+ let data;
330
690
  try {
331
- login = await run("Signing in with asc web auth login", [
332
- "web",
333
- "auth",
334
- "login",
335
- ...appleId ? ["--apple-id", appleId] : [],
336
- "--two-factor-code-command",
337
- twoFactor.command,
338
- "--output",
339
- "json"
340
- ], { ASC_WEB_PASSWORD: password });
691
+ data = await irisRequest(session, "Creating the App Store Connect API key", "POST", "/apiKeys", { data: {
692
+ type: "apiKeys",
693
+ attributes: {
694
+ nickname: name,
695
+ roles: [role],
696
+ allAppsVisible: true,
697
+ keyType: "PUBLIC_API"
698
+ }
699
+ } });
341
700
  } catch (error) {
342
- if (twoFactor.cancelled()) throw new AscCommandError("Signing in was cancelled.", void 0, { cause: error });
701
+ const hint = error instanceof AppleSignInError && error.status !== void 0 ? createFailureHint(error.status, error.body ?? "") : void 0;
702
+ if (hint) throw new AppleSignInError(`${error.message}\n${hint}`, {
703
+ ...error.status === void 0 ? {} : { status: error.status },
704
+ cause: error
705
+ });
343
706
  throw error;
344
- } finally {
345
- await twoFactor.close();
346
707
  }
347
- if (login.authenticated !== true) throw new AscCommandError("asc web auth login finished without a signed-in session.", 0);
348
- const signedIn = {
349
- ...text(login.appleId) ? { appleId: text(login.appleId) } : {},
350
- ...text(login.publicProviderId) ? { teamId: text(login.publicProviderId) } : {},
351
- ...text(login.developerTeamId) ? { developerTeamId: text(login.developerTeamId) } : {}
352
- };
353
- const chosen = teamId ?? await chooseTeam?.(signedIn);
354
- const team = chosen === void 0 || chosen === signedIn.teamId ? signedIn : {
355
- ...signedIn.appleId ? { appleId: signedIn.appleId } : {},
356
- teamId: chosen
708
+ const keyId = text(data.id);
709
+ if (!keyId) throw new AppleSignInError("App Store Connect created a key without an ID.");
710
+ const revoke = async () => {
711
+ if (disposed) return false;
712
+ return irisRequest(session, "Revoking the key", "PATCH", `/apiKeys/${encodeURIComponent(keyId)}`, { data: {
713
+ id: keyId,
714
+ type: "apiKeys",
715
+ attributes: { isActive: false }
716
+ } }).then(() => true, () => false);
357
717
  };
358
- const sessionArgs = [...signedIn.appleId ? ["--apple-id", signedIn.appleId] : [], ...chosen === void 0 ? [] : ["--public-provider-id", chosen]];
359
- let created;
360
- try {
361
- created = await run("Creating the App Store Connect API key", [
362
- "web",
363
- "api-keys",
364
- "create",
365
- "--name",
366
- name,
367
- "--role",
368
- role,
369
- "--output-dir",
370
- path.join(work.root, "keys"),
371
- ...sessionArgs,
372
- "--output",
373
- "json"
374
- ]);
375
- } catch (error) {
376
- const stderr = error instanceof AscCommandError && isRecord(error.cause) ? String(error.cause.stderr ?? "") : "";
377
- const hint = createFailureHint(stderr);
378
- if (hint && error instanceof AscCommandError) throw new AscCommandError(`${error.message}\n${hint}`, error.exitCode, { cause: error });
379
- throw error;
380
- }
381
- const keyId = text(created.keyId);
382
- if (!keyId) throw new AscCommandError("asc web api-keys create printed no key ID.", 0);
383
- const revoke = () => run("Revoking the key", [
384
- "web",
385
- "api-keys",
386
- "revoke",
387
- "--key-id",
388
- keyId,
389
- "--type",
390
- "team",
391
- "--confirm",
392
- ...sessionArgs,
393
- "--output",
394
- "json"
395
- ]).then((json) => json.active === false || json.status === "revoked", () => false);
396
718
  let p8;
397
719
  let issuerId;
398
720
  try {
399
- const issuer = text(created.issuerId);
400
- const p8Path = text(created.p8Path);
401
- const keys = path.join(work.root, "keys");
402
- if (!issuer) throw new Error("asc printed no issuer ID for the key.");
403
- if (!p8Path || await fs.realpath(path.dirname(path.resolve(p8Path))) !== await fs.realpath(keys)) throw new Error("asc saved the key's .p8 outside its output directory.");
404
- p8 = (await fs.readFile(p8Path, "utf-8")).trim();
721
+ p8 = await downloadP8(session, keyId, wait);
405
722
  registerSecretValue(p8);
406
723
  registerSecretValue(Buffer.from(p8).toString("base64"));
407
724
  assertP8(p8);
725
+ const details = await irisRequest(session, "Reading the key's issuer ID", "GET", `/apiKeys/${encodeURIComponent(keyId)}?include=provider`);
726
+ const issuer = issuerOf(details) ?? issuerOf(data);
727
+ if (!issuer) throw new Error("App Store Connect named no issuer ID for the key.");
408
728
  issuerId = issuer;
409
729
  } catch (error) {
410
730
  const revoked = await revoke();
@@ -414,13 +734,13 @@ const createAscCliKeyIssuer = ({ asc, env = process.env, prompts = cliPrompts }
414
734
  p8,
415
735
  keyId,
416
736
  issuerId,
417
- name: text(created.name) ?? name,
418
- team,
737
+ name: text(isRecord(data.attributes) ? data.attributes.nickname : "") ?? name,
738
+ team: toTeam(appleId, provider),
419
739
  revoke,
420
- dispose: work.dispose
740
+ dispose
421
741
  };
422
742
  } catch (error) {
423
- await work.dispose();
743
+ await dispose();
424
744
  throw error;
425
745
  }
426
746
  };
@@ -429,121 +749,11 @@ const createAscCliKeyIssuer = ({ asc, env = process.env, prompts = cliPrompts }
429
749
  /** Where team API keys are listed and revoked in App Store Connect. */
430
750
  const ASC_INTEGRATIONS_URL = "https://appstoreconnect.apple.com/access/integrations/api";
431
751
  /**
432
- * Hot Updater's sign-in, the one place that picks how it is done: asc, the
433
- * open-source App Store Connect CLI. Another implementation of
752
+ * Hot Updater's sign-in, the one place that picks how it is done: App Store
753
+ * Connect's own web sign-in, with no other tool. Another implementation of
434
754
  * `IssueAscApiKey` replaces it here without touching its callers.
435
755
  */
436
- const issueAscApiKey = (request) => createAscCliKeyIssuer()(request);
437
- //#endregion
438
- //#region src/utils/cocoapods.ts
439
- const installPodsIfNeeded = async (sourceDir) => {
440
- const podfilePath = path$1.join(sourceDir, "Podfile");
441
- if (!fs$1.existsSync(podfilePath)) {
442
- p.log.info("No Podfile found, skipping CocoaPods installation");
443
- return;
444
- }
445
- const gemfilePaths = [path$1.join(sourceDir, "Gemfile"), path$1.join(getCwd(), "Gemfile")];
446
- const shouldUseBundler = (await Promise.all(gemfilePaths.map(checkShouldUseBundler))).some(Boolean);
447
- const reactNative = getReactNativeMetadatas();
448
- const plan = resolvePodInstallPlan({
449
- version: reactNative.version,
450
- env: process.env
451
- });
452
- if (plan.runCodegen) await runReactNativeCodegen({
453
- projectRoot: getCwd(),
454
- reactNativePath: reactNative.packagePath,
455
- sourceDir
456
- });
457
- try {
458
- if (shouldUseBundler) {
459
- p.log.info("Using bundler for CocoaPods installation");
460
- const bundleSpinner = p.spinner();
461
- bundleSpinner.start("Installing Ruby gems");
462
- await execa("bundle", ["install"], { cwd: sourceDir });
463
- bundleSpinner.stop("Ruby gems installed");
464
- const podSpinner = p.spinner();
465
- podSpinner.start("Installing CocoaPods dependencies");
466
- await execa("bundle", [
467
- "exec",
468
- "pod",
469
- "install"
470
- ], {
471
- cwd: sourceDir,
472
- env: plan.env
473
- });
474
- podSpinner.stop("CocoaPods dependencies installed");
475
- } else {
476
- const spinner = p.spinner();
477
- spinner.start("Installing CocoaPods dependencies");
478
- await execa("pod", ["install"], {
479
- cwd: sourceDir,
480
- env: plan.env
481
- });
482
- spinner.stop("CocoaPods dependencies installed");
483
- }
484
- } catch (error) {
485
- throw new Error(`pod install failed: ${error}`);
486
- }
487
- };
488
- const checkShouldUseBundler = async (gemfilePath) => {
489
- try {
490
- if (!fs$1.existsSync(gemfilePath)) return false;
491
- return (await fs$1.promises.readFile(gemfilePath, "utf-8")).includes("cocoapods");
492
- } catch {
493
- return false;
494
- }
495
- };
496
- /**
497
- * Runs React Native codegen into `<sourceDir>/build/generated/ios`, as the
498
- * React Native CLI does before `pod install`. Clearing the old output first
499
- * drops the modules of removed libraries.
500
- */
501
- const runReactNativeCodegen = async ({ projectRoot, reactNativePath, sourceDir }) => {
502
- await fs$1.promises.rm(path$1.join(sourceDir, "build", "generated", "ios"), {
503
- recursive: true,
504
- force: true
505
- });
506
- const spinner = p.spinner();
507
- spinner.start("Running React Native codegen");
508
- try {
509
- await execa("node", [
510
- path$1.join(reactNativePath, "scripts", "generate-codegen-artifacts.js"),
511
- "-p",
512
- projectRoot,
513
- "-o",
514
- sourceDir,
515
- "-t",
516
- "ios"
517
- ], { cwd: projectRoot });
518
- } catch (error) {
519
- spinner.stop("React Native codegen failed");
520
- throw new Error(`React Native codegen failed: ${error}`);
521
- }
522
- spinner.stop("React Native codegen done");
523
- };
524
- /**
525
- * The environment `pod install` runs with, and whether codegen runs first.
526
- *
527
- * From React Native 0.79, `RCT_IGNORE_PODS_DEPRECATION=1` silences the
528
- * deprecation notice for calling `pod install` directly and also sets
529
- * `RCT_SKIP_CODEGEN=1`, because the React Native CLI runs codegen itself
530
- * first. Hot Updater sets it the same way and runs codegen too, unless the
531
- * user's `RCT_SKIP_CODEGEN=1` takes codegen over. Before 0.79, and when the
532
- * version is unknown, CocoaPods runs codegen. A user's value of a flag wins.
533
- */
534
- const resolvePodInstallPlan = ({ version, env }) => {
535
- const podsSkipCodegen = version.major > 0 || version.minor >= 79;
536
- const usePrebuiltReactNative = version.major > 0 || version.minor >= 81;
537
- const ignorePodsDeprecation = env["RCT_IGNORE_PODS_DEPRECATION"] ?? (podsSkipCodegen ? "1" : void 0);
538
- return {
539
- runCodegen: podsSkipCodegen && ignorePodsDeprecation === "1" && env["RCT_SKIP_CODEGEN"] !== "1",
540
- env: {
541
- ...ignorePodsDeprecation !== void 0 && { RCT_IGNORE_PODS_DEPRECATION: ignorePodsDeprecation },
542
- RCT_USE_RN_DEP: env["RCT_USE_RN_DEP"] ?? (usePrebuiltReactNative ? "1" : "0"),
543
- RCT_USE_PREBUILT_RNCORE: env["RCT_USE_PREBUILT_RNCORE"] ?? (usePrebuiltReactNative ? "1" : "0")
544
- }
545
- };
546
- };
756
+ const issueAscApiKey = (request) => createAscKeyIssuer()(request);
547
757
  //#endregion
548
758
  //#region src/utils/createRandomTmpDir.ts
549
759
  const TERMINATION_SIGNALS$2 = [
@@ -597,777 +807,295 @@ const removeTmpDir = async (directory) => {
597
807
  if (liveDirectories.delete(directory) && liveDirectories.size === 0) stopListening();
598
808
  };
599
809
  //#endregion
600
- //#region src/utils/platform.ts
810
+ //#region src/utils/escapeUnzipPattern.ts
601
811
  /**
602
- * Platform configurations for different Apple platforms
812
+ * A zip entry name as `unzip` reads a literal member. It takes `*`, `?` and
813
+ * `[...]` in a member name as wildcards, which a backslash escapes, so an
814
+ * app named `My[Dev].app` would otherwise match nothing.
603
815
  */
604
- const platformConfigs = { ios: {
605
- name: "ios",
606
- deviceSdk: "iphoneos",
607
- simulatorSdk: "iphonesimulator",
608
- supportsSimulator: true,
609
- deviceDestination: "platform=iOS",
610
- simulatorDestination: "platform=iOS Simulator"
611
- } };
816
+ const escapeUnzipPattern = (name) => name.replace(/[[\]*?\\]/gu, "\\$&");
612
817
  //#endregion
613
- //#region src/utils/destination.ts
614
- const buildDestinationString = ({ deviceType, platform, useGeneric }) => `${useGeneric ? "generic/" : ""}${deviceType === "device" ? platformConfigs[platform].deviceDestination : platformConfigs[platform].simulatorDestination}`;
818
+ //#region src/utils/readIpaInfo.ts
819
+ const INFO_PLIST_KEYS = {
820
+ bundleId: "CFBundleIdentifier",
821
+ shortVersion: "CFBundleShortVersionString",
822
+ bundleVersion: "CFBundleVersion"
823
+ };
615
824
  /**
616
- * Resolves IosBuildDestination to xcodebuild destination format
825
+ * Runs `read` on a copy of the app's `Payload/<App>.app/Info.plist` out of an
826
+ * `.ipa`, never a framework's or an extension's, which nest deeper.
617
827
  */
618
- const resolveDestination = ({ destination, useGeneric }) => {
619
- if (typeof destination === "object") {
620
- if ("id" in destination) return `id=${destination.id}`;
621
- if ("name" in destination) return `name=${destination.name}`;
622
- }
623
- switch (destination) {
624
- case "ios-device": return buildDestinationString({
625
- platform: "ios",
626
- deviceType: "device",
627
- useGeneric
628
- });
629
- case "ios-simulator": return buildDestinationString({
630
- platform: "ios",
631
- deviceType: "simulator",
632
- useGeneric
633
- });
634
- }
635
- };
636
- const resolveDestinations = ({ destinations, useGeneric }) => {
637
- return destinations.map((destination) => resolveDestination({
638
- destination,
639
- useGeneric
640
- }));
641
- };
642
- const getDefaultDestination = ({ platform, useGeneric, deviceType }) => {
643
- return buildDestinationString({
644
- deviceType,
645
- platform,
646
- useGeneric
647
- });
648
- };
649
- //#endregion
650
- //#region src/utils/parseXcodeProjectInfo.ts
651
- const parseXcodeProjectInfo = async (sourceDir) => {
652
- const files = await fs$1.promises.readdir(sourceDir);
653
- const workspace = files.find((file) => file.endsWith(".xcworkspace"));
654
- if (workspace) return {
655
- isWorkspace: true,
656
- name: workspace,
657
- path: path$1.join(sourceDir, workspace)
658
- };
659
- const project = files.find((file) => file.endsWith(".xcodeproj"));
660
- if (project) return {
661
- isWorkspace: false,
662
- name: project,
663
- path: path$1.join(sourceDir, project)
664
- };
665
- throw new Error(`No Xcode project or workspace found in ${sourceDir}`);
666
- };
667
- //#endregion
668
- //#region src/utils/prettifyXcodebuildError.ts
669
- const prettifyXcodebuildError = (error) => {
670
- if (error instanceof BuildFailedError) {
671
- const errorLines = error.summary.join("\n");
672
- const message = errorLines.includes("error: No profiles for") || errorLines.includes("error: Provisioning profile") ? "Not valid provisioning profile is set in the project. Check out the Signing & Capabilities tab in Xcode." : error.message;
673
- return new BuildFailedError(`Xcodebuild failed: ${message}`, {
674
- logPath: error.logPath,
675
- summary: error.summary,
676
- cause: error.cause
828
+ const withIpaInfoPlist = async (ipaPath, read) => {
829
+ const { stdout } = await execa("unzip", ["-Z1", ipaPath]);
830
+ const entry = stdout.split("\n").map((name) => name.trim()).find((name) => /^Payload\/[^/]+\.app\/Info\.plist$/u.test(name));
831
+ if (entry === void 0) throw new Error(`${path.basename(ipaPath)} has no Payload/<App>.app/Info.plist.`);
832
+ const directory = await createRandomTmpDir();
833
+ try {
834
+ const infoPlist = path.join(directory, "Info.plist");
835
+ await execa("unzip", [
836
+ "-p",
837
+ ipaPath,
838
+ escapeUnzipPattern(entry)
839
+ ], { stdout: { file: infoPlist } });
840
+ return await read(infoPlist);
841
+ } finally {
842
+ await fs.promises.rm(directory, {
843
+ recursive: true,
844
+ force: true
677
845
  });
678
846
  }
679
- return /* @__PURE__ */ new Error(`Xcodebuild failed: ${error}`);
680
847
  };
681
- //#endregion
682
- //#region src/utils/createXcodebuildLogger.ts
683
- const createXcodebuildLogger = ({ logPrefix }) => new BuildLogger({
684
- logPrefix,
685
- importantLogPatterns: [
686
- "error:",
687
- "** BUILD FAILED **",
688
- "** ARCHIVE FAILED **",
689
- "The following build commands failed:",
690
- "note: Building targets in dependency order",
691
- "note: Target dependency graph",
692
- "Running script",
693
- "[CP-User]",
694
- "[CP] Check Pods Manifest.lock",
695
- "Build Succeeded"
696
- ],
697
- progressStages: [
698
- ["Building targets in dependency order", "Target dependency graph"],
699
- ["Write Auxiliary File", "[CP] Check Pods Manifest.lock"],
700
- [
701
- "Running script",
702
- "[CP-User] [RN]Check rncore",
703
- "[CP-User] [Hermes] Replace Hermes",
704
- "[CP-User] [RN]Check FBReactNativeSpec"
705
- ],
706
- [
707
- "Processing",
708
- "ProcessProductPackaging",
709
- "ProcessProductPackagingDER"
710
- ],
711
- ["Compiling"],
712
- ["RegisterExecutionPolicyException"],
713
- ["Touching"],
714
- ["Building library", "Create Universal Binary"],
715
- ["Copying"],
716
- [
717
- "Build Succeeded",
718
- "BUILD SUCCEEDED",
719
- "ARCHIVE SUCCEEDED"
720
- ]
721
- ],
722
- failureSummary: {
723
- lines: [/(^|:\s)error: /, /^\*\* [A-Z ]+ FAILED \*\*$/],
724
- blocks: [{
725
- start: "The following build commands failed:",
726
- end: /^\(\d+ failures?\)$/,
727
- includeEnd: true
728
- }]
848
+ /** What App Store Connect files an `.ipa` under. */
849
+ const readIpaInfo = (ipaPath) => withIpaInfoPlist(ipaPath, async (infoPlist) => {
850
+ const info = {};
851
+ for (const [field, key] of Object.entries(INFO_PLIST_KEYS)) {
852
+ const { stdout: value, exitCode } = await execa("plutil", [
853
+ "-extract",
854
+ key,
855
+ "raw",
856
+ "-o",
857
+ "-",
858
+ infoPlist
859
+ ], { reject: false });
860
+ if (exitCode !== 0 || !value.trim()) throw new Error(`${path.basename(ipaPath)}'s Info.plist has no ${key}.`);
861
+ info[field] = value.trim();
729
862
  }
863
+ return info;
864
+ });
865
+ /** Whether Xcode marked an `.ipa`'s app for TestFlight internal testing only. */
866
+ const readIpaInternalTestingOnly = (ipaPath) => withIpaInfoPlist(ipaPath, async (infoPlist) => {
867
+ const { stdout: value, exitCode } = await execa("plutil", [
868
+ "-extract",
869
+ "TFInternalTestingOnly",
870
+ "raw",
871
+ "-o",
872
+ "-",
873
+ infoPlist
874
+ ], { reject: false });
875
+ return exitCode === 0 && value.trim() === "true";
876
+ });
877
+ /**
878
+ * Whether an `.ipa`'s app answers export compliance in its Info.plist. Either
879
+ * value is an answer, so this asks only whether the key is there.
880
+ */
881
+ const readIpaHasExportComplianceKey = (ipaPath) => withIpaInfoPlist(ipaPath, async (infoPlist) => {
882
+ const { exitCode } = await execa("plutil", [
883
+ "-extract",
884
+ "ITSAppUsesNonExemptEncryption",
885
+ "raw",
886
+ "-o",
887
+ "-",
888
+ infoPlist
889
+ ], { reject: false });
890
+ return exitCode === 0;
730
891
  });
731
892
  //#endregion
732
- //#region src/utils/runXcodebuildWithLogging.ts
733
- let cachedXcbeautifyAvailability = null;
734
- const TERMINATION_SIGNALS$1 = ["SIGINT", "SIGTERM"];
735
- const isXcbeautifyAvailable = async () => {
736
- if (cachedXcbeautifyAvailability !== null) return cachedXcbeautifyAvailability;
737
- try {
738
- await execa("which", ["xcbeautify"]);
739
- cachedXcbeautifyAvailability = true;
740
- return true;
741
- } catch {
742
- cachedXcbeautifyAvailability = false;
743
- return false;
744
- }
745
- };
746
- const createRawXcodebuildProcess = ({ args, env, sourceDir }) => {
747
- return execa("xcodebuild", args, {
748
- cwd: sourceDir,
749
- all: true,
750
- buffer: false,
751
- env: {
752
- ...process.env,
753
- ...env,
754
- NSUnbufferedIO: "YES"
755
- }
756
- });
757
- };
758
- const createXcbeautifyProcess = ({ cwd }) => {
759
- return execa("xcbeautify", [], {
760
- cwd,
761
- all: true,
762
- buffer: false
893
+ //#region src/utils/xcodeSigning.ts
894
+ /**
895
+ * How a device build signs with automatic signing, authenticated by the
896
+ * scheme's App Store Connect API key: the xcodebuild arguments, and the key.
897
+ * The key is resolved only here, for a device build of a scheme with
898
+ * `signing`. Without `credentials`, it resolves from the environment or the
899
+ * config's `secrets` adapter, and the temporary files are deleted when the
900
+ * process exits.
901
+ */
902
+ const resolveXcodeSigning = async ({ schemeConfig, credentials }) => {
903
+ const reference = schemeConfig.signing?.ascApiKey;
904
+ if (!reference) return;
905
+ const apiKey = await (credentials ?? createCredentialResolver()).resolve({
906
+ kind: "asc-api-key",
907
+ name: parseSecretReference(reference, "signing.ascApiKey")
763
908
  });
764
- };
765
- /** Why xcodebuild failed, without its command line. */
766
- const describeFailure = (error) => {
767
- if (error instanceof ExecaError) {
768
- if (error.signal) return `xcodebuild was stopped by ${error.signal}.`;
769
- if (error.exitCode !== void 0) return `xcodebuild exited with code ${error.exitCode}.`;
770
- }
771
- return error instanceof Error ? error.message : String(error);
772
- };
773
- const runXcodebuildWithLogging = async ({ args, env, sourceDir, successMessage, failureMessage, logPrefix }) => {
774
- const useXcbeautify = await isXcbeautifyAvailable();
775
- const logger = createXcodebuildLogger({ logPrefix });
776
- await logger.start();
777
- const activeProcesses = [];
778
- const terminateActiveProcesses = () => {
779
- for (const activeProcess of activeProcesses) activeProcess.kill();
909
+ return {
910
+ authenticationArgs: [
911
+ "-allowProvisioningUpdates",
912
+ "-authenticationKeyPath",
913
+ apiKey.keyPath,
914
+ "-authenticationKeyID",
915
+ apiKey.keyId,
916
+ "-authenticationKeyIssuerID",
917
+ apiKey.issuerId
918
+ ],
919
+ apiKey
780
920
  };
781
- for (const signal of TERMINATION_SIGNALS$1) process.once(signal, terminateActiveProcesses);
782
- try {
783
- const xcodebuildProcess = createRawXcodebuildProcess({
784
- args,
785
- env,
786
- sourceDir
787
- });
788
- activeProcesses.push(xcodebuildProcess);
789
- const xcodebuildOutput = xcodebuildProcess.all ?? xcodebuildProcess.stdout;
790
- let xcbeautifyProcess = null;
791
- if (useXcbeautify && xcodebuildOutput) {
792
- xcbeautifyProcess = createXcbeautifyProcess({ cwd: sourceDir });
793
- activeProcesses.push(xcbeautifyProcess);
794
- }
795
- const logging = xcodebuildOutput ? logger.processStream(xcodebuildOutput, { display: xcbeautifyProcess ? xcbeautifyProcess.all ?? xcbeautifyProcess.stdout ?? void 0 : void 0 }) : Promise.resolve();
796
- const xcbeautifyInput = xcbeautifyProcess?.stdin;
797
- if (xcodebuildOutput && xcbeautifyInput) {
798
- xcbeautifyInput.on("error", () => {
799
- xcodebuildOutput.unpipe(xcbeautifyInput);
800
- });
801
- xcodebuildOutput.pipe(xcbeautifyInput);
802
- }
803
- const [xcodebuildResult, loggingResult] = await Promise.allSettled([
804
- xcodebuildProcess,
805
- logging,
806
- xcbeautifyProcess
807
- ]);
808
- if (xcodebuildResult.status === "rejected") throw xcodebuildResult.reason;
809
- if (loggingResult.status === "rejected") throw loggingResult.reason;
810
- logger.stop(successMessage);
811
- } catch (error) {
812
- logger.writeError(error);
813
- logger.stop(failureMessage, false);
814
- throw new BuildFailedError(`${failureMessage}: ${describeFailure(error)}`, {
815
- logPath: logger.logPath,
816
- summary: logger.failureSummary,
817
- cause: error
818
- });
819
- } finally {
820
- for (const signal of TERMINATION_SIGNALS$1) process.off(signal, terminateActiveProcesses);
821
- await logger.close();
822
- }
823
921
  };
824
- //#endregion
825
- //#region src/utils/writeBuildXcconfig.ts
826
- const SDK_CONDITIONS = [
827
- "",
828
- "[sdk=iphoneos*]",
829
- "[sdk=iphonesimulator*]"
830
- ];
922
+ const APP_STORE_CONNECT_EXPORT_OPTIONS = `<?xml version="1.0" encoding="UTF-8"?>
923
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
924
+ <plist version="1.0">
925
+ <dict>
926
+ <key>method</key>
927
+ <string>app-store-connect</string>
928
+ <key>signingStyle</key>
929
+ <string>automatic</string>
930
+ </dict>
931
+ </plist>
932
+ `;
933
+ /** The export option that keeps a build from App Store review. */
934
+ const INTERNAL_TESTING_ONLY = "testFlightInternalTestingOnly";
831
935
  /**
832
- * Finds a setting of `keys` that an included xcconfig sets with a condition
833
- * the build xcconfig does not, such as `[config=Release]` or `[arch=arm64]`,
834
- * which would outrank the build's own. It follows `#include`s, which are
835
- * relative to the including file.
936
+ * Writes the export options of a scheme that signs with an App Store Connect
937
+ * API key and sets no `exportOptionsPlist`: an App Store Connect export with
938
+ * automatic signing, internal testing only for a sandbox build.
836
939
  */
837
- const findConditionalSetting = async (files, keys, visited = /* @__PURE__ */ new Set()) => {
838
- for (const file of files) {
839
- if (visited.has(file) || !fs$1.existsSync(file)) continue;
840
- visited.add(file);
841
- const lines = (await fs$1.promises.readFile(file, "utf-8")).split("\n");
842
- for (const [index, line] of lines.entries()) {
843
- const include = line.match(/^\s*#include\??\s*"([^"]+)"/)?.[1];
844
- if (include) {
845
- const found = await findConditionalSetting([path$1.resolve(path$1.dirname(file), include)], keys, visited);
846
- if (found) return found;
847
- continue;
848
- }
849
- const [, key, conditions] = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)((?:\[[^\]]*\])+)\s*=/) ?? [];
850
- if (key && keys.includes(key) && !SDK_CONDITIONS.includes(conditions)) return `${file}:${index + 1} sets ${key}${conditions}`;
851
- }
852
- }
940
+ const writeAppStoreConnectExportOptions = async (directory, { internalTestingOnly = false } = {}) => {
941
+ const exportOptionsPlist = path.join(directory, "ExportOptions.plist");
942
+ await fs.promises.writeFile(exportOptionsPlist, internalTestingOnly ? APP_STORE_CONNECT_EXPORT_OPTIONS.replace("</dict>", ` <key>${INTERNAL_TESTING_ONLY}</key>\n <true/>\n</dict>`) : APP_STORE_CONNECT_EXPORT_OPTIONS);
943
+ return exportOptionsPlist;
853
944
  };
854
945
  /**
855
- * Writes the xcconfig a build loads, which sets the CLI's build settings
856
- * over every other. xcodebuild ranks an `-xcconfig`'s settings above the
857
- * command line's, so the scheme's `xcconfig` and each `-xcconfig` in
858
- * `extraParams` are included, in order, before `settings`, and the build
859
- * loads only this one.
946
+ * `testFlightInternalTestingOnly` in export options: undefined without it.
860
947
  */
861
- const writeBuildXcconfig = async ({ directory, sourceDir, xcconfig, extraParams = [], settings }) => {
862
- const included = xcconfig ? [xcconfig] : [];
863
- const otherParams = [];
864
- for (let i = 0; i < extraParams.length; i++) if (extraParams[i] === "-xcconfig" && i + 1 < extraParams.length) included.push(extraParams[++i]);
865
- else otherParams.push(extraParams[i]);
866
- const includedFiles = included.map((file) => path$1.resolve(sourceDir, file));
867
- const conditional = await findConditionalSetting(includedFiles, Object.keys(settings));
868
- if (conditional) throw new Error(`${conditional}, which would outrank the value the build sets. Set it without that condition, or remove it.`);
869
- const buildXcconfig = path$1.join(directory, "HotUpdater.xcconfig");
870
- await fs$1.promises.writeFile(buildXcconfig, [
871
- ...includedFiles.map((file) => `#include "${file}"`),
872
- ...Object.entries(settings).flatMap(([key, value]) => SDK_CONDITIONS.map((condition) => `${key}${condition} = ${value}`)),
873
- ""
874
- ].join("\n"));
875
- return {
876
- xcconfig: buildXcconfig,
877
- extraParams: otherParams
878
- };
948
+ const readInternalTestingOnly = async (exportOptionsPlist) => {
949
+ const uncommented = (await fs.promises.readFile(exportOptionsPlist, "utf-8").catch(() => void 0))?.replace(/<!--[\s\S]*?-->/gu, "");
950
+ if (uncommented?.includes("<plist")) {
951
+ const match = new RegExp(`<key>\\s*${INTERNAL_TESTING_ONLY}\\s*</key>\\s*<(true|false)\\s*/>`, "u").exec(uncommented);
952
+ return match ? match[1] === "true" : void 0;
953
+ }
954
+ const { stdout, exitCode } = await execa("plutil", [
955
+ "-extract",
956
+ INTERNAL_TESTING_ONLY,
957
+ "raw",
958
+ "-o",
959
+ "-",
960
+ exportOptionsPlist
961
+ ], { reject: false });
962
+ return exitCode === 0 ? stdout.trim() === "true" : void 0;
879
963
  };
880
964
  /**
881
- * Automatic signing over a target set to manual signing, whose provisioning
882
- * profile and identity Xcode would otherwise report as conflicting.
965
+ * Refuses a sandbox scheme's App Store Connect export that turns internal
966
+ * testing off: Apple keeps a build out of review only with it on. Another
967
+ * method's `.ipa` never reaches App Store Connect.
883
968
  */
884
- const AUTOMATIC_SIGNING = {
885
- CODE_SIGN_STYLE: "Automatic",
886
- PROVISIONING_PROFILE: "",
887
- PROVISIONING_PROFILE_SPECIFIER: "",
888
- CODE_SIGN_IDENTITY: "Apple Development"
969
+ const assertSandboxExportOptions = async (schemeName, exportOptionsPlist) => {
970
+ if (APP_STORE_EXPORT_METHODS.has(await readExportMethod(exportOptionsPlist)) && await readInternalTestingOnly(exportOptionsPlist) === false) throw new Error(`The sandbox scheme ${schemeName} turns ${INTERNAL_TESTING_ONLY} off in exportOptionsPlist.\nRemove the key, or set it to true.`);
889
971
  };
890
972
  /**
891
- * The settings a build sets over the scheme's: the MIN_BUNDLE_ID the CLI
892
- * issues and reports, and automatic signing when an App Store Connect API
893
- * key signs, which a target set to manual signing would not use.
973
+ * The export options a sandbox scheme's `exportOptionsPlist` exports with:
974
+ * the file itself, or a copy in `directory` that turns internal testing on
975
+ * when an App Store Connect export leaves it out.
894
976
  */
895
- const buildSettingsOverScheme = ({ minBundleId, authenticationArgs }) => ({
896
- HOT_UPDATER_MIN_BUNDLE_ID: minBundleId,
897
- ...authenticationArgs ? AUTOMATIC_SIGNING : {}
898
- });
977
+ const resolveSandboxExportOptions = async (schemeName, exportOptionsPlist, directory) => {
978
+ await assertSandboxExportOptions(schemeName, exportOptionsPlist);
979
+ if (!APP_STORE_EXPORT_METHODS.has(await readExportMethod(exportOptionsPlist)) || await readInternalTestingOnly(exportOptionsPlist) === true) return exportOptionsPlist;
980
+ const copy = path.join(directory, "ExportOptions.plist");
981
+ await fs.promises.copyFile(exportOptionsPlist, copy);
982
+ await execa("plutil", [
983
+ "-insert",
984
+ INTERNAL_TESTING_ONLY,
985
+ "-bool",
986
+ "true",
987
+ copy
988
+ ]);
989
+ return copy;
990
+ };
991
+ /** The export methods whose `.ipa` App Store Connect takes. */
992
+ const APP_STORE_EXPORT_METHODS = /* @__PURE__ */ new Set(["app-store", "app-store-connect"]);
993
+ /** The `method` of export options, or "" when it has none or can't be read. */
994
+ const readExportMethod = async (exportOptionsPlist) => {
995
+ const xml = (await fs.promises.readFile(exportOptionsPlist, "utf-8").catch(() => void 0))?.replace(/<!--[\s\S]*?-->/gu, "").match(/<key>\s*method\s*<\/key>\s*<string>\s*([^<]*?)\s*<\/string>/u);
996
+ if (xml) return xml[1];
997
+ const { stdout, exitCode } = await execa("plutil", [
998
+ "-extract",
999
+ "method",
1000
+ "raw",
1001
+ "-o",
1002
+ "-",
1003
+ exportOptionsPlist
1004
+ ], { reject: false });
1005
+ return exitCode === 0 ? stdout.trim() : "";
1006
+ };
1007
+ /**
1008
+ * Whether a device build exports for the devices its profile lists: with
1009
+ * `release-testing`, or `ad-hoc`, Xcode's older name for it. On an empty
1010
+ * keychain with the API key, Apple's cloud-managed distribution certificate
1011
+ * signs it, as it does an App Store Connect export.
1012
+ */
1013
+ const exportsForRegisteredDevices = async ({ exportOptionsPlist }) => exportOptionsPlist !== void 0 && ["release-testing", "ad-hoc"].includes(await readExportMethod(exportOptionsPlist));
1014
+ /**
1015
+ * Whether a device build exports for App Store Connect: with its
1016
+ * `exportOptionsPlist`'s method, or, without one, as a scheme signing with
1017
+ * an App Store Connect API key does. Such an `.ipa` is signed with Apple's
1018
+ * cloud-managed distribution certificate, never with a development
1019
+ * certificate the archive was signed with.
1020
+ */
1021
+ const exportsForAppStoreConnect = async (schemeConfig) => !schemeConfig.exportOptionsPlist || APP_STORE_EXPORT_METHODS.has(await readExportMethod(schemeConfig.exportOptionsPlist));
899
1022
  //#endregion
900
- //#region src/builder/archiveXcodeProject.ts
1023
+ //#region src/uploadToTestFlight.ts
1024
+ const API_URL$2 = "https://api.appstoreconnect.apple.com";
1025
+ /** Apple accepts tokens that expire within 20 minutes. */
1026
+ const TOKEN_LIFETIME_SECONDS = 1200;
1027
+ /** A token is replaced well before it expires, so no request carries a stale one. */
1028
+ const TOKEN_REUSE_SECONDS = 600;
1029
+ /** The parts of an `.ipa` sent at once. */
1030
+ const UPLOAD_CONCURRENCY = 4;
1031
+ /** Attempts to create the build upload and to commit the uploaded `.ipa`. */
1032
+ const COMMIT_ATTEMPTS = 3;
1033
+ /** Attempts per part: a part is a plain PUT, safe to repeat. */
1034
+ const UPLOAD_ATTEMPTS = 3;
1035
+ const IN_PROGRESS_STATES = /* @__PURE__ */ new Set(["AWAITING_UPLOAD", "PROCESSING"]);
1036
+ /** The error App Store Connect answers with when a build number is taken. */
1037
+ const DUPLICATE_ERROR_CODE = "ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE";
901
1038
  /**
902
- * Archives the scheme into `archiveDirectory`. The build's xcconfig is
903
- * written to a temporary directory, removed whether the archive succeeds or
904
- * not.
1039
+ * App Store Connect refused the upload: it already has a build with the
1040
+ * `.ipa`'s version and build number, from this or another upload, and takes
1041
+ * each build number once per version.
905
1042
  */
906
- const archiveXcodeProject = async ({ sourceDir, archiveDirectory, platform, installPods, destination, extraParams, configuration, xcodeScheme, xcconfig, logPrefix, minBundleId, authenticationArgs }) => {
907
- if (installPods) await installPodsIfNeeded(sourceDir);
908
- const xcodeProject = await parseXcodeProjectInfo(sourceDir);
909
- const archiveName = `${xcodeProject.name.replace(".xcworkspace", "").replace(".xcodeproj", "")}.xcarchive`;
910
- const archivePath = path$1.join(archiveDirectory, archiveName);
911
- const tmpDir = await createRandomTmpDir();
912
- try {
913
- const build = await writeBuildXcconfig({
914
- directory: tmpDir,
915
- sourceDir,
916
- xcconfig,
917
- extraParams,
918
- settings: buildSettingsOverScheme({
919
- minBundleId,
920
- authenticationArgs
921
- })
922
- });
923
- const archiveArgs = prepareArchiveArgs({
924
- authenticationArgs,
925
- minBundleId,
926
- archivePath,
927
- platform,
928
- sourceDir,
929
- xcodeProject,
930
- configuration,
931
- extraParams: build.extraParams,
932
- destination,
933
- xcconfig: build.xcconfig,
934
- xcodeScheme
935
- });
936
- p.log.info(`Xcode Archive Settings:
937
- Project ${xcodeProject.name}
938
- Scheme ${xcodeScheme}
939
- Platform ${platform}
940
- Command xcodebuild ${archiveArgs.join(" ")}
941
- `);
942
- try {
943
- await runXcodebuildWithLogging({
944
- args: archiveArgs,
945
- env: { HOT_UPDATER_MIN_BUNDLE_ID: minBundleId },
946
- failureMessage: "Archive failed",
947
- logPrefix,
948
- sourceDir,
949
- successMessage: "Archive completed successfully"
950
- });
951
- return { archivePath };
952
- } catch (error) {
953
- throw prettifyXcodebuildError(error);
954
- }
955
- } finally {
956
- await removeTmpDir(tmpDir);
1043
+ var TestFlightBuildExistsError = class extends Error {
1044
+ shortVersion;
1045
+ bundleVersion;
1046
+ name = "TestFlightBuildExistsError";
1047
+ constructor(shortVersion, bundleVersion, options) {
1048
+ super(`App Store Connect already has build ${bundleVersion} of version ${shortVersion}.\nUse a new build number (CFBundleVersion).`, options);
1049
+ this.shortVersion = shortVersion;
1050
+ this.bundleVersion = bundleVersion;
957
1051
  }
958
1052
  };
959
- const prepareArchiveArgs = ({ xcodeScheme, archivePath, platform, sourceDir, xcodeProject, configuration = "Release", xcconfig, extraParams, destination = [], minBundleId, authenticationArgs }) => {
960
- const args = [
961
- xcodeProject.isWorkspace ? "-workspace" : "-project",
962
- path$1.join(sourceDir, xcodeProject.name),
963
- "-scheme",
964
- xcodeScheme,
965
- "-configuration",
966
- configuration,
967
- "archive",
968
- "-archivePath",
969
- archivePath,
970
- `HOT_UPDATER_MIN_BUNDLE_ID=${minBundleId}`
971
- ];
972
- if (authenticationArgs) args.push(...authenticationArgs);
973
- if (xcconfig) args.push("-xcconfig", xcconfig);
974
- if (extraParams) args.push(...extraParams);
975
- const resolvedDestinations = resolveDestinations({
976
- destinations: destination,
977
- useGeneric: true
978
- });
979
- if (resolvedDestinations.length === 0) resolvedDestinations.push(getDefaultDestination({
980
- deviceType: "device",
981
- platform,
982
- useGeneric: true
983
- }));
984
- for (const destination of resolvedDestinations) args.push("-destination", destination);
985
- return args;
1053
+ /** An App Store Connect API request that failed, with the errors it answered. */
1054
+ var AppStoreConnectError = class extends Error {
1055
+ status;
1056
+ errors;
1057
+ /** The answer's `Retry-After` header, for a rate limit. */
1058
+ retryAfter;
1059
+ constructor(action, status, errors, retryAfter = null) {
1060
+ const details = errors.map((error) => error.detail ?? error.title ?? error.code).filter(Boolean);
1061
+ super(`${action} failed (HTTP ${status})${details.length > 0 ? `: ${details.join(" ")}` : "."}`);
1062
+ this.name = "AppStoreConnectError";
1063
+ this.status = status;
1064
+ this.errors = errors;
1065
+ this.retryAfter = retryAfter;
1066
+ }
986
1067
  };
987
- //#endregion
988
- //#region src/builder/buildXcodeProject.ts
989
1068
  /**
990
- * Builds the scheme in a temporary DerivedData directory, copies the built
991
- * `.app` to `outputDirectory`, and removes DerivedData, which takes 10 GB or
992
- * more, whether the build succeeds or not.
1069
+ * An App Store Connect API token: an ES256 JWT, whose signature JWS encodes
1070
+ * as the raw 64-byte r || s, not the DER Node signs by default.
993
1071
  */
994
- const buildXcodeProject = async ({ sourceDir, outputDirectory, platform, xcodeScheme, configuration, deviceType, logPrefix, destination = [], useGenericDestination = false, installPods, extraParams, minBundleId, authenticationArgs }) => {
995
- if (installPods) await installPodsIfNeeded(sourceDir);
996
- const xcodeProject = await parseXcodeProjectInfo(sourceDir);
997
- const tmpDir = await createRandomTmpDir();
1072
+ const createAppStoreConnectToken = ({ privateKey, keyId, issuerId, issuedAtSeconds = Math.floor(Date.now() / 1e3) }) => {
1073
+ const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
1074
+ const signingInput = `${encode({
1075
+ alg: "ES256",
1076
+ kid: keyId,
1077
+ typ: "JWT"
1078
+ })}.${encode({
1079
+ iss: issuerId,
1080
+ iat: issuedAtSeconds,
1081
+ exp: issuedAtSeconds + TOKEN_LIFETIME_SECONDS,
1082
+ aud: "appstoreconnect-v1"
1083
+ })}`;
1084
+ return `${signingInput}.${crypto$1.sign("sha256", Buffer.from(signingInput), {
1085
+ key: privateKey,
1086
+ dsaEncoding: "ieee-p1363"
1087
+ }).toString("base64url")}`;
1088
+ };
1089
+ const readPrivateKey = async (keyPath) => {
998
1090
  try {
999
- const derivedDataPath = path$1.join(tmpDir, "DerivedData");
1000
- const resolvedDestinations = resolveDestinations({
1001
- destinations: destination,
1002
- useGeneric: useGenericDestination
1003
- });
1004
- if (resolvedDestinations.length === 0) resolvedDestinations.push(getDefaultDestination({
1005
- deviceType,
1006
- platform,
1007
- useGeneric: useGenericDestination
1008
- }));
1009
- const build = await writeBuildXcconfig({
1010
- directory: tmpDir,
1011
- sourceDir,
1012
- extraParams,
1013
- settings: buildSettingsOverScheme({
1014
- minBundleId,
1015
- authenticationArgs
1016
- })
1017
- });
1018
- const buildArgs = prepareBuildArgs({
1019
- authenticationArgs,
1020
- xcconfig: build.xcconfig,
1021
- minBundleId,
1022
- configuration,
1023
- derivedDataPath,
1024
- deviceType,
1025
- resolvedDestinations,
1026
- extraParams: build.extraParams,
1027
- platform,
1028
- xcodeScheme,
1029
- sourceDir,
1030
- xcodeProject
1031
- });
1032
- p.log.info(`Xcode Build Settings:
1033
- Project ${xcodeProject.name}
1034
- Scheme ${xcodeScheme}
1035
- Configuration ${configuration}
1036
- Platform ${platform}
1037
- Device Type ${deviceType}
1038
- Command xcodebuild ${buildArgs.join(" ")}
1039
- `);
1040
- let builtAppPath;
1041
- try {
1042
- await runXcodebuildWithLogging({
1043
- args: buildArgs,
1044
- env: { HOT_UPDATER_MIN_BUNDLE_ID: minBundleId },
1045
- sourceDir,
1046
- logPrefix,
1047
- successMessage: "Build completed successfully",
1048
- failureMessage: "Build failed"
1049
- });
1050
- ({appPath: builtAppPath} = await getBuildSettings({
1051
- configuration,
1052
- derivedDataPath,
1053
- resolvedDestinations,
1054
- xcodeScheme,
1055
- sourceDir,
1056
- xcodeProject
1057
- }));
1058
- } catch (error) {
1059
- throw prettifyXcodebuildError(error);
1060
- }
1061
- const appPath = path$1.join(outputDirectory, path$1.basename(builtAppPath));
1062
- await fs$1.promises.cp(builtAppPath, appPath, { recursive: true });
1063
- return { appPath };
1064
- } finally {
1065
- await removeTmpDir(tmpDir);
1091
+ return crypto$1.createPrivateKey(await fs.promises.readFile(keyPath, "utf-8"));
1092
+ } catch {
1093
+ throw new Error("The App Store Connect API key is not a .p8 private key.");
1066
1094
  }
1067
1095
  };
1068
- const prepareBuildArgs = ({ xcodeProject, sourceDir, platform, xcodeScheme, configuration, deviceType, resolvedDestinations, derivedDataPath, extraParams, minBundleId, authenticationArgs, xcconfig }) => {
1069
- const sdk = deviceType === "simulator" ? platformConfigs[platform].simulatorSdk : platformConfigs[platform].deviceSdk;
1070
- const args = [
1071
- xcodeProject.isWorkspace ? "-workspace" : "-project",
1072
- path$1.join(sourceDir, xcodeProject.name),
1073
- "-scheme",
1074
- xcodeScheme,
1075
- "-configuration",
1076
- configuration,
1077
- "-sdk",
1078
- sdk,
1079
- "-derivedDataPath",
1080
- derivedDataPath,
1081
- `HOT_UPDATER_MIN_BUNDLE_ID=${minBundleId}`,
1082
- "build"
1083
- ];
1084
- if (authenticationArgs) args.push(...authenticationArgs);
1085
- args.push("-xcconfig", xcconfig);
1086
- if (extraParams) args.push(...extraParams);
1087
- for (const dest of resolvedDestinations) args.push("-destination", dest);
1088
- return args;
1089
- };
1090
- const getBuildSettings = async ({ xcodeProject, sourceDir, xcodeScheme, configuration, resolvedDestinations, derivedDataPath }) => {
1091
- const destinationArgs = resolvedDestinations.flatMap((dest) => ["-destination", dest]);
1092
- const { stdout: buildSettings } = await execa("xcodebuild", [
1093
- xcodeProject.isWorkspace ? "-workspace" : "-project",
1094
- xcodeProject.name,
1095
- "-scheme",
1096
- xcodeScheme,
1097
- "-configuration",
1098
- configuration,
1099
- ...destinationArgs,
1100
- "-derivedDataPath",
1101
- derivedDataPath,
1102
- "-showBuildSettings",
1103
- "-json"
1104
- ], { cwd: sourceDir });
1105
- const settings = JSON.parse(buildSettings).filter(({ target }) => target !== "React" && target !== "React-Core");
1106
- if (settings.length === 0) throw new Error("Failed to get build settings for your project");
1107
- const targetSettings = settings[0].buildSettings;
1108
- const wrapperExtension = targetSettings.WRAPPER_EXTENSION;
1109
- if (wrapperExtension !== "app" && wrapperExtension !== "framework") throw new Error(`Expected wrapper extension to be "app" or "framework" but found: ${wrapperExtension}`);
1110
- const targetBuildDir = targetSettings.TARGET_BUILD_DIR;
1111
- const executableFolderPath = targetSettings.EXECUTABLE_FOLDER_PATH;
1112
- const fullProductName = targetSettings.FULL_PRODUCT_NAME;
1113
- const infoPlistPath = targetSettings.INFOPLIST_PATH;
1114
- if (!targetBuildDir || !executableFolderPath || !fullProductName) throw new Error("Failed to get build paths from build settings");
1115
- return {
1116
- appPath: path$1.join(targetBuildDir, executableFolderPath),
1117
- infoPlistPath: path$1.join(targetBuildDir, infoPlistPath)
1118
- };
1119
- };
1120
- //#endregion
1121
- //#region src/builder/exportXcodeArchive.ts
1122
- /** Exports the archive into `exportPath`. */
1123
- const exportXcodeArchive = async ({ archivePath, exportPath, sourceDir, exportExtraParams, exportOptionsPlist, logPrefix, authenticationArgs }) => {
1124
- const exportArgs = prepareExportArgs({
1125
- authenticationArgs,
1126
- archivePath,
1127
- exportPath,
1128
- exportOptionsPlist,
1129
- exportExtraParams
1130
- });
1131
- try {
1132
- await runXcodebuildWithLogging({
1133
- args: exportArgs,
1134
- sourceDir,
1135
- successMessage: "Archive exported successfully",
1136
- failureMessage: "Export failed",
1137
- logPrefix
1138
- });
1139
- return { exportPath };
1140
- } catch (error) {
1141
- throw prettifyXcodebuildError(error);
1142
- }
1143
- };
1144
- const prepareExportArgs = ({ exportPath, archivePath, exportExtraParams, exportOptionsPlist, authenticationArgs }) => {
1145
- const args = [
1146
- "-exportArchive",
1147
- "-archivePath",
1148
- archivePath,
1149
- "-exportPath",
1150
- exportPath
1151
- ];
1152
- if (authenticationArgs) args.push(...authenticationArgs);
1153
- if (exportExtraParams) args.push(...exportExtraParams);
1154
- args.push("-exportOptionsPlist", exportOptionsPlist);
1155
- return args;
1156
- };
1157
- //#endregion
1158
- //#region src/utils/assertXcodebuildExist.ts
1159
- const assertXcodebuildExist = async () => {
1160
- try {
1161
- await execa("which", ["xcodebuild"]);
1162
- } catch {
1163
- p.log.error(`${colors.blueBright("xcodebuild")} resolve failed. Ensure that xcode is installed on your machine or xcodebuild is included in your path`);
1164
- process.exit(1);
1165
- }
1166
- };
1167
- //#endregion
1168
- //#region src/utils/escapeUnzipPattern.ts
1169
- /**
1170
- * A zip entry name as `unzip` reads a literal member. It takes `*`, `?` and
1171
- * `[...]` in a member name as wildcards, which a backslash escapes, so an
1172
- * app named `My[Dev].app` would otherwise match nothing.
1173
- */
1174
- const escapeUnzipPattern = (name) => name.replace(/[[\]*?\\]/gu, "\\$&");
1175
- //#endregion
1176
- //#region src/utils/readIpaInfo.ts
1177
- const INFO_PLIST_KEYS = {
1178
- bundleId: "CFBundleIdentifier",
1179
- shortVersion: "CFBundleShortVersionString",
1180
- bundleVersion: "CFBundleVersion"
1181
- };
1182
- /**
1183
- * Reads the app's `Payload/<App>.app/Info.plist` out of an `.ipa`, never a
1184
- * framework's or an extension's, which nest deeper.
1185
- */
1186
- const readIpaInfo = async (ipaPath) => {
1187
- const { stdout } = await execa("unzip", ["-Z1", ipaPath]);
1188
- const entry = stdout.split("\n").map((name) => name.trim()).find((name) => /^Payload\/[^/]+\.app\/Info\.plist$/u.test(name));
1189
- if (entry === void 0) throw new Error(`${path$1.basename(ipaPath)} has no Payload/<App>.app/Info.plist.`);
1190
- const directory = await createRandomTmpDir();
1191
- try {
1192
- const infoPlist = path$1.join(directory, "Info.plist");
1193
- await execa("unzip", [
1194
- "-p",
1195
- ipaPath,
1196
- escapeUnzipPattern(entry)
1197
- ], { stdout: { file: infoPlist } });
1198
- const info = {};
1199
- for (const [field, key] of Object.entries(INFO_PLIST_KEYS)) {
1200
- const { stdout: value, exitCode } = await execa("plutil", [
1201
- "-extract",
1202
- key,
1203
- "raw",
1204
- "-o",
1205
- "-",
1206
- infoPlist
1207
- ], { reject: false });
1208
- if (exitCode !== 0 || !value.trim()) throw new Error(`${path$1.basename(ipaPath)}'s Info.plist has no ${key}.`);
1209
- info[field] = value.trim();
1210
- }
1211
- return info;
1212
- } finally {
1213
- await fs$1.promises.rm(directory, {
1214
- recursive: true,
1215
- force: true
1216
- });
1217
- }
1218
- };
1219
- //#endregion
1220
- //#region src/utils/xcodeSigning.ts
1221
- /**
1222
- * How a device build signs with automatic signing, authenticated by the
1223
- * scheme's App Store Connect API key: the xcodebuild arguments, and the key.
1224
- * The key is resolved only here, for a device build of a scheme with
1225
- * `signing`. Without `credentials`, it resolves from the environment or the
1226
- * config's `secrets` adapter, and the temporary files are deleted when the
1227
- * process exits.
1228
- */
1229
- const resolveXcodeSigning = async ({ schemeConfig, credentials }) => {
1230
- const reference = schemeConfig.signing?.ascApiKey;
1231
- if (!reference) return;
1232
- const apiKey = await (credentials ?? createCredentialResolver()).resolve({
1233
- kind: "asc-api-key",
1234
- name: parseSecretReference(reference, "signing.ascApiKey")
1235
- });
1236
- return {
1237
- authenticationArgs: [
1238
- "-allowProvisioningUpdates",
1239
- "-authenticationKeyPath",
1240
- apiKey.keyPath,
1241
- "-authenticationKeyID",
1242
- apiKey.keyId,
1243
- "-authenticationKeyIssuerID",
1244
- apiKey.issuerId
1245
- ],
1246
- apiKey
1247
- };
1248
- };
1249
- const APP_STORE_CONNECT_EXPORT_OPTIONS = `<?xml version="1.0" encoding="UTF-8"?>
1250
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1251
- <plist version="1.0">
1252
- <dict>
1253
- <key>method</key>
1254
- <string>app-store-connect</string>
1255
- <key>signingStyle</key>
1256
- <string>automatic</string>
1257
- </dict>
1258
- </plist>
1259
- `;
1260
- /**
1261
- * Writes the export options of a scheme that signs with an App Store Connect
1262
- * API key and sets no `exportOptionsPlist`: an App Store Connect export with
1263
- * automatic signing.
1264
- */
1265
- const writeAppStoreConnectExportOptions = async (directory) => {
1266
- const exportOptionsPlist = path$1.join(directory, "ExportOptions.plist");
1267
- await fs$1.promises.writeFile(exportOptionsPlist, APP_STORE_CONNECT_EXPORT_OPTIONS);
1268
- return exportOptionsPlist;
1269
- };
1270
- /** The export methods whose `.ipa` App Store Connect takes. */
1271
- const APP_STORE_EXPORT_METHODS = /* @__PURE__ */ new Set(["app-store", "app-store-connect"]);
1272
- /** The `method` of export options, or "" when it has none or can't be read. */
1273
- const readExportMethod = async (exportOptionsPlist) => {
1274
- const xml = (await fs$1.promises.readFile(exportOptionsPlist, "utf-8").catch(() => void 0))?.replace(/<!--[\s\S]*?-->/gu, "").match(/<key>\s*method\s*<\/key>\s*<string>\s*([^<]*?)\s*<\/string>/u);
1275
- if (xml) return xml[1];
1276
- const { stdout, exitCode } = await execa("plutil", [
1277
- "-extract",
1278
- "method",
1279
- "raw",
1280
- "-o",
1281
- "-",
1282
- exportOptionsPlist
1283
- ], { reject: false });
1284
- return exitCode === 0 ? stdout.trim() : "";
1285
- };
1286
- /**
1287
- * Whether a device build exports for App Store Connect: with its
1288
- * `exportOptionsPlist`'s method, or, without one, as a scheme signing with
1289
- * an App Store Connect API key does. Such an `.ipa` is signed with Apple's
1290
- * cloud-managed distribution certificate, never with a development
1291
- * certificate the archive was signed with.
1292
- */
1293
- const exportsForAppStoreConnect = async (schemeConfig) => !schemeConfig.exportOptionsPlist || APP_STORE_EXPORT_METHODS.has(await readExportMethod(schemeConfig.exportOptionsPlist));
1294
- //#endregion
1295
- //#region src/uploadToTestFlight.ts
1296
- const API_URL$1 = "https://api.appstoreconnect.apple.com";
1297
- /** Apple accepts tokens that expire within 20 minutes. */
1298
- const TOKEN_LIFETIME_SECONDS = 1200;
1299
- /** A token is replaced well before it expires, so no request carries a stale one. */
1300
- const TOKEN_REUSE_SECONDS = 600;
1301
- /** The parts of an `.ipa` sent at once. */
1302
- const UPLOAD_CONCURRENCY = 4;
1303
- /** Attempts to create the build upload and to commit the uploaded `.ipa`. */
1304
- const COMMIT_ATTEMPTS = 3;
1305
- /** Attempts per part: a part is a plain PUT, safe to repeat. */
1306
- const UPLOAD_ATTEMPTS = 3;
1307
- const IN_PROGRESS_STATES = /* @__PURE__ */ new Set(["AWAITING_UPLOAD", "PROCESSING"]);
1308
- /** The error App Store Connect answers with when a build number is taken. */
1309
- const DUPLICATE_ERROR_CODE = "ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE";
1310
- /**
1311
- * App Store Connect refused the upload: it already has a build with the
1312
- * `.ipa`'s version and build number, from this or another upload, and takes
1313
- * each build number once per version.
1314
- */
1315
- var TestFlightBuildExistsError = class extends Error {
1316
- shortVersion;
1317
- bundleVersion;
1318
- name = "TestFlightBuildExistsError";
1319
- constructor(shortVersion, bundleVersion, options) {
1320
- super(`App Store Connect already has build ${bundleVersion} of version ${shortVersion}. Each build of a version needs a new build number (CFBundleVersion).`, options);
1321
- this.shortVersion = shortVersion;
1322
- this.bundleVersion = bundleVersion;
1323
- }
1324
- };
1325
- /** An App Store Connect API request that failed, with the errors it answered. */
1326
- var AppStoreConnectError = class extends Error {
1327
- status;
1328
- errors;
1329
- /** The answer's `Retry-After` header, for a rate limit. */
1330
- retryAfter;
1331
- constructor(action, status, errors, retryAfter = null) {
1332
- const details = errors.map((error) => error.detail ?? error.title ?? error.code).filter(Boolean);
1333
- super(`${action} failed (HTTP ${status})${details.length > 0 ? `: ${details.join(" ")}` : "."}`);
1334
- this.name = "AppStoreConnectError";
1335
- this.status = status;
1336
- this.errors = errors;
1337
- this.retryAfter = retryAfter;
1338
- }
1339
- };
1340
- /**
1341
- * An App Store Connect API token: an ES256 JWT, whose signature JWS encodes
1342
- * as the raw 64-byte r || s, not the DER Node signs by default.
1343
- */
1344
- const createAppStoreConnectToken = ({ privateKey, keyId, issuerId, issuedAtSeconds = Math.floor(Date.now() / 1e3) }) => {
1345
- const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
1346
- const signingInput = `${encode({
1347
- alg: "ES256",
1348
- kid: keyId,
1349
- typ: "JWT"
1350
- })}.${encode({
1351
- iss: issuerId,
1352
- iat: issuedAtSeconds,
1353
- exp: issuedAtSeconds + TOKEN_LIFETIME_SECONDS,
1354
- aud: "appstoreconnect-v1"
1355
- })}`;
1356
- return `${signingInput}.${crypto$1.sign("sha256", Buffer.from(signingInput), {
1357
- key: privateKey,
1358
- dsaEncoding: "ieee-p1363"
1359
- }).toString("base64url")}`;
1360
- };
1361
- const readPrivateKey = async (keyPath) => {
1362
- try {
1363
- return crypto$1.createPrivateKey(await fs$1.promises.readFile(keyPath, "utf-8"));
1364
- } catch {
1365
- throw new Error("The App Store Connect API key is not a .p8 private key.");
1366
- }
1367
- };
1368
- const readApiErrors = async (response) => {
1369
- const body = await response.json().catch(() => void 0);
1370
- return Array.isArray(body?.errors) ? body.errors : [];
1096
+ const readApiErrors = async (response) => {
1097
+ const body = await response.json().catch(() => void 0);
1098
+ return Array.isArray(body?.errors) ? body.errors : [];
1371
1099
  };
1372
1100
  const describeDetails = (details) => details.map((detail) => `${detail.description ?? "(no description)"}${detail.code ? ` (${detail.code})` : ""}`);
1373
1101
  /** Answers a request may outlive: a timeout, a rate limit, a server error. */
@@ -1444,7 +1172,7 @@ const runConcurrently = async (items, concurrency, run) => {
1444
1172
  */
1445
1173
  const SIGNING_SETTING = /^\s*(CODE_SIGNING_ALLOWED|CODE_SIGNING_REQUIRED)((?:\[[^\]]*\])*)\s*=\s*([^\s/]*)\s*(?:\/\/.*)?$/u;
1446
1174
  /** A scheme's `exportOptionsPlist`, which resolves from the project's root. */
1447
- const schemeFile = (file) => path$1.isAbsolute(file) ? file : path$1.resolve(getCwd(), file);
1175
+ const schemeFile = (file) => path.isAbsolute(file) ? file : path.resolve(getCwd(), file);
1448
1176
  /** Applies one assignment, as Xcode does: the last unconditional one wins. */
1449
1177
  const applySetting = (settings, line, label) => {
1450
1178
  const [, key, conditions, value] = line.match(SIGNING_SETTING) ?? [];
@@ -1464,10 +1192,10 @@ const applySetting = (settings, line, label) => {
1464
1192
  const applyXcconfig = async (file, label, settings, including) => {
1465
1193
  if (including.has(file)) return;
1466
1194
  including.add(file);
1467
- const uncommented = (await fs$1.promises.readFile(file, "utf-8").catch(() => void 0))?.replace(/\/\*[\s\S]*?\*\//gu, (comment) => comment.replace(/[^\n]/gu, ""));
1195
+ const uncommented = (await fs.promises.readFile(file, "utf-8").catch(() => void 0))?.replace(/\/\*[\s\S]*?\*\//gu, (comment) => comment.replace(/[^\n]/gu, ""));
1468
1196
  for (const line of uncommented?.split("\n") ?? []) {
1469
1197
  const include = line.match(/^\s*#include\??\s*"([^"]+)"/u)?.[1];
1470
- if (include) await applyXcconfig(path$1.resolve(path$1.dirname(file), include), include, settings, including);
1198
+ if (include) await applyXcconfig(path.resolve(path.dirname(file), include), include, settings, including);
1471
1199
  else applySetting(settings, line, label);
1472
1200
  }
1473
1201
  including.delete(file);
@@ -1489,7 +1217,7 @@ const codeSigningOff = async (iosScheme) => {
1489
1217
  };
1490
1218
  for (const entry of extraParams) applySetting(settings, entry, "extraParams");
1491
1219
  const xcconfigs = [...iosScheme.xcconfig ? [iosScheme.xcconfig] : [], ...extraParams.flatMap((entry, index) => entry === "-xcconfig" && index + 1 < extraParams.length ? [extraParams[index + 1]] : [])];
1492
- for (const xcconfig of xcconfigs) await applyXcconfig(path$1.resolve(getCwd(), "ios", xcconfig), xcconfig, settings, /* @__PURE__ */ new Set());
1220
+ for (const xcconfig of xcconfigs) await applyXcconfig(path.resolve(getCwd(), "ios", xcconfig), xcconfig, settings, /* @__PURE__ */ new Set());
1493
1221
  for (const [key, { value, where }] of settings.values) if (/^no$/iu.test(value) && !settings.conditional.has(key)) return where;
1494
1222
  };
1495
1223
  /**
@@ -1504,15 +1232,15 @@ const codeSigningOff = async (iosScheme) => {
1504
1232
  * it (`assertTestFlightExportOptions`).
1505
1233
  */
1506
1234
  const resolveTestFlightUploadKey = async ({ scheme, iosScheme }) => {
1507
- if (iosScheme.simulator) throw new Error(`TestFlight takes an .ipa, and the scheme ${scheme} builds a simulator .app.`);
1235
+ if (iosScheme.simulator) throw new Error(`The scheme ${scheme} builds a simulator .app, not an .ipa for TestFlight.`);
1508
1236
  const configuration = iosScheme.configuration ?? "Release";
1509
- if (/debug$/i.test(configuration)) throw new Error(`TestFlight takes a release build, and the scheme ${scheme} builds the ${configuration} configuration, which loads its JavaScript from Metro.`);
1237
+ if (/debug$/i.test(configuration)) throw new Error(`The scheme ${scheme} builds ${configuration}; TestFlight takes a release build.`);
1510
1238
  const unsigned = await codeSigningOff(iosScheme);
1511
- if (unsigned) throw new Error(`TestFlight takes a signed .ipa, and the scheme ${scheme} turns code signing off (${unsigned}).`);
1512
- if (!iosScheme.exportOptionsPlist && !iosScheme.signing) throw new Error(`The scheme ${scheme} archives without exporting an .ipa. Set signing.ascApiKey, or an exportOptionsPlist with the method app-store-connect.`);
1513
- if (iosScheme.exportOptionsPlist && fs$1.existsSync(schemeFile(iosScheme.exportOptionsPlist))) {
1239
+ if (unsigned) throw new Error(`The scheme ${scheme} turns code signing off:\n${unsigned}`);
1240
+ if (!iosScheme.exportOptionsPlist && !iosScheme.signing) throw new Error(`The scheme ${scheme} archives without exporting an .ipa.\nSet signing.ascApiKey, or exportOptionsPlist with method app-store-connect.`);
1241
+ if (iosScheme.exportOptionsPlist && fs.existsSync(schemeFile(iosScheme.exportOptionsPlist))) {
1514
1242
  const method = await readExportMethod(schemeFile(iosScheme.exportOptionsPlist));
1515
- if (!APP_STORE_EXPORT_METHODS.has(method)) throw new Error(`TestFlight takes an .ipa exported for App Store Connect, and the scheme ${scheme}'s exportOptionsPlist exports with the method ${method || "(none)"}. Set its method to app-store-connect.`);
1243
+ if (!APP_STORE_EXPORT_METHODS.has(method)) throw new Error(`The scheme ${scheme}'s exportOptionsPlist uses method ${method || "(none)"}.\nSet its method to app-store-connect for TestFlight.`);
1516
1244
  }
1517
1245
  return {
1518
1246
  kind: "asc-api-key",
@@ -1527,7 +1255,7 @@ const resolveTestFlightUploadKey = async ({ scheme, iosScheme }) => {
1527
1255
  const assertTestFlightExportOptions = async (schemeConfig) => {
1528
1256
  if (!schemeConfig.exportOptionsPlist) return;
1529
1257
  const method = await readExportMethod(schemeConfig.exportOptionsPlist);
1530
- if (!APP_STORE_EXPORT_METHODS.has(method)) throw new Error(`TestFlight takes an .ipa exported for App Store Connect, and the scheme ${schemeConfig.hotUpdaterSchemeName}'s exportOptionsPlist exports with the method ${method || "(none)"}. Set its method to app-store-connect.`);
1258
+ if (!APP_STORE_EXPORT_METHODS.has(method)) throw new Error(`The scheme ${schemeConfig.hotUpdaterSchemeName}'s exportOptionsPlist uses method ${method || "(none)"}.\nSet its method to app-store-connect for TestFlight.`);
1531
1259
  };
1532
1260
  /**
1533
1261
  * Requests to the App Store Connect API with `apiKey`: each carries a token
@@ -1552,7 +1280,7 @@ const createAppStoreConnectRequest = ({ apiKey, privateKey, fetch }) => {
1552
1280
  return `Bearer ${token.value}`;
1553
1281
  };
1554
1282
  return async (action, method, pathname, body) => {
1555
- const response = await fetch(`${API_URL$1}${pathname}`, {
1283
+ const response = await fetch(`${API_URL$2}${pathname}`, {
1556
1284
  method,
1557
1285
  headers: {
1558
1286
  Authorization: authorization(),
@@ -1562,8 +1290,8 @@ const createAppStoreConnectRequest = ({ apiKey, privateKey, fetch }) => {
1562
1290
  });
1563
1291
  if (!response.ok) {
1564
1292
  const error = new AppStoreConnectError(action, response.status, await readApiErrors(response), response.headers.get("retry-after"));
1565
- if (response.status === 401) throw new Error("App Store Connect refused the API key: check its key ID and issuer ID, and that the key is not revoked.", { cause: error });
1566
- if (response.status === 403) throw new Error(`${error.message} An API key with the Admin, App Manager, or Developer role uploads builds.`, { cause: error });
1293
+ if (response.status === 401) throw new Error("App Store Connect refused the API key.\nCheck its key ID and issuer ID, and that it isn't revoked.", { cause: error });
1294
+ if (response.status === 403) throw new Error(isProgramLicenseAgreementError(error.errors) ? `${action} failed (HTTP 403).\n${PROGRAM_LICENSE_AGREEMENT_HINT}` : `${error.message}\nUploads need a key with the Admin, App Manager, or Developer role.`, { cause: error });
1567
1295
  throw error;
1568
1296
  }
1569
1297
  return response.status === 204 ? void 0 : await response.json();
@@ -1576,7 +1304,7 @@ const findApp = async (request, bundleId) => {
1576
1304
  "fields[apps]": "bundleId"
1577
1305
  })}`));
1578
1306
  const app = apps.find((app) => app.attributes?.bundleId === bundleId);
1579
- if (!app) throw new Error(`App Store Connect has no app with the bundle ID ${bundleId} that this API key can see. Create the app in App Store Connect, or use a key of its team.`);
1307
+ if (!app) throw new Error(`App Store Connect has no app ${bundleId} that this API key can see.\nCreate the app in App Store Connect, or use a key of its team.`);
1580
1308
  return {
1581
1309
  app,
1582
1310
  testFlightUrl: `https://appstoreconnect.apple.com/apps/${app.id}/testflight/ios`
@@ -1619,11 +1347,11 @@ const findTestFlightBuild = async ({ ipaPath, apiKey, fetch = globalThis.fetch }
1619
1347
  * for App Store Connect to accept or reject the build.
1620
1348
  */
1621
1349
  const uploadToTestFlight = async ({ ipaPath, apiKey, fetch = globalThis.fetch, pollIntervalMs = 5e3, processingTimeoutMs = 18e5 }) => {
1622
- const ipaName = path$1.basename(ipaPath);
1350
+ const ipaName = path.basename(ipaPath);
1623
1351
  const [info, privateKey, { size: fileSize }] = await Promise.all([
1624
1352
  readIpaInfo(ipaPath),
1625
1353
  readPrivateKey(apiKey.keyPath),
1626
- fs$1.promises.stat(ipaPath)
1354
+ fs.promises.stat(ipaPath)
1627
1355
  ]);
1628
1356
  const request = createAppStoreConnectRequest({
1629
1357
  apiKey,
@@ -1648,14 +1376,18 @@ const uploadToTestFlight = async ({ ipaPath, apiKey, fetch = globalThis.fetch, p
1648
1376
  } }));
1649
1377
  } catch (error) {
1650
1378
  if (error instanceof AppStoreConnectError && error.status === 409 && error.errors.some((apiError) => apiError.code === DUPLICATE_ERROR_CODE)) {
1651
- if (unanswered) throw new Error(`App Store Connect already has build ${info.bundleVersion} of version ${info.shortVersion}, which a request of this upload it did not answer may have reserved. Upload with a new build number (CFBundleVersion).`, { cause: error });
1379
+ if (unanswered) throw new Error([
1380
+ `App Store Connect already has build ${info.bundleVersion} of version ${info.shortVersion}.`,
1381
+ "An unanswered request of this upload may have reserved it.",
1382
+ "Upload with a new build number (CFBundleVersion)."
1383
+ ].join("\n"), { cause: error });
1652
1384
  throw new TestFlightBuildExistsError(info.shortVersion, info.bundleVersion, { cause: error });
1653
1385
  }
1654
1386
  if (!isRetryable(error) || attempt === COMMIT_ATTEMPTS) throw error;
1655
1387
  if (!isRateLimited(error)) unanswered = true;
1656
1388
  await sleep(retryDelayMs(error, attempt));
1657
1389
  }
1658
- p.log.info(`Uploading ${ipaName} (version ${info.shortVersion}, build ${info.bundleVersion}) to App Store Connect`);
1390
+ p.log.info(`Uploading ${ipaName} ${info.shortVersion} (${info.bundleVersion}) to App Store Connect`);
1659
1391
  const removeUpload = async () => {
1660
1392
  for (let attempt = 1;; attempt++) try {
1661
1393
  await request("Removing the build upload", "DELETE", `/v1/buildUploads/${buildUploadId}`);
@@ -1663,7 +1395,11 @@ const uploadToTestFlight = async ({ ipaPath, apiKey, fetch = globalThis.fetch, p
1663
1395
  } catch (error) {
1664
1396
  if (error instanceof AppStoreConnectError && error.status === 404) return;
1665
1397
  if (!isRetryable(error) || attempt === COMMIT_ATTEMPTS) {
1666
- p.log.warn(`App Store Connect kept the unfinished build upload ${buildUploadId}, which reserves build ${info.bundleVersion} of version ${info.shortVersion}: ${error.message} Upload with a new build number (CFBundleVersion).`);
1398
+ p.log.warn([
1399
+ `App Store Connect kept the unfinished upload of build ${info.bundleVersion}.`,
1400
+ error.message,
1401
+ "Upload with a new build number (CFBundleVersion)."
1402
+ ].join("\n"));
1667
1403
  return;
1668
1404
  }
1669
1405
  await sleep(retryDelayMs(error, attempt));
@@ -1705,7 +1441,12 @@ const uploadToTestFlight = async ({ ipaPath, apiKey, fetch = globalThis.fetch, p
1705
1441
  } });
1706
1442
  break;
1707
1443
  } catch (error) {
1708
- const unconfirmed = () => new Error(`App Store Connect did not confirm the upload of build ${info.bundleVersion}: ${error.message} Check the build in TestFlight before you upload it again: ${testFlightUrl}`, { cause: error });
1444
+ const unconfirmed = () => new Error([
1445
+ `App Store Connect didn't confirm the upload of build ${info.bundleVersion}.`,
1446
+ error.message,
1447
+ "Check TestFlight before you upload it again:",
1448
+ testFlightUrl
1449
+ ].join("\n"), { cause: error });
1709
1450
  if (!isRetryable(error)) {
1710
1451
  if (commitUnanswered) throw unconfirmed();
1711
1452
  await removeUpload();
@@ -1731,8 +1472,13 @@ const uploadToTestFlight = async ({ ipaPath, apiKey, fetch = globalThis.fetch, p
1731
1472
  if (state.state === "PROCESSING") reportedProcessing = true;
1732
1473
  if (!state.state || IN_PROGRESS_STATES.has(state.state)) {
1733
1474
  if (Date.now() >= deadline) {
1734
- if (!reportedProcessing) throw new Error(`App Store Connect did not report build ${info.bundleVersion} processing${lastError instanceof Error ? `: ${lastError.message}` : state.state ? ` (${state.state}).` : "."} Check the build in TestFlight: ${testFlightUrl}`, { cause: lastError });
1735
- p.log.warn(`App Store Connect is still processing build ${info.bundleVersion}. It appears in TestFlight once processing finishes: ${testFlightUrl}`);
1475
+ if (!reportedProcessing) throw new Error([
1476
+ `App Store Connect didn't report build ${info.bundleVersion} processing.`,
1477
+ lastError instanceof Error ? lastError.message : state.state ? `State: ${state.state}` : void 0,
1478
+ "Check the build in TestFlight:",
1479
+ testFlightUrl
1480
+ ].filter(Boolean).join("\n"), { cause: lastError });
1481
+ p.log.warn(`App Store Connect is still processing build ${info.bundleVersion}.\nTestFlight lists it once processing finishes:\n${testFlightUrl}`);
1736
1482
  return {
1737
1483
  appId: app.id,
1738
1484
  buildUploadId,
@@ -1760,33 +1506,1002 @@ const uploadToTestFlight = async ({ ipaPath, apiKey, fetch = globalThis.fetch, p
1760
1506
  };
1761
1507
  }
1762
1508
  };
1763
- /**
1764
- * Sends each part App Store Connect asked for: the bytes at its offset, with
1765
- * only the headers it lists, since the URLs are presigned: another header,
1766
- * or the App Store Connect token, would break their signature.
1767
- */
1768
- const uploadParts = async ({ ipaPath, operations, fetch }) => {
1769
- const file = await fs$1.promises.open(ipaPath, "r");
1509
+ /**
1510
+ * Sends each part App Store Connect asked for: the bytes at its offset, with
1511
+ * only the headers it lists, since the URLs are presigned: another header,
1512
+ * or the App Store Connect token, would break their signature.
1513
+ */
1514
+ const uploadParts = async ({ ipaPath, operations, fetch }) => {
1515
+ const file = await fs.promises.open(ipaPath, "r");
1516
+ try {
1517
+ await runConcurrently(operations, UPLOAD_CONCURRENCY, async (operation, index) => {
1518
+ const body = Buffer.alloc(operation.length);
1519
+ const { bytesRead } = await file.read(body, 0, operation.length, operation.offset);
1520
+ if (bytesRead !== operation.length) throw new Error(`${path.basename(ipaPath)} changed while it was uploading.`);
1521
+ const headers = {};
1522
+ for (const { name, value } of operation.requestHeaders ?? []) headers[name] = value;
1523
+ for (let attempt = 1;; attempt++) {
1524
+ const response = await fetch(operation.url, {
1525
+ method: operation.method,
1526
+ headers,
1527
+ body
1528
+ }).catch((error) => error);
1529
+ if (!(response instanceof Error) && response.ok) return;
1530
+ if (!(response instanceof Error || isRetryableStatus(response.status)) || attempt === UPLOAD_ATTEMPTS) throw new Error(`Uploading part ${index + 1} of ${operations.length} failed: ${response instanceof Error ? response.message : `HTTP ${response.status}`}.`);
1531
+ await sleep(retryDelayMs(response, attempt));
1532
+ }
1533
+ });
1534
+ } finally {
1535
+ await file.close();
1536
+ }
1537
+ };
1538
+ //#endregion
1539
+ //#region src/asc/devices.ts
1540
+ const API_URL$1 = "https://api.appstoreconnect.apple.com";
1541
+ const DEVICE_FIELDS = "name,udid,status,deviceClass";
1542
+ const PAGE_SIZE = 200;
1543
+ /** More pages than an account's yearly limit of devices can fill. */
1544
+ const MAX_PAGES = 50;
1545
+ const deviceOf = ({ id, attributes }) => ({
1546
+ id,
1547
+ name: attributes?.name ?? "",
1548
+ udid: attributes?.udid ?? "",
1549
+ status: attributes?.status ?? "",
1550
+ deviceClass: attributes?.deviceClass ?? null
1551
+ });
1552
+ /**
1553
+ * A 403 from this API means something else than an upload's. A key's role
1554
+ * decides it, and only the person who owns the key can change that, so no key
1555
+ * is issued here.
1556
+ */
1557
+ const describingAccess = async (run) => {
1558
+ try {
1559
+ return await run();
1560
+ } catch (error) {
1561
+ const cause = error instanceof Error ? error.cause : void 0;
1562
+ if (cause instanceof AppStoreConnectError && cause.status === 403 && !isProgramLicenseAgreementError(cause.errors)) throw new Error("App Store Connect doesn't let this API key register devices.\nUse a key with the Admin role: npx hot-updater apple login", { cause });
1563
+ throw error;
1564
+ }
1565
+ };
1566
+ const readPages = async (request, firstPath) => {
1567
+ const devices = [];
1568
+ let pathname = firstPath;
1569
+ for (let page = 0; pathname !== void 0; page += 1) {
1570
+ if (page === MAX_PAGES) throw new Error("App Store Connect's device list didn't end.");
1571
+ const path = pathname;
1572
+ const answer = await retrying(() => request("Reading App Store Connect's devices", "GET", path));
1573
+ devices.push(...answer.data.map(deviceOf));
1574
+ const next = answer.links?.next;
1575
+ if (next !== void 0 && !next.startsWith(`${API_URL$1}/`)) throw new Error("App Store Connect's next page is on another host.");
1576
+ pathname = next?.slice(37);
1577
+ }
1578
+ return devices;
1579
+ };
1580
+ const listPath = (filter = {}) => `/v1/devices?${new URLSearchParams({
1581
+ "filter[platform]": "IOS",
1582
+ ...filter,
1583
+ "fields[devices]": DEVICE_FIELDS,
1584
+ limit: String(PAGE_SIZE)
1585
+ })}`;
1586
+ /** Every iPhone and iPad the Apple account has registered. */
1587
+ const listAscDevices = async ({ apiKey, fetch = globalThis.fetch }) => {
1588
+ const privateKey = await readPrivateKey(apiKey.keyPath);
1589
+ const request = createAppStoreConnectRequest({
1590
+ apiKey,
1591
+ privateKey,
1592
+ fetch
1593
+ });
1594
+ return describingAccess(() => readPages(request, listPath()));
1595
+ };
1596
+ const keyOf = (udid) => normalizeIosUdid(udid) ?? udid.toLowerCase();
1597
+ const findDevices = async (request, udids) => new Map((await readPages(request, listPath({ "filter[udid]": udids.join(",") }))).map((device) => [keyOf(device.udid), device]));
1598
+ /**
1599
+ * Registers devices with the Apple account, each at most once: a device that
1600
+ * is already there succeeds and changes nothing, so running it again is safe,
1601
+ * and so is a race with another run, which App Store Connect answers with 409.
1602
+ * A disabled device stays disabled, since its slot is already spent and someone
1603
+ * chose to disable it. It only registers: Xcode adds a registered device to the
1604
+ * profile at the next export, so an `.ipa` signed before never gains it.
1605
+ */
1606
+ const addAscDevices = async ({ devices, apiKey, fetch = globalThis.fetch }) => {
1607
+ const privateKey = await readPrivateKey(apiKey.keyPath);
1608
+ const request = createAppStoreConnectRequest({
1609
+ apiKey,
1610
+ privateKey,
1611
+ fetch
1612
+ });
1613
+ return describingAccess(async () => {
1614
+ const found = await findDevices(request, devices.map(({ udid }) => udid));
1615
+ const outcomes = [];
1616
+ for (const { udid, name } of devices) {
1617
+ const existing = found.get(keyOf(udid));
1618
+ if (existing !== void 0) {
1619
+ outcomes.push({
1620
+ udid,
1621
+ outcome: existing.status === "DISABLED" ? "disabled" : "already-registered",
1622
+ device: existing
1623
+ });
1624
+ continue;
1625
+ }
1626
+ try {
1627
+ const { data } = await retrying(() => request(`Registering ${udid}`, "POST", "/v1/devices", { data: {
1628
+ type: "devices",
1629
+ attributes: {
1630
+ name,
1631
+ platform: "IOS",
1632
+ udid
1633
+ }
1634
+ } }));
1635
+ outcomes.push({
1636
+ udid,
1637
+ outcome: "registered",
1638
+ device: deviceOf(data)
1639
+ });
1640
+ } catch (error) {
1641
+ if (!(error instanceof AppStoreConnectError) || error.status !== 409) throw error;
1642
+ const raced = (await findDevices(request, [udid])).get(keyOf(udid));
1643
+ if (raced !== void 0) {
1644
+ outcomes.push({
1645
+ udid,
1646
+ outcome: raced.status === "DISABLED" ? "disabled" : "already-registered",
1647
+ device: raced
1648
+ });
1649
+ continue;
1650
+ }
1651
+ const reason = error.errors.map(({ detail, title }) => detail ?? title).filter(Boolean).join(" ");
1652
+ outcomes.push({
1653
+ udid,
1654
+ outcome: "refused",
1655
+ reason: reason || "App Store Connect refused it.",
1656
+ limitReached: /maximum|limit/iu.test(reason)
1657
+ });
1658
+ }
1659
+ }
1660
+ return outcomes;
1661
+ });
1662
+ };
1663
+ //#endregion
1664
+ //#region src/utils/formatCommand.ts
1665
+ /**
1666
+ * A command to print, broken at spaces with ` \` once a line would pass
1667
+ * `width`, each continuation indented two spaces, so a terminal never wraps
1668
+ * it mid-word and it still pastes as one command.
1669
+ */
1670
+ const formatCommand = (words, width = 74) => {
1671
+ const lines = [];
1672
+ let line = "";
1673
+ for (const word of words) {
1674
+ const next = line ? `${line} ${word}` : word;
1675
+ if (line && next.length > width - 2) {
1676
+ lines.push(`${line} \\`);
1677
+ line = ` ${word}`;
1678
+ } else line = next;
1679
+ }
1680
+ lines.push(line);
1681
+ return lines.join("\n");
1682
+ };
1683
+ //#endregion
1684
+ //#region src/utils/cocoapods.ts
1685
+ /**
1686
+ * A failed command's error: the command, then the last lines of its
1687
+ * output, stdout and stderr as printed, without execa's full message.
1688
+ */
1689
+ const commandFailure = (command, error) => {
1690
+ const { all, stderr, stdout } = error ?? {};
1691
+ const detail = String(all || [stdout, stderr].filter(Boolean).join("\n") || "").trimEnd().split("\n").filter((line) => line.trim()).slice(-12).join("\n") || (error instanceof Error ? error.message : String(error));
1692
+ return new Error(`${command} failed.\n${detail}`, { cause: error });
1693
+ };
1694
+ /**
1695
+ * A line of the progress meter curl prints on stderr for each pod it
1696
+ * downloads, such as React Native's prebuilt core.
1697
+ */
1698
+ const DOWNLOAD_PROGRESS = [
1699
+ /^% Total +% Received/,
1700
+ /^Dload +Upload/,
1701
+ /^\d{1,3} +[\d.]+[kMGT]? +\d{1,3} +[\d.]+[kMGT]? /
1702
+ ];
1703
+ /**
1704
+ * `pod install`'s output: its live line shows the pod it installs, its log
1705
+ * keeps the whole output, and a failure prints CocoaPods' `[!]` errors and a
1706
+ * crash's `SomeError - …` line with its last lines, without the download
1707
+ * progress CocoaPods' curl prints on stderr.
1708
+ */
1709
+ const createPodInstallLogger = () => new BuildLogger({
1710
+ logPrefix: "pod-install",
1711
+ createPhaseReader: () => (line) => {
1712
+ const installing = /^Installing (\S+)/.exec(line);
1713
+ if (installing) return `Installing ${installing[1]}`;
1714
+ return /^(Analyzing dependencies|Downloading dependencies|Generating Pods project|Integrating client project)$/.test(line) ? line : void 0;
1715
+ },
1716
+ failureSummary: {
1717
+ lines: [/^[A-Z]\w*(::\w+)*Error - /],
1718
+ blocks: [{
1719
+ start: /^\[!\] /,
1720
+ end: /^$/,
1721
+ includeEnd: false
1722
+ }],
1723
+ ignore: DOWNLOAD_PROGRESS,
1724
+ tail: 4,
1725
+ stopAfter: /^\[!\] Oh no, an error occurred\.$/,
1726
+ maxWidth: 76
1727
+ }
1728
+ });
1729
+ /**
1730
+ * Runs `pod install` as a step whose failure prints CocoaPods' errors and
1731
+ * the log's path, then throws a `BuildFailedError`.
1732
+ */
1733
+ const runPodInstall = async ({ command, env, sourceDir }) => {
1734
+ const logger = createPodInstallLogger();
1735
+ const failureMessage = `${command.join(" ")} failed`;
1736
+ await logger.start({
1737
+ title: "Installing CocoaPods dependencies",
1738
+ header: [`$ ${formatCommand([...Object.entries(env).map(([name, value]) => `${name}=${value}`), ...command])}`, ""]
1739
+ });
1740
+ try {
1741
+ const podProcess = execa(command[0], command.slice(1), {
1742
+ cwd: sourceDir,
1743
+ env,
1744
+ all: true,
1745
+ buffer: false
1746
+ });
1747
+ const logging = podProcess.all ? logger.processStream(podProcess.all) : Promise.resolve();
1748
+ const [podResult, loggingResult] = await Promise.allSettled([podProcess, logging]);
1749
+ if (podResult.status === "rejected") throw podResult.reason;
1750
+ if (loggingResult.status === "rejected") throw loggingResult.reason;
1751
+ logger.stop("CocoaPods dependencies installed");
1752
+ } catch (error) {
1753
+ logger.writeError(error);
1754
+ const reason = error instanceof ExecaError && error.exitCode !== void 0 ? `exited with code ${error.exitCode}` : error instanceof Error ? error.message : String(error);
1755
+ logger.stop(`${failureMessage} · ${reason}`, false);
1756
+ throw new BuildFailedError(`${failureMessage}: ${reason}`, {
1757
+ logPath: logger.logPath,
1758
+ summary: logger.failureSummary,
1759
+ cause: error
1760
+ });
1761
+ } finally {
1762
+ await logger.close();
1763
+ }
1764
+ };
1765
+ const installPodsIfNeeded = async (sourceDir) => {
1766
+ const podfilePath = path.join(sourceDir, "Podfile");
1767
+ if (!fs.existsSync(podfilePath)) {
1768
+ p.log.info("No Podfile found, skipping CocoaPods installation");
1769
+ return {
1770
+ codegen: false,
1771
+ pods: false
1772
+ };
1773
+ }
1774
+ const gemfilePaths = [path.join(sourceDir, "Gemfile"), path.join(getCwd(), "Gemfile")];
1775
+ const shouldUseBundler = (await Promise.all(gemfilePaths.map(checkShouldUseBundler))).some(Boolean);
1776
+ const reactNative = getReactNativeMetadatas();
1777
+ const plan = resolvePodInstallPlan({
1778
+ version: reactNative.version,
1779
+ env: process.env
1780
+ });
1781
+ if (plan.runCodegen) await runReactNativeCodegen({
1782
+ projectRoot: getCwd(),
1783
+ reactNativePath: reactNative.packagePath,
1784
+ sourceDir
1785
+ });
1786
+ if (shouldUseBundler) {
1787
+ const bundleSpinner = p.spinner();
1788
+ bundleSpinner.start("Installing Ruby gems");
1789
+ try {
1790
+ await execa("bundle", ["install"], {
1791
+ cwd: sourceDir,
1792
+ all: true
1793
+ });
1794
+ } catch (error) {
1795
+ bundleSpinner.error("bundle install failed");
1796
+ throw commandFailure("bundle install", error);
1797
+ }
1798
+ bundleSpinner.stop("Ruby gems installed");
1799
+ }
1800
+ await runPodInstall({
1801
+ command: shouldUseBundler ? [
1802
+ "bundle",
1803
+ "exec",
1804
+ "pod",
1805
+ "install"
1806
+ ] : ["pod", "install"],
1807
+ env: plan.env,
1808
+ sourceDir
1809
+ });
1810
+ return {
1811
+ codegen: plan.runCodegen,
1812
+ pods: true
1813
+ };
1814
+ };
1815
+ const checkShouldUseBundler = async (gemfilePath) => {
1816
+ try {
1817
+ if (!fs.existsSync(gemfilePath)) return false;
1818
+ return (await fs.promises.readFile(gemfilePath, "utf-8")).includes("cocoapods");
1819
+ } catch {
1820
+ return false;
1821
+ }
1822
+ };
1823
+ /**
1824
+ * Runs React Native codegen into `<sourceDir>/build/generated/ios`, as the
1825
+ * React Native CLI does before `pod install`. Clearing the old output first
1826
+ * drops the modules of removed libraries.
1827
+ */
1828
+ const runReactNativeCodegen = async ({ projectRoot, reactNativePath, sourceDir }) => {
1829
+ await fs.promises.rm(path.join(sourceDir, "build", "generated", "ios"), {
1830
+ recursive: true,
1831
+ force: true
1832
+ });
1833
+ const spinner = p.spinner();
1834
+ spinner.start("Running React Native codegen");
1835
+ try {
1836
+ await execa("node", [
1837
+ path.join(reactNativePath, "scripts", "generate-codegen-artifacts.js"),
1838
+ "-p",
1839
+ projectRoot,
1840
+ "-o",
1841
+ sourceDir,
1842
+ "-t",
1843
+ "ios"
1844
+ ], {
1845
+ cwd: projectRoot,
1846
+ all: true
1847
+ });
1848
+ } catch (error) {
1849
+ spinner.error("React Native codegen failed");
1850
+ throw commandFailure("React Native codegen", error);
1851
+ }
1852
+ spinner.stop("React Native codegen done");
1853
+ };
1854
+ /**
1855
+ * The environment `pod install` runs with, and whether codegen runs first.
1856
+ *
1857
+ * From React Native 0.79, `RCT_IGNORE_PODS_DEPRECATION=1` silences the
1858
+ * deprecation notice for calling `pod install` directly and also sets
1859
+ * `RCT_SKIP_CODEGEN=1`, because the React Native CLI runs codegen itself
1860
+ * first. Hot Updater sets it the same way and runs codegen too, unless the
1861
+ * user's `RCT_SKIP_CODEGEN=1` takes codegen over. Before 0.79, and when the
1862
+ * version is unknown, CocoaPods runs codegen. A user's value of a flag wins.
1863
+ */
1864
+ const resolvePodInstallPlan = ({ version, env }) => {
1865
+ const podsSkipCodegen = version.major > 0 || version.minor >= 79;
1866
+ const usePrebuiltReactNative = version.major > 0 || version.minor >= 81;
1867
+ const ignorePodsDeprecation = env["RCT_IGNORE_PODS_DEPRECATION"] ?? (podsSkipCodegen ? "1" : void 0);
1868
+ return {
1869
+ runCodegen: podsSkipCodegen && ignorePodsDeprecation === "1" && env["RCT_SKIP_CODEGEN"] !== "1",
1870
+ env: {
1871
+ ...ignorePodsDeprecation !== void 0 && { RCT_IGNORE_PODS_DEPRECATION: ignorePodsDeprecation },
1872
+ RCT_USE_RN_DEP: env["RCT_USE_RN_DEP"] ?? (usePrebuiltReactNative ? "1" : "0"),
1873
+ RCT_USE_PREBUILT_RNCORE: env["RCT_USE_PREBUILT_RNCORE"] ?? (usePrebuiltReactNative ? "1" : "0")
1874
+ }
1875
+ };
1876
+ };
1877
+ //#endregion
1878
+ //#region src/utils/platform.ts
1879
+ /**
1880
+ * Platform configurations for different Apple platforms
1881
+ */
1882
+ const platformConfigs = { ios: {
1883
+ name: "ios",
1884
+ deviceSdk: "iphoneos",
1885
+ simulatorSdk: "iphonesimulator",
1886
+ supportsSimulator: true,
1887
+ deviceDestination: "platform=iOS",
1888
+ simulatorDestination: "platform=iOS Simulator"
1889
+ } };
1890
+ //#endregion
1891
+ //#region src/utils/destination.ts
1892
+ const buildDestinationString = ({ deviceType, platform, useGeneric }) => `${useGeneric ? "generic/" : ""}${deviceType === "device" ? platformConfigs[platform].deviceDestination : platformConfigs[platform].simulatorDestination}`;
1893
+ /**
1894
+ * Resolves IosBuildDestination to xcodebuild destination format
1895
+ */
1896
+ const resolveDestination = ({ destination, useGeneric }) => {
1897
+ if (typeof destination === "object") {
1898
+ if ("id" in destination) return `id=${destination.id}`;
1899
+ if ("name" in destination) return `name=${destination.name}`;
1900
+ }
1901
+ switch (destination) {
1902
+ case "ios-device": return buildDestinationString({
1903
+ platform: "ios",
1904
+ deviceType: "device",
1905
+ useGeneric
1906
+ });
1907
+ case "ios-simulator": return buildDestinationString({
1908
+ platform: "ios",
1909
+ deviceType: "simulator",
1910
+ useGeneric
1911
+ });
1912
+ }
1913
+ };
1914
+ const resolveDestinations = ({ destinations, useGeneric }) => {
1915
+ return destinations.map((destination) => resolveDestination({
1916
+ destination,
1917
+ useGeneric
1918
+ }));
1919
+ };
1920
+ const getDefaultDestination = ({ platform, useGeneric, deviceType }) => {
1921
+ return buildDestinationString({
1922
+ deviceType,
1923
+ platform,
1924
+ useGeneric
1925
+ });
1926
+ };
1927
+ //#endregion
1928
+ //#region src/utils/parseXcodeProjectInfo.ts
1929
+ const parseXcodeProjectInfo = async (sourceDir) => {
1930
+ const files = await fs.promises.readdir(sourceDir);
1931
+ const workspace = files.find((file) => file.endsWith(".xcworkspace"));
1932
+ if (workspace) return {
1933
+ isWorkspace: true,
1934
+ name: workspace,
1935
+ path: path.join(sourceDir, workspace)
1936
+ };
1937
+ const project = files.find((file) => file.endsWith(".xcodeproj"));
1938
+ if (project) return {
1939
+ isWorkspace: false,
1940
+ name: project,
1941
+ path: path.join(sourceDir, project)
1942
+ };
1943
+ throw new Error(`No Xcode project or workspace found in ${sourceDir}`);
1944
+ };
1945
+ //#endregion
1946
+ //#region src/utils/prettifyXcodebuildError.ts
1947
+ const prettifyXcodebuildError = (error) => {
1948
+ if (error instanceof BuildFailedError) {
1949
+ const errorLines = error.summary.join("\n");
1950
+ const hint = mentionsProgramLicenseAgreement(errorLines) ? PROGRAM_LICENSE_AGREEMENT_HINT : errorLines.includes("error: No profiles for") || errorLines.includes("error: Provisioning profile") ? "No valid provisioning profile is set in the project.\nCheck the Signing & Capabilities tab in Xcode." : null;
1951
+ return new BuildFailedError(hint ?? error.message, {
1952
+ logPath: error.logPath,
1953
+ summary: error.summary,
1954
+ hint,
1955
+ cause: error.cause
1956
+ });
1957
+ }
1958
+ return /* @__PURE__ */ new Error(`Xcodebuild failed: ${error}`);
1959
+ };
1960
+ //#endregion
1961
+ //#region src/utils/xcodebuildPhase.ts
1962
+ /** The `(in target 'X' from project 'Y')` that ends an action's line. */
1963
+ const TARGET = /\(in target '([^']+)' from project '[^']+'\)\s*$/;
1964
+ /** A `PhaseScriptExecution` line's script phase, its spaces escaped. */
1965
+ const SCRIPT = /^PhaseScriptExecution ((?:\\.|[^\s\\])+)/;
1966
+ /** A batched `SwiftCompile`'s files: `Compiling\ A.swift,\ B.swift`. */
1967
+ const SWIFT_BATCH = /^SwiftCompile \S+ \S+ Compiling\\ ((?:\\.|[^\s\\])+)/;
1968
+ const unescape = (value) => value.replace(/\\(.)/g, "$1");
1969
+ /** Actions whose lines say what xcodebuild is doing, by their first word. */
1970
+ const ACTIONS = {
1971
+ CompileAssetCatalog: "Compiling assets",
1972
+ CompileAssetCatalogVariant: "Compiling assets",
1973
+ LinkAssetCatalog: "Compiling assets",
1974
+ CompileStoryboard: "Compiling storyboards",
1975
+ CompileXIB: "Compiling storyboards",
1976
+ LinkStoryboards: "Compiling storyboards",
1977
+ Ld: "Linking",
1978
+ Libtool: "Linking",
1979
+ CodeSign: "Signing",
1980
+ ProcessInfoPlistFile: "Processing",
1981
+ ProcessProductPackaging: "Processing",
1982
+ ProcessProductPackagingDER: "Processing",
1983
+ CopySwiftLibs: "Copying",
1984
+ CpResource: "Copying",
1985
+ GenerateDSYMFile: "Generating dSYM",
1986
+ Strip: "Stripping",
1987
+ Validate: "Validating"
1988
+ };
1989
+ const COMPILES = /* @__PURE__ */ new Set([
1990
+ "CompileC",
1991
+ "SwiftCompile",
1992
+ "CompileSwift"
1993
+ ]);
1994
+ const PRECOMPILES = /* @__PURE__ */ new Set([
1995
+ "PrecompileModule",
1996
+ "ScanDependencies",
1997
+ "SwiftExplicitDependencyGeneratePcm",
1998
+ "SwiftExplicitDependencyCompileModuleFromInterface"
1999
+ ]);
2000
+ const plural = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
2001
+ /**
2002
+ * Reads the phase of an `xcodebuild` build, archive, or export from its raw
2003
+ * output: `Compiling React-Core · 412 files`, `Linking CodexRelay`,
2004
+ * `Signing CodexRelay`, `Bundling JavaScript`, with the target each
2005
+ * action's line names.
2006
+ */
2007
+ const createXcodebuildPhaseReader = () => {
2008
+ let compiled = 0;
2009
+ let precompiled = 0;
2010
+ return (line) => {
2011
+ const space = line.indexOf(" ");
2012
+ const action = space === -1 ? line : line.slice(0, space);
2013
+ const target = TARGET.exec(line)?.[1];
2014
+ const withTarget = (phase) => target ? `${phase} ${target}` : phase;
2015
+ if (COMPILES.has(action)) {
2016
+ const batch = SWIFT_BATCH.exec(line)?.[1];
2017
+ compiled += batch ? unescape(batch).split(",").length : 1;
2018
+ return `${withTarget("Compiling")} · ${plural(compiled, "file")}`;
2019
+ }
2020
+ if (PRECOMPILES.has(action)) {
2021
+ precompiled += 1;
2022
+ return `Precompiling modules · ${precompiled}`;
2023
+ }
2024
+ if (action === "PhaseScriptExecution") {
2025
+ const script = unescape(SCRIPT.exec(line)?.[1] ?? "");
2026
+ if (script === "Bundle React Native code and images") return "Bundling JavaScript";
2027
+ return script ? `Running ${script}` : withTarget("Running a script");
2028
+ }
2029
+ const phase = ACTIONS[action];
2030
+ if (phase) return withTarget(phase);
2031
+ if (line === "Prepare packages" || line.startsWith("Resolve Package")) return "Resolving packages";
2032
+ if (line === "ComputeTargetDependencyGraph") return "Planning the build";
2033
+ };
2034
+ };
2035
+ //#endregion
2036
+ //#region src/utils/createXcodebuildLogger.ts
2037
+ const createXcodebuildLogger = ({ logPrefix, logFilePath }) => new BuildLogger({
2038
+ logPrefix,
2039
+ logFilePath,
2040
+ createPhaseReader: createXcodebuildPhaseReader,
2041
+ failureSummary: {
2042
+ lines: [/(^|:\s)error: /, /^\*\* [A-Z ]+ FAILED \*\*$/],
2043
+ blocks: [{
2044
+ start: "The following build commands failed:",
2045
+ end: /^\(\d+ failures?\)$/,
2046
+ includeEnd: true
2047
+ }, {
2048
+ start: /^error: exportArchive /,
2049
+ end: /^$/,
2050
+ includeEnd: false
2051
+ }]
2052
+ }
2053
+ });
2054
+ //#endregion
2055
+ //#region src/utils/runXcodebuildWithLogging.ts
2056
+ const TERMINATION_SIGNALS$1 = ["SIGINT", "SIGTERM"];
2057
+ const createRawXcodebuildProcess = ({ args, env, sourceDir }) => {
2058
+ return execa("xcodebuild", args, {
2059
+ cwd: sourceDir,
2060
+ all: true,
2061
+ buffer: false,
2062
+ env: {
2063
+ ...process.env,
2064
+ ...env,
2065
+ NSUnbufferedIO: "YES"
2066
+ }
2067
+ });
2068
+ };
2069
+ /** Why xcodebuild failed, without its command line. */
2070
+ const describeFailure = (error) => {
2071
+ if (error instanceof ExecaError) {
2072
+ if (error.signal) return `xcodebuild was stopped by ${error.signal}.`;
2073
+ if (error.exitCode !== void 0) return `xcodebuild exited with code ${error.exitCode}.`;
2074
+ }
2075
+ return error instanceof Error ? error.message : String(error);
2076
+ };
2077
+ /**
2078
+ * Runs xcodebuild as a step titled `title`: its live line shows the build's
2079
+ * phase, the log file keeps the command and the whole output, and a failure
2080
+ * prints the output's errors and the log's path on stderr.
2081
+ */
2082
+ const runXcodebuildWithLogging = async ({ args, env, sourceDir, title, successMessage, failureMessage, logPrefix, logFilePath, header = [] }) => {
2083
+ const logger = createXcodebuildLogger({
2084
+ logPrefix,
2085
+ logFilePath
2086
+ });
2087
+ await logger.start({
2088
+ title,
2089
+ header: [
2090
+ ...header,
2091
+ `$ ${formatCommand(["xcodebuild", ...args])}`,
2092
+ ""
2093
+ ]
2094
+ });
2095
+ const activeProcesses = [];
2096
+ const terminateActiveProcesses = () => {
2097
+ for (const activeProcess of activeProcesses) activeProcess.kill();
2098
+ };
2099
+ for (const signal of TERMINATION_SIGNALS$1) process.once(signal, terminateActiveProcesses);
2100
+ try {
2101
+ const xcodebuildProcess = createRawXcodebuildProcess({
2102
+ args,
2103
+ env,
2104
+ sourceDir
2105
+ });
2106
+ activeProcesses.push(xcodebuildProcess);
2107
+ const xcodebuildOutput = xcodebuildProcess.all ?? xcodebuildProcess.stdout;
2108
+ const logging = xcodebuildOutput ? logger.processStream(xcodebuildOutput) : Promise.resolve();
2109
+ const [xcodebuildResult, loggingResult] = await Promise.allSettled([xcodebuildProcess, logging]);
2110
+ if (xcodebuildResult.status === "rejected") throw xcodebuildResult.reason;
2111
+ if (loggingResult.status === "rejected") throw loggingResult.reason;
2112
+ logger.stop(successMessage);
2113
+ return { logFilePath: logger.logFilePath };
2114
+ } catch (error) {
2115
+ logger.writeError(error);
2116
+ const reason = describeFailure(error);
2117
+ logger.stop(`${failureMessage} · ${reason.replace(/\.$/, "")}`, false);
2118
+ throw new BuildFailedError(`${failureMessage}: ${reason}`, {
2119
+ logPath: logger.logPath,
2120
+ summary: logger.failureSummary,
2121
+ cause: error
2122
+ });
2123
+ } finally {
2124
+ for (const signal of TERMINATION_SIGNALS$1) process.off(signal, terminateActiveProcesses);
2125
+ await logger.close();
2126
+ }
2127
+ };
2128
+ //#endregion
2129
+ //#region src/utils/writeBuildXcconfig.ts
2130
+ const SDK_CONDITIONS = [
2131
+ "",
2132
+ "[sdk=iphoneos*]",
2133
+ "[sdk=iphonesimulator*]"
2134
+ ];
2135
+ /**
2136
+ * Finds a setting of `keys` that an included xcconfig sets with a condition
2137
+ * the build xcconfig does not, such as `[config=Release]` or `[arch=arm64]`,
2138
+ * which would outrank the build's own. It follows `#include`s, which are
2139
+ * relative to the including file.
2140
+ */
2141
+ const findConditionalSetting = async (files, keys, visited = /* @__PURE__ */ new Set()) => {
2142
+ for (const file of files) {
2143
+ if (visited.has(file) || !fs.existsSync(file)) continue;
2144
+ visited.add(file);
2145
+ const lines = (await fs.promises.readFile(file, "utf-8")).split("\n");
2146
+ for (const [index, line] of lines.entries()) {
2147
+ const include = line.match(/^\s*#include\??\s*"([^"]+)"/)?.[1];
2148
+ if (include) {
2149
+ const found = await findConditionalSetting([path.resolve(path.dirname(file), include)], keys, visited);
2150
+ if (found) return found;
2151
+ continue;
2152
+ }
2153
+ const [, key, conditions] = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)((?:\[[^\]]*\])+)\s*=/) ?? [];
2154
+ if (key && keys.includes(key) && !SDK_CONDITIONS.includes(conditions)) return `${file}:${index + 1} sets ${key}${conditions}`;
2155
+ }
2156
+ }
2157
+ };
2158
+ /**
2159
+ * Writes the xcconfig a build loads, which sets the CLI's build settings
2160
+ * over every other. xcodebuild ranks an `-xcconfig`'s settings above the
2161
+ * command line's, so the scheme's `xcconfig` and each `-xcconfig` in
2162
+ * `extraParams` are included, in order, before `settings`, and the build
2163
+ * loads only this one.
2164
+ */
2165
+ const writeBuildXcconfig = async ({ directory, sourceDir, xcconfig, extraParams = [], settings }) => {
2166
+ const included = xcconfig ? [xcconfig] : [];
2167
+ const otherParams = [];
2168
+ for (let i = 0; i < extraParams.length; i++) if (extraParams[i] === "-xcconfig" && i + 1 < extraParams.length) included.push(extraParams[++i]);
2169
+ else otherParams.push(extraParams[i]);
2170
+ const includedFiles = included.map((file) => path.resolve(sourceDir, file));
2171
+ const conditional = await findConditionalSetting(includedFiles, Object.keys(settings));
2172
+ if (conditional) throw new Error(`${conditional}, which would outrank the value the build sets. Set it without that condition, or remove it.`);
2173
+ const buildXcconfig = path.join(directory, "HotUpdater.xcconfig");
2174
+ await fs.promises.writeFile(buildXcconfig, [
2175
+ ...includedFiles.map((file) => `#include "${file}"`),
2176
+ ...Object.entries(settings).flatMap(([key, value]) => SDK_CONDITIONS.map((condition) => `${key}${condition} = ${value}`)),
2177
+ ""
2178
+ ].join("\n"));
2179
+ return {
2180
+ xcconfig: buildXcconfig,
2181
+ extraParams: otherParams
2182
+ };
2183
+ };
2184
+ /**
2185
+ * Automatic signing over a target set to manual signing, whose provisioning
2186
+ * profile and identity Xcode would otherwise report as conflicting.
2187
+ */
2188
+ const AUTOMATIC_SIGNING = {
2189
+ CODE_SIGN_STYLE: "Automatic",
2190
+ PROVISIONING_PROFILE: "",
2191
+ PROVISIONING_PROFILE_SPECIFIER: "",
2192
+ CODE_SIGN_IDENTITY: "Apple Development"
2193
+ };
2194
+ /** The sandbox layer's sources, by the file names the podspec excludes. */
2195
+ const SANDBOX_SOURCES = "HotUpdaterSandbox*";
2196
+ /** What each of those sources is wrapped in: without it, they compile to nothing. */
2197
+ const SANDBOX_CONDITION = "HOT_UPDATER_SANDBOX_LAYER";
2198
+ /**
2199
+ * The settings a build sets over the scheme's: the MIN_BUNDLE_ID the CLI
2200
+ * issues and reports, and automatic signing when an App Store Connect API key
2201
+ * signs, which a target set to manual signing would not use.
2202
+ *
2203
+ * A sandbox scheme brings the sandbox layer's sources back, and sets the
2204
+ * condition they compile under, which nothing else sets: any build can undo the
2205
+ * podspec's exclusion, and those sources then compile to nothing. Any other scheme
2206
+ * excludes them again: a scheme's `xcconfig`, which outranks the pod's settings
2207
+ * on every target, would otherwise replace the podspec's exclusion, and the
2208
+ * layer would compile into a store build.
2209
+ */
2210
+ const buildSettingsOverScheme = ({ minBundleId, authenticationArgs, sandbox = false }) => ({
2211
+ HOT_UPDATER_MIN_BUNDLE_ID: minBundleId,
2212
+ ...authenticationArgs ? AUTOMATIC_SIGNING : {},
2213
+ ...sandbox ? {
2214
+ INCLUDED_SOURCE_FILE_NAMES: SANDBOX_SOURCES,
2215
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: `$(inherited) ${SANDBOX_CONDITION}`,
2216
+ GCC_PREPROCESSOR_DEFINITIONS: `$(inherited) ${SANDBOX_CONDITION}=1`
2217
+ } : { EXCLUDED_SOURCE_FILE_NAMES: `$(inherited) ${SANDBOX_SOURCES}` }
2218
+ });
2219
+ //#endregion
2220
+ //#region src/builder/archiveXcodeProject.ts
2221
+ /**
2222
+ * Archives the scheme into `archiveDirectory`. The build's xcconfig is
2223
+ * written to a temporary directory, removed whether the archive succeeds or
2224
+ * not.
2225
+ */
2226
+ const archiveXcodeProject = async ({ sourceDir, archiveDirectory, platform, installPods, destination, extraParams, configuration, xcodeScheme, xcconfig, logPrefix, header = [], minBundleId, authenticationArgs, sandbox }) => {
2227
+ if (installPods) await installPodsIfNeeded(sourceDir);
2228
+ const xcodeProject = await parseXcodeProjectInfo(sourceDir);
2229
+ const archiveName = `${xcodeProject.name.replace(".xcworkspace", "").replace(".xcodeproj", "")}.xcarchive`;
2230
+ const archivePath = path.join(archiveDirectory, archiveName);
2231
+ const tmpDir = await createRandomTmpDir();
2232
+ try {
2233
+ const build = await writeBuildXcconfig({
2234
+ directory: tmpDir,
2235
+ sourceDir,
2236
+ xcconfig,
2237
+ extraParams,
2238
+ settings: buildSettingsOverScheme({
2239
+ minBundleId,
2240
+ authenticationArgs,
2241
+ sandbox
2242
+ })
2243
+ });
2244
+ const archiveArgs = prepareArchiveArgs({
2245
+ authenticationArgs,
2246
+ minBundleId,
2247
+ archivePath,
2248
+ platform,
2249
+ sourceDir,
2250
+ xcodeProject,
2251
+ configuration,
2252
+ extraParams: build.extraParams,
2253
+ destination,
2254
+ xcconfig: build.xcconfig,
2255
+ xcodeScheme
2256
+ });
2257
+ try {
2258
+ const { logFilePath } = await runXcodebuildWithLogging({
2259
+ args: archiveArgs,
2260
+ env: { HOT_UPDATER_MIN_BUNDLE_ID: minBundleId },
2261
+ title: `Archiving ${xcodeScheme}`,
2262
+ successMessage: `Archived ${xcodeScheme}`,
2263
+ failureMessage: "Archive failed",
2264
+ logPrefix,
2265
+ header: [
2266
+ ...header,
2267
+ `Project ${xcodeProject.name}`,
2268
+ `Scheme ${xcodeScheme}`,
2269
+ `Platform ${platform}`
2270
+ ],
2271
+ sourceDir
2272
+ });
2273
+ return {
2274
+ archivePath,
2275
+ logFilePath
2276
+ };
2277
+ } catch (error) {
2278
+ throw prettifyXcodebuildError(error);
2279
+ }
2280
+ } finally {
2281
+ await removeTmpDir(tmpDir);
2282
+ }
2283
+ };
2284
+ const prepareArchiveArgs = ({ xcodeScheme, archivePath, platform, sourceDir, xcodeProject, configuration = "Release", xcconfig, extraParams, destination = [], minBundleId, authenticationArgs }) => {
2285
+ const args = [
2286
+ xcodeProject.isWorkspace ? "-workspace" : "-project",
2287
+ path.join(sourceDir, xcodeProject.name),
2288
+ "-scheme",
2289
+ xcodeScheme,
2290
+ "-configuration",
2291
+ configuration,
2292
+ "archive",
2293
+ "-archivePath",
2294
+ archivePath,
2295
+ `HOT_UPDATER_MIN_BUNDLE_ID=${minBundleId}`
2296
+ ];
2297
+ if (authenticationArgs) args.push(...authenticationArgs);
2298
+ if (xcconfig) args.push("-xcconfig", xcconfig);
2299
+ if (extraParams) args.push(...extraParams);
2300
+ const resolvedDestinations = resolveDestinations({
2301
+ destinations: destination,
2302
+ useGeneric: true
2303
+ });
2304
+ if (resolvedDestinations.length === 0) resolvedDestinations.push(getDefaultDestination({
2305
+ deviceType: "device",
2306
+ platform,
2307
+ useGeneric: true
2308
+ }));
2309
+ for (const destination of resolvedDestinations) args.push("-destination", destination);
2310
+ return args;
2311
+ };
2312
+ //#endregion
2313
+ //#region src/builder/buildXcodeProject.ts
2314
+ /**
2315
+ * Builds the scheme in a temporary DerivedData directory, copies the built
2316
+ * `.app` to `outputDirectory`, and removes DerivedData, which takes 10 GB or
2317
+ * more, whether the build succeeds or not.
2318
+ */
2319
+ const buildXcodeProject = async ({ sourceDir, outputDirectory, platform, xcodeScheme, configuration, deviceType, logPrefix, destination = [], useGenericDestination = false, installPods, xcconfig, extraParams, minBundleId, authenticationArgs, sandbox, header = [] }) => {
2320
+ if (installPods) await installPodsIfNeeded(sourceDir);
2321
+ const xcodeProject = await parseXcodeProjectInfo(sourceDir);
2322
+ const tmpDir = await createRandomTmpDir();
2323
+ try {
2324
+ const derivedDataPath = path.join(tmpDir, "DerivedData");
2325
+ const resolvedDestinations = resolveDestinations({
2326
+ destinations: destination,
2327
+ useGeneric: useGenericDestination
2328
+ });
2329
+ if (resolvedDestinations.length === 0) resolvedDestinations.push(getDefaultDestination({
2330
+ deviceType,
2331
+ platform,
2332
+ useGeneric: useGenericDestination
2333
+ }));
2334
+ const build = await writeBuildXcconfig({
2335
+ directory: tmpDir,
2336
+ sourceDir,
2337
+ xcconfig,
2338
+ extraParams,
2339
+ settings: buildSettingsOverScheme({
2340
+ minBundleId,
2341
+ authenticationArgs,
2342
+ sandbox
2343
+ })
2344
+ });
2345
+ const buildArgs = prepareBuildArgs({
2346
+ authenticationArgs,
2347
+ xcconfig: build.xcconfig,
2348
+ minBundleId,
2349
+ configuration,
2350
+ derivedDataPath,
2351
+ deviceType,
2352
+ resolvedDestinations,
2353
+ extraParams: build.extraParams,
2354
+ platform,
2355
+ xcodeScheme,
2356
+ sourceDir,
2357
+ xcodeProject
2358
+ });
2359
+ let builtAppPath;
2360
+ let logFilePath;
2361
+ try {
2362
+ ({logFilePath} = await runXcodebuildWithLogging({
2363
+ args: buildArgs,
2364
+ env: { HOT_UPDATER_MIN_BUNDLE_ID: minBundleId },
2365
+ sourceDir,
2366
+ logPrefix,
2367
+ header: [
2368
+ ...header,
2369
+ `Project ${xcodeProject.name}`,
2370
+ `Scheme ${xcodeScheme}`,
2371
+ `Configuration ${configuration}`,
2372
+ `Platform ${platform}`,
2373
+ `Device type ${deviceType}`
2374
+ ],
2375
+ title: `Building ${xcodeScheme}`,
2376
+ successMessage: `Built ${xcodeScheme}`,
2377
+ failureMessage: "Build failed"
2378
+ }));
2379
+ ({appPath: builtAppPath} = await getBuildSettings({
2380
+ configuration,
2381
+ derivedDataPath,
2382
+ resolvedDestinations,
2383
+ xcodeScheme,
2384
+ sourceDir,
2385
+ xcodeProject,
2386
+ xcconfig: build.xcconfig,
2387
+ extraParams: build.extraParams
2388
+ }));
2389
+ } catch (error) {
2390
+ throw prettifyXcodebuildError(error);
2391
+ }
2392
+ const appPath = path.join(outputDirectory, path.basename(builtAppPath));
2393
+ await fs.promises.cp(builtAppPath, appPath, { recursive: true });
2394
+ return {
2395
+ appPath,
2396
+ logFilePath
2397
+ };
2398
+ } finally {
2399
+ await removeTmpDir(tmpDir);
2400
+ }
2401
+ };
2402
+ const prepareBuildArgs = ({ xcodeProject, sourceDir, platform, xcodeScheme, configuration, deviceType, resolvedDestinations, derivedDataPath, extraParams, minBundleId, authenticationArgs, xcconfig }) => {
2403
+ const sdk = deviceType === "simulator" ? platformConfigs[platform].simulatorSdk : platformConfigs[platform].deviceSdk;
2404
+ const args = [
2405
+ xcodeProject.isWorkspace ? "-workspace" : "-project",
2406
+ path.join(sourceDir, xcodeProject.name),
2407
+ "-scheme",
2408
+ xcodeScheme,
2409
+ "-configuration",
2410
+ configuration,
2411
+ "-sdk",
2412
+ sdk,
2413
+ "-derivedDataPath",
2414
+ derivedDataPath,
2415
+ `HOT_UPDATER_MIN_BUNDLE_ID=${minBundleId}`,
2416
+ "build"
2417
+ ];
2418
+ if (authenticationArgs) args.push(...authenticationArgs);
2419
+ args.push("-xcconfig", xcconfig);
2420
+ if (extraParams) args.push(...extraParams);
2421
+ for (const dest of resolvedDestinations) args.push("-destination", dest);
2422
+ return args;
2423
+ };
2424
+ const BUILD_SETTING = /^[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])*=/u;
2425
+ const getBuildSettings = async ({ xcodeProject, sourceDir, xcodeScheme, configuration, resolvedDestinations, derivedDataPath, xcconfig, extraParams }) => {
2426
+ const destinationArgs = resolvedDestinations.flatMap((dest) => ["-destination", dest]);
2427
+ const { stdout: buildSettings } = await execa("xcodebuild", [
2428
+ xcodeProject.isWorkspace ? "-workspace" : "-project",
2429
+ xcodeProject.name,
2430
+ "-scheme",
2431
+ xcodeScheme,
2432
+ "-configuration",
2433
+ configuration,
2434
+ ...destinationArgs,
2435
+ "-derivedDataPath",
2436
+ derivedDataPath,
2437
+ "-xcconfig",
2438
+ xcconfig,
2439
+ ...extraParams.filter((param) => BUILD_SETTING.test(param)),
2440
+ "-showBuildSettings",
2441
+ "-json"
2442
+ ], { cwd: sourceDir });
2443
+ const settings = JSON.parse(buildSettings).filter(({ target }) => target !== "React" && target !== "React-Core");
2444
+ if (settings.length === 0) throw new Error("Failed to get build settings for your project");
2445
+ const targetSettings = settings[0].buildSettings;
2446
+ const wrapperExtension = targetSettings.WRAPPER_EXTENSION;
2447
+ if (wrapperExtension !== "app" && wrapperExtension !== "framework") throw new Error(`Expected wrapper extension to be "app" or "framework" but found: ${wrapperExtension}`);
2448
+ const targetBuildDir = targetSettings.TARGET_BUILD_DIR;
2449
+ const executableFolderPath = targetSettings.EXECUTABLE_FOLDER_PATH;
2450
+ const fullProductName = targetSettings.FULL_PRODUCT_NAME;
2451
+ const infoPlistPath = targetSettings.INFOPLIST_PATH;
2452
+ if (!targetBuildDir || !executableFolderPath || !fullProductName) throw new Error("Failed to get build paths from build settings");
2453
+ return {
2454
+ appPath: path.join(targetBuildDir, executableFolderPath),
2455
+ infoPlistPath: path.join(targetBuildDir, infoPlistPath)
2456
+ };
2457
+ };
2458
+ //#endregion
2459
+ //#region src/builder/exportXcodeArchive.ts
2460
+ /** Exports the archive into `exportPath`. */
2461
+ const exportXcodeArchive = async ({ archivePath, exportPath, sourceDir, exportExtraParams, exportOptionsPlist, logPrefix, logFilePath, title, authenticationArgs }) => {
2462
+ const exportArgs = prepareExportArgs({
2463
+ authenticationArgs,
2464
+ archivePath,
2465
+ exportPath,
2466
+ exportOptionsPlist,
2467
+ exportExtraParams
2468
+ });
2469
+ try {
2470
+ await runXcodebuildWithLogging({
2471
+ args: exportArgs,
2472
+ sourceDir,
2473
+ title: `Exporting ${title}`,
2474
+ successMessage: `Exported ${title}`,
2475
+ failureMessage: "Export failed",
2476
+ logPrefix,
2477
+ logFilePath
2478
+ });
2479
+ return { exportPath };
2480
+ } catch (error) {
2481
+ throw prettifyXcodebuildError(error);
2482
+ }
2483
+ };
2484
+ const prepareExportArgs = ({ exportPath, archivePath, exportExtraParams, exportOptionsPlist, authenticationArgs }) => {
2485
+ const args = [
2486
+ "-exportArchive",
2487
+ "-archivePath",
2488
+ archivePath,
2489
+ "-exportPath",
2490
+ exportPath
2491
+ ];
2492
+ if (authenticationArgs) args.push(...authenticationArgs);
2493
+ if (exportExtraParams) args.push(...exportExtraParams);
2494
+ args.push("-exportOptionsPlist", exportOptionsPlist);
2495
+ return args;
2496
+ };
2497
+ //#endregion
2498
+ //#region src/utils/assertXcodebuildExist.ts
2499
+ const assertXcodebuildExist = async () => {
1770
2500
  try {
1771
- await runConcurrently(operations, UPLOAD_CONCURRENCY, async (operation, index) => {
1772
- const body = Buffer.alloc(operation.length);
1773
- const { bytesRead } = await file.read(body, 0, operation.length, operation.offset);
1774
- if (bytesRead !== operation.length) throw new Error(`${path$1.basename(ipaPath)} changed while it was uploading.`);
1775
- const headers = {};
1776
- for (const { name, value } of operation.requestHeaders ?? []) headers[name] = value;
1777
- for (let attempt = 1;; attempt++) {
1778
- const response = await fetch(operation.url, {
1779
- method: operation.method,
1780
- headers,
1781
- body
1782
- }).catch((error) => error);
1783
- if (!(response instanceof Error) && response.ok) return;
1784
- if (!(response instanceof Error || isRetryableStatus(response.status)) || attempt === UPLOAD_ATTEMPTS) throw new Error(`Uploading part ${index + 1} of ${operations.length} failed: ${response instanceof Error ? response.message : `HTTP ${response.status}`}.`);
1785
- await sleep(retryDelayMs(response, attempt));
1786
- }
1787
- });
1788
- } finally {
1789
- await file.close();
2501
+ await execa("which", ["xcodebuild"]);
2502
+ } catch {
2503
+ p.log.error(`${colors.blueBright("xcodebuild")} resolve failed. Ensure that xcode is installed on your machine or xcodebuild is included in your path`);
2504
+ process.exit(1);
1790
2505
  }
1791
2506
  };
1792
2507
  //#endregion
@@ -1812,7 +2527,7 @@ const restoreLive = () => {
1812
2527
  * such as two self-hosted runner instances, would each restore the other's
1813
2528
  * keychain. It is in the user's caches, whatever TMPDIR a runner sets.
1814
2529
  */
1815
- const defaultLockPath = () => path$1.join(os$1.homedir(), "Library", "Caches", "hot-updater", "signing-keychain.lock");
2530
+ const defaultLockPath = () => path.join(os.homedir(), "Library", "Caches", "hot-updater", "signing-keychain.lock");
1816
2531
  /** lockf's exit code when `-t 0` finds the lock held. */
1817
2532
  const EX_TEMPFAIL = 75;
1818
2533
  /**
@@ -1860,10 +2575,10 @@ const holdWithLockf = (lockPath, wait) => new Promise((resolve, reject) => {
1860
2575
  });
1861
2576
  });
1862
2577
  const acquireWithLockf = async (lockPath) => {
1863
- await fs$1.promises.mkdir(path$1.dirname(lockPath), { recursive: true });
2578
+ await fs.promises.mkdir(path.dirname(lockPath), { recursive: true });
1864
2579
  const release = await holdWithLockf(lockPath, false);
1865
2580
  if (release) return release;
1866
- p.log.info("Waiting for another build that signs in a keychain of its own under this macOS user.");
2581
+ p.log.info("Waiting for another build's signing keychain under this macOS user.");
1867
2582
  return await holdWithLockf(lockPath, true);
1868
2583
  };
1869
2584
  /**
@@ -1872,7 +2587,7 @@ const acquireWithLockf = async (lockPath) => {
1872
2587
  * still finds a signing identity a self-hosted runner keeps and creates a
1873
2588
  * new one only when it has none.
1874
2589
  */
1875
- const createSigningKeychain = async ({ security = runSecurity, directory = os$1.tmpdir(), lockPath = defaultLockPath(), acquireLock = acquireWithLockf } = {}) => {
2590
+ const createSigningKeychain = async ({ security = runSecurity, directory = os.tmpdir(), lockPath = defaultLockPath(), acquireLock = acquireWithLockf } = {}) => {
1876
2591
  if (live) throw new Error("A signing keychain is already in use by this process.");
1877
2592
  live = { restore: () => void 0 };
1878
2593
  let releaseLock;
@@ -1901,7 +2616,7 @@ const createSigningKeychain = async ({ security = runSecurity, directory = os$1.
1901
2616
  await releaseLock();
1902
2617
  throw error;
1903
2618
  }
1904
- const keychainPath = path$1.join(directory, `hot-updater-${crypto$1.randomBytes(6).toString("hex")}.keychain-db`);
2619
+ const keychainPath = path.join(directory, `hot-updater-${crypto$1.randomBytes(6).toString("hex")}.keychain-db`);
1905
2620
  const password = crypto$1.randomBytes(24).toString("base64url");
1906
2621
  registerSecretValue(password);
1907
2622
  const restoreArgs = [
@@ -1934,7 +2649,12 @@ const createSigningKeychain = async ({ security = runSecurity, directory = os$1.
1934
2649
  live = void 0;
1935
2650
  process.off("exit", restoreLive);
1936
2651
  await releaseLock().catch(() => void 0);
1937
- if (failures.length > 0) p.log.warn(`Restoring the keychains after the build failed (${failures.join("; ")}). Check \`security list-keychains -d user\` and \`security default-keychain -d user\`, and delete ${keychainPath} if it is left.`);
2652
+ if (failures.length > 0) p.log.warn([
2653
+ "Couldn't restore the keychains after the build.",
2654
+ ...failures,
2655
+ "Check security list-keychains -d user and default-keychain -d user,",
2656
+ `and delete ${keychainPath} if it is left.`
2657
+ ].join("\n"));
1938
2658
  })();
1939
2659
  return disposal;
1940
2660
  };
@@ -1979,170 +2699,808 @@ const createSigningKeychain = async ({ security = runSecurity, directory = os$1.
1979
2699
  return {
1980
2700
  path: keychainPath,
1981
2701
  certificates: async () => {
2702
+ const identities = new Set([...(await security([
2703
+ "find-identity",
2704
+ "-p",
2705
+ "codesigning",
2706
+ keychainPath
2707
+ ])).matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s/gm)].map((match) => match[1]));
2708
+ if (identities.size === 0) return [];
1982
2709
  return ((await security([
1983
2710
  "find-certificate",
1984
2711
  "-a",
1985
2712
  "-p",
1986
2713
  keychainPath
1987
- ])).match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g) ?? []).map((pem) => {
2714
+ ])).match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g) ?? []).flatMap((pem) => {
1988
2715
  const certificate = new crypto$1.X509Certificate(pem);
1989
- return {
2716
+ if (!identities.has(certificate.fingerprint.replaceAll(":", ""))) return [];
2717
+ return [{
1990
2718
  serialNumber: normalizeSerial(certificate.serialNumber),
1991
2719
  commonName: certificate.subject.match(/^CN=(.*)$/m)?.[1] ?? certificate.subject
1992
- };
2720
+ }];
1993
2721
  });
1994
2722
  },
1995
2723
  dispose
1996
2724
  };
1997
2725
  };
2726
+ /** A request App Store Connect refused, in one line. */
2727
+ var AppStoreConnectRefusal = class extends Error {
2728
+ /** Whether the team has a Program License Agreement to accept. */
2729
+ agreement;
2730
+ constructor(message, agreement) {
2731
+ super(message);
2732
+ this.agreement = agreement;
2733
+ }
2734
+ };
2735
+ const refusal$1 = async (action, response) => {
2736
+ const body = await response.json().catch(() => void 0);
2737
+ return new AppStoreConnectRefusal(`${action} failed (HTTP ${response.status}).`, isProgramLicenseAgreementError(Array.isArray(body?.errors) ? body.errors : []));
2738
+ };
2739
+ /**
2740
+ * Revokes the certificates Xcode created in the build's keychain, whose
2741
+ * private keys the keychain's deletion destroys: on a runner that starts
2742
+ * empty, Xcode creates a development certificate for every build, and App
2743
+ * Store Connect refuses new ones once a team has its maximum. Each is found
2744
+ * in the team's certificates by serial number. A revocation that fails is
2745
+ * reported with each certificate's name and serial and where to revoke it
2746
+ * by hand, and never fails the build.
2747
+ */
2748
+ const revokeKeychainCertificates = async ({ certificates, apiKey, privateKey, fetch = globalThis.fetch }) => {
2749
+ const revoked = [];
2750
+ const failed = [];
2751
+ /** Why none could be revoked: the token or the listing failed. */
2752
+ let reason;
2753
+ let agreement = false;
2754
+ if (certificates.length === 0) return {
2755
+ revoked: [],
2756
+ failed: []
2757
+ };
2758
+ try {
2759
+ const token = createAppStoreConnectToken({
2760
+ privateKey: privateKey ?? crypto$1.createPrivateKey(await fs.promises.readFile(apiKey.keyPath, "utf-8")),
2761
+ keyId: apiKey.keyId,
2762
+ issuerId: apiKey.issuerId
2763
+ });
2764
+ registerSecretValue(token);
2765
+ const headers = { Authorization: `Bearer ${token}` };
2766
+ const idsBySerial = /* @__PURE__ */ new Map();
2767
+ let next = `${API_URL}/v1/certificates?${new URLSearchParams({
2768
+ "fields[certificates]": "serialNumber",
2769
+ limit: "200"
2770
+ })}`;
2771
+ while (next) {
2772
+ const response = await fetch(next, { headers });
2773
+ if (!response.ok) throw await refusal$1("Listing the team's certificates", response);
2774
+ const body = await response.json();
2775
+ for (const { id, attributes } of body.data ?? []) if (attributes?.serialNumber) idsBySerial.set(normalizeSerial(attributes.serialNumber), id);
2776
+ next = body.links?.next;
2777
+ }
2778
+ for (const certificate of certificates) {
2779
+ const id = idsBySerial.get(certificate.serialNumber);
2780
+ if (id === void 0) continue;
2781
+ const response = await fetch(`${API_URL}/v1/certificates/${id}`, {
2782
+ method: "DELETE",
2783
+ headers
2784
+ });
2785
+ if (response.ok || response.status === 404) revoked.push(certificate);
2786
+ else {
2787
+ agreement ||= (await refusal$1("Revoking", response)).agreement;
2788
+ failed.push({
2789
+ certificate,
2790
+ status: response.status
2791
+ });
2792
+ }
2793
+ }
2794
+ } catch (error) {
2795
+ reason = error instanceof Error ? error.message : String(error);
2796
+ agreement ||= error instanceof AppStoreConnectRefusal && error.agreement;
2797
+ for (const certificate of certificates) if (!revoked.includes(certificate)) failed.push({ certificate });
2798
+ }
2799
+ const describe = ({ commonName, serialNumber }) => `${commonName} (serial ${serialNumber})`;
2800
+ if (revoked.length > 0) p.log.info(["Revoked the certificates Xcode created for this build:", ...revoked.flatMap(({ commonName, serialNumber }) => [commonName, `Serial ${serialNumber}`])].join("\n"));
2801
+ if (failed.length > 0) p.log.warn([
2802
+ "Couldn't revoke the certificates Xcode created for this build.",
2803
+ ...reason === void 0 ? [] : [reason],
2804
+ ...agreement ? [PROGRAM_LICENSE_AGREEMENT_HINT] : [],
2805
+ ...failed.flatMap(({ certificate, status }) => [certificate.commonName, `Serial ${certificate.serialNumber}${status === void 0 ? "" : ` (HTTP ${status})`}`]),
2806
+ CERTIFICATES_URL
2807
+ ].join("\n"));
2808
+ return {
2809
+ revoked: revoked.map(describe),
2810
+ failed: failed.map(({ certificate }) => describe(certificate))
2811
+ };
2812
+ };
2813
+ const TERMINATION_SIGNALS = [
2814
+ "SIGHUP",
2815
+ "SIGINT",
2816
+ "SIGTERM"
2817
+ ];
2818
+ /**
2819
+ * Runs `run`, the archive and export of a build that signs with an App
2820
+ * Store Connect API key, in a keychain of its own when `enabled` (in CI),
2821
+ * then revokes the certificates Xcode created in it and deletes it. A
2822
+ * termination signal does the same before the process ends with it: the
2823
+ * certificates are read from the keychain before it is deleted, and the key
2824
+ * is read into memory first, since the build's temporary key file is deleted
2825
+ * on the signal. A second signal restores the keychains at once.
2826
+ *
2827
+ * `keepDistribution` keeps a distribution certificate out of the revoking, for
2828
+ * an ad hoc export: Xcode may have signed the `.ipa` with one it created here,
2829
+ * rather than the cloud-managed one, and installs may need it valid. Only the
2830
+ * development certificates Xcode created for the archive are then revoked.
2831
+ */
2832
+ const withSigningKeychain = async ({ enabled, keepDistribution = false, apiKey, run, security, lockPath, acquireLock, fetch }) => {
2833
+ if (!enabled) return run();
2834
+ const privateKey = crypto$1.createPrivateKey(await fs.promises.readFile(apiKey.keyPath, "utf-8"));
2835
+ const keychain = await createSigningKeychain({
2836
+ security,
2837
+ lockPath,
2838
+ acquireLock
2839
+ });
2840
+ p.log.info("Signing in a keychain of this build's own (CI is set).");
2841
+ let cleanup;
2842
+ const release = () => {
2843
+ cleanup ??= (async () => {
2844
+ const certificates = await keychain.certificates().catch(() => []);
2845
+ await keychain.dispose();
2846
+ await revokeKeychainCertificates({
2847
+ certificates: keepDistribution ? certificates.filter(({ commonName }) => !commonName.includes("Distribution")) : certificates,
2848
+ apiKey,
2849
+ privateKey,
2850
+ fetch
2851
+ });
2852
+ })();
2853
+ return cleanup;
2854
+ };
2855
+ const stopListening = () => {
2856
+ for (const signal of TERMINATION_SIGNALS) process.off(signal, onSignal);
2857
+ };
2858
+ const onSignal = (signal) => {
2859
+ if (cleanup) {
2860
+ stopListening();
2861
+ restoreLive();
2862
+ process.kill(process.pid, signal);
2863
+ return;
2864
+ }
2865
+ release().finally(() => {
2866
+ stopListening();
2867
+ if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
2868
+ });
2869
+ };
2870
+ for (const signal of TERMINATION_SIGNALS) process.on(signal, onSignal);
2871
+ try {
2872
+ return await run();
2873
+ } finally {
2874
+ await release();
2875
+ stopListening();
2876
+ }
2877
+ };
2878
+ //#endregion
2879
+ //#region src/utils/readBuiltApp.ts
2880
+ const readInfoValue = async (infoPlist, key) => {
2881
+ const { stdout, exitCode } = await execa("plutil", [
2882
+ "-extract",
2883
+ key,
2884
+ "raw",
2885
+ "-o",
2886
+ "-",
2887
+ infoPlist
2888
+ ], { reject: false });
2889
+ return exitCode === 0 && stdout.trim() ? stdout.trim() : null;
2890
+ };
2891
+ /**
2892
+ * What the built `.app` reports at runtime, from its Info.plist: the
2893
+ * `CFBundleShortVersionString`, `CFBundleVersion` (the build number) and
2894
+ * `HOT_UPDATER_CHANNEL` the build settings,
2895
+ * an `xcconfig` and `extraParams` expanded.
2896
+ */
2897
+ const readBuiltApp = async (appPath) => {
2898
+ const infoPlist = path.join(appPath, "Info.plist");
2899
+ const [appVersion, channel, buildNumber] = await Promise.all([
2900
+ readInfoValue(infoPlist, "CFBundleShortVersionString"),
2901
+ readInfoValue(infoPlist, "HOT_UPDATER_CHANNEL"),
2902
+ readInfoValue(infoPlist, "CFBundleVersion")
2903
+ ]);
2904
+ return {
2905
+ appVersion,
2906
+ channel,
2907
+ buildNumber
2908
+ };
2909
+ };
2910
+ //#endregion
2911
+ //#region src/sandboxTestFlight.ts
2912
+ /**
2913
+ * The states of a version Apple hasn't approved, which still takes builds.
2914
+ * Any other state, such as one Apple adds later, counts as closed: a raise
2915
+ * costs a sandbox build nothing, and an upload to a closed train costs one.
2916
+ */
2917
+ const OPEN_VERSION_STATES = /* @__PURE__ */ new Set([
2918
+ "PREPARE_FOR_SUBMISSION",
2919
+ "READY_FOR_REVIEW",
2920
+ "WAITING_FOR_REVIEW",
2921
+ "IN_REVIEW",
2922
+ "WAITING_FOR_EXPORT_COMPLIANCE",
2923
+ "PENDING_CONTRACT",
2924
+ "INVALID_BINARY",
2925
+ "METADATA_REJECTED",
2926
+ "REJECTED",
2927
+ "DEVELOPER_REJECTED"
2928
+ ]);
2929
+ /** A version as numbers: `1.6.2`, or null for one that isn't only numbers. */
2930
+ const parseVersion = (version) => /^\d+(\.\d+)*$/u.test(version) ? version.split(".").map(Number) : null;
2931
+ /** Negative, zero or positive as `a` is below, equal to or above `b`. */
2932
+ const compareVersions = (a, b) => {
2933
+ for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
2934
+ const difference = (a[i] ?? 0) - (b[i] ?? 0);
2935
+ if (difference !== 0) return difference;
2936
+ }
2937
+ return 0;
2938
+ };
2939
+ /** The highest of `versions`, ignoring any that aren't only numbers. */
2940
+ const highestVersion = (versions) => {
2941
+ let highest = null;
2942
+ for (const text of versions) {
2943
+ const parts = parseVersion(text);
2944
+ if (parts && (!highest || compareVersions(parts, highest.parts) > 0)) highest = {
2945
+ text,
2946
+ parts
2947
+ };
2948
+ }
2949
+ return highest?.text ?? null;
2950
+ };
2951
+ /** The highest integer build number among `versions`. */
2952
+ const highestBuildNumberOf = (versions) => {
2953
+ const numbers = versions.filter((version) => /^\d+$/u.test(version)).map(Number);
2954
+ return numbers.length > 0 ? Math.max(...numbers) : null;
2955
+ };
2956
+ /**
2957
+ * Reads what a sandbox build must fit before it is built: the versions Apple
2958
+ * approved, from `/v1/appStoreVersions`, since a closed train's builds look
2959
+ * like any others in `/v1/builds`, and the app's highest build number.
2960
+ */
2961
+ const readAppStoreTrain = async ({ bundleId, apiKey, fetch = globalThis.fetch }) => {
2962
+ const privateKey = await readPrivateKey(apiKey.keyPath);
2963
+ const request = createAppStoreConnectRequest({
2964
+ apiKey,
2965
+ privateKey,
2966
+ fetch
2967
+ });
2968
+ const { app } = await findApp(request, bundleId);
2969
+ const [{ data: versions }, { data: builds }] = await Promise.all([retrying(() => request("Reading the App Store versions", "GET", `/v1/apps/${app.id}/appStoreVersions?${new URLSearchParams({
2970
+ "filter[platform]": "IOS",
2971
+ "fields[appStoreVersions]": "versionString,appVersionState,appStoreState",
2972
+ limit: "200"
2973
+ })}`)), retrying(() => request("Reading the app's builds", "GET", `/v1/builds?${new URLSearchParams({
2974
+ "filter[app]": app.id,
2975
+ sort: "-uploadedDate",
2976
+ "fields[builds]": "version",
2977
+ limit: "200"
2978
+ })}`))]);
2979
+ const closed = versions.flatMap(({ attributes }) => {
2980
+ const state = attributes?.appVersionState ?? attributes?.appStoreState;
2981
+ return attributes?.versionString && !(state && OPEN_VERSION_STATES.has(state)) ? [attributes.versionString] : [];
2982
+ });
2983
+ return {
2984
+ highestClosedVersion: highestVersion(closed),
2985
+ highestBuildNumber: highestBuildNumberOf(builds.flatMap(({ attributes }) => attributes?.version ?? []))
2986
+ };
2987
+ };
2988
+ /**
2989
+ * What a sandbox device build needs from App Store Connect, read before the
2990
+ * build. An export for elsewhere has no train, and without an API key it
2991
+ * can't be read: the store would say so after the upload. What a closed train
2992
+ * does to the build waits for the archive (`patchSandboxArchive`): only the
2993
+ * archived app holds the version an `xcconfig` or `extraParams` settled on,
2994
+ * which the project's files don't.
2995
+ */
2996
+ const prepareSandboxArchive = async ({ schemeConfig, apiKey, updateStrategy, fetch }) => {
2997
+ if (!await exportsForAppStoreConnect(schemeConfig)) return { updateStrategy };
2998
+ if (!apiKey) {
2999
+ p.log.warn("No App Store Connect API key, so the sandbox build can't check for a closed version.\nSet signing.ascApiKey on the scheme.");
3000
+ return { updateStrategy };
3001
+ }
3002
+ return {
3003
+ train: await readAppStoreTrain({
3004
+ bundleId: schemeConfig.bundleIdentifier,
3005
+ apiKey,
3006
+ ...fetch ? { fetch } : {}
3007
+ }),
3008
+ updateStrategy
3009
+ };
3010
+ };
3011
+ /** Whether Apple refuses a build of `version`, as `train` says. */
3012
+ const isVersionTrainClosed = (version, { highestClosedVersion }) => {
3013
+ const parts = parseVersion(version);
3014
+ const closed = highestClosedVersion === null ? null : parseVersion(highestClosedVersion);
3015
+ return parts !== null && closed !== null && compareVersions(parts, closed) <= 0;
3016
+ };
3017
+ /**
3018
+ * What a sandbox build does with a closed version train. Under the fingerprint
3019
+ * strategy it raises its own version past the closed one, which targets no
3020
+ * update. Under appVersion the version is what updates target, so it refuses
3021
+ * rather than move them silently.
3022
+ */
3023
+ const sandboxVersionDecision = ({ version, train, updateStrategy }) => {
3024
+ if (!isVersionTrainClosed(version, train)) return { kind: "keep" };
3025
+ const closed = train.highestClosedVersion;
3026
+ if (updateStrategy === "appVersion") return {
3027
+ kind: "refuse",
3028
+ message: `App Store Connect closed version ${closed}, so TestFlight refuses ${version}.\nRaise the app version.`
3029
+ };
3030
+ const [major = 0, minor = 0, patch = 0] = parseVersion(closed);
3031
+ return {
3032
+ kind: "raise",
3033
+ version: `${major}.${minor}.${patch + 1}`
3034
+ };
3035
+ };
3036
+ /**
3037
+ * Refuses, before the upload, a sandbox `.ipa` Xcode didn't mark for internal
3038
+ * testing only: App Store Connect would let it reach App Store review.
3039
+ */
3040
+ const assertIpaIsInternalOnly = async (ipaPath) => {
3041
+ if (!await readIpaInternalTestingOnly(ipaPath)) throw new Error(`${path.basename(ipaPath)} isn't marked for internal testing only (TFInternalTestingOnly), so it wasn't uploaded.\nExport it with testFlightInternalTestingOnly.`);
3042
+ };
3043
+ /** How long App Store Connect may take to list a build it accepted. */
3044
+ const AUDIENCE_TIMEOUT_MS = 3e5;
3045
+ const STATE_OF_INTERNAL_BUILD = {
3046
+ MISSING_EXPORT_COMPLIANCE: "missing-compliance",
3047
+ IN_EXPORT_COMPLIANCE_REVIEW: "missing-compliance",
3048
+ PROCESSING: "processing",
3049
+ PROCESSING_EXCEPTION: "failed",
3050
+ EXPIRED: "expired"
3051
+ };
3052
+ /**
3053
+ * One read of a version and build number: its audience, processing state,
3054
+ * expiry, and internal testing state. Null while App Store Connect lists none.
3055
+ */
3056
+ const readBuildStatus = async (request, { appId, shortVersion, bundleVersion }) => {
3057
+ const { data, included } = await retrying(() => request("Reading the build", "GET", `/v1/builds?${new URLSearchParams({
3058
+ "filter[app]": appId,
3059
+ "filter[version]": bundleVersion,
3060
+ ...shortVersion === null ? {} : { "filter[preReleaseVersion.version]": shortVersion },
3061
+ "fields[builds]": "buildAudienceType,processingState,expirationDate,expired,buildBetaDetail",
3062
+ include: "buildBetaDetail",
3063
+ "fields[buildBetaDetails]": "internalBuildState",
3064
+ limit: "1"
3065
+ })}`));
3066
+ const build = data[0];
3067
+ if (!build) return null;
3068
+ const internal = included?.find(({ type }) => type === "buildBetaDetails")?.attributes?.internalBuildState;
3069
+ const processing = build.attributes?.processingState;
3070
+ const expiration = build.attributes?.expirationDate;
3071
+ const state = build.attributes?.expired ? "expired" : processing === "PROCESSING" || !processing ? "processing" : processing !== "VALID" ? "failed" : STATE_OF_INTERNAL_BUILD[internal ?? ""] ?? "ready";
3072
+ return {
3073
+ buildId: build.id,
3074
+ audience: build.attributes?.buildAudienceType ?? null,
3075
+ state,
3076
+ ...state === "missing-compliance" && internal === "IN_EXPORT_COMPLIANCE_REVIEW" ? { inExportComplianceReview: true } : {},
3077
+ expiresAtMs: expiration ? Date.parse(expiration) : null
3078
+ };
3079
+ };
3080
+ /**
3081
+ * Fails unless App Store Connect holds the uploaded sandbox build for internal
3082
+ * testing only, as `buildAudienceType` says once the build is listed, and
3083
+ * returns what that read says of it.
3084
+ */
3085
+ const assertBuildIsInternalOnly = async ({ ipaPath, apiKey, fetch = globalThis.fetch, pollIntervalMs = 5e3, timeoutMs = AUDIENCE_TIMEOUT_MS }) => {
3086
+ const [info, privateKey] = await Promise.all([readIpaInfo(ipaPath), readPrivateKey(apiKey.keyPath)]);
3087
+ const request = createAppStoreConnectRequest({
3088
+ apiKey,
3089
+ privateKey,
3090
+ fetch
3091
+ });
3092
+ const { app, testFlightUrl } = await findApp(request, info.bundleId);
3093
+ const label = `${info.shortVersion} (${info.bundleVersion})`;
3094
+ const deadline = Date.now() + timeoutMs;
3095
+ for (;;) {
3096
+ const status = await readBuildStatus(request, {
3097
+ appId: app.id,
3098
+ shortVersion: info.shortVersion,
3099
+ bundleVersion: info.bundleVersion
3100
+ });
3101
+ if (status?.audience === "INTERNAL_ONLY") return {
3102
+ ...status,
3103
+ appId: app.id,
3104
+ testFlightUrl
3105
+ };
3106
+ if (status?.audience) throw new Error(`App Store Connect holds sandbox build ${label} for ${status.audience}, not INTERNAL_ONLY.\nExpire it in TestFlight:\n${testFlightUrl}`);
3107
+ if (Date.now() >= deadline) throw new Error(`App Store Connect didn't say who sandbox build ${label} is for.\nCheck that it is internal only in TestFlight:\n${testFlightUrl}`);
3108
+ await sleep(pollIntervalMs);
3109
+ }
3110
+ };
3111
+ /**
3112
+ * The internal TestFlight group named `name`, read before anything is built.
3113
+ * An external group is refused: its builds go to Beta App Review, and a sandbox
3114
+ * build is for internal testing only.
3115
+ */
3116
+ const findInternalBetaGroup = async ({ bundleId, name, apiKey, fetch = globalThis.fetch }) => {
3117
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3118
+ const request = createAppStoreConnectRequest({
3119
+ apiKey,
3120
+ privateKey,
3121
+ fetch
3122
+ });
3123
+ const { app, testFlightUrl } = await findApp(request, bundleId);
3124
+ return readInternalBetaGroup(request, {
3125
+ appId: app.id,
3126
+ bundleId,
3127
+ name,
3128
+ testFlightUrl
3129
+ });
3130
+ };
3131
+ /** The group named `name` of an app, refused unless it is internal. */
3132
+ const readInternalBetaGroup = async (request, { appId, bundleId, name, testFlightUrl }) => {
3133
+ const { data } = await retrying(() => request("Reading the TestFlight groups", "GET", `/v1/betaGroups?${new URLSearchParams({
3134
+ "filter[app]": appId,
3135
+ "filter[name]": name,
3136
+ "fields[betaGroups]": "name,isInternalGroup,hasAccessToAllBuilds",
3137
+ limit: "200"
3138
+ })}`));
3139
+ const group = data.find(({ attributes }) => attributes?.name === name);
3140
+ if (!group) throw new Error(`App Store Connect has no TestFlight group ${name} for ${bundleId}.\nCreate it as an internal group:\n${testFlightUrl}`);
3141
+ if (group.attributes?.isInternalGroup !== true) throw new Error(`TestFlight group ${name} is external, and a sandbox build is for internal testing only.\nName an internal group.`);
3142
+ return {
3143
+ id: group.id,
3144
+ name,
3145
+ hasAccessToAllBuilds: group.attributes.hasAccessToAllBuilds === true
3146
+ };
3147
+ };
3148
+ /** How long a build's processing may hold up its group and What to Test. */
3149
+ const DISTRIBUTION_TIMEOUT_MS = 9e5;
3150
+ /** What to Test's locale: the language the CLI writes it in. */
3151
+ const WHAT_TO_TEST_LOCALE = "en-US";
1998
3152
  /**
1999
- * Revokes the certificates Xcode created in the build's keychain, whose
2000
- * private keys the keychain's deletion destroys: on a runner that starts
2001
- * empty, Xcode creates a development certificate for every build, and App
2002
- * Store Connect refuses new ones once a team has its maximum. Each is found
2003
- * in the team's certificates by serial number. A revocation that fails is
2004
- * reported with where to revoke it by hand, and never fails the build.
3153
+ * Adds a processed build to its internal group and sets its What to Test, which
3154
+ * App Store Connect takes once the build is processed. A build still processing
3155
+ * after `timeoutMs` keeps its upload: a warning says what to do by hand. Returns
3156
+ * the build's state.
2005
3157
  */
2006
- const revokeKeychainCertificates = async ({ certificates, apiKey, privateKey, fetch = globalThis.fetch }) => {
2007
- const revoked = [];
2008
- const failed = [];
2009
- if (certificates.length === 0) return {
2010
- revoked,
2011
- failed
3158
+ const distributeTestFlightBuild = async ({ build: { appId, shortVersion, bundleVersion, testFlightUrl }, group, whatToTest, apiKey, fetch = globalThis.fetch, pollIntervalMs = 15e3, timeoutMs = DISTRIBUTION_TIMEOUT_MS }) => {
3159
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3160
+ const request = createAppStoreConnectRequest({
3161
+ apiKey,
3162
+ privateKey,
3163
+ fetch
3164
+ });
3165
+ const build = {
3166
+ appId,
3167
+ shortVersion,
3168
+ bundleVersion,
3169
+ testFlightUrl
2012
3170
  };
2013
- const describe = ({ commonName, serialNumber }) => `${commonName} (serial ${serialNumber})`;
2014
- try {
2015
- const token = createAppStoreConnectToken({
2016
- privateKey: privateKey ?? crypto$1.createPrivateKey(await fs$1.promises.readFile(apiKey.keyPath, "utf-8")),
2017
- keyId: apiKey.keyId,
2018
- issuerId: apiKey.issuerId
2019
- });
2020
- registerSecretValue(token);
2021
- const headers = { Authorization: `Bearer ${token}` };
2022
- const idsBySerial = /* @__PURE__ */ new Map();
2023
- let next = `${API_URL}/v1/certificates?${new URLSearchParams({
2024
- "fields[certificates]": "serialNumber",
2025
- limit: "200"
2026
- })}`;
2027
- while (next) {
2028
- const response = await fetch(next, { headers });
2029
- if (!response.ok) throw new Error(`Listing the team's certificates failed (HTTP ${response.status}).`);
2030
- const body = await response.json();
2031
- for (const { id, attributes } of body.data ?? []) if (attributes?.serialNumber) idsBySerial.set(normalizeSerial(attributes.serialNumber), id);
2032
- next = body.links?.next;
2033
- }
2034
- for (const certificate of certificates) {
2035
- const id = idsBySerial.get(certificate.serialNumber);
2036
- if (id === void 0) continue;
2037
- const response = await fetch(`${API_URL}/v1/certificates/${id}`, {
2038
- method: "DELETE",
2039
- headers
2040
- });
2041
- if (response.ok || response.status === 404) revoked.push(describe(certificate));
2042
- else failed.push(`${describe(certificate)}: HTTP ${response.status}`);
3171
+ const status = await waitUntilProcessed(request, build, await readBuildStatus(request, build), {
3172
+ pollIntervalMs,
3173
+ timeoutMs,
3174
+ unset: "its testers and What to Test"
3175
+ });
3176
+ if (!status || status.state === "processing") return status;
3177
+ const { buildId } = status;
3178
+ if (group && !group.hasAccessToAllBuilds) await addBuildToGroup(request, build, buildId, group);
3179
+ if (whatToTest !== void 0) await setWhatToTest(request, buildId, whatToTest);
3180
+ return status;
3181
+ };
3182
+ /**
3183
+ * Reads the build until App Store Connect has processed it, from the status a
3184
+ * read already has, for what it takes only then. A build still processing after
3185
+ * `timeoutMs` keeps its upload: a warning says what is `unset`. One that can't
3186
+ * be processed fails.
3187
+ */
3188
+ const waitUntilProcessed = async (request, build, listed, { pollIntervalMs, timeoutMs, unset }) => {
3189
+ const label = `${build.shortVersion} (${build.bundleVersion})`;
3190
+ const deadline = Date.now() + timeoutMs;
3191
+ let status = listed;
3192
+ while (!status || status.state === "processing") {
3193
+ if (Date.now() >= deadline) {
3194
+ p.log.warn(`App Store Connect is still processing build ${label}, so ${unset} aren't set.\nSet them in TestFlight:\n${build.testFlightUrl}`);
3195
+ return status;
2043
3196
  }
2044
- } catch (error) {
2045
- const reason = error instanceof Error ? error.message : String(error);
2046
- for (const certificate of certificates) if (!revoked.includes(describe(certificate))) failed.push(`${describe(certificate)}: ${reason}`);
3197
+ await sleep(pollIntervalMs);
3198
+ status = await readBuildStatus(request, build);
2047
3199
  }
2048
- if (revoked.length > 0) p.log.info(`Revoked the signing certificates Xcode created for this build, whose keys the build's keychain held: ${revoked.join(", ")}.`);
2049
- if (failed.length > 0) p.log.warn(`Revoking the signing certificates Xcode created for this build failed, and their keys are deleted with the build's keychain: ${failed.join("; ")}. Revoke them at ${CERTIFICATES_URL}, since App Store Connect stops creating certificates at a team's maximum.`);
2050
- return {
2051
- revoked,
2052
- failed
2053
- };
3200
+ if (status.state === "failed") throw new Error(`App Store Connect couldn't process build ${label}.\nCheck it in TestFlight:\n${build.testFlightUrl}`);
3201
+ return status;
2054
3202
  };
2055
- const TERMINATION_SIGNALS = [
2056
- "SIGHUP",
2057
- "SIGINT",
2058
- "SIGTERM"
2059
- ];
3203
+ const addBuildToGroup = (request, { shortVersion, bundleVersion }, buildId, group) => retrying(() => request(`Adding build ${shortVersion} (${bundleVersion}) to ${group.name}`, "POST", `/v1/betaGroups/${group.id}/relationships/builds`, { data: [{
3204
+ type: "builds",
3205
+ id: buildId
3206
+ }] }));
2060
3207
  /**
2061
- * Runs `run`, the archive and export of a build that signs with an App
2062
- * Store Connect API key, in a keychain of its own when `enabled` (in CI),
2063
- * then revokes the certificates Xcode created in it and deletes it. A
2064
- * termination signal does the same before the process ends with it: the
2065
- * certificates are read from the keychain before it is deleted, and the key
2066
- * is read into memory first, since the build's temporary key file is deleted
2067
- * on the signal. A second signal restores the keychains at once.
3208
+ * Applies an internal group to a build already on TestFlight, as an upload does,
3209
+ * so a reused build reaches the group named now. One process reads the app, the
3210
+ * build and the group once each. Reading a build's `betaGroups` relationship
3211
+ * answered 403 when we tried it, so this doesn't check membership first: every
3212
+ * run adds the build. A build not `isOffered` gets nothing: it needs a new
3213
+ * build, which checks the group itself. A build still processing waits as an
3214
+ * upload's does, and the next run applies the group again.
2068
3215
  */
2069
- const withSigningKeychain = async ({ enabled, apiKey, run, security, lockPath, acquireLock, fetch }) => {
2070
- if (!enabled) return run();
2071
- const privateKey = crypto$1.createPrivateKey(await fs$1.promises.readFile(apiKey.keyPath, "utf-8"));
2072
- const keychain = await createSigningKeychain({
2073
- security,
2074
- lockPath,
2075
- acquireLock
3216
+ const applyTestFlightGroup = async ({ bundleId, shortVersion, bundleVersion, name, isOffered, apiKey, fetch = globalThis.fetch, pollIntervalMs = 15e3, timeoutMs = DISTRIBUTION_TIMEOUT_MS }) => {
3217
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3218
+ const request = createAppStoreConnectRequest({
3219
+ apiKey,
3220
+ privateKey,
3221
+ fetch
2076
3222
  });
2077
- p.log.info("Signing in a keychain of this build's own, deleted when it ends (CI is set).");
2078
- let cleanup;
2079
- const release = () => {
2080
- cleanup ??= (async () => {
2081
- const certificates = await keychain.certificates().catch(() => []);
2082
- await keychain.dispose();
2083
- await revokeKeychainCertificates({
2084
- certificates,
2085
- apiKey,
2086
- privateKey,
2087
- fetch
2088
- });
2089
- })();
2090
- return cleanup;
3223
+ const { app, testFlightUrl } = await findApp(request, bundleId);
3224
+ const build = {
3225
+ appId: app.id,
3226
+ shortVersion,
3227
+ bundleVersion,
3228
+ testFlightUrl
2091
3229
  };
2092
- const stopListening = () => {
2093
- for (const signal of TERMINATION_SIGNALS) process.off(signal, onSignal);
3230
+ const listed = await readBuildStatus(request, build);
3231
+ if (!isOffered(listed)) return {
3232
+ testFlightUrl,
3233
+ status: listed,
3234
+ outcome: "not-offered"
2094
3235
  };
2095
- const onSignal = (signal) => {
2096
- if (cleanup) {
2097
- stopListening();
2098
- restoreLive();
2099
- process.kill(process.pid, signal);
2100
- return;
2101
- }
2102
- release().finally(() => {
2103
- stopListening();
2104
- if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
2105
- });
3236
+ const group = await readInternalBetaGroup(request, {
3237
+ appId: app.id,
3238
+ bundleId,
3239
+ name,
3240
+ testFlightUrl
3241
+ });
3242
+ if (group.hasAccessToAllBuilds) return {
3243
+ testFlightUrl,
3244
+ status: listed,
3245
+ outcome: "takes-every-build"
2106
3246
  };
2107
- for (const signal of TERMINATION_SIGNALS) process.on(signal, onSignal);
3247
+ const status = await waitUntilProcessed(request, build, listed, {
3248
+ pollIntervalMs,
3249
+ timeoutMs,
3250
+ unset: "its testers"
3251
+ });
3252
+ if (!status || status.state === "processing") return {
3253
+ testFlightUrl,
3254
+ status,
3255
+ outcome: "pending"
3256
+ };
3257
+ await addBuildToGroup(request, build, status.buildId, group);
3258
+ return {
3259
+ testFlightUrl,
3260
+ status,
3261
+ outcome: "added"
3262
+ };
3263
+ };
3264
+ /** Sets a build's What to Test: creates it, or updates the one a rerun left. */
3265
+ const setWhatToTest = async (request, buildId, whatsNew) => {
2108
3266
  try {
2109
- return await run();
2110
- } finally {
2111
- await release();
2112
- stopListening();
3267
+ await retrying(() => request("Setting What to Test", "POST", "/v1/betaBuildLocalizations", { data: {
3268
+ type: "betaBuildLocalizations",
3269
+ attributes: {
3270
+ locale: WHAT_TO_TEST_LOCALE,
3271
+ whatsNew
3272
+ },
3273
+ relationships: { build: { data: {
3274
+ type: "builds",
3275
+ id: buildId
3276
+ } } }
3277
+ } }));
3278
+ } catch (error) {
3279
+ if (!(error instanceof AppStoreConnectError) || error.status !== 409) throw error;
3280
+ const { data } = await retrying(() => request("Reading What to Test", "GET", `/v1/builds/${buildId}/betaBuildLocalizations?${new URLSearchParams({
3281
+ "fields[betaBuildLocalizations]": "locale",
3282
+ limit: "200"
3283
+ })}`));
3284
+ const existing = data.find(({ attributes }) => attributes?.locale === WHAT_TO_TEST_LOCALE);
3285
+ if (!existing) throw error;
3286
+ await retrying(() => request("Setting What to Test", "PATCH", `/v1/betaBuildLocalizations/${existing.id}`, { data: {
3287
+ type: "betaBuildLocalizations",
3288
+ id: existing.id,
3289
+ attributes: { whatsNew }
3290
+ } }));
2113
3291
  }
2114
3292
  };
3293
+ /**
3294
+ * What App Store Connect says of a build a run recorded as uploaded, which a
3295
+ * later run reuses: its page, and its state and expiry, or a null status when
3296
+ * it no longer lists the build.
3297
+ */
3298
+ const readTestFlightBuildStatus = async ({ bundleId, shortVersion, bundleVersion, apiKey, fetch = globalThis.fetch }) => {
3299
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3300
+ const request = createAppStoreConnectRequest({
3301
+ apiKey,
3302
+ privateKey,
3303
+ fetch
3304
+ });
3305
+ const { app, testFlightUrl } = await findApp(request, bundleId);
3306
+ return {
3307
+ testFlightUrl,
3308
+ status: await readBuildStatus(request, {
3309
+ appId: app.id,
3310
+ shortVersion,
3311
+ bundleVersion
3312
+ })
3313
+ };
3314
+ };
2115
3315
  //#endregion
2116
- //#region src/utils/readBuiltApp.ts
2117
- const readInfoValue = async (infoPlist, key) => {
3316
+ //#region src/utils/sandboxInfoPlist.ts
3317
+ const URL_TYPE_NAME = "hot-updater-sandbox";
3318
+ const CAMERA_USAGE = "Scans the QR code of a preview to open it in this build.";
3319
+ const LOCAL_NETWORK_USAGE = "Connects to the dev server you choose on this network.";
3320
+ const ATS_KEY = "NSAppTransportSecurity";
3321
+ const ATS_LOCAL_NETWORKING_KEY = "NSAllowsLocalNetworking";
3322
+ /** A refusal the command prints as it is: the build ran as it should. */
3323
+ const refusal = (message) => new BuildFailedError(message, {
3324
+ logPath: null,
3325
+ summary: [],
3326
+ hint: message
3327
+ });
3328
+ const plutil = (args) => execa("plutil", args);
3329
+ const readValue = async (plist, key) => {
2118
3330
  const { stdout, exitCode } = await execa("plutil", [
2119
3331
  "-extract",
2120
3332
  key,
2121
3333
  "raw",
2122
3334
  "-o",
2123
3335
  "-",
2124
- infoPlist
3336
+ plist
2125
3337
  ], { reject: false });
2126
3338
  return exitCode === 0 && stdout.trim() ? stdout.trim() : null;
2127
3339
  };
3340
+ const setString = (plist, key, value) => plutil([
3341
+ "-replace",
3342
+ key,
3343
+ "-string",
3344
+ value,
3345
+ plist
3346
+ ]);
3347
+ /** Appends a URL type with the sandbox's scheme to the app's own. */
3348
+ const addUrlScheme = async (plist, urlScheme) => {
3349
+ const urlType = JSON.stringify({
3350
+ CFBundleURLName: URL_TYPE_NAME,
3351
+ CFBundleURLSchemes: [urlScheme]
3352
+ });
3353
+ const { stdout, exitCode } = await execa("plutil", [
3354
+ "-extract",
3355
+ "CFBundleURLTypes",
3356
+ "json",
3357
+ "-o",
3358
+ "-",
3359
+ plist
3360
+ ], { reject: false });
3361
+ if (exitCode !== 0) {
3362
+ await plutil([
3363
+ "-insert",
3364
+ "CFBundleURLTypes",
3365
+ "-json",
3366
+ `[${urlType}]`,
3367
+ plist
3368
+ ]);
3369
+ return;
3370
+ }
3371
+ const existing = JSON.parse(stdout);
3372
+ await plutil([
3373
+ "-insert",
3374
+ `CFBundleURLTypes.${existing.length}`,
3375
+ "-json",
3376
+ urlType,
3377
+ plist
3378
+ ]);
3379
+ };
3380
+ const hasKey = async (plist, key) => {
3381
+ const { exitCode } = await execa("plutil", [
3382
+ "-extract",
3383
+ key,
3384
+ "xml1",
3385
+ "-o",
3386
+ "-",
3387
+ plist
3388
+ ], { reject: false });
3389
+ return exitCode === 0;
3390
+ };
2128
3391
  /**
2129
- * What the built `.app` reports at runtime, from its Info.plist: the
2130
- * `CFBundleShortVersionString`, `CFBundleVersion` (the build number) and
2131
- * `HOT_UPDATER_CHANNEL` the build settings,
2132
- * an `xcconfig` and `extraParams` expanded.
3392
+ * What the sandbox's screen asks the system for: the camera for its QR scanner,
3393
+ * and the local network for a dev server. A value the app already set stays, and
3394
+ * nested App Transport Security entries stay beside the one this adds.
2133
3395
  */
2134
- const readBuiltApp = async (appPath) => {
2135
- const infoPlist = path$1.join(appPath, "Info.plist");
2136
- const [appVersion, channel, buildNumber] = await Promise.all([
2137
- readInfoValue(infoPlist, "CFBundleShortVersionString"),
2138
- readInfoValue(infoPlist, "HOT_UPDATER_CHANNEL"),
2139
- readInfoValue(infoPlist, "CFBundleVersion")
3396
+ const addSandboxPermissions = async (plist) => {
3397
+ for (const [key, value] of [["NSCameraUsageDescription", CAMERA_USAGE], ["NSLocalNetworkUsageDescription", LOCAL_NETWORK_USAGE]]) if (!await hasKey(plist, key)) await plutil([
3398
+ "-insert",
3399
+ key,
3400
+ "-string",
3401
+ value,
3402
+ plist
3403
+ ]);
3404
+ if (!await hasKey(plist, ATS_KEY)) await plutil([
3405
+ "-insert",
3406
+ ATS_KEY,
3407
+ "-json",
3408
+ `{"${ATS_LOCAL_NETWORKING_KEY}":true}`,
3409
+ plist
3410
+ ]);
3411
+ else if (!await hasKey(plist, `${ATS_KEY}.${ATS_LOCAL_NETWORKING_KEY}`)) await plutil([
3412
+ "-insert",
3413
+ `${ATS_KEY}.${ATS_LOCAL_NETWORKING_KEY}`,
3414
+ "-bool",
3415
+ "true",
3416
+ plist
3417
+ ]);
3418
+ };
3419
+ /**
3420
+ * The app's dedicated URL scheme, default channel, and the sandbox's key. The
3421
+ * URL scheme and App Store Connect's app come from the scheme's
3422
+ * `bundleIdentifier`, while Xcode's build settings decide the app's ID, so an
3423
+ * app of another ID stops here, before anything is signed or uploaded.
3424
+ */
3425
+ const patchAppInfoPlist = async (plist, scheme) => {
3426
+ const built = await readValue(plist, "CFBundleIdentifier");
3427
+ if (built !== scheme.bundleIdentifier) throw refusal(`The sandbox scheme ${scheme.hotUpdaterSchemeName} sets bundleIdentifier ${scheme.bundleIdentifier}, but Xcode built ${built ?? "no bundle ID"}.\nSet bundleIdentifier to the ID its configuration builds.`);
3428
+ await setString(plist, "HOT_UPDATER_CHANNEL", sandboxChannelOf(scheme.hotUpdaterSchemeName));
3429
+ await plutil([
3430
+ "-replace",
3431
+ SANDBOX_INFO_PLIST_KEY,
3432
+ "-bool",
3433
+ "true",
3434
+ plist
3435
+ ]);
3436
+ await addUrlScheme(plist, sandboxUrlSchemeOf(scheme.bundleIdentifier));
3437
+ await addSandboxPermissions(plist);
3438
+ };
3439
+ /** The Info.plist of each app extension inside an `.app`. */
3440
+ const extensionInfoPlists = (appPath) => ["PlugIns", "Extensions"].flatMap((directory) => {
3441
+ const extensions = path.join(appPath, directory);
3442
+ if (!fs.existsSync(extensions)) return [];
3443
+ return fs.readdirSync(extensions).filter((name) => name.endsWith(".appex")).map((name) => path.join(extensions, name, "Info.plist"));
3444
+ });
3445
+ /**
3446
+ * Makes the archived app a sandbox app before `-exportArchive`, which signs
3447
+ * what it finds, so no project file changes: its URL scheme, default channel
3448
+ * and key, and from App Store Connect, the version a closed train needs and
3449
+ * the next build number, in its extensions too, which must match it.
3450
+ */
3451
+ const patchSandboxArchive = async ({ archivePath, appPath, schemeConfig, plan }) => {
3452
+ const appPlist = path.join(appPath, "Info.plist");
3453
+ await patchAppInfoPlist(appPlist, schemeConfig);
3454
+ const train = plan?.train;
3455
+ if (!train) return;
3456
+ const version = await readValue(appPlist, "CFBundleShortVersionString");
3457
+ const buildNumber = await readValue(appPlist, "CFBundleVersion");
3458
+ const raised = version === null ? void 0 : sandboxVersionDecision({
3459
+ version,
3460
+ train,
3461
+ updateStrategy: plan.updateStrategy
3462
+ });
3463
+ if (raised?.kind === "refuse") throw refusal(raised.message);
3464
+ const newVersion = raised?.kind === "raise" ? raised.version : null;
3465
+ const newBuildNumber = nextBuildNumber(buildNumber, train.highestBuildNumber);
3466
+ const bundles = [appPlist, ...extensionInfoPlists(appPath)];
3467
+ const archivePlist = path.join(archivePath, "Info.plist");
3468
+ const properties = "ApplicationProperties";
3469
+ if (newVersion !== null) {
3470
+ for (const plist of bundles) await setString(plist, "CFBundleShortVersionString", newVersion);
3471
+ await setString(archivePlist, `${properties}.CFBundleShortVersionString`, newVersion);
3472
+ p.log.info(`Sandbox version ${newVersion}: App Store Connect closed ${version}.`);
3473
+ }
3474
+ if (newBuildNumber !== null) {
3475
+ for (const plist of bundles) await setString(plist, "CFBundleVersion", newBuildNumber);
3476
+ await setString(archivePlist, `${properties}.CFBundleVersion`, newBuildNumber);
3477
+ }
3478
+ };
3479
+ /**
3480
+ * The build number to set over `current`: the one after App Store Connect's
3481
+ * highest, or null to keep `current`, already higher, or one that isn't an
3482
+ * integer such as `1.2.3`.
3483
+ */
3484
+ const nextBuildNumber = (current, highest) => {
3485
+ if (highest === null) return null;
3486
+ if (current !== null && !/^\d+$/u.test(current)) return null;
3487
+ if (current !== null && Number(current) > highest) return null;
3488
+ return String(highest + 1);
3489
+ };
3490
+ /**
3491
+ * Makes a built simulator `.app` a sandbox app, and signs it again ad hoc, as
3492
+ * Xcode does for the simulator, since its signature covers the Info.plist.
3493
+ */
3494
+ const patchSandboxSimulatorApp = async (appPath, schemeConfig) => {
3495
+ await patchAppInfoPlist(path.join(appPath, "Info.plist"), schemeConfig);
3496
+ await execa("codesign", [
3497
+ "--force",
3498
+ "--sign",
3499
+ "-",
3500
+ "--timestamp=none",
3501
+ "--preserve-metadata=entitlements",
3502
+ appPath
2140
3503
  ]);
2141
- return {
2142
- appVersion,
2143
- channel,
2144
- buildNumber
2145
- };
2146
3504
  };
2147
3505
  //#endregion
2148
3506
  //#region src/buildIos.ts
@@ -2155,7 +3513,7 @@ const readBuiltApp = async (appPath) => {
2155
3513
  * once the caller has copied it out. A failed build removes it, and every
2156
3514
  * other directory the build used, itself.
2157
3515
  */
2158
- const buildIos = async ({ schemeConfig, minBundleId = createMinBundleId(), credentials }) => {
3516
+ const buildIos = async ({ schemeConfig, minBundleId = createMinBundleId(), credentials, sandbox, logHeader = [] }) => {
2159
3517
  await assertXcodebuildExist();
2160
3518
  if (schemeConfig.simulator && schemeConfig.destination.length) {
2161
3519
  p.log.error("The scheme option 'simulator' is not compatible with the 'destination' option.");
@@ -2168,7 +3526,9 @@ const buildIos = async ({ schemeConfig, minBundleId = createMinBundleId(), crede
2168
3526
  schemeConfig,
2169
3527
  minBundleId,
2170
3528
  credentials,
2171
- buildDirectory
3529
+ sandbox,
3530
+ buildDirectory,
3531
+ logHeader
2172
3532
  }),
2173
3533
  dispose: () => removeTmpDir(buildDirectory)
2174
3534
  };
@@ -2177,28 +3537,32 @@ const buildIos = async ({ schemeConfig, minBundleId = createMinBundleId(), crede
2177
3537
  throw error;
2178
3538
  }
2179
3539
  };
2180
- const buildInto = async ({ schemeConfig, minBundleId, credentials, buildDirectory }) => {
2181
- const iosProjectRoot = path$1.join(getCwd(), "ios");
3540
+ const buildInto = async ({ schemeConfig, minBundleId, credentials, sandbox, buildDirectory, logHeader }) => {
3541
+ const iosProjectRoot = path.join(getCwd(), "ios");
2182
3542
  if (schemeConfig.simulator) {
2183
- const appDir = path$1.join(buildDirectory, "app");
2184
- await fs$1.promises.mkdir(appDir, { recursive: true });
2185
- const { appPath } = await buildXcodeProject({
3543
+ const appDir = path.join(buildDirectory, "app");
3544
+ await fs.promises.mkdir(appDir, { recursive: true });
3545
+ const { appPath, logFilePath } = await buildXcodeProject({
2186
3546
  sourceDir: iosProjectRoot,
2187
3547
  outputDirectory: appDir,
2188
3548
  logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build`,
3549
+ header: logHeader,
2189
3550
  platform: schemeConfig.platform,
2190
3551
  xcodeScheme: schemeConfig.scheme,
2191
3552
  configuration: schemeConfig.configuration,
2192
3553
  deviceType: "simulator",
2193
3554
  installPods: schemeConfig.installPods,
3555
+ xcconfig: schemeConfig.xcconfig,
2194
3556
  extraParams: schemeConfig.extraParams,
2195
3557
  useGenericDestination: true,
2196
- minBundleId
3558
+ minBundleId,
3559
+ sandbox: schemeConfig.sandbox
2197
3560
  });
2198
- p.log.success(`.app file created: ${path$1.basename(appPath)}`);
3561
+ if (schemeConfig.sandbox) await patchSandboxSimulatorApp(appPath, schemeConfig);
2199
3562
  return {
2200
3563
  buildDirectory,
2201
3564
  buildArtifactPath: appPath,
3565
+ logFilePath,
2202
3566
  builtApp: await readBuiltApp(appPath)
2203
3567
  };
2204
3568
  } else {
@@ -2209,17 +3573,23 @@ const buildInto = async ({ schemeConfig, minBundleId, credentials, buildDirector
2209
3573
  if (!signing) return archiveAndExport({
2210
3574
  schemeConfig,
2211
3575
  minBundleId,
2212
- buildDirectory
3576
+ sandbox,
3577
+ buildDirectory,
3578
+ logHeader
2213
3579
  });
2214
- const appStoreConnect = await exportsForAppStoreConnect(schemeConfig);
2215
- if (isCI() && !appStoreConnect) p.log.info("This export isn't for App Store Connect, so it signs in the runner's own keychains and keeps the certificates Xcode creates.");
3580
+ const registeredDevices = await exportsForRegisteredDevices(schemeConfig);
3581
+ const ownKeychain = registeredDevices || await exportsForAppStoreConnect(schemeConfig);
3582
+ if (isCI() && !ownKeychain) p.log.info("Signing in the runner's own keychains (not an App Store Connect or ad hoc export).");
2216
3583
  return withSigningKeychain({
2217
- enabled: isCI() && appStoreConnect,
3584
+ enabled: isCI() && ownKeychain,
3585
+ keepDistribution: registeredDevices,
2218
3586
  apiKey: signing.apiKey,
2219
3587
  run: () => archiveAndExport({
2220
3588
  schemeConfig,
2221
3589
  minBundleId,
3590
+ sandbox,
2222
3591
  buildDirectory,
3592
+ logHeader,
2223
3593
  authenticationArgs: signing.authenticationArgs
2224
3594
  })
2225
3595
  });
@@ -2229,12 +3599,12 @@ const buildInto = async ({ schemeConfig, minBundleId, credentials, buildDirector
2229
3599
  * Archives a device build and exports its `.ipa`, or returns the
2230
3600
  * `.xcarchive` of a scheme it cannot export.
2231
3601
  */
2232
- const archiveAndExport = async ({ schemeConfig, minBundleId, buildDirectory, authenticationArgs }) => {
2233
- const iosProjectRoot = path$1.join(getCwd(), "ios");
2234
- const archiveDir = path$1.join(buildDirectory, "archive");
2235
- const exportDir = path$1.join(buildDirectory, "export");
2236
- await fs$1.promises.mkdir(archiveDir, { recursive: true });
2237
- const { archivePath } = await archiveXcodeProject({
3602
+ const archiveAndExport = async ({ schemeConfig, minBundleId, sandbox, buildDirectory, logHeader, authenticationArgs }) => {
3603
+ const iosProjectRoot = path.join(getCwd(), "ios");
3604
+ const archiveDir = path.join(buildDirectory, "archive");
3605
+ const exportDir = path.join(buildDirectory, "export");
3606
+ await fs.promises.mkdir(archiveDir, { recursive: true });
3607
+ const { archivePath, logFilePath } = await archiveXcodeProject({
2238
3608
  archiveDirectory: archiveDir,
2239
3609
  authenticationArgs,
2240
3610
  minBundleId,
@@ -2246,20 +3616,29 @@ const archiveAndExport = async ({ schemeConfig, minBundleId, buildDirectory, aut
2246
3616
  extraParams: schemeConfig.extraParams,
2247
3617
  configuration: schemeConfig.configuration,
2248
3618
  installPods: schemeConfig.installPods,
2249
- logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build-archive`
3619
+ logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build`,
3620
+ header: logHeader,
3621
+ sandbox: schemeConfig.sandbox
2250
3622
  });
2251
3623
  const appFromArchive = extractAppFromXcarchive(archivePath);
2252
- const archivedAppPath = appFromArchive ? path$1.join(archiveDir, path$1.basename(appFromArchive)) : void 0;
2253
- if (appFromArchive && archivedAppPath) {
2254
- await fs$1.promises.cp(appFromArchive, archivedAppPath, { recursive: true });
2255
- p.log.success(".app extracted from .xcarchive");
3624
+ if (schemeConfig.sandbox) {
3625
+ if (!appFromArchive) throw new Error(`The archive ${archivePath} has no app to patch.`);
3626
+ await patchSandboxArchive({
3627
+ archivePath,
3628
+ appPath: appFromArchive,
3629
+ schemeConfig,
3630
+ plan: sandbox
3631
+ });
2256
3632
  }
3633
+ const archivedAppPath = appFromArchive ? path.join(archiveDir, path.basename(appFromArchive)) : void 0;
3634
+ if (appFromArchive && archivedAppPath) await fs.promises.cp(appFromArchive, archivedAppPath, { recursive: true });
2257
3635
  if (!schemeConfig.exportOptionsPlist && !authenticationArgs) return {
2258
3636
  buildDirectory,
2259
3637
  buildArtifactPath: archivePath,
3638
+ logFilePath,
2260
3639
  builtApp: archivedAppPath ? await readBuiltApp(archivedAppPath) : void 0
2261
3640
  };
2262
- await fs$1.promises.mkdir(exportDir, { recursive: true });
3641
+ await fs.promises.mkdir(exportDir, { recursive: true });
2263
3642
  const exportArchive = (exportOptionsPlist) => exportXcodeArchive({
2264
3643
  archivePath,
2265
3644
  exportPath: exportDir,
@@ -2267,55 +3646,49 @@ const archiveAndExport = async ({ schemeConfig, minBundleId, buildDirectory, aut
2267
3646
  exportExtraParams: schemeConfig.exportExtraParams,
2268
3647
  exportOptionsPlist,
2269
3648
  sourceDir: iosProjectRoot,
2270
- logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build-export`
3649
+ logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build`,
3650
+ logFilePath: logFilePath ?? void 0,
3651
+ title: schemeConfig.scheme
2271
3652
  });
2272
- if (schemeConfig.exportOptionsPlist) await exportArchive(schemeConfig.exportOptionsPlist);
3653
+ const { exportOptionsPlist } = schemeConfig;
3654
+ if (exportOptionsPlist && !schemeConfig.sandbox) await exportArchive(exportOptionsPlist);
2273
3655
  else {
2274
3656
  const exportOptionsDir = await createRandomTmpDir();
2275
3657
  try {
2276
- await exportArchive(await writeAppStoreConnectExportOptions(exportOptionsDir));
3658
+ await exportArchive(exportOptionsPlist ? await resolveSandboxExportOptions(schemeConfig.hotUpdaterSchemeName, exportOptionsPlist, exportOptionsDir) : await writeAppStoreConnectExportOptions(exportOptionsDir, { internalTestingOnly: schemeConfig.sandbox }));
2277
3659
  } finally {
2278
3660
  await removeTmpDir(exportOptionsDir);
2279
3661
  }
2280
3662
  }
2281
- const ipaFile = fs$1.readdirSync(exportDir).find((file) => file.endsWith(".ipa"));
3663
+ await keepOnlyIpas(exportDir);
3664
+ const ipaFile = fs.readdirSync(exportDir).find((file) => file.endsWith(".ipa"));
2282
3665
  if (!ipaFile) throw new Error("IPA file not found after export");
2283
3666
  return {
2284
3667
  buildDirectory,
2285
- buildArtifactPath: path$1.join(exportDir, ipaFile),
3668
+ buildArtifactPath: path.join(exportDir, ipaFile),
3669
+ logFilePath,
2286
3670
  builtApp: archivedAppPath ? await readBuiltApp(archivedAppPath) : void 0
2287
3671
  };
2288
3672
  };
3673
+ /**
3674
+ * Leaves only the `.ipa` in an export's folder. Xcode writes `Packaging.log`
3675
+ * beside it, which holds the API key's bearer token for its 20 minutes, and the
3676
+ * build's output and its cache copy the whole build directory into the project.
3677
+ */
3678
+ const keepOnlyIpas = async (exportDir) => {
3679
+ for (const entry of await fs.promises.readdir(exportDir)) if (!entry.endsWith(".ipa")) await fs.promises.rm(path.join(exportDir, entry), {
3680
+ recursive: true,
3681
+ force: true
3682
+ });
3683
+ };
2289
3684
  const extractAppFromXcarchive = (archivePath) => {
2290
- const productsPath = path$1.join(archivePath, "Products", "Applications");
2291
- if (!fs$1.existsSync(productsPath)) return;
2292
- const appFile = fs$1.readdirSync(productsPath).find((file) => file.endsWith(".app"));
2293
- if (appFile) return path$1.join(productsPath, appFile);
3685
+ const productsPath = path.join(archivePath, "Products", "Applications");
3686
+ if (!fs.existsSync(productsPath)) return;
3687
+ const appFile = fs.readdirSync(productsPath).find((file) => file.endsWith(".app"));
3688
+ if (appFile) return path.join(productsPath, appFile);
2294
3689
  p.log.warn("Failed to extract .app from xcarchive");
2295
3690
  };
2296
3691
  //#endregion
2297
- //#region src/utils/enrichNativeBuildIosScheme.ts
2298
- const resolveExportOptionsPlist = (exportOptionsPlist) => {
2299
- const resolvedExportOptionsPlist = exportOptionsPlist ? path$1.isAbsolute(exportOptionsPlist) ? exportOptionsPlist : path$1.resolve(getCwd(), exportOptionsPlist) : void 0;
2300
- if (resolvedExportOptionsPlist && !fs$1.existsSync(resolvedExportOptionsPlist)) {
2301
- p.log.error(`exportOptionsPlist doesn't exist in ${resolvedExportOptionsPlist}`);
2302
- process.exit(1);
2303
- }
2304
- return resolvedExportOptionsPlist;
2305
- };
2306
- const enrichNativeBuildIosScheme = async ({ scheme, hotUpdaterSchemeName }) => {
2307
- return {
2308
- platform: "ios",
2309
- installPods: false,
2310
- configuration: "Release",
2311
- destination: [],
2312
- simulator: false,
2313
- ...scheme,
2314
- exportOptionsPlist: resolveExportOptionsPlist(scheme.exportOptionsPlist),
2315
- hotUpdaterSchemeName
2316
- };
2317
- };
2318
- //#endregion
2319
3692
  //#region src/utils/extractBuiltInBundle.ts
2320
3693
  /** The file React Native's Xcode build phase writes into the `.app`. */
2321
3694
  const BUILT_IN_BUNDLE = "main.jsbundle";
@@ -2325,16 +3698,16 @@ const BUILT_IN_BUNDLE = "main.jsbundle";
2325
3698
  * the built-in bundle, byte for byte, which no rebuild reproduces.
2326
3699
  */
2327
3700
  const extractBuiltInBundle = async ({ artifactPath, outputPath }) => {
2328
- await fs$1.promises.mkdir(path$1.dirname(outputPath), { recursive: true });
2329
- if (path$1.extname(artifactPath) === ".app") {
2330
- const source = path$1.join(artifactPath, BUILT_IN_BUNDLE);
2331
- if (!fs$1.existsSync(source)) throw new Error(`${path$1.basename(artifactPath)} has no ${BUILT_IN_BUNDLE}. A debug build loads its bundle from Metro instead.`);
2332
- await fs$1.promises.copyFile(source, outputPath);
3701
+ await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });
3702
+ if (path.extname(artifactPath) === ".app") {
3703
+ const source = path.join(artifactPath, BUILT_IN_BUNDLE);
3704
+ if (!fs.existsSync(source)) throw new Error(`${path.basename(artifactPath)} has no ${BUILT_IN_BUNDLE}. A debug build loads its bundle from Metro instead.`);
3705
+ await fs.promises.copyFile(source, outputPath);
2333
3706
  return;
2334
3707
  }
2335
3708
  const { stdout } = await execa("unzip", ["-Z1", artifactPath]);
2336
3709
  const entry = stdout.split("\n").find((name) => /^Payload\/[^/]+\.app\/main\.jsbundle$/u.test(name.trim()))?.trim();
2337
- if (entry === void 0) throw new Error(`${path$1.basename(artifactPath)} has no Payload/<App>.app/${BUILT_IN_BUNDLE}.`);
3710
+ if (entry === void 0) throw new Error(`${path.basename(artifactPath)} has no Payload/<App>.app/${BUILT_IN_BUNDLE}.`);
2338
3711
  await execa("unzip", [
2339
3712
  "-p",
2340
3713
  artifactPath,
@@ -2346,7 +3719,7 @@ const extractBuiltInBundle = async ({ artifactPath, outputPath }) => {
2346
3719
  * `outputPath`, which then holds the `.app` directory.
2347
3720
  */
2348
3721
  const extractAppBundle = async ({ archivePath, outputPath }) => {
2349
- await fs$1.promises.mkdir(outputPath, { recursive: true });
3722
+ await fs.promises.mkdir(outputPath, { recursive: true });
2350
3723
  await execa("ditto", [
2351
3724
  "-x",
2352
3725
  "-k",
@@ -2359,8 +3732,8 @@ const extractAppBundle = async ({ archivePath, outputPath }) => {
2359
3732
  * so a simulator build uploads and downloads as a single artifact.
2360
3733
  */
2361
3734
  const archiveAppBundle = async ({ appPath, outputPath }) => {
2362
- await fs$1.promises.mkdir(path$1.dirname(outputPath), { recursive: true });
2363
- await fs$1.promises.rm(outputPath, { force: true });
3735
+ await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });
3736
+ await fs.promises.rm(outputPath, { force: true });
2364
3737
  await execa("ditto", [
2365
3738
  "-c",
2366
3739
  "-k",
@@ -2371,4 +3744,97 @@ const archiveAppBundle = async ({ appPath, outputPath }) => {
2371
3744
  ]);
2372
3745
  };
2373
3746
  //#endregion
2374
- export { ASC_INTEGRATIONS_URL, TestFlightBuildExistsError, archiveAppBundle, assertTestFlightExportOptions, buildIos, enrichNativeBuildIosScheme, extractAppBundle, extractBuiltInBundle, findTestFlightBuild, installPodsIfNeeded, issueAscApiKey, resolveTestFlightUploadKey, uploadToTestFlight };
3747
+ //#region src/simulator.ts
3748
+ const simctl = async (args) => {
3749
+ try {
3750
+ return (await execa("xcrun", ["simctl", ...args])).stdout;
3751
+ } catch (error) {
3752
+ const { code, stderr, shortMessage } = error;
3753
+ if (code === "ENOENT") throw new Error("The iOS Simulator needs Xcode on a Mac.\nInstall Xcode, then run this again.");
3754
+ throw new Error(stderr?.trim() || shortMessage || String(error));
3755
+ }
3756
+ };
3757
+ /** Every simulator on this Mac, booted or not. */
3758
+ const listSimulators = async () => {
3759
+ const { devices } = JSON.parse(await simctl([
3760
+ "list",
3761
+ "devices",
3762
+ "--json"
3763
+ ]));
3764
+ return Object.values(devices).flat().map(({ udid, name, state }) => ({
3765
+ udid,
3766
+ name,
3767
+ state
3768
+ }));
3769
+ };
3770
+ /**
3771
+ * The simulator to install on: `udid`, or else the only booted one, by its
3772
+ * UDID. `simctl`'s own `booted` alias picks one of several by itself.
3773
+ */
3774
+ const selectSimulator = (simulators, udid) => {
3775
+ if (udid !== void 0) {
3776
+ const simulator = simulators.find((candidate) => candidate.udid === udid);
3777
+ if (simulator === void 0) throw new Error(`No iOS Simulator has the UDID ${udid}.\nList them: xcrun simctl list devices`);
3778
+ if (simulator.state !== "Booted") throw new Error(`${simulator.name} isn't booted.\nBoot it: xcrun simctl boot ${udid}`);
3779
+ return simulator;
3780
+ }
3781
+ const booted = simulators.filter(({ state }) => state === "Booted");
3782
+ const [only] = booted;
3783
+ if (only === void 0) throw new Error("No iOS Simulator is booted.\nBoot one: open -a Simulator");
3784
+ if (booted.length > 1) throw new Error([
3785
+ `${booted.length} iOS Simulators are booted:`,
3786
+ ...booted.map(({ udid, name }) => ` ${udid} ${name}`),
3787
+ "Pick one with --simulator <udid>."
3788
+ ].join("\n"));
3789
+ return only;
3790
+ };
3791
+ /**
3792
+ * Unpacks a simulator build's `.app.zip` into `outputPath`, and returns the
3793
+ * `.app` in it.
3794
+ */
3795
+ const extractSimulatorApp = async ({ archivePath, outputPath }) => {
3796
+ await extractAppBundle({
3797
+ archivePath,
3798
+ outputPath
3799
+ });
3800
+ const app = (await fs.promises.readdir(outputPath)).find((entry) => entry.endsWith(".app"));
3801
+ if (app === void 0) throw new Error(`${path.basename(archivePath)} holds no .app.`);
3802
+ return path.join(outputPath, app);
3803
+ };
3804
+ /** Installs a `.app` on a booted simulator, and opens it. */
3805
+ const installOnSimulator = async ({ udid, appPath, appId }) => {
3806
+ await simctl([
3807
+ "install",
3808
+ udid,
3809
+ appPath
3810
+ ]);
3811
+ await simctl([
3812
+ "launch",
3813
+ udid,
3814
+ appId
3815
+ ]);
3816
+ };
3817
+ //#endregion
3818
+ //#region src/utils/enrichNativeBuildIosScheme.ts
3819
+ const resolveExportOptionsPlist = (exportOptionsPlist) => {
3820
+ const resolvedExportOptionsPlist = exportOptionsPlist ? path.isAbsolute(exportOptionsPlist) ? exportOptionsPlist : path.resolve(getCwd(), exportOptionsPlist) : void 0;
3821
+ if (resolvedExportOptionsPlist && !fs.existsSync(resolvedExportOptionsPlist)) {
3822
+ p.log.error(`exportOptionsPlist doesn't exist in ${resolvedExportOptionsPlist}`);
3823
+ process.exit(1);
3824
+ }
3825
+ return resolvedExportOptionsPlist;
3826
+ };
3827
+ const enrichNativeBuildIosScheme = async ({ scheme, hotUpdaterSchemeName }) => {
3828
+ return {
3829
+ platform: "ios",
3830
+ installPods: false,
3831
+ configuration: "Release",
3832
+ destination: [],
3833
+ simulator: false,
3834
+ ...scheme,
3835
+ exportOptionsPlist: resolveExportOptionsPlist(scheme.exportOptionsPlist),
3836
+ hotUpdaterSchemeName
3837
+ };
3838
+ };
3839
+ //#endregion
3840
+ export { ASC_INTEGRATIONS_URL, TestFlightBuildExistsError, addAscDevices, applyTestFlightGroup, archiveAppBundle, assertBuildIsInternalOnly, assertIpaIsInternalOnly, assertSandboxExportOptions, assertTestFlightExportOptions, buildIos, distributeTestFlightBuild, enrichNativeBuildIosScheme, extractAppBundle, extractBuiltInBundle, extractSimulatorApp, findInternalBetaGroup, findTestFlightBuild, installOnSimulator, installPodsIfNeeded, isVersionTrainClosed, issueAscApiKey, listAscDevices, listSimulators, prepareSandboxArchive, readIpaHasExportComplianceKey, readTestFlightBuildStatus, resolveTestFlightUploadKey, selectSimulator, uploadToTestFlight };