home-hosted 0.12.0 → 0.13.0
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/README.md +95 -49
- package/dist/chunks/{archive-DpCwA8Nf.js → archive-DP-XQR8X.js} +15 -2
- package/dist/chunks/archive-DP-XQR8X.js.map +1 -0
- package/dist/chunks/{atomic-CEfCUfkQ.js → atomic-C1PfJpE7.js} +3 -2
- package/dist/chunks/atomic-C1PfJpE7.js.map +1 -0
- package/dist/chunks/{backup-CPrJVPJI.js → backup-CZcVca2a.js} +101 -76
- package/dist/chunks/backup-CZcVca2a.js.map +1 -0
- package/dist/chunks/{backups-Bd2SF2qd.js → backups-CFRaWe_m.js} +881 -536
- package/dist/chunks/backups-CFRaWe_m.js.map +1 -0
- package/dist/chunks/{contracts-ku5ypHXJ.js → contracts-CMBD1TF9.js} +381 -407
- package/dist/chunks/contracts-CMBD1TF9.js.map +1 -0
- package/dist/chunks/{daemon-TwXk5vb8.js → daemon-qKVECISl.js} +52 -20
- package/dist/chunks/daemon-qKVECISl.js.map +1 -0
- package/dist/chunks/{docker-CGv4Uv7w.js → docker-Cy9Lyvda.js} +4 -3
- package/dist/chunks/docker-Cy9Lyvda.js.map +1 -0
- package/dist/chunks/{down-BlX5X3bm.js → down-pKbGCW9d.js} +22 -17
- package/dist/chunks/down-pKbGCW9d.js.map +1 -0
- package/dist/chunks/{init-DdmqHVra.js → init-BZ7hK9Vf.js} +19 -6
- package/dist/chunks/init-BZ7hK9Vf.js.map +1 -0
- package/dist/chunks/{last-stop-BZ08Z89-.js → last-stop-C-BXz_XI.js} +6 -5
- package/dist/chunks/last-stop-C-BXz_XI.js.map +1 -0
- package/dist/chunks/{layout-D74TGUnr.js → layout-DwTtmund.js} +2 -2
- package/dist/chunks/{layout-D74TGUnr.js.map → layout-DwTtmund.js.map} +1 -1
- package/dist/chunks/lazy-Ce5zEAq1.js +66 -0
- package/dist/chunks/lazy-Ce5zEAq1.js.map +1 -0
- package/dist/chunks/{log-buffer-HnP0jKhZ.js → log-buffer-Dy9HHDMD.js} +114 -50
- package/dist/chunks/log-buffer-Dy9HHDMD.js.map +1 -0
- package/dist/chunks/{logs-gI_69Q1P.js → logs---TI_bxM.js} +23 -21
- package/dist/chunks/logs---TI_bxM.js.map +1 -0
- package/dist/chunks/{migrate-BTlsibvF.js → migrate-Cfoq-Vgh.js} +5 -5
- package/dist/chunks/{migrate-BTlsibvF.js.map → migrate-Cfoq-Vgh.js.map} +1 -1
- package/dist/chunks/{nanny-CjnnrIpm.js → nanny-B-Eu0sFW.js} +3 -3
- package/dist/chunks/{nanny-CjnnrIpm.js.map → nanny-B-Eu0sFW.js.map} +1 -1
- package/dist/chunks/{nanny-20aBXL1o.js → nanny-BtWfy0QH.js} +121 -23
- package/dist/chunks/nanny-BtWfy0QH.js.map +1 -0
- package/dist/chunks/{nanny-DUaAfCV-.js → nanny-ChMtq1Zl.js} +3 -3
- package/dist/chunks/{nanny-DUaAfCV-.js.map → nanny-ChMtq1Zl.js.map} +1 -1
- package/dist/chunks/{nanny-sweep-Ca9kPAVi.js → nanny-sweep-DErnlPY1.js} +5 -4
- package/dist/chunks/nanny-sweep-DErnlPY1.js.map +1 -0
- package/dist/chunks/{parse-B9owE47G.js → parse-DhmG26fI.js} +4 -4
- package/dist/chunks/{parse-B9owE47G.js.map → parse-DhmG26fI.js.map} +1 -1
- package/dist/chunks/{paths-BT94q6-w.js → paths-CGlGDrOU.js} +36 -2
- package/dist/chunks/paths-CGlGDrOU.js.map +1 -0
- package/dist/chunks/{restart-UZgeDukG.js → restart-Des4DrAN.js} +25 -59
- package/dist/chunks/restart-Des4DrAN.js.map +1 -0
- package/dist/chunks/{schema-o7Lgk0V1.js → schema-B240VXcV.js} +11 -10
- package/dist/chunks/schema-B240VXcV.js.map +1 -0
- package/dist/chunks/{secrets-D7PdYh71.js → secrets-BieELnZh.js} +22 -4
- package/dist/chunks/secrets-BieELnZh.js.map +1 -0
- package/dist/chunks/{server-BuIeSsRu.js → server-Bge2r2qQ.js} +3 -3
- package/dist/chunks/{server-BuIeSsRu.js.map → server-Bge2r2qQ.js.map} +1 -1
- package/dist/chunks/{set-password-DegMumPh.js → set-password-D5vZqqSX.js} +7 -7
- package/dist/chunks/set-password-D5vZqqSX.js.map +1 -0
- package/dist/chunks/{set-token-21d1FTDC.js → set-token-obPiEJYk.js} +7 -7
- package/dist/chunks/set-token-obPiEJYk.js.map +1 -0
- package/dist/chunks/{settings-BVSBnIwJ.js → settings-xu-XTfWg.js} +126 -35
- package/dist/chunks/settings-xu-XTfWg.js.map +1 -0
- package/dist/chunks/{setup-temp-XiuAtiW2.js → setup-temp-CAN4_bA-.js} +6 -6
- package/dist/chunks/setup-temp-CAN4_bA-.js.map +1 -0
- package/dist/chunks/{src-BL97vLVb.js → src-BtWMFmzZ.js} +2246 -1061
- package/dist/chunks/src-BtWMFmzZ.js.map +1 -0
- package/dist/chunks/{status-EuWdRq8Q.js → status-DT1EsA-B.js} +12 -8
- package/dist/chunks/status-DT1EsA-B.js.map +1 -0
- package/dist/chunks/{ui-DbPuwddJ.js → ui-D562aqw5.js} +9 -7
- package/dist/chunks/ui-D562aqw5.js.map +1 -0
- package/dist/chunks/{ui-revert-BhqOAhmM.js → ui-revert-EkBBwRTt.js} +3 -3
- package/dist/chunks/{ui-revert-BhqOAhmM.js.map → ui-revert-EkBBwRTt.js.map} +1 -1
- package/dist/chunks/{ui-switch-CMoslPO2.js → ui-switch-BnZTdMDd.js} +3 -3
- package/dist/chunks/{ui-switch-CMoslPO2.js.map → ui-switch-BnZTdMDd.js.map} +1 -1
- package/dist/chunks/{ui-update-TTBBoDik.js → ui-update-_xryLYxw.js} +5 -5
- package/dist/chunks/{ui-update-TTBBoDik.js.map → ui-update-_xryLYxw.js.map} +1 -1
- package/dist/chunks/{up-C4H13hBw.js → up-Pdz-l6IH.js} +25 -11
- package/dist/chunks/up-Pdz-l6IH.js.map +1 -0
- package/dist/chunks/{usage-CSBgLRN5.js → usage-DFrCVXpT.js} +29 -3
- package/dist/chunks/usage-DFrCVXpT.js.map +1 -0
- package/dist/chunks/{workspaces-CAln2sQ7.js → workspaces-DYcfvKV_.js} +16 -8
- package/dist/chunks/workspaces-DYcfvKV_.js.map +1 -0
- package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -1
- package/dist/cli.js +80 -70
- package/dist/cli.js.map +1 -1
- package/dist/client.js +25 -1
- package/dist/client.js.map +1 -1
- package/dist/types/api/backups.d.ts +8 -3
- package/dist/types/api/control.d.ts +4 -3
- package/dist/types/api/events.d.ts +2 -1
- package/dist/types/api/health.d.ts +1 -0
- package/dist/types/api/metrics.d.ts +3 -1
- package/dist/types/api/settings.d.ts +2 -2
- package/dist/types/api/state.d.ts +8 -2
- package/dist/types/app.d.ts +26 -11
- package/dist/types/cli/backup.d.ts +7 -0
- package/dist/types/cli/down.d.ts +5 -0
- package/dist/types/cli/logs.d.ts +14 -2
- package/dist/types/cli/restart.d.ts +0 -1
- package/dist/types/cli/set-password.d.ts +2 -2
- package/dist/types/cli/up.d.ts +8 -2
- package/dist/types/client.d.ts +5618 -11
- package/dist/types/config/secrets.d.ts +2 -0
- package/dist/types/config/settings.d.ts +54 -8
- package/dist/types/config/store.d.ts +16 -3
- package/dist/types/config/workspaces.d.ts +4 -1
- package/dist/types/helpers/copy-tree.d.ts +5 -0
- package/dist/types/helpers/daemon.d.ts +20 -7
- package/dist/types/helpers/error.d.ts +8 -0
- package/dist/types/helpers/event-stream.d.ts +21 -0
- package/dist/types/helpers/openapi.d.ts +12 -24
- package/dist/types/helpers/paths.d.ts +18 -0
- package/dist/types/helpers/utf8-chunks.d.ts +15 -0
- package/dist/types/middleware/auth.d.ts +19 -3
- package/dist/types/providers/host.d.ts +1 -1
- package/dist/types/providers/log-tail.d.ts +27 -0
- package/dist/types/providers/nanny-sweep.d.ts +3 -0
- package/dist/types/providers/nanny.d.ts +10 -0
- package/dist/types/providers/proc.d.ts +9 -0
- package/dist/types/providers/process.d.ts +17 -0
- package/dist/types/providers/telegram.d.ts +45 -3
- package/dist/types/providers/wsl-temperature.d.ts +0 -4
- package/dist/types/services/auth.d.ts +36 -4
- package/dist/types/services/backups.d.ts +125 -1
- package/dist/types/services/ddns.d.ts +5 -0
- package/dist/types/services/exposure.d.ts +54 -1
- package/dist/types/services/history.d.ts +1 -0
- package/dist/types/services/host-monitor.d.ts +1 -0
- package/dist/types/services/log-buffer.d.ts +11 -0
- package/dist/types/services/log-files.d.ts +1 -11
- package/dist/types/services/log-relay.d.ts +0 -1
- package/dist/types/services/panel.d.ts +19 -0
- package/dist/types/services/proxy-certificates/certificates.d.ts +116 -0
- package/dist/types/services/proxy.d.ts +46 -69
- package/dist/types/services/state.d.ts +0 -3
- package/dist/types/services/supervisor/entry.d.ts +10 -0
- package/dist/types/services/supervisor/health.d.ts +3 -2
- package/dist/types/services/supervisor/output.d.ts +126 -0
- package/dist/types/services/supervisor/persistent.d.ts +4 -1
- package/dist/types/services/supervisor/records.d.ts +81 -1
- package/dist/types/services/supervisor.d.ts +32 -0
- package/dist/types/shared/action-outcome.d.ts +25 -0
- package/dist/types/shared/api-client.d.ts +218 -4
- package/dist/types/shared/backup-scope.d.ts +58 -0
- package/dist/types/shared/contracts.d.ts +142 -200
- package/dist/types/shared/ddns-form.d.ts +13 -0
- package/dist/types/shared/form-repair.d.ts +6 -0
- package/dist/types/shared/lazy.d.ts +4 -0
- package/dist/types/shared/live-frames.d.ts +22 -0
- package/dist/types/shared/live-series.d.ts +21 -0
- package/dist/types/shared/live-store.d.ts +72 -0
- package/dist/types/shared/patch-diff.d.ts +13 -2
- package/dist/types/shared/proxy-form.d.ts +2 -0
- package/dist/types/shared/server-form.d.ts +121 -0
- package/dist/types/shared/stream-access.d.ts +20 -0
- package/docs/API.md +45 -16
- package/docs/BACKUPS.md +31 -11
- package/docs/CLI.md +34 -61
- package/docs/DDNS.md +3 -1
- package/docs/NOTIFICATIONS.md +7 -1
- package/docs/REVERSE_PROXY.md +7 -1
- package/docs/SECURITY.md +21 -10
- package/docs/SERVERS.md +102 -23
- package/docs/UI_CREATION.md +10 -1
- package/docs/demo/blank-host-restore.sh +4 -3
- package/package.json +5 -7
- package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +1 -0
- package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +1 -0
- package/uis/stock/dist/assets/LogViewer-DIliXy62.js +1 -0
- package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +1 -0
- package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +39 -0
- package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +1 -0
- package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +2 -0
- package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +1 -0
- package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +2 -0
- package/uis/stock/dist/assets/de-BRITeb0H.js +1 -0
- package/uis/stock/dist/assets/es-B2zIEssV.js +1 -0
- package/uis/stock/dist/assets/fr-s0ZOBEqh.js +1 -0
- package/uis/stock/dist/assets/index-C1MehbKy.css +2 -0
- package/uis/stock/dist/assets/index-CnBN54wF.js +15 -0
- package/uis/stock/dist/assets/ja-CU7MR85V.js +1 -0
- package/uis/stock/dist/assets/ko-tL5Me6d-.js +1 -0
- package/uis/stock/dist/assets/ru-92yrvkNJ.js +1 -0
- package/uis/stock/dist/assets/vi-CzvY16k2.js +1 -0
- package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +1 -0
- package/uis/stock/dist/index.html +3 -2
- package/uis/stock/dist/ui.json +3 -3
- package/dist/chunks/archive-DpCwA8Nf.js.map +0 -1
- package/dist/chunks/atomic-CEfCUfkQ.js.map +0 -1
- package/dist/chunks/backup-CPrJVPJI.js.map +0 -1
- package/dist/chunks/backups-Bd2SF2qd.js.map +0 -1
- package/dist/chunks/contracts-ku5ypHXJ.js.map +0 -1
- package/dist/chunks/daemon-TwXk5vb8.js.map +0 -1
- package/dist/chunks/docker-CGv4Uv7w.js.map +0 -1
- package/dist/chunks/down-BlX5X3bm.js.map +0 -1
- package/dist/chunks/init-DdmqHVra.js.map +0 -1
- package/dist/chunks/last-stop-BZ08Z89-.js.map +0 -1
- package/dist/chunks/log-buffer-HnP0jKhZ.js.map +0 -1
- package/dist/chunks/logs-gI_69Q1P.js.map +0 -1
- package/dist/chunks/nanny-20aBXL1o.js.map +0 -1
- package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +0 -1
- package/dist/chunks/paths-BT94q6-w.js.map +0 -1
- package/dist/chunks/restart-UZgeDukG.js.map +0 -1
- package/dist/chunks/schema-o7Lgk0V1.js.map +0 -1
- package/dist/chunks/secrets-D7PdYh71.js.map +0 -1
- package/dist/chunks/set-password-DegMumPh.js.map +0 -1
- package/dist/chunks/set-token-21d1FTDC.js.map +0 -1
- package/dist/chunks/settings-BVSBnIwJ.js.map +0 -1
- package/dist/chunks/setup-temp-XiuAtiW2.js.map +0 -1
- package/dist/chunks/src-BL97vLVb.js.map +0 -1
- package/dist/chunks/status-EuWdRq8Q.js.map +0 -1
- package/dist/chunks/ui-DbPuwddJ.js.map +0 -1
- package/dist/chunks/up-C4H13hBw.js.map +0 -1
- package/dist/chunks/usage-CSBgLRN5.js.map +0 -1
- package/dist/chunks/workspaces-CAln2sQ7.js.map +0 -1
- package/docs/RESTORE_DEMO.md +0 -306
- package/uis/stock/dist/assets/de-DyGrM1KK.js +0 -1
- package/uis/stock/dist/assets/es-BebHdc0E.js +0 -1
- package/uis/stock/dist/assets/fr-DsDTrxhI.js +0 -1
- package/uis/stock/dist/assets/index-6LANO2Ua.css +0 -2
- package/uis/stock/dist/assets/index-D06cUZbM.js +0 -56
- package/uis/stock/dist/assets/ja-D3RARJjW.js +0 -1
- package/uis/stock/dist/assets/ko-CKI3dFoD.js +0 -1
- package/uis/stock/dist/assets/ru-DEU5ujXt.js +0 -1
- package/uis/stock/dist/assets/vi-ULKPnasj.js +0 -1
- package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"docker-Cy9Lyvda.js","names":[],"sources":["../../src/providers/docker.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\nimport { type } from 'arktype'\nimport { lazy } from '#src/shared/lazy'\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * CPU and memory of a compose project's **containers**, which the process-tree sampler cannot see.\n *\n * A compose stack is not a process tree: `docker compose up` is a wrapper, and its containers live\n * in another namespace. A stack burning 99% CPU reported `cpuPercent: 0` — the wrapper — so\n * `resources.maxRssBytes` could never fire for a leaking container.\n *\n * Detection is deliberately narrow: `command` must be `docker` (with `compose`) or `docker-compose`.\n * A shell that runs docker and a `docker run` are not recognized and keep the process-tree sample,\n * because a wrong guess attributes a stranger's containers to an entry. An entry's own `env` and\n * `envFile` **are** read; the panel's own environment is not. Attribution is by compose's own\n * labels, never \"every container on this machine\".\n *\n * See `.agentDocs/GOTCHAS.md` (\"Metrics\") for the measured failure and the deliberate limits.\n */\n\n/** How long a completed reading is reused. */\nconst DOCKER_CACHE_MS = 10_000\n\n/**\n * `docker stats --no-stream` samples for about a second before printing (measured 2.0–2.2 s per\n * call here), so it is not a read to perform inside the 1 s supervisor tick: it would delay the\n * whole state frame. Nor one per entry per 5 s sample, which is why one call names every container\n * of every docker-backed entry.\n *\n * Reusing a reading for ten seconds keeps the frame responsive and cuts the spawns from roughly\n * 17 000 a day per entry to about 8 600 for the whole workspace; a memory ceiling that acts up to\n * ~12 s late is still a ceiling. The same discipline, and for the same reason, as `SWAP_CACHE_MS`\n * in `src/providers/host.ts`.\n */\n\n/** The file names compose itself tries, in order, in the directory it runs from (or a parent of it). */\nconst COMPOSE_FILES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml']\n\n/** A compose global option before the subcommand, whose value is the next word. */\nconst COMPOSE_VALUE_FLAGS = new Set(['-p', '--project-name', '-f', '--file', '--project-directory', '--env-file', '--profile', '--ansi', '--progress', '--parallel'])\n\n/** A compose global option before the subcommand that takes no value. */\nconst COMPOSE_VALUELESS_FLAGS = new Set(['--compatibility', '--dry-run', '--no-ansi', '--verbose', '-h', '--help'])\n\n/** `docker`'s own options before `compose`, whose value is the next word. */\nconst DOCKER_VALUE_FLAGS = new Set(['-c', '--context', '-H', '--host', '-l', '--log-level', '--config'])\n\nconst PS_FORMAT = '{{.ID}}\\t{{.Names}}\\t{{.Label \"com.docker.compose.project\"}}\\t{{.Label \"com.docker.compose.project.config_files\"}}'\n\n/** One container docker reports, with the labels that attribute it to a project. */\nexport interface ContainerRow {\n id: string\n name: string\n project: string | null\n configFiles: string[]\n}\n\n/** What one compose entry's containers add up to. */\nexport interface ComposeReading {\n /** Summed CPU share, so 200 is two saturated cores. */\n cpuPercent: number\n rssBytes: number\n /** Processes inside the containers — the same question the tree sampler answers. */\n processes: number\n /** How many containers the sum covers. */\n containers: number\n}\n\n/** The evidence that an entry runs a compose project, and the key its containers are attributed by. */\nexport interface ComposeTarget {\n /** What the caller looks the reading up by: the project, else the compose files. */\n key: string\n project: string | null\n configFiles: string[]\n}\n\nconst EMPTY: ReadonlyMap<string, ComposeReading> = new Map()\n\n/** One `docker stats --format json` line. Unknown keys are normal — docker adds fields over time. */\nconst statsLineSchema = lazy(() => type({\n 'CPUPerc': 'string',\n 'ID': 'string',\n 'MemUsage': 'string',\n 'PIDs': 'string',\n '+': 'ignore',\n}))\n\nconst BYTE_SCALES: Record<string, number> = {\n b: 1,\n kb: 1000,\n kib: 1024,\n mb: 1000 ** 2,\n mib: 1024 ** 2,\n gb: 1000 ** 3,\n gib: 1024 ** 3,\n tb: 1000 ** 4,\n tib: 1024 ** 4,\n}\n\n/** `816KiB` -> bytes. Docker prints binary units for memory, and `0B` for a container that is not running. */\nexport function parseHumanBytes(value: string): number | null {\n const match = /^([\\d.]+)\\s*([a-z]+)$/i.exec(value.trim())\n if (match === null)\n return null\n const amount = Number.parseFloat(match[1]!)\n const scale = BYTE_SCALES[match[2]!.toLowerCase()]\n if (scale === undefined || !Number.isFinite(amount))\n return null\n return amount * scale\n}\n\n/** `MemUsage` is `used / limit`; only the used part measures this stack. */\nexport function parseMemUsage(value: string): number | null {\n const [used = ''] = value.split('/')\n return parseHumanBytes(used)\n}\n\n/** `99.61%` -> 99.61. `--` is docker's \"no reading\", which must not become a zero. */\nexport function parsePercent(value: string): number | null {\n const match = /^([\\d.]+)%$/.exec(value.trim())\n if (match === null)\n return null\n const parsed = Number.parseFloat(match[1]!)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/** The containers docker reports, from the tab-separated `--format` above. */\nexport function parseDockerPs(text: string): ContainerRow[] {\n const rows: ContainerRow[] = []\n for (const line of text.split(/\\r?\\n/)) {\n if (line.trim().length === 0)\n continue\n const [id = '', name = '', project = '', files = ''] = line.split('\\t')\n if (id.trim().length === 0)\n continue\n rows.push({\n id: id.trim(),\n name: name.trim(),\n project: project.trim().length > 0 ? project.trim() : null,\n configFiles: files.split(',').map(entry => entry.trim()).filter(entry => entry.length > 0),\n })\n }\n return rows\n}\n\n/** Per-container readings from `docker stats --no-stream --format json`, keyed by container id. */\nexport function parseDockerStats(text: string): Map<string, Omit<ComposeReading, 'containers'>> {\n const readings = new Map<string, Omit<ComposeReading, 'containers'>>()\n for (const line of text.split(/\\r?\\n/)) {\n if (line.trim().length === 0)\n continue\n let raw: unknown\n try {\n raw = JSON.parse(line)\n }\n catch {\n continue\n }\n const parsed = statsLineSchema(raw)\n if (parsed instanceof type.errors)\n continue\n const cpuPercent = parsePercent(parsed.CPUPerc)\n const rssBytes = parseMemUsage(parsed.MemUsage)\n const processes = Number.parseInt(parsed.PIDs, 10)\n // One unreadable field makes the container unmeasured; a zero there would be invented.\n if (cpuPercent === null || rssBytes === null || !Number.isInteger(processes))\n continue\n /*\n * A container with no processes is not idle — it is not running this stack's work.\n *\n * `docker stats` prints `0.00% / 0B / 0 PIDs` for one in `Restarting`, and publishing that is\n * the zero the repo forbids: measured, a flapping entry served `hh_server_rss_bytes 0` and\n * `hh_server_cpu_percent 0`, steady while reported `running`, indistinguishable from a real\n * idle reading and structurally unable to trip `resources.maxRssBytes`. `PIDs 0` is the one\n * field that says so — a live container always has at least one.\n */\n if (processes === 0)\n continue\n // Docker prints a rounded human size (`1.035MiB`), so the byte value is fractional; rounded to\n // a whole byte here, so every reading has the same unit whatever produced it.\n readings.set(parsed.ID, { cpuPercent, rssBytes: Math.round(rssBytes), processes })\n }\n return readings\n}\n\n/** Same file, on a platform whose paths are case-insensitive. */\nfunction samePath(left: string, right: string): boolean {\n const a = path.resolve(left)\n const b = path.resolve(right)\n return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b\n}\n\n/** The argv of the compose command this entry runs, or null when the entry is not docker-backed. */\nfunction composeArgv(command: string, args: string[]): string[] | null {\n const name = path.basename(command).toLowerCase().replace(/\\.exe$/, '')\n if (name === 'docker-compose')\n return args\n if (name !== 'docker')\n return null\n\n for (let index = 0; index < args.length; index++) {\n const arg = args[index]!\n if (arg === 'compose')\n return args.slice(index + 1)\n if (arg.startsWith('-')) {\n // `docker --context box compose up`: the flag's value is not the subcommand.\n if (DOCKER_VALUE_FLAGS.has(arg) && !arg.includes('='))\n index += 1\n continue\n }\n // A different docker subcommand, so there is no compose project behind this entry.\n return null\n }\n return null\n}\n\n/**\n * The compose options before the subcommand, and where the subcommand starts.\n *\n * Compose requires its global options **before** the subcommand — it answers `unknown shorthand\n * flag: 'p'` for `up -p x` — so only this leading run can carry the project name or the file.\n */\nexport function parseComposeHead(args: string[]): {\n subcommandAt: number\n projectName: string | null\n files: string[]\n projectDirectory: string | null\n} {\n const result = { subcommandAt: args.length, projectName: null as string | null, files: [] as string[], projectDirectory: null as string | null }\n\n for (let index = 0; index < args.length; index++) {\n const arg = args[index]!\n if (!arg.startsWith('-')) {\n result.subcommandAt = index\n return result\n }\n // `--file=compose.yml` and the short attached `-fcompose.yml` / `-pblog` forms.\n if (arg.startsWith('--') && arg.includes('=')) {\n const [flag, value = ''] = [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)]\n if (flag === '--project-name' || flag === '--file' || flag === '--project-directory') {\n if (flag === '--project-name')\n result.projectName = value\n else if (flag === '--file')\n result.files.push(value)\n else result.projectDirectory = value\n }\n continue\n }\n if (!arg.startsWith('--') && arg.length > 2 && COMPOSE_VALUE_FLAGS.has(arg.slice(0, 2))) {\n const value = arg.slice(2)\n if (arg.startsWith('-p'))\n result.projectName = value\n else if (arg.startsWith('-f'))\n result.files.push(value)\n continue\n }\n\n if (COMPOSE_VALUELESS_FLAGS.has(arg))\n continue\n if (!COMPOSE_VALUE_FLAGS.has(arg))\n // An option this does not know: it still takes no *subcommand* position, so keep scanning.\n continue\n\n const value = args[index + 1]\n if (value === undefined)\n return result\n index += 1\n if (arg === '-p' || arg === '--project-name')\n result.projectName = value\n else if (arg === '-f' || arg === '--file')\n result.files.push(value)\n else if (arg === '--project-directory')\n result.projectDirectory = value\n }\n\n return result\n}\n\n/** The compose file compose would pick: the first known name here or in a parent directory. */\nexport function findComposeFile(from: string): string[] {\n let dir = path.resolve(from)\n for (;;) {\n for (const name of COMPOSE_FILES) {\n const candidate = path.join(dir, name)\n try {\n if (fs.statSync(candidate).isFile())\n return [candidate]\n }\n catch {\n // Not this name.\n }\n }\n const parent = path.dirname(dir)\n if (parent === dir)\n return []\n dir = parent\n }\n}\n\n/** Whether this argv runs a compose stack, without resolving anything — a cheap pre-check. */\nexport function isComposeCommand(command: string, args: string[]): boolean {\n return composeArgv(command, args) !== null\n}\n\n/**\n * The compose project an entry runs, from evidence in its own config: the command it spawns, its\n * argv, its cwd and its environment. `null` means \"sample the process tree\", which is the right\n * answer for every entry this cannot attribute honestly — see the module comment for the limits.\n */\nexport function composeTarget(input: {\n command: string\n args: string[]\n cwd: string\n env?: Record<string, string | undefined>\n}): ComposeTarget | null {\n const composeArgs = composeArgv(input.command, input.args)\n if (composeArgs === null)\n return null\n\n const head = parseComposeHead(composeArgs)\n /*\n * The entry's own environment only — **not** `process.env`.\n *\n * The panel itself often runs under compose, and inheriting its `COMPOSE_PROJECT_NAME` made that\n * one name every entry's project: measured with two entries and the panel's env carrying\n * `COMPOSE_PROJECT_NAME=shared-stack`, both reported `cpuPercent: 199.4, rssBytes: 183500800` —\n * each summing both stacks — and a memory ceiling on one fired on the other's containers. The\n * panel's environment is not the entry's.\n */\n const project = head.projectName\n ?? (input.env?.COMPOSE_PROJECT_NAME !== undefined && input.env.COMPOSE_PROJECT_NAME.length > 0\n ? input.env.COMPOSE_PROJECT_NAME\n : null)\n\n const directory = head.projectDirectory === null ? input.cwd : path.resolve(input.cwd, head.projectDirectory)\n const configFiles = head.files.length > 0\n ? head.files.map(file => path.resolve(directory, file))\n : findComposeFile(directory)\n\n if (project === null && configFiles.length === 0)\n // Neither label to attribute by: these containers cannot be told from the rest of the box's.\n return null\n\n return { key: project === null ? `files:${configFiles.join('\\u0000')}` : `project:${project}`, project, configFiles }\n}\n\n/**\n * The containers belonging to one target, or `null` when that cannot be decided.\n *\n * `null` is the ambiguity refusal: two projects sharing a compose file can only be told apart by an\n * explicit project name, so picking one would report another stack's CPU and RSS as this entry's.\n */\nexport function attributeContainers(target: ComposeTarget, rows: ContainerRow[]): ContainerRow[] | null {\n if (target.project !== null)\n return rows.filter(row => row.project === target.project)\n\n const matched = rows.filter(row => row.configFiles.some(file => target.configFiles.some(own => samePath(file, own))))\n const projects = new Set(matched.map(row => row.project))\n return projects.size <= 1 ? matched : null\n}\n\n/**\n * The sum over one project's containers.\n *\n * Exported so the arithmetic is testable against the shapes docker actually prints; the class below\n * only decides when to spawn. `null` for no containers, and for a listed container without a\n * reading — an under-report is the one direction a memory ceiling must not miss.\n */\nexport function sumContainers(rows: ContainerRow[], readings: Map<string, Omit<ComposeReading, 'containers'>>): ComposeReading | null {\n if (rows.length === 0)\n return null\n let cpuPercent = 0\n let rssBytes = 0\n let processes = 0\n for (const row of rows) {\n const reading = readings.get(row.id)\n if (reading === undefined)\n return null\n cpuPercent += reading.cpuPercent\n rssBytes += reading.rssBytes\n processes += reading.processes\n }\n return {\n cpuPercent: Math.round(cpuPercent * 10) / 10,\n rssBytes: Math.round(rssBytes),\n processes,\n containers: rows.length,\n }\n}\n\n/** Whether a container publishing a port belongs to the stack this entry itself declares. */\nexport function isOwnStack(holder: { project: string | null, composeDir: string | null }, target: ComposeTarget | null): boolean {\n if (target === null)\n return false\n // A non-null project on both sides is the exact answer, and `null === null` must not read as one.\n if (holder.project !== null && target.project !== null)\n return holder.project === target.project\n // Otherwise the working directory compose recorded is the one holding this entry's compose file.\n // Most entries never pass `-p`, so the project name is unknown on both sides and the directory is\n // the evidence that remains — measured: without this, an entry's own already-up stack read as a\n // stranger, and the only escape hatch offered was `kill`.\n if (holder.composeDir === null)\n return false\n return target.configFiles.some(file => samePath(path.dirname(file), holder.composeDir!))\n}\n\n/** One target's running containers from a fresh `docker ps`, or `null` when docker cannot answer. */\nexport async function composeContainers(target: ComposeTarget): Promise<ContainerRow[] | null> {\n try {\n const listing = await execFileAsync('docker', [\n 'ps',\n '--filter',\n 'label=com.docker.compose.project',\n '--format',\n PS_FORMAT,\n ], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 })\n return attributeContainers(target, parseDockerPs(listing.stdout))\n }\n catch {\n // Docker absent, down or not permissioned. \"Cannot ask\" is not \"nothing is running\".\n return null\n }\n}\n\n/**\n * Stops every container of one target and reports what is still running afterwards.\n *\n * The answer comes from a **fresh listing**, not from `docker stop`'s exit code: a stop that\n * printed success for a container still listed is the empty success this exists to refuse.\n * `null` means docker could not be asked, which is not the same as \"it stopped\".\n */\nexport async function stopComposeContainers(target: ComposeTarget): Promise<{ stopped: string[], survivors: string[] } | null> {\n const before = await composeContainers(target)\n if (before === null)\n return null\n if (before.length === 0)\n return { stopped: [], survivors: [] }\n\n try {\n await execFileAsync('docker', ['stop', ...before.map(row => row.name)], { timeout: 120_000, maxBuffer: 4 * 1024 * 1024 })\n }\n catch {\n // A non-zero exit only means one name failed; the relisting below is what decides.\n }\n\n const after = await composeContainers(target)\n if (after === null)\n return null\n const remaining = new Set(after.map(row => row.name))\n return {\n stopped: before.map(row => row.name).filter(name => !remaining.has(name)),\n survivors: after.map(row => row.name),\n }\n}\n\n/**\n * Container readings per compose project, refreshed out of band.\n *\n * One `docker ps` and one batched `docker stats` serve every docker-backed entry, however many\n * there are. When docker cannot be reached the cache is emptied rather than filled with zeros: the\n * caller keeps the process-tree sample, which is at least true of the wrapper, and a metric with no\n * reading is never published as an idle one.\n */\nexport class DockerMetrics {\n private cache: { at: number, byKey: Map<string, ComposeReading> } | null = null\n private refreshing: Promise<void> | null = null\n\n /**\n * The last completed readings, and a refresh started when they are stale.\n *\n * Deliberately synchronous: the spawn takes seconds, and awaiting it here would stretch the\n * supervisor tick that publishes the whole state frame. A fresh reading lands on a later tick.\n */\n readings(targets: ComposeTarget[], now = Date.now()): ReadonlyMap<string, ComposeReading> {\n // A stamp in the future (a backwards clock step) counts as stale, so a reading cannot stick.\n const fresh = this.cache !== null && now >= this.cache.at && now - this.cache.at < DOCKER_CACHE_MS\n if (!fresh && targets.length > 0 && this.refreshing === null) {\n this.refreshing = this.refresh(targets, now).finally(() => {\n this.refreshing = null\n })\n }\n return this.cache?.byKey ?? EMPTY\n }\n\n /** Resolves once the refresh in flight, if any, has finished. */\n async settle(): Promise<void> {\n await this.refreshing\n }\n\n /** One listing and one batched stats call; replaces the cache only with a complete answer. */\n async refresh(targets: ComposeTarget[], now = Date.now()): Promise<void> {\n const byKey = new Map<string, ComposeReading>()\n try {\n const listing = await execFileAsync('docker', [\n 'ps',\n // A compose container is the only kind this can attribute, and the filter also keeps a box\n // full of `docker run` containers out of the listing.\n '--filter',\n 'label=com.docker.compose.project',\n '--format',\n PS_FORMAT,\n ], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 })\n\n const rows = parseDockerPs(listing.stdout)\n const perTarget = new Map<string, ContainerRow[]>()\n const ids = new Set<string>()\n for (const target of targets) {\n const matched = attributeContainers(target, rows)\n // No running container of this project: there is nothing of the stack to measure, and the\n // wrapper the entry spawned is the truth of what is running. The caller keeps its sample.\n if (matched === null || matched.length === 0)\n continue\n perTarget.set(target.key, matched)\n for (const row of matched) ids.add(row.id)\n }\n if (ids.size === 0) {\n this.cache = { at: now, byKey }\n return\n }\n\n const stats = await execFileAsync('docker', ['stats', '--no-stream', '--format', 'json', ...ids], {\n timeout: 15_000,\n maxBuffer: 8 * 1024 * 1024,\n })\n const readings = parseDockerStats(stats.stdout)\n for (const [key, matched] of perTarget) {\n // A partial sum is not a smaller reading, it is a wrong one; only complete sums are kept.\n const summed = sumContainers(matched, readings)\n if (summed !== null)\n byKey.set(key, summed)\n }\n }\n catch {\n // docker absent, not running or not permissioned: no reading, never a zero.\n byKey.clear()\n }\n this.cache = { at: now, byKey }\n }\n}\n"],"mappings":";;;;;;;;AAQA,IAAM,gBAAgB,UAAU,QAAQ;;;;;;;;;;;;;;;;;AAmBxC,IAAM,kBAAkB;;;;;;;;;;;;;AAexB,IAAM,gBAAgB;CAAC;CAAgB;CAAe;CAAuB;AAAoB;;AAGjG,IAAM,sCAAsB,IAAI,IAAI;CAAC;CAAM;CAAkB;CAAM;CAAU;CAAuB;CAAc;CAAa;CAAU;CAAc;AAAY,CAAC;;AAGpK,IAAM,0CAA0B,IAAI,IAAI;CAAC;CAAmB;CAAa;CAAa;CAAa;CAAM;AAAQ,CAAC;;AAGlH,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAM;CAAa;CAAM;CAAU;CAAM;CAAe;AAAU,CAAC;AAEvG,IAAM,YAAY;AA6BlB,IAAM,wBAA6C,IAAI,IAAI;;AAG3D,IAAM,kBAAkB,WAAW,KAAK;CACtC,WAAW;CACX,MAAM;CACN,YAAY;CACZ,QAAQ;CACR,KAAK;AACP,CAAC,CAAC;AAEF,IAAM,cAAsC;CAC1C,GAAG;CACH,IAAI;CACJ,KAAK;CACL,IAAI,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C,EAAA,CAEb,MAAM;GACzC,MAAM,4BAAY,IAAI,IAA4B;GAClD,MAAM,sBAAM,IAAI,IAAY;GAC5B,KAAK,MAAM,UAAU,SAAS;IAC5B,MAAM,UAAU,oBAAoB,QAAQ,IAAI;IAGhD,IAAI,YAAY,QAAQ,QAAQ,WAAW,GACzC;IACF,UAAU,IAAI,OAAO,KAAK,OAAO;IACjC,KAAK,MAAM,OAAO,SAAS,IAAI,IAAI,IAAI,EAAE;GAC3C;GACA,IAAI,IAAI,SAAS,GAAG;IAClB,KAAK,QAAQ;KAAE,IAAI;KAAK;IAAM;IAC9B;GACF;GAMA,MAAM,WAAW,kBAAiB,MAJd,cAAc,UAAU;IAAC;IAAS;IAAe;IAAY;IAAQ,GAAG;GAAG,GAAG;IAChG,SAAS;IACT,WAAW;GACb,CAAC,EAAA,CACuC,MAAM;GAC9C,KAAK,MAAM,CAAC,KAAK,YAAY,WAAW;IAEtC,MAAM,SAAS,cAAc,SAAS,QAAQ;IAC9C,IAAI,WAAW,MACb,MAAM,IAAI,KAAK,MAAM;GACzB;EACF,QACM;GAEJ,MAAM,MAAM;EACd;EACA,KAAK,QAAQ;GAAE,IAAI;GAAK;EAAM;CAChC;AACF"}
|
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { d as dim, g as paint, h as invocation, m as green, r as versionMismatchNote, u as delay, y as refusal } from "../cli.js";
|
|
2
|
-
import { n as recordCleanStop } from "./last-stop-
|
|
3
|
-
import { r as isComposeCommand } from "./docker-
|
|
2
|
+
import { n as recordCleanStop } from "./last-stop-C-BXz_XI.js";
|
|
3
|
+
import { r as isComposeCommand } from "./docker-Cy9Lyvda.js";
|
|
4
4
|
import process from "node:process";
|
|
5
5
|
import { defineCommand } from "citty";
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import { spawnSync } from "node:child_process";
|
|
8
8
|
//#region src/cli/down.ts
|
|
9
9
|
async function runDown(options = {}) {
|
|
10
|
-
const { clearRuntime, configuredPanelAddress, isLiveLiveness, readRuntime, requestShutdown, runtimeLiveness } = await import("./daemon-
|
|
11
|
-
const result = {
|
|
10
|
+
const { clearRuntime, configuredPanelAddress, isLiveLiveness, readRuntime, requestShutdown, runtimeLiveness } = await import("./daemon-qKVECISl.js");
|
|
11
|
+
const result = {
|
|
12
|
+
ok: true,
|
|
13
|
+
stoppedPersistent: []
|
|
14
|
+
};
|
|
12
15
|
const before = options.withPersistent === true ? await livePersistents() : [];
|
|
13
16
|
const finish = async () => {
|
|
14
17
|
result.stoppedPersistent.push(...await reportPersistent(options, before));
|
|
@@ -17,12 +20,13 @@ async function runDown(options = {}) {
|
|
|
17
20
|
const runtime = readRuntime();
|
|
18
21
|
if (runtime === null) {
|
|
19
22
|
const leftover = await configuredPanelAddress();
|
|
20
|
-
if (leftover
|
|
21
|
-
refusal(`
|
|
23
|
+
if (leftover?.kind === "panel") {
|
|
24
|
+
refusal(`this home's panel is answering on ${leftover.url}, but no run.json records which process owns it — stop it yourself, or free that port, then run \`${invocation()} up\``);
|
|
22
25
|
process.exitCode = 1;
|
|
26
|
+
result.ok = false;
|
|
23
27
|
return finish();
|
|
24
28
|
}
|
|
25
|
-
process.stdout.write("home-hosted is not running\n");
|
|
29
|
+
process.stdout.write(leftover?.kind === "other" ? `home-hosted is not running (port ${leftover.port} is taken by another process — nothing of this home to stop)\n` : "home-hosted is not running\n");
|
|
26
30
|
return finish();
|
|
27
31
|
}
|
|
28
32
|
const liveness = await runtimeLiveness(runtime);
|
|
@@ -66,6 +70,7 @@ async function runDown(options = {}) {
|
|
|
66
70
|
refusal(`could not stop pid ${runtime.pid} — it is still running, and its record was kept`);
|
|
67
71
|
process.stderr.write(`${dim(`stop it yourself with \`kill -9 ${runtime.pid}\` (Windows: \`taskkill /PID ${runtime.pid} /F\`), then run \`down\` again`)}\n`);
|
|
68
72
|
process.exitCode = 1;
|
|
73
|
+
result.ok = false;
|
|
69
74
|
return finish();
|
|
70
75
|
}
|
|
71
76
|
clearRuntime();
|
|
@@ -80,8 +85,8 @@ async function runDown(options = {}) {
|
|
|
80
85
|
* `down` reads them itself — after a crash there is nobody left to ask.
|
|
81
86
|
*/
|
|
82
87
|
async function livePersistents() {
|
|
83
|
-
const { livePersistentEntries } = await import("./nanny-sweep-
|
|
84
|
-
const { hhDir } = await import("./paths-
|
|
88
|
+
const { livePersistentEntries } = await import("./nanny-sweep-DErnlPY1.js");
|
|
89
|
+
const { hhDir } = await import("./paths-CGlGDrOU.js").then((n) => n.d);
|
|
85
90
|
return livePersistentEntries(hhDir);
|
|
86
91
|
}
|
|
87
92
|
/** `workspace/id`, because a server id is only unique inside its workspace. */
|
|
@@ -102,7 +107,7 @@ async function stopPersistents(before) {
|
|
|
102
107
|
done,
|
|
103
108
|
survived
|
|
104
109
|
};
|
|
105
|
-
const { stopPersistentEntries } = await import("./nanny-sweep-
|
|
110
|
+
const { stopPersistentEntries } = await import("./nanny-sweep-DErnlPY1.js");
|
|
106
111
|
const results = await stopPersistentEntries(handles, { stopFor: await stopPolicyLookup() });
|
|
107
112
|
for (const result of results) {
|
|
108
113
|
const label = persistentLabel(result.handle);
|
|
@@ -138,7 +143,7 @@ function exitCodeForStops(results) {
|
|
|
138
143
|
* back to the defaults — the host is being brought down either way.
|
|
139
144
|
*/
|
|
140
145
|
async function stopPolicyLookup() {
|
|
141
|
-
const { stopSchema } = await import("./contracts-
|
|
146
|
+
const { stopSchema } = await import("./contracts-CMBD1TF9.js").then((n) => n.f);
|
|
142
147
|
const read = await serversReader();
|
|
143
148
|
const policies = /* @__PURE__ */ new Map();
|
|
144
149
|
return (handle) => {
|
|
@@ -162,8 +167,8 @@ async function stopPolicyLookup() {
|
|
|
162
167
|
* replaced to avoid, so an unreadable config widens the wait instead of shortening it.
|
|
163
168
|
*/
|
|
164
169
|
async function configuredServers() {
|
|
165
|
-
const { WorkspaceRegistry } = await import("./workspaces-
|
|
166
|
-
const { DEFAULT_WORKSPACE_ID, workspacesPath } = await import("./paths-
|
|
170
|
+
const { WorkspaceRegistry } = await import("./workspaces-DYcfvKV_.js").then((n) => n.i);
|
|
171
|
+
const { DEFAULT_WORKSPACE_ID, workspacesPath } = await import("./paths-CGlGDrOU.js").then((n) => n.d);
|
|
167
172
|
let ids = [DEFAULT_WORKSPACE_ID];
|
|
168
173
|
let complete = true;
|
|
169
174
|
if (fs.existsSync(workspacesPath)) {
|
|
@@ -196,8 +201,8 @@ async function configuredServers() {
|
|
|
196
201
|
*/
|
|
197
202
|
async function serversReader() {
|
|
198
203
|
const { readStateFile } = await import("./config-text-DifCHhnz.js").then((n) => n.t);
|
|
199
|
-
const { parseServersFile, parseWorkspaceSettings } = await import("./parse-
|
|
200
|
-
const { workspaceServersPath, workspaceSettingsPath } = await import("./paths-
|
|
204
|
+
const { parseServersFile, parseWorkspaceSettings } = await import("./parse-DhmG26fI.js").then((n) => n.a);
|
|
205
|
+
const { workspaceServersPath, workspaceSettingsPath } = await import("./paths-CGlGDrOU.js").then((n) => n.d);
|
|
201
206
|
return (workspaceId) => {
|
|
202
207
|
const file = workspaceServersPath(workspaceId);
|
|
203
208
|
if (!fs.existsSync(file)) return {
|
|
@@ -326,7 +331,7 @@ async function reportPersistent(options, before = []) {
|
|
|
326
331
|
return stopped;
|
|
327
332
|
}
|
|
328
333
|
async function waitForExit(pid, timeoutMs) {
|
|
329
|
-
const { isProcessAlive } = await import("./daemon-
|
|
334
|
+
const { isProcessAlive } = await import("./daemon-qKVECISl.js");
|
|
330
335
|
const deadline = Date.now() + timeoutMs;
|
|
331
336
|
while (Date.now() < deadline) {
|
|
332
337
|
if (!isProcessAlive(pid)) return true;
|
|
@@ -375,4 +380,4 @@ var downCommand = defineCommand({
|
|
|
375
380
|
//#endregion
|
|
376
381
|
export { downCommand, runDown };
|
|
377
382
|
|
|
378
|
-
//# sourceMappingURL=down-
|
|
383
|
+
//# sourceMappingURL=down-pKbGCW9d.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"down-pKbGCW9d.js","names":[],"sources":["../../src/cli/down.ts"],"sourcesContent":["import type { PersistentHandle } from '#src/providers/nanny-sweep'\nimport type { ServerConfig, StopConfig } from '#src/shared/contracts'\nimport { spawnSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { delay, dim, green, invocation, paint, refusal } from '#src/cli/io'\nimport { recordCleanStop } from '#src/helpers/last-stop'\nimport { versionMismatchNote } from '#src/helpers/version'\nimport { isComposeCommand } from '#src/providers/docker'\n\n/**\n * `down` stops the panel and everything it supervises.\n *\n * A `persistent: true` entry is the one thing it deliberately leaves running, which is what\n * `--with-persistent` changes: the same stop, extended to those entries. While the panel is\n * up they are stopped through it, so the stop is recorded like a click in the UI; once it is\n * gone their nannies are signalled directly, because the state files are then the only record.\n */\n\nexport interface DownOptions {\n /** Also stop every persistent entry, in every workspace. */\n withPersistent?: boolean\n}\n\n/** Which persistent entries this stop ended, as `(workspace, id)` — what `restart` starts back. */\nexport interface DownResult {\n /**\n * False when a panel of this home may still be running: it could not be stopped, or it answers\n * without a `run.json` to stop it by. `restart` must not go on to `up` over it.\n */\n ok: boolean\n stoppedPersistent: Array<{ workspaceId: string, serverId: string }>\n}\n\nexport async function runDown(options: DownOptions = {}): Promise<DownResult> {\n const { clearRuntime, configuredPanelAddress, isLiveLiveness, readRuntime, requestShutdown, runtimeLiveness } = await import('#src/helpers/daemon')\n\n const result: DownResult = { ok: true, stoppedPersistent: [] }\n // What was running before this command did anything. The panel ends the entries itself when\n // asked, so afterwards they are simply gone — and the difference between \"was running\" and\n // \"still running\" is the only account of what was stopped. `restart` starts exactly that list.\n const before = options.withPersistent === true ? await livePersistents() : []\n // Filled by whichever path got here, so one place decides what was stopped and what survived.\n const finish = async (): Promise<DownResult> => {\n result.stoppedPersistent.push(...await reportPersistent(options, before))\n return result\n }\n\n const runtime = readRuntime()\n if (runtime === null) {\n // \"Nothing is running\" is a claim about the machine, not just about the record — and the record\n // is what `run.json` holds. A panel whose `run.json` is gone still listens, and saying \"not\n // running\" over it made `down && up` in a deploy script proceed against a live panel that then\n // held its port. Nothing here can *prove* ownership of a pid, so this only reports: it never\n // signals what it cannot identify.\n const leftover = await configuredPanelAddress()\n if (leftover?.kind === 'panel') {\n // Refused, not a success line: a deploy chain that continues here starts a second panel\n // against a live one. It says where and what to do, and signals nothing.\n refusal(`this home's panel is answering on ${leftover.url}, but no run.json records which process owns it — stop it yourself, or free that port, then run \\`${invocation()} up\\``)\n process.exitCode = 1\n result.ok = false\n // Persistent entries are still the thing easiest to forget, so their report still runs.\n return finish()\n }\n // Another home's panel (or anything else) on the same port is not ours to stop: nothing of this\n // home is running, which is what `down` was asked to make true.\n process.stdout.write(leftover?.kind === 'other'\n ? `home-hosted is not running (port ${leftover.port} is taken by another process — nothing of this home to stop)\\n`\n : 'home-hosted is not running\\n')\n // The panel's absence is exactly when a persistent entry is easiest to forget: it outlives\n // the panel by design, so \"nothing is running\" must not be said by omission here.\n return finish()\n }\n\n const liveness = await runtimeLiveness(runtime)\n // Nothing at all is behind the pid, so the record is simply stale: delete it, and do not touch the\n // network — a port this record names may now belong to an unrelated service.\n if (liveness === 'gone') {\n clearRuntime()\n process.stdout.write(`home-hosted is not running (removed a stale run.json from home-hosted ${runtime.version})\\n`)\n return finish()\n }\n\n /** What was stopped, and whether this CLI is a different release than it was. */\n const reportStopped = (forced: boolean): void => {\n process.stdout.write(`${green('stopped')}${forced ? ' (forced)' : ''} ${dim(`— was home-hosted ${runtime.version}`)}\\n`)\n const note = versionMismatchNote(runtime.version)\n if (note !== null)\n process.stdout.write(`${dim(note)}\\n`)\n }\n\n let answered = false\n // A graceful stop is under way only when the panel accepted the request or received SIGTERM.\n let stopping = true\n if (isLiveLiveness(liveness)) {\n process.stdout.write(`stopping pid ${runtime.pid}…\\n`)\n // The panel's own endpoint stops supervised servers cleanly on every platform; a signal is the\n // fallback for a wedged or unreachable process. Only a pid whose identity is confirmed is ever\n // signalled, and this branch is the only one that signals at all.\n // The panel ends the persistent entries itself when asked: it is the only one that can\n // record the stop (log line, history, health) and consume the state file in order.\n answered = await requestShutdown(runtime, 4000, { withPersistent: options.withPersistent === true })\n if (!answered)\n stopping = signal(runtime.pid, 'SIGTERM')\n }\n else {\n /**\n * The pid is alive but was born **after** this record was written, so it is some other process\n * that inherited the number — and it must never be signalled.\n *\n * The graceful stop is still offered, because it authenticates itself: `/_hh/shutdown` answers\n * only to the token in this `run.json`, which only the panel that wrote it knows. A reply is\n * therefore proof the panel *is* ours, which keeps it stoppable in the one case the birth time\n * can be wrong about — a forward wall-clock step, where the kernel's `btime` moves and a live\n * panel looks recycled. Either way this returns: `runtime.pid` is not the answering process, so\n * it is not signalled and the record is left for that panel to overwrite.\n */\n const answeredByPanel = await requestShutdown(runtime, 4000, { withPersistent: options.withPersistent === true })\n if (!answeredByPanel) {\n process.stdout.write(`home-hosted is not running (the pid in run.json, ${runtime.pid}, belongs to another process — it was not signalled)\\n`)\n return finish()\n }\n process.stdout.write(`stopped the panel on ${runtime.url} (its pid in run.json, ${runtime.pid}, was another process and was left alone)\\n`)\n clearRuntime()\n recordCleanStop()\n return finish()\n }\n\n // Nothing told the process to stop, so there is nothing to wait out; go straight to the forced stop.\n const budget = stopping ? await shutdownBudget(options.withPersistent === true) : 0\n if (await waitForExit(runtime.pid, budget)) {\n clearRuntime()\n recordCleanStop()\n reportStopped(false)\n return finish()\n }\n\n process.stdout.write(`${dim('it did not stop in time — forcing')}\\n`)\n forceStop(runtime.pid)\n // The forced stop's outcome decides the report, the exit code **and** whether the record may go.\n //\n // `forceStop` cannot report its own failure: `signal` swallows every error and `taskkill`'s exit\n // status is never read. This line used to discard `waitForExit`'s answer, `clearRuntime()` ran\n // regardless, and the command printed \"stopped (forced)\" and exited 0 — for a panel that was\n // still alive and still holding its port. Deleting run.json then destroyed the only record of it,\n // so `down && up` in a deploy script proceeded against a live panel. The graceful branch above\n // already asks this question before it clears; the forced branch is the one path that skipped it.\n if (!await waitForExit(runtime.pid, 5000)) {\n // Both lines are the refusal, and a refusal is one message on one stream (stderr): the remedy\n // is part of the reason. Printed to stdout it read as the command's answer, so a `down` in a\n // script — where stdout is the record — showed the failure in the same place success goes.\n refusal(`could not stop pid ${runtime.pid} — it is still running, and its record was kept`)\n process.stderr.write(`${dim(`stop it yourself with \\`kill -9 ${runtime.pid}\\` (Windows: \\`taskkill /PID ${runtime.pid} /F\\`), then run \\`down\\` again`)}\\n`)\n process.exitCode = 1\n result.ok = false\n return finish()\n }\n clearRuntime()\n recordCleanStop()\n reportStopped(true)\n return finish()\n}\n\n/**\n * The persistent entries this host has running, as their state files describe them.\n *\n * Every workspace keeps its own `.state`, and only the panel normally sees all of them, so\n * `down` reads them itself — after a crash there is nobody left to ask.\n */\nexport async function livePersistents(): Promise<PersistentHandle[]> {\n const { livePersistentEntries } = await import('#src/providers/nanny-sweep')\n const { hhDir } = await import('#src/helpers/paths')\n return livePersistentEntries(hhDir)\n}\n\n/** `workspace/id`, because a server id is only unique inside its workspace. */\nexport function persistentLabel(handle: Readonly<PersistentHandle>): string {\n return `${handle.workspaceId}/${handle.serverId}`\n}\n\n/**\n * Stops what is left of the snapshot: with the panel gone each nanny is signalled directly, and\n * its state file consumed once it is really gone. Returns which were ended here and which\n * survived, so the caller can account for the rest as the panel's work.\n */\nasync function stopPersistents(before: PersistentHandle[]): Promise<{ done: Set<string>, survived: Set<string> }> {\n const done = new Set<string>()\n const survived = new Set<string>()\n // Read again rather than trusting the snapshot: the panel's shutdown has been happening in\n // the meantime, and a nanny it already ended must not be signalled a second time.\n const live = new Set((await livePersistents()).map(persistentLabel))\n const handles = before.filter(handle => live.has(persistentLabel(handle)))\n if (handles.length === 0)\n return { done, survived }\n\n const { stopPersistentEntries } = await import('#src/providers/nanny-sweep')\n const results = await stopPersistentEntries(handles, { stopFor: await stopPolicyLookup() })\n\n for (const result of results) {\n const label = persistentLabel(result.handle)\n if (result.stopped) {\n done.add(label)\n process.stdout.write(`${green('stopped')} persistent ${label}\\n`)\n continue\n }\n survived.add(label)\n process.stderr.write(`${paint('31', 'error')} persistent ${label}: ${result.error}\\n`)\n }\n // A stop that left a server running is a failed stop, never a quiet success.\n const code = exitCodeForStops(results)\n if (code !== 0)\n process.exitCode = code\n return { done, survived }\n}\n\n/**\n * The exit code these stops earn: any survivor is a failure, because the command was asked to\n * stop them and the host is still running one. Separated from the printing so the rule is\n * pinned where it can be read, not inferred from a process's status.\n */\nexport function exitCodeForStops(results: ReadonlyArray<Readonly<{ stopped: boolean }>>): 0 | 1 {\n return results.some(result => !result.stopped) ? 1 : 0\n}\n\n/**\n * Each entry's own `stop` policy, read from the workspace that declares it.\n *\n * The grace period is the entry's, not a constant: the nanny forwards it to the child it\n * owns, so a shorter one here would escalate to `SIGKILL` while a shutdown the config asked\n * to allow more time for was still running. A workspace whose config cannot be read falls\n * back to the defaults — the host is being brought down either way.\n */\nasync function stopPolicyLookup(): Promise<(handle: PersistentHandle) => StopConfig> {\n const { stopSchema } = await import('#src/shared/contracts')\n const read = await serversReader()\n const policies = new Map<string, Map<string, StopConfig>>()\n\n return (handle) => {\n let byId = policies.get(handle.workspaceId)\n if (byId === undefined) {\n byId = new Map(read(handle.workspaceId).servers.map(server => [server.id, server.stop]))\n policies.set(handle.workspaceId, byId)\n }\n return byId.get(handle.serverId) ?? stopSchema.assert({})\n }\n}\n\n/**\n * Every workspace's entries, and whether that answer is **complete**.\n *\n * Read without writing: `WorkspaceStore.load()` seeds a missing config, so a `down` that only needs a\n * stop budget would create a workspace directory and two files on the way. Parsing the file directly\n * leaves that to the panel.\n *\n * `complete` is what the budget rests on. A workspace whose config cannot be read yields no entries,\n * and a budget computed from \"no entries\" is the 20 s floor — the exact failure a fixed 20 s wait was\n * replaced to avoid, so an unreadable config widens the wait instead of shortening it.\n */\nasync function configuredServers(): Promise<{ servers: ServerConfig[], complete: boolean }> {\n const { WorkspaceRegistry } = await import('#src/config/workspaces')\n const { DEFAULT_WORKSPACE_ID, workspacesPath } = await import('#src/helpers/paths')\n let ids = [DEFAULT_WORKSPACE_ID]\n let complete = true\n if (fs.existsSync(workspacesPath)) {\n const registry = new WorkspaceRegistry(workspacesPath)\n registry.load()\n if (registry.configError === null) {\n ids = registry.all().map(workspace => workspace.id)\n }\n else {\n // The registry names no workspace, so neither does this budget; the listed default is a guess.\n complete = false\n }\n }\n\n const read = await serversReader()\n const servers: ServerConfig[] = []\n for (const id of ids) {\n const workspace = read(id)\n if (!workspace.complete)\n complete = false\n servers.push(...workspace.servers)\n }\n return { servers, complete }\n}\n\n/**\n * One workspace's entries, parsed read-only: a config this CLI cannot read reports itself.\n *\n * The workspace's `defaults` block is resolved exactly as the panel resolves it, because a `stop`\n * grace that lives there is part of what the budget must cover. Passing `{}` read only each entry's\n * own `stop`: a workspace declaring `defaults.stop.graceMs: 120000` with an entry that spells none\n * measured a 20 s budget against the 132 s the panel actually needed, and `down` then SIGKILLed it\n * mid-grace — the same defect the widening above exists to avoid, reached through a valid config\n * rather than a broken one.\n */\nexport async function serversReader(): Promise<(workspaceId: string) => { servers: ServerConfig[], complete: boolean }> {\n const { readStateFile } = await import('#src/helpers/config-text')\n const { parseServersFile, parseWorkspaceSettings } = await import('#src/config/parse')\n const { workspaceServersPath, workspaceSettingsPath } = await import('#src/helpers/paths')\n return (workspaceId) => {\n const file = workspaceServersPath(workspaceId)\n if (!fs.existsSync(file)) {\n // Nothing declared is a real answer: a workspace with no entries stops nothing.\n return { servers: [], complete: true }\n }\n const resolved = workspaceDefaults(workspaceId, readStateFile, workspaceSettingsPath, parseWorkspaceSettings)\n try {\n const parsed = parseServersFile(JSON.parse(readStateFile(file)), resolved.defaults)\n // A settings file this CLI could not turn into defaults is as unknowable as a broken servers\n // file: the grace it declares is invisible, and the budget computed without it is the 20 s floor\n // — which SIGKILLs a panel still inside a grace the person configured.\n return { servers: parsed.servers, complete: parsed.errors.length === 0 && resolved.complete }\n }\n catch {\n return { servers: [], complete: false }\n }\n }\n}\n\n/**\n * The `defaults` group a workspace's settings file declares, and whether that answer is trustworthy.\n *\n * An **absent** file is a real answer — `{}`, `complete: true` — because a workspace with no settings\n * has no `defaults` to miss and the seed declares none. A file that is there but cannot be read, or\n * carries a `defaults` value this release rejects, is a different fact: the grace it declares is\n * invisible to the budget, and a budget computed without it is the 20 s floor. Reporting that as\n * `complete: false` widens the wait to the ceiling, which is the safe direction — too long costs a\n * slower `down`, too short kills a panel inside a grace the person configured.\n */\nfunction workspaceDefaults(\n workspaceId: string,\n readStateFile: (file: string) => string,\n workspaceSettingsPath: (id: string) => string,\n parseWorkspaceSettings: (raw: unknown) => { config: { defaults?: Record<string, unknown> } | null, errors: string[] },\n): { defaults: Record<string, unknown>, complete: boolean } {\n const file = workspaceSettingsPath(workspaceId)\n if (!fs.existsSync(file))\n return { defaults: {}, complete: true }\n try {\n const parsed = parseWorkspaceSettings(JSON.parse(readStateFile(file)))\n if (parsed.errors.length > 0)\n return { defaults: {}, complete: false }\n return { defaults: (parsed.config?.defaults ?? {}) as Record<string, unknown>, complete: true }\n }\n catch {\n return { defaults: {}, complete: false }\n }\n}\n\nconst SHUTDOWN_FLOOR_MS = 20_000\nconst SHUTDOWN_CEILING_MS = 10 * 60_000\n/** `stopComposeContainers`' own `docker stop` timeout, plus its two listings. */\nconst COMPOSE_STOP_MS = 130_000\n\n/**\n * How long to give the panel, from whatever this CLI could read of its config.\n *\n * A config it could not read makes the answer unknowable rather than empty, and an unknowable config\n * means an entry with a long grace may be one the read never showed. Widening to the ceiling there is\n * the safe direction: waiting too long costs a slower `down`, waiting too little SIGKILLs a panel\n * still inside a grace the person configured.\n */\nasync function shutdownBudget(withPersistent: boolean): Promise<number> {\n const { servers, complete } = await configuredServers()\n if (!complete) {\n process.stderr.write(`${dim('could not read every server config — allowing the panel the full stop budget')}\\n`)\n return SHUTDOWN_CEILING_MS\n }\n return shutdownBudgetMs(servers, withPersistent)\n}\n\n/**\n * How long the panel may take to stop what it supervises before `down` forces it.\n *\n * This is the slowest entry's stop, because the path `down` takes — `/_hh/shutdown` → `PanelService\n * .dispose` — stops every workspace's entries through `Promise.all`. (`stopAll`, behind the panel's\n * own stop-all route, is sequential; a caller budgeting for *that* would need the sum, not the max.)\n *\n * The slowest entry is its grace, the SIGKILL wait after it, a second round for a persistent child\n * signalled alone, and a compose stack's `docker stop` — plus a margin.\n */\nexport function shutdownBudgetMs(servers: ReadonlyArray<Pick<ServerConfig, 'command' | 'args' | 'persistent' | 'stop'>>, withPersistent: boolean): number {\n let slowest = 0\n for (const server of servers) {\n if (server.persistent && !withPersistent)\n continue\n const round = server.stop.graceMs + 2000\n let ms = round\n if (server.persistent && !server.stop.killGroup)\n ms += round\n if (server.stop.killPortHolders)\n ms += round\n if (isComposeCommand(server.command, server.args))\n ms += COMPOSE_STOP_MS\n slowest = Math.max(slowest, ms)\n }\n return Math.min(SHUTDOWN_CEILING_MS, Math.max(SHUTDOWN_FLOOR_MS, slowest + 10_000))\n}\n\n/**\n * The last step: name what the flag left running, or stop what the panel could not and account\n * for every entry that was running when this command started.\n *\n * The panel does the stopping whenever it is reachable — it is the only process that can record\n * it — so what is left of the snapshot is what still needs a signal here. Anything else in the\n * snapshot was ended by the panel, and is reported as stopped; a survivor is never reported as\n * stopped, or `restart` would treat a failed stop as a successful one.\n */\nasync function reportPersistent(options: DownOptions, before: PersistentHandle[] = []): Promise<DownResult['stoppedPersistent']> {\n if (options.withPersistent !== true) {\n const running = await livePersistents()\n if (running.length === 0)\n return []\n process.stdout.write(`${dim(`${running.length} persistent server(s) left running: ${running.map(persistentLabel).join(', ')}\\n`)}`)\n process.stdout.write(`${dim('stop one from the panel, or pass --with-persistent')}\\n`)\n return []\n }\n\n const ended = await stopPersistents(before)\n const stopped: DownResult['stoppedPersistent'] = []\n for (const handle of before) {\n const label = persistentLabel(handle)\n // A survivor is never reported as stopped, or `restart` would treat a failed stop as one.\n if (ended.survived.has(label))\n continue\n // Not ended here, so the panel did it on the way out: either way it is stopped, and the\n // caller cannot tell the two apart — nor should it have to.\n if (!ended.done.has(label))\n process.stdout.write(`${green('stopped')} persistent ${label}\\n`)\n stopped.push({ workspaceId: handle.workspaceId, serverId: handle.serverId })\n }\n return stopped\n}\n\nasync function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {\n const { isProcessAlive } = await import('#src/helpers/daemon')\n const deadline = Date.now() + timeoutMs\n\n while (Date.now() < deadline) {\n if (!isProcessAlive(pid))\n return true\n await delay(200)\n }\n return !isProcessAlive(pid)\n}\n\n/** Whether the signal was delivered; `false` for a pid that is gone or not ours to signal (EPERM). */\nfunction signal(pid: number, name: NodeJS.Signals): boolean {\n try {\n process.kill(pid, name)\n return true\n }\n catch {\n return false\n }\n}\n\n/**\n * Only the panel's own pid, as SIGKILL is on POSIX: `taskkill /T` follows parent pids, which a\n * detached spawn keeps on Windows, so it also killed every persistent entry's nanny.\n */\nexport function forceStopCommand(pid: number, platform: NodeJS.Platform = process.platform): [string, string[]] | null {\n return platform === 'win32' ? ['taskkill', ['/PID', String(pid), '/F']] : null\n}\n\nfunction forceStop(pid: number): void {\n const command = forceStopCommand(pid)\n if (command !== null) {\n spawnSync(command[0], command[1], { windowsHide: true })\n return\n }\n signal(pid, 'SIGKILL')\n}\n\nexport const downCommand = defineCommand({\n meta: { name: 'down' },\n args: {\n withPersistent: { type: 'boolean', description: 'also stop every persistent entry, in every workspace' },\n },\n run: async ({ args }) => {\n await runDown({ withPersistent: args.withPersistent === true })\n },\n})\n"],"mappings":";;;;;;;;AAmCA,eAAsB,QAAQ,UAAuB,CAAC,GAAwB;CAC5E,MAAM,EAAE,cAAc,wBAAwB,gBAAgB,aAAa,iBAAiB,oBAAoB,MAAM,OAAO;CAE7H,MAAM,SAAqB;EAAE,IAAI;EAAM,mBAAmB,CAAC;CAAE;CAI7D,MAAM,SAAS,QAAQ,mBAAmB,OAAO,MAAM,gBAAgB,IAAI,CAAC;CAE5E,MAAM,SAAS,YAAiC;EAC9C,OAAO,kBAAkB,KAAK,GAAG,MAAM,iBAAiB,SAAS,MAAM,CAAC;EACxE,OAAO;CACT;CAEA,MAAM,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Aa,UAAU,CAAC,YAAY;EAAC;EAAQ,OAAO,GAAG;EAAG;CAAI,CAAC,IAAI;AAC5E;AAEA,SAAS,UAAU,KAAmB;CACpC,MAAM,UAAU,iBAAiB,GAAG;CACpC,IAAI,YAAY,MAAM;EACpB,UAAU,QAAQ,IAAI,QAAQ,IAAI,EAAE,aAAa,KAAK,CAAC;EACvD;CACF;CACA,OAAO,KAAK,SAAS;AACvB;AAEA,IAAa,cAAc,cAAc;CACvC,MAAM,EAAE,MAAM,OAAO;CACrB,MAAM,EACJ,gBAAgB;EAAE,MAAM;EAAW,aAAa;CAAuD,EACzG;CACA,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,QAAQ,EAAE,gBAAgB,KAAK,mBAAmB,KAAK,CAAC;CAChE;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as errorMessage, _ as prompt, c as bold, d as dim, f as fail,
|
|
1
|
+
import { C as errorMessage, _ as prompt, c as bold, d as dim, f as fail, h as invocation, l as confirm, m as green, t as appVersion, x as shellQuote, y as refusal } from "../cli.js";
|
|
2
2
|
import process from "node:process";
|
|
3
3
|
import { defineCommand } from "citty";
|
|
4
4
|
import path from "node:path";
|
|
@@ -113,9 +113,17 @@ function nextSteps(pm, install, cd) {
|
|
|
113
113
|
command: lead(installCommand(pm)),
|
|
114
114
|
text: "install the dependency"
|
|
115
115
|
});
|
|
116
|
+
/**
|
|
117
|
+
* No password is printed here, and none may be.
|
|
118
|
+
*
|
|
119
|
+
* This line used to promise "default password `hh`", which was the shared pre-0.12 boot password:
|
|
120
|
+
* a fresh scaffold generates a **random** first-run password and `up` prints it once, so following
|
|
121
|
+
* this hint answered 401 at a login screen that names no credential. Naming any fixed password is
|
|
122
|
+
* the same defect in a new spelling — there is none to name.
|
|
123
|
+
*/
|
|
116
124
|
steps.push({
|
|
117
125
|
command: lead(runCommand$1(pm, "up")),
|
|
118
|
-
text: "start the panel
|
|
126
|
+
text: "start the panel — it prints the first-run password once, on this line"
|
|
119
127
|
});
|
|
120
128
|
steps.push({
|
|
121
129
|
command: null,
|
|
@@ -190,7 +198,7 @@ function which(command) {
|
|
|
190
198
|
}
|
|
191
199
|
async function runInit(options) {
|
|
192
200
|
const assumeYes = options.yes;
|
|
193
|
-
if (!assumeYes && process.stdin.isTTY !== true) fail(
|
|
201
|
+
if (!assumeYes && process.stdin.isTTY !== true) fail(`init needs a terminal to ask in.\n take the defaults with: ${invocation()} init --yes [--dir <dir>]`);
|
|
194
202
|
const defaultDir = options.dir ?? "./my-servers";
|
|
195
203
|
const dir = assumeYes ? defaultDir : (await prompt(`Project directory (${defaultDir}) `)).trim() || defaultDir;
|
|
196
204
|
const defaultName = path.basename(path.resolve(dir));
|
|
@@ -223,19 +231,24 @@ async function runInit(options) {
|
|
|
223
231
|
});
|
|
224
232
|
process.stdout.write(` ${dim("git repository initialized")}\n`);
|
|
225
233
|
}
|
|
234
|
+
let installed = install;
|
|
226
235
|
if (install) {
|
|
227
236
|
process.stdout.write(`${dim(`installing with ${pm}…`)}\n`);
|
|
228
237
|
if (spawnSync(pm, installArgs(pm), {
|
|
229
238
|
cwd: target,
|
|
230
239
|
stdio: "inherit",
|
|
231
240
|
shell: process.platform === "win32"
|
|
232
|
-
}).status !== 0)
|
|
241
|
+
}).status !== 0) {
|
|
242
|
+
installed = false;
|
|
243
|
+
refusal(`the ${pm} install failed — the project is in ${target}, but its dependencies are not installed`);
|
|
244
|
+
process.exitCode = 1;
|
|
245
|
+
}
|
|
233
246
|
}
|
|
234
247
|
const relative = path.relative(process.cwd(), target);
|
|
235
248
|
const where = relative.length === 0 || relative.startsWith("..") ? target : relative;
|
|
236
249
|
const cd = relative.length === 0 ? "" : cdCommand(where);
|
|
237
250
|
process.stdout.write(`\nNext:\n`);
|
|
238
|
-
for (const step of nextSteps(pm,
|
|
251
|
+
for (const step of nextSteps(pm, installed, cd)) {
|
|
239
252
|
if (step.command === null) {
|
|
240
253
|
process.stdout.write(` ${dim(step.text)}\n`);
|
|
241
254
|
continue;
|
|
@@ -260,4 +273,4 @@ var initCommand = defineCommand({
|
|
|
260
273
|
//#endregion
|
|
261
274
|
export { initCommand };
|
|
262
275
|
|
|
263
|
-
//# sourceMappingURL=init-
|
|
276
|
+
//# sourceMappingURL=init-BZ7hK9Vf.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init-BZ7hK9Vf.js","names":["runCommand"],"sources":["../../src/services/init.ts","../../src/cli/init.ts"],"sourcesContent":["import type { Stats } from 'node:fs'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { shellQuote } from '#src/helpers/shell'\nimport { appVersion } from '#src/helpers/version'\n\nexport type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\nexport interface InitOptions {\n dir: string\n name: string\n pm: PackageManager\n install: boolean\n git: boolean\n}\n\nexport interface InitResult {\n dir: string\n created: boolean\n files: string[]\n installed: boolean\n git: boolean\n}\n\n/** The scripts every scaffolded project gets; all of them keep state inside the project. */\nexport function projectScripts(): Record<string, string> {\n const withState = (args: string): string => `home-hosted ${args} --home ./state`\n return {\n 'up': withState('up'),\n 'down': withState('down'),\n 'restart': withState('restart'),\n 'status': withState('status'),\n 'set-password': withState('set-password'),\n 'set-token': withState('set-token'),\n 'migrate': withState('migrate'),\n }\n}\n\n/** `home-hosted` is pinned to the version that wrote the project, and open to newer ones. */\nexport function projectManifest(name: string): string {\n return `${JSON.stringify({\n name,\n version: '0.1.0',\n private: true,\n description: 'Servers supervised by home-hosted.',\n type: 'module',\n engines: { node: '>=24.0.0' },\n scripts: projectScripts(),\n dependencies: { 'home-hosted': `^${appVersion()}` },\n }, null, 2)}\\n`\n}\n\n/**\n * State is generated, so it stays out. The workspace definitions worth committing\n * (`.hh/settings.json`, `.hh/workspaces.json`, and each workspace's\n * `settings.json` + `servers.config.json`) are un-ignored explicitly.\n */\nexport function projectGitignore(): string {\n // `state/.hh/*` excludes the workspace *directories*, and git will not descend into\n // an excluded directory — so the file-level negations below can never match unless\n // the directories themselves are un-ignored first. Without `!state/.hh/*/` the\n // workspace definitions stayed out of the very repo this scaffold creates.\n return `node_modules/\n\n# home-hosted: state is local, the workspace definitions are tracked\nstate/.hh/*\n!state/.hh/settings.json\n!state/.hh/workspaces.json\nstate/.hh/*/*\n!state/.hh/*/\n!state/.hh/*/settings.json\n!state/.hh/*/servers.config.json\ndata/\n`\n}\n\nexport function isEmptyDir(dir: string): boolean {\n try {\n return fs.readdirSync(dir).every(entry => entry === '.git')\n }\n catch {\n return true\n }\n}\n\nfunction assertUsableDir(dir: string): void {\n let stats: Stats | null = null\n try {\n stats = fs.statSync(dir)\n }\n catch {\n return\n }\n if (!stats.isDirectory())\n throw new Error(`${dir} exists and is not a directory`)\n if (!isEmptyDir(dir))\n throw new Error(`${dir} is not empty — pick another directory, or empty it first`)\n}\n\n/** Writes the project skeleton. Nothing is installed or initialized here. */\nexport function scaffold(options: InitOptions): InitResult {\n const dir = path.resolve(options.dir)\n assertUsableDir(dir)\n\n const existed = fs.existsSync(dir)\n fs.mkdirSync(dir, { recursive: true })\n\n const files: Array<[string, string]> = [\n ['package.json', projectManifest(options.name)],\n ['.gitignore', projectGitignore()],\n ]\n for (const [name, contents] of files)\n fs.writeFileSync(path.join(dir, name), contents)\n\n return {\n dir,\n created: !existed,\n files: files.map(([name]) => name),\n installed: false,\n git: false,\n }\n}\n\nexport const PACKAGE_MANAGERS: PackageManager[] = ['pnpm', 'npm', 'yarn', 'bun']\n\n/** The package manager this machine actually has, preferring pnpm. */\nexport function detectPackageManager(exists: (command: string) => boolean): PackageManager {\n const found = PACKAGE_MANAGERS.find(pm => exists(pm))\n return found ?? 'npm'\n}\n\n/** How to run one of the project's scripts with a given package manager. */\nexport function runCommand(pm: PackageManager, script: string): string {\n return pm === 'npm' ? `npm run ${script}` : `${pm} run ${script}`\n}\n\n/**\n * One line of `init`'s \"Next:\" block. A step is either a command to type or a prose line beneath\n * the one above it, and the two are kept apart so the block can be asserted without a terminal.\n */\nexport interface NextStep {\n /** The command, already `cd`-prefixed; `null` when the line is prose about the step above. */\n command: string | null\n /** What the command does, or the prose itself. */\n text: string\n}\n\n/**\n * What `init` hands the person once the project is written.\n *\n * Built here rather than printed inline for two reasons, both measured. The install step was\n * missing under `--no-install`, so the scripts it went on to name answered `home-hosted: command\n * not found` (npm exits 127) — the one sequence the scaffold exists to hand over, broken at step\n * one. And the password hint named a page the UI does not have: the sidebar entry is **Global\n * settings**, and \"Settings → Authentication\" names nothing a person can click.\n */\nexport function nextSteps(pm: PackageManager, install: boolean, cd: string): NextStep[] {\n // The block is a sequence a person walks down, so `cd` belongs on the first command only: the\n // reader arrives in the project once and every later line runs from there.\n const steps: NextStep[] = []\n const lead = (command: string): string => (steps.length === 0 ? `${cd}${command}` : command)\n\n // The dependency has to exist before any of the project's scripts resolve: `pnpm run up` shells\n // out to `node_modules/.bin/home-hosted`, which `--no-install` deliberately leaves absent.\n if (!install)\n steps.push({ command: lead(installCommand(pm)), text: 'install the dependency' })\n /**\n * No password is printed here, and none may be.\n *\n * This line used to promise \"default password `hh`\", which was the shared pre-0.12 boot password:\n * a fresh scaffold generates a **random** first-run password and `up` prints it once, so following\n * this hint answered 401 at a login screen that names no credential. Naming any fixed password is\n * the same defect in a new spelling — there is none to name.\n */\n steps.push({ command: lead(runCommand(pm, 'up')), text: 'start the panel — it prints the first-run password once, on this line' })\n steps.push({ command: null, text: 'then change that password under Global settings → Authentication, and add your servers' })\n steps.push({ command: `${runCommand(pm, 'set-token')} --generate`, text: 'for scripts and agents' })\n return steps\n}\n\n/**\n * The `cd` that reaches a scaffolded project, quoted for the shell it will be pasted into.\n *\n * The quoting rule is `shellQuote` (`helpers/shell.ts`), shared with every other string this\n * package prints for a person to copy: `init` printed `cd my servers && npm run up` for a directory\n * with a space, which the shell answers `cd: too many arguments` — an error naming a command the\n * person did not compose, on the one line the scaffold exists to hand them over.\n */\nexport function cdCommand(where: string): string {\n return `cd ${shellQuote(where)} && `\n}\n\n/** Install arguments for a scaffolded project (the manifest already lists the dependency). */\nexport function installArgs(pm: PackageManager): string[] {\n return pm === 'yarn' ? [] : ['install']\n}\n\n/**\n * The install command as a person types it — `pnpm install`, `yarn` with no argument.\n *\n * Distinct from `runCommand`, which runs one of the project's **scripts**: `npm run install` is not\n * an install, it is a script named `install` that this manifest does not declare.\n */\nexport function installCommand(pm: PackageManager): string {\n return [pm, ...installArgs(pm)].join(' ')\n}\n","import { spawnSync } from 'node:child_process'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, confirm, dim, fail, green, invocation, prompt, refusal } from '#src/cli/io'\nimport { cdCommand, detectPackageManager, installArgs, nextSteps, PACKAGE_MANAGERS, scaffold } from '#src/services/init'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * `init` scaffolds a project that keeps its whole setup — state, data and the\n * server definitions — inside its own directory. Interactive by nature, but\n * `--yes` takes every default so an agent or a CI job can run it unattended.\n */\n\nexport const initArgs = {\n dir: { type: 'string', description: 'where to scaffold (default: ./my-servers)' },\n name: { type: 'string', description: 'package name (default: the directory name)' },\n pm: { type: 'string', description: 'pnpm | npm | yarn | bun (default: the first one installed)' },\n install: { type: 'boolean', default: true, negativeDescription: 'write the files, install nothing' },\n yes: { type: 'boolean', alias: 'y', description: 'take every default, ask nothing' },\n} as const\n\nfunction which(command: string): boolean {\n const probe = spawnSync(command, ['--version'], { stdio: 'ignore', shell: process.platform === 'win32' })\n return probe.status === 0\n}\n\nexport async function runInit(options: { dir?: string, name?: string, pm?: string, noInstall: boolean, yes: boolean }): Promise<void> {\n const assumeYes = options.yes\n if (!assumeYes && process.stdin.isTTY !== true) {\n fail(`init needs a terminal to ask in.\\n take the defaults with: ${invocation()} init --yes [--dir <dir>]`)\n }\n\n const defaultDir = options.dir ?? './my-servers'\n const dir = assumeYes ? defaultDir : (await prompt(`Project directory (${defaultDir}) `)).trim() || defaultDir\n const defaultName = path.basename(path.resolve(dir))\n const name = options.name ?? (assumeYes ? defaultName : (await prompt(`Package name (${defaultName}) `)).trim() || defaultName)\n\n let pm = options.pm\n if (pm !== undefined && !(PACKAGE_MANAGERS as string[]).includes(pm))\n fail(`unknown package manager: ${pm} (expected one of ${PACKAGE_MANAGERS.join(', ')})`)\n const detected = detectPackageManager(which)\n if (pm === undefined)\n pm = assumeYes ? detected : (await prompt(`Package manager (${detected}) `)).trim() || detected\n\n const install = options.noInstall\n ? false\n : assumeYes || (await confirm('Install the dependencies now?', true))\n const git = assumeYes ? which('git') : which('git') && (await confirm('Initialize a git repository?', true))\n\n try {\n const result = scaffold({ dir, name, pm: pm as never, install, git })\n process.stdout.write(`${green('project created')} in ${result.dir}\\n`)\n for (const file of result.files)\n process.stdout.write(` ${dim(file)}\\n`)\n }\n catch (error) {\n fail(errorMessage(error))\n }\n\n const target = path.resolve(dir)\n if (git) {\n spawnSync('git', ['init', '-q'], { cwd: target, stdio: 'inherit', shell: process.platform === 'win32' })\n process.stdout.write(` ${dim('git repository initialized')}\\n`)\n }\n\n let installed = install\n if (install) {\n process.stdout.write(`${dim(`installing with ${pm}…`)}\\n`)\n const result = spawnSync(pm as string, installArgs(pm as never), {\n cwd: target,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n })\n // A failed install is a failed `init`: the files are there, but the next steps do not work yet.\n // Said on stderr with exit 1, so `init --yes && …` in a script stops; \"Next\" then lists the install.\n if (result.status !== 0) {\n installed = false\n refusal(`the ${pm} install failed — the project is in ${target}, but its dependencies are not installed`)\n process.exitCode = 1\n }\n }\n\n // A path inside the working directory reads better relative; anything else absolute.\n const relative = path.relative(process.cwd(), target)\n const where = relative.length === 0 || relative.startsWith('..') ? target : relative\n const cd = relative.length === 0 ? '' : cdCommand(where)\n process.stdout.write(`\\nNext:\\n`)\n for (const step of nextSteps(pm as never, installed, cd)) {\n if (step.command === null) {\n process.stdout.write(` ${dim(step.text)}\\n`)\n continue\n }\n // The command is the bold half; the line's own explanation keeps its place beside it.\n const padding = ' '.repeat(5)\n process.stdout.write(` ${bold(step.command)}${padding}${step.text}\\n`)\n }\n}\n\nexport const initCommand = defineCommand({\n meta: { name: 'init' },\n args: initArgs,\n run: async ({ args }) => {\n await runInit({\n dir: args.dir,\n name: args.name,\n pm: args.pm,\n noInstall: args.install === false,\n yes: args.yes === true,\n })\n },\n})\n"],"mappings":";;;;;;;;AAyBA,SAAgB,iBAAyC;CACvD,MAAM,aAAa,SAAyB,eAAe,KAAK;CAChE,OAAO;EACL,MAAM,UAAU,IAAI;EACpB,QAAQ,UAAU,MAAM;EACxB,WAAW,UAAU,SAAS;EAC9B,UAAU,UAAU,QAAQ;EAC5B,gBAAgB,UAAU,cAAc;EACxC,aAAa,UAAU,WAAW;EAClC,WAAW,UAAU,SAAS;CAChC;AACF;;AAGA,SAAgB,gBAAgB,MAAsB;CACpD,OAAO,GAAG,KAAK,UAAU;EACvB;EACA,SAAS;EACT,SAAS;EACT,aAAa;EACb,MAAM;EACN,SAAS,EAAE,MAAM,WAAW;EAC5B,SAAS,eAAe;EACxB,cAAc,EAAE,eAAe,IAAI,WAAW,IAAI;CACpD,GAAG,MAAM,CAAC,EAAE;AACd;;;;;;AAOA,SAAgB,mBAA2B;CAKzC,OAAO;;;;;;;;;;;;AAYT;AAEA,SAAgB,WAAW,KAAsB;CAC/C,IAAI;EACF,OAAO,GAAG,YAAY,GAAG,CAAC,CAAC,OAAM,UAAS,UAAU,MAAM;CAC5D,QACM;EACJ,OAAO;CACT;AACF;AAEA,SAAS,gBAAgB,KAAmB;CAC1C,IAAI,QAAsB;CAC1B,IAAI;EACF,QAAQ,GAAG,SAAS,GAAG;CACzB,QACM;EACJ;CACF;CACA,IAAI,CAAC,MAAM,YAAY,GACrB,MAAM,IAAI,MAAM,GAAG,IAAI,+BAA+B;CACxD,IAAI,CAAC,WAAW,GAAG,GACjB,MAAM,IAAI,MAAM,GAAG,IAAI,0DAA0D;AACrF;;AAGA,SAAgB,SAAS,SAAkC;CACzD,MAAM,MAAM,KAAK,QAAQ,QAAQ,GAAG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K,SAAS,WAAW,IAAI,KAAK,UAAU,KAAK;CACvD,QAAQ,OAAO,MAAM,WAAW;CAChC,KAAK,MAAM,QAAQ,UAAU,IAAa,WAAW,EAAE,GAAG;EACxD,IAAI,KAAK,YAAY,MAAM;GACzB,QAAQ,OAAO,MAAM,KAAK,IAAI,KAAK,IAAI,EAAE,GAAG;GAC5C;EACF;EAEA,MAAM,UAAU,IAAI,OAAO,CAAC;EAC5B,QAAQ,OAAO,MAAM,KAAK,KAAK,KAAK,OAAO,IAAI,UAAU,KAAK,KAAK,GAAG;CACxE;AACF;AAEA,IAAa,cAAc,cAAc;CACvC,MAAM,EAAE,MAAM,OAAO;CACrB,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,QAAQ;GACZ,KAAK,KAAK;GACV,MAAM,KAAK;GACX,IAAI,KAAK;GACT,WAAW,KAAK,YAAY;GAC5B,KAAK,KAAK,QAAQ;EACpB,CAAC;CACH;AACF,CAAC"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import {
|
|
2
|
+
import { c as hhDir } from "./paths-CGlGDrOU.js";
|
|
3
|
+
import { t as writeFileAtomic } from "./atomic-C1PfJpE7.js";
|
|
3
4
|
import { n as readStateFile } from "./config-text-DifCHhnz.js";
|
|
4
|
-
import {
|
|
5
|
+
import { t as lazy } from "./lazy-Ce5zEAq1.js";
|
|
5
6
|
import path from "node:path";
|
|
6
7
|
import { type } from "arktype";
|
|
7
8
|
//#region src/helpers/last-stop.ts
|
|
@@ -21,12 +22,12 @@ var last_stop_exports = /* @__PURE__ */ __exportAll({
|
|
|
21
22
|
* Only a deliberate stop writes it. A panel that was killed has nobody to write anything, which is
|
|
22
23
|
* why a *stale record* stays the signal for that one — see `status`.
|
|
23
24
|
*/
|
|
24
|
-
var lastStopSchema = type({
|
|
25
|
+
var lastStopSchema = lazy(() => type({
|
|
25
26
|
/** Milliseconds since the epoch, from the process that stopped it. */
|
|
26
27
|
at: "number",
|
|
27
28
|
/** How it stopped. `down` is the only writer today; the field exists so a future cause is named. */
|
|
28
29
|
reason: "\"down\""
|
|
29
|
-
});
|
|
30
|
+
}));
|
|
30
31
|
var lastStopPath = path.join(hhDir, ".last-stop.json");
|
|
31
32
|
/** Records a deliberate stop. Best-effort: a panel that stopped is stopped, whatever this file does. */
|
|
32
33
|
function recordCleanStop(at = Date.now()) {
|
|
@@ -49,4 +50,4 @@ function readLastStop() {
|
|
|
49
50
|
//#endregion
|
|
50
51
|
export { recordCleanStop as n, last_stop_exports as t };
|
|
51
52
|
|
|
52
|
-
//# sourceMappingURL=last-stop-
|
|
53
|
+
//# sourceMappingURL=last-stop-C-BXz_XI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"last-stop-C-BXz_XI.js","names":[],"sources":["../../src/helpers/last-stop.ts"],"sourcesContent":["import path from 'node:path'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { hhDir } from '#src/helpers/paths'\nimport { lazy } from '#src/shared/lazy'\n\n/**\n * How the panel last stopped — the fact `status` could not report.\n *\n * A clean `down` deletes `run.json`, and so does `up` when it finds a record with nothing behind the\n * pid. So \"no record\" covered both \"you stopped it\" and \"it died and the next start tidied up\", and a\n * script could only tell them apart by inferring from which *keys* were absent. This records the\n * answer instead of leaving it to be guessed.\n *\n * Only a deliberate stop writes it. A panel that was killed has nobody to write anything, which is\n * why a *stale record* stays the signal for that one — see `status`.\n */\nexport const lastStopSchema = lazy(() => type({\n /** Milliseconds since the epoch, from the process that stopped it. */\n at: 'number',\n /** How it stopped. `down` is the only writer today; the field exists so a future cause is named. */\n reason: '\"down\"',\n}))\n\nexport type LastStop = typeof lastStopSchema.infer\n\nconst lastStopPath = path.join(hhDir, '.last-stop.json')\n\n/** Records a deliberate stop. Best-effort: a panel that stopped is stopped, whatever this file does. */\nexport function recordCleanStop(at = Date.now()): void {\n try {\n writeFileAtomic(lastStopPath, `${JSON.stringify({ at, reason: 'down' }, null, 2)}\\n`, { mode: 0o600 })\n }\n catch {\n // The stop itself succeeded; a missing marker only costs `status` one detail.\n }\n}\n\n/** The last deliberate stop, or null when there is none (or it cannot be read). */\nexport function readLastStop(): LastStop | null {\n try {\n const parsed = lastStopSchema(JSON.parse(readStateFile(lastStopPath)) as unknown)\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkBA,IAAa,iBAAiB,WAAW,KAAK;;CAE5C,IAAI;;CAEJ,QAAQ;AACV,CAAC,CAAC;AAIF,IAAM,eAAe,KAAK,KAAK,OAAO,iBAAiB;;AAGvD,SAAgB,gBAAgB,KAAK,KAAK,IAAI,GAAS;CACrD,IAAI;EACF,gBAAgB,cAAc,GAAG,KAAK,UAAU;GAAE;GAAI,QAAQ;EAAO,GAAG,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;CACvG,QACM,CAEN;AACF;;AAGA,SAAgB,eAAgC;CAC9C,IAAI;EACF,MAAM,SAAS,eAAe,KAAK,MAAM,cAAc,YAAY,CAAC,CAAY;EAChF,OAAO,kBAAkB,KAAK,SAAS,OAAO;CAChD,QACM;EACJ,OAAO;CACT;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as appVersion } from "../cli.js";
|
|
2
|
-
import {
|
|
2
|
+
import { s as hasLegacyLayout, u as legacy } from "./paths-CGlGDrOU.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
//#region src/config/layout.ts
|
|
5
5
|
/**
|
|
@@ -21,4 +21,4 @@ function ensureLayout() {
|
|
|
21
21
|
//#endregion
|
|
22
22
|
export { ensureLayout };
|
|
23
23
|
|
|
24
|
-
//# sourceMappingURL=layout-
|
|
24
|
+
//# sourceMappingURL=layout-DwTtmund.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layout-
|
|
1
|
+
{"version":3,"file":"layout-DwTtmund.js","names":[],"sources":["../../src/config/layout.ts"],"sourcesContent":["import fs from 'node:fs'\nimport { hasLegacyLayout, legacy } from '#src/helpers/paths'\nimport { appVersion } from '#src/helpers/version'\n\n/**\n * Refuses a state directory this release cannot use, before any command resolves a\n * path into it.\n *\n * Through 0.7.x this relocated a pre-workspace `$HHOSTED_HOME` automatically. 0.8.0\n * dropped the mover, so an instance that never crossed `.hh` is stopped instead of\n * being read as an empty one — its `servers.config.json` would otherwise sit unread\n * beside a panel supervising nothing, with no error anywhere. The migration itself is\n * unchanged and still shipped: the 0.7 line performs it on its first run.\n */\nexport function ensureLayout(): void {\n if (!hasLegacyLayout())\n return\n\n const found = [legacy.configPath, legacy.secretsPath].filter(file => fs.existsSync(file))\n throw new Error(\n `${found.join(', ')} belongs to home-hosted 0.6.x, which ${appVersion()} no longer relocates.\\n`\n + ' Install the latest 0.7.x once — it moves that state into .hh/ on its first run — then start this release.\\n'\n + ' Nothing has been changed or deleted.',\n )\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,SAAgB,eAAqB;CACnC,IAAI,CAAC,gBAAgB,GACnB;CAEF,MAAM,QAAQ,CAAC,OAAO,YAAY,OAAO,WAAW,CAAC,CAAC,QAAO,SAAQ,GAAG,WAAW,IAAI,CAAC;CACxF,MAAM,IAAI,MACR,GAAG,MAAM,KAAK,IAAI,EAAE,uCAAuC,WAAW,EAAE;uCAG1E;AACF"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
//#region src/shared/lazy.ts
|
|
2
|
+
/**
|
|
3
|
+
* A schema that is built the first time something uses it.
|
|
4
|
+
*
|
|
5
|
+
* Building every ArkType schema in `contracts.ts` took ~1.2 s at import — longer than most CLI
|
|
6
|
+
* commands then ran, paid by every command, every spawned test child and every UI load, for schemas
|
|
7
|
+
* the caller never touched. The wrapper is typed as the schema itself, so nothing that imports it
|
|
8
|
+
* changes.
|
|
9
|
+
*
|
|
10
|
+
* It is a zero-length function on purpose: ArkType resolves a zero-argument function handed to it
|
|
11
|
+
* as a definition by calling it (a thunk), so `type({ a: lazySchema })`, `.or(lazySchema)` and
|
|
12
|
+
* friends receive the real node, never this wrapper. Called with arguments it validates, like the
|
|
13
|
+
* schema it stands for.
|
|
14
|
+
*/
|
|
15
|
+
var builds = 0;
|
|
16
|
+
/**
|
|
17
|
+
* Every lazy schema declared so far, in declaration order.
|
|
18
|
+
*
|
|
19
|
+
* A definition error in a schema no longer fails the import — that is the point of `lazy` — so
|
|
20
|
+
* something has to actually build them to find one. `test/shared/lazy.test.ts` used to walk the
|
|
21
|
+
* **exports** of `contracts.ts` for that, which meant a schema that stopped being exported also
|
|
22
|
+
* stopped being checked (found the hard way: un-exporting 58 internal-only schemas silently took the
|
|
23
|
+
* guard's coverage from 153 to 95 and the test said so). Registering here instead makes the check
|
|
24
|
+
* cover every schema the module declares, exported or not.
|
|
25
|
+
*
|
|
26
|
+
* Bounded: `lazy()` is called at module scope once per schema, so this holds one thunk per schema
|
|
27
|
+
* for the life of the process.
|
|
28
|
+
*/
|
|
29
|
+
var declared = [];
|
|
30
|
+
function lazy(build) {
|
|
31
|
+
let built;
|
|
32
|
+
const real = () => {
|
|
33
|
+
if (built === void 0) {
|
|
34
|
+
built = build();
|
|
35
|
+
builds += 1;
|
|
36
|
+
}
|
|
37
|
+
return built;
|
|
38
|
+
};
|
|
39
|
+
declared.push(real);
|
|
40
|
+
/** Methods bound once to the real schema, so `this` inside ArkType is never the wrapper. */
|
|
41
|
+
const bound = /* @__PURE__ */ new Map();
|
|
42
|
+
return new Proxy((() => void 0), {
|
|
43
|
+
apply(_target, thisArg, args) {
|
|
44
|
+
const schema = real();
|
|
45
|
+
return args.length === 0 ? schema : Reflect.apply(schema, thisArg, args);
|
|
46
|
+
},
|
|
47
|
+
get(_target, key) {
|
|
48
|
+
if (key === "length") return 0;
|
|
49
|
+
const schema = real();
|
|
50
|
+
const value = Reflect.get(schema, key, schema);
|
|
51
|
+
if (typeof value !== "function" || "~standard" in value) return value;
|
|
52
|
+
let method = bound.get(key);
|
|
53
|
+
if (method === void 0) {
|
|
54
|
+
method = value.bind(schema);
|
|
55
|
+
bound.set(key, method);
|
|
56
|
+
}
|
|
57
|
+
return method;
|
|
58
|
+
},
|
|
59
|
+
has: (_target, key) => Reflect.has(real(), key),
|
|
60
|
+
getPrototypeOf: () => Reflect.getPrototypeOf(real())
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { lazy as t };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=lazy-Ce5zEAq1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lazy-Ce5zEAq1.js","names":[],"sources":["../../src/shared/lazy.ts"],"sourcesContent":["/**\n * A schema that is built the first time something uses it.\n *\n * Building every ArkType schema in `contracts.ts` took ~1.2 s at import — longer than most CLI\n * commands then ran, paid by every command, every spawned test child and every UI load, for schemas\n * the caller never touched. The wrapper is typed as the schema itself, so nothing that imports it\n * changes.\n *\n * It is a zero-length function on purpose: ArkType resolves a zero-argument function handed to it\n * as a definition by calling it (a thunk), so `type({ a: lazySchema })`, `.or(lazySchema)` and\n * friends receive the real node, never this wrapper. Called with arguments it validates, like the\n * schema it stands for.\n */\nlet builds = 0\n\n/** How many lazy schemas have been built so far, so a test can prove an import built none. */\nexport function lazyBuilds(): number {\n return builds\n}\n\n/**\n * Every lazy schema declared so far, in declaration order.\n *\n * A definition error in a schema no longer fails the import — that is the point of `lazy` — so\n * something has to actually build them to find one. `test/shared/lazy.test.ts` used to walk the\n * **exports** of `contracts.ts` for that, which meant a schema that stopped being exported also\n * stopped being checked (found the hard way: un-exporting 58 internal-only schemas silently took the\n * guard's coverage from 153 to 95 and the test said so). Registering here instead makes the check\n * cover every schema the module declares, exported or not.\n *\n * Bounded: `lazy()` is called at module scope once per schema, so this holds one thunk per schema\n * for the life of the process.\n */\nconst declared: Array<() => unknown> = []\n\nexport function lazySchemas(): ReadonlyArray<() => unknown> {\n return declared\n}\n\nexport function lazy<T extends object>(build: () => T): T {\n let built: T | undefined\n const real = (): T => {\n if (built === undefined) {\n built = build()\n builds += 1\n }\n return built\n }\n // Registered once per schema, at module scope, so the build-guard test can reach every one.\n declared.push(real)\n /** Methods bound once to the real schema, so `this` inside ArkType is never the wrapper. */\n const bound = new Map<PropertyKey, unknown>()\n\n return new Proxy((() => undefined) as unknown as T, {\n apply(_target, thisArg, args: unknown[]) {\n const schema = real()\n return args.length === 0 ? schema : Reflect.apply(schema as (...a: unknown[]) => unknown, thisArg, args)\n },\n get(_target, key) {\n // ArkType's thunk test reads `length`; the real schema's is not 0.\n if (key === 'length')\n return 0\n const schema = real()\n const value: unknown = Reflect.get(schema, key, schema)\n // A schema-valued property (`.in`, `.internal`) is returned as it is; a method is bound.\n if (typeof value !== 'function' || '~standard' in value)\n return value\n let method = bound.get(key)\n if (method === undefined) {\n method = (value as (...a: unknown[]) => unknown).bind(schema)\n bound.set(key, method)\n }\n return method\n },\n has: (_target, key) => Reflect.has(real(), key),\n getPrototypeOf: () => Reflect.getPrototypeOf(real()),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,IAAI,SAAS;;;;;;;;;;;;;;AAoBb,IAAM,WAAiC,CAAC;AAMxC,SAAgB,KAAuB,OAAmB;CACxD,IAAI;CACJ,MAAM,aAAgB;EACpB,IAAI,UAAU,KAAA,GAAW;GACvB,QAAQ,MAAM;GACd,UAAU;EACZ;EACA,OAAO;CACT;CAEA,SAAS,KAAK,IAAI;;CAElB,MAAM,wBAAQ,IAAI,IAA0B;CAE5C,OAAO,IAAI,aAAa,KAAA,IAA4B;EAClD,MAAM,SAAS,SAAS,MAAiB;GACvC,MAAM,SAAS,KAAK;GACpB,OAAO,KAAK,WAAW,IAAI,SAAS,QAAQ,MAAM,QAAwC,SAAS,IAAI;EACzG;EACA,IAAI,SAAS,KAAK;GAEhB,IAAI,QAAQ,UACV,OAAO;GACT,MAAM,SAAS,KAAK;GACpB,MAAM,QAAiB,QAAQ,IAAI,QAAQ,KAAK,MAAM;GAEtD,IAAI,OAAO,UAAU,cAAc,eAAe,OAChD,OAAO;GACT,IAAI,SAAS,MAAM,IAAI,GAAG;GAC1B,IAAI,WAAW,KAAA,GAAW;IACxB,SAAU,MAAuC,KAAK,MAAM;IAC5D,MAAM,IAAI,KAAK,MAAM;GACvB;GACA,OAAO;EACT;EACA,MAAM,SAAS,QAAQ,QAAQ,IAAI,KAAK,GAAG,GAAG;EAC9C,sBAAsB,QAAQ,eAAe,KAAK,CAAC;CACrD,CAAC;AACH"}
|