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