home-hosted 0.9.5 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -252,7 +252,6 @@ function rejectUnknownFlags(argv, argsDef) {
252
252
  */
253
253
  function buildDaemonArgv(flags) {
254
254
  const args = ["up", "--foreground"];
255
- if (flags.config !== void 0) args.push("--config", flags.config);
256
255
  if (flags.port !== void 0) args.push("--port", String(flags.port));
257
256
  if (flags.host !== void 0) args.push("--host", flags.host);
258
257
  if (!flags.autostart) args.push("--no-autostart");
@@ -739,7 +738,7 @@ function duplicateWebhookIds(targets) {
739
738
  }
740
739
  return [...duplicates];
741
740
  }
742
- var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, backupFileSchema, backupEntrySchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, serverOrphanSchema, workspaceViewSchema, appStateSchema, logQuerySchema, actionResultSchema, deliveryResultSchema, passwordSetResponseSchema, tlsReviewResponseSchema, okResponseSchema, backupFilesResponseSchema, uiInstallResponseSchema, backupCreatedResponseSchema, logLinesResponseSchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
741
+ var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, backupHookSchema, backupHookOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, backupFileSchema, backupEntrySchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, serverOrphanSchema, workspaceViewSchema, appStateSchema, logQuerySchema, actionResultSchema, deliveryResultSchema, passwordSetResponseSchema, tlsReviewResponseSchema, okResponseSchema, backupFilesResponseSchema, uiInstallResponseSchema, backupCreatedResponseSchema, logLinesResponseSchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
743
742
  var init_contracts = __esmMin((() => {
744
743
  bindSchema = type("\"local\" | \"lan\" | /^\\d{1,3}(?:\\.\\d{1,3}){3}$/");
745
744
  workspaceIdSchema = type("/^[a-z0-9][a-z0-9_-]*$/");
@@ -811,6 +810,22 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
811
810
  runOnce: "boolean = true"
812
811
  }).onUndeclaredKey("reject");
813
812
  bootstrapOrNullSchema = bootstrapSchema.or(type("null"));
813
+ backupHookSchema = type({
814
+ command: "string >= 1",
815
+ args: type("string[]").default(() => []),
816
+ env: type("Record<string, string>").default(() => ({})),
817
+ timeoutMs: "number >= 1000 = 600000",
818
+ /**
819
+ * How long to wait for the entry to answer before running a `load`.
820
+ *
821
+ * Only matters for `load`, and only for an entry with no `port`: the wait is normally "the port
822
+ * accepts a connection", which an entry that declares no port cannot offer. Two seconds by
823
+ * default, because a portless entry usually starts fast and a fixed wait is pure delay; a slow
824
+ * database reached over a socket should raise it.
825
+ */
826
+ waitMs: "number >= 0 = 2000"
827
+ }).onUndeclaredKey("reject");
828
+ backupHookOrNullSchema = backupHookSchema.or(type("null"));
814
829
  labelOrNullSchema = type("string | null");
815
830
  logBufferLinesSchema = type("50 <= number.integer <= 100000");
816
831
  serverSchema = type({
@@ -834,6 +849,16 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
834
849
  */
835
850
  dataEnvs: type("Record<string, string>").default(() => ({})),
836
851
  bootstrap: bootstrapOrNullSchema.optional(),
852
+ /**
853
+ * Run before this entry's data is captured, writing into `{dumpDir}`.
854
+ *
855
+ * For a database: `mongodump --archive={dumpDir}/db.archive`. A failed dump **refuses the backup**
856
+ * rather than archiving a stale directory next to it — the whole point is that the dump is the
857
+ * authoritative copy.
858
+ */
859
+ dump: backupHookOrNullSchema.optional(),
860
+ /** Run after this entry's data is restored, reading from `{dumpDir}`. Its server is stopped first. */
861
+ load: backupHookOrNullSchema.optional(),
837
862
  port: portSchema.optional(),
838
863
  bind: bindSchema.default(() => "local"),
839
864
  onPortConflict: onPortConflictDefaultSchema,
@@ -1217,6 +1242,8 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1217
1242
  env: "Record<string, string>?",
1218
1243
  dataEnvs: "Record<string, string>?",
1219
1244
  bootstrap: bootstrapOrNullSchema.optional(),
1245
+ dump: backupHookOrNullSchema.optional(),
1246
+ load: backupHookOrNullSchema.optional(),
1220
1247
  port: portSchema.optional(),
1221
1248
  bind: bindSchema.optional(),
1222
1249
  onPortConflict: onPortConflictSchema.optional(),
@@ -1279,6 +1306,15 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1279
1306
  /** The `runOnce` bootstrap already ran for this entry. */
1280
1307
  "bootstrapDone": "boolean",
1281
1308
  /**
1309
+ * A restored dump this entry still has to load, and where it is.
1310
+ *
1311
+ * The restore cannot run the load hook itself: `mongorestore` needs a server that is answering, and
1312
+ * the entry is stopped at that moment. So the restore stages the dump and records it here, and the
1313
+ * next `start` runs the hook once the process is up. Persisted, because a restore followed by a
1314
+ * panel restart must not lose the load.
1315
+ */
1316
+ "pendingLoad?": "string | null",
1317
+ /**
1282
1318
  * The last child this panel spawned for a non-persistent entry. A detached child
1283
1319
  * outlives the panel, so this is the only way a later boot recognizes its own
1284
1320
  * survivor instead of spawning a second copy beside it.
@@ -1731,6 +1767,19 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1731
1767
  "schema?": "number"
1732
1768
  }),
1733
1769
  "items": restoreItemSchema.array(),
1770
+ /**
1771
+ * One row per backup hook that ran, so a person can see which entries brought their own dump.
1772
+ *
1773
+ * Optional, like every new response field: an older panel never sends it and an older UI never
1774
+ * reads it. `output` is a bounded tail, not a log — enough to see what `mongorestore` said.
1775
+ */
1776
+ "hooks?": type({
1777
+ "serverId": "string",
1778
+ "workspaceId": "string",
1779
+ "action": "\"dump\" | \"load\"",
1780
+ "ok": "boolean",
1781
+ "output?": "string"
1782
+ }).array(),
1734
1783
  "applied": type("string[]"),
1735
1784
  /**
1736
1785
  * The ids `applied` names, so a UI resolves each through `items` and renders its own label.
@@ -4085,6 +4134,16 @@ function createControlRoute(deps) {
4085
4134
  assertLocalCall(c, "create a backup");
4086
4135
  const password = c.req.query("password");
4087
4136
  const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4137
+ if (c.req.query("confirm") !== "true") {
4138
+ const view = buildBackupsView(deps.backups);
4139
+ const wanted = include === void 0 ? null : new Set(include);
4140
+ const entries = view.entries.filter((entry) => wanted === null || wanted.has(entry.id) || entry.workspaceId !== void 0 && wanted.has(`workspace:${entry.workspaceId}`));
4141
+ return c.json({
4142
+ apply: false,
4143
+ entries,
4144
+ includePaths: view.includePaths
4145
+ });
4146
+ }
4088
4147
  const result = await deps.backups.create({
4089
4148
  password,
4090
4149
  include
@@ -12599,6 +12658,113 @@ var init_secret_parts = __esmMin((() => {
12599
12658
  EXTRA_FIELDS = { ddns: ["ddns", "ddnsKdf"] };
12600
12659
  }));
12601
12660
  //#endregion
12661
+ //#region src/helpers/restore-lock.ts
12662
+ function readRecord(file) {
12663
+ try {
12664
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
12665
+ if (typeof parsed.pid !== "number" || typeof parsed.startedAt !== "number") return null;
12666
+ return {
12667
+ pid: parsed.pid,
12668
+ startedAt: parsed.startedAt,
12669
+ action: typeof parsed.action === "string" ? parsed.action : "restore",
12670
+ birthAt: typeof parsed.birthAt === "number" ? parsed.birthAt : null
12671
+ };
12672
+ } catch {
12673
+ return null;
12674
+ }
12675
+ }
12676
+ /**
12677
+ * Is the recorded holder still the process that took it?
12678
+ *
12679
+ * Signal 0 alone is not enough — pids are recycled, and a zombie answers it — so the process's own
12680
+ * start time is compared with the recorded one where the platform can report it. Elsewhere the pid is
12681
+ * all there is, and an alive pid is taken as alive, which errs towards "somebody is working" rather
12682
+ * than stealing a live lock.
12683
+ */
12684
+ function holderIsAlive(record) {
12685
+ try {
12686
+ process.kill(record.pid, 0);
12687
+ } catch (error) {
12688
+ return error.code === "EPERM";
12689
+ }
12690
+ const birth = processBirthSync(record.pid);
12691
+ if (birth === null) return true;
12692
+ if (record.birthAt != null) return Math.abs(birth - record.birthAt) <= BIRTH_TOLERANCE_MS;
12693
+ return birth <= record.startedAt + BIRTH_TOLERANCE_MS;
12694
+ }
12695
+ /** Wall-clock start of a pid in ms, or null where the platform cannot report one. */
12696
+ function processBirthSync(pid) {
12697
+ try {
12698
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
12699
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
12700
+ const ticks = Number.parseFloat(fields[19] ?? "");
12701
+ if (!Number.isFinite(ticks)) return null;
12702
+ const boot = /^btime (\d+)$/m.exec(fs.readFileSync("/proc/stat", "utf8"))?.[1];
12703
+ if (boot === void 0) return null;
12704
+ return Number.parseInt(boot, 10) * 1e3 + ticks / 100 * 1e3;
12705
+ } catch {
12706
+ return null;
12707
+ }
12708
+ }
12709
+ /**
12710
+ * Take the restore lock, or explain who holds it.
12711
+ *
12712
+ * `null` means somebody else is restoring. The caller reports it rather than queueing: a restore is
12713
+ * an interactive decision, and waiting on one you did not start is not what a person asked for.
12714
+ */
12715
+ function acquireRestoreLock(hhDir, action = "restore") {
12716
+ const file = path.join(hhDir, "restore.lock");
12717
+ fs.mkdirSync(hhDir, { recursive: true });
12718
+ const mine = {
12719
+ pid: process.pid,
12720
+ startedAt: Date.now(),
12721
+ action,
12722
+ birthAt: processBirthSync(process.pid)
12723
+ };
12724
+ const release = () => {
12725
+ const current = readRecord(file);
12726
+ if (current !== null && (current.pid !== mine.pid || current.startedAt !== mine.startedAt)) return;
12727
+ fs.rmSync(file, { force: true });
12728
+ };
12729
+ const existing = readRecord(file);
12730
+ if (existing !== null) {
12731
+ if (!(!holderIsAlive(existing) || Date.now() - existing.startedAt > STALE_AFTER_MS)) return { heldBy: existing };
12732
+ writeFileAtomic(file, `${JSON.stringify(mine)}\n`, { mode: 384 });
12733
+ return {
12734
+ release,
12735
+ replaced: existing
12736
+ };
12737
+ }
12738
+ try {
12739
+ fs.writeFileSync(file, `${JSON.stringify(mine)}\n`, {
12740
+ flag: "wx",
12741
+ mode: 384
12742
+ });
12743
+ } catch (error) {
12744
+ if (error.code === "EEXIST") {
12745
+ const holder = readRecord(file);
12746
+ return holder === null ? { heldBy: {
12747
+ pid: 0,
12748
+ startedAt: Date.now(),
12749
+ action: "unreadable"
12750
+ } } : { heldBy: holder };
12751
+ }
12752
+ throw error;
12753
+ }
12754
+ let released = false;
12755
+ return { release: () => {
12756
+ if (released) return;
12757
+ released = true;
12758
+ release();
12759
+ } };
12760
+ }
12761
+ var STALE_AFTER_MS, BIRTH_TOLERANCE_MS;
12762
+ var init_restore_lock = __esmMin((() => {
12763
+ init_atomic();
12764
+ STALE_AFTER_MS = 18e5;
12765
+ BIRTH_TOLERANCE_MS = 2e3;
12766
+ }));
12767
+ //#endregion
12602
12768
  //#region src/providers/archive.ts
12603
12769
  /** Recognised by content, never by the file's name. */
12604
12770
  function isZipArchive(file) {
@@ -12797,6 +12963,142 @@ var init_archive = __esmMin((() => {
12797
12963
  ];
12798
12964
  }));
12799
12965
  //#endregion
12966
+ //#region src/providers/process.ts
12967
+ /**
12968
+ * Resolves a bare command through the entry's own directory and the project's
12969
+ * `node_modules/.bin` first, so a server installed as a project dependency is
12970
+ * found even when the launcher's PATH has no pnpm-injected bin dir.
12971
+ */
12972
+ function resolveCommand(command, ...searchDirs) {
12973
+ if (command.includes("/") || command.includes("\\")) return command;
12974
+ const candidates = process.platform === "win32" && path.extname(command) === "" ? [command, ...WINDOWS_SHIM_EXTENSIONS.map((extension) => `${command}${extension}`)] : [command];
12975
+ for (const dir of searchDirs) for (const candidate of candidates) {
12976
+ const local = path.join(dir, "node_modules", ".bin", candidate);
12977
+ if (fs.existsSync(local)) return local;
12978
+ }
12979
+ return command;
12980
+ }
12981
+ /** Relative entry paths belong to the project that launched the panel. */
12982
+ function resolveCwd(cwd, base = projectDir) {
12983
+ return path.resolve(base, cwd);
12984
+ }
12985
+ /** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */
12986
+ function needsShell(command) {
12987
+ return process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
12988
+ }
12989
+ function spawnManaged(spec, options = {}) {
12990
+ return spawn(spec.command, spec.args, {
12991
+ cwd: spec.cwd,
12992
+ env: {
12993
+ ...process.env,
12994
+ ...spec.env
12995
+ },
12996
+ detached: options.detached ?? true,
12997
+ stdio: [
12998
+ "ignore",
12999
+ "pipe",
13000
+ "pipe"
13001
+ ],
13002
+ shell: needsShell(spec.command),
13003
+ windowsHide: true
13004
+ });
13005
+ }
13006
+ /** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */
13007
+ async function terminate(child, options) {
13008
+ if (child.exitCode !== null || child.signalCode !== null) return "exited";
13009
+ const exited = waitForExit$1(child, options.graceMs);
13010
+ signalChild(child, options.signal, options.killGroup);
13011
+ if (await exited) return "exited";
13012
+ signalChild(child, "SIGKILL", options.killGroup);
13013
+ await waitForExit$1(child, 2e3);
13014
+ return "force-killed";
13015
+ }
13016
+ /**
13017
+ * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and
13018
+ * `/F` is the only reliable way to stop a console process.
13019
+ */
13020
+ async function killTreeWindows(pid) {
13021
+ try {
13022
+ await execFileAsync$1("taskkill", [
13023
+ "/pid",
13024
+ String(pid),
13025
+ "/T",
13026
+ "/F"
13027
+ ], { timeout: 5e3 });
13028
+ } catch {}
13029
+ }
13030
+ function signalChild(child, signal, killGroup) {
13031
+ const pid = child.pid;
13032
+ if (pid === void 0) return;
13033
+ signalPid(pid, signal, killGroup);
13034
+ }
13035
+ function signalPid(pid, signal, killGroup) {
13036
+ if (process.platform === "win32") {
13037
+ if (killGroup) killTreeWindows(pid);
13038
+ else try {
13039
+ process.kill(pid, signal);
13040
+ } catch {}
13041
+ return;
13042
+ }
13043
+ if (killGroup) try {
13044
+ process.kill(-pid, signal);
13045
+ return;
13046
+ } catch {}
13047
+ try {
13048
+ process.kill(pid, signal);
13049
+ } catch {}
13050
+ }
13051
+ /**
13052
+ * The same shutdown a supervised child gets, for a process we adopted instead of
13053
+ * spawned: a detached successor is not our child, so it is signalled by pid (and
13054
+ * by process group when asked) and its exit is polled rather than awaited.
13055
+ *
13056
+ * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned
13057
+ * `false` for `EPERM`, so a process that was there but not ours to signal read as "exited" and
13058
+ * `'force-killed'` was returned for one still running. One predicate, one answer.
13059
+ */
13060
+ async function terminatePid(pid, options) {
13061
+ if (!isProcessAlive(pid)) return "exited";
13062
+ signalPid(pid, options.signal, options.killGroup);
13063
+ const deadline = Date.now() + Math.max(0, options.graceMs);
13064
+ while (Date.now() < deadline && isProcessAlive(pid)) await delay$1(50);
13065
+ if (!isProcessAlive(pid)) return "exited";
13066
+ signalPid(pid, "SIGKILL", options.killGroup);
13067
+ const hardDeadline = Date.now() + 2e3;
13068
+ while (Date.now() < hardDeadline && isProcessAlive(pid)) await delay$1(50);
13069
+ return "force-killed";
13070
+ }
13071
+ function delay$1(ms) {
13072
+ return new Promise((resolve) => setTimeout(resolve, ms));
13073
+ }
13074
+ function waitForExit$1(child, timeoutMs) {
13075
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
13076
+ if (timeoutMs <= 0) return Promise.resolve(false);
13077
+ return new Promise((resolve) => {
13078
+ const timer = setTimeout(() => {
13079
+ child.removeListener("exit", onExit);
13080
+ resolve(false);
13081
+ }, timeoutMs);
13082
+ function onExit() {
13083
+ clearTimeout(timer);
13084
+ resolve(true);
13085
+ }
13086
+ child.once("exit", onExit);
13087
+ });
13088
+ }
13089
+ var execFileAsync$1, WINDOWS_SHIM_EXTENSIONS;
13090
+ var init_process = __esmMin((() => {
13091
+ init_paths();
13092
+ init_port();
13093
+ execFileAsync$1 = promisify(execFile);
13094
+ WINDOWS_SHIM_EXTENSIONS = [
13095
+ ".cmd",
13096
+ ".exe",
13097
+ ".bat",
13098
+ ".ps1"
13099
+ ];
13100
+ }));
13101
+ //#endregion
12800
13102
  //#region src/helpers/backoff.ts
12801
13103
  /** Exponential backoff: base * factor^(attempt - 1), capped at maxDelayMs. */
12802
13104
  function computeBackoff(attempt, options) {
@@ -13011,164 +13313,28 @@ var init_health_check = __esmMin((() => {
13011
13313
  MAX_BODY_BYTES = 1e6;
13012
13314
  }));
13013
13315
  //#endregion
13014
- //#region src/providers/process.ts
13316
+ //#region src/services/dependencies.ts
13015
13317
  /**
13016
- * Resolves a bare command through the entry's own directory and the project's
13017
- * `node_modules/.bin` first, so a server installed as a project dependency is
13018
- * found even when the launcher's PATH has no pnpm-injected bin dir.
13318
+ * Orders servers so every dependency comes before its dependents.
13319
+ *
13320
+ * Cycles and unknown ids are ignored here — the config store reports them as
13321
+ * config errors — so this can never throw and stall supervision.
13019
13322
  */
13020
- function resolveCommand(command, ...searchDirs) {
13021
- if (command.includes("/") || command.includes("\\")) return command;
13022
- const candidates = process.platform === "win32" && path.extname(command) === "" ? [command, ...WINDOWS_SHIM_EXTENSIONS.map((extension) => `${command}${extension}`)] : [command];
13023
- for (const dir of searchDirs) for (const candidate of candidates) {
13024
- const local = path.join(dir, "node_modules", ".bin", candidate);
13025
- if (fs.existsSync(local)) return local;
13026
- }
13027
- return command;
13028
- }
13029
- /** Relative entry paths belong to the project that launched the panel. */
13030
- function resolveCwd(cwd, base = projectDir) {
13031
- return path.resolve(base, cwd);
13032
- }
13033
- /** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */
13034
- function needsShell(command) {
13035
- return process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
13036
- }
13037
- function spawnManaged(spec, options = {}) {
13038
- return spawn(spec.command, spec.args, {
13039
- cwd: spec.cwd,
13040
- env: {
13041
- ...process.env,
13042
- ...spec.env
13043
- },
13044
- detached: options.detached ?? true,
13045
- stdio: [
13046
- "ignore",
13047
- "pipe",
13048
- "pipe"
13049
- ],
13050
- shell: needsShell(spec.command),
13051
- windowsHide: true
13052
- });
13053
- }
13054
- /** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */
13055
- async function terminate(child, options) {
13056
- if (child.exitCode !== null || child.signalCode !== null) return "exited";
13057
- const exited = waitForExit$1(child, options.graceMs);
13058
- signalChild(child, options.signal, options.killGroup);
13059
- if (await exited) return "exited";
13060
- signalChild(child, "SIGKILL", options.killGroup);
13061
- await waitForExit$1(child, 2e3);
13062
- return "force-killed";
13063
- }
13064
- /**
13065
- * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and
13066
- * `/F` is the only reliable way to stop a console process.
13067
- */
13068
- async function killTreeWindows(pid) {
13069
- try {
13070
- await execFileAsync$1("taskkill", [
13071
- "/pid",
13072
- String(pid),
13073
- "/T",
13074
- "/F"
13075
- ], { timeout: 5e3 });
13076
- } catch {}
13077
- }
13078
- function signalChild(child, signal, killGroup) {
13079
- const pid = child.pid;
13080
- if (pid === void 0) return;
13081
- signalPid(pid, signal, killGroup);
13082
- }
13083
- function signalPid(pid, signal, killGroup) {
13084
- if (process.platform === "win32") {
13085
- if (killGroup) killTreeWindows(pid);
13086
- else try {
13087
- process.kill(pid, signal);
13088
- } catch {}
13089
- return;
13090
- }
13091
- if (killGroup) try {
13092
- process.kill(-pid, signal);
13093
- return;
13094
- } catch {}
13095
- try {
13096
- process.kill(pid, signal);
13097
- } catch {}
13098
- }
13099
- /**
13100
- * The same shutdown a supervised child gets, for a process we adopted instead of
13101
- * spawned: a detached successor is not our child, so it is signalled by pid (and
13102
- * by process group when asked) and its exit is polled rather than awaited.
13103
- *
13104
- * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned
13105
- * `false` for `EPERM`, so a process that was there but not ours to signal read as "exited" and
13106
- * `'force-killed'` was returned for one still running. One predicate, one answer.
13107
- */
13108
- async function terminatePid(pid, options) {
13109
- if (!isProcessAlive(pid)) return "exited";
13110
- signalPid(pid, options.signal, options.killGroup);
13111
- const deadline = Date.now() + Math.max(0, options.graceMs);
13112
- while (Date.now() < deadline && isProcessAlive(pid)) await delay$1(50);
13113
- if (!isProcessAlive(pid)) return "exited";
13114
- signalPid(pid, "SIGKILL", options.killGroup);
13115
- const hardDeadline = Date.now() + 2e3;
13116
- while (Date.now() < hardDeadline && isProcessAlive(pid)) await delay$1(50);
13117
- return "force-killed";
13118
- }
13119
- function delay$1(ms) {
13120
- return new Promise((resolve) => setTimeout(resolve, ms));
13121
- }
13122
- function waitForExit$1(child, timeoutMs) {
13123
- if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
13124
- if (timeoutMs <= 0) return Promise.resolve(false);
13125
- return new Promise((resolve) => {
13126
- const timer = setTimeout(() => {
13127
- child.removeListener("exit", onExit);
13128
- resolve(false);
13129
- }, timeoutMs);
13130
- function onExit() {
13131
- clearTimeout(timer);
13132
- resolve(true);
13133
- }
13134
- child.once("exit", onExit);
13135
- });
13136
- }
13137
- var execFileAsync$1, WINDOWS_SHIM_EXTENSIONS;
13138
- var init_process = __esmMin((() => {
13139
- init_paths();
13140
- init_port();
13141
- execFileAsync$1 = promisify(execFile);
13142
- WINDOWS_SHIM_EXTENSIONS = [
13143
- ".cmd",
13144
- ".exe",
13145
- ".bat",
13146
- ".ps1"
13147
- ];
13148
- }));
13149
- //#endregion
13150
- //#region src/services/dependencies.ts
13151
- /**
13152
- * Orders servers so every dependency comes before its dependents.
13153
- *
13154
- * Cycles and unknown ids are ignored here — the config store reports them as
13155
- * config errors — so this can never throw and stall supervision.
13156
- */
13157
- function orderByDependencies(servers) {
13158
- const byId = new Map(servers.map((server) => [server.id, server]));
13159
- const ordered = [];
13160
- const visited = /* @__PURE__ */ new Set();
13161
- const visit = (server) => {
13162
- if (visited.has(server.id)) return;
13163
- visited.add(server.id);
13164
- for (const dependency of server.dependsOn) {
13165
- const target = byId.get(dependency);
13166
- if (target && target.id !== server.id) visit(target);
13167
- }
13168
- ordered.push(server);
13169
- };
13170
- for (const server of servers) visit(server);
13171
- return ordered;
13323
+ function orderByDependencies(servers) {
13324
+ const byId = new Map(servers.map((server) => [server.id, server]));
13325
+ const ordered = [];
13326
+ const visited = /* @__PURE__ */ new Set();
13327
+ const visit = (server) => {
13328
+ if (visited.has(server.id)) return;
13329
+ visited.add(server.id);
13330
+ for (const dependency of server.dependsOn) {
13331
+ const target = byId.get(dependency);
13332
+ if (target && target.id !== server.id) visit(target);
13333
+ }
13334
+ ordered.push(server);
13335
+ };
13336
+ for (const server of servers) visit(server);
13337
+ return ordered;
13172
13338
  }
13173
13339
  /**
13174
13340
  * The transitive dependencies of a server, **deepest first** — the order they have to be started in, so
@@ -13559,6 +13725,7 @@ var init_supervisor = __esmMin((() => {
13559
13725
  init_paths();
13560
13726
  init_runtime();
13561
13727
  init_template();
13728
+ init_backup_hook();
13562
13729
  init_entry_state();
13563
13730
  init_health_check();
13564
13731
  init_identity();
@@ -13730,7 +13897,10 @@ var init_supervisor = __esmMin((() => {
13730
13897
  ok: false,
13731
13898
  error: `server "${id}" is disabled`
13732
13899
  };
13733
- if (entry.status === "running" || entry.status === "starting" || entry.starting) return { ok: true };
13900
+ if (entry.status === "running" || entry.status === "starting" || entry.starting) {
13901
+ if (entry.pendingLoad !== null) this.runPendingLoad(entry);
13902
+ return { ok: true };
13903
+ }
13734
13904
  if (entry.stopping) return {
13735
13905
  ok: false,
13736
13906
  error: `server "${id}" is stopping`
@@ -13781,11 +13951,58 @@ var init_supervisor = __esmMin((() => {
13781
13951
  error: conflict.error
13782
13952
  };
13783
13953
  if (conflict.kind === "adopt") return this.adoptEntry(entry, conflict.pid, `a detached restart of this entry is already serving port ${entry.config.port}`);
13784
- return this.spawnEntry(entry);
13954
+ const started = this.spawnEntry(entry);
13955
+ if (entry.pendingLoad !== null) this.runPendingLoad(entry);
13956
+ return started;
13785
13957
  } finally {
13786
13958
  entry.starting = false;
13787
13959
  }
13788
13960
  }
13961
+ /**
13962
+ * Run the load hook a restore left behind, once the entry is answering.
13963
+ *
13964
+ * Waits for the port to accept a connection before running it: `mongorestore` and `pg_restore`
13965
+ * connect, so running them the instant the process is spawned fails with "connection refused" —
13966
+ * which is exactly the failure that made this a staged load rather than an inline one.
13967
+ */
13968
+ async runPendingLoad(entry) {
13969
+ const dumpDir = entry.pendingLoad;
13970
+ const hook = entry.config.load;
13971
+ if (entry.loadingPending || dumpDir === null || hook === void 0 || hook === null) {
13972
+ if (hook === void 0 || hook === null) {
13973
+ entry.pendingLoad = null;
13974
+ this.persistEntryState(entry);
13975
+ }
13976
+ return;
13977
+ }
13978
+ entry.loadingPending = true;
13979
+ if (entry.config.port !== null) {
13980
+ const deadline = Date.now() + hook.timeoutMs;
13981
+ while (Date.now() < deadline && entry.status !== "stopped") {
13982
+ if (await probePort("127.0.0.1", entry.config.port)) break;
13983
+ await new Promise((resolve) => setTimeout(resolve, 500));
13984
+ }
13985
+ } else if (hook.waitMs > 0) await new Promise((resolve) => setTimeout(resolve, hook.waitMs));
13986
+ entry.pendingLoad = null;
13987
+ this.persistEntryState(entry);
13988
+ const result = await runBackupHook(hook, entry.config, dumpDir);
13989
+ entry.loadingPending = false;
13990
+ this.log(entry, "system", result.ok ? "load: the restored dump was applied" : `load: ${hookFailure("load", entry.config, result)}`);
13991
+ }
13992
+ /**
13993
+ * Mark that a restored dump is waiting to be loaded, on the entry and on disk.
13994
+ *
13995
+ * Persisted because the restore normally happens before the entry has ever started, and a panel
13996
+ * restart in between must not lose it.
13997
+ */
13998
+ stagePendingLoad(id, dumpDir) {
13999
+ const entry = this.entries.get(id);
14000
+ if (entry === void 0) return;
14001
+ entry.pendingLoad = dumpDir;
14002
+ this.persistEntryState(entry);
14003
+ this.log(entry, "system", `load: a restored dump is waiting, it runs on the next start`);
14004
+ if (entry.status === "running" && !entry.starting) this.runPendingLoad(entry);
14005
+ }
13789
14006
  async stop(id) {
13790
14007
  const entry = this.entries.get(id);
13791
14008
  if (!entry) return missingServer(id);
@@ -14112,6 +14329,8 @@ var init_supervisor = __esmMin((() => {
14112
14329
  actor: "policy",
14113
14330
  removed: false,
14114
14331
  bootstrapDone: persisted?.bootstrapDone ?? !config.bootstrap,
14332
+ pendingLoad: persisted?.pendingLoad ?? null,
14333
+ loadingPending: false,
14115
14334
  logs: new LogBuffer(config.logBufferLines),
14116
14335
  echoed: /* @__PURE__ */ new Set(),
14117
14336
  responseMs: null,
@@ -15025,6 +15244,7 @@ var init_supervisor = __esmMin((() => {
15025
15244
  restarts: entry.restarts,
15026
15245
  healthRestarts: entry.healthRestarts,
15027
15246
  bootstrapDone: entry.bootstrapDone,
15247
+ pendingLoad: entry.pendingLoad,
15028
15248
  lastPid: entry.config.persistent ? null : entry.lastChild?.pid ?? null,
15029
15249
  lastStartedAt: entry.config.persistent ? null : entry.lastChild?.startedAt ?? null
15030
15250
  });
@@ -15104,6 +15324,103 @@ var init_supervisor = __esmMin((() => {
15104
15324
  };
15105
15325
  }));
15106
15326
  //#endregion
15327
+ //#region src/providers/backup-hook.ts
15328
+ function tail(previous, chunk) {
15329
+ const next = previous + chunk;
15330
+ return next.length <= OUTPUT_TAIL_BYTES ? next : next.slice(next.length - OUTPUT_TAIL_BYTES);
15331
+ }
15332
+ /**
15333
+ * Run a hook for one entry.
15334
+ *
15335
+ * `dumpDir` is passed in rather than templated by the caller so the same absolute path can be handed
15336
+ * to `dump` and later to `load`, which is what makes the pair symmetric.
15337
+ */
15338
+ async function runBackupHook(hook, server, dumpDir, options = {}) {
15339
+ const vars = {
15340
+ ...serverTemplateVars(server),
15341
+ dumpDir
15342
+ };
15343
+ const cwd = resolveCwd(server.cwd);
15344
+ const args = resolveTemplates(hook.args, vars);
15345
+ if (options.requireDumpDir !== false) fs.mkdirSync(dumpDir, { recursive: true });
15346
+ let child;
15347
+ try {
15348
+ child = spawn(hook.command, args, {
15349
+ cwd,
15350
+ env: {
15351
+ ...process.env,
15352
+ ...resolveRecord(hook.env, vars)
15353
+ },
15354
+ stdio: [
15355
+ "ignore",
15356
+ "pipe",
15357
+ "pipe"
15358
+ ],
15359
+ windowsHide: true
15360
+ });
15361
+ } catch (error) {
15362
+ return {
15363
+ ok: false,
15364
+ code: null,
15365
+ output: "",
15366
+ error: `could not start: ${error.message}`
15367
+ };
15368
+ }
15369
+ let output = "";
15370
+ child.stdout?.on("data", (chunk) => {
15371
+ output = tail(output, chunk.toString());
15372
+ });
15373
+ child.stderr?.on("data", (chunk) => {
15374
+ output = tail(output, chunk.toString());
15375
+ });
15376
+ const outcome = await new Promise((resolve) => {
15377
+ const timer = setTimeout(() => {
15378
+ try {
15379
+ child.kill("SIGKILL");
15380
+ } catch {}
15381
+ resolve({
15382
+ code: null,
15383
+ error: `timed out after ${hook.timeoutMs}ms`
15384
+ });
15385
+ }, hook.timeoutMs);
15386
+ child.once("exit", (code) => {
15387
+ clearTimeout(timer);
15388
+ resolve({ code });
15389
+ });
15390
+ child.once("error", (error) => {
15391
+ clearTimeout(timer);
15392
+ resolve({
15393
+ code: null,
15394
+ error: error.message
15395
+ });
15396
+ });
15397
+ });
15398
+ return {
15399
+ ok: outcome.error === void 0 && outcome.code === 0,
15400
+ code: outcome.code,
15401
+ output,
15402
+ ...outcome.error === void 0 ? {} : { error: outcome.error }
15403
+ };
15404
+ }
15405
+ /**
15406
+ * The line a person reads when a hook fails.
15407
+ *
15408
+ * Names the entry, the program and the last thing it said — a bare "the backup failed" would send
15409
+ * them to the panel's log to find out which of five databases refused.
15410
+ */
15411
+ function hookFailure(action, server, result) {
15412
+ const detail = result.error ?? (result.code === null ? "no exit code" : `exit ${result.code}`);
15413
+ const said = result.output.trim().split("\n").filter((line) => line.trim().length > 0).slice(-3).join(" / ");
15414
+ return `the ${action} hook for "${server.id}" failed (${detail})${said.length === 0 ? "" : `: ${said}`}`;
15415
+ }
15416
+ var OUTPUT_TAIL_BYTES;
15417
+ var init_backup_hook = __esmMin((() => {
15418
+ init_template();
15419
+ init_process();
15420
+ init_supervisor();
15421
+ OUTPUT_TAIL_BYTES = 8192;
15422
+ }));
15423
+ //#endregion
15107
15424
  //#region src/shared/generated.ts
15108
15425
  /**
15109
15426
  * True when a path *relative to the declared root* looks generated. Accepts
@@ -15173,6 +15490,23 @@ var init_generated = __esmMin((() => {
15173
15490
  * is made of allowed characters, so segments are checked explicitly and any
15174
15491
  * entry that could resolve outside the staging directory aborts the restore.
15175
15492
  */
15493
+ /**
15494
+ * The servers an archive carries for one workspace, from its staged config.
15495
+ *
15496
+ * A restore reads this rather than `getSources()` because the live config is the *old* one at this
15497
+ * point: the files have just been overwritten, and the hooks to run belong to the machine being
15498
+ * cloned. A config that will not parse yields no servers, so the caller reports a missing hook
15499
+ * rather than throwing.
15500
+ */
15501
+ function readArchivedServers(staging, workspaceId, defaults = {}) {
15502
+ const text = readText(path.join(staging, "workspaces", workspaceId, "servers.config.json"));
15503
+ if (text === null) return [];
15504
+ try {
15505
+ return parseServersFile(JSON.parse(text), defaults).servers;
15506
+ } catch {
15507
+ return [];
15508
+ }
15509
+ }
15176
15510
  function isSafeArchiveEntry(entry) {
15177
15511
  if (entry.startsWith("/") || entry.includes("\0")) return false;
15178
15512
  const cleaned = entry.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -15271,6 +15605,35 @@ function resolveBackupPaths(servers, includePaths = [], vars) {
15271
15605
  });
15272
15606
  }
15273
15607
  /**
15608
+ * What a backup captures, from a workspace list and the panel-wide paths.
15609
+ *
15610
+ * The **one** implementation, called by the running panel and by the CLI when no panel is up. A
15611
+ * second copy is how an offline backup would quietly capture something different from an online one
15612
+ * — and the archive is the thing people restore from, so a silent difference is the worst kind.
15613
+ *
15614
+ * `runningServers` stays a callback rather than a list: the panel answers it from live supervisor
15615
+ * views, and an offline caller answers it from the nanny state on disk. It is optional because a
15616
+ * caller that cannot know leaves it out; the warning it feeds is then simply absent.
15617
+ */
15618
+ function buildBackupSources(input) {
15619
+ return {
15620
+ globalSettingsPath: input.globalSettingsPath,
15621
+ globalSecretsPath: input.globalSecretsPath,
15622
+ tlsDir: input.tlsDir,
15623
+ registryPath: input.registryPath,
15624
+ includePaths: [...input.includePaths],
15625
+ ...input.runningServers === void 0 ? {} : { runningServers: input.runningServers },
15626
+ workspaces: input.workspaces.map((workspace) => ({
15627
+ id: workspace.id,
15628
+ label: workspace.label,
15629
+ settingsPath: workspace.settingsPath,
15630
+ serversPath: workspace.serversPath,
15631
+ secretsPath: workspace.secretsPath,
15632
+ servers: workspace.servers
15633
+ }))
15634
+ };
15635
+ }
15636
+ /**
15274
15637
  * A restored settings file is accepted when this release can read it — through
15275
15638
  * the same tolerant parser the stores use, so an archive from a newer release
15276
15639
  * keeps only the keys this one understands instead of being refused outright.
@@ -15392,7 +15755,7 @@ function readableWorkspaceSettings(text) {
15392
15755
  return false;
15393
15756
  }
15394
15757
  }
15395
- var MANIFEST, REGISTRY, ALLOWED_ROOTS, SUFFIX, AUTO_PREFIX, RELOADABLE, SECRET_LABELS, BackupService;
15758
+ var MANIFEST, REGISTRY, ALLOWED_ROOTS, SUFFIX, PENDING_LOAD, AUTO_PREFIX, RELOADABLE, SECRET_LABELS, BackupService;
15396
15759
  var init_backups = __esmMin((() => {
15397
15760
  init_migrations();
15398
15761
  init_parse();
@@ -15402,9 +15765,11 @@ var init_backups = __esmMin((() => {
15402
15765
  init_env_file();
15403
15766
  init_logger();
15404
15767
  init_paths();
15768
+ init_restore_lock();
15405
15769
  init_template();
15406
15770
  init_version();
15407
15771
  init_archive();
15772
+ init_backup_hook();
15408
15773
  init_supervisor();
15409
15774
  init_contracts();
15410
15775
  init_error_message();
@@ -15415,9 +15780,11 @@ var init_backups = __esmMin((() => {
15415
15780
  ALLOWED_ROOTS = /* @__PURE__ */ new Set([
15416
15781
  "global",
15417
15782
  "workspaces",
15418
- "data"
15783
+ "data",
15784
+ "dumps"
15419
15785
  ]);
15420
15786
  SUFFIX = ".zip";
15787
+ PENDING_LOAD = "pending-load";
15421
15788
  AUTO_PREFIX = "auto";
15422
15789
  RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/;
15423
15790
  SECRET_LABELS = {
@@ -15577,6 +15944,36 @@ var init_backups = __esmMin((() => {
15577
15944
  if (capturesSecrets("global:secrets")) copySecrets("global/secrets.json", sources.globalSecretsPath, "global:secrets", "global");
15578
15945
  if (capturesGlobal("global:tls")) copy("global/tls", sources.tlsDir);
15579
15946
  this.copyInto(staging, `global/${REGISTRY}`, sources.registryPath);
15947
+ /**
15948
+ * The dump phase: give every entry with a `dump` hook the chance to produce a consistent copy.
15949
+ *
15950
+ * Before anything is copied, because the dump is the authoritative artifact — the raw data
15951
+ * directory beside it is a convenience, and a dump that failed must not leave an archive that
15952
+ * looks complete. The output lands in `dumps/<workspace>/<server>/`, which the restore side
15953
+ * fills again at the same path, so `{dumpDir}` means the same thing in both directions.
15954
+ */
15955
+ const dumped = [];
15956
+ for (const workspace of sources.workspaces) for (const server of workspace.servers) {
15957
+ const hook = server.dump;
15958
+ if (hook === void 0 || hook === null) continue;
15959
+ if (wanted !== null && !wanted.has(`workspace:${workspace.id}`) && !wanted.has(`workspace:${workspace.id}:dump:${server.id}`)) continue;
15960
+ const relative = path.join("dumps", workspace.id, server.id);
15961
+ const result = await runBackupHook(hook, server, path.join(staging, relative));
15962
+ if (!result.ok) {
15963
+ fs.rmSync(staging, {
15964
+ recursive: true,
15965
+ force: true
15966
+ });
15967
+ return {
15968
+ ok: false,
15969
+ error: hookFailure("dump", server, result)
15970
+ };
15971
+ }
15972
+ dumped.push({
15973
+ workspaceId: workspace.id,
15974
+ serverId: server.id
15975
+ });
15976
+ }
15580
15977
  const data = [];
15581
15978
  for (const workspace of sources.workspaces) {
15582
15979
  const root = `workspaces/${workspace.id}`;
@@ -15615,7 +16012,8 @@ var init_backups = __esmMin((() => {
15615
16012
  hostname: os.hostname(),
15616
16013
  writtenBy: appVersion(),
15617
16014
  schema: 2,
15618
- data
16015
+ data,
16016
+ ...dumped.length === 0 ? {} : { dumps: dumped }
15619
16017
  };
15620
16018
  fs.writeFileSync(path.join(staging, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
15621
16019
  await createZip(staging, destination, password === null ? {} : { password });
@@ -15664,6 +16062,18 @@ var init_backups = __esmMin((() => {
15664
16062
  * archive's manifest alone.
15665
16063
  */
15666
16064
  async restore(archivePath, options) {
16065
+ const lock = options.confirm ? acquireRestoreLock(this.options.dataRoot) : null;
16066
+ if (lock !== null && "heldBy" in lock) throw new DetailedError(`another restore is running (pid ${lock.heldBy.pid}, since ${new Date(lock.heldBy.startedAt).toISOString()}) — wait for it, or remove ${path.join(this.options.dataRoot, "restore.lock")} if it is stale`, {
16067
+ statusCode: 409,
16068
+ code: "RESTORE_IN_PROGRESS"
16069
+ });
16070
+ try {
16071
+ return await this.applyRestore(archivePath, options);
16072
+ } finally {
16073
+ if (lock !== null && !("heldBy" in lock)) lock.release();
16074
+ }
16075
+ }
16076
+ async applyRestore(archivePath, options) {
15667
16077
  const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
15668
16078
  const plan = {
15669
16079
  dryRun: !options.confirm,
@@ -16029,6 +16439,18 @@ var init_backups = __esmMin((() => {
16029
16439
  * apply closure so a dry run reports the same list the apply would.
16030
16440
  */
16031
16441
  const runningOwners = new Set((sources.runningServers?.() ?? []).map((entry) => `${entry.workspaceId}:${entry.serverId}`));
16442
+ for (const dump of manifest.dumps ?? []) {
16443
+ const from = path.join(staging, "dumps", dump.workspaceId, dump.serverId);
16444
+ if (!fs.existsSync(from)) continue;
16445
+ addItem({
16446
+ id: `workspace:${dump.workspaceId}:dump:${dump.serverId}`,
16447
+ label: `dump:${dump.serverId}`,
16448
+ kind: "data",
16449
+ restorable: true,
16450
+ workspaceId: dump.workspaceId,
16451
+ note: null
16452
+ }, () => {});
16453
+ }
16032
16454
  const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : [];
16033
16455
  for (const entry of archivedEntries) {
16034
16456
  const archivedPath = typeof entry.path === "string" ? entry.path : "";
@@ -16108,6 +16530,49 @@ var init_backups = __esmMin((() => {
16108
16530
  });
16109
16531
  plan.createdWorkspaces.push(workspace.id);
16110
16532
  }
16533
+ /**
16534
+ * The load phase: let each restored entry put its own dump back.
16535
+ *
16536
+ * After the files landed and before the panel reloads, so the engine reads a config this
16537
+ * release has just written rather than the one it replaced. Only the entries the archive
16538
+ * actually brought a dump for — an archive taken before the hook existed has none, and running
16539
+ * `mongorestore` on a directory that is not there fails the whole restore for no reason.
16540
+ */
16541
+ const archivedDumps = manifest.dumps ?? [];
16542
+ const pendingLoads = [];
16543
+ for (const entry of archivedDumps) {
16544
+ if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${entry.workspaceId}:`))) continue;
16545
+ if (!actions.has(`workspace:${entry.workspaceId}:dump:${entry.serverId}`) && !actions.has(`workspace:${entry.workspaceId}`)) continue;
16546
+ const server = readArchivedServers(staging, entry.workspaceId).find((candidate) => candidate.id === entry.serverId);
16547
+ if (server?.load === void 0 || server.load === null) {
16548
+ plan.skipped.push(`the dump for "${entry.serverId}" was restored but this entry has no load hook`);
16549
+ continue;
16550
+ }
16551
+ const dumpDir = path.join(staging, "dumps", entry.workspaceId, entry.serverId);
16552
+ if (!fs.existsSync(dumpDir)) {
16553
+ plan.skipped.push(`the dump for "${entry.serverId}" is missing from the archive`);
16554
+ continue;
16555
+ }
16556
+ const staged = path.join(this.options.dataRoot, PENDING_LOAD, entry.workspaceId, entry.serverId);
16557
+ fs.mkdirSync(path.dirname(staged), { recursive: true });
16558
+ fs.cpSync(dumpDir, staged, {
16559
+ recursive: true,
16560
+ force: true
16561
+ });
16562
+ pendingLoads.push({
16563
+ workspaceId: entry.workspaceId,
16564
+ serverId: entry.serverId,
16565
+ staged
16566
+ });
16567
+ plan.hooks = [...plan.hooks ?? [], {
16568
+ serverId: entry.serverId,
16569
+ workspaceId: entry.workspaceId,
16570
+ action: "load",
16571
+ ok: true,
16572
+ output: "staged — runs when this entry next starts"
16573
+ }];
16574
+ }
16575
+ for (const load of pendingLoads) this.options.onLoadPending?.(load.workspaceId, load.serverId, load.staged);
16111
16576
  if (this.options.onRestored !== void 0 && [...actions.keys()].some((id) => RELOADABLE.test(id))) {
16112
16577
  plan.reloaded = true;
16113
16578
  this.options.onRestored();
@@ -17992,6 +18457,8 @@ var init_panel = __esmMin((() => {
17992
18457
  init_paths();
17993
18458
  init_version();
17994
18459
  init_ddns$2();
18460
+ init_entry_state();
18461
+ init_backups();
17995
18462
  init_config_watch();
17996
18463
  init_ddns();
17997
18464
  init_history();
@@ -18110,7 +18577,7 @@ var init_panel = __esmMin((() => {
18110
18577
  }
18111
18578
  /** The sources a backup archive is built from and restored into. */
18112
18579
  backupSources() {
18113
- return {
18580
+ return buildBackupSources({
18114
18581
  globalSettingsPath: this.options.settings.path,
18115
18582
  globalSecretsPath: this.options.secrets.path,
18116
18583
  tlsDir: this.options.tls.directory,
@@ -18128,7 +18595,7 @@ var init_panel = __esmMin((() => {
18128
18595
  secretsPath: runtime.secrets.path,
18129
18596
  servers: runtime.store.servers
18130
18597
  }))
18131
- };
18598
+ });
18132
18599
  }
18133
18600
  create(input) {
18134
18601
  const workspace = this.options.registry.create(input);
@@ -18201,6 +18668,25 @@ var init_panel = __esmMin((() => {
18201
18668
  * an archive brought therefore waited for a panel restart — which is why the start of
18202
18669
  * newly appeared autostart entries belongs here, the one place that knows what was new.
18203
18670
  */
18671
+ /**
18672
+ * Record a dump a restore staged, so this entry's next start loads it.
18673
+ *
18674
+ * Written to the entry's own state file rather than memory: the restore usually happens before the
18675
+ * entry has ever started, and a panel restart between the two must not lose the load.
18676
+ */
18677
+ stagePendingLoad(workspaceId, serverId, dumpDir) {
18678
+ const stateDir = workspaceStateDir(workspaceId);
18679
+ fs.mkdirSync(stateDir, { recursive: true });
18680
+ const statePath = entryStatePath(stateDir, serverId);
18681
+ writeEntryState(statePath, {
18682
+ ...readEntryState(statePath) ?? {
18683
+ restarts: 0,
18684
+ bootstrapDone: false
18685
+ },
18686
+ pendingLoad: dumpDir
18687
+ });
18688
+ this.runtimes.get(workspaceId)?.supervisor.stagePendingLoad(serverId, dumpDir);
18689
+ }
18204
18690
  reloadAll() {
18205
18691
  this.options.settings.load();
18206
18692
  for (const runtime of this.workspaces()) {
@@ -18244,7 +18730,7 @@ var init_panel = __esmMin((() => {
18244
18730
  createRuntime(workspace) {
18245
18731
  const id = workspace.id;
18246
18732
  fs.mkdirSync(workspaceDir(id), { recursive: true });
18247
- const store = new WorkspaceStore(id, workspaceSettingsPath(id), id === this.options.registry.defaultId && this.options.defaultServersPath !== void 0 ? this.options.defaultServersPath : workspaceServersPath(id));
18733
+ const store = new WorkspaceStore(id, workspaceSettingsPath(id), workspaceServersPath(id));
18248
18734
  store.load();
18249
18735
  store.writeJsonSchema();
18250
18736
  const secrets = new SecretsStore(workspaceSecretsPath(id), void 0, "workspace");
@@ -19197,7 +19683,7 @@ async function runControlPlane(options) {
19197
19683
  });
19198
19684
  if (trustWarning !== null) logger.warn(trustWarning);
19199
19685
  if (options.printConfig) {
19200
- printEffectiveConfig(settings, registry, options);
19686
+ printEffectiveConfig(settings, registry);
19201
19687
  return;
19202
19688
  }
19203
19689
  if (!await isPortFree(intended.port)) {
@@ -19270,7 +19756,8 @@ async function runControlPlane(options) {
19270
19756
  getConfig: () => settings.backups,
19271
19757
  getSources: () => panel.backupSources(),
19272
19758
  ensureWorkspace: (input) => panel?.ensureWorkspace(input),
19273
- onRestored: () => panel?.reloadAll()
19759
+ onRestored: () => panel?.reloadAll(),
19760
+ onLoadPending: (workspaceId, serverId, dumpDir) => panel?.stagePendingLoad(workspaceId, serverId, dumpDir)
19274
19761
  });
19275
19762
  panel = new PanelService({
19276
19763
  registry,
@@ -19284,8 +19771,7 @@ async function runControlPlane(options) {
19284
19771
  hub,
19285
19772
  control: () => controlServer.endpoint,
19286
19773
  proxy: () => proxy,
19287
- autostart: options.autostart,
19288
- ...options.configPath === void 0 ? {} : { defaultServersPath: options.configPath }
19774
+ autostart: options.autostart
19289
19775
  });
19290
19776
  for (const workspace of panel.workspaces()) {
19291
19777
  const store = workspace.store;
@@ -19389,7 +19875,7 @@ async function runControlPlane(options) {
19389
19875
  process.on("SIGTERM", () => onSignal("SIGTERM"));
19390
19876
  }
19391
19877
  /** `--print-config`: the global settings and every workspace, without starting anything. */
19392
- function printEffectiveConfig(settings, registry, options) {
19878
+ function printEffectiveConfig(settings, registry) {
19393
19879
  const workspaces = registry.all().map((workspace) => {
19394
19880
  const dir = path.join(hhDir, workspace.id);
19395
19881
  const read = (name) => {
@@ -19399,18 +19885,11 @@ function printEffectiveConfig(settings, registry, options) {
19399
19885
  return null;
19400
19886
  }
19401
19887
  };
19402
- const serversFile = workspace.id === registry.defaultId && options.configPath !== void 0 ? options.configPath : path.join(dir, "servers.config.json");
19403
- let servers = null;
19404
- try {
19405
- servers = JSON.parse(fs.readFileSync(serversFile, "utf8"));
19406
- } catch {
19407
- servers = null;
19408
- }
19409
19888
  return {
19410
19889
  id: workspace.id,
19411
19890
  label: workspace.label,
19412
19891
  settings: read("settings.json"),
19413
- servers
19892
+ servers: read("servers.config.json")
19414
19893
  };
19415
19894
  });
19416
19895
  process.stdout.write(`${JSON.stringify({
@@ -19466,7 +19945,6 @@ function toUpFlags(args) {
19466
19945
  if (!Number.isInteger(port) || port <= 0 || port > 65535) fail(`invalid port: ${args.port}`);
19467
19946
  }
19468
19947
  return {
19469
- config: args.config,
19470
19948
  port,
19471
19949
  host: args.host,
19472
19950
  autostart: args.autostart !== false,
@@ -19479,7 +19957,6 @@ async function runUp(flags, entry) {
19479
19957
  if (flags.foreground || flags.printConfig) {
19480
19958
  const { runControlPlane } = await Promise.resolve().then(() => (init_src(), src_exports));
19481
19959
  await runControlPlane({
19482
- configPath: flags.config,
19483
19960
  port: flags.port,
19484
19961
  host: flags.host,
19485
19962
  autostart: flags.autostart,
@@ -19565,11 +20042,6 @@ var init_up = __esmMin((() => {
19565
20042
  init_version();
19566
20043
  DEFAULT_PORT$1 = 3999;
19567
20044
  upArgs = {
19568
- config: {
19569
- type: "string",
19570
- alias: "c",
19571
- description: "the default workspace's servers config (default: <state>/.hh/default/servers.config.json)"
19572
- },
19573
20045
  port: {
19574
20046
  type: "string",
19575
20047
  alias: "p",
@@ -20174,7 +20646,7 @@ var migrate_exports = /* @__PURE__ */ __exportAll({
20174
20646
  runMigrate: () => runMigrate
20175
20647
  });
20176
20648
  /** Every file a migration may have to stamp, and how this release reads it. */
20177
- function targets(configOverride) {
20649
+ function targets() {
20178
20650
  const list = [{
20179
20651
  file: globalSettingsPath,
20180
20652
  label: "global settings",
@@ -20190,7 +20662,7 @@ function targets(configOverride) {
20190
20662
  validate: (raw) => parseWorkspaceSettings(raw).errors[0] ?? null
20191
20663
  });
20192
20664
  list.push({
20193
- file: workspace.id === registry.defaultId && configOverride !== void 0 ? configOverride : workspaceServersPath(workspace.id),
20665
+ file: workspaceServersPath(workspace.id),
20194
20666
  label: `workspace ${workspace.id} servers`,
20195
20667
  validate: (raw) => {
20196
20668
  let defaults = {};
@@ -20206,8 +20678,8 @@ function targets(configOverride) {
20206
20678
  }
20207
20679
  return list;
20208
20680
  }
20209
- async function runMigrate(config, dryRun, yes) {
20210
- const existing = targets(config).filter((target) => fs.existsSync(target.file));
20681
+ async function runMigrate(dryRun, yes) {
20682
+ const existing = targets().filter((target) => fs.existsSync(target.file));
20211
20683
  if (existing.length === 0) fail(`no home-hosted state to migrate — nothing at ${globalSettingsPath} or any workspace`);
20212
20684
  const consented = yes || (process.env.HHOSTED_MIGRATE ?? "").toLowerCase() === "allow";
20213
20685
  let stampOnly = 0;
@@ -20280,11 +20752,6 @@ var init_migrate = __esmMin((() => {
20280
20752
  init_error_message();
20281
20753
  init_shape();
20282
20754
  migrateArgs = {
20283
- config: {
20284
- type: "string",
20285
- alias: "c",
20286
- description: "the default workspace's servers config (default: <state>/.hh/default/servers.config.json)"
20287
- },
20288
20755
  dryRun: {
20289
20756
  type: "boolean",
20290
20757
  description: "print what would change, write nothing"
@@ -20299,7 +20766,7 @@ var init_migrate = __esmMin((() => {
20299
20766
  meta: { name: "migrate" },
20300
20767
  args: migrateArgs,
20301
20768
  run: async ({ args }) => {
20302
- await runMigrate(args.config, args.dryRun === true, args.yes === true);
20769
+ await runMigrate(args.dryRun === true, args.yes === true);
20303
20770
  }
20304
20771
  });
20305
20772
  }));
@@ -20971,6 +21438,149 @@ var init_ui_revert = __esmMin((() => {
20971
21438
  });
20972
21439
  }));
20973
21440
  //#endregion
21441
+ //#region src/cli/backup-offline.ts
21442
+ /**
21443
+ * A backup service for a host whose panel is **not running**.
21444
+ *
21445
+ * `backup` used to need the daemon because the service is built inside it, so backing up or
21446
+ * restoring meant leaving the panel up — the opposite of what someone migrating a machine wants.
21447
+ * Nothing in the service needs the daemon: every source is a file, and the one live fact it wants
21448
+ * (which entries are running) is on disk as the nanny state each entry writes.
21449
+ *
21450
+ * This builds the same sources the panel does, through the same `buildBackupSources`, so an offline
21451
+ * archive cannot differ from an online one. `runningServers` is answered from `.state/*.json` rather
21452
+ * than from supervisor views: a *persistent* entry keeps running when the panel stops, so "no panel"
21453
+ * does not mean "nothing is running", and the restore warning has to keep telling the truth.
21454
+ */
21455
+ /** The workspace ids this host knows, from the registry on disk. */
21456
+ function workspaceIds(registry) {
21457
+ return registry.all().map((workspace) => ({
21458
+ id: workspace.id,
21459
+ label: workspace.label
21460
+ }));
21461
+ }
21462
+ /**
21463
+ * Entries whose nanny is alive right now, read from the state files they rewrite.
21464
+ *
21465
+ * Every path comes from `hhDir`, never from the module-level helpers: those resolve from this
21466
+ * process's own `HHOSTED_HOME`, so a caller passing `--home` elsewhere would read a different host's
21467
+ * state — which is exactly how a test came to depend on the developer's real `~/.home-hosted`.
21468
+ */
21469
+ function runningFromDisk(hhDir, ids) {
21470
+ const running = [];
21471
+ for (const workspaceId of ids) {
21472
+ const stateDir = path.join(hhDir, workspaceId, ".state");
21473
+ let names;
21474
+ try {
21475
+ names = fs.readdirSync(stateDir);
21476
+ } catch {
21477
+ continue;
21478
+ }
21479
+ for (const name of names) {
21480
+ if (!name.endsWith(".json") || name.endsWith(".spec.json") || name.endsWith(".tmp")) continue;
21481
+ const serverId = name.replace(/\.run\.json$|\.json$/, "");
21482
+ if (serverId.length === 0) continue;
21483
+ const state = readNannyState(path.join(stateDir, name));
21484
+ if (state === null) continue;
21485
+ if (Date.now() - state.heartbeatAt <= 3e4) running.push({
21486
+ workspaceId,
21487
+ serverId
21488
+ });
21489
+ }
21490
+ }
21491
+ return running;
21492
+ }
21493
+ /**
21494
+ * Build the service against this host's files.
21495
+ *
21496
+ * `ensureWorkspace` and `onRestored` are the two panel hooks, and both are deliberately absent: with
21497
+ * no daemon there is nothing to reload, and a restore that brings a workspace this host lacks leaves
21498
+ * it on disk for the next `up` to pick up. The registry is written by the service itself, which is
21499
+ * what makes that work.
21500
+ */
21501
+ function createOfflineBackup(options = {}) {
21502
+ const hhDir$1 = options.hhDir ?? hhDir;
21503
+ const settingsPath = options.settingsPath ?? globalSettingsPath;
21504
+ const registryPath = path.join(hhDir$1, path.basename(workspacesPath));
21505
+ const settings = new GlobalSettingsStore(settingsPath);
21506
+ settings.load();
21507
+ const registry = new WorkspaceRegistry(registryPath);
21508
+ registry.load();
21509
+ const workspaces = workspaceIds(registry);
21510
+ const ids = workspaces.map((workspace) => workspace.id);
21511
+ const loaded = workspaces.map((workspace) => {
21512
+ const dir = path.join(hhDir$1, workspace.id);
21513
+ const settingsPath = path.join(dir, "settings.json");
21514
+ const serversPath = path.join(dir, "servers.config.json");
21515
+ const secretsPath = path.join(dir, ".secrets.json");
21516
+ const store = new WorkspaceStore(workspace.id, settingsPath, serversPath);
21517
+ store.load();
21518
+ return {
21519
+ id: workspace.id,
21520
+ label: workspace.label,
21521
+ settingsPath,
21522
+ serversPath,
21523
+ secretsPath,
21524
+ servers: store.servers
21525
+ };
21526
+ });
21527
+ return {
21528
+ service: new BackupService({
21529
+ dataRoot: hhDir$1,
21530
+ getConfig: () => settings.backups,
21531
+ /**
21532
+ * Register a workspace the archive brought.
21533
+ *
21534
+ * A panel-only hook in the running case, because the panel creates the runtime itself. With no
21535
+ * panel there is nobody to do it, so the registry is written here — otherwise a restored
21536
+ * workspace's files land on disk unreachable, and the next `up` never looks at them.
21537
+ */
21538
+ /**
21539
+ * Record the staged dump so the entry's next `up` loads it.
21540
+ *
21541
+ * Nothing is running to hold it in memory, so this is the only path that matters offline: the
21542
+ * panel is started afterwards, reads the entry state, and runs the hook.
21543
+ */
21544
+ onLoadPending: (workspaceId, serverId, dumpDir) => {
21545
+ const dir = path.join(hhDir$1, workspaceId, ".state");
21546
+ fs.mkdirSync(dir, { recursive: true });
21547
+ const statePath = entryStatePath(dir, serverId);
21548
+ writeEntryState(statePath, {
21549
+ ...readEntryState(statePath) ?? {
21550
+ restarts: 0,
21551
+ bootstrapDone: false
21552
+ },
21553
+ pendingLoad: dumpDir
21554
+ });
21555
+ },
21556
+ ensureWorkspace: (input) => {
21557
+ if (registry.has(input.id)) return;
21558
+ registry.create(input);
21559
+ },
21560
+ getSources: () => buildBackupSources({
21561
+ globalSettingsPath: settings.path,
21562
+ globalSecretsPath: path.join(hhDir$1, path.basename(globalSecretsPath)),
21563
+ tlsDir: path.join(hhDir$1, path.basename(tlsDir)),
21564
+ registryPath,
21565
+ includePaths: settings.backups.includePaths,
21566
+ runningServers: () => runningFromDisk(hhDir$1, ids),
21567
+ workspaces: loaded
21568
+ })
21569
+ }),
21570
+ workspaceIds: ids,
21571
+ runningNow: () => runningFromDisk(hhDir$1, ids)
21572
+ };
21573
+ }
21574
+ var init_backup_offline = __esmMin((() => {
21575
+ init_settings$1();
21576
+ init_store();
21577
+ init_workspaces();
21578
+ init_paths();
21579
+ init_entry_state();
21580
+ init_nanny$2();
21581
+ init_backups();
21582
+ }));
21583
+ //#endregion
20974
21584
  //#region src/cli/backup.ts
20975
21585
  var backup_exports = /* @__PURE__ */ __exportAll({
20976
21586
  backupCommand: () => backupCommand,
@@ -20989,74 +21599,339 @@ async function livePanel() {
20989
21599
  const runtime = daemon.readRuntime();
20990
21600
  if (runtime === null || !await daemon.runtimeIsAlive(runtime)) {
20991
21601
  if (runtime !== null && await daemon.runtimeIsGone(runtime)) daemon.clearRuntime();
20992
- fail(`home-hosted is not running — start it with \`${invocation()} up\`, then run this again`);
21602
+ return null;
20993
21603
  }
20994
21604
  return Object.assign(runtime, { request: daemon.requestControl });
20995
21605
  }
21606
+ /**
21607
+ * Whether to talk to a panel or work on the files directly.
21608
+ *
21609
+ * Both paths run the same service, so the only question is who owns the state: a live panel is the
21610
+ * authority on what is running, and a stopped one has no opinion to disagree with.
21611
+ */
21612
+ async function usesPanel() {
21613
+ const daemon = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
21614
+ const runtime = daemon.readRuntime();
21615
+ if (runtime === null || !await daemon.runtimeIsAlive(runtime)) return false;
21616
+ return (await daemon.probeRuntime(runtime)).reachable;
21617
+ }
21618
+ /**
21619
+ * The offline service.
21620
+ *
21621
+ * It reads the same files the panel does — every workspace's `settings.json` and
21622
+ * `servers.config.json` under the state root — so an archive taken with the panel down holds what a
21623
+ * running one would have captured.
21624
+ */
21625
+ async function offlineBackup() {
21626
+ return createOfflineBackup();
21627
+ }
20996
21628
  /** Turn a non-200 control answer into the panel's own message, or the status. */
20997
21629
  function refusal(answer) {
20998
21630
  const body = answer.body;
20999
21631
  if (body?.message !== void 0) fail(body.message);
21000
21632
  fail(`the panel answered ${answer.status}`);
21001
21633
  }
21634
+ /**
21635
+ * The flag combination, as far as it can be judged without asking the panel.
21636
+ *
21637
+ * `null` means "neither flag", which only the caller can resolve — it lists the available ids, and
21638
+ * that needs a panel. Every other case is decided here, before any lookup, so a typo is refused
21639
+ * whether or not anything is running.
21640
+ */
21641
+ function parseScope(all, raw) {
21642
+ if (all && raw !== void 0) fail("--include and --all are exclusive — pass one or the other");
21643
+ if (all) return { kind: "all" };
21644
+ if (raw === void 0) return null;
21645
+ const ids = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
21646
+ if (ids.length === 0) fail("--include is empty — name the ids to act on, or pass --all for everything");
21647
+ return {
21648
+ kind: "include",
21649
+ ids
21650
+ };
21651
+ }
21652
+ /**
21653
+ * Neither flag given. Refused outright — the ids are a *bonus*, not the reason.
21654
+ *
21655
+ * The refusal must not depend on a panel being up: a mistyped command deserves the flag error, not
21656
+ * "home-hosted is not running". So the list is best-effort, and a failure to produce it is silent.
21657
+ */
21658
+ async function refuseWithoutScope(action, suffix) {
21659
+ const ids = await availableIdsFor(action, suffix).catch(() => []);
21660
+ fail(`name what to act on — pass --include <ids> or --all${ids.length === 0 ? "" : `\n\navailable:\n${ids.map((id) => ` ${id}`).join("\n")}`}`);
21661
+ }
21662
+ /**
21663
+ * The ids this action could be scoped to.
21664
+ *
21665
+ * `create` asks what the entries declare; `restore` asks what the archive holds. Both come from the
21666
+ * panel, so the list in a refusal is the real one rather than a hardcoded guess. A panel that cannot
21667
+ * be reached yields no ids — the refusal still fires, it just cannot enumerate.
21668
+ */
21669
+ async function availableIdsFor(action, suffix) {
21670
+ const daemon = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
21671
+ const runtime = daemon.readRuntime();
21672
+ if (runtime === null) return [];
21673
+ const path = action === "create" ? "/_hh/backups" : "/_hh/backups/restore";
21674
+ const answer = await daemon.requestControl(runtime, `${path}${suffix}`, 12e4);
21675
+ if (answer === null || answer.status !== 200) return [];
21676
+ const body = answer.body;
21677
+ return ((action === "create" ? body?.entries : body?.items) ?? []).map((item) => item.id).filter((id) => typeof id === "string");
21678
+ }
21679
+ /** `?a=b`, or `''`. */
21680
+ function suffixOf(query) {
21681
+ return query.size === 0 ? "" : `?${query.toString()}`;
21682
+ }
21683
+ /** Appends one query parameter, keeping the `?`/`&` right. */
21684
+ function withParam(suffix, key, value) {
21685
+ return `${suffix}${suffix === "" ? "?" : "&"}${key}=${encodeURIComponent(value)}`;
21686
+ }
21687
+ /**
21688
+ * Ask before writing.
21689
+ *
21690
+ * A session that cannot be asked gets the plan and a one-line instruction — not a silent write, and
21691
+ * not a silent no-op that looks like one.
21692
+ */
21693
+ async function consent(question) {
21694
+ if (process.stdin.isTTY !== true) {
21695
+ process.stdout.write("\nnot applied — this session cannot ask. Re-run with `--confirm` to apply.\n");
21696
+ return false;
21697
+ }
21698
+ const answer = await prompt(`${question} [y/N] `);
21699
+ if (/^yes$|^y$/i.test(answer.trim())) {
21700
+ process.stdout.write("\n");
21701
+ return true;
21702
+ }
21703
+ process.stdout.write("cancelled — nothing was written\n");
21704
+ return false;
21705
+ }
21706
+ /**
21707
+ * Run against the panel when one is up, and against the files when it is not.
21708
+ *
21709
+ * Both run the same `BackupService`, so the archive cannot differ; only the authority on what is
21710
+ * running changes. A stopped panel is exactly when someone wants to back up or restore — the services
21711
+ * are down because they stopped them on purpose.
21712
+ */
21002
21713
  async function runBackupList(json) {
21003
- const runtime = await livePanel();
21004
- const answer = await runtime.request(runtime, "/_hh/backups", 3e4, "GET");
21005
- if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21006
- if (answer.status !== 200) refusal(answer);
21007
- const view = answer.body;
21714
+ if (await usesPanel()) {
21715
+ const runtime = await livePanel();
21716
+ if (runtime !== null) {
21717
+ const answer = await runtime.request(runtime, "/_hh/backups", 3e4, "GET");
21718
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21719
+ if (answer.status !== 200) refusal(answer);
21720
+ printList(answer.body, json);
21721
+ return;
21722
+ }
21723
+ }
21724
+ const { service } = await offlineBackup();
21725
+ await service.warm();
21726
+ printList(service.view(), json);
21727
+ }
21728
+ function printList(view, json) {
21008
21729
  const files = view?.files ?? [];
21009
21730
  if (json) {
21010
21731
  process.stdout.write(`${JSON.stringify(view, null, 2)}\n`);
21011
21732
  return;
21012
21733
  }
21013
21734
  if (files.length === 0) {
21014
- process.stdout.write(`no backups yet — \`${invocation()} backup create\` takes one\n`);
21735
+ process.stdout.write(`no backups yet — \`${invocation()} backup create --all\` takes one\n`);
21015
21736
  return;
21016
21737
  }
21017
21738
  const noun = files.length === 1 ? "archive" : "archives";
21018
21739
  process.stdout.write(`${bold(String(files.length))} ${noun}${view?.dir === void 0 ? "" : ` in ${dim(view.dir)}`}\n`);
21019
21740
  for (const file of files) {
21020
- const when = file.createdAt === null ? "" : new Date(file.createdAt).toISOString().replace("T", " ").slice(0, 16);
21741
+ const when = file.createdAt == null ? "" : new Date(file.createdAt).toISOString().replace("T", " ").slice(0, 16);
21021
21742
  process.stdout.write(` ${file.name.padEnd(36)} ${human(file.sizeBytes).padStart(8)} ${dim(when)}${file.automatic ? dim(" auto") : ""}\n`);
21022
21743
  }
21023
21744
  }
21745
+ /**
21746
+ * Name the entries still running, without blocking.
21747
+ *
21748
+ * A **persistent** entry keeps running while the panel is stopped, so "panel off" is not "services
21749
+ * off" — and its data being captured mid-write is worth knowing before it is relied on. Warned rather
21750
+ * than refused: the user may know, and the panel's own backup has always proceeded here.
21751
+ */
21752
+ function warnRunning(entries) {
21753
+ if (entries.length === 0) return;
21754
+ const named = entries.map((entry) => entry.serverId ?? entry.id ?? "").filter((name) => name.length > 0);
21755
+ const isOne = named.length === 1;
21756
+ process.stdout.write(`${dim(`! ${named.length} entr${isOne ? "y is" : "ies are"} still running (${named.join(", ")}) — its data may be captured mid-write`)}\n`);
21757
+ }
21024
21758
  async function runBackupCreate(options) {
21025
- const runtime = await livePanel();
21026
- const query = new URLSearchParams();
21027
- if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21028
- if (options.include !== void 0 && options.include.length > 0) query.set("include", options.include.join(","));
21029
- const suffix = query.size === 0 ? "" : `?${query.toString()}`;
21030
- const answer = await runtime.request(runtime, `/_hh/backups${suffix}`, 6e5);
21031
- if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21032
- if (answer.status !== 200) refusal(answer);
21033
- const file = answer.body?.file;
21034
- if (file === void 0) fail("the panel reported success but named no archive");
21759
+ const scope = options.scope;
21760
+ const online = await usesPanel();
21761
+ const entries = await (async () => {
21762
+ if (online) {
21763
+ const runtime = await livePanel();
21764
+ if (runtime !== null) {
21765
+ const answer = await runtime.request(runtime, "/_hh/backups", 12e4);
21766
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21767
+ if (answer.status !== 200) refusal(answer);
21768
+ return answer.body?.entries ?? [];
21769
+ }
21770
+ }
21771
+ const { service } = await offlineBackup();
21772
+ await service.warm();
21773
+ return service.view().entries;
21774
+ })();
21775
+ const wanted = scope.kind === "all" ? entries : entries.filter((entry) => scope.ids.some((id) => entry.id === id || id.startsWith(`${entry.id}:`)));
21776
+ if (!options.confirm) {
21777
+ if (options.json) {
21778
+ process.stdout.write(`${JSON.stringify({
21779
+ action: "create",
21780
+ apply: false,
21781
+ entries: wanted
21782
+ }, null, 2)}\n`);
21783
+ return;
21784
+ }
21785
+ process.stdout.write(`${bold("Plan")} — what a backup would capture; nothing has been written yet\n`);
21786
+ for (const entry of wanted) {
21787
+ process.stdout.write(` ${String(entry.kind ?? "entry").padEnd(10)} ${entry.id}${entry.note == null ? "" : ` ${dim(`(${entry.note})`)}`}\n`);
21788
+ for (const item of entry.items ?? []) process.stdout.write(` ${dim("-")} ${item.id}\n`);
21789
+ }
21790
+ if (wanted.length === 0) {
21791
+ process.stdout.write(" (nothing matched — check --include, or what the entries declare)\n");
21792
+ return;
21793
+ }
21794
+ warnRunning(await runningEntries());
21795
+ if (!await consent("Take this backup?")) return;
21796
+ }
21797
+ const include = scope.kind === "include" ? scope.ids : void 0;
21798
+ const file = (await (async () => {
21799
+ if (online) {
21800
+ const runtime = await livePanel();
21801
+ if (runtime !== null) {
21802
+ const query = new URLSearchParams();
21803
+ if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21804
+ if (include !== void 0) query.set("include", include.join(","));
21805
+ const answer = await runtime.request(runtime, `/_hh/backups${withParam(suffixOf(query), "confirm", "true")}`, 6e5);
21806
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21807
+ if (answer.status !== 200) refusal(answer);
21808
+ return answer.body;
21809
+ }
21810
+ }
21811
+ const { service } = await offlineBackup();
21812
+ await service.warm();
21813
+ const result = await service.create({
21814
+ password: options.password,
21815
+ include
21816
+ });
21817
+ if (!result.ok) fail(result.error ?? "the backup failed");
21818
+ return { file: result.file };
21819
+ })())?.file;
21820
+ if (file === void 0) fail("the backup reported success but named no archive");
21821
+ if (options.json) {
21822
+ process.stdout.write(`${JSON.stringify({
21823
+ action: "create",
21824
+ apply: true,
21825
+ file
21826
+ }, null, 2)}\n`);
21827
+ return;
21828
+ }
21035
21829
  process.stdout.write(`${green("backup created")} ${file.name} ${dim(`(${human(file.sizeBytes)})`)}\n`);
21036
21830
  }
21831
+ /**
21832
+ * The entries running right now.
21833
+ *
21834
+ * Read from the state files in **both** cases: the panel's own backup view has no per-entry running
21835
+ * flag to read, and the state files are the same witness the panel's supervisor would give — a
21836
+ * persistent entry keeps its nanny alive and rewrites that file whether or not the panel is up.
21837
+ */
21838
+ async function runningEntries() {
21839
+ return (await offlineBackup()).runningNow();
21840
+ }
21037
21841
  async function runBackupRestore(options) {
21038
- const runtime = await livePanel();
21039
- const query = new URLSearchParams({ name: options.name });
21040
- if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21041
- if (options.include !== void 0 && options.include.length > 0) query.set("include", options.include.join(","));
21042
- if (options.confirm) query.set("confirm", "true");
21043
- const answer = await runtime.request(runtime, `/_hh/backups/restore?${query.toString()}`, 6e5);
21044
- if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21045
- if (answer.status !== 200) refusal(answer);
21046
- const plan = answer.body;
21047
- const items = plan?.items ?? [];
21048
- if (!options.confirm) {
21842
+ const scope = options.scope;
21843
+ const service = await usesPanel() ? null : (await offlineBackup()).service;
21844
+ if (service !== null) await service.warm();
21845
+ const plan = await (async () => {
21846
+ if (service !== null) {
21847
+ const archive = service.resolve(options.name);
21848
+ if (archive === null) fail(`no backup named "${options.name}" — \`${invocation()} backup list\` shows them`);
21849
+ return await service.restore(archive, {
21850
+ confirm: false,
21851
+ password: options.password,
21852
+ include: scope.kind === "include" ? scope.ids : void 0
21853
+ });
21854
+ }
21855
+ const runtime = await livePanel();
21856
+ if (runtime === null) fail(`the control panel is not answering — try again once it is up`);
21857
+ const base = new URLSearchParams({ name: options.name });
21858
+ if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21859
+ if (scope.kind === "include") base.set("include", scope.ids.join(","));
21860
+ const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
21861
+ if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21862
+ if (answer.status !== 200) refusal(answer);
21863
+ return answer.body;
21864
+ })();
21865
+ const items = (plan?.items ?? []).filter((item) => item.selected !== false);
21866
+ if (options.json && !options.confirm) {
21867
+ process.stdout.write(`${JSON.stringify({
21868
+ action: "restore",
21869
+ apply: false,
21870
+ name: options.name,
21871
+ items,
21872
+ warnings: plan?.warnings ?? []
21873
+ }, null, 2)}\n`);
21874
+ return;
21875
+ }
21876
+ if (!options.json) {
21049
21877
  process.stdout.write(`${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
21050
- for (const item of items) process.stdout.write(` ${item.kind.padEnd(10)} ${item.id}\n`);
21878
+ for (const item of items) process.stdout.write(` ${String(item.kind ?? "item").padEnd(10)} ${item.id ?? item.label ?? ""}\n`);
21051
21879
  for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21052
- process.stdout.write(`\napply it with \`${invocation()} backup restore ${options.name} --confirm\`\n`);
21053
- return;
21880
+ if (items.length === 0) {
21881
+ process.stdout.write(" (nothing to restore — check --include, or what this host declares)\n");
21882
+ return;
21883
+ }
21884
+ }
21885
+ if (!options.confirm && !await consent(`Restore these ${items.length} item(s) over this host?`)) return;
21886
+ {
21887
+ const outcome = await (async () => {
21888
+ if (service !== null) {
21889
+ const archive = service.resolve(options.name);
21890
+ const result = await service.restore(archive, {
21891
+ confirm: true,
21892
+ password: options.password,
21893
+ include: scope.kind === "include" ? scope.ids : void 0
21894
+ });
21895
+ return {
21896
+ items: (result.items ?? []).filter((item) => item.selected !== false),
21897
+ hooks: (result.hooks ?? []).filter((hook) => hook.action === "load")
21898
+ };
21899
+ }
21900
+ const runtime = await livePanel();
21901
+ if (runtime === null) fail("the control panel stopped answering — nothing further was written");
21902
+ const base = new URLSearchParams({ name: options.name });
21903
+ if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21904
+ if (scope.kind === "include") base.set("include", scope.ids.join(","));
21905
+ const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
21906
+ if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21907
+ if (answer.status !== 200) refusal(answer);
21908
+ const result = answer.body;
21909
+ return {
21910
+ items: (result?.items ?? plan?.items ?? []).filter((item) => item.selected !== false),
21911
+ hooks: (result?.hooks ?? plan?.hooks ?? []).filter((hook) => hook.action === "load")
21912
+ };
21913
+ })();
21914
+ const applied = outcome.items;
21915
+ if (options.json) {
21916
+ process.stdout.write(`${JSON.stringify({
21917
+ action: "restore",
21918
+ apply: true,
21919
+ name: options.name,
21920
+ items: applied,
21921
+ hooks: outcome.hooks,
21922
+ warnings: plan?.warnings ?? []
21923
+ }, null, 2)}\n`);
21924
+ return;
21925
+ }
21926
+ process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${options.name}\n`);
21927
+ for (const hook of outcome.hooks) process.stdout.write(` ${dim(`load ${hook.serverId}: ${hook.output ?? "staged"}`)}\n`);
21928
+ for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21929
+ if (service !== null) process.stdout.write(dim(`the panel is not running, so nothing was reloaded — the next \`${invocation()} up\` reads what was restored\n`));
21054
21930
  }
21055
- process.stdout.write(`${green("restored")} ${items.length} ${items.length === 1 ? "item" : "items"} from ${options.name}\n`);
21056
- for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21057
21931
  }
21058
21932
  var backupCommand;
21059
21933
  var init_backup = __esmMin((() => {
21934
+ init_backup_offline();
21060
21935
  init_io();
21061
21936
  init_error_message();
21062
21937
  backupCommand = defineCommand({
@@ -21078,33 +21953,43 @@ var init_backup = __esmMin((() => {
21078
21953
  },
21079
21954
  include: {
21080
21955
  type: "string",
21081
- description: "comma-separated item ids to capture, or to restore"
21956
+ description: "comma-separated item ids to act on"
21957
+ },
21958
+ all: {
21959
+ type: "boolean",
21960
+ description: "act on everything, rather than naming ids"
21082
21961
  },
21083
21962
  confirm: {
21084
21963
  type: "boolean",
21085
- description: "apply a restore instead of only planning it"
21964
+ description: "apply without asking (a restore writes over live data)"
21086
21965
  },
21087
21966
  json: {
21088
21967
  type: "boolean",
21089
- description: "print machine-readable JSON (list)"
21968
+ description: "print the plan or the result as JSON"
21090
21969
  }
21091
21970
  },
21092
21971
  async run({ args }) {
21093
21972
  try {
21094
- const include = args.include === void 0 ? void 0 : args.include.split(",").filter((part) => part.length > 0);
21095
21973
  const action = args.action === void 0 || args.action.length === 0 ? "list" : args.action;
21974
+ const parsed = action === "create" || action === "restore" ? parseScope(args.all === true, args.include) : null;
21096
21975
  if (action === "list") await runBackupList(args.json === true);
21097
- else if (action === "create") await runBackupCreate({
21098
- password: args.password,
21099
- include
21100
- });
21101
- else if (action === "restore") {
21976
+ else if (action === "create") {
21977
+ const scope = parsed ?? await refuseWithoutScope("create", "");
21978
+ await runBackupCreate({
21979
+ password: args.password,
21980
+ scope,
21981
+ confirm: args.confirm === true,
21982
+ json: args.json === true
21983
+ });
21984
+ } else if (action === "restore") {
21102
21985
  if (args.target === void 0 || args.target.length === 0) fail("restore needs the archive name — `backup list` shows them");
21986
+ const scope = parsed ?? await refuseWithoutScope("restore", `?name=${encodeURIComponent(args.target)}`);
21103
21987
  await runBackupRestore({
21104
21988
  name: args.target,
21105
21989
  password: args.password,
21106
- include,
21107
- confirm: args.confirm === true
21990
+ scope,
21991
+ confirm: args.confirm === true,
21992
+ json: args.json === true
21108
21993
  });
21109
21994
  } else fail(`unknown action "${action}" — use list, create or restore`);
21110
21995
  } catch (error) {
@@ -21331,7 +22216,6 @@ var OPTION_WIDTH = 21;
21331
22216
  var UP_SECTION = {
21332
22217
  heading: "Options for up/restart",
21333
22218
  lines: [
21334
- ["-c, --config <file>", "default workspace servers config (default: <state>/.hh/default/servers.config.json)"],
21335
22219
  ["-p, --port <port>", "control panel port (default: 3999)"],
21336
22220
  ["--host <bind>", "local | lan | an ipv4 address (default: local)"],
21337
22221
  ["--open", "open the panel in a browser once it is up"],
@@ -21357,10 +22241,11 @@ var BACKUP_SECTION = {
21357
22241
  lines: [
21358
22242
  ["list | create | restore", "what to do (default: list)"],
21359
22243
  ["<name>", "the archive, for restore — `backup list` shows them"],
22244
+ ["--include <ids>", "comma-separated item ids to act on (required for create/restore)"],
22245
+ ["--all", "act on everything; one of --include or --all is required"],
21360
22246
  ["--password <text>", "encrypt a new archive, or unlock one on restore"],
21361
- ["--include <ids>", "comma-separated item ids to capture, or to restore"],
21362
- ["--confirm", "apply a restore instead of only planning it"],
21363
- ["--json", "machine-readable output (list)"]
22247
+ ["--confirm", "apply without asking (create and restore plan first)"],
22248
+ ["--json", "print the plan or the result as JSON"]
21364
22249
  ]
21365
22250
  };
21366
22251
  var SERVER_SECTION = {
@@ -21385,11 +22270,7 @@ var SET_TOKEN_SECTION = {
21385
22270
  };
21386
22271
  var MIGRATE_SECTION = {
21387
22272
  heading: "Options for migrate",
21388
- lines: [
21389
- ["-c, --config <file>", "one config file to migrate (default: every file this state root owns)"],
21390
- ["--dry-run", "print what would change, write nothing"],
21391
- ["-y, --yes", "apply without asking (or set HHOSTED_MIGRATE=allow)"]
21392
- ]
22273
+ lines: [["--dry-run", "print what would change, write nothing"], ["-y, --yes", "apply without asking (or set HHOSTED_MIGRATE=allow)"]]
21393
22274
  };
21394
22275
  var INIT_SECTION = {
21395
22276
  heading: "Options for init",