{"draft":null,"from":2,"to":318,"files":[{"path":"client/launch.mjs","added":254,"removed":0,"diff":"--- /dev/null\n+++ b/client/launch.mjs\n@@ -0,0 +1,254 @@\n+// Runs abso from a git checkout of it and keeps that checkout current.\n+//\n+// Point a command at this file (node <checkout>/client/launch.mjs <args>) and it:\n+// - runs the client: a plain-JS bundle of it in this process when one matches the checkout's commit,\n+//   otherwise client/abso.ts in a second node. Node strips types from every client file on every run,\n+//   so the bundle starts several times faster;\n+// - at most every 5 minutes, and within 30 seconds of a stale bundle, starts a background step that\n+//   fast-forwards the checkout (on main only), runs npm install when package-lock.json changed, and\n+//   builds the bundle. That step never blocks or fails the command, and only one runs at a time.\n+//\n+// stdin, stdout, stderr, the arguments and the exit code pass through untouched: the exit codes carry\n+// meaning (2 refused, 3 still queued). The launcher's own notices go only to ~/.abso/launcher.log.\n+//\n+// The bundle is client/dist/abso.mjs, with the commit it was built from in client/dist/abso.mjs.commit.\n+// It sits one folder under client/, so the client's own folder (client-version.ts) is still client/.\n+// It is built with esbuild when the checkout has it (in worker/ or at the root): bundled, for node24,\n+// as an ES module, with no build commit stamped in, since a stamped client calls itself a downloaded\n+// copy. It is built to a temporary file and renamed into place, and marked current only after every\n+// require left in it resolves and it runs --version. If it still fails to load, the same run falls\n+// back to client/abso.ts and writes one line to the log, so edit hooks keep recording.\n+//\n+// Plain JS on purpose: this file is loaded on every command, before any bundle.\n+import { execFileSync, spawn } from \"node:child_process\";\n+import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from \"node:fs\";\n+import { createRequire } from \"node:module\";\n+import { homedir } from \"node:os\";\n+import { dirname, join, resolve } from \"node:path\";\n+import { fileURLToPath, pathToFileURL } from \"node:url\";\n+\n+const repo = dirname(dirname(fileURLToPath(import.meta.url)));\n+const state = join(homedir(), \".abso\");\n+const stamp = join(state, \"client-update.stamp\");\n+const every = 5 * 60 * 1000;\n+const bundle = join(repo, \"client\", \"dist\", \"abso.mjs\");\n+const bundleCommit = `${bundle}.commit`;\n+/** Set on the background step's own node, which updates the checkout and exits. */\n+const UPDATE = \"ABSO_LAUNCH_UPDATE\";\n+/** Set by the bundle's first line: an error after it came from the command, so it's never run again. */\n+const STARTED = \"__absoBundleStarted\";\n+\n+/**\n+ * The checkout's git folders: its own (HEAD) and the shared one (refs, info/exclude). They are the same\n+ * folder in a plain clone; in a worktree .git is a file naming its own folder, which names the shared one.\n+ */\n+function gitDirs(root = repo) {\n+\tconst dot = join(root, \".git\");\n+\ttry {\n+\t\tif (statSync(dot).isDirectory()) return { own: dot, common: dot };\n+\t\tconst own = resolve(\n+\t\t\troot,\n+\t\t\treadFileSync(dot, \"utf8\")\n+\t\t\t\t.trim()\n+\t\t\t\t.replace(/^gitdir:\\s*/, \"\"),\n+\t\t);\n+\t\tlet common = own;\n+\t\ttry {\n+\t\t\tcommon = resolve(own, readFileSync(join(own, \"commondir\"), \"utf8\").trim());\n+\t\t} catch {}\n+\t\treturn { own, common };\n+\t} catch {\n+\t\treturn undefined;\n+\t}\n+}\n+\n+/** The checkout's commit, read from .git without running git; undefined if it can't be read. */\n+function headCommit(root = repo) {\n+\tconst dirs = gitDirs(root);\n+\tif (!dirs) return undefined;\n+\ttry {\n+\t\tconst head = readFileSync(join(dirs.own, \"HEAD\"), \"utf8\").trim();\n+\t\tif (!head.startsWith(\"ref:\")) return head;\n+\t\tconst ref = head.slice(4).trim();\n+\t\tfor (const dir of [dirs.own, dirs.common]) {\n+\t\t\ttry {\n+\t\t\t\treturn readFileSync(join(dir, ...ref.split(\"/\")), \"utf8\").trim();\n+\t\t\t} catch {}\n+\t\t}\n+\t\tconst line = readFileSync(join(dirs.common, \"packed-refs\"), \"utf8\")\n+\t\t\t.split(\"\\n\")\n+\t\t\t.find((l) => l.endsWith(` ${ref}`));\n+\t\treturn line?.split(\" \")[0];\n+\t} catch {\n+\t\treturn undefined;\n+\t}\n+}\n+\n+/**\n+ * Runs fn under a lock folder, or not at all when another run holds it. A lock older than 10 minutes is a\n+ * dead run's: it is renamed aside before it's removed, so of two runs that find it stale only one takes it\n+ * over, and one that renamed away a lock taken over a moment ago puts it back.\n+ */\n+function locked(lock, fn) {\n+\tconst stale = (path) => Date.now() - statSync(path).mtimeMs > 10 * 60 * 1000;\n+\ttry {\n+\t\tif (stale(lock)) {\n+\t\t\tconst aside = `${lock}.${process.pid}.stale`;\n+\t\t\trenameSync(lock, aside);\n+\t\t\tif (stale(aside)) rmSync(aside, { recursive: true, force: true });\n+\t\t\telse {\n+\t\t\t\trenameSync(aside, lock);\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t}\n+\t} catch {}\n+\ttry {\n+\t\tmkdirSync(lock);\n+\t} catch {\n+\t\treturn;\n+\t}\n+\ttry {\n+\t\tfn();\n+\t} finally {\n+\t\trmSync(lock, { recursive: true, force: true });\n+\t}\n+}\n+\n+/** One line in the launcher's log, never on the command's own output. */\n+function note(text) {\n+\ttry {\n+\t\tmkdirSync(state, { recursive: true });\n+\t\tappendFileSync(join(state, \"launcher.log\"), `${new Date().toISOString()} abso launch: ${text}\\n`);\n+\t} catch {}\n+}\n+\n+/**\n+ * The background step, one at a time under a lock (a second one finds it taken and exits): fast-forward,\n+ * install when the lock file moved, then the bundle.\n+ */\n+function update() {\n+\tconst git = (...a) => execFileSync(\"git\", [\"-C\", repo, ...a], { encoding: \"utf8\", windowsHide: true });\n+\tmkdirSync(state, { recursive: true });\n+\tlocked(join(state, \"client-update.lock\"), () => {\n+\t\ttry {\n+\t\t\tif (git(\"branch\", \"--show-current\").trim() === \"main\") {\n+\t\t\t\tconst before = git(\"rev-parse\", \"HEAD\").trim();\n+\t\t\t\tgit(\"fetch\", \"-q\", \"origin\", \"main\");\n+\t\t\t\tgit(\"merge\", \"-q\", \"--ff-only\", \"origin/main\");\n+\t\t\t\tif (git(\"diff\", \"--name-only\", before, \"HEAD\", \"--\", \"package-lock.json\").trim())\n+\t\t\t\t\texecFileSync(\"npm\", [\"install\", \"--no-audit\", \"--no-fund\"], {\n+\t\t\t\t\t\tcwd: repo,\n+\t\t\t\t\t\tstdio: \"ignore\",\n+\t\t\t\t\t\twindowsHide: true,\n+\t\t\t\t\t\tshell: true,\n+\t\t\t\t\t});\n+\t\t\t}\n+\t\t} catch {}\n+\t\ttry {\n+\t\t\tbuild(git(\"rev-parse\", \"HEAD\").trim());\n+\t\t} catch (e) {\n+\t\t\tnote(`the bundle wasn't built (${String(e?.message).split(\"\\n\")[0]}); client/abso.ts runs until it is`);\n+\t\t}\n+\t});\n+}\n+\n+/** Builds the bundle for this commit, unless it's already current or the checkout has no esbuild. */\n+function build(head) {\n+\ttry {\n+\t\tif (readFileSync(bundleCommit, \"utf8\").trim() === head) return;\n+\t} catch {}\n+\tconst require = createRequire(import.meta.url);\n+\tlet esbuild;\n+\ttry {\n+\t\tesbuild = require(require.resolve(\"esbuild\", { paths: [join(repo, \"worker\"), repo] }));\n+\t} catch {\n+\t\treturn;\n+\t}\n+\tconst exclude = join(gitDirs()?.common ?? join(repo, \".git\"), \"info\", \"exclude\");\n+\ttry {\n+\t\tif (!readFileSync(exclude, \"utf8\").split(/\\r?\\n/).includes(\"client/dist/\"))\n+\t\t\tappendFileSync(exclude, \"\\nclient/dist/\\n\");\n+\t} catch {}\n+\tmkdirSync(dirname(bundle), { recursive: true });\n+\tconst tmp = bundle.replace(/\\.mjs$/, `.${process.pid}.tmp.mjs`);\n+\ttry {\n+\t\tesbuild.buildSync({\n+\t\t\tentryPoints: [join(repo, \"client\", \"abso.ts\")],\n+\t\t\tbundle: true,\n+\t\t\tplatform: \"node\",\n+\t\t\tformat: \"esm\",\n+\t\t\ttarget: \"node24\",\n+\t\t\toutfile: tmp,\n+\t\t\tlogLevel: \"silent\",\n+\t\t\t// A bundled CommonJS package (yaml) calls require(\"process\") lazily, which an ES module\n+\t\t\t// bundle can't do without a real require. The flag says the bundle started running.\n+\t\t\tbanner: {\n+\t\t\t\tjs: `globalThis.${STARTED} = true; import { createRequire as __absoCreateRequire } from \"node:module\"; const require = __absoCreateRequire(import.meta.url);`,\n+\t\t\t},\n+\t\t});\n+\t\tconst from = createRequire(bundle);\n+\t\tfor (const m of readFileSync(tmp, \"utf8\").matchAll(/__require\\(\"([^\"]+)\"\\)/g)) from.resolve(m[1]);\n+\t\texecFileSync(process.execPath, [tmp, \"--version\"], { cwd: repo, stdio: \"ignore\", windowsHide: true });\n+\t\trenameSync(tmp, bundle);\n+\t\twriteFileSync(bundleCommit, `${head}\\n`);\n+\t} finally {\n+\t\trmSync(tmp, { force: true });\n+\t}\n+}\n+\n+/** Runs client/abso.ts in a second node, and exits with its code. */\n+function runTs() {\n+\tconst child = spawn(process.execPath, [join(repo, \"client\", \"abso.ts\"), ...process.argv.slice(2)], {\n+\t\tstdio: \"inherit\",\n+\t});\n+\tchild.on(\"exit\", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));\n+}\n+\n+/** Starts the background step when it's due: every 5 minutes, or within 30 seconds of a stale bundle. */\n+function maybeUpdate(fresh) {\n+\ttry {\n+\t\tlet last = 0;\n+\t\ttry {\n+\t\t\tlast = statSync(stamp).mtimeMs;\n+\t\t} catch {}\n+\t\tif (Date.now() - last <= (fresh ? every : 30_000)) return;\n+\t\tmkdirSync(state, { recursive: true });\n+\t\twriteFileSync(stamp, `${new Date().toISOString()}\\n`);\n+\t\tspawn(process.execPath, [fileURLToPath(import.meta.url)], {\n+\t\t\tdetached: true,\n+\t\t\tstdio: \"ignore\",\n+\t\t\twindowsHide: true,\n+\t\t\tenv: { ...process.env, [UPDATE]: \"1\" },\n+\t\t}).unref();\n+\t} catch {}\n+}\n+\n+/** The command: the bundle when it matches the checkout, else client/abso.ts. */\n+async function run() {\n+\tconst head = headCommit();\n+\tlet fresh = false;\n+\ttry {\n+\t\tfresh = head !== undefined && readFileSync(bundleCommit, \"utf8\").trim() === head;\n+\t} catch {}\n+\tmaybeUpdate(fresh);\n+\tif (!fresh) return runTs();\n+\t// In this process: the client reads its arguments from process.argv, as if run as `node client/dist/abso.mjs`.\n+\tconst args = process.argv;\n+\tprocess.argv = [args[0], bundle, ...args.slice(2)];\n+\ttry {\n+\t\tawait import(pathToFileURL(bundle).href);\n+\t} catch (e) {\n+\t\t// Only a bundle that never started falls back: one that can't be found or parsed, or imports\n+\t\t// something missing. Anything else came from the command itself, which the .ts would repeat.\n+\t\tconst code = e?.code;\n+\t\tconst loading =\n+\t\t\te instanceof SyntaxError || code === \"ERR_MODULE_NOT_FOUND\" || code === \"ERR_UNSUPPORTED_ESM_URL_SCHEME\";\n+\t\tif (!loading || globalThis[STARTED] === true) throw e;\n+\t\tnote(`the bundle didn't load (${code ?? e?.name}: ${String(e?.message).split(\"\\n\")[0]}), ran client/abso.ts`);\n+\t\tprocess.argv = args;\n+\t\trunTs();\n+\t}\n+}\n+\n+if (process.env[UPDATE] === \"1\") update();\n+else await run();"}],"unmatched":[]}