import { execFileSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; import { homedir } from 'node:os'; import { basename, isAbsolute, join, resolve, sep } from 'node:path'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { PRODUCT_DECLARATION_KEY, type ProductIdentity, workbenchProductId, } from './product-locator'; /** Where a project declares its workbench, relative to the project root. */ export const WORKBENCH_LOCATOR_PATH = '.volter/workbench.json'; /** The release's own record, written beside the tarball by * `scripts/workbench/build-release.mjs`. */ const RELEASE_RECORD = 'BUILD.json'; /** The REH launcher inside a fork checkout — the marker that says "sources". */ const SOURCES_LAUNCHER = join('scripts', 'code-server.sh'); /** What `scripts/workbench/overlay.mjs` leaves in a checkout it has overlaid. */ const OVERLAY_RECORD = '.volter-overlay.json'; /** What the session reports about the workbench it is running. */ export interface WorkbenchIdentity { readonly kind: 'release' | 'sources'; /** The directory named by the declaration or the flag, resolved absolute. */ readonly dir: string; /** The Code-OSS fork commit these bytes are. */ readonly commit: string; readonly product: string; } /** Everything the session needs to run it, identity included. */ export interface ResolvedWorkbench extends WorkbenchIdentity { /** The executable to spawn, already known to exist. */ readonly serverBin: string; /** Its working directory — the package root, or the checkout. */ readonly cwd: string; } /** The exact file to write, quoted in every refusal that wants one. */ export function workbenchDeclarationExample(projectRoot: string): string { return ( `${join(projectRoot, WORKBENCH_LOCATOR_PATH)}:\n` + ' { "workbench": "" }' ); } /** * The workbench directory this project declares, or `null` when it declares * none. Throws when the file exists and is not exactly `{ "workbench": }` * — unrecognized keys are refused. */ export function readWorkbenchDeclaration(projectRoot: string): string | null { const file = join(projectRoot, WORKBENCH_LOCATOR_PATH); if (!existsSync(file)) return null; let parsed: unknown; try { parsed = JSON.parse(readFileSync(file, 'utf8')); } catch (error) { throw new Error( `${file} is not valid JSON (${error instanceof Error ? error.message : String(error)}). It says ` + `which Code-OSS workbench this project opens in, and nothing else:\n${workbenchDeclarationExample(projectRoot)}`, ); } if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { throw new Error( `${file} must be a JSON object naming one workbench:\n${workbenchDeclarationExample(projectRoot)}`, ); } const record = parsed as Record; const extra = Object.keys(record).filter((key) => key !== 'workbench'); if (extra.length > 0) { throw new Error( `${file} carries ${extra.map((key) => `"${key}"`).join(', ')}, which this document has no meaning for. ` + `It names ONE key:\n${workbenchDeclarationExample(projectRoot)}`, ); } const declared = record['workbench']; if (typeof declared !== 'string' || declared.trim() === '') { throw new Error( `${file} names no workbench directory:\n${workbenchDeclarationExample(projectRoot)}`, ); } return isAbsolute(declared) ? resolve(declared) : resolve(projectRoot, declared); } /** * WRITE THE DECLARATION — the one record of which workbench THIS machine opens * this project in. Written by ` create --workbench `, and written * by the fetch below, so the two paths cannot leave two different shapes of * file behind. */ export function writeWorkbenchDeclaration(projectRoot: string, workbenchDir: string): void { mkdirSync(join(projectRoot, '.volter'), { recursive: true }); writeFileSync( join(projectRoot, WORKBENCH_LOCATOR_PATH), `${JSON.stringify({ workbench: resolve(workbenchDir) }, null, 2)}\n`, ); } /** * The url the workbench answers on — the ONE url a person opens under the * frame. Spelled here so the CLI's launch line and the session's tab bijection * cannot disagree about it. * * `?project=` is the one boot param the Volter editor carries; the session's * one-origin proxy redirects it to the workbench's own `?folder=`, and * `frame-proxy.ts` says why it must be a redirect. */ export function workbenchUrl(proxyPort: number, projectRoot: string): string { const id = basename(resolve(projectRoot)); // Cookies ignore ports. A shared loopback hostname can inherit another // local VS Code app's secret-storage cookie and select its absent key server. // Give each project a stable host; browsers resolve *.localhost to loopback. return `http://editor-${projectKey(projectRoot)}.localhost:${proxyPort}/?project=${encodeURIComponent(id)}`; } /** A project's stable key on this machine: its page's host, and its workbench extensions folder. */ export function projectKey(projectRoot: string): string { return createHash('sha256').update(resolve(projectRoot)).digest('hex').slice(0, 16); } /** This machine in the build script's own platform vocabulary. */ function machinePlatform(): string { return `${process.platform}-${process.arch}`; } /** The workbench at `dir`, refused where it is built for another product than `expectedProduct`; none named (a session * whose project's product cannot be resolved, which `/__editor/served-modules` explains) is not judged. */ export function resolveWorkbench(dir: string, expectedProduct?: string): ResolvedWorkbench { const root = resolve(dir); const resolved = existsSync(join(root, RELEASE_RECORD)) ? resolveRelease(root) : existsSync(join(root, SOURCES_LAUNCHER)) ? resolveSources(root) : null; if (resolved === null) { throw new Error( `${root} is neither a Code-OSS release nor a fork checkout: it carries no ${RELEASE_RECORD} (the record ` + `scripts/workbench/build-release.mjs writes beside its tarball) and no ${SOURCES_LAUNCHER}. Name the ` + 'directory the release was extracted into, or the fork checkout itself.', ); } if (expectedProduct !== undefined && resolved.product !== expectedProduct) { throw new Error( `${root} is a ${resolved.product} workbench and this project opens in ${expectedProduct}. A workbench is ` + "built for ONE product — the editor kit and that product's workbench half are overlaid on the fork " + "together — so its title, its look and its commands are the other product's, whatever this session " + `serves into it. ${ resolved.kind === 'sources' ? `Re-overlay the checkout:\n node scripts/workbench/dev.mjs --checkout ${root} --product ${expectedProduct}` : `Name a ${expectedProduct} release in .volter/workbench.json, or cut one:\n node scripts/workbench/build-release.mjs --product ${expectedProduct} --platform ${machinePlatform()} --checkout ` }`, ); } return resolved; } /** * The five fields the launch depends on — `target`, `platform`, `commit`, * `serverBin` and `product`. The rest of `BUILD.json` is the build's own * provenance (sizes, sha256, the node it was built with) and is read by a * person, not by this. */ function resolveRelease(dir: string): ResolvedWorkbench { const record = join(dir, RELEASE_RECORD); const cut = `node scripts/workbench/build-release.mjs --product --platform ${machinePlatform()} --checkout --out ${dir}`; let parsed: Record; try { parsed = JSON.parse(readFileSync(record, 'utf8')) as Record; } catch (error) { throw new Error(`${record} could not be read: ${String(error)}`); } const needed = ['target', 'platform', 'commit', 'serverBin', 'product'] as const; const missing = needed.filter((key) => typeof parsed[key] !== 'string'); if (missing.length > 0) { throw new Error( `${record} is not a release record this understands: ${missing.join(', ')} ` + `${missing.length === 1 ? 'is' : 'are'} missing or not a string. A release names ${needed.join(', ')} — ` + 'the five fields scripts/workbench/build-release.mjs writes and this one spawns from. ' + 'The record must name the product compiled into the workbench. Re-cut it:\n ' + cut, ); } const target = parsed['target'] as string; const platform = parsed['platform'] as string; const commit = parsed['commit'] as string; const serverBin = parsed['serverBin'] as string; const product = parsed['product'] as string; const machine = machinePlatform(); if (platform !== machine) { throw new Error( `${dir} was built for ${platform} and this machine is ${machine}. A Code-OSS server package carries its ` + "own platform's node binary and native modules, so it cannot run here — and this never falls back to a " + `source checkout, because a boot that silently was not the release measures nothing. Cut the ${machine} ` + `release:\n node scripts/workbench/build-release.mjs --product ${product} --platform ${machine} --checkout `, ); } const packageRoot = join(dir, target); const serverBinPath = join(packageRoot, serverBin); if (!existsSync(serverBinPath)) { const tarball = typeof parsed['tarball'] === 'string' ? (parsed['tarball'] as string) : `${target}-.tar.gz`; throw new Error( `${dir} records ${target}, but ${serverBinPath} is not there — the tarball has not been extracted beside ` + `${RELEASE_RECORD}. Run:\n tar -xzf ${join(dir, tarball)} -C ${dir}`, ); } return { kind: 'release', dir, commit, product, serverBin: serverBinPath, cwd: packageRoot }; } /** * A fork checkout. The commit is the working tree's, read with git: a checkout * has no file that states it, and a stale one would name bytes nobody is * running. The PRODUCT is the overlay's own record — a checkout with none has * no volter tier in it at all, and that is refused here rather than left to * surface as a workbench where `Volter: Open Workspace` does not exist. */ function resolveSources(dir: string): ResolvedWorkbench { let commit: string; try { commit = execFileSync('git', ['rev-parse', 'HEAD'], { windowsHide: true, cwd: dir, encoding: 'utf8' }).trim(); } catch (error) { throw new Error( `${dir} carries ${SOURCES_LAUNCHER}, so it reads as a Code-OSS fork checkout, but \`git rev-parse HEAD\` ` + `there failed (${error instanceof Error ? error.message : String(error)}). A checkout's commit is the ` + 'only record of which fork this workbench is.', ); } const marker = join(dir, OVERLAY_RECORD); if (!existsSync(marker)) { throw new Error( `${dir} is a Code-OSS checkout with no volter overlay: ${OVERLAY_RECORD} is not there, so nothing of the ` + 'editor is compiled into it and the workbench would come up as plain Code-OSS. Overlay and compile it:\n' + ` node scripts/workbench/dev.mjs --checkout ${dir} --product `, ); } let product: unknown; try { product = (JSON.parse(readFileSync(marker, 'utf8')) as Record)['product']; } catch (error) { throw new Error(`${marker} could not be read: ${String(error)}`); } if (typeof product !== 'string' || product === '') { throw new Error( `${marker} names no product. It is written by scripts/workbench/overlay.mjs and says which product's ` + 'workbench half is in this checkout; re-run the overlay rather than editing it.', ); } return { kind: 'sources', dir, commit, product, serverBin: join(dir, SOURCES_LAUNCHER), cwd: dir, }; } // --------------------------------------------------------------------------- // THE PRODUCT'S OWN WORKBENCH — the third resolution step, and the only one // that needs nothing on the machine but the product. // --------------------------------------------------------------------------- /** The fork's own repository, where a cut release is published. Private today; * the fetch below is the same call either way, with a token or without one. */ const RELEASE_REPO = 'volter-ai/code-oss'; /** * WHERE FETCHED BYTES LIVE — one directory per release tag, per user (`~/.volter/workbenches`). * * Keyed by the TAG and nothing else, because that is what makes it a cache and * not a decision: two projects on the same release share one directory, * a second `create` consults no network, and a release is immutable, so a tag * that is here is the tag that was published. Which workbench a project opens * in is still recorded in the PROJECT (`.volter/workbench.json`, written the * moment this resolves) — nothing ever searches this directory. */ export const WORKBENCH_CACHE_ROOT = join(homedir(), '.volter', 'workbenches'); /** Where the fetch talks. `log` is a line; `progress` is ONE line rewritten in * place (216 MB is a wait, and a wait with no number is a hang). */ export interface WorkbenchFetchIO { readonly log: (line: string) => void; readonly progress?: (line: string) => void; } /** * THE WORKBENCH THIS PROJECT OPENS IN, resolved in three steps: * * 1. `--workbench ` — one launch, writes nothing. * 2. `/.volter/workbench.json` — this machine's record for this project. * 3. the PRODUCT's declared release — fetched once, then written into (2). * * Step 3 is what makes the product's `create` open something * on a machine that has never built anything, and it is why the CLI resolves * the product BEFORE the workbench. */ export async function resolveWorkbenchForProject(options: { projectRoot: string; product: ProductIdentity; /** `--workbench `, when the person passed one. */ override?: string | undefined; io: WorkbenchFetchIO; }): Promise { const { projectRoot, product, override, io } = options; const productId = workbenchProductId(product.name); if (override !== undefined) return resolveWorkbench(resolve(override), productId); // A declaration under the cache root is the one the fetch below wrote: the // product's pin decides it, so a pin that moved, or a cache that was // cleared, fetches again instead of opening a stale release or refusing a // directory that is gone. const declared = readWorkbenchDeclaration(projectRoot); const fetchRecord = declared !== null && product.workbench !== null && declared.startsWith(`${WORKBENCH_CACHE_ROOT}${sep}`); if (declared !== null && !fetchRecord) return resolveWorkbench(declared, productId); if (product.workbench === null) throw new Error( `${product.name} is a private source product with no released workbench. ` + `Pass --workbench or declare it in ${WORKBENCH_LOCATOR_PATH}. ` + 'Public distribution requires a pinned workbench release and checksum.', ); const tag = product.workbench.release; const dir = join(WORKBENCH_CACHE_ROOT, tag); // A CACHED TAG IS NEVER RE-FETCHED. The marker is the release's own record, // so a directory that lost its extraction reads as absent and is fetched // again rather than resolving into a refusal a person cannot act on. const fetched = !existsSync(join(dir, RELEASE_RECORD)); if (fetched) await fetchDeclaredRelease(product, tag, dir, io); else io.log(`Workbench ${tag} is already installed (${dir}).`); const workbench = resolveWorkbench(dir, productId); writeWorkbenchDeclaration(projectRoot, dir); io.log(`Declared in ${WORKBENCH_LOCATOR_PATH}: ${dir}`); return workbench; } /** A GitHub release asset, as much of one as this reads. */ interface ReleaseAsset { readonly id: number; readonly name: string; readonly size: number; } /** * The token, from the two doors a person has: the environment, or the `gh` they * are already logged into. Deliberately not a file of ours, not a setting and * not a prompt — a credential this reads is one somebody else's tool already * owns. */ function githubToken(): string | null { const fromEnv = process.env['GITHUB_TOKEN']; if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return fromEnv.trim(); try { const out = execFileSync('gh', ['auth', 'token'], { windowsHide: true, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], }).trim(); return out === '' ? null : out; } catch { return null; } } function apiHeaders(token: string | null): Record { return { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'volter-workbench-locator', ...(token === null ? {} : { Authorization: `Bearer ${token}` }), }; } function megabytes(bytes: number): string { return (bytes / 1024 ** 2).toFixed(0); } /** The line a refusal prints when the release is not reachable — both doors, * named, because "no credentials" with no names is the same as no message. */ function tokenDoors(): string { return ( ' GITHUB_TOKEN= — in this shell, or\n' + ' gh auth login — so `gh auth token` answers' ); } /** The CLI prints only Error.message. Keep the public request/stage and Node's * nested transport code there, without printing auth headers or signed redirects. * The original thrown value is retained as cause for callers that can inspect it. */ async function downloadOperation( stage: string, url: string, token: string | null, operation: () => Promise, ): Promise { try { return await operation(); } catch (cause) { const seen = new Set(); const redact = (text: string): string => { const withoutToken = token === null ? text : text.replaceAll(token, '[redacted]'); return withoutToken.replace(/https?:\/\/[^\s"<>]+/gi, (raw) => { try { const parsed = new URL(raw); parsed.username = ''; parsed.password = ''; parsed.search = ''; parsed.hash = ''; return parsed.href; } catch { return '[redacted URL]'; } }).slice(0, 1000); }; const describe = (error: unknown, depth: number): string => { if (seen.has(error) || depth > 4) return '[cause omitted]'; seen.add(error); if (typeof error !== 'object' || error === null) return redact(String(error)); const fields = error as { name?: unknown; message?: unknown; code?: unknown; cause?: unknown; errors?: unknown }; const name = typeof fields.name === 'string' ? fields.name : 'Error'; const message = typeof fields.message === 'string' ? fields.message : 'Unknown transport error'; const code = typeof fields.code === 'string' ? ` [${fields.code}]` : ''; let detail = redact(`${name}${code}: ${message}`); if (fields.cause !== undefined) detail += `; caused by ${describe(fields.cause, depth + 1)}`; if (Array.isArray(fields.errors)) detail += `; ${fields.errors.slice(0, 4).map((error) => describe(error, depth + 1)).join('; ')}`; return detail; }; throw new Error(`Workbench download failed during ${stage} at ${url}: ${describe(cause, 0)}`, { cause }); } } function assetUrl(asset: ReleaseAsset): string { return `https://api.github.com/repos/${RELEASE_REPO}/releases/assets/${asset.id}`; } /** * FETCH ONE PUBLISHED RELEASE into `dir`, atomically: everything lands in a * sibling `.partial` directory and is renamed into place at the end, so a * directory under `~/.volter/workbenches` either is a whole workbench or is not * there. Any failure — a refused download, a sha that does not match the * product's pin, a tar that dies — deletes the partial and refuses. */ async function fetchDeclaredRelease( product: ProductIdentity, tag: string, dir: string, io: WorkbenchFetchIO, ): Promise { if (product.workbench === null) throw new Error('Cannot download an unpinned workbench.'); const productId = workbenchProductId(product.name); const machine = machinePlatform(); const token = githubToken(); const partial = join(WORKBENCH_CACHE_ROOT, `.${tag}.${process.pid}.partial`); const cutLine = ` node scripts/workbench/build-release.mjs --product ${productId} --platform ${machine} ` + '--checkout --publish'; const releaseUrl = `https://api.github.com/repos/${RELEASE_REPO}/releases/tags/${encodeURIComponent(tag)}`; const response = await downloadOperation('release metadata request', releaseUrl, token, () => fetch(releaseUrl, { headers: apiHeaders(token) })); if (response.status === 404 && token === null) throw new Error( `${product.name} opens in the Code-OSS workbench published as ${tag} on ${RELEASE_REPO}, and ` + 'that repository answers 404 to this machine — it is private, and nothing here has a ' + 'GitHub token to read it with. Two doors, either one:\n' + `${tokenDoors()}\n` + 'Or name a workbench you already have, which needs no network at all:\n' + ` ${product.command} edit --workbench `, ); if (response.status === 404) throw new Error( `${RELEASE_REPO} has no release tagged ${tag}, and that is the workbench ${product.name} ` + `declares (package.json#${PRODUCT_DECLARATION_KEY}.workbench). Either the declaration names ` + 'a tag that was never published, or this token cannot see the repository. Cut and publish ' + `it:\n${cutLine}`, ); if (!response.ok) throw new Error( `${RELEASE_REPO}'s release ${tag} answered ${response.status} ${response.statusText}. That is ` + `the workbench ${product.name} declares; ` + `${token === null ? 'no token was found' : 'the token this machine has was used'}.` + (token === null ? `\n${tokenDoors()}` : ''), ); const metadata = await downloadOperation('release metadata response', releaseUrl, token, () => response.json()); const assets = (metadata as { assets?: ReleaseAsset[] }).assets ?? []; const record = assets.find((asset) => asset.name === RELEASE_RECORD); const tarball = assets.find((asset) => asset.name.endsWith('.tar.gz')); if (record === undefined || tarball === undefined) throw new Error( `Release ${tag} on ${RELEASE_REPO} carries ` + `${assets.length === 0 ? 'no assets' : assets.map((asset) => asset.name).join(', ')}. ` + `A workbench release is a tarball and its ${RELEASE_RECORD}, both uploaded by ` + `\`build-release.mjs --publish\`; re-publish it:\n${cutLine}`, ); rmSync(partial, { recursive: true, force: true }); mkdirSync(partial, { recursive: true }); try { // Read the compatibility record before downloading the workbench artifact. const recordText = await downloadAssetText(record, token); const built = await downloadOperation('BUILD.json parse', assetUrl(record), token, async () => JSON.parse(recordText) as Record); if (built['platform'] !== machine) throw new Error( `Release ${tag} was built for ${String(built['platform'])} and this machine is ${machine}. A ` + "Code-OSS server package carries its own platform's node binary and native modules, so it " + `cannot run here, and nothing falls back. Cut and publish the ${machine} release:\n${cutLine}`, ); if (built['tarballSha256'] !== product.workbench.tarballSha256) throw new Error( `Release ${tag}'s own ${RELEASE_RECORD} records tarballSha256 ${String(built['tarballSha256'])} ` + `and ${product.name} pins ${product.workbench.tarballSha256}. A release is immutable, so these ` + 'two cannot disagree about one tag: either the product declares the wrong release, or the ' + 'release was replaced. Nothing was downloaded.', ); writeFileSync(join(partial, RELEASE_RECORD), recordText); io.log( `Fetching the ${productId} workbench ${tag} from ${RELEASE_REPO} — ` + `${megabytes(tarball.size)} MB, once for this user on this computer.`, ); const tarballPath = join(partial, tarball.name); let announced = 0; const sha = await downloadAsset(tarball, token, tarballPath, (received) => { if (received - announced < 4 * 1024 ** 2 && received !== tarball.size) return; announced = received; io.progress?.( ` ${megabytes(received)} / ${megabytes(tarball.size)} MB ` + `(${Math.floor((received / tarball.size) * 100)}%)`, ); }); if (sha !== product.workbench.tarballSha256) throw new Error( `The download of ${tag} hashes to ${sha} and ${product.name} pins ` + `${product.workbench.tarballSha256}. These are not the bytes this product runs in; the ` + 'partial download was deleted and nothing was extracted.', ); io.log(` sha256 ${sha.slice(0, 12)}… matches the pin. Extracting…`); // Windows' own tar (bsdtar, System32) — Git's GNU tar, often first on PATH, reads the // "C:" of a path as a remote host. const tar = process.platform === 'win32' ? join(process.env['SystemRoot'] ?? 'C:\\Windows', 'System32', 'tar.exe') : 'tar'; execFileSync(tar, ['-xzf', tarballPath, '-C', partial], { windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'], }); // The tarball has done its job and is 216 MB; the extraction is what runs. rmSync(tarballPath, { force: true }); if (existsSync(join(dir, RELEASE_RECORD))) { // Another process won the same race. A release is immutable, so its // directory is ours too — take it and drop this copy. rmSync(partial, { recursive: true, force: true }); } else { rmSync(dir, { recursive: true, force: true }); renameSync(partial, dir); } io.log(`Workbench installed at ${dir}.`); } catch (error) { rmSync(partial, { recursive: true, force: true }); throw error; } } /** One asset's bytes as text — for `BUILD.json`, which is a kilobyte. */ async function downloadAssetText(asset: ReleaseAsset, token: string | null): Promise { const url = assetUrl(asset); const response = await downloadOperation('BUILD.json request', url, token, () => fetch(url, { headers: { ...apiHeaders(token), Accept: 'application/octet-stream' } })); if (!response.ok) throw new Error( `${asset.name} of ${RELEASE_REPO} answered ${response.status} ${response.statusText}.`, ); return await downloadOperation('BUILD.json response', url, token, () => response.text()); } /** * One asset's bytes to a file, hashing them ON THE WAY THROUGH — a 216 MB * tarball is not read twice, and it is never held in memory. */ async function downloadAsset( asset: ReleaseAsset, token: string | null, destination: string, onProgress: (received: number) => void, ): Promise { const url = assetUrl(asset); const response = await downloadOperation('archive request', url, token, () => fetch(url, { headers: { ...apiHeaders(token), Accept: 'application/octet-stream' } })); if (!response.ok || response.body === null) throw new Error( `${asset.name} of ${RELEASE_REPO} answered ${response.status} ${response.statusText}.`, ); const hash = createHash('sha256'); let received = 0; await downloadOperation('archive transfer', url, token, () => pipeline( Readable.fromWeb(response.body as never), async function* (source: AsyncIterable) { for await (const chunk of source) { hash.update(chunk); received += chunk.length; onProgress(received); yield chunk; } }, createWriteStream(destination), )); return hash.digest('hex'); }