Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Drives the real shell installer against a local GitHub fixture.
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as NodeChildProcess from "node:child_process";
4import * as NodeCrypto from "node:crypto";
5import * as NodeFSP from "node:fs/promises";
6import * as NodeHttp from "node:http";
7import * as NodeOS from "node:os";
8import * as NodePath from "node:path";
9import { describe, expect, it } from "vite-plus/test";
10
11const nightlies = Array.from({ length: 100 }, (_, index) => ({
12 tag_name: `v1.2.4-nightly.20261020.${200 - index}`,
13}));
14
15describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer home", () => {
16 it("installs a relative home from a directory ending in a newline", async () => {
17 const temporaryRoot = await NodeFSP.realpath(
18 await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-home-")),
19 );
20 const root = NodePath.join(temporaryRoot, "cwd\n");
21 const homeName = "-custom home\\home\n";
22 const home = NodePath.join(root, homeName);
23 const version = "1.2.3";
24 const target = NodePath.join(home, "runtime/versions", version);
25 const launcher = NodePath.join(root, "bin/t3");
26 try {
27 await NodeFSP.mkdir(target, { recursive: true });
28 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), `${version}\n`);
29 await NodeFSP.writeFile(NodePath.join(target, "t3"), "#!/bin/sh\necho 't3 v1.2.3'\n", {
30 mode: 0o755,
31 });
32 const { status, stdout, stderr } = NodeChildProcess.spawnSync(
33 "sh",
34 [NodePath.resolve(import.meta.dirname, "install.sh")],
35 {
36 cwd: root,
37 env: {
38 ...process.env,
39 HOME: root,
40 T3CODE_HOME: homeName,
41 T3CODE_VERSION: version,
42 T3CODE_INSTALL_BIN_DIR: NodePath.dirname(launcher),
43 T3CODE_RELEASE_BASE_URL: "http://127.0.0.1:1",
44 },
45 encoding: "utf8",
46 },
47 );
48 expect(status, stdout + stderr).toBe(0);
49 expect(stderr).toContain(`Installed T3 Code ${version}`);
50 expect(await NodeFSP.readlink(launcher)).toBe(NodePath.join(target, "t3"));
51 expect(
52 NodeChildProcess.execFileSync(launcher, ["--version"], {
53 cwd: NodeOS.tmpdir(),
54 encoding: "utf8",
55 }).trim(),
56 ).toBe("t3 v1.2.3");
57 } finally {
58 await NodeFSP.rm(temporaryRoot, { recursive: true, force: true });
59 }
60 });
61});
62
63// regression: #22490
64describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer channel lookup", () => {
65 it.each([
66 ["stable", "1.2.3"],
67 ["preview", "1.2.4-preview.20261019.50"],
68 ])("finds the newest %s release behind a full page of nightlies", async (channel, version) => {
69 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-index-"));
70 const target = NodePath.join(root, "home/runtime/versions", version);
71 const server = NodeHttp.createServer((request, response) => {
72 const url = new URL(request.url ?? "/", "http://fixture");
73 const body =
74 url.pathname === "/pingdotgg/t3code/releases/latest" &&
75 request.headers.accept === "application/json"
76 ? { tag_name: "v1.2.3" }
77 : url.pathname === "/repos/pingdotgg/t3code/releases"
78 ? { "1": nightlies, "2": [{ tag_name: `v${version}` }, { tag_name: "v1.2.3" }] }[
79 url.searchParams.get("page") ?? ""
80 ]
81 : undefined;
82 if (body === undefined) response.statusCode = 404;
83 // The API pretty-prints and the installer reads it line by line.
84 response.end(JSON.stringify(body ?? [], null, 2));
85 });
86 try {
87 // An existing completed install isolates release resolution from archive downloads.
88 await NodeFSP.mkdir(target, { recursive: true });
89 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), `${version}\n`);
90 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
91 const address = server.address();
92 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
93 const origin = `http://127.0.0.1:${address.port}`;
94 const source = await NodeFSP.readFile(
95 NodePath.resolve(import.meta.dirname, "install.sh"),
96 "utf8",
97 );
98 const installer = NodePath.join(root, "install.sh");
99 await NodeFSP.writeFile(installer, source.replace(/https:\/\/(api\.)?github\.com/g, origin));
100 const { code, output } = await new Promise<{ code: number | null; output: string }>(
101 (resolve, reject) => {
102 const child = NodeChildProcess.spawn("sh", [installer], {
103 env: {
104 ...process.env,
105 T3CODE_VERSION: "",
106 T3CODE_CHANNEL: channel,
107 T3CODE_HOME: NodePath.join(root, "home"),
108 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
109 // A wrong version must fail here instead of downloading a real release.
110 T3CODE_RELEASE_BASE_URL: origin,
111 },
112 stdio: ["ignore", "pipe", "pipe"],
113 });
114 let output = "";
115 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
116 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
117 child.on("error", reject);
118 child.on("close", (code) => resolve({ code, output }));
119 },
120 );
121 expect(code, output).toBe(0);
122 expect(output).toContain(`Installed T3 Code ${version}`);
123 } finally {
124 server.closeAllConnections();
125 await new Promise<void>((resolve) => server.close(() => resolve()));
126 await NodeFSP.rm(root, { recursive: true, force: true });
127 }
128 });
129});
130
131/** Runs an installer for a version that is already unpacked, so only the t3 command step runs. */
132async function installOver(input: {
133 readonly script: "install.sh" | "install.ps1";
134 readonly home: string;
135 readonly binDir: string;
136 readonly env?: NodeJS.ProcessEnv;
137 readonly cwd?: string;
138}) {
139 const target = NodePath.join(input.home, "runtime", "versions", "1.2.3");
140 await NodeFSP.mkdir(target, { recursive: true });
141 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), "1.2.3\n");
142 const installer = NodePath.resolve(import.meta.dirname, input.script);
143 const [command, args] =
144 input.script === "install.sh"
145 ? ["sh", [installer]]
146 : ["powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", installer]];
147 const result = NodeChildProcess.spawnSync(command, args, {
148 encoding: "utf8",
149 ...(input.cwd === undefined ? {} : { cwd: input.cwd }),
150 env: {
151 ...process.env,
152 T3CODE_CHANNEL: "",
153 T3CODE_VERSION: "1.2.3",
154 T3CODE_HOME: input.home,
155 T3CODE_INSTALL_BIN_DIR: input.binDir,
156 T3CODE_RELEASE_BASE_URL: "http://127.0.0.1:9",
157 ...input.env,
158 },
159 });
160 return { code: result.status, output: `${result.stdout}${result.stderr}`, target };
161}
162
163describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("install.sh t3 command", () => {
164 it("replaces only this home's own links and prints a PATH command", async () => {
165 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-link-"));
166 try {
167 const home = NodePath.join(root, "home");
168 const binDir = NodePath.join(root, "bin");
169 const link = NodePath.join(binDir, "t3");
170 await NodeFSP.mkdir(binDir, { recursive: true });
171
172 await NodeFSP.writeFile(link, "#!/bin/sh\necho mine\n");
173 const foreign = await installOver({ script: "install.sh", home, binDir });
174 expect(foreign.code).not.toBe(0);
175 expect(foreign.output).toContain(`another t3 is already at ${link}`);
176 expect(await NodeFSP.readFile(link, "utf8")).toBe("#!/bin/sh\necho mine\n");
177 // Not even from inside the versions folder, where `.` would resolve into it.
178 const fromVersions = await installOver({
179 script: "install.sh",
180 home,
181 binDir,
182 cwd: foreign.target,
183 });
184 expect(fromVersions.code).not.toBe(0);
185 expect(await NodeFSP.readFile(link, "utf8")).toBe("#!/bin/sh\necho mine\n");
186
187 // A link that only looks like it points into versions (join() would normalize the ..).
188 await NodeFSP.rm(link);
189 await NodeFSP.mkdir(NodePath.join(home, "other"), { recursive: true });
190 await NodeFSP.writeFile(NodePath.join(home, "other/t3"), "#!/bin/sh\n");
191 await NodeFSP.symlink(`${home}/runtime/versions/../../other/t3`, link);
192 const climbing = await installOver({ script: "install.sh", home, binDir });
193 expect(climbing.code).not.toBe(0);
194 expect(await NodeFSP.readlink(link)).toBe(`${home}/runtime/versions/../../other/t3`);
195
196 // Only `<version>/t3` counts, not another program inside a version.
197 await NodeFSP.rm(link);
198 await NodeFSP.symlink(NodePath.join(home, "runtime/versions/1.0.0/helper"), link);
199 const sibling = await installOver({ script: "install.sh", home, binDir });
200 expect(sibling.code).not.toBe(0);
201 expect(await NodeFSP.readlink(link)).toBe(
202 NodePath.join(home, "runtime/versions/1.0.0/helper"),
203 );
204
205 // An upgrade over an older version's link, written through a symlinked T3 home.
206 await NodeFSP.rm(link);
207 await NodeFSP.symlink(NodePath.join(home, "runtime/versions/1.0.0/t3"), link);
208 await NodeFSP.symlink(home, NodePath.join(root, "alias"));
209 const upgrade = await installOver({
210 script: "install.sh",
211 home: NodePath.join(root, "alias"),
212 binDir,
213 env: { HOME: root, SHELL: "/bin/zsh", PATH: "/usr/bin:/bin" },
214 });
215 expect(upgrade.code, upgrade.output).toBe(0);
216 expect(await NodeFSP.readlink(link)).toBe(
217 NodePath.join(root, "alias/runtime/versions/1.2.3/t3"),
218 );
219 expect(upgrade.output).toContain(
220 `printf '\\n%s\\n' 'export PATH="$PATH:$HOME/bin"' >> ~/.zshrc`,
221 );
222
223 // Containers and CI often have no SHELL; `set -u` must not stop the installer there.
224 const noShell = await installOver({
225 script: "install.sh",
226 home,
227 binDir,
228 env: { HOME: root, SHELL: undefined, PATH: "/usr/bin:/bin" },
229 });
230 expect(noShell.code, noShell.output).toBe(0);
231 expect(noShell.output).toContain(`Add ${binDir} to your PATH`);
232
233 // Its folder on PATH with a trailing slash is still this t3, not another one.
234 const slashed = await installOver({
235 script: "install.sh",
236 home,
237 binDir,
238 env: { HOME: root, PATH: `${binDir}/:/usr/bin:/bin` },
239 });
240 expect(slashed.code, slashed.output).toBe(0);
241 expect(slashed.output).toContain("Run t3 to use T3 Code here");
242
243 // A relative folder is made absolute, so the PATH command never follows the working directory.
244 const relative = await installOver({
245 script: "install.sh",
246 home,
247 binDir: "bin",
248 cwd: root,
249 env: { HOME: root, SHELL: "/bin/zsh", PATH: "/usr/bin:/bin" },
250 });
251 expect(relative.code, relative.output).toBe(0);
252 expect(relative.output).toContain(`'export PATH="$PATH:$HOME/bin"'`);
253
254 await NodeFSP.rm(link);
255 await NodeFSP.symlink(NodePath.join(home, "bin/t3"), link);
256 const overDesktop = await installOver({
257 script: "install.sh",
258 home: `${home}//`,
259 binDir: `${binDir}/`,
260 });
261 expect(overDesktop.code, overDesktop.output).toBe(0);
262 expect(await NodeFSP.readlink(link)).toBe(NodePath.join(home, "runtime/versions/1.2.3/t3"));
263 } finally {
264 await NodeFSP.rm(root, { recursive: true, force: true });
265 }
266 });
267});
268
269describe.skipIf(HostProcess.Platform.defaultValue() !== "win32")("install.ps1 t3 command", () => {
270 it("replaces only its own t3.cmd, also in non-ASCII and bracketed paths", async () => {
271 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-ps1-"));
272 try {
273 // Windows PowerShell 5.1 reads files as ANSI by default and expands wildcards in paths.
274 const home = NodePath.join(root, "José", ".t3");
275 const binDir = NodePath.join(root, "bin[t3]");
276 const shim = NodePath.join(binDir, "t3.cmd");
277 await NodeFSP.mkdir(binDir, { recursive: true });
278
279 const desktopShim = '@echo off\r\n"C:\\Program Files\\T3 Code\\T3 Code.exe" "x" %*\r\n';
280 await NodeFSP.writeFile(shim, desktopShim);
281 const foreign = await installOver({ script: "install.ps1", home, binDir });
282 expect(foreign.code).not.toBe(0);
283 expect(foreign.output).toContain("another t3 is already at");
284 expect(await NodeFSP.readFile(shim, "utf8")).toBe(desktopShim);
285
286 // A hand-edited wrapper may set its own environment; replacing it would drop that.
287 const edited = `@echo off\r\nset "T3CODE_HOME=D:\\other"\r\n"${NodePath.join(home, "runtime", "versions", "1.0.0", "t3.exe")}" %*`;
288 await NodeFSP.writeFile(shim, edited, "utf8");
289 const wrapper = await installOver({ script: "install.ps1", home, binDir });
290 expect(wrapper.code).not.toBe(0);
291 expect(await NodeFSP.readFile(shim, "utf8")).toBe(edited);
292
293 const climbing = `@echo off\r\n"${NodePath.join(home, "runtime", "versions")}\\..\\other\\t3.exe" %*`;
294 await NodeFSP.writeFile(shim, climbing, "utf8");
295 const outside = await installOver({ script: "install.ps1", home, binDir });
296 expect(outside.code).not.toBe(0);
297 expect(await NodeFSP.readFile(shim, "utf8")).toBe(climbing);
298
299 const older = NodePath.join(home, "runtime", "versions", "1.0.0", "t3.exe");
300 await NodeFSP.writeFile(shim, `@echo off\r\n"${older}" %*`, "utf8");
301 const upgrade = await installOver({ script: "install.ps1", home, binDir });
302 expect(upgrade.code, upgrade.output).toBe(0);
303 expect(await NodeFSP.readFile(shim, "utf8")).toContain(
304 NodePath.join(upgrade.target, "t3.exe"),
305 );
306
307 const again = await installOver({ script: "install.ps1", home, binDir });
308 expect(again.code, again.output).toBe(0);
309
310 // Another t3 first on PATH still runs, so the installer names this one in full.
311 const otherBin = NodePath.join(root, "other");
312 await NodeFSP.mkdir(otherBin);
313 await NodeFSP.writeFile(NodePath.join(otherBin, "t3.cmd"), "@echo off\r\n");
314 // Windows spells it Path; a second PATH key would be ambiguous.
315 const pathKey =
316 Object.keys(process.env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
317 const shadowed = await installOver({
318 script: "install.ps1",
319 home,
320 binDir,
321 env: { [pathKey]: `${otherBin};${process.env[pathKey] ?? ""}` },
322 });
323 expect(shadowed.code, shadowed.output).toBe(0);
324 expect(shadowed.output).toContain(
325 `Another t3 at ${NodePath.join(otherBin, "t3.cmd")} runs first`,
326 );
327
328 // Its own folder on PATH with a trailing separator is already on PATH.
329 const slashed = await installOver({
330 script: "install.ps1",
331 home,
332 binDir,
333 env: { [pathKey]: `${binDir}\\;${process.env[pathKey] ?? ""}` },
334 });
335 expect(slashed.code, slashed.output).toBe(0);
336 expect(slashed.output).toContain("to use T3 Code here");
337 // The same when the install folder itself is given with a trailing separator.
338 const bothSlashed = await installOver({
339 script: "install.ps1",
340 home,
341 binDir: `${binDir}\\`,
342 env: { [pathKey]: `${binDir}\\;${process.env[pathKey] ?? ""}` },
343 });
344 expect(bothSlashed.code, bothSlashed.output).toBe(0);
345 expect(bothSlashed.output).toContain("to use T3 Code here");
346 } finally {
347 await NodeFSP.rm(root, { recursive: true, force: true });
348 }
349 });
350});
351
352describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer checksum", () => {
353 it.each(
354 ["home\\data", "home\ndata"].flatMap((homeName) =>
355 [true, false].map((validChecksum) => ({ homeName, validChecksum })),
356 ),
357 )(
358 "verifies home $homeName with valid checksum $validChecksum",
359 async ({ homeName, validChecksum }) => {
360 const availableTools = ["sha256sum", "shasum"].filter(
361 (tool) =>
362 NodeChildProcess.spawnSync("sh", ["-c", 'command -v "$1"', "sh", tool]).status === 0,
363 );
364 expect(availableTools.length).toBeGreaterThan(0);
365 for (const checksumTool of availableTools) {
366 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-checksum-"));
367 const home = NodePath.join(root, homeName);
368 const version = "1.2.3";
369 const stem = `t3-${version}-linux-${HostProcess.Architecture.defaultValue()}`;
370 const archiveName = `${stem}.tar.gz`;
371 const server = NodeHttp.createServer();
372 try {
373 const tools = NodePath.join(root, "tools");
374 await NodeFSP.mkdir(tools);
375 for (const command of [
376 "sh",
377 "uname",
378 "tar",
379 "gzip",
380 "cut",
381 "curl",
382 "grep",
383 "mkdir",
384 "mktemp",
385 "rm",
386 "mv",
387 "ln",
388 checksumTool,
389 ]) {
390 const executable = NodeChildProcess.execFileSync(
391 "sh",
392 ["-c", 'command -v "$1"', "sh", command],
393 { encoding: "utf8" },
394 ).trim();
395 await NodeFSP.symlink(executable, NodePath.join(tools, command));
396 }
397 await NodeFSP.mkdir(NodePath.join(root, stem));
398 await NodeFSP.writeFile(
399 NodePath.join(root, stem, "t3"),
400 "#!/bin/sh\necho 't3 v1.2.3'\n",
401 { mode: 0o755 },
402 );
403 const archivePath = NodePath.join(root, archiveName);
404 NodeChildProcess.execFileSync("tar", ["-czf", archivePath, "-C", root, stem]);
405 const archive = await NodeFSP.readFile(archivePath);
406 const digest = NodeCrypto.createHash("sha256").update(archive).digest("hex");
407 server.on("request", (request, response) => {
408 response.end(
409 request.url?.endsWith("/SHA256SUMS")
410 ? `${validChecksum ? digest : "0".repeat(64)} ${archiveName}\n`
411 : archive,
412 );
413 });
414 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
415 const address = server.address();
416 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
417 const { code, output } = await new Promise<{ code: number | null; output: string }>(
418 (resolve, reject) => {
419 const child = NodeChildProcess.spawn(
420 "sh",
421 [NodePath.resolve(import.meta.dirname, "install.sh")],
422 {
423 env: {
424 ...process.env,
425 PATH: tools,
426 T3CODE_VERSION: version,
427 T3CODE_HOME: home,
428 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
429 T3CODE_RELEASE_BASE_URL: `http://127.0.0.1:${address.port}`,
430 },
431 stdio: ["ignore", "pipe", "pipe"],
432 },
433 );
434 let output = "";
435 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
436 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
437 child.on("error", reject);
438 child.on("close", (code) => resolve({ code, output }));
439 },
440 );
441 const versions = NodePath.join(home, "runtime/versions");
442 if (validChecksum) {
443 expect(code, `${checksumTool}: ${output}`).toBe(0);
444 expect(
445 await NodeFSP.readFile(NodePath.join(versions, version, ".install-complete"), "utf8"),
446 ).toBe("1.2.3\n");
447 expect(
448 NodeChildProcess.execFileSync(NodePath.join(root, "bin/t3"), ["--version"], {
449 encoding: "utf8",
450 }).trim(),
451 ).toBe("t3 v1.2.3");
452 } else {
453 expect(code).not.toBe(0);
454 expect(output).toContain("checksum mismatch");
455 expect(output).not.toContain("Installed T3 Code");
456 expect(await NodeFSP.readdir(versions)).toEqual([]);
457 }
458 } finally {
459 server.closeAllConnections();
460 await new Promise<void>((resolve) => server.close(() => resolve()));
461 await NodeFSP.rm(root, { recursive: true, force: true });
462 }
463 }
464 },
465 );
466});