@hot-updater/android-helper 1.2.0-rc.6 → 1.2.0-rc.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4,121 +4,40 @@ import fs from "fs";
4
4
  import { ExecaError, execa } from "execa";
5
5
  import os from "os";
6
6
  import JSZip from "jszip";
7
+ import { createRequire } from "module";
8
+ import { SANDBOX_ACTIVITY, SANDBOX_APPLICATION_ID_SUFFIX, SANDBOX_META_DATA, SANDBOX_URL_SCHEME_META_DATA, sandboxUrlSchemeOf } from "@hot-updater/protocol/native-artifact";
9
+ import { XMLParser } from "fast-xml-parser";
7
10
  import crypto from "crypto";
8
11
  import { pipeline } from "stream/promises";
9
12
  import { createInflateRaw } from "zlib";
10
- import crypto$1 from "node:crypto";
13
+ //#region src/utils/gradlePhase.ts
14
+ /** `> Task :app:compileReleaseKotlin`, with an outcome such as `UP-TO-DATE`. */
15
+ const TASK = /^> Task (:\S+)/;
16
+ const CONFIGURE = /^> Configure project (:\S*)/;
17
+ /**
18
+ * Reads the phase of a Gradle build from its plain console output: the
19
+ * task it runs, after how many it has run, such as
20
+ * `312 tasks · :app:mergeReleaseResources`.
21
+ */
22
+ const createGradlePhaseReader = () => {
23
+ let tasks = 0;
24
+ return (line) => {
25
+ const task = TASK.exec(line)?.[1];
26
+ if (task) {
27
+ tasks += 1;
28
+ return `${tasks} task${tasks === 1 ? "" : "s"} · ${task}`;
29
+ }
30
+ const project = CONFIGURE.exec(line)?.[1];
31
+ if (project) return `Configuring ${project}`;
32
+ if (line.startsWith("Starting a Gradle Daemon")) return "Starting the Gradle daemon";
33
+ if (line.startsWith("Downloading https://services.gradle.org/")) return "Downloading Gradle";
34
+ };
35
+ };
36
+ //#endregion
11
37
  //#region src/utils/createGradleLogger.ts
12
38
  const createGradleLogger = ({ logPrefix }) => new BuildLogger({
13
39
  logPrefix,
14
- importantLogPatterns: [
15
- "error:",
16
- "Error:",
17
- "ERROR:",
18
- "> Task :",
19
- "BUILD FAILED",
20
- "BUILD SUCCESSFUL",
21
- "FAILURE: Build failed with an exception.",
22
- "* What went wrong:",
23
- "Execution failed for task",
24
- "Could not resolve",
25
- "Failed to",
26
- "Unable to load script",
27
- "Metro encountered an error",
28
- "React Native CLI",
29
- "Android resource compilation failed",
30
- "Duplicate class",
31
- "Program type already present",
32
- "actionable tasks:",
33
- "Deprecated Gradle features were used",
34
- ":app:configureCMake",
35
- ":app:buildCMake",
36
- ":app:compileDebugKotlin",
37
- ":app:compileReleaseKotlin",
38
- ":app:compileDebugJavaWithJavac",
39
- ":app:compileReleaseJavaWithJavac",
40
- ":app:mergeDebugResources",
41
- ":app:mergeReleaseResources",
42
- ":app:processDebugResources",
43
- ":app:processReleaseResources",
44
- ":app:packageDebug",
45
- ":app:packageRelease",
46
- ":app:assembleDebug",
47
- ":app:assembleRelease"
48
- ],
49
- progressStages: [
50
- [
51
- "buildKotlinToolingMetadata",
52
- "generateAutolinkingNewArchitectureFiles",
53
- "generateAutolinkingPackageList",
54
- "generateCodegenSchemaFromJavaScript",
55
- "generateCodegenArtifactsFromSchema",
56
- "generateReactNativeEntryPoint"
57
- ],
58
- [
59
- "createBundleReleaseJsAndAssets",
60
- "bundleReleaseJsAndAssets",
61
- "bundleDebugJsAndAssets"
62
- ],
63
- [
64
- "generateReleaseResValues",
65
- "generateDebugResValues",
66
- "generateReleaseResources",
67
- "generateDebugResources",
68
- "mergeReleaseResources",
69
- "mergeDebugResources"
70
- ],
71
- [
72
- "processReleaseResources",
73
- "processDebugResources",
74
- "processReleaseManifest",
75
- "processDebugManifest",
76
- "processDebugMainManifest",
77
- "parseReleaseLocalResources",
78
- "parseDebugLocalResources"
79
- ],
80
- ["compileReleaseKotlin", "compileDebugKotlin"],
81
- ["compileReleaseJavaWithJavac", "compileDebugJavaWithJavac"],
82
- [
83
- /configureCMake\w+\[/,
84
- /buildCMake\w+\[/,
85
- "mergeReleaseJniLibFolders",
86
- "mergeDebugJniLibFolders",
87
- "mergeReleaseNativeLibs",
88
- "mergeDebugNativeLibs"
89
- ],
90
- [
91
- "desugarReleaseFileDependencies",
92
- "desugarDebugFileDependencies",
93
- "dexBuilderRelease",
94
- "dexBuilderDebug",
95
- "mergeDexRelease",
96
- "mergeExtDexRelease",
97
- "mergeExtDexDebug",
98
- "mergeProjectDexRelease",
99
- "mergeProjectDexDebug",
100
- "mergeLibDexRelease",
101
- "mergeLibDexDebug",
102
- "mergeDebugGlobalSynthetics",
103
- "mergeReleaseGlobalSynthetics",
104
- "transformClassesWithDex"
105
- ],
106
- [
107
- "compressReleaseAssets",
108
- "compressDebugAssets",
109
- "optimizeReleaseResources",
110
- "mergeReleaseAssets",
111
- "mergeDebugAssets"
112
- ],
113
- [
114
- "packageRelease",
115
- "packageDebug",
116
- "assembleRelease",
117
- "assembleDebug"
118
- ],
119
- ["bundleRelease", "bundleDebug"],
120
- ["BUILD SUCCESSFUL", /\d+ actionable tasks:/]
121
- ],
40
+ createPhaseReader: createGradlePhaseReader,
122
41
  failureSummary: {
123
42
  lines: [
124
43
  /^e: /,
@@ -153,6 +72,75 @@ const formatCommand = (words, width = 74) => {
153
72
  return lines.join("\n");
154
73
  };
155
74
  //#endregion
75
+ //#region src/utils/windowsGradle.ts
76
+ /**
77
+ * The init script every Windows build runs with. ninja 1.10.2, which the
78
+ * Android SDK's CMake 3.22.1 ships, can't reach a path over MAX_PATH (260
79
+ * characters), and React Native's codegen object paths, which repeat the
80
+ * project's path, pass it. At 259, CMake hashes the long part of an object's
81
+ * name so the whole path stays within it; at 250, an object directory of
82
+ * 179 characters left no room for the hash and a 40-character file name.
83
+ * Only the names of objects under `.cxx` change, never what they compile
84
+ * to.
85
+ *
86
+ * Expo's root project plugin (expo-modules-autolinking 58,
87
+ * `ExpoRootProjectPlugin.kt` `setDefaultCmakeObjectPathMax`) gives every
88
+ * module `-DCMAKE_OBJECT_PATH_MAX` from the `expo.android.cmakeObjectPathMax`
89
+ * property, 1024 when unset, which it reads with `findProperty` as a string
90
+ * when it applies. So the script sets that property on the root project
91
+ * first, unless gradle.properties, the user's, `-P` or the environment set
92
+ * it. Their value stands, `0` included, which turns Expo's limit off and
93
+ * leaves CMake's own: then no module gets one from this script either. A
94
+ * module whose own CMake arguments set CMAKE_OBJECT_PATH_MAX, in its default
95
+ * config, a build type or a flavor, keeps its own.
96
+ */
97
+ const WINDOWS_INIT_SCRIPT = `// Written by hot-updater for one Windows build: object paths within MAX_PATH.
98
+ // Set by the project, a person or the environment, not this script: their
99
+ // value stands, and 0, which turns Expo's limit off, too.
100
+ def expoLimitSetElsewhere = false
101
+ gradle.rootProject { root ->
102
+ if (root.hasProperty('expo.android.cmakeObjectPathMax')) {
103
+ expoLimitSetElsewhere = true
104
+ } else {
105
+ root.ext.set('expo.android.cmakeObjectPathMax', '259')
106
+ }
107
+ }
108
+ allprojects { project ->
109
+ ['com.android.application', 'com.android.library'].each { id ->
110
+ project.plugins.withId(id) {
111
+ project.extensions.getByName('androidComponents').finalizeDsl { android ->
112
+ def configs = [android.defaultConfig] + android.buildTypes.toList() + android.productFlavors.toList()
113
+ def own = configs.any { config ->
114
+ config.externalNativeBuild.cmake.arguments.any { it.startsWith('-DCMAKE_OBJECT_PATH_MAX') }
115
+ }
116
+ if (!own && !expoLimitSetElsewhere) {
117
+ android.defaultConfig.externalNativeBuild.cmake.arguments.add('-DCMAKE_OBJECT_PATH_MAX=259')
118
+ }
119
+ }
120
+ }
121
+ }
122
+ }
123
+ `;
124
+ /**
125
+ * Runs `build` with the Gradle arguments a Windows build needs: none
126
+ * elsewhere. The init script is written outside the project, and removed
127
+ * after.
128
+ */
129
+ const withWindowsGradleArgs = async (build) => {
130
+ if (!process.platform.startsWith("win")) return build([]);
131
+ const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), "hot-updater-windows-"));
132
+ try {
133
+ const script = path.join(directory, "windows.init.gradle");
134
+ await fs.promises.writeFile(script, WINDOWS_INIT_SCRIPT);
135
+ return await build(["--init-script", script]);
136
+ } finally {
137
+ await fs.promises.rm(directory, {
138
+ recursive: true,
139
+ force: true
140
+ });
141
+ }
142
+ };
143
+ //#endregion
156
144
  //#region src/builder/runGradle.ts
157
145
  /** Why Gradle failed, without its command line. */
158
146
  const describeFailure = (error) => {
@@ -169,54 +157,84 @@ function getTaskNames(moduleName, tasks) {
169
157
  return tasks.map((task) => `${moduleName}:${task}`);
170
158
  }
171
159
  /**
172
- * Get gradle wrapper command based on platform
160
+ * The project's Gradle wrapper. On Windows by its path: cmd.exe finds no
161
+ * program in the current directory with NoDefaultCurrentDirectoryInExePath.
162
+ */
163
+ const getGradleWrapper = (androidProjectPath) => process.platform.startsWith("win") ? path.join(androidProjectPath, "gradlew.bat") : "./gradlew";
164
+ /** A variable a POSIX shell can't name, as the signing environment's are. */
165
+ const isShellName = (name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
166
+ /**
167
+ * The command that runs the wrapper with `env`. The wrapper's `#!/bin/sh` is
168
+ * dash on Debian and Ubuntu, which silently drops a variable whose name isn't
169
+ * a shell name, such as `ORG_GRADLE_PROJECT_android.injected.signing.store.file`:
170
+ * the build then signs with the project's own config. bash keeps them.
173
171
  */
174
- const getGradleWrapper = () => process.platform.startsWith("win") ? "gradlew.bat" : "./gradlew";
172
+ const gradleCommand = (androidProjectPath, env) => {
173
+ const wrapper = getGradleWrapper(androidProjectPath);
174
+ return wrapper === "./gradlew" && Object.keys(env ?? {}).some((name) => !isShellName(name)) ? ["bash", [wrapper]] : [wrapper, []];
175
+ };
175
176
  /**
176
177
  * Run gradle build with specified tasks and arguments
177
178
  */
178
- async function runGradle({ tasks, logPrefix, args, env, androidProjectPath, appModuleName }) {
179
+ async function runGradle(args) {
180
+ const logFilePath = await runGradleTasks(args);
181
+ return {
182
+ ...await findBuildDirectory({
183
+ androidProjectPath: args.androidProjectPath,
184
+ moduleName: args.appModuleName,
185
+ tasks: args.tasks
186
+ }),
187
+ logFilePath
188
+ };
189
+ }
190
+ /** Runs tasks that leave no artifact to find, and returns the build log, or null. */
191
+ async function runGradleTasks({ tasks, logPrefix, args, env, androidProjectPath, appModuleName, logHeader = [] }) {
179
192
  const gradleArgs = getTaskNames(appModuleName, tasks);
180
193
  gradleArgs.push("-x", "lint");
181
194
  if (args.extraParams) gradleArgs.push(...args.extraParams);
182
- p.log.info([
183
- "Gradle build",
184
- `Project ${path.relative(getCwd(), androidProjectPath) || "."}`,
185
- `App module ${appModuleName}`,
186
- `Tasks ${tasks.join(", ")}`,
187
- "Command",
188
- formatCommand([path.basename(getGradleWrapper()), ...gradleArgs])
189
- ].join("\n"));
190
195
  if ("port" in args && args.port != null) gradleArgs.push(`-PreactNativeDevServerPort=${args.port}`);
191
- const logger = createGradleLogger({ logPrefix });
192
- await logger.start();
193
- try {
194
- const gradle = execa(getGradleWrapper(), gradleArgs, {
195
- cwd: androidProjectPath,
196
- env,
197
- all: true,
198
- buffer: false
199
- });
200
- const outputStream = gradle.all ?? gradle.stdout;
201
- const [gradleResult, loggingResult] = await Promise.allSettled([gradle, outputStream ? logger.processStream(outputStream) : void 0]);
202
- if (gradleResult.status === "rejected") throw gradleResult.reason;
203
- if (loggingResult.status === "rejected") throw loggingResult.reason;
204
- logger.stop();
205
- } catch (e) {
206
- logger.writeError(e);
207
- logger.stop("Build failed", false);
208
- throw new BuildFailedError(`Build failed: ${describeFailure(e)}`, {
209
- logPath: logger.logPath,
210
- summary: logger.failureSummary,
211
- cause: e
196
+ return withWindowsGradleArgs(async (platformArgs) => {
197
+ const finalArgs = [...gradleArgs, ...platformArgs];
198
+ const logger = createGradleLogger({ logPrefix });
199
+ await logger.start({
200
+ title: `Building ${tasks.join(", ")}`,
201
+ header: [
202
+ ...logHeader,
203
+ `Project ${path.relative(getCwd(), androidProjectPath) || "."}`,
204
+ `App module ${appModuleName}`,
205
+ `Tasks ${tasks.join(", ")}`,
206
+ `$ ${formatCommand([path.basename(getGradleWrapper(androidProjectPath)), ...finalArgs])}`,
207
+ ""
208
+ ]
212
209
  });
213
- } finally {
214
- await logger.close();
215
- }
216
- return findBuildDirectory({
217
- androidProjectPath,
218
- moduleName: appModuleName,
219
- tasks
210
+ let logFilePath = null;
211
+ try {
212
+ const [command, prefix] = gradleCommand(androidProjectPath, env);
213
+ const gradle = execa(command, [...prefix, ...finalArgs], {
214
+ cwd: androidProjectPath,
215
+ env,
216
+ all: true,
217
+ buffer: false
218
+ });
219
+ const outputStream = gradle.all ?? gradle.stdout;
220
+ const [gradleResult, loggingResult] = await Promise.allSettled([gradle, outputStream ? logger.processStream(outputStream) : void 0]);
221
+ if (gradleResult.status === "rejected") throw gradleResult.reason;
222
+ if (loggingResult.status === "rejected") throw loggingResult.reason;
223
+ logger.stop(`Built ${tasks.join(", ")}`);
224
+ logFilePath = logger.logFilePath;
225
+ } catch (e) {
226
+ logger.writeError(e);
227
+ const reason = describeFailure(e);
228
+ logger.stop(`Build failed · ${reason.replace(/\.$/, "")}`, false);
229
+ throw new BuildFailedError(`Build failed: ${reason}`, {
230
+ logPath: logger.logPath,
231
+ summary: logger.failureSummary,
232
+ cause: e
233
+ });
234
+ } finally {
235
+ await logger.close();
236
+ }
237
+ return logFilePath;
220
238
  });
221
239
  }
222
240
  /**
@@ -252,6 +270,82 @@ async function getBuildOutputFilePath({ aab, appModuleName, buildDirectory, vari
252
270
  process.exit(1);
253
271
  }
254
272
  //#endregion
273
+ //#region src/utils/channelGradle.ts
274
+ /** Text as a single-quoted Groovy string. */
275
+ const groovyString$1 = (text) => `'${text.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'").replace(/\n/gu, "\\n")}'`;
276
+ /**
277
+ * The init script that makes one build embed `channel`, so no project file
278
+ * changes: on the app module, a task rewrites the variant's merged manifest
279
+ * (AGP's `MERGED_MANIFEST` transform), replacing or adding the
280
+ * `com.hotupdater.CHANNEL` meta-data the SDK reads. It runs after every
281
+ * manifest merged, the app's, a flavor's, an Expo config plugin's and a
282
+ * sandbox build's, so the channel is this one whatever they set.
283
+ */
284
+ const channelInitScript = ({ appModuleName, variant, channel }) => `// Written by hot-updater for one build: the channel it embeds.
285
+ def appModule = ${groovyString$1(`:${appModuleName}`)}
286
+ def variantName = ${groovyString$1(variant.toLowerCase())}
287
+ def channel = ${groovyString$1(channel)}
288
+ allprojects { project ->
289
+ if (project.path != appModule) return
290
+ project.plugins.withId('com.android.application') {
291
+ def components = project.extensions.getByName('androidComponents')
292
+ def mergedManifest = components.getClass().classLoader
293
+ .loadClass('com.android.build.api.artifact.SingleArtifact$MERGED_MANIFEST')
294
+ .getField('INSTANCE').get(null)
295
+ components.onVariants(components.selector().all()) { v ->
296
+ if (v.name.toLowerCase() != variantName) return
297
+ def stamp = project.tasks.register("hotUpdaterChannel\${v.name.capitalize()}", HotUpdaterChannelManifest) {
298
+ it.channel.set(channel)
299
+ }
300
+ v.artifacts.use(stamp)
301
+ .wiredWithFiles({ it.inputManifest }, { it.outputManifest })
302
+ .toTransform(mergedManifest)
303
+ }
304
+ }
305
+ }
306
+
307
+ abstract class HotUpdaterChannelManifest extends DefaultTask {
308
+ @InputFile abstract RegularFileProperty getInputManifest()
309
+ @OutputFile abstract RegularFileProperty getOutputManifest()
310
+ @Input abstract Property<String> getChannel()
311
+
312
+ @TaskAction void stamp() {
313
+ def value = channel.get()
314
+ .replace('&', '&amp;').replace('"', '&quot;')
315
+ .replace('<', '&lt;').replace('>', '&gt;')
316
+ def text = inputManifest.get().asFile.getText('UTF-8')
317
+ .replaceAll(/(?s)<meta-data\\b(?:(?!\\/>|>).)*?android:name="com\\.hotupdater\\.CHANNEL"(?:(?!\\/>|>).)*?(?:\\/>|>.*?<\\/meta-data>)\\s*/, '')
318
+ def entry = "<meta-data android:name=\\"com.hotupdater.CHANNEL\\" android:value=\\"\${value}\\" />"
319
+ def closing = text.lastIndexOf('</application>')
320
+ if (closing < 0) throw new GradleException('The merged manifest has no <application>.')
321
+ outputManifest.get().asFile.setText(text.substring(0, closing) + entry + '\\n ' + text.substring(closing), 'UTF-8')
322
+ }
323
+ }
324
+ `;
325
+ /**
326
+ * Runs `build` with the Gradle arguments that make it embed `channel`: none
327
+ * without one. The init script is written outside the project, and removed
328
+ * after.
329
+ */
330
+ const withChannelGradleArgs = async (channel, scheme, build) => {
331
+ if (channel === void 0) return build([]);
332
+ const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), "hot-updater-channel-"));
333
+ try {
334
+ const script = path.join(directory, "channel.init.gradle");
335
+ await fs.promises.writeFile(script, channelInitScript({
336
+ appModuleName: scheme.appModuleName,
337
+ variant: scheme.variant,
338
+ channel
339
+ }));
340
+ return await build(["--init-script", script]);
341
+ } finally {
342
+ await fs.promises.rm(directory, {
343
+ recursive: true,
344
+ force: true
345
+ });
346
+ }
347
+ };
348
+ //#endregion
255
349
  //#region src/utils/gradleSigning.ts
256
350
  const isDebugVariant = (variant) => /debug$/i.test(variant);
257
351
  /**
@@ -311,6 +405,8 @@ const findAapt2 = (androidProjectPath) => {
311
405
  return fs.readdirSync(buildTools).sort(compareVersions).reverse().map((version) => path.join(buildTools, version, executable)).find((aapt2) => fs.existsSync(aapt2));
312
406
  };
313
407
  const RAW_MARKER = "\" (Raw: \"";
408
+ /** aapt2's output lines: aapt2.exe ends each with CRLF. */
409
+ const outputLines = (output) => output.split(/\r?\n/);
314
410
  /**
315
411
  * An attribute aapt2 prints as `="<value>" (Raw: "<value>")`, given the text
316
412
  * after `="`. aapt2 does not escape the value, so it is the prefix the rest
@@ -338,21 +434,23 @@ const readAttribute = (line, marker) => {
338
434
  * A `<meta-data>` value from `aapt2 dump xmltree` of the manifest: the
339
435
  * literal, or a resource reference such as `@string/channel`. null when the
340
436
  * manifest has none, and undefined when aapt2 printed one it cannot read
341
- * exactly.
437
+ * exactly, or a meta-data whose name it cannot read.
342
438
  */
343
439
  const parseManifestMetaData = (xmltree, name) => {
344
- const lines = xmltree.split("\n");
440
+ const lines = outputLines(xmltree);
441
+ let unreadable = false;
345
442
  for (let i = 0; i < lines.length; i++) {
346
443
  if (!/^\s*E: meta-data\b/.test(lines[i])) continue;
347
444
  let metaDataName = null;
348
445
  let value = null;
349
446
  for (let j = i + 1; j < lines.length && /^\s*A: /.test(lines[j]); j++) {
350
- metaDataName ||= readAttribute(lines[j], ":name(0x01010003)=");
447
+ if (metaDataName === null) metaDataName = readAttribute(lines[j], ":name(0x01010003)=");
351
448
  if (value === null) value = readAttribute(lines[j], ":value(0x01010024)=");
352
449
  }
353
450
  if (metaDataName === name) return value ?? void 0;
451
+ if (metaDataName === void 0) unreadable = true;
354
452
  }
355
- return null;
453
+ return unreadable ? void 0 : null;
356
454
  };
357
455
  /**
358
456
  * The `android:versionName` of the `<manifest>` element in `aapt2 dump
@@ -360,7 +458,7 @@ const parseManifestMetaData = (xmltree, name) => {
360
458
  * without one, and undefined when it cannot be read exactly.
361
459
  */
362
460
  const parseManifestVersionName = (xmltree) => {
363
- for (const line of xmltree.split("\n")) {
461
+ for (const line of outputLines(xmltree)) {
364
462
  const value = readAttribute(line, ":versionName(0x0101021c)=");
365
463
  if (value !== null) return value;
366
464
  }
@@ -380,7 +478,7 @@ const parseManifestVersionCode = (xmltree) => {
380
478
  * table has none aapt2 printed on one line.
381
479
  */
382
480
  const parseResourceString = (resources, reference) => {
383
- const lines = resources.split("\n");
481
+ const lines = outputLines(resources);
384
482
  const start = lines.findIndex((line) => {
385
483
  const [, id, name] = line.match(/^\s*resource (0x[0-9a-f]+) (\S+)/) ?? [];
386
484
  return id !== void 0 && (reference === `@${id}` || reference === `@${name}`);
@@ -510,20 +608,338 @@ const readBuiltVersionCode = async ({ artifactPath, androidProjectPath }) => {
510
608
  }
511
609
  };
512
610
  //#endregion
611
+ //#region src/utils/sandboxManifest.ts
612
+ const MAIN = "android.intent.action.MAIN";
613
+ const LAUNCHER = "android.intent.category.LAUNCHER";
614
+ const SHORTCUTS = "android.app.shortcuts";
615
+ const ANDROID = "android:";
616
+ const asArray = (value) => value === void 0 || value === null || value === "" ? [] : Array.isArray(value) ? value : [value];
617
+ const attribute = (element, name) => {
618
+ const value = element[`${ANDROID}${name}`];
619
+ return typeof value === "string" ? value : void 0;
620
+ };
621
+ const filtersOf = (component) => asArray(component["intent-filter"]).map((filter) => ({
622
+ actions: asArray(filter["action"]),
623
+ categories: asArray(filter["category"]),
624
+ data: asArray(filter["data"]),
625
+ attributes: Object.fromEntries(Object.entries(filter).filter(([name]) => name.startsWith(ANDROID)))
626
+ }));
627
+ const opensAsLauncher = ({ actions, categories }) => actions.some((action) => attribute(action, "name") === MAIN) && categories.some((category) => attribute(category, "name") === LAUNCHER);
628
+ /** Task settings a sandbox activity can't share a task with: what, and how to fix it. */
629
+ const taskRefusal = (name, activity) => {
630
+ const launchMode = attribute(activity, "launchMode");
631
+ if (launchMode === "singleInstance" || launchMode === "singleInstancePerTask") return `Sandbox builds don't support launchMode ${launchMode} on the launcher ${name}.\nUse singleTask or the default launch mode.`;
632
+ if (attribute(activity, "taskAffinity") !== void 0) return `Sandbox builds don't support taskAffinity on the launcher ${name}.\nRemove it from this build variant.`;
633
+ const documents = attribute(activity, "documentLaunchMode");
634
+ if (documents !== void 0 && documents !== "none") return `Sandbox builds don't support documentLaunchMode ${documents} on the launcher ${name}.\nRemove it from this build variant.`;
635
+ return null;
636
+ };
637
+ /**
638
+ * The launcher entry of a variant's merged manifest, which already holds what
639
+ * its flavors, build type and libraries declare. It refuses what a sandbox
640
+ * build can't take over: none or several entries, a filter it can't move whole,
641
+ * and task settings its activity can't share a task with.
642
+ */
643
+ const resolveSandboxLauncher = (mergedManifest) => {
644
+ const application = new XMLParser({
645
+ ignoreAttributes: false,
646
+ attributeNamePrefix: ""
647
+ }).parse(mergedManifest)?.manifest?.application;
648
+ const activities = asArray(application?.["activity"]);
649
+ const aliases = asArray(application?.["activity-alias"]);
650
+ const entries = [...activities.map((element) => ({
651
+ kind: "activity",
652
+ element
653
+ })), ...aliases.map((element) => ({
654
+ kind: "activity-alias",
655
+ element
656
+ }))].flatMap(({ kind, element }) => {
657
+ const filters = filtersOf(element).filter(opensAsLauncher);
658
+ return filters.length === 0 ? [] : [{
659
+ kind,
660
+ element,
661
+ filters
662
+ }];
663
+ });
664
+ const names = entries.map(({ element }) => attribute(element, "name") ?? "?");
665
+ 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.");
666
+ 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.`);
667
+ const { kind, element, filters } = entries[0];
668
+ const name = names[0];
669
+ 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.`);
670
+ 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.`);
671
+ const targetActivity = kind === "activity-alias" ? attribute(element, "targetActivity") : void 0;
672
+ const activity = kind === "activity" ? element : activities.find((item) => attribute(item, "name") === targetActivity);
673
+ 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.`);
674
+ const refusal = taskRefusal(name, activity);
675
+ if (refusal !== null) throw new Error(refusal);
676
+ const launcherProcess = attribute(activity, "process");
677
+ 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.`);
678
+ const shortcuts = asArray(element["meta-data"]).find((item) => attribute(item, "name") === SHORTCUTS);
679
+ const label = attribute(element, "label");
680
+ const icon = attribute(element, "icon");
681
+ const roundIcon = attribute(element, "roundIcon");
682
+ const shortcutsResource = shortcuts && attribute(shortcuts, "resource");
683
+ return {
684
+ kind,
685
+ name,
686
+ ...targetActivity === void 0 ? {} : { targetActivity },
687
+ filter: filters[0],
688
+ ...label === void 0 ? {} : { label },
689
+ ...icon === void 0 ? {} : { icon },
690
+ ...roundIcon === void 0 ? {} : { roundIcon },
691
+ ...shortcutsResource === void 0 ? {} : { shortcuts: shortcutsResource }
692
+ };
693
+ };
694
+ const COMPONENTS = [
695
+ "activity",
696
+ "activity-alias",
697
+ "service",
698
+ "receiver"
699
+ ];
700
+ /**
701
+ * The URL schemes a variant's merged manifest declares in its components'
702
+ * intent filters, in lower case: a sandbox build registers none of them.
703
+ */
704
+ const declaredUrlSchemes = (mergedManifest) => {
705
+ const application = new XMLParser({
706
+ ignoreAttributes: false,
707
+ attributeNamePrefix: ""
708
+ }).parse(mergedManifest)?.manifest?.application;
709
+ return COMPONENTS.flatMap((component) => asArray(application?.[component])).flatMap((element) => filtersOf(element).flatMap(({ data }) => data.flatMap((item) => {
710
+ const scheme = attribute(item, "scheme");
711
+ return scheme === void 0 ? [] : [scheme.toLowerCase()];
712
+ })));
713
+ };
714
+ const xml = (text) => text.replace(/&/gu, "&amp;").replace(/"/gu, "&quot;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;");
715
+ const attributesOf = (element) => Object.entries(element).filter(([, value]) => typeof value === "string").map(([name, value]) => ` ${name}="${xml(value)}"`).join("");
716
+ /** A launcher filter, element by element: the merger matches a filter by content. */
717
+ const filterXml = ({ actions, categories, data, attributes }, extra = "") => [
718
+ `<intent-filter${attributesOf(attributes)}${extra}>`,
719
+ ...actions.map((item) => ` <action${attributesOf(item)} />`),
720
+ ...categories.map((item) => ` <category${attributesOf(item)} />`),
721
+ ...data.map((item) => ` <data${attributesOf(item)} />`),
722
+ "</intent-filter>"
723
+ ].map((line) => ` ${line}`).join("\n");
724
+ const optional = (name, value) => value === void 0 ? "" : ` android:${name}="${xml(value)}"`;
725
+ /**
726
+ * The manifest a sandbox build overlays on the app's, which keeps the app's
727
+ * channel: a sandbox build embeds the project's, as any build does. The launcher's
728
+ * filter, label, icon and static shortcuts move to the sandbox's activity, which
729
+ * also takes the links of `urlScheme`, which its `<meta-data>` names for the
730
+ * build to read; the rest of the app's activity stays, so its own links still
731
+ * reach it.
732
+ * The dev server is plain http, which a project's network security config can
733
+ * still refuse: the screen then says so.
734
+ */
735
+ const sandboxManifestOverlay = ({ urlScheme, launcher }) => `<?xml version="1.0" encoding="utf-8"?>
736
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
737
+ <application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic">
738
+ <meta-data android:name="${SANDBOX_META_DATA}" android:value="true" />
739
+ <activity android:name="${SANDBOX_ACTIVITY}" android:exported="true" android:launchMode="singleTop" android:theme="@style/HotUpdaterSandboxTheme" android:configChanges="density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:enableOnBackInvokedCallback="true"${optional("label", launcher.label)}${optional("icon", launcher.icon)}${optional("roundIcon", launcher.roundIcon)}>
740
+ ${filterXml(launcher.filter)}
741
+ <intent-filter>
742
+ <action android:name="android.intent.action.VIEW" />
743
+ <category android:name="android.intent.category.DEFAULT" />
744
+ <category android:name="android.intent.category.BROWSABLE" />
745
+ <data android:scheme="${xml(urlScheme)}" />
746
+ </intent-filter>
747
+ <meta-data android:name="com.hotupdater.sandbox.HOST_ACTIVITY" android:value="${xml(launcher.name)}" />
748
+ <meta-data android:name="${SANDBOX_URL_SCHEME_META_DATA}" android:value="${xml(urlScheme)}" />${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" android:resource="${xml(launcher.shortcuts)}" />`}
749
+ </activity>
750
+ <${launcher.kind} android:name="${xml(launcher.name)}"${optional("targetActivity", launcher.targetActivity)}>
751
+ ${filterXml(launcher.filter, " tools:node=\"remove\"")}${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" tools:node="remove" />`}
752
+ </${launcher.kind}>
753
+ <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" />
754
+ <provider android:name="com.hotupdater.HotUpdaterSandboxProcess" android:authorities="\${applicationId}.hotupdater.sandbox" android:exported="false" />
755
+ </application>
756
+ </manifest>
757
+ `;
758
+ /** Newest first: the manifest of the task that ran last, under `directory`. */
759
+ const manifestsUnder = (directory) => {
760
+ if (!fs.existsSync(directory)) return [];
761
+ return fs.readdirSync(directory, { recursive: true }).map(String).filter((file) => path.basename(file) === "AndroidManifest.xml").map((file) => path.join(directory, file)).sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
762
+ };
763
+ /** The Gradle task that merges a variant's manifest. */
764
+ const mergeManifestTask = (variant) => `process${variant.charAt(0).toUpperCase()}${variant.slice(1)}MainManifest`;
765
+ /**
766
+ * The manifest the merge task of `variant` wrote: AGP 7 and 8 keep it under
767
+ * `build/intermediates/merged_manifest`, in a directory per variant.
768
+ */
769
+ const readMergedManifest = ({ androidProjectPath, appModuleName, variant }) => {
770
+ const variantDirectory = `${variant.charAt(0).toLowerCase()}${variant.slice(1)}`;
771
+ const intermediates = path.join(androidProjectPath, appModuleName, "build/intermediates");
772
+ const [manifest] = ["merged_manifest", "merged_manifests"].flatMap((name) => manifestsUnder(path.join(intermediates, name, variantDirectory)));
773
+ 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.`);
774
+ return fs.readFileSync(manifest, "utf-8");
775
+ };
776
+ //#endregion
777
+ //#region src/utils/sandboxGradle.ts
778
+ const UNSUPPORTED_DSL = `Sandbox builds don't support AGP 9's default DSL yet.
779
+ Set android.newDsl=false in android/gradle.properties.`;
780
+ /** The message when the build type has a manifest the overlay would replace. */
781
+ const ownManifest = (manifest) => `A sandbox build can't merge with ${manifest}.\nMove what it declares to src/main/AndroidManifest.xml.`;
782
+ /** The message when no project compiled the SDK from source, which a dev server needs. */
783
+ const PREBUILT_SDK = `This app takes @hot-updater/react-native as a prebuilt AAR, and a sandbox build compiles the SDK from source.
784
+ Add the SDK's autolinked project to this build instead of the AAR.`;
785
+ /** Text as a single-quoted Groovy string. */
786
+ const groovyString = (text) => `'${text.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'").replace(/\n/gu, "\\n")}'`;
787
+ /**
788
+ * The init script of one sandbox build, so no project file changes: on the app
789
+ * module, it appends the sandbox's suffix to defaultConfig, where AGP puts any
790
+ * flavor's and build type's after it, and adds `overlay` to the variant's build
791
+ * type. It runs in `finalizeDsl`, after the project's own settings.
792
+ */
793
+ const sandboxInitScript = ({ appModuleName, variant, overlay, minVersionCode }) => `// Written by hot-updater for one sandbox build.
794
+ def appModule = ${groovyString(`:${appModuleName}`)}
795
+ def variant = ${groovyString(variant.toLowerCase())}
796
+ def overlay = new File(${groovyString(overlay)})
797
+ def minVersionCode = ${minVersionCode ?? "null"}
798
+ allprojects { project ->
799
+ if (project.path != appModule) return
800
+ // In this build alone: an init script also runs for React Native's included
801
+ // Gradle plugin. The SDK's sandbox script sets this on the project it compiles.
802
+ gradle.taskGraph.whenReady {
803
+ if (!gradle.rootProject.ext.has('hotUpdaterSandboxSdkProject')) {
804
+ throw new GradleException(${groovyString(PREBUILT_SDK)})
805
+ }
806
+ }
807
+ project.plugins.withId('com.android.application') {
808
+ def components = project.extensions.getByName('androidComponents')
809
+ if (components.pluginVersion.major >= 9 && project.findProperty('android.newDsl')?.toString() != 'false') {
810
+ throw new GradleException(${groovyString(UNSUPPORTED_DSL)})
811
+ }
812
+ components.finalizeDsl { dsl ->
813
+ def buildType = dsl.buildTypes.collect { it.name }
814
+ .findAll { variant.endsWith(it.toLowerCase()) }
815
+ .max { it.length() }
816
+ if (buildType == null) {
817
+ throw new GradleException("No build type of \${project.path} builds variant \${variant}.")
818
+ }
819
+ def manifest = dsl.sourceSets.getByName(buildType).manifest
820
+ def own = manifest.srcFile
821
+ if (own.exists()) {
822
+ throw new GradleException(${groovyString(ownManifest("@MANIFEST@"))}.replace('@MANIFEST@', 'android/' + project.rootDir.toPath().relativize(own.toPath())))
823
+ }
824
+ dsl.defaultConfig.applicationIdSuffix = (dsl.defaultConfig.applicationIdSuffix ?: '') + ${groovyString(SANDBOX_APPLICATION_ID_SUFFIX)}
825
+ manifest.srcFile(overlay)
826
+ if (minVersionCode != null) {
827
+ dsl.defaultConfig.versionCode = Math.max(dsl.defaultConfig.versionCode ?: 0, minVersionCode)
828
+ dsl.productFlavors.each { flavor ->
829
+ if (flavor.versionCode != null) flavor.versionCode = Math.max(flavor.versionCode, minVersionCode)
830
+ }
831
+ }
832
+ }
833
+ }
834
+ }
835
+ `;
836
+ /**
837
+ * Runs `build` with the Gradle arguments of a scheme: none for a normal one. A
838
+ * sandbox scheme's attach the SDK's sandbox layer and name the init script,
839
+ * written outside the project with its manifest overlay, and removed after.
840
+ * Kotlin compiles from scratch, since the sandbox layer's sources come and go.
841
+ * `readEffectiveManifest` is the variant's merged manifest before the overlay,
842
+ * which the overlay takes the launcher from.
843
+ */
844
+ const withSandboxGradleArgs = async (scheme, readEffectiveManifest, build, { minVersionCode } = {}) => {
845
+ if (!scheme.sandbox) return build([]);
846
+ 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.`);
847
+ const effectiveManifest = await readEffectiveManifest();
848
+ const launcher = resolveSandboxLauncher(effectiveManifest);
849
+ const urlScheme = scheme.sandboxUrlScheme ?? sandboxUrlSchemeOf(scheme.packageName);
850
+ if (declaredUrlSchemes(effectiveManifest).includes(urlScheme.toLowerCase())) throw new Error(`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.`);
851
+ const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), "hot-updater-sandbox-"));
852
+ try {
853
+ const overlay = path.join(directory, "AndroidManifest.xml");
854
+ const initScript = path.join(directory, "sandbox.init.gradle");
855
+ await fs.promises.writeFile(overlay, sandboxManifestOverlay({
856
+ urlScheme,
857
+ launcher
858
+ }));
859
+ await fs.promises.writeFile(initScript, sandboxInitScript({
860
+ appModuleName: scheme.appModuleName,
861
+ variant: scheme.variant,
862
+ overlay,
863
+ ...minVersionCode === void 0 ? {} : { minVersionCode }
864
+ }));
865
+ return await build([
866
+ "--init-script",
867
+ initScript,
868
+ `-PhotUpdaterSandbox=${scheme.hotUpdaterSchemeName}`,
869
+ "-Pkotlin.incremental=false"
870
+ ]);
871
+ } finally {
872
+ await fs.promises.rm(directory, {
873
+ recursive: true,
874
+ force: true
875
+ });
876
+ }
877
+ };
878
+ /** The major version of the Android Gradle Plugin the project pins, or null. */
879
+ const readAgpMajor = (androidProjectPath) => {
880
+ const rootBuild = ["build.gradle", "build.gradle.kts"].map((file) => path.join(androidProjectPath, file)).filter((file) => fs.existsSync(file)).map((file) => fs.readFileSync(file, "utf-8")).join("\n");
881
+ const pinned = /com\.android\.tools\.build:gradle:(\d+)/u.exec(rootBuild);
882
+ if (pinned) return Number(pinned[1]);
883
+ try {
884
+ const manifest = createRequire(path.join(androidProjectPath, "package.json")).resolve("react-native/package.json");
885
+ const catalog = fs.readFileSync(path.join(path.dirname(manifest), "gradle/libs.versions.toml"), "utf-8");
886
+ const agp = /^\s*agp\s*=\s*"(\d+)/mu.exec(catalog);
887
+ return agp ? Number(agp[1]) : null;
888
+ } catch {
889
+ return null;
890
+ }
891
+ };
892
+ /**
893
+ * Why a sandbox build of a scheme can't work, read from the project's files
894
+ * before anything is built, or null. The init script checks again, with what
895
+ * Gradle actually resolved.
896
+ */
897
+ const findSandboxGradleBlocker = ({ variant = "Release", appModuleName = "app" }) => {
898
+ const androidProjectPath = path.join(getCwd(), "android");
899
+ if (!fs.existsSync(androidProjectPath)) return null;
900
+ const properties = path.join(androidProjectPath, "gradle.properties");
901
+ const newDsl = fs.existsSync(properties) ? /^\s*android\.newDsl\s*=\s*(\S+)/mu.exec(fs.readFileSync(properties, "utf-8"))?.[1] : void 0;
902
+ if (newDsl === "true" || newDsl === void 0 && (readAgpMajor(androidProjectPath) ?? 0) >= 9) return UNSUPPORTED_DSL;
903
+ const buildType = /([A-Z]?[a-z0-9]+)$/u.exec(variant)?.[1]?.toLowerCase();
904
+ const manifest = `${appModuleName}/src/${buildType}/AndroidManifest.xml`;
905
+ return buildType && fs.existsSync(path.join(androidProjectPath, manifest)) ? ownManifest(`android/${manifest}`) : null;
906
+ };
907
+ //#endregion
513
908
  //#region src/buildAndroid.ts
514
- const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), credentials }) => {
909
+ const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), credentials, logHeader, minVersionCode, channel }) => {
515
910
  const androidProjectPath = path.join(getCwd(), "android");
516
- const result = await runGradle({
517
- args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`] },
518
- env: await resolveGradleSigningEnv({
519
- schemeConfig,
520
- credentials
521
- }),
911
+ const env = await resolveGradleSigningEnv({
912
+ schemeConfig,
913
+ credentials
914
+ });
915
+ const result = await withSandboxGradleArgs(schemeConfig, async () => {
916
+ await runGradleTasks({
917
+ args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`] },
918
+ env,
919
+ appModuleName: schemeConfig.appModuleName,
920
+ tasks: [mergeManifestTask(schemeConfig.variant)],
921
+ logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-manifest`,
922
+ androidProjectPath,
923
+ logHeader
924
+ });
925
+ return readMergedManifest({
926
+ androidProjectPath,
927
+ appModuleName: schemeConfig.appModuleName,
928
+ variant: schemeConfig.variant
929
+ });
930
+ }, (sandboxArgs) => withChannelGradleArgs(channel, schemeConfig, (channelArgs) => runGradle({
931
+ args: { extraParams: [
932
+ `-PMIN_BUNDLE_ID=${minBundleId}`,
933
+ ...sandboxArgs,
934
+ ...channelArgs
935
+ ] },
936
+ env,
522
937
  appModuleName: schemeConfig.appModuleName,
523
938
  tasks: schemeConfig.aab ? [`bundle${schemeConfig.variant}`] : [`assemble${schemeConfig.variant}`],
524
939
  logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-build`,
525
- androidProjectPath
526
- });
940
+ androidProjectPath,
941
+ logHeader
942
+ })), minVersionCode === void 0 ? {} : { minVersionCode });
527
943
  return {
528
944
  ...result,
529
945
  builtApp: await readBuiltApp({
@@ -533,6 +949,105 @@ const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), c
533
949
  };
534
950
  };
535
951
  //#endregion
952
+ //#region src/device.ts
953
+ /** The SDK's adb, or the one on the PATH without an SDK in the environment. */
954
+ const adbPath = () => {
955
+ const sdk = process.env["ANDROID_HOME"] || process.env["ANDROID_SDK_ROOT"];
956
+ const executable = process.platform.startsWith("win") ? "adb.exe" : "adb";
957
+ const fromSdk = sdk && path.join(sdk, "platform-tools", executable);
958
+ return fromSdk && fs.existsSync(fromSdk) ? fromSdk : executable;
959
+ };
960
+ const adb = async (args) => {
961
+ try {
962
+ return (await execa(adbPath(), args)).stdout;
963
+ } catch (error) {
964
+ const { code, stderr, stdout, shortMessage } = error;
965
+ if (code === "ENOENT") throw new Error("adb isn't installed.\nInstall Android platform-tools, or set ANDROID_HOME.");
966
+ throw new Error(stderr?.trim() || stdout?.trim() || shortMessage || String(error));
967
+ }
968
+ };
969
+ /** What `adb devices` lists. */
970
+ const listAdbDevices = async () => (await adb(["devices"])).split("\n").slice(1).map((line) => line.trim().split(/\s+/u)).flatMap(([serial, state]) => serial && state ? [{
971
+ serial,
972
+ state
973
+ }] : []);
974
+ /**
975
+ * The device to install on: `serial`, as adb's own `ANDROID_SERIAL` names it
976
+ * too, or else the only one that takes commands.
977
+ */
978
+ const selectAdbDevice = (devices, serial = process.env["ANDROID_SERIAL"] || void 0) => {
979
+ if (serial !== void 0) {
980
+ const device = devices.find((candidate) => candidate.serial === serial);
981
+ if (device === void 0) throw new Error(`${serial} isn't connected.\nList them: adb devices`);
982
+ if (device.state !== "device") throw new Error(`${serial} is ${device.state}.\nList them: adb devices`);
983
+ return device;
984
+ }
985
+ const ready = devices.filter(({ state }) => state === "device");
986
+ const [only] = ready;
987
+ 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.");
988
+ if (ready.length > 1) throw new Error([
989
+ `${ready.length} Android devices are connected:`,
990
+ ...ready.map(({ serial }) => ` ${serial}`),
991
+ "Pick one with --device <serial>."
992
+ ].join("\n"));
993
+ return only;
994
+ };
995
+ /** A failure adb reports for an install another install of the app stands in the way of. */
996
+ const NEEDS_UNINSTALL = /^INSTALL_FAILED_(UPDATE_INCOMPATIBLE|VERSION_DOWNGRADE)\b/u;
997
+ const LAUNCHER_CATEGORY = "android.intent.category.LAUNCHER";
998
+ /** An application ID's form, checked before it reaches the device's shell. */
999
+ const APP_ID = /^[A-Za-z][A-Za-z0-9_.]*$/u;
1000
+ /** `<application ID>/<activity>`, as `resolve-activity --brief` prints it. */
1001
+ const ACTIVITY = /^[A-Za-z0-9_.]+\/[A-Za-z0-9_.$]+$/u;
1002
+ /**
1003
+ * Installs an APK on a device, and opens its launcher activity. `appId` is
1004
+ * the APK's own application ID, whatever suffix its build gave it.
1005
+ */
1006
+ const installOnAndroidDevice = async ({ serial, apkPath, appId }) => {
1007
+ if (!APP_ID.test(appId)) throw new Error(`The APK's application ID isn't valid: ${appId}`);
1008
+ try {
1009
+ await adb([
1010
+ "-s",
1011
+ serial,
1012
+ "install",
1013
+ "-r",
1014
+ apkPath
1015
+ ]);
1016
+ } catch (error) {
1017
+ const message = error instanceof Error ? error.message : String(error);
1018
+ const failure = /Failure \[([^\]]+)\]/u.exec(message)?.[1] ?? message;
1019
+ 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}`);
1020
+ }
1021
+ const activity = (await adb([
1022
+ "-s",
1023
+ serial,
1024
+ "shell",
1025
+ "cmd",
1026
+ "package",
1027
+ "resolve-activity",
1028
+ "--brief",
1029
+ "-c",
1030
+ LAUNCHER_CATEGORY,
1031
+ appId
1032
+ ])).trim().split("\n").at(-1)?.trim();
1033
+ if (activity === void 0 || !ACTIVITY.test(activity)) throw new Error(`${appId} is installed, and has no launcher activity to open.`);
1034
+ const started = await adb([
1035
+ "-s",
1036
+ serial,
1037
+ "shell",
1038
+ "am",
1039
+ "start",
1040
+ "-a",
1041
+ "android.intent.action.MAIN",
1042
+ "-c",
1043
+ LAUNCHER_CATEGORY,
1044
+ "-n",
1045
+ `'${activity}'`
1046
+ ]);
1047
+ const error = /^Error: .*$/mu.exec(started)?.[0];
1048
+ if (error !== void 0) throw new Error(`${appId} is installed, and didn't open. ${error}`);
1049
+ };
1050
+ //#endregion
536
1051
  //#region src/uploadToPlay.ts
537
1052
  const API_URL = "https://androidpublisher.googleapis.com";
538
1053
  /** Where Google serves resumable upload sessions, as its docs show both. */
@@ -636,7 +1151,7 @@ const explain = (error, packageName) => {
636
1151
  if (status === 401 || /does not have permission/i.test(apiMessage)) return new Error([
637
1152
  `The Play service account can't release ${packageName}.`,
638
1153
  "Invite its email in Play Console (Users and permissions) to release to",
639
- "testing tracks, and enable the Google Play Android Developer API."
1154
+ "testing tracks (Release to production for production), and enable the Google Play Android Developer API."
640
1155
  ].join("\n"), { cause: error });
641
1156
  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 });
642
1157
  if (/version code .*(already been used|already used)/i.test(apiMessage)) return new PlayVersionCodeUsedError({ cause: error });
@@ -645,8 +1160,8 @@ const explain = (error, packageName) => {
645
1160
  /**
646
1161
  * Requests to the Google Play Developer API for `packageName`, as the
647
1162
  * service account: each carries an access token, exchanged for a signed
648
- * assertion and replaced well before it expires. The key issuer checks a
649
- * new key's access with it too.
1163
+ * assertion and replaced well before it expires. `checkPlayAccess`
1164
+ * checks a key's access with it too.
650
1165
  */
651
1166
  const createPlayClient = ({ json, packageName, fetch }) => {
652
1167
  const account = readServiceAccount(json);
@@ -695,53 +1210,128 @@ const createPlayClient = ({ json, packageName, fetch }) => {
695
1210
  };
696
1211
  };
697
1212
  /**
698
- * Whether Google Play's internal testing track already releases the
699
- * `.aab`'s version code, as when a reused native build was uploaded
700
- * before. It reads the track in an edit it then deletes, changing nothing.
1213
+ * Play Console's page that invites `email` as a user. `_` stands for the
1214
+ * developer account the browser is signed in to, so no ID is needed.
701
1215
  */
702
- const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccount: { json }, fetch = globalThis.fetch }) => {
703
- const { app, request } = createPlayClient({
704
- json,
705
- packageName,
706
- fetch
1216
+ const playConsoleInviteUrl = (email) => `https://play.google.com/console/u/0/developers/_/users-and-permissions?invite=${encodeURIComponent(email)}`;
1217
+ const readClientEmail = (json) => {
1218
+ try {
1219
+ const { client_email } = JSON.parse(json);
1220
+ return typeof client_email === "string" ? client_email : "";
1221
+ } catch {
1222
+ return "";
1223
+ }
1224
+ };
1225
+ /**
1226
+ * Checks once whether the service account's key reaches `packageName`: it
1227
+ * opens an edit of the app and deletes it again, which changes nothing.
1228
+ * Throws only for what says nothing about access, such as a network error.
1229
+ */
1230
+ const checkPlayAccess = async ({ serviceAccount: { json }, packageName, fetch = globalThis.fetch }) => {
1231
+ const email = readClientEmail(json);
1232
+ const refused = (error) => ({
1233
+ status: "refused",
1234
+ email,
1235
+ reason: error instanceof Error ? error.message : String(error)
707
1236
  });
708
- let editId;
1237
+ let play;
709
1238
  try {
710
- ({id: editId} = await request("Opening a Google Play edit", "POST", `${API_URL}${app}/edits`, {}));
1239
+ play = createPlayClient({
1240
+ json,
1241
+ packageName,
1242
+ fetch
1243
+ });
711
1244
  } catch (error) {
712
- throw explain(error, packageName);
1245
+ return refused(error);
713
1246
  }
714
- const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
715
1247
  try {
716
- const { releases = [] } = await request("Reading the internal track", "GET", `${edit}/tracks/${INTERNAL_TRACK}`);
717
- return releases.some(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
1248
+ await play.authorization();
718
1249
  } catch (error) {
719
- throw explain(error, packageName);
720
- } finally {
721
- await request("Deleting the Google Play edit", "DELETE", edit).catch(() => void 0);
1250
+ if (error instanceof TypeError) throw error;
1251
+ return refused(error);
1252
+ }
1253
+ const edits = `${API_URL}${play.app}/edits`;
1254
+ try {
1255
+ const edit = await play.request(`Opening an edit of ${packageName}`, "POST", edits, {});
1256
+ if (edit?.id) await play.request("Deleting the edit", "DELETE", `${edits}/${encodeURIComponent(edit.id)}`).catch(() => {});
1257
+ return { status: "ready" };
1258
+ } catch (error) {
1259
+ if (error instanceof GooglePlayError) {
1260
+ if (error.status === 401 || error.status === 403) return {
1261
+ status: "denied",
1262
+ email
1263
+ };
1264
+ if (error.status === 404) return {
1265
+ status: "not-found",
1266
+ email
1267
+ };
1268
+ }
1269
+ throw error;
722
1270
  }
723
1271
  };
724
1272
  /**
725
- * Whether Google Play releases any version of `packageName` on any track,
726
- * which means Play has the app's upload key. It reads the tracks in an edit
727
- * it then deletes, changing nothing.
1273
+ * Reads the app in an edit it then deletes, changing nothing.
728
1274
  */
729
- const hasPlayReleases = async ({ packageName, serviceAccount: { json }, fetch = globalThis.fetch }) => {
1275
+ const readInEdit = async ({ packageName, serviceAccount: { json }, fetch }, read) => {
730
1276
  const { app, request } = createPlayClient({
731
1277
  json,
732
1278
  packageName,
733
1279
  fetch
734
1280
  });
735
- const { id: editId } = await request("Opening a Google Play edit", "POST", `${API_URL}${app}/edits`, {});
1281
+ let editId;
1282
+ try {
1283
+ ({id: editId} = await request("Opening a Google Play edit", "POST", `${API_URL}${app}/edits`, {}));
1284
+ } catch (error) {
1285
+ throw explain(error, packageName);
1286
+ }
736
1287
  const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
737
1288
  try {
738
- const { tracks = [] } = await request("Reading the tracks", "GET", `${edit}/tracks`);
739
- return tracks.some(({ releases = [] }) => releases.some(({ versionCodes = [] }) => versionCodes.length > 0));
1289
+ return await read(request, edit);
1290
+ } catch (error) {
1291
+ throw explain(error, packageName);
740
1292
  } finally {
741
1293
  await request("Deleting the Google Play edit", "DELETE", edit).catch(() => void 0);
742
1294
  }
743
1295
  };
744
1296
  /**
1297
+ * The status of the selected track's release holding `versionCode`, defaulting
1298
+ * to internal testing, such as
1299
+ * `completed` or `draft`, or null when the track doesn't hold it: never
1300
+ * uploaded, or replaced by a newer release, which testers get instead.
1301
+ */
1302
+ const readPlayTrackRelease = ({ versionCode, track = INTERNAL_TRACK, packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
1303
+ packageName,
1304
+ serviceAccount,
1305
+ fetch
1306
+ }, async (request, edit) => {
1307
+ const { releases = [] } = await request(`Reading the ${track} track`, "GET", `${edit}/tracks/${encodeURIComponent(track)}`);
1308
+ const release = releases.find(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
1309
+ return release ? release.status ?? "completed" : null;
1310
+ });
1311
+ /**
1312
+ * Whether Google Play's internal testing track already releases the
1313
+ * `.aab`'s version code, as when a reused native build was uploaded before.
1314
+ */
1315
+ const findPlayInternalRelease = async (options) => await readPlayTrackRelease(options) !== null;
1316
+ /**
1317
+ * The highest version code Google Play has taken for the app, on any track,
1318
+ * or null with none: a new `.aab` needs one above it.
1319
+ */
1320
+ const readPlayHighestVersionCode = ({ packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
1321
+ packageName,
1322
+ serviceAccount,
1323
+ fetch
1324
+ }, async (request, edit) => {
1325
+ const { bundles = [] } = await request("Reading the app's bundles", "GET", `${edit}/bundles`);
1326
+ const codes = bundles.flatMap(({ versionCode }) => versionCode ?? []);
1327
+ return codes.length > 0 ? Math.max(...codes) : null;
1328
+ });
1329
+ /**
1330
+ * The link that opts a tester in to the app's testing tracks. A build on the
1331
+ * internal track installs through it, for the testers Play Console lists.
1332
+ */
1333
+ const playTestingUrl = (packageName) => `https://play.google.com/apps/testing/${encodeURIComponent(packageName)}`;
1334
+ /**
745
1335
  * The common name of every Android debug certificate: Android Studio's and
746
1336
  * the Android Gradle plugin's (`CN=Android Debug, O=Android, C=US`), and React
747
1337
  * Native's template `debug.keystore` (`CN=Android Debug, OU=Android,
@@ -769,12 +1359,13 @@ const assertPlaySigned = async (aabPath) => {
769
1359
  ].join("\n"));
770
1360
  };
771
1361
  /**
772
- * Uploads an `.aab` to Google Play's internal testing track with the Google
1362
+ * Uploads or promotes an `.aab` to a Google Play track with the Google
773
1363
  * Play Developer API: it opens an edit, uploads the bundle, releases its
774
- * version code to the internal track, and commits the edit, which it
1364
+ * version code to the selected track, and commits the edit, which it
775
1365
  * deletes again when any step fails. The service account stays in memory.
776
1366
  */
777
- const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fetch = globalThis.fetch, commitRetryDelayMs = 2e3 }) => {
1367
+ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fetch = globalThis.fetch, commitRetryDelayMs = 2e3, track = "internal", rollout = 100, existingVersionCode }) => {
1368
+ if (!Number.isInteger(rollout) || rollout < 1 || rollout > 100 || track === "internal" && rollout < 100) throw new Error(track === "internal" && rollout < 100 ? "Play internal testing does not support staged rollout." : "Rollout must be an integer from 1 to 100.");
778
1369
  const { app, authorization, request } = createPlayClient({
779
1370
  json,
780
1371
  packageName,
@@ -788,20 +1379,28 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
788
1379
  }
789
1380
  const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
790
1381
  try {
791
- p.log.info(`Uploading ${packageName}'s .aab to Google Play`);
792
- const versionCode = await uploadBundle({
1382
+ p.log.info(`${existingVersionCode === void 0 ? "Uploading" : "Promoting"} ${packageName} to Google Play`);
1383
+ const versionCode = existingVersionCode ?? await uploadBundle({
793
1384
  aabPath,
794
1385
  sessionUrl: `${API_URL}/upload${app}/edits/${encodeURIComponent(editId)}/bundles?uploadType=resumable`,
795
1386
  authorization,
796
1387
  fetch
797
1388
  });
1389
+ const existingRelease = (existingVersionCode === void 0 ? void 0 : await request("Reading the Google Play track", "GET", `${edit}/tracks/${track}`))?.releases?.find((release) => release.versionCodes?.includes(String(versionCode)));
798
1390
  const release = async (status) => {
799
- await request("Releasing to the internal track", "PUT", `${edit}/tracks/${INTERNAL_TRACK}`, {
800
- track: INTERNAL_TRACK,
801
- releases: [{
802
- versionCodes: [String(versionCode)],
803
- status
804
- }]
1391
+ const updatedRelease = {
1392
+ ...existingRelease,
1393
+ versionCodes: existingRelease?.versionCodes ?? [String(versionCode)],
1394
+ status
1395
+ };
1396
+ if (status === "inProgress") updatedRelease.userFraction = rollout / 100;
1397
+ else {
1398
+ delete updatedRelease.userFraction;
1399
+ delete updatedRelease.countryTargeting;
1400
+ }
1401
+ await request(`Releasing to the ${track} track`, "PUT", `${edit}/tracks/${track}`, {
1402
+ track,
1403
+ releases: [updatedRelease]
805
1404
  });
806
1405
  await commit({
807
1406
  request,
@@ -810,10 +1409,11 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
810
1409
  });
811
1410
  };
812
1411
  try {
813
- await release("completed");
1412
+ const status = rollout < 100 ? "inProgress" : "completed";
1413
+ await release(status);
814
1414
  return {
815
1415
  versionCode,
816
- status: "completed"
1416
+ status
817
1417
  };
818
1418
  } catch (error) {
819
1419
  if (!(error instanceof GooglePlayError) || !DRAFT_APP_ERRORS.some((message) => error.apiMessage.includes(message))) throw error;
@@ -845,7 +1445,7 @@ const commit = async ({ request, edit, retryDelayMs }) => {
845
1445
  if (!(error instanceof GooglePlayError) || error.status >= 500 || error.status === 429) throw new Error([
846
1446
  "Google Play didn't confirm the release.",
847
1447
  error instanceof Error ? error.message : String(error),
848
- "Check internal testing in Play Console before you upload it again."
1448
+ "Check the release in Play Console before you upload it again."
849
1449
  ].join("\n"), { cause: error });
850
1450
  if (error.status !== 400) throw error;
851
1451
  if (!changesNotSentForReview && error.apiMessage.includes(NEEDS_CHANGES_NOT_SENT_FOR_REVIEW)) {
@@ -1084,515 +1684,29 @@ const extractBuiltInBundle = async ({ artifactPath, outputPath }) => {
1084
1684
  await (entry.method === 8 ? pipeline(source, createInflateRaw(), fs.createWriteStream(outputPath)) : pipeline(source, fs.createWriteStream(outputPath)));
1085
1685
  };
1086
1686
  //#endregion
1087
- //#region src/google/googleApi.ts
1088
- /** A Google Cloud or Google Play API request that failed, with Google's error. */
1089
- var GoogleApiError = class extends Error {
1090
- status;
1091
- /** Google's canonical status, such as `PERMISSION_DENIED`. */
1092
- apiStatus;
1093
- apiMessage;
1094
- /** The `ErrorInfo` reasons, such as `SERVICE_DISABLED`. */
1095
- reasons;
1096
- /** The `PreconditionFailure` violation types, such as an org policy constraint. */
1097
- violations;
1098
- /** The `ErrorInfo` consumer of a disabled service, such as `projects/123`. */
1099
- consumer;
1100
- constructor(action, status, body = {}) {
1101
- const apiMessage = body.apiMessage ?? "";
1102
- super(`${action} failed (HTTP ${status})${apiMessage ? `: ${apiMessage}` : "."}`);
1103
- this.name = "GoogleApiError";
1104
- this.status = status;
1105
- this.apiStatus = body.apiStatus;
1106
- this.apiMessage = apiMessage;
1107
- this.reasons = body.reasons ?? [];
1108
- this.violations = body.violations ?? [];
1109
- this.consumer = body.consumer;
1110
- }
1111
- };
1112
- /** Google's error body, `{ error: { code, status, message, details } }`. */
1113
- const readError = async (action, response) => {
1114
- let error;
1115
- try {
1116
- error = (await response.json()).error;
1117
- } catch {}
1118
- const details = Array.isArray(error?.details) ? error.details : [];
1119
- const info = details.filter((detail) => typeof detail.reason === "string");
1120
- return new GoogleApiError(action, response.status, {
1121
- ...typeof error?.status === "string" ? { apiStatus: error.status } : {},
1122
- ...typeof error?.message === "string" ? { apiMessage: error.message } : {},
1123
- reasons: info.map((detail) => detail.reason),
1124
- violations: details.flatMap((detail) => (detail.violations ?? []).flatMap((violation) => typeof violation.type === "string" ? [violation.type] : [])),
1125
- ...info.find((detail) => detail.metadata?.["consumer"]) ? { consumer: info.find((detail) => detail.metadata?.["consumer"]).metadata["consumer"] } : {}
1126
- });
1127
- };
1128
- /** Whether Google answered that a service is disabled in a project. */
1129
- 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));
1130
- /** Requests with the signed-in user's access token, throwing `GoogleApiError`. */
1131
- const createGoogleRequest = ({ accessToken, fetch }) => async (action, method, url, body) => {
1132
- const response = await fetch(url, {
1133
- method,
1134
- headers: {
1135
- authorization: `Bearer ${accessToken}`,
1136
- ...body === void 0 ? {} : { "content-type": "application/json" }
1137
- },
1138
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
1139
- });
1140
- if (!response.ok) throw await readError(action, response);
1141
- const text = await response.text();
1142
- return text ? JSON.parse(text) : {};
1143
- };
1144
- /**
1145
- * Polls `operation` at `origin` until it is done, returning its response or
1146
- * throwing its error as a `GoogleApiError` with the operation's code.
1147
- */
1148
- const waitForOperation = async ({ request, origin, operation, action, sleep, intervalMs = 2e3, attempts = 60 }) => {
1149
- let current = operation;
1150
- for (let attempt = 0; !current.done; attempt++) {
1151
- if (attempt >= attempts || !current.name) throw new Error(`${action} did not finish in time.`);
1152
- await sleep(intervalMs);
1153
- current = await request(action, "GET", `${origin}/${current.name}`);
1154
- }
1155
- if (current.error) throw new GoogleApiError(action, 400, {
1156
- apiMessage: current.error.message ?? "",
1157
- ...current.error.code === 7 ? { apiStatus: "PERMISSION_DENIED" } : {},
1158
- ...current.error.code === 8 ? { apiStatus: "RESOURCE_EXHAUSTED" } : {}
1159
- });
1160
- return current.response;
1161
- };
1162
- //#endregion
1163
- //#region src/google/types.ts
1164
- /** A named failure of `issuePlayServiceAccount`, with what to do in its message. */
1165
- var PlayServiceAccountError = class extends Error {
1166
- code;
1167
- constructor(code, message, options) {
1168
- super(message, options);
1169
- this.name = "PlayServiceAccountError";
1170
- this.code = code;
1171
- }
1172
- };
1173
- /** The service account Hot Updater creates, `hot-updater-play@<project>.iam.gserviceaccount.com`. */
1174
- const PLAY_SERVICE_ACCOUNT_ID = "hot-updater-play";
1175
- //#endregion
1176
- //#region src/google/googleKeyIssuer.ts
1177
- const PUBLISHER_API = "https://androidpublisher.googleapis.com/androidpublisher/v3";
1178
- const RESOURCE_MANAGER_API = "https://cloudresourcemanager.googleapis.com";
1179
- const SERVICE_USAGE_API = "https://serviceusage.googleapis.com";
1180
- const IAM_API = "https://iam.googleapis.com/v1";
1181
- const GCLOUD_INSTALL_URL = "https://cloud.google.com/sdk/docs/install";
1182
- /** The Google Play Android Developer API, which the service account calls. */
1183
- const PLAY_API = "androidpublisher.googleapis.com";
1184
- /** IAM creates the service account; the Play Developer API is what it calls. */
1185
- const SERVICES = ["iam.googleapis.com", PLAY_API];
1186
- const KEY_CREATION_CONSTRAINT = "constraints/iam.disableServiceAccountKeyCreation";
1187
- /** Retries while Google enables an API or creates a service account. */
1188
- const PROPAGATION_ATTEMPTS = 12;
1189
- const PROPAGATION_DELAY_MS = 1e4;
1190
- /** Checks of the key's access to the app, about ten minutes of them. */
1191
- const ACCESS_ATTEMPTS = 120;
1192
- const ACCESS_DELAY_MS = 5e3;
1193
- const sleepFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1194
- const runWithExeca = async (file, args, options) => (await execa(file, args, options?.interactive ? { stdio: "inherit" } : { stdin: "ignore" })).stdout ?? "";
1195
- /**
1196
- * Play Console's page that invites `email` as a user. `_` stands for the
1197
- * developer account the browser is signed in to, so no ID is needed.
1198
- */
1199
- const playConsoleInviteUrl = (email) => `https://play.google.com/console/u/0/developers/_/users-and-permissions?invite=${encodeURIComponent(email)}`;
1200
- /** A project ID nobody has: Google Cloud's are global. */
1201
- const newProjectId = () => `${PLAY_SERVICE_ACCOUNT_ID}-${crypto$1.randomBytes(3).toString("hex")}`;
1202
- const isNotFound = (error) => error instanceof GoogleApiError && error.status === 404;
1203
- const isConflict = (error) => error instanceof GoogleApiError && error.status === 409;
1204
- /** The API is disabled in another project than the one set up: waiting does not help. */
1205
- const consumerApiDisabled = (error) => new PlayServiceAccountError("api-not-enabled", `${error.apiMessage}\nEnable it in ${error.consumer ?? "that project"}, then run this again.`, { cause: error });
1206
- const isDenied = (error) => error instanceof GoogleApiError && (error.status === 403 || error.apiStatus === "PERMISSION_DENIED");
1207
- /** The Google Account gcloud uses, if one is active. */
1208
- const activeAccount = async (run) => (await run("gcloud", [
1209
- "auth",
1210
- "list",
1211
- "--filter=status:ACTIVE",
1212
- "--format=value(account)"
1213
- ])).trim().split("\n")[0]?.trim() || void 0;
1214
- /** Stops before anything else, a prompt included, when gcloud is not installed. */
1215
- const requireGcloud = async (run) => {
1216
- try {
1217
- await run("gcloud", ["--version"]);
1218
- } catch (error) {
1219
- throw new PlayServiceAccountError("gcloud-not-installed", [
1220
- "gcloud CLI is not installed.",
1221
- "Install it, then run this again:",
1222
- GCLOUD_INSTALL_URL
1223
- ].join("\n"), { cause: error });
1224
- }
1225
- };
1226
- /** gcloud's access token, after `gcloud auth login` when no account is active. */
1227
- const signInWithGcloud = async ({ run, onStep }) => {
1228
- let account = await activeAccount(run);
1229
- if (account === void 0) {
1230
- await run("gcloud", ["auth", "login"], { interactive: true }).catch(() => {});
1231
- account = await activeAccount(run);
1232
- if (account === void 0) throw new PlayServiceAccountError("gcloud-not-signed-in", "gcloud has no active Google Account.\nRun gcloud auth login, then run this again.");
1233
- }
1234
- onStep(`Signed in to gcloud as ${account}`);
1235
- const accessToken = (await run("gcloud", ["auth", "print-access-token"])).trim();
1236
- registerSecretValue(accessToken);
1237
- return accessToken;
1238
- };
1239
- /**
1240
- * `IssuePlayServiceAccount` with the gcloud CLI's sign-in and Google's own
1241
- * APIs:
1242
- *
1243
- * 1. once gcloud is found, `askPackageName` names the app, and gcloud's
1244
- * Google Account, signed in with `gcloud auth login` when none is
1245
- * active, the access token the Google Cloud steps use;
1246
- * 2. the account's only project with the Play Developer API, else the one
1247
- * `chooseProject` picks, else a new one, gets the IAM and Play Developer
1248
- * APIs enabled, and the service account `hot-updater-play` its JSON key;
1249
- * 3. the developer invites the service account in Play Console, which
1250
- * `onInvite` opens: gcloud's token may not manage Google Play users;
1251
- * 4. the key itself opens an edit of the app until Google Play lets it,
1252
- * and is deleted again when it never does.
1253
- *
1254
- * Each step reuses what an earlier run created: the project and the
1255
- * service account.
1256
- */
1257
- const createGoogleKeyIssuer = ({ fetch = globalThis.fetch, sleep = sleepFor, run = runWithExeca } = {}) => async (request) => {
1258
- const { onStep = () => {} } = request;
1259
- await requireGcloud(run);
1260
- const packageName = await request.askPackageName();
1261
- const accessToken = await signInWithGcloud({
1262
- run,
1263
- onStep
1264
- });
1265
- const google = createGoogleRequest({
1266
- accessToken,
1267
- fetch
1268
- });
1269
- const project = await chooseProject({
1270
- google,
1271
- request,
1272
- sleep,
1273
- onStep
1274
- });
1275
- const { projectId } = project;
1276
- onStep(`Enabling the APIs in ${projectId}`);
1277
- await enableServices({
1278
- google,
1279
- projectId,
1280
- sleep
1281
- });
1282
- onStep(`Creating the service account in ${projectId}`);
1283
- const email = await ensureServiceAccount({
1284
- google,
1285
- project,
1286
- sleep
1287
- });
1288
- onStep("Creating the service account's JSON key");
1289
- const key = await createKey({
1290
- google,
1291
- project,
1292
- email,
1293
- sleep
1294
- });
1295
- const revoke = async () => {
1296
- try {
1297
- await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`);
1298
- return true;
1299
- } catch (error) {
1300
- return isNotFound(error);
1301
- }
1302
- };
1303
- const inviteUrl = playConsoleInviteUrl(email);
1304
- try {
1305
- await request.onInvite(inviteUrl, email);
1306
- onStep("Waiting for the Play Console invite");
1307
- await waitForPlayAccess({
1308
- json: key.json,
1309
- packageName,
1310
- fetch,
1311
- sleep
1312
- });
1313
- } catch (error) {
1314
- const deleted = await revoke();
1315
- throw new PlayServiceAccountError("play-access-pending", [
1316
- `The key can't release ${packageName} yet.`,
1317
- "Invite the service account in Play Console with release access:",
1318
- email,
1319
- inviteUrl,
1320
- "A new app needs its first .aab uploaded in Play Console.",
1321
- ...deleted ? [] : [`Delete its unused key ${key.keyId} in Google Cloud:`, `https://console.cloud.google.com/iam-admin/serviceaccounts?project=${encodeURIComponent(projectId)}`],
1322
- "Then run: npx hot-updater google-play login"
1323
- ].join("\n"), { cause: error });
1324
- }
1325
- return {
1326
- json: key.json,
1327
- keyId: key.keyId,
1328
- email,
1329
- projectId,
1330
- revoke,
1331
- dispose: async () => {}
1332
- };
1333
- };
1334
- /**
1335
- * Waits until the key opens an edit of `packageName`, which Google Play
1336
- * allows once the service account is a Play Console user with access to
1337
- * the app, then deletes the edit, which changed nothing. Google may not
1338
- * take a key just created for a while either.
1339
- */
1340
- const waitForPlayAccess = async ({ json, packageName, fetch, sleep }) => {
1341
- const play = createPlayClient({
1342
- json,
1343
- packageName,
1344
- fetch
1345
- });
1346
- const edits = `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits`;
1347
- for (let attempt = 1;; attempt++) {
1348
- if (attempt > 1) await sleep(ACCESS_DELAY_MS);
1349
- let ready = true;
1350
- try {
1351
- await play.authorization();
1352
- } catch {
1353
- ready = false;
1354
- }
1355
- if (ready) try {
1356
- const edit = await play.request(`Opening an edit of ${packageName}`, "POST", edits);
1357
- if (edit?.id) await play.request("Deleting the edit", "DELETE", `${edits}/${edit.id}`).catch(() => {});
1358
- return;
1359
- } catch (error) {
1360
- if (!(error instanceof GooglePlayError) || ![
1361
- 401,
1362
- 403,
1363
- 404
1364
- ].includes(error.status)) throw error;
1365
- }
1366
- if (attempt >= ACCESS_ATTEMPTS) throw new Error("Google Play did not let the key reach the app in time.");
1367
- }
1368
- };
1369
- /** The account's active projects, every page of them. */
1370
- const listProjects = async (google) => {
1371
- const projects = [];
1372
- let pageToken;
1373
- do {
1374
- const page = await google("Listing the Google Cloud projects", "GET", `${RESOURCE_MANAGER_API}/v3/projects:search?${new URLSearchParams({
1375
- query: "state:ACTIVE",
1376
- ...pageToken ? { pageToken } : {}
1377
- })}`);
1378
- for (const project of page.projects ?? []) if (project.projectId) projects.push({
1379
- projectId: project.projectId,
1380
- ...project.displayName ? { displayName: project.displayName } : {},
1381
- ...projectNumberOf(project.name)
1382
- });
1383
- pageToken = page.nextPageToken || void 0;
1384
- } while (pageToken);
1385
- return projects;
1386
- };
1387
- /** Service Usage reads of the projects' Play Developer API, at most this many at once. */
1388
- const API_CHECK_CONCURRENCY = 8;
1389
- /**
1390
- * Whether each project has the Google Play Developer API enabled, by one
1391
- * Service Usage read each; a project this account may not read counts as
1392
- * without it.
1393
- */
1394
- const withPlayApiState = async (google, projects) => {
1395
- const states = [];
1396
- for (let start = 0; start < projects.length; start += API_CHECK_CONCURRENCY) states.push(...await Promise.all(projects.slice(start, start + API_CHECK_CONCURRENCY).map(({ projectId }) => google("Reading the project's APIs", "GET", `${SERVICE_USAGE_API}/v1/projects/${encodeURIComponent(projectId)}/services/${PLAY_API}`).then(({ state }) => state === "ENABLED", () => false))));
1397
- return projects.map((project, index) => ({
1398
- ...project,
1399
- playApiEnabled: states[index]
1400
- }));
1401
- };
1402
- /** The display name of the project Hot Updater creates. */
1403
- const PROJECT_DISPLAY_NAME = "Hot Updater Play";
1404
- /**
1405
- * The project the service account goes in: a new one for an account
1406
- * without projects; the only project with the Play Developer API, without
1407
- * asking; else the one the developer picks, or a new one.
1408
- */
1409
- const chooseProject = async ({ google, request, sleep, onStep }) => {
1410
- const listed = await listProjects(google);
1411
- if (listed.length === 0) return createProject({
1412
- google,
1413
- sleep,
1414
- onStep
1415
- });
1416
- const projects = await withPlayApiState(google, listed);
1417
- const enabled = projects.filter(({ playApiEnabled }) => playApiEnabled);
1418
- if (enabled.length === 1) {
1419
- const [only] = enabled;
1420
- onStep(`Using ${only.projectId}, the project with the Play Developer API`);
1421
- return only;
1422
- }
1423
- const chosen = await request.chooseProject(projects.map(({ projectId, displayName, playApiEnabled }) => ({
1424
- projectId,
1425
- ...displayName ? { displayName } : {},
1426
- playApiEnabled
1427
- })));
1428
- if (chosen === null) return createProject({
1429
- google,
1430
- sleep,
1431
- onStep
1432
- });
1433
- return projects.find((project) => project.projectId === chosen) ?? { projectId: chosen };
1434
- };
1435
- /** A new project, `hot-updater-play-<random>`, once Google has created it. */
1436
- const createProject = async ({ google, sleep, onStep }) => {
1437
- const projectId = newProjectId();
1438
- onStep(`Creating the Google Cloud project ${projectId}`);
1439
- try {
1440
- const operation = await google("Creating the Google Cloud project", "POST", `${RESOURCE_MANAGER_API}/v3/projects`, {
1441
- projectId,
1442
- displayName: PROJECT_DISPLAY_NAME
1443
- });
1444
- const created = await waitForOperation({
1445
- request: google,
1446
- origin: `${RESOURCE_MANAGER_API}/v3`,
1447
- operation,
1448
- action: "Creating the Google Cloud project",
1449
- sleep
1450
- });
1451
- return {
1452
- projectId,
1453
- ...projectNumberOf(created?.name)
1454
- };
1455
- } catch (error) {
1456
- if (!(error instanceof GoogleApiError)) throw error;
1457
- if (error.status === 429 || error.apiStatus === "RESOURCE_EXHAUSTED" || /quota/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-quota", [
1458
- "Google Cloud has no project quota left for this account.",
1459
- error.apiMessage || "Quota exceeded.",
1460
- "Delete a project you no longer use, then run this again:",
1461
- "https://console.cloud.google.com/cloud-resource-manager"
1462
- ].join("\n"), { cause: error });
1463
- if (/terms of service/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-create-denied", "This Google Account hasn't accepted the Google Cloud Terms of Service.\nAccept them at https://console.cloud.google.com, then run this again.", { cause: error });
1464
- if (isDenied(error) || error.apiStatus === "FAILED_PRECONDITION") throw new PlayServiceAccountError("project-create-denied", [
1465
- "This Google Account may not create Google Cloud projects.",
1466
- error.apiMessage || "Permission denied.",
1467
- "Ask an admin for the Project Creator role."
1468
- ].join("\n"), { 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 consumerApiDisabled(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}.\n${error.apiMessage}\nWait 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", [
1512
- `This Google Account may not enable APIs in ${projectId}.`,
1513
- error.apiMessage || "Permission denied.",
1514
- "Pick a project you own, or ask its owner for the Editor role."
1515
- ].join("\n"), { cause: error });
1516
- throw error;
1517
- }
1518
- };
1519
- /** The `hot-updater-play` service account's email, created unless it exists. */
1520
- const ensureServiceAccount = async ({ google, project, sleep }) => {
1521
- const { projectId } = project;
1522
- const email = `${PLAY_SERVICE_ACCOUNT_ID}@${projectId}.iam.gserviceaccount.com`;
1523
- try {
1524
- return (await whilePropagating({
1525
- project,
1526
- sleep,
1527
- run: () => google("Creating the service account", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts`, {
1528
- accountId: "hot-updater-play",
1529
- serviceAccount: {
1530
- displayName: "Hot Updater Play uploads",
1531
- description: "Uploads Android App Bundles to Google Play for hot-updater native-build android --submit play-internal."
1532
- }
1533
- })
1534
- })).email ?? email;
1535
- } catch (error) {
1536
- if (isConflict(error)) return email;
1537
- if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", [
1538
- `This Google Account may not create service accounts in ${projectId}.`,
1539
- error.apiMessage || "Permission denied.",
1540
- "Pick a project you own, or ask for the Service Account Admin role."
1541
- ].join("\n"), { cause: error });
1542
- throw error;
1543
- }
1544
- };
1545
- /** A new JSON key of the service account, checked and masked in the CLI's output. */
1546
- const createKey = async ({ google, project, email, sleep }) => {
1547
- const { projectId } = project;
1548
- let key;
1549
- try {
1550
- key = await whilePropagating({
1551
- project,
1552
- sleep,
1553
- notFound: true,
1554
- run: () => google("Creating the key", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts/${email}/keys`, {
1555
- privateKeyType: "TYPE_GOOGLE_CREDENTIALS_FILE",
1556
- keyAlgorithm: "KEY_ALG_RSA_2048"
1557
- })
1558
- });
1559
- } catch (error) {
1560
- if (error instanceof GoogleApiError && (error.violations.includes(KEY_CREATION_CONSTRAINT) || /disableServiceAccountKeyCreation/u.test(error.apiMessage))) throw new PlayServiceAccountError("key-creation-disabled", [
1561
- `iam.disableServiceAccountKeyCreation forbids keys in ${projectId}.`,
1562
- "Ask an organization policy admin to allow keys for this project,",
1563
- "or run this again with a project outside the organization."
1564
- ].join("\n"), { cause: error });
1565
- throw error;
1566
- }
1567
- if (!key.name || !key.privateKeyData) throw new Error("Google Cloud created the key without its JSON file.");
1568
- registerSecretValue(key.privateKeyData);
1569
- const json = Buffer.from(key.privateKeyData, "base64").toString("utf-8");
1570
- registerSecretValue(json);
1571
- let parsed;
1572
- try {
1573
- parsed = JSON.parse(json);
1574
- } catch {
1575
- parsed = {};
1687
+ //#region src/playTracks.ts
1688
+ /** Google Play destinations and their API tracks. */
1689
+ const PLAY_TRACKS = {
1690
+ "play-internal": {
1691
+ track: "internal",
1692
+ label: "Play internal",
1693
+ name: "Google Play internal testing"
1694
+ },
1695
+ "play-closed": {
1696
+ track: "alpha",
1697
+ label: "Play closed",
1698
+ name: "Google Play closed testing"
1699
+ },
1700
+ "play-open": {
1701
+ track: "beta",
1702
+ label: "Play open",
1703
+ name: "Google Play open testing"
1704
+ },
1705
+ "play-production": {
1706
+ track: "production",
1707
+ label: "Play production",
1708
+ name: "Google Play production"
1576
1709
  }
1577
- if (typeof parsed.private_key !== "string") {
1578
- await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`).catch(() => {});
1579
- throw new Error("Google Cloud created a key that is no JSON key file.");
1580
- }
1581
- registerSecretValue(parsed.private_key);
1582
- return {
1583
- json,
1584
- name: key.name,
1585
- keyId: key.name.split("/").pop()
1586
- };
1587
1710
  };
1588
1711
  //#endregion
1589
- //#region src/playServiceAccount.ts
1590
- /**
1591
- * Hot Updater's issuer, the one place that picks how it is done: gcloud's
1592
- * sign-in, then the Cloud Resource Manager, Service Usage, IAM, and Play
1593
- * Developer APIs. Another implementation of `IssuePlayServiceAccount`
1594
- * replaces it here without touching its callers.
1595
- */
1596
- const issuePlayServiceAccount = (request) => createGoogleKeyIssuer()(request);
1597
- //#endregion
1598
- export { PLAY_SERVICE_ACCOUNT_ID, PlayServiceAccountError, PlayVersionCodeUsedError, assertPlaySigned, buildAndroid, enrichNativeBuildAndroidScheme, extractBuiltInBundle, findPlayInternalRelease, hasPlayReleases, issuePlayServiceAccount, readBuiltApp, readBuiltPackageName, readBuiltVersionCode, resolvePlayUploadServiceAccount, uploadToPlay };
1712
+ export { PLAY_TRACKS, PlayVersionCodeUsedError, assertPlaySigned, buildAndroid, checkPlayAccess, enrichNativeBuildAndroidScheme, extractBuiltInBundle, findPlayInternalRelease, findSandboxGradleBlocker, installOnAndroidDevice, listAdbDevices, playConsoleInviteUrl, playTestingUrl, readBuiltApp, readBuiltPackageName, readBuiltVersionCode, readPlayHighestVersionCode, readPlayTrackRelease, resolvePlayUploadServiceAccount, selectAdbDevice, uploadToPlay };