Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import * as NodeURL from "node:url";
6import { expect, it } from "vite-plus/test";
7import { cacheKey, seedPreparedCache } from "./server-compile-cache.ts";
8
9it.each(["x64", "arm64"])("skips prepared bytecode generation on Linux %s", async (arch) => {
10 const { spawnSync } = await import("node:child_process");
11 const hook = NodeURL.fileURLToPath(
12 new URL("../prepare-server-compile-cache.cjs", import.meta.url),
13 );
14 const result = spawnSync(
15 process.execPath,
16 [
17 "-e",
18 `Object.defineProperty(process, "platform", { value: "linux" });
19 Object.defineProperty(process, "arch", { value: ${JSON.stringify(arch)} });
20 require(${JSON.stringify(hook)})({ electronPlatformName: "linux", arch: ${arch === "x64" ? 1 : 3} }).catch(error => { console.error(error); process.exitCode = 1; });`,
21 ],
22 { encoding: "utf8" },
23 );
24 expect(result.status, result.stderr).toBe(0);
25 expect(result.stdout).toContain("Skipping unsupported target linux");
26});
27
28it("prepares macOS x64 cache on an ARM64 build host", async () => {
29 const { spawnSync } = await import("node:child_process");
30 const root = NodeFS.realpathSync(
31 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-rosetta-cache-")),
32 );
33 try {
34 const resources = NodePath.join(root, "Fixture.app", "Contents", "Resources");
35 const archive = NodePath.join(resources, "app.asar");
36 const dist = NodePath.join(archive, "apps/server/dist");
37 const helper = NodePath.join(archive, "apps/desktop/dist-electron/serverCompileCache.cjs");
38 NodeFS.mkdirSync(dist, { recursive: true });
39 NodeFS.mkdirSync(NodePath.dirname(helper), { recursive: true });
40 NodeFS.writeFileSync(NodePath.join(dist, "binCli-fixture.mjs"), "export const answer = 42;");
41 NodeFS.writeFileSync(
42 helper,
43 `module.exports = require(${JSON.stringify(NodeURL.fileURLToPath(new URL("./server-compile-cache.ts", import.meta.url)))});`,
44 );
45 const hook = NodeURL.fileURLToPath(
46 new URL("../prepare-server-compile-cache.cjs", import.meta.url),
47 );
48 // The fixture uses Node for generation; the hook still sees an ARM64 macOS build host.
49 const result = spawnSync(
50 process.execPath,
51 [
52 "-e",
53 `
54 const childProcess = require("node:child_process");
55 const spawn = childProcess.spawnSync;
56 childProcess.spawnSync = (executable, args, options) => {
57 require("node:assert/strict").equal(executable, ${JSON.stringify(NodePath.join(root, "Fixture.app", "Contents", "MacOS", "Fixture"))});
58 return spawn(process.execPath, args, options);
59 };
60 Object.defineProperty(process, "platform", { value: "darwin" });
61 Object.defineProperty(process, "arch", { value: "arm64" });
62 require(${JSON.stringify(hook)})({
63 appOutDir: ${JSON.stringify(root)}, electronPlatformName: "darwin", arch: 1,
64 packager: { appInfo: { productFilename: "Fixture" } }
65 }).catch(error => { console.error(error); process.exitCode = 1; });
66 `,
67 ],
68 { encoding: "utf8" },
69 );
70 expect(result.status, result.stderr).toBe(0);
71 const manifest = JSON.parse(
72 NodeFS.readFileSync(NodePath.join(resources, "server-compile-cache/manifest.json"), "utf8"),
73 );
74 expect(manifest.entries).toEqual([
75 {
76 module: "app.asar/apps/server/dist/binCli-fixture.mjs",
77 file: expect.stringMatching(/^[a-f0-9]{8}$/),
78 },
79 ]);
80 expect(
81 NodeFS.statSync(NodePath.join(resources, "server-compile-cache", manifest.entries[0].file))
82 .size,
83 ).toBeGreaterThan(0);
84 } finally {
85 NodeFS.rmSync(root, { recursive: true, force: true });
86 }
87});
88
89it("seeds relocated cache entries without allowing writes into shipped resources", () => {
90 const root = NodeFS.realpathSync(
91 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-prepared-test-")),
92 );
93 try {
94 const prepared = NodePath.join(root, "resources", "server-compile-cache");
95 const active = NodePath.join(root, "user", "different-uid-tag");
96 NodeFS.mkdirSync(prepared, { recursive: true });
97 NodeFS.mkdirSync(active, { recursive: true });
98 NodeFS.writeFileSync(NodePath.join(prepared, "12345678"), "prepared bytes");
99 const manifest = {
100 format: 1,
101 runtime: "matching",
102 entries: [{ module: "app.asar/apps/server/dist/chunk.mjs", file: "12345678" }],
103 };
104 NodeFS.writeFileSync(NodePath.join(prepared, "manifest.json"), JSON.stringify(manifest));
105 expect(seedPreparedCache(prepared, active, "wrong-engine")).toBe(false);
106 expect(seedPreparedCache(prepared, active, "matching")).toBe(true);
107 const key = cacheKey(active, NodePath.join(root, "resources", manifest.entries[0]!.module));
108 expect(NodeFS.readFileSync(NodePath.join(active, key), "utf8")).toBe("prepared bytes");
109 // Node persists by replacing the directory entry, never by overwriting the linked inode.
110 NodeFS.rmSync(NodePath.join(active, key));
111 NodeFS.writeFileSync(NodePath.join(active, key), "runtime replacement");
112 expect(NodeFS.readFileSync(NodePath.join(prepared, "12345678"), "utf8")).toBe("prepared bytes");
113 expect(seedPreparedCache(prepared, active, "matching")).toBe(true);
114 expect(NodeFS.readFileSync(NodePath.join(active, key), "utf8")).toBe("runtime replacement");
115 const missing = { module: "app.asar/apps/server/dist/missing.mjs", file: "87654321" };
116 for (const entries of [
117 [...manifest.entries, missing],
118 [missing, ...manifest.entries],
119 ]) {
120 NodeFS.writeFileSync(
121 NodePath.join(prepared, "manifest.json"),
122 JSON.stringify({ ...manifest, entries }),
123 );
124 expect(seedPreparedCache(prepared, active, "matching")).toBe(false);
125 }
126 NodeFS.writeFileSync(NodePath.join(prepared, "manifest.json"), "corrupt");
127 expect(seedPreparedCache(prepared, active, "matching")).toBe(false);
128 expect(seedPreparedCache(NodePath.join(root, "missing"), active, "matching")).toBe(false);
129 } finally {
130 NodeFS.rmSync(root, { recursive: true, force: true });
131 }
132});
133
134it.each(["app", "server"])(
135 "generates %s.asar cache with the consumer engine and falls back after damage",
136 async (archive) => {
137 const { spawnSync } = await import("node:child_process");
138 const helper = new URL("./server-compile-cache.ts", import.meta.url).href;
139 const root = NodeFS.realpathSync(
140 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cache-engine-")),
141 );
142 const run = (code: string) => {
143 const env = {
144 ...process.env,
145 NODE_DEBUG_NATIVE: "COMPILE_CACHE",
146 NODE_COMPILE_CACHE: undefined,
147 NODE_DISABLE_COMPILE_CACHE: undefined,
148 };
149 const result = spawnSync(process.execPath, ["--input-type=module", "-e", code], {
150 env,
151 encoding: "utf8",
152 });
153 expect(result.status, result.stderr).toBe(0);
154 return result.stderr;
155 };
156 try {
157 const producer = NodePath.join(root, "producer", "resources");
158 const consumer = NodePath.join(root, "relocated", "resources");
159 const relative = `${archive}.asar/apps/server/dist/binCli-fixture.mjs`;
160 NodeFS.mkdirSync(NodePath.dirname(NodePath.join(producer, relative)), { recursive: true });
161 NodeFS.writeFileSync(NodePath.join(producer, relative), "export const answer = 42;");
162 run(
163 `import {generatePreparedServerCache} from ${JSON.stringify(helper)}; await generatePreparedServerCache(${JSON.stringify(producer)});`,
164 );
165 NodeFS.cpSync(producer, consumer, { recursive: true });
166 const consume = (home: string, appImage = false) =>
167 run(
168 `if (${appImage}) process.env.APPIMAGE = "fixture"; import {enablePreparedServerCache} from ${JSON.stringify(helper)}; import {pathToFileURL} from 'node:url'; if(!enablePreparedServerCache(${JSON.stringify(NodePath.join(consumer, relative))},${JSON.stringify(NodePath.join(root, home))})) throw Error('cache disabled'); const m = await import(pathToFileURL(${JSON.stringify(NodePath.join(consumer, relative))}).href); if(m.answer!==42) throw Error('source fallback failed');`,
169 );
170 const prepared = NodePath.join(consumer, "server-compile-cache");
171 NodeFS.chmodSync(prepared, 0o555);
172 expect(consume("first-user")).toContain("was accepted");
173 expect(consume("appimage-user", true)).toContain("was accepted");
174 expect(NodeFS.readdirSync(NodePath.join(root, "appimage-user", "server"))).toEqual([]);
175 NodeFS.chmodSync(prepared, 0o755);
176 for (const file of NodeFS.readdirSync(prepared).filter((file) => file !== "manifest.json")) {
177 NodeFS.writeFileSync(NodePath.join(prepared, file), "broken");
178 }
179 expect(consume("second-user")).toContain("was not initialized");
180 for (const file of NodeFS.readdirSync(prepared).filter((file) => file !== "manifest.json")) {
181 expect(NodeFS.readFileSync(NodePath.join(prepared, file), "utf8")).toBe("broken");
182 }
183 NodeFS.rmSync(prepared, { recursive: true });
184 expect(consume("third-user")).toContain("was not initialized");
185 } finally {
186 NodeFS.rmSync(root, { recursive: true, force: true });
187 }
188 },
189);