Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(package): Windows Node and Engram downloads for runtime staging

Marcelito73bd6c633f7b
diff --git a/scripts/package/lib.mjs b/scripts/package/lib.mjs
index 973d99a..e9bb18d 100644
--- a/scripts/package/lib.mjs
+++ b/scripts/package/lib.mjs
@@ -1,6 +1,6 @@
// Pure helpers for staging the installed app's runtime (`stage-runtime.mjs`).
import { createHash } from "node:crypto";
-import { createReadStream, lstatSync, readdirSync } from "node:fs";
+import { createReadStream, lstatSync, readdirSync, renameSync } from "node:fs";
import { join } from "node:path";
/**
@@ -11,13 +11,14 @@ export const TARGETS = Object.freeze({
"darwin-arm64": { platform: "darwin", arch: "arm64", node: "darwin-arm64", engram: "darwin_arm64" },
"linux-arm64": { platform: "linux", arch: "arm64", node: "linux-arm64", engram: "linux_arm64" },
"linux-x64": { platform: "linux", arch: "x64", node: "linux-x64", engram: "linux_amd64" },
+ "windows-x64": { platform: "win32", arch: "x64", node: "win-x64", engram: "windows_amd64" },
});
/** The Node release staged when `.nvmrc` names only a major version; it must stay on that major. */
export const PINNED_NODE_VERSION = "24.14.1";
export const USAGE =
- "usage: stage-runtime --target <darwin-arm64|linux-arm64|linux-x64> [--out <dir>] [--engram-version <x.y.z>]";
+ "usage: stage-runtime --target <darwin-arm64|linux-arm64|linux-x64|windows-x64> [--out <dir>] [--engram-version <x.y.z>]";
/** Parses the command line; throws with the usage on anything unexpected. */
export function parseArgs(argv) {
@@ -68,11 +69,75 @@ export function nodeVersion(nvmrc, pinned = PINNED_NODE_VERSION) {
}
export function nodeArchiveName(version, target) {
- return `node-v${version}-${TARGETS[target].node}.tar.gz`;
+ return `node-v${version}-${TARGETS[target].node}.${target === "windows-x64" ? "zip" : "tar.gz"}`;
}
-export function engramArchiveName(version, target) {
- return `engram_${version}_${TARGETS[target].engram}.tar.gz`;
+export function engramArchiveName(version, target, listing = "") {
+ const base = `engram_${version}_${TARGETS[target].engram}`;
+ if (target !== "windows-x64") return `${base}.tar.gz`;
+ const candidates = ["zip", "tar.gz"]
+ .map((ext) => `${base}.${ext}`)
+ .filter((name) => {
+ try {
+ checksumFor(listing, name);
+ return true;
+ } catch {
+ return false;
+ }
+ });
+ if (candidates.length !== 1)
+ throw new Error(
+ "Windows Engram needs exactly one supported archive in the release checksum list (ZIP or tar.gz).",
+ );
+ return candidates[0];
+}
+
+/** Members extracted by system tar; Windows' ZIP layout is normalized afterwards. */
+export function nodeExtractionPlan(version, target) {
+ const windows = target === "windows-x64";
+ const root = nodeArchiveName(version, target).replace(/\.(tar\.gz|zip)$/, "");
+ return {
+ flag: windows ? "-xf" : "-xzf",
+ members: (windows
+ ? ["node.exe", "node_modules/npm", "LICENSE"]
+ : ["bin/node", "lib/node_modules/npm", "LICENSE"]
+ ).map((path) => `${root}/${path}`),
+ moves: windows
+ ? [
+ ["node.exe", "bin/node.exe"],
+ ["node_modules", "lib/node_modules"],
+ ]
+ : [],
+ };
+}
+
+/** Errors Windows reports while another process (its real-time scanner) still holds files inside the folder. */
+const HELD = new Set(["EPERM", "EACCES", "EBUSY"]);
+
+function sleepSync(ms) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+
+/**
+ * Renames a folder that was just extracted. Windows' real-time scanner briefly holds the new files,
+ * and renaming their folder is refused until it lets go (observed: refused at 0 and 5 s, allowed at
+ * 20 s). Only those errors are retried, until `timeoutMs`; any other error, or the same one after
+ * the limit, is thrown as it is.
+ */
+export function renameWhenReleased(
+ from,
+ to,
+ { rename = renameSync, sleep = sleepSync, now = Date.now, timeoutMs = 60_000, intervalMs = 500 } = {},
+) {
+ const deadline = now() + timeoutMs;
+ for (;;) {
+ try {
+ return rename(from, to);
+ } catch (error) {
+ if (!HELD.has(error?.code) || now() >= deadline) throw error;
+ sleep(intervalMs);
+ }
+ }
}
/** The SHA-256 a `SHASUMS256.txt` / `checksums.txt` listing gives `fileName`; throws when it is absent. */
@@ -158,7 +223,9 @@ export function buildManifest({ target, versions, daemonCommit, sizeBytes, stage
}
/** A `bin/npm` or `bin/npx` that runs the staged Node's own npm, wherever the folder is copied. */
-export function npmWrapper(cli) {
+export function npmWrapper(cli, platform = "unix") {
+ if (platform === "win32")
+ return `@echo off\r\n"%~dp0node.exe" "%~dp0..\\lib\\node_modules\\npm\\bin\\${cli}" %*\r\n`;
return `#!/bin/sh
# Runs the npm bundled with this Node; a script rather than Node's symlink, so copies that follow links work.
self=$0
diff --git a/scripts/package/stage-runtime.mjs b/scripts/package/stage-runtime.mjs
index 60c20e2..b8e97bc 100644
--- a/scripts/package/stage-runtime.mjs
+++ b/scripts/package/stage-runtime.mjs
@@ -30,9 +30,11 @@ import {
engramReleaseVersion,
formatSize,
nodeArchiveName,
+ nodeExtractionPlan,
nodeVersion,
npmWrapper,
parseArgs,
+ renameWhenReleased,
symlinksIn,
treeSize,
verifyChecksum,
@@ -117,20 +119,20 @@ async function stageNode(out, target) {
);
const node = join(out, "node");
mkdirSync(join(node, "bin"), { recursive: true });
- const root = archiveName.replace(/\.tar\.gz$/, "");
+ const plan = nodeExtractionPlan(version, target);
// Only the binary, npm, and the license: headers, docs, and corepack are left out.
- run("tar", [
- "-xzf",
- archive,
- "-C",
- node,
- "--strip-components=1",
- `${root}/bin/node`,
- `${root}/lib/node_modules/npm`,
- `${root}/LICENSE`,
- ]);
- writeFileSync(join(node, "bin", "npm"), npmWrapper("npm-cli.js"), { mode: 0o755 });
- writeFileSync(join(node, "bin", "npx"), npmWrapper("npx-cli.js"), { mode: 0o755 });
+ run("tar", [plan.flag, archive, "-C", node, "--strip-components=1", ...plan.members]);
+ for (const [from, to] of plan.moves) {
+ mkdirSync(join(node, "lib"), { recursive: true });
+ renameWhenReleased(join(node, from), join(node, to));
+ }
+ const windows = target === "windows-x64";
+ for (const name of ["npm", "npx"])
+ writeFileSync(
+ join(node, "bin", `${name}${windows ? ".cmd" : ""}`),
+ npmWrapper(`${name}-cli.js`, windows ? "win32" : "unix"),
+ { mode: 0o755 },
+ );
return version;
}
@@ -226,18 +228,20 @@ async function stageEngram(out, target, requested) {
const { version, source } = await engramVersion(requested);
say(`Engram ${version} (${source})`);
const base = `${ENGRAM_RELEASES}/download/v${version}`;
- const archiveName = engramArchiveName(version, target);
+ const listing = await text(`${base}/checksums.txt`);
+ const archiveName = engramArchiveName(version, target, listing);
const archive = await verifiedDownload(
`${base}/${archiveName}`,
archiveName,
- checksumFor(await text(`${base}/checksums.txt`), archiveName),
+ checksumFor(listing, archiveName),
);
const extracted = mkdtempSync(join(CACHE, "engram-"));
- run("tar", ["-xzf", archive, "-C", extracted, "engram"]);
- const binary = join(extracted, "engram");
- if (!lstatSync(binary).isFile()) throw new Error(`${archiveName} has no regular engram binary.`);
- copyFileSync(binary, join(out, "bin", "engram"));
- chmodSync(join(out, "bin", "engram"), 0o755);
+ const name = target === "windows-x64" ? "engram.exe" : "engram";
+ run("tar", [archiveName.endsWith(".zip") ? "-xf" : "-xzf", archive, "-C", extracted, name]);
+ const binary = join(extracted, name);
+ if (!lstatSync(binary).isFile()) throw new Error(`${archiveName} has no regular ${name} binary.`);
+ copyFileSync(binary, join(out, "bin", name));
+ chmodSync(join(out, "bin", name), 0o755);
rmSync(extracted, { recursive: true });
return { version, source };
}
@@ -255,6 +259,9 @@ async function main() {
const options = parseArgs(process.argv.slice(2));
const { target } = options;
assertHostTarget(target);
+ // The Windows downloads are in place; its isolated dependency install is not yet.
+ if (target === "windows-x64")
+ throw new Error("Staging the Windows runtime is not available yet: its isolated install comes next.");
const out = resolve(
process.env.INIT_CWD ?? process.cwd(),
options.out ?? join(REPO, "build", "runtime", target),
diff --git a/scripts/package/test/lib.test.ts b/scripts/package/test/lib.test.ts
index 6aa6278..9e4eb00 100644
--- a/scripts/package/test/lib.test.ts
+++ b/scripts/package/test/lib.test.ts
@@ -10,8 +10,11 @@ import {
engramReleaseVersion,
hostTarget,
nodeArchiveName,
+ nodeExtractionPlan,
nodeVersion,
+ npmWrapper,
parseArgs,
+ renameWhenReleased,
symlinksIn,
treeSize,
verifyChecksum,
@@ -27,7 +30,7 @@ describe("parseArgs", () => {
it("refuses a missing or unknown target, unknown flags, and a flag without a value", () => {
expect(() => parseArgs(["--out", "/tmp/r"])).toThrow(/Missing --target/);
- expect(() => parseArgs(["--target", "windows-x64"])).toThrow(/Unknown target windows-x64/);
+ expect(() => parseArgs(["--target", "windows-arm64"])).toThrow(/Unknown target windows-arm64/);
expect(() => parseArgs(["--target", "linux-x64", "--force", "1"])).toThrow(/Unexpected argument --force/);
expect(() => parseArgs(["--target", "--out", "/tmp/r"])).toThrow(/Unexpected argument --target/);
expect(() => parseArgs(["--target", "linux-x64", "--engram-version", "latest"])).toThrow(/x\.y\.z/);
@@ -39,6 +42,9 @@ describe("host target", () => {
expect(hostTarget("darwin", "arm64")).toBe("darwin-arm64");
expect(hostTarget("linux", "x64")).toBe("linux-x64");
expect(hostTarget("darwin", "x64")).toBeUndefined();
+ expect(hostTarget("win32", "x64")).toBe("windows-x64");
+ expect(parseArgs(["--target", "windows-x64"]).target).toBe("windows-x64");
+ expect(() => assertHostTarget("windows-x64", "linux-x64")).toThrow(/Cannot stage/);
});
it("refuses to stage another platform's runtime, naming the way out", () => {
@@ -95,6 +101,105 @@ describe("checksums", () => {
});
});
+describe("Windows staging downloads", () => {
+ it("extracts the official Node ZIP and normalizes its layout without changing Unix", () => {
+ expect(nodeArchiveName("24.14.1", "windows-x64")).toBe("node-v24.14.1-win-x64.zip");
+ expect(nodeExtractionPlan("24.14.1", "windows-x64")).toEqual({
+ flag: "-xf",
+ members: [
+ "node-v24.14.1-win-x64/node.exe",
+ "node-v24.14.1-win-x64/node_modules/npm",
+ "node-v24.14.1-win-x64/LICENSE",
+ ],
+ moves: [
+ ["node.exe", "bin/node.exe"],
+ ["node_modules", "lib/node_modules"],
+ ],
+ });
+ expect(nodeExtractionPlan("24.14.1", "linux-x64")).toEqual({
+ flag: "-xzf",
+ members: [
+ "node-v24.14.1-linux-x64/bin/node",
+ "node-v24.14.1-linux-x64/lib/node_modules/npm",
+ "node-v24.14.1-linux-x64/LICENSE",
+ ],
+ moves: [],
+ });
+ });
+
+ describe("renaming a folder Windows briefly holds after extraction", () => {
+ const locked = (code: string) =>
+ Object.assign(new Error(`${code}: operation not permitted, rename`), { code });
+ // A clock the fake sleep advances, so the deadline is exercised without waiting.
+ const clock = () => {
+ const state = { now: 0, slept: [] as number[] };
+ return {
+ state,
+ now: () => state.now,
+ sleep: (ms: number) => {
+ state.slept.push(ms);
+ state.now += ms;
+ },
+ };
+ };
+
+ it("retries a lock error until the folder is released", () => {
+ const { state, now, sleep } = clock();
+ const calls: string[][] = [];
+ const rename = (from: string, to: string) => {
+ calls.push([from, to]);
+ if (calls.length <= 2) throw locked(calls.length === 1 ? "EPERM" : "EBUSY");
+ };
+ renameWhenReleased("node/node_modules", "node/lib/node_modules", { rename, sleep, now });
+ expect(calls).toEqual(Array(3).fill(["node/node_modules", "node/lib/node_modules"]));
+ expect(state.slept).toEqual([500, 500]);
+ });
+
+ it("gives up with the original error once the lock outlasts the limit", () => {
+ const { state, now, sleep } = clock();
+ let attempts = 0;
+ const rename = () => {
+ attempts += 1;
+ throw locked("EACCES");
+ };
+ expect(() => renameWhenReleased("a", "b", { rename, sleep, now, timeoutMs: 2_000 })).toThrow(
+ "EACCES: operation not permitted, rename",
+ );
+ expect(attempts).toBe(5);
+ expect(state.now).toBe(2_000);
+ });
+
+ it("does not retry other errors", () => {
+ const { state, now, sleep } = clock();
+ const rename = () => {
+ throw Object.assign(new Error("ENOENT: no such file or directory, rename"), { code: "ENOENT" });
+ };
+ expect(() => renameWhenReleased("a", "b", { rename, sleep, now })).toThrow("ENOENT");
+ expect(state.slept).toEqual([]);
+ });
+ });
+
+ it("requires checksum-list evidence for the Windows Engram archive format", () => {
+ expect(() => engramArchiveName("3.2.1", "windows-x64")).toThrow(/checksum/);
+ for (const extension of ["zip", "tar.gz"]) {
+ const name = `engram_3.2.1_windows_amd64.${extension}`;
+ expect(engramArchiveName("3.2.1", "windows-x64", `${"a".repeat(64)} ${name}\n`)).toBe(name);
+ }
+ expect(() => engramArchiveName("3.2.1", "windows-x64", "")).toThrow(/checksum/);
+ const ambiguous = ["zip", "tar.gz"]
+ .map((ext) => `${"b".repeat(64)} engram_3.2.1_windows_amd64.${ext}`)
+ .join("\n");
+ expect(() => engramArchiveName("3.2.1", "windows-x64", ambiguous)).toThrow(/exactly one/);
+ });
+
+ it("writes a Windows npm.cmd for the bundled npm and keeps the Unix script", () => {
+ expect(npmWrapper("npm-cli.js", "win32")).toContain(
+ '"%~dp0node.exe" "%~dp0..\\lib\\node_modules\\npm\\bin\\npm-cli.js" %*',
+ );
+ expect(npmWrapper("npm-cli.js")).toContain('exec "$bin/node"');
+ });
+});
+
describe("tree and manifest", () => {
it("sizes a tree without following links, and lists the links", () => {
const dir = mkdtempSync(join(tmpdir(), "stage-runtime-"));