@threenative/runtime-native 0.2.0 → 0.3.0

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.
@@ -14,7 +14,8 @@ import {
14
14
  } from 'node:fs';
15
15
  import { dirname, join, posix, resolve } from 'node:path';
16
16
  import { fileURLToPath, pathToFileURL } from 'node:url';
17
- import { downloadReleaseArtifact, verifyChecksum } from './install-prebuilt.mjs';
17
+ import { downloadReleaseArtifact, releaseManifestUrl, verifyChecksum } from './install-prebuilt.mjs';
18
+ import { assertAndroidAssetsDecodable, deriveAndroidWebpSupport } from './asset-preflight.mjs';
18
19
 
19
20
  const runtimeRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
20
21
  export const GRADLE_WRAPPER_URL =
@@ -22,13 +23,73 @@ export const GRADLE_WRAPPER_URL =
22
23
  export const GRADLE_WRAPPER_SHA256 =
23
24
  'd3b261c2820e9e3d8d639ed084900f11f4a86050a8f83342ade7b6bc9b0d2bdd';
24
25
 
26
+ export const ANDROID_ABIS = ['arm64-v8a', 'x86_64'];
27
+ export const ANDROID_ENGINES = ['quickjs', 'v8'];
28
+
29
+ /**
30
+ * The QuickJS prebuilt set. Unchanged, and still the meaning of the unqualified release keys.
31
+ *
32
+ * `libmystral-runtime.so` here is the QuickJS-linked runtime: the interpreter is compiled *into*
33
+ * it, which is why the V8 set below needs a different runtime binary rather than the same one plus
34
+ * a library.
35
+ */
36
+ /**
37
+ * The Android SDL3 version, owned here because this file is the one that ships.
38
+ *
39
+ * It was written out by hand in four places and a bump left three of them naming an archive that
40
+ * no longer existed. `download-deps.mjs` imports it rather than the other way round: that script
41
+ * is a development-time provisioning path and is deliberately not in the published package, so a
42
+ * published install importing it fails at require time — which is what the clean-room Android
43
+ * test caught.
44
+ *
45
+ * 3.2.30 is the first release in this line whose 64-bit Android libraries carry 16 KB LOAD
46
+ * alignment, which Android 15 and later require. Do not go back.
47
+ */
48
+ export const SDL3_ANDROID_VERSION = '3.2.30';
49
+
25
50
  export const ANDROID_PREBUILT_ASSETS = {
26
51
  'android-arm64-v8a-runtime': 'jniLibs/arm64-v8a/libmystral-runtime.so',
27
52
  'android-arm64-v8a-sdl3': 'jniLibs/arm64-v8a/libSDL3.so',
28
- 'android-sdl3-aar': 'SDL3-3.2.8.aar',
53
+ 'android-sdl3-aar': `SDL3-${SDL3_ANDROID_VERSION}.aar`,
29
54
  'android-x86_64-runtime': 'jniLibs/x86_64/libmystral-runtime.so',
30
55
  'android-x86_64-sdl3': 'jniLibs/x86_64/libSDL3.so',
31
56
  };
57
+
58
+ /**
59
+ * The V8 prebuilt set, added 2026-08-16 by PRD-130 Phase 4.
60
+ *
61
+ * Before this, the prebuilt path could not express V8 at all: it shipped four files, none of them
62
+ * V8, so a project built from a release artifact got QuickJS **whatever the default said**. Flipping
63
+ * the engine default without this would have produced a default only operators with an NDK ever
64
+ * received.
65
+ *
66
+ * The runtime binary is engine-qualified rather than shared, because it genuinely differs — 60.4 MB
67
+ * linked against V8 against 66.6 MB with QuickJS compiled in. Publishing one runtime and bolting a
68
+ * library onto it would produce a process that reports the wrong engine, which is exactly the class
69
+ * of failure `--expect-engine` exists to catch.
70
+ */
71
+ export const ANDROID_PREBUILT_V8_ASSETS = {
72
+ 'android-arm64-v8a-runtime-v8': 'jniLibs/arm64-v8a/libmystral-runtime.so',
73
+ 'android-arm64-v8a-sdl3': 'jniLibs/arm64-v8a/libSDL3.so',
74
+ 'android-arm64-v8a-v8': 'jniLibs/arm64-v8a/libv8android.so',
75
+ 'android-arm64-v8a-libcxx': 'jniLibs/arm64-v8a/libc++_shared.so',
76
+ 'android-arm64-v8a-v8-snapshot': 'assets/v8/arm64-v8a/snapshot_blob.bin',
77
+ 'android-sdl3-aar': `SDL3-${SDL3_ANDROID_VERSION}.aar`,
78
+ 'android-x86_64-runtime-v8': 'jniLibs/x86_64/libmystral-runtime.so',
79
+ 'android-x86_64-sdl3': 'jniLibs/x86_64/libSDL3.so',
80
+ 'android-x86_64-v8': 'jniLibs/x86_64/libv8android.so',
81
+ 'android-x86_64-libcxx': 'jniLibs/x86_64/libc++_shared.so',
82
+ 'android-x86_64-v8-snapshot': 'assets/v8/x86_64/snapshot_blob.bin',
83
+ };
84
+
85
+ /** The prebuilt set one engine needs. The engine name is the same one the source path uses. */
86
+ export function androidPrebuiltAssets(engine = 'v8') {
87
+ const name = String(engine).toLowerCase();
88
+ if (!ANDROID_ENGINES.includes(name)) {
89
+ throw new Error(`Unknown Android JS engine '${engine}'; expected one of ${ANDROID_ENGINES.join(', ')}.`);
90
+ }
91
+ return name === 'v8' ? ANDROID_PREBUILT_V8_ASSETS : ANDROID_PREBUILT_ASSETS;
92
+ }
32
93
  export const NATIVE_ORIENTATIONS = ['landscape', 'portrait', 'sensor'];
33
94
 
34
95
  function androidPaths(root = runtimeRoot) {
@@ -37,7 +98,18 @@ function androidPaths(root = runtimeRoot) {
37
98
  androidManifest: join(root, 'android', 'app', 'src', 'main', 'AndroidManifest.xml'),
38
99
  androidStrings: join(root, 'android', 'app', 'src', 'main', 'res', 'values', 'strings.xml'),
39
100
  androidTheme: join(root, 'android', 'app', 'src', 'main', 'res', 'values', 'themes.xml'),
101
+ androidBranding: join(root, 'android', 'app', 'src', 'main', 'res', 'values', 'branding.xml'),
40
102
  androidGradle: join(root, 'android', 'app', 'build.gradle.kts'),
103
+ androidAdaptiveIcon: join(
104
+ root,
105
+ 'android',
106
+ 'app',
107
+ 'src',
108
+ 'main',
109
+ 'res',
110
+ 'mipmap-anydpi-v26',
111
+ 'ic_launcher.xml',
112
+ ),
41
113
  androidIcon: join(
42
114
  root,
43
115
  'android',
@@ -48,13 +120,47 @@ function androidPaths(root = runtimeRoot) {
48
120
  'mipmap-xxxhdpi',
49
121
  'ic_launcher.png',
50
122
  ),
123
+ androidForeground: join(
124
+ root,
125
+ 'android',
126
+ 'app',
127
+ 'src',
128
+ 'main',
129
+ 'res',
130
+ 'drawable-nodpi',
131
+ 'ic_launcher_foreground.png',
132
+ ),
133
+ androidMonochrome: join(
134
+ root,
135
+ 'android',
136
+ 'app',
137
+ 'src',
138
+ 'main',
139
+ 'res',
140
+ 'drawable-nodpi',
141
+ 'ic_launcher_monochrome.png',
142
+ ),
143
+ androidSplash: join(
144
+ root,
145
+ 'android',
146
+ 'app',
147
+ 'src',
148
+ 'main',
149
+ 'res',
150
+ 'drawable-nodpi',
151
+ 'tn_boot_splash.png',
152
+ ),
51
153
  };
52
154
  }
53
155
 
54
156
  export const DEFAULT_ANDROID_CONFIG = {
55
157
  app: { id: 'com.threenative.game', name: 'ThreeNative', version: '0.1.0', build: 1 },
56
- display: { orientation: 'landscape', fullscreen: true, keepScreenOn: false },
158
+ display: { orientation: 'landscape', fullscreen: true, keepScreenOn: false, maxFps: 60, backgroundMode: 'pause' },
57
159
  window: { title: 'ThreeNative', width: 1280, height: 720, resizable: true },
160
+ // `native` is PRD-216's CanvasLayer renderer: no WebView, no CSS, no second process. A game
161
+ // that never states a renderer therefore ships no overlay, which is what acceptance criterion 5
162
+ // asks for. Templates state `web` explicitly.
163
+ ui: { renderer: 'native' },
58
164
  };
59
165
 
60
166
  function configValue(value, orientation) {
@@ -62,7 +168,10 @@ function configValue(value, orientation) {
62
168
  const app = source.app && typeof source.app === 'object' ? source.app : {};
63
169
  const display = source.display && typeof source.display === 'object' ? source.display : {};
64
170
  const window = source.window && typeof source.window === 'object' ? source.window : {};
171
+ const bootSplash = source.bootSplash && typeof source.bootSplash === 'object' ? source.bootSplash : {};
172
+ const ui = source.ui && typeof source.ui === 'object' ? source.ui : {};
65
173
  return {
174
+ ui: { ...DEFAULT_ANDROID_CONFIG.ui, ...ui },
66
175
  app: { ...DEFAULT_ANDROID_CONFIG.app, ...app },
67
176
  display: {
68
177
  ...DEFAULT_ANDROID_CONFIG.display,
@@ -70,6 +179,7 @@ function configValue(value, orientation) {
70
179
  orientation: orientation ?? display.orientation ?? DEFAULT_ANDROID_CONFIG.display.orientation,
71
180
  },
72
181
  window: { ...DEFAULT_ANDROID_CONFIG.window, ...window },
182
+ ...(source.bootSplash === undefined ? {} : { bootSplash: { ...bootSplash } }),
73
183
  };
74
184
  }
75
185
 
@@ -108,6 +218,85 @@ function orientationValue(value = 'landscape') {
108
218
  );
109
219
  }
110
220
 
221
+ function androidIcons(config) {
222
+ const app = config.app ?? {};
223
+ return app.icons?.android ?? {};
224
+ }
225
+
226
+ function hasAndroidIcon(config) {
227
+ return iconForeground(config) !== undefined;
228
+ }
229
+
230
+ function appIcon(config) {
231
+ return config.app?.icon;
232
+ }
233
+
234
+ function iconForeground(config) {
235
+ return androidIcons(config).foreground ?? appIcon(config);
236
+ }
237
+
238
+ function iconMonochrome(config) {
239
+ return androidIcons(config).monochrome ?? iconForeground(config);
240
+ }
241
+
242
+ function iconBackground(config) {
243
+ return androidIcons(config).background ?? config.bootSplash?.backgroundColor ?? '#000000';
244
+ }
245
+
246
+ function bootSplashBackground(config) {
247
+ return config.bootSplash?.backgroundColor ?? '#000000';
248
+ }
249
+
250
+ function setThemeItem(source, name, value) {
251
+ const item = new RegExp(`<item\\s+name="${name}">[\\s\\S]*?<\\/item>`, 'u');
252
+ const rendered = `<item name="${name}">${value}</item>`;
253
+ if (item.test(source)) return source.replace(item, rendered);
254
+ return source.replace(/\s*<\/style>/u, `\n ${rendered}\n </style>`);
255
+ }
256
+
257
+ export function renderAndroidBrandingResources(config) {
258
+ const icons = androidIcons(config);
259
+ const hasIcon = hasAndroidIcon(config);
260
+ const adaptive = hasIcon
261
+ ? `<?xml version="1.0" encoding="utf-8"?>
262
+ <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
263
+ <background android:drawable="@color/tn_icon_background" />
264
+ <foreground android:drawable="@drawable/ic_launcher_foreground" />
265
+ <monochrome android:drawable="@drawable/ic_launcher_monochrome" />
266
+ </adaptive-icon>
267
+ `
268
+ : undefined;
269
+ const colors = `<?xml version="1.0" encoding="utf-8"?>
270
+ <resources>
271
+ <color name="tn_icon_background">${xmlEscape(iconBackground(config))}</color>
272
+ <color name="tn_boot_splash_background">${xmlEscape(bootSplashBackground(config))}</color>
273
+ </resources>
274
+ `;
275
+ return {
276
+ adaptive,
277
+ colors,
278
+ foreground: icons.foreground ?? appIcon(config),
279
+ monochrome: icons.monochrome ?? icons.foreground ?? appIcon(config),
280
+ splash: config.bootSplash?.image,
281
+ };
282
+ }
283
+
284
+ /**
285
+ * Insert or replace an `<activity>`-scoped `<property>` element.
286
+ *
287
+ * `<property>` is not `<meta-data>`: the platform reads compat properties only from the former, so
288
+ * `upsertApplicationMetadata` cannot express this.
289
+ */
290
+ function upsertActivityProperty(source, name, value) {
291
+ const escapedName = name.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
292
+ const existing = new RegExp(`\\s*<property\\s+android:name="${escapedName}"[^>]*/>`, 'u');
293
+ const element = `\n <property android:name="${name}" android:value="${value}" />`;
294
+ if (existing.test(source)) return source.replace(existing, element);
295
+ const activity = /<activity\b[^>]*>/u.exec(source);
296
+ if (!activity) return source;
297
+ return source.replace(activity[0], `${activity[0]}${element}`);
298
+ }
299
+
111
300
  export function renderAndroidManifest(source, orientation = 'landscape') {
112
301
  const config = configValue(typeof orientation === 'string' ? undefined : orientation, typeof orientation === 'string' ? orientation : undefined);
113
302
  const value = orientationValue(config.display.orientation);
@@ -119,15 +308,60 @@ export function renderAndroidManifest(source, orientation = 'landscape') {
119
308
  application[0],
120
309
  setXmlAttribute(application[0], 'icon', config.app.icon === undefined ? undefined : '@mipmap/ic_launcher'),
121
310
  );
311
+ rendered = rendered.replace(
312
+ /<application\b[^>]*>/u,
313
+ (tag) => setXmlAttribute(tag, 'icon', hasAndroidIcon(config) ? '@mipmap/ic_launcher' : undefined),
314
+ );
315
+ rendered = rendered.replace(
316
+ /<application\b[^>]*>/u,
317
+ (tag) => setXmlAttribute(tag, 'roundIcon', hasAndroidIcon(config) ? '@mipmap/ic_launcher' : undefined),
318
+ );
122
319
  const renderedActivity = setXmlAttribute(
123
320
  activity[0],
124
321
  'screenOrientation',
125
322
  value,
126
323
  );
127
324
  rendered = rendered.replace(activity[0], renderedActivity);
325
+ // Opt out of the platform's orientation override.
326
+ //
327
+ // Android 16+ applies `SCREEN_ORIENTATION_FULL_USER` on top of an app's declared orientation for
328
+ // apps it considers non-adaptive, which is why a manifest reading
329
+ // `android:screenOrientation="landscape"` still came up portrait on a Pixel 8 —
330
+ // `dumpsys activity activities` showed `overrideOrientation=SCREEN_ORIENTATION_FULL_USER` and the
331
+ // window simply followed the device. This property is the documented way to decline that
332
+ // override, and it is only set when the game actually asked for a fixed orientation: a game
333
+ // configured `sensor` wants the platform behaviour and must not opt out of it.
334
+ if (value !== 'sensor') {
335
+ rendered = upsertActivityProperty(
336
+ rendered,
337
+ 'android.window.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE',
338
+ 'false',
339
+ );
340
+ }
128
341
  rendered = upsertApplicationMetadata(rendered, 'TN_KEEP_SCREEN_ON', String(config.display.keepScreenOn));
342
+ rendered = upsertApplicationMetadata(rendered, 'TN_MAX_FPS', String(config.display.maxFps));
343
+ // `display.backgroundMode`. Carried as metadata beside the others so the activity can hand it to
344
+ // the native host, which decides whether the render loop parks when the player leaves. Fail
345
+ // closed on a value nobody defined: an unrecognized mode ships as 'pause'.
346
+ rendered = upsertApplicationMetadata(
347
+ rendered,
348
+ 'TN_BACKGROUND_MODE',
349
+ config.display.backgroundMode === 'continue' ? 'continue' : 'pause',
350
+ );
351
+ // `ui.renderer`. The activity reads this to decide whether to attach the WebView overlay at all,
352
+ // so a game that did not opt in ships no overlay and no extra process. Fail closed on a value
353
+ // nobody defined: anything but 'web' is the native renderer.
354
+ rendered = upsertApplicationMetadata(
355
+ rendered,
356
+ 'TN_UI_RENDERER',
357
+ config.ui.renderer === 'web' ? 'web' : 'native',
358
+ );
129
359
  rendered = upsertApplicationMetadata(rendered, 'TN_WINDOW_TITLE', '@string/window_title');
130
- return upsertApplicationMetadata(rendered, 'TN_FULLSCREEN', String(config.display.fullscreen));
360
+ rendered = upsertApplicationMetadata(rendered, 'TN_FULLSCREEN', String(config.display.fullscreen));
361
+ // Also carried as metadata, not only as `android:screenOrientation`: the activity re-requests it
362
+ // in `onCreate`, because the manifest attribute alone did not hold a landscape game in landscape
363
+ // on a Pixel 8.
364
+ return upsertApplicationMetadata(rendered, 'TN_ORIENTATION', config.display.orientation);
131
365
  }
132
366
 
133
367
  export function renderAndroidStrings(source, config) {
@@ -147,8 +381,17 @@ export function renderAndroidTheme(source, config) {
147
381
  const parent = value.display.fullscreen ? 'android:Theme.NoTitleBar.Fullscreen' : 'android:Theme.NoTitleBar';
148
382
  let rendered = source.replace(/(parent=")[^"]*(")/u, `$1${parent}$2`);
149
383
  const item = /<item\s+name="android:windowFullscreen">[\s\S]*?<\/item>/u;
150
- if (item.test(rendered)) return rendered.replace(item, `<item name="android:windowFullscreen">${fullscreen}</item>`);
151
- return rendered.replace(/\s*<\/style>/u, `\n <item name="android:windowFullscreen">${fullscreen}</item>\n </style>`);
384
+ rendered = item.test(rendered)
385
+ ? rendered.replace(item, `<item name="android:windowFullscreen">${fullscreen}</item>`)
386
+ : rendered.replace(/\s*<\/style>/u, `\n <item name="android:windowFullscreen">${fullscreen}</item>\n </style>`);
387
+ rendered = setThemeItem(rendered, 'android:windowSplashScreenBackground', '@color/tn_boot_splash_background');
388
+ if (hasAndroidIcon(config)) {
389
+ rendered = setThemeItem(rendered, 'android:windowSplashScreenAnimatedIcon', '@drawable/ic_launcher_foreground');
390
+ }
391
+ if (configValue(config).bootSplash?.image !== undefined) {
392
+ rendered = setThemeItem(rendered, 'android:windowSplashScreenBrandingImage', '@drawable/tn_boot_splash');
393
+ }
394
+ return rendered;
152
395
  }
153
396
 
154
397
  export function renderAndroidBuildGradle(source, config) {
@@ -169,11 +412,24 @@ function installAndroidFiles(config, root = runtimeRoot) {
169
412
  androidManifest,
170
413
  androidStrings,
171
414
  androidTheme,
415
+ androidBranding,
172
416
  androidGradle,
417
+ androidAdaptiveIcon,
173
418
  androidIcon,
419
+ androidForeground,
420
+ androidMonochrome,
421
+ androidSplash,
174
422
  } = androidPaths(root);
175
- if (config.app.icon !== undefined && (!existsSync(config.app.icon) || !statSync(config.app.icon).isFile())) {
176
- throw new Error(`TN_CONFIG_ICON_MISSING: app.icon does not exist: ${config.app.icon}`);
423
+ const branding = renderAndroidBrandingResources(config);
424
+ const requiredAssets = [
425
+ [branding.foreground, 'TN_CONFIG_BRAND_ANDROID_FOREGROUND_MISSING'],
426
+ [branding.monochrome, 'TN_CONFIG_BRAND_ANDROID_MONOCHROME_MISSING'],
427
+ [branding.splash, 'TN_CONFIG_BRAND_SPLASH_MISSING'],
428
+ ];
429
+ for (const [file, code] of requiredAssets) {
430
+ if (file !== undefined && (!existsSync(file) || !statSync(file).isFile())) {
431
+ throw new Error(`${code}: declared Android brand asset does not exist: ${file}`);
432
+ }
177
433
  }
178
434
  const originals = new Map([
179
435
  [androidManifest, readFileSync(androidManifest)],
@@ -181,33 +437,84 @@ function installAndroidFiles(config, root = runtimeRoot) {
181
437
  [androidTheme, readFileSync(androidTheme)],
182
438
  [androidGradle, readFileSync(androidGradle)],
183
439
  ]);
440
+ const generated = [androidBranding, androidAdaptiveIcon, androidForeground, androidMonochrome, androidSplash];
441
+ const generatedOriginals = new Map(
442
+ generated.map((file) => [file, existsSync(file) ? readFileSync(file) : undefined]),
443
+ );
184
444
  const iconOriginal = existsSync(androidIcon) ? readFileSync(androidIcon) : undefined;
185
445
  writeFileSync(androidManifest, renderAndroidManifest(originals.get(androidManifest).toString('utf8'), config));
186
446
  writeFileSync(androidStrings, renderAndroidStrings(originals.get(androidStrings).toString('utf8'), config));
187
447
  writeFileSync(androidTheme, renderAndroidTheme(originals.get(androidTheme).toString('utf8'), config));
188
448
  writeFileSync(androidGradle, renderAndroidBuildGradle(originals.get(androidGradle).toString('utf8'), config));
189
- if (config.app.icon !== undefined) {
449
+ writeFileSync(androidBranding, branding.colors);
450
+ if (branding.adaptive !== undefined) {
451
+ mkdirSync(dirname(androidAdaptiveIcon), { recursive: true });
452
+ writeFileSync(androidAdaptiveIcon, branding.adaptive);
453
+ } else {
454
+ rmSync(androidAdaptiveIcon, { force: true });
455
+ }
456
+ if (branding.foreground !== undefined) {
457
+ mkdirSync(dirname(androidForeground), { recursive: true });
458
+ copyFileSync(branding.foreground, androidForeground);
459
+ } else {
460
+ rmSync(androidForeground, { force: true });
461
+ }
462
+ if (branding.monochrome !== undefined) {
463
+ mkdirSync(dirname(androidMonochrome), { recursive: true });
464
+ copyFileSync(branding.monochrome, androidMonochrome);
465
+ } else {
466
+ rmSync(androidMonochrome, { force: true });
467
+ }
468
+ if (branding.splash !== undefined) {
469
+ mkdirSync(dirname(androidSplash), { recursive: true });
470
+ copyFileSync(branding.splash, androidSplash);
471
+ } else {
472
+ rmSync(androidSplash, { force: true });
473
+ }
474
+ if (branding.foreground !== undefined) {
190
475
  mkdirSync(dirname(androidIcon), { recursive: true });
191
- copyFileSync(config.app.icon, androidIcon);
476
+ copyFileSync(branding.foreground, androidIcon);
192
477
  } else {
193
478
  rmSync(androidIcon, { force: true });
194
479
  }
195
480
  return () => {
196
481
  for (const [file, original] of originals) restoreFile(file, original);
197
482
  restoreFile(androidIcon, iconOriginal);
483
+ for (const [file, original] of generatedOriginals) restoreFile(file, original);
198
484
  };
199
485
  }
200
486
 
201
487
  export async function prepareAndroidPrebuilts(options = {}) {
488
+ // Defaults to the engine the source path defaults to. Two names for one choice is how the flag
489
+ // gets forgotten, so the prebuilt path takes the same engine names the Gradle property does.
490
+ const engine = String(options.engine ?? 'v8').toLowerCase();
491
+ const assets = androidPrebuiltAssets(engine);
492
+ // Name the source the download will really read. `downloadReleaseArtifact` prefers
493
+ // THREENATIVE_PREBUILT_MANIFEST over the release URL, so reporting the URL when the env hook is
494
+ // set sends a reader to a 404 that had nothing to do with their failure.
495
+ const expectedSource =
496
+ options.manifestPath ??
497
+ process.env.THREENATIVE_PREBUILT_MANIFEST ??
498
+ options.manifestUrl ??
499
+ releaseManifestUrl(options.version);
500
+ const downloadOptions = {
501
+ ...options,
502
+ manifestUrl: options.manifestUrl ?? releaseManifestUrl(options.version),
503
+ };
202
504
  const downloads = await Promise.all(
203
- Object.keys(ANDROID_PREBUILT_ASSETS).map(async (key) => [
204
- key,
205
- await downloadReleaseArtifact(key, options),
206
- ]),
505
+ Object.keys(assets).map(async (key) => {
506
+ try {
507
+ return [key, await downloadReleaseArtifact(key, downloadOptions)];
508
+ } catch (error) {
509
+ throw new Error(
510
+ `Android prebuilt '${key}' expected from '${expectedSource}': ${error instanceof Error ? error.message : String(error)}`,
511
+ );
512
+ }
513
+ }),
207
514
  );
208
515
  const prebuiltRoot = resolve(options.outputRoot ?? join(runtimeRoot, 'android', 'prebuilt'));
209
516
  for (const [key, contents] of downloads) {
210
- const output = join(prebuiltRoot, ANDROID_PREBUILT_ASSETS[key]);
517
+ const output = join(prebuiltRoot, assets[key]);
211
518
  mkdirSync(dirname(output), { recursive: true });
212
519
  writeFileSync(output, contents);
213
520
  }
@@ -250,6 +557,7 @@ function listFiles(directory, relative = '') {
250
557
  export function stageAndroidAssets(
251
558
  assets,
252
559
  destination = join(runtimeRoot, 'android', 'app', 'build', 'generated', 'threenative', 'assets', 'game'),
560
+ runtimeSource = runtimeRoot,
253
561
  ) {
254
562
  rmSync(destination, { force: true, recursive: true });
255
563
  mkdirSync(destination, { recursive: true });
@@ -257,6 +565,12 @@ export function stageAndroidAssets(
257
565
  if (!statSync(assets).isDirectory()) {
258
566
  throw new Error(`Android assets path is not a directory: ${assets}`);
259
567
  }
568
+ // Read the assets before copying them. Everything this catches — OGG the decoder rejects, WebP
569
+ // the runtime was built without, interleaved buffers WebGPU refuses to make a pipeline for —
570
+ // otherwise ships in an APK that installs, launches and draws nothing.
571
+ // Derived from the runtime this build is about to pack, not declared here. A hardcoded claim
572
+ // goes stale the moment the build changes under it, which is exactly what happened to WebP.
573
+ assertAndroidAssetsDecodable(assets, { webp: deriveAndroidWebpSupport(runtimeSource) });
260
574
  const files = listFiles(assets);
261
575
  for (const file of files) {
262
576
  const output = join(destination, file);
@@ -266,6 +580,47 @@ export function stageAndroidAssets(
266
580
  return files;
267
581
  }
268
582
 
583
+ /**
584
+ * Stage the built UI bundle so `WebViewAssetLoader` can serve it from an HTTPS-like origin.
585
+ *
586
+ * Fail closed both ways. A game whose renderer is `web` and whose UI never built would install,
587
+ * launch and show a blank overlay over a working game — the most expensive shape of "it looks
588
+ * broken and the logs are clean". And a game whose renderer is `native` must ship no UI bundle
589
+ * at all, because acceptance criterion 5 is that opting out costs nothing.
590
+ */
591
+ export function stageAndroidUi(ui, renderer, destination) {
592
+ rmSync(destination, { force: true, recursive: true });
593
+ if (renderer !== 'web') {
594
+ if (ui) {
595
+ throw new Error(
596
+ `TN_UI_BUNDLE_UNEXPECTED: a UI bundle was staged for a game whose ui.renderer is '${renderer}'. ` +
597
+ 'The native renderer ships no WebView; remove the bundle or set ui.renderer to "web".',
598
+ );
599
+ }
600
+ return [];
601
+ }
602
+ if (!ui || !existsSync(ui)) {
603
+ throw new Error(
604
+ `TN_UI_BUNDLE_MISSING: ui.renderer is "web" but no built UI was found at ${ui ?? '(not provided)'}. ` +
605
+ 'Build the UI before packaging, or set ui.renderer to "native".',
606
+ );
607
+ }
608
+ if (!statSync(ui).isDirectory()) throw new Error(`TN_UI_BUNDLE_MISSING: not a directory: ${ui}`);
609
+ const files = listFiles(ui);
610
+ if (!files.includes('index.html')) {
611
+ throw new Error(
612
+ `TN_UI_BUNDLE_MISSING: ${ui} has no index.html, which is the page the overlay loads.`,
613
+ );
614
+ }
615
+ mkdirSync(destination, { recursive: true });
616
+ for (const file of files) {
617
+ const output = join(destination, file);
618
+ mkdirSync(dirname(output), { recursive: true });
619
+ cpSync(join(ui, file), output);
620
+ }
621
+ return files;
622
+ }
623
+
269
624
  export async function packageAndroid(
270
625
  bundle,
271
626
  requestedOutput,
@@ -274,7 +629,17 @@ export async function packageAndroid(
274
629
  config = undefined,
275
630
  options = {},
276
631
  ) {
277
- const packageRoot = resolve(options.runtimeRoot ?? runtimeRoot);
632
+ // `THREENATIVE_RUNTIME_SOURCE` points the packager at a runtime **source checkout**, which is
633
+ // the only route that works today for a consumer install.
634
+ //
635
+ // A game in a sandbox resolves `runtime-native` to the published tarball, which ships no
636
+ // `CMakeLists.txt`, so the check below always takes the download path — and the download path
637
+ // fetches a GitHub release that does not exist, in a repository that is private. Every consumer
638
+ // on 0.2.0 gets `HTTP 404` naming a URL and no next step. `packageAndroid` has always accepted
639
+ // `options.runtimeRoot`; it simply was not reachable from the CLI or the environment.
640
+ const packageRoot = resolve(
641
+ options.runtimeRoot ?? process.env.THREENATIVE_RUNTIME_SOURCE ?? runtimeRoot,
642
+ );
278
643
  const { androidRoot } = androidPaths(packageRoot);
279
644
  const declared = configValue(config, orientation);
280
645
  orientationValue(declared.display.orientation);
@@ -287,12 +652,21 @@ export async function packageAndroid(
287
652
  await ensureWrapper();
288
653
  const sourceCheckout =
289
654
  existsSync(join(packageRoot, 'CMakeLists.txt')) &&
290
- existsSync(join(packageRoot, 'third_party', 'sdl3-android', 'SDL3-3.2.8.aar'));
655
+ existsSync(join(packageRoot, 'third_party', 'sdl3-android', `SDL3-${SDL3_ANDROID_VERSION}.aar`));
291
656
  if (!sourceCheckout) {
292
657
  const preparePrebuilts =
293
658
  options.prepareAndroidPrebuilts ??
294
659
  (() => prepareAndroidPrebuilts({ outputRoot: join(packageRoot, 'android', 'prebuilt') }));
295
- await preparePrebuilts();
660
+ try {
661
+ await preparePrebuilts();
662
+ } catch (error) {
663
+ // Name the cause and the way out. The bare HTTP status told a person which URL failed and
664
+ // nothing about why a published install can never satisfy it.
665
+ throw new Error(
666
+ `${error instanceof Error ? error.message : String(error)}\n\nThis install has no runtime source checkout at ${packageRoot}, so it tried to download\nprebuilt Android artifacts from a GitHub release. Point the packager at a source\ncheckout of @threenative/runtime-native instead:\n\n THREENATIVE_RUNTIME_SOURCE=/path/to/packages/runtime-native pnpm build:android\n`,
667
+ { cause: error },
668
+ );
669
+ }
296
670
  }
297
671
  const generatedAssets = join(
298
672
  packageRoot,
@@ -311,7 +685,8 @@ export async function packageAndroid(
311
685
  );
312
686
  mkdirSync(dirname(assetBundle), { recursive: true });
313
687
  copyFileSync(bundle, assetBundle);
314
- stageAndroidAssets(assets, join(generatedAssets, 'game'));
688
+ stageAndroidAssets(assets, join(generatedAssets, 'game'), packageRoot);
689
+ stageAndroidUi(options.ui, declared.ui.renderer === 'web' ? 'web' : 'native', join(generatedAssets, 'ui'));
315
690
  const restoreFiles = installAndroidFiles(declared, packageRoot);
316
691
  try {
317
692
  const command = process.platform === 'win32' ? gradlew : 'sh';
@@ -361,13 +736,14 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
361
736
  const assetsIndex = process.argv.indexOf('--assets');
362
737
  const orientationIndex = process.argv.indexOf('--orientation');
363
738
  const configIndex = process.argv.indexOf('--config');
739
+ const uiIndex = process.argv.indexOf('--ui');
364
740
  if (
365
741
  bundleIndex === -1 ||
366
742
  !process.argv[bundleIndex + 1] ||
367
743
  process.argv[bundleIndex + 1].startsWith('--')
368
744
  ) {
369
745
  console.error(
370
- 'Usage: package-android.mjs --bundle FILE [--output FILE] [--assets DIR] [--orientation landscape|portrait|sensor] [--config FILE]',
746
+ 'Usage: package-android.mjs --bundle FILE [--output FILE] [--assets DIR] [--ui DIR] [--orientation landscape|portrait|sensor] [--config FILE]',
371
747
  );
372
748
  process.exitCode = 1;
373
749
  } else if (
@@ -394,6 +770,9 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
394
770
  ) {
395
771
  console.error('--config requires a value.');
396
772
  process.exitCode = 1;
773
+ } else if (uiIndex !== -1 && (!process.argv[uiIndex + 1] || process.argv[uiIndex + 1].startsWith('--'))) {
774
+ console.error('--ui requires a value.');
775
+ process.exitCode = 1;
397
776
  } else {
398
777
  try {
399
778
  const configPath = configIndex === -1 ? undefined : resolve(process.argv[configIndex + 1]);
@@ -403,6 +782,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
403
782
  assetsIndex === -1 ? undefined : resolve(process.argv[assetsIndex + 1]),
404
783
  orientationIndex === -1 ? undefined : process.argv[orientationIndex + 1],
405
784
  readAndroidConfig(configPath),
785
+ uiIndex === -1 ? {} : { ui: resolve(process.argv[uiIndex + 1]) },
406
786
  );
407
787
  } catch (error) {
408
788
  console.error(error instanceof Error ? error.message : String(error));