home-hosted 0.9.6 → 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.
@@ -12914,6 +12963,142 @@ var init_archive = __esmMin((() => {
12914
12963
  ];
12915
12964
  }));
12916
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
12917
13102
  //#region src/helpers/backoff.ts
12918
13103
  /** Exponential backoff: base * factor^(attempt - 1), capped at maxDelayMs. */
12919
13104
  function computeBackoff(attempt, options) {
@@ -13128,142 +13313,6 @@ var init_health_check = __esmMin((() => {
13128
13313
  MAX_BODY_BYTES = 1e6;
13129
13314
  }));
13130
13315
  //#endregion
13131
- //#region src/providers/process.ts
13132
- /**
13133
- * Resolves a bare command through the entry's own directory and the project's
13134
- * `node_modules/.bin` first, so a server installed as a project dependency is
13135
- * found even when the launcher's PATH has no pnpm-injected bin dir.
13136
- */
13137
- function resolveCommand(command, ...searchDirs) {
13138
- if (command.includes("/") || command.includes("\\")) return command;
13139
- const candidates = process.platform === "win32" && path.extname(command) === "" ? [command, ...WINDOWS_SHIM_EXTENSIONS.map((extension) => `${command}${extension}`)] : [command];
13140
- for (const dir of searchDirs) for (const candidate of candidates) {
13141
- const local = path.join(dir, "node_modules", ".bin", candidate);
13142
- if (fs.existsSync(local)) return local;
13143
- }
13144
- return command;
13145
- }
13146
- /** Relative entry paths belong to the project that launched the panel. */
13147
- function resolveCwd(cwd, base = projectDir) {
13148
- return path.resolve(base, cwd);
13149
- }
13150
- /** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */
13151
- function needsShell(command) {
13152
- return process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
13153
- }
13154
- function spawnManaged(spec, options = {}) {
13155
- return spawn(spec.command, spec.args, {
13156
- cwd: spec.cwd,
13157
- env: {
13158
- ...process.env,
13159
- ...spec.env
13160
- },
13161
- detached: options.detached ?? true,
13162
- stdio: [
13163
- "ignore",
13164
- "pipe",
13165
- "pipe"
13166
- ],
13167
- shell: needsShell(spec.command),
13168
- windowsHide: true
13169
- });
13170
- }
13171
- /** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */
13172
- async function terminate(child, options) {
13173
- if (child.exitCode !== null || child.signalCode !== null) return "exited";
13174
- const exited = waitForExit$1(child, options.graceMs);
13175
- signalChild(child, options.signal, options.killGroup);
13176
- if (await exited) return "exited";
13177
- signalChild(child, "SIGKILL", options.killGroup);
13178
- await waitForExit$1(child, 2e3);
13179
- return "force-killed";
13180
- }
13181
- /**
13182
- * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and
13183
- * `/F` is the only reliable way to stop a console process.
13184
- */
13185
- async function killTreeWindows(pid) {
13186
- try {
13187
- await execFileAsync$1("taskkill", [
13188
- "/pid",
13189
- String(pid),
13190
- "/T",
13191
- "/F"
13192
- ], { timeout: 5e3 });
13193
- } catch {}
13194
- }
13195
- function signalChild(child, signal, killGroup) {
13196
- const pid = child.pid;
13197
- if (pid === void 0) return;
13198
- signalPid(pid, signal, killGroup);
13199
- }
13200
- function signalPid(pid, signal, killGroup) {
13201
- if (process.platform === "win32") {
13202
- if (killGroup) killTreeWindows(pid);
13203
- else try {
13204
- process.kill(pid, signal);
13205
- } catch {}
13206
- return;
13207
- }
13208
- if (killGroup) try {
13209
- process.kill(-pid, signal);
13210
- return;
13211
- } catch {}
13212
- try {
13213
- process.kill(pid, signal);
13214
- } catch {}
13215
- }
13216
- /**
13217
- * The same shutdown a supervised child gets, for a process we adopted instead of
13218
- * spawned: a detached successor is not our child, so it is signalled by pid (and
13219
- * by process group when asked) and its exit is polled rather than awaited.
13220
- *
13221
- * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned
13222
- * `false` for `EPERM`, so a process that was there but not ours to signal read as "exited" and
13223
- * `'force-killed'` was returned for one still running. One predicate, one answer.
13224
- */
13225
- async function terminatePid(pid, options) {
13226
- if (!isProcessAlive(pid)) return "exited";
13227
- signalPid(pid, options.signal, options.killGroup);
13228
- const deadline = Date.now() + Math.max(0, options.graceMs);
13229
- while (Date.now() < deadline && isProcessAlive(pid)) await delay$1(50);
13230
- if (!isProcessAlive(pid)) return "exited";
13231
- signalPid(pid, "SIGKILL", options.killGroup);
13232
- const hardDeadline = Date.now() + 2e3;
13233
- while (Date.now() < hardDeadline && isProcessAlive(pid)) await delay$1(50);
13234
- return "force-killed";
13235
- }
13236
- function delay$1(ms) {
13237
- return new Promise((resolve) => setTimeout(resolve, ms));
13238
- }
13239
- function waitForExit$1(child, timeoutMs) {
13240
- if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
13241
- if (timeoutMs <= 0) return Promise.resolve(false);
13242
- return new Promise((resolve) => {
13243
- const timer = setTimeout(() => {
13244
- child.removeListener("exit", onExit);
13245
- resolve(false);
13246
- }, timeoutMs);
13247
- function onExit() {
13248
- clearTimeout(timer);
13249
- resolve(true);
13250
- }
13251
- child.once("exit", onExit);
13252
- });
13253
- }
13254
- var execFileAsync$1, WINDOWS_SHIM_EXTENSIONS;
13255
- var init_process = __esmMin((() => {
13256
- init_paths();
13257
- init_port();
13258
- execFileAsync$1 = promisify(execFile);
13259
- WINDOWS_SHIM_EXTENSIONS = [
13260
- ".cmd",
13261
- ".exe",
13262
- ".bat",
13263
- ".ps1"
13264
- ];
13265
- }));
13266
- //#endregion
13267
13316
  //#region src/services/dependencies.ts
13268
13317
  /**
13269
13318
  * Orders servers so every dependency comes before its dependents.
@@ -13676,6 +13725,7 @@ var init_supervisor = __esmMin((() => {
13676
13725
  init_paths();
13677
13726
  init_runtime();
13678
13727
  init_template();
13728
+ init_backup_hook();
13679
13729
  init_entry_state();
13680
13730
  init_health_check();
13681
13731
  init_identity();
@@ -13847,7 +13897,10 @@ var init_supervisor = __esmMin((() => {
13847
13897
  ok: false,
13848
13898
  error: `server "${id}" is disabled`
13849
13899
  };
13850
- 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
+ }
13851
13904
  if (entry.stopping) return {
13852
13905
  ok: false,
13853
13906
  error: `server "${id}" is stopping`
@@ -13898,11 +13951,58 @@ var init_supervisor = __esmMin((() => {
13898
13951
  error: conflict.error
13899
13952
  };
13900
13953
  if (conflict.kind === "adopt") return this.adoptEntry(entry, conflict.pid, `a detached restart of this entry is already serving port ${entry.config.port}`);
13901
- return this.spawnEntry(entry);
13954
+ const started = this.spawnEntry(entry);
13955
+ if (entry.pendingLoad !== null) this.runPendingLoad(entry);
13956
+ return started;
13902
13957
  } finally {
13903
13958
  entry.starting = false;
13904
13959
  }
13905
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
+ }
13906
14006
  async stop(id) {
13907
14007
  const entry = this.entries.get(id);
13908
14008
  if (!entry) return missingServer(id);
@@ -14229,6 +14329,8 @@ var init_supervisor = __esmMin((() => {
14229
14329
  actor: "policy",
14230
14330
  removed: false,
14231
14331
  bootstrapDone: persisted?.bootstrapDone ?? !config.bootstrap,
14332
+ pendingLoad: persisted?.pendingLoad ?? null,
14333
+ loadingPending: false,
14232
14334
  logs: new LogBuffer(config.logBufferLines),
14233
14335
  echoed: /* @__PURE__ */ new Set(),
14234
14336
  responseMs: null,
@@ -15142,6 +15244,7 @@ var init_supervisor = __esmMin((() => {
15142
15244
  restarts: entry.restarts,
15143
15245
  healthRestarts: entry.healthRestarts,
15144
15246
  bootstrapDone: entry.bootstrapDone,
15247
+ pendingLoad: entry.pendingLoad,
15145
15248
  lastPid: entry.config.persistent ? null : entry.lastChild?.pid ?? null,
15146
15249
  lastStartedAt: entry.config.persistent ? null : entry.lastChild?.startedAt ?? null
15147
15250
  });
@@ -15221,6 +15324,103 @@ var init_supervisor = __esmMin((() => {
15221
15324
  };
15222
15325
  }));
15223
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
15224
15424
  //#region src/shared/generated.ts
15225
15425
  /**
15226
15426
  * True when a path *relative to the declared root* looks generated. Accepts
@@ -15290,6 +15490,23 @@ var init_generated = __esmMin((() => {
15290
15490
  * is made of allowed characters, so segments are checked explicitly and any
15291
15491
  * entry that could resolve outside the staging directory aborts the restore.
15292
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
+ }
15293
15510
  function isSafeArchiveEntry(entry) {
15294
15511
  if (entry.startsWith("/") || entry.includes("\0")) return false;
15295
15512
  const cleaned = entry.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -15538,7 +15755,7 @@ function readableWorkspaceSettings(text) {
15538
15755
  return false;
15539
15756
  }
15540
15757
  }
15541
- 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;
15542
15759
  var init_backups = __esmMin((() => {
15543
15760
  init_migrations();
15544
15761
  init_parse();
@@ -15552,6 +15769,7 @@ var init_backups = __esmMin((() => {
15552
15769
  init_template();
15553
15770
  init_version();
15554
15771
  init_archive();
15772
+ init_backup_hook();
15555
15773
  init_supervisor();
15556
15774
  init_contracts();
15557
15775
  init_error_message();
@@ -15562,9 +15780,11 @@ var init_backups = __esmMin((() => {
15562
15780
  ALLOWED_ROOTS = /* @__PURE__ */ new Set([
15563
15781
  "global",
15564
15782
  "workspaces",
15565
- "data"
15783
+ "data",
15784
+ "dumps"
15566
15785
  ]);
15567
15786
  SUFFIX = ".zip";
15787
+ PENDING_LOAD = "pending-load";
15568
15788
  AUTO_PREFIX = "auto";
15569
15789
  RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/;
15570
15790
  SECRET_LABELS = {
@@ -15724,6 +15944,36 @@ var init_backups = __esmMin((() => {
15724
15944
  if (capturesSecrets("global:secrets")) copySecrets("global/secrets.json", sources.globalSecretsPath, "global:secrets", "global");
15725
15945
  if (capturesGlobal("global:tls")) copy("global/tls", sources.tlsDir);
15726
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
+ }
15727
15977
  const data = [];
15728
15978
  for (const workspace of sources.workspaces) {
15729
15979
  const root = `workspaces/${workspace.id}`;
@@ -15762,7 +16012,8 @@ var init_backups = __esmMin((() => {
15762
16012
  hostname: os.hostname(),
15763
16013
  writtenBy: appVersion(),
15764
16014
  schema: 2,
15765
- data
16015
+ data,
16016
+ ...dumped.length === 0 ? {} : { dumps: dumped }
15766
16017
  };
15767
16018
  fs.writeFileSync(path.join(staging, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
15768
16019
  await createZip(staging, destination, password === null ? {} : { password });
@@ -16188,6 +16439,18 @@ var init_backups = __esmMin((() => {
16188
16439
  * apply closure so a dry run reports the same list the apply would.
16189
16440
  */
16190
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
+ }
16191
16454
  const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : [];
16192
16455
  for (const entry of archivedEntries) {
16193
16456
  const archivedPath = typeof entry.path === "string" ? entry.path : "";
@@ -16267,6 +16530,49 @@ var init_backups = __esmMin((() => {
16267
16530
  });
16268
16531
  plan.createdWorkspaces.push(workspace.id);
16269
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);
16270
16576
  if (this.options.onRestored !== void 0 && [...actions.keys()].some((id) => RELOADABLE.test(id))) {
16271
16577
  plan.reloaded = true;
16272
16578
  this.options.onRestored();
@@ -18151,6 +18457,7 @@ var init_panel = __esmMin((() => {
18151
18457
  init_paths();
18152
18458
  init_version();
18153
18459
  init_ddns$2();
18460
+ init_entry_state();
18154
18461
  init_backups();
18155
18462
  init_config_watch();
18156
18463
  init_ddns();
@@ -18361,6 +18668,25 @@ var init_panel = __esmMin((() => {
18361
18668
  * an archive brought therefore waited for a panel restart — which is why the start of
18362
18669
  * newly appeared autostart entries belongs here, the one place that knows what was new.
18363
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
+ }
18364
18690
  reloadAll() {
18365
18691
  this.options.settings.load();
18366
18692
  for (const runtime of this.workspaces()) {
@@ -18404,7 +18730,7 @@ var init_panel = __esmMin((() => {
18404
18730
  createRuntime(workspace) {
18405
18731
  const id = workspace.id;
18406
18732
  fs.mkdirSync(workspaceDir(id), { recursive: true });
18407
- 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));
18408
18734
  store.load();
18409
18735
  store.writeJsonSchema();
18410
18736
  const secrets = new SecretsStore(workspaceSecretsPath(id), void 0, "workspace");
@@ -19357,7 +19683,7 @@ async function runControlPlane(options) {
19357
19683
  });
19358
19684
  if (trustWarning !== null) logger.warn(trustWarning);
19359
19685
  if (options.printConfig) {
19360
- printEffectiveConfig(settings, registry, options);
19686
+ printEffectiveConfig(settings, registry);
19361
19687
  return;
19362
19688
  }
19363
19689
  if (!await isPortFree(intended.port)) {
@@ -19430,7 +19756,8 @@ async function runControlPlane(options) {
19430
19756
  getConfig: () => settings.backups,
19431
19757
  getSources: () => panel.backupSources(),
19432
19758
  ensureWorkspace: (input) => panel?.ensureWorkspace(input),
19433
- onRestored: () => panel?.reloadAll()
19759
+ onRestored: () => panel?.reloadAll(),
19760
+ onLoadPending: (workspaceId, serverId, dumpDir) => panel?.stagePendingLoad(workspaceId, serverId, dumpDir)
19434
19761
  });
19435
19762
  panel = new PanelService({
19436
19763
  registry,
@@ -19444,8 +19771,7 @@ async function runControlPlane(options) {
19444
19771
  hub,
19445
19772
  control: () => controlServer.endpoint,
19446
19773
  proxy: () => proxy,
19447
- autostart: options.autostart,
19448
- ...options.configPath === void 0 ? {} : { defaultServersPath: options.configPath }
19774
+ autostart: options.autostart
19449
19775
  });
19450
19776
  for (const workspace of panel.workspaces()) {
19451
19777
  const store = workspace.store;
@@ -19549,7 +19875,7 @@ async function runControlPlane(options) {
19549
19875
  process.on("SIGTERM", () => onSignal("SIGTERM"));
19550
19876
  }
19551
19877
  /** `--print-config`: the global settings and every workspace, without starting anything. */
19552
- function printEffectiveConfig(settings, registry, options) {
19878
+ function printEffectiveConfig(settings, registry) {
19553
19879
  const workspaces = registry.all().map((workspace) => {
19554
19880
  const dir = path.join(hhDir, workspace.id);
19555
19881
  const read = (name) => {
@@ -19559,18 +19885,11 @@ function printEffectiveConfig(settings, registry, options) {
19559
19885
  return null;
19560
19886
  }
19561
19887
  };
19562
- const serversFile = workspace.id === registry.defaultId && options.configPath !== void 0 ? options.configPath : path.join(dir, "servers.config.json");
19563
- let servers = null;
19564
- try {
19565
- servers = JSON.parse(fs.readFileSync(serversFile, "utf8"));
19566
- } catch {
19567
- servers = null;
19568
- }
19569
19888
  return {
19570
19889
  id: workspace.id,
19571
19890
  label: workspace.label,
19572
19891
  settings: read("settings.json"),
19573
- servers
19892
+ servers: read("servers.config.json")
19574
19893
  };
19575
19894
  });
19576
19895
  process.stdout.write(`${JSON.stringify({
@@ -19626,7 +19945,6 @@ function toUpFlags(args) {
19626
19945
  if (!Number.isInteger(port) || port <= 0 || port > 65535) fail(`invalid port: ${args.port}`);
19627
19946
  }
19628
19947
  return {
19629
- config: args.config,
19630
19948
  port,
19631
19949
  host: args.host,
19632
19950
  autostart: args.autostart !== false,
@@ -19639,7 +19957,6 @@ async function runUp(flags, entry) {
19639
19957
  if (flags.foreground || flags.printConfig) {
19640
19958
  const { runControlPlane } = await Promise.resolve().then(() => (init_src(), src_exports));
19641
19959
  await runControlPlane({
19642
- configPath: flags.config,
19643
19960
  port: flags.port,
19644
19961
  host: flags.host,
19645
19962
  autostart: flags.autostart,
@@ -19725,11 +20042,6 @@ var init_up = __esmMin((() => {
19725
20042
  init_version();
19726
20043
  DEFAULT_PORT$1 = 3999;
19727
20044
  upArgs = {
19728
- config: {
19729
- type: "string",
19730
- alias: "c",
19731
- description: "the default workspace's servers config (default: <state>/.hh/default/servers.config.json)"
19732
- },
19733
20045
  port: {
19734
20046
  type: "string",
19735
20047
  alias: "p",
@@ -20334,7 +20646,7 @@ var migrate_exports = /* @__PURE__ */ __exportAll({
20334
20646
  runMigrate: () => runMigrate
20335
20647
  });
20336
20648
  /** Every file a migration may have to stamp, and how this release reads it. */
20337
- function targets(configOverride) {
20649
+ function targets() {
20338
20650
  const list = [{
20339
20651
  file: globalSettingsPath,
20340
20652
  label: "global settings",
@@ -20350,7 +20662,7 @@ function targets(configOverride) {
20350
20662
  validate: (raw) => parseWorkspaceSettings(raw).errors[0] ?? null
20351
20663
  });
20352
20664
  list.push({
20353
- file: workspace.id === registry.defaultId && configOverride !== void 0 ? configOverride : workspaceServersPath(workspace.id),
20665
+ file: workspaceServersPath(workspace.id),
20354
20666
  label: `workspace ${workspace.id} servers`,
20355
20667
  validate: (raw) => {
20356
20668
  let defaults = {};
@@ -20366,8 +20678,8 @@ function targets(configOverride) {
20366
20678
  }
20367
20679
  return list;
20368
20680
  }
20369
- async function runMigrate(config, dryRun, yes) {
20370
- 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));
20371
20683
  if (existing.length === 0) fail(`no home-hosted state to migrate — nothing at ${globalSettingsPath} or any workspace`);
20372
20684
  const consented = yes || (process.env.HHOSTED_MIGRATE ?? "").toLowerCase() === "allow";
20373
20685
  let stampOnly = 0;
@@ -20440,11 +20752,6 @@ var init_migrate = __esmMin((() => {
20440
20752
  init_error_message();
20441
20753
  init_shape();
20442
20754
  migrateArgs = {
20443
- config: {
20444
- type: "string",
20445
- alias: "c",
20446
- description: "the default workspace's servers config (default: <state>/.hh/default/servers.config.json)"
20447
- },
20448
20755
  dryRun: {
20449
20756
  type: "boolean",
20450
20757
  description: "print what would change, write nothing"
@@ -20459,7 +20766,7 @@ var init_migrate = __esmMin((() => {
20459
20766
  meta: { name: "migrate" },
20460
20767
  args: migrateArgs,
20461
20768
  run: async ({ args }) => {
20462
- await runMigrate(args.config, args.dryRun === true, args.yes === true);
20769
+ await runMigrate(args.dryRun === true, args.yes === true);
20463
20770
  }
20464
20771
  });
20465
20772
  }));
@@ -21228,6 +21535,24 @@ function createOfflineBackup(options = {}) {
21228
21535
  * panel there is nobody to do it, so the registry is written here — otherwise a restored
21229
21536
  * workspace's files land on disk unreachable, and the next `up` never looks at them.
21230
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
+ },
21231
21556
  ensureWorkspace: (input) => {
21232
21557
  if (registry.has(input.id)) return;
21233
21558
  registry.create(input);
@@ -21251,6 +21576,7 @@ var init_backup_offline = __esmMin((() => {
21251
21576
  init_store();
21252
21577
  init_workspaces();
21253
21578
  init_paths();
21579
+ init_entry_state();
21254
21580
  init_nanny$2();
21255
21581
  init_backups();
21256
21582
  }));
@@ -21292,11 +21618,9 @@ async function usesPanel() {
21292
21618
  /**
21293
21619
  * The offline service.
21294
21620
  *
21295
- * `--config` is an `up`-only flag: it is not written to settings, and `run.json`'s `configPath` is the
21296
- * state directory, not a servers file. So an offline run cannot know about one, and reads the default
21297
- * workspace's `servers.config.json` — the same file the panel reads when started without `--config`.
21298
- * A `--config` project has to start the panel first, which is the honest limit rather than a silent
21299
- * difference between the two paths.
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.
21300
21624
  */
21301
21625
  async function offlineBackup() {
21302
21626
  return createOfflineBackup();
@@ -21560,14 +21884,18 @@ async function runBackupRestore(options) {
21560
21884
  }
21561
21885
  if (!options.confirm && !await consent(`Restore these ${items.length} item(s) over this host?`)) return;
21562
21886
  {
21563
- const applied = await (async () => {
21887
+ const outcome = await (async () => {
21564
21888
  if (service !== null) {
21565
21889
  const archive = service.resolve(options.name);
21566
- return ((await service.restore(archive, {
21890
+ const result = await service.restore(archive, {
21567
21891
  confirm: true,
21568
21892
  password: options.password,
21569
21893
  include: scope.kind === "include" ? scope.ids : void 0
21570
- })).items ?? []).filter((item) => item.selected !== false);
21894
+ });
21895
+ return {
21896
+ items: (result.items ?? []).filter((item) => item.selected !== false),
21897
+ hooks: (result.hooks ?? []).filter((hook) => hook.action === "load")
21898
+ };
21571
21899
  }
21572
21900
  const runtime = await livePanel();
21573
21901
  if (runtime === null) fail("the control panel stopped answering — nothing further was written");
@@ -21577,19 +21905,26 @@ async function runBackupRestore(options) {
21577
21905
  const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
21578
21906
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21579
21907
  if (answer.status !== 200) refusal(answer);
21580
- return (answer.body?.items ?? plan?.items ?? []).filter((item) => item.selected !== false);
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
+ };
21581
21913
  })();
21914
+ const applied = outcome.items;
21582
21915
  if (options.json) {
21583
21916
  process.stdout.write(`${JSON.stringify({
21584
21917
  action: "restore",
21585
21918
  apply: true,
21586
21919
  name: options.name,
21587
21920
  items: applied,
21921
+ hooks: outcome.hooks,
21588
21922
  warnings: plan?.warnings ?? []
21589
21923
  }, null, 2)}\n`);
21590
21924
  return;
21591
21925
  }
21592
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`);
21593
21928
  for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21594
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`));
21595
21930
  }
@@ -21881,7 +22216,6 @@ var OPTION_WIDTH = 21;
21881
22216
  var UP_SECTION = {
21882
22217
  heading: "Options for up/restart",
21883
22218
  lines: [
21884
- ["-c, --config <file>", "default workspace servers config (default: <state>/.hh/default/servers.config.json)"],
21885
22219
  ["-p, --port <port>", "control panel port (default: 3999)"],
21886
22220
  ["--host <bind>", "local | lan | an ipv4 address (default: local)"],
21887
22221
  ["--open", "open the panel in a browser once it is up"],
@@ -21936,11 +22270,7 @@ var SET_TOKEN_SECTION = {
21936
22270
  };
21937
22271
  var MIGRATE_SECTION = {
21938
22272
  heading: "Options for migrate",
21939
- lines: [
21940
- ["-c, --config <file>", "one config file to migrate (default: every file this state root owns)"],
21941
- ["--dry-run", "print what would change, write nothing"],
21942
- ["-y, --yes", "apply without asking (or set HHOSTED_MIGRATE=allow)"]
21943
- ]
22273
+ lines: [["--dry-run", "print what would change, write nothing"], ["-y, --yes", "apply without asking (or set HHOSTED_MIGRATE=allow)"]]
21944
22274
  };
21945
22275
  var INIT_SECTION = {
21946
22276
  heading: "Options for init",