@threenative/runtime-native 0.3.2 → 0.3.3

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.
@@ -8,24 +8,244 @@ import {
8
8
  mkdirSync,
9
9
  readFileSync,
10
10
  readdirSync,
11
+ renameSync,
11
12
  rmSync,
12
13
  statSync,
13
14
  writeFileSync,
14
15
  } from 'node:fs';
15
- import { dirname, join, posix, resolve } from 'node:path';
16
+ import { homedir } from 'node:os';
17
+ import { dirname, join, resolve } from 'node:path';
16
18
  import { fileURLToPath, pathToFileURL } from 'node:url';
17
19
  import { downloadReleaseArtifact, releaseManifestUrl, verifyChecksum } from './install-prebuilt.mjs';
20
+ import { listFiles, selectManifestAssets } from './asset-manifest.mjs';
18
21
  import { assertAndroidAssetsDecodable, deriveAndroidWebpSupport } from './asset-preflight.mjs';
22
+ import {
23
+ assertAndroidArtifact16KbAlignment,
24
+ resolveZipalignCandidates,
25
+ } from './check-android-16kb-alignment.mjs';
19
26
 
20
27
  const runtimeRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
21
28
  export const GRADLE_WRAPPER_URL =
22
- 'https://raw.githubusercontent.com/gradle/gradle/v8.5.0/gradle/wrapper/gradle-wrapper.jar';
29
+ 'https://raw.githubusercontent.com/gradle/gradle/v8.13.0/gradle/wrapper/gradle-wrapper.jar';
23
30
  export const GRADLE_WRAPPER_SHA256 =
24
- 'd3b261c2820e9e3d8d639ed084900f11f4a86050a8f83342ade7b6bc9b0d2bdd';
31
+ '81a82aaea5abcc8ff68b3dfcb58b3c3c429378efd98e7433460610fecd7ae45f';
25
32
 
26
33
  export const ANDROID_ABIS = ['arm64-v8a', 'x86_64'];
27
34
  export const ANDROID_ENGINES = ['quickjs', 'v8'];
28
35
 
36
+ /**
37
+ * The Android submission API level Google Play requires of a new app or update.
38
+ *
39
+ * PRD-212 phase 1. It is the one literal the packaging layer owns; the shipped
40
+ * `android/app/build.gradle.kts` carries the same number, and `assertAndroidSubmissionTargetSdk`
41
+ * refuses a build whose rendered project is below it. Raise both together — Play raises the floor
42
+ * on its own schedule, and a build that silently drops below it ships an artifact that is
43
+ * rejected at upload.
44
+ */
45
+ export const ANDROID_SUBMISSION_TARGET_SDK = 36;
46
+
47
+ /** The `targetSdk` a Gradle Android project source declares, if it declares one. */
48
+ export function androidGradleTargetSdk(source) {
49
+ const match = /targetSdk\s*=\s*(\d+)/u.exec(String(source ?? ''));
50
+ return match === null ? undefined : Number(match[1]);
51
+ }
52
+
53
+ /**
54
+ * Refuse a rendered Android project whose `targetSdk` is below the submission floor.
55
+ *
56
+ * Fail closed on a missing `targetSdk`: an unparsable project is a project whose submission level
57
+ * nobody can vouch for, which is exactly what this gate exists to catch.
58
+ */
59
+ export function assertAndroidSubmissionTargetSdk(source, required = ANDROID_SUBMISSION_TARGET_SDK) {
60
+ const declared = androidGradleTargetSdk(source);
61
+ if (declared === undefined) {
62
+ throw new Error(
63
+ `TN_ANDROID_TARGET_SDK_MISSING: android/app/build.gradle.kts declares no targetSdk; submission requires API ${required}.`,
64
+ );
65
+ }
66
+ if (declared < required) {
67
+ throw new Error(
68
+ `TN_ANDROID_TARGET_SDK_BELOW_SUBMISSION: targetSdk ${declared} is below the required API ${required}; update android/app/build.gradle.kts before packaging a release.`,
69
+ );
70
+ }
71
+ return declared;
72
+ }
73
+
74
+ /**
75
+ * The four Gradle project properties a consumer-owned release signs with.
76
+ *
77
+ * PRD-212 phase 3. The names are the contract between the game's build environment and
78
+ * `android/app/build.gradle.kts`; `packages/create-threenative/src/doctor.ts` predicts the same four
79
+ * in their `ORG_GRADLE_PROJECT_` transport spelling, and a test fails if the two lists drift.
80
+ * Values are read here only to hand them to the signing subprocess and are never logged or
81
+ * serialized into the packaging config.
82
+ */
83
+ export const ANDROID_RELEASE_SIGNING_PROPERTIES = Object.freeze({
84
+ keystore: 'threenativeKeystore',
85
+ keyAlias: 'threenativeKeystoreAlias',
86
+ keystorePassword: 'threenativeKeystorePassword',
87
+ keyPassword: 'threenativeKeyPassword',
88
+ });
89
+
90
+ /**
91
+ * Resolve the signing inputs from the build environment, resolving the keystore against the
92
+ * consumer project rather than the engine's Android project directory.
93
+ *
94
+ * Returns the password values so they can be forwarded to Gradle; callers must not print them.
95
+ */
96
+ export function androidReleaseSigning(environment = process.env, projectRoot = undefined) {
97
+ const read = (property) => (environment[`ORG_GRADLE_PROJECT_${property}`] ?? '').trim();
98
+ const keystore = read(ANDROID_RELEASE_SIGNING_PROPERTIES.keystore);
99
+ const resolvedKeystore =
100
+ keystore.length === 0 || projectRoot === undefined ? keystore : resolve(projectRoot, keystore);
101
+ const values = {
102
+ keystore: resolvedKeystore,
103
+ keyAlias: read(ANDROID_RELEASE_SIGNING_PROPERTIES.keyAlias),
104
+ keystorePassword: read(ANDROID_RELEASE_SIGNING_PROPERTIES.keystorePassword),
105
+ keyPassword: read(ANDROID_RELEASE_SIGNING_PROPERTIES.keyPassword),
106
+ };
107
+ const missing = Object.entries(values)
108
+ .filter(([, value]) => value.length === 0)
109
+ .map(([role]) => `ORG_GRADLE_PROJECT_${ANDROID_RELEASE_SIGNING_PROPERTIES[role]}`);
110
+ return {
111
+ ...values,
112
+ complete: missing.length === 0,
113
+ missing,
114
+ };
115
+ }
116
+
117
+ /** The environment Gradle sees, with the four signing properties rewritten to resolved values. */
118
+ export function androidSigningGradleEnvironment(signing, environment = process.env) {
119
+ return {
120
+ ...environment,
121
+ ORG_GRADLE_PROJECT_threenativeKeystore: signing.keystore,
122
+ ORG_GRADLE_PROJECT_threenativeKeystoreAlias: signing.keyAlias,
123
+ ORG_GRADLE_PROJECT_threenativeKeystorePassword: signing.keystorePassword,
124
+ ORG_GRADLE_PROJECT_threenativeKeyPassword: signing.keyPassword,
125
+ };
126
+ }
127
+
128
+ /** Locate an Android build tool on `PATH`, then in the SDK's `build-tools/<version>/`. */
129
+ export function findAndroidBuildTool(name, environment = process.env) {
130
+ const suffix = process.platform === 'win32' ? '.bat' : '';
131
+ const onPath = spawnSync(`${name}${suffix}`, ['--version'], {
132
+ encoding: 'utf8',
133
+ stdio: ['ignore', 'pipe', 'pipe'],
134
+ timeout: 5_000,
135
+ });
136
+ if (onPath.error === undefined && onPath.status !== null) return `${name}${suffix}`;
137
+ const roots = [environment.ANDROID_HOME, environment.ANDROID_SDK_ROOT]
138
+ .filter((root) => typeof root === 'string' && root.length > 0)
139
+ .concat(join(homedir(), 'Android', 'Sdk'));
140
+ for (const root of roots) {
141
+ if (!existsSync(root)) continue;
142
+ const buildTools = join(root, 'build-tools');
143
+ if (!existsSync(buildTools)) continue;
144
+ const versions = readdirSync(buildTools).sort((left, right) =>
145
+ right.localeCompare(left, 'en', { numeric: true }),
146
+ );
147
+ for (const version of versions) {
148
+ const candidate = join(buildTools, version, `${name}${suffix}`);
149
+ if (existsSync(candidate)) return candidate;
150
+ }
151
+ const direct = join(root, 'tools', 'bin', `${name}${suffix}`);
152
+ if (existsSync(direct)) return direct;
153
+ }
154
+ return undefined;
155
+ }
156
+
157
+ function onlySelfSignedCertificateErrors(output) {
158
+ const errors = /^Error:[ \t]*\r?\n((?:[^\r\n]+\r?\n)+)/mu.exec(output)?.[1]
159
+ .trim().split(/\r?\n/u).map((line) => line.trim()) ?? [];
160
+ const selfSigned = 'This jar contains entries whose signer certificate is self-signed.';
161
+ return errors.includes(selfSigned) && errors.every((line) =>
162
+ line === selfSigned ||
163
+ /^This jar contains entries whose certificate chain is invalid\. Reason: PKIX path building failed: .*: unable to find valid certification path to requested target$/u.test(line),
164
+ );
165
+ }
166
+
167
+ /**
168
+ * Prove a release artifact is really signed, targets the submission SDK and is not debuggable.
169
+ *
170
+ * `verifyReleaseSignature` is the injectable seam the integration lane uses to stand in for the
171
+ * SDK tools; on a real build the signature is read with `apksigner` (APK) or `jarsigner` (AAB), and
172
+ * a missing verifier is a blocker rather than a silent pass. An APK is additionally read back with
173
+ * `aapt`, so the gate checks the artifact itself — its packaged `targetSdkVersion` and absence of
174
+ * `application-debuggable` — rather than trusting the Gradle source. Nothing here reads a signing
175
+ * value except the tool invocations Gradle already owns.
176
+ */
177
+ export function verifyAndroidReleaseArtifact(artifact, request, options = {}) {
178
+ const environment = options.environment ?? process.env;
179
+ const run = options.spawnSync ?? spawnSync;
180
+ if (options.verifyReleaseSignature !== undefined) {
181
+ return options.verifyReleaseSignature(artifact, request);
182
+ }
183
+ const locate = (name) =>
184
+ options.findBuildTool !== undefined
185
+ ? options.findBuildTool(name)
186
+ : findAndroidBuildTool(name, environment);
187
+ const tool = request.format === 'aab' ? 'jarsigner' : 'apksigner';
188
+ const executable = locate(tool);
189
+ if (executable === undefined) {
190
+ throw new Error(
191
+ `TN_ANDROID_SIGNATURE_TOOL_MISSING: ${tool} is unavailable, so the ${request.format} signature cannot be verified. Install the Android build-tools, or set ANDROID_HOME.`,
192
+ );
193
+ }
194
+ const args = tool === 'apksigner'
195
+ ? ['verify', '--print-certs', artifact]
196
+ : ['-J-Duser.language=en', '-J-Duser.country=US', '-verify', '-strict', artifact];
197
+ const result = run(executable, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
198
+ if (result.error) throw result.error;
199
+ const output = `${result.stdout ?? ''}${result.stderr ?? ''}`;
200
+ // Android signing certificates are normally self-signed (jarsigner warning bit 4).
201
+ // That bit also covers expired certificates, so accept only the named self-signed errors.
202
+ // Strict verification still rejects unsigned entries (bit 16) and invalid signatures.
203
+ // An entirely unsigned archive can exit 0, so positive signature evidence is required too.
204
+ const signatureValid = tool === 'apksigner'
205
+ ? result.status === 0
206
+ : (result.status === 0 || (result.status === 4 && onlySelfSignedCertificateErrors(output))) &&
207
+ /^jar verified(?:\.|, with signer errors\.)\r?$/mu.test(output);
208
+ if (!signatureValid) {
209
+ throw new Error(
210
+ `TN_ANDROID_SIGNATURE_INVALID: ${tool} rejected ${artifact}: ${output.trim() || 'unknown reason'}`,
211
+ );
212
+ }
213
+ const facts = { output };
214
+ if (request.format === 'aab') return facts;
215
+ // The APK's own badging is the artifact-level half of the phase-1 gate: a project whose source
216
+ // says 36 but whose packaged manifest says 35 is what a source-only check misses.
217
+ const aapt = locate('aapt');
218
+ if (aapt === undefined) {
219
+ throw new Error(
220
+ `TN_ANDROID_BADGING_TOOL_MISSING: aapt is unavailable, so the release APK's targetSdk and debuggable state cannot be read. Install the Android build-tools, or set ANDROID_HOME.`,
221
+ );
222
+ }
223
+ const badging = run(aapt, ['dump', 'badging', artifact], {
224
+ encoding: 'utf8',
225
+ stdio: ['ignore', 'pipe', 'pipe'],
226
+ });
227
+ if (badging.error) throw badging.error;
228
+ const badgingText = `${badging.stdout ?? ''}${badging.stderr ?? ''}`;
229
+ if (badging.status !== 0) {
230
+ throw new Error(`TN_ANDROID_BADGING_FAILED: aapt could not read ${artifact}.`);
231
+ }
232
+ const targetSdk = /targetSdkVersion:'(\d+)'/u.exec(badgingText)?.[1];
233
+ if (targetSdk === undefined) {
234
+ throw new Error(`TN_ANDROID_BADGING_INCOMPLETE: aapt reported no targetSdkVersion for ${artifact}.`);
235
+ }
236
+ if (Number(targetSdk) < ANDROID_SUBMISSION_TARGET_SDK) {
237
+ throw new Error(
238
+ `TN_ANDROID_TARGET_SDK_BELOW_SUBMISSION: packaged targetSdk ${targetSdk} is below the required API ${ANDROID_SUBMISSION_TARGET_SDK}.`,
239
+ );
240
+ }
241
+ if (/application-debuggable/u.test(badgingText)) {
242
+ throw new Error(`TN_ANDROID_ARTIFACT_DEBUGGABLE: ${artifact} is debuggable.`);
243
+ }
244
+ return { output, targetSdk: Number(targetSdk) };
245
+ }
246
+
247
+
248
+
29
249
  /**
30
250
  * The QuickJS prebuilt set. Unchanged, and still the meaning of the unqualified release keys.
31
251
  *
@@ -543,17 +763,6 @@ export async function ensureGradleWrapper(options = {}) {
543
763
  return output;
544
764
  }
545
765
 
546
- function listFiles(directory, relative = '') {
547
- const files = [];
548
- for (const entry of readdirSync(join(directory, relative), { withFileTypes: true })) {
549
- const path = relative ? posix.join(relative, entry.name) : entry.name;
550
- if (entry.isDirectory()) files.push(...listFiles(directory, path));
551
- else if (entry.isFile()) files.push(path);
552
- else throw new Error(`Unsupported Android asset entry: ${join(directory, path)}`);
553
- }
554
- return files.sort();
555
- }
556
-
557
766
  export function stageAndroidAssets(
558
767
  assets,
559
768
  destination = join(runtimeRoot, 'android', 'app', 'build', 'generated', 'threenative', 'assets', 'game'),
@@ -571,7 +780,7 @@ export function stageAndroidAssets(
571
780
  // Derived from the runtime this build is about to pack, not declared here. A hardcoded claim
572
781
  // goes stale the moment the build changes under it, which is exactly what happened to WebP.
573
782
  assertAndroidAssetsDecodable(assets, { webp: deriveAndroidWebpSupport(runtimeSource) });
574
- const files = listFiles(assets);
783
+ const files = selectManifestAssets(assets);
575
784
  for (const file of files) {
576
785
  const output = join(destination, file);
577
786
  mkdirSync(dirname(output), { recursive: true });
@@ -621,6 +830,163 @@ export function stageAndroidUi(ui, renderer, destination) {
621
830
  return files;
622
831
  }
623
832
 
833
+ export const ANDROID_BUILD_MODES = ['debug', 'release'];
834
+ export const ANDROID_BUILD_FORMATS = ['apk', 'aab'];
835
+
836
+ /**
837
+ * Resolve a requested mode/format pair into the Gradle task and the artifact it must produce.
838
+ *
839
+ * PRD-212 phase 2. `debug/apk` stays the default; a release APK and a release AAB are the two
840
+ * explicit routes. An AAB is a Play submission shape, so `debug/aab` is refused before any work.
841
+ */
842
+ export function androidBuildRequest(mode = 'debug', format = 'apk') {
843
+ const resolvedMode = String(mode).toLowerCase();
844
+ const resolvedFormat = String(format).toLowerCase();
845
+ if (!ANDROID_BUILD_MODES.includes(resolvedMode)) {
846
+ throw new Error(
847
+ `TN_ANDROID_BUILD_MODE_INVALID: unknown mode '${mode}'; expected debug or release.`,
848
+ );
849
+ }
850
+ if (!ANDROID_BUILD_FORMATS.includes(resolvedFormat)) {
851
+ throw new Error(
852
+ `TN_ANDROID_BUILD_FORMAT_INVALID: unknown format '${format}'; expected apk or aab.`,
853
+ );
854
+ }
855
+ if (resolvedFormat === 'aab' && resolvedMode !== 'release') {
856
+ throw new Error('TN_ANDROID_BUILD_UNSUPPORTED: --format aab requires --mode release.');
857
+ }
858
+ const task =
859
+ resolvedFormat === 'aab'
860
+ ? 'bundleRelease'
861
+ : resolvedMode === 'release'
862
+ ? 'assembleRelease'
863
+ : 'assembleDebug';
864
+ return { format: resolvedFormat, mode: resolvedMode, task };
865
+ }
866
+
867
+ /**
868
+ * The ABI override the packager hands Gradle.
869
+ *
870
+ * A release is what Play installs on a phone, where only `arm64-v8a` runs, so release names that
871
+ * one slice; the `x86_64` emulator dev lane lives in debug, which keeps Gradle's both-ABI default. An explicit
872
+ * `-PthreenativeAbis` from the caller wins in both modes — no default overrides a named set.
873
+ */
874
+ export function androidAbiGradleArgs(mode, extraGradleArgs = []) {
875
+ const namesAbis = extraGradleArgs.some((arg) =>
876
+ /^(?:-P|--project-prop=)threenativeAbis=/u.test(arg),
877
+ );
878
+ return mode === 'release' && !namesAbis ? ['-PthreenativeAbis=arm64-v8a'] : [];
879
+ }
880
+
881
+ /**
882
+ * The ABI set a Gradle invocation builds: its last `-PthreenativeAbis`, or `undefined` for Gradle's
883
+ * own default. The 16 KB census checks exactly this set, so a release (arm64-v8a) or an
884
+ * emulator-only (x86_64) build is not failed for the slice it deliberately left out.
885
+ */
886
+ export function androidRequestedAbis(gradleArgs) {
887
+ const value = gradleArgs
888
+ .map((arg) => /^(?:-P|--project-prop=)threenativeAbis=(.*)$/u.exec(arg)?.[1])
889
+ .filter((entry) => entry !== undefined)
890
+ .at(-1);
891
+ return value
892
+ ?.split(',')
893
+ .map((abi) => abi.trim())
894
+ .filter((abi) => abi.length > 0);
895
+ }
896
+
897
+ /**
898
+ * The exact artifacts a resolved request may produce, in preference order.
899
+ *
900
+ * A release APK is signed, so only `app-release.apk` satisfies it; `app-release-unsigned.apk` is a
901
+ * failed release and is named separately so the refusal can say so. A debug request is the only
902
+ * route that accepts `app-debug.apk`, which is how a debug artifact stops being reported as a
903
+ * release.
904
+ */
905
+ export function androidArtifactCandidates(packageRoot, request) {
906
+ const outputs = join(packageRoot, 'android', 'app', 'build', 'outputs');
907
+ if (request.format === 'aab') return [join(outputs, 'bundle', 'release', 'app-release.aab')];
908
+ if (request.mode === 'debug') return [join(outputs, 'apk', 'debug', 'app-debug.apk')];
909
+ return [join(outputs, 'apk', 'release', 'app-release.apk')];
910
+ }
911
+
912
+ /** The unsigned release APK AGP emits when no signing config is applied. */
913
+ export function androidUnsignedReleaseApk(packageRoot) {
914
+ return join(packageRoot, 'android', 'app', 'build', 'outputs', 'apk', 'release', 'app-release-unsigned.apk');
915
+ }
916
+
917
+ /**
918
+ * Align the finished APK's uncompressed libraries to 16 KB, then re-sign it.
919
+ *
920
+ * AGP 8.2.2 stores shared libraries uncompressed but aligns them to 4 KB, so a device with 16 KB
921
+ * pages cannot map them straight out of the archive — the census below caught exactly that on
922
+ * `lib/arm64-v8a/libSDL3.so`, at offset 0x11d000. Alignment is an archive property, not a
923
+ * compiler one, so no amount of correctly built `.so` files fixes it; the SDK's own `zipalign -P 16`
924
+ * does, and `apksigner` puts the signature back afterwards because zipalign rewrites the archive.
925
+ *
926
+ * Fails closed: no zipalign, no apksigner, or a non-zero exit is an error, never a skip. An APK
927
+ * that silently ships 4 KB-aligned libraries is the defect this whole path exists to prevent.
928
+ */
929
+ function alignAndroidArchive(apkPath, options = {}) {
930
+ const spawn = options.spawnSync ?? spawnSync;
931
+ const zipalign =
932
+ options.zipalign ??
933
+ resolveZipalignCandidates().find(
934
+ (candidate) => candidate === 'zipalign' || existsSync(candidate),
935
+ );
936
+ if (zipalign === undefined)
937
+ throw new Error(
938
+ 'No zipalign found. Install Android SDK build-tools, or set TN_ZIPALIGN, so the packaged ' +
939
+ 'APK can be aligned to 16 KB.',
940
+ );
941
+ const aligned = `${apkPath}.aligned`;
942
+ rmSync(aligned, { force: true });
943
+ const alignResult = spawn(zipalign, ['-P', '16', '-f', '4', apkPath, aligned], {
944
+ encoding: 'utf8',
945
+ stdio: 'inherit',
946
+ });
947
+ if (alignResult.error) throw alignResult.error;
948
+ if (alignResult.status !== 0)
949
+ throw new Error(`${zipalign} exited with code ${alignResult.status ?? 'unknown'}.`);
950
+ const apksigner = zipalign === 'zipalign' ? 'apksigner' : join(dirname(zipalign), 'apksigner');
951
+ const keystore =
952
+ options.keystore ?? join(process.env.HOME ?? homedir(), '.android', 'debug.keystore');
953
+ if (!existsSync(keystore))
954
+ throw new Error(
955
+ `Cannot re-sign the aligned APK: no keystore at ${keystore}. Run a Gradle debug build once ` +
956
+ 'to create the debug keystore, or pass an explicit keystore.',
957
+ );
958
+ const signResult = spawn(
959
+ apksigner,
960
+ [
961
+ 'sign',
962
+ '--ks',
963
+ keystore,
964
+ '--ks-pass',
965
+ 'env:TN_ANDROID_KEYSTORE_PASSWORD',
966
+ '--ks-key-alias',
967
+ options.keystoreAlias ?? 'androiddebugkey',
968
+ '--key-pass',
969
+ 'env:TN_ANDROID_KEY_PASSWORD',
970
+ aligned,
971
+ ],
972
+ {
973
+ encoding: 'utf8',
974
+ stdio: 'inherit',
975
+ env: {
976
+ ...process.env,
977
+ TN_ANDROID_KEYSTORE_PASSWORD: options.keystorePassword ?? 'android',
978
+ TN_ANDROID_KEY_PASSWORD: options.keyPassword ?? 'android',
979
+ },
980
+ },
981
+ );
982
+ if (signResult.error) throw signResult.error;
983
+ if (signResult.status !== 0)
984
+ throw new Error(`${apksigner} exited with code ${signResult.status ?? 'unknown'}.`);
985
+ renameSync(aligned, apkPath);
986
+ rmSync(`${aligned}.idsig`, { force: true });
987
+ return zipalign;
988
+ }
989
+
624
990
  export async function packageAndroid(
625
991
  bundle,
626
992
  requestedOutput,
@@ -635,6 +1001,21 @@ export async function packageAndroid(
635
1001
  options.runtimeRoot ?? process.env.THREENATIVE_RUNTIME_SOURCE ?? runtimeRoot,
636
1002
  );
637
1003
  const { androidRoot } = androidPaths(packageRoot);
1004
+ // Validate the request before any asset work or Gradle: an unsupported mode/format pair must
1005
+ // fail with a named reason, not after a ten-minute build produces the wrong artifact.
1006
+ const request = androidBuildRequest(options.mode, options.format);
1007
+ const environment = options.environment ?? process.env;
1008
+ const signing =
1009
+ request.mode === 'release'
1010
+ ? androidReleaseSigning(environment, options.projectRoot)
1011
+ : undefined;
1012
+ if (signing !== undefined && !signing.complete) {
1013
+ // Never fall back to debug keys or an unsigned release. The names are safe to print; the
1014
+ // values never are.
1015
+ throw new Error(
1016
+ `TN_ANDROID_SIGNING_INCOMPLETE: release signing inputs are not set: ${signing.missing.join(', ')}. Export them from the game's build environment (see packages/runtime-native/README.md).`,
1017
+ );
1018
+ }
638
1019
  const sourceCheckout = existsSync(join(packageRoot, 'CMakeLists.txt'));
639
1020
  if (sourceCheckout && options.allowSourceBuild !== true) {
640
1021
  throw new Error(
@@ -694,6 +1075,9 @@ export async function packageAndroid(
694
1075
  stageAndroidUi(options.ui, declared.ui.renderer === 'web' ? 'web' : 'native', join(generatedAssets, 'ui'));
695
1076
  const restoreFiles = installAndroidFiles(declared, packageRoot);
696
1077
  try {
1078
+ // The subject of the build, after branding rewrote it: the submission floor is a property of
1079
+ // the project Gradle is about to compile, not of a constant the packager hopes still matches it.
1080
+ assertAndroidSubmissionTargetSdk(readFileSync(androidPaths(packageRoot).androidGradle, 'utf8'));
697
1081
  const command = process.platform === 'win32' ? gradlew : 'sh';
698
1082
  // Build variants the app already understands — `-PthreenativeJsEngine=v8`,
699
1083
  // `-PthreenativeVsync=false` — are only reachable if something can pass them through. Without
@@ -701,34 +1085,86 @@ export async function packageAndroid(
701
1085
  const extraGradleArgs = (process.env.THREENATIVE_GRADLE_ARGS ?? '')
702
1086
  .split(' ')
703
1087
  .filter((entry) => entry.length > 0);
704
- const baseArgs = ['assembleDebug', '-x', 'buildAndroidFirstProofBundle', ...extraGradleArgs];
1088
+ const baseArgs = [
1089
+ request.task,
1090
+ '-x',
1091
+ 'buildAndroidFirstProofBundle',
1092
+ ...androidAbiGradleArgs(request.mode, extraGradleArgs),
1093
+ ...extraGradleArgs,
1094
+ ];
705
1095
  const args = process.platform === 'win32' ? baseArgs : [gradlew, ...baseArgs];
706
1096
  const spawn = options.spawnSync ?? spawnSync;
707
1097
  const result = spawn(command, args, {
708
1098
  cwd: androidRoot,
709
1099
  encoding: 'utf8',
1100
+ // The signing values reach Gradle only as project properties from the game's environment; the
1101
+ // keystore path was resolved against the consumer project above. Nothing here logs them.
1102
+ ...(signing === undefined
1103
+ ? {}
1104
+ : { env: androidSigningGradleEnvironment(signing, environment) }),
710
1105
  stdio: 'inherit',
711
1106
  });
712
1107
  if (result.error) throw result.error;
713
1108
  if (result.status !== 0)
714
1109
  throw new Error(`Gradle exited with code ${result.status ?? 'unknown'}.`);
715
- const apk = join(
716
- packageRoot,
717
- 'android',
718
- 'app',
719
- 'build',
720
- 'outputs',
721
- 'apk',
722
- 'debug',
723
- 'app-debug.apk',
724
- );
725
- if (!existsSync(apk)) throw new Error(`Gradle did not produce the expected APK: ${apk}`);
726
- const output = requestedOutput ? resolve(requestedOutput) : apk;
727
- if (output !== apk) {
1110
+ const candidates = androidArtifactCandidates(packageRoot, request);
1111
+ const artifact = candidates.find((candidate) => existsSync(candidate));
1112
+ if (artifact === undefined) {
1113
+ if (
1114
+ request.mode === 'release' &&
1115
+ request.format === 'apk' &&
1116
+ existsSync(androidUnsignedReleaseApk(packageRoot))
1117
+ ) {
1118
+ throw new Error(
1119
+ 'TN_ANDROID_RELEASE_UNSIGNED: Gradle produced an unsigned release APK, so signing did not apply. Check the four signing property values; a release never falls back to debug keys.',
1120
+ );
1121
+ }
1122
+ throw new Error(
1123
+ `TN_ANDROID_ARTIFACT_MISSING: Gradle ${request.task} produced no ${request.format} at ${candidates.join(' or ')}.`,
1124
+ );
1125
+ }
1126
+ const output = requestedOutput ? resolve(requestedOutput) : artifact;
1127
+ if (output !== artifact) {
728
1128
  mkdirSync(dirname(output), { recursive: true });
729
- copyFileSync(apk, output);
1129
+ copyFileSync(artifact, output);
1130
+ }
1131
+ // APKs are aligned to 16 KB and censused on the artifact that ships. A release APK is re-signed
1132
+ // with the consumer's own key, never the debug keystore; an AAB is left to Gradle's signing.
1133
+ if (request.format === 'apk') {
1134
+ if (options.alignArchive !== false) {
1135
+ alignAndroidArchive(output, {
1136
+ ...(options.align ?? {}),
1137
+ ...(request.mode === 'release'
1138
+ ? {
1139
+ keystore: signing.keystore,
1140
+ keystoreAlias: signing.keyAlias,
1141
+ keystorePassword: signing.keystorePassword,
1142
+ keyPassword: signing.keyPassword,
1143
+ }
1144
+ : {}),
1145
+ });
1146
+ }
1147
+ // The 16 KB census runs on the artifact that ships, not on the build directory it came from.
1148
+ const abis = androidRequestedAbis(baseArgs);
1149
+ const census = assertAndroidArtifact16KbAlignment(output, {
1150
+ ...(abis === undefined ? {} : { abis }),
1151
+ ...(options.artifact16Kb ?? {}),
1152
+ });
1153
+ for (const library of census.libraries) {
1154
+ console.log(
1155
+ ` 16 KB ok: ${library.entry} (${library.compression}, offset 0x${library.dataOffset.toString(16)}, ` +
1156
+ `LOAD ${library.alignments.map((value) => `0x${value.toString(16)}`).join(', ')})`,
1157
+ );
1158
+ }
1159
+ console.log(
1160
+ `ThreeNative Android APK: ${output} — ${census.libraries.length} native libraries 16 KB clean` +
1161
+ `${census.zipalign ? `, archive offsets confirmed by ${census.zipalign}` : ''}`,
1162
+ );
1163
+ }
1164
+ if (request.mode === 'release') {
1165
+ // Signature and non-debuggable proof come from the shipped artifact, after any alignment.
1166
+ verifyAndroidReleaseArtifact(output, request, options);
730
1167
  }
731
- console.log(`ThreeNative Android APK: ${output}`);
732
1168
  return output;
733
1169
  } finally {
734
1170
  restoreFiles();
@@ -742,6 +1178,9 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
742
1178
  const orientationIndex = process.argv.indexOf('--orientation');
743
1179
  const configIndex = process.argv.indexOf('--config');
744
1180
  const uiIndex = process.argv.indexOf('--ui');
1181
+ const projectRootIndex = process.argv.indexOf('--project-root');
1182
+ const modeIndex = process.argv.indexOf('--mode');
1183
+ const formatIndex = process.argv.indexOf('--format');
745
1184
  const allowSourceBuild = process.argv.includes('--allow-source-build');
746
1185
  if (
747
1186
  bundleIndex === -1 ||
@@ -749,7 +1188,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
749
1188
  process.argv[bundleIndex + 1].startsWith('--')
750
1189
  ) {
751
1190
  console.error(
752
- 'Usage: package-android.mjs --bundle FILE [--output FILE] [--assets DIR] [--ui DIR] [--orientation landscape|portrait|sensor] [--config FILE] [--allow-source-build]',
1191
+ 'Usage: package-android.mjs --bundle FILE [--output FILE] [--assets DIR] [--ui DIR] [--orientation landscape|portrait|sensor] [--config FILE] [--mode debug|release] [--format apk|aab] [--project-root DIR] [--allow-source-build]',
753
1192
  );
754
1193
  process.exitCode = 1;
755
1194
  } else if (
@@ -790,6 +1229,13 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
790
1229
  readAndroidConfig(configPath),
791
1230
  {
792
1231
  ...(uiIndex === -1 ? {} : { ui: resolve(process.argv[uiIndex + 1]) }),
1232
+ ...(modeIndex === -1 ? {} : { mode: process.argv[modeIndex + 1] }),
1233
+ ...(formatIndex === -1 ? {} : { format: process.argv[formatIndex + 1] }),
1234
+ // The consumer project root: a relative keystore path in the environment must resolve
1235
+ // against the game, not the engine's Android project the packager runs inside.
1236
+ ...(projectRootIndex === -1
1237
+ ? {}
1238
+ : { projectRoot: resolve(process.argv[projectRootIndex + 1]) }),
793
1239
  // Maintainer route for source-checkout builds: the guard requires an
794
1240
  // explicit opt-in, and this flag is its CLI spelling.
795
1241
  ...(allowSourceBuild ? { allowSourceBuild: true } : {}),