home-hosted 0.13.0 → 0.20.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 +117 -322
- package/bin/home-hosted.mjs +41 -0
- package/dist/chunks/account-DiLrSyww.js +359 -0
- package/dist/chunks/account-DiLrSyww.js.map +1 -0
- package/dist/chunks/add-DEIYVkNK.js +183 -0
- package/dist/chunks/add-DEIYVkNK.js.map +1 -0
- package/dist/chunks/{archive-DP-XQR8X.js → archive-DFi3qK1c.js} +25 -73
- package/dist/chunks/archive-DFi3qK1c.js.map +1 -0
- package/dist/chunks/{atomic-C1PfJpE7.js → atomic-SZUwDtGD.js} +3 -6
- package/dist/chunks/atomic-SZUwDtGD.js.map +1 -0
- package/dist/chunks/{backup-CZcVca2a.js → backup-DnyxIzw0.js} +110 -190
- package/dist/chunks/backup-DnyxIzw0.js.map +1 -0
- package/dist/chunks/backups-BrrN6cwW.js +2203 -0
- package/dist/chunks/backups-BrrN6cwW.js.map +1 -0
- package/dist/chunks/bind-DIxrnUst.js +43 -0
- package/dist/chunks/bind-DIxrnUst.js.map +1 -0
- package/dist/chunks/config-text-DxMOQQnk.js +34 -0
- package/dist/chunks/config-text-DxMOQQnk.js.map +1 -0
- package/dist/chunks/{contracts-CMBD1TF9.js → contracts-CxZ7u1L3.js} +1239 -1454
- package/dist/chunks/contracts-CxZ7u1L3.js.map +1 -0
- package/dist/chunks/daemon-BAAYUYQC.js +211 -0
- package/dist/chunks/daemon-BAAYUYQC.js.map +1 -0
- package/dist/chunks/daemon-log-Ccu-69vB.js +179 -0
- package/dist/chunks/daemon-log-Ccu-69vB.js.map +1 -0
- package/dist/chunks/deploy-CggSOEkq.js +144 -0
- package/dist/chunks/deploy-CggSOEkq.js.map +1 -0
- package/dist/chunks/{docker-Cy9Lyvda.js → docker--Un0uLfF.js} +32 -68
- package/dist/chunks/docker--Un0uLfF.js.map +1 -0
- package/dist/chunks/{down-pKbGCW9d.js → down-CpIN7LEQ.js} +34 -94
- package/dist/chunks/down-CpIN7LEQ.js.map +1 -0
- package/dist/chunks/exposure-CDJNvOCK.js +229 -0
- package/dist/chunks/exposure-CDJNvOCK.js.map +1 -0
- package/dist/chunks/import-Bd4VZH0f.js +205 -0
- package/dist/chunks/import-Bd4VZH0f.js.map +1 -0
- package/dist/chunks/import-plan--fDS_l5r.js +147 -0
- package/dist/chunks/import-plan--fDS_l5r.js.map +1 -0
- package/dist/chunks/import-write-BTfbeV26.js +42 -0
- package/dist/chunks/import-write-BTfbeV26.js.map +1 -0
- package/dist/chunks/{init-BZ7hK9Vf.js → init-Bv3oH65x.js} +14 -50
- package/dist/chunks/init-Bv3oH65x.js.map +1 -0
- package/dist/chunks/job-CYOdN6Ub.js +341 -0
- package/dist/chunks/job-CYOdN6Ub.js.map +1 -0
- package/dist/chunks/jobs-BX4ahcfh.js +489 -0
- package/dist/chunks/jobs-BX4ahcfh.js.map +1 -0
- package/dist/chunks/last-stop-DD3lHwo_.js +42 -0
- package/dist/chunks/last-stop-DD3lHwo_.js.map +1 -0
- package/dist/chunks/layout-D0ysDNav.js +18 -0
- package/dist/chunks/layout-D0ysDNav.js.map +1 -0
- package/dist/chunks/lazy-kfcBNeqj.js +48 -0
- package/dist/chunks/lazy-kfcBNeqj.js.map +1 -0
- package/dist/chunks/log-buffer-B7jmn7ts.js +110 -0
- package/dist/chunks/log-buffer-B7jmn7ts.js.map +1 -0
- package/dist/chunks/log-files-CZL2UhuE.js +488 -0
- package/dist/chunks/log-files-CZL2UhuE.js.map +1 -0
- package/dist/chunks/{logger-B5U4GD3j.js → logger-BnrKTBHQ.js} +2 -6
- package/dist/chunks/logger-BnrKTBHQ.js.map +1 -0
- package/dist/chunks/{logs---TI_bxM.js → logs-DxKI6OW2.js} +23 -73
- package/dist/chunks/logs-DxKI6OW2.js.map +1 -0
- package/dist/chunks/ls-BseUHy_m.js +128 -0
- package/dist/chunks/ls-BseUHy_m.js.map +1 -0
- package/dist/chunks/migrate-D4w_dXDm.js +268 -0
- package/dist/chunks/migrate-D4w_dXDm.js.map +1 -0
- package/dist/chunks/{nanny-B-Eu0sFW.js → nanny-BWh7nuvv.js} +21 -14
- package/dist/chunks/nanny-BWh7nuvv.js.map +1 -0
- package/dist/chunks/{nanny-ChMtq1Zl.js → nanny-BjF2-1pv.js} +3 -3
- package/dist/chunks/{nanny-ChMtq1Zl.js.map → nanny-BjF2-1pv.js.map} +1 -1
- package/dist/chunks/nanny-DGTXVq5d.js +806 -0
- package/dist/chunks/nanny-DGTXVq5d.js.map +1 -0
- package/dist/chunks/{nanny-sweep-DErnlPY1.js → nanny-sweep-hjmZ_p7S.js} +14 -24
- package/dist/chunks/nanny-sweep-hjmZ_p7S.js.map +1 -0
- package/dist/chunks/{nearest-6KgQEDUe.js → nearest-DOx4jySJ.js} +2 -10
- package/dist/chunks/nearest-DOx4jySJ.js.map +1 -0
- package/dist/chunks/{parse-DhmG26fI.js → parse-DVMPLUDe.js} +47 -72
- package/dist/chunks/parse-DVMPLUDe.js.map +1 -0
- package/dist/chunks/password-policy-Clq6PGE-.js +9 -0
- package/dist/chunks/password-policy-Clq6PGE-.js.map +1 -0
- package/dist/chunks/{paths-CGlGDrOU.js → paths-C34-TJLh.js} +32 -56
- package/dist/chunks/paths-C34-TJLh.js.map +1 -0
- package/dist/chunks/{port-B8WBTRMk.js → port-CnsrxKNR.js} +27 -71
- package/dist/chunks/port-CnsrxKNR.js.map +1 -0
- package/dist/chunks/process-CboOFPU_.js +192 -0
- package/dist/chunks/process-CboOFPU_.js.map +1 -0
- package/dist/chunks/{restart-Des4DrAN.js → restart-C0J8dZ2L.js} +11 -29
- package/dist/chunks/restart-C0J8dZ2L.js.map +1 -0
- package/dist/chunks/run-deploy-DoNDvwT4.js +91 -0
- package/dist/chunks/run-deploy-DoNDvwT4.js.map +1 -0
- package/dist/chunks/{schema-B240VXcV.js → schema-CZ6f-PHD.js} +7 -20
- package/dist/chunks/schema-CZ6f-PHD.js.map +1 -0
- package/dist/chunks/secret-MY397r90.js +219 -0
- package/dist/chunks/secret-MY397r90.js.map +1 -0
- package/dist/chunks/secrets-CG5N4lwY.js +1061 -0
- package/dist/chunks/secrets-CG5N4lwY.js.map +1 -0
- package/dist/chunks/server-Dm_dXfTW.js +255 -0
- package/dist/chunks/server-Dm_dXfTW.js.map +1 -0
- package/dist/chunks/server-attention-UQwYXqKe.js +10 -0
- package/dist/chunks/server-attention-UQwYXqKe.js.map +1 -0
- package/dist/chunks/server-create-D7nvhgBd.js +96 -0
- package/dist/chunks/server-create-D7nvhgBd.js.map +1 -0
- package/dist/chunks/server-ids-BEQD2rFz.js +23 -0
- package/dist/chunks/server-ids-BEQD2rFz.js.map +1 -0
- package/dist/chunks/server-vars-DMYmHutL.js +27 -0
- package/dist/chunks/server-vars-DMYmHutL.js.map +1 -0
- package/dist/chunks/service-C8l-ewNA.js +585 -0
- package/dist/chunks/service-C8l-ewNA.js.map +1 -0
- package/dist/chunks/{settings-xu-XTfWg.js → settings-CtYDs5PX.js} +62 -78
- package/dist/chunks/settings-CtYDs5PX.js.map +1 -0
- package/dist/chunks/{setup-temp-CAN4_bA-.js → setup-temp-TAtDmMMU.js} +43 -37
- package/dist/chunks/setup-temp-TAtDmMMU.js.map +1 -0
- package/dist/chunks/shape-CDGeYl_J.js +9 -0
- package/dist/chunks/shape-CDGeYl_J.js.map +1 -0
- package/dist/chunks/{src-BtWMFmzZ.js → src-BnzkVy_M.js} +12548 -10576
- package/dist/chunks/src-BnzkVy_M.js.map +1 -0
- package/dist/chunks/{status-DT1EsA-B.js → status-efbbfYZQ.js} +53 -26
- package/dist/chunks/status-efbbfYZQ.js.map +1 -0
- package/dist/chunks/store-Bs_Lljjm.js +2082 -0
- package/dist/chunks/store-Bs_Lljjm.js.map +1 -0
- package/dist/chunks/template-xan58bJh.js +28 -0
- package/dist/chunks/template-xan58bJh.js.map +1 -0
- package/dist/chunks/token-DDeWfZA4.js +142 -0
- package/dist/chunks/token-DDeWfZA4.js.map +1 -0
- package/dist/chunks/{ui-D562aqw5.js → ui-BcIAtyxE.js} +68 -79
- package/dist/chunks/ui-BcIAtyxE.js.map +1 -0
- package/dist/chunks/{ui-dir-CsU3uLNV.js → ui-dir-ClCzVRc3.js} +3 -7
- package/dist/chunks/ui-dir-ClCzVRc3.js.map +1 -0
- package/dist/chunks/ui-format-CDvvqOoi.js +53 -0
- package/dist/chunks/ui-format-CDvvqOoi.js.map +1 -0
- package/dist/chunks/{ui-release-DKzVvlLd.js → ui-release-XbJ85pYI.js} +36 -38
- package/dist/chunks/ui-release-XbJ85pYI.js.map +1 -0
- package/dist/chunks/{ui-revert-EkBBwRTt.js → ui-revert-Dgawq7ze.js} +4 -4
- package/dist/chunks/ui-revert-Dgawq7ze.js.map +1 -0
- package/dist/chunks/{ui-switch-BnZTdMDd.js → ui-switch-CfQMbZ0g.js} +31 -38
- package/dist/chunks/ui-switch-CfQMbZ0g.js.map +1 -0
- package/dist/chunks/{ui-update-_xryLYxw.js → ui-update-B3PPivUm.js} +30 -48
- package/dist/chunks/ui-update-B3PPivUm.js.map +1 -0
- package/dist/chunks/ui-update-CAiH2tFb.js +109 -0
- package/dist/chunks/ui-update-CAiH2tFb.js.map +1 -0
- package/dist/chunks/{up-Pdz-l6IH.js → up-BQSnYxYd.js} +47 -53
- package/dist/chunks/up-BQSnYxYd.js.map +1 -0
- package/dist/chunks/{usage-DFrCVXpT.js → usage-KG8TeOio.js} +7 -20
- package/dist/chunks/usage-KG8TeOio.js.map +1 -0
- package/dist/chunks/{workspaces-DYcfvKV_.js → workspaces-D9akpzU8.js} +80 -68
- package/dist/chunks/workspaces-D9akpzU8.js.map +1 -0
- package/dist/chunks/{wsl-temperature-BiCI4iK6.js → wsl-temperature-D-_d4Yk1.js} +47 -42
- package/dist/chunks/wsl-temperature-D-_d4Yk1.js.map +1 -0
- package/dist/cli.js +306 -238
- package/dist/cli.js.map +1 -1
- package/dist/client.js +76 -29
- package/dist/client.js.map +1 -1
- package/dist/types/api/acme.d.ts +3 -7
- package/dist/types/api/auth/$.routes.d.ts +107 -16
- package/dist/types/api/backups.d.ts +5 -5
- package/dist/types/api/control.d.ts +747 -38
- package/dist/types/api/ddns.d.ts +13 -18
- package/dist/types/api/events.d.ts +9 -3
- package/dist/types/api/health.d.ts +2 -4
- package/dist/types/api/jobs.d.ts +438 -0
- package/dist/types/api/logs.d.ts +20 -0
- package/dist/types/api/metrics.d.ts +2 -5
- package/dist/types/api/notifications.d.ts +3 -6
- package/dist/types/api/proxy.d.ts +63 -23
- package/dist/types/api/server-ops.d.ts +17 -0
- package/dist/types/api/servers/$.routes.d.ts +418 -186
- package/dist/types/api/session-required.d.ts +16 -0
- package/dist/types/api/settings.d.ts +7 -7
- package/dist/types/api/state.d.ts +100 -10
- package/dist/types/api/static.d.ts +2 -2
- package/dist/types/api/tls.d.ts +2 -5
- package/dist/types/api/workspaces/$.routes.d.ts +186 -12
- package/dist/types/api/wsl-temperature.d.ts +4 -10
- package/dist/types/app.d.ts +4511 -2778
- package/dist/types/cli/account.d.ts +23 -0
- package/dist/types/cli/add.d.ts +96 -0
- package/dist/types/cli/args.d.ts +24 -35
- package/dist/types/cli/backup-offline.d.ts +2 -8
- package/dist/types/cli/backup.d.ts +12 -21
- package/dist/types/cli/down.d.ts +15 -41
- package/dist/types/cli/import-plan.d.ts +55 -0
- package/dist/types/cli/import-write.d.ts +5 -0
- package/dist/types/cli/import.d.ts +86 -0
- package/dist/types/cli/io.d.ts +26 -35
- package/dist/types/cli/job.d.ts +99 -0
- package/dist/types/cli/logs.d.ts +1 -10
- package/dist/types/cli/ls.d.ts +57 -0
- package/dist/types/cli/migrate.d.ts +31 -8
- package/dist/types/cli/nearest.d.ts +1 -9
- package/dist/types/cli/run-deploy.d.ts +36 -0
- package/dist/types/cli/secret.d.ts +90 -0
- package/dist/types/cli/server.d.ts +6 -15
- package/dist/types/cli/service.d.ts +135 -0
- package/dist/types/cli/setup-temp.d.ts +17 -13
- package/dist/types/cli/status.d.ts +7 -1
- package/dist/types/cli/token.d.ts +6 -0
- package/dist/types/cli/ui-switch.d.ts +3 -14
- package/dist/types/cli/ui-update.d.ts +3 -16
- package/dist/types/cli/up.d.ts +9 -22
- package/dist/types/cli/usage.d.ts +2 -6
- package/dist/types/cli.d.ts +1 -10
- package/dist/types/client.d.ts +4099 -1142
- package/dist/types/config/accounts.d.ts +16 -0
- package/dist/types/config/jobs.d.ts +68 -0
- package/dist/types/config/layout.d.ts +2 -8
- package/dist/types/config/migrations.d.ts +9 -41
- package/dist/types/config/parse.d.ts +8 -13
- package/dist/types/config/patch.d.ts +1 -6
- package/dist/types/config/schema.d.ts +16 -18
- package/dist/types/config/secret-parts.d.ts +6 -27
- package/dist/types/config/secrets.d.ts +167 -88
- package/dist/types/config/seed.d.ts +1 -6
- package/dist/types/config/server-ids.d.ts +2 -11
- package/dist/types/config/settings.d.ts +13 -49
- package/dist/types/config/store.d.ts +17 -54
- package/dist/types/config/workspaces.d.ts +24 -56
- package/dist/types/helpers/action-result.d.ts +18 -32
- package/dist/types/helpers/atomic.d.ts +1 -4
- package/dist/types/helpers/backoff.d.ts +0 -1
- package/dist/types/helpers/bind.d.ts +3 -11
- package/dist/types/helpers/config-text.d.ts +4 -19
- package/dist/types/helpers/cookies.d.ts +2 -7
- package/dist/types/helpers/copy-tree.d.ts +4 -12
- package/dist/types/helpers/daemon-log.d.ts +8 -33
- package/dist/types/helpers/daemon.d.ts +20 -70
- package/dist/types/helpers/deferred.d.ts +2 -4
- package/dist/types/helpers/env-file.d.ts +2 -7
- package/dist/types/helpers/error.d.ts +3 -14
- package/dist/types/helpers/event-stream.d.ts +18 -10
- package/dist/types/helpers/factory.d.ts +2 -3
- package/dist/types/helpers/last-stop.d.ts +5 -12
- package/dist/types/helpers/logger.d.ts +1 -5
- package/dist/types/helpers/open.d.ts +0 -1
- package/dist/types/helpers/openapi.d.ts +19 -5
- package/dist/types/helpers/paths.d.ts +18 -53
- package/dist/types/helpers/restore-lock.d.ts +2 -17
- package/dist/types/helpers/runtime.d.ts +3 -13
- package/dist/types/helpers/secret-compare.d.ts +2 -10
- package/dist/types/helpers/server-create.d.ts +15 -0
- package/dist/types/helpers/shell.d.ts +2 -16
- package/dist/types/helpers/sse.d.ts +8 -6
- package/dist/types/helpers/ui-dir.d.ts +1 -5
- package/dist/types/helpers/utf8-chunks.d.ts +2 -8
- package/dist/types/helpers/validate.d.ts +2 -4
- package/dist/types/helpers/validator.d.ts +8 -4
- package/dist/types/helpers/version.d.ts +1 -6
- package/dist/types/helpers/workspace.d.ts +24 -16
- package/dist/types/index.d.ts +2 -3
- package/dist/types/middleware/auth.d.ts +8 -27
- package/dist/types/middleware/body-limit.d.ts +10 -0
- package/dist/types/middleware/host.d.ts +4 -23
- package/dist/types/middleware/loopback.d.ts +1 -8
- package/dist/types/middleware/token-scope.d.ts +34 -0
- package/dist/types/node-compat.d.ts +43 -0
- package/dist/types/openapi-reference.d.ts +4 -19
- package/dist/types/openapi.d.ts +5 -8
- package/dist/types/providers/archive.d.ts +8 -25
- package/dist/types/providers/backup-hook.d.ts +4 -19
- package/dist/types/providers/ddns/dyndns2.d.ts +0 -3
- package/dist/types/providers/ddns/index.d.ts +2 -3
- package/dist/types/providers/ddns/ip.d.ts +2 -12
- package/dist/types/providers/ddns/namecheap-api.d.ts +3 -2
- package/dist/types/providers/ddns/types.d.ts +6 -32
- package/dist/types/providers/ddns/zone.d.ts +1 -4
- package/dist/types/providers/docker.d.ts +18 -45
- package/dist/types/providers/entry-state.d.ts +4 -9
- package/dist/types/providers/health-check.d.ts +1 -5
- package/dist/types/providers/host.d.ts +33 -108
- package/dist/types/providers/identity.d.ts +9 -34
- package/dist/types/providers/log-tail.d.ts +14 -24
- package/dist/types/providers/nanny-sweep.d.ts +8 -25
- package/dist/types/providers/nanny.d.ts +16 -58
- package/dist/types/providers/port.d.ts +28 -83
- package/dist/types/providers/proc.d.ts +22 -80
- package/dist/types/providers/process.d.ts +12 -36
- package/dist/types/providers/proxy/admin.d.ts +11 -0
- package/dist/types/providers/proxy/types.d.ts +4 -16
- package/dist/types/providers/telegram.d.ts +1 -17
- package/dist/types/providers/ui-release.d.ts +15 -25
- package/dist/types/providers/webhook.d.ts +8 -29
- package/dist/types/providers/wsl-temperature.d.ts +13 -22
- package/dist/types/services/acme-challenge.d.ts +2 -16
- package/dist/types/services/auth.d.ts +65 -80
- package/dist/types/services/backups/archive-safety.d.ts +30 -0
- package/dist/types/services/backups/paths.d.ts +31 -0
- package/dist/types/services/backups.d.ts +61 -271
- package/dist/types/services/config-watch.d.ts +3 -15
- package/dist/types/services/control-server.d.ts +6 -10
- package/dist/types/services/ddns.d.ts +12 -13
- package/dist/types/services/dependencies.d.ts +3 -14
- package/dist/types/services/deploy.d.ts +34 -0
- package/dist/types/services/events.d.ts +15 -9
- package/dist/types/services/exposure.d.ts +13 -63
- package/dist/types/services/history.d.ts +5 -14
- package/dist/types/services/host-monitor.d.ts +6 -11
- package/dist/types/services/init.d.ts +5 -35
- package/dist/types/services/job-ledger.d.ts +27 -0
- package/dist/types/services/jobs.d.ts +113 -0
- package/dist/types/services/log-buffer.d.ts +7 -8
- package/dist/types/services/log-files.d.ts +12 -42
- package/dist/types/services/log-relay.d.ts +3 -13
- package/dist/types/services/nanny.d.ts +3 -10
- package/dist/types/services/notifications.d.ts +31 -61
- package/dist/types/services/panel.d.ts +32 -78
- package/dist/types/services/proxy-certificates/certificates.d.ts +31 -69
- package/dist/types/services/proxy-config.d.ts +15 -36
- package/dist/types/services/proxy-dns01.d.ts +14 -0
- package/dist/types/services/proxy.d.ts +73 -254
- package/dist/types/services/scheduler.d.ts +46 -0
- package/dist/types/services/state.d.ts +17 -8
- package/dist/types/services/supervisor/compose.d.ts +2 -6
- package/dist/types/services/supervisor/entry.d.ts +29 -32
- package/dist/types/services/supervisor/health.d.ts +8 -31
- package/dist/types/services/supervisor/job-run.d.ts +36 -0
- package/dist/types/services/supervisor/output.d.ts +13 -77
- package/dist/types/services/supervisor/persistent.d.ts +5 -11
- package/dist/types/services/supervisor/port-preflight.d.ts +4 -10
- package/dist/types/services/supervisor/records.d.ts +27 -60
- package/dist/types/services/supervisor/restart-required.d.ts +13 -0
- package/dist/types/services/supervisor/spawn.d.ts +3 -5
- package/dist/types/services/supervisor/view.d.ts +3 -1
- package/dist/types/services/supervisor.d.ts +31 -43
- package/dist/types/services/tls.d.ts +6 -17
- package/dist/types/services/ui-update.d.ts +19 -17
- package/dist/types/services/ui.d.ts +10 -19
- package/dist/types/shared/action-outcome.d.ts +2 -7
- package/dist/types/shared/api-client.d.ts +133 -177
- package/dist/types/shared/api-scopes.d.ts +17 -0
- package/dist/types/shared/backup-scope.d.ts +16 -90
- package/dist/types/shared/clone.d.ts +2 -11
- package/dist/types/shared/contracts/accounts.d.ts +99 -0
- package/dist/types/shared/contracts/backups.d.ts +219 -0
- package/dist/types/shared/contracts/ddns.d.ts +208 -0
- package/dist/types/shared/contracts/frames.d.ts +1395 -0
- package/dist/types/shared/contracts/index.d.ts +3 -0
- package/dist/types/shared/contracts/logs.d.ts +107 -0
- package/dist/types/shared/contracts/proxy.d.ts +303 -0
- package/dist/types/shared/contracts.d.ts +852 -1982
- package/dist/types/shared/cpu-scale.d.ts +3 -19
- package/dist/types/shared/crash-cause.d.ts +8 -0
- package/dist/types/shared/cron.d.ts +70 -0
- package/dist/types/shared/ddns-form.d.ts +9 -43
- package/dist/types/shared/endpoint.d.ts +1 -7
- package/dist/types/shared/error-codes.d.ts +438 -0
- package/dist/types/shared/error-message.d.ts +1 -7
- package/dist/types/shared/fields.d.ts +7 -17
- package/dist/types/shared/form-repair.d.ts +1 -5
- package/dist/types/shared/generated.d.ts +3 -19
- package/dist/types/shared/host-readings.d.ts +25 -128
- package/dist/types/shared/lazy.d.ts +1 -1
- package/dist/types/shared/live-frames.d.ts +2 -8
- package/dist/types/shared/live-series.d.ts +2 -8
- package/dist/types/shared/live-store.d.ts +4 -8
- package/dist/types/shared/log-download.d.ts +6 -0
- package/dist/types/shared/meta.d.ts +6 -0
- package/dist/types/shared/password-policy.d.ts +10 -0
- package/dist/types/shared/patch-diff.d.ts +13 -72
- package/dist/types/shared/port-reading.d.ts +18 -0
- package/dist/types/shared/probe-latency.d.ts +3 -21
- package/dist/types/shared/proxy-form.d.ts +33 -74
- package/dist/types/shared/proxy-validate.d.ts +11 -0
- package/dist/types/shared/query-params.d.ts +8 -0
- package/dist/types/shared/server-attention.d.ts +2 -27
- package/dist/types/shared/server-form.d.ts +15 -54
- package/dist/types/shared/server-key.d.ts +1 -12
- package/dist/types/shared/server-readings.d.ts +7 -32
- package/dist/types/shared/server-url.d.ts +9 -31
- package/dist/types/shared/shape.d.ts +1 -16
- package/dist/types/shared/stream-access.d.ts +2 -8
- package/dist/types/shared/ui-format.d.ts +25 -65
- package/docs/API.md +315 -107
- package/docs/BACKUPS.md +61 -56
- package/docs/CLI.md +255 -49
- package/docs/DDNS.md +35 -49
- package/docs/JOBS.md +129 -0
- package/docs/NOTIFICATIONS.md +58 -90
- package/docs/REVERSE_PROXY.md +116 -188
- package/docs/SECURITY.md +126 -44
- package/docs/SERVERS.md +282 -409
- package/docs/UI_CREATION.md +90 -47
- package/docs/demo/blank-host-restore.sh +31 -7
- package/package.json +15 -6
- package/scripts/prepare.mjs +47 -0
- package/uis/stock/dist/assets/CopyButton-8mliL0xi.js +1 -0
- package/uis/stock/dist/assets/GlobalSettingsView-BINXY77E.js +1 -0
- package/uis/stock/dist/assets/LogViewer-kiSnTwdY.js +1 -0
- package/uis/stock/dist/assets/LogsView-DDXf_ONs.js +1 -0
- package/uis/stock/dist/assets/Modal-lrUuViF2.js +39 -0
- package/uis/stock/dist/assets/ProxyView-uXMaJdSQ.js +1 -0
- package/uis/stock/dist/assets/ServerDetailView-CW0Vb_c0.js +4 -0
- package/uis/stock/dist/assets/SettingsShell-B135xWjJ.js +1 -0
- package/uis/stock/dist/assets/SettingsView-BLtWxVkl.js +2 -0
- package/uis/stock/dist/assets/de-BIoTrHBQ.js +1 -0
- package/uis/stock/dist/assets/es-x4-ih8lH.js +1 -0
- package/uis/stock/dist/assets/fr-DatqBBkO.js +1 -0
- package/uis/stock/dist/assets/index-CnojaKcA.css +2 -0
- package/uis/stock/dist/assets/index-D-CiZReu.js +16 -0
- package/uis/stock/dist/assets/ja-CW1703Gw.js +1 -0
- package/uis/stock/dist/assets/ko-wFbT4XtK.js +1 -0
- package/uis/stock/dist/assets/ru-C1p5C4VN.js +1 -0
- package/uis/stock/dist/assets/useUnsavedGuard-BcsXsfCC.js +9 -0
- package/uis/stock/dist/assets/vi-CDqr0uie.js +1 -0
- package/uis/stock/dist/assets/zh-CN-BJ7iit-X.js +1 -0
- package/uis/stock/dist/index.html +4 -3
- package/uis/stock/dist/ui.json +3 -3
- package/dist/chunks/archive-DP-XQR8X.js.map +0 -1
- package/dist/chunks/atomic-C1PfJpE7.js.map +0 -1
- package/dist/chunks/backup-CZcVca2a.js.map +0 -1
- package/dist/chunks/backups-CFRaWe_m.js +0 -4691
- package/dist/chunks/backups-CFRaWe_m.js.map +0 -1
- package/dist/chunks/config-text-DifCHhnz.js +0 -50
- package/dist/chunks/config-text-DifCHhnz.js.map +0 -1
- package/dist/chunks/contracts-CMBD1TF9.js.map +0 -1
- package/dist/chunks/daemon-log-BVj8cDEo.js +0 -241
- package/dist/chunks/daemon-log-BVj8cDEo.js.map +0 -1
- package/dist/chunks/daemon-qKVECISl.js +0 -247
- package/dist/chunks/daemon-qKVECISl.js.map +0 -1
- package/dist/chunks/docker-Cy9Lyvda.js.map +0 -1
- package/dist/chunks/down-pKbGCW9d.js.map +0 -1
- package/dist/chunks/init-BZ7hK9Vf.js.map +0 -1
- package/dist/chunks/last-stop-C-BXz_XI.js +0 -53
- package/dist/chunks/last-stop-C-BXz_XI.js.map +0 -1
- package/dist/chunks/layout-DwTtmund.js +0 -24
- package/dist/chunks/layout-DwTtmund.js.map +0 -1
- package/dist/chunks/lazy-Ce5zEAq1.js +0 -66
- package/dist/chunks/lazy-Ce5zEAq1.js.map +0 -1
- package/dist/chunks/log-buffer-Dy9HHDMD.js +0 -414
- package/dist/chunks/log-buffer-Dy9HHDMD.js.map +0 -1
- package/dist/chunks/logger-B5U4GD3j.js.map +0 -1
- package/dist/chunks/logs---TI_bxM.js.map +0 -1
- package/dist/chunks/migrate-Cfoq-Vgh.js +0 -155
- package/dist/chunks/migrate-Cfoq-Vgh.js.map +0 -1
- package/dist/chunks/nanny-B-Eu0sFW.js.map +0 -1
- package/dist/chunks/nanny-BtWfy0QH.js +0 -1167
- package/dist/chunks/nanny-BtWfy0QH.js.map +0 -1
- package/dist/chunks/nanny-sweep-DErnlPY1.js.map +0 -1
- package/dist/chunks/nearest-6KgQEDUe.js.map +0 -1
- package/dist/chunks/parse-DhmG26fI.js.map +0 -1
- package/dist/chunks/paths-CGlGDrOU.js.map +0 -1
- package/dist/chunks/port-B8WBTRMk.js.map +0 -1
- package/dist/chunks/restart-Des4DrAN.js.map +0 -1
- package/dist/chunks/schema-B240VXcV.js.map +0 -1
- package/dist/chunks/secrets-BieELnZh.js +0 -562
- package/dist/chunks/secrets-BieELnZh.js.map +0 -1
- package/dist/chunks/server-Bge2r2qQ.js +0 -169
- package/dist/chunks/server-Bge2r2qQ.js.map +0 -1
- package/dist/chunks/server-ids-DRuNLVCV.js +0 -32
- package/dist/chunks/server-ids-DRuNLVCV.js.map +0 -1
- package/dist/chunks/set-password-D5vZqqSX.js +0 -43
- package/dist/chunks/set-password-D5vZqqSX.js.map +0 -1
- package/dist/chunks/set-token-obPiEJYk.js +0 -78
- package/dist/chunks/set-token-obPiEJYk.js.map +0 -1
- package/dist/chunks/settings-xu-XTfWg.js.map +0 -1
- package/dist/chunks/setup-temp-CAN4_bA-.js.map +0 -1
- package/dist/chunks/shape-DnTKzjQ2.js +0 -24
- package/dist/chunks/shape-DnTKzjQ2.js.map +0 -1
- package/dist/chunks/src-BtWMFmzZ.js.map +0 -1
- package/dist/chunks/status-DT1EsA-B.js.map +0 -1
- package/dist/chunks/ui-D562aqw5.js.map +0 -1
- package/dist/chunks/ui-dir-CsU3uLNV.js.map +0 -1
- package/dist/chunks/ui-release-DKzVvlLd.js.map +0 -1
- package/dist/chunks/ui-revert-EkBBwRTt.js.map +0 -1
- package/dist/chunks/ui-switch-BnZTdMDd.js.map +0 -1
- package/dist/chunks/ui-update-_xryLYxw.js.map +0 -1
- package/dist/chunks/up-Pdz-l6IH.js.map +0 -1
- package/dist/chunks/usage-DFrCVXpT.js.map +0 -1
- package/dist/chunks/workspaces-DYcfvKV_.js.map +0 -1
- package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +0 -1
- package/dist/types/cli/set-password.d.ts +0 -14
- package/dist/types/cli/set-token.d.ts +0 -21
- package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +0 -1
- package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +0 -1
- package/uis/stock/dist/assets/LogViewer-DIliXy62.js +0 -1
- package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +0 -1
- package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +0 -39
- package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +0 -1
- package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +0 -2
- package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +0 -1
- package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +0 -2
- package/uis/stock/dist/assets/de-BRITeb0H.js +0 -1
- package/uis/stock/dist/assets/es-B2zIEssV.js +0 -1
- package/uis/stock/dist/assets/fr-s0ZOBEqh.js +0 -1
- package/uis/stock/dist/assets/index-C1MehbKy.css +0 -2
- package/uis/stock/dist/assets/index-CnBN54wF.js +0 -15
- package/uis/stock/dist/assets/ja-CU7MR85V.js +0 -1
- package/uis/stock/dist/assets/ko-tL5Me6d-.js +0 -1
- package/uis/stock/dist/assets/ru-92yrvkNJ.js +0 -1
- package/uis/stock/dist/assets/vi-CzvY16k2.js +0 -1
- package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nanny-BtWfy0QH.js","names":["execFileAsync","execFileAsync"],"sources":["../../src/providers/proc.ts","../../src/providers/identity.ts","../../src/providers/process.ts","../../src/providers/nanny.ts"],"sourcesContent":["import type { ProcessResources } from '#src/shared/contracts'\nimport { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\ninterface ProcRow {\n pid: number\n ppid: number\n rssKb: number\n /** Cumulative CPU seconds, when the platform reports it (Linux, Windows). */\n cpuSeconds?: number\n /** Instantaneous/decaying CPU percent, when the platform reports it (macOS). */\n cpuPercent?: number\n}\n\nexport function parsePsOutput(text: string): ProcRow[] {\n const rows: ProcRow[] = []\n for (const line of text.split('\\n')) {\n const parts = line.trim().split(/\\s+/)\n if (parts.length < 4)\n continue\n const [pid, ppid, rss, cpu] = parts.map(entry => Number.parseFloat(entry))\n if (pid === undefined || ppid === undefined || rss === undefined || !Number.isFinite(pid))\n continue\n rows.push({ pid, ppid, rssKb: rss, cpuPercent: Number.isFinite(cpu) ? cpu : undefined })\n }\n return rows\n}\n\n/** CSV from `Get-CimInstance ... | ConvertTo-Csv`, or wmic's `/format:csv`. */\nexport function parseWindowsCsv(text: string): ProcRow[] {\n const rows: ProcRow[] = []\n const lines = text.split(/\\r?\\n/).filter(line => line.trim().length > 0)\n const header = lines.shift()\n if (header === undefined)\n return rows\n\n const columns = header.split(',').map(entry => entry.replace(/\"/g, '').trim().toLowerCase())\n const index = (name: string): number => columns.indexOf(name.toLowerCase())\n const pidAt = index('ProcessId')\n const ppidAt = index('ParentProcessId')\n const rssAt = index('WorkingSetSize')\n const kernelAt = index('KernelModeTime')\n const userAt = index('UserModeTime')\n\n for (const line of lines) {\n const cells = line.split(',').map(entry => entry.replace(/\"/g, '').trim())\n const pid = Number.parseInt(cells[pidAt] ?? '', 10)\n if (!Number.isFinite(pid))\n continue\n\n // A missing time column must read as \"unknown\", never as zero CPU.\n const kernel = kernelAt >= 0 ? Number.parseInt(cells[kernelAt] ?? '', 10) : Number.NaN\n const user = userAt >= 0 ? Number.parseInt(cells[userAt] ?? '', 10) : Number.NaN\n const hasTimes = Number.isFinite(kernel) && Number.isFinite(user)\n\n rows.push({\n pid,\n ppid: Number.parseInt(cells[ppidAt] ?? '', 10) || 0,\n // WorkingSetSize is bytes on Windows; the sampler sums kilobytes.\n rssKb: (Number.parseInt(cells[rssAt] ?? '', 10) || 0) / 1024,\n cpuSeconds: hasTimes ? (kernel + user) / 1e7 /* 100ns units */ : undefined,\n })\n }\n\n return rows\n}\n\nlet clockTicks: number | null = null\nlet pageKb: number | null = null\n\n/** The kernel page size in kB (4 on x86, often 16 or 64 on arm64), read once. */\nasync function getPageKb(): Promise<number> {\n if (pageKb !== null)\n return pageKb\n try {\n const { stdout } = await execFileAsync('getconf', ['PAGESIZE'], { timeout: 2000 })\n const bytes = Number.parseInt(stdout.trim(), 10)\n pageKb = Number.isFinite(bytes) && bytes > 0 ? bytes / 1024 : 4\n }\n catch {\n pageKb = 4\n }\n return pageKb\n}\n\n/** Linux jiffies per second; `getconf` is POSIX, with the usual default behind it. */\nasync function getClockTicks(): Promise<number> {\n if (clockTicks !== null)\n return clockTicks\n try {\n const { stdout } = await execFileAsync('getconf', ['CLK_TCK'], { timeout: 2000 })\n const parsed = Number.parseInt(stdout.trim(), 10)\n clockTicks = Number.isFinite(parsed) && parsed > 0 ? parsed : 100\n }\n catch {\n clockTicks = 100\n }\n return clockTicks\n}\n\n/**\n * `/proc/<pid>/stat` needs care: the comm field is parenthesised and may itself\n * contain spaces or parentheses, so parsing starts after the last `)`.\n */\nfunction parseStat(pid: number, content: string, pageSizeKb = 4): ProcRow | null {\n const close = content.lastIndexOf(')')\n if (close < 0)\n return null\n const fields = content.slice(close + 2).split(' ')\n const ppid = Number.parseInt(fields[1] ?? '', 10)\n const utime = Number.parseInt(fields[11] ?? '', 10)\n const stime = Number.parseInt(fields[12] ?? '', 10)\n const rssPages = Number.parseInt(fields[21] ?? '', 10)\n\n if (!Number.isFinite(ppid) || !Number.isFinite(utime) || !Number.isFinite(stime))\n return null\n return { pid, ppid, rssKb: Number.isFinite(rssPages) ? rssPages * pageSizeKb : 0, cpuSeconds: utime + stime }\n}\n\n/** Processes read between two turns of the event loop, so a large host never stalls it. */\nconst SCAN_BATCH = 64\n\nasync function readLinux(): Promise<ProcRow[]> {\n const rows: ProcRow[] = []\n let names: string[] = []\n try {\n names = fs.readdirSync('/proc')\n }\n catch {\n return rows\n }\n\n // One read per process: `stat`'s resident page count times the real page size is VmRSS.\n const pageSizeKb = await getPageKb()\n let read = 0\n for (const name of names) {\n if (!/^\\d+$/.test(name))\n continue\n const pid = Number.parseInt(name, 10)\n try {\n const row = parseStat(pid, fs.readFileSync(`/proc/${pid}/stat`, 'utf8'), pageSizeKb)\n if (row !== null)\n rows.push(row)\n }\n catch {\n // Exited between listing and reading.\n }\n if (++read % SCAN_BATCH === 0)\n await new Promise(resolve => setImmediate(resolve))\n }\n\n return rows\n}\n\nasync function readPosix(): Promise<ProcRow[]> {\n const { stdout } = await execFileAsync('ps', ['-Ao', 'pid=,ppid=,rss=,%cpu='], { timeout: 5000, maxBuffer: 16 * 1024 * 1024 })\n return parsePsOutput(stdout)\n}\n\nasync function readWindows(): Promise<ProcRow[]> {\n const script = 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime | ConvertTo-Csv -NoTypeInformation'\n try {\n const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {\n timeout: 8000,\n maxBuffer: 16 * 1024 * 1024,\n })\n return parseWindowsCsv(stdout)\n }\n catch {\n try {\n const { stdout } = await execFileAsync('wmic', [\n 'process',\n 'get',\n 'ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime',\n '/format:csv',\n ], { timeout: 8000, maxBuffer: 16 * 1024 * 1024 })\n return parseWindowsCsv(stdout)\n }\n catch {\n // Neither tool is available; resource sampling degrades to \"unknown\".\n return []\n }\n }\n}\n\nlet scans = 0\n\n/** Test hook: how many real process-table scans have run. */\nexport function processScanCount(): number {\n return scans\n}\n\nfunction scanProcesses(): Promise<ProcRow[]> {\n scans += 1\n if (process.platform === 'linux')\n return readLinux()\n if (process.platform === 'win32')\n return readWindows()\n return readPosix()\n}\n\ninterface ProcessScan { at: number, rows: ProcRow[] }\nlet lastScan: { at: number, scan: Promise<ProcessScan> } | null = null\n\n/**\n * The process table. `reuseMs` lets a caller accept a scan that is in flight or that recent — the\n * resource samplers do, because every workspace has one and entries come due on their own second,\n * so one tick could otherwise walk `/proc` (or spawn PowerShell) once per workspace per due entry.\n * Anything deciding *ownership* passes 0: a process spawned a moment ago must be in its answer.\n */\nfunction readProcesses(now = Date.now(), reuseMs = 0): Promise<ProcessScan> {\n if (reuseMs > 0 && lastScan !== null && now - lastScan.at < reuseMs)\n return lastScan.scan\n // Stamped with when it was taken, so a sampler handed a reused scan times its CPU delta right.\n const scan = scanProcesses().then(rows => ({ at: now, rows }))\n lastScan = { at: now, scan }\n scan.catch(() => {\n if (lastScan?.scan === scan)\n lastScan = null\n })\n return scan\n}\n\n/** Test hook: the next read scans afresh. */\nexport function forgetProcessScan(): void {\n lastScan = null\n}\n\nfunction collectTree(rootPid: number, children: Map<number, number[]>): number[] {\n const pids: number[] = []\n const stack = [rootPid]\n const seen = new Set<number>()\n\n while (stack.length > 0) {\n const pid = stack.pop()!\n if (seen.has(pid))\n continue\n seen.add(pid)\n pids.push(pid)\n for (const child of children.get(pid) ?? []) stack.push(child)\n }\n\n return pids\n}\n\n/**\n * CPU time a tree used over one interval, from per-pid cumulative counters.\n *\n * Pure, and separated from the scan because this is where both CPU bugs lived — and a scan of the\n * live process table cannot pin arithmetic that depends on a child appearing or vanishing between\n * two reads.\n *\n * `previous` is the **whole process table** of the prior scan, not just this tree: that is what\n * lets a process which joins the tree later be charged only its interval, and what the caller\n * guarantees.\n *\n * Three rules make the answer a real interval:\n *\n * - A pid in both maps contributes the difference. `next >= previous` is required: a recycled pid\n * reports less than the process that used to hold it, and that is not a delta.\n * - A pid only in `next` was **born inside the window**, so its whole counter accrued in it.\n * - A pid only in `previous` **exited inside the window**; its time is already accounted for by the\n * samples where it was alive, and it contributes nothing. The old code summed the tree on both\n * sides, so an exit made the total *drop*, the delta went negative and the reading was discarded\n * — the gap. Summing only pids present in `next` is what removes it.\n *\n * `null` when the map has nothing usable, so a caller reports \"unknown\" instead of `0`.\n */\nexport function treeCpuUsedSeconds(\n previous: Map<number, number>,\n next: Map<number, number>,\n treePids: number[],\n): number | null {\n let used = 0\n let sawAny = false\n for (const pid of treePids) {\n const current = next.get(pid)\n if (current === undefined)\n continue\n const before = previous.get(pid)\n if (before === undefined) {\n used += current\n sawAny = true\n continue\n }\n if (current >= before) {\n used += current - before\n sawAny = true\n }\n }\n return sawAny ? used : null\n}\n\n/**\n * The same walk, keeping *which root* each pid belongs to.\n *\n * A refusal has to name the server to go and stop, and a pid on its own is not that: the panel\n * supervised 14 entries and told the operator \"held by pid 135113, which this panel supervises —\n * stop that server instead\", with no way to tell which of the 14 it meant. The tree loses that\n * fact, so the attribution is collected here, where the walk already happens, rather than by a\n * second scan.\n *\n * Ownership has to mean the *tree*: a persistent entry runs under a nanny, and a wrapper entry\n * spawns the real server one generation down. Both keep the pid the panel recorded, but the process\n * holding the port is a descendant of it — and a descendant classified as a stranger is one\n * `kill`/`free-port` away from stopping a server this panel is responsible for.\n *\n * A backend that cannot run answers with the roots alone, which is the old, narrower behaviour\n * rather than a wrong one.\n *\n * When two roots are nested, the ancestor keeps the pid: it is the older claim and still true.\n */\nexport async function processTreeOwners(roots: number[]): Promise<Map<number, number>> {\n const owners = new Map<number, number>()\n for (const root of roots) {\n if (!owners.has(root))\n owners.set(root, root)\n }\n if (roots.length === 0)\n return owners\n\n try {\n const { rows } = await readProcesses()\n const children = new Map<number, number[]>()\n for (const row of rows) {\n const siblings = children.get(row.ppid) ?? []\n siblings.push(row.pid)\n children.set(row.ppid, siblings)\n }\n for (const root of roots) {\n for (const pid of collectTree(root, children)) {\n if (!owners.has(pid))\n owners.set(pid, root)\n }\n }\n }\n catch {\n // Sampling already treats an unreadable table as \"nothing to say\".\n }\n\n return owners\n}\n\n/**\n * Samples CPU and RSS for a process *and its descendants*.\n *\n * Descendants matter: a wrapper that spawns the real server detached owns the\n * tree, and only the tree's RSS means anything.\n *\n * Backends: `/proc` on Linux, `ps` on macOS/other POSIX, and Win32_Process via\n * PowerShell (wmic as a fallback) on Windows. When a backend cannot run, samples\n * are null rather than wrong.\n */\nexport class ProcessSampler {\n /** `reuseMs`: accept a process scan this recent from any sampler (0 = always scan fresh). */\n constructor(private readonly reuseMs = 0) {}\n\n /**\n * Cumulative CPU seconds per pid, from the **whole process table** of the last scan.\n *\n * A tree is not a fixed set of processes: a wrapper spawns and reaps children continuously, so\n * \"the sum over whatever is in the tree now\" is not comparable with the previous sum. Measuring\n * that rule against a wrapper respawning a 1.5 s worker, **two samples in every three were\n * discarded**: the child's exit made the sum drop, the delta went negative, and the reading was\n * thrown away — the gaps a person sees on a live server.\n *\n * Baselining every pid the scan saw, rather than only the tree's, is what makes each delta a\n * real interval. A process that was already running has a previous counter even if it only\n * joined this tree afterwards, so it cannot be charged its whole lifetime; and a pid absent from\n * the previous scan was born inside the window, so its counter really did accrue in it.\n */\n private previousTable: { at: number, cpuSeconds: Map<number, number> } | null = null\n\n /**\n * Roots whose next sample must not be differenced, stamped with when they were forgotten.\n *\n * `forget` is called when an entry stops, exits or is restarted: the pid is gone, so the reading\n * after it must be `null` rather than a delta against a previous life. The baseline is one table\n * for the whole scan, so this is the per-root suppression. Pruned at each scan, which bounds it\n * to the restarts that happened since the last one.\n */\n private readonly forgotten = new Map<number, number>()\n\n /** Each root's latest reading, answered again when the only scan available is one already used. */\n private readonly lastReadings = new Map<number, ProcessResources>()\n\n async sample(rootPid: number, now = Date.now()): Promise<ProcessResources | null> {\n const samples = await this.sampleMany([rootPid], now)\n return samples.get(rootPid) ?? null\n }\n\n async sampleMany(rootPids: number[], now = Date.now()): Promise<Map<number, ProcessResources | null>> {\n const results = new Map<number, ProcessResources | null>()\n if (rootPids.length === 0)\n return results\n\n let rows: ProcRow[] = []\n let scannedAt = now\n try {\n const scan = await readProcesses(now, this.reuseMs)\n rows = scan.rows\n scannedAt = scan.at\n }\n catch {\n rows = []\n }\n\n // The same scan this sampler already differenced: a second delta would be zero, not a reading.\n if (this.previousTable !== null && this.previousTable.at === scannedAt && rows.length > 0) {\n for (const rootPid of rootPids)\n results.set(rootPid, this.lastReadings.get(rootPid) ?? null)\n return results\n }\n\n const byPid = new Map(rows.map(row => [row.pid, row]))\n const children = new Map<number, number[]>()\n for (const row of rows) {\n const siblings = children.get(row.ppid) ?? []\n siblings.push(row.pid)\n children.set(row.ppid, siblings)\n }\n\n // One baseline for the scan, shared by every root: they were all read at the same instant.\n const before = this.previousTable\n const elapsedSeconds = before === null ? 0 : (scannedAt - before.at) / 1000\n const ticks = process.platform === 'linux' ? await getClockTicks() : 1\n // Stored in *seconds*, the unit the comparison uses. Keeping raw jiffies here made every\n // Linux delta compare `seconds` against `jiffies`, so each one looked negative and was skipped.\n const tableCpuSeconds = new Map<number, number>()\n for (const row of rows) {\n if (row.cpuSeconds !== undefined)\n tableCpuSeconds.set(row.pid, row.cpuSeconds / ticks)\n }\n\n for (const rootPid of rootPids) {\n if (!byPid.has(rootPid)) {\n results.set(rootPid, null)\n continue\n }\n\n // A root forgotten since the last scan has no baseline to be measured against: its next\n // reading is the first of a new life, so it reports \"no window yet\" and re-baselines.\n const wasForgotten = this.forgotten.delete(rootPid)\n const pids = collectTree(rootPid, children)\n let rssKb = 0\n let percentAverage: number | null = null\n // Per-pid cumulative seconds for this tree, in the unit the comparison uses. Linux reports\n // jiffies; every other backend reports seconds already.\n const treeSeconds = new Map<number, number>()\n\n for (const pid of pids) {\n const row = byPid.get(pid)\n if (!row)\n continue\n rssKb += row.rssKb\n if (row.cpuPercent !== undefined)\n percentAverage = (percentAverage ?? 0) + row.cpuPercent\n if (row.cpuSeconds !== undefined)\n treeSeconds.set(pid, row.cpuSeconds / ticks)\n }\n\n const usedSeconds = before === null\n ? null\n : treeCpuUsedSeconds(before.cpuSeconds, treeSeconds, pids)\n let cpuPercent: number | null = percentAverage\n if (cpuPercent === null && !wasForgotten && usedSeconds !== null && elapsedSeconds > 0)\n cpuPercent = (usedSeconds / elapsedSeconds) * 100\n\n results.set(rootPid, {\n cpuPercent: cpuPercent === null ? null : Math.round(cpuPercent * 10) / 10,\n rssBytes: Math.round(rssKb * 1024),\n processes: pids.length,\n sampledAt: scannedAt,\n })\n }\n\n this.previousTable = { at: scannedAt, cpuSeconds: tableCpuSeconds }\n for (const [pid, reading] of results) {\n if (reading !== null)\n this.lastReadings.set(pid, reading)\n else\n this.lastReadings.delete(pid)\n }\n return results\n }\n\n /**\n * Marks a root's next reading as the first of a new life.\n *\n * Called when an entry stops, exits or is restarted. Without it a recycled pid — or the very\n * next sample of the same root — would be differenced against a counter from the previous run,\n * which is not an interval. The scan-wide table cannot be cleared per root, so the suppression\n * is remembered here and consumed by that root's next sample.\n */\n forget(rootPid: number): void {\n this.lastReadings.delete(rootPid)\n this.forgotten.set(rootPid, Date.now())\n }\n}\n\n/**\n * Does this process carry the environment the supervisor gave the entry?\n *\n * A program that restarts itself — especially a plugin doing it — leaves behind a\n * detached process that still inherits `HHOSTED_SERVER_ID`, and that marker is what\n * tells a legitimate successor apart from a stranger squatting on the port.\n *\n * Linux reads `/proc`; macOS asks `ps -E`; Windows has no per-process environment,\n * so the answer is always \"no\" there and ownership falls back to the port policy.\n */\nexport async function processCarriesServerId(pid: number, serverId: string): Promise<boolean> {\n if (serverId.length === 0)\n return false\n const needle = `HHOSTED_SERVER_ID=${serverId}`\n\n if (process.platform === 'linux') {\n try {\n const raw = await fs.promises.readFile(`/proc/${pid}/environ`, 'utf8')\n return raw.split('\\0').includes(needle)\n }\n catch {\n return false\n }\n }\n\n if (process.platform === 'darwin') {\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-E', '-ww', '-o', 'command='], { timeout: 3000 })\n // Values with spaces are unquoted in this output, so the marker is matched as a word.\n return new RegExp(`(?:^|\\\\s)${needle}(?:\\\\s|$)`).test(stdout)\n }\n catch {\n return false\n }\n }\n\n return false\n}\n","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 { processCarriesServerId } from '#src/providers/proc'\n\nconst execFileAsync = promisify(execFile)\n\n/** What the panel actually spawned for an entry: the argv it has to recognize again. */\nexport interface SpawnInfo {\n command: string\n args: string[]\n cwd: string\n}\n\n/**\n * Splits a command line into words, undoing the quoting Windows put there. `CommandLine`\n * is the raw string from the spawn call, so `\"C:\\a b\\x.cmd\" /c` is one argv entry plus\n * two words, and a quoted argument that contains spaces has to come back as one word.\n *\n * Windows also *escapes* a quote inside an argument as `\\\"` (Node does this for any argv\n * containing a quote), so the escape is undone here — otherwise every argument with a\n * quote in it survives as a stray backslash and never matches what the panel spawned.\n */\nexport function splitCommandLine(line: string): string[] {\n const words: string[] = []\n let current = ''\n let quoted = false\n let started = false\n\n const chars = [...line.trim()]\n for (let index = 0; index < chars.length; index += 1) {\n const char = chars[index]!\n\n // A backslash run escapes only the quote that follows it; any other backslash is a\n // literal path separator. Node emits `\\\"` for an argument's own quote, and treating\n // that quote as a delimiter closed the argument early — so the rest of the line\n // (including the *next* argument) was swallowed into the same word, and an entry\n // whose argv contains a quote was not recognized as its own successor.\n if (char === '\\\\') {\n let run = 0\n while (chars[index + run] === '\\\\') run += 1\n const next = chars[index + run]\n if (next !== '\"') {\n current += '\\\\'.repeat(run)\n started = true\n index += run - 1\n continue\n }\n // 2n backslashes then a quote: n literal backslashes, and the quote is a real\n // delimiter. 2n+1: n literal backslashes and a literal quote.\n current += '\\\\'.repeat(Math.floor(run / 2))\n started = true\n if (run % 2 === 1) {\n current += '\"'\n index += run\n continue\n }\n quoted = !quoted\n index += run\n continue\n }\n\n if (char === '\"') {\n quoted = !quoted\n // A quote is both a delimiter and proof that a (possibly empty) word exists.\n started = true\n continue\n }\n if (!quoted && /\\s/.test(char)) {\n if (started)\n words.push(current)\n current = ''\n started = false\n continue\n }\n current += char\n started = true\n }\n\n if (started)\n words.push(current)\n return words\n}\n\nfunction comparable(target: string): string {\n // Quotes around a whole word are stripped; whitespace never is. `SpawnInfo.args` is the\n // argv `spawn` was handed, where a whitespace argument is still an argument, so trimming\n // here would make it compare equal to a missing one. A `\\\"` is Windows' escape for a\n // quote inside an argument, and the word it sits in is compared against the raw argv.\n const value = target.replace(/^\"(.*)\"$/, '$1').replace(/\\\\(?=\")/g, '')\n return process.platform === 'win32' ? value.toLowerCase() : value\n}\n\n/**\n * Literal comparison for an argument: the same text, modulo the case folding Windows needs\n * and the quoting a command line shuffles around.\n *\n * Deliberately *not* `sameWord`: folding an argument to its basename would let this\n * entry's `/srv/web/build/server.js` equal a stranger's `/tmp/evil/build/server.js`, and a\n * match here is what `reclaim` kills. Nor is it a plain string equality: reading an argv\n * back out of a Windows `CommandLine` cannot preserve quotes exactly — the OS escapes an\n * argument's own quote as `\\\"` and strips the structural ones — so quotes and backslashes\n * are dropped from both sides. That leaves the arguments' actual text, which is what the\n * match is about.\n */\nfunction sameArg(a: string, b: string): boolean {\n const normalize = (value: string): string => comparable(value).replace(/[\"\\\\]/g, '')\n return normalize(a) === normalize(b)\n}\n\n/** Whether a value names a file with no directory part, under either platform's separator. */\nfunction isBare(value: string): boolean {\n return !value.includes('/') && !value.includes('\\\\')\n}\n\n/**\n * The same file spelled differently compares equal — but only while one of the two spellings is a\n * bare name, which is the case the fallback exists for: the config says `node` and the process table\n * reports `/usr/bin/node`, or the reverse on Windows.\n *\n * When **both** spellings name a directory, they are two different files. Comparing basenames\n * unconditionally made `/tmp/evil/server.js` match `/srv/web/server.js`, and a false match here is\n * not cosmetic: the panel would treat a process it never spawned as its own entry, so `follow` adopts\n * a stranger and `reclaim`/`kill` may remove one.\n */\nfunction sameWord(a: string, b: string): boolean {\n const left = comparable(a)\n const right = comparable(b)\n if (left === right)\n return true\n if (!isBare(left) && !isBare(right))\n return false\n return path.basename(left) === path.basename(right)\n || (path.extname(b) === '' && path.basename(left, path.extname(left)) === right)\n || (path.extname(a) === '' && path.basename(right, path.extname(right)) === left)\n}\n\n/**\n * True when the argv a process is running is the entry's own: the image must match where\n * `spawn` would have looked it up — the image Path, or the first word of the command line\n * — and the words after it must open with the entry's args, compared literally. So\n * `spawn --port 4000` also covers `spawn -p 4000 --extra`, which is what a self-restarting\n * wrapper does, while `/tmp/evil/server.js` never covers `/srv/web/server.js` — two paths that name\n * a directory are different files, and the basename fallback applies only while one spelling is bare\n * (see `sameWord`).\n *\n * `words` must already be the process's own argv. A command-line *string* is only correct\n * on Windows, where the OS hands one out; `/proc/<pid>/cmdline` quotes are literal bytes\n * of an argument, so re-joining that argv into one string corrupts it.\n */\nexport function matchesSpawn(info: { words: string[], imagePath?: string | null }, spawn: SpawnInfo): boolean {\n const { words } = info\n const first = words[0] ?? ''\n\n // The image may be the first word, or absent from the command line entirely — a shim or\n // an interpreter reports its own image while the argv still carries what we passed.\n const imageMatches = sameWord(first, spawn.command)\n || (info.imagePath != null && info.imagePath !== '' && sameWord(info.imagePath, spawn.command))\n if (!imageMatches)\n return false\n\n // `>` rather than `>=`: a process has to have *more* words than we have args, so an\n // argument can never be satisfied by a word that is not there.\n const offset = sameWord(first, spawn.command) ? 1 : 0\n if (words.length < spawn.args.length + offset)\n return false\n\n return spawn.args.every((arg, index) => sameArg(words[index + offset]!, arg))\n}\n\n/** The argv of a pid on the platforms whose process table can answer it; null otherwise. */\nexport async function processArgv(pid: number): Promise<string[] | null> {\n if (process.platform === 'win32')\n return null\n\n if (process.platform === 'linux') {\n try {\n const raw = await fs.promises.readFile(`/proc/${pid}/cmdline`)\n // Every word is NUL-terminated, so the file ends with an empty element to drop — and only\n // that one. An argument may itself be empty, which is two NULs, and filtering every empty\n // string pulled the words after it into its place: the entry's own successor stopped\n // matching its argv, and a stranger's did.\n const words = raw.toString('utf8').split('\\0')\n if (words.at(-1) === '')\n words.pop()\n return words.length > 0 ? words : null\n }\n catch {\n return null\n }\n }\n\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-ww', '-o', 'command='], { timeout: 3000 })\n // macOS receives one line and has to split it back into words here. `ps` joins argv\n // with spaces and quotes none of them, so an argument that itself contains a space\n // cannot be told from two arguments — that entry then fails to match and blocks,\n // which is the safe direction to be wrong in.\n const words = splitCommandLine(stdout.trim())\n return words.length > 0 ? words : null\n }\n catch {\n return null\n }\n}\n\nconst windowsFilter = /^\\d+$/\n\n/**\n * The first two rows of `ConvertTo-Csv` output: the header and the first record. PowerShell\n * quotes and doubles its way around CSV, so `a,\"b\"\"c\"` is three fields with the second\n * reading `b\"c`.\n */\nfunction parseCsvRows(output: string): [string[] | null, string[] | null] {\n const rows: string[][] = []\n let row: string[] = []\n let field = ''\n let quoted = false\n\n for (let index = 0; index < output.length; index++) {\n const char = output[index]!\n if (quoted) {\n if (char !== '\"') {\n field += char\n continue\n }\n if (output[index + 1] === '\"') {\n field += '\"'\n index++\n continue\n }\n quoted = false\n continue\n }\n\n if (char === '\"') {\n quoted = true\n continue\n }\n if (char === ',') {\n row.push(field)\n field = ''\n continue\n }\n if (char === '\\n') {\n row.push(field.replace(/\\r$/, ''))\n rows.push(row)\n row = []\n field = ''\n continue\n }\n field += char\n }\n\n if (field.length > 0 || row.length > 0)\n rows.push([...row, field.replace(/\\r$/, '')])\n\n return [rows[0] ?? null, rows[1] ?? null]\n}\n\n/**\n * `Win32_Process` for one pid, or null when it cannot be read.\n *\n * The whole round trip — launching PowerShell, loading the CIM provider, serializing —\n * costs seconds on a cold runner, so the timeout is generous and the result is converted\n * to CSV rather than JSON: CSV survives a value that contains a quote or a newline, which\n * an argv legitimately can.\n */\nexport async function windowsProcessInfo(pid: number): Promise<{ commandLine: string, imagePath: string | null } | null> {\n if (!windowsFilter.test(String(pid)))\n return null\n\n try {\n const script = `Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\" | Select-Object CommandLine,ExecutablePath | ConvertTo-Csv -NoTypeInformation`\n const { stdout } = await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 20000, windowsHide: true })\n const [headers, values] = parseCsvRows(stdout)\n if (!headers || !values)\n return null\n\n const commandLineIndex = headers.indexOf('CommandLine')\n const imageIndex = headers.indexOf('ExecutablePath')\n const commandLine = commandLineIndex >= 0 ? values[commandLineIndex] : undefined\n if (commandLine === undefined || commandLine.length === 0)\n return null\n\n const imagePath = imageIndex >= 0 ? values[imageIndex] : undefined\n return { commandLine, imagePath: imagePath && imagePath.length > 0 ? imagePath : null }\n }\n catch {\n return null\n }\n}\n\n/**\n * Which of these pids look like this entry's own detached successor. The environment\n * marker is authoritative where the platform can read it; otherwise the answer rests on\n * the entry's own argv, which is the only signal a detached successor is obliged to keep\n * — and the only one Windows exposes at all.\n */\nexport async function identifyHolders(serverId: string, spawn: SpawnInfo, pids: number[]): Promise<number[]> {\n const found: number[] = []\n\n for (const pid of pids) {\n if (await processCarriesServerId(pid, serverId)) {\n found.push(pid)\n continue\n }\n\n // An empty argv proves nothing, so a marker is the only way in without it.\n if (spawn.args.length === 0)\n continue\n\n if (process.platform === 'win32') {\n const info = await windowsProcessInfo(pid)\n if (info && matchesSpawn({ words: splitCommandLine(info.commandLine), imagePath: info.imagePath }, spawn))\n found.push(pid)\n continue\n }\n\n const argv = await processArgv(pid)\n if (argv !== null && matchesSpawn({ words: argv }, spawn))\n found.push(pid)\n }\n\n return found\n}\n","import type { ChildProcess } from 'node:child_process'\nimport { execFile, spawn } 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 { projectDir } from '#src/helpers/paths'\nimport { isProcessAlive } from '#src/providers/port'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface SpawnSpec {\n command: string\n args: string[]\n cwd: string\n env: Record<string, string>\n}\n\n/**\n * The files `npm`/`pnpm` write into `node_modules/.bin` on Windows, in the order Node can\n * actually start them.\n *\n * All of `foo`, `foo.cmd` and `foo.ps1` exist there — the extension-less one is a `#!/bin/sh`\n * script, which is the POSIX shim, not a program Windows can spawn. Preferring it (the order\n * `[command, ...shims]` gave) resolved to a file whose first line is `#!/bin/sh`: Node has no\n * shell to hand it to, so the entry started nothing. `spawn` reports that as `ENOENT` and the\n * panel used to blame the missing program.\n *\n * `.exe` leads because it needs no shell; `.cmd`/`.bat` follow and go through `needsShell()`.\n * `.ps1` is last: it is a PowerShell script, which `cmd.exe` does not run on its own.\n */\nconst WINDOWS_SHIM_EXTENSIONS = ['.exe', '.cmd', '.bat', '.ps1']\n\n/**\n * Resolves a bare command through the entry's own directory and the project's\n * `node_modules/.bin` first, so a server installed as a project dependency is\n * found even when the launcher's PATH has no pnpm-injected bin dir.\n */\nexport function resolveCommand(command: string, ...searchDirs: string[]): string {\n if (command.includes('/') || command.includes('\\\\'))\n return command\n\n const candidates = process.platform === 'win32' && path.extname(command) === ''\n ? WINDOWS_SHIM_EXTENSIONS.map(extension => `${command}${extension}`)\n : [command]\n\n for (const dir of searchDirs) {\n for (const candidate of candidates) {\n const local = path.join(dir, 'node_modules', '.bin', candidate)\n if (fs.existsSync(local))\n return local\n }\n }\n\n if (process.platform === 'win32' && path.extname(command) === '')\n return windowsShimOnPath(command) ?? command\n return command\n}\n\n/**\n * A bare name that `PATH` resolves to a `.cmd`/`.bat` (`pnpm`, `npm`, `yarn`) comes back with that\n * extension, so `needsShell` sees it: `spawn` without a shell only finds `.com`/`.exe` and answers\n * `ENOENT`. The name stays bare (`npm.cmd`), so `cmd.exe` searches for it and a `Program Files`\n * path is never split. `null` when the first match by `PATHEXT` order needs no shell, or none exists.\n */\nfunction windowsShimOnPath(command: string): string | null {\n const runnable = new Set(['.com', '.exe', '.bat', '.cmd'])\n const extensions = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')\n .split(';')\n .map(extension => extension.trim().toLowerCase())\n .filter(extension => runnable.has(extension))\n for (const dir of pathDirs()) {\n for (const extension of extensions) {\n if (isExecutable(path.join(dir, `${command}${extension}`)))\n return extension === '.bat' || extension === '.cmd' ? `${command}${extension}` : null\n }\n }\n return null\n}\n\nfunction pathDirs(): string[] {\n return (process.env.PATH ?? '').split(path.delimiter).filter(dir => dir.length > 0)\n}\n\n/**\n * Does this program exist where `spawn` would look it up, and where?\n *\n * Used only to tell a **pasted command line** apart from a missing program: `spawn` answers both\n * with the same `ENOENT`, and the two have opposite fixes. `null` means it was not found anywhere\n * this process would search.\n *\n * A bare name is searched on `PATH` (plus `.exe`/`.cmd`/`.bat` on Windows, because that is what\n * the OS appends); anything with a separator is a path and is stat'd as written.\n */\nexport function findProgram(command: string, cwd: string = projectDir): string | null {\n const isPath = command.includes('/') || command.includes('\\\\')\n if (isPath) {\n const resolved = path.resolve(cwd, command)\n return isExecutable(resolved) ? resolved : null\n }\n\n const extensions = process.platform === 'win32' ? ['', ...WINDOWS_SHIM_EXTENSIONS] : ['']\n for (const dir of pathDirs()) {\n for (const extension of extensions) {\n const candidate = path.join(dir, `${command}${extension}`)\n if (isExecutable(candidate))\n return candidate\n }\n }\n return null\n}\n\n/** A file this user may run. A directory named like a program is not one. */\nfunction isExecutable(file: string): boolean {\n try {\n if (!fs.statSync(file).isFile())\n return false\n if (process.platform === 'win32')\n return true\n fs.accessSync(file, fs.constants.X_OK)\n return true\n }\n catch {\n return false\n }\n}\n\n/** Relative entry paths belong to the project that launched the panel. */\nexport function resolveCwd(cwd: string, base: string = projectDir): string {\n return path.resolve(base, cwd)\n}\n\n/** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */\nexport function needsShell(command: string): boolean {\n return process.platform === 'win32' && /\\.(?:cmd|bat)$/i.test(command)\n}\n\nexport interface SpawnOptions {\n /**\n * A supervised child gets its own process group, so one `kill(-pid)` stops the tree.\n * A child spawned by a nanny does not: it shares the nanny's group, which is the\n * group the panel signals — so the same one-signal semantics still reach both.\n */\n detached?: boolean\n /**\n * Open descriptors for the child's output, instead of a pipe this process reads.\n *\n * A pipe makes this process its **read end**, so the child does not survive us: kill the panel,\n * the read end closes, and the child's next write to stdout fails with `EPIPE` — which ends a\n * process that was supposed to outlive the panel. A file the child opens takes this process out of\n * the chain: the descriptor belongs to the child, and the panel reads the bytes back afterwards.\n *\n * The caller owns these (it opens them with `openOutput` and closes its own copies after the\n * spawn); `spawn` duplicates them onto the child's table.\n */\n output?: { stdout: number, stderr: number }\n}\n\nexport function spawnManaged(spec: SpawnSpec, options: SpawnOptions = {}): ChildProcess {\n return spawn(spec.command, spec.args, {\n cwd: spec.cwd,\n env: { ...process.env, ...spec.env },\n // Own process group: a stop can signal the whole tree with one kill(-pid).\n detached: options.detached ?? true,\n // A descriptor the child inherits, or a pipe we hold the other end of — see `SpawnOptions`.\n stdio: options.output === undefined\n ? ['ignore', 'pipe', 'pipe']\n : ['ignore', options.output.stdout, options.output.stderr],\n shell: needsShell(spec.command),\n windowsHide: true,\n })\n}\n\nexport interface TerminateOptions {\n signal: NodeJS.Signals\n killGroup: boolean\n graceMs: number\n /** The SIGKILL escalation reaches the group even when the graceful signal went to the pid alone. */\n escalateGroup?: boolean\n}\n\n/** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */\nexport async function terminate(child: ChildProcess, options: TerminateOptions): Promise<'exited' | 'force-killed'> {\n if (child.exitCode !== null || child.signalCode !== null)\n return 'exited'\n\n const exited = waitForExit(child, options.graceMs)\n signalChild(child, options.signal, options.killGroup)\n\n if (await exited)\n return 'exited'\n\n signalChild(child, 'SIGKILL', options.escalateGroup ?? options.killGroup)\n await waitForExit(child, 2000)\n return 'force-killed'\n}\n\n/**\n * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and\n * `/F` is the only reliable way to stop a console process.\n */\nexport async function killTreeWindows(pid: number): Promise<void> {\n try {\n await execFileAsync('taskkill', ['/pid', String(pid), '/T', '/F'], { timeout: 5000 })\n }\n catch {\n // Already gone, or taskkill is unavailable.\n }\n}\n\n/** SIGKILL to a `spawnManaged` child and everything it started: its group, or its tree on Windows. */\nexport function forceKillTree(child: ChildProcess): void {\n if (child.exitCode === null && child.signalCode === null)\n signalChild(child, 'SIGKILL', true)\n}\n\nfunction signalChild(child: ChildProcess, signal: NodeJS.Signals, killGroup: boolean): void {\n const pid = child.pid\n if (pid === undefined)\n return\n signalPid(pid, signal, killGroup)\n}\n\nfunction signalPid(pid: number, signal: NodeJS.Signals, killGroup: boolean): void {\n if (process.platform === 'win32') {\n if (killGroup) {\n void killTreeWindows(pid)\n }\n else {\n try {\n process.kill(pid, signal)\n }\n catch {\n // already exited\n }\n }\n return\n }\n\n if (killGroup) {\n try {\n process.kill(-pid, signal)\n return\n }\n catch {\n // group already gone, fall through to the single pid\n }\n }\n\n try {\n process.kill(pid, signal)\n }\n catch {\n // already exited\n }\n}\n\n/**\n * The same shutdown a supervised child gets, for a process we adopted instead of\n * spawned: a detached successor is not our child, so it is signalled by pid (and\n * by process group when asked) and its exit is polled rather than awaited.\n *\n * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned\n * `false` for `EPERM`, so a process that was there but not ours to signal read as \"exited\" and\n * `'force-killed'` was returned for one still running. One predicate, one answer.\n */\nexport async function terminatePid(pid: number, options: TerminateOptions): Promise<'exited' | 'force-killed'> {\n if (!isProcessAlive(pid))\n return 'exited'\n\n signalPid(pid, options.signal, options.killGroup)\n\n const deadline = Date.now() + Math.max(0, options.graceMs)\n while (Date.now() < deadline && isProcessAlive(pid))\n await delay(50)\n if (!isProcessAlive(pid))\n return 'exited'\n\n signalPid(pid, 'SIGKILL', options.escalateGroup ?? options.killGroup)\n const hardDeadline = Date.now() + 2000\n while (Date.now() < hardDeadline && isProcessAlive(pid))\n await delay(50)\n return 'force-killed'\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n if (child.exitCode !== null || child.signalCode !== null)\n return Promise.resolve(true)\n if (timeoutMs <= 0)\n return Promise.resolve(false)\n\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n child.removeListener('exit', onExit)\n resolve(false)\n }, timeoutMs)\n\n function onExit(): void {\n clearTimeout(timer)\n resolve(true)\n }\n\n child.once('exit', onExit)\n })\n}\n","import type { ProcessBirth } from '#src/providers/port'\nimport type { TerminateOptions } from '#src/providers/process'\nimport type { NannyExit, NannySpec, NannyState, StopConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { NANNY_COMMAND } from '#src/helpers/runtime'\nimport { processArgv } from '#src/providers/identity'\nimport { processLiveness } from '#src/providers/port'\nimport { processCarriesServerId } from '#src/providers/proc'\nimport { findProgram } from '#src/providers/process'\nimport { nannySpecSchema, nannyStateSchema } from '#src/shared/contracts'\n\n/**\n * A persistent entry is not run by the panel: the panel spawns a *nanny* that owns\n * the child's pipes, writes its output to the entry's JSONL log and keeps a small\n * state file. That is what lets the entry survive a panel stop, restart or kill\n * without losing its log or its identity — the pipes belong to a process that stays.\n *\n * These are the files and the liveness rules behind that arrangement; the nanny\n * itself is `src/services/nanny.ts`.\n */\n\n/** The spec carries expanded `env`, so it lives only from spawn to read. */\nconst SPEC_MODE = 0o600\n\n/** Suffix of a spawn spec, so a sweep and the state reader can tell them apart. */\nexport const SPEC_SUFFIX = '.spec.json'\n\n/**\n * The signals a nanny traps and forwards to its child. Any other signal ends the nanny outright,\n * so nothing was forwarded — see `stopPersistentEntries`, which then signals the child directly.\n */\nexport const NANNY_TRAPPED_SIGNALS: ReadonlySet<NodeJS.Signals> = new Set(['SIGTERM', 'SIGINT'])\n\n/**\n * How a nanny is stopped. A trapped signal goes to the nanny's pid alone and the nanny signals its\n * own group once (`killGroup` is honoured there): signalling the group from here as well delivered\n * the stop to the child twice. The SIGKILL escalation still covers the whole group. Windows has no\n * signal a nanny can trap, so its stop is unchanged.\n */\nexport function nannyStopOptions(stop: StopConfig, platform: NodeJS.Platform = process.platform): TerminateOptions {\n if (platform === 'win32' || !stop.killGroup || !NANNY_TRAPPED_SIGNALS.has(stop.signal))\n return stop\n return { ...stop, killGroup: false, escalateGroup: true }\n}\n\n/** How often a nanny rewrites its state file. */\nexport const NANNY_HEARTBEAT_MS = 5000\n\n/** A heartbeat older than this is not evidence of anything. */\nexport const HEARTBEAT_STALE_MS = 30_000\n\n/**\n * The state directory is passed in rather than read from a global: the panel injects\n * `$HHOSTED_HOME/.state`, and a test injects its own temp directory.\n */\nexport function nannySpecPath(dir: string, id: string): string {\n return path.join(dir, `${id}${SPEC_SUFFIX}`)\n}\n\nexport function nannyStatePath(dir: string, id: string): string {\n return path.join(dir, `${id}.json`)\n}\n\n/** The file a nanny writes and the panel tails; one derivation, so they cannot drift. */\nexport function nannyLogFile(logDir: string, id: string): string {\n return path.join(logDir, `${id}.log`)\n}\n\n/**\n * How to run this CLI again as a nanny. The panel was itself launched through this\n * entry point (`up` re-spawns itself with it), so `process.argv[1]` is the one path\n * that works under tsx, from `dist/cli.js` and through the published bin alike.\n */\nexport function nannyEntryPoint(): string {\n return process.argv[1] ?? ''\n}\n\n/** Written before the spawn, consumed by the nanny, never left behind. */\nexport function writeNannySpec(file: string, spec: NannySpec): void {\n writeFileAtomic(file, JSON.stringify(spec), { mode: SPEC_MODE })\n}\n\nexport function clearNannySpec(file: string): void {\n fs.rmSync(file, { force: true })\n}\n\n/**\n * Reads and unlinks in one step: the spec holds expanded secrets, and a spec left\n * behind — a nanny that died before reading it, a panel killed mid-spawn — is a\n * secret file with no owner. It is consumed even when it cannot be parsed.\n */\nexport function takeNannySpec(file: string): NannySpec {\n const raw = fs.readFileSync(file, 'utf8')\n fs.rmSync(file, { force: true })\n\n const parsed = nannySpecSchema(JSON.parse(raw))\n if (parsed instanceof type.errors)\n throw new Error(`invalid nanny spec: ${parsed.summary}`)\n return parsed\n}\n\n/**\n * Nothing can be waiting on a spec before this panel has spawned a nanny, so every\n * one still on disk at boot belongs to a nanny that never read it.\n */\nexport function sweepNannySpecs(dir: string): number {\n let swept = 0\n for (const name of readSpecNames(dir)) {\n fs.rmSync(path.join(dir, name), { force: true })\n swept += 1\n }\n return swept\n}\n\nfunction readSpecNames(dir: string): string[] {\n try {\n return fs.readdirSync(dir).filter(name => name.endsWith(SPEC_SUFFIX))\n }\n catch {\n return []\n }\n}\n\n/** A stale or foreign file reads as \"no state\", never as a throw. */\nexport function readNannyState(file: string): NannyState | null {\n try {\n const parsed = nannyStateSchema(JSON.parse(fs.readFileSync(file, 'utf8')))\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n\nexport function writeNannyState(file: string, state: NannyState): void {\n writeFileAtomic(file, JSON.stringify(state))\n}\n\nexport function clearNannyState(file: string): void {\n fs.rmSync(file, { force: true })\n}\n\n/**\n * The same wording the supervisor uses for a child's exit, so history reads alike — plus a hint\n * when the code has a conventional meaning, because `code 137` alone tells an operator nothing and\n * that is the one they most want explained (a container limit or the kernel OOM killer).\n *\n * The hint is worded as a possibility, never a claim: 128+N is a shell convention, and a program\n * is free to exit 137 for its own reasons — a JVM reports OOM that way itself. 126 and 127 are\n * firmer, since the shell sets those when it cannot run the command at all.\n */\nexport function describeNannyExit(exit: NannyExit): string {\n if (exit.signal !== null)\n return `signal ${exit.signal}`\n const hint = exitCodeHint(exit.code)\n return hint === null ? `code ${exit.code}` : `code ${exit.code} (${hint})`\n}\n\n/** What a conventional exit code usually means, or null when there is nothing to add. */\nfunction exitCodeHint(code: number | null): string | null {\n if (code === null || code === 0)\n return null\n if (code === 126)\n return 'the command is not executable'\n if (code === 127)\n return 'the command was not found'\n if (code <= 128 || code > 128 + 64)\n return null\n const signal = signalName(code - 128)\n if (signal === null)\n return null\n return code === 137\n ? `${signal} — which the kernel sends when memory runs out`\n : `${signal}, if the shell reported the kill`\n}\n\n/**\n * A spawn failure in words a person can act on.\n *\n * Node reports a missing program as `spawn <cmd> ENOENT` — the same errno as a missing *file*, and\n * the same wording whichever of the two it is. A user who pasted `java -jar server.jar` into\n * `command` saw exactly that and had nothing to go on: the message names the whole line, so it\n * reads as \"the program is missing\" even when the program is fine and only the argument is wrong.\n *\n * `command` is the configured program, so the two cases can be told apart: if a bare name has no\n * path separator, the shell would have searched `PATH` and this one did not.\n *\n * A **missing working directory** is the third cause of the same errno, and it is the one a\n * deployment hits: `spawn` resolves `cwd` before it looks for the program, so an entry whose `cwd`\n * does not exist *under this launch directory* fails exactly like an uninstalled program. That read\n * sent a person to `which node` while `node` was fine and only the relative path was wrong (a unit\n * file with no `WorkingDirectory=`, a container started from `/`). `cwd` is therefore checked first:\n * if it is not an existing directory, nothing else about the spawn could have worked.\n */\nexport function describeSpawnError(error: NodeJS.ErrnoException, command: string, cwd?: string): string {\n const missingDir = cwd === undefined ? null : describeMissingDir(cwd)\n if (missingDir !== null && (error.code === 'ENOENT' || error.code === 'ENOTDIR'))\n return missingDir\n\n if (error.code === 'ENOENT') {\n const pasted = describePastedCommandLine(command, cwd)\n if (pasted !== null)\n return pasted\n return command.includes('/') || command.includes('\\\\')\n // A path was given, so the path is what is missing — the file, or a directory on the way.\n ? `\\`${command}\\` does not exist — check the path, and any directory on the way to it`\n // A bare name: spawn does not search a shell's PATH aliases, and the program may simply\n // not be installed. Naming the program is the whole value here.\n : `\\`${command}\\` was not found — is it installed, and is it on PATH for the user running the panel?`\n }\n if (error.code === 'EACCES')\n return `\\`${command}\\` exists but is not executable — ${notExecutableHint()}`\n return `${error.message} (while running \\`${command}\\`)`\n}\n\n/**\n * What to do about `EACCES`, in the shell of the platform the panel is running on.\n *\n * `chmod +x` is not a Windows program: `cmd.exe` answers `'chmod' is not recognized…`, so the one\n * line that exists to offer a way out sent the reader to a second dead end. The platform is the\n * only signal available, exactly as it is for `shellQuote` (`helpers/shell.ts`); one function so a\n * second `EACCES` message cannot be written with the POSIX half alone.\n */\nfunction notExecutableHint(): string {\n return process.platform === 'win32'\n // Windows has no executable bit: `EACCES` there means an ACL or a blocked file, not a mode.\n ? 'check its permissions (Windows has no executable bit — look at the file\\'s Security tab for a denied account)'\n : 'check its permissions (chmod +x)'\n}\n\n/**\n * The first mistake the Add-server form invites: a whole command line typed into `Command`.\n *\n * `Command` is spawned **without a shell** and `Arguments` is a separate field, so `node server.js`\n * names a program called `node server.js`. The fix is to split it — and the sentence has to say so,\n * because the alternative reading (\"node is not installed\") is what sends someone to `which node`\n * while `node` is right there.\n *\n * Only claimed when the evidence is unambiguous: the field has whitespace, and the program it opens\n * with **does** resolve. So a genuinely missing program keeps the message about PATH, and a path with\n * a space in it is never split (it has no bare first word that resolves). See `findProgram`.\n */\nfunction describePastedCommandLine(command: string, cwd?: string): string | null {\n const words = command.trim().split(/\\s+/)\n if (words.length < 2)\n return null\n const program = words[0]!\n if (findProgram(program, cwd) === null)\n return null\n return `\\`${command}\\` is a whole command line, but \\`Command\\` is spawned without a shell — this release looks for a program named \\`${command}\\`. Put \\`${program}\\` in \\`Command\\` and the rest in \\`Arguments\\`, one argument per line`\n}\n\n/** Why a working directory cannot be used, in one sentence, or null when it can. */\nfunction describeMissingDir(cwd: string): string | null {\n try {\n if (fs.statSync(cwd).isDirectory())\n return null\n return `the working directory \\`${cwd}\\` is not a directory — a relative \\`cwd\\` resolves against the directory the panel was started from`\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return `the working directory \\`${cwd}\\` does not exist — a relative \\`cwd\\` resolves against the directory the panel was started from, so a service started from elsewhere (systemd, docker, a login shell) looks in a different place`\n }\n return `the working directory \\`${cwd}\\` cannot be read — check its permissions`\n }\n}\n\n/** `SIGKILL` for 9, or null when the number names nothing. */\nfunction signalName(number: number): string | null {\n for (const [name, value] of Object.entries(os.constants.signals)) {\n if (value === number)\n return name\n }\n return null\n}\n\n/**\n * Is the nanny this state describes still ours? A live pid proves nothing on its\n * own — pids are reused, and the heartbeat is written *into the file*, not by the\n * process the file names, so a recycled pid with a recent write reads as running.\n * `startedAt` settles that first (`processLiveness`), exactly as `run.json` uses it:\n * the nanny stamps its record during its own boot, so its process is always born\n * before the stamp. The environment marker (Linux, macOS) or the argv we spawned it\n * with answers the rest, Windows included.\n */\nexport async function nannyIsAlive(state: NannyState, id: string, options: { readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {}): Promise<boolean> {\n if (state.nannyPid <= 0)\n return false\n // `'recycled'` is decisive and needs no threshold: a pid born after the record cannot be the\n // nanny that wrote it. `'gone'` is the plain dead pid. `'live'` and `'unknown'` both carry on —\n // a platform that cannot report a birth time must not have its running nanny dismissed.\n const liveness = await processLiveness(state.nannyPid, state.startedAt, options)\n if (liveness === 'gone' || liveness === 'recycled')\n return false\n if (Date.now() - state.heartbeatAt <= HEARTBEAT_STALE_MS)\n return true\n if (await processCarriesServerId(state.nannyPid, id))\n return true\n\n const words = await processArgv(state.nannyPid)\n return words !== null\n && words.includes(NANNY_COMMAND)\n && words.some(word => word.endsWith(`${id}.spec.json`))\n}\n\n/**\n * The nanny's child, when that pid is still the process it spawned — `null` otherwise. Used to stop a\n * child the nanny could not pass a stop on to, which happens *after* the nanny is gone, so a pid alone\n * could be anybody's by then. The nanny stamps `startedAt` just before it spawns the child, so the\n * child is born within the stamp's tolerance and a pid born later is a recycled one. Where the\n * platform reports no birth, the environment marker decides.\n */\nexport async function nannyChildPid(state: NannyState, options: { readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {}): Promise<number | null> {\n const pid = state.childPid\n if (pid === null || pid <= 0)\n return null\n const liveness = await processLiveness(pid, state.startedAt, options)\n if (liveness === 'live')\n return pid\n if (liveness === 'unknown' && await processCarriesServerId(pid, state.serverId))\n return pid\n return null\n}\n"],"mappings":";;;;;;;;;;;;;;AAMA,IAAMA,kBAAgB,UAAU,QAAQ;AAYxC,SAAgB,cAAc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/E,IAAI,aAAa,UAAU,aAAa,YACtC,OAAO;CACT,IAAI,KAAK,IAAI,IAAI,MAAM,eAAA,KACrB,OAAO;CACT,IAAI,MAAM,uBAAuB,MAAM,UAAU,EAAE,GACjD,OAAO;CAET,MAAM,QAAQ,MAAM,YAAY,MAAM,QAAQ;CAC9C,OAAO,UAAU,QACZ,MAAM,SAAA,SAAsB,KAC5B,MAAM,MAAK,SAAQ,KAAK,SAAS,GAAG,GAAG,WAAW,CAAC;AAC1D;;;;;;;;AASA,eAAsB,cAAc,OAAmB,UAAyE,CAAC,GAA2B;CAC1J,MAAM,MAAM,MAAM;CAClB,IAAI,QAAQ,QAAQ,OAAO,GACzB,OAAO;CACT,MAAM,WAAW,MAAM,gBAAgB,KAAK,MAAM,WAAW,OAAO;CACpE,IAAI,aAAa,QACf,OAAO;CACT,IAAI,aAAa,aAAa,MAAM,uBAAuB,KAAK,MAAM,QAAQ,GAC5E,OAAO;CACT,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nanny-sweep-DErnlPY1.js","names":[],"sources":["../../src/providers/nanny-sweep.ts"],"sourcesContent":["import type { NannyState, StopConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { NANNY_TRAPPED_SIGNALS, nannyChildPid, nannyIsAlive, nannySpecPath, nannyStatePath, nannyStopOptions, readNannyState, SPEC_SUFFIX } from '#src/providers/nanny'\nimport { isProcessAlive } from '#src/providers/port'\nimport { terminatePid } from '#src/providers/process'\nimport { stopSchema } from '#src/shared/contracts'\n\n/**\n * Finds and ends the persistent entries a host is running, with no panel in the loop.\n *\n * `down` leaves these alone on purpose, so `--with-persistent` is the one caller that has to\n * act on them — often after the panel is already gone. The nanny state files are the only\n * record that survives that, and they are per workspace, so every workspace is read.\n *\n * The **nanny** is what gets signalled: it traps the signal and forwards the entry's own\n * `stop` policy to the child it owns, which is what the panel's stop does. That is also why\n * this cannot go through `/_hh` — after a crash there is nothing left to ask.\n */\n\n/** One live persistent entry, as its state file describes it. */\nexport interface PersistentHandle {\n workspaceId: string\n serverId: string\n state: NannyState\n /** The workspace's `.state` directory, which owns the state file. */\n dir: string\n}\n\n/**\n * Every workspace's state directory.\n *\n * Read here rather than through `workspaceStateDir()`, which resolves from *this* process's\n * `HHOSTED_HOME`: a caller passing `--home` elsewhere would otherwise sweep another host's\n * state — the mistake `backup-offline` already paid for.\n */\nfunction stateDirs(hhDir: string): Array<{ workspaceId: string, dir: string }> {\n try {\n return fs.readdirSync(hhDir, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && !entry.name.startsWith('.'))\n .map(entry => entry.name)\n .filter(id => /^[a-z0-9][a-z0-9_-]*$/.test(id))\n .map(workspaceId => ({ workspaceId, dir: path.join(hhDir, workspaceId, '.state') }))\n }\n catch {\n return []\n }\n}\n\n/**\n * The persistent entries whose nanny is running right now.\n *\n * A `<id>.run.json` file is a *non-persistent* child's own record and carries no nanny, so it\n * is skipped by suffix — the same distinction `backup-offline` relies on. `nannyIsAlive` is\n * the identity check: a live pid alone proves nothing, since pids are reused.\n */\nexport async function livePersistentEntries(hhDir: string): Promise<PersistentHandle[]> {\n const found: PersistentHandle[] = []\n\n for (const { workspaceId, dir } of stateDirs(hhDir)) {\n let names: string[]\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n // No persistent entry was ever started in this workspace.\n continue\n }\n\n for (const name of names) {\n if (!name.endsWith('.json') || name.endsWith(SPEC_SUFFIX))\n continue\n // One file per entry, named for it: a file that disagrees with its own name is not\n // something to act on.\n const serverId = name.slice(0, -'.json'.length)\n const state = readNannyState(path.join(dir, name))\n if (state === null || state.serverId !== serverId)\n continue\n if (await nannyIsAlive(state, serverId))\n found.push({ workspaceId, serverId, state, dir })\n }\n }\n return found\n}\n\n/** What one stop did, so a survivor is reported rather than dressed up as success. */\nexport interface PersistentStop {\n handle: PersistentHandle\n stopped: boolean\n error: string | null\n}\n\n/**\n * Stops these entries and consumes the record of each one that ended.\n *\n * `stopFor` is the entry's own `stop` config, read by the caller from the workspace that\n * declares it: the grace period here has to be the one the entry asked for, or a stop that\n * was still finishing its shutdown reads as a failure and escalates to `SIGKILL`.\n */\nexport async function stopPersistentEntries(\n handles: PersistentHandle[],\n options: {\n stopFor?: (handle: PersistentHandle) => StopConfig\n /**\n * The one thing a test cannot supply: `SIGKILL` is not survivable, and a pid this process\n * may not signal (the real survivor) is a second user this host has no way to create. The\n * seam is the terminator, not the decision — everything below still runs.\n */\n terminate?: typeof terminatePid\n /** Whether the state's child pid is still the process the nanny spawned (`nannyChildPid`). */\n childPid?: typeof nannyChildPid\n } = {},\n): Promise<PersistentStop[]> {\n const results: PersistentStop[] = []\n const terminate = options.terminate ?? terminatePid\n // `.assert` returns the parsed value with the schema's defaults filled in; the plain call\n // type is `Value | errors`, which would make every field a type error to read.\n const defaultStop = stopSchema.assert({})\n\n for (const handle of handles) {\n const stop = options.stopFor?.(handle) ?? defaultStop\n const { state, dir, serverId } = handle\n const nanny = await terminate(state.nannyPid, nannyStopOptions(stop))\n\n // A nanny this process could not signal, or one that outlived `SIGKILL`, keeps its\n // record: it is the only way a later boot can find that process again.\n if (isProcessAlive(state.nannyPid)) {\n results.push({ handle, stopped: false, error: `pid ${state.nannyPid} survived the stop — its record is kept, so the next \\`up\\` can still find it` })\n continue\n }\n\n // A nanny stops its child on the graceful path. A signal it does not trap — `SIGKILL` above\n // all — ends it outright, so nothing was forwarded; and with `killGroup: false` the group\n // signal never reached the child either. The pid in the state file is then the only handle on\n // a server that would otherwise keep serving. The configured signal decides this, never the\n // terminator's own label: `SIGKILL` always reports `force-killed`, which says nothing about\n // whether the nanny had a chance to pass the stop on.\n const orphaned = state.childPid !== null && state.childPid > 0\n && !stop.killGroup\n && (!NANNY_TRAPPED_SIGNALS.has(stop.signal) || nanny === 'force-killed')\n // Only once it is known to be that child: the nanny is gone, so the pid may be recycled already.\n const child = orphaned ? await (options.childPid ?? nannyChildPid)(state) : null\n if (child !== null)\n await terminate(child, { signal: 'SIGKILL', killGroup: false, graceMs: 0 })\n\n consumeRecord(dir, serverId)\n results.push({ handle, stopped: true, error: null })\n }\n return results\n}\n\n/**\n * The record goes only once the process it names is gone: a state file kept past its process\n * is a false reattach waiting, which is what `resumePersistent` exists to prevent.\n */\nfunction consumeRecord(dir: string, serverId: string): void {\n for (const file of [nannyStatePath(dir, serverId), nannySpecPath(dir, serverId)]) {\n try {\n fs.rmSync(file, { force: true })\n }\n catch {\n // A file this process may not remove is the next boot's business, not a stop failure.\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAoCA,SAAS,UAAU,OAA4D;CAC7E,IAAI;EACF,OAAO,GAAG,YAAY,OAAO,EAAE,eAAe,KAAK,CAAC,CAAC,CAClD,QAAO,UAAS,MAAM,YAAY,KAAK,CAAC,MAAM,KAAK,WAAW,GAAG,CAAC,CAAC,CACnE,KAAI,UAAS,MAAM,IAAI,CAAC,CACxB,QAAO,OAAM,wBAAwB,KAAK,EAAE,CAAC,CAAC,CAC9C,KAAI,iBAAgB;GAAE;GAAa,KAAK,KAAK,KAAK,OAAO,aAAa,QAAQ;EAAE,EAAE;CACvF,QACM;EACJ,OAAO,CAAC;CACV;AACF;;;;;;;;AASA,eAAsB,sBAAsB,OAA4C;CACtF,MAAM,QAA4B,CAAC;CAEnC,KAAK,MAAM,EAAE,aAAa,SAAS,UAAU,KAAK,GAAG;EACnD,IAAI;EACJ,IAAI;GACF,QAAQ,GAAG,YAAY,GAAG;EAC5B,QACM;GAEJ;EACF;EAEA,KAAK,MAAM,QAAQ,OAAO;GACxB,IAAI,CAAC,KAAK,SAAS,OAAO,KAAK,KAAK,SAAA,YAAoB,GACtD;GAGF,MAAM,WAAW,KAAK,MAAM,GAAG,EAAe;GAC9C,MAAM,QAAQ,eAAe,KAAK,KAAK,KAAK,IAAI,CAAC;GACjD,IAAI,UAAU,QAAQ,MAAM,aAAa,UACvC;GACF,IAAI,MAAM,aAAa,OAAO,QAAQ,GACpC,MAAM,KAAK;IAAE;IAAa;IAAU;IAAO;GAAI,CAAC;EACpD;CACF;CACA,OAAO;AACT;;;;;;;;AAgBA,eAAsB,sBACpB,SACA,UAUI,CAAC,GACsB;CAC3B,MAAM,UAA4B,CAAC;CACnC,MAAM,YAAY,QAAQ,aAAa;CAGvC,MAAM,cAAc,WAAW,OAAO,CAAC,CAAC;CAExC,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,OAAO,QAAQ,UAAU,MAAM,KAAK;EAC1C,MAAM,EAAE,OAAO,KAAK,aAAa;EACjC,MAAM,QAAQ,MAAM,UAAU,MAAM,UAAU,iBAAiB,IAAI,CAAC;EAIpE,IAAI,eAAe,MAAM,QAAQ,GAAG;GAClC,QAAQ,KAAK;IAAE;IAAQ,SAAS;IAAO,OAAO,OAAO,MAAM,SAAS;GAA+E,CAAC;GACpJ;EACF;EAYA,MAAM,QAJW,MAAM,aAAa,QAAQ,MAAM,WAAW,KACxD,CAAC,KAAK,cACL,CAAC,sBAAsB,IAAI,KAAK,MAAM,KAAK,UAAU,kBAElC,OAAO,QAAQ,YAAY,cAAA,CAAe,KAAK,IAAI;EAC5E,IAAI,UAAU,MACZ,MAAM,UAAU,OAAO;GAAE,QAAQ;GAAW,WAAW;GAAO,SAAS;EAAE,CAAC;EAE5E,cAAc,KAAK,QAAQ;EAC3B,QAAQ,KAAK;GAAE;GAAQ,SAAS;GAAM,OAAO;EAAK,CAAC;CACrD;CACA,OAAO;AACT;;;;;AAMA,SAAS,cAAc,KAAa,UAAwB;CAC1D,KAAK,MAAM,QAAQ,CAAC,eAAe,KAAK,QAAQ,GAAG,cAAc,KAAK,QAAQ,CAAC,GAC7E,IAAI;EACF,GAAG,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;CACjC,QACM,CAEN;AAEJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nearest-6KgQEDUe.js","names":[],"sources":["../../src/cli/nearest.ts"],"sourcesContent":["/** No suggestion further than this, however long the word — see the bound in `nearestWord`. */\nconst ABSOLUTE_BOUND = 2\n\n/**\n * The nearest word to a typo, or null when nothing is close.\n *\n * Two callers need it — a mistyped command and a mistyped option — so it takes its candidate list as\n * a parameter rather than reaching for one. One implementation, so both suggest by the same rule.\n *\n * Levenshtein distance, capped: only a genuinely near miss is worth naming, because suggesting an\n * unrelated word is worse than suggesting none.\n */\nexport function nearestWord(input: string, candidates: readonly string[]): string | null {\n if (candidates.length === 0)\n return null\n\n const distance = (a: string, b: string): number => {\n // Iterative single-row DP, so a long word costs no matrix.\n let previous = Array.from({ length: b.length + 1 }, (_, i) => i)\n for (let i = 1; i <= a.length; i += 1) {\n const current = [i]\n for (let j = 1; j <= b.length; j += 1) {\n const substitution = previous[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1)\n current[j] = Math.min(current[j - 1]! + 1, previous[j]! + 1, substitution)\n }\n previous = current\n }\n return previous[b.length]!\n }\n\n const best = candidates\n .map(name => ({ name, d: distance(input.toLowerCase(), name.toLowerCase()) }))\n .sort((left, right) => left.d - right.d || left.name.localeCompare(right.name))[0]\n\n if (best === undefined)\n return null\n // Two bounds, because one is not enough for option names.\n //\n // The proportional bound alone (\"half the shorter word\") is what a long command needs:\n // `stats`→`status` is 1 apart and should be suggested. But short option names share prefixes —\n // `no-open` and `no-yes` are three apart while their meaningful halves are unrelated, so half of\n // six let it through and the hint named the wrong flag (`--no-open` where `--no-autostart` was\n // meant). Requiring the distance to also be small in absolute terms rejects a match carried by a\n // shared `no-` or a one-letter alias.\n const proportional = Math.floor(Math.min(input.length, best.name.length) / 2)\n const allowed = Math.min(proportional, ABSOLUTE_BOUND)\n return best.d <= allowed ? best.name : null\n}\n"],"mappings":";;;;AACA,IAAM,iBAAiB;;;;;;;;;;AAWvB,SAAgB,YAAY,OAAe,YAA8C;CACvF,IAAI,WAAW,WAAW,GACxB,OAAO;CAET,MAAM,YAAY,GAAW,MAAsB;EAEjD,IAAI,WAAW,MAAM,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,GAAG,MAAM,CAAC;EAC/D,KAAK,IAAI,IAAI,GAAG,KAAK,EAAE,QAAQ,KAAK,GAAG;GACrC,MAAM,UAAU,CAAC,CAAC;GAClB,KAAK,IAAI,IAAI,GAAG,KAAK,EAAE,QAAQ,KAAK,GAAG;IACrC,MAAM,eAAe,SAAS,IAAI,MAAO,EAAE,IAAI,OAAO,EAAE,IAAI,KAAK,IAAI;IACrE,QAAQ,KAAK,KAAK,IAAI,QAAQ,IAAI,KAAM,GAAG,SAAS,KAAM,GAAG,YAAY;GAC3E;GACA,WAAW;EACb;EACA,OAAO,SAAS,EAAE;CACpB;CAEA,MAAM,OAAO,WACV,KAAI,UAAS;EAAE;EAAM,GAAG,SAAS,MAAM,YAAY,GAAG,KAAK,YAAY,CAAC;CAAE,EAAE,CAAC,CAC7E,MAAM,MAAM,UAAU,KAAK,IAAI,MAAM,KAAK,KAAK,KAAK,cAAc,MAAM,IAAI,CAAC,CAAC,CAAC;CAElF,IAAI,SAAS,KAAA,GACX,OAAO;CAST,MAAM,eAAe,KAAK,MAAM,KAAK,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,IAAI,CAAC;CAC5E,MAAM,UAAU,KAAK,IAAI,cAAc,cAAc;CACrD,OAAO,KAAK,KAAK,UAAU,KAAK,OAAO;AACzC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"parse-DhmG26fI.js","names":["problems"],"sources":["../../src/config/migrations.ts","../../src/config/parse.ts"],"sourcesContent":["/**\n * The config shape this release understands. It is shared by every file that\n * carries a `meta` stamp (the global settings, each workspace's settings and its\n * servers config), because a migration has to be able to lift any of them.\n *\n * Bump it only for a change that an older release cannot simply ignore, and add\n * the step that lifts the previous shape to it in `configMigrations` — then a\n * config that needs it refuses to start until `home-hosted migrate` has run.\n *\n * 1 — the shape that has been in use up to and including 0.6.x, plus the `meta`\n * block this constant was introduced with. Unstamped files are schema 1.\n * 2 — notifications: one Telegram singleton plus a webhook list became one `destinations`\n * list of typed entries, and the shared policy moved to `notifications.defaults`.\n */\nimport { LEGACY_TELEGRAM_ID } from '#src/config/secrets'\n\nexport const CONFIG_SCHEMA = 2\n\n/**\n * The schema of a file that carries no `meta` stamp at all.\n *\n * A literal, **not** `CONFIG_SCHEMA`: an unstamped file predates the stamp, so it is the *oldest* shape,\n * and reading it as the current one would skip every migration the moment `CONFIG_SCHEMA` is bumped —\n * the file would then be stamped as the new schema without ever being lifted to it.\n *\n * **Schema 1 is the oldest stamped shape**, but an unstamped file is not necessarily that one: the\n * seeds this release writes carry no `meta` at all, and they are written in the *current* shape. So\n * an unstamped file cannot be told apart from a pre-stamp one, and both are read as the shape that\n * predates the stamp — schema 1. That is what makes the distinction safe in the direction that\n * matters: a released file is lifted, and a seed is written in a shape schema 1 can describe,\n * because every field added since is optional with a default.\n *\n * (This was `1` with the note \"a hypothetical `to: 2` step\" — and then 2 arrived, which is how the\n * seeds started refusing to load. They now carry a stamp of their own; see `config/seed.ts`.)\n */\nexport const UNSTAMPED_SCHEMA = 1\n\n/** A settings or servers file, as read: whatever keys it carries. */\nexport type RawConfig = Record<string, unknown>\n\nexport interface ConfigMigration {\n /** The schema this step produces; steps run in ascending order. */\n to: number\n /** One line, printed by `migrate` before anything is written. */\n describe: string\n apply: (config: RawConfig) => RawConfig\n}\n\n/**\n * The id the pre-list Telegram destination takes.\n *\n * **The one definition**, imported from the secrets reader, because that is where the bot token for\n * it already sits: the two have to agree on the id or the upgrade loses a working Telegram. They\n * were two literals with a comment claiming they were shared, and drifting one was undetected.\n */\n\n/**\n * Schema 1 → 2: `notifications.{telegram, webhooks}` → `notifications.{defaults, destinations}`.\n *\n * The old singleton becomes one `telegram` destination, and each webhook keeps its id, so a\n * destination's cooldown, last-result record and Telegram token all still point at the same thing.\n * `useOwnSettings` is set **true** on every migrated destination: before this schema each one\n * carried its own toggles, and reading one as \"inherit\" would silently change what it delivers.\n * The old webhook `enabled` default (true) and the Telegram one (false) are preserved as they were.\n */\nfunction notificationsToDestinations(config: RawConfig): RawConfig {\n const notifications = config.notifications\n if (notifications === null || typeof notifications !== 'object' || Array.isArray(notifications))\n return config\n\n const group = notifications as Record<string, unknown>\n // Already migrated, or a shape this step does not know: leave it to the reader.\n if (group.destinations !== undefined || (group.telegram === undefined && group.webhooks === undefined))\n return config\n\n const destinations: Array<Record<string, unknown>> = []\n const telegram = group.telegram\n if (telegram !== null && typeof telegram === 'object') {\n const { enabled, chatId, ...policy } = telegram as Record<string, unknown>\n destinations.push({ kind: 'telegram', id: LEGACY_TELEGRAM_ID, enabled: enabled ?? false, chatId: chatId ?? '', useOwnSettings: true, ...policy })\n }\n if (Array.isArray(group.webhooks)) {\n for (const entry of group.webhooks) {\n if (entry === null || typeof entry !== 'object')\n continue\n destinations.push({ kind: 'webhook', useOwnSettings: true, ...(entry as Record<string, unknown>) })\n }\n }\n\n const next: Record<string, unknown> = { ...group, destinations }\n delete next.telegram\n delete next.webhooks\n return { ...config, notifications: next }\n}\n\n/**\n * Every published migration, oldest first. Keep this list small and permanent:\n * a config may arrive from any earlier release, so a step is never removed.\n */\nexport const configMigrations: ConfigMigration[] = [\n {\n to: 2,\n describe: 'notifications: fold the Telegram singleton and the webhook list into one `destinations` list, with a shared `defaults` block',\n apply: notificationsToDestinations,\n },\n]\n\nexport interface MigrationPlan {\n from: number\n to: number\n steps: ConfigMigration[]\n /** The file was written by a release newer than this one. */\n tooNew: boolean\n /**\n * The schema the steps actually reach, which is `to` only when the chain is unbroken.\n *\n * A **gap** in `configMigrations` — a step lifting 1→2 published without one lifting 2→3 — leaves the\n * file part-way while `migrate` stamps it as the current schema anyway: it writes\n * `schema: CONFIG_SCHEMA` unconditionally. The file then claims a shape it does not have, which is the\n * same silent corruption the unstamped default caused. This makes the gap detectable.\n */\n reached: number\n}\n\nexport interface MigrationOptions {\n /** Defaults to every migration this release ships. */\n migrations?: ConfigMigration[]\n /** The schema to reach; defaults to what this release understands. */\n to?: number\n}\n\n/** What would have to run to bring `from` up to `to`. */\nexport function planConfigMigrations(from: number, options: MigrationOptions = {}): MigrationPlan {\n const to = options.to ?? CONFIG_SCHEMA\n const migrations = options.migrations ?? configMigrations\n const steps = migrations\n .filter(migration => migration.to > from && migration.to <= to)\n .sort((a, b) => a.to - b.to)\n return { from, to, steps, tooNew: from > to, reached: steps.at(-1)?.to ?? from }\n}\n\n/**\n * Applies the plan in order; the caller owns writing the result.\n *\n * The result carries `meta.schema` set to the schema the steps reached, so it is readable by this\n * release's own parser — which refuses a file whose stamp still says an older schema. Without that,\n * `migrate` validated its own output as \"needs 1 migration\" and refused every config it exists to\n * lift.\n */\nexport function applyConfigMigrations(config: RawConfig, from: number, options: MigrationOptions = {}): { config: RawConfig, applied: ConfigMigration[] } {\n const plan = planConfigMigrations(from, options)\n let current = config\n for (const step of plan.steps)\n current = step.apply(current)\n if (plan.steps.length === 0)\n return { config: current, applied: plan.steps }\n\n const meta = current.meta !== null && typeof current.meta === 'object' && !Array.isArray(current.meta)\n ? current.meta as Record<string, unknown>\n : {}\n return { config: { ...current, meta: { ...meta, schema: plan.reached } }, applied: plan.steps }\n}\n","import type { MigrationOptions } from '#src/config/migrations'\nimport type { ResolvedGlobalConfig, ResolvedWorkspaceSettings } from '#src/config/schema'\nimport type { ServerConfig } from '#src/shared/contracts'\nimport { type } from 'arktype'\nimport { CONFIG_SCHEMA, planConfigMigrations, UNSTAMPED_SCHEMA } from '#src/config/migrations'\nimport {\n backupsSchema,\n controlSchema,\n ddnsConfigSchema,\n defaultsSchema,\n GLOBAL_SETTINGS_KEYS,\n hostSchema,\n logsSchema,\n mergeDefaults,\n notificationsSchema,\n proxyConfigSchema,\n SERVERS_FILE_KEYS,\n serverSchema,\n WORKSPACE_SETTINGS_KEYS,\n} from '#src/config/schema'\nimport { appVersion } from '#src/helpers/version'\nimport { isRecord } from '#src/shared/shape'\n\nexport interface ConfigParse<T> {\n /** Null when something made the file unusable; `errors` says why. */\n config: T | null\n /** Blocking problems: what the panel must not start on. */\n errors: string[]\n /** Keys a newer release wrote that this one does not know, by path. */\n unknownKeys: string[]\n /** Real but non-blocking problems: supervision still runs, the file is still used. */\n warnings: string[]\n /** The shape the file declares; an unstamped file reads as the current one. */\n schemaVersion: number\n /** What wrote it, when the file says. */\n writtenBy: string | null\n}\n\ntype Validator = (input: unknown) => unknown\n\n/** ArkType reports an unrecognized key with this problem, carrying its path. */\nconst UNDECLARED = 'must be removed'\n\nfunction deleteAtPath(root: Record<string, unknown>, path: readonly (string | number)[]): void {\n let node: unknown = root\n for (const key of path.slice(0, -1)) {\n node = Array.isArray(node) ? node[Number(key)] : isRecord(node) ? node[key] : undefined\n if (node === undefined)\n return\n }\n const last = path[path.length - 1]\n if (last === undefined)\n return\n if (isRecord(node))\n delete node[String(last)]\n else if (Array.isArray(node) && typeof last === 'number')\n node.splice(last, 1)\n}\n\n/**\n * Validates one object against one schema, tolerating keys the schema does not\n * know: a config written by a newer release has to keep working here, and losing\n * the *whole group* to schema defaults would silently reset the listener port,\n * the bind and the auth policy over a single unrecognized key.\n *\n * Only unrecognized keys are dropped, and each one is reported. Anything else is\n * a real problem, returned for the caller to refuse on.\n */\nexport function parseTolerant(\n value: unknown,\n schema: Validator,\n prefix: string,\n unknownKeys: string[],\n): { value: unknown, error: string | null } {\n const candidate = structuredClone(value)\n\n for (let pass = 0; pass < 25; pass++) {\n const parsed = schema(candidate)\n if (!(parsed instanceof type.errors))\n return { value: parsed, error: null }\n\n const problems = parsed as unknown as Array<{ path: (string | number)[], problem: string }>\n const removable = problems.filter(problem => problem.problem === UNDECLARED)\n if (removable.length === 0)\n return { value: null, error: parsed.summary }\n\n if (!isRecord(candidate))\n return { value: null, error: parsed.summary }\n\n for (const problem of removable) {\n const at = `${prefix}.${problem.path.join('.')}`\n if (!unknownKeys.includes(at))\n unknownKeys.push(at)\n deleteAtPath(candidate, problem.path)\n }\n }\n\n return { value: null, error: 'too many unrecognized keys to ignore' }\n}\n\ninterface GroupedParse<T> {\n keys: readonly string[]\n groups: ReadonlyArray<readonly [string, Validator]>\n build: (meta: { writtenBy: string, schema: number }, groups: Record<string, unknown>) => T\n}\n\n/** A file's `meta` stamp, and the one gate both readers must answer identically. */\ninterface Stamp {\n schemaVersion: number\n writtenBy: string | null\n /** A blocking problem: the file names a shape, or a migration, this release cannot reach. */\n error: string | null\n}\n\n/**\n * Reads `meta`, then refuses a file this release cannot use.\n *\n * Both readers need this and the two messages have to stay in step: a file written by a\n * newer release, and one whose migration has not been applied, are different problems with\n * different fixes (`install that release` vs. `run migrate`). Written once here, so a change\n * to either wording cannot land on one path only.\n */\nfunction readStamp(raw: Record<string, unknown>, options: MigrationOptions): Stamp {\n const meta = isRecord(raw.meta) ? raw.meta : null\n const schemaVersion = typeof meta?.schema === 'number' ? meta.schema : UNSTAMPED_SCHEMA\n const writtenBy = typeof meta?.writtenBy === 'string' && meta.writtenBy.length > 0 ? meta.writtenBy : null\n\n if (schemaVersion > CONFIG_SCHEMA)\n return { schemaVersion, writtenBy, error: `written by home-hosted ${writtenBy ?? 'a newer release'} (config schema ${schemaVersion}); this release understands schema ${CONFIG_SCHEMA}` }\n\n const { steps } = planConfigMigrations(schemaVersion, options)\n if (steps.length > 0)\n return { schemaVersion, writtenBy, error: `config schema ${schemaVersion} needs ${steps.length} migration${steps.length === 1 ? '' : 's'} before this release can use it` }\n\n return { schemaVersion, writtenBy, error: null }\n}\n\n/**\n * Reads one settings file from any release: schema guard, unrecognized keys\n * reported and left on disk, blocking problems returned for the caller to refuse on.\n */\nfunction parseGrouped<T>(raw: unknown, label: string, definition: GroupedParse<T>, options: MigrationOptions): ConfigParse<T> {\n const unknownKeys: string[] = []\n const errors: string[] = []\n const warnings: string[] = []\n const result: ConfigParse<T> = { config: null, errors, unknownKeys, warnings, schemaVersion: UNSTAMPED_SCHEMA, writtenBy: null }\n\n if (!isRecord(raw)) {\n errors.push(`the ${label} must contain a JSON object`)\n return result\n }\n\n const stamp = readStamp(raw, options)\n result.schemaVersion = stamp.schemaVersion\n result.writtenBy = stamp.writtenBy\n if (stamp.error !== null) {\n errors.push(stamp.error)\n return result\n }\n\n for (const key of Object.keys(raw)) {\n if (!definition.keys.includes(key))\n unknownKeys.push(key)\n }\n\n const groups: Record<string, unknown> = {}\n for (const [name, schema] of definition.groups) {\n const parsed = parseTolerant(raw[name] ?? {}, schema, name, unknownKeys)\n if (parsed.error !== null)\n errors.push(`${name}: ${parsed.error}`)\n groups[name] = parsed.value ?? schema({})\n }\n\n if (errors.length > 0)\n return result\n\n result.config = definition.build({ writtenBy: stamp.writtenBy ?? '', schema: stamp.schemaVersion }, groups)\n return result\n}\n\n/** `$HHOSTED_HOME/.hh/settings.json`. */\nexport function parseGlobalSettings(raw: unknown, options: MigrationOptions = {}): ConfigParse<ResolvedGlobalConfig> {\n return parseGrouped(raw, 'settings file', {\n keys: GLOBAL_SETTINGS_KEYS,\n groups: [\n ['control', controlSchema as unknown as Validator],\n ['host', hostSchema as unknown as Validator],\n ['backups', backupsSchema as unknown as Validator],\n ['proxy', proxyConfigSchema as unknown as Validator],\n ],\n build: (meta, groups) => ({\n meta,\n control: groups.control as ResolvedGlobalConfig['control'],\n host: groups.host as ResolvedGlobalConfig['host'],\n backups: groups.backups as ResolvedGlobalConfig['backups'],\n proxy: groups.proxy as ResolvedGlobalConfig['proxy'],\n }),\n }, options)\n}\n\n/** `$HHOSTED_HOME/.hh/<id>/settings.json`. */\nexport function parseWorkspaceSettings(raw: unknown, options: MigrationOptions = {}): ConfigParse<ResolvedWorkspaceSettings> {\n return parseGrouped(raw, 'workspace settings file', {\n keys: WORKSPACE_SETTINGS_KEYS,\n groups: [\n ['defaults', defaultsSchema as unknown as Validator],\n ['logs', logsSchema as unknown as Validator],\n ['notifications', notificationsSchema as unknown as Validator],\n ['ddns', ddnsConfigSchema as unknown as Validator],\n ],\n build: (meta, groups) => ({\n meta,\n defaults: groups.defaults as ResolvedWorkspaceSettings['defaults'],\n logs: groups.logs as ResolvedWorkspaceSettings['logs'],\n notifications: groups.notifications as ResolvedWorkspaceSettings['notifications'],\n ddns: groups.ddns as ResolvedWorkspaceSettings['ddns'],\n }),\n }, options)\n}\n\nexport interface ServersParse {\n servers: ServerConfig[]\n errors: string[]\n unknownKeys: string[]\n warnings: string[]\n schemaVersion: number\n writtenBy: string | null\n}\n\n/**\n * `$HHOSTED_HOME/.hh/<id>/servers.config.json`: just the entries, each resolved\n * against the workspace's defaults.\n */\nexport function parseServersFile(raw: unknown, defaults: Record<string, unknown>, options: MigrationOptions = {}): ServersParse {\n const unknownKeys: string[] = []\n const errors: string[] = []\n const warnings: string[] = []\n const result: ServersParse = { servers: [], errors, unknownKeys, warnings, schemaVersion: UNSTAMPED_SCHEMA, writtenBy: null }\n\n if (!isRecord(raw)) {\n errors.push('the servers config must contain a JSON object')\n return result\n }\n\n const stamp = readStamp(raw, options)\n result.schemaVersion = stamp.schemaVersion\n result.writtenBy = stamp.writtenBy\n if (stamp.error !== null) {\n errors.push(stamp.error)\n return result\n }\n\n for (const key of Object.keys(raw)) {\n if (!(SERVERS_FILE_KEYS as readonly string[]).includes(key))\n unknownKeys.push(key)\n }\n\n const seen = new Set<string>()\n const rawServers = Array.isArray(raw.servers) ? raw.servers : []\n\n rawServers.forEach((entry, index) => {\n const label = `servers[${index}]`\n const merged = isRecord(entry) ? mergeDefaults(defaults, entry) : entry\n const parsed = parseTolerant(merged, serverSchema as unknown as Validator, label, unknownKeys)\n if (parsed.error !== null) {\n const id = isRecord(entry) ? entry.id : undefined\n errors.push(`${label}${typeof id === 'string' ? ` (\"${id}\")` : ''}: ${parsed.error}`)\n return\n }\n const server = parsed.value as ServerConfig\n if (seen.has(server.id)) {\n errors.push(`${label}: duplicate id \"${server.id}\"`)\n return\n }\n seen.add(server.id)\n // `null` and absent both mean \"no label\", so they are normalised to one spelling here — the same\n // treatment `port` gets, and what lets a hand-edited `\"label\": null` load instead of refusing the\n // whole config.\n const { label: entryLabel, ...rest } = server\n result.servers.push({ ...rest, port: server.port ?? null, ...(entryLabel === null || entryLabel === undefined ? {} : { label: entryLabel }) })\n })\n\n // Cross-field problems are reported, never fatal: supervision still runs.\n warnings.push(...validateCrossField(result.servers))\n\n return result\n}\n\n/**\n * Config that validates field-by-field but is wrong as a whole.\n *\n * Warned rather than refused, because supervision still runs and a hard failure would take a working\n * panel down over a setting one field away from correct.\n */\nfunction validateCrossField(servers: ServerConfig[]): string[] {\n const ids = new Set(servers.map(server => server.id))\n const errors: string[] = []\n\n for (const server of servers) {\n const { health } = server\n // A `HEAD` response carries no body, so the probe skips the assertion — and a health check that\n // silently stops checking is worse than one that fails, because nothing says it did. Measured with\n // the real probe: `method: HEAD` plus a body requirement reported a server healthy whose body did\n // not match. Left as a warning: the entry still runs, and the person is told what to change.\n if (health.mode === 'http' && health.http.method === 'HEAD' && health.http.expectBody.length > 0)\n errors.push(`\"${server.id}\" requires a response body with method HEAD, which has none — the body check is ignored`)\n\n // `allowInvalidCert` only means anything over TLS; set on a plain-http check it reads as a\n // setting that is silently in force. Said out loud so it is not mistaken for one.\n if (health.mode === 'http' && health.http.scheme === 'http' && health.http.allowInvalidCert)\n errors.push(`\"${server.id}\" sets allowInvalidCert on an http probe, where there is no certificate to check`)\n\n for (const dependency of server.dependsOn) {\n if (dependency === server.id)\n errors.push(`\"${server.id}\" depends on itself`)\n else if (!ids.has(dependency))\n errors.push(`\"${server.id}\" depends on unknown server \"${dependency}\"`)\n }\n }\n\n const visiting = new Set<string>()\n const settled = new Set<string>()\n const byId = new Map(servers.map(server => [server.id, server]))\n const walk = (id: string): void => {\n if (settled.has(id))\n return\n if (visiting.has(id)) {\n errors.push(`dependency cycle through \"${id}\"`)\n return\n }\n visiting.add(id)\n for (const dependency of byId.get(id)?.dependsOn ?? []) walk(dependency)\n visiting.delete(id)\n settled.add(id)\n }\n for (const server of servers) walk(server.id)\n\n // Two entries on one port: one starts and the other goes `conflict`, and the operator finds out\n // from a card. A cycle and an unknown dependency id are already warned about here, so this is the\n // same mechanism rather than a new one — and it is a warning, not an error, because the entries\n // may be mutually exclusive by design (`onPortConflict` decides who wins).\n const byPort = new Map<number, string[]>()\n for (const server of servers) {\n // A disabled entry never binds, so it cannot clash with anything.\n if (server.port === null || !server.enabled)\n continue\n byPort.set(server.port, [...(byPort.get(server.port) ?? []), server.id])\n }\n for (const [port, ids] of byPort) {\n if (ids.length > 1)\n errors.push(`port ${port} is declared by ${ids.map(id => `\"${id}\"`).join(', ')} — only one can bind it`)\n }\n\n return [...new Set(errors)]\n}\n\n/** Adds the stamp every write carries, so the next release can tell what wrote the file. */\nexport function stampConfig<T extends { $schema?: string, meta?: unknown }>(draft: T): T {\n const { $schema, meta: _meta, ...rest } = draft\n return {\n ...($schema === undefined ? {} : { $schema }),\n meta: { writtenBy: appVersion(), schema: CONFIG_SCHEMA },\n ...rest,\n } as T\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAS,4BAA4B,QAA8B;CACjE,MAAM,gBAAgB,OAAO;CAC7B,IAAI,kBAAkB,QAAQ,OAAO,kBAAkB,YAAY,MAAM,QAAQ,aAAa,GAC5F,OAAO;CAET,MAAM,QAAQ;CAEd,IAAI,MAAM,iBAAiB,KAAA,KAAc,MAAM,aAAa,KAAA,KAAa,MAAM,aAAa,KAAA,GAC1F,OAAO;CAET,MAAM,eAA+C,CAAC;CACtD,MAAM,WAAW,MAAM;CACvB,IAAI,aAAa,QAAQ,OAAO,aAAa,UAAU;EACrD,MAAM,EAAE,SAAS,QAAQ,GAAG,WAAW;EACvC,aAAa,KAAK;GAAE,MAAM;GAAY,IAAI;GAAoB,SAAS,WAAW;GAAO,QAAQ,UAAU;GAAI,gBAAgB;GAAM,GAAG;EAAO,CAAC;CAClJ;CACA,IAAI,MAAM,QAAQ,MAAM,QAAQ,GAC9B,KAAK,MAAM,SAAS,MAAM,UAAU;EAClC,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC;EACF,aAAa,KAAK;GAAE,MAAM;GAAW,gBAAgB;GAAM,GAAI;EAAkC,CAAC;CACpG;CAGF,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,KAAI,OAAM,IAAI,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,wBAAwB;CAG3G,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;;AAGA,SAAgB,YAA4D,OAAa;CACvF,MAAM,EAAE,SAAS,MAAM,OAAO,GAAG,SAAS;CAC1C,OAAO;EACL,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ;EAC3C,MAAM;GAAE,WAAW,WAAW;GAAG,QAAA;EAAsB;EACvD,GAAG;CACL;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"paths-CGlGDrOU.js","names":[],"sources":["../../src/helpers/paths.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\n/**\n * Where home-hosted keeps everything it owns. `HHOSTED_HOME` overrides it —\n * which is how a project repo keeps its own state directory while the package\n * itself ships no configuration at all.\n *\n * Everything below `dataRoot/.hh`: the global panel state at its top level, and\n * one directory per workspace. A workspace owns its settings, servers, secrets,\n * logs and nanny state; only what is genuinely panel-wide (listener, auth,\n * host vitals, backups, TLS, UI, run.json) stays global.\n */\nexport function resolveDataRoot(): string {\n const override = process.env.HHOSTED_HOME\n if (override !== undefined && override.length > 0)\n return path.resolve(override)\n return path.join(os.homedir(), '.home-hosted')\n}\n\nexport const dataRoot = resolveDataRoot()\n\n/**\n * The directory home-hosted was started from. Relative entry paths (`cwd`,\n * declared data directories) resolve against it, so the project's own launcher\n * decides the base instead of wherever the package happens to be installed.\n * `HHOSTED_PROJECT` pins it explicitly.\n */\nexport function resolveProjectDir(): string {\n const override = process.env.HHOSTED_PROJECT\n if (override !== undefined && override.length > 0)\n return path.resolve(override)\n return process.cwd()\n}\n\nexport const projectDir = resolveProjectDir()\n\n/** The internal state root: global files here, one directory per workspace. */\nexport const hhDir = path.join(dataRoot, '.hh')\n\nexport const DEFAULT_WORKSPACE_ID = 'default'\n\n/**\n * Creates `dir` (and its parents) for state this home owns, with `.hh` itself at `0700`.\n *\n * `.hh` holds server output, configs with `env` values and the proxy's keys, so it is the owner's\n * alone. A bare `mkdirSync(..., { recursive: true })` under it made `.hh` `0755` whenever something\n * other than `up` got there first — `backup list` on a fresh home did. Every creator goes through\n * here, so the mode does not depend on which command ran first. A directory outside `.hh` is\n * created as asked.\n */\nexport function ensureStateDir(dir: string = hhDir): void {\n const relative = path.relative(hhDir, dir)\n const inside = relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))\n if (inside && !fs.existsSync(hhDir))\n fs.mkdirSync(hhDir, { recursive: true, mode: 0o700 })\n fs.mkdirSync(dir, { recursive: true })\n}\n\n/**\n * A stable, non-reversible name for a state root.\n *\n * The panel reports it on `/healthz` to a loopback caller, so a CLI with no `run.json` can tell its\n * own panel from another home's panel (or anything else) on the configured port — two homes may\n * share one. A hash, not the path, so the answer names no directory.\n */\nexport function homeFingerprint(root: string = dataRoot): string {\n let resolved = root\n try {\n resolved = fs.realpathSync(root)\n }\n catch {\n // Not created yet: the resolved path is still the same answer both sides compute.\n }\n return createHash('sha256').update(resolved).digest('hex').slice(0, 16)\n}\n\n// ---------------------------------------------------------------- global state\n\n/** Panel-wide settings: listener, auth, TLS policy, host vitals, backups. */\nexport const globalSettingsPath = path.join(hhDir, 'settings.json')\n/** Password hash + API token hash; written with mode 0600. */\nexport const globalSecretsPath = path.join(hhDir, '.control-secrets.json')\n/** The workspace registry: ids and labels. */\nexport const workspacesPath = path.join(hhDir, 'workspaces.json')\n/** Uploaded TLS PEM pair (the key is written 0600). */\nexport const tlsDir = path.join(hhDir, '.tls')\n/** The panel's own console log. */\nexport const daemonLogPath = path.join(hhDir, '.logs', 'home-hosted.log')\n/** `run.json` records the live control plane. */\nexport const runtimePath = path.join(hhDir, 'run.json')\n/** The installed UI; `UiService` owns everything under it. */\nexport const uiDir = path.join(hhDir, '.ui')\n\n// ----------------------------------------------------------------- reverse proxy\n\n/** Everything the reverse proxy owns: engine binary, its data, its state and logs. */\nexport const proxyDir = path.join(hhDir, '.proxy')\n/** The engine binary the panel installed, plus the record of what it installed. */\nexport const proxyBinDir = path.join(proxyDir, 'bin')\n/** The engine's own data and configuration directories, pinned away from `$HOME`. */\nexport const proxyEngineDir = path.join(proxyDir, 'engine')\n/** The generated engine configuration, rewritten on every change. */\nexport const proxyConfigPath = path.join(proxyEngineDir, 'current.json')\n/** The last configuration that applied, kept so a rejected change can be reverted. */\nexport const proxyPreviousConfigPath = path.join(proxyEngineDir, 'previous.json')\n/** The nanny's spec and state for the engine process, so it outlives the panel. */\nexport const proxyStateDir = path.join(proxyDir, 'state')\n/** How the panel reaches a running engine's admin endpoint. */\nexport const proxyAdminPath = path.join(proxyStateDir, 'admin.json')\n/** The PEM pair a route with `tls: \"manual\"` serves. */\nexport const proxyTlsDir = path.join(proxyDir, 'tls')\n/** The credentials the engine presents to the panel's DNS-01 endpoint, 0600. */\nexport const proxyChallengeAuthPath = path.join(proxyStateDir, 'challenge.json')\n\n// ------------------------------------------------------------- workspace state\n\nexport function workspaceDir(id: string): string {\n return path.join(hhDir, id)\n}\n\n/** Workspace-scoped settings: server defaults, logs, notifications, DDNS. */\nexport function workspaceSettingsPath(id: string): string {\n return path.join(workspaceDir(id), 'settings.json')\n}\n\n/** The servers a workspace supervises. */\nexport function workspaceServersPath(id: string): string {\n return path.join(workspaceDir(id), 'servers.config.json')\n}\n\n/** Workspace secrets: Telegram bot token and DDNS credentials. Mode 0600. */\nexport function workspaceSecretsPath(id: string): string {\n return path.join(workspaceDir(id), '.secrets.json')\n}\n\n/** Rotated per-server JSONL logs. */\nexport function workspaceLogsDir(id: string): string {\n return path.join(workspaceDir(id), '.logs')\n}\n\n/** Persisted restart/crash history for one workspace. */\nexport function workspaceHistoryPath(id: string): string {\n return path.join(workspaceLogsDir(id), 'history.json')\n}\n\n/** Per-entry nanny state and spawn specs — how a persistent server survives a restart. */\nexport function workspaceStateDir(id: string): string {\n return path.join(workspaceDir(id), '.state')\n}\n\n/**\n * The last public address each DDNS target was confirmed to serve.\n *\n * A name no server id can produce (ids carry no `.`): `ddns.json` is also the nanny state of a\n * persistent entry with the id `ddns`, and each overwrote the other.\n */\nexport function workspaceDdnsStatePath(id: string): string {\n return path.join(workspaceStateDir(id), 'ddns.cache.json')\n}\n\n/** Where releases before `ddns.cache.json` kept that cache, read once and then removed. */\nexport function workspaceLegacyDdnsStatePath(id: string): string {\n return path.join(workspaceStateDir(id), 'ddns.json')\n}\n\n// -------------------------------------------------------------------- legacy\n\n/**\n * Where a pre-workspace `$HHOSTED_HOME` kept its config and secrets: directly\n * under `dataRoot`. Nothing reads these; they only identify an instance this\n * release refuses to start against.\n */\nexport const legacy = {\n configPath: path.join(dataRoot, 'servers.config.json'),\n secretsPath: path.join(dataRoot, '.control-secrets.json'),\n} as const\n\n/**\n * True when a pre-workspace instance left state at the old paths **and** never\n * crossed into `.hh`: `workspaces.json` means the layout is current, so a stray\n * root-level copy beside it is not an old instance.\n */\nexport function hasLegacyLayout(): boolean {\n if (fs.existsSync(workspacesPath))\n return false\n return fs.existsSync(legacy.configPath) || fs.existsSync(legacy.secretsPath)\n}\n\n/** Expands `~` and resolves relative paths against `base`, for config-declared paths. */\nexport function resolveUserPath(target: string, base = projectDir): string {\n let value = target\n if (value === '~')\n value = os.homedir()\n else if (value.startsWith('~/') || value.startsWith('~\\\\'))\n value = path.join(os.homedir(), value.slice(2))\n return path.isAbsolute(value) ? value : path.resolve(base, value)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,kBAA0B;CACxC,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,KAAA,KAAa,SAAS,SAAS,GAC9C,OAAO,KAAK,QAAQ,QAAQ;CAC9B,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,cAAc;AAC/C;AAEA,IAAa,WAAW,gBAAgB;;;;;;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AAW,cAAc,GAC9B,OAAO;CACT,OAAO,GAAG,WAAW,OAAO,UAAU,KAAK,GAAG,WAAW,OAAO,WAAW;AAC7E;;AAGA,SAAgB,gBAAgB,QAAgB,OAAO,YAAoB;CACzE,IAAI,QAAQ;CACZ,IAAI,UAAU,KACZ,QAAQ,GAAG,QAAQ;MAChB,IAAI,MAAM,WAAW,IAAI,KAAK,MAAM,WAAW,KAAK,GACvD,QAAQ,KAAK,KAAK,GAAG,QAAQ,GAAG,MAAM,MAAM,CAAC,CAAC;CAChD,OAAO,KAAK,WAAW,KAAK,IAAI,QAAQ,KAAK,QAAQ,MAAM,KAAK;AAClE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"port-B8WBTRMk.js","names":[],"sources":["../../src/providers/port.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport net from 'node:net'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/** True when something accepts TCP connections on host:port. */\nexport function probePort(host: string, port: number, timeoutMs = 1500): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = net.connect({ host, port })\n const done = (result: boolean): void => {\n socket.removeAllListeners()\n socket.destroy()\n resolve(result)\n }\n socket.setTimeout(timeoutMs)\n socket.once('connect', () => done(true))\n socket.once('timeout', () => done(false))\n socket.once('error', () => done(false))\n })\n}\n\n/** A port is free when nothing is listening on it (loopback is enough to detect conflicts). */\nexport async function isPortFree(port: number, host = '127.0.0.1', timeoutMs = 1000): Promise<boolean> {\n return !(await probePort(host, port, timeoutMs))\n}\n\n/**\n * Kills whatever holds the port, minus `exclude` (the panel's own process tree).\n * Only used as a last resort for wrappers that spawn their real server detached,\n * where a process-group signal cannot reach it.\n */\nexport async function killPortHolders(port: number, exclude?: ReadonlySet<number>): Promise<number[]> {\n const pids = (await listPortHolders(port)).filter(pid => !exclude?.has(pid))\n for (const pid of pids) {\n try {\n process.kill(pid, 'SIGKILL')\n }\n catch {\n // already gone\n }\n }\n return pids\n}\n\n/**\n * Signal 0 asks the OS whether the pid still exists, without touching it.\n *\n * `EPERM` means the process is there but is **not ours to signal** — a port holder owned by another\n * user is exactly that. Returning `false` for it made `nannyIsAlive` report a live nanny as gone, so\n * `resumePersistent` consumed its state file and started a second copy of the entry while the first ran\n * on untracked. `helpers/daemon.ts` already had this right; the two predicates now agree.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n }\n catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/** Linux jiffies per second: the near-universal default, since `/proc` needs no `getconf`. */\nconst LINUX_HZ = 100\n\n/** When a process started, and whether it has exited but is not reaped yet. */\nexport interface ProcessBirth {\n /** Epoch ms the process started, as the OS reports it. */\n startMs: number\n /** A zombie: exited, still answering signal 0, and nobody's to signal. */\n zombie: boolean\n}\n\n/**\n * `/proc/<pid>/stat` field 22 is the start time in clock ticks since boot, which only\n * becomes an epoch by adding `btime` from `/proc/stat`. Field 3 is the state.\n *\n * The comm field is parenthesised and may itself hold spaces and parentheses, so the\n * fields are counted from after the **last** `)`. Counting from the first would shift\n * every offset for a process whose name contains a `)`, and this value decides whether a\n * live-looking pid is really the daemon.\n */\nexport function parseProcBirth(content: string, btimeSeconds: number, hz = LINUX_HZ): ProcessBirth | null {\n const close = content.lastIndexOf(')')\n if (close < 0)\n return null\n const fields = content.slice(close + 2).split(' ')\n const ticks = Number.parseInt(fields[19] ?? '', 10)\n if (!Number.isFinite(ticks) || ticks < 0)\n return null\n return { startMs: btimeSeconds * 1000 + (ticks / hz) * 1000, zombie: fields[0] === 'Z' }\n}\n\n/**\n * One `ps -o state=,lstart=` row, e.g. `S Wed Oct 7 19:43:26 2026` (macOS, other POSIX).\n * The leading weekday is stripped before parsing: `Date.parse` is not obliged to accept it\n * and it says nothing the date does not.\n */\nexport function parsePsBirth(output: string): ProcessBirth | null {\n const line = output.trim().split('\\n')[0]?.trim() ?? ''\n if (line.length === 0)\n return null\n const [state = '', ...rest] = line.split(/\\s+/)\n const startMs = Date.parse(rest.join(' ').replace(/^[A-Z]{3,9}\\s+/i, ''))\n if (!Number.isFinite(startMs))\n return null\n return { startMs, zombie: state.startsWith('Z') }\n}\n\n/** 100ns ticks between the FILETIME epoch (1601) and the Unix epoch (1970). */\nconst FILETIME_UNIX_OFFSET_MS = 11644473600000\n\n/**\n * FILETIME ticks (100ns since **1601**, UTC) to a Unix epoch in ms — the shape\n * `DateTime.ToFileTimeUtc()` returns.\n *\n * The epoch matters: `DateTime.Ticks` counts from **0001**, not 1601, and the two differ by\n * 1600 years. Reading the wrong one put every Windows panel ~1600 years in the future, which\n * `processLiveness` then called `recycled` — a live panel that could never signal-stop itself.\n * The PowerShell call below therefore asks for `ToFileTimeUtc()` explicitly, and this is exported\n * so the conversion is pinned by a test.\n */\nexport function parseFiletime(ticks: number): number | null {\n if (!Number.isFinite(ticks) || ticks <= 0)\n return null\n return ticks / 1e4 - FILETIME_UNIX_OFFSET_MS\n}\n\n/**\n * When the pid started, from the platform's own process table. `null` when the platform\n * cannot say — an unreadable `/proc`, no `ps`, or no PowerShell — which the caller must\n * read as \"unknown\", never as \"gone\".\n */\nexport async function processBirth(pid: number): Promise<ProcessBirth | null> {\n if (!Number.isInteger(pid) || pid <= 0)\n return null\n\n if (process.platform === 'linux') {\n try {\n const [stat, system] = await Promise.all([\n fs.promises.readFile(`/proc/${pid}/stat`, 'utf8'),\n fs.promises.readFile('/proc/stat', 'utf8'),\n ])\n const btime = /^btime (\\d+)$/m.exec(system)?.[1]\n if (btime === undefined)\n return null\n return parseProcBirth(stat, Number.parseInt(btime, 10))\n }\n catch {\n return null\n }\n }\n\n if (process.platform === 'win32') {\n try {\n // `ToFileTimeUtc()`, not `.Ticks`: the latter is 100ns since 0001 and would be read as\n // ~1600 years in the future. ToFileTimeUtc normalizes to UTC and the 1601 epoch, which is\n // what `parseFiletime` expects.\n const script = `$p = Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\"; if ($p) { $p.CreationDate.ToFileTimeUtc() }`\n const { stdout } = await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 20000, windowsHide: true })\n const startMs = parseFiletime(Number.parseFloat(stdout.trim()))\n return startMs === null ? null : { startMs, zombie: false }\n }\n catch {\n return null\n }\n }\n\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'state=,lstart='], { timeout: 3000 })\n return parsePsBirth(stdout)\n }\n catch {\n return null\n }\n}\n\n/** Is the process at `pid` the one a record stamped `startedAt` describes? */\nexport type ProcessLiveness\n /** Alive, and born when the record implies. */\n = | 'live'\n /** Nothing is running behind the pid: absent, or a zombie nobody has reaped. */\n | 'gone'\n /** A live pid, but born *after* the record was written — the OS recycled it. */\n | 'recycled'\n /** The platform would not report a birth time, so the live pid is all there is to go on. */\n | 'unknown'\n\n/**\n * A pid is **not** an identity. The OS hands a dead process's pid to an unrelated one later, and a\n * zombie — exited but not yet reaped by its parent — still answers signal 0. So `isProcessAlive`\n * alone can report a long-dead daemon as live, which is what let `up` say \"already running\" and\n * `status` say \"running, but not answering\" against a stale `run.json`, and what let `down` signal\n * whatever stranger had inherited the pid.\n *\n * `startedAt` settles it in one direction, with no threshold to guess at: the daemon writes its\n * record *during its own boot*, so its process is necessarily born **before** that stamp. A pid born\n * after it is not that process, whoever else it now is. The comparison is deliberately one-sided —\n * the other direction would have to tell a recycled pid from a wall clock that merely moved, and it\n * cannot, so a record is never called stale for being *older* than its process.\n *\n * `'unknown'` is not `'gone'`: a platform that cannot report a birth time must not have its live pid\n * dismissed, or a running panel's record would be cleared out from under it.\n */\nexport async function processLiveness(\n pid: number,\n startedAt: number,\n options: { toleranceMs?: number, readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {},\n): Promise<ProcessLiveness> {\n if (!isProcessAlive(pid))\n return 'gone'\n\n const birth = await (options.readBirth ?? processBirth)(pid)\n if (birth === null)\n return 'unknown'\n if (birth.zombie)\n return 'gone'\n\n // The tolerance absorbs the one-second granularity of `ps -o lstart=`, which can report a\n // process as born a fraction *after* `startedAt` even though it really started before it.\n return birth.startMs > startedAt + (options.toleranceMs ?? 2000) ? 'recycled' : 'live'\n}\n\nfunction signalPid(pid: number, name: NodeJS.Signals): void {\n try {\n process.kill(pid, name)\n }\n catch {\n // already gone, or not ours to signal\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\n/**\n * Asks specific pids to leave, politely first: a stray dev server stops on\n * SIGTERM, and only what ignores it is killed. Deciding *which* pids may be\n * touched belongs to the caller — this only does the signalling.\n */\nexport async function terminatePids(\n pids: number[],\n options: { graceMs?: number } = {},\n): Promise<{ stopped: number[], forced: number[] }> {\n const graceMs = options.graceMs ?? 3000\n const targets = [...new Set(pids)]\n // Only what was actually there is claimed as stopped; a pid that had already\n // exited is neither ours to report nor ours to kill.\n const aliveBefore = targets.filter(isProcessAlive)\n\n for (const pid of aliveBefore) signalPid(pid, 'SIGTERM')\n\n const deadline = Date.now() + graceMs\n let alive = aliveBefore.filter(isProcessAlive)\n while (alive.length > 0 && Date.now() < deadline) {\n await delay(100)\n alive = alive.filter(isProcessAlive)\n }\n\n const stopped = aliveBefore.filter(pid => !alive.includes(pid))\n for (const pid of alive) signalPid(pid, 'SIGKILL')\n if (alive.length > 0 && graceMs > 0)\n await delay(150)\n\n return { stopped, forced: alive }\n}\n\n/**\n * One filtered `netstat` per family. `-p TCP` alone lists IPv4 only, while Node's default `listen()`\n * binds `[::]`; an unfiltered `-ano` lists every connection and UDP socket, which is slow enough on a\n * busy machine to hit the lookup's timeout — and a timeout reads as \"nothing holds the port\".\n */\nexport const NETSTAT_LISTENER_ARGS: ReadonlyArray<readonly string[]> = [['-ano', '-p', 'TCP'], ['-ano', '-p', 'TCPv6']]\n\n/** `netstat -ano` lines: ` TCP 127.0.0.1:4010 0.0.0.0:0 LISTENING 1234`; UDP rows are skipped. */\nexport function parseNetstatListeners(output: string, port: number): number[] {\n const pids = new Set<number>()\n\n for (const line of output.split(/\\r?\\n/)) {\n const cells = line.trim().split(/\\s+/)\n if (cells.length < 5)\n continue\n if ((cells[0] ?? '').toUpperCase() !== 'TCP')\n continue\n const local = cells[1] ?? ''\n const state = cells[3] ?? ''\n const pid = Number.parseInt(cells[4] ?? '', 10)\n const localPort = Number.parseInt(local.slice(local.lastIndexOf(':') + 1), 10)\n if (state.toUpperCase() !== 'LISTENING' || localPort !== port)\n continue\n if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)\n pids.add(pid)\n }\n\n return [...pids]\n}\n\n/**\n * The container publishing a host port, when docker is holding it.\n *\n * A published port is bound by `docker-proxy`, which runs as **root** — so `lsof`/`fuser` return\n * nothing for it, and `listPortHolders` reports an empty list for a port that is plainly refusing\n * every bind. Docker itself answers the question without privileges, and names the stack too, so\n * the caller can say *whose* stack it is instead of \"nothing is listening\".\n */\nexport interface DockerPortHolder {\n /** `com.docker.compose.project.working_dir` when the container came from compose. */\n composeDir: string | null\n /** `com.docker.compose.project`, so a caller can tell this entry's own stack from a stranger's. */\n project: string | null\n container: string\n port: number\n}\n\nexport async function findDockerPortHolder(port: number): Promise<DockerPortHolder | null> {\n try {\n const { stdout } = await execFileAsync('docker', [\n 'ps',\n '--filter',\n `publish=${port}`,\n '--format',\n '{{.Names}}\\t{{.Label \"com.docker.compose.project\"}}\\t{{.Label \"com.docker.compose.project.working_dir\"}}',\n ], { timeout: 3000 })\n const line = stdout.split('\\n').find(entry => entry.trim().length > 0)\n if (line === undefined)\n return null\n const [container = '', project = '', composeDir = ''] = line.split('\\t')\n if (container.trim().length === 0)\n return null\n return {\n container: container.trim(),\n project: project.trim().length > 0 ? project.trim() : null,\n composeDir: composeDir.trim().length > 0 ? composeDir.trim() : null,\n port,\n }\n }\n catch {\n // docker absent, not running, or not permissioned: no claim either way.\n return null\n }\n}\n\n/**\n * Stops the container publishing a host port, which is how docker's port is freed.\n *\n * The socket belongs to a root-owned `docker-proxy`, so there is no pid this process may signal —\n * but the container is the panel's to stop through docker itself, which needs no privileges\n * beyond the socket the user already has. `docker stop` releases the published port and leaves the\n * stack's other services alone.\n */\nexport async function releaseDockerPort(holder: DockerPortHolder, timeoutMs = 20000): Promise<boolean> {\n try {\n await execFileAsync('docker', ['stop', holder.container], { timeout: timeoutMs })\n return true\n }\n catch {\n return false\n }\n}\n\nexport async function listPortHolders(port: number): Promise<number[]> {\n if (process.platform === 'win32') {\n const outputs = await Promise.all(NETSTAT_LISTENER_ARGS.map(args =>\n execFileAsync('netstat', [...args], { timeout: 10000 }).then(result => result.stdout, () => '')))\n return [...new Set(outputs.flatMap(output => parseNetstatListeners(output, port)))]\n }\n\n try {\n const { stdout } = await execFileAsync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], { timeout: 3000 })\n return parsePids(stdout)\n }\n catch {\n // lsof missing or nothing listening\n }\n\n try {\n const { stdout } = await execFileAsync('fuser', [`${port}/tcp`], { timeout: 3000 })\n return parsePids(stdout)\n }\n catch {\n return []\n }\n}\n\n/**\n * Pids from `lsof -ti` (one per line) or `fuser` (space-separated, on one line, with a leading\n * space) — both shapes arrive here, which is why the split is on `\\s+` rather than `\\n`.\n *\n * Exported for its test: this feeds `killPortHolders`, which sends SIGKILL, so a parser that\n * picked up the wrong number would kill an unrelated process. The filter is not decorative —\n * `Number.parseInt('')` is NaN for the empty leading cell, and a pid of 0 or our own is dropped.\n */\nexport function parsePids(stdout: string): number[] {\n return [...new Set(\n stdout.split(/\\s+/)\n .map(entry => Number.parseInt(entry, 10))\n .filter(pid => Number.isInteger(pid) && pid > 0 && pid !== process.pid),\n )]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAM,gBAAgB,UAAU,QAAQ;;AAGxC,SAAgB,UAAU,MAAc,MAAc,YAAY,MAAwB;CACxF,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAS,IAAI,QAAQ;GAAE;GAAM;EAAK,CAAC;EACzC,M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G,KAAK,MAAM,KAAK,QAAQ,QAAQ,GAAG,CAC1E,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"restart-Des4DrAN.js","names":[],"sources":["../../src/cli/restart.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { runDown } from '#src/cli/down'\nimport { fail, invocation, paint } from '#src/cli/io'\nimport { runServerAction } from '#src/cli/server'\nimport { checkedUpFlags, runUp, upArgs } from '#src/cli/up'\n\n/**\n * `restart` restarts the panel (`down`, then `up`) — or, given a server id, just that entry.\n *\n * The id is optional on purpose. `restart` already meant the panel, and it still does when\n * called the way it always was; adding a positional would have been a hard error before this\n * (\"Unexpected argument 'web'\"), so nothing existing changes meaning. The per-server case is\n * what the UI's Restart button has always done and the shell could not.\n */\n\n/**\n * The `up` flags that mean nothing to `restart <id>`, as citty parses them.\n *\n * The bare form forwards all of them — `restart --print-config` is a real, tested use. The id form\n * asks the panel to restart one entry over `/_hh` and never runs `down` or `up`, so a panel-level\n * flag has nothing to act on: `restart web --port 5000` used to report \"restarted web\" having\n * changed no port. `upArgs` declares no defaults, so a flag that was not given is `undefined`.\n */\nconst PANEL_ONLY_FLAGS = [\n ['port', '--port'],\n ['host', '--host'],\n ['autostart', '--no-autostart'],\n ['open', '--open'],\n ['foreground', '--foreground'],\n ['printConfig', '--print-config'],\n] as const\n\nexport function restartCommand(entry: string) {\n return defineCommand({\n meta: { name: 'restart' },\n args: {\n ...upArgs,\n // `down`'s own flag, so the two commands cannot drift about what it means. Declared\n // here as well because citty reads one command's definitions, not two.\n withPersistent: { type: 'boolean', description: 'stop the persistent entries too, instead of leaving them running' },\n // Declared here rather than in `server.ts` because only `restart` takes it bare: for\n // `start`/`stop` the id is required, and citty's refusal is replaced by our own message.\n id: { type: 'positional', required: false, description: 'restart just this server instead of the panel' },\n workspace: { type: 'string', alias: 'w', description: 'the workspace to act in (default: the panel\\'s default workspace)' },\n },\n run: async ({ args }) => {\n const id = typeof args.id === 'string' ? args.id.trim() : ''\n\n if (id.length > 0) {\n // One entry, so the panel stays up. A bare `restart` would have taken the whole\n // panel — and every other server — down with it.\n if (args.withPersistent === true)\n fail('restart <id> restarts one server — drop --with-persistent, or use it on a bare `restart`')\n const panelFlag = PANEL_ONLY_FLAGS.find(([key]) => args[key] !== undefined)\n if (panelFlag !== undefined)\n fail(`restart <id> restarts one server and takes no panel option — drop ${panelFlag[1]}, or use it on a bare \\`restart\\``)\n const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : undefined\n await runServerAction('restart', id, workspace)\n return\n }\n\n // The panel's own restart takes no `--workspace`: it is not a per-server idea.\n if (args.workspace !== undefined)\n fail(`restart --workspace needs a server id — \\`${invocation()} restart <id> --workspace <id>\\``)\n\n // `--with-persistent` restarts them, it does not merely stop them. `up` would *reattach*\n // to a nanny left alive, so stopping them first is what makes this a restart at all —\n // and a stopped entry is only started back by `up`'s autostart pass, which an entry with\n // `autostart: false` is not in. Those are therefore started back explicitly.\n //\n // Every `up` flag is checked before anything is stopped: `restart --port abc` used to take the\n // panel down and only then refuse the port, leaving nothing running.\n const flags = await checkedUpFlags(args)\n const down = await runDown({ withPersistent: args.withPersistent === true })\n // `down` has already said why; going on to `up` would start a second panel over a live one.\n if (!down.ok)\n process.exit(1)\n await runUp(flags, entry)\n if (down.stoppedPersistent.length > 0)\n await startPersistentBack(down.stoppedPersistent)\n },\n })\n}\n\n/**\n * Starts the entries this restart stopped, through the panel that just came back.\n *\n * Only the ones `up` did not already start: its autostart pass runs asynchronously and a second\n * start of a running entry is a plain `{ ok: true }`, so re-asking is harmless — but the\n * entries with `autostart: false`, the reason this exists, would never come back otherwise.\n */\nasync function startPersistentBack(stopped: Array<{ workspaceId: string, serverId: string }>): Promise<void> {\n const { readRuntime, requestControl } = await import('#src/helpers/daemon')\n const runtime = readRuntime()\n if (runtime === null)\n return\n\n for (const { workspaceId, serverId } of stopped) {\n const workspace = `?workspace=${encodeURIComponent(workspaceId)}`\n const answer = await requestControl(runtime, `/_hh/servers/${encodeURIComponent(serverId)}/start${workspace}`)\n const body = (answer?.body ?? {}) as { ok?: boolean, error?: string }\n if (body.ok !== true)\n process.stderr.write(`${paint('31', 'error')} ${workspaceId}/${serverId} did not come back: ${body.error ?? `the panel answered ${answer?.status}`}\\n`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,mBAAmB;CACvB,CAAC,QAAQ,QAAQ;CACjB,CAAC,QAAQ,QAAQ;CACjB,CAAC,aAAa,gBAAgB;CAC9B,CAAC,QAAQ,QAAQ;CACjB,CAAC,cAAc,cAAc;CAC7B,CAAC,eAAe,gBAAgB;AAClC;AAEA,SAAgB,eAAe,OAAe;CAC5C,OAAO,cAAc;EACnB,MAAM,EAAE,MAAM,UAAU;EACxB,MAAM;GACJ,GAAG;GAGH,gBAAgB;IAAE,MAAM;IAAW,aAAa;GAAmE;GAGnH,IAAI;IAAE,MAAM;IAAc,UAAU;IAAO,aAAa;GAAgD;GACxG,WAAW;IAAE,MAAM;IAAU,OAAO;IAAK,aAAa;GAAoE;EAC5H;EACA,KAAK,OAAO,EAAE,WAAW;GACvB,MAAM,KAAK,OAAO,KAAK,OAAO,WAAW,KAAK,GAAG,KAAK,IAAI;GAE1D,IAAI,GAAG,SAAS,GAAG;IAGjB,IAAI,KAAK,mBAAmB,MAC1B,KAAK,0FAA0F;IACjG,MAAM,YAAY,iBAAiB,MAAM,CAAC,SAAS,KAAK,SAAS,KAAA,CAAS;IAC1E,IAAI,cAAc,KAAA,GAChB,KAAK,qEAAqE,UAAU,GAAG,kCAAkC;IAC3H,MAAM,YAAY,OAAO,KAAK,cAAc,WAAW,KAAK,UAAU,KAAK,IAAI,KAAA;IAC/E,MAAM,gBAAgB,WAAW,IAAI,SAAS;IAC9C;GACF;GAGA,IAAI,KAAK,cAAc,KAAA,GACrB,KAAK,6CAA6C,WAAW,EAAE,iCAAiC;GASlG,MAAM,QAAQ,MAAM,eAAe,IAAI;GACvC,MAAM,OAAO,MAAM,QAAQ,EAAE,gBAAgB,KAAK,mBAAmB,KAAK,CAAC;GAE3E,IAAI,CAAC,KAAK,IACR,QAAQ,KAAK,CAAC;GAChB,MAAM,MAAM,OAAO,KAAK;GACxB,IAAI,KAAK,kBAAkB,SAAS,GAClC,MAAM,oBAAoB,KAAK,iBAAiB;EACpD;CACF,CAAC;AACH;;;;;;;;AASA,eAAe,oBAAoB,SAA0E;CAC3G,MAAM,EAAE,aAAa,mBAAmB,MAAM,OAAO;CACrD,MAAM,UAAU,YAAY;CAC5B,IAAI,YAAY,MACd;CAEF,KAAK,MAAM,EAAE,aAAa,cAAc,SAAS;EAC/C,MAAM,YAAY,cAAc,mBAAmB,WAAW;EAC9D,MAAM,SAAS,MAAM,eAAe,SAAS,gBAAgB,mBAAmB,QAAQ,EAAE,QAAQ,WAAW;EAC7G,MAAM,OAAQ,QAAQ,QAAQ,CAAC;EAC/B,IAAI,KAAK,OAAO,MACd,QAAQ,OAAO,MAAM,GAAG,MAAM,MAAM,OAAO,EAAE,GAAG,YAAY,GAAG,SAAS,sBAAsB,KAAK,SAAS,sBAAsB,QAAQ,SAAS,GAAG;CAC1J;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schema-B240VXcV.js","names":[],"sources":["../../src/config/schema.ts"],"sourcesContent":["import type { ServerConfig } from '#src/shared/contracts'\nimport { type } from 'arktype'\nimport {\n backupsSchema,\n controlSchema,\n ddnsConfigSchema,\n defaultsSchema,\n hostSchema,\n logsSchema,\n notificationsSchema,\n proxyConfigSchema,\n serverSchema,\n} from '#src/shared/contracts'\nimport { lazy } from '#src/shared/lazy'\nimport { isRecord } from '#src/shared/shape'\n\nexport { backupsSchema, controlSchema, ddnsConfigSchema, defaultsSchema, hostSchema, logsSchema, notificationsSchema, proxyConfigSchema, serverSchema }\n\n/**\n * Which release wrote the file, and the config shape it wrote. Optional so a\n * config from before the stamp still reads, and so an archive made by an older\n * release still restores.\n */\nexport const metaSchema = lazy(() => type({\n writtenBy: 'string = \"\"',\n schema: 'number.integer >= 1 = 1',\n}).onUndeclaredKey('reject'))\n\n/**\n * `$HHOSTED_HOME/.hh/settings.json`: the settings that belong to the panel\n * itself — its listener, authentication, TLS policy, host vitals, backups and\n * the reverse proxy. Nothing here is per workspace.\n */\nexport const globalSettingsSchema = lazy(() => type({\n $schema: 'string?',\n meta: metaSchema.optional(),\n control: controlSchema.default(() => ({})),\n host: hostSchema.default(() => ({})),\n backups: backupsSchema.default(() => ({})),\n proxy: proxyConfigSchema.default(() => ({})),\n}).onUndeclaredKey('reject'))\n\n/** `$HHOSTED_HOME/.hh/<id>/settings.json`: what one workspace owns on its own. */\nexport const workspaceSettingsSchema = lazy(() => type({\n $schema: 'string?',\n meta: metaSchema.optional(),\n defaults: defaultsSchema.default(() => ({})),\n logs: logsSchema.default(() => ({})),\n notifications: notificationsSchema.default(() => ({})),\n ddns: ddnsConfigSchema.default(() => ({})),\n}).onUndeclaredKey('reject'))\n\n/** `$HHOSTED_HOME/.hh/<id>/servers.config.json`: the entries this workspace supervises. */\nexport const serversFileSchema = lazy(() => type({\n $schema: 'string?',\n meta: metaSchema.optional(),\n servers: serverSchema.array().default(() => []),\n}).onUndeclaredKey('reject'))\n\nexport type ResolvedGlobalConfig = typeof globalSettingsSchema.infer\nexport type ResolvedWorkspaceSettings = typeof workspaceSettingsSchema.infer\nexport type ResolvedServersFile = typeof serversFileSchema.infer\n\n/** Same shape as the settings output, with each server `port` normalized to `null` when unset. */\nexport type ResolvedWorkspaceConfig = ResolvedWorkspaceSettings & { servers: ServerConfig[] }\n\n/** Every key `globalSettingsSchema` knows, for reporting blocks a newer release added. */\nexport const GLOBAL_SETTINGS_KEYS = ['$schema', 'meta', 'control', 'host', 'backups', 'proxy'] as const\nexport const WORKSPACE_SETTINGS_KEYS = ['$schema', 'meta', 'defaults', 'logs', 'notifications', 'ddns'] as const\nexport const SERVERS_FILE_KEYS = ['$schema', 'meta', 'servers'] as const\n\n/**\n * Resolves one entry against the workspace's server defaults. A group (`restart`,\n * `health`, `health.http`, `stop`) merges key by key, so an entry that decides one\n * member does not silently fall back to the *schema* default for the others — which\n * is the whole point of the workspace having defaults at all.\n */\nexport function mergeDefaults(\n defaults: Record<string, unknown>,\n entry: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...entry }\n for (const [key, value] of Object.entries(defaults)) {\n const current = merged[key]\n if (current === undefined)\n merged[key] = value\n else if (isRecord(value) && isRecord(current))\n merged[key] = mergeDefaults(value, current)\n }\n return merged\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,aAAa,WAAW,KAAK;CACxC,WAAW;CACX,QAAQ;AACV,CAAC,CAAC,CAAC,gBAAgB,QAAQ,CAAC;;;;;;AAO5B,IAAa,uBAAuB,WAAW,KAAK;CAClD,SAAS;CACT,MAAM,WAAW,SAAS;CAC1B,SAAS,cAAc,eAAe,CAAC,EAAE;CACzC,MAAM,WAAW,eAAe,CAAC,EAAE;CACnC,SAAS,cAAc,eAAe,CAAC,EAAE;CACzC,OAAO,kBAAkB,eAAe,CAAC,EAAE;AAC7C,CAAC,CAAC,CAAC,gBAAgB,QAAQ,CAAC;;AAG5B,IAAa,0BAA0B,WAAW,KAAK;CACrD,SAAS;CACT,MAAM,WAAW,SAAS;CAC1B,UAAU,eAAe,eAAe,CAAC,EAAE;CAC3C,MAAM,WAAW,eAAe,CAAC,EAAE;CACnC,eAAe,oBAAoB,eAAe,CAAC,EAAE;CACrD,MAAM,iBAAiB,eAAe,CAAC,EAAE;AAC3C,CAAC,CAAC,CAAC,gBAAgB,QAAQ,CAAC;;AAG5B,IAAa,oBAAoB,WAAW,KAAK;CAC/C,SAAS;CACT,MAAM,WAAW,SAAS;CAC1B,SAAS,aAAa,MAAM,CAAC,CAAC,cAAc,CAAC,CAAC;AAChD,CAAC,CAAC,CAAC,gBAAgB,QAAQ,CAAC;;AAU5B,IAAa,uBA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