@threenative/runtime-native 0.3.1 → 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.
@@ -1,227 +1,34 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { spawnSync } from 'node:child_process';
4
- import { createHash } from 'node:crypto';
5
- import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
6
- import { basename, dirname, join, resolve } from 'node:path';
7
- import { fileURLToPath, pathToFileURL } from 'node:url';
8
- import { PNG } from 'pngjs';
9
-
10
- const READY_MARKER = 'TN_NATIVE_SMOKE_READY:webgpu';
11
- const ASSET_MARKER = 'TN_NATIVE_STARTER_ASSETS_LOADED:texture,glb';
12
- // Measured: a drawn starter frame has ~17,000 distinct colours, a lost capture had 5.
13
- const UNRENDERED_FRAME_COLOR_FLOOR = 64;
14
- // 64x64. Below this the frame is a fixture, not a capture.
15
- const UNRENDERED_FRAME_MIN_PIXELS = 4096;
16
- const ASSET_PIXEL_FLOOR = 100;
17
- // The packaged proof is a cyan/magenta checkerboard pennant, and it is identified by CHANNEL
18
- // MARGIN rather than by distance to the authored texture colour. The gate reads a lit, tonemapped
19
- // render, and the authored cyan never reaches the screen: measured on the CI capture of run
20
- // 34076016432, the pennant's cyan renders as rgb(86,180,189) — 103 away from the authored
21
- // [18,220,255] — while the ocean behind it sits at 149 and the sky at 140. Any absolute-distance
22
- // threshold wide enough to admit the asset also admits the sea, which is how a frame showing the
23
- // pennant plainly was rejected with 798,464 of 921,600 pixels classified as proof.
24
- //
25
- // Magenta is the discriminator, because an ocean world contains none: 521 magenta pixels on the
26
- // pennant, against 0 in the same frame with the pennant cropped away.
27
- const PROOF_MAGENTA_MIN_MARGIN = 40;
28
- // Corroborating cyan, counted only inside the magenta bounds so the background cannot supply it.
29
- const PROOF_CYAN_MIN_MARGIN = 70;
30
- const PROOF_CYAN_IN_BOUNDS_FLOOR = 50;
31
- // A proof region may occupy up to a quarter of a rendered frame; a wash that reaches almost every
32
- // part of the frame must not count as localized evidence.
33
- const MAX_ASSET_BOUNDS_FRACTION = 0.25;
34
- // Bounds alone cannot separate a small asset from magenta scattered thinly across the frame, since
35
- // scattered pixels share almost the same bounding box as a solid one. Density does: the pennant
36
- // fills 0.236 of its own bounds, scattered noise fills 0.04.
37
- const MIN_ASSET_BOUNDS_DENSITY = 0.1;
38
-
39
- function isProofMagenta(data, offset) {
40
- return (
41
- data[offset + 3] > 0 &&
42
- data[offset] > data[offset + 1] + PROOF_MAGENTA_MIN_MARGIN &&
43
- data[offset + 2] > data[offset + 1] + PROOF_MAGENTA_MIN_MARGIN
44
- );
45
- }
46
-
47
- function isProofCyan(data, offset) {
48
- return (
49
- data[offset + 3] > 0 &&
50
- data[offset + 1] - data[offset] > PROOF_CYAN_MIN_MARGIN &&
51
- data[offset + 2] - data[offset] > PROOF_CYAN_MIN_MARGIN
4
+ import { realpathSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ export * from './verify-starter-desktop-base.mjs';
9
+ export * from './verify-starter-consumer.mjs';
10
+
11
+ // PRD-365 owns the installed desktop-container verifier and PRD-375 its brand inspection; PRD-366
12
+ // adds consumer-gameplay qualification without forking or replacing either. Imports see every
13
+ // contract through the re-exports above -- including `verifyContainerBrand`, so `--brand-only` and
14
+ // its callers keep resolving through this path. The CLI keeps the historical desktop behavior
15
+ // unless the consumer route is explicitly requested, so `--brand-only` and `--config` reach the
16
+ // base file's hardened flag parser rather than being re-implemented here.
17
+ if (process.argv[1] && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) {
18
+ const directory = dirname(fileURLToPath(import.meta.url));
19
+ const consumer = process.argv.includes('--consumer') || process.argv.includes('--qualify-existing');
20
+ const target = join(
21
+ directory,
22
+ consumer ? 'verify-starter-consumer.mjs' : 'verify-starter-desktop-base.mjs',
52
23
  );
53
- }
54
-
55
- function countProofCyanInBounds(png, bounds) {
56
- let cyan = 0;
57
- for (let y = bounds.minY; y <= bounds.maxY; y += 1) {
58
- for (let x = bounds.minX; x <= bounds.maxX; x += 1) {
59
- if (isProofCyan(png.data, (y * png.width + x) * 4)) cyan += 1;
60
- }
61
- }
62
- return cyan;
63
- }
64
-
65
- // Localization is a question about a capture, not about a texture, so only a capture-sized frame
66
- // reaches this. The distribution test feeds the packaged 16x16 proof itself, where the asset
67
- // legitimately fills the whole frame and asking where it sits has no meaning.
68
- function assertProofIsLocalized(png, bounds, magentaAssetPixels) {
69
- const boundsArea = (bounds.maxX - bounds.minX + 1) * (bounds.maxY - bounds.minY + 1);
70
- const boundsFraction = boundsArea / (png.width * png.height);
71
- if (boundsFraction > MAX_ASSET_BOUNDS_FRACTION) {
72
- throw new Error(
73
- `TN_NATIVE_STARTER_ASSET_NOT_LOCALIZED: magenta spans ${(boundsFraction * 100).toFixed(1)}% of the frame, which is a wash, not the proof asset.`,
74
- );
75
- }
76
- const density = magentaAssetPixels / boundsArea;
77
- if (density < MIN_ASSET_BOUNDS_DENSITY) {
78
- throw new Error(
79
- `TN_NATIVE_STARTER_ASSET_NOT_LOCALIZED: magenta fills only ${(density * 100).toFixed(1)}% of its own bounds, which is scatter, not the proof asset.`,
80
- );
81
- }
82
- }
83
-
84
- // One pass over the frame: the colour census the unrendered-frame floor reads, and the magenta
85
- // pixel count with the bounds it occupies.
86
- function scanProofMagenta(png) {
87
- const colors = new Set();
88
- const bounds = { maxX: -1, maxY: -1, minX: png.width, minY: png.height };
89
- let magentaAssetPixels = 0;
90
- for (let index = 0; index < png.data.length; index += 4) {
91
- colors.add(
92
- `${png.data[index]},${png.data[index + 1]},${png.data[index + 2]},${png.data[index + 3]}`,
93
- );
94
- if (!isProofMagenta(png.data, index)) continue;
95
- magentaAssetPixels += 1;
96
- const pixel = index / 4;
97
- const x = pixel % png.width;
98
- const y = Math.floor(pixel / png.width);
99
- if (x < bounds.minX) bounds.minX = x;
100
- if (x > bounds.maxX) bounds.maxX = x;
101
- if (y < bounds.minY) bounds.minY = y;
102
- if (y > bounds.maxY) bounds.maxY = y;
103
- }
104
- return { bounds, colors, magentaAssetPixels };
105
- }
106
-
107
- export function inspectStarterScreenshot(path) {
108
- if (!existsSync(path)) throw new Error(`TN_NATIVE_STARTER_SCREENSHOT_MISSING: ${path}`);
109
- const png = PNG.sync.read(readFileSync(path));
110
- const { bounds, colors, magentaAssetPixels } = scanProofMagenta(png);
111
- if (colors.size < 2) throw new Error('TN_NATIVE_STARTER_SCREENSHOT_BLANK: one-color frame.');
112
- // A one-colour guard is too weak to catch the capture this gate actually loses. A rendered
113
- // starter frame carries roughly 17k distinct colours; an intermittent CI failure captured five —
114
- // flat background, two flat shapes, thirteen pixels of the GLB — while the run log still showed
115
- // TN_NATIVE_STARTER_ASSETS_LOADED and "Rendered 300 frames". That frame was never drawn, and
116
- // reporting it as a missing asset sends the reader hunting for a texture that loaded fine.
117
- // Only meaningful at capture resolution. A 16x16 synthetic fixture — what the installed-verifier
118
- // distribution test feeds this function — is legitimately two colours, and judging it by the
119
- // diversity a 1280x720 render carries would reject a frame that is exactly what it claims to be.
120
- const rendered = png.width * png.height >= UNRENDERED_FRAME_MIN_PIXELS;
121
- if (rendered && colors.size < UNRENDERED_FRAME_COLOR_FLOOR) {
122
- throw new Error(
123
- `TN_NATIVE_STARTER_FRAME_NOT_RENDERED: only ${colors.size} distinct colours in ${png.width}x${png.height}. The run log may still show every marker: this is the capture, not the scene.`,
124
- );
125
- }
126
- if (magentaAssetPixels < ASSET_PIXEL_FLOOR) {
127
- throw new Error(
128
- `TN_NATIVE_STARTER_ASSET_NOT_VISIBLE: found ${magentaAssetPixels} magenta proof pixels in a frame of ${colors.size} colours.`,
129
- );
130
- }
131
- if (rendered) assertProofIsLocalized(png, bounds, magentaAssetPixels);
132
- const cyanAssetPixels = countProofCyanInBounds(png, bounds);
133
- if (cyanAssetPixels < PROOF_CYAN_IN_BOUNDS_FLOOR) {
134
- throw new Error(
135
- `TN_NATIVE_STARTER_ASSET_NOT_VISIBLE: magenta found but only ${cyanAssetPixels} cyan proof pixels inside its bounds; the checkerboard needs both colours.`,
136
- );
137
- }
138
- return {
139
- colors: colors.size,
140
- cyanAssetPixels,
141
- height: png.height,
142
- magentaAssetPixels,
143
- width: png.width,
144
- };
145
- }
146
-
147
- export function analyzeStarterLog(log, frames = 300) {
148
- const failures = [];
149
- for (const marker of [READY_MARKER, ASSET_MARKER, `TN_NATIVE_SMOKE_${frames}_FRAMES:${frames}`]) {
150
- if (!log.includes(marker)) failures.push(`missing ${marker}`);
151
- }
152
- if (!new RegExp(`Rendered ${frames} frames in \\d+ms`, 'u').test(log)) {
153
- failures.push(`missing exact ${frames}-frame completion`);
154
- }
155
- for (const pattern of [/TN_NATIVE_START_FAILED/u, /validation error/iu, /TypeError:/u]) {
156
- if (pattern.test(log)) failures.push(`runtime log matched ${pattern}`);
157
- }
158
- // The capture is only evidence if the world was on screen when it was taken. The host holds the
159
- // screenshot until the startup gate opens and says so; a 0 here means it captured the loading
160
- // state after waiting out its budget, which is the difference between a 17,000-colour frame and
161
- // a five-colour one.
162
- if (log.includes('TN_STARTUP_CAPTURE_READY:0')) {
163
- failures.push('startup gate never opened before capture (TN_STARTUP_CAPTURE_READY:0)');
164
- }
165
- return failures;
166
- }
167
-
168
- export function verifyStarterDesktop({ frames = 300, project = process.cwd() } = {}) {
169
- const projectRoot = resolve(project);
170
- const manifest = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
171
- const projectName = basename(String(manifest.name ?? 'starter').replace(/^@[^/]+\//u, ''));
172
- const executableName = process.platform === 'win32' ? `${projectName}.exe` : projectName;
173
- const artifact = join(projectRoot, 'dist-native', executableName);
174
- if (!existsSync(artifact)) {
175
- throw new Error(`TN_NATIVE_STARTER_ARTIFACT_MISSING: run pnpm build:desktop first (${artifact}).`);
176
- }
177
- const artifactDirectory = join(projectRoot, 'artifacts', 'native');
178
- const screenshot = join(artifactDirectory, 'starter-desktop.png');
179
- const logPath = join(artifactDirectory, 'starter-desktop.log');
180
- const reportPath = join(artifactDirectory, 'starter-desktop-report.json');
181
- mkdirSync(artifactDirectory, { recursive: true });
182
- const runtimeArgs = ['--screenshot', screenshot, '--frames', String(frames)];
183
- // See verify-desktop-core.mjs: `xvfb-run` hands back its own failing cleanup kill's status.
184
- const displayHelper = join(dirname(fileURLToPath(import.meta.url)), 'xvfb.sh');
185
- if (process.platform === 'linux' && !existsSync(displayHelper)) {
186
- throw new Error(`TN_NATIVE_STARTER_DISPLAY_SUPPORT_MISSING: ${displayHelper}`);
187
- }
188
- const command = process.platform === 'linux' ? 'sh' : artifact;
189
- const args = process.platform === 'linux'
190
- ? [displayHelper, artifact, ...runtimeArgs]
191
- : runtimeArgs;
192
- const result = spawnSync(command, args, {
193
- cwd: projectRoot,
194
- encoding: 'utf8',
195
- env: process.platform === 'linux' ? { ...process.env, SDL_VIDEODRIVER: 'x11' } : process.env,
196
- timeout: 120_000,
24
+ const result = spawnSync(process.execPath, [target, ...process.argv.slice(2)], {
25
+ cwd: process.cwd(),
26
+ env: process.env,
27
+ stdio: 'inherit',
197
28
  });
198
- if (result.error) throw result.error;
199
- const log = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
200
- writeFileSync(logPath, log);
201
- if (result.status !== 0) throw new Error(`TN_NATIVE_STARTER_EXIT_${result.status}:\n${log}`);
202
- const failures = analyzeStarterLog(log, frames);
203
- if (failures.length > 0) throw new Error(`TN_NATIVE_STARTER_LOG_FAILED:\n${failures.join('\n')}`);
204
- const image = inspectStarterScreenshot(screenshot);
205
- const report = {
206
- artifact,
207
- completedAt: new Date().toISOString(),
208
- frames,
209
- image,
210
- log: logPath,
211
- pass: true,
212
- screenshot,
213
- screenshotSha256: createHash('sha256').update(readFileSync(screenshot)).digest('hex'),
214
- };
215
- writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
216
- return report;
217
- }
218
-
219
- if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
220
- try {
221
- const report = verifyStarterDesktop();
222
- console.log(`starter desktop gate passed: ${report.frames} frames, ${report.image.colors} colors, ${report.image.cyanAssetPixels} asset pixels`);
223
- } catch (error) {
224
- console.error(error instanceof Error ? error.message : String(error));
225
- process.exitCode = 1;
29
+ if (result.error) {
30
+ console.error(result.error.message);
31
+ process.exit(1);
226
32
  }
33
+ process.exit(Number.isInteger(result.status) ? result.status : 1);
227
34
  }
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ import assert from 'node:assert/strict';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync, mkdtempSync, rmdirSync, rmSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join, resolve } from 'node:path';
7
+ import { parseArgs } from 'node:util';
8
+ import { CONTAINER_MANIFEST, resolveContainer } from './desktop-distribution.mjs';
9
+ import { verifyWindowsUninstall } from './windows-installer.mjs';
10
+
11
+ // Exercise the exact final setup: no rebuilding or substitution of its executable.
12
+ const { values } = parseArgs({ options: {
13
+ installer: { type: 'string' }, project: { type: 'string' },
14
+ scenario: { type: 'string' }, artifacts: { type: 'string' },
15
+ 'require-signed': { type: 'boolean', default: false },
16
+ } });
17
+ if (process.platform !== 'win32') throw new Error('TN_INSTALLER_VERIFY_HOST: run this command on Windows.');
18
+ for (const key of ['installer', 'project', 'scenario']) {
19
+ if (!values[key]) throw new Error(`TN_INSTALLER_VERIFY_ARGUMENT: --${key} is required.`);
20
+ }
21
+ const installer = resolve(values.installer);
22
+ const project = resolve(values.project);
23
+ const scenario = resolve(values.scenario);
24
+ const artifacts = resolve(values.artifacts ?? join(project, 'artifacts/windows-installer'));
25
+ const cli = join(project, 'node_modules/@threenative/playtest/dist/runner/cli.js');
26
+ for (const path of [installer, scenario, cli]) assert.ok(existsSync(path), `Missing verification input: ${path}`);
27
+ const temporary = mkdtempSync(join(tmpdir(), 'tn-installer-proof-'));
28
+ const directory = join(temporary, 'Installed Game');
29
+ const container = join(directory, 'game');
30
+ function run(command, args, options) {
31
+ const result = spawnSync(command, args, { stdio: 'inherit', timeout: 180_000, ...options });
32
+ if (result.error) throw result.error;
33
+ assert.equal(result.status, 0, `${command} failed with status ${result.status}`);
34
+ }
35
+ try {
36
+ // NSIS consumes the unquoted final /D= path, even when it contains spaces.
37
+ run(installer, ['/S', `/D=${directory}`], { windowsVerbatimArguments: true, argv0: `"${installer}"` });
38
+ const manifest = resolveContainer(container);
39
+ if (values['require-signed']) assert.equal(manifest.signed, true, 'Signed installer qualification requires a signed release');
40
+ assert.equal(manifest.platform, 'win32-x64');
41
+ const executable = join(container, manifest.executable);
42
+ const uninstaller = join(directory, 'Uninstall.exe');
43
+ assert.ok(existsSync(uninstaller), 'Installer did not provide an uninstaller');
44
+ if (manifest.signed) {
45
+ for (const target of [installer, executable, uninstaller]) run('signtool', ['verify', '/pa', target]);
46
+ }
47
+ run(process.execPath, [cli, scenario, '--target', 'desktop', '--executable', executable,
48
+ '--project', project, '--artifacts', artifacts, '--host-arg', '--windowed']);
49
+ run(uninstaller, ['/S', `_?=${directory}`], { windowsVerbatimArguments: true, argv0: `"${uninstaller}"` });
50
+ const remaining = verifyWindowsUninstall(directory, [...Object.keys(manifest.resources), CONTAINER_MANIFEST]);
51
+ // _?= makes uninstall synchronous; Windows keeps the running uninstaller until it exits.
52
+ rmSync(uninstaller, { force: true });
53
+ if (remaining.length) {
54
+ console.log(`TN_WINDOWS_INSTALLER_UNOWNED_RETAINED:${JSON.stringify({ directory, entries: remaining })}`);
55
+ } else {
56
+ if (existsSync(directory)) rmdirSync(directory);
57
+ rmdirSync(temporary);
58
+ }
59
+ console.log(`TN_WINDOWS_INSTALLER_PASS: ${installer}; installed gameplay and uninstall passed`);
60
+ } catch (error) {
61
+ console.error(`TN_WINDOWS_INSTALLER_PROOF_RETAINED: ${temporary}`);
62
+ throw error;
63
+ }
@@ -0,0 +1,181 @@
1
+ import { existsSync, lstatSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join, relative, win32 } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ function compilerString(value) {
6
+ // Character expansion prevents authored ${defines} and $%environment% from being evaluated.
7
+ return String(value).replaceAll('$', () => '${U+24}').replaceAll('"', '$\\"')
8
+ .replaceAll('\r', '$\\r').replaceAll('\n', '$\\n');
9
+ }
10
+
11
+ function nsis(value) {
12
+ return compilerString(String(value).replaceAll('$', () => '$$'));
13
+ }
14
+
15
+ function quote(value) {
16
+ return `"${compilerString(value)}"`;
17
+ }
18
+
19
+ function checkPaths(files) {
20
+ if (!Array.isArray(files) || files.length === 0) throw new Error('TN_WINDOWS_INSTALLER_EMPTY');
21
+ const seen = new Set();
22
+ for (const file of files) {
23
+ if (typeof file !== 'string' || win32.isAbsolute(file) ||
24
+ file.split('/').some((part) => !part || part === '.' || part === '..' ||
25
+ /[<>:"\\|?*]|[. ]$/u.test(part) || [...part].some((character) => character.charCodeAt(0) < 32) ||
26
+ /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(part))) {
27
+ throw new Error(`TN_WINDOWS_INSTALLER_PATH_INVALID: ${file}`);
28
+ }
29
+ const key = file.toLowerCase();
30
+ if (seen.has(key)) throw new Error(`TN_WINDOWS_INSTALLER_PATH_COLLISION: ${file}`);
31
+ seen.add(key);
32
+ }
33
+ for (const file of seen) {
34
+ const parts = file.split('/');
35
+ while (parts.length > 1) {
36
+ parts.pop();
37
+ if (seen.has(parts.join('/'))) throw new Error(`TN_WINDOWS_INSTALLER_PATH_COLLISION: ${file}`);
38
+ }
39
+ }
40
+ }
41
+
42
+ /** Check removal of the sealed payload; runtime-created data belongs to the player. */
43
+ export function verifyWindowsUninstall(directory, files) {
44
+ checkPaths(files);
45
+ for (const path of [...files.map((file) => join('game', file)), '.threenative-installer.ini']) {
46
+ if (lstatSync(join(directory, path), { throwIfNoEntry: false }))
47
+ throw new Error(`Uninstaller retained owned payload: ${path}`);
48
+ }
49
+ if (!existsSync(directory)) return [];
50
+ // Dirents let us inventory links without traversing their targets.
51
+ return readdirSync(directory, { recursive: true, withFileTypes: true })
52
+ .map((entry) => ({
53
+ path: relative(directory, join(entry.parentPath, entry.name)).replaceAll('\\', '/'),
54
+ type: entry.isSymbolicLink() ? 'link' : entry.isDirectory() ? 'directory' : entry.isFile() ? 'file' : 'other',
55
+ }))
56
+ // NSIS cannot remove its own running executable in synchronous _?= mode; the verifier does.
57
+ .filter((entry) => entry.path !== 'Uninstall.exe')
58
+ .sort((a, b) => a.path.localeCompare(b.path));
59
+ }
60
+
61
+ const ensureWebView = [
62
+ 'param([Parameter(Mandatory=$true)][string]$Bootstrapper)',
63
+ "$ErrorActionPreference = 'Stop'",
64
+ 'function HasRuntime {',
65
+ " foreach ($hive in @('CurrentUser', 'LocalMachine')) {",
66
+ ' $base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::$hive, [Microsoft.Win32.RegistryView]::Registry32)',
67
+ ' $key = $null',
68
+ ' try {',
69
+ " $key = $base.OpenSubKey('SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}')",
70
+ ' $version = $null',
71
+ " if ($null -ne $key -and [Version]::TryParse([string]$key.GetValue('pv'), [ref]$version) -and $version.Major -gt 0) { return $true }",
72
+ ' } finally {',
73
+ ' if ($null -ne $key) { $key.Dispose() }',
74
+ ' $base.Dispose()',
75
+ ' }',
76
+ ' }',
77
+ ' return $false',
78
+ '}',
79
+ 'if (HasRuntime) { exit 0 }',
80
+ "$process = Start-Process -FilePath $Bootstrapper -ArgumentList '/silent', '/install' -Wait -PassThru",
81
+ "if ($process.ExitCode -ne 0) { throw ('WebView2 setup failed: ' + $process.ExitCode) }",
82
+ "if (-not (HasRuntime)) { throw 'WebView2 setup returned without installing a valid runtime.' }",
83
+ ].join('\n');
84
+
85
+ /** Render only explicit owned files; the uninstaller never recursively removes an install folder. */
86
+ export function windowsInstallerScript({ root, output, manifest, files, bootstrapper, icon, signer }) {
87
+ const { id, name, version } = manifest.app;
88
+ if (!/^[a-z0-9][a-z0-9._-]+$/iu.test(id)) throw new Error('TN_WINDOWS_INSTALLER_APP_ID_INVALID');
89
+ checkPaths(files);
90
+ if (!files.includes(manifest.executable)) throw new Error('TN_WINDOWS_INSTALLER_EXECUTABLE_MISSING');
91
+ const installed = (file) => `$INSTDIR\\game${file ? `\\${nsis(file.replaceAll('/', '\\'))}` : ''}`;
92
+ const directories = new Set([installed('')]);
93
+ for (const file of files) {
94
+ const parts = file.split('/');
95
+ for (let count = parts.length - 1; count > 0; count -= 1) {
96
+ directories.add(installed(parts.slice(0, count).join('/')));
97
+ }
98
+ }
99
+ const values = {
100
+ NAME: nsis(name), ID: nsis(id), VERSION: nsis(version), OUTPUT: compilerString(output),
101
+ SHORTCUT: nsis([...String(name)].map((character) => character.charCodeAt(0) < 32 ? '_' : character)
102
+ .join('').replace(/[<>:"/\\|?*]/gu, '_').replace(/[. ]+$/u, '') || id),
103
+ EXECUTABLE: nsis(manifest.executable.replaceAll('/', '\\')),
104
+ REGISTRY: nsis(`Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${id}`),
105
+ ICON: icon ? `!define MUI_ICON ${quote(icon)}\n!define MUI_UNICON ${quote(icon)}` : '',
106
+ SIGN_UNINSTALLER: signer ? `!uninstfinalize ${quote(signer)} = 0` : '',
107
+ WEBVIEW: bootstrapper ? [
108
+ ' InitPluginsDir',
109
+ ' SetOutPath "$PLUGINSDIR"',
110
+ ` File /oname=WebView2Setup.exe ${quote(bootstrapper)}`,
111
+ ` File /oname=ensure-webview.ps1 ${quote(join(dirname(output), 'ensure-webview.ps1'))}`,
112
+ ' ExecWait \'"$SYSDIR\\WindowsPowerShell\\v1.0\\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\\ensure-webview.ps1" -Bootstrapper "$PLUGINSDIR\\WebView2Setup.exe"\' $0',
113
+ ' IfErrors webviewFailed',
114
+ ' StrCmp $0 0 webviewReady webviewFailed',
115
+ 'webviewFailed:',
116
+ ' MessageBox MB_OK|MB_ICONSTOP "Microsoft WebView2 could not be installed. Check your internet connection and run setup again." /SD IDOK',
117
+ ' SetErrorLevel 1',
118
+ ' Abort',
119
+ 'webviewReady:',
120
+ ].join('\n') : '',
121
+ INSTALL_FILES: files.map((file) => [
122
+ ` SetOutPath "${installed(file.includes('/') ? file.slice(0, file.lastIndexOf('/')) : '')}"`,
123
+ ` File "/oname=${nsis(file.split('/').at(-1))}" ${quote(join(root, file))}`,
124
+ ' IfErrors failed',
125
+ ].join('\n')).join('\n'),
126
+ DELETE_FILES: files.map((file) => ` Delete "${installed(file)}"`).join('\n'),
127
+ DELETE_DIRECTORIES: [...directories].sort((a, b) => b.length - a.length)
128
+ .map((directory) => ` RMDir "${directory}"`).join('\n'),
129
+ };
130
+ return readFileSync(new URL('./windows-installer.nsi', import.meta.url), 'utf8')
131
+ .replace(/@TN_([A-Z_]+)@/gu, (_match, key) => {
132
+ if (!Object.hasOwn(values, key)) throw new Error(`Unknown installer template field: ${key}`);
133
+ return values[key];
134
+ });
135
+ }
136
+
137
+ export function buildWindowsInstaller({ root, output, manifest, files, icon, run, signing }) {
138
+ const directory = dirname(output);
139
+ let bootstrapper;
140
+ if (manifest.ui) {
141
+ bootstrapper = join(directory, 'WebView2Setup.exe');
142
+ const script = join(directory, 'download-webview.ps1');
143
+ writeFileSync(script, [
144
+ "$ErrorActionPreference = 'Stop'",
145
+ "Invoke-WebRequest -UseBasicParsing -Uri 'https://go.microsoft.com/fwlink/p/?LinkId=2124703' -OutFile $env:TN_WEBVIEW_BOOTSTRAPPER_OUTPUT",
146
+ '$signature = Get-AuthenticodeSignature -LiteralPath $env:TN_WEBVIEW_BOOTSTRAPPER_OUTPUT',
147
+ "if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch '(^|, )CN=Microsoft Corporation(,|$)') { throw 'WebView2 bootstrapper does not have a valid Microsoft signature.' }",
148
+ ].join('\n'));
149
+ const download = run('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script], {
150
+ env: { ...process.env, TN_WEBVIEW_BOOTSTRAPPER_OUTPUT: bootstrapper },
151
+ });
152
+ if (download.error || download.status !== 0 || !existsSync(bootstrapper)) {
153
+ throw new Error(`TN_WEBVIEW2_BOOTSTRAPPER_FAILED: ${download.error?.message || download.stderr || 'download or Microsoft signature verification failed'}`);
154
+ }
155
+ writeFileSync(join(directory, 'ensure-webview.ps1'), ensureWebView);
156
+ }
157
+ let signer;
158
+ if (signing) {
159
+ const helper = join(directory, 'sign-uninstaller.mjs');
160
+ const moduleUrl = pathToFileURL(join(import.meta.dirname, 'desktop-distribution.mjs')).href;
161
+ writeFileSync(helper, `import { signDesktopArtifact } from ${JSON.stringify(moduleUrl)};\nsignDesktopArtifact({ platform: 'win32', signing: JSON.parse(process.env.TN_WINDOWS_INSTALLER_SIGNING), target: process.argv[2] });\n`);
162
+ signer = `"${process.execPath}" "${helper}" "%1"`;
163
+ }
164
+ const script = join(directory, 'installer.nsi');
165
+ writeFileSync(script, windowsInstallerScript({ root, output, manifest, files, bootstrapper, icon, signer }));
166
+ const options = {
167
+ cwd: directory,
168
+ env: { ...process.env, ...(signing ? { TN_WINDOWS_INSTALLER_SIGNING: JSON.stringify(signing) } : {}) },
169
+ };
170
+ let result = run('makensis', ['-V2', script], options);
171
+ if (result.error?.code === 'ENOENT' && process.platform === 'win32') {
172
+ const installedCompiler = [process.env['ProgramFiles(x86)'], process.env.ProgramFiles].filter(Boolean)
173
+ .map((directory) => join(directory, 'NSIS', 'makensis.exe')).find(existsSync);
174
+ if (installedCompiler) result = run(installedCompiler, ['-V2', script], options);
175
+ }
176
+ if (result.error || result.status !== 0 || !existsSync(output) ||
177
+ readFileSync(output).subarray(0, 2).toString() !== 'MZ') {
178
+ throw new Error(`TN_WINDOWS_INSTALLER_FAILED: ${result.error?.message || result.stderr || 'makensis did not produce a Windows installer'}; install NSIS and ensure makensis is on PATH.`);
179
+ }
180
+ return output;
181
+ }
@@ -0,0 +1,114 @@
1
+ Unicode true
2
+ !include "MUI2.nsh"
3
+ !include "x64.nsh"
4
+ Name "@TN_NAME@"
5
+ OutFile "@TN_OUTPUT@"
6
+ InstallDir "$LOCALAPPDATA\Programs\@TN_ID@"
7
+ InstallDirRegKey HKCU "@TN_REGISTRY@" "InstallLocation"
8
+ RequestExecutionLevel user
9
+ AllowSkipFiles off
10
+ SetCompressor /SOLID lzma
11
+ @TN_ICON@
12
+ @TN_SIGN_UNINSTALLER@
13
+ !insertmacro MUI_PAGE_WELCOME
14
+ !insertmacro MUI_PAGE_DIRECTORY
15
+ !insertmacro MUI_PAGE_INSTFILES
16
+ !insertmacro MUI_PAGE_FINISH
17
+ !insertmacro MUI_UNPAGE_CONFIRM
18
+ !insertmacro MUI_UNPAGE_INSTFILES
19
+ !insertmacro MUI_LANGUAGE "English"
20
+
21
+ Section "Install"
22
+ SetShellVarContext current
23
+ ${IfNot} ${RunningX64}
24
+ MessageBox MB_OK|MB_ICONSTOP "This game requires 64-bit Windows." /SD IDOK
25
+ SetErrorLevel 1
26
+ Abort
27
+ ${EndIf}
28
+ ReadRegStr $0 HKCU "@TN_REGISTRY@" "InstallLocation"
29
+ StrCmp $0 "" locationReady
30
+ StrCmp $0 $INSTDIR locationReady
31
+ MessageBox MB_OK|MB_ICONSTOP "This game is already installed at $0. Uninstall it before choosing a different directory." /SD IDOK
32
+ SetErrorLevel 1
33
+ Abort
34
+ locationReady:
35
+ ReadINIStr $0 "$INSTDIR\.threenative-installer.ini" "Application" "Id"
36
+ StrCmp $0 "@TN_ID@" owned
37
+ FindFirst $1 $2 "$INSTDIR\*"
38
+ checkDirectory:
39
+ StrCmp $2 "" emptyDirectory
40
+ StrCmp $2 "." nextEntry
41
+ StrCmp $2 ".." nextEntry
42
+ FindClose $1
43
+ Goto occupied
44
+ nextEntry:
45
+ FindNext $1 $2
46
+ Goto checkDirectory
47
+ emptyDirectory:
48
+ FindClose $1
49
+ Goto prerequisites
50
+ occupied:
51
+ MessageBox MB_OK|MB_ICONSTOP "Choose an empty installation directory." /SD IDOK
52
+ SetErrorLevel 1
53
+ Abort
54
+ owned:
55
+ Goto prerequisites
56
+ prerequisites:
57
+ ClearErrors
58
+ @TN_WEBVIEW@
59
+ IfFileExists "$INSTDIR\Uninstall.exe" 0 fresh
60
+ ExecWait '"$INSTDIR\Uninstall.exe" /S _?=$INSTDIR' $0
61
+ IfErrors failed
62
+ StrCmp $0 0 fresh failed
63
+ fresh:
64
+ ClearErrors
65
+ CreateDirectory "$INSTDIR"
66
+ WriteINIStr "$INSTDIR\.threenative-installer.ini" "Application" "Id" "@TN_ID@"
67
+ IfErrors failed
68
+ @TN_INSTALL_FILES@
69
+ WriteUninstaller "$INSTDIR\Uninstall.exe"
70
+ IfErrors failed
71
+ CreateDirectory "$SMPROGRAMS\@TN_ID@"
72
+ CreateShortCut "$SMPROGRAMS\@TN_ID@\@TN_SHORTCUT@.lnk" "$INSTDIR\game\@TN_EXECUTABLE@"
73
+ WriteRegStr HKCU "@TN_REGISTRY@" "DisplayName" "@TN_NAME@"
74
+ WriteRegStr HKCU "@TN_REGISTRY@" "DisplayVersion" "@TN_VERSION@"
75
+ WriteRegStr HKCU "@TN_REGISTRY@" "InstallLocation" "$INSTDIR"
76
+ WriteRegStr HKCU "@TN_REGISTRY@" "DisplayIcon" "$INSTDIR\game\@TN_EXECUTABLE@"
77
+ WriteRegStr HKCU "@TN_REGISTRY@" "UninstallString" '$\"$INSTDIR\Uninstall.exe$\"'
78
+ WriteRegStr HKCU "@TN_REGISTRY@" "QuietUninstallString" '$\"$INSTDIR\Uninstall.exe$\" /S'
79
+ WriteRegDWORD HKCU "@TN_REGISTRY@" "NoModify" 1
80
+ WriteRegDWORD HKCU "@TN_REGISTRY@" "NoRepair" 1
81
+ IfErrors failed
82
+ Goto done
83
+ failed:
84
+ MessageBox MB_OK|MB_ICONSTOP "Installation failed. Close the game, check free space, and run setup again." /SD IDOK
85
+ SetErrorLevel 1
86
+ Abort
87
+ done:
88
+ SectionEnd
89
+
90
+ Section "Uninstall"
91
+ SetShellVarContext current
92
+ ReadINIStr $0 "$INSTDIR\.threenative-installer.ini" "Application" "Id"
93
+ StrCmp $0 "@TN_ID@" remove refused
94
+ remove:
95
+ ClearErrors
96
+ @TN_DELETE_FILES@
97
+ IfErrors refused
98
+ @TN_DELETE_DIRECTORIES@
99
+ ReadRegStr $0 HKCU "@TN_REGISTRY@" "InstallLocation"
100
+ StrCmp $0 $INSTDIR 0 keepRegistration
101
+ Delete "$SMPROGRAMS\@TN_ID@\@TN_SHORTCUT@.lnk"
102
+ RMDir "$SMPROGRAMS\@TN_ID@"
103
+ DeleteRegKey HKCU "@TN_REGISTRY@"
104
+ keepRegistration:
105
+ Delete "$INSTDIR\.threenative-installer.ini"
106
+ Delete "$INSTDIR\Uninstall.exe"
107
+ RMDir "$INSTDIR"
108
+ Goto removed
109
+ refused:
110
+ MessageBox MB_OK|MB_ICONSTOP "Uninstall could not remove the game. Close it and run uninstall again." /SD IDOK
111
+ SetErrorLevel 1
112
+ Abort
113
+ removed:
114
+ SectionEnd