@threenative/runtime-native 0.3.0 → 0.3.1

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.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { createHash } from 'node:crypto';
4
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
5
  import { dirname, join, resolve } from 'node:path';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
7
 
@@ -9,29 +9,69 @@ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
9
9
  const packageVersion = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')).version;
10
10
  export const RELEASE_REPOSITORY = 'ThreeNativeHQ/threenative';
11
11
 
12
+ /** Every asset a packaged consumer or native release workflow may request. */
13
+ export const PREBUILT_ASSET_NAMES = Object.freeze({
14
+ 'android-arm64-v8a-runtime': 'threenative-runtime-android-arm64-v8a.so',
15
+ 'android-arm64-v8a-runtime-v8': 'threenative-runtime-android-arm64-v8a-v8.so',
16
+ 'android-arm64-v8a-sdl3': 'threenative-sdl3-android-arm64-v8a.so',
17
+ 'android-arm64-v8a-v8': 'threenative-v8-android-arm64-v8a.so',
18
+ 'android-arm64-v8a-libcxx': 'threenative-libcxx-android-arm64-v8a.so',
19
+ 'android-arm64-v8a-v8-snapshot': 'threenative-v8-snapshot-android-arm64-v8a.bin',
20
+ 'android-sdl3-aar': 'threenative-sdl3-android.aar',
21
+ 'android-x86_64-runtime': 'threenative-runtime-android-x86_64.so',
22
+ 'android-x86_64-runtime-v8': 'threenative-runtime-android-x86_64-v8.so',
23
+ 'android-x86_64-sdl3': 'threenative-sdl3-android-x86_64.so',
24
+ 'android-x86_64-v8': 'threenative-v8-android-x86_64.so',
25
+ 'android-x86_64-libcxx': 'threenative-libcxx-android-x86_64.so',
26
+ 'android-x86_64-v8-snapshot': 'threenative-v8-snapshot-android-x86_64.bin',
27
+ 'darwin-arm64': 'threenative-runtime-darwin-arm64',
28
+ 'darwin-arm64-tools': 'threenative-tools-darwin-arm64',
29
+ 'ios-simulator-arm64': 'threenative-ios-simulator-arm64.zip',
30
+ 'linux-x64': 'threenative-runtime-linux-x64',
31
+ 'linux-x64-tools': 'threenative-tools-linux-x64',
32
+ 'win32-x64': 'threenative-runtime-win32-x64.exe',
33
+ 'win32-x64-tools': 'threenative-tools-win32-x64.exe',
34
+ });
35
+
12
36
  /** Every key a packaged consumer or native release workflow may request. */
13
- export const PREBUILT_KEYS = Object.freeze([
14
- 'android-arm64-v8a-runtime',
15
- 'android-arm64-v8a-runtime-v8',
16
- 'android-arm64-v8a-sdl3',
17
- 'android-arm64-v8a-v8',
18
- 'android-arm64-v8a-libcxx',
19
- 'android-arm64-v8a-v8-snapshot',
20
- 'android-sdl3-aar',
21
- 'android-x86_64-runtime',
22
- 'android-x86_64-runtime-v8',
23
- 'android-x86_64-sdl3',
24
- 'android-x86_64-v8',
25
- 'android-x86_64-libcxx',
26
- 'android-x86_64-v8-snapshot',
27
- 'darwin-arm64',
28
- 'linux-x64',
29
- 'ios-simulator-arm64',
30
- 'win32-x64',
31
- ]);
37
+ export const PREBUILT_KEYS = Object.freeze(Object.keys(PREBUILT_ASSET_NAMES));
38
+
39
+ /**
40
+ * Rows this repository builds and verifies on every release run but does not publish.
41
+ *
42
+ * Only macOS. Gatekeeper hard-refuses an unsigned, un-notarized bundle downloaded from the web, so
43
+ * a macOS asset without an Apple Developer Program identity is not a shippable artifact — it is a
44
+ * support ticket. Windows is different: an unsigned executable runs, SmartScreen only warns, so
45
+ * `win32-x64` ships unsigned rather than waiting on a certificate.
46
+ *
47
+ * The row keeps building and verifying on every release run — a row that stops compiling rots
48
+ * silently — it is simply not advertised as downloadable, which is the narrowing PRD-262 allows in
49
+ * place of building every claimed row. Publishing it again is one entry, once the Apple identity
50
+ * exists. Status and cost of every platform's signing inputs: `docs/RELEASE-SIGNING.md`.
51
+ */
52
+ export const UNPUBLISHED_PREBUILT_KEYS = Object.freeze(['darwin-arm64', 'darwin-arm64-tools']);
53
+
54
+ /** The exact cohort a release publishes and a consumer may download. */
55
+ export const PUBLISHED_PREBUILT_KEYS = Object.freeze(
56
+ PREBUILT_KEYS.filter((key) => !UNPUBLISHED_PREBUILT_KEYS.includes(key)),
57
+ );
32
58
 
33
59
  const supported = new Set(['darwin-arm64', 'linux-x64', 'win32-x64']);
34
60
 
61
+ /**
62
+ * The desktop runtime dispatches `threenative build --target desktop` to a `mystral-tools` helper
63
+ * sitting beside its own executable (`src/cli/tool_dispatch.cpp:52`). A consumer that installs only
64
+ * the runtime gets `build tool helper is missing` and exit 127, so the helper is a published
65
+ * release asset of its own and is installed beside the runtime by the same atomic install.
66
+ */
67
+ export function toolsKey(key) {
68
+ return supported.has(key) ? `${key}-tools` : undefined;
69
+ }
70
+
71
+ export function toolsFilename(platform = process.platform) {
72
+ return platform === 'win32' ? 'mystral-tools.exe' : 'mystral-tools';
73
+ }
74
+
35
75
  export function platformKey(platform = process.platform, arch = process.arch) {
36
76
  const key = `${platform}-${arch}`;
37
77
  if (!supported.has(key)) throw new Error(`Unsupported native runtime platform '${key}'.`);
@@ -50,10 +90,20 @@ export function verifyChecksum(contents, expected, key) {
50
90
  }
51
91
 
52
92
  function releaseFromManifest(manifest, key) {
53
- const release = manifest.artifacts?.[key];
93
+ if (UNPUBLISHED_PREBUILT_KEYS.includes(key)) {
94
+ const error = new Error(
95
+ `No prebuilt release is published for '${key}'. This platform builds from an engine checkout until its release credentials exist; see PRD-262.`,
96
+ );
97
+ error.code = 'PREBUILT_RELEASE_UNPUBLISHED';
98
+ throw error;
99
+ }
100
+ const release = manifest?.artifacts?.[key];
54
101
  if (!release?.url || !release?.sha256) {
55
102
  throw new Error(`No prebuilt release asset is recorded for '${key}'.`);
56
103
  }
104
+ if (typeof release.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(release.sha256)) {
105
+ throw new Error(`Invalid prebuilt SHA-256 for '${key}'.`);
106
+ }
57
107
  const url = new URL(release.url);
58
108
  if (url.protocol !== 'https:' && process.env.THREENATIVE_ALLOW_INSECURE_PREBUILT !== '1') {
59
109
  throw new Error(`Prebuilt release URL for '${key}' must use HTTPS.`);
@@ -61,13 +111,91 @@ function releaseFromManifest(manifest, key) {
61
111
  return release;
62
112
  }
63
113
 
114
+ function isLoopbackFixture(url) {
115
+ return process.env.THREENATIVE_ALLOW_INSECURE_PREBUILT === '1' &&
116
+ url.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname) &&
117
+ !url.username && !url.password;
118
+ }
119
+
120
+ function validateManifestEnvelope(manifest, options) {
121
+ if (manifest?.schemaVersion !== 1) throw new Error('Unsupported or missing prebuilt manifest schemaVersion.');
122
+ const version = options.version ?? packageVersion;
123
+ if (manifest.version !== version) {
124
+ throw new Error(`Prebuilt manifest version mismatch: expected ${version}, received ${manifest.version}.`);
125
+ }
126
+ if (typeof manifest.sourceSha !== 'string' || !/^[a-f0-9]{40}$/u.test(manifest.sourceSha)) {
127
+ throw new Error('Prebuilt manifest must record a full source SHA.');
128
+ }
129
+ if (options.sourceSha !== undefined && manifest.sourceSha !== options.sourceSha) {
130
+ throw new Error(`Prebuilt source SHA mismatch: expected ${options.sourceSha}, received ${manifest.sourceSha}.`);
131
+ }
132
+ if (!manifest.artifacts || typeof manifest.artifacts !== 'object' || Array.isArray(manifest.artifacts)) {
133
+ throw new Error('Prebuilt manifest artifacts must be an object.');
134
+ }
135
+ return version;
136
+ }
137
+
138
+ function validateManifestArtifact(manifest, key, version) {
139
+ if (!Object.hasOwn(PREBUILT_ASSET_NAMES, key)) throw new Error(`Unknown prebuilt release key '${key}'.`);
140
+ const release = releaseFromManifest(manifest, key);
141
+ if (!Number.isSafeInteger(release.size) || release.size <= 0) {
142
+ throw new Error(`Prebuilt release size for '${key}' must be a positive integer.`);
143
+ }
144
+ const expectedUrl = `${releaseManifestUrl(version).replace('/prebuilt-lock.json', '')}/${PREBUILT_ASSET_NAMES[key]}`;
145
+ const url = new URL(release.url);
146
+ if (release.url !== expectedUrl && !isLoopbackFixture(url)) {
147
+ throw new Error(`Prebuilt release URL for '${key}' must match version ${version}: ${expectedUrl}.`);
148
+ }
149
+ }
150
+
151
+ /** Validate the entire advertised cohort before selecting even one consumer artifact. */
152
+ export function validateReleaseManifest(manifest, options = {}) {
153
+ const version = validateManifestEnvelope(manifest, options);
154
+ // iOS retains its separate release gate; it is not a prerequisite for a non-iOS consumer.
155
+ const requiredKeys = options.requiredKeys ??
156
+ PUBLISHED_PREBUILT_KEYS.filter((key) => !key.startsWith('ios-'));
157
+ for (const key of requiredKeys) releaseFromManifest(manifest, key);
158
+ for (const key of Object.keys(manifest.artifacts)) validateManifestArtifact(manifest, key, version);
159
+ return manifest;
160
+ }
161
+
162
+ /** The release workflow uses this same validator, including its existing iOS requirement. */
163
+ export function generateReleaseManifest(directory, { repository, tag, sourceSha }) {
164
+ if (repository !== RELEASE_REPOSITORY) {
165
+ throw new Error(`Prebuilt releases must be published by ${RELEASE_REPOSITORY}, received ${repository}.`);
166
+ }
167
+ if (tag !== `runtime-native-v${packageVersion}`) {
168
+ throw new Error(`Prebuilt release tag must be runtime-native-v${packageVersion}, received ${tag}.`);
169
+ }
170
+ const published = PUBLISHED_PREBUILT_KEYS.map((key) => [key, PREBUILT_ASSET_NAMES[key]]);
171
+ const expected = published.map(([, name]) => name).sort();
172
+ const actual = readdirSync(directory).sort();
173
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {
174
+ throw new Error(`Incomplete prebuilt release matrix: expected ${expected.join(', ')}; received ${actual.join(', ')}.`);
175
+ }
176
+ const artifacts = Object.fromEntries(published.map(([key, name]) => {
177
+ const contents = readFileSync(join(directory, name));
178
+ if (contents.length === 0) throw new Error(`Prebuilt release asset '${key}' is empty.`);
179
+ return [key, { sha256: sha256(contents), size: contents.length,
180
+ url: `${releaseManifestUrl().replace('/prebuilt-lock.json', '')}/${name}` }];
181
+ }));
182
+ return validateReleaseManifest({ schemaVersion: 1, version: packageVersion, sourceSha, artifacts },
183
+ { sourceSha, requiredKeys: PUBLISHED_PREBUILT_KEYS });
184
+ }
185
+
64
186
  export function readRelease(manifestPath, key) {
65
187
  if (!existsSync(manifestPath)) {
66
188
  const error = new Error(`No prebuilt release manifest exists for '${key}'; this target remains OPEN.`);
67
189
  error.code = 'PREBUILT_RELEASE_MISSING';
68
190
  throw error;
69
191
  }
70
- return releaseFromManifest(JSON.parse(readFileSync(manifestPath, 'utf8')), key);
192
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
193
+ // Explicit artifact-only local pins predate the envelope. Never downgrade a partially
194
+ // specified candidate, and never allow this compatibility path for a remote default lock.
195
+ if (manifest && ['schemaVersion', 'version', 'sourceSha'].some((field) => Object.hasOwn(manifest, field))) {
196
+ validateReleaseManifest(manifest);
197
+ }
198
+ return releaseFromManifest(manifest, key);
71
199
  }
72
200
 
73
201
  export function releaseManifestUrl(version = packageVersion) {
@@ -76,8 +204,72 @@ export function releaseManifestUrl(version = packageVersion) {
76
204
 
77
205
  export function writeInstallStatus(status, statusPath = join(packageRoot, 'prebuilt', 'install-status.json')) {
78
206
  mkdirSync(dirname(statusPath), { recursive: true });
79
- writeFileSync(statusPath, `${JSON.stringify(status, null, 2)}\n`);
80
- return statusPath;
207
+ const temporary = `${statusPath}.${randomUUID()}.tmp`;
208
+ try {
209
+ writeFileSync(temporary, `${JSON.stringify(status, null, 2)}\n`, { flag: 'wx' });
210
+ renameSync(temporary, statusPath);
211
+ return statusPath;
212
+ } finally {
213
+ rmSync(temporary, { force: true });
214
+ }
215
+ }
216
+
217
+ function createInstallPlan(options) {
218
+ const platform = options.platform ?? process.platform;
219
+ const key = `${platform}-${options.arch ?? process.arch}`;
220
+ const filename = platform === 'win32' ? 'threenative-runtime.exe' : 'threenative-runtime';
221
+ const output = resolve(options.output ?? join(packageRoot, 'prebuilt', key, filename));
222
+ const statusPath = resolve(options.statusPath ?? (options.output
223
+ ? join(dirname(output), 'install-status.json')
224
+ : join(packageRoot, 'prebuilt', 'install-status.json')));
225
+ if (output === statusPath) throw new Error('Prebuilt output and install status paths must differ.');
226
+ const toolsOutput = join(dirname(output), toolsFilename(platform));
227
+ if (toolsOutput === output) throw new Error('Prebuilt runtime and build tool helper paths must differ.');
228
+ return { platform, key, output, statusPath, toolsOutput, toolsKey: toolsKey(key),
229
+ status: { key, url: options.manifestPath ?? process.env.THREENATIVE_PREBUILT_MANIFEST ??
230
+ options.manifestUrl ?? releaseManifestUrl(), version: packageVersion } };
231
+ }
232
+
233
+ function beginInstall(plan, arch) {
234
+ rmSync(plan.output, { force: true });
235
+ rmSync(plan.toolsOutput, { force: true });
236
+ rmSync(plan.statusPath, { force: true });
237
+ writeInstallStatus({ ...plan.status, ok: false, reason: 'installing' }, plan.statusPath);
238
+ platformKey(plan.platform, arch);
239
+ }
240
+
241
+ function publishBinary(target, contents, platform) {
242
+ const temporary = `${target}.${randomUUID()}.tmp`;
243
+ try {
244
+ mkdirSync(dirname(target), { recursive: true });
245
+ writeFileSync(temporary, contents, { flag: 'wx' });
246
+ if (platform !== 'win32') chmodSync(temporary, 0o755);
247
+ renameSync(temporary, target);
248
+ } finally {
249
+ rmSync(temporary, { force: true });
250
+ }
251
+ }
252
+
253
+ // The success marker is written only once both binaries are in place: a desktop build that finds
254
+ // the runtime but not the helper dies inside the packager with exit 127, which is exactly the
255
+ // stale-success shape this install exists to prevent.
256
+ function publishInstall(plan, contents, toolsContents) {
257
+ publishBinary(plan.output, contents, plan.platform);
258
+ publishBinary(plan.toolsOutput, toolsContents, plan.platform);
259
+ writeInstallStatus({ ...plan.status, ok: true, reason: 'installed', sha256: sha256(contents),
260
+ toolsSha256: sha256(toolsContents) }, plan.statusPath);
261
+ }
262
+
263
+ function recordInstallFailure(plan, error) {
264
+ try {
265
+ rmSync(plan.output, { force: true });
266
+ rmSync(plan.toolsOutput, { force: true });
267
+ writeInstallStatus({ ...plan.status, ok: false,
268
+ reason: error instanceof Error ? error.message : String(error) }, plan.statusPath);
269
+ } catch (statusError) {
270
+ rmSync(plan.statusPath, { force: true });
271
+ throw new Error(`Could not invalidate prebuilt install for '${plan.key}': ${statusError instanceof Error ? statusError.message : String(statusError)}`, { cause: error });
272
+ }
81
273
  }
82
274
 
83
275
  async function fetchRelease(manifestUrl, key) {
@@ -100,7 +292,7 @@ async function fetchRelease(manifestUrl, key) {
100
292
  if (response.status === 404) error.code = 'PREBUILT_RELEASE_MISSING';
101
293
  throw error;
102
294
  }
103
- return releaseFromManifest(await response.json(), key);
295
+ return releaseFromManifest(validateReleaseManifest(await response.json()), key);
104
296
  }
105
297
 
106
298
  export async function downloadReleaseArtifact(key, options = {}) {
@@ -119,21 +311,66 @@ export async function downloadReleaseArtifact(key, options = {}) {
119
311
  if (!response.ok) {
120
312
  throw new Error(`Prebuilt release fetch failed for '${key}' at ${release.url}: HTTP ${response.status}.`);
121
313
  }
122
- const contents = Buffer.from(await response.arrayBuffer());
314
+ let contents;
315
+ try {
316
+ contents = Buffer.from(await response.arrayBuffer());
317
+ } catch (error) {
318
+ throw new Error(`Prebuilt release body failed for '${key}' at ${release.url}: ${error instanceof Error ? error.message : String(error)}`);
319
+ }
123
320
  verifyChecksum(contents, release.sha256, key);
321
+ if (contents.length === 0 || (release.size !== undefined && contents.length !== release.size)) {
322
+ throw new Error(`Prebuilt release size verification failed for '${key}': received ${contents.length} bytes.`);
323
+ }
124
324
  return contents;
125
325
  }
126
326
 
327
+ /** Reuse only a complete install for this exact package, platform and manifest selection. */
328
+ function isVerifiedInstall(plan, options) {
329
+ try {
330
+ const status = JSON.parse(readFileSync(plan.statusPath, 'utf8'));
331
+ if (status.ok !== true || status.key !== plan.key ||
332
+ status.version !== plan.status.version || status.url !== plan.status.url) return false;
333
+ // A caller can replace a local lock without changing its path. That explicit pin must
334
+ // still authorize these bytes, and a missing/invalid pin must never be bypassed by cache.
335
+ const manifestPath = options.manifestPath ?? process.env.THREENATIVE_PREBUILT_MANIFEST;
336
+ const pinned = manifestPath ? readRelease(resolve(manifestPath), plan.key) : undefined;
337
+ if (pinned && pinned.sha256 !== status.sha256) return false;
338
+ const contents = readFileSync(plan.output);
339
+ if (contents.length === 0 || (pinned?.size !== undefined && contents.length !== pinned.size)) return false;
340
+ verifyChecksum(contents, status.sha256, plan.key);
341
+ // A cached runtime without its verified helper is not a reusable desktop install.
342
+ if (typeof status.toolsSha256 !== 'string') return false;
343
+ const pinnedTools = manifestPath ? readRelease(resolve(manifestPath), plan.toolsKey) : undefined;
344
+ if (pinnedTools && pinnedTools.sha256 !== status.toolsSha256) return false;
345
+ const tools = readFileSync(plan.toolsOutput);
346
+ if (tools.length === 0 || (pinnedTools?.size !== undefined && tools.length !== pinnedTools.size)) return false;
347
+ verifyChecksum(tools, status.toolsSha256, plan.toolsKey);
348
+ return true;
349
+ } catch {
350
+ return false;
351
+ }
352
+ }
353
+
127
354
  export async function installPrebuilt(options = {}) {
128
- const key = platformKey(options.platform, options.arch);
129
- const contents = await downloadReleaseArtifact(key, options);
130
- const filename = process.platform === 'win32' ? 'threenative-runtime.exe' : 'threenative-runtime';
131
- const output = resolve(options.output ?? join(packageRoot, 'prebuilt', key, filename));
132
- mkdirSync(dirname(output), { recursive: true });
133
- writeFileSync(output, contents);
134
- if (process.platform !== 'win32') chmodSync(output, 0o755);
135
- console.log(`Installed verified ThreeNative runtime for '${key}'.`);
136
- return output;
355
+ const plan = createInstallPlan(options);
356
+ try {
357
+ // Packaging may reuse verified bytes offline. Explicit install/retry keeps its original
358
+ // invalidation semantics, including removing an earlier binary on a failed retry.
359
+ if (options.reuse === true) {
360
+ platformKey(plan.platform, options.arch);
361
+ if (isVerifiedInstall(plan, options)) return plan.output;
362
+ }
363
+ // A failed retry must not leave an earlier binary usable or its old success marker intact.
364
+ beginInstall(plan, options.arch);
365
+ const contents = await downloadReleaseArtifact(plan.key, options);
366
+ const toolsContents = await downloadReleaseArtifact(plan.toolsKey, options);
367
+ publishInstall(plan, contents, toolsContents);
368
+ console.log(`Installed verified ThreeNative runtime and build tool helper for '${plan.key}'.`);
369
+ return plan.output;
370
+ } catch (error) {
371
+ recordInstallFailure(plan, error);
372
+ throw error;
373
+ }
137
374
  }
138
375
 
139
376
  if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
@@ -141,26 +378,16 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
141
378
  if (sourceCheckout) {
142
379
  console.log('ThreeNative runtime source checkout detected; prebuilt install is deferred to package testing.');
143
380
  } else {
144
- const key = `${process.platform}-${process.arch}`;
145
- const url = process.env.THREENATIVE_PREBUILT_MANIFEST ?? releaseManifestUrl();
146
381
  installPrebuilt()
147
- .then(() => writeInstallStatus({ key, ok: true, reason: 'installed', url, version: packageVersion }))
148
382
  .catch((error) => {
149
383
  const reason = error instanceof Error ? error.message : String(error);
150
- try {
151
- writeInstallStatus({ key, ok: false, reason, url, version: packageVersion });
152
- } catch (statusError) {
153
- console.error(
154
- `Could not record prebuilt install status: ${statusError instanceof Error ? statusError.message : String(statusError)}`,
155
- );
156
- }
157
384
  // An unpublished release is a packaging-state fact, not a broken download. The web game
158
385
  // this install carries must not lose node_modules/.bin over an optional native binary;
159
386
  // the native lanes fail closed later, on the missing binary itself.
160
- if (error instanceof Error && error.code === 'PREBUILT_RELEASE_MISSING') {
387
+ if (error instanceof Error &&
388
+ ['PREBUILT_RELEASE_MISSING', 'PREBUILT_RELEASE_UNPUBLISHED'].includes(error.code)) {
161
389
  console.warn(
162
- `No prebuilt release is published for v${packageVersion} (${reason}). ` +
163
- 'Continuing without the native runtime; desktop and device lanes fail closed on the missing binary.',
390
+ `No prebuilt release is published for v${packageVersion} (${reason}). Continuing without the native runtime; desktop and device lanes fail closed on the missing binary.`,
164
391
  );
165
392
  return;
166
393
  }
@@ -156,7 +156,7 @@ function androidPaths(root = runtimeRoot) {
156
156
  export const DEFAULT_ANDROID_CONFIG = {
157
157
  app: { id: 'com.threenative.game', name: 'ThreeNative', version: '0.1.0', build: 1 },
158
158
  display: { orientation: 'landscape', fullscreen: true, keepScreenOn: false, maxFps: 60, backgroundMode: 'pause' },
159
- window: { title: 'ThreeNative', width: 1280, height: 720, resizable: true },
159
+ window: { title: 'ThreeNative', width: 1280, height: 720, maximized: false, resizable: true },
160
160
  // `native` is PRD-216's CanvasLayer renderer: no WebView, no CSS, no second process. A game
161
161
  // that never states a renderer therefore ships no overlay, which is what acceptance criterion 5
162
162
  // asks for. Templates state `web` explicitly.
@@ -629,18 +629,26 @@ export async function packageAndroid(
629
629
  config = undefined,
630
630
  options = {},
631
631
  ) {
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.
632
+ // Source identity must not depend on whether downloaded dependencies are already present.
633
+ // Otherwise a partially provisioned checkout silently takes the consumer download path.
640
634
  const packageRoot = resolve(
641
635
  options.runtimeRoot ?? process.env.THREENATIVE_RUNTIME_SOURCE ?? runtimeRoot,
642
636
  );
643
637
  const { androidRoot } = androidPaths(packageRoot);
638
+ const sourceCheckout = existsSync(join(packageRoot, 'CMakeLists.txt'));
639
+ if (sourceCheckout && options.allowSourceBuild !== true) {
640
+ throw new Error(
641
+ `Android build resolved a source checkout at ${packageRoot} with no explicit opt-in. ` +
642
+ 'Pass --allow-source-build (or { allowSourceBuild: true }) for a maintainer build; ' +
643
+ 'consumer builds use the prebuilt path from a published install.',
644
+ );
645
+ }
646
+ if (sourceCheckout && !existsSync(join(packageRoot, 'third_party', 'sdl3-android', `SDL3-${SDL3_ANDROID_VERSION}.aar`))) {
647
+ throw new Error(
648
+ `Android source checkout at ${packageRoot} is missing SDL3-${SDL3_ANDROID_VERSION}.aar. ` +
649
+ 'Provision the maintainer dependencies with node scripts/download-deps.mjs --android from the runtime checkout, then retry --allow-source-build.',
650
+ );
651
+ }
644
652
  const declared = configValue(config, orientation);
645
653
  orientationValue(declared.display.orientation);
646
654
  const gradlew = join(androidRoot, process.platform === 'win32' ? 'gradlew.bat' : 'gradlew');
@@ -650,9 +658,6 @@ export async function packageAndroid(
650
658
  options.ensureGradleWrapper ??
651
659
  (() => ensureGradleWrapper({ output: join(androidRoot, 'gradle', 'wrapper', 'gradle-wrapper.jar') }));
652
660
  await ensureWrapper();
653
- const sourceCheckout =
654
- existsSync(join(packageRoot, 'CMakeLists.txt')) &&
655
- existsSync(join(packageRoot, 'third_party', 'sdl3-android', `SDL3-${SDL3_ANDROID_VERSION}.aar`));
656
661
  if (!sourceCheckout) {
657
662
  const preparePrebuilts =
658
663
  options.prepareAndroidPrebuilts ??
@@ -663,7 +668,7 @@ export async function packageAndroid(
663
668
  // Name the cause and the way out. The bare HTTP status told a person which URL failed and
664
669
  // nothing about why a published install can never satisfy it.
665
670
  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`,
671
+ `${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 exec threenative build --target android --allow-source-build\n`,
667
672
  { cause: error },
668
673
  );
669
674
  }
@@ -737,13 +742,14 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
737
742
  const orientationIndex = process.argv.indexOf('--orientation');
738
743
  const configIndex = process.argv.indexOf('--config');
739
744
  const uiIndex = process.argv.indexOf('--ui');
745
+ const allowSourceBuild = process.argv.includes('--allow-source-build');
740
746
  if (
741
747
  bundleIndex === -1 ||
742
748
  !process.argv[bundleIndex + 1] ||
743
749
  process.argv[bundleIndex + 1].startsWith('--')
744
750
  ) {
745
751
  console.error(
746
- 'Usage: package-android.mjs --bundle FILE [--output FILE] [--assets DIR] [--ui DIR] [--orientation landscape|portrait|sensor] [--config FILE]',
752
+ 'Usage: package-android.mjs --bundle FILE [--output FILE] [--assets DIR] [--ui DIR] [--orientation landscape|portrait|sensor] [--config FILE] [--allow-source-build]',
747
753
  );
748
754
  process.exitCode = 1;
749
755
  } else if (
@@ -782,7 +788,12 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
782
788
  assetsIndex === -1 ? undefined : resolve(process.argv[assetsIndex + 1]),
783
789
  orientationIndex === -1 ? undefined : process.argv[orientationIndex + 1],
784
790
  readAndroidConfig(configPath),
785
- uiIndex === -1 ? {} : { ui: resolve(process.argv[uiIndex + 1]) },
791
+ {
792
+ ...(uiIndex === -1 ? {} : { ui: resolve(process.argv[uiIndex + 1]) }),
793
+ // Maintainer route for source-checkout builds: the guard requires an
794
+ // explicit opt-in, and this flag is its CLI spelling.
795
+ ...(allowSourceBuild ? { allowSourceBuild: true } : {}),
796
+ },
786
797
  );
787
798
  } catch (error) {
788
799
  console.error(error instanceof Error ? error.message : String(error));
@@ -19,13 +19,38 @@ import { dirname, join, resolve } from 'node:path';
19
19
  import { fileURLToPath, pathToFileURL } from 'node:url';
20
20
 
21
21
  import { assertNativeAssetsDecodable, deriveDesktopWebpSupport } from './asset-preflight.mjs';
22
+ import { installPrebuilt } from './install-prebuilt.mjs';
22
23
 
23
24
  const runtimeRoot = resolve(fileURLToPath(new URL('..', import.meta.url)));
24
25
 
26
+ /**
27
+ * Resolve the desktop runtime binary a consumer build compiles against.
28
+ *
29
+ * A published install ships no compiled runtime until the postinstall hook fetches one, so a
30
+ * missing `--runtime` installs from the release manifest rather than failing with a bare
31
+ * "missing file". `THREENATIVE_RUNTIME_SOURCE` remains the decoder-preflight source only: it
32
+ * never selects or substitutes the runtime binary, and no code path here reads a checkout as
33
+ * the runtime. `options.runtimeSource` is an explicit test seam for the preflight directory.
34
+ */
35
+ export async function resolveDesktopRuntime(explicit, options = {}) {
36
+ if (explicit) {
37
+ if (!existsSync(explicit)) throw new Error(`Missing prebuilt runtime for '${process.platform}-${process.arch}': ${explicit}`);
38
+ return explicit;
39
+ }
40
+ const sourceOverride = options.runtimeSource ?? process.env.THREENATIVE_RUNTIME_SOURCE;
41
+ if (sourceOverride) {
42
+ throw new Error(
43
+ `Desktop source-checkout preflight is set (THREENATIVE_RUNTIME_SOURCE=${sourceOverride}) but no --runtime was provided. ` +
44
+ 'Pass the checkout-built --runtime explicitly for a maintainer build; consumer builds unset the override and install from the release manifest.',
45
+ );
46
+ }
47
+ return installPrebuilt({ ...options.install, reuse: true });
48
+ }
49
+
25
50
  export const DEFAULT_DESKTOP_CONFIG = {
26
51
  app: { id: 'com.threenative.game', name: 'ThreeNative', version: '0.1.0', build: 1 },
27
52
  display: { orientation: 'landscape', fullscreen: true, keepScreenOn: false, maxFps: 60 },
28
- window: { title: 'ThreeNative', width: 1280, height: 720, resizable: true },
53
+ window: { title: 'ThreeNative', width: 1280, height: 720, maximized: false, resizable: true },
29
54
  };
30
55
 
31
56
  function readConfig(configPath) {
@@ -43,11 +68,14 @@ export function parseArgs(args) {
43
68
  const flag = args[index];
44
69
  const value = args[index + 1];
45
70
  if (!['--assets', '--bundle', '--config', '--output', '--runtime', '--ui'].includes(flag) || !value) {
46
- throw new Error('Usage: package-desktop.mjs --bundle FILE --runtime FILE --output FILE [--assets DIR] [--ui DIR] [--config FILE]');
71
+ throw new Error('Usage: package-desktop.mjs --bundle FILE --output FILE [--runtime FILE] [--assets DIR] [--ui DIR] [--config FILE]');
47
72
  }
48
73
  options[flag.slice(2)] = resolve(value);
49
74
  }
50
- for (const required of ['bundle', 'output', 'runtime']) {
75
+ // `--runtime` is optional: a consumer build with no `--runtime` installs the verified
76
+ // prebuilt from the release manifest via resolveDesktopRuntime. A maintainer build passes
77
+ // the checkout-built binary explicitly.
78
+ for (const required of ['bundle', 'output']) {
51
79
  if (!options[required]) throw new Error(`Missing --${required}.`);
52
80
  }
53
81
  return options;
@@ -58,9 +86,23 @@ export function packageDesktop(options) {
58
86
  if (!['linux-x64', 'linux-arm64', 'darwin-x64', 'darwin-arm64', 'win32-x64'].includes(key)) {
59
87
  throw new Error(`Unsupported desktop platform '${key}'.`);
60
88
  }
61
- for (const [label, file] of [['native bundle', options.bundle], ['prebuilt runtime', options.runtime]]) {
62
- if (!existsSync(file)) throw new Error(`Missing ${label} for '${key}': ${file}`);
89
+ if (!options.bundle || !existsSync(options.bundle)) {
90
+ throw new Error(`Missing native bundle for '${key}': ${options.bundle ?? '(not provided)'}`);
91
+ }
92
+ // An explicit `--runtime` keeps the original sync body: the preflight failure the
93
+ // decoder tests assert stays a sync throw. Only the missing-runtime install is async.
94
+ if (options.runtime) {
95
+ if (!existsSync(options.runtime)) {
96
+ throw new Error(`Missing prebuilt runtime for '${key}': ${options.runtime}`);
97
+ }
98
+ return compileDesktopArtifact(options, options.runtime);
63
99
  }
100
+ return resolveDesktopRuntime(undefined, { runtimeSource: options.runtimeSource, install: options.install }).then((runtime) =>
101
+ compileDesktopArtifact(options, runtime),
102
+ );
103
+ }
104
+
105
+ function compileDesktopArtifact(options, runtime) {
64
106
  const output = process.platform === 'win32' && !options.output.endsWith('.exe')
65
107
  ? `${options.output}.exe`
66
108
  : options.output;
@@ -72,6 +114,7 @@ export function packageDesktop(options) {
72
114
  options.assets,
73
115
  staging,
74
116
  options.config === undefined ? undefined : readConfig(options.config),
117
+ process.env.THREENATIVE_RUNTIME_SOURCE ?? runtimeRoot,
75
118
  );
76
119
  // The UI bundle sits beside the executable rather than inside it. Desktop compiles to one
77
120
  // file, but the overlay's web view reads its page from a real path — that is what gives it a
@@ -93,7 +136,7 @@ export function packageDesktop(options) {
93
136
  '--out',
94
137
  output,
95
138
  ];
96
- const result = spawnSync(options.runtime, args, { encoding: 'utf8', stdio: 'inherit' });
139
+ const result = spawnSync(runtime, args, { encoding: 'utf8', stdio: 'inherit' });
97
140
  if (result.error) throw result.error;
98
141
  if (result.status !== 0)
99
142
  throw new Error(`Runtime packager exited with code ${result.status ?? 'unknown'}.`);
@@ -192,7 +235,7 @@ export function stageDesktopFiles(
192
235
 
193
236
  if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
194
237
  try {
195
- packageDesktop(parseArgs(process.argv.slice(2)));
238
+ await packageDesktop(parseArgs(process.argv.slice(2)));
196
239
  } catch (error) {
197
240
  console.error(error instanceof Error ? error.message : String(error));
198
241
  process.exitCode = 1;