@hot-updater/apple-helper 1.2.0-rc.5 → 1.2.0-rc.50

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
@@ -25,6 +25,9 @@ let node_crypto = require("node:crypto");
25
25
  node_crypto = __toESM(node_crypto, 1);
26
26
  let node_timers_promises = require("node:timers/promises");
27
27
  let _hot_updater_cli_tools = require("@hot-updater/cli-tools");
28
+ let _hot_updater_protocol_native_artifact = require("@hot-updater/protocol/native-artifact");
29
+ let crypto = require("crypto");
30
+ crypto = __toESM(crypto, 1);
28
31
  let fs = require("fs");
29
32
  fs = __toESM(fs, 1);
30
33
  let path = require("path");
@@ -35,8 +38,6 @@ let node_fs_promises = require("node:fs/promises");
35
38
  let node_os = require("node:os");
36
39
  let node_path = require("node:path");
37
40
  let child_process = require("child_process");
38
- let crypto = require("crypto");
39
- crypto = __toESM(crypto, 1);
40
41
  let os = require("os");
41
42
  os = __toESM(os, 1);
42
43
  //#region src/asc/appleSrp.ts
@@ -551,6 +552,23 @@ const signInToAppStoreConnect = async ({ appleId, password, prompts, fetch = glo
551
552
  }
552
553
  };
553
554
  //#endregion
555
+ //#region src/asc/programLicenseAgreement.ts
556
+ /**
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".
560
+ */
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
554
572
  //#region src/asc/ascKeyIssuer.ts
555
573
  const IRIS_URL = "https://appstoreconnect.apple.com/iris/v1";
556
574
  /**
@@ -603,7 +621,7 @@ const irisDetail = (body) => {
603
621
  };
604
622
  /** What to do about a key App Store Connect would not create. */
605
623
  const createFailureHint = (status, body) => {
606
- if (/agreement/iu.test(body)) return "The Account Holder must accept the new Apple Developer Program License\nAgreement at https://developer.apple.com/account, then run this again.";
624
+ if (/agreement/iu.test(body)) return PROGRAM_LICENSE_AGREEMENT_HINT;
607
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}`;
608
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.";
609
627
  };
@@ -765,116 +783,6 @@ const ASC_INTEGRATIONS_URL = "https://appstoreconnect.apple.com/access/integrati
765
783
  */
766
784
  const issueAscApiKey = (request) => createAscKeyIssuer()(request);
767
785
  //#endregion
768
- //#region src/utils/cocoapods.ts
769
- const installPodsIfNeeded = async (sourceDir) => {
770
- const podfilePath = path.default.join(sourceDir, "Podfile");
771
- if (!fs.default.existsSync(podfilePath)) {
772
- _hot_updater_cli_tools.p.log.info("No Podfile found, skipping CocoaPods installation");
773
- return;
774
- }
775
- const gemfilePaths = [path.default.join(sourceDir, "Gemfile"), path.default.join((0, _hot_updater_cli_tools.getCwd)(), "Gemfile")];
776
- const shouldUseBundler = (await Promise.all(gemfilePaths.map(checkShouldUseBundler))).some(Boolean);
777
- const reactNative = (0, _hot_updater_cli_tools.getReactNativeMetadatas)();
778
- const plan = resolvePodInstallPlan({
779
- version: reactNative.version,
780
- env: process.env
781
- });
782
- if (plan.runCodegen) await runReactNativeCodegen({
783
- projectRoot: (0, _hot_updater_cli_tools.getCwd)(),
784
- reactNativePath: reactNative.packagePath,
785
- sourceDir
786
- });
787
- try {
788
- if (shouldUseBundler) {
789
- _hot_updater_cli_tools.p.log.info("Using bundler for CocoaPods installation");
790
- const bundleSpinner = _hot_updater_cli_tools.p.spinner();
791
- bundleSpinner.start("Installing Ruby gems");
792
- await (0, execa.execa)("bundle", ["install"], { cwd: sourceDir });
793
- bundleSpinner.stop("Ruby gems installed");
794
- const podSpinner = _hot_updater_cli_tools.p.spinner();
795
- podSpinner.start("Installing CocoaPods dependencies");
796
- await (0, execa.execa)("bundle", [
797
- "exec",
798
- "pod",
799
- "install"
800
- ], {
801
- cwd: sourceDir,
802
- env: plan.env
803
- });
804
- podSpinner.stop("CocoaPods dependencies installed");
805
- } else {
806
- const spinner = _hot_updater_cli_tools.p.spinner();
807
- spinner.start("Installing CocoaPods dependencies");
808
- await (0, execa.execa)("pod", ["install"], {
809
- cwd: sourceDir,
810
- env: plan.env
811
- });
812
- spinner.stop("CocoaPods dependencies installed");
813
- }
814
- } catch (error) {
815
- throw new Error(`pod install failed: ${error}`);
816
- }
817
- };
818
- const checkShouldUseBundler = async (gemfilePath) => {
819
- try {
820
- if (!fs.default.existsSync(gemfilePath)) return false;
821
- return (await fs.default.promises.readFile(gemfilePath, "utf-8")).includes("cocoapods");
822
- } catch {
823
- return false;
824
- }
825
- };
826
- /**
827
- * Runs React Native codegen into `<sourceDir>/build/generated/ios`, as the
828
- * React Native CLI does before `pod install`. Clearing the old output first
829
- * drops the modules of removed libraries.
830
- */
831
- const runReactNativeCodegen = async ({ projectRoot, reactNativePath, sourceDir }) => {
832
- await fs.default.promises.rm(path.default.join(sourceDir, "build", "generated", "ios"), {
833
- recursive: true,
834
- force: true
835
- });
836
- const spinner = _hot_updater_cli_tools.p.spinner();
837
- spinner.start("Running React Native codegen");
838
- try {
839
- await (0, execa.execa)("node", [
840
- path.default.join(reactNativePath, "scripts", "generate-codegen-artifacts.js"),
841
- "-p",
842
- projectRoot,
843
- "-o",
844
- sourceDir,
845
- "-t",
846
- "ios"
847
- ], { cwd: projectRoot });
848
- } catch (error) {
849
- spinner.stop("React Native codegen failed");
850
- throw new Error(`React Native codegen failed: ${error}`);
851
- }
852
- spinner.stop("React Native codegen done");
853
- };
854
- /**
855
- * The environment `pod install` runs with, and whether codegen runs first.
856
- *
857
- * From React Native 0.79, `RCT_IGNORE_PODS_DEPRECATION=1` silences the
858
- * deprecation notice for calling `pod install` directly and also sets
859
- * `RCT_SKIP_CODEGEN=1`, because the React Native CLI runs codegen itself
860
- * first. Hot Updater sets it the same way and runs codegen too, unless the
861
- * user's `RCT_SKIP_CODEGEN=1` takes codegen over. Before 0.79, and when the
862
- * version is unknown, CocoaPods runs codegen. A user's value of a flag wins.
863
- */
864
- const resolvePodInstallPlan = ({ version, env }) => {
865
- const podsSkipCodegen = version.major > 0 || version.minor >= 79;
866
- const usePrebuiltReactNative = version.major > 0 || version.minor >= 81;
867
- const ignorePodsDeprecation = env["RCT_IGNORE_PODS_DEPRECATION"] ?? (podsSkipCodegen ? "1" : void 0);
868
- return {
869
- runCodegen: podsSkipCodegen && ignorePodsDeprecation === "1" && env["RCT_SKIP_CODEGEN"] !== "1",
870
- env: {
871
- ...ignorePodsDeprecation !== void 0 && { RCT_IGNORE_PODS_DEPRECATION: ignorePodsDeprecation },
872
- RCT_USE_RN_DEP: env["RCT_USE_RN_DEP"] ?? (usePrebuiltReactNative ? "1" : "0"),
873
- RCT_USE_PREBUILT_RNCORE: env["RCT_USE_PREBUILT_RNCORE"] ?? (usePrebuiltReactNative ? "1" : "0")
874
- }
875
- };
876
- };
877
- //#endregion
878
786
  //#region src/utils/createRandomTmpDir.ts
879
787
  const TERMINATION_SIGNALS$2 = [
880
788
  "SIGHUP",
@@ -927,1241 +835,1778 @@ const removeTmpDir = async (directory) => {
927
835
  if (liveDirectories.delete(directory) && liveDirectories.size === 0) stopListening();
928
836
  };
929
837
  //#endregion
930
- //#region src/utils/platform.ts
838
+ //#region src/utils/escapeUnzipPattern.ts
931
839
  /**
932
- * 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.
933
843
  */
934
- const platformConfigs = { ios: {
935
- name: "ios",
936
- deviceSdk: "iphoneos",
937
- simulatorSdk: "iphonesimulator",
938
- supportsSimulator: true,
939
- deviceDestination: "platform=iOS",
940
- simulatorDestination: "platform=iOS Simulator"
941
- } };
844
+ const escapeUnzipPattern = (name) => name.replace(/[[\]*?\\]/gu, "\\$&");
942
845
  //#endregion
943
- //#region src/utils/destination.ts
944
- 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
+ };
945
852
  /**
946
- * 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.
947
855
  */
948
- const resolveDestination = ({ destination, useGeneric }) => {
949
- if (typeof destination === "object") {
950
- if ("id" in destination) return `id=${destination.id}`;
951
- if ("name" in destination) return `name=${destination.name}`;
952
- }
953
- switch (destination) {
954
- case "ios-device": return buildDestinationString({
955
- platform: "ios",
956
- deviceType: "device",
957
- useGeneric
958
- });
959
- case "ios-simulator": return buildDestinationString({
960
- platform: "ios",
961
- deviceType: "simulator",
962
- useGeneric
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
963
873
  });
964
874
  }
965
875
  };
966
- const resolveDestinations = ({ destinations, useGeneric }) => {
967
- return destinations.map((destination) => resolveDestination({
968
- destination,
969
- useGeneric
970
- }));
971
- };
972
- const getDefaultDestination = ({ platform, useGeneric, deviceType }) => {
973
- return buildDestinationString({
974
- deviceType,
975
- platform,
976
- useGeneric
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();
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;
919
+ });
920
+ //#endregion
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")
977
936
  });
937
+ return {
938
+ authenticationArgs: [
939
+ "-allowProvisioningUpdates",
940
+ "-authenticationKeyPath",
941
+ apiKey.keyPath,
942
+ "-authenticationKeyID",
943
+ apiKey.keyId,
944
+ "-authenticationKeyIssuerID",
945
+ apiKey.issuerId
946
+ ],
947
+ apiKey
948
+ };
978
949
  };
979
- //#endregion
980
- //#region src/utils/formatCommand.ts
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";
981
963
  /**
982
- * A command to print, broken at spaces with ` \` once a line would pass
983
- * `width`, each continuation indented two spaces, so a terminal never wraps
984
- * it mid-word and it still pastes as one command.
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.
985
967
  */
986
- const formatCommand = (words, width = 74) => {
987
- const lines = [];
988
- let line = "";
989
- for (const word of words) {
990
- const next = line ? `${line} ${word}` : word;
991
- if (line && next.length > width - 2) {
992
- lines.push(`${line} \\`);
993
- line = ` ${word}`;
994
- } else line = next;
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;
972
+ };
973
+ /**
974
+ * `testFlightInternalTestingOnly` in export options: undefined without it.
975
+ */
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;
995
981
  }
996
- lines.push(line);
997
- return lines.join("\n");
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;
998
991
  };
999
- //#endregion
1000
- //#region src/utils/parseXcodeProjectInfo.ts
1001
- const parseXcodeProjectInfo = async (sourceDir) => {
1002
- const files = await fs.default.promises.readdir(sourceDir);
1003
- const workspace = files.find((file) => file.endsWith(".xcworkspace"));
1004
- if (workspace) return {
1005
- isWorkspace: true,
1006
- name: workspace,
1007
- path: path.default.join(sourceDir, workspace)
1008
- };
1009
- const project = files.find((file) => file.endsWith(".xcodeproj"));
1010
- if (project) return {
1011
- isWorkspace: false,
1012
- name: project,
1013
- path: path.default.join(sourceDir, project)
1014
- };
1015
- throw new Error(`No Xcode project or workspace found in ${sourceDir}`);
992
+ /**
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.
996
+ */
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.`);
999
+ };
1000
+ /**
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.
1004
+ */
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() : "";
1016
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));
1017
1050
  //#endregion
1018
- //#region src/utils/prettifyXcodebuildError.ts
1019
- const prettifyXcodebuildError = (error) => {
1020
- if (error instanceof _hot_updater_cli_tools.BuildFailedError) {
1021
- const errorLines = error.summary.join("\n");
1022
- const message = 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." : error.message;
1023
- return new _hot_updater_cli_tools.BuildFailedError(message, {
1024
- logPath: error.logPath,
1025
- summary: error.summary,
1026
- cause: error.cause
1027
- });
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";
1066
+ /**
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.
1070
+ */
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;
1028
1079
  }
1029
- return /* @__PURE__ */ new Error(`Xcodebuild failed: ${error}`);
1030
1080
  };
1031
- //#endregion
1032
- //#region src/utils/createXcodebuildLogger.ts
1033
- const createXcodebuildLogger = ({ logPrefix }) => new _hot_updater_cli_tools.BuildLogger({
1034
- logPrefix,
1035
- importantLogPatterns: [
1036
- "error:",
1037
- "** BUILD FAILED **",
1038
- "** ARCHIVE FAILED **",
1039
- "The following build commands failed:",
1040
- "note: Building targets in dependency order",
1041
- "note: Target dependency graph",
1042
- "Running script",
1043
- "[CP-User]",
1044
- "[CP] Check Pods Manifest.lock",
1045
- "Build Succeeded"
1046
- ],
1047
- progressStages: [
1048
- ["Building targets in dependency order", "Target dependency graph"],
1049
- ["Write Auxiliary File", "[CP] Check Pods Manifest.lock"],
1050
- [
1051
- "Running script",
1052
- "[CP-User] [RN]Check rncore",
1053
- "[CP-User] [Hermes] Replace Hermes",
1054
- "[CP-User] [RN]Check FBReactNativeSpec"
1055
- ],
1056
- [
1057
- "Processing",
1058
- "ProcessProductPackaging",
1059
- "ProcessProductPackagingDER"
1060
- ],
1061
- ["Compiling"],
1062
- ["RegisterExecutionPolicyException"],
1063
- ["Touching"],
1064
- ["Building library", "Create Universal Binary"],
1065
- ["Copying"],
1066
- [
1067
- "Build Succeeded",
1068
- "BUILD SUCCEEDED",
1069
- "ARCHIVE SUCCEEDED"
1070
- ]
1071
- ],
1072
- failureSummary: {
1073
- lines: [/(^|:\s)error: /, /^\*\* [A-Z ]+ FAILED \*\*$/],
1074
- blocks: [{
1075
- start: "The following build commands failed:",
1076
- end: /^\(\d+ failures?\)$/,
1077
- includeEnd: true
1078
- }]
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;
1079
1094
  }
1080
- });
1081
- //#endregion
1082
- //#region src/utils/runXcodebuildWithLogging.ts
1083
- let cachedXcbeautifyAvailability = null;
1084
- const TERMINATION_SIGNALS$1 = ["SIGINT", "SIGTERM"];
1085
- const isXcbeautifyAvailable = async () => {
1086
- if (cachedXcbeautifyAvailability !== null) return cachedXcbeautifyAvailability;
1095
+ };
1096
+ /**
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.
1099
+ */
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) => {
1087
1118
  try {
1088
- await (0, execa.execa)("which", ["xcbeautify"]);
1089
- cachedXcbeautifyAvailability = true;
1090
- return true;
1119
+ return crypto.default.createPrivateKey(await fs.default.promises.readFile(keyPath, "utf-8"));
1091
1120
  } catch {
1092
- cachedXcbeautifyAvailability = false;
1093
- return false;
1121
+ throw new Error("The App Store Connect API key is not a .p8 private key.");
1094
1122
  }
1095
1123
  };
1096
- const createRawXcodebuildProcess = ({ args, env, sourceDir }) => {
1097
- return (0, execa.execa)("xcodebuild", args, {
1098
- cwd: sourceDir,
1099
- all: true,
1100
- buffer: false,
1101
- env: {
1102
- ...process.env,
1103
- ...env,
1104
- NSUnbufferedIO: "YES"
1105
- }
1106
- });
1107
- };
1108
- const createXcbeautifyProcess = ({ cwd }) => {
1109
- return (0, execa.execa)("xcbeautify", [], {
1110
- cwd,
1111
- all: true,
1112
- buffer: false
1113
- });
1114
- };
1115
- /** Why xcodebuild failed, without its command line. */
1116
- const describeFailure = (error) => {
1117
- if (error instanceof execa.ExecaError) {
1118
- if (error.signal) return `xcodebuild was stopped by ${error.signal}.`;
1119
- if (error.exitCode !== void 0) return `xcodebuild exited with code ${error.exitCode}.`;
1120
- }
1121
- return error instanceof Error ? error.message : String(error);
1124
+ const readApiErrors = async (response) => {
1125
+ const body = await response.json().catch(() => void 0);
1126
+ return Array.isArray(body?.errors) ? body.errors : [];
1122
1127
  };
1123
- const runXcodebuildWithLogging = async ({ args, env, sourceDir, successMessage, failureMessage, logPrefix }) => {
1124
- const useXcbeautify = await isXcbeautifyAvailable();
1125
- const logger = createXcodebuildLogger({ logPrefix });
1126
- await logger.start();
1127
- const activeProcesses = [];
1128
- const terminateActiveProcesses = () => {
1129
- for (const activeProcess of activeProcesses) activeProcess.kill();
1130
- };
1131
- for (const signal of TERMINATION_SIGNALS$1) process.once(signal, terminateActiveProcesses);
1132
- try {
1133
- const xcodebuildProcess = createRawXcodebuildProcess({
1134
- args,
1135
- env,
1136
- sourceDir
1137
- });
1138
- activeProcesses.push(xcodebuildProcess);
1139
- const xcodebuildOutput = xcodebuildProcess.all ?? xcodebuildProcess.stdout;
1140
- let xcbeautifyProcess = null;
1141
- if (useXcbeautify && xcodebuildOutput) {
1142
- xcbeautifyProcess = createXcbeautifyProcess({ cwd: sourceDir });
1143
- activeProcesses.push(xcbeautifyProcess);
1144
- }
1145
- const logging = xcodebuildOutput ? logger.processStream(xcodebuildOutput, { display: xcbeautifyProcess ? xcbeautifyProcess.all ?? xcbeautifyProcess.stdout ?? void 0 : void 0 }) : Promise.resolve();
1146
- const xcbeautifyInput = xcbeautifyProcess?.stdin;
1147
- if (xcodebuildOutput && xcbeautifyInput) {
1148
- xcbeautifyInput.on("error", () => {
1149
- xcodebuildOutput.unpipe(xcbeautifyInput);
1150
- });
1151
- xcodebuildOutput.pipe(xcbeautifyInput);
1152
- }
1153
- const [xcodebuildResult, loggingResult] = await Promise.allSettled([
1154
- xcodebuildProcess,
1155
- logging,
1156
- xcbeautifyProcess
1157
- ]);
1158
- if (xcodebuildResult.status === "rejected") throw xcodebuildResult.reason;
1159
- if (loggingResult.status === "rejected") throw loggingResult.reason;
1160
- logger.stop(successMessage);
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();
1161
1146
  } catch (error) {
1162
- logger.writeError(error);
1163
- logger.stop(failureMessage, false);
1164
- throw new _hot_updater_cli_tools.BuildFailedError(`${failureMessage}: ${describeFailure(error)}`, {
1165
- logPath: logger.logPath,
1166
- summary: logger.failureSummary,
1167
- cause: error
1168
- });
1169
- } finally {
1170
- for (const signal of TERMINATION_SIGNALS$1) process.off(signal, terminateActiveProcesses);
1171
- await logger.close();
1147
+ if (!retryable(error) || attempt === COMMIT_ATTEMPTS) throw error;
1148
+ await sleep(retryDelayMs(error, attempt));
1172
1149
  }
1173
1150
  };
1174
- //#endregion
1175
- //#region src/utils/writeBuildXcconfig.ts
1176
- const SDK_CONDITIONS = [
1177
- "",
1178
- "[sdk=iphoneos*]",
1179
- "[sdk=iphonesimulator*]"
1180
- ];
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;
1181
1154
  /**
1182
- * Finds a setting of `keys` that an included xcconfig sets with a condition
1183
- * the build xcconfig does not, such as `[config=Release]` or `[arch=arm64]`,
1184
- * which would outrank the build's own. It follows `#include`s, which are
1185
- * relative to the including file.
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.
1186
1157
  */
1187
- const findConditionalSetting = async (files, keys, visited = /* @__PURE__ */ new Set()) => {
1188
- for (const file of files) {
1189
- if (visited.has(file) || !fs.default.existsSync(file)) continue;
1190
- visited.add(file);
1191
- const lines = (await fs.default.promises.readFile(file, "utf-8")).split("\n");
1192
- for (const [index, line] of lines.entries()) {
1193
- const include = line.match(/^\s*#include\??\s*"([^"]+)"/)?.[1];
1194
- if (include) {
1195
- const found = await findConditionalSetting([path.default.resolve(path.default.dirname(file), include)], keys, visited);
1196
- if (found) return found;
1197
- continue;
1198
- }
1199
- const [, key, conditions] = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)((?:\[[^\]]*\])+)\s*=/) ?? [];
1200
- if (key && keys.includes(key) && !SDK_CONDITIONS.includes(conditions)) return `${file}:${index + 1} sets ${key}${conditions}`;
1201
- }
1202
- }
1203
- };
1158
+ const RATE_LIMIT_DELAY_MS = 15e3;
1204
1159
  /**
1205
- * Writes the xcconfig a build loads, which sets the CLI's build settings
1206
- * over every other. xcodebuild ranks an `-xcconfig`'s settings above the
1207
- * command line's, so the scheme's `xcconfig` and each `-xcconfig` in
1208
- * `extraParams` are included, in order, before `settings`, and the build
1209
- * loads only this one.
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.
1210
1164
  */
1211
- const writeBuildXcconfig = async ({ directory, sourceDir, xcconfig, extraParams = [], settings }) => {
1212
- const included = xcconfig ? [xcconfig] : [];
1213
- const otherParams = [];
1214
- for (let i = 0; i < extraParams.length; i++) if (extraParams[i] === "-xcconfig" && i + 1 < extraParams.length) included.push(extraParams[++i]);
1215
- else otherParams.push(extraParams[i]);
1216
- const includedFiles = included.map((file) => path.default.resolve(sourceDir, file));
1217
- const conditional = await findConditionalSetting(includedFiles, Object.keys(settings));
1218
- if (conditional) throw new Error(`${conditional}, which would outrank the value the build sets. Set it without that condition, or remove it.`);
1219
- const buildXcconfig = path.default.join(directory, "HotUpdater.xcconfig");
1220
- await fs.default.promises.writeFile(buildXcconfig, [
1221
- ...includedFiles.map((file) => `#include "${file}"`),
1222
- ...Object.entries(settings).flatMap(([key, value]) => SDK_CONDITIONS.map((condition) => `${key}${condition} = ${value}`)),
1223
- ""
1224
- ].join("\n"));
1225
- return {
1226
- xcconfig: buildXcconfig,
1227
- extraParams: otherParams
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
1228
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);
1229
1176
  };
1230
1177
  /**
1231
- * Automatic signing over a target set to manual signing, whose provisioning
1232
- * profile and identity Xcode would otherwise report as conflicting.
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.
1233
1181
  */
1234
- const AUTOMATIC_SIGNING = {
1235
- CODE_SIGN_STYLE: "Automatic",
1236
- PROVISIONING_PROFILE: "",
1237
- PROVISIONING_PROFILE_SPECIFIER: "",
1238
- CODE_SIGN_IDENTITY: "Apple Development"
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
+ }
1193
+ }
1194
+ }));
1195
+ if (failure) throw failure.error;
1239
1196
  };
1240
1197
  /**
1241
- * The settings a build sets over the scheme's: the MIN_BUNDLE_ID the CLI
1242
- * issues and reports, and automatic signing when an App Store Connect API
1243
- * key signs, which a target set to manual signing would not use.
1198
+ * A signing build setting's assignment: the key, any conditions such as
1199
+ * `[sdk=iphoneos*]`, and the value, without a trailing comment.
1244
1200
  */
1245
- const buildSettingsOverScheme = ({ minBundleId, authenticationArgs }) => ({
1246
- HOT_UPDATER_MIN_BUNDLE_ID: minBundleId,
1247
- ...authenticationArgs ? AUTOMATIC_SIGNING : {}
1248
- });
1249
- //#endregion
1250
- //#region src/builder/archiveXcodeProject.ts
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}`
1212
+ });
1213
+ };
1251
1214
  /**
1252
- * Archives the scheme into `archiveDirectory`. The build's xcconfig is
1253
- * written to a temporary directory, removed whether the archive succeeds or
1254
- * not.
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.
1255
1219
  */
1256
- const archiveXcodeProject = async ({ sourceDir, archiveDirectory, platform, installPods, destination, extraParams, configuration, xcodeScheme, xcconfig, logPrefix, minBundleId, authenticationArgs }) => {
1257
- if (installPods) await installPodsIfNeeded(sourceDir);
1258
- const xcodeProject = await parseXcodeProjectInfo(sourceDir);
1259
- const archiveName = `${xcodeProject.name.replace(".xcworkspace", "").replace(".xcodeproj", "")}.xcarchive`;
1260
- const archivePath = path.default.join(archiveDirectory, archiveName);
1261
- const tmpDir = await createRandomTmpDir();
1262
- try {
1263
- const build = await writeBuildXcconfig({
1264
- directory: tmpDir,
1265
- sourceDir,
1266
- xcconfig,
1267
- extraParams,
1268
- settings: buildSettingsOverScheme({
1269
- minBundleId,
1270
- authenticationArgs
1271
- })
1272
- });
1273
- const archiveArgs = prepareArchiveArgs({
1274
- authenticationArgs,
1275
- minBundleId,
1276
- archivePath,
1277
- platform,
1278
- sourceDir,
1279
- xcodeProject,
1280
- configuration,
1281
- extraParams: build.extraParams,
1282
- destination,
1283
- xcconfig: build.xcconfig,
1284
- xcodeScheme
1285
- });
1286
- _hot_updater_cli_tools.p.log.info([
1287
- "Xcode archive",
1288
- `Project ${xcodeProject.name}`,
1289
- `Scheme ${xcodeScheme}`,
1290
- `Platform ${platform}`,
1291
- "Command",
1292
- formatCommand(["xcodebuild", ...archiveArgs])
1293
- ].join("\n"));
1294
- try {
1295
- await runXcodebuildWithLogging({
1296
- args: archiveArgs,
1297
- env: { HOT_UPDATER_MIN_BUNDLE_ID: minBundleId },
1298
- failureMessage: "Archive failed",
1299
- logPrefix,
1300
- sourceDir,
1301
- successMessage: "Archive completed successfully"
1302
- });
1303
- return { archivePath };
1304
- } catch (error) {
1305
- throw prettifyXcodebuildError(error);
1306
- }
1307
- } finally {
1308
- await removeTmpDir(tmpDir);
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);
1309
1228
  }
1229
+ including.delete(file);
1310
1230
  };
1311
- const prepareArchiveArgs = ({ xcodeScheme, archivePath, platform, sourceDir, xcodeProject, configuration = "Release", xcconfig, extraParams, destination = [], minBundleId, authenticationArgs }) => {
1312
- const args = [
1313
- xcodeProject.isWorkspace ? "-workspace" : "-project",
1314
- path.default.join(sourceDir, xcodeProject.name),
1315
- "-scheme",
1316
- xcodeScheme,
1317
- "-configuration",
1318
- configuration,
1319
- "archive",
1320
- "-archivePath",
1321
- archivePath,
1322
- `HOT_UPDATER_MIN_BUNDLE_ID=${minBundleId}`
1323
- ];
1324
- if (authenticationArgs) args.push(...authenticationArgs);
1325
- if (xcconfig) args.push("-xcconfig", xcconfig);
1326
- if (extraParams) args.push(...extraParams);
1327
- const resolvedDestinations = resolveDestinations({
1328
- destinations: destination,
1329
- useGeneric: true
1330
- });
1331
- if (resolvedDestinations.length === 0) resolvedDestinations.push(getDefaultDestination({
1332
- deviceType: "device",
1333
- platform,
1334
- useGeneric: true
1335
- }));
1336
- for (const destination of resolvedDestinations) args.push("-destination", destination);
1337
- return args;
1231
+ /**
1232
+ * Where the scheme turns code signing off, after every override the build
1233
+ * applies: the `extraParams` settings first, then the xcconfigs the build
1234
+ * xcconfig includes over them, in order, its `xcconfig` and each
1235
+ * `-xcconfig` in `extraParams`, which resolve from `ios/`, where xcodebuild
1236
+ * runs (`writeBuildXcconfig`). Undefined when it signs, or when a
1237
+ * conditional setting, such as `[sdk=iphoneos*]`, may decide: the build
1238
+ * does.
1239
+ */
1240
+ const codeSigningOff = async (iosScheme) => {
1241
+ const extraParams = iosScheme.extraParams ?? [];
1242
+ const settings = {
1243
+ values: /* @__PURE__ */ new Map(),
1244
+ conditional: /* @__PURE__ */ new Set()
1245
+ };
1246
+ for (const entry of extraParams) applySetting(settings, entry, "extraParams");
1247
+ const xcconfigs = [...iosScheme.xcconfig ? [iosScheme.xcconfig] : [], ...extraParams.flatMap((entry, index) => entry === "-xcconfig" && index + 1 < extraParams.length ? [extraParams[index + 1]] : [])];
1248
+ for (const xcconfig of xcconfigs) await applyXcconfig(path.default.resolve((0, _hot_updater_cli_tools.getCwd)(), "ios", xcconfig), xcconfig, settings, /* @__PURE__ */ new Set());
1249
+ for (const [key, { value, where }] of settings.values) if (/^no$/iu.test(value) && !settings.conditional.has(key)) return where;
1338
1250
  };
1339
- //#endregion
1340
- //#region src/builder/buildXcodeProject.ts
1341
1251
  /**
1342
- * Builds the scheme in a temporary DerivedData directory, copies the built
1343
- * `.app` to `outputDirectory`, and removes DerivedData, which takes 10 GB or
1344
- * more, whether the build succeeds or not.
1252
+ * The App Store Connect API key a scheme's `.ipa` uploads with: the
1253
+ * `signing.ascApiKey` it signs with, or else the `asc-api-key` item. It reads
1254
+ * the config, and the scheme's files that exist before the native projects
1255
+ * are written, and throws, saying why, for a scheme whose build App Store
1256
+ * Connect would not take: a simulator `.app`, a Debug configuration, which
1257
+ * loads its JavaScript from Metro, code signing turned off, an
1258
+ * `.xcarchive` it cannot export, or export options of another method. An
1259
+ * `exportOptionsPlist` the adapter's prebuild writes later is checked after
1260
+ * it (`assertTestFlightExportOptions`).
1345
1261
  */
1346
- const buildXcodeProject = async ({ sourceDir, outputDirectory, platform, xcodeScheme, configuration, deviceType, logPrefix, destination = [], useGenericDestination = false, installPods, extraParams, minBundleId, authenticationArgs }) => {
1347
- if (installPods) await installPodsIfNeeded(sourceDir);
1348
- const xcodeProject = await parseXcodeProjectInfo(sourceDir);
1349
- const tmpDir = await createRandomTmpDir();
1350
- try {
1351
- const derivedDataPath = path.default.join(tmpDir, "DerivedData");
1352
- const resolvedDestinations = resolveDestinations({
1353
- destinations: destination,
1354
- useGeneric: useGenericDestination
1355
- });
1356
- if (resolvedDestinations.length === 0) resolvedDestinations.push(getDefaultDestination({
1357
- deviceType,
1358
- platform,
1359
- useGeneric: useGenericDestination
1360
- }));
1361
- const build = await writeBuildXcconfig({
1362
- directory: tmpDir,
1363
- sourceDir,
1364
- extraParams,
1365
- settings: buildSettingsOverScheme({
1366
- minBundleId,
1367
- authenticationArgs
1368
- })
1369
- });
1370
- const buildArgs = prepareBuildArgs({
1371
- authenticationArgs,
1372
- xcconfig: build.xcconfig,
1373
- minBundleId,
1374
- configuration,
1375
- derivedDataPath,
1376
- deviceType,
1377
- resolvedDestinations,
1378
- extraParams: build.extraParams,
1379
- platform,
1380
- xcodeScheme,
1381
- sourceDir,
1382
- xcodeProject
1383
- });
1384
- _hot_updater_cli_tools.p.log.info([
1385
- "Xcode build",
1386
- `Project ${xcodeProject.name}`,
1387
- `Scheme ${xcodeScheme}`,
1388
- `Configuration ${configuration}`,
1389
- `Platform ${platform}`,
1390
- `Device type ${deviceType}`,
1391
- "Command",
1392
- formatCommand(["xcodebuild", ...buildArgs])
1393
- ].join("\n"));
1394
- let builtAppPath;
1395
- try {
1396
- await runXcodebuildWithLogging({
1397
- args: buildArgs,
1398
- env: { HOT_UPDATER_MIN_BUNDLE_ID: minBundleId },
1399
- sourceDir,
1400
- logPrefix,
1401
- successMessage: "Build completed successfully",
1402
- failureMessage: "Build failed"
1403
- });
1404
- ({appPath: builtAppPath} = await getBuildSettings({
1405
- configuration,
1406
- derivedDataPath,
1407
- resolvedDestinations,
1408
- xcodeScheme,
1409
- sourceDir,
1410
- xcodeProject
1411
- }));
1412
- } catch (error) {
1413
- throw prettifyXcodebuildError(error);
1414
- }
1415
- const appPath = path.default.join(outputDirectory, path.default.basename(builtAppPath));
1416
- await fs.default.promises.cp(builtAppPath, appPath, { recursive: true });
1417
- return { appPath };
1418
- } finally {
1419
- await removeTmpDir(tmpDir);
1262
+ const resolveTestFlightUploadKey = async ({ scheme, iosScheme }) => {
1263
+ if (iosScheme.simulator) throw new Error(`The scheme ${scheme} builds a simulator .app, not an .ipa for TestFlight.`);
1264
+ const configuration = iosScheme.configuration ?? "Release";
1265
+ if (/debug$/i.test(configuration)) throw new Error(`The scheme ${scheme} builds ${configuration}; TestFlight takes a release build.`);
1266
+ const unsigned = await codeSigningOff(iosScheme);
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.`);
1269
+ if (iosScheme.exportOptionsPlist && fs.default.existsSync(schemeFile(iosScheme.exportOptionsPlist))) {
1270
+ const method = await readExportMethod(schemeFile(iosScheme.exportOptionsPlist));
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.`);
1420
1272
  }
1273
+ return {
1274
+ kind: "asc-api-key",
1275
+ name: iosScheme.signing ? (0, _hot_updater_cli_tools.parseSecretReference)(iosScheme.signing.ascApiKey, "signing.ascApiKey") : "asc-api-key"
1276
+ };
1421
1277
  };
1422
- const prepareBuildArgs = ({ xcodeProject, sourceDir, platform, xcodeScheme, configuration, deviceType, resolvedDestinations, derivedDataPath, extraParams, minBundleId, authenticationArgs, xcconfig }) => {
1423
- const sdk = deviceType === "simulator" ? platformConfigs[platform].simulatorSdk : platformConfigs[platform].deviceSdk;
1424
- const args = [
1425
- xcodeProject.isWorkspace ? "-workspace" : "-project",
1426
- path.default.join(sourceDir, xcodeProject.name),
1427
- "-scheme",
1428
- xcodeScheme,
1429
- "-configuration",
1430
- configuration,
1431
- "-sdk",
1432
- sdk,
1433
- "-derivedDataPath",
1434
- derivedDataPath,
1435
- `HOT_UPDATER_MIN_BUNDLE_ID=${minBundleId}`,
1436
- "build"
1437
- ];
1438
- if (authenticationArgs) args.push(...authenticationArgs);
1439
- args.push("-xcconfig", xcconfig);
1440
- if (extraParams) args.push(...extraParams);
1441
- for (const dest of resolvedDestinations) args.push("-destination", dest);
1442
- return args;
1443
- };
1444
- const getBuildSettings = async ({ xcodeProject, sourceDir, xcodeScheme, configuration, resolvedDestinations, derivedDataPath }) => {
1445
- const destinationArgs = resolvedDestinations.flatMap((dest) => ["-destination", dest]);
1446
- const { stdout: buildSettings } = await (0, execa.execa)("xcodebuild", [
1447
- xcodeProject.isWorkspace ? "-workspace" : "-project",
1448
- xcodeProject.name,
1449
- "-scheme",
1450
- xcodeScheme,
1451
- "-configuration",
1452
- configuration,
1453
- ...destinationArgs,
1454
- "-derivedDataPath",
1455
- derivedDataPath,
1456
- "-showBuildSettings",
1457
- "-json"
1458
- ], { cwd: sourceDir });
1459
- const settings = JSON.parse(buildSettings).filter(({ target }) => target !== "React" && target !== "React-Core");
1460
- if (settings.length === 0) throw new Error("Failed to get build settings for your project");
1461
- const targetSettings = settings[0].buildSettings;
1462
- const wrapperExtension = targetSettings.WRAPPER_EXTENSION;
1463
- if (wrapperExtension !== "app" && wrapperExtension !== "framework") throw new Error(`Expected wrapper extension to be "app" or "framework" but found: ${wrapperExtension}`);
1464
- const targetBuildDir = targetSettings.TARGET_BUILD_DIR;
1465
- const executableFolderPath = targetSettings.EXECUTABLE_FOLDER_PATH;
1466
- const fullProductName = targetSettings.FULL_PRODUCT_NAME;
1467
- const infoPlistPath = targetSettings.INFOPLIST_PATH;
1468
- if (!targetBuildDir || !executableFolderPath || !fullProductName) throw new Error("Failed to get build paths from build settings");
1469
- return {
1470
- appPath: path.default.join(targetBuildDir, executableFolderPath),
1471
- infoPlistPath: path.default.join(targetBuildDir, infoPlistPath)
1472
- };
1473
- };
1474
- //#endregion
1475
- //#region src/builder/exportXcodeArchive.ts
1476
- /** Exports the archive into `exportPath`. */
1477
- const exportXcodeArchive = async ({ archivePath, exportPath, sourceDir, exportExtraParams, exportOptionsPlist, logPrefix, authenticationArgs }) => {
1478
- const exportArgs = prepareExportArgs({
1479
- authenticationArgs,
1480
- archivePath,
1481
- exportPath,
1482
- exportOptionsPlist,
1483
- exportExtraParams
1484
- });
1485
- try {
1486
- await runXcodebuildWithLogging({
1487
- args: exportArgs,
1488
- sourceDir,
1489
- successMessage: "Archive exported successfully",
1490
- failureMessage: "Export failed",
1491
- logPrefix
1492
- });
1493
- return { exportPath };
1494
- } catch (error) {
1495
- throw prettifyXcodebuildError(error);
1496
- }
1497
- };
1498
- const prepareExportArgs = ({ exportPath, archivePath, exportExtraParams, exportOptionsPlist, authenticationArgs }) => {
1499
- const args = [
1500
- "-exportArchive",
1501
- "-archivePath",
1502
- archivePath,
1503
- "-exportPath",
1504
- exportPath
1505
- ];
1506
- if (authenticationArgs) args.push(...authenticationArgs);
1507
- if (exportExtraParams) args.push(...exportExtraParams);
1508
- args.push("-exportOptionsPlist", exportOptionsPlist);
1509
- return args;
1510
- };
1511
- //#endregion
1512
- //#region src/utils/assertXcodebuildExist.ts
1513
- const assertXcodebuildExist = async () => {
1514
- try {
1515
- await (0, execa.execa)("which", ["xcodebuild"]);
1516
- } catch {
1517
- _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`);
1518
- process.exit(1);
1519
- }
1520
- };
1521
- //#endregion
1522
- //#region src/utils/escapeUnzipPattern.ts
1523
1278
  /**
1524
- * A zip entry name as `unzip` reads a literal member. It takes `*`, `?` and
1525
- * `[...]` in a member name as wildcards, which a backslash escapes, so an
1526
- * app named `My[Dev].app` would otherwise match nothing.
1279
+ * Throws when the scheme's `exportOptionsPlist` exports with another method
1280
+ * than App Store Connect's, whose `.ipa` App Store Connect refuses. It reads
1281
+ * the file, which an adapter's prebuild may write, so it runs after it.
1527
1282
  */
1528
- const escapeUnzipPattern = (name) => name.replace(/[[\]*?\\]/gu, "\\$&");
1529
- //#endregion
1530
- //#region src/utils/readIpaInfo.ts
1531
- const INFO_PLIST_KEYS = {
1532
- bundleId: "CFBundleIdentifier",
1533
- shortVersion: "CFBundleShortVersionString",
1534
- bundleVersion: "CFBundleVersion"
1283
+ const assertTestFlightExportOptions = async (schemeConfig) => {
1284
+ if (!schemeConfig.exportOptionsPlist) return;
1285
+ const method = await readExportMethod(schemeConfig.exportOptionsPlist);
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.`);
1535
1287
  };
1536
1288
  /**
1537
- * Reads the app's `Payload/<App>.app/Info.plist` out of an `.ipa`, never a
1538
- * framework's or an extension's, which nest deeper.
1289
+ * Requests to the App Store Connect API with `apiKey`: each carries a token
1290
+ * signed with its private key, replaced well before it expires.
1539
1291
  */
1540
- const readIpaInfo = async (ipaPath) => {
1541
- const { stdout } = await (0, execa.execa)("unzip", ["-Z1", ipaPath]);
1542
- const entry = stdout.split("\n").map((name) => name.trim()).find((name) => /^Payload\/[^/]+\.app\/Info\.plist$/u.test(name));
1543
- if (entry === void 0) throw new Error(`${path.default.basename(ipaPath)} has no Payload/<App>.app/Info.plist.`);
1544
- const directory = await createRandomTmpDir();
1545
- try {
1546
- const infoPlist = path.default.join(directory, "Info.plist");
1547
- await (0, execa.execa)("unzip", [
1548
- "-p",
1549
- ipaPath,
1550
- escapeUnzipPattern(entry)
1551
- ], { stdout: { file: infoPlist } });
1552
- const info = {};
1553
- for (const [field, key] of Object.entries(INFO_PLIST_KEYS)) {
1554
- const { stdout: value, exitCode } = await (0, execa.execa)("plutil", [
1555
- "-extract",
1556
- key,
1557
- "raw",
1558
- "-o",
1559
- "-",
1560
- infoPlist
1561
- ], { reject: false });
1562
- if (exitCode !== 0 || !value.trim()) throw new Error(`${path.default.basename(ipaPath)}'s Info.plist has no ${key}.`);
1563
- info[field] = value.trim();
1292
+ const createAppStoreConnectRequest = ({ apiKey, privateKey, fetch }) => {
1293
+ let token;
1294
+ const authorization = () => {
1295
+ const now = Math.floor(Date.now() / 1e3);
1296
+ if (!token || now - token.issuedAtSeconds >= TOKEN_REUSE_SECONDS) {
1297
+ token = {
1298
+ value: createAppStoreConnectToken({
1299
+ privateKey,
1300
+ keyId: apiKey.keyId,
1301
+ issuerId: apiKey.issuerId,
1302
+ issuedAtSeconds: now
1303
+ }),
1304
+ issuedAtSeconds: now
1305
+ };
1306
+ (0, _hot_updater_cli_tools.registerSecretValue)(token.value);
1564
1307
  }
1565
- return info;
1566
- } finally {
1567
- await fs.default.promises.rm(directory, {
1568
- recursive: true,
1569
- force: true
1308
+ return `Bearer ${token.value}`;
1309
+ };
1310
+ return async (action, method, pathname, body) => {
1311
+ const response = await fetch(`${API_URL$2}${pathname}`, {
1312
+ method,
1313
+ headers: {
1314
+ Authorization: authorization(),
1315
+ ...body ? { "Content-Type": "application/json" } : {}
1316
+ },
1317
+ ...body ? { body: JSON.stringify(body) } : {}
1570
1318
  });
1571
- }
1319
+ if (!response.ok) {
1320
+ const error = new AppStoreConnectError(action, response.status, await readApiErrors(response), response.headers.get("retry-after"));
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 });
1323
+ throw error;
1324
+ }
1325
+ return response.status === 204 ? void 0 : await response.json();
1326
+ };
1327
+ };
1328
+ /** The App Store Connect app of `bundleId`, and its TestFlight page. */
1329
+ const findApp = async (request, bundleId) => {
1330
+ const { data: apps } = await retrying(() => request("Finding the App Store Connect app", "GET", `/v1/apps?${new URLSearchParams({
1331
+ "filter[bundleId]": bundleId,
1332
+ "fields[apps]": "bundleId"
1333
+ })}`));
1334
+ const app = apps.find((app) => app.attributes?.bundleId === bundleId);
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.`);
1336
+ return {
1337
+ app,
1338
+ testFlightUrl: `https://appstoreconnect.apple.com/apps/${app.id}/testflight/ios`
1339
+ };
1572
1340
  };
1573
- //#endregion
1574
- //#region src/utils/xcodeSigning.ts
1575
1341
  /**
1576
- * How a device build signs with automatic signing, authenticated by the
1577
- * scheme's App Store Connect API key: the xcodebuild arguments, and the key.
1578
- * The key is resolved only here, for a device build of a scheme with
1579
- * `signing`. Without `credentials`, it resolves from the environment or the
1580
- * config's `secrets` adapter, and the temporary files are deleted when the
1581
- * process exits.
1342
+ * Whether App Store Connect already has the `.ipa`'s build: a build of its
1343
+ * version with its build number, which TestFlight lists or is processing,
1344
+ * as when a reused native build was uploaded before. A build upload that
1345
+ * never finished is no build, so uploading again fails as it would without
1346
+ * this check.
1582
1347
  */
1583
- const resolveXcodeSigning = async ({ schemeConfig, credentials }) => {
1584
- const reference = schemeConfig.signing?.ascApiKey;
1585
- if (!reference) return;
1586
- const apiKey = await (credentials ?? (0, _hot_updater_cli_tools.createCredentialResolver)()).resolve({
1587
- kind: "asc-api-key",
1588
- name: (0, _hot_updater_cli_tools.parseSecretReference)(reference, "signing.ascApiKey")
1348
+ const findTestFlightBuild = async ({ ipaPath, apiKey, fetch = globalThis.fetch }) => {
1349
+ const [info, privateKey] = await Promise.all([readIpaInfo(ipaPath), readPrivateKey(apiKey.keyPath)]);
1350
+ const request = createAppStoreConnectRequest({
1351
+ apiKey,
1352
+ privateKey,
1353
+ fetch
1589
1354
  });
1355
+ const { app, testFlightUrl } = await findApp(request, info.bundleId);
1356
+ const { data: builds } = await retrying(() => request("Finding the build in App Store Connect", "GET", `/v1/builds?${new URLSearchParams({
1357
+ "filter[app]": app.id,
1358
+ "filter[version]": info.bundleVersion,
1359
+ "filter[preReleaseVersion.version]": info.shortVersion,
1360
+ "fields[builds]": "version",
1361
+ limit: "1"
1362
+ })}`));
1590
1363
  return {
1591
- authenticationArgs: [
1592
- "-allowProvisioningUpdates",
1593
- "-authenticationKeyPath",
1594
- apiKey.keyPath,
1595
- "-authenticationKeyID",
1596
- apiKey.keyId,
1597
- "-authenticationKeyIssuerID",
1598
- apiKey.issuerId
1599
- ],
1600
- apiKey
1364
+ found: builds.length > 0,
1365
+ testFlightUrl,
1366
+ shortVersion: info.shortVersion,
1367
+ bundleVersion: info.bundleVersion
1601
1368
  };
1602
1369
  };
1603
- const APP_STORE_CONNECT_EXPORT_OPTIONS = `<?xml version="1.0" encoding="UTF-8"?>
1604
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1605
- <plist version="1.0">
1606
- <dict>
1607
- <key>method</key>
1608
- <string>app-store-connect</string>
1609
- <key>signingStyle</key>
1610
- <string>automatic</string>
1611
- </dict>
1612
- </plist>
1613
- `;
1614
1370
  /**
1615
- * Writes the export options of a scheme that signs with an App Store Connect
1616
- * API key and sets no `exportOptionsPlist`: an App Store Connect export with
1617
- * automatic signing.
1371
+ * Uploads an `.ipa` to App Store Connect, which lists it in TestFlight, with
1372
+ * the App Store Connect API's build uploads: it finds the app by the
1373
+ * `.ipa`'s bundle ID, reserves the build's version and build number, sends
1374
+ * the file in the parts App Store Connect asks for, commits it, and waits
1375
+ * for App Store Connect to accept or reject the build.
1618
1376
  */
1619
- const writeAppStoreConnectExportOptions = async (directory) => {
1620
- const exportOptionsPlist = path.default.join(directory, "ExportOptions.plist");
1621
- await fs.default.promises.writeFile(exportOptionsPlist, APP_STORE_CONNECT_EXPORT_OPTIONS);
1622
- return exportOptionsPlist;
1623
- };
1624
- /** The export methods whose `.ipa` App Store Connect takes. */
1625
- const APP_STORE_EXPORT_METHODS = /* @__PURE__ */ new Set(["app-store", "app-store-connect"]);
1626
- /** The `method` of export options, or "" when it has none or can't be read. */
1627
- const readExportMethod = async (exportOptionsPlist) => {
1628
- 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);
1629
- if (xml) return xml[1];
1630
- const { stdout, exitCode } = await (0, execa.execa)("plutil", [
1631
- "-extract",
1632
- "method",
1633
- "raw",
1634
- "-o",
1635
- "-",
1636
- exportOptionsPlist
1637
- ], { reject: false });
1638
- return exitCode === 0 ? stdout.trim() : "";
1639
- };
1640
- /**
1641
- * Whether a device build exports for App Store Connect: with its
1642
- * `exportOptionsPlist`'s method, or, without one, as a scheme signing with
1643
- * an App Store Connect API key does. Such an `.ipa` is signed with Apple's
1644
- * cloud-managed distribution certificate, never with a development
1645
- * certificate the archive was signed with.
1377
+ const uploadToTestFlight = async ({ ipaPath, apiKey, fetch = globalThis.fetch, pollIntervalMs = 5e3, processingTimeoutMs = 18e5 }) => {
1378
+ const ipaName = path.default.basename(ipaPath);
1379
+ const [info, privateKey, { size: fileSize }] = await Promise.all([
1380
+ readIpaInfo(ipaPath),
1381
+ readPrivateKey(apiKey.keyPath),
1382
+ fs.default.promises.stat(ipaPath)
1383
+ ]);
1384
+ const request = createAppStoreConnectRequest({
1385
+ apiKey,
1386
+ privateKey,
1387
+ fetch
1388
+ });
1389
+ const { app, testFlightUrl } = await findApp(request, info.bundleId);
1390
+ let buildUploadId;
1391
+ let unanswered = false;
1392
+ for (let attempt = 1; buildUploadId === void 0; attempt++) try {
1393
+ ({data: {id: buildUploadId}} = await request("Creating the build upload", "POST", "/v1/buildUploads", { data: {
1394
+ type: "buildUploads",
1395
+ attributes: {
1396
+ platform: "IOS",
1397
+ cfBundleShortVersionString: info.shortVersion,
1398
+ cfBundleVersion: info.bundleVersion
1399
+ },
1400
+ relationships: { app: { data: {
1401
+ type: "apps",
1402
+ id: app.id
1403
+ } } }
1404
+ } }));
1405
+ } catch (error) {
1406
+ if (error instanceof AppStoreConnectError && error.status === 409 && error.errors.some((apiError) => apiError.code === DUPLICATE_ERROR_CODE)) {
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 });
1412
+ throw new TestFlightBuildExistsError(info.shortVersion, info.bundleVersion, { cause: error });
1413
+ }
1414
+ if (!isRetryable(error) || attempt === COMMIT_ATTEMPTS) throw error;
1415
+ if (!isRateLimited(error)) unanswered = true;
1416
+ await sleep(retryDelayMs(error, attempt));
1417
+ }
1418
+ _hot_updater_cli_tools.p.log.info(`Uploading ${ipaName} ${info.shortVersion} (${info.bundleVersion}) to App Store Connect`);
1419
+ const removeUpload = async () => {
1420
+ for (let attempt = 1;; attempt++) try {
1421
+ await request("Removing the build upload", "DELETE", `/v1/buildUploads/${buildUploadId}`);
1422
+ return;
1423
+ } catch (error) {
1424
+ if (error instanceof AppStoreConnectError && error.status === 404) return;
1425
+ if (!isRetryable(error) || attempt === COMMIT_ATTEMPTS) {
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"));
1431
+ return;
1432
+ }
1433
+ await sleep(retryDelayMs(error, attempt));
1434
+ }
1435
+ };
1436
+ let fileId;
1437
+ try {
1438
+ const { data } = await retrying(() => request("Reserving the .ipa upload", "POST", "/v1/buildUploadFiles", { data: {
1439
+ type: "buildUploadFiles",
1440
+ attributes: {
1441
+ assetType: "ASSET",
1442
+ fileName: ipaName,
1443
+ fileSize,
1444
+ uti: "com.apple.ipa"
1445
+ },
1446
+ relationships: { buildUpload: { data: {
1447
+ type: "buildUploads",
1448
+ id: buildUploadId
1449
+ } } }
1450
+ } }), isRateLimited);
1451
+ fileId = data.id;
1452
+ const operations = data.attributes?.uploadOperations ?? [];
1453
+ if (operations.length === 0) throw new Error("App Store Connect returned no upload operations.");
1454
+ await uploadParts({
1455
+ ipaPath,
1456
+ operations,
1457
+ fetch
1458
+ });
1459
+ } catch (error) {
1460
+ await removeUpload();
1461
+ throw error;
1462
+ }
1463
+ let commitUnanswered = false;
1464
+ for (let attempt = 1;; attempt++) try {
1465
+ await request("Committing the .ipa upload", "PATCH", `/v1/buildUploadFiles/${fileId}`, { data: {
1466
+ type: "buildUploadFiles",
1467
+ id: fileId,
1468
+ attributes: { uploaded: true }
1469
+ } });
1470
+ break;
1471
+ } catch (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 });
1478
+ if (!isRetryable(error)) {
1479
+ if (commitUnanswered) throw unconfirmed();
1480
+ await removeUpload();
1481
+ throw error;
1482
+ }
1483
+ commitUnanswered = true;
1484
+ const fileState = await retrying(() => request("Reading the .ipa upload", "GET", `/v1/buildUploadFiles/${fileId}?fields[buildUploadFiles]=assetDeliveryState`)).then(({ data }) => data.attributes?.assetDeliveryState?.state).catch(() => void 0);
1485
+ if (fileState && fileState !== "AWAITING_UPLOAD") break;
1486
+ if (attempt === COMMIT_ATTEMPTS) throw unconfirmed();
1487
+ await sleep(retryDelayMs(error, attempt));
1488
+ }
1489
+ const deadline = Date.now() + processingTimeoutMs;
1490
+ let reportedProcessing = false;
1491
+ let lastError;
1492
+ for (let failedReads = 0;;) {
1493
+ let readError;
1494
+ const read = await request("Reading the build upload", "GET", `/v1/buildUploads/${buildUploadId}`).catch((error) => {
1495
+ if (!isRetryable(error)) throw error;
1496
+ lastError = readError = error;
1497
+ });
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.
1646
1541
  */
1647
- const exportsForAppStoreConnect = async (schemeConfig) => !schemeConfig.exportOptionsPlist || APP_STORE_EXPORT_METHODS.has(await readExportMethod(schemeConfig.exportOptionsPlist));
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
+ };
1648
1566
  //#endregion
1649
- //#region src/uploadToTestFlight.ts
1567
+ //#region src/asc/devices.ts
1650
1568
  const API_URL$1 = "https://api.appstoreconnect.apple.com";
1651
- /** Apple accepts tokens that expire within 20 minutes. */
1652
- const TOKEN_LIFETIME_SECONDS = 1200;
1653
- /** A token is replaced well before it expires, so no request carries a stale one. */
1654
- const TOKEN_REUSE_SECONDS = 600;
1655
- /** The parts of an `.ipa` sent at once. */
1656
- const UPLOAD_CONCURRENCY = 4;
1657
- /** Attempts to create the build upload and to commit the uploaded `.ipa`. */
1658
- const COMMIT_ATTEMPTS = 3;
1659
- /** Attempts per part: a part is a plain PUT, safe to repeat. */
1660
- const UPLOAD_ATTEMPTS = 3;
1661
- const IN_PROGRESS_STATES = /* @__PURE__ */ new Set(["AWAITING_UPLOAD", "PROCESSING"]);
1662
- /** The error App Store Connect answers with when a build number is taken. */
1663
- const DUPLICATE_ERROR_CODE = "ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE";
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
+ });
1664
1580
  /**
1665
- * App Store Connect refused the upload: it already has a build with the
1666
- * `.ipa`'s version and build number, from this or another upload, and takes
1667
- * each build number once per version.
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.
1668
1584
  */
1669
- var TestFlightBuildExistsError = class extends Error {
1670
- shortVersion;
1671
- bundleVersion;
1672
- name = "TestFlightBuildExistsError";
1673
- constructor(shortVersion, bundleVersion, options) {
1674
- super(`App Store Connect already has build ${bundleVersion} of version ${shortVersion}.\nUse a new build number (CFBundleVersion).`, options);
1675
- this.shortVersion = shortVersion;
1676
- this.bundleVersion = bundleVersion;
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;
1677
1592
  }
1678
1593
  };
1679
- /** An App Store Connect API request that failed, with the errors it answered. */
1680
- var AppStoreConnectError = class extends Error {
1681
- status;
1682
- errors;
1683
- /** The answer's `Retry-After` header, for a rate limit. */
1684
- retryAfter;
1685
- constructor(action, status, errors, retryAfter = null) {
1686
- const details = errors.map((error) => error.detail ?? error.title ?? error.code).filter(Boolean);
1687
- super(`${action} failed (HTTP ${status})${details.length > 0 ? `: ${details.join(" ")}` : "."}`);
1688
- this.name = "AppStoreConnectError";
1689
- this.status = status;
1690
- this.errors = errors;
1691
- this.retryAfter = retryAfter;
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);
1692
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()));
1693
1623
  };
1624
+ const keyOf = (udid) => (0, _hot_updater_protocol_native_artifact.normalizeIosUdid)(udid) ?? udid.toLowerCase();
1694
1625
  /**
1695
- * An App Store Connect API token: an ES256 JWT, whose signature JWS encodes
1696
- * as the raw 64-byte r || s, not the DER Node signs by default.
1626
+ * The account's devices of these UDIDs, by their normalized form. The filter
1627
+ * names each UDID as given and in both cases: App Store Connect keeps a
1628
+ * device's own case, which a registry's lower-case copy may not match.
1697
1629
  */
1698
- const createAppStoreConnectToken = ({ privateKey, keyId, issuerId, issuedAtSeconds = Math.floor(Date.now() / 1e3) }) => {
1699
- const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
1700
- const signingInput = `${encode({
1701
- alg: "ES256",
1702
- kid: keyId,
1703
- typ: "JWT"
1704
- })}.${encode({
1705
- iss: issuerId,
1706
- iat: issuedAtSeconds,
1707
- exp: issuedAtSeconds + TOKEN_LIFETIME_SECONDS,
1708
- aud: "appstoreconnect-v1"
1709
- })}`;
1710
- return `${signingInput}.${crypto.default.sign("sha256", Buffer.from(signingInput), {
1711
- key: privateKey,
1712
- dsaEncoding: "ieee-p1363"
1713
- }).toString("base64url")}`;
1714
- };
1715
- const readPrivateKey = async (keyPath) => {
1716
- try {
1717
- return crypto.default.createPrivateKey(await fs.default.promises.readFile(keyPath, "utf-8"));
1718
- } catch {
1719
- throw new Error("The App Store Connect API key is not a .p8 private key.");
1720
- }
1721
- };
1722
- const readApiErrors = async (response) => {
1723
- const body = await response.json().catch(() => void 0);
1724
- return Array.isArray(body?.errors) ? body.errors : [];
1725
- };
1726
- const describeDetails = (details) => details.map((detail) => `${detail.description ?? "(no description)"}${detail.code ? ` (${detail.code})` : ""}`);
1727
- /** Answers a request may outlive: a timeout, a rate limit, a server error. */
1728
- const isRetryableStatus = (status) => status === 408 || status === 429 || status >= 500;
1729
- /**
1730
- * Whether a request may succeed when sent again: a retryable answer, or a
1731
- * network failure, which fetch rejects with a TypeError. A refused key or
1732
- * request is not.
1733
- */
1734
- const isRetryable = (error) => error instanceof AppStoreConnectError ? isRetryableStatus(error.status) : error instanceof TypeError;
1735
- /** Whether App Store Connect refused a request for its rate limit only. */
1736
- const isRateLimited = (error) => error instanceof AppStoreConnectError && error.status === 429;
1737
- /**
1738
- * Runs `request`, again after a failure `retryable` accepts, up to the
1739
- * attempts.
1740
- */
1741
- const retrying = async (request, retryable = isRetryable) => {
1742
- for (let attempt = 1;; attempt++) try {
1743
- return await request();
1744
- } catch (error) {
1745
- if (!retryable(error) || attempt === COMMIT_ATTEMPTS) throw error;
1746
- await sleep(retryDelayMs(error, attempt));
1747
- }
1748
- };
1749
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1750
- /** The longest wait before a retry, so a run stays bounded. */
1751
- const MAX_RETRY_DELAY_MS = 6e4;
1752
- /**
1753
- * The first wait after a rate limit without `Retry-After`: App Store Connect
1754
- * limits a key per rolling hour, so a retry within seconds meets it again.
1755
- */
1756
- const RATE_LIMIT_DELAY_MS = 15e3;
1757
- /**
1758
- * How long to wait before sending a request again after `failure`, an
1759
- * answer or the error it raised: the `Retry-After` seconds it asks for, a
1760
- * longer backoff for a rate limit without one, and else a growing backoff,
1761
- * all within a bound.
1762
- */
1763
- const retryDelayMs = (failure, attempt) => {
1764
- const { status, retryAfter } = failure instanceof Response ? {
1765
- status: failure.status,
1766
- retryAfter: failure.headers.get("retry-after")
1767
- } : failure instanceof AppStoreConnectError ? failure : {
1768
- status: 0,
1769
- retryAfter: null
1770
- };
1771
- const seconds = retryAfter === null || retryAfter.trim() === "" ? NaN : Number(retryAfter);
1772
- const delay = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : status === 429 ? RATE_LIMIT_DELAY_MS * attempt : 1e3 * attempt;
1773
- return Math.min(delay, MAX_RETRY_DELAY_MS);
1774
- };
1630
+ const findDevices = async (request, udids) => new Map((await readPages(request, listPath({ "filter[udid]": [...new Set(udids.flatMap((udid) => [
1631
+ udid.trim(),
1632
+ udid.trim().toLowerCase(),
1633
+ udid.trim().toUpperCase()
1634
+ ]))].join(",") }))).map((device) => [keyOf(device.udid), device]));
1775
1635
  /**
1776
- * Runs `run` over `items`, at most `concurrency` at a time. After the first
1777
- * failure no item starts, and it throws that failure once every running item
1778
- * has settled, so nothing is still sending when the caller cleans up.
1636
+ * Registers devices with the Apple account, each at most once: a device that
1637
+ * is already there succeeds and changes nothing, so running it again is safe,
1638
+ * and so is a race with another run, which App Store Connect answers with 409.
1639
+ * A disabled device stays disabled, since its slot is already spent and someone
1640
+ * chose to disable it. It only registers: Xcode adds a registered device to the
1641
+ * profile at the next export, so an `.ipa` signed before never gains it.
1779
1642
  */
1780
- const runConcurrently = async (items, concurrency, run) => {
1781
- let next = 0;
1782
- let failure;
1783
- await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
1784
- while (!failure && next < items.length) {
1785
- const index = next++;
1643
+ const addAscDevices = async ({ devices, apiKey, fetch = globalThis.fetch }) => {
1644
+ const privateKey = await readPrivateKey(apiKey.keyPath);
1645
+ const request = createAppStoreConnectRequest({
1646
+ apiKey,
1647
+ privateKey,
1648
+ fetch
1649
+ });
1650
+ return describingAccess(async () => {
1651
+ const found = await findDevices(request, devices.map(({ udid }) => udid));
1652
+ const outcomes = [];
1653
+ for (const { udid, name } of devices) {
1654
+ const existing = found.get(keyOf(udid));
1655
+ if (existing !== void 0) {
1656
+ outcomes.push({
1657
+ udid,
1658
+ outcome: existing.status === "DISABLED" ? "disabled" : "already-registered",
1659
+ device: existing
1660
+ });
1661
+ continue;
1662
+ }
1786
1663
  try {
1787
- await run(items[index], index);
1664
+ const { data } = await retrying(() => request(`Registering ${udid}`, "POST", "/v1/devices", { data: {
1665
+ type: "devices",
1666
+ attributes: {
1667
+ name,
1668
+ platform: "IOS",
1669
+ udid
1670
+ }
1671
+ } }));
1672
+ outcomes.push({
1673
+ udid,
1674
+ outcome: "registered",
1675
+ device: deviceOf(data)
1676
+ });
1788
1677
  } catch (error) {
1789
- failure ??= { error };
1678
+ if (!(error instanceof AppStoreConnectError) || error.status !== 409) throw error;
1679
+ const raced = (await findDevices(request, [udid])).get(keyOf(udid));
1680
+ if (raced !== void 0) {
1681
+ outcomes.push({
1682
+ udid,
1683
+ outcome: raced.status === "DISABLED" ? "disabled" : "already-registered",
1684
+ device: raced
1685
+ });
1686
+ continue;
1687
+ }
1688
+ const reason = error.errors.map(({ detail, title }) => detail ?? title).filter(Boolean).join(" ");
1689
+ outcomes.push({
1690
+ udid,
1691
+ outcome: "refused",
1692
+ reason: reason || "App Store Connect refused it.",
1693
+ limitReached: /maximum|limit/iu.test(reason)
1694
+ });
1790
1695
  }
1791
1696
  }
1792
- }));
1793
- if (failure) throw failure.error;
1697
+ return outcomes;
1698
+ });
1699
+ };
1700
+ /** The Apple account's device for a UDID, in either case, or null. */
1701
+ const findAscDevice = async ({ udid, apiKey, fetch = globalThis.fetch }) => {
1702
+ const privateKey = await readPrivateKey(apiKey.keyPath);
1703
+ const request = createAppStoreConnectRequest({
1704
+ apiKey,
1705
+ privateKey,
1706
+ fetch
1707
+ });
1708
+ return describingAccess(async () => (await findDevices(request, [udid])).get(keyOf(udid)) ?? null);
1794
1709
  };
1795
1710
  /**
1796
- * A signing build setting's assignment: the key, any conditions such as
1797
- * `[sdk=iphoneos*]`, and the value, without a trailing comment.
1711
+ * Changes a registered device's name or status in the Apple account: the name
1712
+ * App Store Connect shows, or `DISABLED`, which keeps it out of every new
1713
+ * profile of every app on the team. Disabling never returns its slot: the
1714
+ * account's device count resets only with its membership year.
1798
1715
  */
1799
- const SIGNING_SETTING = /^\s*(CODE_SIGNING_ALLOWED|CODE_SIGNING_REQUIRED)((?:\[[^\]]*\])*)\s*=\s*([^\s/]*)\s*(?:\/\/.*)?$/u;
1800
- /** A scheme's `exportOptionsPlist`, which resolves from the project's root. */
1801
- const schemeFile = (file) => path.default.isAbsolute(file) ? file : path.default.resolve((0, _hot_updater_cli_tools.getCwd)(), file);
1802
- /** Applies one assignment, as Xcode does: the last unconditional one wins. */
1803
- const applySetting = (settings, line, label) => {
1804
- const [, key, conditions, value] = line.match(SIGNING_SETTING) ?? [];
1805
- if (!key) return;
1806
- if (conditions) settings.conditional.add(key);
1807
- else settings.values.set(key, {
1808
- value,
1809
- where: `${line.trim()} in ${label}`
1716
+ const updateAscDevice = async ({ device, change, apiKey, fetch = globalThis.fetch }) => {
1717
+ const privateKey = await readPrivateKey(apiKey.keyPath);
1718
+ const request = createAppStoreConnectRequest({
1719
+ apiKey,
1720
+ privateKey,
1721
+ fetch
1722
+ });
1723
+ return describingAccess(async () => {
1724
+ const { data } = await retrying(() => request("name" in change ? `Renaming ${device.udid}` : `Disabling ${device.udid}`, "PATCH", `/v1/devices/${encodeURIComponent(device.id)}`, { data: {
1725
+ type: "devices",
1726
+ id: device.id,
1727
+ attributes: change
1728
+ } }));
1729
+ return deviceOf(data);
1810
1730
  });
1811
1731
  };
1732
+ //#endregion
1733
+ //#region src/utils/formatCommand.ts
1812
1734
  /**
1813
- * Applies an xcconfig's signing settings over `settings`, in order,
1814
- * following its `#include`s, which resolve from the including file, as
1815
- * Xcode reads it. A file included again applies again; only an include
1816
- * cycle (`including`) stops.
1735
+ * A command to print, broken at spaces with ` \` once a line would pass
1736
+ * `width`, each continuation indented two spaces, so a terminal never wraps
1737
+ * it mid-word and it still pastes as one command.
1817
1738
  */
1818
- const applyXcconfig = async (file, label, settings, including) => {
1819
- if (including.has(file)) return;
1820
- including.add(file);
1821
- const uncommented = (await fs.default.promises.readFile(file, "utf-8").catch(() => void 0))?.replace(/\/\*[\s\S]*?\*\//gu, (comment) => comment.replace(/[^\n]/gu, ""));
1822
- for (const line of uncommented?.split("\n") ?? []) {
1823
- const include = line.match(/^\s*#include\??\s*"([^"]+)"/u)?.[1];
1824
- if (include) await applyXcconfig(path.default.resolve(path.default.dirname(file), include), include, settings, including);
1825
- else applySetting(settings, line, label);
1739
+ const formatCommand = (words, width = 74) => {
1740
+ const lines = [];
1741
+ let line = "";
1742
+ for (const word of words) {
1743
+ const next = line ? `${line} ${word}` : word;
1744
+ if (line && next.length > width - 2) {
1745
+ lines.push(`${line} \\`);
1746
+ line = ` ${word}`;
1747
+ } else line = next;
1826
1748
  }
1827
- including.delete(file);
1749
+ lines.push(line);
1750
+ return lines.join("\n");
1828
1751
  };
1752
+ //#endregion
1753
+ //#region src/utils/cocoapods.ts
1829
1754
  /**
1830
- * Where the scheme turns code signing off, after every override the build
1831
- * applies: the `extraParams` settings first, then the xcconfigs the build
1832
- * xcconfig includes over them, in order, its `xcconfig` and each
1833
- * `-xcconfig` in `extraParams`, which resolve from `ios/`, where xcodebuild
1834
- * runs (`writeBuildXcconfig`). Undefined when it signs, or when a
1835
- * conditional setting, such as `[sdk=iphoneos*]`, may decide: the build
1836
- * does.
1755
+ * A failed command's error, as `native-build` prints a refusal: why, from its
1756
+ * output without stack frames, then `rerun`, the command to run in the
1757
+ * project, on one line, as the one next step.
1837
1758
  */
1838
- const codeSigningOff = async (iosScheme) => {
1839
- const extraParams = iosScheme.extraParams ?? [];
1840
- const settings = {
1841
- values: /* @__PURE__ */ new Map(),
1842
- conditional: /* @__PURE__ */ new Set()
1843
- };
1844
- for (const entry of extraParams) applySetting(settings, entry, "extraParams");
1845
- const xcconfigs = [...iosScheme.xcconfig ? [iosScheme.xcconfig] : [], ...extraParams.flatMap((entry, index) => entry === "-xcconfig" && index + 1 < extraParams.length ? [extraParams[index + 1]] : [])];
1846
- for (const xcconfig of xcconfigs) await applyXcconfig(path.default.resolve((0, _hot_updater_cli_tools.getCwd)(), "ios", xcconfig), xcconfig, settings, /* @__PURE__ */ new Set());
1847
- for (const [key, { value, where }] of settings.values) if (/^no$/iu.test(value) && !settings.conditional.has(key)) return where;
1759
+ const commandFailure = (command, error, rerun) => {
1760
+ const { message } = (0, _hot_updater_cli_tools.commandFailedError)(command, error, rerun);
1761
+ return new _hot_updater_cli_tools.BuildFailedError(message, {
1762
+ logPath: null,
1763
+ summary: [],
1764
+ hint: message,
1765
+ cause: error
1766
+ });
1848
1767
  };
1849
1768
  /**
1850
- * The App Store Connect API key a scheme's `.ipa` uploads with: the
1851
- * `signing.ascApiKey` it signs with, or else the `asc-api-key` item. It reads
1852
- * the config, and the scheme's files that exist before the native projects
1853
- * are written, and throws, saying why, for a scheme whose build App Store
1854
- * Connect would not take: a simulator `.app`, a Debug configuration, which
1855
- * loads its JavaScript from Metro, code signing turned off, an
1856
- * `.xcarchive` it cannot export, or export options of another method. An
1857
- * `exportOptionsPlist` the adapter's prebuild writes later is checked after
1858
- * it (`assertTestFlightExportOptions`).
1769
+ * A line of the progress meter curl prints on stderr for each pod it
1770
+ * downloads, such as React Native's prebuilt core.
1859
1771
  */
1860
- const resolveTestFlightUploadKey = async ({ scheme, iosScheme }) => {
1861
- if (iosScheme.simulator) throw new Error(`The scheme ${scheme} builds a simulator .app, not an .ipa for TestFlight.`);
1862
- const configuration = iosScheme.configuration ?? "Release";
1863
- if (/debug$/i.test(configuration)) throw new Error(`The scheme ${scheme} builds ${configuration}; TestFlight takes a release build.`);
1864
- const unsigned = await codeSigningOff(iosScheme);
1865
- if (unsigned) throw new Error(`The scheme ${scheme} turns code signing off:\n${unsigned}`);
1866
- 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.`);
1867
- if (iosScheme.exportOptionsPlist && fs.default.existsSync(schemeFile(iosScheme.exportOptionsPlist))) {
1868
- const method = await readExportMethod(schemeFile(iosScheme.exportOptionsPlist));
1869
- 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.`);
1772
+ const DOWNLOAD_PROGRESS = [
1773
+ /^% Total +% Received/,
1774
+ /^Dload +Upload/,
1775
+ /^\d{1,3} +[\d.]+[kMGT]? +\d{1,3} +[\d.]+[kMGT]? /
1776
+ ];
1777
+ /**
1778
+ * `pod install`'s output: its live line shows the pod it installs, its log
1779
+ * keeps the whole output, and a failure prints CocoaPods' `[!]` errors and a
1780
+ * crash's `SomeError - …` line with its last lines, without the download
1781
+ * progress CocoaPods' curl prints on stderr.
1782
+ */
1783
+ const createPodInstallLogger = () => new _hot_updater_cli_tools.BuildLogger({
1784
+ logPrefix: "pod-install",
1785
+ createPhaseReader: () => (line) => {
1786
+ const installing = /^Installing (\S+)/.exec(line);
1787
+ if (installing) return `Installing ${installing[1]}`;
1788
+ return /^(Analyzing dependencies|Downloading dependencies|Generating Pods project|Integrating client project)$/.test(line) ? line : void 0;
1789
+ },
1790
+ failureSummary: {
1791
+ lines: [/^[A-Z]\w*(::\w+)*Error - /],
1792
+ blocks: [{
1793
+ start: /^\[!\] /,
1794
+ end: /^$/,
1795
+ includeEnd: false
1796
+ }],
1797
+ ignore: DOWNLOAD_PROGRESS,
1798
+ tail: 4,
1799
+ stopAfter: /^\[!\] Oh no, an error occurred\.$/,
1800
+ maxWidth: 76
1801
+ }
1802
+ });
1803
+ /**
1804
+ * Runs `pod install` as a step whose failure prints CocoaPods' errors and
1805
+ * the log's path, then throws a `BuildFailedError`.
1806
+ */
1807
+ const runPodInstall = async ({ command, env, sourceDir }) => {
1808
+ const logger = createPodInstallLogger();
1809
+ const failureMessage = `${command.join(" ")} failed`;
1810
+ await logger.start({
1811
+ title: "Installing CocoaPods dependencies",
1812
+ header: [`$ ${formatCommand([...Object.entries(env).map(([name, value]) => `${name}=${value}`), ...command])}`, ""]
1813
+ });
1814
+ try {
1815
+ const podProcess = (0, execa.execa)(command[0], command.slice(1), {
1816
+ cwd: sourceDir,
1817
+ env,
1818
+ all: true,
1819
+ buffer: false
1820
+ });
1821
+ const logging = podProcess.all ? logger.processStream(podProcess.all) : Promise.resolve();
1822
+ const [podResult, loggingResult] = await Promise.allSettled([podProcess, logging]);
1823
+ if (podResult.status === "rejected") throw podResult.reason;
1824
+ if (loggingResult.status === "rejected") throw loggingResult.reason;
1825
+ logger.stop("CocoaPods dependencies installed");
1826
+ } catch (error) {
1827
+ logger.writeError(error);
1828
+ const reason = error instanceof execa.ExecaError && error.exitCode !== void 0 ? `exited with code ${error.exitCode}` : error instanceof Error ? error.message : String(error);
1829
+ logger.stop(`${failureMessage} · ${reason}`, false);
1830
+ throw new _hot_updater_cli_tools.BuildFailedError(`${failureMessage}: ${reason}`, {
1831
+ logPath: logger.logPath,
1832
+ summary: logger.failureSummary,
1833
+ cause: error
1834
+ });
1835
+ } finally {
1836
+ await logger.close();
1837
+ }
1838
+ };
1839
+ const installPodsIfNeeded = async (sourceDir) => {
1840
+ const podfilePath = path.default.join(sourceDir, "Podfile");
1841
+ if (!fs.default.existsSync(podfilePath)) {
1842
+ _hot_updater_cli_tools.p.log.info("No Podfile found, skipping CocoaPods installation");
1843
+ return {
1844
+ codegen: false,
1845
+ pods: false
1846
+ };
1847
+ }
1848
+ const gemfilePaths = [path.default.join(sourceDir, "Gemfile"), path.default.join((0, _hot_updater_cli_tools.getCwd)(), "Gemfile")];
1849
+ const shouldUseBundler = (await Promise.all(gemfilePaths.map(checkShouldUseBundler))).some(Boolean);
1850
+ const reactNative = (0, _hot_updater_cli_tools.getReactNativeMetadatas)();
1851
+ const plan = resolvePodInstallPlan({
1852
+ version: reactNative.version,
1853
+ env: process.env
1854
+ });
1855
+ if (plan.runCodegen) await runReactNativeCodegen({
1856
+ projectRoot: (0, _hot_updater_cli_tools.getCwd)(),
1857
+ reactNativePath: reactNative.packagePath,
1858
+ sourceDir
1859
+ });
1860
+ if (shouldUseBundler) {
1861
+ const bundleSpinner = _hot_updater_cli_tools.p.spinner();
1862
+ bundleSpinner.start("Installing Ruby gems");
1863
+ try {
1864
+ await (0, execa.execa)("bundle", ["install"], {
1865
+ cwd: sourceDir,
1866
+ all: true
1867
+ });
1868
+ } catch (error) {
1869
+ bundleSpinner.error("bundle install failed");
1870
+ throw commandFailure("bundle install", error, sourceDir === (0, _hot_updater_cli_tools.getCwd)() ? "bundle install" : `${(0, _hot_updater_cli_tools.shellCommandLine)((0, _hot_updater_cli_tools.getCwd)(), ["cd", sourceDir])} && bundle install`);
1871
+ }
1872
+ bundleSpinner.stop("Ruby gems installed");
1870
1873
  }
1874
+ await runPodInstall({
1875
+ command: shouldUseBundler ? [
1876
+ "bundle",
1877
+ "exec",
1878
+ "pod",
1879
+ "install"
1880
+ ] : ["pod", "install"],
1881
+ env: plan.env,
1882
+ sourceDir
1883
+ });
1871
1884
  return {
1872
- kind: "asc-api-key",
1873
- name: iosScheme.signing ? (0, _hot_updater_cli_tools.parseSecretReference)(iosScheme.signing.ascApiKey, "signing.ascApiKey") : "asc-api-key"
1885
+ codegen: plan.runCodegen,
1886
+ pods: true
1874
1887
  };
1875
1888
  };
1876
- /**
1877
- * Throws when the scheme's `exportOptionsPlist` exports with another method
1878
- * than App Store Connect's, whose `.ipa` App Store Connect refuses. It reads
1879
- * the file, which an adapter's prebuild may write, so it runs after it.
1880
- */
1881
- const assertTestFlightExportOptions = async (schemeConfig) => {
1882
- if (!schemeConfig.exportOptionsPlist) return;
1883
- const method = await readExportMethod(schemeConfig.exportOptionsPlist);
1884
- 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.`);
1889
+ const checkShouldUseBundler = async (gemfilePath) => {
1890
+ try {
1891
+ if (!fs.default.existsSync(gemfilePath)) return false;
1892
+ return (await fs.default.promises.readFile(gemfilePath, "utf-8")).includes("cocoapods");
1893
+ } catch {
1894
+ return false;
1895
+ }
1885
1896
  };
1886
1897
  /**
1887
- * Requests to the App Store Connect API with `apiKey`: each carries a token
1888
- * signed with its private key, replaced well before it expires.
1898
+ * Runs React Native codegen into `<sourceDir>/build/generated/ios`, as the
1899
+ * React Native CLI does before `pod install`. Clearing the old output first
1900
+ * drops the modules of removed libraries.
1889
1901
  */
1890
- const createAppStoreConnectRequest = ({ apiKey, privateKey, fetch }) => {
1891
- let token;
1892
- const authorization = () => {
1893
- const now = Math.floor(Date.now() / 1e3);
1894
- if (!token || now - token.issuedAtSeconds >= TOKEN_REUSE_SECONDS) {
1895
- token = {
1896
- value: createAppStoreConnectToken({
1897
- privateKey,
1898
- keyId: apiKey.keyId,
1899
- issuerId: apiKey.issuerId,
1900
- issuedAtSeconds: now
1901
- }),
1902
- issuedAtSeconds: now
1903
- };
1904
- (0, _hot_updater_cli_tools.registerSecretValue)(token.value);
1905
- }
1906
- return `Bearer ${token.value}`;
1907
- };
1908
- return async (action, method, pathname, body) => {
1909
- const response = await fetch(`${API_URL$1}${pathname}`, {
1910
- method,
1911
- headers: {
1912
- Authorization: authorization(),
1913
- ...body ? { "Content-Type": "application/json" } : {}
1914
- },
1915
- ...body ? { body: JSON.stringify(body) } : {}
1902
+ const runReactNativeCodegen = async ({ projectRoot, reactNativePath, sourceDir }) => {
1903
+ await fs.default.promises.rm(path.default.join(sourceDir, "build", "generated", "ios"), {
1904
+ recursive: true,
1905
+ force: true
1906
+ });
1907
+ const args = [
1908
+ path.default.join(reactNativePath, "scripts", "generate-codegen-artifacts.js"),
1909
+ "-p",
1910
+ projectRoot,
1911
+ "-o",
1912
+ sourceDir,
1913
+ "-t",
1914
+ "ios"
1915
+ ];
1916
+ const spinner = _hot_updater_cli_tools.p.spinner();
1917
+ spinner.start("Running React Native codegen");
1918
+ try {
1919
+ await (0, execa.execa)("node", args, {
1920
+ cwd: projectRoot,
1921
+ all: true
1916
1922
  });
1917
- if (!response.ok) {
1918
- const error = new AppStoreConnectError(action, response.status, await readApiErrors(response), response.headers.get("retry-after"));
1919
- 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 });
1920
- if (response.status === 403) throw new Error(`${error.message}\nUploads need a key with the Admin, App Manager, or Developer role.`, { cause: error });
1921
- throw error;
1922
- }
1923
- return response.status === 204 ? void 0 : await response.json();
1924
- };
1923
+ } catch (error) {
1924
+ spinner.error("React Native codegen failed");
1925
+ throw commandFailure("React Native codegen", error, (0, _hot_updater_cli_tools.shellCommandLine)(projectRoot, ["node", ...args]));
1926
+ }
1927
+ spinner.stop("React Native codegen done");
1925
1928
  };
1926
- /** The App Store Connect app of `bundleId`, and its TestFlight page. */
1927
- const findApp = async (request, bundleId) => {
1928
- const { data: apps } = await retrying(() => request("Finding the App Store Connect app", "GET", `/v1/apps?${new URLSearchParams({
1929
- "filter[bundleId]": bundleId,
1930
- "fields[apps]": "bundleId"
1931
- })}`));
1932
- const app = apps.find((app) => app.attributes?.bundleId === bundleId);
1933
- 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.`);
1929
+ /**
1930
+ * The environment `pod install` runs with, and whether codegen runs first.
1931
+ *
1932
+ * From React Native 0.79, `RCT_IGNORE_PODS_DEPRECATION=1` silences the
1933
+ * deprecation notice for calling `pod install` directly and also sets
1934
+ * `RCT_SKIP_CODEGEN=1`, because the React Native CLI runs codegen itself
1935
+ * first. Hot Updater sets it the same way and runs codegen too, unless the
1936
+ * user's `RCT_SKIP_CODEGEN=1` takes codegen over. Before 0.79, and when the
1937
+ * version is unknown, CocoaPods runs codegen. A user's value of a flag wins.
1938
+ */
1939
+ const resolvePodInstallPlan = ({ version, env }) => {
1940
+ const podsSkipCodegen = version.major > 0 || version.minor >= 79;
1941
+ const usePrebuiltReactNative = version.major > 0 || version.minor >= 81;
1942
+ const ignorePodsDeprecation = env["RCT_IGNORE_PODS_DEPRECATION"] ?? (podsSkipCodegen ? "1" : void 0);
1934
1943
  return {
1935
- app,
1936
- testFlightUrl: `https://appstoreconnect.apple.com/apps/${app.id}/testflight/ios`
1944
+ runCodegen: podsSkipCodegen && ignorePodsDeprecation === "1" && env["RCT_SKIP_CODEGEN"] !== "1",
1945
+ env: {
1946
+ ...ignorePodsDeprecation !== void 0 && { RCT_IGNORE_PODS_DEPRECATION: ignorePodsDeprecation },
1947
+ RCT_USE_RN_DEP: env["RCT_USE_RN_DEP"] ?? (usePrebuiltReactNative ? "1" : "0"),
1948
+ RCT_USE_PREBUILT_RNCORE: env["RCT_USE_PREBUILT_RNCORE"] ?? (usePrebuiltReactNative ? "1" : "0")
1949
+ }
1937
1950
  };
1938
1951
  };
1952
+ //#endregion
1953
+ //#region src/utils/platform.ts
1939
1954
  /**
1940
- * Whether App Store Connect already has the `.ipa`'s build: a build of its
1941
- * version with its build number, which TestFlight lists or is processing,
1942
- * as when a reused native build was uploaded before. A build upload that
1943
- * never finished is no build, so uploading again fails as it would without
1944
- * this check.
1955
+ * Platform configurations for different Apple platforms
1945
1956
  */
1946
- const findTestFlightBuild = async ({ ipaPath, apiKey, fetch = globalThis.fetch }) => {
1947
- const [info, privateKey] = await Promise.all([readIpaInfo(ipaPath), readPrivateKey(apiKey.keyPath)]);
1948
- const request = createAppStoreConnectRequest({
1949
- apiKey,
1950
- privateKey,
1951
- fetch
1957
+ const platformConfigs = { ios: {
1958
+ name: "ios",
1959
+ deviceSdk: "iphoneos",
1960
+ simulatorSdk: "iphonesimulator",
1961
+ supportsSimulator: true,
1962
+ deviceDestination: "platform=iOS",
1963
+ simulatorDestination: "platform=iOS Simulator"
1964
+ } };
1965
+ //#endregion
1966
+ //#region src/utils/destination.ts
1967
+ const buildDestinationString = ({ deviceType, platform, useGeneric }) => `${useGeneric ? "generic/" : ""}${deviceType === "device" ? platformConfigs[platform].deviceDestination : platformConfigs[platform].simulatorDestination}`;
1968
+ /**
1969
+ * Resolves IosBuildDestination to xcodebuild destination format
1970
+ */
1971
+ const resolveDestination = ({ destination, useGeneric }) => {
1972
+ if (typeof destination === "object") {
1973
+ if ("id" in destination) return `id=${destination.id}`;
1974
+ if ("name" in destination) return `name=${destination.name}`;
1975
+ }
1976
+ switch (destination) {
1977
+ case "ios-device": return buildDestinationString({
1978
+ platform: "ios",
1979
+ deviceType: "device",
1980
+ useGeneric
1981
+ });
1982
+ case "ios-simulator": return buildDestinationString({
1983
+ platform: "ios",
1984
+ deviceType: "simulator",
1985
+ useGeneric
1986
+ });
1987
+ }
1988
+ };
1989
+ const resolveDestinations = ({ destinations, useGeneric }) => {
1990
+ return destinations.map((destination) => resolveDestination({
1991
+ destination,
1992
+ useGeneric
1993
+ }));
1994
+ };
1995
+ const getDefaultDestination = ({ platform, useGeneric, deviceType }) => {
1996
+ return buildDestinationString({
1997
+ deviceType,
1998
+ platform,
1999
+ useGeneric
1952
2000
  });
1953
- const { app, testFlightUrl } = await findApp(request, info.bundleId);
1954
- const { data: builds } = await retrying(() => request("Finding the build in App Store Connect", "GET", `/v1/builds?${new URLSearchParams({
1955
- "filter[app]": app.id,
1956
- "filter[version]": info.bundleVersion,
1957
- "filter[preReleaseVersion.version]": info.shortVersion,
1958
- "fields[builds]": "version",
1959
- limit: "1"
1960
- })}`));
1961
- return {
1962
- found: builds.length > 0,
1963
- testFlightUrl,
1964
- shortVersion: info.shortVersion,
1965
- bundleVersion: info.bundleVersion
2001
+ };
2002
+ //#endregion
2003
+ //#region src/utils/parseXcodeProjectInfo.ts
2004
+ const parseXcodeProjectInfo = async (sourceDir) => {
2005
+ const files = await fs.default.promises.readdir(sourceDir);
2006
+ const workspace = files.find((file) => file.endsWith(".xcworkspace"));
2007
+ if (workspace) return {
2008
+ isWorkspace: true,
2009
+ name: workspace,
2010
+ path: path.default.join(sourceDir, workspace)
2011
+ };
2012
+ const project = files.find((file) => file.endsWith(".xcodeproj"));
2013
+ if (project) return {
2014
+ isWorkspace: false,
2015
+ name: project,
2016
+ path: path.default.join(sourceDir, project)
1966
2017
  };
2018
+ throw new Error(`No Xcode project or workspace found in ${sourceDir}`);
2019
+ };
2020
+ //#endregion
2021
+ //#region src/utils/prettifyXcodebuildError.ts
2022
+ const prettifyXcodebuildError = (error) => {
2023
+ if (error instanceof _hot_updater_cli_tools.BuildFailedError) {
2024
+ const errorLines = error.summary.join("\n");
2025
+ 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;
2026
+ return new _hot_updater_cli_tools.BuildFailedError(hint ?? error.message, {
2027
+ logPath: error.logPath,
2028
+ summary: error.summary,
2029
+ hint,
2030
+ cause: error.cause
2031
+ });
2032
+ }
2033
+ return /* @__PURE__ */ new Error(`Xcodebuild failed: ${error}`);
2034
+ };
2035
+ //#endregion
2036
+ //#region src/utils/xcodebuildPhase.ts
2037
+ /** The `(in target 'X' from project 'Y')` that ends an action's line. */
2038
+ const TARGET = /\(in target '([^']+)' from project '[^']+'\)\s*$/;
2039
+ /** A `PhaseScriptExecution` line's script phase, its spaces escaped. */
2040
+ const SCRIPT = /^PhaseScriptExecution ((?:\\.|[^\s\\])+)/;
2041
+ /** A batched `SwiftCompile`'s files: `Compiling\ A.swift,\ B.swift`. */
2042
+ const SWIFT_BATCH = /^SwiftCompile \S+ \S+ Compiling\\ ((?:\\.|[^\s\\])+)/;
2043
+ const unescape = (value) => value.replace(/\\(.)/g, "$1");
2044
+ /** Actions whose lines say what xcodebuild is doing, by their first word. */
2045
+ const ACTIONS = {
2046
+ CompileAssetCatalog: "Compiling assets",
2047
+ CompileAssetCatalogVariant: "Compiling assets",
2048
+ LinkAssetCatalog: "Compiling assets",
2049
+ CompileStoryboard: "Compiling storyboards",
2050
+ CompileXIB: "Compiling storyboards",
2051
+ LinkStoryboards: "Compiling storyboards",
2052
+ Ld: "Linking",
2053
+ Libtool: "Linking",
2054
+ CodeSign: "Signing",
2055
+ ProcessInfoPlistFile: "Processing",
2056
+ ProcessProductPackaging: "Processing",
2057
+ ProcessProductPackagingDER: "Processing",
2058
+ CopySwiftLibs: "Copying",
2059
+ CpResource: "Copying",
2060
+ GenerateDSYMFile: "Generating dSYM",
2061
+ Strip: "Stripping",
2062
+ Validate: "Validating"
1967
2063
  };
2064
+ const COMPILES = /* @__PURE__ */ new Set([
2065
+ "CompileC",
2066
+ "SwiftCompile",
2067
+ "CompileSwift"
2068
+ ]);
2069
+ const PRECOMPILES = /* @__PURE__ */ new Set([
2070
+ "PrecompileModule",
2071
+ "ScanDependencies",
2072
+ "SwiftExplicitDependencyGeneratePcm",
2073
+ "SwiftExplicitDependencyCompileModuleFromInterface"
2074
+ ]);
2075
+ const plural = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
1968
2076
  /**
1969
- * Uploads an `.ipa` to App Store Connect, which lists it in TestFlight, with
1970
- * the App Store Connect API's build uploads: it finds the app by the
1971
- * `.ipa`'s bundle ID, reserves the build's version and build number, sends
1972
- * the file in the parts App Store Connect asks for, commits it, and waits
1973
- * for App Store Connect to accept or reject the build.
2077
+ * Reads the phase of an `xcodebuild` build, archive, or export from its raw
2078
+ * output: `Compiling React-Core · 412 files`, `Linking ExampleApp`,
2079
+ * `Signing ExampleApp`, `Bundling JavaScript`, with the target each
2080
+ * action's line names.
1974
2081
  */
1975
- const uploadToTestFlight = async ({ ipaPath, apiKey, fetch = globalThis.fetch, pollIntervalMs = 5e3, processingTimeoutMs = 18e5 }) => {
1976
- const ipaName = path.default.basename(ipaPath);
1977
- const [info, privateKey, { size: fileSize }] = await Promise.all([
1978
- readIpaInfo(ipaPath),
1979
- readPrivateKey(apiKey.keyPath),
1980
- fs.default.promises.stat(ipaPath)
1981
- ]);
1982
- const request = createAppStoreConnectRequest({
1983
- apiKey,
1984
- privateKey,
1985
- fetch
1986
- });
1987
- const { app, testFlightUrl } = await findApp(request, info.bundleId);
1988
- let buildUploadId;
1989
- let unanswered = false;
1990
- for (let attempt = 1; buildUploadId === void 0; attempt++) try {
1991
- ({data: {id: buildUploadId}} = await request("Creating the build upload", "POST", "/v1/buildUploads", { data: {
1992
- type: "buildUploads",
1993
- attributes: {
1994
- platform: "IOS",
1995
- cfBundleShortVersionString: info.shortVersion,
1996
- cfBundleVersion: info.bundleVersion
1997
- },
1998
- relationships: { app: { data: {
1999
- type: "apps",
2000
- id: app.id
2001
- } } }
2002
- } }));
2003
- } catch (error) {
2004
- if (error instanceof AppStoreConnectError && error.status === 409 && error.errors.some((apiError) => apiError.code === DUPLICATE_ERROR_CODE)) {
2005
- if (unanswered) throw new Error([
2006
- `App Store Connect already has build ${info.bundleVersion} of version ${info.shortVersion}.`,
2007
- "An unanswered request of this upload may have reserved it.",
2008
- "Upload with a new build number (CFBundleVersion)."
2009
- ].join("\n"), { cause: error });
2010
- throw new TestFlightBuildExistsError(info.shortVersion, info.bundleVersion, { cause: error });
2082
+ const createXcodebuildPhaseReader = () => {
2083
+ let compiled = 0;
2084
+ let precompiled = 0;
2085
+ return (line) => {
2086
+ const space = line.indexOf(" ");
2087
+ const action = space === -1 ? line : line.slice(0, space);
2088
+ const target = TARGET.exec(line)?.[1];
2089
+ const withTarget = (phase) => target ? `${phase} ${target}` : phase;
2090
+ if (COMPILES.has(action)) {
2091
+ const batch = SWIFT_BATCH.exec(line)?.[1];
2092
+ compiled += batch ? unescape(batch).split(",").length : 1;
2093
+ return `${withTarget("Compiling")} · ${plural(compiled, "file")}`;
2011
2094
  }
2012
- if (!isRetryable(error) || attempt === COMMIT_ATTEMPTS) throw error;
2013
- if (!isRateLimited(error)) unanswered = true;
2014
- await sleep(retryDelayMs(error, attempt));
2015
- }
2016
- _hot_updater_cli_tools.p.log.info(`Uploading ${ipaName} ${info.shortVersion} (${info.bundleVersion}) to App Store Connect`);
2017
- const removeUpload = async () => {
2018
- for (let attempt = 1;; attempt++) try {
2019
- await request("Removing the build upload", "DELETE", `/v1/buildUploads/${buildUploadId}`);
2020
- return;
2021
- } catch (error) {
2022
- if (error instanceof AppStoreConnectError && error.status === 404) return;
2023
- if (!isRetryable(error) || attempt === COMMIT_ATTEMPTS) {
2024
- _hot_updater_cli_tools.p.log.warn([
2025
- `App Store Connect kept the unfinished upload of build ${info.bundleVersion}.`,
2026
- error.message,
2027
- "Upload with a new build number (CFBundleVersion)."
2028
- ].join("\n"));
2029
- return;
2030
- }
2031
- await sleep(retryDelayMs(error, attempt));
2095
+ if (PRECOMPILES.has(action)) {
2096
+ precompiled += 1;
2097
+ return `Precompiling modules · ${precompiled}`;
2032
2098
  }
2099
+ if (action === "PhaseScriptExecution") {
2100
+ const script = unescape(SCRIPT.exec(line)?.[1] ?? "");
2101
+ if (script === "Bundle React Native code and images") return "Bundling JavaScript";
2102
+ return script ? `Running ${script}` : withTarget("Running a script");
2103
+ }
2104
+ const phase = ACTIONS[action];
2105
+ if (phase) return withTarget(phase);
2106
+ if (line === "Prepare packages" || line.startsWith("Resolve Package")) return "Resolving packages";
2107
+ if (line === "ComputeTargetDependencyGraph") return "Planning the build";
2033
2108
  };
2034
- let fileId;
2035
- try {
2036
- const { data } = await retrying(() => request("Reserving the .ipa upload", "POST", "/v1/buildUploadFiles", { data: {
2037
- type: "buildUploadFiles",
2038
- attributes: {
2039
- assetType: "ASSET",
2040
- fileName: ipaName,
2041
- fileSize,
2042
- uti: "com.apple.ipa"
2043
- },
2044
- relationships: { buildUpload: { data: {
2045
- type: "buildUploads",
2046
- id: buildUploadId
2047
- } } }
2048
- } }), isRateLimited);
2049
- fileId = data.id;
2050
- const operations = data.attributes?.uploadOperations ?? [];
2051
- if (operations.length === 0) throw new Error("App Store Connect returned no upload operations.");
2052
- await uploadParts({
2053
- ipaPath,
2054
- operations,
2055
- fetch
2109
+ };
2110
+ //#endregion
2111
+ //#region src/utils/createXcodebuildLogger.ts
2112
+ const createXcodebuildLogger = ({ logPrefix, logFilePath }) => new _hot_updater_cli_tools.BuildLogger({
2113
+ logPrefix,
2114
+ logFilePath,
2115
+ createPhaseReader: createXcodebuildPhaseReader,
2116
+ failureSummary: {
2117
+ lines: [/(^|:\s)error: /, /^\*\* [A-Z ]+ FAILED \*\*$/],
2118
+ blocks: [{
2119
+ start: "The following build commands failed:",
2120
+ end: /^\(\d+ failures?\)$/,
2121
+ includeEnd: true
2122
+ }, {
2123
+ start: /^error: exportArchive /,
2124
+ end: /^$/,
2125
+ includeEnd: false
2126
+ }]
2127
+ }
2128
+ });
2129
+ //#endregion
2130
+ //#region src/utils/runXcodebuildWithLogging.ts
2131
+ const TERMINATION_SIGNALS$1 = ["SIGINT", "SIGTERM"];
2132
+ const createRawXcodebuildProcess = ({ args, env, sourceDir }) => {
2133
+ return (0, execa.execa)("xcodebuild", args, {
2134
+ cwd: sourceDir,
2135
+ all: true,
2136
+ buffer: false,
2137
+ env: {
2138
+ ...process.env,
2139
+ ...env,
2140
+ NSUnbufferedIO: "YES"
2141
+ }
2142
+ });
2143
+ };
2144
+ /** Why xcodebuild failed, without its command line. */
2145
+ const describeFailure = (error) => {
2146
+ if (error instanceof execa.ExecaError) {
2147
+ if (error.signal) return `xcodebuild was stopped by ${error.signal}.`;
2148
+ if (error.exitCode !== void 0) return `xcodebuild exited with code ${error.exitCode}.`;
2149
+ }
2150
+ return error instanceof Error ? error.message : String(error);
2151
+ };
2152
+ /**
2153
+ * Runs xcodebuild as a step titled `title`: its live line shows the build's
2154
+ * phase, the log file keeps the command and the whole output, and a failure
2155
+ * prints the output's errors and the log's path on stderr.
2156
+ */
2157
+ const runXcodebuildWithLogging = async ({ args, env, sourceDir, title, successMessage, failureMessage, logPrefix, logFilePath, header = [] }) => {
2158
+ const logger = createXcodebuildLogger({
2159
+ logPrefix,
2160
+ logFilePath
2161
+ });
2162
+ await logger.start({
2163
+ title,
2164
+ header: [
2165
+ ...header,
2166
+ `$ ${formatCommand(["xcodebuild", ...args])}`,
2167
+ ""
2168
+ ]
2169
+ });
2170
+ const activeProcesses = [];
2171
+ const terminateActiveProcesses = () => {
2172
+ for (const activeProcess of activeProcesses) activeProcess.kill();
2173
+ };
2174
+ for (const signal of TERMINATION_SIGNALS$1) process.once(signal, terminateActiveProcesses);
2175
+ try {
2176
+ const xcodebuildProcess = createRawXcodebuildProcess({
2177
+ args,
2178
+ env,
2179
+ sourceDir
2056
2180
  });
2181
+ activeProcesses.push(xcodebuildProcess);
2182
+ const xcodebuildOutput = xcodebuildProcess.all ?? xcodebuildProcess.stdout;
2183
+ const logging = xcodebuildOutput ? logger.processStream(xcodebuildOutput) : Promise.resolve();
2184
+ const [xcodebuildResult, loggingResult] = await Promise.allSettled([xcodebuildProcess, logging]);
2185
+ if (xcodebuildResult.status === "rejected") throw xcodebuildResult.reason;
2186
+ if (loggingResult.status === "rejected") throw loggingResult.reason;
2187
+ logger.stop(successMessage);
2188
+ return { logFilePath: logger.logFilePath };
2057
2189
  } catch (error) {
2058
- await removeUpload();
2059
- throw error;
2190
+ logger.writeError(error);
2191
+ const reason = describeFailure(error);
2192
+ logger.stop(`${failureMessage} · ${reason.replace(/\.$/, "")}`, false);
2193
+ throw new _hot_updater_cli_tools.BuildFailedError(`${failureMessage}: ${reason}`, {
2194
+ logPath: logger.logPath,
2195
+ summary: logger.failureSummary,
2196
+ cause: error
2197
+ });
2198
+ } finally {
2199
+ for (const signal of TERMINATION_SIGNALS$1) process.off(signal, terminateActiveProcesses);
2200
+ await logger.close();
2060
2201
  }
2061
- let commitUnanswered = false;
2062
- for (let attempt = 1;; attempt++) try {
2063
- await request("Committing the .ipa upload", "PATCH", `/v1/buildUploadFiles/${fileId}`, { data: {
2064
- type: "buildUploadFiles",
2065
- id: fileId,
2066
- attributes: { uploaded: true }
2067
- } });
2068
- break;
2069
- } catch (error) {
2070
- const unconfirmed = () => new Error([
2071
- `App Store Connect didn't confirm the upload of build ${info.bundleVersion}.`,
2072
- error.message,
2073
- "Check TestFlight before you upload it again:",
2074
- testFlightUrl
2075
- ].join("\n"), { cause: error });
2076
- if (!isRetryable(error)) {
2077
- if (commitUnanswered) throw unconfirmed();
2078
- await removeUpload();
2079
- throw error;
2202
+ };
2203
+ //#endregion
2204
+ //#region src/utils/writeBuildXcconfig.ts
2205
+ const SDK_CONDITIONS = [
2206
+ "",
2207
+ "[sdk=iphoneos*]",
2208
+ "[sdk=iphonesimulator*]"
2209
+ ];
2210
+ /**
2211
+ * Finds a setting of `keys` that an included xcconfig sets with a condition
2212
+ * the build xcconfig does not, such as `[config=Release]` or `[arch=arm64]`,
2213
+ * which would outrank the build's own. It follows `#include`s, which are
2214
+ * relative to the including file.
2215
+ */
2216
+ const findConditionalSetting = async (files, keys, visited = /* @__PURE__ */ new Set()) => {
2217
+ for (const file of files) {
2218
+ if (visited.has(file) || !fs.default.existsSync(file)) continue;
2219
+ visited.add(file);
2220
+ const lines = (await fs.default.promises.readFile(file, "utf-8")).split("\n");
2221
+ for (const [index, line] of lines.entries()) {
2222
+ const include = line.match(/^\s*#include\??\s*"([^"]+)"/)?.[1];
2223
+ if (include) {
2224
+ const found = await findConditionalSetting([path.default.resolve(path.default.dirname(file), include)], keys, visited);
2225
+ if (found) return found;
2226
+ continue;
2227
+ }
2228
+ const [, key, conditions] = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)((?:\[[^\]]*\])+)\s*=/) ?? [];
2229
+ if (key && keys.includes(key) && !SDK_CONDITIONS.includes(conditions)) return `${file}:${index + 1} sets ${key}${conditions}`;
2080
2230
  }
2081
- commitUnanswered = true;
2082
- const fileState = await retrying(() => request("Reading the .ipa upload", "GET", `/v1/buildUploadFiles/${fileId}?fields[buildUploadFiles]=assetDeliveryState`)).then(({ data }) => data.attributes?.assetDeliveryState?.state).catch(() => void 0);
2083
- if (fileState && fileState !== "AWAITING_UPLOAD") break;
2084
- if (attempt === COMMIT_ATTEMPTS) throw unconfirmed();
2085
- await sleep(retryDelayMs(error, attempt));
2086
2231
  }
2087
- const deadline = Date.now() + processingTimeoutMs;
2088
- let reportedProcessing = false;
2089
- let lastError;
2090
- for (let failedReads = 0;;) {
2091
- let readError;
2092
- const read = await request("Reading the build upload", "GET", `/v1/buildUploads/${buildUploadId}`).catch((error) => {
2093
- if (!isRetryable(error)) throw error;
2094
- lastError = readError = error;
2232
+ };
2233
+ /**
2234
+ * Writes the xcconfig a build loads, which sets the CLI's build settings
2235
+ * over every other. xcodebuild ranks an `-xcconfig`'s settings above the
2236
+ * command line's, so the scheme's `xcconfig` and each `-xcconfig` in
2237
+ * `extraParams` are included, in order, before `settings`, and the build
2238
+ * loads only this one.
2239
+ */
2240
+ const writeBuildXcconfig = async ({ directory, sourceDir, xcconfig, extraParams = [], settings }) => {
2241
+ const included = xcconfig ? [xcconfig] : [];
2242
+ const otherParams = [];
2243
+ for (let i = 0; i < extraParams.length; i++) if (extraParams[i] === "-xcconfig" && i + 1 < extraParams.length) included.push(extraParams[++i]);
2244
+ else otherParams.push(extraParams[i]);
2245
+ const includedFiles = included.map((file) => path.default.resolve(sourceDir, file));
2246
+ const conditional = await findConditionalSetting(includedFiles, Object.keys(settings));
2247
+ if (conditional) throw new Error(`${conditional}, which would outrank the value the build sets. Set it without that condition, or remove it.`);
2248
+ const buildXcconfig = path.default.join(directory, "HotUpdater.xcconfig");
2249
+ await fs.default.promises.writeFile(buildXcconfig, [
2250
+ ...includedFiles.map((file) => `#include "${file}"`),
2251
+ ...Object.entries(settings).flatMap(([key, value]) => SDK_CONDITIONS.map((condition) => `${key}${condition} = ${value}`)),
2252
+ ""
2253
+ ].join("\n"));
2254
+ return {
2255
+ xcconfig: buildXcconfig,
2256
+ extraParams: otherParams
2257
+ };
2258
+ };
2259
+ /**
2260
+ * Automatic signing over a target set to manual signing, whose provisioning
2261
+ * profile and identity Xcode would otherwise report as conflicting.
2262
+ */
2263
+ const AUTOMATIC_SIGNING = {
2264
+ CODE_SIGN_STYLE: "Automatic",
2265
+ PROVISIONING_PROFILE: "",
2266
+ PROVISIONING_PROFILE_SPECIFIER: "",
2267
+ CODE_SIGN_IDENTITY: "Apple Development"
2268
+ };
2269
+ /** The sandbox layer's sources, by the file names the podspec excludes. */
2270
+ const SANDBOX_SOURCES = "HotUpdaterSandbox*";
2271
+ /** What each of those sources is wrapped in: without it, they compile to nothing. */
2272
+ const SANDBOX_CONDITION = "HOT_UPDATER_SANDBOX_LAYER";
2273
+ /**
2274
+ * The settings a build sets over the scheme's: the MIN_BUNDLE_ID the CLI
2275
+ * issues and reports, and automatic signing when an App Store Connect API key
2276
+ * signs, which a target set to manual signing would not use.
2277
+ *
2278
+ * A sandbox scheme brings the sandbox layer's sources back, and sets the
2279
+ * condition they compile under, which nothing else sets: any build can undo the
2280
+ * podspec's exclusion, and those sources then compile to nothing. Any other scheme
2281
+ * excludes them again: a scheme's `xcconfig`, which outranks the pod's settings
2282
+ * on every target, would otherwise replace the podspec's exclusion, and the
2283
+ * layer would compile into a store build.
2284
+ */
2285
+ const buildSettingsOverScheme = ({ minBundleId, authenticationArgs, sandbox = false }) => ({
2286
+ HOT_UPDATER_MIN_BUNDLE_ID: minBundleId,
2287
+ ...authenticationArgs ? AUTOMATIC_SIGNING : {},
2288
+ ...sandbox ? {
2289
+ INCLUDED_SOURCE_FILE_NAMES: SANDBOX_SOURCES,
2290
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: `$(inherited) ${SANDBOX_CONDITION}`,
2291
+ GCC_PREPROCESSOR_DEFINITIONS: `$(inherited) ${SANDBOX_CONDITION}=1`
2292
+ } : { EXCLUDED_SOURCE_FILE_NAMES: `$(inherited) ${SANDBOX_SOURCES}` }
2293
+ });
2294
+ //#endregion
2295
+ //#region src/builder/archiveXcodeProject.ts
2296
+ /**
2297
+ * Archives the scheme into `archiveDirectory`. The build's xcconfig is
2298
+ * written to a temporary directory, removed whether the archive succeeds or
2299
+ * not.
2300
+ */
2301
+ const archiveXcodeProject = async ({ sourceDir, archiveDirectory, platform, installPods, destination, extraParams, configuration, xcodeScheme, xcconfig, logPrefix, header = [], minBundleId, authenticationArgs, sandbox }) => {
2302
+ if (installPods) await installPodsIfNeeded(sourceDir);
2303
+ const xcodeProject = await parseXcodeProjectInfo(sourceDir);
2304
+ const archiveName = `${xcodeProject.name.replace(".xcworkspace", "").replace(".xcodeproj", "")}.xcarchive`;
2305
+ const archivePath = path.default.join(archiveDirectory, archiveName);
2306
+ const tmpDir = await createRandomTmpDir();
2307
+ try {
2308
+ const build = await writeBuildXcconfig({
2309
+ directory: tmpDir,
2310
+ sourceDir,
2311
+ xcconfig,
2312
+ extraParams,
2313
+ settings: buildSettingsOverScheme({
2314
+ minBundleId,
2315
+ authenticationArgs,
2316
+ sandbox
2317
+ })
2095
2318
  });
2096
- failedReads = read ? 0 : failedReads + 1;
2097
- const state = read ? read.data.attributes?.state ?? {} : {};
2098
- if (state.state === "PROCESSING") reportedProcessing = true;
2099
- if (!state.state || IN_PROGRESS_STATES.has(state.state)) {
2100
- if (Date.now() >= deadline) {
2101
- if (!reportedProcessing) throw new Error([
2102
- `App Store Connect didn't report build ${info.bundleVersion} processing.`,
2103
- lastError instanceof Error ? lastError.message : state.state ? `State: ${state.state}` : void 0,
2104
- "Check the build in TestFlight:",
2105
- testFlightUrl
2106
- ].filter(Boolean).join("\n"), { cause: lastError });
2107
- _hot_updater_cli_tools.p.log.warn(`App Store Connect is still processing build ${info.bundleVersion}.\nTestFlight lists it once processing finishes:\n${testFlightUrl}`);
2108
- return {
2109
- appId: app.id,
2110
- buildUploadId,
2111
- state: "PROCESSING",
2112
- testFlightUrl,
2113
- shortVersion: info.shortVersion,
2114
- bundleVersion: info.bundleVersion
2115
- };
2116
- }
2117
- await sleep(readError === void 0 ? pollIntervalMs : Math.max(pollIntervalMs, retryDelayMs(readError, failedReads)));
2118
- continue;
2319
+ const archiveArgs = prepareArchiveArgs({
2320
+ authenticationArgs,
2321
+ minBundleId,
2322
+ archivePath,
2323
+ platform,
2324
+ sourceDir,
2325
+ xcodeProject,
2326
+ configuration,
2327
+ extraParams: build.extraParams,
2328
+ destination,
2329
+ xcconfig: build.xcconfig,
2330
+ xcodeScheme
2331
+ });
2332
+ try {
2333
+ const { logFilePath } = await runXcodebuildWithLogging({
2334
+ args: archiveArgs,
2335
+ env: { HOT_UPDATER_MIN_BUNDLE_ID: minBundleId },
2336
+ title: `Archiving ${xcodeScheme}`,
2337
+ successMessage: `Archived ${xcodeScheme}`,
2338
+ failureMessage: "Archive failed",
2339
+ logPrefix,
2340
+ header: [
2341
+ ...header,
2342
+ `Project ${xcodeProject.name}`,
2343
+ `Scheme ${xcodeScheme}`,
2344
+ `Platform ${platform}`
2345
+ ],
2346
+ sourceDir
2347
+ });
2348
+ return {
2349
+ archivePath,
2350
+ logFilePath
2351
+ };
2352
+ } catch (error) {
2353
+ throw prettifyXcodebuildError(error);
2119
2354
  }
2120
- for (const warning of describeDetails(state.warnings ?? [])) _hot_updater_cli_tools.p.log.warn(warning);
2121
- if (state.state !== "COMPLETE") {
2122
- const errors = describeDetails(state.errors ?? []);
2123
- throw new Error([`App Store Connect rejected build ${info.bundleVersion} of version ${info.shortVersion} (${state.state}).`, ...errors.map((error) => `- ${error}`)].join("\n"));
2355
+ } finally {
2356
+ await removeTmpDir(tmpDir);
2357
+ }
2358
+ };
2359
+ const prepareArchiveArgs = ({ xcodeScheme, archivePath, platform, sourceDir, xcodeProject, configuration = "Release", xcconfig, extraParams, destination = [], minBundleId, authenticationArgs }) => {
2360
+ const args = [
2361
+ xcodeProject.isWorkspace ? "-workspace" : "-project",
2362
+ path.default.join(sourceDir, xcodeProject.name),
2363
+ "-scheme",
2364
+ xcodeScheme,
2365
+ "-configuration",
2366
+ configuration,
2367
+ "archive",
2368
+ "-archivePath",
2369
+ archivePath,
2370
+ `HOT_UPDATER_MIN_BUNDLE_ID=${minBundleId}`
2371
+ ];
2372
+ if (authenticationArgs) args.push(...authenticationArgs);
2373
+ if (xcconfig) args.push("-xcconfig", xcconfig);
2374
+ if (extraParams) args.push(...extraParams);
2375
+ const resolvedDestinations = resolveDestinations({
2376
+ destinations: destination,
2377
+ useGeneric: true
2378
+ });
2379
+ if (resolvedDestinations.length === 0) resolvedDestinations.push(getDefaultDestination({
2380
+ deviceType: "device",
2381
+ platform,
2382
+ useGeneric: true
2383
+ }));
2384
+ for (const destination of resolvedDestinations) args.push("-destination", destination);
2385
+ return args;
2386
+ };
2387
+ //#endregion
2388
+ //#region src/builder/buildXcodeProject.ts
2389
+ /**
2390
+ * Builds the scheme in a temporary DerivedData directory, copies the built
2391
+ * `.app` to `outputDirectory`, and removes DerivedData, which takes 10 GB or
2392
+ * more, whether the build succeeds or not.
2393
+ */
2394
+ const buildXcodeProject = async ({ sourceDir, outputDirectory, platform, xcodeScheme, configuration, deviceType, logPrefix, destination = [], useGenericDestination = false, installPods, xcconfig, extraParams, minBundleId, authenticationArgs, sandbox, header = [] }) => {
2395
+ if (installPods) await installPodsIfNeeded(sourceDir);
2396
+ const xcodeProject = await parseXcodeProjectInfo(sourceDir);
2397
+ const tmpDir = await createRandomTmpDir();
2398
+ try {
2399
+ const derivedDataPath = path.default.join(tmpDir, "DerivedData");
2400
+ const resolvedDestinations = resolveDestinations({
2401
+ destinations: destination,
2402
+ useGeneric: useGenericDestination
2403
+ });
2404
+ if (resolvedDestinations.length === 0) resolvedDestinations.push(getDefaultDestination({
2405
+ deviceType,
2406
+ platform,
2407
+ useGeneric: useGenericDestination
2408
+ }));
2409
+ const build = await writeBuildXcconfig({
2410
+ directory: tmpDir,
2411
+ sourceDir,
2412
+ xcconfig,
2413
+ extraParams,
2414
+ settings: buildSettingsOverScheme({
2415
+ minBundleId,
2416
+ authenticationArgs,
2417
+ sandbox
2418
+ })
2419
+ });
2420
+ const buildArgs = prepareBuildArgs({
2421
+ authenticationArgs,
2422
+ xcconfig: build.xcconfig,
2423
+ minBundleId,
2424
+ configuration,
2425
+ derivedDataPath,
2426
+ deviceType,
2427
+ resolvedDestinations,
2428
+ extraParams: build.extraParams,
2429
+ platform,
2430
+ xcodeScheme,
2431
+ sourceDir,
2432
+ xcodeProject
2433
+ });
2434
+ let builtAppPath;
2435
+ let logFilePath;
2436
+ try {
2437
+ ({logFilePath} = await runXcodebuildWithLogging({
2438
+ args: buildArgs,
2439
+ env: { HOT_UPDATER_MIN_BUNDLE_ID: minBundleId },
2440
+ sourceDir,
2441
+ logPrefix,
2442
+ header: [
2443
+ ...header,
2444
+ `Project ${xcodeProject.name}`,
2445
+ `Scheme ${xcodeScheme}`,
2446
+ `Configuration ${configuration}`,
2447
+ `Platform ${platform}`,
2448
+ `Device type ${deviceType}`
2449
+ ],
2450
+ title: `Building ${xcodeScheme}`,
2451
+ successMessage: `Built ${xcodeScheme}`,
2452
+ failureMessage: "Build failed"
2453
+ }));
2454
+ ({appPath: builtAppPath} = await getBuildSettings({
2455
+ configuration,
2456
+ derivedDataPath,
2457
+ resolvedDestinations,
2458
+ xcodeScheme,
2459
+ sourceDir,
2460
+ xcodeProject,
2461
+ xcconfig: build.xcconfig,
2462
+ extraParams: build.extraParams
2463
+ }));
2464
+ } catch (error) {
2465
+ throw prettifyXcodebuildError(error);
2124
2466
  }
2467
+ const appPath = path.default.join(outputDirectory, path.default.basename(builtAppPath));
2468
+ await fs.default.promises.cp(builtAppPath, appPath, { recursive: true });
2125
2469
  return {
2126
- appId: app.id,
2127
- buildUploadId,
2128
- state: "COMPLETE",
2129
- testFlightUrl,
2130
- shortVersion: info.shortVersion,
2131
- bundleVersion: info.bundleVersion
2470
+ appPath,
2471
+ logFilePath
2132
2472
  };
2473
+ } finally {
2474
+ await removeTmpDir(tmpDir);
2133
2475
  }
2134
2476
  };
2135
- /**
2136
- * Sends each part App Store Connect asked for: the bytes at its offset, with
2137
- * only the headers it lists, since the URLs are presigned: another header,
2138
- * or the App Store Connect token, would break their signature.
2139
- */
2140
- const uploadParts = async ({ ipaPath, operations, fetch }) => {
2141
- const file = await fs.default.promises.open(ipaPath, "r");
2477
+ const prepareBuildArgs = ({ xcodeProject, sourceDir, platform, xcodeScheme, configuration, deviceType, resolvedDestinations, derivedDataPath, extraParams, minBundleId, authenticationArgs, xcconfig }) => {
2478
+ const sdk = deviceType === "simulator" ? platformConfigs[platform].simulatorSdk : platformConfigs[platform].deviceSdk;
2479
+ const args = [
2480
+ xcodeProject.isWorkspace ? "-workspace" : "-project",
2481
+ path.default.join(sourceDir, xcodeProject.name),
2482
+ "-scheme",
2483
+ xcodeScheme,
2484
+ "-configuration",
2485
+ configuration,
2486
+ "-sdk",
2487
+ sdk,
2488
+ "-derivedDataPath",
2489
+ derivedDataPath,
2490
+ `HOT_UPDATER_MIN_BUNDLE_ID=${minBundleId}`,
2491
+ "build"
2492
+ ];
2493
+ if (deviceType === "simulator") args.push("ARCHS=arm64");
2494
+ if (authenticationArgs) args.push(...authenticationArgs);
2495
+ args.push("-xcconfig", xcconfig);
2496
+ if (extraParams) args.push(...extraParams);
2497
+ for (const dest of resolvedDestinations) args.push("-destination", dest);
2498
+ return args;
2499
+ };
2500
+ const BUILD_SETTING = /^[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])*=/u;
2501
+ const getBuildSettings = async ({ xcodeProject, sourceDir, xcodeScheme, configuration, resolvedDestinations, derivedDataPath, xcconfig, extraParams }) => {
2502
+ const destinationArgs = resolvedDestinations.flatMap((dest) => ["-destination", dest]);
2503
+ const { stdout: buildSettings } = await (0, execa.execa)("xcodebuild", [
2504
+ xcodeProject.isWorkspace ? "-workspace" : "-project",
2505
+ xcodeProject.name,
2506
+ "-scheme",
2507
+ xcodeScheme,
2508
+ "-configuration",
2509
+ configuration,
2510
+ ...destinationArgs,
2511
+ "-derivedDataPath",
2512
+ derivedDataPath,
2513
+ "-xcconfig",
2514
+ xcconfig,
2515
+ ...extraParams.filter((param) => BUILD_SETTING.test(param)),
2516
+ "-showBuildSettings",
2517
+ "-json"
2518
+ ], { cwd: sourceDir });
2519
+ const settings = JSON.parse(buildSettings).filter(({ target }) => target !== "React" && target !== "React-Core");
2520
+ if (settings.length === 0) throw new Error("Failed to get build settings for your project");
2521
+ const targetSettings = settings[0].buildSettings;
2522
+ const wrapperExtension = targetSettings.WRAPPER_EXTENSION;
2523
+ if (wrapperExtension !== "app" && wrapperExtension !== "framework") throw new Error(`Expected wrapper extension to be "app" or "framework" but found: ${wrapperExtension}`);
2524
+ const targetBuildDir = targetSettings.TARGET_BUILD_DIR;
2525
+ const executableFolderPath = targetSettings.EXECUTABLE_FOLDER_PATH;
2526
+ const fullProductName = targetSettings.FULL_PRODUCT_NAME;
2527
+ const infoPlistPath = targetSettings.INFOPLIST_PATH;
2528
+ if (!targetBuildDir || !executableFolderPath || !fullProductName) throw new Error("Failed to get build paths from build settings");
2529
+ return {
2530
+ appPath: path.default.join(targetBuildDir, executableFolderPath),
2531
+ infoPlistPath: path.default.join(targetBuildDir, infoPlistPath)
2532
+ };
2533
+ };
2534
+ //#endregion
2535
+ //#region src/builder/exportXcodeArchive.ts
2536
+ /** Exports the archive into `exportPath`. */
2537
+ const exportXcodeArchive = async ({ archivePath, exportPath, sourceDir, exportExtraParams, exportOptionsPlist, logPrefix, logFilePath, title, authenticationArgs }) => {
2538
+ const exportArgs = prepareExportArgs({
2539
+ authenticationArgs,
2540
+ archivePath,
2541
+ exportPath,
2542
+ exportOptionsPlist,
2543
+ exportExtraParams
2544
+ });
2142
2545
  try {
2143
- await runConcurrently(operations, UPLOAD_CONCURRENCY, async (operation, index) => {
2144
- const body = Buffer.alloc(operation.length);
2145
- const { bytesRead } = await file.read(body, 0, operation.length, operation.offset);
2146
- if (bytesRead !== operation.length) throw new Error(`${path.default.basename(ipaPath)} changed while it was uploading.`);
2147
- const headers = {};
2148
- for (const { name, value } of operation.requestHeaders ?? []) headers[name] = value;
2149
- for (let attempt = 1;; attempt++) {
2150
- const response = await fetch(operation.url, {
2151
- method: operation.method,
2152
- headers,
2153
- body
2154
- }).catch((error) => error);
2155
- if (!(response instanceof Error) && response.ok) return;
2156
- 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}`}.`);
2157
- await sleep(retryDelayMs(response, attempt));
2158
- }
2546
+ await runXcodebuildWithLogging({
2547
+ args: exportArgs,
2548
+ sourceDir,
2549
+ title: `Exporting ${title}`,
2550
+ successMessage: `Exported ${title}`,
2551
+ failureMessage: "Export failed",
2552
+ logPrefix,
2553
+ logFilePath
2159
2554
  });
2160
- } finally {
2161
- await file.close();
2555
+ return { exportPath };
2556
+ } catch (error) {
2557
+ throw prettifyXcodebuildError(error);
2558
+ }
2559
+ };
2560
+ const prepareExportArgs = ({ exportPath, archivePath, exportExtraParams, exportOptionsPlist, authenticationArgs }) => {
2561
+ const args = [
2562
+ "-exportArchive",
2563
+ "-archivePath",
2564
+ archivePath,
2565
+ "-exportPath",
2566
+ exportPath
2567
+ ];
2568
+ if (authenticationArgs) args.push(...authenticationArgs);
2569
+ if (exportExtraParams) args.push(...exportExtraParams);
2570
+ args.push("-exportOptionsPlist", exportOptionsPlist);
2571
+ return args;
2572
+ };
2573
+ //#endregion
2574
+ //#region src/utils/assertXcodebuildExist.ts
2575
+ const assertXcodebuildExist = async () => {
2576
+ try {
2577
+ await (0, execa.execa)("which", ["xcodebuild"]);
2578
+ } catch {
2579
+ _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`);
2580
+ process.exit(1);
2162
2581
  }
2163
2582
  };
2164
2583
  //#endregion
2584
+ //#region src/utils/channelInfoPlist.ts
2585
+ /**
2586
+ * Makes a built app embed `channel`: its Info.plist's `HOT_UPDATER_CHANNEL`,
2587
+ * which the SDK reads, whatever the project's Info.plist or an Expo config
2588
+ * plugin set. The app's signature covers the Info.plist, so an archived app
2589
+ * is stamped before its export signs it, and a simulator app is signed again
2590
+ * ad hoc after, as Xcode does for the simulator.
2591
+ */
2592
+ const stampAppChannel = async (appPath, channel, { signAdHoc = false } = {}) => {
2593
+ await (0, execa.execa)("plutil", [
2594
+ "-replace",
2595
+ "HOT_UPDATER_CHANNEL",
2596
+ "-string",
2597
+ channel,
2598
+ path.default.join(appPath, "Info.plist")
2599
+ ]);
2600
+ if (signAdHoc) await (0, execa.execa)("codesign", [
2601
+ "--force",
2602
+ "--sign",
2603
+ "-",
2604
+ "--timestamp=none",
2605
+ "--preserve-metadata=entitlements",
2606
+ appPath
2607
+ ]);
2608
+ };
2609
+ //#endregion
2165
2610
  //#region src/utils/ciSigningKeychain.ts
2166
2611
  const API_URL = "https://api.appstoreconnect.apple.com";
2167
2612
  const CERTIFICATES_URL = "https://developer.apple.com/account/resources/certificates/list";
@@ -2356,38 +2801,62 @@ const createSigningKeychain = async ({ security = runSecurity, directory = os.de
2356
2801
  return {
2357
2802
  path: keychainPath,
2358
2803
  certificates: async () => {
2804
+ const identities = new Set([...(await security([
2805
+ "find-identity",
2806
+ "-p",
2807
+ "codesigning",
2808
+ keychainPath
2809
+ ])).matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s/gm)].map((match) => match[1]));
2810
+ if (identities.size === 0) return [];
2359
2811
  return ((await security([
2360
2812
  "find-certificate",
2361
2813
  "-a",
2362
2814
  "-p",
2363
2815
  keychainPath
2364
- ])).match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g) ?? []).map((pem) => {
2816
+ ])).match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g) ?? []).flatMap((pem) => {
2365
2817
  const certificate = new crypto.default.X509Certificate(pem);
2366
- return {
2818
+ if (!identities.has(certificate.fingerprint.replaceAll(":", ""))) return [];
2819
+ return [{
2367
2820
  serialNumber: normalizeSerial(certificate.serialNumber),
2368
2821
  commonName: certificate.subject.match(/^CN=(.*)$/m)?.[1] ?? certificate.subject
2369
- };
2822
+ }];
2370
2823
  });
2371
2824
  },
2372
2825
  dispose
2373
2826
  };
2374
2827
  };
2828
+ /** A request App Store Connect refused, in one line. */
2829
+ var AppStoreConnectRefusal = class extends Error {
2830
+ /** Whether the team has a Program License Agreement to accept. */
2831
+ agreement;
2832
+ constructor(message, agreement) {
2833
+ super(message);
2834
+ this.agreement = agreement;
2835
+ }
2836
+ };
2837
+ const refusal$1 = async (action, response) => {
2838
+ const body = await response.json().catch(() => void 0);
2839
+ return new AppStoreConnectRefusal(`${action} failed (HTTP ${response.status}).`, isProgramLicenseAgreementError(Array.isArray(body?.errors) ? body.errors : []));
2840
+ };
2375
2841
  /**
2376
2842
  * Revokes the certificates Xcode created in the build's keychain, whose
2377
2843
  * private keys the keychain's deletion destroys: on a runner that starts
2378
2844
  * empty, Xcode creates a development certificate for every build, and App
2379
2845
  * Store Connect refuses new ones once a team has its maximum. Each is found
2380
2846
  * in the team's certificates by serial number. A revocation that fails is
2381
- * reported with where to revoke it by hand, and never fails the build.
2847
+ * reported with each certificate's name and serial and where to revoke it
2848
+ * by hand, and never fails the build.
2382
2849
  */
2383
2850
  const revokeKeychainCertificates = async ({ certificates, apiKey, privateKey, fetch = globalThis.fetch }) => {
2384
2851
  const revoked = [];
2385
2852
  const failed = [];
2853
+ /** Why none could be revoked: the token or the listing failed. */
2854
+ let reason;
2855
+ let agreement = false;
2386
2856
  if (certificates.length === 0) return {
2387
- revoked,
2388
- failed
2857
+ revoked: [],
2858
+ failed: []
2389
2859
  };
2390
- const describe = ({ commonName, serialNumber }) => `${commonName} (serial ${serialNumber})`;
2391
2860
  try {
2392
2861
  const token = createAppStoreConnectToken({
2393
2862
  privateKey: privateKey ?? crypto.default.createPrivateKey(await fs.default.promises.readFile(apiKey.keyPath, "utf-8")),
@@ -2403,7 +2872,7 @@ const revokeKeychainCertificates = async ({ certificates, apiKey, privateKey, fe
2403
2872
  })}`;
2404
2873
  while (next) {
2405
2874
  const response = await fetch(next, { headers });
2406
- if (!response.ok) throw new Error(`Listing the team's certificates failed (HTTP ${response.status}).`);
2875
+ if (!response.ok) throw await refusal$1("Listing the team's certificates", response);
2407
2876
  const body = await response.json();
2408
2877
  for (const { id, attributes } of body.data ?? []) if (attributes?.serialNumber) idsBySerial.set(normalizeSerial(attributes.serialNumber), id);
2409
2878
  next = body.links?.next;
@@ -2415,23 +2884,32 @@ const revokeKeychainCertificates = async ({ certificates, apiKey, privateKey, fe
2415
2884
  method: "DELETE",
2416
2885
  headers
2417
2886
  });
2418
- if (response.ok || response.status === 404) revoked.push(describe(certificate));
2419
- else failed.push(`${describe(certificate)}: HTTP ${response.status}`);
2887
+ if (response.ok || response.status === 404) revoked.push(certificate);
2888
+ else {
2889
+ agreement ||= (await refusal$1("Revoking", response)).agreement;
2890
+ failed.push({
2891
+ certificate,
2892
+ status: response.status
2893
+ });
2894
+ }
2420
2895
  }
2421
2896
  } catch (error) {
2422
- const reason = error instanceof Error ? error.message : String(error);
2423
- for (const certificate of certificates) if (!revoked.includes(describe(certificate))) failed.push(`${describe(certificate)}: ${reason}`);
2897
+ reason = error instanceof Error ? error.message : String(error);
2898
+ agreement ||= error instanceof AppStoreConnectRefusal && error.agreement;
2899
+ for (const certificate of certificates) if (!revoked.includes(certificate)) failed.push({ certificate });
2424
2900
  }
2425
- if (revoked.length > 0) _hot_updater_cli_tools.p.log.info(["Revoked the certificates Xcode created for this build:", ...revoked].join("\n"));
2901
+ const describe = ({ commonName, serialNumber }) => `${commonName} (serial ${serialNumber})`;
2902
+ 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"));
2426
2903
  if (failed.length > 0) _hot_updater_cli_tools.p.log.warn([
2427
2904
  "Couldn't revoke the certificates Xcode created for this build.",
2428
- ...failed,
2429
- "Revoke them at:",
2905
+ ...reason === void 0 ? [] : [reason],
2906
+ ...agreement ? [PROGRAM_LICENSE_AGREEMENT_HINT] : [],
2907
+ ...failed.flatMap(({ certificate, status }) => [certificate.commonName, `Serial ${certificate.serialNumber}${status === void 0 ? "" : ` (HTTP ${status})`}`]),
2430
2908
  CERTIFICATES_URL
2431
2909
  ].join("\n"));
2432
2910
  return {
2433
- revoked,
2434
- failed
2911
+ revoked: revoked.map(describe),
2912
+ failed: failed.map(({ certificate }) => describe(certificate))
2435
2913
  };
2436
2914
  };
2437
2915
  const TERMINATION_SIGNALS = [
@@ -2447,8 +2925,13 @@ const TERMINATION_SIGNALS = [
2447
2925
  * certificates are read from the keychain before it is deleted, and the key
2448
2926
  * is read into memory first, since the build's temporary key file is deleted
2449
2927
  * on the signal. A second signal restores the keychains at once.
2928
+ *
2929
+ * `keepDistribution` keeps a distribution certificate out of the revoking, for
2930
+ * an ad hoc export: Xcode may have signed the `.ipa` with one it created here,
2931
+ * rather than the cloud-managed one, and installs may need it valid. Only the
2932
+ * development certificates Xcode created for the archive are then revoked.
2450
2933
  */
2451
- const withSigningKeychain = async ({ enabled, apiKey, run, security, lockPath, acquireLock, fetch }) => {
2934
+ const withSigningKeychain = async ({ enabled, keepDistribution = false, apiKey, run, security, lockPath, acquireLock, fetch }) => {
2452
2935
  if (!enabled) return run();
2453
2936
  const privateKey = crypto.default.createPrivateKey(await fs.default.promises.readFile(apiKey.keyPath, "utf-8"));
2454
2937
  const keychain = await createSigningKeychain({
@@ -2463,7 +2946,7 @@ const withSigningKeychain = async ({ enabled, apiKey, run, security, lockPath, a
2463
2946
  const certificates = await keychain.certificates().catch(() => []);
2464
2947
  await keychain.dispose();
2465
2948
  await revokeKeychainCertificates({
2466
- certificates,
2949
+ certificates: keepDistribution ? certificates.filter(({ commonName }) => !commonName.includes("Distribution")) : certificates,
2467
2950
  apiKey,
2468
2951
  privateKey,
2469
2952
  fetch
@@ -2471,59 +2954,810 @@ const withSigningKeychain = async ({ enabled, apiKey, run, security, lockPath, a
2471
2954
  })();
2472
2955
  return cleanup;
2473
2956
  };
2474
- const stopListening = () => {
2475
- for (const signal of TERMINATION_SIGNALS) process.off(signal, onSignal);
2957
+ const stopListening = () => {
2958
+ for (const signal of TERMINATION_SIGNALS) process.off(signal, onSignal);
2959
+ };
2960
+ const onSignal = (signal) => {
2961
+ if (cleanup) {
2962
+ stopListening();
2963
+ restoreLive();
2964
+ process.kill(process.pid, signal);
2965
+ return;
2966
+ }
2967
+ release().finally(() => {
2968
+ stopListening();
2969
+ if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
2970
+ });
2971
+ };
2972
+ for (const signal of TERMINATION_SIGNALS) process.on(signal, onSignal);
2973
+ try {
2974
+ return await run();
2975
+ } finally {
2976
+ await release();
2977
+ stopListening();
2978
+ }
2979
+ };
2980
+ //#endregion
2981
+ //#region src/utils/readBuiltApp.ts
2982
+ const readInfoValue = async (infoPlist, key) => {
2983
+ const { stdout, exitCode } = await (0, execa.execa)("plutil", [
2984
+ "-extract",
2985
+ key,
2986
+ "raw",
2987
+ "-o",
2988
+ "-",
2989
+ infoPlist
2990
+ ], { reject: false });
2991
+ return exitCode === 0 && stdout.trim() ? stdout.trim() : null;
2992
+ };
2993
+ /**
2994
+ * What the built `.app` reports at runtime, from its Info.plist: the
2995
+ * `CFBundleShortVersionString`, `CFBundleVersion` (the build number) and
2996
+ * `HOT_UPDATER_CHANNEL` the build settings,
2997
+ * an `xcconfig` and `extraParams` expanded.
2998
+ */
2999
+ const readBuiltApp = async (appPath) => {
3000
+ const infoPlist = path.default.join(appPath, "Info.plist");
3001
+ const [appVersion, channel, buildNumber] = await Promise.all([
3002
+ readInfoValue(infoPlist, "CFBundleShortVersionString"),
3003
+ readInfoValue(infoPlist, "HOT_UPDATER_CHANNEL"),
3004
+ readInfoValue(infoPlist, "CFBundleVersion")
3005
+ ]);
3006
+ return {
3007
+ appVersion,
3008
+ channel,
3009
+ buildNumber
3010
+ };
3011
+ };
3012
+ //#endregion
3013
+ //#region src/utils/readIpaSigning.ts
3014
+ /**
3015
+ * How an exported `.ipa` is signed: its distribution, team, the devices its
3016
+ * profiles list, and the bundle IDs they are for. Null for one it can't read.
3017
+ */
3018
+ const readIpaSigning = async (ipaPath) => {
3019
+ try {
3020
+ return await (0, _hot_updater_protocol_native_artifact.readIpaInstallInfo)((0, _hot_updater_protocol_native_artifact.blobSource)(await fs.default.openAsBlob(ipaPath)));
3021
+ } catch {
3022
+ return null;
3023
+ }
3024
+ };
3025
+ //#endregion
3026
+ //#region src/sandboxTestFlight.ts
3027
+ /**
3028
+ * The states of a version Apple hasn't approved, which still takes builds.
3029
+ * Any other state, such as one Apple adds later, counts as closed: a raise
3030
+ * costs a sandbox build nothing, and an upload to a closed train costs one.
3031
+ */
3032
+ const OPEN_VERSION_STATES = /* @__PURE__ */ new Set([
3033
+ "PREPARE_FOR_SUBMISSION",
3034
+ "READY_FOR_REVIEW",
3035
+ "WAITING_FOR_REVIEW",
3036
+ "IN_REVIEW",
3037
+ "WAITING_FOR_EXPORT_COMPLIANCE",
3038
+ "PENDING_CONTRACT",
3039
+ "INVALID_BINARY",
3040
+ "METADATA_REJECTED",
3041
+ "REJECTED",
3042
+ "DEVELOPER_REJECTED"
3043
+ ]);
3044
+ /** A version as numbers: `1.6.2`, or null for one that isn't only numbers. */
3045
+ const parseVersion = (version) => /^\d+(\.\d+)*$/u.test(version) ? version.split(".").map(Number) : null;
3046
+ /** Negative, zero or positive as `a` is below, equal to or above `b`. */
3047
+ const compareVersions = (a, b) => {
3048
+ for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
3049
+ const difference = (a[i] ?? 0) - (b[i] ?? 0);
3050
+ if (difference !== 0) return difference;
3051
+ }
3052
+ return 0;
3053
+ };
3054
+ /** The highest of `versions`, ignoring any that aren't only numbers. */
3055
+ const highestVersion = (versions) => {
3056
+ let highest = null;
3057
+ for (const text of versions) {
3058
+ const parts = parseVersion(text);
3059
+ if (parts && (!highest || compareVersions(parts, highest.parts) > 0)) highest = {
3060
+ text,
3061
+ parts
3062
+ };
3063
+ }
3064
+ return highest?.text ?? null;
3065
+ };
3066
+ /** The highest integer build number among `versions`. */
3067
+ const highestBuildNumberOf = (versions) => {
3068
+ const numbers = versions.filter((version) => /^\d+$/u.test(version)).map(Number);
3069
+ return numbers.length > 0 ? Math.max(...numbers) : null;
3070
+ };
3071
+ /**
3072
+ * Reads what a sandbox build must fit before it is built: the versions Apple
3073
+ * approved, from `/v1/appStoreVersions`, since a closed train's builds look
3074
+ * like any others in `/v1/builds`, and the app's highest build number.
3075
+ */
3076
+ const readAppStoreTrain = async ({ bundleId, apiKey, fetch = globalThis.fetch }) => {
3077
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3078
+ const request = createAppStoreConnectRequest({
3079
+ apiKey,
3080
+ privateKey,
3081
+ fetch
3082
+ });
3083
+ const { app } = await findApp(request, bundleId);
3084
+ const [{ data: versions }, { data: builds }] = await Promise.all([retrying(() => request("Reading the App Store versions", "GET", `/v1/apps/${app.id}/appStoreVersions?${new URLSearchParams({
3085
+ "filter[platform]": "IOS",
3086
+ "fields[appStoreVersions]": "versionString,appVersionState,appStoreState",
3087
+ limit: "200"
3088
+ })}`)), retrying(() => request("Reading the app's builds", "GET", `/v1/builds?${new URLSearchParams({
3089
+ "filter[app]": app.id,
3090
+ sort: "-uploadedDate",
3091
+ "fields[builds]": "version",
3092
+ limit: "200"
3093
+ })}`))]);
3094
+ const closed = versions.flatMap(({ attributes }) => {
3095
+ const state = attributes?.appVersionState ?? attributes?.appStoreState;
3096
+ return attributes?.versionString && !(state && OPEN_VERSION_STATES.has(state)) ? [attributes.versionString] : [];
3097
+ });
3098
+ return {
3099
+ highestClosedVersion: highestVersion(closed),
3100
+ highestBuildNumber: highestBuildNumberOf(builds.flatMap(({ attributes }) => attributes?.version ?? []))
3101
+ };
3102
+ };
3103
+ /**
3104
+ * What a sandbox device build needs from App Store Connect, read before the
3105
+ * build. An export for elsewhere has no train, and without an API key it
3106
+ * can't be read: the store would say so after the upload. What a closed train
3107
+ * does to the build waits for the archive (`patchSandboxArchive`): only the
3108
+ * archived app holds the version an `xcconfig` or `extraParams` settled on,
3109
+ * which the project's files don't.
3110
+ */
3111
+ const prepareSandboxArchive = async ({ schemeConfig, apiKey, updateStrategy, fetch }) => {
3112
+ if (!await exportsForAppStoreConnect(schemeConfig)) return { updateStrategy };
3113
+ if (!apiKey) {
3114
+ _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.");
3115
+ return { updateStrategy };
3116
+ }
3117
+ return {
3118
+ train: await readAppStoreTrain({
3119
+ bundleId: schemeConfig.bundleIdentifier,
3120
+ apiKey,
3121
+ ...fetch ? { fetch } : {}
3122
+ }),
3123
+ updateStrategy
3124
+ };
3125
+ };
3126
+ /** Whether Apple refuses a build of `version`, as `train` says. */
3127
+ const isVersionTrainClosed = (version, { highestClosedVersion }) => {
3128
+ const parts = parseVersion(version);
3129
+ const closed = highestClosedVersion === null ? null : parseVersion(highestClosedVersion);
3130
+ return parts !== null && closed !== null && compareVersions(parts, closed) <= 0;
3131
+ };
3132
+ /**
3133
+ * What a sandbox build does with a closed version train. Under the fingerprint
3134
+ * strategy it raises its own version past the closed one, which targets no
3135
+ * update. Under appVersion the version is what updates target, so it refuses
3136
+ * rather than move them silently.
3137
+ */
3138
+ const sandboxVersionDecision = ({ version, train, updateStrategy }) => {
3139
+ if (!isVersionTrainClosed(version, train)) return { kind: "keep" };
3140
+ const closed = train.highestClosedVersion;
3141
+ if (updateStrategy === "appVersion") return {
3142
+ kind: "refuse",
3143
+ message: `App Store Connect closed version ${closed}, so TestFlight refuses ${version}.\nRaise the app version.`
3144
+ };
3145
+ const [major = 0, minor = 0, patch = 0] = parseVersion(closed);
3146
+ return {
3147
+ kind: "raise",
3148
+ version: `${major}.${minor}.${patch + 1}`
3149
+ };
3150
+ };
3151
+ /**
3152
+ * Refuses, before the upload, a sandbox `.ipa` Xcode didn't mark for internal
3153
+ * testing only: App Store Connect would let it reach App Store review.
3154
+ */
3155
+ const assertIpaIsInternalOnly = async (ipaPath) => {
3156
+ 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.`);
3157
+ };
3158
+ /** How long App Store Connect may take to list a build it accepted. */
3159
+ const AUDIENCE_TIMEOUT_MS = 3e5;
3160
+ const STATE_OF_INTERNAL_BUILD = {
3161
+ MISSING_EXPORT_COMPLIANCE: "missing-compliance",
3162
+ IN_EXPORT_COMPLIANCE_REVIEW: "missing-compliance",
3163
+ PROCESSING: "processing",
3164
+ PROCESSING_EXCEPTION: "failed",
3165
+ EXPIRED: "expired"
3166
+ };
3167
+ /**
3168
+ * One read of a version and build number: its audience, processing state,
3169
+ * expiry, and internal testing state. Null while App Store Connect lists none.
3170
+ */
3171
+ const readBuildStatus = async (request, { appId, shortVersion, bundleVersion }) => {
3172
+ const { data, included } = await retrying(() => request("Reading the build", "GET", `/v1/builds?${new URLSearchParams({
3173
+ "filter[app]": appId,
3174
+ "filter[version]": bundleVersion,
3175
+ ...shortVersion === null ? {} : { "filter[preReleaseVersion.version]": shortVersion },
3176
+ "fields[builds]": "buildAudienceType,processingState,expirationDate,expired,buildBetaDetail",
3177
+ include: "buildBetaDetail",
3178
+ "fields[buildBetaDetails]": "internalBuildState",
3179
+ limit: "1"
3180
+ })}`));
3181
+ const build = data[0];
3182
+ if (!build) return null;
3183
+ const internal = included?.find(({ type }) => type === "buildBetaDetails")?.attributes?.internalBuildState;
3184
+ const processing = build.attributes?.processingState;
3185
+ const expiration = build.attributes?.expirationDate;
3186
+ const state = build.attributes?.expired ? "expired" : processing === "PROCESSING" || !processing ? "processing" : processing !== "VALID" ? "failed" : STATE_OF_INTERNAL_BUILD[internal ?? ""] ?? "ready";
3187
+ return {
3188
+ buildId: build.id,
3189
+ audience: build.attributes?.buildAudienceType ?? null,
3190
+ state,
3191
+ ...state === "missing-compliance" && internal === "IN_EXPORT_COMPLIANCE_REVIEW" ? { inExportComplianceReview: true } : {},
3192
+ expiresAtMs: expiration ? Date.parse(expiration) : null
3193
+ };
3194
+ };
3195
+ /**
3196
+ * Fails unless App Store Connect holds the uploaded sandbox build for internal
3197
+ * testing only, as `buildAudienceType` says once the build is listed, and
3198
+ * returns what that read says of it.
3199
+ */
3200
+ const assertBuildIsInternalOnly = async ({ ipaPath, apiKey, fetch = globalThis.fetch, pollIntervalMs = 5e3, timeoutMs = AUDIENCE_TIMEOUT_MS }) => {
3201
+ const [info, privateKey] = await Promise.all([readIpaInfo(ipaPath), readPrivateKey(apiKey.keyPath)]);
3202
+ const request = createAppStoreConnectRequest({
3203
+ apiKey,
3204
+ privateKey,
3205
+ fetch
3206
+ });
3207
+ const { app, testFlightUrl } = await findApp(request, info.bundleId);
3208
+ const label = `${info.shortVersion} (${info.bundleVersion})`;
3209
+ const deadline = Date.now() + timeoutMs;
3210
+ for (;;) {
3211
+ const status = await readBuildStatus(request, {
3212
+ appId: app.id,
3213
+ shortVersion: info.shortVersion,
3214
+ bundleVersion: info.bundleVersion
3215
+ });
3216
+ if (status?.audience === "INTERNAL_ONLY") return {
3217
+ ...status,
3218
+ appId: app.id,
3219
+ testFlightUrl
3220
+ };
3221
+ 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}`);
3222
+ 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}`);
3223
+ await sleep(pollIntervalMs);
3224
+ }
3225
+ };
3226
+ /**
3227
+ * The internal TestFlight group named `name`, read before anything is built.
3228
+ * An external group is refused: its builds go to Beta App Review, and a sandbox
3229
+ * build is for internal testing only.
3230
+ */
3231
+ const findInternalBetaGroup = async ({ bundleId, name, apiKey, fetch = globalThis.fetch }) => {
3232
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3233
+ const request = createAppStoreConnectRequest({
3234
+ apiKey,
3235
+ privateKey,
3236
+ fetch
3237
+ });
3238
+ const { app, testFlightUrl } = await findApp(request, bundleId);
3239
+ return readInternalBetaGroup(request, {
3240
+ appId: app.id,
3241
+ bundleId,
3242
+ name,
3243
+ testFlightUrl
3244
+ });
3245
+ };
3246
+ /** The group named `name` of an app, refused unless it is internal. */
3247
+ const readInternalBetaGroup = async (request, { appId, bundleId, name, testFlightUrl }) => {
3248
+ const { data } = await retrying(() => request("Reading the TestFlight groups", "GET", `/v1/betaGroups?${new URLSearchParams({
3249
+ "filter[app]": appId,
3250
+ "filter[name]": name,
3251
+ "fields[betaGroups]": "name,isInternalGroup,hasAccessToAllBuilds",
3252
+ limit: "200"
3253
+ })}`));
3254
+ const group = data.find(({ attributes }) => attributes?.name === name);
3255
+ if (!group) throw new Error(`App Store Connect has no TestFlight group ${name} for ${bundleId}.\nCreate it as an internal group:\n${testFlightUrl}`);
3256
+ 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.`);
3257
+ return {
3258
+ id: group.id,
3259
+ name,
3260
+ hasAccessToAllBuilds: group.attributes.hasAccessToAllBuilds === true
3261
+ };
3262
+ };
3263
+ /** How long a build's processing may hold up its group and What to Test. */
3264
+ const DISTRIBUTION_TIMEOUT_MS = 9e5;
3265
+ /** What to Test's locale: the language the CLI writes it in. */
3266
+ const WHAT_TO_TEST_LOCALE = "en-US";
3267
+ /**
3268
+ * Adds a processed build to its internal group and sets its What to Test, which
3269
+ * App Store Connect takes once the build is processed. A build still processing
3270
+ * after `timeoutMs` keeps its upload: a warning says what to do by hand. Returns
3271
+ * the build's state.
3272
+ */
3273
+ const distributeTestFlightBuild = async ({ build: { appId, shortVersion, bundleVersion, testFlightUrl }, group, whatToTest, apiKey, fetch = globalThis.fetch, pollIntervalMs = 15e3, timeoutMs = DISTRIBUTION_TIMEOUT_MS }) => {
3274
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3275
+ const request = createAppStoreConnectRequest({
3276
+ apiKey,
3277
+ privateKey,
3278
+ fetch
3279
+ });
3280
+ const build = {
3281
+ appId,
3282
+ shortVersion,
3283
+ bundleVersion,
3284
+ testFlightUrl
3285
+ };
3286
+ const status = await waitUntilProcessed(request, build, await readBuildStatus(request, build), {
3287
+ pollIntervalMs,
3288
+ timeoutMs,
3289
+ unset: "its testers and What to Test"
3290
+ });
3291
+ if (!status || status.state === "processing") return status;
3292
+ const { buildId } = status;
3293
+ if (group && !group.hasAccessToAllBuilds) await addBuildToGroup(request, build, buildId, group);
3294
+ if (whatToTest !== void 0) await setWhatToTest(request, buildId, whatToTest);
3295
+ return status;
3296
+ };
3297
+ /**
3298
+ * Reads the build until App Store Connect has processed it, from the status a
3299
+ * read already has, for what it takes only then. A build still processing after
3300
+ * `timeoutMs` keeps its upload: a warning says what is `unset`. One that can't
3301
+ * be processed fails.
3302
+ */
3303
+ const waitUntilProcessed = async (request, build, listed, { pollIntervalMs, timeoutMs, unset }) => {
3304
+ const label = `${build.shortVersion} (${build.bundleVersion})`;
3305
+ const deadline = Date.now() + timeoutMs;
3306
+ let status = listed;
3307
+ while (!status || status.state === "processing") {
3308
+ if (Date.now() >= deadline) {
3309
+ _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}`);
3310
+ return status;
3311
+ }
3312
+ await sleep(pollIntervalMs);
3313
+ status = await readBuildStatus(request, build);
3314
+ }
3315
+ if (status.state === "failed") throw new Error(`App Store Connect couldn't process build ${label}.\nCheck it in TestFlight:\n${build.testFlightUrl}`);
3316
+ return status;
3317
+ };
3318
+ const addBuildToGroup = (request, { shortVersion, bundleVersion }, buildId, group) => retrying(() => request(`Adding build ${shortVersion} (${bundleVersion}) to ${group.name}`, "POST", `/v1/betaGroups/${group.id}/relationships/builds`, { data: [{
3319
+ type: "builds",
3320
+ id: buildId
3321
+ }] }));
3322
+ /**
3323
+ * Applies an internal group to a build already on TestFlight, as an upload does,
3324
+ * so a reused build reaches the group named now. One process reads the app, the
3325
+ * build and the group once each. Reading a build's `betaGroups` relationship
3326
+ * answered 403 when we tried it, so this doesn't check membership first: every
3327
+ * run adds the build. A build not `isOffered` gets nothing: it needs a new
3328
+ * build, which checks the group itself. A build still processing waits as an
3329
+ * upload's does, and the next run applies the group again.
3330
+ */
3331
+ const applyTestFlightGroup = async ({ bundleId, shortVersion, bundleVersion, name, isOffered, apiKey, fetch = globalThis.fetch, pollIntervalMs = 15e3, timeoutMs = DISTRIBUTION_TIMEOUT_MS }) => {
3332
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3333
+ const request = createAppStoreConnectRequest({
3334
+ apiKey,
3335
+ privateKey,
3336
+ fetch
3337
+ });
3338
+ const { app, testFlightUrl } = await findApp(request, bundleId);
3339
+ const build = {
3340
+ appId: app.id,
3341
+ shortVersion,
3342
+ bundleVersion,
3343
+ testFlightUrl
3344
+ };
3345
+ const listed = await readBuildStatus(request, build);
3346
+ if (!isOffered(listed)) return {
3347
+ testFlightUrl,
3348
+ status: listed,
3349
+ outcome: "not-offered"
2476
3350
  };
2477
- const onSignal = (signal) => {
2478
- if (cleanup) {
2479
- stopListening();
2480
- restoreLive();
2481
- process.kill(process.pid, signal);
2482
- return;
2483
- }
2484
- release().finally(() => {
2485
- stopListening();
2486
- if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
2487
- });
3351
+ const group = await readInternalBetaGroup(request, {
3352
+ appId: app.id,
3353
+ bundleId,
3354
+ name,
3355
+ testFlightUrl
3356
+ });
3357
+ if (group.hasAccessToAllBuilds) return {
3358
+ testFlightUrl,
3359
+ status: listed,
3360
+ outcome: "takes-every-build"
2488
3361
  };
2489
- for (const signal of TERMINATION_SIGNALS) process.on(signal, onSignal);
3362
+ const status = await waitUntilProcessed(request, build, listed, {
3363
+ pollIntervalMs,
3364
+ timeoutMs,
3365
+ unset: "its testers"
3366
+ });
3367
+ if (!status || status.state === "processing") return {
3368
+ testFlightUrl,
3369
+ status,
3370
+ outcome: "pending"
3371
+ };
3372
+ await addBuildToGroup(request, build, status.buildId, group);
3373
+ return {
3374
+ testFlightUrl,
3375
+ status,
3376
+ outcome: "added"
3377
+ };
3378
+ };
3379
+ /** Sets a build's What to Test: creates it, or updates the one a rerun left. */
3380
+ const setWhatToTest = async (request, buildId, whatsNew) => {
2490
3381
  try {
2491
- return await run();
2492
- } finally {
2493
- await release();
2494
- stopListening();
3382
+ await retrying(() => request("Setting What to Test", "POST", "/v1/betaBuildLocalizations", { data: {
3383
+ type: "betaBuildLocalizations",
3384
+ attributes: {
3385
+ locale: WHAT_TO_TEST_LOCALE,
3386
+ whatsNew
3387
+ },
3388
+ relationships: { build: { data: {
3389
+ type: "builds",
3390
+ id: buildId
3391
+ } } }
3392
+ } }));
3393
+ } catch (error) {
3394
+ if (!(error instanceof AppStoreConnectError) || error.status !== 409) throw error;
3395
+ const { data } = await retrying(() => request("Reading What to Test", "GET", `/v1/builds/${buildId}/betaBuildLocalizations?${new URLSearchParams({
3396
+ "fields[betaBuildLocalizations]": "locale",
3397
+ limit: "200"
3398
+ })}`));
3399
+ const existing = data.find(({ attributes }) => attributes?.locale === WHAT_TO_TEST_LOCALE);
3400
+ if (!existing) throw error;
3401
+ await retrying(() => request("Setting What to Test", "PATCH", `/v1/betaBuildLocalizations/${existing.id}`, { data: {
3402
+ type: "betaBuildLocalizations",
3403
+ id: existing.id,
3404
+ attributes: { whatsNew }
3405
+ } }));
2495
3406
  }
2496
3407
  };
3408
+ /**
3409
+ * What App Store Connect says of a build a run recorded as uploaded, which a
3410
+ * later run reuses: its page, and its state and expiry, or a null status when
3411
+ * it no longer lists the build.
3412
+ */
3413
+ const readTestFlightBuildStatus = async ({ bundleId, shortVersion, bundleVersion, apiKey, fetch = globalThis.fetch }) => {
3414
+ const privateKey = await readPrivateKey(apiKey.keyPath);
3415
+ const request = createAppStoreConnectRequest({
3416
+ apiKey,
3417
+ privateKey,
3418
+ fetch
3419
+ });
3420
+ const { app, testFlightUrl } = await findApp(request, bundleId);
3421
+ return {
3422
+ testFlightUrl,
3423
+ status: await readBuildStatus(request, {
3424
+ appId: app.id,
3425
+ shortVersion,
3426
+ bundleVersion
3427
+ })
3428
+ };
3429
+ };
2497
3430
  //#endregion
2498
- //#region src/utils/readBuiltApp.ts
2499
- const readInfoValue = async (infoPlist, key) => {
3431
+ //#region src/utils/sandboxInfoPlist.ts
3432
+ const CAMERA_USAGE = "Scans the QR code of a preview to open it in this build.";
3433
+ const LOCAL_NETWORK_USAGE = "Connects to the dev server you choose on this network.";
3434
+ const ATS_KEY = "NSAppTransportSecurity";
3435
+ const ATS_LOCAL_NETWORKING_KEY = "NSAllowsLocalNetworking";
3436
+ /** A refusal the command prints as it is: the build ran as it should. */
3437
+ const refusal = (message) => new _hot_updater_cli_tools.BuildFailedError(message, {
3438
+ logPath: null,
3439
+ summary: [],
3440
+ hint: message
3441
+ });
3442
+ const plutil = (args) => (0, execa.execa)("plutil", args);
3443
+ const readValue = async (plist, key) => {
2500
3444
  const { stdout, exitCode } = await (0, execa.execa)("plutil", [
2501
3445
  "-extract",
2502
3446
  key,
2503
3447
  "raw",
2504
3448
  "-o",
2505
3449
  "-",
2506
- infoPlist
3450
+ plist
2507
3451
  ], { reject: false });
2508
3452
  return exitCode === 0 && stdout.trim() ? stdout.trim() : null;
2509
3453
  };
3454
+ const setString = (plist, key, value) => plutil([
3455
+ "-replace",
3456
+ key,
3457
+ "-string",
3458
+ value,
3459
+ plist
3460
+ ]);
3461
+ /** The app's own URL types, or null when it has none. */
3462
+ const readUrlTypes = async (plist) => {
3463
+ const { stdout, exitCode } = await (0, execa.execa)("plutil", [
3464
+ "-extract",
3465
+ "CFBundleURLTypes",
3466
+ "json",
3467
+ "-o",
3468
+ "-",
3469
+ plist
3470
+ ], { reject: false });
3471
+ return exitCode === 0 ? JSON.parse(stdout) : null;
3472
+ };
3473
+ const isSandboxUrlType = (type) => type?.CFBundleURLName === _hot_updater_protocol_native_artifact.SANDBOX_URL_TYPE_NAME;
2510
3474
  /**
2511
- * What the built `.app` reports at runtime, from its Info.plist: the
2512
- * `CFBundleShortVersionString`, `CFBundleVersion` (the build number) and
2513
- * `HOT_UPDATER_CHANNEL` the build settings,
2514
- * an `xcconfig` and `extraParams` expanded.
3475
+ * Appends a URL type with the sandbox's scheme to the app's own, or, in an
3476
+ * app an earlier patch made a sandbox app, replaces the one that patch added.
2515
3477
  */
2516
- const readBuiltApp = async (appPath) => {
2517
- const infoPlist = path.default.join(appPath, "Info.plist");
2518
- const [appVersion, channel, buildNumber] = await Promise.all([
2519
- readInfoValue(infoPlist, "CFBundleShortVersionString"),
2520
- readInfoValue(infoPlist, "HOT_UPDATER_CHANNEL"),
2521
- readInfoValue(infoPlist, "CFBundleVersion")
3478
+ const addUrlScheme = async (plist, urlScheme, existing, patchedBefore) => {
3479
+ const urlType = JSON.stringify({
3480
+ CFBundleURLName: _hot_updater_protocol_native_artifact.SANDBOX_URL_TYPE_NAME,
3481
+ CFBundleURLSchemes: [urlScheme]
3482
+ });
3483
+ const patched = patchedBefore ? existing?.findIndex(isSandboxUrlType) ?? -1 : -1;
3484
+ if (patched !== -1) {
3485
+ await plutil([
3486
+ "-remove",
3487
+ `CFBundleURLTypes.${patched}`,
3488
+ plist
3489
+ ]);
3490
+ await plutil([
3491
+ "-insert",
3492
+ `CFBundleURLTypes.${patched}`,
3493
+ "-json",
3494
+ urlType,
3495
+ plist
3496
+ ]);
3497
+ return;
3498
+ }
3499
+ if (existing === null) {
3500
+ await plutil([
3501
+ "-insert",
3502
+ "CFBundleURLTypes",
3503
+ "-json",
3504
+ `[${urlType}]`,
3505
+ plist
3506
+ ]);
3507
+ return;
3508
+ }
3509
+ await plutil([
3510
+ "-insert",
3511
+ `CFBundleURLTypes.${existing.length}`,
3512
+ "-json",
3513
+ urlType,
3514
+ plist
3515
+ ]);
3516
+ };
3517
+ /** The schemes a URL type lists. */
3518
+ const schemesOf = (type) => {
3519
+ const schemes = type?.CFBundleURLSchemes;
3520
+ return Array.isArray(schemes) ? schemes : [];
3521
+ };
3522
+ /** Whether URL types list `urlScheme`, as iOS compares schemes: ignoring case. */
3523
+ const registersUrlScheme = (urlTypes, urlScheme) => urlTypes.some((type) => {
3524
+ const schemes = type?.CFBundleURLSchemes;
3525
+ return Array.isArray(schemes) && schemes.some((scheme) => typeof scheme === "string" && scheme.toLowerCase() === urlScheme.toLowerCase());
3526
+ });
3527
+ const hasKey = async (plist, key) => {
3528
+ const { exitCode } = await (0, execa.execa)("plutil", [
3529
+ "-extract",
3530
+ key,
3531
+ "xml1",
3532
+ "-o",
3533
+ "-",
3534
+ plist
3535
+ ], { reject: false });
3536
+ return exitCode === 0;
3537
+ };
3538
+ /**
3539
+ * What the sandbox's screen asks the system for: the camera for its QR scanner,
3540
+ * and the local network for a dev server. A value the app already set stays, and
3541
+ * nested App Transport Security entries stay beside the one this adds.
3542
+ */
3543
+ const addSandboxPermissions = async (plist) => {
3544
+ for (const [key, value] of [["NSCameraUsageDescription", CAMERA_USAGE], ["NSLocalNetworkUsageDescription", LOCAL_NETWORK_USAGE]]) if (!await hasKey(plist, key)) await plutil([
3545
+ "-insert",
3546
+ key,
3547
+ "-string",
3548
+ value,
3549
+ plist
3550
+ ]);
3551
+ if (!await hasKey(plist, ATS_KEY)) await plutil([
3552
+ "-insert",
3553
+ ATS_KEY,
3554
+ "-json",
3555
+ `{"${ATS_LOCAL_NETWORKING_KEY}":true}`,
3556
+ plist
3557
+ ]);
3558
+ else if (!await hasKey(plist, `${ATS_KEY}.${ATS_LOCAL_NETWORKING_KEY}`)) await plutil([
3559
+ "-insert",
3560
+ `${ATS_KEY}.${ATS_LOCAL_NETWORKING_KEY}`,
3561
+ "-bool",
3562
+ "true",
3563
+ plist
3564
+ ]);
3565
+ };
3566
+ /**
3567
+ * The app's dedicated URL scheme and the sandbox's key: its channel stays the
3568
+ * project's, as any build's does. The
3569
+ * URL scheme, unless the scheme sets one, and App Store Connect's app come
3570
+ * from the scheme's `bundleIdentifier`, while Xcode's build settings decide
3571
+ * the app's ID, so an app of another ID stops here, before anything is signed
3572
+ * or uploaded.
3573
+ */
3574
+ const patchAppInfoPlist = async (plist, scheme) => {
3575
+ const built = await readValue(plist, "CFBundleIdentifier");
3576
+ 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.`);
3577
+ const urlScheme = scheme.sandboxUrlScheme ?? (0, _hot_updater_protocol_native_artifact.sandboxUrlSchemeOf)(scheme.bundleIdentifier);
3578
+ const urlTypes = await readUrlTypes(plist);
3579
+ const patchedBefore = await readValue(plist, _hot_updater_protocol_native_artifact.SANDBOX_INFO_PLIST_KEY) === "true";
3580
+ const appUrlTypes = (urlTypes ?? []).filter((type) => !(patchedBefore && isSandboxUrlType(type)));
3581
+ if (appUrlTypes.some(isSandboxUrlType)) throw refusal(`The app has a URL type named ${_hot_updater_protocol_native_artifact.SANDBOX_URL_TYPE_NAME}, the name a sandbox build registers its URL scheme under.\nRename the app's URL type.`);
3582
+ if (patchedBefore) await refuseForeignSandboxUrlTypes(plist, urlTypes ?? [], scheme);
3583
+ if (registersUrlScheme(appUrlTypes, urlScheme)) throw refusal(`The sandbox scheme ${scheme.hotUpdaterSchemeName} registers URL scheme ${urlScheme}, which the app registers itself.\nSet sandbox.urlScheme to a scheme the app doesn't register.`);
3584
+ await plutil([
3585
+ "-replace",
3586
+ _hot_updater_protocol_native_artifact.SANDBOX_INFO_PLIST_KEY,
3587
+ "-bool",
3588
+ "true",
3589
+ plist
3590
+ ]);
3591
+ await addUrlScheme(plist, urlScheme, urlTypes, patchedBefore);
3592
+ await setString(plist, _hot_updater_protocol_native_artifact.SANDBOX_URL_SCHEME_INFO_PLIST_KEY, urlScheme);
3593
+ await addSandboxPermissions(plist);
3594
+ };
3595
+ /**
3596
+ * A key's value as written, or undefined when the plist has no such key:
3597
+ * strings, numbers and booleans as they are, and any other type as itself
3598
+ * named, which no rule takes. `-extract … json` refuses a lone scalar.
3599
+ */
3600
+ const readTyped = async (plist, key) => {
3601
+ const type = await (0, execa.execa)("plutil", [
3602
+ "-type",
3603
+ key,
3604
+ plist
3605
+ ], { reject: false });
3606
+ if (type.exitCode !== 0) return void 0;
3607
+ const { stdout } = await (0, execa.execa)("plutil", [
3608
+ "-extract",
3609
+ key,
3610
+ "raw",
3611
+ "-o",
3612
+ "-",
3613
+ plist
3614
+ ], {
3615
+ reject: false,
3616
+ stripFinalNewline: false
3617
+ });
3618
+ const raw = stdout.endsWith("\n") ? stdout.slice(0, -1) : stdout;
3619
+ switch (type.stdout.trim()) {
3620
+ case "string": return raw;
3621
+ case "integer":
3622
+ case "float": return Number(raw);
3623
+ case "bool": return raw === "true";
3624
+ default: return `<${type.stdout.trim()}>`;
3625
+ }
3626
+ };
3627
+ /**
3628
+ * Refuses, in an app an earlier patch made a sandbox app, what replacing its
3629
+ * URL type of the sandbox's name could break: by `recordedSandboxUrlScheme`'s
3630
+ * rule, the one URL type of the name must hold the one scheme the patch
3631
+ * recorded alone. A prerelease's patch recorded none, and registered one with
3632
+ * the derived scheme's prefix.
3633
+ */
3634
+ const refuseForeignSandboxUrlTypes = async (plist, urlTypes, scheme) => {
3635
+ const named = urlTypes.filter(isSandboxUrlType);
3636
+ const value = await readTyped(plist, _hot_updater_protocol_native_artifact.SANDBOX_URL_SCHEME_INFO_PLIST_KEY);
3637
+ const recorded = (0, _hot_updater_protocol_native_artifact.recordedSandboxUrlScheme)(value, named);
3638
+ if (typeof recorded === "string") return;
3639
+ const schemes = named.flatMap(schemesOf);
3640
+ if (recorded === void 0) {
3641
+ const only = named.length === 1 && schemes.length === 1 ? schemes[0] : null;
3642
+ if (typeof only === "string" && (0, _hot_updater_protocol_native_artifact.isSandboxUrlScheme)(only)) return;
3643
+ } else if (!(0, _hot_updater_protocol_native_artifact.isRecordedUrlSchemeSyntax)(value)) throw refusal(`The app's Info.plist records sandbox URL scheme ${JSON.stringify(value)} in ${_hot_updater_protocol_native_artifact.SANDBOX_URL_SCHEME_INFO_PLIST_KEY}, which isn't a URL scheme.\nBuild the app again: a new build records none.`);
3644
+ const keep = (0, _hot_updater_protocol_native_artifact.isRecordedUrlSchemeSyntax)(value) ? value : (0, _hot_updater_protocol_native_artifact.sandboxUrlSchemeOf)(scheme.bundleIdentifier);
3645
+ const holds = schemes.map(String).join(", ") || "no scheme";
3646
+ const found = named.length === 1 ? `The app's ${_hot_updater_protocol_native_artifact.SANDBOX_URL_TYPE_NAME} URL type holds ${holds}.` : `The app has ${named.length} ${_hot_updater_protocol_native_artifact.SANDBOX_URL_TYPE_NAME} URL types${named.length === 0 ? "" : `, holding ${holds}`}.`;
3647
+ throw refusal(`${found}\nKeep exactly one ${_hot_updater_protocol_native_artifact.SANDBOX_URL_TYPE_NAME} URL type, holding only ${keep}, and move the rest to a URL type of the app's own.`);
3648
+ };
3649
+ /** The Info.plist of each app extension inside an `.app`. */
3650
+ const extensionInfoPlists = (appPath) => ["PlugIns", "Extensions"].flatMap((directory) => {
3651
+ const extensions = path.default.join(appPath, directory);
3652
+ if (!fs.default.existsSync(extensions)) return [];
3653
+ return fs.default.readdirSync(extensions).filter((name) => name.endsWith(".appex")).map((name) => path.default.join(extensions, name, "Info.plist"));
3654
+ });
3655
+ /**
3656
+ * Makes the archived app a sandbox app before `-exportArchive`, which signs
3657
+ * what it finds, so no project file changes: its URL scheme and key, and from App Store Connect, the version a closed train needs and
3658
+ * the next build number, in its extensions too, which must match it.
3659
+ */
3660
+ const patchSandboxArchive = async ({ archivePath, appPath, schemeConfig, plan }) => {
3661
+ const appPlist = path.default.join(appPath, "Info.plist");
3662
+ await patchAppInfoPlist(appPlist, schemeConfig);
3663
+ const train = plan?.train;
3664
+ if (!train) return;
3665
+ const version = await readValue(appPlist, "CFBundleShortVersionString");
3666
+ const buildNumber = await readValue(appPlist, "CFBundleVersion");
3667
+ const raised = version === null ? void 0 : sandboxVersionDecision({
3668
+ version,
3669
+ train,
3670
+ updateStrategy: plan.updateStrategy
3671
+ });
3672
+ if (raised?.kind === "refuse") throw refusal(raised.message);
3673
+ const newVersion = raised?.kind === "raise" ? raised.version : null;
3674
+ const newBuildNumber = nextBuildNumber(buildNumber, train.highestBuildNumber);
3675
+ const bundles = [appPlist, ...extensionInfoPlists(appPath)];
3676
+ const archivePlist = path.default.join(archivePath, "Info.plist");
3677
+ const properties = "ApplicationProperties";
3678
+ if (newVersion !== null) {
3679
+ for (const plist of bundles) await setString(plist, "CFBundleShortVersionString", newVersion);
3680
+ await setString(archivePlist, `${properties}.CFBundleShortVersionString`, newVersion);
3681
+ _hot_updater_cli_tools.p.log.info(`Sandbox version ${newVersion}: App Store Connect closed ${version}.`);
3682
+ }
3683
+ if (newBuildNumber !== null) {
3684
+ for (const plist of bundles) await setString(plist, "CFBundleVersion", newBuildNumber);
3685
+ await setString(archivePlist, `${properties}.CFBundleVersion`, newBuildNumber);
3686
+ }
3687
+ };
3688
+ /**
3689
+ * The build number to set over `current`: the one after App Store Connect's
3690
+ * highest, or null to keep `current`, already higher, or one that isn't an
3691
+ * integer such as `1.2.3`.
3692
+ */
3693
+ const nextBuildNumber = (current, highest) => {
3694
+ if (highest === null) return null;
3695
+ if (current !== null && !/^\d+$/u.test(current)) return null;
3696
+ if (current !== null && Number(current) > highest) return null;
3697
+ return String(highest + 1);
3698
+ };
3699
+ /**
3700
+ * Makes a built simulator `.app` a sandbox app, and signs it again ad hoc, as
3701
+ * Xcode does for the simulator, since its signature covers the Info.plist.
3702
+ */
3703
+ const patchSandboxSimulatorApp = async (appPath, schemeConfig) => {
3704
+ await patchAppInfoPlist(path.default.join(appPath, "Info.plist"), schemeConfig);
3705
+ await (0, execa.execa)("codesign", [
3706
+ "--force",
3707
+ "--sign",
3708
+ "-",
3709
+ "--timestamp=none",
3710
+ "--preserve-metadata=entitlements",
3711
+ appPath
2522
3712
  ]);
3713
+ };
3714
+ //#endregion
3715
+ //#region src/utils/savedAdHocProfiles.ts
3716
+ /**
3717
+ * Where Xcode and the system keep the provisioning profiles a Mac has saved:
3718
+ * older Xcode in `MobileDevice`, Xcode 16 and later in its `UserData`.
3719
+ */
3720
+ const provisioningProfileDirs = (home = os.default.homedir()) => [path.default.join(home, "Library", "MobileDevice", "Provisioning Profiles"), path.default.join(home, "Library", "Developer", "Xcode", "UserData", "Provisioning Profiles")];
3721
+ const PROFILE_FILE = /\.(?:mobileprovision|provisionprofile)$/u;
3722
+ /**
3723
+ * Deletes the ad hoc profiles Xcode made and saved on this Mac for one app's
3724
+ * bundle IDs in one team, so its next export asks Apple for a new one, which
3725
+ * lists every device the account has enabled now. A profile goes only when all
3726
+ * of these hold: Xcode manages it (`IsXcodeManaged`), it is an ad hoc profile,
3727
+ * its team is `teamId`, and its `application-identifier` is `<teamId>.<one of
3728
+ * bundleIds>`. A manual or development profile, another team's, and another
3729
+ * app's always stay. A file it can't read stays too.
3730
+ */
3731
+ const removeSavedAdHocProfiles = async ({ teamId, bundleIds, dirs = provisioningProfileDirs() }) => {
3732
+ const applicationIds = new Set(bundleIds.map((bundleId) => `${teamId}.${bundleId}`));
3733
+ const removed = [];
3734
+ const failed = [];
3735
+ for (const dir of dirs) {
3736
+ const names = await fs.default.promises.readdir(dir).catch(() => []);
3737
+ for (const name of names) {
3738
+ if (!PROFILE_FILE.test(name)) continue;
3739
+ const file = path.default.join(dir, name);
3740
+ let profile;
3741
+ try {
3742
+ profile = (0, _hot_updater_protocol_native_artifact.readProvisioningProfile)(await fs.default.promises.readFile(file));
3743
+ } catch {
3744
+ continue;
3745
+ }
3746
+ if (!profile.xcodeManaged || profile.distribution !== "ad-hoc" || profile.teamId !== teamId || profile.applicationIdentifier === null || !applicationIds.has(profile.applicationIdentifier)) continue;
3747
+ try {
3748
+ await fs.default.promises.rm(file);
3749
+ removed.push(profile.uuid ?? name);
3750
+ } catch (error) {
3751
+ failed.push({
3752
+ file,
3753
+ reason: error instanceof Error ? error.message : String(error)
3754
+ });
3755
+ }
3756
+ }
3757
+ }
2523
3758
  return {
2524
- appVersion,
2525
- channel,
2526
- buildNumber
3759
+ removed,
3760
+ failed
2527
3761
  };
2528
3762
  };
2529
3763
  //#endregion
@@ -2537,7 +3771,7 @@ const readBuiltApp = async (appPath) => {
2537
3771
  * once the caller has copied it out. A failed build removes it, and every
2538
3772
  * other directory the build used, itself.
2539
3773
  */
2540
- const buildIos = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials }) => {
3774
+ const buildIos = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials, sandbox, logHeader = [], expectedDevices, channel }) => {
2541
3775
  await assertXcodebuildExist();
2542
3776
  if (schemeConfig.simulator && schemeConfig.destination.length) {
2543
3777
  _hot_updater_cli_tools.p.log.error("The scheme option 'simulator' is not compatible with the 'destination' option.");
@@ -2550,7 +3784,11 @@ const buildIos = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools
2550
3784
  schemeConfig,
2551
3785
  minBundleId,
2552
3786
  credentials,
2553
- buildDirectory
3787
+ sandbox,
3788
+ buildDirectory,
3789
+ logHeader,
3790
+ expectedDevices,
3791
+ channel
2554
3792
  }),
2555
3793
  dispose: () => removeTmpDir(buildDirectory)
2556
3794
  };
@@ -2559,27 +3797,33 @@ const buildIos = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools
2559
3797
  throw error;
2560
3798
  }
2561
3799
  };
2562
- const buildInto = async ({ schemeConfig, minBundleId, credentials, buildDirectory }) => {
3800
+ const buildInto = async ({ schemeConfig, minBundleId, credentials, sandbox, buildDirectory, logHeader, expectedDevices, channel }) => {
2563
3801
  const iosProjectRoot = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "ios");
2564
3802
  if (schemeConfig.simulator) {
2565
3803
  const appDir = path.default.join(buildDirectory, "app");
2566
3804
  await fs.default.promises.mkdir(appDir, { recursive: true });
2567
- const { appPath } = await buildXcodeProject({
3805
+ const { appPath, logFilePath } = await buildXcodeProject({
2568
3806
  sourceDir: iosProjectRoot,
2569
3807
  outputDirectory: appDir,
2570
3808
  logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build`,
3809
+ header: logHeader,
2571
3810
  platform: schemeConfig.platform,
2572
3811
  xcodeScheme: schemeConfig.scheme,
2573
3812
  configuration: schemeConfig.configuration,
2574
3813
  deviceType: "simulator",
2575
3814
  installPods: schemeConfig.installPods,
3815
+ xcconfig: schemeConfig.xcconfig,
2576
3816
  extraParams: schemeConfig.extraParams,
2577
3817
  useGenericDestination: true,
2578
- minBundleId
3818
+ minBundleId,
3819
+ sandbox: schemeConfig.sandbox
2579
3820
  });
3821
+ if (schemeConfig.sandbox) await patchSandboxSimulatorApp(appPath, schemeConfig);
3822
+ if (channel !== void 0) await stampAppChannel(appPath, channel, { signAdHoc: true });
2580
3823
  return {
2581
3824
  buildDirectory,
2582
3825
  buildArtifactPath: appPath,
3826
+ logFilePath,
2583
3827
  builtApp: await readBuiltApp(appPath)
2584
3828
  };
2585
3829
  } else {
@@ -2590,18 +3834,28 @@ const buildInto = async ({ schemeConfig, minBundleId, credentials, buildDirector
2590
3834
  if (!signing) return archiveAndExport({
2591
3835
  schemeConfig,
2592
3836
  minBundleId,
2593
- buildDirectory
3837
+ sandbox,
3838
+ buildDirectory,
3839
+ logHeader,
3840
+ expectedDevices,
3841
+ channel
2594
3842
  });
2595
- const appStoreConnect = await exportsForAppStoreConnect(schemeConfig);
2596
- if ((0, _hot_updater_cli_tools.isCI)() && !appStoreConnect) _hot_updater_cli_tools.p.log.info("Signing in the runner's own keychains (not an App Store Connect export).");
3843
+ const registeredDevices = await exportsForRegisteredDevices(schemeConfig);
3844
+ const ownKeychain = registeredDevices || await exportsForAppStoreConnect(schemeConfig);
3845
+ 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).");
2597
3846
  return withSigningKeychain({
2598
- enabled: (0, _hot_updater_cli_tools.isCI)() && appStoreConnect,
3847
+ enabled: (0, _hot_updater_cli_tools.isCI)() && ownKeychain,
3848
+ keepDistribution: registeredDevices,
2599
3849
  apiKey: signing.apiKey,
2600
3850
  run: () => archiveAndExport({
2601
3851
  schemeConfig,
2602
3852
  minBundleId,
3853
+ sandbox,
2603
3854
  buildDirectory,
2604
- authenticationArgs: signing.authenticationArgs
3855
+ logHeader,
3856
+ authenticationArgs: signing.authenticationArgs,
3857
+ expectedDevices,
3858
+ channel
2605
3859
  })
2606
3860
  });
2607
3861
  }
@@ -2610,12 +3864,13 @@ const buildInto = async ({ schemeConfig, minBundleId, credentials, buildDirector
2610
3864
  * Archives a device build and exports its `.ipa`, or returns the
2611
3865
  * `.xcarchive` of a scheme it cannot export.
2612
3866
  */
2613
- const archiveAndExport = async ({ schemeConfig, minBundleId, buildDirectory, authenticationArgs }) => {
3867
+ const archiveAndExport = async ({ schemeConfig, minBundleId, sandbox, buildDirectory, logHeader, authenticationArgs, expectedDevices, channel }) => {
3868
+ if (channel !== void 0 && !schemeConfig.exportOptionsPlist && !authenticationArgs) throw new Error(`The scheme ${schemeConfig.hotUpdaterSchemeName} archives without exporting, so its app can't embed a --channel and stay signed.\nSet exportOptionsPlist or signing.ascApiKey on the scheme.`);
2614
3869
  const iosProjectRoot = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "ios");
2615
3870
  const archiveDir = path.default.join(buildDirectory, "archive");
2616
3871
  const exportDir = path.default.join(buildDirectory, "export");
2617
3872
  await fs.default.promises.mkdir(archiveDir, { recursive: true });
2618
- const { archivePath } = await archiveXcodeProject({
3873
+ const { archivePath, logFilePath } = await archiveXcodeProject({
2619
3874
  archiveDirectory: archiveDir,
2620
3875
  authenticationArgs,
2621
3876
  minBundleId,
@@ -2627,43 +3882,109 @@ const archiveAndExport = async ({ schemeConfig, minBundleId, buildDirectory, aut
2627
3882
  extraParams: schemeConfig.extraParams,
2628
3883
  configuration: schemeConfig.configuration,
2629
3884
  installPods: schemeConfig.installPods,
2630
- logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build-archive`
3885
+ logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build`,
3886
+ header: logHeader,
3887
+ sandbox: schemeConfig.sandbox
2631
3888
  });
2632
3889
  const appFromArchive = extractAppFromXcarchive(archivePath);
3890
+ if (schemeConfig.sandbox) {
3891
+ if (!appFromArchive) throw new Error(`The archive ${archivePath} has no app to patch.`);
3892
+ await patchSandboxArchive({
3893
+ archivePath,
3894
+ appPath: appFromArchive,
3895
+ schemeConfig,
3896
+ plan: sandbox
3897
+ });
3898
+ }
3899
+ if (channel !== void 0) {
3900
+ if (!appFromArchive) throw new Error(`The archive ${archivePath} has no app to stamp.`);
3901
+ await stampAppChannel(appFromArchive, channel);
3902
+ }
2633
3903
  const archivedAppPath = appFromArchive ? path.default.join(archiveDir, path.default.basename(appFromArchive)) : void 0;
2634
3904
  if (appFromArchive && archivedAppPath) await fs.default.promises.cp(appFromArchive, archivedAppPath, { recursive: true });
2635
3905
  if (!schemeConfig.exportOptionsPlist && !authenticationArgs) return {
2636
3906
  buildDirectory,
2637
3907
  buildArtifactPath: archivePath,
3908
+ logFilePath,
2638
3909
  builtApp: archivedAppPath ? await readBuiltApp(archivedAppPath) : void 0
2639
3910
  };
2640
- await fs.default.promises.mkdir(exportDir, { recursive: true });
2641
- const exportArchive = (exportOptionsPlist) => exportXcodeArchive({
2642
- archivePath,
2643
- exportPath: exportDir,
2644
- authenticationArgs,
2645
- exportExtraParams: schemeConfig.exportExtraParams,
2646
- exportOptionsPlist,
2647
- sourceDir: iosProjectRoot,
2648
- logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build-export`
2649
- });
2650
- if (schemeConfig.exportOptionsPlist) await exportArchive(schemeConfig.exportOptionsPlist);
3911
+ let exportMethod;
3912
+ const runExport = async (exportOptionsPlist) => {
3913
+ exportMethod = await readExportMethod(exportOptionsPlist).catch(() => "") || void 0;
3914
+ await exportXcodeArchive({
3915
+ archivePath,
3916
+ exportPath: exportDir,
3917
+ authenticationArgs,
3918
+ exportExtraParams: schemeConfig.exportExtraParams,
3919
+ exportOptionsPlist,
3920
+ sourceDir: iosProjectRoot,
3921
+ logPrefix: `ios-${schemeConfig.hotUpdaterSchemeName}-build`,
3922
+ logFilePath: logFilePath ?? void 0,
3923
+ title: schemeConfig.scheme
3924
+ });
3925
+ };
3926
+ const exportOnce = async (exportOptionsPlist) => {
3927
+ await fs.default.promises.rm(exportDir, {
3928
+ recursive: true,
3929
+ force: true
3930
+ });
3931
+ await fs.default.promises.mkdir(exportDir, { recursive: true });
3932
+ try {
3933
+ await runExport(exportOptionsPlist);
3934
+ } finally {
3935
+ await keepOnlyIpas(exportDir);
3936
+ }
3937
+ };
3938
+ const exportArchive = async (exportOptionsPlist) => {
3939
+ await exportOnce(exportOptionsPlist);
3940
+ if (!expectedDevices?.length) return;
3941
+ const ipaFile = findIpa(exportDir);
3942
+ if (ipaFile === void 0) return;
3943
+ const signed = await readIpaSigning(path.default.join(exportDir, ipaFile));
3944
+ if (signed === null || signed.teamId === null) return;
3945
+ const missing = expectedDevices.filter((udid) => !signed.devices.includes(udid.toLowerCase()));
3946
+ if (missing.length === 0 || signed.distribution !== "ad-hoc") return;
3947
+ const { removed, failed } = await removeSavedAdHocProfiles({
3948
+ teamId: signed.teamId,
3949
+ bundleIds: signed.profileBundleIds
3950
+ });
3951
+ for (const { file, reason } of failed) _hot_updater_cli_tools.p.log.warn(`Couldn't delete the saved profile ${file}: ${reason}`);
3952
+ if (removed.length === 0) return;
3953
+ _hot_updater_cli_tools.p.log.info(`Exporting again · a saved ad hoc profile lacked ${missing.length} approved ${missing.length === 1 ? "device" : "devices"}`);
3954
+ await exportOnce(exportOptionsPlist);
3955
+ };
3956
+ const { exportOptionsPlist } = schemeConfig;
3957
+ if (exportOptionsPlist && !schemeConfig.sandbox) await exportArchive(exportOptionsPlist);
2651
3958
  else {
2652
3959
  const exportOptionsDir = await createRandomTmpDir();
2653
3960
  try {
2654
- await exportArchive(await writeAppStoreConnectExportOptions(exportOptionsDir));
3961
+ await exportArchive(exportOptionsPlist ? await resolveSandboxExportOptions(schemeConfig.hotUpdaterSchemeName, exportOptionsPlist, exportOptionsDir) : await writeAppStoreConnectExportOptions(exportOptionsDir, { internalTestingOnly: schemeConfig.sandbox }));
2655
3962
  } finally {
2656
3963
  await removeTmpDir(exportOptionsDir);
2657
3964
  }
2658
3965
  }
2659
- const ipaFile = fs.default.readdirSync(exportDir).find((file) => file.endsWith(".ipa"));
3966
+ const ipaFile = findIpa(exportDir);
2660
3967
  if (!ipaFile) throw new Error("IPA file not found after export");
2661
3968
  return {
2662
3969
  buildDirectory,
2663
3970
  buildArtifactPath: path.default.join(exportDir, ipaFile),
3971
+ logFilePath,
3972
+ ...exportMethod === void 0 ? {} : { exportMethod },
2664
3973
  builtApp: archivedAppPath ? await readBuiltApp(archivedAppPath) : void 0
2665
3974
  };
2666
3975
  };
3976
+ const findIpa = (exportDir) => fs.default.readdirSync(exportDir).find((file) => file.endsWith(".ipa"));
3977
+ /**
3978
+ * Leaves only the `.ipa` in an export's folder. Xcode writes `Packaging.log`
3979
+ * beside it, which holds the API key's bearer token for its 20 minutes, and the
3980
+ * build's output and its cache copy the whole build directory into the project.
3981
+ */
3982
+ const keepOnlyIpas = async (exportDir) => {
3983
+ for (const entry of await fs.default.promises.readdir(exportDir)) if (!entry.endsWith(".ipa")) await fs.default.promises.rm(path.default.join(exportDir, entry), {
3984
+ recursive: true,
3985
+ force: true
3986
+ });
3987
+ };
2667
3988
  const extractAppFromXcarchive = (archivePath) => {
2668
3989
  const productsPath = path.default.join(archivePath, "Products", "Applications");
2669
3990
  if (!fs.default.existsSync(productsPath)) return;
@@ -2672,28 +3993,6 @@ const extractAppFromXcarchive = (archivePath) => {
2672
3993
  _hot_updater_cli_tools.p.log.warn("Failed to extract .app from xcarchive");
2673
3994
  };
2674
3995
  //#endregion
2675
- //#region src/utils/enrichNativeBuildIosScheme.ts
2676
- const resolveExportOptionsPlist = (exportOptionsPlist) => {
2677
- const resolvedExportOptionsPlist = exportOptionsPlist ? path.default.isAbsolute(exportOptionsPlist) ? exportOptionsPlist : path.default.resolve((0, _hot_updater_cli_tools.getCwd)(), exportOptionsPlist) : void 0;
2678
- if (resolvedExportOptionsPlist && !fs.default.existsSync(resolvedExportOptionsPlist)) {
2679
- _hot_updater_cli_tools.p.log.error(`exportOptionsPlist doesn't exist in ${resolvedExportOptionsPlist}`);
2680
- process.exit(1);
2681
- }
2682
- return resolvedExportOptionsPlist;
2683
- };
2684
- const enrichNativeBuildIosScheme = async ({ scheme, hotUpdaterSchemeName }) => {
2685
- return {
2686
- platform: "ios",
2687
- installPods: false,
2688
- configuration: "Release",
2689
- destination: [],
2690
- simulator: false,
2691
- ...scheme,
2692
- exportOptionsPlist: resolveExportOptionsPlist(scheme.exportOptionsPlist),
2693
- hotUpdaterSchemeName
2694
- };
2695
- };
2696
- //#endregion
2697
3996
  //#region src/utils/extractBuiltInBundle.ts
2698
3997
  /** The file React Native's Xcode build phase writes into the `.app`. */
2699
3998
  const BUILT_IN_BUNDLE = "main.jsbundle";
@@ -2749,16 +4048,138 @@ const archiveAppBundle = async ({ appPath, outputPath }) => {
2749
4048
  ]);
2750
4049
  };
2751
4050
  //#endregion
4051
+ //#region src/simulator.ts
4052
+ const simctl = async (args) => {
4053
+ try {
4054
+ return (await (0, execa.execa)("xcrun", ["simctl", ...args])).stdout;
4055
+ } catch (error) {
4056
+ const { code, stderr, shortMessage } = error;
4057
+ if (code === "ENOENT") throw new Error("The iOS Simulator needs Xcode on a Mac.\nInstall Xcode, then run this again.");
4058
+ throw new Error(stderr?.trim() || shortMessage || String(error));
4059
+ }
4060
+ };
4061
+ /** Every simulator on this Mac, booted or not. */
4062
+ const listSimulators = async () => {
4063
+ const { devices } = JSON.parse(await simctl([
4064
+ "list",
4065
+ "devices",
4066
+ "--json"
4067
+ ]));
4068
+ return Object.values(devices).flat().map(({ udid, name, state }) => ({
4069
+ udid,
4070
+ name,
4071
+ state
4072
+ }));
4073
+ };
4074
+ /**
4075
+ * The simulator to install on: `udid`, or else the only booted one, by its
4076
+ * UDID. `simctl`'s own `booted` alias picks one of several by itself.
4077
+ */
4078
+ const selectSimulator = (simulators, udid) => {
4079
+ if (udid !== void 0) {
4080
+ const simulator = simulators.find((candidate) => candidate.udid === udid);
4081
+ if (simulator === void 0) throw new Error(`No iOS Simulator has the UDID ${udid}.\nList them: xcrun simctl list devices`);
4082
+ if (simulator.state !== "Booted") throw new Error(`${simulator.name} isn't booted.\nBoot it: xcrun simctl boot ${udid}`);
4083
+ return simulator;
4084
+ }
4085
+ const booted = simulators.filter(({ state }) => state === "Booted");
4086
+ const [only] = booted;
4087
+ if (only === void 0) throw new Error("No iOS Simulator is booted.\nBoot one: open -a Simulator");
4088
+ if (booted.length > 1) throw new Error([
4089
+ `${booted.length} iOS Simulators are booted:`,
4090
+ ...booted.map(({ udid, name }) => ` ${udid} ${name}`),
4091
+ "Pick one with --simulator <udid>."
4092
+ ].join("\n"));
4093
+ return only;
4094
+ };
4095
+ /**
4096
+ * Unpacks a simulator build's `.app.zip` into `outputPath`, and returns the
4097
+ * `.app` in it.
4098
+ */
4099
+ const extractSimulatorApp = async ({ archivePath, outputPath }) => {
4100
+ await extractAppBundle({
4101
+ archivePath,
4102
+ outputPath
4103
+ });
4104
+ const app = (await fs.default.promises.readdir(outputPath)).find((entry) => entry.endsWith(".app"));
4105
+ if (app === void 0) throw new Error(`${path.default.basename(archivePath)} holds no .app.`);
4106
+ return path.default.join(outputPath, app);
4107
+ };
4108
+ /**
4109
+ * Installs a `.app` on a booted simulator, and opens it: with `url`, through
4110
+ * that URL, which starts the app with it as a scanned link does.
4111
+ */
4112
+ const installOnSimulator = async ({ udid, appPath, appId, url }) => {
4113
+ await simctl([
4114
+ "install",
4115
+ udid,
4116
+ appPath
4117
+ ]);
4118
+ await simctl(url === void 0 ? [
4119
+ "launch",
4120
+ udid,
4121
+ appId
4122
+ ] : [
4123
+ "openurl",
4124
+ udid,
4125
+ url
4126
+ ]);
4127
+ };
4128
+ //#endregion
4129
+ //#region src/utils/enrichNativeBuildIosScheme.ts
4130
+ const resolveExportOptionsPlist = (exportOptionsPlist) => {
4131
+ const resolvedExportOptionsPlist = exportOptionsPlist ? path.default.isAbsolute(exportOptionsPlist) ? exportOptionsPlist : path.default.resolve((0, _hot_updater_cli_tools.getCwd)(), exportOptionsPlist) : void 0;
4132
+ if (resolvedExportOptionsPlist && !fs.default.existsSync(resolvedExportOptionsPlist)) {
4133
+ _hot_updater_cli_tools.p.log.error(`exportOptionsPlist doesn't exist in ${resolvedExportOptionsPlist}`);
4134
+ process.exit(1);
4135
+ }
4136
+ return resolvedExportOptionsPlist;
4137
+ };
4138
+ const enrichNativeBuildIosScheme = async ({ scheme, hotUpdaterSchemeName }) => {
4139
+ return {
4140
+ platform: "ios",
4141
+ installPods: false,
4142
+ configuration: "Release",
4143
+ destination: [],
4144
+ simulator: false,
4145
+ ...scheme,
4146
+ exportOptionsPlist: resolveExportOptionsPlist(scheme.exportOptionsPlist),
4147
+ hotUpdaterSchemeName
4148
+ };
4149
+ };
4150
+ //#endregion
2752
4151
  exports.ASC_INTEGRATIONS_URL = ASC_INTEGRATIONS_URL;
2753
4152
  exports.TestFlightBuildExistsError = TestFlightBuildExistsError;
4153
+ exports.addAscDevices = addAscDevices;
4154
+ exports.applyTestFlightGroup = applyTestFlightGroup;
2754
4155
  exports.archiveAppBundle = archiveAppBundle;
4156
+ exports.assertBuildIsInternalOnly = assertBuildIsInternalOnly;
4157
+ exports.assertIpaIsInternalOnly = assertIpaIsInternalOnly;
4158
+ exports.assertSandboxExportOptions = assertSandboxExportOptions;
2755
4159
  exports.assertTestFlightExportOptions = assertTestFlightExportOptions;
2756
4160
  exports.buildIos = buildIos;
4161
+ exports.distributeTestFlightBuild = distributeTestFlightBuild;
2757
4162
  exports.enrichNativeBuildIosScheme = enrichNativeBuildIosScheme;
4163
+ exports.exportsForAppStoreConnect = exportsForAppStoreConnect;
4164
+ exports.exportsForRegisteredDevices = exportsForRegisteredDevices;
2758
4165
  exports.extractAppBundle = extractAppBundle;
2759
4166
  exports.extractBuiltInBundle = extractBuiltInBundle;
4167
+ exports.extractSimulatorApp = extractSimulatorApp;
4168
+ exports.findAscDevice = findAscDevice;
4169
+ exports.findInternalBetaGroup = findInternalBetaGroup;
2760
4170
  exports.findTestFlightBuild = findTestFlightBuild;
4171
+ exports.installOnSimulator = installOnSimulator;
2761
4172
  exports.installPodsIfNeeded = installPodsIfNeeded;
4173
+ exports.isVersionTrainClosed = isVersionTrainClosed;
2762
4174
  exports.issueAscApiKey = issueAscApiKey;
4175
+ exports.listAscDevices = listAscDevices;
4176
+ exports.listSimulators = listSimulators;
4177
+ exports.prepareSandboxArchive = prepareSandboxArchive;
4178
+ exports.provisioningProfileDirs = provisioningProfileDirs;
4179
+ exports.readIpaHasExportComplianceKey = readIpaHasExportComplianceKey;
4180
+ exports.readTestFlightBuildStatus = readTestFlightBuildStatus;
4181
+ exports.removeSavedAdHocProfiles = removeSavedAdHocProfiles;
2763
4182
  exports.resolveTestFlightUploadKey = resolveTestFlightUploadKey;
4183
+ exports.selectSimulator = selectSimulator;
4184
+ exports.updateAscDevice = updateAscDevice;
2764
4185
  exports.uploadToTestFlight = uploadToTestFlight;