Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

swift-testflight.ts

680 lines25.6 KB

1#!/usr/bin/env node
2​
3// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalFetch:off preferSchemaOverJson:off - This standalone release tool uses Node APIs and validates JSON at the API boundary.
4import * as NodeCrypto from "node:crypto";
5import * as NodeChildProcess from "node:child_process";
6import * as NodeFSP from "node:fs/promises";
7import * as NodeOS from "node:os";
8import * as NodePath from "node:path";
9import * as NodeUtil from "node:util";
10​
11const API_ORIGIN = "https://api.appstoreconnect.apple.com";
12const BUNDLE_ID = "com.t3tools.t3code.swiftui";
13const TOKEN_SECONDS = 600;
14​
15function isRecord(value: unknown): value is Record<string, unknown> {
16 return typeof value === "object" && value !== null && !Array.isArray(value);
18​
19function record(value: unknown, label: string) {
20 if (!isRecord(value)) throw new Error(`Expected an object for ${label}.`);
21 return value;
23​
24function text(value: unknown, label: string) {
25 if (typeof value !== "string" || !value.trim()) {
26 throw new Error(`Expected a nonempty string for ${label}.`);
27 }
28 return value;
30​
31function boolean(value: unknown, label: string) {
32 if (typeof value !== "boolean") throw new Error(`Expected a boolean for ${label}.`);
33 return value;
35​
36function items(value: unknown, label: string): unknown[] {
37 if (!Array.isArray(value)) throw new Error(`Expected a list for ${label}.`);
38 return value;
40​
41function resource(value: unknown, type: string) {
42 const data = record(value, type);
43 if (data.type !== type) throw new Error(`Expected an App Store Connect ${type} resource.`);
44 return {
45 id: text(data.id, `${type}.id`),
46 attributes: record(data.attributes ?? {}, `${type}.attributes`),
47 relationships: record(data.relationships ?? {}, `${type}.relationships`),
48 };
50​
51type Resource = ReturnType<typeof resource>;
52​
53function relationship(value: Resource, name: string, type: string) {
54 const relation = record(value.relationships[name], `${name} relationship`);
55 return relation.data === null ? undefined : resource(relation.data, type).id;
57​
58export function parseTestFlightEnv(source: string) {
59 const env = NodeUtil.parseEnv(source);
60 const config = {
61 keyId: text(env.T3_SWIFT_ASC_KEY_ID, "T3_SWIFT_ASC_KEY_ID"),
62 issuerId: text(env.T3_SWIFT_ASC_ISSUER_ID, "T3_SWIFT_ASC_ISSUER_ID"),
63 appId: text(env.T3_SWIFT_ASC_APP_ID, "T3_SWIFT_ASC_APP_ID"),
64 publicGroupId: text(env.T3_SWIFT_ASC_PUBLIC_GROUP_ID, "T3_SWIFT_ASC_PUBLIC_GROUP_ID"),
65 internalGroupId: text(env.T3_SWIFT_ASC_INTERNAL_GROUP_ID, "T3_SWIFT_ASC_INTERNAL_GROUP_ID"),
66 };
67 if (config.publicGroupId === config.internalGroupId) {
68 throw new Error("Public and internal groups must be different.");
69 }
70 const encodedKey = text(env.T3_SWIFT_ASC_PRIVATE_KEY_BASE64, "T3_SWIFT_ASC_PRIVATE_KEY_BASE64");
71 let privateKey: NodeCrypto.KeyObject;
72 try {
73 const decoded = Buffer.from(encodedKey, "base64");
74 if (decoded.toString("base64") !== encodedKey) throw new Error("invalid base64");
75 privateKey = NodeCrypto.createPrivateKey(decoded);
76 } catch {
77 throw new Error("T3_SWIFT_ASC_PRIVATE_KEY_BASE64 must contain the base64-encoded .p8 file.");
78 }
79 requireAppStorePrivateKey(privateKey);
80 return { config, privateKey };
82​
83type TestFlightConfig = ReturnType<typeof parseTestFlightEnv>["config"];
84type BuildSelection = { build: string; version: string };
85​
86export async function readTestFlightEnv(path: string) {
87 let file: NodeFSP.FileHandle | undefined;
88 let source: string;
89 try {
90 file = await NodeFSP.open(expandHome(path), "r");
91 const metadata = await file.stat();
92 if (!metadata.isFile() || (metadata.mode & 0o077) !== 0) {
93 throw new Error("unsafe permissions");
94 }
95 source = await file.readFile("utf8");
96 } catch {
97 throw new Error(
98 `Cannot read TestFlight env file at ${path}. Use a private file with mode 600.`,
99 );
100 } finally {
101 await file?.close();
102 }
103 return parseTestFlightEnv(source);
105​
106function validateBuildSelection(selection: BuildSelection) {
107 if (
108 !/^\d+(?:\.\d+){0,2}$/u.test(selection.build) ||
109 !/^\d+\.\d+(?:\.\d+)?$/u.test(selection.version)
110 ) {
111 throw new Error("Use an exact numeric build number and version.");
112 }
113 return selection;
115​
116function requireAppStorePrivateKey(privateKey: NodeCrypto.KeyObject) {
117 if (
118 privateKey.type !== "private" ||
119 privateKey.asymmetricKeyType !== "ec" ||
120 privateKey.asymmetricKeyDetails?.namedCurve !== "prime256v1"
121 ) {
122 throw new Error("App Store Connect requires a P-256 private key.");
123 }
125​
126export function makeAppStoreToken(
127 config: Pick<TestFlightConfig, "keyId" | "issuerId">,
128 privateKey: NodeCrypto.KeyObject,
129 nowSeconds = Math.floor(Date.now() / 1_000),
130) {
131 requireAppStorePrivateKey(privateKey);
132 const header = Buffer.from(
133 JSON.stringify({ alg: "ES256", kid: config.keyId, typ: "JWT" }),
134 ).toString("base64url");
135 const payload = Buffer.from(
136 JSON.stringify({
137 iss: config.issuerId,
138 iat: nowSeconds,
139 exp: nowSeconds + TOKEN_SECONDS,
140 aud: "appstoreconnect-v1",
141 }),
142 ).toString("base64url");
143 const input = `${header}.${payload}`;
144 const signature = NodeCrypto.sign("sha256", Buffer.from(input), {
145 key: privateKey,
146 dsaEncoding: "ieee-p1363",
147 });
148 return `${input}.${signature.toString("base64url")}`;
150​
151// All writes use the app and groups verified by status(). No credentials go into command output.
152export function createTestFlightClient(
153 config: TestFlightConfig,
154 privateKey: NodeCrypto.KeyObject,
155 fetchImpl: typeof fetch = fetch,
156) {
157 async function request(path: string, method = "GET", body?: unknown): Promise<unknown> {
158 const url = new URL(path, API_ORIGIN);
159 if (url.origin !== API_ORIGIN || !url.pathname.startsWith("/v1/")) {
160 throw new Error("Refusing an App Store Connect request to an unexpected URL.");
161 }
162 const operation = `${method} ${url.pathname}`;
163 const uncertainWrite =
164 method === "GET" ? "" : " The write was not retried. Run status before trying again.";
165 const token = makeAppStoreToken(config, privateKey);
166 let response: Response;
167 try {
168 response = await fetchImpl(url, {
169 method,
170 headers: {
171 Authorization: `Bearer ${token}`,
172 "Content-Type": "application/json",
173 },
174 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
175 redirect: "error",
176 signal: AbortSignal.timeout(30_000),
177 });
178 } catch {
179 throw new Error(`App Store Connect ${operation} failed or timed out.${uncertainWrite}`);
180 }
181 if (response.status === 204 && response.ok) return undefined;
182 const result: unknown = await response.json().catch(() => undefined);
183 if (!response.ok) {
184 const details =
185 isRecord(result) && Array.isArray(result.errors)
186 ? result.errors
187 .filter(isRecord)
188 .map((error) =>
189 [error.code, error.title, error.detail]
190 .filter((part): part is string => typeof part === "string")
191 .join(": "),
192 )
193 .join("; ")
194 .replaceAll(token, "[redacted token]")
195 : "";
196 throw new Error(
197 `App Store Connect ${operation}: HTTP ${response.status}${details ? ` (${details.slice(0, 1_000)})` : ""}.${uncertainWrite}`,
198 );
199 }
200 return result;
201 }
202​
203 async function getResource(path: string, type: string) {
204 const response = record(await request(path), type);
205 return resource(response.data, type);
206 }
207​
208 async function list(path: string, type: string) {
209 const result: Resource[] = [];
210 const visited = new Set<string>();
211 let next: string | undefined = path;
212 while (next) {
213 if (visited.has(next)) throw new Error("App Store Connect repeated a page URL.");
214 visited.add(next);
215 const response = record(await request(next), `${type} response`);
216 result.push(...items(response.data, type).map((item) => resource(item, type)));
217 const links = record(response.links ?? {}, `${type} links`);
218 next =
219 links.next === undefined || links.next === null ? undefined : text(links.next, "next page");
220 }
221 return result;
222 }
223​
224 async function group(id: string, internal: boolean) {
225 const value = await getResource(
226 `/v1/betaGroups/${encodeURIComponent(id)}?include=app`,
227 "betaGroups",
228 );
229 if (value.id !== id || relationship(value, "app", "apps") !== config.appId) {
230 throw new Error("Refusing a beta group that does not belong to the configured SwiftUI app.");
231 }
232 if (boolean(value.attributes.isInternalGroup, "isInternalGroup") !== internal) {
233 throw new Error("The configured beta group has the wrong internal/external type.");
234 }
235 return {
236 id,
237 name: text(value.attributes.name, "group name"),
238 internal,
239 allBuilds: value.attributes.hasAccessToAllBuilds === true,
240 publicLinkEnabled: value.attributes.publicLinkEnabled === true,
241 };
242 }
243​
244 async function verifyApp() {
245 const app = await getResource(`/v1/apps/${encodeURIComponent(config.appId)}`, "apps");
246 if (app.id !== config.appId || app.attributes.bundleId !== BUNDLE_ID) {
247 throw new Error(`Refusing to use an app other than ${BUNDLE_ID}. Check appId.`);
248 }
249 return app;
250 }
251​
252 function buildQuery(selection: BuildSelection) {
253 validateBuildSelection(selection);
254 return new URLSearchParams({
255 "filter[app]": config.appId,
256 "filter[version]": selection.build,
257 "filter[preReleaseVersion.version]": selection.version,
258 "filter[preReleaseVersion.platform]": "IOS",
259 limit: "2",
260 });
261 }
262​
263 async function verifyUpload(selection: BuildSelection) {
264 await Promise.all([
265 verifyApp(),
266 group(config.internalGroupId, true),
267 group(config.publicGroupId, false),
268 ]);
269 const existing = await list(`/v1/builds?${buildQuery(selection)}`, "builds");
270 if (existing.length > 0) {
271 throw new Error(
272 `Build ${selection.version} (${selection.build}) already exists. Run status; refusing another upload.`,
273 );
274 }
275 }
276​
277 async function status(selection: BuildSelection) {
278 const [app, internalGroup, publicGroup] = await Promise.all([
279 verifyApp(),
280 group(config.internalGroupId, true),
281 group(config.publicGroupId, false),
282 ]);
283 const query = buildQuery(selection);
284 query.set("include", "app,preReleaseVersion,buildBetaDetail,betaAppReviewSubmission");
285 const response = record(await request(`/v1/builds?${query}`), "builds response");
286 const builds = items(response.data, "builds");
287 if (builds.length !== 1) {
288 throw new Error(
289 `Expected one SwiftUI build ${selection.version} (${selection.build}); found ${builds.length}.`,
290 );
291 }
292 const build = resource(builds[0], "builds");
293 if (
294 relationship(build, "app", "apps") !== app.id ||
295 build.attributes.version !== selection.build
296 ) {
297 throw new Error("App Store Connect returned a different app or build. Nothing was changed.");
298 }
299 const included = items(response.included ?? [], "included resources").map((value) =>
300 record(value, "included resource"),
301 );
302 function includedResource(name: string, type: string) {
303 const id = relationship(build, name, type);
304 if (!id) return undefined;
305 const value = included.find((item) => item.type === type && item.id === id);
306 if (!value) throw new Error(`App Store Connect omitted the build's ${name}.`);
307 return resource(value, type);
308 }
309 const version = includedResource("preReleaseVersion", "preReleaseVersions");
310 if (
311 version?.attributes.version !== selection.version ||
312 version.attributes.platform !== "IOS"
313 ) {
314 throw new Error(
315 "App Store Connect returned a different version or platform. Nothing was changed.",
316 );
317 }
318 async function optionalBuildResource(name: string, type: string) {
319 const relation = build.relationships[name];
320 if (isRecord(relation) && relation.data !== undefined) return includedResource(name, type);
321 // A missing linkage is not proof that no review exists. Read the filtered collection.
322 const query = new URLSearchParams({ "filter[build]": build.id, limit: "2" });
323 const values = await list(`/v1/${type}?${query}`, type);
324 if (values.length > 1)
325 throw new Error(`App Store Connect returned multiple ${name} resources.`);
326 return values[0];
327 }
328 const [detail, review] = await Promise.all([
329 optionalBuildResource("buildBetaDetail", "buildBetaDetails"),
330 optionalBuildResource("betaAppReviewSubmission", "betaAppReviewSubmissions"),
331 ]);
332 // Apple accepts one relationship filter. The build's app was checked above.
333 const membershipQuery = new URLSearchParams({
334 "filter[builds]": build.id,
335 limit: "200",
336 });
337 const memberships = await list(`/v1/betaGroups?${membershipQuery}`, "betaGroups");
338 const groups = [internalGroup, publicGroup].map((item) => ({
339 ...item,
340 assigned:
341 memberships.some((member) => member.id === item.id) || (item.internal && item.allBuilds),
342 }));
343 const externalState = detail
344 ? text(detail.attributes.externalBuildState, "externalBuildState")
345 : undefined;
346 return {
347 appId: app.id,
348 appName: text(app.attributes.name, "app name"),
349 bundleId: BUNDLE_ID,
350 primaryLocale: text(app.attributes.primaryLocale, "primaryLocale"),
351 buildId: build.id,
352 ...selection,
353 processingState: text(build.attributes.processingState, "processingState"),
354 expired: boolean(build.attributes.expired, "expired"),
355 audience: text(build.attributes.buildAudienceType, "buildAudienceType"),
356 detailId: detail?.id,
357 externalState,
358 internalState: detail
359 ? text(detail.attributes.internalBuildState, "internalBuildState")
360 : undefined,
361 autoNotifyEnabled: detail
362 ? boolean(detail.attributes.autoNotifyEnabled, "autoNotifyEnabled")
363 : false,
364 reviewState: review ? text(review.attributes.betaReviewState, "betaReviewState") : undefined,
365 groups,
366 publicTesting:
367 externalState === "IN_BETA_TESTING" &&
368 groups.some((item) => !item.internal && item.assigned && item.publicLinkEnabled),
369 };
370 }
371​
372 function requirePublishable(current: Awaited<ReturnType<typeof status>>) {
373 if (current.expired) throw new Error("This build has expired. Upload a new build.");
374 if (current.processingState !== "VALID") {
375 throw new Error(`Build processing is ${current.processingState}. Nothing was published.`);
376 }
377 if (current.audience !== "APP_STORE_ELIGIBLE") {
378 throw new Error("This build is internal-only and cannot be released to the public beta.");
379 }
380 if (!current.groups.some((item) => !item.internal && item.publicLinkEnabled)) {
381 throw new Error("The configured public beta group does not have an enabled public link.");
382 }
383 const allowed = [
384 "READY_FOR_BETA_SUBMISSION",
385 "WAITING_FOR_BETA_REVIEW",
386 "IN_BETA_REVIEW",
387 "BETA_APPROVED",
388 "READY_FOR_BETA_TESTING",
389 "IN_BETA_TESTING",
390 ];
391 if (
392 !current.externalState ||
393 !allowed.includes(current.externalState) ||
394 current.reviewState === "REJECTED"
395 ) {
396 throw new Error(
397 `Build is not ready for publication: ${current.externalState ?? "no beta details"}${current.reviewState ? ` (${current.reviewState})` : ""}.`,
398 );
399 }
400 return text(current.detailId, "build beta detail ID");
401 }
402​
403 async function publish(selection: BuildSelection, notes: string) {
404 const whatsNew = notes.trim();
405 if (!whatsNew || whatsNew.length > 4_000) {
406 throw new Error("TestFlight notes must contain between 1 and 4,000 characters.");
407 }
408 let current = await status(selection);
409 const detailId = requirePublishable(current);
410 const localizations = await list(
411 `/v1/builds/${encodeURIComponent(current.buildId)}/betaBuildLocalizations?limit=200`,
412 "betaBuildLocalizations",
413 );
414 const localization = localizations.find(
415 (item) => item.attributes.locale === current.primaryLocale,
416 );
417 if (localization && localization.attributes.whatsNew !== whatsNew) {
418 await request(`/v1/betaBuildLocalizations/${encodeURIComponent(localization.id)}`, "PATCH", {
419 data: { type: "betaBuildLocalizations", id: localization.id, attributes: { whatsNew } },
420 });
421 } else if (!localization) {
422 await request("/v1/betaBuildLocalizations", "POST", {
423 data: {
424 type: "betaBuildLocalizations",
425 attributes: { locale: current.primaryLocale, whatsNew },
426 relationships: { build: { data: { type: "builds", id: current.buildId } } },
427 },
428 });
429 }
430 if (!current.autoNotifyEnabled) {
431 await request(`/v1/buildBetaDetails/${encodeURIComponent(detailId)}`, "PATCH", {
432 data: { type: "buildBetaDetails", id: detailId, attributes: { autoNotifyEnabled: true } },
433 });
434 }
435 for (const id of [config.internalGroupId, config.publicGroupId]) {
436 current = await status(selection);
437 requirePublishable(current);
438 if (current.groups.some((item) => item.id === id && item.assigned)) continue;
439 await request(`/v1/betaGroups/${encodeURIComponent(id)}/relationships/builds`, "POST", {
440 data: [{ type: "builds", id: current.buildId }],
441 });
442 }
443 current = await status(selection);
444 requirePublishable(current);
445 if (current.externalState === "READY_FOR_BETA_SUBMISSION" && !current.reviewState) {
446 await request("/v1/betaAppReviewSubmissions", "POST", {
447 data: {
448 type: "betaAppReviewSubmissions",
449 relationships: { build: { data: { type: "builds", id: current.buildId } } },
450 },
451 });
452 } else if (
453 current.externalState === "READY_FOR_BETA_TESTING" ||
454 current.externalState === "BETA_APPROVED"
455 ) {
456 await request("/v1/buildBetaNotifications", "POST", {
457 data: {
458 type: "buildBetaNotifications",
459 relationships: { build: { data: { type: "builds", id: current.buildId } } },
460 },
461 });
462 }
463 return status(selection);
464 }
465​
466 return { status, publish, verifyUpload };
468​
469export function validateUploadMetadata(infoPlist: unknown, exportOptions: unknown) {
470 const info = record(infoPlist, "archived app Info.plist");
471 if (info.CFBundleIdentifier !== BUNDLE_ID || info.DTPlatformName !== "iphoneos") {
472 throw new Error("Upload requires an iPhoneOS archive of the Release SwiftUI app.");
473 }
474 const options = record(exportOptions, "export options");
475 if (options.method !== "app-store-connect" || options.destination !== "upload") {
476 throw new Error("Export options must use method app-store-connect and destination upload.");
477 }
478 if (options.manageAppVersionAndBuildNumber !== false) {
479 throw new Error("Export options must set manageAppVersionAndBuildNumber to false.");
480 }
481 if (options.testFlightInternalTestingOnly === true) {
482 throw new Error("Refusing an internal-only export for the public TestFlight app.");
483 }
484 return validateBuildSelection({
485 build: text(info.CFBundleVersion, "CFBundleVersion"),
486 version: text(info.CFBundleShortVersionString, "CFBundleShortVersionString"),
487 });
489​
490async function readPlist(path: string): Promise<unknown> {
491 const execFile = NodeUtil.promisify(NodeChildProcess.execFile);
492 try {
493 const { stdout } = await execFile("/usr/bin/plutil", ["-convert", "json", "-o", "-", path], {
494 encoding: "utf8",
495 timeout: 10_000,
496 maxBuffer: 2 * 1_024 * 1_024,
497 });
498 return JSON.parse(stdout);
499 } catch {
500 throw new Error(`Cannot read plist at ${path}.`);
501 }
503​
504async function uploadArchive(
505 archive: string,
506 exportOptions: string,
507 config: TestFlightConfig,
508 privateKey: NodeCrypto.KeyObject,
509 verifyUpload: (selection: BuildSelection) => Promise<void>,
510) {
511 const archivePath = NodePath.resolve(expandHome(archive));
512 const optionsPath = NodePath.resolve(expandHome(exportOptions));
513 const [info, options] = await Promise.all([
514 readPlist(NodePath.join(archivePath, "Products/Applications/T3Code.app/Info.plist")),
515 readPlist(optionsPath),
516 ]);
517 const selection = validateUploadMetadata(info, options);
518 await verifyUpload(selection);
519 await withTemporaryPrivateKey(
520 privateKey,
521 (keyPath) =>
522 new Promise<void>((resolve, reject) => {
523 const child = NodeChildProcess.spawn(
524 "xcodebuild",
525 [
526 "-exportArchive",
527 "-archivePath",
528 archivePath,
529 "-exportOptionsPlist",
530 optionsPath,
531 "-authenticationKeyPath",
532 keyPath,
533 "-authenticationKeyID",
534 config.keyId,
535 "-authenticationKeyIssuerID",
536 config.issuerId,
537 ],
538 { stdio: "inherit" },
539 );
540 child.once("error", () => reject(new Error("Could not start xcodebuild.")));
541 child.once("exit", (code) =>
542 code === 0
543 ? resolve()
544 : reject(new Error("Xcode upload failed. Check status before trying another upload.")),
545 );
546 }),
547 );
548 process.stdout.write(
549 `Xcode uploaded SwiftUI ${selection.version} (${selection.build}). Check status after Apple processes it.\n`,
550 );
552​
553// Xcode needs a file. REST requests use only the in-memory key.
554export async function withTemporaryPrivateKey(
555 privateKey: NodeCrypto.KeyObject,
556 operation: (keyPath: string) => Promise<void>,
557) {
558 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-swift-testflight-"));
559 try {
560 await NodeFSP.chmod(directory, 0o700);
561 const keyPath = NodePath.join(directory, "AuthKey.p8");
562 await NodeFSP.writeFile(keyPath, privateKey.export({ format: "pem", type: "pkcs8" }), {
563 mode: 0o600,
564 flag: "wx",
565 });
566 await operation(keyPath);
567 } finally {
568 await NodeFSP.rm(directory, { recursive: true, force: true });
569 }
571​
572export function parseTestFlightArgs(args: string[]) {
573 const { values, positionals } = NodeUtil.parseArgs({
574 args,
575 allowPositionals: true,
576 options: {
577 "env-file": { type: "string" },
578 build: { type: "string" },
579 version: { type: "string" },
580 "notes-file": { type: "string" },
581 archive: { type: "string" },
582 "export-options": { type: "string" },
583 help: { type: "boolean" },
584 },
585 });
586 if (values.help) return { command: "help" as const };
587 const command = positionals[0];
588 if (
589 positionals.length !== 1 ||
590 (command !== "status" && command !== "publish" && command !== "upload")
591 ) {
592 throw new Error("Choose status, publish, or upload. Use --help for usage.");
593 }
594 const envFile =
595 values["env-file"] ??
596 process.env.T3_SWIFT_TESTFLIGHT_ENV_FILE ??
597 NodePath.join(NodeOS.homedir(), ".config/t3code/.env.testflight");
598 if (command === "upload") {
599 if (values.build || values.version || values["notes-file"]) {
600 throw new Error(
601 "Upload reads the build and version from the archive; do not supply --build, --version, or --notes-file.",
602 );
603 }
604 return {
605 command: "upload" as const,
606 envFile,
607 archive: text(values.archive, "--archive"),
608 exportOptions: text(values["export-options"], "--export-options"),
609 };
610 }
611 if (values.archive || values["export-options"])
612 throw new Error("Archive options are only valid with upload.");
613 const selection = validateBuildSelection({
614 build: text(values.build, "--build"),
615 version: text(values.version, "--version"),
616 });
617 if (command === "status" && values["notes-file"]) {
618 throw new Error("--notes-file is only valid with publish.");
619 }
620 return command === "publish"
621 ? {
622 command: "publish" as const,
623 envFile,
624 ...selection,
625 notesFile: text(values["notes-file"], "--notes-file"),
626 }
627 : { command: "status" as const, envFile, ...selection };
629​
630function expandHome(path: string) {
631 return path.startsWith("~/") ? NodePath.join(NodeOS.homedir(), path.slice(2)) : path;
633​
634async function main() {
635 const args = parseTestFlightArgs(process.argv.slice(2));
636 if (args.command === "help") {
637 process.stdout.write(`Usage:
638 node scripts/swift-testflight.ts status --build 46 --version 0.1.0
639 node scripts/swift-testflight.ts publish --build 46 --version 0.1.0 --notes-file /path/to/notes.txt
640 node scripts/swift-testflight.ts upload --archive /path/to/T3Code.xcarchive --export-options /path/to/ExportOptions.plist
641​
642Optional: --env-file /path/to/.env or T3_SWIFT_TESTFLIGHT_ENV_FILE.
643Default env file: ~/.config/t3code/.env.testflight (mode 600, never committed).
644Required variables: T3_SWIFT_ASC_KEY_ID, T3_SWIFT_ASC_ISSUER_ID,
645T3_SWIFT_ASC_PRIVATE_KEY_BASE64, T3_SWIFT_ASC_APP_ID,
646T3_SWIFT_ASC_PUBLIC_GROUP_ID, T3_SWIFT_ASC_INTERNAL_GROUP_ID.
647Only the Release SwiftUI app and the two configured existing groups are supported.
648Publish does not upload, create testers, change signing, or expire other builds.
649`);
650 return;
651 }
652 const { config, privateKey } = await readTestFlightEnv(args.envFile);
653 const client = createTestFlightClient(config, privateKey);
654 if (args.command === "upload") {
655 await uploadArchive(args.archive, args.exportOptions, config, privateKey, client.verifyUpload);
656 return;
657 }
658 const selection = { build: args.build, version: args.version };
659 const result =
660 args.command === "publish"
661 ? await client.publish(selection, await NodeFSP.readFile(expandHome(args.notesFile), "utf8"))
662 : await client.status(selection);
663 process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
664 if (args.command === "publish") {
665 process.stdout.write(
666 result.publicTesting
667 ? "Public beta testing is active.\n"
668 : `Public testing is not active yet. Apple reports ${result.externalState ?? result.processingState}. Run status to check again.\n`,
669 );
670 }
672​
673if (import.meta.main) {
674 main().catch((error: unknown) => {
675 process.stderr.write(
676 `${error instanceof Error ? error.message : "TestFlight command failed."}\n`,
677 );
678 process.exitCode = 1;
679 });