@hot-updater/android-helper 1.2.0-rc.40 → 1.2.0-rc.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -225,6 +225,82 @@ async function getBuildOutputFilePath({ aab, appModuleName, buildDirectory, vari
225
225
  process.exit(1);
226
226
  }
227
227
  //#endregion
228
+ //#region src/utils/channelGradle.ts
229
+ /** Text as a single-quoted Groovy string. */
230
+ const groovyString$1 = (text) => `'${text.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'").replace(/\n/gu, "\\n")}'`;
231
+ /**
232
+ * The init script that makes one build embed `channel`, so no project file
233
+ * changes: on the app module, a task rewrites the variant's merged manifest
234
+ * (AGP's `MERGED_MANIFEST` transform), replacing or adding the
235
+ * `com.hotupdater.CHANNEL` meta-data the SDK reads. It runs after every
236
+ * manifest merged, the app's, a flavor's, an Expo config plugin's and a
237
+ * sandbox build's, so the channel is this one whatever they set.
238
+ */
239
+ const channelInitScript = ({ appModuleName, variant, channel }) => `// Written by hot-updater for one build: the channel it embeds.
240
+ def appModule = ${groovyString$1(`:${appModuleName}`)}
241
+ def variantName = ${groovyString$1(variant.toLowerCase())}
242
+ def channel = ${groovyString$1(channel)}
243
+ allprojects { project ->
244
+ if (project.path != appModule) return
245
+ project.plugins.withId('com.android.application') {
246
+ def components = project.extensions.getByName('androidComponents')
247
+ def mergedManifest = components.getClass().classLoader
248
+ .loadClass('com.android.build.api.artifact.SingleArtifact$MERGED_MANIFEST')
249
+ .getField('INSTANCE').get(null)
250
+ components.onVariants(components.selector().all()) { v ->
251
+ if (v.name.toLowerCase() != variantName) return
252
+ def stamp = project.tasks.register("hotUpdaterChannel\${v.name.capitalize()}", HotUpdaterChannelManifest) {
253
+ it.channel.set(channel)
254
+ }
255
+ v.artifacts.use(stamp)
256
+ .wiredWithFiles({ it.inputManifest }, { it.outputManifest })
257
+ .toTransform(mergedManifest)
258
+ }
259
+ }
260
+ }
261
+
262
+ abstract class HotUpdaterChannelManifest extends DefaultTask {
263
+ @InputFile abstract RegularFileProperty getInputManifest()
264
+ @OutputFile abstract RegularFileProperty getOutputManifest()
265
+ @Input abstract Property<String> getChannel()
266
+
267
+ @TaskAction void stamp() {
268
+ def value = channel.get()
269
+ .replace('&', '&amp;').replace('"', '&quot;')
270
+ .replace('<', '&lt;').replace('>', '&gt;')
271
+ def text = inputManifest.get().asFile.getText('UTF-8')
272
+ .replaceAll(/(?s)<meta-data\\b(?:(?!\\/>|>).)*?android:name="com\\.hotupdater\\.CHANNEL"(?:(?!\\/>|>).)*?(?:\\/>|>.*?<\\/meta-data>)\\s*/, '')
273
+ def entry = "<meta-data android:name=\\"com.hotupdater.CHANNEL\\" android:value=\\"\${value}\\" />"
274
+ def closing = text.lastIndexOf('</application>')
275
+ if (closing < 0) throw new GradleException('The merged manifest has no <application>.')
276
+ outputManifest.get().asFile.setText(text.substring(0, closing) + entry + '\\n ' + text.substring(closing), 'UTF-8')
277
+ }
278
+ }
279
+ `;
280
+ /**
281
+ * Runs `build` with the Gradle arguments that make it embed `channel`: none
282
+ * without one. The init script is written outside the project, and removed
283
+ * after.
284
+ */
285
+ const withChannelGradleArgs = async (channel, scheme, build) => {
286
+ if (channel === void 0) return build([]);
287
+ const directory = await fs.default.promises.mkdtemp(path.default.join(os.default.tmpdir(), "hot-updater-channel-"));
288
+ try {
289
+ const script = path.default.join(directory, "channel.init.gradle");
290
+ await fs.default.promises.writeFile(script, channelInitScript({
291
+ appModuleName: scheme.appModuleName,
292
+ variant: scheme.variant,
293
+ channel
294
+ }));
295
+ return await build(["--init-script", script]);
296
+ } finally {
297
+ await fs.default.promises.rm(directory, {
298
+ recursive: true,
299
+ force: true
300
+ });
301
+ }
302
+ };
303
+ //#endregion
228
304
  //#region src/utils/gradleSigning.ts
229
305
  const isDebugVariant = (variant) => /debug$/i.test(variant);
230
306
  /**
@@ -598,8 +674,8 @@ const filterXml = ({ actions, categories, data, attributes }, extra = "") => [
598
674
  ].map((line) => ` ${line}`).join("\n");
599
675
  const optional = (name, value) => value === void 0 ? "" : ` android:${name}="${xml(value)}"`;
600
676
  /**
601
- * The manifest a sandbox build overlays on the app's. `tools:replace` wins over
602
- * a channel the app's manifest sets, as an Expo project's does. The launcher's
677
+ * The manifest a sandbox build overlays on the app's, which keeps the app's
678
+ * channel: a sandbox build embeds the project's, as any build does. The launcher's
603
679
  * filter, label, icon and static shortcuts move to the sandbox's activity, which
604
680
  * also takes the links of `urlScheme`, which its `<meta-data>` names for the
605
681
  * build to read; the rest of the app's activity stays, so its own links still
@@ -607,10 +683,9 @@ const optional = (name, value) => value === void 0 ? "" : ` android:${name}="${x
607
683
  * The dev server is plain http, which a project's network security config can
608
684
  * still refuse: the screen then says so.
609
685
  */
610
- const sandboxManifestOverlay = ({ channel, urlScheme, launcher }) => `<?xml version="1.0" encoding="utf-8"?>
686
+ const sandboxManifestOverlay = ({ urlScheme, launcher }) => `<?xml version="1.0" encoding="utf-8"?>
611
687
  <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
612
688
  <application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic">
613
- <meta-data android:name="com.hotupdater.CHANNEL" android:value="${xml(channel)}" tools:replace="android:value" />
614
689
  <meta-data android:name="${_hot_updater_protocol_native_artifact.SANDBOX_META_DATA}" android:value="true" />
615
690
  <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)}>
616
691
  ${filterXml(launcher.filter)}
@@ -729,7 +804,6 @@ const withSandboxGradleArgs = async (scheme, readEffectiveManifest, build, { min
729
804
  const overlay = path.default.join(directory, "AndroidManifest.xml");
730
805
  const initScript = path.default.join(directory, "sandbox.init.gradle");
731
806
  await fs.default.promises.writeFile(overlay, sandboxManifestOverlay({
732
- channel: (0, _hot_updater_protocol_native_artifact.sandboxChannelOf)(scheme.hotUpdaterSchemeName),
733
807
  urlScheme,
734
808
  launcher
735
809
  }));
@@ -783,7 +857,7 @@ const findSandboxGradleBlocker = ({ variant = "Release", appModuleName = "app" }
783
857
  };
784
858
  //#endregion
785
859
  //#region src/buildAndroid.ts
786
- const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials, logHeader, minVersionCode }) => {
860
+ const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials, logHeader, minVersionCode, channel }) => {
787
861
  const androidProjectPath = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "android");
788
862
  const env = await resolveGradleSigningEnv({
789
863
  schemeConfig,
@@ -804,15 +878,19 @@ const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_t
804
878
  appModuleName: schemeConfig.appModuleName,
805
879
  variant: schemeConfig.variant
806
880
  });
807
- }, (sandboxArgs) => runGradle({
808
- args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`, ...sandboxArgs] },
881
+ }, (sandboxArgs) => withChannelGradleArgs(channel, schemeConfig, (channelArgs) => runGradle({
882
+ args: { extraParams: [
883
+ `-PMIN_BUNDLE_ID=${minBundleId}`,
884
+ ...sandboxArgs,
885
+ ...channelArgs
886
+ ] },
809
887
  env,
810
888
  appModuleName: schemeConfig.appModuleName,
811
889
  tasks: schemeConfig.aab ? [`bundle${schemeConfig.variant}`] : [`assemble${schemeConfig.variant}`],
812
890
  logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-build`,
813
891
  androidProjectPath,
814
892
  logHeader
815
- }), minVersionCode === void 0 ? {} : { minVersionCode });
893
+ })), minVersionCode === void 0 ? {} : { minVersionCode });
816
894
  return {
817
895
  ...result,
818
896
  builtApp: await readBuiltApp({
package/dist/index.d.cts CHANGED
@@ -13,7 +13,7 @@ declare const enrichNativeBuildAndroidScheme: ({ schemeConfig, hotUpdaterSchemeN
13
13
  }) => Promise<EnrichedNativeBuildAndroidScheme>;
14
14
  //#endregion
15
15
  //#region src/buildAndroid.d.ts
16
- declare const buildAndroid: ({ schemeConfig, minBundleId, credentials, logHeader, minVersionCode }: {
16
+ declare const buildAndroid: ({ schemeConfig, minBundleId, credentials, logHeader, minVersionCode, channel }: {
17
17
  schemeConfig: EnrichedNativeBuildAndroidScheme;
18
18
  /** The MIN_BUNDLE_ID the build compiles in. */
19
19
  minBundleId?: string;
@@ -23,6 +23,11 @@ declare const buildAndroid: ({ schemeConfig, minBundleId, credentials, logHeader
23
23
  logHeader?: string[];
24
24
  /** The lowest version code a sandbox build may have. */
25
25
  minVersionCode?: number;
26
+ /**
27
+ * The channel the build embeds, whatever the project's files or an Expo
28
+ * config plugin set; without it, theirs.
29
+ */
30
+ channel?: string;
26
31
  }) => Promise<{
27
32
  buildDirectory: string;
28
33
  buildArtifactPath: string;
package/dist/index.d.mts CHANGED
@@ -14,7 +14,7 @@ declare const enrichNativeBuildAndroidScheme: ({ schemeConfig, hotUpdaterSchemeN
14
14
  }) => Promise<EnrichedNativeBuildAndroidScheme>;
15
15
  //#endregion
16
16
  //#region src/buildAndroid.d.ts
17
- declare const buildAndroid: ({ schemeConfig, minBundleId, credentials, logHeader, minVersionCode }: {
17
+ declare const buildAndroid: ({ schemeConfig, minBundleId, credentials, logHeader, minVersionCode, channel }: {
18
18
  schemeConfig: EnrichedNativeBuildAndroidScheme;
19
19
  /** The MIN_BUNDLE_ID the build compiles in. */
20
20
  minBundleId?: string;
@@ -24,6 +24,11 @@ declare const buildAndroid: ({ schemeConfig, minBundleId, credentials, logHeader
24
24
  logHeader?: string[];
25
25
  /** The lowest version code a sandbox build may have. */
26
26
  minVersionCode?: number;
27
+ /**
28
+ * The channel the build embeds, whatever the project's files or an Expo
29
+ * config plugin set; without it, theirs.
30
+ */
31
+ channel?: string;
27
32
  }) => Promise<{
28
33
  buildDirectory: string;
29
34
  buildArtifactPath: string;
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import { ExecaError, execa } from "execa";
5
5
  import os from "os";
6
6
  import JSZip from "jszip";
7
7
  import { createRequire } from "module";
8
- import { SANDBOX_ACTIVITY, SANDBOX_APPLICATION_ID_SUFFIX, SANDBOX_META_DATA, SANDBOX_URL_SCHEME_META_DATA, sandboxChannelOf, sandboxUrlSchemeOf } from "@hot-updater/protocol/native-artifact";
8
+ import { SANDBOX_ACTIVITY, SANDBOX_APPLICATION_ID_SUFFIX, SANDBOX_META_DATA, SANDBOX_URL_SCHEME_META_DATA, sandboxUrlSchemeOf } from "@hot-updater/protocol/native-artifact";
9
9
  import { XMLParser } from "fast-xml-parser";
10
10
  import crypto from "crypto";
11
11
  import { pipeline } from "stream/promises";
@@ -197,6 +197,82 @@ async function getBuildOutputFilePath({ aab, appModuleName, buildDirectory, vari
197
197
  process.exit(1);
198
198
  }
199
199
  //#endregion
200
+ //#region src/utils/channelGradle.ts
201
+ /** Text as a single-quoted Groovy string. */
202
+ const groovyString$1 = (text) => `'${text.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'").replace(/\n/gu, "\\n")}'`;
203
+ /**
204
+ * The init script that makes one build embed `channel`, so no project file
205
+ * changes: on the app module, a task rewrites the variant's merged manifest
206
+ * (AGP's `MERGED_MANIFEST` transform), replacing or adding the
207
+ * `com.hotupdater.CHANNEL` meta-data the SDK reads. It runs after every
208
+ * manifest merged, the app's, a flavor's, an Expo config plugin's and a
209
+ * sandbox build's, so the channel is this one whatever they set.
210
+ */
211
+ const channelInitScript = ({ appModuleName, variant, channel }) => `// Written by hot-updater for one build: the channel it embeds.
212
+ def appModule = ${groovyString$1(`:${appModuleName}`)}
213
+ def variantName = ${groovyString$1(variant.toLowerCase())}
214
+ def channel = ${groovyString$1(channel)}
215
+ allprojects { project ->
216
+ if (project.path != appModule) return
217
+ project.plugins.withId('com.android.application') {
218
+ def components = project.extensions.getByName('androidComponents')
219
+ def mergedManifest = components.getClass().classLoader
220
+ .loadClass('com.android.build.api.artifact.SingleArtifact$MERGED_MANIFEST')
221
+ .getField('INSTANCE').get(null)
222
+ components.onVariants(components.selector().all()) { v ->
223
+ if (v.name.toLowerCase() != variantName) return
224
+ def stamp = project.tasks.register("hotUpdaterChannel\${v.name.capitalize()}", HotUpdaterChannelManifest) {
225
+ it.channel.set(channel)
226
+ }
227
+ v.artifacts.use(stamp)
228
+ .wiredWithFiles({ it.inputManifest }, { it.outputManifest })
229
+ .toTransform(mergedManifest)
230
+ }
231
+ }
232
+ }
233
+
234
+ abstract class HotUpdaterChannelManifest extends DefaultTask {
235
+ @InputFile abstract RegularFileProperty getInputManifest()
236
+ @OutputFile abstract RegularFileProperty getOutputManifest()
237
+ @Input abstract Property<String> getChannel()
238
+
239
+ @TaskAction void stamp() {
240
+ def value = channel.get()
241
+ .replace('&', '&amp;').replace('"', '&quot;')
242
+ .replace('<', '&lt;').replace('>', '&gt;')
243
+ def text = inputManifest.get().asFile.getText('UTF-8')
244
+ .replaceAll(/(?s)<meta-data\\b(?:(?!\\/>|>).)*?android:name="com\\.hotupdater\\.CHANNEL"(?:(?!\\/>|>).)*?(?:\\/>|>.*?<\\/meta-data>)\\s*/, '')
245
+ def entry = "<meta-data android:name=\\"com.hotupdater.CHANNEL\\" android:value=\\"\${value}\\" />"
246
+ def closing = text.lastIndexOf('</application>')
247
+ if (closing < 0) throw new GradleException('The merged manifest has no <application>.')
248
+ outputManifest.get().asFile.setText(text.substring(0, closing) + entry + '\\n ' + text.substring(closing), 'UTF-8')
249
+ }
250
+ }
251
+ `;
252
+ /**
253
+ * Runs `build` with the Gradle arguments that make it embed `channel`: none
254
+ * without one. The init script is written outside the project, and removed
255
+ * after.
256
+ */
257
+ const withChannelGradleArgs = async (channel, scheme, build) => {
258
+ if (channel === void 0) return build([]);
259
+ const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), "hot-updater-channel-"));
260
+ try {
261
+ const script = path.join(directory, "channel.init.gradle");
262
+ await fs.promises.writeFile(script, channelInitScript({
263
+ appModuleName: scheme.appModuleName,
264
+ variant: scheme.variant,
265
+ channel
266
+ }));
267
+ return await build(["--init-script", script]);
268
+ } finally {
269
+ await fs.promises.rm(directory, {
270
+ recursive: true,
271
+ force: true
272
+ });
273
+ }
274
+ };
275
+ //#endregion
200
276
  //#region src/utils/gradleSigning.ts
201
277
  const isDebugVariant = (variant) => /debug$/i.test(variant);
202
278
  /**
@@ -570,8 +646,8 @@ const filterXml = ({ actions, categories, data, attributes }, extra = "") => [
570
646
  ].map((line) => ` ${line}`).join("\n");
571
647
  const optional = (name, value) => value === void 0 ? "" : ` android:${name}="${xml(value)}"`;
572
648
  /**
573
- * The manifest a sandbox build overlays on the app's. `tools:replace` wins over
574
- * a channel the app's manifest sets, as an Expo project's does. The launcher's
649
+ * The manifest a sandbox build overlays on the app's, which keeps the app's
650
+ * channel: a sandbox build embeds the project's, as any build does. The launcher's
575
651
  * filter, label, icon and static shortcuts move to the sandbox's activity, which
576
652
  * also takes the links of `urlScheme`, which its `<meta-data>` names for the
577
653
  * build to read; the rest of the app's activity stays, so its own links still
@@ -579,10 +655,9 @@ const optional = (name, value) => value === void 0 ? "" : ` android:${name}="${x
579
655
  * The dev server is plain http, which a project's network security config can
580
656
  * still refuse: the screen then says so.
581
657
  */
582
- const sandboxManifestOverlay = ({ channel, urlScheme, launcher }) => `<?xml version="1.0" encoding="utf-8"?>
658
+ const sandboxManifestOverlay = ({ urlScheme, launcher }) => `<?xml version="1.0" encoding="utf-8"?>
583
659
  <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
584
660
  <application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic">
585
- <meta-data android:name="com.hotupdater.CHANNEL" android:value="${xml(channel)}" tools:replace="android:value" />
586
661
  <meta-data android:name="${SANDBOX_META_DATA}" android:value="true" />
587
662
  <activity android:name="${SANDBOX_ACTIVITY}" android:exported="true" android:launchMode="singleTop" android:theme="@style/HotUpdaterSandboxTheme" android:configChanges="density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:enableOnBackInvokedCallback="true"${optional("label", launcher.label)}${optional("icon", launcher.icon)}${optional("roundIcon", launcher.roundIcon)}>
588
663
  ${filterXml(launcher.filter)}
@@ -701,7 +776,6 @@ const withSandboxGradleArgs = async (scheme, readEffectiveManifest, build, { min
701
776
  const overlay = path.join(directory, "AndroidManifest.xml");
702
777
  const initScript = path.join(directory, "sandbox.init.gradle");
703
778
  await fs.promises.writeFile(overlay, sandboxManifestOverlay({
704
- channel: sandboxChannelOf(scheme.hotUpdaterSchemeName),
705
779
  urlScheme,
706
780
  launcher
707
781
  }));
@@ -755,7 +829,7 @@ const findSandboxGradleBlocker = ({ variant = "Release", appModuleName = "app" }
755
829
  };
756
830
  //#endregion
757
831
  //#region src/buildAndroid.ts
758
- const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), credentials, logHeader, minVersionCode }) => {
832
+ const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), credentials, logHeader, minVersionCode, channel }) => {
759
833
  const androidProjectPath = path.join(getCwd(), "android");
760
834
  const env = await resolveGradleSigningEnv({
761
835
  schemeConfig,
@@ -776,15 +850,19 @@ const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), c
776
850
  appModuleName: schemeConfig.appModuleName,
777
851
  variant: schemeConfig.variant
778
852
  });
779
- }, (sandboxArgs) => runGradle({
780
- args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`, ...sandboxArgs] },
853
+ }, (sandboxArgs) => withChannelGradleArgs(channel, schemeConfig, (channelArgs) => runGradle({
854
+ args: { extraParams: [
855
+ `-PMIN_BUNDLE_ID=${minBundleId}`,
856
+ ...sandboxArgs,
857
+ ...channelArgs
858
+ ] },
781
859
  env,
782
860
  appModuleName: schemeConfig.appModuleName,
783
861
  tasks: schemeConfig.aab ? [`bundle${schemeConfig.variant}`] : [`assemble${schemeConfig.variant}`],
784
862
  logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-build`,
785
863
  androidProjectPath,
786
864
  logHeader
787
- }), minVersionCode === void 0 ? {} : { minVersionCode });
865
+ })), minVersionCode === void 0 ? {} : { minVersionCode });
788
866
  return {
789
867
  ...result,
790
868
  builtApp: await readBuiltApp({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hot-updater/android-helper",
3
- "version": "1.2.0-rc.40",
3
+ "version": "1.2.0-rc.42",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -30,9 +30,9 @@
30
30
  "execa": "9.5.2",
31
31
  "fast-xml-parser": "5.7.2",
32
32
  "jszip": "^3.10.1",
33
- "@hot-updater/cli-tools": "1.2.0-rc.40",
34
- "@hot-updater/protocol": "1.2.0-rc.40",
35
- "@hot-updater/plugin-core": "1.2.0-rc.40"
33
+ "@hot-updater/cli-tools": "1.2.0-rc.42",
34
+ "@hot-updater/plugin-core": "1.2.0-rc.42",
35
+ "@hot-updater/protocol": "1.2.0-rc.42"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/node": "^20"