e7ecd712e2
--installer unpacks a private NSIS into <out>/tools/nsis, but dpkg-deb creates only the leaf directory, so the build failed whenever --out had no tools/ yet. The parent is created first.
865 lines
32 KiB
JavaScript
865 lines
32 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* Build the optional Windows bundle for Luminary.
|
|
*
|
|
* This is deliberately *outside* the main build: it only reads the repository
|
|
* (`dist/`, `server/`, `package.json`) and writes everything into a directory
|
|
* outside the checkout. Nothing in `src/`, `server/`, `package.json`, the
|
|
* Dockerfile, the deploy script or `dist/` is modified by this file, and no npm
|
|
* script is added for it. Run it directly:
|
|
*
|
|
* node windows/build.mjs # build dist/ then the bundle
|
|
* node windows/build.mjs --skip-build # reuse the existing dist/
|
|
* node windows/build.mjs --out D:\lum # choose the output directory
|
|
*
|
|
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
|
|
* the parent of `server/`), so it is a plain folder plus a launcher:
|
|
*
|
|
* <out>/Luminary/
|
|
* node.exe official Node 24 win-x64, SHA-256 checked
|
|
* Luminary.cmd / .vbs PowerShell launcher (start, health wait, browser)
|
|
* Luminary.exe only when a Go toolchain builds it
|
|
* Stop Luminary.cmd
|
|
* Luminary.ps1 start/stop/status logic shared by both launchers
|
|
* app/ unchanged server/, dist/, production node_modules/
|
|
* README-windows.txt
|
|
* version.txt
|
|
*/
|
|
import { createHash } from 'node:crypto';
|
|
import { spawnSync } from 'node:child_process';
|
|
import {
|
|
cpSync,
|
|
existsSync,
|
|
mkdirSync,
|
|
readFileSync,
|
|
readdirSync,
|
|
renameSync,
|
|
rmSync,
|
|
statSync,
|
|
writeFileSync,
|
|
} from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import zlib from 'node:zlib';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
const ROOT = path.resolve(HERE, '..');
|
|
const LAUNCHER_FILES = path.join(HERE, 'launcher');
|
|
const RELEASES_DIR = path.join(HERE, 'releases');
|
|
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
const DEFAULT_NODE = 'v24.22.2';
|
|
|
|
const HELP = `Luminary Windows bundle
|
|
|
|
Usage: node windows/build.mjs [options]
|
|
|
|
--out <dir> output directory (default: <cache>/luminary-windows).
|
|
Must be outside this repository; the bundle is staged in
|
|
<out>/stage and zipped to <out>/Luminary-<ver>-win-x64.zip.
|
|
--skip-build reuse the existing dist/ instead of running npm run build
|
|
--node <version> bundled Node version, e.g. v24.22.2 (must be >= 24)
|
|
--launcher <kind> auto (default), ps or go. "go" needs a Go toolchain and
|
|
produces Luminary.exe; "ps" always works.
|
|
--allow-dirty skip the check that the checkout is clean outside windows/
|
|
--installer also build Luminary-<ver>-win-x64-setup.exe with NSIS
|
|
(fetches a private NSIS copy on Linux if makensis is absent)
|
|
--no-installer skip the setup exe even when makensis is installed
|
|
--publish copy the finished zip and setup exe to windows/releases
|
|
(plus a SHA256SUMS.txt) so they can be transferred to a PC
|
|
--webview2 <exe> ship a prebuilt LuminaryWindow.exe (native WebView2 window).
|
|
Build it with:
|
|
docker run --rm -v $PWD/windows/launcher:/src \\
|
|
-v /tmp/wv:/out -w /src/webview2 \\
|
|
mcr.microsoft.com/dotnet/sdk:8.0 \\
|
|
dotnet publish -c Release -o /out
|
|
--help print this text
|
|
|
|
Nothing in the repository is modified: the only writes outside the output
|
|
directory are the ones npm and nodejs.org make for their own caches.
|
|
`;
|
|
|
|
function fail(message) {
|
|
process.stderr.write(`windows: FAILED: ${message}\n`);
|
|
process.exit(1);
|
|
}
|
|
|
|
function log(step, message) {
|
|
process.stdout.write(`windows: ${step.padEnd(9)} ${message}\n`);
|
|
}
|
|
|
|
function warn(message) {
|
|
process.stderr.write(`windows: warning: ${message}\n`);
|
|
}
|
|
|
|
function defaultOutDir() {
|
|
if (process.platform === 'win32') {
|
|
const base = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
|
return path.join(base, 'Luminary', 'build');
|
|
}
|
|
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-windows');
|
|
}
|
|
|
|
function parseArgs(argv) {
|
|
const options = {
|
|
out: defaultOutDir(),
|
|
node: DEFAULT_NODE,
|
|
launcher: 'auto',
|
|
build: true,
|
|
allowDirty: false,
|
|
installer: 'auto',
|
|
publish: false,
|
|
webview2: null,
|
|
help: false,
|
|
};
|
|
const value = (index, flag) => {
|
|
const next = argv[index + 1];
|
|
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
|
|
return next;
|
|
};
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const arg = argv[i];
|
|
if (arg === '--out') {
|
|
options.out = path.resolve(value(i, arg));
|
|
i += 1;
|
|
} else if (arg === '--node') {
|
|
const version = value(i, arg);
|
|
options.node = version.startsWith('v') ? version : `v${version}`;
|
|
i += 1;
|
|
} else if (arg === '--launcher') {
|
|
options.launcher = value(i, arg);
|
|
i += 1;
|
|
} else if (arg === '--skip-build') {
|
|
options.build = false;
|
|
} else if (arg === '--installer') {
|
|
options.installer = 'yes';
|
|
} else if (arg === '--no-installer') {
|
|
options.installer = 'no';
|
|
} else if (arg === '--allow-dirty') {
|
|
options.allowDirty = true;
|
|
} else if (arg === '--publish') {
|
|
options.publish = true;
|
|
} else if (arg === '--webview2') {
|
|
options.webview2 = path.resolve(value(i, arg));
|
|
i += 1;
|
|
} else if (arg === '--help' || arg === '-h') {
|
|
options.help = true;
|
|
} else {
|
|
fail(`unknown option ${arg} (see --help)`);
|
|
}
|
|
}
|
|
if (!['auto', 'ps', 'go'].includes(options.launcher)) {
|
|
fail(`--launcher must be auto, ps or go (got ${options.launcher})`);
|
|
}
|
|
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
|
|
fail(`--node must look like v24.22.2 (got ${options.node})`);
|
|
}
|
|
return options;
|
|
}
|
|
|
|
function git(args, { trim = true } = {}) {
|
|
const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });
|
|
if (result.error || result.status !== 0) return null;
|
|
return trim ? result.stdout.trim() : result.stdout;
|
|
}
|
|
|
|
/**
|
|
* The bundle must not land in the checkout: a staged Windows Node runtime and
|
|
* node_modules would otherwise be rsynced to production by scripts/deploy.mjs
|
|
* and grow the Docker build context.
|
|
*/
|
|
function assertOutsideRepo(outDir) {
|
|
const relative = path.relative(ROOT, outDir);
|
|
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
|
|
if (inside) {
|
|
fail(
|
|
`--out resolves inside the repository (${outDir}).\n` +
|
|
'The bundle is large and would be copied by the deploy rsync; pick an\n' +
|
|
'output directory outside the checkout, or omit --out to use the cache.',
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Only this folder may be dirty. `logo.png` is a long-standing untracked asset
|
|
* in this checkout and is not part of the app, so it is tolerated.
|
|
*/
|
|
function checkRepoClean(options) {
|
|
// Not trimmed: porcelain lines start with two status columns and a space, and
|
|
// trimming the output would eat the leading space of the first line, shifting
|
|
// its path by one character.
|
|
const status = git(['status', '--porcelain'], { trim: false });
|
|
if (status === null) {
|
|
warn('git is unavailable here; skipping the worktree check');
|
|
return;
|
|
}
|
|
const unexpected = status
|
|
.split('\n')
|
|
.filter((line) => line.length > 3)
|
|
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
|
|
.filter((file) => file && !file.startsWith('windows/') && file !== 'logo.png');
|
|
if (!unexpected.length) return;
|
|
if (options.allowDirty) {
|
|
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
|
|
return;
|
|
}
|
|
fail(
|
|
`the checkout has changes outside windows/:\n ${unexpected.join('\n ')}\n` +
|
|
'Commit or stash them, or pass --allow-dirty to build anyway.',
|
|
);
|
|
}
|
|
|
|
function readPackage() {
|
|
const file = path.join(ROOT, 'package.json');
|
|
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
|
|
return JSON.parse(readFileSync(file, 'utf8'));
|
|
}
|
|
|
|
function run(command, args, cwd, extraEnv) {
|
|
log('run', [command, ...args].join(' '));
|
|
const result = spawnSync(command, args, {
|
|
cwd,
|
|
stdio: 'inherit',
|
|
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
|
|
});
|
|
if (result.error) fail(`${command} could not start: ${result.error.message}`);
|
|
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
|
|
}
|
|
|
|
function ensureUi(options) {
|
|
const dist = path.join(ROOT, 'dist', 'index.html');
|
|
if (options.build) {
|
|
log('ui', 'npm run build (typecheck + vite build, the normal artifact)');
|
|
run(NPM, ['run', 'build'], ROOT);
|
|
} else {
|
|
log('ui', 'reusing the existing dist/ (--skip-build)');
|
|
}
|
|
if (!existsSync(dist)) {
|
|
fail('dist/index.html is missing; drop --skip-build or run "npm run build" first');
|
|
}
|
|
return dist;
|
|
}
|
|
|
|
function copyServer(bundle) {
|
|
const server = path.join(bundle, 'app', 'server');
|
|
cpSync(path.join(ROOT, 'server'), server, {
|
|
recursive: true,
|
|
filter: (source) => {
|
|
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
|
|
// The developer catalog and the test files never belong in a bundle.
|
|
if (relative === 'data' || relative.startsWith('data/')) return false;
|
|
if (/\.test\.mjs$/.test(relative)) return false;
|
|
return true;
|
|
},
|
|
});
|
|
}
|
|
|
|
function copyLegal(bundle) {
|
|
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
|
|
const source = path.join(ROOT, name);
|
|
if (existsSync(source)) cpSync(source, path.join(bundle, name));
|
|
}
|
|
const licenses = path.join(ROOT, 'licenses');
|
|
if (existsSync(licenses)) cpSync(licenses, path.join(bundle, 'licenses'), { recursive: true });
|
|
}
|
|
|
|
/** Copies a text file with CRLF endings, which cmd.exe and PowerShell expect. */
|
|
function copyText(source, dest) {
|
|
const body = readFileSync(source, 'utf8').replace(/\r?\n/g, '\r\n');
|
|
writeFileSync(dest, body);
|
|
}
|
|
|
|
function installWindowsDeps(bundle) {
|
|
const appDir = path.join(bundle, 'app');
|
|
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
|
|
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
|
|
log('deps', 'npm ci --omit=dev --os=win32 --cpu=x64 (sharp win32-x64 prebuild)');
|
|
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
|
|
// prebuilt binary through optionalDependencies, and running a Windows-only
|
|
// script on the build host would fail for no reason. The ONNX skip keeps the
|
|
// postinstall from downloading the CUDA build; CPU binaries ship in the package.
|
|
run(
|
|
NPM,
|
|
[
|
|
'ci',
|
|
'--omit=dev',
|
|
'--os=win32',
|
|
'--cpu=x64',
|
|
'--no-audit',
|
|
'--no-fund',
|
|
'--ignore-scripts',
|
|
],
|
|
appDir,
|
|
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
|
|
);
|
|
// .bin shims are for a shell, not for `node server/index.mjs`; on a Linux
|
|
// build they would also be POSIX symlinks inside the zip.
|
|
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
|
|
verifySharp(appDir);
|
|
}
|
|
|
|
function verifySharp(appDir) {
|
|
const dir = path.join(appDir, 'node_modules', '@img', 'sharp-win32-x64');
|
|
if (!existsSync(dir)) {
|
|
warn('@img/sharp-win32-x64 is missing; the server will fall back to PNG proxies');
|
|
return;
|
|
}
|
|
const binaries = [];
|
|
const walk = (current) => {
|
|
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
|
const absolute = path.join(current, entry.name);
|
|
if (entry.isDirectory()) walk(absolute);
|
|
else if (/\.(node|dll)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
|
|
}
|
|
};
|
|
walk(dir);
|
|
if (!binaries.some((file) => file.endsWith('.node'))) {
|
|
warn('@img/sharp-win32-x64 has no .node binary; check the installed package');
|
|
} else {
|
|
log('deps', `sharp win32-x64 ready (${binaries.length} native files)`);
|
|
}
|
|
}
|
|
|
|
function sha256File(file) {
|
|
return createHash('sha256').update(readFileSync(file)).digest('hex');
|
|
}
|
|
|
|
async function download(url) {
|
|
const response = await fetch(url);
|
|
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
|
|
return Buffer.from(await response.arrayBuffer());
|
|
}
|
|
|
|
async function ensureNode(outDir, version) {
|
|
const major = Number(version.slice(1).split('.')[0]);
|
|
if (major < 24) {
|
|
fail(`Node ${version} is too old: node:sqlite and type stripping need 24 LTS`);
|
|
}
|
|
const cache = path.join(outDir, 'cache');
|
|
mkdirSync(cache, { recursive: true });
|
|
const exe = path.join(cache, `node-${version}-win-x64.exe`);
|
|
const sums = path.join(cache, `SHASUMS256-${version}.txt`);
|
|
const base = `https://nodejs.org/dist/${version}`;
|
|
if (!existsSync(exe)) {
|
|
log('node', `downloading ${base}/win-x64/node.exe`);
|
|
try {
|
|
writeFileSync(exe, await download(`${base}/win-x64/node.exe`));
|
|
} catch (error) {
|
|
fail(`could not download node.exe: ${error.message}`);
|
|
}
|
|
} else {
|
|
log('node', `using cached ${path.basename(exe)}`);
|
|
}
|
|
if (!existsSync(sums)) {
|
|
try {
|
|
writeFileSync(sums, (await download(`${base}/SHASUMS256.txt`)).toString('utf8'));
|
|
} catch (error) {
|
|
warn(`could not fetch SHASUMS256.txt (${error.message}); the cached node.exe is unverified`);
|
|
}
|
|
}
|
|
const hash = sha256File(exe);
|
|
if (existsSync(sums)) {
|
|
const line = readFileSync(sums, 'utf8')
|
|
.split('\n')
|
|
.map((row) => row.trim().split(/\s+/))
|
|
.find((row) => row[1] === 'win-x64/node.exe');
|
|
if (!line) fail(`SHASUMS256.txt for ${version} has no win-x64/node.exe entry`);
|
|
if (hash !== line[0]) {
|
|
rmSync(exe, { force: true });
|
|
fail(`node.exe failed its SHA-256 check (${hash} != ${line[0]}); re-run to download again`);
|
|
}
|
|
log('node', `${version} win-x64 verified (sha256 ${hash.slice(0, 12)}…)`);
|
|
} else {
|
|
warn(`using node.exe without a published checksum (sha256 ${hash})`);
|
|
}
|
|
return { exe, hash };
|
|
}
|
|
|
|
function goAvailable() {
|
|
const result = spawnSync('go', ['version'], { encoding: 'utf8' });
|
|
return !result.error && result.status === 0;
|
|
}
|
|
|
|
function chooseLauncher(requested) {
|
|
if (requested === 'ps') return 'ps';
|
|
if (requested === 'go') {
|
|
if (!goAvailable()) {
|
|
fail(
|
|
'--launcher go needs a Go toolchain (https://go.dev/dl/), or build the exe\n' +
|
|
'in the container: docker build -f windows/Dockerfile --output type=local,dest=<dir> .',
|
|
);
|
|
}
|
|
return 'go';
|
|
}
|
|
return goAvailable() ? 'go' : 'ps';
|
|
}
|
|
|
|
function installLauncher(bundle, kind) {
|
|
const files = ['Luminary.ps1', 'Stop Luminary.cmd'];
|
|
if (kind === 'go') {
|
|
const source = path.join(LAUNCHER_FILES, 'go');
|
|
log('launcher', 'go build -trimpath -H windowsgui (Luminary.exe)');
|
|
run(
|
|
'go',
|
|
[
|
|
'build',
|
|
'-trimpath',
|
|
'-ldflags',
|
|
'-s -w -H windowsgui',
|
|
'-o',
|
|
path.join(bundle, 'Luminary.exe'),
|
|
'.',
|
|
],
|
|
source,
|
|
{ GOOS: 'windows', GOARCH: 'amd64', CGO_ENABLED: '0' },
|
|
);
|
|
} else {
|
|
files.push('Luminary.cmd', 'Luminary.vbs');
|
|
}
|
|
for (const name of files) {
|
|
copyText(path.join(LAUNCHER_FILES, name), path.join(bundle, name));
|
|
}
|
|
// Binary icon for shortcuts and the installer; no CRLF pass on this one.
|
|
const icon = path.join(LAUNCHER_FILES, 'Luminary.ico');
|
|
if (existsSync(icon)) cpSync(icon, path.join(bundle, 'Luminary.ico'));
|
|
// The PowerShell launcher is always present: it implements the shared
|
|
// start/stop/status logic and "Stop Luminary.cmd" calls it in both modes.
|
|
log('launcher', kind === 'go' ? 'Luminary.exe' : 'Luminary.cmd + Luminary.vbs');
|
|
}
|
|
|
|
function writeVersion(bundle, pkg, launcher, nodeVersion, nodeHash, nodeSize) {
|
|
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
|
|
// The hash is on the node line so the launcher can quote it verbatim when
|
|
// node.exe goes missing (antivirus) and the user needs to verify a restore.
|
|
const lines = [
|
|
`Luminary ${pkg.version}`,
|
|
`commit ${commit}`,
|
|
`built ${new Date().toISOString()}`,
|
|
`node ${nodeVersion} win-x64 sha256 ${nodeHash} size ${nodeSize}`,
|
|
`launcher ${launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd / Luminary.vbs'}`,
|
|
];
|
|
const text = `${lines.join('\n')}\n`;
|
|
writeFileSync(path.join(bundle, 'version.txt'), text);
|
|
return { version: pkg.version, commit };
|
|
}
|
|
|
|
function writeBundleReadme(bundle, info) {
|
|
const start = info.launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd (or Luminary.vbs for no console window)';
|
|
const body = `Luminary ${info.version} for Windows (x64) — portable bundle
|
|
=================================================
|
|
|
|
Start: double-click ${start}
|
|
Stop: double-click "Stop Luminary.cmd"
|
|
Open: the launcher opens http://127.0.0.1:8787 (the next free port if busy)
|
|
Data: %LOCALAPPDATA%\\Luminary\\data (originals, previews, SQLite catalog)
|
|
Logs: logs\\server.out.log and logs\\server.err.log
|
|
Check: "Luminary.cmd -Verify" lists the files a complete bundle needs
|
|
Repair: "Luminary.cmd -Repair" downloads node.exe again and verifies its sha256
|
|
Sign-in: none — single-user desktop mode, no account setup
|
|
Network: none — the app and its local engine stay on this PC, so it starts
|
|
and runs with the network disconnected
|
|
Window: opens in its own window (native when bundled, else chromeless Edge/Chrome);
|
|
"Luminary.cmd -Browser" for a normal tab
|
|
|
|
Requirements
|
|
- Windows 10 or 11, 64-bit.
|
|
- A current browser (Edge, Chrome or Firefox) with WebGL2 for the Develop
|
|
module.
|
|
- Nothing else. Node.js is included as node.exe, and no .NET, Visual C++
|
|
Redistributable, admin rights or installer is needed.
|
|
- About 250 MB free where the data folder lives.
|
|
|
|
The first launch creates the data folder and the catalog. Nothing is installed
|
|
and nothing is written next to Windows or Program Files, so you can move this
|
|
folder anywhere (including a USB drive) as long as it stays writable.
|
|
|
|
If an antivirus removes node.exe, the launcher offers to download it on the next
|
|
start (or run "Luminary.cmd -Repair"). On Windows older than 10 the launcher
|
|
says so before starting instead of failing halfway.
|
|
|
|
Back up the catalog by copying the whole data folder while Luminary is stopped,
|
|
including lumenroom.db, lumenroom.db-wal, lumenroom.db-shm and secret.key.
|
|
|
|
Updating: stop Luminary, replace app\\ and node.exe from a newer bundle, then
|
|
start it again. The data folder is outside the bundle and is untouched.
|
|
|
|
Notes
|
|
- Extract the whole zip before running anything. A file opened from inside
|
|
the zip preview is copied out on its own and will not find node.exe.
|
|
- Windows 8.1 and older also need the Universal C Runtime (KB2999226);
|
|
Windows 10 and 11 already include it.
|
|
- This build is single-user: it creates one local admin on first start and
|
|
opens signed in. It is not meant for several people sharing one Windows
|
|
login with separate accounts.
|
|
- The bundle is unsigned, so SmartScreen may ask once ("More info" -> "Run anyway").
|
|
- The local engine listens on 127.0.0.1 only: it is a background process on
|
|
this PC, not a network service. Set HOST=0.0.0.0 before starting only if
|
|
client proofing galleries must be reachable from other devices on the LAN.
|
|
- RAW decoding uses the bundled libraw WebAssembly; sharp's Windows prebuilt
|
|
binary is included, so there is nothing else to install.
|
|
`;
|
|
writeFileSync(path.join(bundle, 'README-windows.txt'), body.replace(/\r?\n/g, '\r\n'));
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ zip ---- */
|
|
|
|
const CRC_TABLE = (() => {
|
|
const table = new Uint32Array(256);
|
|
for (let n = 0; n < 256; n++) {
|
|
let c = n;
|
|
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
table[n] = c >>> 0;
|
|
}
|
|
return table;
|
|
})();
|
|
|
|
function crc32(buffer) {
|
|
let c = 0xffffffff;
|
|
for (let i = 0; i < buffer.length; i++) c = CRC_TABLE[(c ^ buffer[i]) & 0xff] ^ (c >>> 8);
|
|
return (c ^ 0xffffffff) >>> 0;
|
|
}
|
|
|
|
function listFiles(dir) {
|
|
const files = [];
|
|
const walk = (current) => {
|
|
const entries = readdirSync(current, { withFileTypes: true }).sort((a, b) =>
|
|
a.name.localeCompare(b.name),
|
|
);
|
|
for (const entry of entries) {
|
|
const absolute = path.join(current, entry.name);
|
|
if (entry.isDirectory()) walk(absolute);
|
|
else if (entry.isFile()) files.push(absolute);
|
|
}
|
|
};
|
|
walk(dir);
|
|
return files;
|
|
}
|
|
|
|
/**
|
|
* Minimal ZIP writer (deflate, no zip64). Keeping it here avoids a dependency,
|
|
* and every entry carries the same fixed timestamp instead of inheriting the
|
|
* filesystem's, so two builds differ only by the files' own content.
|
|
*/
|
|
function writeZip(sourceDir, zipPath) {
|
|
// 2020-01-01 00:00:00 in MS-DOS date/time form.
|
|
const time = 0;
|
|
const date = (40 << 9) | (1 << 5) | 1;
|
|
const parts = [];
|
|
const central = [];
|
|
let offset = 0;
|
|
for (const absolute of listFiles(sourceDir)) {
|
|
const name = path.relative(sourceDir, absolute).split(path.sep).join('/');
|
|
const data = readFileSync(absolute);
|
|
const crc = crc32(data);
|
|
const deflated = zlib.deflateRawSync(data, { level: 9 });
|
|
const useDeflate = deflated.length < data.length;
|
|
const body = useDeflate ? deflated : data;
|
|
const method = useDeflate ? 8 : 0;
|
|
const nameBytes = Buffer.from(name, 'utf8');
|
|
|
|
const local = Buffer.alloc(30);
|
|
local.writeUInt32LE(0x04034b50, 0);
|
|
local.writeUInt16LE(20, 4);
|
|
local.writeUInt16LE(0x0800, 6); // UTF-8 names
|
|
local.writeUInt16LE(method, 8);
|
|
local.writeUInt16LE(time, 10);
|
|
local.writeUInt16LE(date, 12);
|
|
local.writeUInt32LE(crc, 14);
|
|
local.writeUInt32LE(body.length, 18);
|
|
local.writeUInt32LE(data.length, 22);
|
|
local.writeUInt16LE(nameBytes.length, 26);
|
|
local.writeUInt16LE(0, 28);
|
|
parts.push(local, nameBytes, body);
|
|
|
|
const entry = Buffer.alloc(46);
|
|
entry.writeUInt32LE(0x02014b50, 0);
|
|
entry.writeUInt16LE(20, 4);
|
|
entry.writeUInt16LE(20, 6);
|
|
entry.writeUInt16LE(0x0800, 8);
|
|
entry.writeUInt16LE(method, 10);
|
|
entry.writeUInt16LE(time, 12);
|
|
entry.writeUInt16LE(date, 14);
|
|
entry.writeUInt32LE(crc, 16);
|
|
entry.writeUInt32LE(body.length, 20);
|
|
entry.writeUInt32LE(data.length, 24);
|
|
entry.writeUInt16LE(nameBytes.length, 28);
|
|
entry.writeUInt16LE(0, 30);
|
|
entry.writeUInt16LE(0, 32);
|
|
entry.writeUInt16LE(0, 34);
|
|
entry.writeUInt16LE(0, 36);
|
|
entry.writeUInt32LE(0, 38);
|
|
entry.writeUInt32LE(offset, 42);
|
|
central.push(entry, nameBytes);
|
|
|
|
offset += local.length + nameBytes.length + body.length;
|
|
}
|
|
const directory = Buffer.concat(central);
|
|
const end = Buffer.alloc(22);
|
|
const count = central.length / 2;
|
|
end.writeUInt32LE(0x06054b50, 0);
|
|
end.writeUInt16LE(0, 4);
|
|
end.writeUInt16LE(0, 6);
|
|
end.writeUInt16LE(count, 8);
|
|
end.writeUInt16LE(count, 10);
|
|
end.writeUInt32LE(directory.length, 12);
|
|
end.writeUInt32LE(offset, 16);
|
|
end.writeUInt16LE(0, 20);
|
|
writeFileSync(zipPath, Buffer.concat([...parts, directory, end]));
|
|
return { files: count, bytes: statSync(zipPath).size };
|
|
}
|
|
|
|
/* ------------------------------------------------------------- installer ---- */
|
|
|
|
function dirSizeBytes(dir) {
|
|
let total = 0;
|
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
const absolute = path.join(dir, entry.name);
|
|
total += entry.isDirectory() ? dirSizeBytes(absolute) : statSync(absolute).size;
|
|
}
|
|
return total;
|
|
}
|
|
|
|
function cachedMakensis(outDir) {
|
|
const root = path.join(outDir, 'tools', 'nsis');
|
|
const bin = path.join(root, 'usr', 'bin', 'makensis');
|
|
if (!existsSync(bin)) return null;
|
|
return { bin, nsisdir: path.join(root, 'usr', 'share', 'nsis') };
|
|
}
|
|
|
|
function findMakensis(outDir) {
|
|
if (process.env.MAKENSIS) {
|
|
return { bin: process.env.MAKENSIS, nsisdir: process.env.NSISDIR || null };
|
|
}
|
|
const cached = cachedMakensis(outDir);
|
|
if (cached) return cached;
|
|
const which = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['makensis'], {
|
|
encoding: 'utf8',
|
|
});
|
|
const found = !which.error && which.status === 0 ? which.stdout.split(/\r?\n/)[0].trim() : '';
|
|
return found ? { bin: found, nsisdir: process.env.NSISDIR || null } : null;
|
|
}
|
|
|
|
/**
|
|
* NSIS is a small cross-compiler: on Linux it produces the same .exe as it
|
|
* would on Windows. Ubuntu ships it as two .debs, which unpack into the build
|
|
* cache without root, so a fresh host can build the installer unattended.
|
|
*/
|
|
async function fetchMakensis(outDir) {
|
|
if (process.platform !== 'linux' || process.arch !== 'x64') return null;
|
|
const dpkg = spawnSync('dpkg-deb', ['--version'], { stdio: 'ignore' });
|
|
if (dpkg.error || dpkg.status !== 0) return null;
|
|
const packVersion = '3.09-4ubuntu1';
|
|
const base = 'http://archive.ubuntu.com/ubuntu/pool/universe/n/nsis';
|
|
const debs = path.join(outDir, 'cache', 'nsis-debs');
|
|
const root = path.join(outDir, 'tools', 'nsis');
|
|
mkdirSync(debs, { recursive: true });
|
|
rmSync(root, { recursive: true, force: true });
|
|
// dpkg-deb -x creates the destination itself but not its parents, and a
|
|
// fresh --out has no tools/ yet.
|
|
mkdirSync(root, { recursive: true });
|
|
for (const name of [`nsis_${packVersion}_amd64.deb`, `nsis-common_${packVersion}_all.deb`]) {
|
|
const file = path.join(debs, name);
|
|
if (!existsSync(file)) {
|
|
try {
|
|
writeFileSync(file, await download(`${base}/${name}`));
|
|
} catch (error) {
|
|
warn(`could not download ${name} (${error.message})`);
|
|
return null;
|
|
}
|
|
}
|
|
const unpack = spawnSync('dpkg-deb', ['-x', file, root], { encoding: 'utf8' });
|
|
if (unpack.error || unpack.status !== 0) {
|
|
warn(`could not unpack ${name}: ${(unpack.stderr || '').trim() || 'dpkg-deb failed'}`);
|
|
return null;
|
|
}
|
|
}
|
|
return cachedMakensis(outDir);
|
|
}
|
|
|
|
async function resolveMakensis(outDir, required) {
|
|
const found = findMakensis(outDir);
|
|
if (found) return found;
|
|
if (!required) return null;
|
|
log('nsis', 'makensis not found; unpacking a private NSIS into the build cache');
|
|
const fetched = await fetchMakensis(outDir);
|
|
if (fetched) {
|
|
log('nsis', `NSIS ${packVersionOf(fetched.bin)} ready (no root install needed)`);
|
|
return fetched;
|
|
}
|
|
fail(
|
|
'NSIS is required for --installer and was not found.\n' +
|
|
' Ubuntu/Debian: sudo apt install nsis\n' +
|
|
' macOS: brew install makensis\n' +
|
|
' Windows: https://nsis.sourceforge.io\n' +
|
|
' or set MAKENSIS=/path/to/makensis',
|
|
);
|
|
}
|
|
|
|
function packVersionOf(makensis) {
|
|
const result = spawnSync(makensis, ['-VERSION'], { encoding: 'utf8' });
|
|
return !result.error && result.status === 0 ? result.stdout.trim() : 'unknown version';
|
|
}
|
|
|
|
function buildInstaller({ outDir, bundle, pkg, makensis }) {
|
|
const script = path.join(HERE, 'installer.nsi');
|
|
if (!existsSync(script)) fail(`installer script missing: ${script}`);
|
|
const outputDir = path.join(outDir, 'installer');
|
|
mkdirSync(outputDir, { recursive: true });
|
|
const setup = path.join(outputDir, `Luminary-${pkg.version}-win-x64-setup.exe`);
|
|
rmSync(setup, { force: true });
|
|
|
|
// NSIS wants four numeric fields; 0.5.1 -> 0.5.1.0
|
|
const fields = pkg.version.split('.').map((n) => Number(n) || 0);
|
|
while (fields.length < 4) fields.push(0);
|
|
const version4 = fields.slice(0, 4).join('.');
|
|
const installKb = Math.ceil(dirSizeBytes(bundle) / 1024);
|
|
|
|
log('installer', `makensis ${path.basename(script)} (${(installKb / 1024).toFixed(0)} MB payload)`);
|
|
run(
|
|
makensis.bin,
|
|
[
|
|
'-V2',
|
|
`-DAPP_VERSION=${pkg.version}`,
|
|
`-DAPP_VERSION4=${version4}`,
|
|
`-DSOURCE_DIR=${bundle}`,
|
|
`-DOUTPUT_DIR=${outputDir}`,
|
|
`-DICON=${path.join(LAUNCHER_FILES, 'Luminary.ico')}`,
|
|
`-DINSTALL_KB=${installKb}`,
|
|
script,
|
|
],
|
|
ROOT,
|
|
makensis.nsisdir ? { NSISDIR: makensis.nsisdir } : undefined,
|
|
);
|
|
if (!existsSync(setup)) fail('makensis reported success but produced no setup exe');
|
|
return { path: setup, bytes: statSync(setup).size };
|
|
}
|
|
|
|
/* ----------------------------------------------------------------- main ---- */
|
|
|
|
async function main() {
|
|
const options = parseArgs(process.argv.slice(2));
|
|
if (options.help) {
|
|
process.stdout.write(HELP);
|
|
return 0;
|
|
}
|
|
assertOutsideRepo(options.out);
|
|
const pkg = readPackage();
|
|
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
|
|
log('out', options.out);
|
|
checkRepoClean(options);
|
|
ensureUi(options);
|
|
|
|
// Settle the launcher before anything is copied: a missing Go toolchain
|
|
// should fail in a second, not after a download and an npm install.
|
|
const launcher = chooseLauncher(options.launcher);
|
|
|
|
// Build into a sibling and swap at the end, so a failed run never replaces
|
|
// the last complete bundle with a partial tree.
|
|
const stageRoot = path.join(options.out, 'stage');
|
|
const workRoot = path.join(options.out, 'stage.next');
|
|
const bundle = path.join(workRoot, 'Luminary');
|
|
rmSync(workRoot, { recursive: true, force: true });
|
|
mkdirSync(path.join(bundle, 'app'), { recursive: true });
|
|
|
|
log('stage', 'copying dist/ and server/ (unchanged layout the server expects)');
|
|
cpSync(path.join(ROOT, 'dist'), path.join(bundle, 'app', 'dist'), { recursive: true });
|
|
copyServer(bundle);
|
|
copyLegal(bundle);
|
|
installWindowsDeps(bundle);
|
|
|
|
const node = await ensureNode(options.out, options.node);
|
|
const bundledNode = path.join(bundle, 'node.exe');
|
|
cpSync(node.exe, bundledNode);
|
|
if (statSync(bundledNode).size !== statSync(node.exe).size) {
|
|
fail('node.exe was truncated while copying it into the bundle');
|
|
}
|
|
|
|
installLauncher(bundle, launcher);
|
|
if (options.webview2) {
|
|
if (!existsSync(options.webview2)) fail(`--webview2 file not found: ${options.webview2}`);
|
|
cpSync(options.webview2, path.join(bundle, 'LuminaryWindow.exe'));
|
|
log('window', `LuminaryWindow.exe (${(statSync(options.webview2).size / 1024 / 1024).toFixed(1)} MB)`);
|
|
}
|
|
|
|
const info = writeVersion(bundle, pkg, launcher, options.node, node.hash, statSync(bundledNode).size);
|
|
writeBundleReadme(bundle, { ...info, launcher });
|
|
|
|
const zipPath = path.join(options.out, `Luminary-${pkg.version}-win-x64.zip`);
|
|
rmSync(zipPath, { force: true });
|
|
log('zip', path.basename(zipPath));
|
|
const zip = writeZip(workRoot, zipPath);
|
|
|
|
rmSync(stageRoot, { recursive: true, force: true });
|
|
renameSync(workRoot, stageRoot);
|
|
|
|
const stagedBundle = path.join(stageRoot, 'Luminary');
|
|
let installer = null;
|
|
if (options.installer !== 'no') {
|
|
const makensis = await resolveMakensis(options.out, options.installer === 'yes');
|
|
if (makensis) {
|
|
installer = buildInstaller({ outDir: options.out, bundle: stagedBundle, pkg, makensis });
|
|
log('installer', `${path.basename(installer.path)} (${(installer.bytes / 1024 / 1024).toFixed(1)} MB)`);
|
|
} else {
|
|
warn('makensis is not installed; shipping the zip only (install NSIS for the setup exe)');
|
|
}
|
|
}
|
|
|
|
// The isolation contract: nothing outside windows/ may have changed.
|
|
if (!options.allowDirty) checkRepoClean(options);
|
|
|
|
// Hand-off copy. The staging and the zip stay outside the checkout; this is
|
|
// the one write into the repository, into windows/releases, for transfer to a
|
|
// Windows machine.
|
|
let published = null;
|
|
if (options.publish) {
|
|
mkdirSync(RELEASES_DIR, { recursive: true });
|
|
const artifacts = [zipPath, ...(installer ? [installer.path] : [])];
|
|
const sums = [];
|
|
for (const artifact of artifacts) {
|
|
const target = path.join(RELEASES_DIR, path.basename(artifact));
|
|
cpSync(artifact, target);
|
|
sums.push(`${sha256File(target)} ${path.basename(target)}`);
|
|
log('publish', path.relative(ROOT, target));
|
|
}
|
|
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
|
|
published = path.join(RELEASES_DIR, path.basename(zipPath));
|
|
}
|
|
|
|
process.stdout.write(
|
|
[
|
|
'',
|
|
'windows build PASSED',
|
|
` artifact ${zipPath}`,
|
|
` size ${(zip.bytes / 1024 / 1024).toFixed(1)} MB (${zip.files} files)`,
|
|
` sha256 ${sha256File(zipPath)}`,
|
|
...(installer
|
|
? [
|
|
` setup ${installer.path}`,
|
|
` setup MB ${(installer.bytes / 1024 / 1024).toFixed(1)}`,
|
|
` setup sha ${sha256File(installer.path)}`,
|
|
]
|
|
: []),
|
|
` node ${options.node} win-x64`,
|
|
` launcher ${launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd / Luminary.vbs'}`,
|
|
...(options.webview2 ? [` window LuminaryWindow.exe (native WebView2)`] : []),
|
|
` staged ${stagedBundle}`,
|
|
...(published ? [` publish ${path.relative(ROOT, published)}`] : []),
|
|
'',
|
|
published
|
|
? 'Only windows/ was written: the zip in windows/releases is ready to transfer.'
|
|
: 'The repository was not modified; only windows/ and the output directory were touched.',
|
|
'',
|
|
].join('\n'),
|
|
);
|
|
return 0;
|
|
}
|
|
|
|
main().then(
|
|
(code) => {
|
|
process.exitCode = code;
|
|
},
|
|
(error) => {
|
|
fail(error instanceof Error ? error.message : String(error));
|
|
},
|
|
);
|