@hot-updater/android-helper 1.2.0-rc.2 → 1.2.0-rc.20

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
@@ -31,125 +31,41 @@ let os = require("os");
31
31
  os = __toESM(os, 1);
32
32
  let jszip = require("jszip");
33
33
  jszip = __toESM(jszip, 1);
34
+ let module$1 = require("module");
35
+ let _hot_updater_protocol_native_artifact = require("@hot-updater/protocol/native-artifact");
36
+ let fast_xml_parser = require("fast-xml-parser");
34
37
  let crypto = require("crypto");
35
38
  crypto = __toESM(crypto, 1);
36
39
  let stream_promises = require("stream/promises");
37
40
  let zlib = require("zlib");
38
- let node_crypto = require("node:crypto");
39
- node_crypto = __toESM(node_crypto, 1);
40
- let node_http = require("node:http");
41
- node_http = __toESM(node_http, 1);
41
+ //#region src/utils/gradlePhase.ts
42
+ /** `> Task :app:compileReleaseKotlin`, with an outcome such as `UP-TO-DATE`. */
43
+ const TASK = /^> Task (:\S+)/;
44
+ const CONFIGURE = /^> Configure project (:\S*)/;
45
+ /**
46
+ * Reads the phase of a Gradle build from its plain console output: the
47
+ * task it runs, after how many it has run, such as
48
+ * `312 tasks · :app:mergeReleaseResources`.
49
+ */
50
+ const createGradlePhaseReader = () => {
51
+ let tasks = 0;
52
+ return (line) => {
53
+ const task = TASK.exec(line)?.[1];
54
+ if (task) {
55
+ tasks += 1;
56
+ return `${tasks} task${tasks === 1 ? "" : "s"} · ${task}`;
57
+ }
58
+ const project = CONFIGURE.exec(line)?.[1];
59
+ if (project) return `Configuring ${project}`;
60
+ if (line.startsWith("Starting a Gradle Daemon")) return "Starting the Gradle daemon";
61
+ if (line.startsWith("Downloading https://services.gradle.org/")) return "Downloading Gradle";
62
+ };
63
+ };
64
+ //#endregion
42
65
  //#region src/utils/createGradleLogger.ts
43
66
  const createGradleLogger = ({ logPrefix }) => new _hot_updater_cli_tools.BuildLogger({
44
67
  logPrefix,
45
- importantLogPatterns: [
46
- "error:",
47
- "Error:",
48
- "ERROR:",
49
- "> Task :",
50
- "BUILD FAILED",
51
- "BUILD SUCCESSFUL",
52
- "FAILURE: Build failed with an exception.",
53
- "* What went wrong:",
54
- "Execution failed for task",
55
- "Could not resolve",
56
- "Failed to",
57
- "Unable to load script",
58
- "Metro encountered an error",
59
- "React Native CLI",
60
- "Android resource compilation failed",
61
- "Duplicate class",
62
- "Program type already present",
63
- "actionable tasks:",
64
- "Deprecated Gradle features were used",
65
- ":app:configureCMake",
66
- ":app:buildCMake",
67
- ":app:compileDebugKotlin",
68
- ":app:compileReleaseKotlin",
69
- ":app:compileDebugJavaWithJavac",
70
- ":app:compileReleaseJavaWithJavac",
71
- ":app:mergeDebugResources",
72
- ":app:mergeReleaseResources",
73
- ":app:processDebugResources",
74
- ":app:processReleaseResources",
75
- ":app:packageDebug",
76
- ":app:packageRelease",
77
- ":app:assembleDebug",
78
- ":app:assembleRelease"
79
- ],
80
- progressStages: [
81
- [
82
- "buildKotlinToolingMetadata",
83
- "generateAutolinkingNewArchitectureFiles",
84
- "generateAutolinkingPackageList",
85
- "generateCodegenSchemaFromJavaScript",
86
- "generateCodegenArtifactsFromSchema",
87
- "generateReactNativeEntryPoint"
88
- ],
89
- [
90
- "createBundleReleaseJsAndAssets",
91
- "bundleReleaseJsAndAssets",
92
- "bundleDebugJsAndAssets"
93
- ],
94
- [
95
- "generateReleaseResValues",
96
- "generateDebugResValues",
97
- "generateReleaseResources",
98
- "generateDebugResources",
99
- "mergeReleaseResources",
100
- "mergeDebugResources"
101
- ],
102
- [
103
- "processReleaseResources",
104
- "processDebugResources",
105
- "processReleaseManifest",
106
- "processDebugManifest",
107
- "processDebugMainManifest",
108
- "parseReleaseLocalResources",
109
- "parseDebugLocalResources"
110
- ],
111
- ["compileReleaseKotlin", "compileDebugKotlin"],
112
- ["compileReleaseJavaWithJavac", "compileDebugJavaWithJavac"],
113
- [
114
- /configureCMake\w+\[/,
115
- /buildCMake\w+\[/,
116
- "mergeReleaseJniLibFolders",
117
- "mergeDebugJniLibFolders",
118
- "mergeReleaseNativeLibs",
119
- "mergeDebugNativeLibs"
120
- ],
121
- [
122
- "desugarReleaseFileDependencies",
123
- "desugarDebugFileDependencies",
124
- "dexBuilderRelease",
125
- "dexBuilderDebug",
126
- "mergeDexRelease",
127
- "mergeExtDexRelease",
128
- "mergeExtDexDebug",
129
- "mergeProjectDexRelease",
130
- "mergeProjectDexDebug",
131
- "mergeLibDexRelease",
132
- "mergeLibDexDebug",
133
- "mergeDebugGlobalSynthetics",
134
- "mergeReleaseGlobalSynthetics",
135
- "transformClassesWithDex"
136
- ],
137
- [
138
- "compressReleaseAssets",
139
- "compressDebugAssets",
140
- "optimizeReleaseResources",
141
- "mergeReleaseAssets",
142
- "mergeDebugAssets"
143
- ],
144
- [
145
- "packageRelease",
146
- "packageDebug",
147
- "assembleRelease",
148
- "assembleDebug"
149
- ],
150
- ["bundleRelease", "bundleDebug"],
151
- ["BUILD SUCCESSFUL", /\d+ actionable tasks:/]
152
- ],
68
+ createPhaseReader: createGradlePhaseReader,
153
69
  failureSummary: {
154
70
  lines: [
155
71
  /^e: /,
@@ -164,6 +80,26 @@ const createGradleLogger = ({ logPrefix }) => new _hot_updater_cli_tools.BuildLo
164
80
  }
165
81
  });
166
82
  //#endregion
83
+ //#region src/utils/formatCommand.ts
84
+ /**
85
+ * A command to print, broken at spaces with ` \` once a line would pass
86
+ * `width`, each continuation indented two spaces, so a terminal never wraps
87
+ * it mid-word and it still pastes as one command.
88
+ */
89
+ const formatCommand = (words, width = 74) => {
90
+ const lines = [];
91
+ let line = "";
92
+ for (const word of words) {
93
+ const next = line ? `${line} ${word}` : word;
94
+ if (line && next.length > width - 2) {
95
+ lines.push(`${line} \\`);
96
+ line = ` ${word}`;
97
+ } else line = next;
98
+ }
99
+ lines.push(line);
100
+ return lines.join("\n");
101
+ };
102
+ //#endregion
167
103
  //#region src/builder/runGradle.ts
168
104
  /** Why Gradle failed, without its command line. */
169
105
  const describeFailure = (error) => {
@@ -183,24 +119,54 @@ function getTaskNames(moduleName, tasks) {
183
119
  * Get gradle wrapper command based on platform
184
120
  */
185
121
  const getGradleWrapper = () => process.platform.startsWith("win") ? "gradlew.bat" : "./gradlew";
122
+ /** A variable a POSIX shell can't name, as the signing environment's are. */
123
+ const isShellName = (name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
124
+ /**
125
+ * The command that runs the wrapper with `env`. The wrapper's `#!/bin/sh` is
126
+ * dash on Debian and Ubuntu, which silently drops a variable whose name isn't
127
+ * a shell name, such as `ORG_GRADLE_PROJECT_android.injected.signing.store.file`:
128
+ * the build then signs with the project's own config. bash keeps them.
129
+ */
130
+ const gradleCommand = (env) => {
131
+ const wrapper = getGradleWrapper();
132
+ return wrapper === "./gradlew" && Object.keys(env ?? {}).some((name) => !isShellName(name)) ? ["bash", [wrapper]] : [wrapper, []];
133
+ };
186
134
  /**
187
135
  * Run gradle build with specified tasks and arguments
188
136
  */
189
- async function runGradle({ tasks, logPrefix, args, env, androidProjectPath, appModuleName }) {
137
+ async function runGradle(args) {
138
+ const logFilePath = await runGradleTasks(args);
139
+ return {
140
+ ...await findBuildDirectory({
141
+ androidProjectPath: args.androidProjectPath,
142
+ moduleName: args.appModuleName,
143
+ tasks: args.tasks
144
+ }),
145
+ logFilePath
146
+ };
147
+ }
148
+ /** Runs tasks that leave no artifact to find, and returns the build log, or null. */
149
+ async function runGradleTasks({ tasks, logPrefix, args, env, androidProjectPath, appModuleName, logHeader = [] }) {
190
150
  const gradleArgs = getTaskNames(appModuleName, tasks);
191
151
  gradleArgs.push("-x", "lint");
192
152
  if (args.extraParams) gradleArgs.push(...args.extraParams);
193
- _hot_updater_cli_tools.p.log.info(`Run Gradle Settings:
194
- Project ${androidProjectPath}
195
- App Module ${appModuleName}
196
- Tasks ${tasks.join(", ")}
197
- Args ${gradleArgs.join(" ")}
198
- `);
199
153
  if ("port" in args && args.port != null) gradleArgs.push(`-PreactNativeDevServerPort=${args.port}`);
200
154
  const logger = createGradleLogger({ logPrefix });
201
- await logger.start();
155
+ await logger.start({
156
+ title: `Building ${tasks.join(", ")}`,
157
+ header: [
158
+ ...logHeader,
159
+ `Project ${path.default.relative((0, _hot_updater_cli_tools.getCwd)(), androidProjectPath) || "."}`,
160
+ `App module ${appModuleName}`,
161
+ `Tasks ${tasks.join(", ")}`,
162
+ `$ ${formatCommand([path.default.basename(getGradleWrapper()), ...gradleArgs])}`,
163
+ ""
164
+ ]
165
+ });
166
+ let logFilePath = null;
202
167
  try {
203
- const gradle = (0, execa.execa)(getGradleWrapper(), gradleArgs, {
168
+ const [command, prefix] = gradleCommand(env);
169
+ const gradle = (0, execa.execa)(command, [...prefix, ...gradleArgs], {
204
170
  cwd: androidProjectPath,
205
171
  env,
206
172
  all: true,
@@ -210,11 +176,13 @@ Args ${gradleArgs.join(" ")}
210
176
  const [gradleResult, loggingResult] = await Promise.allSettled([gradle, outputStream ? logger.processStream(outputStream) : void 0]);
211
177
  if (gradleResult.status === "rejected") throw gradleResult.reason;
212
178
  if (loggingResult.status === "rejected") throw loggingResult.reason;
213
- logger.stop();
179
+ logger.stop(`Built ${tasks.join(", ")}`);
180
+ logFilePath = logger.logFilePath;
214
181
  } catch (e) {
215
182
  logger.writeError(e);
216
- logger.stop("Build failed", false);
217
- throw new _hot_updater_cli_tools.BuildFailedError(`Build failed: ${describeFailure(e)}`, {
183
+ const reason = describeFailure(e);
184
+ logger.stop(`Build failed · ${reason.replace(/\.$/, "")}`, false);
185
+ throw new _hot_updater_cli_tools.BuildFailedError(`Build failed: ${reason}`, {
218
186
  logPath: logger.logPath,
219
187
  summary: logger.failureSummary,
220
188
  cause: e
@@ -222,11 +190,7 @@ Args ${gradleArgs.join(" ")}
222
190
  } finally {
223
191
  await logger.close();
224
192
  }
225
- return findBuildDirectory({
226
- androidProjectPath,
227
- moduleName: appModuleName,
228
- tasks
229
- });
193
+ return logFilePath;
230
194
  }
231
195
  /**
232
196
  * Find the build output directory and artifact path
@@ -257,7 +221,7 @@ async function getBuildOutputFilePath({ aab, appModuleName, buildDirectory, vari
257
221
  const outputFile = `${appModuleName}-${variant}.${aab ? "aab" : "apk"}`;
258
222
  const outputFilePath = path.default.join(buildDirectory, outputFile);
259
223
  if (fs.default.existsSync(outputFilePath)) return outputFilePath;
260
- _hot_updater_cli_tools.p.log.error(`Failed to find the output file for ${outputFilePath}`);
224
+ _hot_updater_cli_tools.p.log.error(`Gradle wrote no ${outputFilePath}.`);
261
225
  process.exit(1);
262
226
  }
263
227
  //#endregion
@@ -277,7 +241,7 @@ const resolveGradleSigningEnv = async ({ schemeConfig, credentials }) => {
277
241
  const reference = schemeConfig.signing?.keystore;
278
242
  if (!reference) return;
279
243
  if (isDebugVariant(schemeConfig.variant)) {
280
- _hot_updater_cli_tools.p.log.info(`${schemeConfig.variant} signs with the debug keystore, so signing.keystore is not used.`);
244
+ _hot_updater_cli_tools.p.log.info(`${schemeConfig.variant} signs with the debug keystore; signing.keystore is unused.`);
281
245
  return;
282
246
  }
283
247
  const keystore = await (credentials ?? (0, _hot_updater_cli_tools.createCredentialResolver)()).resolve({
@@ -430,7 +394,7 @@ const writeBaseModuleApk = async (aabPath, directory) => {
430
394
  const readBuiltApp = async ({ artifactPath, androidProjectPath }) => {
431
395
  const aapt2 = findAapt2(androidProjectPath);
432
396
  if (!aapt2) {
433
- _hot_updater_cli_tools.p.log.warn("aapt2 was not found in the Android SDK's build-tools, so the build reports the app version and channel of the project files.");
397
+ _hot_updater_cli_tools.p.log.warn("No aapt2 in the Android SDK build-tools.\nThe build reports the project files' app version and channel.");
434
398
  return;
435
399
  }
436
400
  const directory = await fs.default.promises.mkdtemp(path.default.join(os.default.tmpdir(), "android-helper-"));
@@ -455,7 +419,7 @@ const readBuiltApp = async ({ artifactPath, androidProjectPath }) => {
455
419
  };
456
420
  const appVersion = await resolve(parseManifestVersionName(xmltree));
457
421
  const channel = await resolve(parseManifestMetaData(xmltree, CHANNEL_META_DATA_KEY));
458
- if (appVersion === void 0 || channel === void 0) _hot_updater_cli_tools.p.log.warn("aapt2 printed the artifact's versionName or com.hotupdater.CHANNEL in a form that cannot be read exactly, so the build reports the project files' value for it.");
422
+ if (appVersion === void 0 || channel === void 0) _hot_updater_cli_tools.p.log.warn("Couldn't read the artifact's versionName or com.hotupdater.CHANNEL exactly.\nThe build reports the project files' value instead.");
459
423
  const versionCode = parseManifestVersionCode(xmltree);
460
424
  return {
461
425
  appVersion: appVersion ?? null,
@@ -519,20 +483,312 @@ const readBuiltVersionCode = async ({ artifactPath, androidProjectPath }) => {
519
483
  }
520
484
  };
521
485
  //#endregion
486
+ //#region src/utils/sandboxManifest.ts
487
+ const MAIN = "android.intent.action.MAIN";
488
+ const LAUNCHER = "android.intent.category.LAUNCHER";
489
+ const SHORTCUTS = "android.app.shortcuts";
490
+ const ANDROID = "android:";
491
+ const asArray = (value) => value === void 0 || value === null || value === "" ? [] : Array.isArray(value) ? value : [value];
492
+ const attribute = (element, name) => {
493
+ const value = element[`${ANDROID}${name}`];
494
+ return typeof value === "string" ? value : void 0;
495
+ };
496
+ const filtersOf = (component) => asArray(component["intent-filter"]).map((filter) => ({
497
+ actions: asArray(filter["action"]),
498
+ categories: asArray(filter["category"]),
499
+ data: asArray(filter["data"]),
500
+ attributes: Object.fromEntries(Object.entries(filter).filter(([name]) => name.startsWith(ANDROID)))
501
+ }));
502
+ const opensAsLauncher = ({ actions, categories }) => actions.some((action) => attribute(action, "name") === MAIN) && categories.some((category) => attribute(category, "name") === LAUNCHER);
503
+ /** Task settings a sandbox activity can't share a task with: what, and how to fix it. */
504
+ const taskRefusal = (name, activity) => {
505
+ const launchMode = attribute(activity, "launchMode");
506
+ if (launchMode === "singleInstance" || launchMode === "singleInstancePerTask") return `Sandbox builds don't support launchMode ${launchMode} on the launcher ${name}.\nUse singleTask or the default launch mode.`;
507
+ if (attribute(activity, "taskAffinity") !== void 0) return `Sandbox builds don't support taskAffinity on the launcher ${name}.\nRemove it from this build variant.`;
508
+ const documents = attribute(activity, "documentLaunchMode");
509
+ if (documents !== void 0 && documents !== "none") return `Sandbox builds don't support documentLaunchMode ${documents} on the launcher ${name}.\nRemove it from this build variant.`;
510
+ return null;
511
+ };
512
+ /**
513
+ * The launcher entry of a variant's merged manifest, which already holds what
514
+ * its flavors, build type and libraries declare. It refuses what a sandbox
515
+ * build can't take over: none or several entries, a filter it can't move whole,
516
+ * and task settings its activity can't share a task with.
517
+ */
518
+ const resolveSandboxLauncher = (mergedManifest) => {
519
+ const application = new fast_xml_parser.XMLParser({
520
+ ignoreAttributes: false,
521
+ attributeNamePrefix: ""
522
+ }).parse(mergedManifest)?.manifest?.application;
523
+ const activities = asArray(application?.["activity"]);
524
+ const aliases = asArray(application?.["activity-alias"]);
525
+ const entries = [...activities.map((element) => ({
526
+ kind: "activity",
527
+ element
528
+ })), ...aliases.map((element) => ({
529
+ kind: "activity-alias",
530
+ element
531
+ }))].flatMap(({ kind, element }) => {
532
+ const filters = filtersOf(element).filter(opensAsLauncher);
533
+ return filters.length === 0 ? [] : [{
534
+ kind,
535
+ element,
536
+ filters
537
+ }];
538
+ });
539
+ const names = entries.map(({ element }) => attribute(element, "name") ?? "?");
540
+ if (entries.length === 0) throw new Error("A sandbox build needs a launcher, and this variant's manifest has none.\nAdd a MAIN + LAUNCHER intent filter to an activity.");
541
+ if (entries.length > 1) throw new Error(`A sandbox build needs one launcher, and this variant has ${names.length}: ${names.join(", ")}.\nKeep one for this build variant.`);
542
+ const { kind, element, filters } = entries[0];
543
+ const name = names[0];
544
+ if (filters.length > 1) throw new Error(`The launcher ${name} has ${filters.length} MAIN + LAUNCHER filters, and a sandbox build can move one.\nKeep one for this build variant.`);
545
+ if (attribute(element, "enabled") === "false") throw new Error(`The launcher ${name} is disabled in the manifest, and a sandbox build can't tell when it would open.\nEnable it for this build variant.`);
546
+ const targetActivity = kind === "activity-alias" ? attribute(element, "targetActivity") : void 0;
547
+ const activity = kind === "activity" ? element : activities.find((item) => attribute(item, "name") === targetActivity);
548
+ if (activity === void 0) throw new Error(`The launcher ${name} targets ${targetActivity ?? "no activity"}, which this variant's manifest doesn't declare.\nFix its android:targetActivity.`);
549
+ const refusal = taskRefusal(name, activity);
550
+ if (refusal !== null) throw new Error(refusal);
551
+ const launcherProcess = attribute(activity, "process");
552
+ if (launcherProcess !== void 0 && launcherProcess !== attribute(application ?? {}, "process")) throw new Error(`Sandbox builds run the launcher in the application's process, and ${name} sets android:process ${launcherProcess}.\nRemove it, or set the same android:process on <application>, for this build variant.`);
553
+ const shortcuts = asArray(element["meta-data"]).find((item) => attribute(item, "name") === SHORTCUTS);
554
+ const label = attribute(element, "label");
555
+ const icon = attribute(element, "icon");
556
+ const roundIcon = attribute(element, "roundIcon");
557
+ const shortcutsResource = shortcuts && attribute(shortcuts, "resource");
558
+ return {
559
+ kind,
560
+ name,
561
+ ...targetActivity === void 0 ? {} : { targetActivity },
562
+ filter: filters[0],
563
+ ...label === void 0 ? {} : { label },
564
+ ...icon === void 0 ? {} : { icon },
565
+ ...roundIcon === void 0 ? {} : { roundIcon },
566
+ ...shortcutsResource === void 0 ? {} : { shortcuts: shortcutsResource }
567
+ };
568
+ };
569
+ const xml = (text) => text.replace(/&/gu, "&amp;").replace(/"/gu, "&quot;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;");
570
+ const attributesOf = (element) => Object.entries(element).filter(([, value]) => typeof value === "string").map(([name, value]) => ` ${name}="${xml(value)}"`).join("");
571
+ /** A launcher filter, element by element: the merger matches a filter by content. */
572
+ const filterXml = ({ actions, categories, data, attributes }, extra = "") => [
573
+ `<intent-filter${attributesOf(attributes)}${extra}>`,
574
+ ...actions.map((item) => ` <action${attributesOf(item)} />`),
575
+ ...categories.map((item) => ` <category${attributesOf(item)} />`),
576
+ ...data.map((item) => ` <data${attributesOf(item)} />`),
577
+ "</intent-filter>"
578
+ ].map((line) => ` ${line}`).join("\n");
579
+ const optional = (name, value) => value === void 0 ? "" : ` android:${name}="${xml(value)}"`;
580
+ /**
581
+ * The manifest a sandbox build overlays on the app's. `tools:replace` wins over
582
+ * a channel the app's manifest sets, as an Expo project's does. The launcher's
583
+ * filter, label, icon and static shortcuts move to the sandbox's activity, which
584
+ * also takes the links of `appId`'s URL scheme; the rest of the app's activity
585
+ * stays, so its own links still reach it. `appId` is the scheme's `packageName`,
586
+ * before the `.sandbox` suffix, so a preview link needs no build to derive it.
587
+ * The dev server is plain http, which a project's network security config can
588
+ * still refuse: the screen then says so.
589
+ */
590
+ const sandboxManifestOverlay = ({ channel, appId, launcher }) => `<?xml version="1.0" encoding="utf-8"?>
591
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
592
+ <application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic">
593
+ <meta-data android:name="com.hotupdater.CHANNEL" android:value="${xml(channel)}" tools:replace="android:value" />
594
+ <meta-data android:name="${_hot_updater_protocol_native_artifact.SANDBOX_META_DATA}" android:value="true" />
595
+ <activity android:name="${_hot_updater_protocol_native_artifact.SANDBOX_ACTIVITY}" android:exported="true" android:launchMode="singleTop" android:theme="@style/HotUpdaterSandboxTheme" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"${optional("label", launcher.label)}${optional("icon", launcher.icon)}${optional("roundIcon", launcher.roundIcon)}>
596
+ ${filterXml(launcher.filter)}
597
+ <intent-filter>
598
+ <action android:name="android.intent.action.VIEW" />
599
+ <category android:name="android.intent.category.DEFAULT" />
600
+ <category android:name="android.intent.category.BROWSABLE" />
601
+ <data android:scheme="${(0, _hot_updater_protocol_native_artifact.sandboxUrlSchemeOf)(appId)}" />
602
+ </intent-filter>
603
+ <meta-data android:name="com.hotupdater.sandbox.HOST_ACTIVITY" android:value="${xml(launcher.name)}" />${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" android:resource="${xml(launcher.shortcuts)}" />`}
604
+ </activity>
605
+ <${launcher.kind} android:name="${xml(launcher.name)}"${optional("targetActivity", launcher.targetActivity)}>
606
+ ${filterXml(launcher.filter, " tools:node=\"remove\"")}${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" tools:node="remove" />`}
607
+ </${launcher.kind}>
608
+ <activity android:name="com.hotupdater.HotUpdaterSandboxRelaunchActivity" android:excludeFromRecents="true" android:exported="false" android:launchMode="singleTask" android:noHistory="true" android:process=":hotupdater_restart" android:theme="@android:style/Theme.NoDisplay" />
609
+ <provider android:name="com.hotupdater.HotUpdaterSandboxProcess" android:authorities="\${applicationId}.hotupdater.sandbox" android:exported="false" />
610
+ </application>
611
+ </manifest>
612
+ `;
613
+ /** Newest first: the manifest of the task that ran last, under `directory`. */
614
+ const manifestsUnder = (directory) => {
615
+ if (!fs.default.existsSync(directory)) return [];
616
+ return fs.default.readdirSync(directory, { recursive: true }).map(String).filter((file) => path.default.basename(file) === "AndroidManifest.xml").map((file) => path.default.join(directory, file)).sort((a, b) => fs.default.statSync(b).mtimeMs - fs.default.statSync(a).mtimeMs);
617
+ };
618
+ /** The Gradle task that merges a variant's manifest. */
619
+ const mergeManifestTask = (variant) => `process${variant.charAt(0).toUpperCase()}${variant.slice(1)}MainManifest`;
620
+ /**
621
+ * The manifest the merge task of `variant` wrote: AGP 7 and 8 keep it under
622
+ * `build/intermediates/merged_manifest`, in a directory per variant.
623
+ */
624
+ const readMergedManifest = ({ androidProjectPath, appModuleName, variant }) => {
625
+ const variantDirectory = `${variant.charAt(0).toLowerCase()}${variant.slice(1)}`;
626
+ const intermediates = path.default.join(androidProjectPath, appModuleName, "build/intermediates");
627
+ const [manifest] = ["merged_manifest", "merged_manifests"].flatMap((name) => manifestsUnder(path.default.join(intermediates, name, variantDirectory)));
628
+ if (manifest === void 0) throw new Error(`Couldn't find the merged manifest of ${variant} under android/${appModuleName}/build/intermediates.\nBuild the variant once, then try again.`);
629
+ return fs.default.readFileSync(manifest, "utf-8");
630
+ };
631
+ //#endregion
632
+ //#region src/utils/sandboxGradle.ts
633
+ const UNSUPPORTED_DSL = `Sandbox builds don't support AGP 9's default DSL yet.
634
+ Set android.newDsl=false in android/gradle.properties.`;
635
+ /** The message when the build type has a manifest the overlay would replace. */
636
+ const ownManifest = (manifest) => `A sandbox build can't merge with ${manifest}.\nMove what it declares to src/main/AndroidManifest.xml.`;
637
+ /** The message when no project compiled the SDK from source, which a dev server needs. */
638
+ const PREBUILT_SDK = `This app takes @hot-updater/react-native as a prebuilt AAR, and a sandbox build compiles the SDK from source.
639
+ Add the SDK's autolinked project to this build instead of the AAR.`;
640
+ /** Text as a single-quoted Groovy string. */
641
+ const groovyString = (text) => `'${text.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'").replace(/\n/gu, "\\n")}'`;
642
+ /**
643
+ * The init script of one sandbox build, so no project file changes: on the app
644
+ * module, it appends the sandbox's suffix to defaultConfig, where AGP puts any
645
+ * flavor's and build type's after it, and adds `overlay` to the variant's build
646
+ * type. It runs in `finalizeDsl`, after the project's own settings.
647
+ */
648
+ const sandboxInitScript = ({ appModuleName, variant, overlay, minVersionCode }) => `// Written by hot-updater for one sandbox build.
649
+ def appModule = ${groovyString(`:${appModuleName}`)}
650
+ def variant = ${groovyString(variant.toLowerCase())}
651
+ def overlay = new File(${groovyString(overlay)})
652
+ def minVersionCode = ${minVersionCode ?? "null"}
653
+ allprojects { project ->
654
+ if (project.path != appModule) return
655
+ // In this build alone: an init script also runs for React Native's included
656
+ // Gradle plugin. The SDK's sandbox script sets this on the project it compiles.
657
+ gradle.taskGraph.whenReady {
658
+ if (!gradle.rootProject.ext.has('hotUpdaterSandboxSdkProject')) {
659
+ throw new GradleException(${groovyString(PREBUILT_SDK)})
660
+ }
661
+ }
662
+ project.plugins.withId('com.android.application') {
663
+ def components = project.extensions.getByName('androidComponents')
664
+ if (components.pluginVersion.major >= 9 && project.findProperty('android.newDsl')?.toString() != 'false') {
665
+ throw new GradleException(${groovyString(UNSUPPORTED_DSL)})
666
+ }
667
+ components.finalizeDsl { dsl ->
668
+ def buildType = dsl.buildTypes.collect { it.name }
669
+ .findAll { variant.endsWith(it.toLowerCase()) }
670
+ .max { it.length() }
671
+ if (buildType == null) {
672
+ throw new GradleException("No build type of \${project.path} builds variant \${variant}.")
673
+ }
674
+ def manifest = dsl.sourceSets.getByName(buildType).manifest
675
+ def own = manifest.srcFile
676
+ if (own.exists()) {
677
+ throw new GradleException(${groovyString(ownManifest("@MANIFEST@"))}.replace('@MANIFEST@', 'android/' + project.rootDir.toPath().relativize(own.toPath())))
678
+ }
679
+ dsl.defaultConfig.applicationIdSuffix = (dsl.defaultConfig.applicationIdSuffix ?: '') + ${groovyString(_hot_updater_protocol_native_artifact.SANDBOX_APPLICATION_ID_SUFFIX)}
680
+ manifest.srcFile(overlay)
681
+ if (minVersionCode != null) {
682
+ dsl.defaultConfig.versionCode = Math.max(dsl.defaultConfig.versionCode ?: 0, minVersionCode)
683
+ dsl.productFlavors.each { flavor ->
684
+ if (flavor.versionCode != null) flavor.versionCode = Math.max(flavor.versionCode, minVersionCode)
685
+ }
686
+ }
687
+ }
688
+ }
689
+ }
690
+ `;
691
+ /**
692
+ * Runs `build` with the Gradle arguments of a scheme: none for a normal one. A
693
+ * sandbox scheme's attach the SDK's sandbox layer and name the init script,
694
+ * written outside the project with its manifest overlay, and removed after.
695
+ * Kotlin compiles from scratch, since the sandbox layer's sources come and go.
696
+ * `readEffectiveManifest` is the variant's merged manifest before the overlay,
697
+ * which the overlay takes the launcher from.
698
+ */
699
+ const withSandboxGradleArgs = async (scheme, readEffectiveManifest, build, { minVersionCode } = {}) => {
700
+ if (!scheme.sandbox) return build([]);
701
+ if (!scheme.packageName) throw new Error(`The sandbox scheme ${scheme.hotUpdaterSchemeName} sets no packageName, which its URL scheme comes from.\nSet packageName on the scheme.`);
702
+ const launcher = resolveSandboxLauncher(await readEffectiveManifest());
703
+ const directory = await fs.default.promises.mkdtemp(path.default.join(os.default.tmpdir(), "hot-updater-sandbox-"));
704
+ try {
705
+ const overlay = path.default.join(directory, "AndroidManifest.xml");
706
+ const initScript = path.default.join(directory, "sandbox.init.gradle");
707
+ await fs.default.promises.writeFile(overlay, sandboxManifestOverlay({
708
+ channel: (0, _hot_updater_protocol_native_artifact.sandboxChannelOf)(scheme.hotUpdaterSchemeName),
709
+ appId: scheme.packageName,
710
+ launcher
711
+ }));
712
+ await fs.default.promises.writeFile(initScript, sandboxInitScript({
713
+ appModuleName: scheme.appModuleName,
714
+ variant: scheme.variant,
715
+ overlay,
716
+ ...minVersionCode === void 0 ? {} : { minVersionCode }
717
+ }));
718
+ return await build([
719
+ "--init-script",
720
+ initScript,
721
+ `-PhotUpdaterSandbox=${scheme.hotUpdaterSchemeName}`,
722
+ "-Pkotlin.incremental=false"
723
+ ]);
724
+ } finally {
725
+ await fs.default.promises.rm(directory, {
726
+ recursive: true,
727
+ force: true
728
+ });
729
+ }
730
+ };
731
+ /** The major version of the Android Gradle Plugin the project pins, or null. */
732
+ const readAgpMajor = (androidProjectPath) => {
733
+ const rootBuild = ["build.gradle", "build.gradle.kts"].map((file) => path.default.join(androidProjectPath, file)).filter((file) => fs.default.existsSync(file)).map((file) => fs.default.readFileSync(file, "utf-8")).join("\n");
734
+ const pinned = /com\.android\.tools\.build:gradle:(\d+)/u.exec(rootBuild);
735
+ if (pinned) return Number(pinned[1]);
736
+ try {
737
+ const manifest = (0, module$1.createRequire)(path.default.join(androidProjectPath, "package.json")).resolve("react-native/package.json");
738
+ const catalog = fs.default.readFileSync(path.default.join(path.default.dirname(manifest), "gradle/libs.versions.toml"), "utf-8");
739
+ const agp = /^\s*agp\s*=\s*"(\d+)/mu.exec(catalog);
740
+ return agp ? Number(agp[1]) : null;
741
+ } catch {
742
+ return null;
743
+ }
744
+ };
745
+ /**
746
+ * Why a sandbox build of a scheme can't work, read from the project's files
747
+ * before anything is built, or null. The init script checks again, with what
748
+ * Gradle actually resolved.
749
+ */
750
+ const findSandboxGradleBlocker = ({ variant = "Release", appModuleName = "app" }) => {
751
+ const androidProjectPath = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "android");
752
+ if (!fs.default.existsSync(androidProjectPath)) return null;
753
+ const properties = path.default.join(androidProjectPath, "gradle.properties");
754
+ const newDsl = fs.default.existsSync(properties) ? /^\s*android\.newDsl\s*=\s*(\S+)/mu.exec(fs.default.readFileSync(properties, "utf-8"))?.[1] : void 0;
755
+ if (newDsl === "true" || newDsl === void 0 && (readAgpMajor(androidProjectPath) ?? 0) >= 9) return UNSUPPORTED_DSL;
756
+ const buildType = /([A-Z]?[a-z0-9]+)$/u.exec(variant)?.[1]?.toLowerCase();
757
+ const manifest = `${appModuleName}/src/${buildType}/AndroidManifest.xml`;
758
+ return buildType && fs.default.existsSync(path.default.join(androidProjectPath, manifest)) ? ownManifest(`android/${manifest}`) : null;
759
+ };
760
+ //#endregion
522
761
  //#region src/buildAndroid.ts
523
- const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials }) => {
762
+ const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials, logHeader, minVersionCode }) => {
524
763
  const androidProjectPath = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "android");
525
- const result = await runGradle({
526
- args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`] },
527
- env: await resolveGradleSigningEnv({
528
- schemeConfig,
529
- credentials
530
- }),
764
+ const env = await resolveGradleSigningEnv({
765
+ schemeConfig,
766
+ credentials
767
+ });
768
+ const result = await withSandboxGradleArgs(schemeConfig, async () => {
769
+ await runGradleTasks({
770
+ args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`] },
771
+ env,
772
+ appModuleName: schemeConfig.appModuleName,
773
+ tasks: [mergeManifestTask(schemeConfig.variant)],
774
+ logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-manifest`,
775
+ androidProjectPath,
776
+ logHeader
777
+ });
778
+ return readMergedManifest({
779
+ androidProjectPath,
780
+ appModuleName: schemeConfig.appModuleName,
781
+ variant: schemeConfig.variant
782
+ });
783
+ }, (sandboxArgs) => runGradle({
784
+ args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`, ...sandboxArgs] },
785
+ env,
531
786
  appModuleName: schemeConfig.appModuleName,
532
787
  tasks: schemeConfig.aab ? [`bundle${schemeConfig.variant}`] : [`assemble${schemeConfig.variant}`],
533
788
  logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-build`,
534
- androidProjectPath
535
- });
789
+ androidProjectPath,
790
+ logHeader
791
+ }), minVersionCode === void 0 ? {} : { minVersionCode });
536
792
  return {
537
793
  ...result,
538
794
  builtApp: await readBuiltApp({
@@ -542,6 +798,105 @@ const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_t
542
798
  };
543
799
  };
544
800
  //#endregion
801
+ //#region src/device.ts
802
+ /** The SDK's adb, or the one on the PATH without an SDK in the environment. */
803
+ const adbPath = () => {
804
+ const sdk = process.env["ANDROID_HOME"] || process.env["ANDROID_SDK_ROOT"];
805
+ const executable = process.platform.startsWith("win") ? "adb.exe" : "adb";
806
+ const fromSdk = sdk && path.default.join(sdk, "platform-tools", executable);
807
+ return fromSdk && fs.default.existsSync(fromSdk) ? fromSdk : executable;
808
+ };
809
+ const adb = async (args) => {
810
+ try {
811
+ return (await (0, execa.execa)(adbPath(), args)).stdout;
812
+ } catch (error) {
813
+ const { code, stderr, stdout, shortMessage } = error;
814
+ if (code === "ENOENT") throw new Error("adb isn't installed.\nInstall Android platform-tools, or set ANDROID_HOME.");
815
+ throw new Error(stderr?.trim() || stdout?.trim() || shortMessage || String(error));
816
+ }
817
+ };
818
+ /** What `adb devices` lists. */
819
+ const listAdbDevices = async () => (await adb(["devices"])).split("\n").slice(1).map((line) => line.trim().split(/\s+/u)).flatMap(([serial, state]) => serial && state ? [{
820
+ serial,
821
+ state
822
+ }] : []);
823
+ /**
824
+ * The device to install on: `serial`, as adb's own `ANDROID_SERIAL` names it
825
+ * too, or else the only one that takes commands.
826
+ */
827
+ const selectAdbDevice = (devices, serial = process.env["ANDROID_SERIAL"] || void 0) => {
828
+ if (serial !== void 0) {
829
+ const device = devices.find((candidate) => candidate.serial === serial);
830
+ if (device === void 0) throw new Error(`${serial} isn't connected.\nList them: adb devices`);
831
+ if (device.state !== "device") throw new Error(`${serial} is ${device.state}.\nList them: adb devices`);
832
+ return device;
833
+ }
834
+ const ready = devices.filter(({ state }) => state === "device");
835
+ const [only] = ready;
836
+ if (only === void 0) throw new Error("No Android device or emulator is connected.\nStart an emulator or connect a phone, then run this again.");
837
+ if (ready.length > 1) throw new Error([
838
+ `${ready.length} Android devices are connected:`,
839
+ ...ready.map(({ serial }) => ` ${serial}`),
840
+ "Pick one with --device <serial>."
841
+ ].join("\n"));
842
+ return only;
843
+ };
844
+ /** A failure adb reports for an install another install of the app stands in the way of. */
845
+ const NEEDS_UNINSTALL = /^INSTALL_FAILED_(UPDATE_INCOMPATIBLE|VERSION_DOWNGRADE)\b/u;
846
+ const LAUNCHER_CATEGORY = "android.intent.category.LAUNCHER";
847
+ /** An application ID's form, checked before it reaches the device's shell. */
848
+ const APP_ID = /^[A-Za-z][A-Za-z0-9_.]*$/u;
849
+ /** `<application ID>/<activity>`, as `resolve-activity --brief` prints it. */
850
+ const ACTIVITY = /^[A-Za-z0-9_.]+\/[A-Za-z0-9_.$]+$/u;
851
+ /**
852
+ * Installs an APK on a device, and opens its launcher activity. `appId` is
853
+ * the APK's own application ID, whatever suffix its build gave it.
854
+ */
855
+ const installOnAndroidDevice = async ({ serial, apkPath, appId }) => {
856
+ if (!APP_ID.test(appId)) throw new Error(`The APK's application ID isn't valid: ${appId}`);
857
+ try {
858
+ await adb([
859
+ "-s",
860
+ serial,
861
+ "install",
862
+ "-r",
863
+ apkPath
864
+ ]);
865
+ } catch (error) {
866
+ const message = error instanceof Error ? error.message : String(error);
867
+ const failure = /Failure \[([^\]]+)\]/u.exec(message)?.[1] ?? message;
868
+ throw new Error(NEEDS_UNINSTALL.test(failure) ? `The installed ${appId} can't be replaced: ${failure}\nUninstall it: adb -s ${serial} uninstall ${appId}` : `adb couldn't install the APK: ${failure}`);
869
+ }
870
+ const activity = (await adb([
871
+ "-s",
872
+ serial,
873
+ "shell",
874
+ "cmd",
875
+ "package",
876
+ "resolve-activity",
877
+ "--brief",
878
+ "-c",
879
+ LAUNCHER_CATEGORY,
880
+ appId
881
+ ])).trim().split("\n").at(-1)?.trim();
882
+ if (activity === void 0 || !ACTIVITY.test(activity)) throw new Error(`${appId} is installed, and has no launcher activity to open.`);
883
+ const started = await adb([
884
+ "-s",
885
+ serial,
886
+ "shell",
887
+ "am",
888
+ "start",
889
+ "-a",
890
+ "android.intent.action.MAIN",
891
+ "-c",
892
+ LAUNCHER_CATEGORY,
893
+ "-n",
894
+ `'${activity}'`
895
+ ]);
896
+ const error = /^Error: .*$/mu.exec(started)?.[0];
897
+ if (error !== void 0) throw new Error(`${appId} is installed, and didn't open. ${error}`);
898
+ };
899
+ //#endregion
545
900
  //#region src/uploadToPlay.ts
546
901
  const API_URL = "https://androidpublisher.googleapis.com";
547
902
  /** Where Google serves resumable upload sessions, as its docs show both. */
@@ -586,7 +941,7 @@ const readServiceAccount = (json) => {
586
941
  throw new Error("The Play service account is not a JSON key file.");
587
942
  }
588
943
  const { client_email, private_key, token_uri } = parsed;
589
- if (typeof client_email !== "string" || typeof private_key !== "string") throw new Error("The Play service account has no client_email or private_key: use the JSON key file Google Cloud creates for the service account.");
944
+ if (typeof client_email !== "string" || typeof private_key !== "string") throw new Error("The Play service account has no client_email or private_key.\nUse the JSON key file Google Cloud creates for it.");
590
945
  (0, _hot_updater_cli_tools.registerSecretValue)(private_key);
591
946
  let privateKey;
592
947
  try {
@@ -632,7 +987,7 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
632
987
  var PlayVersionCodeUsedError = class extends Error {
633
988
  name = "PlayVersionCodeUsedError";
634
989
  constructor(options) {
635
- super("Google Play already has this .aab's version code. Raise versionCode for every build you upload.", options);
990
+ super("Google Play already has this .aab's version code.\nRaise versionCode for every build you upload.", options);
636
991
  }
637
992
  };
638
993
  /**
@@ -642,15 +997,20 @@ var PlayVersionCodeUsedError = class extends Error {
642
997
  const explain = (error, packageName) => {
643
998
  if (!(error instanceof GooglePlayError)) return error;
644
999
  const { status, apiMessage } = error;
645
- if (status === 401 || /does not have permission/i.test(apiMessage)) return new Error(`The Play service account cannot release ${packageName}. Invite its email in Play Console under Users and permissions, with permission to release to testing tracks, and enable the Google Play Android Developer API in its Google Cloud project.`, { cause: error });
646
- if (/package not found/i.test(apiMessage)) return new Error(`Google Play has no app ${packageName}. Create the app in Play Console and upload its first .aab there; the API releases the builds after it.`, { cause: error });
1000
+ if (status === 401 || /does not have permission/i.test(apiMessage)) return new Error([
1001
+ `The Play service account can't release ${packageName}.`,
1002
+ "Invite its email in Play Console (Users and permissions) to release to",
1003
+ "testing tracks, and enable the Google Play Android Developer API."
1004
+ ].join("\n"), { cause: error });
1005
+ if (/package not found/i.test(apiMessage)) return new Error(`Google Play has no app ${packageName}.\nCreate it in Play Console and upload its first .aab there.`, { cause: error });
647
1006
  if (/version code .*(already been used|already used)/i.test(apiMessage)) return new PlayVersionCodeUsedError({ cause: error });
648
1007
  return error;
649
1008
  };
650
1009
  /**
651
1010
  * Requests to the Google Play Developer API for `packageName`, as the
652
1011
  * service account: each carries an access token, exchanged for a signed
653
- * assertion and replaced well before it expires.
1012
+ * assertion and replaced well before it expires. `checkPlayAccess`
1013
+ * checks a key's access with it too.
654
1014
  */
655
1015
  const createPlayClient = ({ json, packageName, fetch }) => {
656
1016
  const account = readServiceAccount(json);
@@ -668,7 +1028,7 @@ const createPlayClient = ({ json, packageName, fetch }) => {
668
1028
  assertion
669
1029
  }).toString()
670
1030
  });
671
- if (!response.ok) throw new Error(`Google refused the Play service account (HTTP ${response.status}): ${await readApiMessage(response) || "check that its key is current and the service account is enabled."}`);
1031
+ if (!response.ok) throw new Error(`Google refused the Play service account (HTTP ${response.status}).\n${await readApiMessage(response) || "Check that its key is current and the service account is enabled."}`);
672
1032
  const { access_token } = await response.json();
673
1033
  if (typeof access_token !== "string" || !access_token) throw new Error("Google answered the Play service account with no access token.");
674
1034
  (0, _hot_updater_cli_tools.registerSecretValue)(access_token);
@@ -699,11 +1059,69 @@ const createPlayClient = ({ json, packageName, fetch }) => {
699
1059
  };
700
1060
  };
701
1061
  /**
702
- * Whether Google Play's internal testing track already releases the
703
- * `.aab`'s version code, as when a reused native build was uploaded
704
- * before. It reads the track in an edit it then deletes, changing nothing.
1062
+ * Play Console's page that invites `email` as a user. `_` stands for the
1063
+ * developer account the browser is signed in to, so no ID is needed.
1064
+ */
1065
+ const playConsoleInviteUrl = (email) => `https://play.google.com/console/u/0/developers/_/users-and-permissions?invite=${encodeURIComponent(email)}`;
1066
+ const readClientEmail = (json) => {
1067
+ try {
1068
+ const { client_email } = JSON.parse(json);
1069
+ return typeof client_email === "string" ? client_email : "";
1070
+ } catch {
1071
+ return "";
1072
+ }
1073
+ };
1074
+ /**
1075
+ * Checks once whether the service account's key reaches `packageName`: it
1076
+ * opens an edit of the app and deletes it again, which changes nothing.
1077
+ * Throws only for what says nothing about access, such as a network error.
1078
+ */
1079
+ const checkPlayAccess = async ({ serviceAccount: { json }, packageName, fetch = globalThis.fetch }) => {
1080
+ const email = readClientEmail(json);
1081
+ const refused = (error) => ({
1082
+ status: "refused",
1083
+ email,
1084
+ reason: error instanceof Error ? error.message : String(error)
1085
+ });
1086
+ let play;
1087
+ try {
1088
+ play = createPlayClient({
1089
+ json,
1090
+ packageName,
1091
+ fetch
1092
+ });
1093
+ } catch (error) {
1094
+ return refused(error);
1095
+ }
1096
+ try {
1097
+ await play.authorization();
1098
+ } catch (error) {
1099
+ if (error instanceof TypeError) throw error;
1100
+ return refused(error);
1101
+ }
1102
+ const edits = `${API_URL}${play.app}/edits`;
1103
+ try {
1104
+ const edit = await play.request(`Opening an edit of ${packageName}`, "POST", edits, {});
1105
+ if (edit?.id) await play.request("Deleting the edit", "DELETE", `${edits}/${encodeURIComponent(edit.id)}`).catch(() => {});
1106
+ return { status: "ready" };
1107
+ } catch (error) {
1108
+ if (error instanceof GooglePlayError) {
1109
+ if (error.status === 401 || error.status === 403) return {
1110
+ status: "denied",
1111
+ email
1112
+ };
1113
+ if (error.status === 404) return {
1114
+ status: "not-found",
1115
+ email
1116
+ };
1117
+ }
1118
+ throw error;
1119
+ }
1120
+ };
1121
+ /**
1122
+ * Reads the app in an edit it then deletes, changing nothing.
705
1123
  */
706
- const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccount: { json }, fetch = globalThis.fetch }) => {
1124
+ const readInEdit = async ({ packageName, serviceAccount: { json }, fetch }, read) => {
707
1125
  const { app, request } = createPlayClient({
708
1126
  json,
709
1127
  packageName,
@@ -717,8 +1135,7 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
717
1135
  }
718
1136
  const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
719
1137
  try {
720
- const { releases = [] } = await request("Reading the internal track", "GET", `${edit}/tracks/${INTERNAL_TRACK}`);
721
- return releases.some(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
1138
+ return await read(request, edit);
722
1139
  } catch (error) {
723
1140
  throw explain(error, packageName);
724
1141
  } finally {
@@ -726,6 +1143,43 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
726
1143
  }
727
1144
  };
728
1145
  /**
1146
+ * The status of the internal testing release holding `versionCode`, such as
1147
+ * `completed` or `draft`, or null when the track doesn't hold it: never
1148
+ * uploaded, or replaced by a newer release, which testers get instead.
1149
+ */
1150
+ const readPlayInternalRelease = ({ versionCode, packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
1151
+ packageName,
1152
+ serviceAccount,
1153
+ fetch
1154
+ }, async (request, edit) => {
1155
+ const { releases = [] } = await request("Reading the internal track", "GET", `${edit}/tracks/${INTERNAL_TRACK}`);
1156
+ const release = releases.find(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
1157
+ return release ? release.status ?? "completed" : null;
1158
+ });
1159
+ /**
1160
+ * Whether Google Play's internal testing track already releases the
1161
+ * `.aab`'s version code, as when a reused native build was uploaded before.
1162
+ */
1163
+ const findPlayInternalRelease = async (options) => await readPlayInternalRelease(options) !== null;
1164
+ /**
1165
+ * The highest version code Google Play has taken for the app, on any track,
1166
+ * or null with none: a new `.aab` needs one above it.
1167
+ */
1168
+ const readPlayHighestVersionCode = ({ packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
1169
+ packageName,
1170
+ serviceAccount,
1171
+ fetch
1172
+ }, async (request, edit) => {
1173
+ const { bundles = [] } = await request("Reading the app's bundles", "GET", `${edit}/bundles`);
1174
+ const codes = bundles.flatMap(({ versionCode }) => versionCode ?? []);
1175
+ return codes.length > 0 ? Math.max(...codes) : null;
1176
+ });
1177
+ /**
1178
+ * The link that opts a tester in to the app's testing tracks. A build on the
1179
+ * internal track installs through it, for the testers Play Console lists.
1180
+ */
1181
+ const playTestingUrl = (packageName) => `https://play.google.com/apps/testing/${encodeURIComponent(packageName)}`;
1182
+ /**
729
1183
  * The common name of every Android debug certificate: Android Studio's and
730
1184
  * the Android Gradle plugin's (`CN=Android Debug, O=Android, C=US`), and React
731
1185
  * Native's template `debug.keystore` (`CN=Android Debug, OU=Android,
@@ -746,7 +1200,11 @@ const assertPlaySigned = async (aabPath) => {
746
1200
  "-jarfile",
747
1201
  aabPath
748
1202
  ], { reject: false });
749
- if (exitCode === 0 && ANDROID_DEBUG_SIGNER.test(String(stdout))) throw new Error(`Google Play refuses an .aab signed with the Android debug keystore, and ${aabPath} is. Set the scheme's signing.keystore, or a release signingConfig in android/app/build.gradle, then build again.`);
1203
+ if (exitCode === 0 && ANDROID_DEBUG_SIGNER.test(String(stdout))) throw new Error([
1204
+ "Google Play refuses an .aab signed with the Android debug keystore.",
1205
+ "Set the scheme's signing.keystore, or a release signingConfig in",
1206
+ "android/app/build.gradle, then build again."
1207
+ ].join("\n"));
750
1208
  };
751
1209
  /**
752
1210
  * Uploads an `.aab` to Google Play's internal testing track with the Google
@@ -797,7 +1255,7 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
797
1255
  };
798
1256
  } catch (error) {
799
1257
  if (!(error instanceof GooglePlayError) || !DRAFT_APP_ERRORS.some((message) => error.apiMessage.includes(message))) throw error;
800
- _hot_updater_cli_tools.p.log.warn(`Play Console has not published ${packageName} yet, which takes only draft releases. The internal release of version code ${versionCode} is a draft: roll it out in Play Console.`);
1258
+ _hot_updater_cli_tools.p.log.warn(`${packageName} isn't published yet, so version code ${versionCode} is a draft.\nRoll it out in Play Console.`);
801
1259
  await release("draft");
802
1260
  return {
803
1261
  versionCode,
@@ -819,10 +1277,14 @@ const commit = async ({ request, edit, retryDelayMs }) => {
819
1277
  let changesNotSentForReview = false;
820
1278
  for (let attempt = 1;; attempt++) try {
821
1279
  await request("Committing the Google Play edit", "POST", `${edit}:commit${changesNotSentForReview ? "?changesNotSentForReview=true" : ""}`);
822
- if (changesNotSentForReview) _hot_updater_cli_tools.p.log.warn("Google Play saved the release without sending it for review, as the app's state requires. Send the changes for review in Play Console.");
1280
+ if (changesNotSentForReview) _hot_updater_cli_tools.p.log.warn("Google Play saved the release without sending it for review.\nSend the changes for review in Play Console.");
823
1281
  return;
824
1282
  } catch (error) {
825
- if (!(error instanceof GooglePlayError) || error.status >= 500 || error.status === 429) throw new Error(`Google Play did not confirm the release: ${error instanceof Error ? error.message : String(error)} Check internal testing in Play Console before you upload this version code again.`, { cause: error });
1283
+ if (!(error instanceof GooglePlayError) || error.status >= 500 || error.status === 429) throw new Error([
1284
+ "Google Play didn't confirm the release.",
1285
+ error instanceof Error ? error.message : String(error),
1286
+ "Check internal testing in Play Console before you upload it again."
1287
+ ].join("\n"), { cause: error });
826
1288
  if (error.status !== 400) throw error;
827
1289
  if (!changesNotSentForReview && error.apiMessage.includes(NEEDS_CHANGES_NOT_SENT_FOR_REVIEW)) {
828
1290
  changesNotSentForReview = true;
@@ -925,9 +1387,9 @@ const confirmedOffset = (response) => {
925
1387
  * from new apps, or a debug variant, which Play refuses.
926
1388
  */
927
1389
  const resolvePlayUploadServiceAccount = ({ scheme, androidScheme }) => {
928
- if (androidScheme.aab === false) throw new Error(`Google Play takes an .aab, and the scheme ${scheme} builds an .apk (aab: false).`);
1390
+ if (androidScheme.aab === false) throw new Error(`The scheme ${scheme} builds an .apk (aab: false); Google Play takes an .aab.`);
929
1391
  const variant = androidScheme.variant ?? "Release";
930
- if (/debug$/i.test(variant)) throw new Error(`Google Play takes a release build, and the scheme ${scheme} builds the ${variant} variant, which is debuggable and loads its JavaScript from Metro.`);
1392
+ if (/debug$/i.test(variant)) throw new Error(`The scheme ${scheme} builds ${variant}; Google Play takes a release build.`);
931
1393
  return {
932
1394
  kind: "play-service-account",
933
1395
  name: "play-service-account"
@@ -1060,608 +1522,23 @@ const extractBuiltInBundle = async ({ artifactPath, outputPath }) => {
1060
1522
  await (entry.method === 8 ? (0, stream_promises.pipeline)(source, (0, zlib.createInflateRaw)(), fs.default.createWriteStream(outputPath)) : (0, stream_promises.pipeline)(source, fs.default.createWriteStream(outputPath)));
1061
1523
  };
1062
1524
  //#endregion
1063
- //#region src/google/googleApi.ts
1064
- /** A Google Cloud or Google Play API request that failed, with Google's error. */
1065
- var GoogleApiError = class extends Error {
1066
- status;
1067
- /** Google's canonical status, such as `PERMISSION_DENIED`. */
1068
- apiStatus;
1069
- apiMessage;
1070
- /** The `ErrorInfo` reasons, such as `SERVICE_DISABLED`. */
1071
- reasons;
1072
- /** The `PreconditionFailure` violation types, such as an org policy constraint. */
1073
- violations;
1074
- /** The `ErrorInfo` consumer of a disabled service, such as `projects/123`. */
1075
- consumer;
1076
- constructor(action, status, body = {}) {
1077
- const apiMessage = body.apiMessage ?? "";
1078
- super(`${action} failed (HTTP ${status})${apiMessage ? `: ${apiMessage}` : "."}`);
1079
- this.name = "GoogleApiError";
1080
- this.status = status;
1081
- this.apiStatus = body.apiStatus;
1082
- this.apiMessage = apiMessage;
1083
- this.reasons = body.reasons ?? [];
1084
- this.violations = body.violations ?? [];
1085
- this.consumer = body.consumer;
1086
- }
1087
- };
1088
- /** Google's error body, `{ error: { code, status, message, details } }`. */
1089
- const readError = async (action, response) => {
1090
- let error;
1091
- try {
1092
- error = (await response.json()).error;
1093
- } catch {}
1094
- const details = Array.isArray(error?.details) ? error.details : [];
1095
- const info = details.filter((detail) => typeof detail.reason === "string");
1096
- return new GoogleApiError(action, response.status, {
1097
- ...typeof error?.status === "string" ? { apiStatus: error.status } : {},
1098
- ...typeof error?.message === "string" ? { apiMessage: error.message } : {},
1099
- reasons: info.map((detail) => detail.reason),
1100
- violations: details.flatMap((detail) => (detail.violations ?? []).flatMap((violation) => typeof violation.type === "string" ? [violation.type] : [])),
1101
- ...info.find((detail) => detail.metadata?.["consumer"]) ? { consumer: info.find((detail) => detail.metadata?.["consumer"]).metadata["consumer"] } : {}
1102
- });
1103
- };
1104
- /** Whether Google answered that a service is disabled in a project. */
1105
- const isServiceDisabled = (error) => error instanceof GoogleApiError && (error.reasons.includes("SERVICE_DISABLED") || /has not been used in project .* or it is disabled/i.test(error.apiMessage));
1106
- /** Requests with the signed-in user's access token, throwing `GoogleApiError`. */
1107
- const createGoogleRequest = ({ accessToken, fetch }) => async (action, method, url, body) => {
1108
- const response = await fetch(url, {
1109
- method,
1110
- headers: {
1111
- authorization: `Bearer ${accessToken}`,
1112
- ...body === void 0 ? {} : { "content-type": "application/json" }
1113
- },
1114
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
1115
- });
1116
- if (!response.ok) throw await readError(action, response);
1117
- const text = await response.text();
1118
- return text ? JSON.parse(text) : {};
1119
- };
1120
- /**
1121
- * Polls `operation` at `origin` until it is done, returning its response or
1122
- * throwing its error as a `GoogleApiError` with the operation's code.
1123
- */
1124
- const waitForOperation = async ({ request, origin, operation, action, sleep, intervalMs = 2e3, attempts = 60 }) => {
1125
- let current = operation;
1126
- for (let attempt = 0; !current.done; attempt++) {
1127
- if (attempt >= attempts || !current.name) throw new Error(`${action} did not finish in time.`);
1128
- await sleep(intervalMs);
1129
- current = await request(action, "GET", `${origin}/${current.name}`);
1130
- }
1131
- if (current.error) throw new GoogleApiError(action, 400, {
1132
- apiMessage: current.error.message ?? "",
1133
- ...current.error.code === 7 ? { apiStatus: "PERMISSION_DENIED" } : {},
1134
- ...current.error.code === 8 ? { apiStatus: "RESOURCE_EXHAUSTED" } : {}
1135
- });
1136
- return current.response;
1137
- };
1138
- //#endregion
1139
- //#region src/google/types.ts
1140
- /** A named failure of `issuePlayServiceAccount`, with what to do in its message. */
1141
- var PlayServiceAccountError = class extends Error {
1142
- code;
1143
- constructor(code, message, options) {
1144
- super(message, options);
1145
- this.name = "PlayServiceAccountError";
1146
- this.code = code;
1147
- }
1148
- };
1149
- /** The environment variables that replace Hot Updater's Google OAuth client. */
1150
- const GOOGLE_OAUTH_CLIENT_ENV_NAMES = {
1151
- clientId: "HOT_UPDATER_GOOGLE_OAUTH_CLIENT_ID",
1152
- clientSecret: "HOT_UPDATER_GOOGLE_OAUTH_CLIENT_SECRET"
1153
- };
1154
- /** The service account Hot Updater creates, `hot-updater-play@<project>.iam.gserviceaccount.com`. */
1155
- const PLAY_SERVICE_ACCOUNT_ID = "hot-updater-play";
1156
- /** Where a Play Console admin finds the developer account ID. */
1157
- const PLAY_CONSOLE_URL = "https://play.google.com/console";
1158
- //#endregion
1159
- //#region src/google/googleSignIn.ts
1160
- const AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/v2/auth";
1161
- const TOKEN_URL = "https://oauth2.googleapis.com/token";
1162
- const REVOKE_URL = "https://oauth2.googleapis.com/revoke";
1163
- /** How long the browser has to come back with the sign-in. */
1164
- const SIGN_IN_TIMEOUT_MS = 3e5;
1165
- const base64url = (bytes) => bytes.toString("base64url");
1166
- const page = (message) => `<!doctype html><meta charset="utf-8"><title>Hot Updater</title><body style="font-family:system-ui;margin:3rem"><p>${message}</p></body>`;
1167
- /**
1168
- * Signs in with Google as an installed app does (RFC 8252): the browser
1169
- * opens Google's own consent screen, so the password and the second factor
1170
- * stay with Google, and the authorization code comes back to a loopback
1171
- * server on 127.0.0.1, bound to a random port for this sign-in only. The
1172
- * code is exchanged with PKCE (S256), and `state` ties the answer to this
1173
- * request.
1174
- *
1175
- * @param onUrl Sees the sign-in URL, to print and open in a browser.
1176
- */
1177
- const signInWithGoogle = async ({ client, scopes, onUrl, fetch = globalThis.fetch, timeoutMs = SIGN_IN_TIMEOUT_MS }) => {
1178
- const verifier = base64url(node_crypto.default.randomBytes(32));
1179
- const challenge = base64url(node_crypto.default.createHash("sha256").update(verifier).digest());
1180
- const state = base64url(node_crypto.default.randomBytes(16));
1181
- const server = node_http.default.createServer();
1182
- await new Promise((resolve, reject) => {
1183
- server.once("error", reject);
1184
- server.listen(0, "127.0.0.1", () => resolve());
1185
- });
1186
- try {
1187
- const { port } = server.address();
1188
- const redirectUri = `http://127.0.0.1:${port}`;
1189
- const code = new Promise((resolve, reject) => {
1190
- const timer = setTimeout(() => reject(new PlayServiceAccountError("sign-in-cancelled", "The Google sign-in did not finish in time.")), timeoutMs);
1191
- timer.unref();
1192
- server.on("request", (req, res) => {
1193
- const query = new URL(req.url ?? "/", redirectUri).searchParams;
1194
- if (query.get("state") !== state) {
1195
- res.writeHead(404).end();
1196
- return;
1197
- }
1198
- const error = query.get("error");
1199
- const answer = query.get("code");
1200
- res.writeHead(error || !answer ? 400 : 200, { "content-type": "text/html; charset=utf-8" }).end(page(error || !answer ? "The sign-in did not finish. Return to the terminal." : "Signed in. Close this tab and return to the terminal."));
1201
- clearTimeout(timer);
1202
- if (error || !answer) reject(new PlayServiceAccountError("sign-in-cancelled", error === "access_denied" ? "The Google sign-in was cancelled." : `The Google sign-in failed: ${error ?? "no authorization code"}.`));
1203
- else resolve(answer);
1204
- });
1205
- });
1206
- code.catch(() => {});
1207
- const url = new URL(AUTHORIZATION_URL);
1208
- url.search = new URLSearchParams({
1209
- client_id: client.clientId,
1210
- redirect_uri: redirectUri,
1211
- response_type: "code",
1212
- scope: scopes.join(" "),
1213
- code_challenge: challenge,
1214
- code_challenge_method: "S256",
1215
- state,
1216
- prompt: "select_account"
1217
- }).toString();
1218
- await onUrl(url.toString());
1219
- const authorizationCode = await code;
1220
- (0, _hot_updater_cli_tools.registerSecretValue)(authorizationCode);
1221
- const response = await fetch(TOKEN_URL, {
1222
- method: "POST",
1223
- headers: { "content-type": "application/x-www-form-urlencoded" },
1224
- body: new URLSearchParams({
1225
- code: authorizationCode,
1226
- client_id: client.clientId,
1227
- ...client.clientSecret ? { client_secret: client.clientSecret } : {},
1228
- redirect_uri: redirectUri,
1229
- grant_type: "authorization_code",
1230
- code_verifier: verifier
1231
- }).toString()
1232
- });
1233
- const token = await response.json().catch(() => ({}));
1234
- if (!response.ok || typeof token.access_token !== "string") throw new PlayServiceAccountError(token.error === "invalid_client" ? "sign-in-not-configured" : "sign-in-cancelled", `Google refused the sign-in (HTTP ${response.status})${typeof token.error_description === "string" ? `: ${token.error_description}` : typeof token.error === "string" ? `: ${token.error}` : "."}`);
1235
- (0, _hot_updater_cli_tools.registerSecretValue)(token.access_token);
1236
- return {
1237
- accessToken: token.access_token,
1238
- scopes: typeof token.scope === "string" ? token.scope.split(" ") : []
1239
- };
1240
- } finally {
1241
- server.closeAllConnections();
1242
- await new Promise((resolve) => server.close(() => resolve()));
1243
- }
1244
- };
1245
- /** Ends a sign-in: Google revokes its access token. Whether Google did. */
1246
- const revokeGoogleToken = async (accessToken, fetch = globalThis.fetch) => {
1247
- try {
1248
- return (await fetch(REVOKE_URL, {
1249
- method: "POST",
1250
- headers: { "content-type": "application/x-www-form-urlencoded" },
1251
- body: new URLSearchParams({ token: accessToken }).toString()
1252
- })).ok;
1253
- } catch {
1254
- return false;
1255
- }
1256
- };
1257
- //#endregion
1258
- //#region src/google/googleKeyIssuer.ts
1259
- const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
1260
- const ANDROID_PUBLISHER_SCOPE = "https://www.googleapis.com/auth/androidpublisher";
1261
- const SCOPES = [CLOUD_PLATFORM_SCOPE, ANDROID_PUBLISHER_SCOPE];
1262
- const PUBLISHER_API = "https://androidpublisher.googleapis.com/androidpublisher/v3";
1263
- const RESOURCE_MANAGER_API = "https://cloudresourcemanager.googleapis.com";
1264
- const SERVICE_USAGE_API = "https://serviceusage.googleapis.com";
1265
- const IAM_API = "https://iam.googleapis.com/v1";
1266
- /** IAM creates the service account; the Play Developer API is what it calls. */
1267
- const SERVICES = ["iam.googleapis.com", "androidpublisher.googleapis.com"];
1268
- /**
1269
- * What the service account may do in Play Console, for the app only: read
1270
- * it, and release to testing tracks, which `--submit play-internal` does.
1271
- */
1272
- const APP_PERMISSIONS = ["CAN_VIEW_NON_FINANCIAL_DATA", "CAN_MANAGE_TRACK_APKS"];
1273
- const KEY_CREATION_CONSTRAINT = "constraints/iam.disableServiceAccountKeyCreation";
1274
- /** Retries while Google enables an API or creates a service account. */
1275
- const PROPAGATION_ATTEMPTS = 12;
1276
- const PROPAGATION_DELAY_MS = 1e4;
1277
- const sleepFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1278
- /** The developer account ID in `input`, a number or a Play Console URL. */
1279
- const parseDeveloperId = (input) => {
1280
- const trimmed = input.trim();
1281
- if (/^\d+$/u.test(trimmed)) return trimmed;
1282
- return trimmed.match(/\/developers\/(\d+)(?:[/?#]|$)/u)?.[1];
1283
- };
1284
- /** A project ID nobody has: Google Cloud's are global. */
1285
- const newProjectId = () => `${PLAY_SERVICE_ACCOUNT_ID}-${node_crypto.default.randomBytes(3).toString("hex")}`;
1286
- const isNotFound = (error) => error instanceof GoogleApiError && error.status === 404;
1287
- const isConflict = (error) => error instanceof GoogleApiError && error.status === 409;
1288
- /** The API is disabled in the OAuth client's own project: waiting does not help. */
1289
- const clientApiDisabled = (error) => new PlayServiceAccountError("api-not-enabled", `${error.apiMessage} The Google OAuth client Hot Updater signs in with belongs to that project, which must enable the API (see ${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientId}).`, { cause: error });
1290
- /** Google's own words, after a message that names the likely cause. */
1291
- const googleSays = (error) => error instanceof GoogleApiError && error.apiMessage ? ` (Google: ${error.apiMessage})` : "";
1292
- /** A Play Console refusal, as `not-play-admin`. */
1293
- const notPlayAdmin = (developerId, error) => new PlayServiceAccountError("not-play-admin", `The Google Account you signed in with is not an admin of the Play Console developer account ${developerId}. Sign in with an account that has the Admin permission there (Users and permissions in ${PLAY_CONSOLE_URL})${googleSays(error)}.`, { cause: error });
1294
- const isDenied = (error) => error instanceof GoogleApiError && (error.status === 403 || error.apiStatus === "PERMISSION_DENIED");
1295
- /**
1296
- * `IssuePlayServiceAccount` with Google's own APIs, after a sign-in on
1297
- * Google's consent screen (OAuth for installed apps, with PKCE and a
1298
- * loopback redirect):
1299
- *
1300
- * 1. the Play Console side is checked first, with no change anywhere: the
1301
- * developer account answers to the account as its admin, and has the app;
1302
- * 2. the chosen Google Cloud project, or a new one, gets the IAM and Play
1303
- * Developer APIs enabled, and the service account `hot-updater-play`;
1304
- * 3. the service account becomes a Play Console user that may release the
1305
- * app to testing tracks;
1306
- * 4. only then is its JSON key created, the last step, so a failure before
1307
- * it leaves no key behind.
1308
- *
1309
- * Each step reuses what an earlier run created: the project, the service
1310
- * account, and its Play Console access.
1311
- */
1312
- const createGoogleKeyIssuer = ({ fetch = globalThis.fetch, sleep = sleepFor } = {}) => async (request) => {
1313
- const { packageName, oauthClient, onStep = () => {} } = request;
1314
- if (!oauthClient?.clientId) throw new PlayServiceAccountError("sign-in-not-configured", `This build of Hot Updater has no Google OAuth client to sign in with. Set ${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientId} and ${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientSecret} to a "Desktop app" OAuth client.`);
1315
- const signIn = await signInWithGoogle({
1316
- client: oauthClient,
1317
- scopes: SCOPES,
1318
- onUrl: request.onSignInUrl,
1319
- fetch
1320
- });
1321
- const dispose = async () => {
1322
- await revokeGoogleToken(signIn.accessToken, fetch);
1323
- };
1324
- try {
1325
- const missing = SCOPES.filter((scope) => !signIn.scopes.includes(scope));
1326
- if (missing.length > 0) throw new PlayServiceAccountError("scope-not-granted", `The sign-in did not allow ${missing.map((scope) => scope === ANDROID_PUBLISHER_SCOPE ? "managing Google Play" : "managing Google Cloud").join(" or ")}. Run this again and keep every box on Google's consent screen ticked.`);
1327
- const google = createGoogleRequest({
1328
- accessToken: signIn.accessToken,
1329
- fetch
1330
- });
1331
- const developerInput = await request.askDeveloperId();
1332
- const developerId = parseDeveloperId(developerInput);
1333
- if (developerId === void 0) throw new PlayServiceAccountError("developer-not-found", `"${developerInput.trim()}" is no developer account ID. Open ${PLAY_CONSOLE_URL}: it is the number after /developers/ in the address.`);
1334
- onStep("Checking the Play Console developer account");
1335
- await checkPlayConsole({
1336
- google,
1337
- developerId,
1338
- packageName
1339
- });
1340
- const project = await chooseProject({
1341
- google,
1342
- request,
1343
- sleep,
1344
- onStep
1345
- });
1346
- const { projectId } = project;
1347
- onStep(`Enabling the Google Play Developer API in ${projectId}`);
1348
- await enableServices({
1349
- google,
1350
- projectId,
1351
- sleep
1352
- });
1353
- onStep(`Creating the service account in ${projectId}`);
1354
- const email = await ensureServiceAccount({
1355
- google,
1356
- project,
1357
- sleep
1358
- });
1359
- onStep(`Giving ${email} release access to ${packageName}`);
1360
- await grantPlayAccess({
1361
- google,
1362
- developerId,
1363
- email,
1364
- packageName
1365
- });
1366
- onStep("Creating the service account's JSON key");
1367
- const key = await createKey({
1368
- google,
1369
- project,
1370
- email,
1371
- sleep
1372
- });
1373
- return {
1374
- json: key.json,
1375
- keyId: key.keyId,
1376
- email,
1377
- projectId,
1378
- developerId,
1379
- revoke: async () => {
1380
- try {
1381
- await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`);
1382
- return true;
1383
- } catch (error) {
1384
- return isNotFound(error);
1385
- }
1386
- },
1387
- dispose
1388
- };
1389
- } catch (error) {
1390
- await dispose();
1391
- throw error;
1392
- }
1393
- };
1394
- /**
1395
- * Whether the signed-in account administers `developerId`, and Google Play
1396
- * has `packageName` there, asked without changing anything: listing the
1397
- * account's users takes the admin permission, and an edit opened on the app
1398
- * is deleted again.
1399
- */
1400
- const checkPlayConsole = async ({ google, developerId, packageName }) => {
1401
- try {
1402
- await google("Listing the Play Console users", "GET", `${PUBLISHER_API}/developers/${developerId}/users?pageSize=1`);
1403
- } catch (error) {
1404
- if (isServiceDisabled(error)) throw clientApiDisabled(error);
1405
- if (isNotFound(error)) throw new PlayServiceAccountError("developer-not-found", `Play Console has no developer account ${developerId}. Open ${PLAY_CONSOLE_URL}: the developer account ID is the number after /developers/ in the address${googleSays(error)}.`, { cause: error });
1406
- if (isDenied(error)) throw notPlayAdmin(developerId, error);
1407
- throw error;
1408
- }
1409
- let edit;
1410
- try {
1411
- edit = await google(`Opening an edit of ${packageName}`, "POST", `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits`);
1412
- } catch (error) {
1413
- if (isServiceDisabled(error)) throw clientApiDisabled(error);
1414
- if (isNotFound(error) || isDenied(error)) throw appNotFound(packageName, developerId, error);
1415
- throw error;
1416
- }
1417
- if (edit.id) await google("Deleting the edit", "DELETE", `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits/${edit.id}`).catch(() => {});
1418
- };
1419
- const appNotFound = (packageName, developerId, cause) => new PlayServiceAccountError("app-not-found", `Google Play has no app ${packageName} in the developer account ${developerId}. Google takes the first .aab of a new app only in Play Console: create the app there, upload one .aab by hand (for example to internal testing), then run this again${googleSays(cause)}.`, { cause });
1420
- /** The account's active projects, every page of them. */
1421
- const listProjects = async (google) => {
1422
- const projects = [];
1423
- let pageToken;
1424
- do {
1425
- const page = await google("Listing the Google Cloud projects", "GET", `${RESOURCE_MANAGER_API}/v3/projects:search?${new URLSearchParams({
1426
- query: "state:ACTIVE",
1427
- ...pageToken ? { pageToken } : {}
1428
- })}`);
1429
- for (const project of page.projects ?? []) if (project.projectId) projects.push({
1430
- projectId: project.projectId,
1431
- ...project.displayName ? { displayName: project.displayName } : {},
1432
- ...projectNumberOf(project.name)
1433
- });
1434
- pageToken = page.nextPageToken || void 0;
1435
- } while (pageToken);
1436
- return projects;
1437
- };
1438
- /** The project the developer picks, or a new one when there is none or they ask. */
1439
- const chooseProject = async ({ google, request, sleep, onStep }) => {
1440
- const projects = await listProjects(google);
1441
- const chosen = projects.length > 0 ? await request.chooseProject(projects.map(({ projectId, displayName }) => ({
1442
- projectId,
1443
- ...displayName ? { displayName } : {}
1444
- }))) : void 0;
1445
- if (chosen !== void 0) return projects.find((project) => project.projectId === chosen) ?? { projectId: chosen };
1446
- const projectId = newProjectId();
1447
- onStep(`Creating the Google Cloud project ${projectId}`);
1448
- try {
1449
- const operation = await google("Creating the Google Cloud project", "POST", `${RESOURCE_MANAGER_API}/v3/projects`, {
1450
- projectId,
1451
- displayName: "Hot Updater Play"
1452
- });
1453
- const created = await waitForOperation({
1454
- request: google,
1455
- origin: `${RESOURCE_MANAGER_API}/v3`,
1456
- operation,
1457
- action: "Creating the Google Cloud project",
1458
- sleep
1459
- });
1460
- return {
1461
- projectId,
1462
- ...projectNumberOf(created?.name)
1463
- };
1464
- } catch (error) {
1465
- if (!(error instanceof GoogleApiError)) throw error;
1466
- if (error.status === 429 || error.apiStatus === "RESOURCE_EXHAUSTED" || /quota/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-quota", `Google Cloud has no project quota left for this account: ${error.apiMessage || "quota exceeded"}. Delete a project you no longer use (https://console.cloud.google.com/cloud-resource-manager), or run this again and pick an existing project.`, { cause: error });
1467
- if (/terms of service/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-create-denied", "This Google Account has not accepted the Google Cloud Terms of Service. Open https://console.cloud.google.com once to accept them, then run this again.", { cause: error });
1468
- if (isDenied(error) || error.apiStatus === "FAILED_PRECONDITION") throw new PlayServiceAccountError("project-create-denied", `This Google Account may not create Google Cloud projects: ${error.apiMessage || "permission denied"}. Ask your organization's admin for the Project Creator role, or run this again and pick an existing project.`, { cause: error });
1469
- throw error;
1470
- }
1471
- };
1472
- /** `projectNumber` from a resource name `projects/<number>`. */
1473
- const projectNumberOf = (name) => {
1474
- const number = name?.match(/^projects\/(\d+)$/u)?.[1];
1475
- return number === void 0 ? {} : { projectNumber: number };
1476
- };
1477
- /**
1478
- * Runs `run` again while Google is still enabling an API in `project`,
1479
- * or, with `notFound`, still creating what it reads.
1480
- */
1481
- const whilePropagating = async ({ run, project, sleep, notFound = false }) => {
1482
- for (let attempt = 1;; attempt++) try {
1483
- return await run();
1484
- } catch (error) {
1485
- const disabled = isServiceDisabled(error);
1486
- if (disabled && !consumerIs(error, project)) throw clientApiDisabled(error);
1487
- if (!disabled && !(notFound && isNotFound(error)) || attempt >= PROPAGATION_ATTEMPTS) {
1488
- if (disabled) throw new PlayServiceAccountError("api-not-enabled", `Google is still enabling the APIs in ${project.projectId}: ${error.apiMessage} Wait a few minutes, then run this again.`, { cause: error });
1489
- throw error;
1490
- }
1491
- await sleep(PROPAGATION_DELAY_MS);
1492
- }
1493
- };
1494
- /**
1495
- * Whether a disabled-service error is about `project` itself, which waiting
1496
- * fixes: Google names the consumer by number, and an error naming none
1497
- * counts as the project's own.
1498
- */
1499
- const consumerIs = (error, project) => error.consumer === void 0 || error.consumer === `projects/${project.projectId}` || (project.projectNumber === void 0 ? true : error.consumer === `projects/${project.projectNumber}`);
1500
- const enableServices = async ({ google, projectId, sleep }) => {
1501
- try {
1502
- const operation = await google("Enabling the APIs", "POST", `${SERVICE_USAGE_API}/v1/projects/${projectId}/services:batchEnable`, { serviceIds: SERVICES });
1503
- await waitForOperation({
1504
- request: google,
1505
- origin: `${SERVICE_USAGE_API}/v1`,
1506
- operation,
1507
- action: "Enabling the APIs",
1508
- sleep
1509
- });
1510
- } catch (error) {
1511
- if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", `This Google Account may not enable APIs in ${projectId}: ${error.apiMessage || "permission denied"}. Pick a project you own, or ask its owner for the Editor role.`, { cause: error });
1512
- throw error;
1513
- }
1514
- };
1515
- /** The `hot-updater-play` service account's email, created unless it exists. */
1516
- const ensureServiceAccount = async ({ google, project, sleep }) => {
1517
- const { projectId } = project;
1518
- const email = `${PLAY_SERVICE_ACCOUNT_ID}@${projectId}.iam.gserviceaccount.com`;
1519
- try {
1520
- return (await whilePropagating({
1521
- project,
1522
- sleep,
1523
- run: () => google("Creating the service account", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts`, {
1524
- accountId: "hot-updater-play",
1525
- serviceAccount: {
1526
- displayName: "Hot Updater Play uploads",
1527
- description: "Uploads Android App Bundles to Google Play for hot-updater native-build android --submit play-internal."
1528
- }
1529
- })
1530
- })).email ?? email;
1531
- } catch (error) {
1532
- if (isConflict(error)) return email;
1533
- if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", `This Google Account may not create service accounts in ${projectId}: ${error.apiMessage || "permission denied"}. Pick a project you own, or ask its owner for the Service Account Admin role.`, { cause: error });
1534
- throw error;
1535
- }
1536
- };
1537
- /**
1538
- * Makes `email` a Play Console user that may release `packageName`, keeping
1539
- * any permission it has: the user and the app's grant are created, or the
1540
- * grant gains the release permissions.
1541
- */
1542
- const grantPlayAccess = async ({ google, developerId, email, packageName }) => {
1543
- const developer = `${PUBLISHER_API}/developers/${developerId}`;
1544
- const user = `${developer}/users/${encodeURIComponent(email)}`;
1545
- try {
1546
- await google("Adding the Play Console user", "POST", `${developer}/users`, {
1547
- name: `developers/${developerId}/users/${email}`,
1548
- email
1549
- });
1550
- } catch (error) {
1551
- if (isDenied(error)) throw notPlayAdmin(developerId, error);
1552
- if (!isConflict(error)) throw error;
1553
- }
1554
- try {
1555
- await google("Granting access to the app", "POST", `${user}/grants`, {
1556
- name: `developers/${developerId}/users/${email}/grants/${packageName}`,
1557
- packageName,
1558
- appLevelPermissions: APP_PERMISSIONS
1559
- });
1560
- return;
1561
- } catch (error) {
1562
- if (isNotFound(error)) throw appNotFound(packageName, developerId, error);
1563
- if (isDenied(error)) throw notPlayAdmin(developerId, error);
1564
- if (!isConflict(error)) throw error;
1565
- }
1566
- const granted = await findGrant({
1567
- google,
1568
- developer,
1569
- email,
1570
- packageName
1571
- });
1572
- const missing = APP_PERMISSIONS.filter((permission) => !granted.includes(permission));
1573
- if (missing.length === 0) return;
1574
- await google("Granting access to the app", "PATCH", `${user}/grants/${encodeURIComponent(packageName)}?updateMask=appLevelPermissions`, { appLevelPermissions: [...granted, ...missing] });
1575
- };
1576
- /** The app permissions `email` holds on `packageName`, from the user list. */
1577
- const findGrant = async ({ google, developer, email, packageName }) => {
1578
- let pageToken;
1579
- do {
1580
- const page = await google("Listing the Play Console users", "GET", `${developer}/users?${new URLSearchParams({
1581
- pageSize: "100",
1582
- ...pageToken ? { pageToken } : {}
1583
- })}`);
1584
- const found = page.users?.find((candidate) => candidate.email === email);
1585
- if (found) return found.grants?.find((grant) => grant.packageName === packageName)?.appLevelPermissions ?? [];
1586
- pageToken = page.nextPageToken || void 0;
1587
- } while (pageToken);
1588
- return [];
1589
- };
1590
- /** A new JSON key of the service account, checked and masked in the CLI's output. */
1591
- const createKey = async ({ google, project, email, sleep }) => {
1592
- const { projectId } = project;
1593
- let key;
1594
- try {
1595
- key = await whilePropagating({
1596
- project,
1597
- sleep,
1598
- notFound: true,
1599
- run: () => google("Creating the key", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts/${email}/keys`, {
1600
- privateKeyType: "TYPE_GOOGLE_CREDENTIALS_FILE",
1601
- keyAlgorithm: "KEY_ALG_RSA_2048"
1602
- })
1603
- });
1604
- } catch (error) {
1605
- if (error instanceof GoogleApiError && (error.violations.includes(KEY_CREATION_CONSTRAINT) || /disableServiceAccountKeyCreation/u.test(error.apiMessage))) throw new PlayServiceAccountError("key-creation-disabled", `An organization policy (iam.disableServiceAccountKeyCreation) forbids service account keys in ${projectId}; organizations created since 2024 enforce it by default. Ask an organization policy admin to allow keys for this project, or run this again with a project outside the organization. The service account ${email} and its Play Console access remain for the next run.`, { cause: error });
1606
- throw error;
1607
- }
1608
- if (!key.name || !key.privateKeyData) throw new Error("Google Cloud created the key without its JSON file.");
1609
- (0, _hot_updater_cli_tools.registerSecretValue)(key.privateKeyData);
1610
- const json = Buffer.from(key.privateKeyData, "base64").toString("utf-8");
1611
- (0, _hot_updater_cli_tools.registerSecretValue)(json);
1612
- let parsed;
1613
- try {
1614
- parsed = JSON.parse(json);
1615
- } catch {
1616
- parsed = {};
1617
- }
1618
- if (typeof parsed.private_key !== "string") {
1619
- await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`).catch(() => {});
1620
- throw new Error("Google Cloud created a key that is no JSON key file.");
1621
- }
1622
- (0, _hot_updater_cli_tools.registerSecretValue)(parsed.private_key);
1623
- return {
1624
- json,
1625
- name: key.name,
1626
- keyId: key.name.split("/").pop()
1627
- };
1628
- };
1629
- //#endregion
1630
- //#region src/playServiceAccount.ts
1631
- /**
1632
- * Hot Updater's Google OAuth client, a "Desktop app" client the sign-in
1633
- * opens Google's consent screen for. Empty in a build that has none, where
1634
- * `HOT_UPDATER_GOOGLE_OAUTH_CLIENT_ID` and `_SECRET` name one.
1635
- */
1636
- const HOT_UPDATER_GOOGLE_OAUTH_CLIENT = {
1637
- clientId: "",
1638
- clientSecret: ""
1639
- };
1640
- /**
1641
- * Hot Updater's issuer, the one place that picks how it is done: Google's
1642
- * OAuth for installed apps, then the Cloud Resource Manager, Service Usage,
1643
- * IAM, and Play Developer APIs. Another implementation of
1644
- * `IssuePlayServiceAccount` replaces it here without touching its callers.
1645
- */
1646
- const issuePlayServiceAccount = (request) => createGoogleKeyIssuer()({
1647
- ...request,
1648
- oauthClient: request.oauthClient ?? HOT_UPDATER_GOOGLE_OAUTH_CLIENT
1649
- });
1650
- //#endregion
1651
- exports.GOOGLE_OAUTH_CLIENT_ENV_NAMES = GOOGLE_OAUTH_CLIENT_ENV_NAMES;
1652
- exports.HOT_UPDATER_GOOGLE_OAUTH_CLIENT = HOT_UPDATER_GOOGLE_OAUTH_CLIENT;
1653
- exports.PLAY_CONSOLE_URL = PLAY_CONSOLE_URL;
1654
- exports.PLAY_SERVICE_ACCOUNT_ID = PLAY_SERVICE_ACCOUNT_ID;
1655
- exports.PlayServiceAccountError = PlayServiceAccountError;
1656
1525
  exports.PlayVersionCodeUsedError = PlayVersionCodeUsedError;
1657
1526
  exports.assertPlaySigned = assertPlaySigned;
1658
1527
  exports.buildAndroid = buildAndroid;
1528
+ exports.checkPlayAccess = checkPlayAccess;
1659
1529
  exports.enrichNativeBuildAndroidScheme = enrichNativeBuildAndroidScheme;
1660
1530
  exports.extractBuiltInBundle = extractBuiltInBundle;
1661
1531
  exports.findPlayInternalRelease = findPlayInternalRelease;
1662
- exports.issuePlayServiceAccount = issuePlayServiceAccount;
1532
+ exports.findSandboxGradleBlocker = findSandboxGradleBlocker;
1533
+ exports.installOnAndroidDevice = installOnAndroidDevice;
1534
+ exports.listAdbDevices = listAdbDevices;
1535
+ exports.playConsoleInviteUrl = playConsoleInviteUrl;
1536
+ exports.playTestingUrl = playTestingUrl;
1663
1537
  exports.readBuiltApp = readBuiltApp;
1664
1538
  exports.readBuiltPackageName = readBuiltPackageName;
1665
1539
  exports.readBuiltVersionCode = readBuiltVersionCode;
1540
+ exports.readPlayHighestVersionCode = readPlayHighestVersionCode;
1541
+ exports.readPlayInternalRelease = readPlayInternalRelease;
1666
1542
  exports.resolvePlayUploadServiceAccount = resolvePlayUploadServiceAccount;
1543
+ exports.selectAdbDevice = selectAdbDevice;
1667
1544
  exports.uploadToPlay = uploadToPlay;