home-hosted 0.13.0 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{backup-CZcVca2a.js → backup-DeAJ3pbO.js} +6 -6
- package/dist/chunks/{backup-CZcVca2a.js.map → backup-DeAJ3pbO.js.map} +1 -1
- package/dist/chunks/{backups-CFRaWe_m.js → backups-twva7x2n.js} +3 -3
- package/dist/chunks/{backups-CFRaWe_m.js.map → backups-twva7x2n.js.map} +1 -1
- package/dist/chunks/{daemon-qKVECISl.js → daemon-CofN9k6Q.js} +3 -3
- package/dist/chunks/{daemon-qKVECISl.js.map → daemon-CofN9k6Q.js.map} +1 -1
- package/dist/chunks/{down-pKbGCW9d.js → down-C59ne5aM.js} +5 -5
- package/dist/chunks/{down-pKbGCW9d.js.map → down-C59ne5aM.js.map} +1 -1
- package/dist/chunks/{nanny-BtWfy0QH.js → nanny-COyCJXj9.js} +10 -5
- package/dist/chunks/nanny-COyCJXj9.js.map +1 -0
- package/dist/chunks/{nanny-ChMtq1Zl.js → nanny-Dnun3hVB.js} +3 -3
- package/dist/chunks/{nanny-ChMtq1Zl.js.map → nanny-Dnun3hVB.js.map} +1 -1
- package/dist/chunks/{nanny-B-Eu0sFW.js → nanny-rewguyXg.js} +2 -2
- package/dist/chunks/{nanny-B-Eu0sFW.js.map → nanny-rewguyXg.js.map} +1 -1
- package/dist/chunks/{nanny-sweep-DErnlPY1.js → nanny-sweep-ClVuNJRo.js} +3 -3
- package/dist/chunks/{nanny-sweep-DErnlPY1.js.map → nanny-sweep-ClVuNJRo.js.map} +1 -1
- package/dist/chunks/{port-B8WBTRMk.js → port-k5VBw8t9.js} +5 -2
- package/dist/chunks/{port-B8WBTRMk.js.map → port-k5VBw8t9.js.map} +1 -1
- package/dist/chunks/{restart-Des4DrAN.js → restart-BYu_E7x5.js} +5 -5
- package/dist/chunks/{restart-Des4DrAN.js.map → restart-BYu_E7x5.js.map} +1 -1
- package/dist/chunks/{server-Bge2r2qQ.js → server-By-zktjx.js} +3 -3
- package/dist/chunks/{server-Bge2r2qQ.js.map → server-By-zktjx.js.map} +1 -1
- package/dist/chunks/{set-token-obPiEJYk.js → set-token-xJkA1IZp.js} +2 -2
- package/dist/chunks/{set-token-obPiEJYk.js.map → set-token-xJkA1IZp.js.map} +1 -1
- package/dist/chunks/{src-BtWMFmzZ.js → src-BOBh9MBf.js} +9 -6
- package/dist/chunks/src-BOBh9MBf.js.map +1 -0
- package/dist/chunks/{status-DT1EsA-B.js → status-B6f2-qhs.js} +2 -2
- package/dist/chunks/{status-DT1EsA-B.js.map → status-B6f2-qhs.js.map} +1 -1
- package/dist/chunks/{up-Pdz-l6IH.js → up-DNZuTi2q.js} +4 -4
- package/dist/chunks/{up-Pdz-l6IH.js.map → up-DNZuTi2q.js.map} +1 -1
- package/dist/chunks/{usage-DFrCVXpT.js → usage-BrnDARNM.js} +2 -2
- package/dist/chunks/{usage-DFrCVXpT.js.map → usage-BrnDARNM.js.map} +1 -1
- package/dist/cli.js +11 -11
- package/package.json +1 -1
- package/uis/stock/dist/ui.json +2 -2
- package/dist/chunks/nanny-BtWfy0QH.js.map +0 -1
- package/dist/chunks/src-BtWMFmzZ.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nanny-
|
|
1
|
+
{"version":3,"file":"nanny-rewguyXg.js","names":[],"sources":["../../src/services/nanny.ts"],"sourcesContent":["import type { ChildProcess } from 'node:child_process'\nimport type { LogStream, NannyExit, NannySpec, NannyState } from '#src/shared/contracts'\nimport process from 'node:process'\nimport { describeNannyExit, describeSpawnError, NANNY_HEARTBEAT_MS, NANNY_TRAPPED_SIGNALS, nannyLogFile, writeNannyState } from '#src/providers/nanny'\nimport { spawnManaged, terminate } from '#src/providers/process'\nimport { LineSplitter } from '#src/services/log-buffer'\nimport { LogFiles } from '#src/services/log-files'\n\n/** Signals this nanny's own process group; false where there is none to signal (Windows, not a leader). */\nfunction signalOwnGroup(signal: NodeJS.Signals): boolean {\n if (process.platform === 'win32')\n return false\n try {\n process.kill(-process.pid, signal)\n return true\n }\n catch {\n return false\n }\n}\n\n/**\n * The nanny of one persistent entry: it spawns the child, owns its pipes, writes its\n * output to the entry's JSONL log and mirrors the child's exit.\n *\n * This is the whole reason a persistent entry survives the panel. The pipes belong to\n * a process that is not the panel, so a panel stop, restart or SIGKILL cannot break\n * them; the log keeps being written; and the exit code the panel would have collected\n * as a parent is left in the state file for whoever comes back.\n *\n * It deliberately does *not* restart anything: retries, backoff and health stay the\n * panel's business, so there is only ever one supervisor making that decision.\n */\nexport async function runNanny(spec: NannySpec, statePath: string): Promise<void> {\n const id = spec.serverId\n const startedAt = Date.now()\n const logFile = nannyLogFile(spec.logDir, id)\n // The file is this entry's log *transport*, not its retention policy: the panel\n // still decides whether that history is served. So it is always written.\n const logFiles = new LogFiles(spec.logDir, () => ({ ...spec.logs, persist: true }))\n\n let childPid: number | null = null\n let lastExit: NannyExit | null = null\n let exitCode = 0\n\n const persistState = (): void => {\n const state: NannyState = {\n serverId: id,\n nannyPid: process.pid,\n childPid,\n startedAt,\n logFile,\n heartbeatAt: Date.now(),\n }\n if (lastExit !== null)\n state.lastExit = lastExit\n writeNannyState(statePath, state)\n }\n\n const emit = (stream: LogStream, text: string): void => {\n logFiles.append(id, { ts: Date.now(), stream, text })\n }\n\n // The traps go up before the child exists, and before anything about this nanny is on\n // disk: a stop that lands in between would otherwise kill a nanny that had not taken\n // over its child yet, orphaning that child with no record of it anywhere.\n let stopping = false\n let pending: NodeJS.Signals | null = null\n let spawned: ChildProcess | null = null\n\n const stopChild = (child: ChildProcess, signal: NodeJS.Signals): void => {\n emit('system', `${signal} — stopping this entry (grace ${spec.stop.graceMs}ms)`)\n // The panel signals this pid alone (`nannyStopOptions`), so `killGroup` is honoured here: one\n // signal to this group reaches the child and what it spawned exactly once, and the copy this\n // nanny receives is ignored. The escalation stays on the child's pid — the group holds us too.\n if (spec.stop.killGroup && NANNY_TRAPPED_SIGNALS.has(spec.stop.signal) && signalOwnGroup(spec.stop.signal)) {\n const escalate = setTimeout(() => {\n try {\n child.kill('SIGKILL')\n }\n catch {\n // already gone\n }\n }, spec.stop.graceMs)\n escalate.unref()\n child.once('exit', () => clearTimeout(escalate))\n return\n }\n void terminate(child, { signal: spec.stop.signal, killGroup: false, graceMs: spec.stop.graceMs })\n }\n\n const onSignal = (signal: NodeJS.Signals): void => {\n if (stopping)\n return\n stopping = true\n // Nothing to stop yet: the spawn is right behind this, and it reads `pending`.\n if (spawned === null)\n pending = signal\n else\n stopChild(spawned, signal)\n }\n\n // The same set `stopPersistentEntries` reads: a signal outside it ends this process without\n // forwarding anything, so the sweep has to signal the child itself.\n for (const signal of NANNY_TRAPPED_SIGNALS)\n process.on(signal, () => onSignal(signal))\n\n // Not detached: the child shares this nanny's process group, which is the group the\n // panel signals — one `kill(-pid)` still reaches the whole tree.\n const child = spawnManaged(\n { command: spec.command, args: spec.args, cwd: spec.cwd, env: spec.env },\n { detached: false },\n )\n spawned = child\n childPid = child.pid ?? null\n persistState()\n emit('system', `persistent: nanny pid ${process.pid} runs this entry`)\n // A stop that arrived before the spawn still has to reach the child it just made.\n if (pending !== null)\n stopChild(child, pending)\n\n const stdout = new LineSplitter((stream, text) => emit(stream, text))\n const stderr = new LineSplitter((stream, text) => emit(stream, text))\n child.stdout?.on('data', chunk => stdout.push('stdout', chunk))\n child.stderr?.on('data', chunk => stderr.push('stderr', chunk))\n\n const heartbeat = setInterval(persistState, NANNY_HEARTBEAT_MS)\n heartbeat.unref()\n\n await new Promise<void>((resolve) => {\n let settled = false\n const finish = (code: number | null, signal: NodeJS.Signals | null, runtimeMs: number, note?: string): void => {\n if (settled)\n return\n settled = true\n clearInterval(heartbeat)\n stdout.flush('stdout')\n stderr.flush('stderr')\n lastExit = { code, signal, at: Date.now(), runtimeMs }\n // The same formatter the panel uses, so the reason an entry died reads identically in the\n // nanny's mirror and in the panel's own log. Hand-rolling it here meant this line lost the\n // exit-code hint that the panel's line gained.\n emit('system', note ?? `persistent: exited with ${describeNannyExit(lastExit)}`)\n persistState()\n logFiles.dispose()\n // The panel reads the real cause from the state file; this is only the mirror.\n exitCode = code ?? (signal === null ? 0 : 1)\n resolve()\n }\n\n child.once('exit', (code, signal) => finish(code, signal, Date.now() - startedAt))\n child.once('error', (error: Error) => {\n // A command that cannot even be spawned: the panel reports it as \"did not start\".\n // Through the same formatter the panel uses, so a missing working directory is named\n // here too — this nanny is the only spawner a persistent entry has.\n finish(null, null, 0, `persistent: could not start the entry: ${describeSpawnError(error as NodeJS.ErrnoException, spec.command, spec.cwd)}`)\n })\n })\n\n // This nanny lives exactly as long as the child it owns, and says so by exiting.\n // Lingering is what an inherited pipe would do to us — a successor that kept our\n // stdout open refs the event loop — and a nanny that outlives its child is worse\n // than useless: the panel would report a healthy entry while the real server is a\n // detached process it can neither stop nor read. Exiting hands the entry back to\n // the panel, which is where `reclaim` can put it under a fresh nanny.\n process.exit(exitCode)\n}\n"],"mappings":";;;;;AASA,SAAS,eAAe,QAAiC;CACvD,IAAI,QAAQ,aAAa,SACvB,OAAO;CACT,IAAI;EACF,QAAQ,KAAK,CAAC,QAAQ,KAAK,MAAM;EACjC,OAAO;CACT,QACM;EACJ,OAAO;CACT;AACF;;;;;;;;;;;;;AAcA,eAAsB,SAAS,MAAiB,WAAkC;CAChF,MAAM,KAAK,KAAK;CAChB,MAAM,YAAY,KAAK,IAAI;CAC3B,MAAM,UAAU,aAAa,KAAK,QAAQ,EAAE;CAG5C,MAAM,WAAW,IAAI,SAAS,KAAK,eAAe;EAAE,GAAG,KAAK;EAAM,SAAS;CAAK,EAAE;CAElF,IAAI,WAA0B;CAC9B,IAAI,WAA6B;CACjC,IAAI,WAAW;CAEf,MAAM,qBAA2B;EAC/B,MAAM,QAAoB;GACxB,UAAU;GACV,UAAU,QAAQ;GAClB;GACA;GACA;GACA,aAAa,KAAK,IAAI;EACxB;EACA,IAAI,aAAa,MACf,MAAM,WAAW;EACnB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AS,KAAK,QAAQ,IAAI,CAAC;CACpE,MAAM,QAAQ,GAAG,SAAQ,UAAS,OAAO,KAAK,UAAU,KAAK,CAAC;CAC9D,MAAM,QAAQ,GAAG,SAAQ,UAAS,OAAO,KAAK,UAAU,KAAK,CAAC;CAE9D,MAAM,YAAY,YAAY,cAAc,kBAAkB;CAC9D,UAAU,MAAM;CAEhB,MAAM,IAAI,SAAe,YAAY;EACnC,IAAI,UAAU;EACd,MAAM,UAAU,MAAqB,QAA+B,WAAmB,SAAwB;GAC7G,IAAI,SACF;GACF,UAAU;GACV,cAAc,SAAS;GACvB,OAAO,MAAM,QAAQ;GACrB,OAAO,MAAM,QAAQ;GACrB,WAAW;IAAE;IAAM;IAAQ,IAAI,KAAK,IAAI;IAAG;GAAU;GAIrD,KAAK,UAAU,QAAQ,2BAA2B,kBAAkB,QAAQ,GAAG;GAC/E,aAAa;GACb,SAAS,QAAQ;GAEjB,WAAW,SAAS,WAAW,OAAO,IAAI;GAC1C,QAAQ;EACV;EAEA,MAAM,KAAK,SAAS,MAAM,WAAW,OAAO,MAAM,QAAQ,KAAK,IAAI,IAAI,SAAS,CAAC;EACjF,MAAM,KAAK,UAAU,UAAiB;GAIpC,OAAO,MAAM,MAAM,GAAG,0CAA0C,mBAAmB,OAAgC,KAAK,SAAS,KAAK,GAAG,GAAG;EAC9I,CAAC;CACH,CAAC;CAQD,QAAQ,KAAK,QAAQ;AACvB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { tt as stopSchema } from "./contracts-CMBD1TF9.js";
|
|
2
|
-
import { E as terminatePid, _ as readNannyState, d as nannyIsAlive, h as nannyStopOptions, l as nannyChildPid, m as nannyStatePath, p as nannySpecPath, r as NANNY_TRAPPED_SIGNALS } from "./nanny-
|
|
3
|
-
import { r as isProcessAlive } from "./port-
|
|
2
|
+
import { E as terminatePid, _ as readNannyState, d as nannyIsAlive, h as nannyStopOptions, l as nannyChildPid, m as nannyStatePath, p as nannySpecPath, r as NANNY_TRAPPED_SIGNALS } from "./nanny-COyCJXj9.js";
|
|
3
|
+
import { r as isProcessAlive } from "./port-k5VBw8t9.js";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs from "node:fs";
|
|
6
6
|
//#region src/providers/nanny-sweep.ts
|
|
@@ -102,4 +102,4 @@ function consumeRecord(dir, serverId) {
|
|
|
102
102
|
//#endregion
|
|
103
103
|
export { livePersistentEntries, stopPersistentEntries };
|
|
104
104
|
|
|
105
|
-
//# sourceMappingURL=nanny-sweep-
|
|
105
|
+
//# sourceMappingURL=nanny-sweep-ClVuNJRo.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nanny-sweep-
|
|
1
|
+
{"version":3,"file":"nanny-sweep-ClVuNJRo.js","names":[],"sources":["../../src/providers/nanny-sweep.ts"],"sourcesContent":["import type { NannyState, StopConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { NANNY_TRAPPED_SIGNALS, nannyChildPid, nannyIsAlive, nannySpecPath, nannyStatePath, nannyStopOptions, readNannyState, SPEC_SUFFIX } from '#src/providers/nanny'\nimport { isProcessAlive } from '#src/providers/port'\nimport { terminatePid } from '#src/providers/process'\nimport { stopSchema } from '#src/shared/contracts'\n\n/**\n * Finds and ends the persistent entries a host is running, with no panel in the loop.\n *\n * `down` leaves these alone on purpose, so `--with-persistent` is the one caller that has to\n * act on them — often after the panel is already gone. The nanny state files are the only\n * record that survives that, and they are per workspace, so every workspace is read.\n *\n * The **nanny** is what gets signalled: it traps the signal and forwards the entry's own\n * `stop` policy to the child it owns, which is what the panel's stop does. That is also why\n * this cannot go through `/_hh` — after a crash there is nothing left to ask.\n */\n\n/** One live persistent entry, as its state file describes it. */\nexport interface PersistentHandle {\n workspaceId: string\n serverId: string\n state: NannyState\n /** The workspace's `.state` directory, which owns the state file. */\n dir: string\n}\n\n/**\n * Every workspace's state directory.\n *\n * Read here rather than through `workspaceStateDir()`, which resolves from *this* process's\n * `HHOSTED_HOME`: a caller passing `--home` elsewhere would otherwise sweep another host's\n * state — the mistake `backup-offline` already paid for.\n */\nfunction stateDirs(hhDir: string): Array<{ workspaceId: string, dir: string }> {\n try {\n return fs.readdirSync(hhDir, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && !entry.name.startsWith('.'))\n .map(entry => entry.name)\n .filter(id => /^[a-z0-9][a-z0-9_-]*$/.test(id))\n .map(workspaceId => ({ workspaceId, dir: path.join(hhDir, workspaceId, '.state') }))\n }\n catch {\n return []\n }\n}\n\n/**\n * The persistent entries whose nanny is running right now.\n *\n * A `<id>.run.json` file is a *non-persistent* child's own record and carries no nanny, so it\n * is skipped by suffix — the same distinction `backup-offline` relies on. `nannyIsAlive` is\n * the identity check: a live pid alone proves nothing, since pids are reused.\n */\nexport async function livePersistentEntries(hhDir: string): Promise<PersistentHandle[]> {\n const found: PersistentHandle[] = []\n\n for (const { workspaceId, dir } of stateDirs(hhDir)) {\n let names: string[]\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n // No persistent entry was ever started in this workspace.\n continue\n }\n\n for (const name of names) {\n if (!name.endsWith('.json') || name.endsWith(SPEC_SUFFIX))\n continue\n // One file per entry, named for it: a file that disagrees with its own name is not\n // something to act on.\n const serverId = name.slice(0, -'.json'.length)\n const state = readNannyState(path.join(dir, name))\n if (state === null || state.serverId !== serverId)\n continue\n if (await nannyIsAlive(state, serverId))\n found.push({ workspaceId, serverId, state, dir })\n }\n }\n return found\n}\n\n/** What one stop did, so a survivor is reported rather than dressed up as success. */\nexport interface PersistentStop {\n handle: PersistentHandle\n stopped: boolean\n error: string | null\n}\n\n/**\n * Stops these entries and consumes the record of each one that ended.\n *\n * `stopFor` is the entry's own `stop` config, read by the caller from the workspace that\n * declares it: the grace period here has to be the one the entry asked for, or a stop that\n * was still finishing its shutdown reads as a failure and escalates to `SIGKILL`.\n */\nexport async function stopPersistentEntries(\n handles: PersistentHandle[],\n options: {\n stopFor?: (handle: PersistentHandle) => StopConfig\n /**\n * The one thing a test cannot supply: `SIGKILL` is not survivable, and a pid this process\n * may not signal (the real survivor) is a second user this host has no way to create. The\n * seam is the terminator, not the decision — everything below still runs.\n */\n terminate?: typeof terminatePid\n /** Whether the state's child pid is still the process the nanny spawned (`nannyChildPid`). */\n childPid?: typeof nannyChildPid\n } = {},\n): Promise<PersistentStop[]> {\n const results: PersistentStop[] = []\n const terminate = options.terminate ?? terminatePid\n // `.assert` returns the parsed value with the schema's defaults filled in; the plain call\n // type is `Value | errors`, which would make every field a type error to read.\n const defaultStop = stopSchema.assert({})\n\n for (const handle of handles) {\n const stop = options.stopFor?.(handle) ?? defaultStop\n const { state, dir, serverId } = handle\n const nanny = await terminate(state.nannyPid, nannyStopOptions(stop))\n\n // A nanny this process could not signal, or one that outlived `SIGKILL`, keeps its\n // record: it is the only way a later boot can find that process again.\n if (isProcessAlive(state.nannyPid)) {\n results.push({ handle, stopped: false, error: `pid ${state.nannyPid} survived the stop — its record is kept, so the next \\`up\\` can still find it` })\n continue\n }\n\n // A nanny stops its child on the graceful path. A signal it does not trap — `SIGKILL` above\n // all — ends it outright, so nothing was forwarded; and with `killGroup: false` the group\n // signal never reached the child either. The pid in the state file is then the only handle on\n // a server that would otherwise keep serving. The configured signal decides this, never the\n // terminator's own label: `SIGKILL` always reports `force-killed`, which says nothing about\n // whether the nanny had a chance to pass the stop on.\n const orphaned = state.childPid !== null && state.childPid > 0\n && !stop.killGroup\n && (!NANNY_TRAPPED_SIGNALS.has(stop.signal) || nanny === 'force-killed')\n // Only once it is known to be that child: the nanny is gone, so the pid may be recycled already.\n const child = orphaned ? await (options.childPid ?? nannyChildPid)(state) : null\n if (child !== null)\n await terminate(child, { signal: 'SIGKILL', killGroup: false, graceMs: 0 })\n\n consumeRecord(dir, serverId)\n results.push({ handle, stopped: true, error: null })\n }\n return results\n}\n\n/**\n * The record goes only once the process it names is gone: a state file kept past its process\n * is a false reattach waiting, which is what `resumePersistent` exists to prevent.\n */\nfunction consumeRecord(dir: string, serverId: string): void {\n for (const file of [nannyStatePath(dir, serverId), nannySpecPath(dir, serverId)]) {\n try {\n fs.rmSync(file, { force: true })\n }\n catch {\n // A file this process may not remove is the next boot's business, not a stop failure.\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAoCA,SAAS,UAAU,OAA4D;CAC7E,IAAI;EACF,OAAO,GAAG,YAAY,OAAO,EAAE,eAAe,KAAK,CAAC,CAAC,CAClD,QAAO,UAAS,MAAM,YAAY,KAAK,CAAC,MAAM,KAAK,WAAW,GAAG,CAAC,CAAC,CACnE,KAAI,UAAS,MAAM,IAAI,CAAC,CACxB,QAAO,OAAM,wBAAwB,KAAK,EAAE,CAAC,CAAC,CAC9C,KAAI,iBAAgB;GAAE;GAAa,KAAK,KAAK,KAAK,OAAO,aAAa,QAAQ;EAAE,EAAE;CACvF,QACM;EACJ,OAAO,CAAC;CACV;AACF;;;;;;;;AASA,eAAsB,sBAAsB,OAA4C;CACtF,MAAM,QAA4B,CAAC;CAEnC,KAAK,MAAM,EAAE,aAAa,SAAS,UAAU,KAAK,GAAG;EACnD,IAAI;EACJ,IAAI;GACF,QAAQ,GAAG,YAAY,GAAG;EAC5B,QACM;GAEJ;EACF;EAEA,KAAK,MAAM,QAAQ,OAAO;GACxB,IAAI,CAAC,KAAK,SAAS,OAAO,KAAK,KAAK,SAAA,YAAoB,GACtD;GAGF,MAAM,WAAW,KAAK,MAAM,GAAG,EAAe;GAC9C,MAAM,QAAQ,eAAe,KAAK,KAAK,KAAK,IAAI,CAAC;GACjD,IAAI,UAAU,QAAQ,MAAM,aAAa,UACvC;GACF,IAAI,MAAM,aAAa,OAAO,QAAQ,GACpC,MAAM,KAAK;IAAE;IAAa;IAAU;IAAO;GAAI,CAAC;EACpD;CACF;CACA,OAAO;AACT;;;;;;;;AAgBA,eAAsB,sBACpB,SACA,UAUI,CAAC,GACsB;CAC3B,MAAM,UAA4B,CAAC;CACnC,MAAM,YAAY,QAAQ,aAAa;CAGvC,MAAM,cAAc,WAAW,OAAO,CAAC,CAAC;CAExC,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,OAAO,QAAQ,UAAU,MAAM,KAAK;EAC1C,MAAM,EAAE,OAAO,KAAK,aAAa;EACjC,MAAM,QAAQ,MAAM,UAAU,MAAM,UAAU,iBAAiB,IAAI,CAAC;EAIpE,IAAI,eAAe,MAAM,QAAQ,GAAG;GAClC,QAAQ,KAAK;IAAE;IAAQ,SAAS;IAAO,OAAO,OAAO,MAAM,SAAS;GAA+E,CAAC;GACpJ;EACF;EAYA,MAAM,QAJW,MAAM,aAAa,QAAQ,MAAM,WAAW,KACxD,CAAC,KAAK,cACL,CAAC,sBAAsB,IAAI,KAAK,MAAM,KAAK,UAAU,kBAElC,OAAO,QAAQ,YAAY,cAAA,CAAe,KAAK,IAAI;EAC5E,IAAI,UAAU,MACZ,MAAM,UAAU,OAAO;GAAE,QAAQ;GAAW,WAAW;GAAO,SAAS;EAAE,CAAC;EAE5E,cAAc,KAAK,QAAQ;EAC3B,QAAQ,KAAK;GAAE;GAAQ,SAAS;GAAM,OAAO;EAAK,CAAC;CACrD;CACA,OAAO;AACT;;;;;AAMA,SAAS,cAAc,KAAa,UAAwB;CAC1D,KAAK,MAAM,QAAQ,CAAC,eAAe,KAAK,QAAQ,GAAG,cAAc,KAAK,QAAQ,CAAC,GAC7E,IAAI;EACF,GAAG,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;CACjC,QACM,CAEN;AAEJ"}
|
|
@@ -298,7 +298,10 @@ async function releaseDockerPort(holder, timeoutMs = 2e4) {
|
|
|
298
298
|
}
|
|
299
299
|
async function listPortHolders(port) {
|
|
300
300
|
if (process.platform === "win32") {
|
|
301
|
-
const outputs = await Promise.all(NETSTAT_LISTENER_ARGS.map((args) => execFileAsync("netstat", [...args], {
|
|
301
|
+
const outputs = await Promise.all(NETSTAT_LISTENER_ARGS.map((args) => execFileAsync("netstat", [...args], {
|
|
302
|
+
timeout: 1e4,
|
|
303
|
+
windowsHide: true
|
|
304
|
+
}).then((result) => result.stdout, () => "")));
|
|
302
305
|
return [...new Set(outputs.flatMap((output) => parseNetstatListeners(output, port)))];
|
|
303
306
|
}
|
|
304
307
|
try {
|
|
@@ -330,4 +333,4 @@ function parsePids(stdout) {
|
|
|
330
333
|
//#endregion
|
|
331
334
|
export { listPortHolders as a, processLiveness as c, killPortHolders as i, releaseDockerPort as l, isPortFree as n, port_exports as o, isProcessAlive as r, probePort as s, findDockerPortHolder as t, terminatePids as u };
|
|
332
335
|
|
|
333
|
-
//# sourceMappingURL=port-
|
|
336
|
+
//# sourceMappingURL=port-k5VBw8t9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"port-B8WBTRMk.js","names":[],"sources":["../../src/providers/port.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport net from 'node:net'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/** True when something accepts TCP connections on host:port. */\nexport function probePort(host: string, port: number, timeoutMs = 1500): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = net.connect({ host, port })\n const done = (result: boolean): void => {\n socket.removeAllListeners()\n socket.destroy()\n resolve(result)\n }\n socket.setTimeout(timeoutMs)\n socket.once('connect', () => done(true))\n socket.once('timeout', () => done(false))\n socket.once('error', () => done(false))\n })\n}\n\n/** A port is free when nothing is listening on it (loopback is enough to detect conflicts). */\nexport async function isPortFree(port: number, host = '127.0.0.1', timeoutMs = 1000): Promise<boolean> {\n return !(await probePort(host, port, timeoutMs))\n}\n\n/**\n * Kills whatever holds the port, minus `exclude` (the panel's own process tree).\n * Only used as a last resort for wrappers that spawn their real server detached,\n * where a process-group signal cannot reach it.\n */\nexport async function killPortHolders(port: number, exclude?: ReadonlySet<number>): Promise<number[]> {\n const pids = (await listPortHolders(port)).filter(pid => !exclude?.has(pid))\n for (const pid of pids) {\n try {\n process.kill(pid, 'SIGKILL')\n }\n catch {\n // already gone\n }\n }\n return pids\n}\n\n/**\n * Signal 0 asks the OS whether the pid still exists, without touching it.\n *\n * `EPERM` means the process is there but is **not ours to signal** — a port holder owned by another\n * user is exactly that. Returning `false` for it made `nannyIsAlive` report a live nanny as gone, so\n * `resumePersistent` consumed its state file and started a second copy of the entry while the first ran\n * on untracked. `helpers/daemon.ts` already had this right; the two predicates now agree.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n }\n catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/** Linux jiffies per second: the near-universal default, since `/proc` needs no `getconf`. */\nconst LINUX_HZ = 100\n\n/** When a process started, and whether it has exited but is not reaped yet. */\nexport interface ProcessBirth {\n /** Epoch ms the process started, as the OS reports it. */\n startMs: number\n /** A zombie: exited, still answering signal 0, and nobody's to signal. */\n zombie: boolean\n}\n\n/**\n * `/proc/<pid>/stat` field 22 is the start time in clock ticks since boot, which only\n * becomes an epoch by adding `btime` from `/proc/stat`. Field 3 is the state.\n *\n * The comm field is parenthesised and may itself hold spaces and parentheses, so the\n * fields are counted from after the **last** `)`. Counting from the first would shift\n * every offset for a process whose name contains a `)`, and this value decides whether a\n * live-looking pid is really the daemon.\n */\nexport function parseProcBirth(content: string, btimeSeconds: number, hz = LINUX_HZ): ProcessBirth | null {\n const close = content.lastIndexOf(')')\n if (close < 0)\n return null\n const fields = content.slice(close + 2).split(' ')\n const ticks = Number.parseInt(fields[19] ?? '', 10)\n if (!Number.isFinite(ticks) || ticks < 0)\n return null\n return { startMs: btimeSeconds * 1000 + (ticks / hz) * 1000, zombie: fields[0] === 'Z' }\n}\n\n/**\n * One `ps -o state=,lstart=` row, e.g. `S Wed Oct 7 19:43:26 2026` (macOS, other POSIX).\n * The leading weekday is stripped before parsing: `Date.parse` is not obliged to accept it\n * and it says nothing the date does not.\n */\nexport function parsePsBirth(output: string): ProcessBirth | null {\n const line = output.trim().split('\\n')[0]?.trim() ?? ''\n if (line.length === 0)\n return null\n const [state = '', ...rest] = line.split(/\\s+/)\n const startMs = Date.parse(rest.join(' ').replace(/^[A-Z]{3,9}\\s+/i, ''))\n if (!Number.isFinite(startMs))\n return null\n return { startMs, zombie: state.startsWith('Z') }\n}\n\n/** 100ns ticks between the FILETIME epoch (1601) and the Unix epoch (1970). */\nconst FILETIME_UNIX_OFFSET_MS = 11644473600000\n\n/**\n * FILETIME ticks (100ns since **1601**, UTC) to a Unix epoch in ms — the shape\n * `DateTime.ToFileTimeUtc()` returns.\n *\n * The epoch matters: `DateTime.Ticks` counts from **0001**, not 1601, and the two differ by\n * 1600 years. Reading the wrong one put every Windows panel ~1600 years in the future, which\n * `processLiveness` then called `recycled` — a live panel that could never signal-stop itself.\n * The PowerShell call below therefore asks for `ToFileTimeUtc()` explicitly, and this is exported\n * so the conversion is pinned by a test.\n */\nexport function parseFiletime(ticks: number): number | null {\n if (!Number.isFinite(ticks) || ticks <= 0)\n return null\n return ticks / 1e4 - FILETIME_UNIX_OFFSET_MS\n}\n\n/**\n * When the pid started, from the platform's own process table. `null` when the platform\n * cannot say — an unreadable `/proc`, no `ps`, or no PowerShell — which the caller must\n * read as \"unknown\", never as \"gone\".\n */\nexport async function processBirth(pid: number): Promise<ProcessBirth | null> {\n if (!Number.isInteger(pid) || pid <= 0)\n return null\n\n if (process.platform === 'linux') {\n try {\n const [stat, system] = await Promise.all([\n fs.promises.readFile(`/proc/${pid}/stat`, 'utf8'),\n fs.promises.readFile('/proc/stat', 'utf8'),\n ])\n const btime = /^btime (\\d+)$/m.exec(system)?.[1]\n if (btime === undefined)\n return null\n return parseProcBirth(stat, Number.parseInt(btime, 10))\n }\n catch {\n return null\n }\n }\n\n if (process.platform === 'win32') {\n try {\n // `ToFileTimeUtc()`, not `.Ticks`: the latter is 100ns since 0001 and would be read as\n // ~1600 years in the future. ToFileTimeUtc normalizes to UTC and the 1601 epoch, which is\n // what `parseFiletime` expects.\n const script = `$p = Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\"; if ($p) { $p.CreationDate.ToFileTimeUtc() }`\n const { stdout } = await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 20000, windowsHide: true })\n const startMs = parseFiletime(Number.parseFloat(stdout.trim()))\n return startMs === null ? null : { startMs, zombie: false }\n }\n catch {\n return null\n }\n }\n\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'state=,lstart='], { timeout: 3000 })\n return parsePsBirth(stdout)\n }\n catch {\n return null\n }\n}\n\n/** Is the process at `pid` the one a record stamped `startedAt` describes? */\nexport type ProcessLiveness\n /** Alive, and born when the record implies. */\n = | 'live'\n /** Nothing is running behind the pid: absent, or a zombie nobody has reaped. */\n | 'gone'\n /** A live pid, but born *after* the record was written — the OS recycled it. */\n | 'recycled'\n /** The platform would not report a birth time, so the live pid is all there is to go on. */\n | 'unknown'\n\n/**\n * A pid is **not** an identity. The OS hands a dead process's pid to an unrelated one later, and a\n * zombie — exited but not yet reaped by its parent — still answers signal 0. So `isProcessAlive`\n * alone can report a long-dead daemon as live, which is what let `up` say \"already running\" and\n * `status` say \"running, but not answering\" against a stale `run.json`, and what let `down` signal\n * whatever stranger had inherited the pid.\n *\n * `startedAt` settles it in one direction, with no threshold to guess at: the daemon writes its\n * record *during its own boot*, so its process is necessarily born **before** that stamp. A pid born\n * after it is not that process, whoever else it now is. The comparison is deliberately one-sided —\n * the other direction would have to tell a recycled pid from a wall clock that merely moved, and it\n * cannot, so a record is never called stale for being *older* than its process.\n *\n * `'unknown'` is not `'gone'`: a platform that cannot report a birth time must not have its live pid\n * dismissed, or a running panel's record would be cleared out from under it.\n */\nexport async function processLiveness(\n pid: number,\n startedAt: number,\n options: { toleranceMs?: number, readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {},\n): Promise<ProcessLiveness> {\n if (!isProcessAlive(pid))\n return 'gone'\n\n const birth = await (options.readBirth ?? processBirth)(pid)\n if (birth === null)\n return 'unknown'\n if (birth.zombie)\n return 'gone'\n\n // The tolerance absorbs the one-second granularity of `ps -o lstart=`, which can report a\n // process as born a fraction *after* `startedAt` even though it really started before it.\n return birth.startMs > startedAt + (options.toleranceMs ?? 2000) ? 'recycled' : 'live'\n}\n\nfunction signalPid(pid: number, name: NodeJS.Signals): void {\n try {\n process.kill(pid, name)\n }\n catch {\n // already gone, or not ours to signal\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\n/**\n * Asks specific pids to leave, politely first: a stray dev server stops on\n * SIGTERM, and only what ignores it is killed. Deciding *which* pids may be\n * touched belongs to the caller — this only does the signalling.\n */\nexport async function terminatePids(\n pids: number[],\n options: { graceMs?: number } = {},\n): Promise<{ stopped: number[], forced: number[] }> {\n const graceMs = options.graceMs ?? 3000\n const targets = [...new Set(pids)]\n // Only what was actually there is claimed as stopped; a pid that had already\n // exited is neither ours to report nor ours to kill.\n const aliveBefore = targets.filter(isProcessAlive)\n\n for (const pid of aliveBefore) signalPid(pid, 'SIGTERM')\n\n const deadline = Date.now() + graceMs\n let alive = aliveBefore.filter(isProcessAlive)\n while (alive.length > 0 && Date.now() < deadline) {\n await delay(100)\n alive = alive.filter(isProcessAlive)\n }\n\n const stopped = aliveBefore.filter(pid => !alive.includes(pid))\n for (const pid of alive) signalPid(pid, 'SIGKILL')\n if (alive.length > 0 && graceMs > 0)\n await delay(150)\n\n return { stopped, forced: alive }\n}\n\n/**\n * One filtered `netstat` per family. `-p TCP` alone lists IPv4 only, while Node's default `listen()`\n * binds `[::]`; an unfiltered `-ano` lists every connection and UDP socket, which is slow enough on a\n * busy machine to hit the lookup's timeout — and a timeout reads as \"nothing holds the port\".\n */\nexport const NETSTAT_LISTENER_ARGS: ReadonlyArray<readonly string[]> = [['-ano', '-p', 'TCP'], ['-ano', '-p', 'TCPv6']]\n\n/** `netstat -ano` lines: ` TCP 127.0.0.1:4010 0.0.0.0:0 LISTENING 1234`; UDP rows are skipped. */\nexport function parseNetstatListeners(output: string, port: number): number[] {\n const pids = new Set<number>()\n\n for (const line of output.split(/\\r?\\n/)) {\n const cells = line.trim().split(/\\s+/)\n if (cells.length < 5)\n continue\n if ((cells[0] ?? '').toUpperCase() !== 'TCP')\n continue\n const local = cells[1] ?? ''\n const state = cells[3] ?? ''\n const pid = Number.parseInt(cells[4] ?? '', 10)\n const localPort = Number.parseInt(local.slice(local.lastIndexOf(':') + 1), 10)\n if (state.toUpperCase() !== 'LISTENING' || localPort !== port)\n continue\n if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)\n pids.add(pid)\n }\n\n return [...pids]\n}\n\n/**\n * The container publishing a host port, when docker is holding it.\n *\n * A published port is bound by `docker-proxy`, which runs as **root** — so `lsof`/`fuser` return\n * nothing for it, and `listPortHolders` reports an empty list for a port that is plainly refusing\n * every bind. Docker itself answers the question without privileges, and names the stack too, so\n * the caller can say *whose* stack it is instead of \"nothing is listening\".\n */\nexport interface DockerPortHolder {\n /** `com.docker.compose.project.working_dir` when the container came from compose. */\n composeDir: string | null\n /** `com.docker.compose.project`, so a caller can tell this entry's own stack from a stranger's. */\n project: string | null\n container: string\n port: number\n}\n\nexport async function findDockerPortHolder(port: number): Promise<DockerPortHolder | null> {\n try {\n const { stdout } = await execFileAsync('docker', [\n 'ps',\n '--filter',\n `publish=${port}`,\n '--format',\n '{{.Names}}\\t{{.Label \"com.docker.compose.project\"}}\\t{{.Label \"com.docker.compose.project.working_dir\"}}',\n ], { timeout: 3000 })\n const line = stdout.split('\\n').find(entry => entry.trim().length > 0)\n if (line === undefined)\n return null\n const [container = '', project = '', composeDir = ''] = line.split('\\t')\n if (container.trim().length === 0)\n return null\n return {\n container: container.trim(),\n project: project.trim().length > 0 ? project.trim() : null,\n composeDir: composeDir.trim().length > 0 ? composeDir.trim() : null,\n port,\n }\n }\n catch {\n // docker absent, not running, or not permissioned: no claim either way.\n return null\n }\n}\n\n/**\n * Stops the container publishing a host port, which is how docker's port is freed.\n *\n * The socket belongs to a root-owned `docker-proxy`, so there is no pid this process may signal —\n * but the container is the panel's to stop through docker itself, which needs no privileges\n * beyond the socket the user already has. `docker stop` releases the published port and leaves the\n * stack's other services alone.\n */\nexport async function releaseDockerPort(holder: DockerPortHolder, timeoutMs = 20000): Promise<boolean> {\n try {\n await execFileAsync('docker', ['stop', holder.container], { timeout: timeoutMs })\n return true\n }\n catch {\n return false\n }\n}\n\nexport async function listPortHolders(port: number): Promise<number[]> {\n if (process.platform === 'win32') {\n const outputs = await Promise.all(NETSTAT_LISTENER_ARGS.map(args =>\n execFileAsync('netstat', [...args], { timeout: 10000 }).then(result => result.stdout, () => '')))\n return [...new Set(outputs.flatMap(output => parseNetstatListeners(output, port)))]\n }\n\n try {\n const { stdout } = await execFileAsync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], { timeout: 3000 })\n return parsePids(stdout)\n }\n catch {\n // lsof missing or nothing listening\n }\n\n try {\n const { stdout } = await execFileAsync('fuser', [`${port}/tcp`], { timeout: 3000 })\n return parsePids(stdout)\n }\n catch {\n return []\n }\n}\n\n/**\n * Pids from `lsof -ti` (one per line) or `fuser` (space-separated, on one line, with a leading\n * space) — both shapes arrive here, which is why the split is on `\\s+` rather than `\\n`.\n *\n * Exported for its test: this feeds `killPortHolders`, which sends SIGKILL, so a parser that\n * picked up the wrong number would kill an unrelated process. The filter is not decorative —\n * `Number.parseInt('')` is NaN for the empty leading cell, and a pid of 0 or our own is dropped.\n */\nexport function parsePids(stdout: string): number[] {\n return [...new Set(\n stdout.split(/\\s+/)\n .map(entry => Number.parseInt(entry, 10))\n .filter(pid => Number.isInteger(pid) && pid > 0 && pid !== process.pid),\n )]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAM,gBAAgB,UAAU,QAAQ;;AAGxC,SAAgB,UAAU,MAAc,MAAc,YAAY,MAAwB;CACxF,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAS,IAAI,QAAQ;GAAE;GAAM;EAAK,CAAC;EACzC,MAAM,QAAQ,WAA0B;GACtC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Q,QAAQ,GAAG,CAC1E,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"port-k5VBw8t9.js","names":[],"sources":["../../src/providers/port.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport net from 'node:net'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/** True when something accepts TCP connections on host:port. */\nexport function probePort(host: string, port: number, timeoutMs = 1500): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = net.connect({ host, port })\n const done = (result: boolean): void => {\n socket.removeAllListeners()\n socket.destroy()\n resolve(result)\n }\n socket.setTimeout(timeoutMs)\n socket.once('connect', () => done(true))\n socket.once('timeout', () => done(false))\n socket.once('error', () => done(false))\n })\n}\n\n/** A port is free when nothing is listening on it (loopback is enough to detect conflicts). */\nexport async function isPortFree(port: number, host = '127.0.0.1', timeoutMs = 1000): Promise<boolean> {\n return !(await probePort(host, port, timeoutMs))\n}\n\n/**\n * Kills whatever holds the port, minus `exclude` (the panel's own process tree).\n * Only used as a last resort for wrappers that spawn their real server detached,\n * where a process-group signal cannot reach it.\n */\nexport async function killPortHolders(port: number, exclude?: ReadonlySet<number>): Promise<number[]> {\n const pids = (await listPortHolders(port)).filter(pid => !exclude?.has(pid))\n for (const pid of pids) {\n try {\n process.kill(pid, 'SIGKILL')\n }\n catch {\n // already gone\n }\n }\n return pids\n}\n\n/**\n * Signal 0 asks the OS whether the pid still exists, without touching it.\n *\n * `EPERM` means the process is there but is **not ours to signal** — a port holder owned by another\n * user is exactly that. Returning `false` for it made `nannyIsAlive` report a live nanny as gone, so\n * `resumePersistent` consumed its state file and started a second copy of the entry while the first ran\n * on untracked. `helpers/daemon.ts` already had this right; the two predicates now agree.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n }\n catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/** Linux jiffies per second: the near-universal default, since `/proc` needs no `getconf`. */\nconst LINUX_HZ = 100\n\n/** When a process started, and whether it has exited but is not reaped yet. */\nexport interface ProcessBirth {\n /** Epoch ms the process started, as the OS reports it. */\n startMs: number\n /** A zombie: exited, still answering signal 0, and nobody's to signal. */\n zombie: boolean\n}\n\n/**\n * `/proc/<pid>/stat` field 22 is the start time in clock ticks since boot, which only\n * becomes an epoch by adding `btime` from `/proc/stat`. Field 3 is the state.\n *\n * The comm field is parenthesised and may itself hold spaces and parentheses, so the\n * fields are counted from after the **last** `)`. Counting from the first would shift\n * every offset for a process whose name contains a `)`, and this value decides whether a\n * live-looking pid is really the daemon.\n */\nexport function parseProcBirth(content: string, btimeSeconds: number, hz = LINUX_HZ): ProcessBirth | null {\n const close = content.lastIndexOf(')')\n if (close < 0)\n return null\n const fields = content.slice(close + 2).split(' ')\n const ticks = Number.parseInt(fields[19] ?? '', 10)\n if (!Number.isFinite(ticks) || ticks < 0)\n return null\n return { startMs: btimeSeconds * 1000 + (ticks / hz) * 1000, zombie: fields[0] === 'Z' }\n}\n\n/**\n * One `ps -o state=,lstart=` row, e.g. `S Wed Oct 7 19:43:26 2026` (macOS, other POSIX).\n * The leading weekday is stripped before parsing: `Date.parse` is not obliged to accept it\n * and it says nothing the date does not.\n */\nexport function parsePsBirth(output: string): ProcessBirth | null {\n const line = output.trim().split('\\n')[0]?.trim() ?? ''\n if (line.length === 0)\n return null\n const [state = '', ...rest] = line.split(/\\s+/)\n const startMs = Date.parse(rest.join(' ').replace(/^[A-Z]{3,9}\\s+/i, ''))\n if (!Number.isFinite(startMs))\n return null\n return { startMs, zombie: state.startsWith('Z') }\n}\n\n/** 100ns ticks between the FILETIME epoch (1601) and the Unix epoch (1970). */\nconst FILETIME_UNIX_OFFSET_MS = 11644473600000\n\n/**\n * FILETIME ticks (100ns since **1601**, UTC) to a Unix epoch in ms — the shape\n * `DateTime.ToFileTimeUtc()` returns.\n *\n * The epoch matters: `DateTime.Ticks` counts from **0001**, not 1601, and the two differ by\n * 1600 years. Reading the wrong one put every Windows panel ~1600 years in the future, which\n * `processLiveness` then called `recycled` — a live panel that could never signal-stop itself.\n * The PowerShell call below therefore asks for `ToFileTimeUtc()` explicitly, and this is exported\n * so the conversion is pinned by a test.\n */\nexport function parseFiletime(ticks: number): number | null {\n if (!Number.isFinite(ticks) || ticks <= 0)\n return null\n return ticks / 1e4 - FILETIME_UNIX_OFFSET_MS\n}\n\n/**\n * When the pid started, from the platform's own process table. `null` when the platform\n * cannot say — an unreadable `/proc`, no `ps`, or no PowerShell — which the caller must\n * read as \"unknown\", never as \"gone\".\n */\nexport async function processBirth(pid: number): Promise<ProcessBirth | null> {\n if (!Number.isInteger(pid) || pid <= 0)\n return null\n\n if (process.platform === 'linux') {\n try {\n const [stat, system] = await Promise.all([\n fs.promises.readFile(`/proc/${pid}/stat`, 'utf8'),\n fs.promises.readFile('/proc/stat', 'utf8'),\n ])\n const btime = /^btime (\\d+)$/m.exec(system)?.[1]\n if (btime === undefined)\n return null\n return parseProcBirth(stat, Number.parseInt(btime, 10))\n }\n catch {\n return null\n }\n }\n\n if (process.platform === 'win32') {\n try {\n // `ToFileTimeUtc()`, not `.Ticks`: the latter is 100ns since 0001 and would be read as\n // ~1600 years in the future. ToFileTimeUtc normalizes to UTC and the 1601 epoch, which is\n // what `parseFiletime` expects.\n const script = `$p = Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\"; if ($p) { $p.CreationDate.ToFileTimeUtc() }`\n const { stdout } = await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 20000, windowsHide: true })\n const startMs = parseFiletime(Number.parseFloat(stdout.trim()))\n return startMs === null ? null : { startMs, zombie: false }\n }\n catch {\n return null\n }\n }\n\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'state=,lstart='], { timeout: 3000 })\n return parsePsBirth(stdout)\n }\n catch {\n return null\n }\n}\n\n/** Is the process at `pid` the one a record stamped `startedAt` describes? */\nexport type ProcessLiveness\n /** Alive, and born when the record implies. */\n = | 'live'\n /** Nothing is running behind the pid: absent, or a zombie nobody has reaped. */\n | 'gone'\n /** A live pid, but born *after* the record was written — the OS recycled it. */\n | 'recycled'\n /** The platform would not report a birth time, so the live pid is all there is to go on. */\n | 'unknown'\n\n/**\n * A pid is **not** an identity. The OS hands a dead process's pid to an unrelated one later, and a\n * zombie — exited but not yet reaped by its parent — still answers signal 0. So `isProcessAlive`\n * alone can report a long-dead daemon as live, which is what let `up` say \"already running\" and\n * `status` say \"running, but not answering\" against a stale `run.json`, and what let `down` signal\n * whatever stranger had inherited the pid.\n *\n * `startedAt` settles it in one direction, with no threshold to guess at: the daemon writes its\n * record *during its own boot*, so its process is necessarily born **before** that stamp. A pid born\n * after it is not that process, whoever else it now is. The comparison is deliberately one-sided —\n * the other direction would have to tell a recycled pid from a wall clock that merely moved, and it\n * cannot, so a record is never called stale for being *older* than its process.\n *\n * `'unknown'` is not `'gone'`: a platform that cannot report a birth time must not have its live pid\n * dismissed, or a running panel's record would be cleared out from under it.\n */\nexport async function processLiveness(\n pid: number,\n startedAt: number,\n options: { toleranceMs?: number, readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {},\n): Promise<ProcessLiveness> {\n if (!isProcessAlive(pid))\n return 'gone'\n\n const birth = await (options.readBirth ?? processBirth)(pid)\n if (birth === null)\n return 'unknown'\n if (birth.zombie)\n return 'gone'\n\n // The tolerance absorbs the one-second granularity of `ps -o lstart=`, which can report a\n // process as born a fraction *after* `startedAt` even though it really started before it.\n return birth.startMs > startedAt + (options.toleranceMs ?? 2000) ? 'recycled' : 'live'\n}\n\nfunction signalPid(pid: number, name: NodeJS.Signals): void {\n try {\n process.kill(pid, name)\n }\n catch {\n // already gone, or not ours to signal\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\n/**\n * Asks specific pids to leave, politely first: a stray dev server stops on\n * SIGTERM, and only what ignores it is killed. Deciding *which* pids may be\n * touched belongs to the caller — this only does the signalling.\n */\nexport async function terminatePids(\n pids: number[],\n options: { graceMs?: number } = {},\n): Promise<{ stopped: number[], forced: number[] }> {\n const graceMs = options.graceMs ?? 3000\n const targets = [...new Set(pids)]\n // Only what was actually there is claimed as stopped; a pid that had already\n // exited is neither ours to report nor ours to kill.\n const aliveBefore = targets.filter(isProcessAlive)\n\n for (const pid of aliveBefore) signalPid(pid, 'SIGTERM')\n\n const deadline = Date.now() + graceMs\n let alive = aliveBefore.filter(isProcessAlive)\n while (alive.length > 0 && Date.now() < deadline) {\n await delay(100)\n alive = alive.filter(isProcessAlive)\n }\n\n const stopped = aliveBefore.filter(pid => !alive.includes(pid))\n for (const pid of alive) signalPid(pid, 'SIGKILL')\n if (alive.length > 0 && graceMs > 0)\n await delay(150)\n\n return { stopped, forced: alive }\n}\n\n/**\n * One filtered `netstat` per family. `-p TCP` alone lists IPv4 only, while Node's default `listen()`\n * binds `[::]`; an unfiltered `-ano` lists every connection and UDP socket, which is slow enough on a\n * busy machine to hit the lookup's timeout — and a timeout reads as \"nothing holds the port\".\n */\nexport const NETSTAT_LISTENER_ARGS: ReadonlyArray<readonly string[]> = [['-ano', '-p', 'TCP'], ['-ano', '-p', 'TCPv6']]\n\n/** `netstat -ano` lines: ` TCP 127.0.0.1:4010 0.0.0.0:0 LISTENING 1234`; UDP rows are skipped. */\nexport function parseNetstatListeners(output: string, port: number): number[] {\n const pids = new Set<number>()\n\n for (const line of output.split(/\\r?\\n/)) {\n const cells = line.trim().split(/\\s+/)\n if (cells.length < 5)\n continue\n if ((cells[0] ?? '').toUpperCase() !== 'TCP')\n continue\n const local = cells[1] ?? ''\n const state = cells[3] ?? ''\n const pid = Number.parseInt(cells[4] ?? '', 10)\n const localPort = Number.parseInt(local.slice(local.lastIndexOf(':') + 1), 10)\n if (state.toUpperCase() !== 'LISTENING' || localPort !== port)\n continue\n if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)\n pids.add(pid)\n }\n\n return [...pids]\n}\n\n/**\n * The container publishing a host port, when docker is holding it.\n *\n * A published port is bound by `docker-proxy`, which runs as **root** — so `lsof`/`fuser` return\n * nothing for it, and `listPortHolders` reports an empty list for a port that is plainly refusing\n * every bind. Docker itself answers the question without privileges, and names the stack too, so\n * the caller can say *whose* stack it is instead of \"nothing is listening\".\n */\nexport interface DockerPortHolder {\n /** `com.docker.compose.project.working_dir` when the container came from compose. */\n composeDir: string | null\n /** `com.docker.compose.project`, so a caller can tell this entry's own stack from a stranger's. */\n project: string | null\n container: string\n port: number\n}\n\nexport async function findDockerPortHolder(port: number): Promise<DockerPortHolder | null> {\n try {\n const { stdout } = await execFileAsync('docker', [\n 'ps',\n '--filter',\n `publish=${port}`,\n '--format',\n '{{.Names}}\\t{{.Label \"com.docker.compose.project\"}}\\t{{.Label \"com.docker.compose.project.working_dir\"}}',\n ], { timeout: 3000 })\n const line = stdout.split('\\n').find(entry => entry.trim().length > 0)\n if (line === undefined)\n return null\n const [container = '', project = '', composeDir = ''] = line.split('\\t')\n if (container.trim().length === 0)\n return null\n return {\n container: container.trim(),\n project: project.trim().length > 0 ? project.trim() : null,\n composeDir: composeDir.trim().length > 0 ? composeDir.trim() : null,\n port,\n }\n }\n catch {\n // docker absent, not running, or not permissioned: no claim either way.\n return null\n }\n}\n\n/**\n * Stops the container publishing a host port, which is how docker's port is freed.\n *\n * The socket belongs to a root-owned `docker-proxy`, so there is no pid this process may signal —\n * but the container is the panel's to stop through docker itself, which needs no privileges\n * beyond the socket the user already has. `docker stop` releases the published port and leaves the\n * stack's other services alone.\n */\nexport async function releaseDockerPort(holder: DockerPortHolder, timeoutMs = 20000): Promise<boolean> {\n try {\n await execFileAsync('docker', ['stop', holder.container], { timeout: timeoutMs })\n return true\n }\n catch {\n return false\n }\n}\n\nexport async function listPortHolders(port: number): Promise<number[]> {\n if (process.platform === 'win32') {\n const outputs = await Promise.all(NETSTAT_LISTENER_ARGS.map(args =>\n execFileAsync('netstat', [...args], { timeout: 10000, windowsHide: true }).then(result => result.stdout, () => '')))\n return [...new Set(outputs.flatMap(output => parseNetstatListeners(output, port)))]\n }\n\n try {\n const { stdout } = await execFileAsync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], { timeout: 3000 })\n return parsePids(stdout)\n }\n catch {\n // lsof missing or nothing listening\n }\n\n try {\n const { stdout } = await execFileAsync('fuser', [`${port}/tcp`], { timeout: 3000 })\n return parsePids(stdout)\n }\n catch {\n return []\n }\n}\n\n/**\n * Pids from `lsof -ti` (one per line) or `fuser` (space-separated, on one line, with a leading\n * space) — both shapes arrive here, which is why the split is on `\\s+` rather than `\\n`.\n *\n * Exported for its test: this feeds `killPortHolders`, which sends SIGKILL, so a parser that\n * picked up the wrong number would kill an unrelated process. The filter is not decorative —\n * `Number.parseInt('')` is NaN for the empty leading cell, and a pid of 0 or our own is dropped.\n */\nexport function parsePids(stdout: string): number[] {\n return [...new Set(\n stdout.split(/\\s+/)\n .map(entry => Number.parseInt(entry, 10))\n .filter(pid => Number.isInteger(pid) && pid > 0 && pid !== process.pid),\n )]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAM,gBAAgB,UAAU,QAAQ;;AAGxC,SAAgB,UAAU,MAAc,MAAc,YAAY,MAAwB;CACxF,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAS,IAAI,QAAQ;GAAE;GAAM;EAAK,CAAC;EACzC,MAAM,QAAQ,WAA0B;GACtC,OAAO,mBAAmB;GAC1B,OAAO,QAAQ;GACf,QAAQ,MAAM;EAChB;EACA,OAAO,WAAW,SAAS;EAC3B,OAAO,KAAK,iBAAiB,KAAK,IAAI,CAAC;EACvC,OAAO,KAAK,iBAAiB,KAAK,KAAK,CAAC;EACxC,OAAO,KAAK,eAAe,KAAK,KAAK,CAAC;CACxC,CAAC;AACH;;AAGA,eAAsB,WAAW,MAAc,OAAO,aAAa,YAAY,KAAwB;CACrG,OAAO,CAAE,MAAM,UAAU,MAAM,MAAM,SAAS;AAChD;;;;;;AAOA,eAAsB,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;AACF;AAEA,eAAsB,gBAAgB,MAAiC;CACrE,IAAI,QAAQ,aAAa,SAAS;EAChC,MAAM,UAAU,MAAM,QAAQ,IAAI,sBAAsB,KAAI,SAC1D,cAAc,WAAW,CAAC,GAAG,IAAI,GAAG;GAAE,SAAS;GAAO,aAAa;EAAK,CAAC,CAAC,CAAC,MAAK,WAAU,OAAO,cAAc,EAAE,CAAC,CAAC;EACrH,OAAO,CAAC,GAAG,IAAI,IAAI,QAAQ,SAAQ,WAAU,sBAAsB,QAAQ,IAAI,CAAC,CAAC,CAAC;CACpF;CAEA,IAAI;EACF,MAAM,EAAE,WAAW,MAAM,cAAc,QAAQ;GAAC;GAAO,OAAO;GAAQ;EAAc,GAAG,EAAE,SAAS,IAAK,CAAC;EACxG,OAAO,UAAU,MAAM;CACzB,QACM,CAEN;CAEA,IAAI;EACF,MAAM,EAAE,WAAW,MAAM,cAAc,SAAS,CAAC,GAAG,KAAK,KAAK,GAAG,EAAE,SAAS,IAAK,CAAC;EAClF,OAAO,UAAU,MAAM;CACzB,QACM;EACJ,OAAO,CAAC;CACV;AACF;;;;;;;;;AAUA,SAAgB,UAAU,QAA0B;CAClD,OAAO,CAAC,GAAG,IAAI,IACb,OAAO,MAAM,KAAK,CAAC,CAChB,KAAI,UAAS,OAAO,SAAS,OAAO,EAAE,CAAC,CAAC,CACxC,QAAO,QAAO,OAAO,UAAU,GAAG,KAAK,MAAM,KAAK,QAAQ,QAAQ,GAAG,CAC1E,CAAC;AACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { f as fail, g as paint, h as invocation } from "../cli.js";
|
|
2
|
-
import { runDown } from "./down-
|
|
3
|
-
import { runServerAction } from "./server-
|
|
4
|
-
import { checkedUpFlags, runUp, upArgs } from "./up-
|
|
2
|
+
import { runDown } from "./down-C59ne5aM.js";
|
|
3
|
+
import { runServerAction } from "./server-By-zktjx.js";
|
|
4
|
+
import { checkedUpFlags, runUp, upArgs } from "./up-DNZuTi2q.js";
|
|
5
5
|
import process from "node:process";
|
|
6
6
|
import { defineCommand } from "citty";
|
|
7
7
|
//#region src/cli/restart.ts
|
|
@@ -76,7 +76,7 @@ function restartCommand(entry) {
|
|
|
76
76
|
* entries with `autostart: false`, the reason this exists, would never come back otherwise.
|
|
77
77
|
*/
|
|
78
78
|
async function startPersistentBack(stopped) {
|
|
79
|
-
const { readRuntime, requestControl } = await import("./daemon-
|
|
79
|
+
const { readRuntime, requestControl } = await import("./daemon-CofN9k6Q.js");
|
|
80
80
|
const runtime = readRuntime();
|
|
81
81
|
if (runtime === null) return;
|
|
82
82
|
for (const { workspaceId, serverId } of stopped) {
|
|
@@ -89,4 +89,4 @@ async function startPersistentBack(stopped) {
|
|
|
89
89
|
//#endregion
|
|
90
90
|
export { restartCommand };
|
|
91
91
|
|
|
92
|
-
//# sourceMappingURL=restart-
|
|
92
|
+
//# sourceMappingURL=restart-BYu_E7x5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"restart-
|
|
1
|
+
{"version":3,"file":"restart-BYu_E7x5.js","names":[],"sources":["../../src/cli/restart.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { runDown } from '#src/cli/down'\nimport { fail, invocation, paint } from '#src/cli/io'\nimport { runServerAction } from '#src/cli/server'\nimport { checkedUpFlags, runUp, upArgs } from '#src/cli/up'\n\n/**\n * `restart` restarts the panel (`down`, then `up`) — or, given a server id, just that entry.\n *\n * The id is optional on purpose. `restart` already meant the panel, and it still does when\n * called the way it always was; adding a positional would have been a hard error before this\n * (\"Unexpected argument 'web'\"), so nothing existing changes meaning. The per-server case is\n * what the UI's Restart button has always done and the shell could not.\n */\n\n/**\n * The `up` flags that mean nothing to `restart <id>`, as citty parses them.\n *\n * The bare form forwards all of them — `restart --print-config` is a real, tested use. The id form\n * asks the panel to restart one entry over `/_hh` and never runs `down` or `up`, so a panel-level\n * flag has nothing to act on: `restart web --port 5000` used to report \"restarted web\" having\n * changed no port. `upArgs` declares no defaults, so a flag that was not given is `undefined`.\n */\nconst PANEL_ONLY_FLAGS = [\n ['port', '--port'],\n ['host', '--host'],\n ['autostart', '--no-autostart'],\n ['open', '--open'],\n ['foreground', '--foreground'],\n ['printConfig', '--print-config'],\n] as const\n\nexport function restartCommand(entry: string) {\n return defineCommand({\n meta: { name: 'restart' },\n args: {\n ...upArgs,\n // `down`'s own flag, so the two commands cannot drift about what it means. Declared\n // here as well because citty reads one command's definitions, not two.\n withPersistent: { type: 'boolean', description: 'stop the persistent entries too, instead of leaving them running' },\n // Declared here rather than in `server.ts` because only `restart` takes it bare: for\n // `start`/`stop` the id is required, and citty's refusal is replaced by our own message.\n id: { type: 'positional', required: false, description: 'restart just this server instead of the panel' },\n workspace: { type: 'string', alias: 'w', description: 'the workspace to act in (default: the panel\\'s default workspace)' },\n },\n run: async ({ args }) => {\n const id = typeof args.id === 'string' ? args.id.trim() : ''\n\n if (id.length > 0) {\n // One entry, so the panel stays up. A bare `restart` would have taken the whole\n // panel — and every other server — down with it.\n if (args.withPersistent === true)\n fail('restart <id> restarts one server — drop --with-persistent, or use it on a bare `restart`')\n const panelFlag = PANEL_ONLY_FLAGS.find(([key]) => args[key] !== undefined)\n if (panelFlag !== undefined)\n fail(`restart <id> restarts one server and takes no panel option — drop ${panelFlag[1]}, or use it on a bare \\`restart\\``)\n const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : undefined\n await runServerAction('restart', id, workspace)\n return\n }\n\n // The panel's own restart takes no `--workspace`: it is not a per-server idea.\n if (args.workspace !== undefined)\n fail(`restart --workspace needs a server id — \\`${invocation()} restart <id> --workspace <id>\\``)\n\n // `--with-persistent` restarts them, it does not merely stop them. `up` would *reattach*\n // to a nanny left alive, so stopping them first is what makes this a restart at all —\n // and a stopped entry is only started back by `up`'s autostart pass, which an entry with\n // `autostart: false` is not in. Those are therefore started back explicitly.\n //\n // Every `up` flag is checked before anything is stopped: `restart --port abc` used to take the\n // panel down and only then refuse the port, leaving nothing running.\n const flags = await checkedUpFlags(args)\n const down = await runDown({ withPersistent: args.withPersistent === true })\n // `down` has already said why; going on to `up` would start a second panel over a live one.\n if (!down.ok)\n process.exit(1)\n await runUp(flags, entry)\n if (down.stoppedPersistent.length > 0)\n await startPersistentBack(down.stoppedPersistent)\n },\n })\n}\n\n/**\n * Starts the entries this restart stopped, through the panel that just came back.\n *\n * Only the ones `up` did not already start: its autostart pass runs asynchronously and a second\n * start of a running entry is a plain `{ ok: true }`, so re-asking is harmless — but the\n * entries with `autostart: false`, the reason this exists, would never come back otherwise.\n */\nasync function startPersistentBack(stopped: Array<{ workspaceId: string, serverId: string }>): Promise<void> {\n const { readRuntime, requestControl } = await import('#src/helpers/daemon')\n const runtime = readRuntime()\n if (runtime === null)\n return\n\n for (const { workspaceId, serverId } of stopped) {\n const workspace = `?workspace=${encodeURIComponent(workspaceId)}`\n const answer = await requestControl(runtime, `/_hh/servers/${encodeURIComponent(serverId)}/start${workspace}`)\n const body = (answer?.body ?? {}) as { ok?: boolean, error?: string }\n if (body.ok !== true)\n process.stderr.write(`${paint('31', 'error')} ${workspaceId}/${serverId} did not come back: ${body.error ?? `the panel answered ${answer?.status}`}\\n`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,mBAAmB;CACvB,CAAC,QAAQ,QAAQ;CACjB,CAAC,QAAQ,QAAQ;CACjB,CAAC,aAAa,gBAAgB;CAC9B,CAAC,QAAQ,QAAQ;CACjB,CAAC,cAAc,cAAc;CAC7B,CAAC,eAAe,gBAAgB;AAClC;AAEA,SAAgB,eAAe,OAAe;CAC5C,OAAO,cAAc;EACnB,MAAM,EAAE,MAAM,UAAU;EACxB,MAAM;GACJ,GAAG;GAGH,gBAAgB;IAAE,MAAM;IAAW,aAAa;GAAmE;GAGnH,IAAI;IAAE,MAAM;IAAc,UAAU;IAAO,aAAa;GAAgD;GACxG,WAAW;IAAE,MAAM;IAAU,OAAO;IAAK,aAAa;GAAoE;EAC5H;EACA,KAA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sBAAsB,QAAQ,SAAS,GAAG;CAC1J;AACF"}
|
|
@@ -12,7 +12,7 @@ var NOTHING_LISTENING = /^nothing is listening on port \d+ any more$/;
|
|
|
12
12
|
* say more about what happened; a refusal never returns at all.
|
|
13
13
|
*/
|
|
14
14
|
async function callServerAction(action, id, workspace, options = {}) {
|
|
15
|
-
const { clearRuntime, readRuntime, requestControl, runtimeIsAlive, runtimeIsGone } = await import("./daemon-
|
|
15
|
+
const { clearRuntime, readRuntime, requestControl, runtimeIsAlive, runtimeIsGone } = await import("./daemon-CofN9k6Q.js");
|
|
16
16
|
const runtime = readRuntime();
|
|
17
17
|
if (runtime === null || !await runtimeIsAlive(runtime)) {
|
|
18
18
|
if (runtime !== null && await runtimeIsGone(runtime)) clearRuntime();
|
|
@@ -61,7 +61,7 @@ async function runServerAction(action, id, workspace) {
|
|
|
61
61
|
* deploy chain that continues against a dead process is the failure this exists to stop.
|
|
62
62
|
*/
|
|
63
63
|
async function confirmStillRunning(id, workspace) {
|
|
64
|
-
const { readRuntime, requestControl } = await import("./daemon-
|
|
64
|
+
const { readRuntime, requestControl } = await import("./daemon-CofN9k6Q.js");
|
|
65
65
|
const runtime = readRuntime();
|
|
66
66
|
if (runtime === null) return;
|
|
67
67
|
await new Promise((resolve) => setTimeout(resolve, START_SETTLE_MS));
|
|
@@ -166,4 +166,4 @@ var stopCommand = serverCommand("stop");
|
|
|
166
166
|
//#endregion
|
|
167
167
|
export { freePortCommand, runServerAction, startCommand, stopCommand };
|
|
168
168
|
|
|
169
|
-
//# sourceMappingURL=server-
|
|
169
|
+
//# sourceMappingURL=server-By-zktjx.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-Bge2r2qQ.js","names":[],"sources":["../../src/cli/server.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { fail, green, invocation } from '#src/cli/io'\n\n/**\n * `start`/`stop`/`restart` for one supervised server.\n *\n * The supervisor lives inside the daemon, so a single server cannot be started or\n * stopped without it: these drive the running panel over its local control channel\n * (the same token `down` uses), which needs no session and no API token.\n *\n * `restart` shares the name with the panel's own restart, which is why the id is optional:\n * bare `restart` stays \"down, then up\", and `restart <id>` is one entry — the same thing the\n * UI's per-server Restart button does, which the shell could not.\n */\n\nexport type ServerAction = 'start' | 'stop' | 'restart'\n\n/** The panel's answer when a port is already free — success for `start --free-port`, refused alone. */\nconst NOTHING_LISTENING = /^nothing is listening on port \\d+ any more$/\n\ninterface ActionBody {\n ok?: boolean\n error?: string\n message?: string\n}\n\n/**\n * Asks the running panel to do one thing to one entry, and turns its answer into an exit code.\n *\n * Shared by every per-server command so the \"the panel is not running\", \"it does not know this\n * command\" and \"it refused, here is why\" sentences exist once. Returns the body, so a caller can\n * say more about what happened; a refusal never returns at all.\n */\nasync function callServerAction(action: string, id: string, workspace?: string, options: { tolerateFree?: boolean } = {}): Promise<ActionBody> {\n const { clearRuntime, readRuntime, requestControl, runtimeIsAlive, runtimeIsGone } = await import('#src/helpers/daemon')\n\n const runtime = readRuntime()\n if (runtime === null || !await runtimeIsAlive(runtime)) {\n // Only a record with nothing behind the pid is deleted — see `runtimeIsGone`.\n if (runtime !== null && await runtimeIsGone(runtime))\n clearRuntime()\n fail(`home-hosted is not running — start it with \\`${invocation()} up\\``)\n }\n\n const query = workspace === undefined || workspace.length === 0 ? '' : `?workspace=${encodeURIComponent(workspace)}`\n const answer = await requestControl(runtime, `/_hh/servers/${encodeURIComponent(id)}/${action}${query}`)\n if (answer === null)\n fail(`the control panel is not answering on ${runtime.probeUrl}`)\n\n const body = (answer.body ?? {}) as ActionBody\n if (body.ok !== true) {\n const reason = body.error ?? body.message\n // `start --free-port` wants the port free, so \"nothing is listening\" is the state it asked for;\n // for `free-port` on its own it is a refusal, because the person asked to free something.\n if (options.tolerateFree === true && reason !== undefined && NOTHING_LISTENING.test(reason))\n return { ...body, ok: true }\n if (reason !== undefined)\n fail(reason)\n // A panel from before this command answers a bare 404: say which release is running\n // rather than leaving a puzzled person staring at a status code.\n if (answer.status === 404)\n fail(`the panel on ${runtime.url} is home-hosted ${runtime.version}, which does not know this command — restart it on this release`)\n fail(`the panel answered ${answer.status}`)\n }\n return body\n}\n\n/** `workspace/id`, or `id` in the default workspace. */\nfunction label(id: string, workspace?: string): string {\n return workspace === undefined ? id : `${workspace}/${id}`\n}\n\n/**\n * How long `start` watches the entry before it reports.\n *\n * `start` on the panel returns the instant the process is spawned — right for a click, wrong for a\n * script: an entry whose command exits immediately printed \"started\" and exited 0, while it was\n * already in its crash-restart loop, so `start x && curl x` raced every boot. One second covers a\n * process that dies on startup without making a healthy start feel hung.\n */\nconst START_SETTLE_MS = 1000\n\n/** The view fields `start` reads back to decide whether the entry actually survived. */\ninterface StartedView {\n status?: string\n lastError?: string | null\n restarts?: number\n}\n\nexport async function runServerAction(action: ServerAction, id: string, workspace?: string): Promise<void> {\n await callServerAction(action, id, workspace)\n\n // Both spawn, so both are verified: `restart <id>` is the same process-start path as `start`, and\n // an entry that dies on boot reports `ok` from either one.\n if (action === 'start' || action === 'restart')\n await confirmStillRunning(id, workspace)\n\n // The past tense is the verb: `restart` says \"restarted\", not \"stopped\".\n const verb = action === 'start' ? 'started' : action === 'stop' ? 'stopped' : 'restarted'\n process.stdout.write(`${green(verb)} ${label(id, workspace)}\\n`)\n}\n\n/**\n * Says so when a just-started entry is already gone.\n *\n * `start` answers on spawn, so a command that exits straight away is reported as started. Reading\n * the entry back is the only honest answer, and it is a **refusal** rather than a success line: a\n * deploy chain that continues against a dead process is the failure this exists to stop.\n */\nasync function confirmStillRunning(id: string, workspace?: string): Promise<void> {\n const { readRuntime, requestControl } = await import('#src/helpers/daemon')\n const runtime = readRuntime()\n if (runtime === null)\n return\n\n await new Promise(resolve => setTimeout(resolve, START_SETTLE_MS))\n\n const query = workspace === undefined || workspace.length === 0 ? '' : `?workspace=${encodeURIComponent(workspace)}`\n const answer = await requestControl(runtime, `/_hh/servers/${encodeURIComponent(id)}${query}`, 15_000, 'GET')\n if (answer === null || answer.status !== 200)\n return\n\n const view = (answer.body ?? {}) as StartedView\n // `running` and `starting` are both alive; `backoff` means it exited and is waiting to retry,\n // which is the case that used to read as success.\n if (view.status === 'running' || view.status === 'starting')\n return\n\n const why = view.lastError === null || view.lastError === undefined || view.lastError.length === 0\n ? `status is ${view.status ?? 'unknown'}`\n : view.lastError\n fail(`server \"${label(id, workspace)}\" did not stay up — ${why}. It was spawned; check \\`${invocation()} logs ${id}\\``)\n}\n\n/**\n * `free-port` — ask whatever holds this entry's port to stop, then say what actually happened.\n *\n * The panel refuses what it supervises rather than signalling it, so a success is not simply\n * \"ok\": the report distinguishes the pids that left, the ones that ignored SIGTERM and had to be\n * killed, and any this panel owns that were deliberately left alone.\n */\nexport async function runFreePort(id: string, workspace?: string, options: { tolerateFree?: boolean } = {}): Promise<void> {\n const body = await callServerAction('free-port', id, workspace, { tolerateFree: options.tolerateFree }) as ActionBody & {\n port?: number | null\n terminated?: number[]\n forced?: number[]\n skipped?: number[]\n free?: boolean\n }\n\n const port = body.port ?? null\n const where = label(id, workspace)\n const terminated = body.terminated ?? []\n const forced = body.forced ?? []\n const skipped = body.skipped ?? []\n\n const parts: string[] = []\n if (terminated.length > 0)\n parts.push(`pid ${terminated.join(', ')} stopped`)\n if (forced.length > 0)\n parts.push(`pid ${forced.join(', ')} had to be killed`)\n if (skipped.length > 0)\n parts.push(`pid ${skipped.join(', ')} left alone (this panel supervises it)`)\n\n // `free: false` with nothing signalled is the panel saying \"there was nothing to free\" — either\n // the port was already idle (tolerated here, since `start --free-port` wanted exactly that) or a\n // socket survived and it refused. `free === false` also covers the tolerated answer, which is the\n // same body with `ok` flipped, so the two callers cannot drift.\n const idle = terminated.length === 0 && forced.length === 0 && skipped.length === 0\n if (port === null || idle) {\n process.stdout.write(`${green('port is free')} ${where}${port === null ? '' : ` on ${port}`}\\n`)\n return\n }\n\n const detail = idle ? 'nothing was listening' : parts.join('; ')\n if (body.free === true) {\n process.stdout.write(`${green('freed')} port ${port} for ${where} — ${detail}\\n`)\n return\n }\n // The port was taken and still is: a socket that survived SIGTERM. Exit 1, because a caller\n // scripting this needs to know the server still cannot start.\n fail(`port ${port} is still in use for ${where} — ${detail}`)\n}\n\n/**\n * `start`, and `start --free-port`.\n *\n * `--free-port` frees the port first, then starts — the one sequence a person actually wants after\n * reading \"port 4010 is already in use\". It is a flag on `start` rather than only a command because\n * the two calls it saves are the common case; `free-port` on its own still exists for when the intent\n * is only to unblock a port.\n */\nfunction serverCommand(action: ServerAction) {\n const withFreePort = action === 'start'\n return defineCommand({\n // No `description`: `cli.ts` owns the one copy (`SYNOPSIS` + `SUMMARIES`) and renders it through\n // `commandHelp`, which `main()` intercepts before citty sees `--help`. citty's own usage printer is\n // the only reader of a subcommand description here and it never runs (`runCommand`, not `runMain`),\n // so a copy in the module is unreachable text that drifts — `migrate`, `up` and `ui-update` had all\n // diverged by the time this was noticed.\n meta: {\n name: action,\n },\n args: {\n // `required: false` keeps citty's own refusal out of the way: the message below\n // names the id and where to find it.\n id: { type: 'positional', required: false, description: 'the server id from the workspace\\'s servers.config.json' },\n workspace: { type: 'string', alias: 'w', description: 'the workspace to act in (default: the panel\\'s default workspace)' },\n ...(withFreePort\n ? { 'free-port': { type: 'boolean', description: 'free the port first, then start (what the panel\\'s Free port button does)' } }\n : {}),\n },\n run: async ({ args }) => {\n const id = typeof args.id === 'string' ? args.id.trim() : ''\n if (id.length === 0)\n fail(`${action} needs a server id — see \\`${invocation()} status\\` or the workspace's servers.config.json`)\n const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : undefined\n // Freeing first is not \"free port, ignore the outcome, then start\": a port that stays taken\n // makes the start fail with the same sentence, so stop here with the port's own reason.\n if (withFreePort && args['free-port'] === true)\n await runFreePort(id, workspace, { tolerateFree: true })\n await runServerAction(action, id, workspace)\n },\n })\n}\n\n/** `free-port <id>` — the panel's Free port button, from a shell. */\nexport const freePortCommand = defineCommand({\n meta: { name: 'free-port' },\n args: {\n id: { type: 'positional', required: false, description: 'the server whose port should be freed' },\n workspace: { type: 'string', alias: 'w', description: 'the workspace to act in (default: the panel\\'s default workspace)' },\n },\n run: async ({ args }) => {\n const id = typeof args.id === 'string' ? args.id.trim() : ''\n if (id.length === 0)\n fail(`free-port needs a server id — see \\`${invocation()} status\\` or the workspace's servers.config.json`)\n const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : undefined\n await runFreePort(id, workspace)\n },\n})\n\nexport const startCommand = serverCommand('start')\nexport const stopCommand = serverCommand('stop')\n// `restart` is deliberately absent: bare `restart` means the *panel*, and `restart <id>` is handled by\n// `cli/restart.ts` through the same `runServerAction`. A `restartServerCommand` used to be exported\n// here — never wired into the command surface, so it read as an entry point nothing could reach.\n"],"mappings":";;;;;AAmBA,IAAM,oBAAoB;;;;;;;;AAe1B,eAAe,iBAAiB,QAAgB,IAAY,WAAoB,UAAsC,CAAC,GAAwB;CAC7I,MAAM,EAAE,cAAc,aAAa,gBAAgB,gBAAgB,kBAAkB,MAAM,OAAO;CAElG,MAAM,UAAU,YAAY;CAC5B,IAAI,YAAY,QAAQ,CAAC,MAAM,eAAe,OAAO,GAAG;EAEtD,IAAI,YAAY,QAAQ,MAAM,cAAc,OAAO,GACjD,aAAa;EACf,KAAK,gDAAgD,WAAW,EAAE,MAAM;CAC1E;CAEA,MAAM,QAAQ,cAAc,KAAA,KAAa,UAAU,WAAW,IAAI,KAAK,cAAc,mBAAmB,SAAS;CACjH,MAAM,SAAS,MAAM,eAAe,SAAS,gBAAgB,mBAAmB,EAAE,EAAE,GAAG,SAAS,OAAO;CACvG,IAAI,WAAW,MACb,KAAK,yCAAyC,QAAQ,UAAU;CAElE,MAAM,OAAQ,OAAO,QAAQ,CAAC;CAC9B,IAAI,KAAK,OAAO,MAAM;EACpB,MAAM,SAAS,KAAK,SAAS,KAAK;EAGlC,IAAI,QAAQ,iBAAiB,QAAQ,WAAW,KAAA,KAAa,kBAAkB,KAAK,MAAM,GACxF,OAAO;GAAE,GAAG;GAAM,IAAI;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AAM,OACR;EACA,MAAM;GAGJ,IAAI;IAAE,MAAM;IAAc,UAAU;IAAO,aAAa;GAA0D;GAClH,WAAW;IAAE,MAAM;IAAU,OAAO;IAAK,aAAa;GAAoE;GAC1H,GAAI,eACA,EAAE,aAAa;IAAE,MAAM;IAAW,aAAa;GAA4E,EAAE,IAC7H,CAAC;EACP;EACA,KAAK,OAAO,EAAE,WAAW;GACvB,MAAM,KAAK,OAAO,KAAK,OAAO,WAAW,KAAK,GAAG,KAAK,IAAI;GAC1D,IAAI,GAAG,WAAW,GAChB,KAAK,GAAG,OAAO,6BAA6B,WAAW,EAAE,iDAAiD;GAC5G,MAAM,YAAY,OAAO,KAAK,cAAc,WAAW,KAAK,UAAU,KAAK,IAAI,KAAA;GAG/E,IAAI,gBAAgB,KAAK,iBAAiB,MACxC,MAAM,YAAY,IAAI,WAAW,EAAE,cAAc,KAAK,CAAC;GACzD,MAAM,gBAAgB,QAAQ,IAAI,SAAS;EAC7C;CACF,CAAC;AACH;;AAGA,IAAa,kBAAkB,cAAc;CAC3C,MAAM,EAAE,MAAM,YAAY;CAC1B,MAAM;EACJ,IAAI;GAAE,MAAM;GAAc,UAAU;GAAO,aAAa;EAAwC;EAChG,WAAW;GAAE,MAAM;GAAU,OAAO;GAAK,aAAa;EAAoE;CAC5H;CACA,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,KAAK,OAAO,KAAK,OAAO,WAAW,KAAK,GAAG,KAAK,IAAI;EAC1D,IAAI,GAAG,WAAW,GAChB,KAAK,uCAAuC,WAAW,EAAE,iDAAiD;EAE5G,MAAM,YAAY,IADA,OAAO,KAAK,cAAc,WAAW,KAAK,UAAU,KAAK,IAAI,KAAA,CAChD;CACjC;AACF,CAAC;AAED,IAAa,eAAe,cAAc,OAAO;AACjD,IAAa,cAAc,cAAc,MAAM"}
|
|
1
|
+
{"version":3,"file":"server-By-zktjx.js","names":[],"sources":["../../src/cli/server.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { fail, green, invocation } from '#src/cli/io'\n\n/**\n * `start`/`stop`/`restart` for one supervised server.\n *\n * The supervisor lives inside the daemon, so a single server cannot be started or\n * stopped without it: these drive the running panel over its local control channel\n * (the same token `down` uses), which needs no session and no API token.\n *\n * `restart` shares the name with the panel's own restart, which is why the id is optional:\n * bare `restart` stays \"down, then up\", and `restart <id>` is one entry — the same thing the\n * UI's per-server Restart button does, which the shell could not.\n */\n\nexport type ServerAction = 'start' | 'stop' | 'restart'\n\n/** The panel's answer when a port is already free — success for `start --free-port`, refused alone. */\nconst NOTHING_LISTENING = /^nothing is listening on port \\d+ any more$/\n\ninterface ActionBody {\n ok?: boolean\n error?: string\n message?: string\n}\n\n/**\n * Asks the running panel to do one thing to one entry, and turns its answer into an exit code.\n *\n * Shared by every per-server command so the \"the panel is not running\", \"it does not know this\n * command\" and \"it refused, here is why\" sentences exist once. Returns the body, so a caller can\n * say more about what happened; a refusal never returns at all.\n */\nasync function callServerAction(action: string, id: string, workspace?: string, options: { tolerateFree?: boolean } = {}): Promise<ActionBody> {\n const { clearRuntime, readRuntime, requestControl, runtimeIsAlive, runtimeIsGone } = await import('#src/helpers/daemon')\n\n const runtime = readRuntime()\n if (runtime === null || !await runtimeIsAlive(runtime)) {\n // Only a record with nothing behind the pid is deleted — see `runtimeIsGone`.\n if (runtime !== null && await runtimeIsGone(runtime))\n clearRuntime()\n fail(`home-hosted is not running — start it with \\`${invocation()} up\\``)\n }\n\n const query = workspace === undefined || workspace.length === 0 ? '' : `?workspace=${encodeURIComponent(workspace)}`\n const answer = await requestControl(runtime, `/_hh/servers/${encodeURIComponent(id)}/${action}${query}`)\n if (answer === null)\n fail(`the control panel is not answering on ${runtime.probeUrl}`)\n\n const body = (answer.body ?? {}) as ActionBody\n if (body.ok !== true) {\n const reason = body.error ?? body.message\n // `start --free-port` wants the port free, so \"nothing is listening\" is the state it asked for;\n // for `free-port` on its own it is a refusal, because the person asked to free something.\n if (options.tolerateFree === true && reason !== undefined && NOTHING_LISTENING.test(reason))\n return { ...body, ok: true }\n if (reason !== undefined)\n fail(reason)\n // A panel from before this command answers a bare 404: say which release is running\n // rather than leaving a puzzled person staring at a status code.\n if (answer.status === 404)\n fail(`the panel on ${runtime.url} is home-hosted ${runtime.version}, which does not know this command — restart it on this release`)\n fail(`the panel answered ${answer.status}`)\n }\n return body\n}\n\n/** `workspace/id`, or `id` in the default workspace. */\nfunction label(id: string, workspace?: string): string {\n return workspace === undefined ? id : `${workspace}/${id}`\n}\n\n/**\n * How long `start` watches the entry before it reports.\n *\n * `start` on the panel returns the instant the process is spawned — right for a click, wrong for a\n * script: an entry whose command exits immediately printed \"started\" and exited 0, while it was\n * already in its crash-restart loop, so `start x && curl x` raced every boot. One second covers a\n * process that dies on startup without making a healthy start feel hung.\n */\nconst START_SETTLE_MS = 1000\n\n/** The view fields `start` reads back to decide whether the entry actually survived. */\ninterface StartedView {\n status?: string\n lastError?: string | null\n restarts?: number\n}\n\nexport async function runServerAction(action: ServerAction, id: string, workspace?: string): Promise<void> {\n await callServerAction(action, id, workspace)\n\n // Both spawn, so both are verified: `restart <id>` is the same process-start path as `start`, and\n // an entry that dies on boot reports `ok` from either one.\n if (action === 'start' || action === 'restart')\n await confirmStillRunning(id, workspace)\n\n // The past tense is the verb: `restart` says \"restarted\", not \"stopped\".\n const verb = action === 'start' ? 'started' : action === 'stop' ? 'stopped' : 'restarted'\n process.stdout.write(`${green(verb)} ${label(id, workspace)}\\n`)\n}\n\n/**\n * Says so when a just-started entry is already gone.\n *\n * `start` answers on spawn, so a command that exits straight away is reported as started. Reading\n * the entry back is the only honest answer, and it is a **refusal** rather than a success line: a\n * deploy chain that continues against a dead process is the failure this exists to stop.\n */\nasync function confirmStillRunning(id: string, workspace?: string): Promise<void> {\n const { readRuntime, requestControl } = await import('#src/helpers/daemon')\n const runtime = readRuntime()\n if (runtime === null)\n return\n\n await new Promise(resolve => setTimeout(resolve, START_SETTLE_MS))\n\n const query = workspace === undefined || workspace.length === 0 ? '' : `?workspace=${encodeURIComponent(workspace)}`\n const answer = await requestControl(runtime, `/_hh/servers/${encodeURIComponent(id)}${query}`, 15_000, 'GET')\n if (answer === null || answer.status !== 200)\n return\n\n const view = (answer.body ?? {}) as StartedView\n // `running` and `starting` are both alive; `backoff` means it exited and is waiting to retry,\n // which is the case that used to read as success.\n if (view.status === 'running' || view.status === 'starting')\n return\n\n const why = view.lastError === null || view.lastError === undefined || view.lastError.length === 0\n ? `status is ${view.status ?? 'unknown'}`\n : view.lastError\n fail(`server \"${label(id, workspace)}\" did not stay up — ${why}. It was spawned; check \\`${invocation()} logs ${id}\\``)\n}\n\n/**\n * `free-port` — ask whatever holds this entry's port to stop, then say what actually happened.\n *\n * The panel refuses what it supervises rather than signalling it, so a success is not simply\n * \"ok\": the report distinguishes the pids that left, the ones that ignored SIGTERM and had to be\n * killed, and any this panel owns that were deliberately left alone.\n */\nexport async function runFreePort(id: string, workspace?: string, options: { tolerateFree?: boolean } = {}): Promise<void> {\n const body = await callServerAction('free-port', id, workspace, { tolerateFree: options.tolerateFree }) as ActionBody & {\n port?: number | null\n terminated?: number[]\n forced?: number[]\n skipped?: number[]\n free?: boolean\n }\n\n const port = body.port ?? null\n const where = label(id, workspace)\n const terminated = body.terminated ?? []\n const forced = body.forced ?? []\n const skipped = body.skipped ?? []\n\n const parts: string[] = []\n if (terminated.length > 0)\n parts.push(`pid ${terminated.join(', ')} stopped`)\n if (forced.length > 0)\n parts.push(`pid ${forced.join(', ')} had to be killed`)\n if (skipped.length > 0)\n parts.push(`pid ${skipped.join(', ')} left alone (this panel supervises it)`)\n\n // `free: false` with nothing signalled is the panel saying \"there was nothing to free\" — either\n // the port was already idle (tolerated here, since `start --free-port` wanted exactly that) or a\n // socket survived and it refused. `free === false` also covers the tolerated answer, which is the\n // same body with `ok` flipped, so the two callers cannot drift.\n const idle = terminated.length === 0 && forced.length === 0 && skipped.length === 0\n if (port === null || idle) {\n process.stdout.write(`${green('port is free')} ${where}${port === null ? '' : ` on ${port}`}\\n`)\n return\n }\n\n const detail = idle ? 'nothing was listening' : parts.join('; ')\n if (body.free === true) {\n process.stdout.write(`${green('freed')} port ${port} for ${where} — ${detail}\\n`)\n return\n }\n // The port was taken and still is: a socket that survived SIGTERM. Exit 1, because a caller\n // scripting this needs to know the server still cannot start.\n fail(`port ${port} is still in use for ${where} — ${detail}`)\n}\n\n/**\n * `start`, and `start --free-port`.\n *\n * `--free-port` frees the port first, then starts — the one sequence a person actually wants after\n * reading \"port 4010 is already in use\". It is a flag on `start` rather than only a command because\n * the two calls it saves are the common case; `free-port` on its own still exists for when the intent\n * is only to unblock a port.\n */\nfunction serverCommand(action: ServerAction) {\n const withFreePort = action === 'start'\n return defineCommand({\n // No `description`: `cli.ts` owns the one copy (`SYNOPSIS` + `SUMMARIES`) and renders it through\n // `commandHelp`, which `main()` intercepts before citty sees `--help`. citty's own usage printer is\n // the only reader of a subcommand description here and it never runs (`runCommand`, not `runMain`),\n // so a copy in the module is unreachable text that drifts — `migrate`, `up` and `ui-update` had all\n // diverged by the time this was noticed.\n meta: {\n name: action,\n },\n args: {\n // `required: false` keeps citty's own refusal out of the way: the message below\n // names the id and where to find it.\n id: { type: 'positional', required: false, description: 'the server id from the workspace\\'s servers.config.json' },\n workspace: { type: 'string', alias: 'w', description: 'the workspace to act in (default: the panel\\'s default workspace)' },\n ...(withFreePort\n ? { 'free-port': { type: 'boolean', description: 'free the port first, then start (what the panel\\'s Free port button does)' } }\n : {}),\n },\n run: async ({ args }) => {\n const id = typeof args.id === 'string' ? args.id.trim() : ''\n if (id.length === 0)\n fail(`${action} needs a server id — see \\`${invocation()} status\\` or the workspace's servers.config.json`)\n const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : undefined\n // Freeing first is not \"free port, ignore the outcome, then start\": a port that stays taken\n // makes the start fail with the same sentence, so stop here with the port's own reason.\n if (withFreePort && args['free-port'] === true)\n await runFreePort(id, workspace, { tolerateFree: true })\n await runServerAction(action, id, workspace)\n },\n })\n}\n\n/** `free-port <id>` — the panel's Free port button, from a shell. */\nexport const freePortCommand = defineCommand({\n meta: { name: 'free-port' },\n args: {\n id: { type: 'positional', required: false, description: 'the server whose port should be freed' },\n workspace: { type: 'string', alias: 'w', description: 'the workspace to act in (default: the panel\\'s default workspace)' },\n },\n run: async ({ args }) => {\n const id = typeof args.id === 'string' ? args.id.trim() : ''\n if (id.length === 0)\n fail(`free-port needs a server id — see \\`${invocation()} status\\` or the workspace's servers.config.json`)\n const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : undefined\n await runFreePort(id, workspace)\n },\n})\n\nexport const startCommand = serverCommand('start')\nexport const stopCommand = serverCommand('stop')\n// `restart` is deliberately absent: bare `restart` means the *panel*, and `restart <id>` is handled by\n// `cli/restart.ts` through the same `runServerAction`. A `restartServerCommand` used to be exported\n// here — never wired into the command surface, so it read as an entry point nothing could reach.\n"],"mappings":";;;;;AAmBA,IAAM,oBAAoB;;;;;;;;AAe1B,eAAe,iBAAiB,QAAgB,IAAY,WAAoB,UAAsC,CAAC,GAAwB;CAC7I,MAAM,EAAE,cAAc,aAAa,gBAAgB,gBAAgB,kBAAkB,MAAM,OAAO;CAElG,MAAM,UAAU,YAAY;CAC5B,IAAI,YAAY,QAAQ,CAAC,MAAM,eAAe,OAAO,GAAG;EAEtD,IAAI,YAAY,QAAQ,MAAM,cAAc,OAAO,GACjD,aAAa;EACf,KAAK,gDAAgD,WAAW,EAAE,MAAM;CAC1E;CAEA,MAAM,QAAQ,cAAc,KAAA,KAAa,UAAU,WAAW,IAAI,KAAK,cAAc,mBAAmB,SAAS;CACjH,MAAM,SAAS,MAAM,eAAe,SAAS,gBAAgB,mBAAmB,EAAE,EAAE,GAAG,SAAS,OAAO;CACvG,IAAI,WAAW,MACb,KAAK,yCAAyC,QAAQ,UAAU;CAElE,MAAM,OAAQ,OAAO,QAAQ,CAAC;CAC9B,IAAI,KAAK,OAAO,MAAM;EACpB,MAAM,SAAS,KAAK,SAAS,KAAK;EAGlC,IAA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
|
@@ -39,7 +39,7 @@ async function runSetToken(generate, clear) {
|
|
|
39
39
|
process.stdout.write(` ${bold(token)}\n`);
|
|
40
40
|
process.stdout.write(`${dim(" shown once — only its SHA-256 is kept on disk, so copy it now")}\n`);
|
|
41
41
|
} else process.stdout.write(`${dim(` stored as ${token.slice(0, 8)}… — the file keeps only its hash`)}\n`);
|
|
42
|
-
const { readRuntime } = await import("./daemon-
|
|
42
|
+
const { readRuntime } = await import("./daemon-CofN9k6Q.js");
|
|
43
43
|
const runtime = readRuntime();
|
|
44
44
|
const base = (runtime?.url ?? `http://127.0.0.1:${DEFAULT_PORT}`).replace(/\/+$/, "");
|
|
45
45
|
if (runtime !== null) {
|
|
@@ -75,4 +75,4 @@ var setTokenCommand = defineCommand({
|
|
|
75
75
|
//#endregion
|
|
76
76
|
export { setTokenCommand };
|
|
77
77
|
|
|
78
|
-
//# sourceMappingURL=set-token-
|
|
78
|
+
//# sourceMappingURL=set-token-xJkA1IZp.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"set-token-
|
|
1
|
+
{"version":3,"file":"set-token-xJkA1IZp.js","names":["secretsPath"],"sources":["../../src/cli/set-token.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, dim, fail, green, invocation, promptHidden } from '#src/cli/io'\nimport { generateApiToken, SecretsStore } from '#src/config/secrets'\nimport { globalSecretsPath as secretsPath } from '#src/helpers/paths'\n\n/** `set-token` sets the bearer credential scripts and agents use. */\n\nconst DEFAULT_PORT = 3999\n\nexport const setTokenArgs = {\n generate: { type: 'boolean', description: 'create a strong token and print it once' },\n clear: { type: 'boolean', description: 'remove the token, so it stops working' },\n} as const\n\nexport async function runSetToken(generate: boolean, clear: boolean): Promise<void> {\n if (generate && clear)\n fail('use either --generate or --clear, not both')\n\n const store = new SecretsStore(secretsPath, undefined, 'global')\n\n if (clear) {\n if (!store.apiTokenSet) {\n process.stdout.write('no API token is set — nothing to clear\\n')\n return\n }\n store.clearApiToken()\n process.stdout.write(`${green('API token cleared')} in ${secretsPath} — it stops working immediately\\n`)\n return\n }\n\n let token: string | null = process.env.HHOSTED_TOKEN ?? null\n if (generate)\n token = generateApiToken()\n else if (token === null && process.stdin.isTTY === true)\n token = await promptHidden('API token: ')\n if (token !== null)\n token = token.trim()\n if (token === null || token.length === 0) {\n fail(`no token given: run \\`${invocation()} set-token --generate\\`, set HHOSTED_TOKEN, or paste one interactively`)\n }\n\n store.setApiToken(token)\n process.stdout.write(`${green(generate ? 'token generated' : 'token stored')} in ${secretsPath} (mode 0600)\\n`)\n if (generate) {\n process.stdout.write(` ${bold(token)}\\n`)\n process.stdout.write(`${dim(' shown once — only its SHA-256 is kept on disk, so copy it now')}\\n`)\n }\n else {\n process.stdout.write(`${dim(` stored as ${token.slice(0, 8)}… — the file keeps only its hash`)}\\n`)\n }\n\n const { readRuntime } = await import('#src/helpers/daemon')\n // Only the panel that owns *this* state directory is worth asking: guessing a\n // port would probe someone else's panel and call the mismatch a failure.\n const runtime = readRuntime()\n const base = (runtime?.url ?? `http://127.0.0.1:${DEFAULT_PORT}`).replace(/\\/+$/, '')\n\n if (runtime !== null) {\n const verified = await verifyToken(base, token)\n if (verified === true)\n process.stdout.write(`${dim(`verified: ${base}/api/auth/session accepted it`)}\\n`)\n else if (verified === false)\n process.stdout.write(`${dim(`the panel at ${base} did not accept it — is it running with this state directory?`)}\\n`)\n }\n\n process.stdout.write(`Use it from a script or an agent:\\n`)\n process.stdout.write(` ${bold(`curl -H \"Authorization: Bearer ${generate ? token : '<token>'}\" ${base}/api/state`)}\\n`)\n process.stdout.write(`${dim('It needs no restart and outlives sessions, and it holds the same access as a signed-in browser — except clearing the panel password, which a token may not do.')}\\n`)\n process.stdout.write(`${dim('Changing the password does NOT revoke it: `set-password` drops sessions and leaves the token working. Rotate with this command if it may have leaked.')}\\n`)\n process.stdout.write(`${dim(`Remove it any time with: ${invocation()} set-token --clear`)}\\n`)\n if (store.usingDefaultPassword)\n process.stdout.write(`${dim('The panel password is still the default — change it before the panel is reachable beyond loopback.')}\\n`)\n}\n\n/** Asks the live panel whether it accepts the token, without failing when it cannot. */\nasync function verifyToken(base: string, token: string): Promise<boolean | null> {\n // An https endpoint is usually TLS this project generated itself, which a plain\n // fetch refuses; the liveness probe in `helpers/daemon` is the one that knows how.\n if (!base.startsWith('http://'))\n return null\n try {\n const response = await fetch(`${base}/api/auth/session`, { headers: { authorization: `Bearer ${token}` } })\n if (!response.ok)\n return false\n const body = await response.json() as { authenticated?: boolean }\n return body.authenticated === true\n }\n catch {\n return null\n }\n}\n\nexport const setTokenCommand = defineCommand({\n meta: { name: 'set-token' },\n args: setTokenArgs,\n run: async ({ args }) => {\n await runSetToken(args.generate === true, args.clear === true)\n },\n})\n"],"mappings":";;;;;;;AAQA,IAAM,eAAe;AAErB,IAAa,eAAe;CAC1B,UAAU;EAAE,MAAM;EAAW,aAAa;CAA0C;CACpF,OAAO;EAAE,MAAM;EAAW,aAAa;CAAwC;AACjF;AAEA,eAAsB,YAAY,UAAmB,OAA+B;CAClF,IAAI,YAAY,OACd,KAAK,4CAA4C;CAEnD,MAAM,QAAQ,IAAI,aAAaA,mBAAa,KAAA,GAAW,QAAQ;CAE/D,IAAI,OAAO;EACT,IAAI,CAAC,MAAM,aAAa;GACtB,QAAQ,OAAO,MAAM,0CAA0C;GAC/D;EACF;EACA,MAAM,cAAc;EACpB,QAAQ,OAAO,MAAM,GAAG,MAAM,mBAAmB,EAAE,MAAMA,kBAAY,kCAAkC;EACvG;CACF;CAEA,IAAI,QAAuB,QAAQ,IAAI,iBAAiB;CACxD,IAAI,UACF,QAAQ,iBAAiB;MACtB,IAAI,UAAU,QAAQ,QAAQ,MAAM,UAAU,MACjD,QAAQ,MAAM,aAAa,aAAa;CAC1C,IAAI,UAAU,MACZ,QAAQ,MAAM,KAAK;CACrB,IAAI,UAAU,QAAQ,MAAM,WAAW,GACrC,KAAK,yBAAyB,WAAW,EAAE,uEAAuE;CAGpH,MAA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AM,WAAW,MAAM,MAAM,GAAG,KAAK,oBAAoB,EAAE,SAAS,EAAE,eAAe,UAAU,QAAQ,EAAE,CAAC;EAC1G,IAAI,CAAC,SAAS,IACZ,OAAO;EAET,QAAO,MADY,SAAS,KAAK,EAAA,CACrB,kBAAkB;CAChC,QACM;EACJ,OAAO;CACT;AACF;AAEA,IAAa,kBAAkB,cAAc;CAC3C,MAAM,EAAE,MAAM,YAAY;CAC1B,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,YAAY,KAAK,aAAa,MAAM,KAAK,UAAU,IAAI;CAC/D;AACF,CAAC"}
|
|
@@ -8,16 +8,16 @@ import { i as generateInitialPassword, n as SecretsStore, o as verifyApiToken, r
|
|
|
8
8
|
import { $ as settingsSavedSchema, A as loginSchema, B as proxyCertificateUploadSchema, C as freePortResultSchema, D as logLinesResponseSchema, E as logHistoryQuerySchema, G as restorePlanSchema, H as proxyEngineInstallSchema, I as okResponseSchema, J as serverPatchSchema, K as restoreRequestSchema, L as parseBind, O as logQuerySchema, P as notificationActionSchema, Q as settingsPatchSchema, R as passwordSchema, U as proxyPatchSchema, V as proxyConfigSchema, W as proxyViewSchema, X as serverViewSchema, Y as serverSchema, Z as sessionViewSchema, _t as wslTemperatureSchema, a as backupCreateSchema, at as tlsUploadSchema, b as destinationTestSchema, c as backupLocalResponseSchema, ct as usageViewSchema, d as bufferedLogsResponseSchema, dt as workspaceRenameSchema, et as settingsViewSchema, g as ddnsViewSchema, gt as workspaceViewSchema, h as ddnsCredentialsSchema, ht as workspaceSettingsViewSchema, i as appStateSchema, it as tlsReviewResponseSchema, k as logServersViewSchema, l as backupSelectionSchema, lt as workspaceCreateSchema, m as ddnsConfigSchema, mt as workspaceSettingsSavedSchema, n as apiErrorSchema, nt as telegramChatsSchema, o as backupCreatedResponseSchema, ot as uiInstallResponseSchema, pt as workspaceSettingsPatchSchema, q as serverCreateSchema, r as apiTokenCreatedSchema, rt as telegramTokenSchema, s as backupFilesResponseSchema, t as actionResultSchema, v as deliveryResultSchema, vt as hostReadings, w as healthResponseSchema, y as destinationIdParamSchema, z as passwordSetResponseSchema } from "./contracts-CMBD1TF9.js";
|
|
9
9
|
import { t as lazy } from "./lazy-Ce5zEAq1.js";
|
|
10
10
|
import { f as applyPatch, n as GlobalSettingsStore, t as ConfigError, u as PROXY_MERGE_KEYS } from "./settings-xu-XTfWg.js";
|
|
11
|
-
import { A as normalizeHost, C as expandEnvList, D as ddnsProvider, E as resolveEnvFilePath, O as ddnsProviderInfos, S as targetProblem, T as loadEnvFile, _ as entryStatePath, a as unknownBackupIds, b as WorkspaceStore, c as serverTemplateVars, d as isExposed, f as lanAddress, g as clearEntryState, h as resolveTemplates, i as selectionWritesCredentials, k as validateDdnsConfig, l as bindHost, m as resolveTemplate, n as buildBackupSources, o as hookFailure, p as resolveRecord, r as selectionOf, s as runBackupHook, t as BackupService, u as displayHost, v as readEntryState, w as expandEnvRecord, x as sendWebhook, y as writeEntryState } from "./backups-
|
|
11
|
+
import { A as normalizeHost, C as expandEnvList, D as ddnsProvider, E as resolveEnvFilePath, O as ddnsProviderInfos, S as targetProblem, T as loadEnvFile, _ as entryStatePath, a as unknownBackupIds, b as WorkspaceStore, c as serverTemplateVars, d as isExposed, f as lanAddress, g as clearEntryState, h as resolveTemplates, i as selectionWritesCredentials, k as validateDdnsConfig, l as bindHost, m as resolveTemplate, n as buildBackupSources, o as hookFailure, p as resolveRecord, r as selectionOf, s as runBackupHook, t as BackupService, u as displayHost, v as readEntryState, w as expandEnvRecord, x as sendWebhook, y as writeEntryState } from "./backups-twva7x2n.js";
|
|
12
12
|
import { n as WorkspaceRegistry, t as WorkspaceError } from "./workspaces-DYcfvKV_.js";
|
|
13
|
-
import { A as processTreeOwners, C as resolveCwd, D as identifyHolders, E as terminatePid, O as ProcessSampler, S as resolveCommand, T as terminate, _ as readNannyState, a as clearNannySpec, c as describeSpawnError, d as nannyIsAlive, f as nannyLogFile, h as nannyStopOptions, k as processCarriesServerId, l as nannyChildPid, m as nannyStatePath, o as clearNannyState, p as nannySpecPath, s as describeNannyExit, u as nannyEntryPoint, v as sweepNannySpecs, w as spawnManaged, x as forceKillTree, y as writeNannySpec } from "./nanny-
|
|
14
|
-
import { a as listPortHolders, c as processLiveness, i as killPortHolders, l as releaseDockerPort, n as isPortFree, r as isProcessAlive, s as probePort, t as findDockerPortHolder, u as terminatePids } from "./port-
|
|
13
|
+
import { A as processTreeOwners, C as resolveCwd, D as identifyHolders, E as terminatePid, O as ProcessSampler, S as resolveCommand, T as terminate, _ as readNannyState, a as clearNannySpec, c as describeSpawnError, d as nannyIsAlive, f as nannyLogFile, h as nannyStopOptions, k as processCarriesServerId, l as nannyChildPid, m as nannyStatePath, o as clearNannyState, p as nannySpecPath, s as describeNannyExit, u as nannyEntryPoint, v as sweepNannySpecs, w as spawnManaged, x as forceKillTree, y as writeNannySpec } from "./nanny-COyCJXj9.js";
|
|
14
|
+
import { a as listPortHolders, c as processLiveness, i as killPortHolders, l as releaseDockerPort, n as isPortFree, r as isProcessAlive, s as probePort, t as findDockerPortHolder, u as terminatePids } from "./port-k5VBw8t9.js";
|
|
15
15
|
import { a as stopComposeContainers, i as isOwnStack, n as composeTarget, r as isComposeCommand, t as DockerMetrics } from "./docker-Cy9Lyvda.js";
|
|
16
16
|
import { a as removeWslTemperatureScript, c as writeWslTemperatureScript, i as probeWslTemperature, l as wslScriptPath, o as tempCommandFor, r as lhmInstalled, t as installLibreHardwareMonitor, u as wslTemperatureStatus } from "./wsl-temperature-BiCI4iK6.js";
|
|
17
17
|
import { UiService } from "./ui-D562aqw5.js";
|
|
18
18
|
import { _ as matchAsset, b as parseRepoSlug, d as fetchRelease, g as isUiAsset, h as isOwnRepo, i as assetDownloadUrl, l as downloadToTemp, t as DEFAULT_REPO } from "./ui-release-DKzVvlLd.js";
|
|
19
19
|
import { ensureLayout } from "./layout-DwTtmund.js";
|
|
20
|
-
import { clearRuntime, newToken, readRuntime, runtimeIsAlive, runtimeIsGone, writeRuntime } from "./daemon-
|
|
20
|
+
import { clearRuntime, newToken, readRuntime, runtimeIsAlive, runtimeIsGone, writeRuntime } from "./daemon-CofN9k6Q.js";
|
|
21
21
|
import { i as LogFiles, n as LogBuffer, r as Utf8Chunks, t as LineSplitter } from "./log-buffer-Dy9HHDMD.js";
|
|
22
22
|
import process from "node:process";
|
|
23
23
|
import path from "node:path";
|
|
@@ -7152,7 +7152,10 @@ async function readSwapUsedPercent() {
|
|
|
7152
7152
|
"-NonInteractive",
|
|
7153
7153
|
"-Command",
|
|
7154
7154
|
"Get-CimInstance Win32_PageFileUsage | Select-Object AllocatedBaseSize,CurrentUsage | ConvertTo-Csv -NoTypeInformation"
|
|
7155
|
-
], {
|
|
7155
|
+
], {
|
|
7156
|
+
timeout: 5e3,
|
|
7157
|
+
windowsHide: true
|
|
7158
|
+
});
|
|
7156
7159
|
return swapPercentFromPageFile(stdout);
|
|
7157
7160
|
} catch {
|
|
7158
7161
|
return 0;
|
|
@@ -12335,4 +12338,4 @@ function restrictStateDir() {
|
|
|
12335
12338
|
//#endregion
|
|
12336
12339
|
export { runControlPlane };
|
|
12337
12340
|
|
|
12338
|
-
//# sourceMappingURL=src-
|
|
12341
|
+
//# sourceMappingURL=src-BOBh9MBf.js.map
|