// Where is this Mirror installed, and what can update it? (CV22.DS10.US2) // // The updater's first question, answered from where the front door ITSELF // lives rather than from configuration. A user who has to tell the updater how // they installed Mirror can tell it wrong, and the answer decides whether the // next step is `git merge --ff-only` or `npm install -g`. // // Three answers, and `unknown` is a real one: an install we cannot identify is // refused with its reason printed, never updated on a guess. import { existsSync, readFileSync, realpathSync } from "node:fs"; import { basename, dirname, join, resolve, sep } from "node:path"; export type InstallKind = | { kind: "clone"; repository: string } | { kind: "package"; root: string; name: string; version: string } | { kind: "unknown"; reason: string }; export interface InstallKindProbe { /** The front door's own resolved path. */ frontDoorPath: string; /** * `npm root -g`, resolved once by the caller, when the caller needs npm's * word that `-g` addresses THIS install: the update lane does. Given as a * string, a package must sit inside it. Omitted or `null` (npm not probed, * or not available), a package is known by its layout alone -- see * `packageByLayout` -- which is what the read-only routes ask, since they * run where npm may not be on the PATH and must still say what this is. */ npmRootGlobal?: string | null; exists?: (path: string) => boolean; readFile?: (path: string) => string; /** * Symlink resolution for the front door's path. `npm link` places a symlink * named like the package under the global root, so a developer's checkout * can be reached through a path that looks installed; what is updated must * be the tree the file really lives in. */ realpath?: (path: string) => string; } /** Is `child` inside `parent`, by path components rather than string prefix? */ function isInside(parent: string, child: string): boolean { const base = resolve(parent); const target = resolve(child); return target === base || target.startsWith(base.endsWith(sep) ? base : base + sep); } /** * The git work tree holding this front door, identified by the repository * marker this project actually has: a root that carries `package.json` and a * `.git` entry (the manifest moved to the root in CV22.DS10.US3, D2). Walking up rather than asking git keeps detection free of a * subprocess and of git's own notion of "inside a work tree", which is true in * places this updater must not touch (a submodule, a nested checkout). */ function cloneRootFor(startDir: string, exists: (path: string) => boolean): string | null { let current = resolve(startDir); for (;;) { if (exists(join(current, ".git")) && exists(join(current, "package.json"))) { return current; } const parent = dirname(current); if (parent === current) return null; current = parent; } } interface Manifest { root: string; name: string; version: string; bins: string[]; } /** The nearest manifest above the front door that names and versions a package. */ function nearestManifest( frontDoorPath: string, stopAt: string | null, exists: (path: string) => boolean, readFile: (path: string) => string, ): Manifest | null { let current = resolve(dirname(frontDoorPath)); const stop = stopAt === null ? null : resolve(stopAt); for (;;) { const manifest = join(current, "package.json"); if (exists(manifest)) { try { const parsed = JSON.parse(readFile(manifest)) as { name?: unknown; version?: unknown; bin?: unknown; }; if (typeof parsed.name === "string" && typeof parsed.version === "string") { const bins = typeof parsed.bin === "string" ? [parsed.name] : typeof parsed.bin === "object" && parsed.bin !== null ? Object.keys(parsed.bin) : []; return { root: current, name: parsed.name, version: parsed.version, bins }; } } catch { // A manifest we cannot read is not a package we should reinstall. return null; } } if (current === stop) return null; const parent = dirname(current); if (parent === current) return null; current = parent; } } /** * The installed package holding this front door, by npm's own word: the * manifest sits inside `npm root -g`. * * Being under SOME `node_modules/` is not enough, and the difference matters: * a project-local dependency would detect as `package`, and `npm install -g` * would then update a completely different tree from the one running. The * global root is the evidence that `-g` addresses THIS install, which is why * the update lane asks this way. */ function packageUnderNpmRoot( frontDoorPath: string, npmRootGlobal: string, exists: (path: string) => boolean, readFile: (path: string) => string, realpath: (path: string) => string, ): InstallKind | null { // Both sides resolved: the front door already is, and npm answers with // the prefix as configured, symlinks and all (/tmp on macOS is one). const root = realpath(resolve(npmRootGlobal)); if (!isInside(root, frontDoorPath)) return null; const manifest = nearestManifest(frontDoorPath, root, exists, readFile); if (manifest === null) return null; return { kind: "package", root: manifest.root, name: manifest.name, version: manifest.version }; } /** * The installed package holding this front door, by its layout, with no * subprocess (CV22.DS10.US3 plateau 4: the read-only routes run where npm may * be off the PATH and must still say what this is). npm has two global * layouts, and in both the bin is what makes a global install global -- a * project that happens to live at `/lib` has the manifest half and not the * bin half: * * - POSIX: the manifest at `/lib/node_modules/`, and one of its * bins at `/bin/`, a symlink that resolves back into the * package. * - Windows: the manifest at `\node_modules\`, and one of its * bins at `\.cmd`, a shim file that runs * `%dp0%\node_modules\\...`. Nothing resolves, so the shim's own * text is the evidence that the bin reaches into THIS package. */ function packageByLayout( frontDoorPath: string, exists: (path: string) => boolean, readFile: (path: string) => string, realpath: (path: string) => string, ): InstallKind | null { const manifest = nearestManifest(frontDoorPath, null, exists, readFile); if (manifest === null) return null; const nodeModules = dirname(manifest.root); if (basename(nodeModules) !== "node_modules") return null; const linked = binLinkedUnderPosixPrefix(manifest, nodeModules, exists, realpath) || binShimmedUnderWindowsPrefix(manifest, nodeModules, exists, readFile); if (!linked) return null; return { kind: "package", root: manifest.root, name: manifest.name, version: manifest.version }; } function binLinkedUnderPosixPrefix( manifest: Manifest, nodeModules: string, exists: (path: string) => boolean, realpath: (path: string) => string, ): boolean { const lib = dirname(nodeModules); if (basename(lib) !== "lib") return false; const prefix = dirname(lib); return manifest.bins.some((bin) => { const link = join(prefix, "bin", bin); return exists(link) && isInside(manifest.root, realpath(link)); }); } /** * Not gated by platform, on purpose: the layout is evidence wherever it is * found, and a Windows-only branch could be exercised only on Windows. Kept * open, macOS and Linux run the Windows tests with fixture paths, and the * `windows-latest` job runs the same tests on the real thing. */ function binShimmedUnderWindowsPrefix( manifest: Manifest, nodeModules: string, exists: (path: string) => boolean, readFile: (path: string) => string, ): boolean { const prefix = dirname(nodeModules); const runsThisPackage = `node_modules/${manifest.name}/`; return manifest.bins.some((bin) => { const shim = join(prefix, `${bin}.cmd`); if (!exists(shim)) return false; try { return readFile(shim).replace(/\\/g, "/").includes(runsThisPackage); } catch { return false; } }); } /** `realpathSync`, except that a path that does not exist is returned as given. */ function safeRealpath(path: string): string { try { return realpathSync(path); } catch { return path; } } /** * This front door's own path, as the filesystem spells it: what every route * hands `detectInstallKind`. From `import.meta.dirname`, so the path never * passes through URL form: a URL's pathname is not a filesystem path. It * percent-encodes every reserved character -- a directory named `Código` or * `John Doe` becomes `C%C3%B3digo`, `John%20Doe` -- and on Windows it spells * `C:\...` as `/C:/...`. Read as a path, none of those exist, so no `.git` * was found above the front door and every such install was `unknown`: the * updater refused, and after CR138 the git rows went blank. The guard row * `url-pathname-as-path` keeps the idiom out of `ts/src` and `ts/scripts`. */ export function thisFrontDoorPath(): string { return join(import.meta.dirname, "..", "frontDoor", "cli.ts"); } export function detectInstallKind(probe: InstallKindProbe): InstallKind { const exists = probe.exists ?? existsSync; const readFile = probe.readFile ?? ((path: string) => readFileSync(path, "utf8")); const realpath = probe.realpath ?? safeRealpath; const frontDoorPath = realpath(resolve(probe.frontDoorPath)); const asPackage = probe.npmRootGlobal ? packageUnderNpmRoot(frontDoorPath, probe.npmRootGlobal, exists, readFile, realpath) : packageByLayout(frontDoorPath, exists, readFile, realpath); if (asPackage !== null) return asPackage; const repository = cloneRootFor(dirname(frontDoorPath), exists); if (repository !== null) return { kind: "clone", repository }; // The reason carries the path the walk started from, spelled as the detector // saw it (CR140): a path that is wrong -- a URL's `%C3%B3` for `ó`, a `/C:/` // for `C:\` -- is then wrong in the report, where `not a git checkout` alone // sent two contributors on two platforms debugging what this line shows. const because = probe.npmRootGlobal === null ? "not a git checkout, and npm is unavailable to identify a package install" : probe.npmRootGlobal === undefined ? "not a git checkout, and not laid out as a global npm install" : "not a git checkout, and not under the global npm root"; return { kind: "unknown", reason: `${because}; looked up from ${frontDoorPath}` }; } /** * Where the repository rows of `status`, `version`, and `diagnose` come from * (CR138): `start` when one is given -- `version --start PATH`, or a test -- * else a clone's own checkout, else nowhere. Never the cwd. For a skill the * cwd is the person's project, and git run there reads that project's config, * where `core.fsmonitor` names a command git runs on `status`. */ export function inspectionRootFor( install: InstallKind, start: string | null | undefined, ): string | null { if (start !== null && start !== undefined) return resolve(start); return install.kind === "clone" ? install.repository : null; } /** One line for a render or a log entry. */ export function describeInstallKind(install: InstallKind): string { if (install.kind === "clone") return `clone (${install.repository})`; if (install.kind === "package") return `package (${install.name}@${install.version})`; return `unknown (${install.reason})`; } /** * The install, for `runtime status` and `runtime version`: the kind, and for * a package the root `npm install -g` replaces, which its one-line form does * not carry (US2 D3, deferred to CV22.DS10.US3 plateau 4). */ export function renderInstallLines(install: InstallKind): string[] { const lines = [`Install: ${describeInstallKind(install)}`]; if (install.kind === "package") lines.push(`Install root: ${install.root}`); return lines; }