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