|
| 1 | +/* oxlint-disable t3code/no-global-process-runtime -- Standalone setup must run before workspace dependencies are installed. */ |
| 2 | +// @effect-diagnostics nodeBuiltinImport:off - standalone bootstrap also runs before dependencies are installed. |
| 3 | +// @effect-diagnostics globalConsole:off globalFetch:off globalDate:off - interactive setup and endpoint verification. |
| 4 | +import * as NodeCrypto from "node:crypto"; |
| 5 | +import * as NodeFSP from "node:fs/promises"; |
| 6 | +import * as NodeOS from "node:os"; |
| 7 | +import * as NodePath from "node:path"; |
| 8 | +import * as NodeReadlinePromises from "node:readline/promises"; |
| 9 | +import { patchNativeCli } from "../src/nativeHook.ts"; |
| 10 | + |
| 11 | +const home = NodeOS.homedir(); |
| 12 | +const root = NodePath.resolve(import.meta.dirname, "../../.."); |
| 13 | +const state = NodePath.join(home, ".config/t3-task-cache"); |
| 14 | +const nonInteractive = process.argv.includes("--non-interactive"); |
| 15 | +const { endpoint: defaultEndpoint } = JSON.parse( |
| 16 | + await NodeFSP.readFile(NodePath.join(root, ".task-cache.json"), "utf8"), |
| 17 | +); |
| 18 | +let credentials: Record<string, { name: string; token: string }> = {}; |
| 19 | +try { |
| 20 | + credentials = JSON.parse( |
| 21 | + await NodeFSP.readFile(NodePath.join(state, "credentials.json"), "utf8"), |
| 22 | + ); |
| 23 | +} catch (error) { |
| 24 | + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; |
| 25 | +} |
| 26 | +const prompt = NodeReadlinePromises.createInterface({ |
| 27 | + input: process.stdin, |
| 28 | + output: process.stdout, |
| 29 | +}); |
| 30 | +let endpoint = process.env.T3_CACHE_SETUP_URL || defaultEndpoint; |
| 31 | +let name = process.env.T3_CACHE_SETUP_NAME || credentials[endpoint]?.name; |
| 32 | +let token = process.env.T3_CACHE_SETUP_TOKEN || credentials[endpoint]?.token; |
| 33 | +try { |
| 34 | + if (!nonInteractive) { |
| 35 | + endpoint = (await prompt.question(`Cache URL [${endpoint}]: `)).trim() || endpoint; |
| 36 | + name = (await prompt.question(`Developer name${name ? ` [${name}]` : ""}: `)).trim() || name; |
| 37 | + prompt.close(); |
| 38 | + if (!token || endpoint !== defaultEndpoint || name !== credentials[endpoint]?.name) { |
| 39 | + if (!process.stdin.isTTY) |
| 40 | + throw new Error("Use T3_CACHE_SETUP_TOKEN for non-interactive setup."); |
| 41 | + process.stdout.write("Credential token (hidden): "); |
| 42 | + process.stdin.setRawMode(true); |
| 43 | + process.stdin.resume(); |
| 44 | + token = await new Promise<string>((resolve, reject) => { |
| 45 | + let value = ""; |
| 46 | + const data = (chunk: Buffer) => { |
| 47 | + for (const character of chunk.toString()) { |
| 48 | + if (character === "\u0003") { |
| 49 | + cleanup(); |
| 50 | + reject(new Error("Cancelled")); |
| 51 | + return; |
| 52 | + } |
| 53 | + if (character === "\r" || character === "\n") { |
| 54 | + cleanup(); |
| 55 | + resolve(value); |
| 56 | + return; |
| 57 | + } |
| 58 | + if (character === "\u007f") value = value.slice(0, -1); |
| 59 | + else value += character; |
| 60 | + } |
| 61 | + }; |
| 62 | + const cleanup = () => { |
| 63 | + process.stdin.off("data", data); |
| 64 | + process.stdin.setRawMode(false); |
| 65 | + process.stdin.pause(); |
| 66 | + process.stdout.write("\n"); |
| 67 | + }; |
| 68 | + process.stdin.on("data", data); |
| 69 | + }); |
| 70 | + } |
| 71 | + } |
| 72 | +} finally { |
| 73 | + prompt.close(); |
| 74 | +} |
| 75 | +if (!name || !token || !/^[a-z0-9-]{1,64}$/.test(name) || token.length < 32) |
| 76 | + throw new Error("A valid developer name and credential token are required."); |
| 77 | +const url = new URL(endpoint); |
| 78 | +if ( |
| 79 | + !["http:", "https:"].includes(url.protocol) || |
| 80 | + url.username || |
| 81 | + url.password || |
| 82 | + url.search || |
| 83 | + url.hash |
| 84 | +) |
| 85 | + throw new Error("Use a cache endpoint without embedded credentials, query, or fragment."); |
| 86 | +endpoint = url.href.replace(/\/$/, ""); |
| 87 | +const response = await fetch(`${endpoint}/telemetry`, { |
| 88 | + method: "POST", |
| 89 | + headers: { |
| 90 | + Authorization: `Basic ${Buffer.from(`${name}:${token}`).toString("base64")}`, |
| 91 | + "Content-Type": "application/json", |
| 92 | + }, |
| 93 | + body: JSON.stringify({ |
| 94 | + id: NodeCrypto.randomBytes(32).toString("hex"), |
| 95 | + recordedAt: Date.now(), |
| 96 | + host: NodeOS.hostname(), |
| 97 | + platform: NodeOS.platform(), |
| 98 | + arch: NodeOS.arch(), |
| 99 | + ci: false, |
| 100 | + runId: "setup", |
| 101 | + tasks: [], |
| 102 | + }), |
| 103 | + signal: AbortSignal.timeout(10_000), |
| 104 | +}); |
| 105 | +await response.body?.cancel(); |
| 106 | +if (!response.ok) |
| 107 | + throw new Error(`Credential verification failed (${response.status}); nothing was installed.`); |
| 108 | + |
| 109 | +const candidates = [NodePath.join(root, "node_modules/vite-plus/dist/bin.js")]; |
| 110 | +for (const directory of [ |
| 111 | + process.env.VITE_PLUS_HOME, |
| 112 | + NodePath.join(home, ".vite-plus/current"), |
| 113 | + NodePath.join(home, ".local/share/vite-plus/current"), |
| 114 | +]) { |
| 115 | + if (directory) candidates.push(NodePath.join(directory, "node_modules/vite-plus/dist/bin.js")); |
| 116 | +} |
| 117 | +for (let index = 0; index < process.argv.length; index++) { |
| 118 | + if (process.argv[index] === "--entrypoint") { |
| 119 | + const entrypoint = process.argv[++index]; |
| 120 | + if (!entrypoint) throw new Error("Missing --entrypoint path"); |
| 121 | + candidates.push(entrypoint); |
| 122 | + } |
| 123 | +} |
| 124 | +const targets = new Map<string, { original: string; patched: string }>(); |
| 125 | +for (const candidate of candidates) { |
| 126 | + try { |
| 127 | + const path = await NodeFSP.realpath(candidate); |
| 128 | + const original = await NodeFSP.readFile(path, "utf8"); |
| 129 | + targets.set(path, { original, patched: patchNativeCli(original) }); |
| 130 | + } catch (error) { |
| 131 | + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; |
| 132 | + } |
| 133 | +} |
| 134 | +if (!targets.size) throw new Error("Install Vite+ before installing its telemetry hook."); |
| 135 | +const hook = await NodeFSP.readFile( |
| 136 | + NodePath.join(root, "node_modules/vite-plus/dist/run-hook.js"), |
| 137 | + "utf8", |
| 138 | +); |
| 139 | +const installed = NodePath.join(home, ".local/share/t3-task-cache"); |
| 140 | +await NodeFSP.mkdir(installed, { recursive: true }); |
| 141 | +for (const file of ["runHook.ts", "telemetry.ts"]) |
| 142 | + await NodeFSP.copyFile( |
| 143 | + NodePath.join(import.meta.dirname, "../src", file), |
| 144 | + NodePath.join(installed, file), |
| 145 | + ); |
| 146 | +const hookConfig = NodePath.join(home, ".config/vite-plus/run-hook.json"); |
| 147 | +await NodeFSP.mkdir(NodePath.dirname(hookConfig), { recursive: true }); |
| 148 | +await NodeFSP.writeFile( |
| 149 | + hookConfig, |
| 150 | + JSON.stringify({ |
| 151 | + rootMarker: ".task-cache.json", |
| 152 | + module: NodePath.join(installed, "runHook.ts"), |
| 153 | + }), |
| 154 | +); |
| 155 | +for (const [path, { original, patched }] of targets) { |
| 156 | + if (original !== patched) { |
| 157 | + await NodeFSP.writeFile(`${path}.before-task-cache`, original, { flag: "wx" }).catch( |
| 158 | + (error) => { |
| 159 | + if (error.code !== "EEXIST") throw error; |
| 160 | + }, |
| 161 | + ); |
| 162 | + await NodeFSP.writeFile(path, patched); |
| 163 | + } |
| 164 | + await NodeFSP.writeFile(NodePath.join(NodePath.dirname(path), "run-hook.js"), hook); |
| 165 | +} |
| 166 | +await NodeFSP.mkdir(state, { recursive: true, mode: 0o700 }); |
| 167 | +credentials[endpoint] = { name, token }; |
| 168 | +await NodeFSP.writeFile(NodePath.join(state, "credentials.json"), JSON.stringify(credentials), { |
| 169 | + mode: 0o600, |
| 170 | +}); |
| 171 | +await NodeFSP.chmod(NodePath.join(state, "credentials.json"), 0o600); |
| 172 | + |
| 173 | +// Remove only the PATH integration installed by the previous task-cache bootstrap. |
| 174 | +for (const file of [".profile", ".bashrc", ".bash_profile", ".zshenv", ".zshrc"]) { |
| 175 | + const path = NodePath.join(home, file); |
| 176 | + try { |
| 177 | + const original = await NodeFSP.readFile(path, "utf8"); |
| 178 | + const cleaned = original |
| 179 | + .split("\n") |
| 180 | + .filter((line) => line !== '. "$HOME/.config/t3-task-cache/env"') |
| 181 | + .join("\n"); |
| 182 | + if (cleaned !== original) await NodeFSP.writeFile(path, cleaned); |
| 183 | + } catch (error) { |
| 184 | + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; |
| 185 | + } |
| 186 | +} |
| 187 | +for (const file of ["vp", "vpr"]) { |
| 188 | + const path = NodePath.join(home, ".local/share/t3-task-cache/bin", file); |
| 189 | + try { |
| 190 | + if ((await NodeFSP.readlink(path)) === "../vp.ts") await NodeFSP.unlink(path); |
| 191 | + } catch (error) { |
| 192 | + if ( |
| 193 | + !( |
| 194 | + error instanceof Error && |
| 195 | + "code" in error && |
| 196 | + ["ENOENT", "EINVAL"].includes(String(error.code)) |
| 197 | + ) |
| 198 | + ) |
| 199 | + throw error; |
| 200 | + } |
| 201 | +} |
| 202 | +console.log( |
| 203 | + `Verified credentials and installed telemetry hooks in ${targets.size} Vite+ entrypoints. Global executables and PATH are unchanged. Open a fresh shell if the old launcher was active.`, |
| 204 | +); |
0 commit comments