import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import fs from "node:fs"; import http from "node:http"; import type net from "node:net"; import os from "node:os"; import path from "node:path"; import { test } from "node:test"; const CLI = new URL("../refs.mjs", import.meta.url).pathname; const INSTALLED = "console.log('installed');\n"; async function attemptUpdate(t: test.TestContext, body: string, checksum: string | null) { const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-update-")); const server = http.createServer((_, response) => response.writeHead(200, checksum ? { "x-refs-sha256": checksum } : {}).end(body)); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); t.after(() => (server.close(), fs.rmSync(home, { recursive: true, force: true }))); const origin = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}`; fs.mkdirSync(path.join(home, "bin")); fs.writeFileSync(path.join(home, "bin", "refs.mjs"), INSTALLED); fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, accessToken: "oauth", expiresAt: Date.now() / 1000 + 3600 })); const result = await new Promise<{ status: number; stderr: string }>((resolve) => execFile(process.execPath, [CLI, "update"], { env: { ...process.env, REFS_HOME: home, PATH: "/nonexistent" } }, (error, _stdout, stderr) => resolve({ status: error ? Number(error.code) : 0, stderr })), ); return { result, installed: fs.readFileSync(path.join(home, "bin", "refs.mjs"), "utf8"), leftovers: fs.readdirSync(path.join(home, "bin")) }; } test("refs update keeps the installed CLI when the download is cut off", async (t) => { const { result, installed, leftovers } = await attemptUpdate(t, "function cut(", null); assert.equal(result.status, 1); assert.equal(installed, INSTALLED); assert.deepEqual(leftovers, ["refs.mjs"]); }); test("refs update keeps the installed CLI when the checksum does not match", async (t) => { const { result, installed } = await attemptUpdate(t, "console.log('new');\n", "0".repeat(64)); assert.equal(result.status, 1); assert.equal(installed, INSTALLED); }); test("refs update replaces the CLI when the download is whole and matches its checksum", async (t) => { const fresh = "console.log('new');\n"; const { result, installed } = await attemptUpdate(t, fresh, createHash("sha256").update(fresh).digest("hex")); assert.equal(result.status, 0, result.stderr); assert.equal(installed, fresh); });