@hot-updater/android-helper 1.2.0-rc.5 → 1.2.0-rc.51
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 +836 -691
- package/dist/index.d.cts +144 -99
- package/dist/index.d.mts +144 -99
- package/dist/index.mjs +827 -687
- package/package.json +5 -4
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
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
160
|
+
* The project's Gradle wrapper. On Windows by its path: cmd.exe finds no
|
|
161
|
+
* program in the current directory with NoDefaultCurrentDirectoryInExePath.
|
|
173
162
|
*/
|
|
174
|
-
const getGradleWrapper = () => process.platform.startsWith("win") ? "gradlew.bat" : "./gradlew";
|
|
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.
|
|
171
|
+
*/
|
|
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(
|
|
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
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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
|
+
]
|
|
199
209
|
});
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
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('&', '&').replace('"', '"')
|
|
315
|
+
.replace('<', '<').replace('>', '>')
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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, "&").replace(/"/gu, """).replace(/</gu, "<").replace(/>/gu, ">");
|
|
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
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
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.
|
|
649
|
-
*
|
|
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
|
-
*
|
|
699
|
-
*
|
|
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
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
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
|
|
1237
|
+
let play;
|
|
709
1238
|
try {
|
|
710
|
-
|
|
1239
|
+
play = createPlayClient({
|
|
1240
|
+
json,
|
|
1241
|
+
packageName,
|
|
1242
|
+
fetch
|
|
1243
|
+
});
|
|
711
1244
|
} catch (error) {
|
|
712
|
-
|
|
1245
|
+
return refused(error);
|
|
713
1246
|
}
|
|
714
|
-
const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
|
|
715
1247
|
try {
|
|
716
|
-
|
|
717
|
-
return releases.some(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
|
|
1248
|
+
await play.authorization();
|
|
718
1249
|
} catch (error) {
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
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
|
-
*
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
739
|
-
|
|
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
|
|
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
|
|
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(
|
|
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
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
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
|
-
|
|
1412
|
+
const status = rollout < 100 ? "inProgress" : "completed";
|
|
1413
|
+
await release(status);
|
|
814
1414
|
return {
|
|
815
1415
|
versionCode,
|
|
816
|
-
status
|
|
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
|
|
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,489 +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/
|
|
1088
|
-
/**
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
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
|
-
/** IAM creates the service account; the Play Developer API is what it calls. */
|
|
1183
|
-
const SERVICES = ["iam.googleapis.com", "androidpublisher.googleapis.com"];
|
|
1184
|
-
const KEY_CREATION_CONSTRAINT = "constraints/iam.disableServiceAccountKeyCreation";
|
|
1185
|
-
/** Retries while Google enables an API or creates a service account. */
|
|
1186
|
-
const PROPAGATION_ATTEMPTS = 12;
|
|
1187
|
-
const PROPAGATION_DELAY_MS = 1e4;
|
|
1188
|
-
/** Checks of the key's access to the app, about ten minutes of them. */
|
|
1189
|
-
const ACCESS_ATTEMPTS = 120;
|
|
1190
|
-
const ACCESS_DELAY_MS = 5e3;
|
|
1191
|
-
const sleepFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1192
|
-
const runWithExeca = async (file, args, options) => (await execa(file, args, options?.interactive ? { stdio: "inherit" } : { stdin: "ignore" })).stdout ?? "";
|
|
1193
|
-
/**
|
|
1194
|
-
* Play Console's page that invites `email` as a user. `_` stands for the
|
|
1195
|
-
* developer account the browser is signed in to, so no ID is needed.
|
|
1196
|
-
*/
|
|
1197
|
-
const playConsoleInviteUrl = (email) => `https://play.google.com/console/u/0/developers/_/users-and-permissions?invite=${encodeURIComponent(email)}`;
|
|
1198
|
-
/** A project ID nobody has: Google Cloud's are global. */
|
|
1199
|
-
const newProjectId = () => `${PLAY_SERVICE_ACCOUNT_ID}-${crypto$1.randomBytes(3).toString("hex")}`;
|
|
1200
|
-
const isNotFound = (error) => error instanceof GoogleApiError && error.status === 404;
|
|
1201
|
-
const isConflict = (error) => error instanceof GoogleApiError && error.status === 409;
|
|
1202
|
-
/** The API is disabled in another project than the one set up: waiting does not help. */
|
|
1203
|
-
const consumerApiDisabled = (error) => new PlayServiceAccountError("api-not-enabled", `${error.apiMessage}\nEnable it in ${error.consumer ?? "that project"}, then run this again.`, { cause: error });
|
|
1204
|
-
const isDenied = (error) => error instanceof GoogleApiError && (error.status === 403 || error.apiStatus === "PERMISSION_DENIED");
|
|
1205
|
-
/** The Google Account gcloud uses, if one is active. */
|
|
1206
|
-
const activeAccount = async (run) => (await run("gcloud", [
|
|
1207
|
-
"auth",
|
|
1208
|
-
"list",
|
|
1209
|
-
"--filter=status:ACTIVE",
|
|
1210
|
-
"--format=value(account)"
|
|
1211
|
-
])).trim().split("\n")[0]?.trim() || void 0;
|
|
1212
|
-
/**
|
|
1213
|
-
* gcloud's access token, after `gcloud auth login` when no account is
|
|
1214
|
-
* active. Stops before any change when gcloud is not installed.
|
|
1215
|
-
*/
|
|
1216
|
-
const signInWithGcloud = async ({ run, onStep }) => {
|
|
1217
|
-
try {
|
|
1218
|
-
await run("gcloud", ["--version"]);
|
|
1219
|
-
} catch (error) {
|
|
1220
|
-
throw new PlayServiceAccountError("gcloud-not-installed", [
|
|
1221
|
-
"gcloud CLI is not installed.",
|
|
1222
|
-
"Install it, then run this again:",
|
|
1223
|
-
GCLOUD_INSTALL_URL
|
|
1224
|
-
].join("\n"), { cause: error });
|
|
1225
|
-
}
|
|
1226
|
-
let account = await activeAccount(run);
|
|
1227
|
-
if (account === void 0) {
|
|
1228
|
-
await run("gcloud", ["auth", "login"], { interactive: true }).catch(() => {});
|
|
1229
|
-
account = await activeAccount(run);
|
|
1230
|
-
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.");
|
|
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"
|
|
1231
1709
|
}
|
|
1232
|
-
onStep(`Signed in to gcloud as ${account}`);
|
|
1233
|
-
const accessToken = (await run("gcloud", ["auth", "print-access-token"])).trim();
|
|
1234
|
-
registerSecretValue(accessToken);
|
|
1235
|
-
return accessToken;
|
|
1236
1710
|
};
|
|
1237
|
-
/**
|
|
1238
|
-
* `IssuePlayServiceAccount` with the gcloud CLI's sign-in and Google's own
|
|
1239
|
-
* APIs:
|
|
1240
|
-
*
|
|
1241
|
-
* 1. gcloud's Google Account, signed in with `gcloud auth login` when none
|
|
1242
|
-
* is active, names the access token the Google Cloud steps use;
|
|
1243
|
-
* 2. the Google Cloud project "Hot Updater Play" an earlier run created, or
|
|
1244
|
-
* a new one, gets the IAM and Play Developer APIs enabled, and the
|
|
1245
|
-
* service account `hot-updater-play` its JSON key;
|
|
1246
|
-
* 3. the developer invites the service account in Play Console, which
|
|
1247
|
-
* `onInvite` opens: gcloud's token may not manage Google Play users;
|
|
1248
|
-
* 4. the key itself opens an edit of the app until Google Play lets it,
|
|
1249
|
-
* and is deleted again when it never does.
|
|
1250
|
-
*
|
|
1251
|
-
* Each step reuses what an earlier run created: the project and the
|
|
1252
|
-
* service account.
|
|
1253
|
-
*/
|
|
1254
|
-
const createGoogleKeyIssuer = ({ fetch = globalThis.fetch, sleep = sleepFor, run = runWithExeca } = {}) => async (request) => {
|
|
1255
|
-
const { packageName, onStep = () => {} } = request;
|
|
1256
|
-
const accessToken = await signInWithGcloud({
|
|
1257
|
-
run,
|
|
1258
|
-
onStep
|
|
1259
|
-
});
|
|
1260
|
-
const google = createGoogleRequest({
|
|
1261
|
-
accessToken,
|
|
1262
|
-
fetch
|
|
1263
|
-
});
|
|
1264
|
-
const project = await chooseProject({
|
|
1265
|
-
google,
|
|
1266
|
-
request,
|
|
1267
|
-
sleep,
|
|
1268
|
-
onStep
|
|
1269
|
-
});
|
|
1270
|
-
const { projectId } = project;
|
|
1271
|
-
onStep(`Enabling the Google Play Developer API in ${projectId}`);
|
|
1272
|
-
await enableServices({
|
|
1273
|
-
google,
|
|
1274
|
-
projectId,
|
|
1275
|
-
sleep
|
|
1276
|
-
});
|
|
1277
|
-
onStep(`Creating the service account in ${projectId}`);
|
|
1278
|
-
const email = await ensureServiceAccount({
|
|
1279
|
-
google,
|
|
1280
|
-
project,
|
|
1281
|
-
sleep
|
|
1282
|
-
});
|
|
1283
|
-
onStep("Creating the service account's JSON key");
|
|
1284
|
-
const key = await createKey({
|
|
1285
|
-
google,
|
|
1286
|
-
project,
|
|
1287
|
-
email,
|
|
1288
|
-
sleep
|
|
1289
|
-
});
|
|
1290
|
-
const revoke = async () => {
|
|
1291
|
-
try {
|
|
1292
|
-
await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`);
|
|
1293
|
-
return true;
|
|
1294
|
-
} catch (error) {
|
|
1295
|
-
return isNotFound(error);
|
|
1296
|
-
}
|
|
1297
|
-
};
|
|
1298
|
-
const inviteUrl = playConsoleInviteUrl(email);
|
|
1299
|
-
try {
|
|
1300
|
-
await request.onInvite(inviteUrl, email);
|
|
1301
|
-
onStep("Waiting for the Play Console invite");
|
|
1302
|
-
await waitForPlayAccess({
|
|
1303
|
-
json: key.json,
|
|
1304
|
-
packageName,
|
|
1305
|
-
fetch,
|
|
1306
|
-
sleep
|
|
1307
|
-
});
|
|
1308
|
-
} catch (error) {
|
|
1309
|
-
const deleted = await revoke();
|
|
1310
|
-
throw new PlayServiceAccountError("play-access-pending", [
|
|
1311
|
-
`The key can't release ${packageName} yet.`,
|
|
1312
|
-
"Invite the service account in Play Console with release access:",
|
|
1313
|
-
email,
|
|
1314
|
-
inviteUrl,
|
|
1315
|
-
"A new app needs its first .aab uploaded in Play Console.",
|
|
1316
|
-
...deleted ? [] : [`Delete its unused key ${key.keyId} in Google Cloud:`, `https://console.cloud.google.com/iam-admin/serviceaccounts?project=${encodeURIComponent(projectId)}`],
|
|
1317
|
-
"Then run: npx hot-updater google-play login"
|
|
1318
|
-
].join("\n"), { cause: error });
|
|
1319
|
-
}
|
|
1320
|
-
return {
|
|
1321
|
-
json: key.json,
|
|
1322
|
-
keyId: key.keyId,
|
|
1323
|
-
email,
|
|
1324
|
-
projectId,
|
|
1325
|
-
revoke,
|
|
1326
|
-
dispose: async () => {}
|
|
1327
|
-
};
|
|
1328
|
-
};
|
|
1329
|
-
/**
|
|
1330
|
-
* Waits until the key opens an edit of `packageName`, which Google Play
|
|
1331
|
-
* allows once the service account is a Play Console user with access to
|
|
1332
|
-
* the app, then deletes the edit, which changed nothing. Google may not
|
|
1333
|
-
* take a key just created for a while either.
|
|
1334
|
-
*/
|
|
1335
|
-
const waitForPlayAccess = async ({ json, packageName, fetch, sleep }) => {
|
|
1336
|
-
const play = createPlayClient({
|
|
1337
|
-
json,
|
|
1338
|
-
packageName,
|
|
1339
|
-
fetch
|
|
1340
|
-
});
|
|
1341
|
-
const edits = `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits`;
|
|
1342
|
-
for (let attempt = 1;; attempt++) {
|
|
1343
|
-
if (attempt > 1) await sleep(ACCESS_DELAY_MS);
|
|
1344
|
-
let ready = true;
|
|
1345
|
-
try {
|
|
1346
|
-
await play.authorization();
|
|
1347
|
-
} catch {
|
|
1348
|
-
ready = false;
|
|
1349
|
-
}
|
|
1350
|
-
if (ready) try {
|
|
1351
|
-
const edit = await play.request(`Opening an edit of ${packageName}`, "POST", edits);
|
|
1352
|
-
if (edit?.id) await play.request("Deleting the edit", "DELETE", `${edits}/${edit.id}`).catch(() => {});
|
|
1353
|
-
return;
|
|
1354
|
-
} catch (error) {
|
|
1355
|
-
if (!(error instanceof GooglePlayError) || ![
|
|
1356
|
-
401,
|
|
1357
|
-
403,
|
|
1358
|
-
404
|
|
1359
|
-
].includes(error.status)) throw error;
|
|
1360
|
-
}
|
|
1361
|
-
if (attempt >= ACCESS_ATTEMPTS) throw new Error("Google Play did not let the key reach the app in time.");
|
|
1362
|
-
}
|
|
1363
|
-
};
|
|
1364
|
-
/** The account's active projects, every page of them. */
|
|
1365
|
-
const listProjects = async (google) => {
|
|
1366
|
-
const projects = [];
|
|
1367
|
-
let pageToken;
|
|
1368
|
-
do {
|
|
1369
|
-
const page = await google("Listing the Google Cloud projects", "GET", `${RESOURCE_MANAGER_API}/v3/projects:search?${new URLSearchParams({
|
|
1370
|
-
query: "state:ACTIVE",
|
|
1371
|
-
...pageToken ? { pageToken } : {}
|
|
1372
|
-
})}`);
|
|
1373
|
-
for (const project of page.projects ?? []) if (project.projectId) projects.push({
|
|
1374
|
-
projectId: project.projectId,
|
|
1375
|
-
...project.displayName ? { displayName: project.displayName } : {},
|
|
1376
|
-
...projectNumberOf(project.name)
|
|
1377
|
-
});
|
|
1378
|
-
pageToken = page.nextPageToken || void 0;
|
|
1379
|
-
} while (pageToken);
|
|
1380
|
-
return projects;
|
|
1381
|
-
};
|
|
1382
|
-
/** The display name of the project Hot Updater creates, which later runs reuse. */
|
|
1383
|
-
const PROJECT_DISPLAY_NAME = "Hot Updater Play";
|
|
1384
|
-
/**
|
|
1385
|
-
* The project the service account goes in, without asking: the one an
|
|
1386
|
-
* earlier run created, else a new one. Only when Google refuses to create
|
|
1387
|
-
* one does the developer pick among the account's projects.
|
|
1388
|
-
*/
|
|
1389
|
-
const chooseProject = async ({ google, request, sleep, onStep }) => {
|
|
1390
|
-
const projects = await listProjects(google);
|
|
1391
|
-
const reused = projects.find((project) => project.displayName === PROJECT_DISPLAY_NAME);
|
|
1392
|
-
if (reused) return reused;
|
|
1393
|
-
try {
|
|
1394
|
-
return await createProject({
|
|
1395
|
-
google,
|
|
1396
|
-
sleep,
|
|
1397
|
-
onStep
|
|
1398
|
-
});
|
|
1399
|
-
} catch (error) {
|
|
1400
|
-
if (!(error instanceof PlayServiceAccountError) || error.code !== "project-quota" && error.code !== "project-create-denied" || projects.length === 0) throw error;
|
|
1401
|
-
const chosen = await request.chooseProject(projects.map(({ projectId, displayName }) => ({
|
|
1402
|
-
projectId,
|
|
1403
|
-
...displayName ? { displayName } : {}
|
|
1404
|
-
})));
|
|
1405
|
-
if (chosen === void 0) throw error;
|
|
1406
|
-
return projects.find((project) => project.projectId === chosen) ?? { projectId: chosen };
|
|
1407
|
-
}
|
|
1408
|
-
};
|
|
1409
|
-
/** A new project, `hot-updater-play-<random>`, once Google has created it. */
|
|
1410
|
-
const createProject = async ({ google, sleep, onStep }) => {
|
|
1411
|
-
const projectId = newProjectId();
|
|
1412
|
-
onStep(`Creating the Google Cloud project ${projectId}`);
|
|
1413
|
-
try {
|
|
1414
|
-
const operation = await google("Creating the Google Cloud project", "POST", `${RESOURCE_MANAGER_API}/v3/projects`, {
|
|
1415
|
-
projectId,
|
|
1416
|
-
displayName: PROJECT_DISPLAY_NAME
|
|
1417
|
-
});
|
|
1418
|
-
const created = await waitForOperation({
|
|
1419
|
-
request: google,
|
|
1420
|
-
origin: `${RESOURCE_MANAGER_API}/v3`,
|
|
1421
|
-
operation,
|
|
1422
|
-
action: "Creating the Google Cloud project",
|
|
1423
|
-
sleep
|
|
1424
|
-
});
|
|
1425
|
-
return {
|
|
1426
|
-
projectId,
|
|
1427
|
-
...projectNumberOf(created?.name)
|
|
1428
|
-
};
|
|
1429
|
-
} catch (error) {
|
|
1430
|
-
if (!(error instanceof GoogleApiError)) throw error;
|
|
1431
|
-
if (error.status === 429 || error.apiStatus === "RESOURCE_EXHAUSTED" || /quota/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-quota", [
|
|
1432
|
-
"Google Cloud has no project quota left for this account.",
|
|
1433
|
-
error.apiMessage || "Quota exceeded.",
|
|
1434
|
-
"Delete a project you no longer use, then run this again:",
|
|
1435
|
-
"https://console.cloud.google.com/cloud-resource-manager"
|
|
1436
|
-
].join("\n"), { cause: error });
|
|
1437
|
-
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 });
|
|
1438
|
-
if (isDenied(error) || error.apiStatus === "FAILED_PRECONDITION") throw new PlayServiceAccountError("project-create-denied", [
|
|
1439
|
-
"This Google Account may not create Google Cloud projects.",
|
|
1440
|
-
error.apiMessage || "Permission denied.",
|
|
1441
|
-
"Ask an admin for the Project Creator role."
|
|
1442
|
-
].join("\n"), { cause: error });
|
|
1443
|
-
throw error;
|
|
1444
|
-
}
|
|
1445
|
-
};
|
|
1446
|
-
/** `projectNumber` from a resource name `projects/<number>`. */
|
|
1447
|
-
const projectNumberOf = (name) => {
|
|
1448
|
-
const number = name?.match(/^projects\/(\d+)$/u)?.[1];
|
|
1449
|
-
return number === void 0 ? {} : { projectNumber: number };
|
|
1450
|
-
};
|
|
1451
|
-
/**
|
|
1452
|
-
* Runs `run` again while Google is still enabling an API in `project`,
|
|
1453
|
-
* or, with `notFound`, still creating what it reads.
|
|
1454
|
-
*/
|
|
1455
|
-
const whilePropagating = async ({ run, project, sleep, notFound = false }) => {
|
|
1456
|
-
for (let attempt = 1;; attempt++) try {
|
|
1457
|
-
return await run();
|
|
1458
|
-
} catch (error) {
|
|
1459
|
-
const disabled = isServiceDisabled(error);
|
|
1460
|
-
if (disabled && !consumerIs(error, project)) throw consumerApiDisabled(error);
|
|
1461
|
-
if (!disabled && !(notFound && isNotFound(error)) || attempt >= PROPAGATION_ATTEMPTS) {
|
|
1462
|
-
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 });
|
|
1463
|
-
throw error;
|
|
1464
|
-
}
|
|
1465
|
-
await sleep(PROPAGATION_DELAY_MS);
|
|
1466
|
-
}
|
|
1467
|
-
};
|
|
1468
|
-
/**
|
|
1469
|
-
* Whether a disabled-service error is about `project` itself, which waiting
|
|
1470
|
-
* fixes: Google names the consumer by number, and an error naming none
|
|
1471
|
-
* counts as the project's own.
|
|
1472
|
-
*/
|
|
1473
|
-
const consumerIs = (error, project) => error.consumer === void 0 || error.consumer === `projects/${project.projectId}` || (project.projectNumber === void 0 ? true : error.consumer === `projects/${project.projectNumber}`);
|
|
1474
|
-
const enableServices = async ({ google, projectId, sleep }) => {
|
|
1475
|
-
try {
|
|
1476
|
-
const operation = await google("Enabling the APIs", "POST", `${SERVICE_USAGE_API}/v1/projects/${projectId}/services:batchEnable`, { serviceIds: SERVICES });
|
|
1477
|
-
await waitForOperation({
|
|
1478
|
-
request: google,
|
|
1479
|
-
origin: `${SERVICE_USAGE_API}/v1`,
|
|
1480
|
-
operation,
|
|
1481
|
-
action: "Enabling the APIs",
|
|
1482
|
-
sleep
|
|
1483
|
-
});
|
|
1484
|
-
} catch (error) {
|
|
1485
|
-
if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", [
|
|
1486
|
-
`This Google Account may not enable APIs in ${projectId}.`,
|
|
1487
|
-
error.apiMessage || "Permission denied.",
|
|
1488
|
-
"Pick a project you own, or ask its owner for the Editor role."
|
|
1489
|
-
].join("\n"), { cause: error });
|
|
1490
|
-
throw error;
|
|
1491
|
-
}
|
|
1492
|
-
};
|
|
1493
|
-
/** The `hot-updater-play` service account's email, created unless it exists. */
|
|
1494
|
-
const ensureServiceAccount = async ({ google, project, sleep }) => {
|
|
1495
|
-
const { projectId } = project;
|
|
1496
|
-
const email = `${PLAY_SERVICE_ACCOUNT_ID}@${projectId}.iam.gserviceaccount.com`;
|
|
1497
|
-
try {
|
|
1498
|
-
return (await whilePropagating({
|
|
1499
|
-
project,
|
|
1500
|
-
sleep,
|
|
1501
|
-
run: () => google("Creating the service account", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts`, {
|
|
1502
|
-
accountId: "hot-updater-play",
|
|
1503
|
-
serviceAccount: {
|
|
1504
|
-
displayName: "Hot Updater Play uploads",
|
|
1505
|
-
description: "Uploads Android App Bundles to Google Play for hot-updater native-build android --submit play-internal."
|
|
1506
|
-
}
|
|
1507
|
-
})
|
|
1508
|
-
})).email ?? email;
|
|
1509
|
-
} catch (error) {
|
|
1510
|
-
if (isConflict(error)) return email;
|
|
1511
|
-
if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", [
|
|
1512
|
-
`This Google Account may not create service accounts in ${projectId}.`,
|
|
1513
|
-
error.apiMessage || "Permission denied.",
|
|
1514
|
-
"Pick a project you own, or ask for the Service Account Admin role."
|
|
1515
|
-
].join("\n"), { cause: error });
|
|
1516
|
-
throw error;
|
|
1517
|
-
}
|
|
1518
|
-
};
|
|
1519
|
-
/** A new JSON key of the service account, checked and masked in the CLI's output. */
|
|
1520
|
-
const createKey = async ({ google, project, email, sleep }) => {
|
|
1521
|
-
const { projectId } = project;
|
|
1522
|
-
let key;
|
|
1523
|
-
try {
|
|
1524
|
-
key = await whilePropagating({
|
|
1525
|
-
project,
|
|
1526
|
-
sleep,
|
|
1527
|
-
notFound: true,
|
|
1528
|
-
run: () => google("Creating the key", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts/${email}/keys`, {
|
|
1529
|
-
privateKeyType: "TYPE_GOOGLE_CREDENTIALS_FILE",
|
|
1530
|
-
keyAlgorithm: "KEY_ALG_RSA_2048"
|
|
1531
|
-
})
|
|
1532
|
-
});
|
|
1533
|
-
} catch (error) {
|
|
1534
|
-
if (error instanceof GoogleApiError && (error.violations.includes(KEY_CREATION_CONSTRAINT) || /disableServiceAccountKeyCreation/u.test(error.apiMessage))) throw new PlayServiceAccountError("key-creation-disabled", [
|
|
1535
|
-
`iam.disableServiceAccountKeyCreation forbids keys in ${projectId}.`,
|
|
1536
|
-
"Ask an organization policy admin to allow keys for this project,",
|
|
1537
|
-
"or run this again with a project outside the organization."
|
|
1538
|
-
].join("\n"), { cause: error });
|
|
1539
|
-
throw error;
|
|
1540
|
-
}
|
|
1541
|
-
if (!key.name || !key.privateKeyData) throw new Error("Google Cloud created the key without its JSON file.");
|
|
1542
|
-
registerSecretValue(key.privateKeyData);
|
|
1543
|
-
const json = Buffer.from(key.privateKeyData, "base64").toString("utf-8");
|
|
1544
|
-
registerSecretValue(json);
|
|
1545
|
-
let parsed;
|
|
1546
|
-
try {
|
|
1547
|
-
parsed = JSON.parse(json);
|
|
1548
|
-
} catch {
|
|
1549
|
-
parsed = {};
|
|
1550
|
-
}
|
|
1551
|
-
if (typeof parsed.private_key !== "string") {
|
|
1552
|
-
await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`).catch(() => {});
|
|
1553
|
-
throw new Error("Google Cloud created a key that is no JSON key file.");
|
|
1554
|
-
}
|
|
1555
|
-
registerSecretValue(parsed.private_key);
|
|
1556
|
-
return {
|
|
1557
|
-
json,
|
|
1558
|
-
name: key.name,
|
|
1559
|
-
keyId: key.name.split("/").pop()
|
|
1560
|
-
};
|
|
1561
|
-
};
|
|
1562
|
-
//#endregion
|
|
1563
|
-
//#region src/playServiceAccount.ts
|
|
1564
|
-
/**
|
|
1565
|
-
* Hot Updater's issuer, the one place that picks how it is done: gcloud's
|
|
1566
|
-
* sign-in, then the Cloud Resource Manager, Service Usage, IAM, and Play
|
|
1567
|
-
* Developer APIs. Another implementation of `IssuePlayServiceAccount`
|
|
1568
|
-
* replaces it here without touching its callers.
|
|
1569
|
-
*/
|
|
1570
|
-
const issuePlayServiceAccount = (request) => createGoogleKeyIssuer()(request);
|
|
1571
1711
|
//#endregion
|
|
1572
|
-
export {
|
|
1712
|
+
export { PLAY_TRACKS, PlayVersionCodeUsedError, assertPlaySigned, buildAndroid, checkPlayAccess, enrichNativeBuildAndroidScheme, extractBuiltInBundle, findPlayInternalRelease, findSandboxGradleBlocker, installOnAndroidDevice, listAdbDevices, playConsoleInviteUrl, playTestingUrl, readBuiltApp, readBuiltPackageName, readBuiltVersionCode, readPlayHighestVersionCode, readPlayTrackRelease, resolvePlayUploadServiceAccount, selectAdbDevice, uploadToPlay };
|