home-hosted 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/README.md +95 -49
  2. package/dist/chunks/{archive-DpCwA8Nf.js → archive-DP-XQR8X.js} +15 -2
  3. package/dist/chunks/archive-DP-XQR8X.js.map +1 -0
  4. package/dist/chunks/{atomic-CEfCUfkQ.js → atomic-C1PfJpE7.js} +3 -2
  5. package/dist/chunks/atomic-C1PfJpE7.js.map +1 -0
  6. package/dist/chunks/{backup-CPrJVPJI.js → backup-DeAJ3pbO.js} +101 -76
  7. package/dist/chunks/backup-DeAJ3pbO.js.map +1 -0
  8. package/dist/chunks/{backups-Bd2SF2qd.js → backups-twva7x2n.js} +882 -537
  9. package/dist/chunks/backups-twva7x2n.js.map +1 -0
  10. package/dist/chunks/{contracts-ku5ypHXJ.js → contracts-CMBD1TF9.js} +381 -407
  11. package/dist/chunks/contracts-CMBD1TF9.js.map +1 -0
  12. package/dist/chunks/{daemon-TwXk5vb8.js → daemon-CofN9k6Q.js} +54 -22
  13. package/dist/chunks/daemon-CofN9k6Q.js.map +1 -0
  14. package/dist/chunks/{docker-CGv4Uv7w.js → docker-Cy9Lyvda.js} +4 -3
  15. package/dist/chunks/docker-Cy9Lyvda.js.map +1 -0
  16. package/dist/chunks/{down-BlX5X3bm.js → down-C59ne5aM.js} +22 -17
  17. package/dist/chunks/down-C59ne5aM.js.map +1 -0
  18. package/dist/chunks/{init-DdmqHVra.js → init-BZ7hK9Vf.js} +19 -6
  19. package/dist/chunks/init-BZ7hK9Vf.js.map +1 -0
  20. package/dist/chunks/{last-stop-BZ08Z89-.js → last-stop-C-BXz_XI.js} +6 -5
  21. package/dist/chunks/last-stop-C-BXz_XI.js.map +1 -0
  22. package/dist/chunks/{layout-D74TGUnr.js → layout-DwTtmund.js} +2 -2
  23. package/dist/chunks/{layout-D74TGUnr.js.map → layout-DwTtmund.js.map} +1 -1
  24. package/dist/chunks/lazy-Ce5zEAq1.js +66 -0
  25. package/dist/chunks/lazy-Ce5zEAq1.js.map +1 -0
  26. package/dist/chunks/{log-buffer-HnP0jKhZ.js → log-buffer-Dy9HHDMD.js} +114 -50
  27. package/dist/chunks/log-buffer-Dy9HHDMD.js.map +1 -0
  28. package/dist/chunks/{logs-gI_69Q1P.js → logs---TI_bxM.js} +23 -21
  29. package/dist/chunks/logs---TI_bxM.js.map +1 -0
  30. package/dist/chunks/{migrate-BTlsibvF.js → migrate-Cfoq-Vgh.js} +5 -5
  31. package/dist/chunks/{migrate-BTlsibvF.js.map → migrate-Cfoq-Vgh.js.map} +1 -1
  32. package/dist/chunks/{nanny-20aBXL1o.js → nanny-COyCJXj9.js} +130 -27
  33. package/dist/chunks/nanny-COyCJXj9.js.map +1 -0
  34. package/dist/chunks/{nanny-DUaAfCV-.js → nanny-Dnun3hVB.js} +3 -3
  35. package/dist/chunks/{nanny-DUaAfCV-.js.map → nanny-Dnun3hVB.js.map} +1 -1
  36. package/dist/chunks/{nanny-CjnnrIpm.js → nanny-rewguyXg.js} +3 -3
  37. package/dist/chunks/{nanny-CjnnrIpm.js.map → nanny-rewguyXg.js.map} +1 -1
  38. package/dist/chunks/{nanny-sweep-Ca9kPAVi.js → nanny-sweep-ClVuNJRo.js} +6 -5
  39. package/dist/chunks/nanny-sweep-ClVuNJRo.js.map +1 -0
  40. package/dist/chunks/{parse-B9owE47G.js → parse-DhmG26fI.js} +4 -4
  41. package/dist/chunks/{parse-B9owE47G.js.map → parse-DhmG26fI.js.map} +1 -1
  42. package/dist/chunks/{paths-BT94q6-w.js → paths-CGlGDrOU.js} +36 -2
  43. package/dist/chunks/paths-CGlGDrOU.js.map +1 -0
  44. package/dist/chunks/{port-B8WBTRMk.js → port-k5VBw8t9.js} +5 -2
  45. package/dist/chunks/{port-B8WBTRMk.js.map → port-k5VBw8t9.js.map} +1 -1
  46. package/dist/chunks/{restart-UZgeDukG.js → restart-BYu_E7x5.js} +25 -59
  47. package/dist/chunks/restart-BYu_E7x5.js.map +1 -0
  48. package/dist/chunks/{schema-o7Lgk0V1.js → schema-B240VXcV.js} +11 -10
  49. package/dist/chunks/schema-B240VXcV.js.map +1 -0
  50. package/dist/chunks/{secrets-D7PdYh71.js → secrets-BieELnZh.js} +22 -4
  51. package/dist/chunks/secrets-BieELnZh.js.map +1 -0
  52. package/dist/chunks/{server-BuIeSsRu.js → server-By-zktjx.js} +3 -3
  53. package/dist/chunks/{server-BuIeSsRu.js.map → server-By-zktjx.js.map} +1 -1
  54. package/dist/chunks/{set-password-DegMumPh.js → set-password-D5vZqqSX.js} +7 -7
  55. package/dist/chunks/set-password-D5vZqqSX.js.map +1 -0
  56. package/dist/chunks/{set-token-21d1FTDC.js → set-token-xJkA1IZp.js} +7 -7
  57. package/dist/chunks/set-token-xJkA1IZp.js.map +1 -0
  58. package/dist/chunks/{settings-BVSBnIwJ.js → settings-xu-XTfWg.js} +126 -35
  59. package/dist/chunks/settings-xu-XTfWg.js.map +1 -0
  60. package/dist/chunks/{setup-temp-XiuAtiW2.js → setup-temp-CAN4_bA-.js} +6 -6
  61. package/dist/chunks/setup-temp-CAN4_bA-.js.map +1 -0
  62. package/dist/chunks/{src-BL97vLVb.js → src-BOBh9MBf.js} +2251 -1063
  63. package/dist/chunks/src-BOBh9MBf.js.map +1 -0
  64. package/dist/chunks/{status-EuWdRq8Q.js → status-B6f2-qhs.js} +12 -8
  65. package/dist/chunks/status-B6f2-qhs.js.map +1 -0
  66. package/dist/chunks/{ui-DbPuwddJ.js → ui-D562aqw5.js} +9 -7
  67. package/dist/chunks/ui-D562aqw5.js.map +1 -0
  68. package/dist/chunks/{ui-revert-BhqOAhmM.js → ui-revert-EkBBwRTt.js} +3 -3
  69. package/dist/chunks/{ui-revert-BhqOAhmM.js.map → ui-revert-EkBBwRTt.js.map} +1 -1
  70. package/dist/chunks/{ui-switch-CMoslPO2.js → ui-switch-BnZTdMDd.js} +3 -3
  71. package/dist/chunks/{ui-switch-CMoslPO2.js.map → ui-switch-BnZTdMDd.js.map} +1 -1
  72. package/dist/chunks/{ui-update-TTBBoDik.js → ui-update-_xryLYxw.js} +5 -5
  73. package/dist/chunks/{ui-update-TTBBoDik.js.map → ui-update-_xryLYxw.js.map} +1 -1
  74. package/dist/chunks/{up-C4H13hBw.js → up-DNZuTi2q.js} +25 -11
  75. package/dist/chunks/up-DNZuTi2q.js.map +1 -0
  76. package/dist/chunks/{usage-CSBgLRN5.js → usage-BrnDARNM.js} +29 -3
  77. package/dist/chunks/usage-BrnDARNM.js.map +1 -0
  78. package/dist/chunks/{workspaces-CAln2sQ7.js → workspaces-DYcfvKV_.js} +16 -8
  79. package/dist/chunks/workspaces-DYcfvKV_.js.map +1 -0
  80. package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -1
  81. package/dist/cli.js +80 -70
  82. package/dist/cli.js.map +1 -1
  83. package/dist/client.js +25 -1
  84. package/dist/client.js.map +1 -1
  85. package/dist/types/api/backups.d.ts +8 -3
  86. package/dist/types/api/control.d.ts +4 -3
  87. package/dist/types/api/events.d.ts +2 -1
  88. package/dist/types/api/health.d.ts +1 -0
  89. package/dist/types/api/metrics.d.ts +3 -1
  90. package/dist/types/api/settings.d.ts +2 -2
  91. package/dist/types/api/state.d.ts +8 -2
  92. package/dist/types/app.d.ts +26 -11
  93. package/dist/types/cli/backup.d.ts +7 -0
  94. package/dist/types/cli/down.d.ts +5 -0
  95. package/dist/types/cli/logs.d.ts +14 -2
  96. package/dist/types/cli/restart.d.ts +0 -1
  97. package/dist/types/cli/set-password.d.ts +2 -2
  98. package/dist/types/cli/up.d.ts +8 -2
  99. package/dist/types/client.d.ts +5618 -11
  100. package/dist/types/config/secrets.d.ts +2 -0
  101. package/dist/types/config/settings.d.ts +54 -8
  102. package/dist/types/config/store.d.ts +16 -3
  103. package/dist/types/config/workspaces.d.ts +4 -1
  104. package/dist/types/helpers/copy-tree.d.ts +5 -0
  105. package/dist/types/helpers/daemon.d.ts +20 -7
  106. package/dist/types/helpers/error.d.ts +8 -0
  107. package/dist/types/helpers/event-stream.d.ts +21 -0
  108. package/dist/types/helpers/openapi.d.ts +12 -24
  109. package/dist/types/helpers/paths.d.ts +18 -0
  110. package/dist/types/helpers/utf8-chunks.d.ts +15 -0
  111. package/dist/types/middleware/auth.d.ts +19 -3
  112. package/dist/types/providers/host.d.ts +1 -1
  113. package/dist/types/providers/log-tail.d.ts +27 -0
  114. package/dist/types/providers/nanny-sweep.d.ts +3 -0
  115. package/dist/types/providers/nanny.d.ts +10 -0
  116. package/dist/types/providers/proc.d.ts +9 -0
  117. package/dist/types/providers/process.d.ts +17 -0
  118. package/dist/types/providers/telegram.d.ts +45 -3
  119. package/dist/types/providers/wsl-temperature.d.ts +0 -4
  120. package/dist/types/services/auth.d.ts +36 -4
  121. package/dist/types/services/backups.d.ts +125 -1
  122. package/dist/types/services/ddns.d.ts +5 -0
  123. package/dist/types/services/exposure.d.ts +54 -1
  124. package/dist/types/services/history.d.ts +1 -0
  125. package/dist/types/services/host-monitor.d.ts +1 -0
  126. package/dist/types/services/log-buffer.d.ts +11 -0
  127. package/dist/types/services/log-files.d.ts +1 -11
  128. package/dist/types/services/log-relay.d.ts +0 -1
  129. package/dist/types/services/panel.d.ts +19 -0
  130. package/dist/types/services/proxy-certificates/certificates.d.ts +116 -0
  131. package/dist/types/services/proxy.d.ts +46 -69
  132. package/dist/types/services/state.d.ts +0 -3
  133. package/dist/types/services/supervisor/entry.d.ts +10 -0
  134. package/dist/types/services/supervisor/health.d.ts +3 -2
  135. package/dist/types/services/supervisor/output.d.ts +126 -0
  136. package/dist/types/services/supervisor/persistent.d.ts +4 -1
  137. package/dist/types/services/supervisor/records.d.ts +81 -1
  138. package/dist/types/services/supervisor.d.ts +32 -0
  139. package/dist/types/shared/action-outcome.d.ts +25 -0
  140. package/dist/types/shared/api-client.d.ts +218 -4
  141. package/dist/types/shared/backup-scope.d.ts +58 -0
  142. package/dist/types/shared/contracts.d.ts +142 -200
  143. package/dist/types/shared/ddns-form.d.ts +13 -0
  144. package/dist/types/shared/form-repair.d.ts +6 -0
  145. package/dist/types/shared/lazy.d.ts +4 -0
  146. package/dist/types/shared/live-frames.d.ts +22 -0
  147. package/dist/types/shared/live-series.d.ts +21 -0
  148. package/dist/types/shared/live-store.d.ts +72 -0
  149. package/dist/types/shared/patch-diff.d.ts +13 -2
  150. package/dist/types/shared/proxy-form.d.ts +2 -0
  151. package/dist/types/shared/server-form.d.ts +121 -0
  152. package/dist/types/shared/stream-access.d.ts +20 -0
  153. package/docs/API.md +45 -16
  154. package/docs/BACKUPS.md +31 -11
  155. package/docs/CLI.md +34 -61
  156. package/docs/DDNS.md +3 -1
  157. package/docs/NOTIFICATIONS.md +7 -1
  158. package/docs/REVERSE_PROXY.md +7 -1
  159. package/docs/SECURITY.md +21 -10
  160. package/docs/SERVERS.md +102 -23
  161. package/docs/UI_CREATION.md +10 -1
  162. package/docs/demo/blank-host-restore.sh +4 -3
  163. package/package.json +5 -7
  164. package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +1 -0
  165. package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +1 -0
  166. package/uis/stock/dist/assets/LogViewer-DIliXy62.js +1 -0
  167. package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +1 -0
  168. package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +39 -0
  169. package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +1 -0
  170. package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +2 -0
  171. package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +1 -0
  172. package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +2 -0
  173. package/uis/stock/dist/assets/de-BRITeb0H.js +1 -0
  174. package/uis/stock/dist/assets/es-B2zIEssV.js +1 -0
  175. package/uis/stock/dist/assets/fr-s0ZOBEqh.js +1 -0
  176. package/uis/stock/dist/assets/index-C1MehbKy.css +2 -0
  177. package/uis/stock/dist/assets/index-CnBN54wF.js +15 -0
  178. package/uis/stock/dist/assets/ja-CU7MR85V.js +1 -0
  179. package/uis/stock/dist/assets/ko-tL5Me6d-.js +1 -0
  180. package/uis/stock/dist/assets/ru-92yrvkNJ.js +1 -0
  181. package/uis/stock/dist/assets/vi-CzvY16k2.js +1 -0
  182. package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +1 -0
  183. package/uis/stock/dist/index.html +3 -2
  184. package/uis/stock/dist/ui.json +3 -3
  185. package/dist/chunks/archive-DpCwA8Nf.js.map +0 -1
  186. package/dist/chunks/atomic-CEfCUfkQ.js.map +0 -1
  187. package/dist/chunks/backup-CPrJVPJI.js.map +0 -1
  188. package/dist/chunks/backups-Bd2SF2qd.js.map +0 -1
  189. package/dist/chunks/contracts-ku5ypHXJ.js.map +0 -1
  190. package/dist/chunks/daemon-TwXk5vb8.js.map +0 -1
  191. package/dist/chunks/docker-CGv4Uv7w.js.map +0 -1
  192. package/dist/chunks/down-BlX5X3bm.js.map +0 -1
  193. package/dist/chunks/init-DdmqHVra.js.map +0 -1
  194. package/dist/chunks/last-stop-BZ08Z89-.js.map +0 -1
  195. package/dist/chunks/log-buffer-HnP0jKhZ.js.map +0 -1
  196. package/dist/chunks/logs-gI_69Q1P.js.map +0 -1
  197. package/dist/chunks/nanny-20aBXL1o.js.map +0 -1
  198. package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +0 -1
  199. package/dist/chunks/paths-BT94q6-w.js.map +0 -1
  200. package/dist/chunks/restart-UZgeDukG.js.map +0 -1
  201. package/dist/chunks/schema-o7Lgk0V1.js.map +0 -1
  202. package/dist/chunks/secrets-D7PdYh71.js.map +0 -1
  203. package/dist/chunks/set-password-DegMumPh.js.map +0 -1
  204. package/dist/chunks/set-token-21d1FTDC.js.map +0 -1
  205. package/dist/chunks/settings-BVSBnIwJ.js.map +0 -1
  206. package/dist/chunks/setup-temp-XiuAtiW2.js.map +0 -1
  207. package/dist/chunks/src-BL97vLVb.js.map +0 -1
  208. package/dist/chunks/status-EuWdRq8Q.js.map +0 -1
  209. package/dist/chunks/ui-DbPuwddJ.js.map +0 -1
  210. package/dist/chunks/up-C4H13hBw.js.map +0 -1
  211. package/dist/chunks/usage-CSBgLRN5.js.map +0 -1
  212. package/dist/chunks/workspaces-CAln2sQ7.js.map +0 -1
  213. package/docs/RESTORE_DEMO.md +0 -306
  214. package/uis/stock/dist/assets/de-DyGrM1KK.js +0 -1
  215. package/uis/stock/dist/assets/es-BebHdc0E.js +0 -1
  216. package/uis/stock/dist/assets/fr-DsDTrxhI.js +0 -1
  217. package/uis/stock/dist/assets/index-6LANO2Ua.css +0 -2
  218. package/uis/stock/dist/assets/index-D06cUZbM.js +0 -56
  219. package/uis/stock/dist/assets/ja-D3RARJjW.js +0 -1
  220. package/uis/stock/dist/assets/ko-CKI3dFoD.js +0 -1
  221. package/uis/stock/dist/assets/ru-DEU5ujXt.js +0 -1
  222. package/uis/stock/dist/assets/vi-ULKPnasj.js +0 -1
  223. package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +0 -1
@@ -1,22 +1,23 @@
1
1
  import { C as errorMessage, t as appVersion } from "../cli.js";
2
- import { t as writeFileAtomic } from "./atomic-CEfCUfkQ.js";
2
+ import { f as projectDir, i as ensureStateDir, r as dataRoot, x as resolveUserPath } from "./paths-CGlGDrOU.js";
3
+ import { t as writeFileAtomic } from "./atomic-C1PfJpE7.js";
3
4
  import { n as readStateFile } from "./config-text-DifCHhnz.js";
4
5
  import { t as logger } from "./logger-B5U4GD3j.js";
5
6
  import { t as isRecord } from "./shape-DnTKzjQ2.js";
6
- import { c as planConfigMigrations, i as parseWorkspaceSettings, n as parseServersFile, o as stampConfig, r as parseTolerant, s as applyConfigMigrations, t as parseGlobalSettings } from "./parse-B9owE47G.js";
7
- import { A as logsSchema, J as serverSchema, P as notificationsSchema, b as duplicateWebhookIds, g as defaultsSchema, lt as workspaceIdSchema, p as ddnsConfigSchema, x as entryStateSchema } from "./contracts-ku5ypHXJ.js";
8
- import { a as mergeDefaults, c as serversFileSchema, l as workspaceSettingsSchema } from "./schema-o7Lgk0V1.js";
9
- import { a as SEED_WORKSPACE_SETTINGS, c as NOTIFICATION_MERGE_KEYS, d as applyPatch, i as SEED_SERVERS_FILE, o as DDNS_MERGE_KEYS, s as EMPTY_MERGE_KEYS, t as ConfigError, u as SERVER_MERGE_KEYS } from "./settings-BVSBnIwJ.js";
10
- import { r as dataRoot, u as projectDir, y as resolveUserPath } from "./paths-BT94q6-w.js";
11
- import { r as workspacesFileSchema } from "./workspaces-CAln2sQ7.js";
12
- import { x as resolveCwd } from "./nanny-20aBXL1o.js";
13
- import { r as isProcessAlive } from "./port-B8WBTRMk.js";
14
- import { a as listZip, i as isZipArchive, n as extractZip, o as copyTree, r as isInvalidPassword, t as createZip } from "./archive-DpCwA8Nf.js";
7
+ import { c as planConfigMigrations, i as parseWorkspaceSettings, n as parseServersFile, o as stampConfig, r as parseTolerant, s as applyConfigMigrations, t as parseGlobalSettings } from "./parse-DhmG26fI.js";
8
+ import { F as notificationsSchema, S as entryStateSchema, Y as serverSchema, _ as defaultsSchema, j as logsSchema, m as ddnsConfigSchema, ut as workspaceIdSchema, x as duplicateWebhookIds } from "./contracts-CMBD1TF9.js";
9
+ import { a as mergeDefaults, c as serversFileSchema, l as workspaceSettingsSchema } from "./schema-B240VXcV.js";
10
+ import { a as SEED_SERVERS_FILE, c as EMPTY_MERGE_KEYS, d as SERVER_MERGE_KEYS, f as applyPatch, l as NOTIFICATION_MERGE_KEYS, o as SEED_WORKSPACE_SETTINGS, r as assertSaveable, s as DDNS_MERGE_KEYS, t as ConfigError } from "./settings-xu-XTfWg.js";
11
+ import { r as workspacesFileSchema } from "./workspaces-DYcfvKV_.js";
12
+ import { C as resolveCwd } from "./nanny-COyCJXj9.js";
13
+ import { r as isProcessAlive } from "./port-k5VBw8t9.js";
14
+ import { a as listZip, i as isZipArchive, n as extractZip, o as copyTree, r as isInvalidPassword, t as createZip } from "./archive-DP-XQR8X.js";
15
15
  import process from "node:process";
16
16
  import path from "node:path";
17
17
  import fs from "node:fs";
18
18
  import { type } from "arktype";
19
19
  import { Buffer } from "node:buffer";
20
+ import { createHash } from "node:crypto";
20
21
  import os from "node:os";
21
22
  import { spawn } from "node:child_process";
22
23
  import { DetailedError } from "@namesmt/utils";
@@ -1610,10 +1611,11 @@ async function sendWebhook(target, event, fetchImpl) {
1610
1611
  const payload = webhookPayload(event);
1611
1612
  const asText = target.format === "text";
1612
1613
  const body = asText ? payload.message : JSON.stringify(payload);
1613
- const url = expandEnv(target.url.trim(), process.env);
1614
+ const configured = target.url.trim();
1615
+ const url = expandEnv(configured, process.env);
1614
1616
  if (url.includes("${")) return {
1615
1617
  ok: false,
1616
- error: `the URL still holds an unexpanded placeholder: ${url}`
1618
+ error: `the URL still holds an unexpanded placeholder: ${configured}`
1617
1619
  };
1618
1620
  const sent = { "content-type": asText ? "text/plain; charset=utf-8" : "application/json" };
1619
1621
  for (const [name, value] of Object.entries(headers)) {
@@ -1626,8 +1628,16 @@ async function sendWebhook(target, event, fetchImpl) {
1626
1628
  method: target.method,
1627
1629
  headers: sent,
1628
1630
  body,
1629
- signal: AbortSignal.timeout(1e4)
1631
+ signal: AbortSignal.timeout(1e4),
1632
+ redirect: "manual"
1630
1633
  });
1634
+ if (response.status >= 300 && response.status < 400) {
1635
+ const location = response.headers.get("location");
1636
+ return {
1637
+ ok: false,
1638
+ error: `answered ${response.status}, a redirect${location === null ? "" : ` to ${location.slice(0, 200)}`} — not followed; set the URL to the final address`
1639
+ };
1640
+ }
1631
1641
  if (!response.ok) {
1632
1642
  const trimmed = (await response.text().catch(() => "")).trim().slice(0, 200);
1633
1643
  return {
@@ -1639,7 +1649,7 @@ async function sendWebhook(target, event, fetchImpl) {
1639
1649
  } catch (error) {
1640
1650
  return {
1641
1651
  ok: false,
1642
- error: errorMessage(error)
1652
+ error: errorMessage(error).replaceAll(url, configured)
1643
1653
  };
1644
1654
  }
1645
1655
  }
@@ -1699,8 +1709,15 @@ var WorkspaceStore = class {
1699
1709
  rawServers = {};
1700
1710
  liveSettings = null;
1701
1711
  liveServers = null;
1702
- lastSettingsText = null;
1703
- lastServersText = null;
1712
+ /** The bytes behind `liveSettings`/`liveServers`: the last revision that parsed. */
1713
+ liveSettingsText = null;
1714
+ liveServersText = null;
1715
+ /** The bytes behind `rawSettings`/`rawServers`, the objects a save patches: what a save may replace. */
1716
+ trustedSettingsText = null;
1717
+ trustedServersText = null;
1718
+ /** The bytes last looked at, so an unchanged file (ours, or a broken edit) is not re-read. */
1719
+ seenSettingsText = null;
1720
+ seenServersText = null;
1704
1721
  resolvedConfig;
1705
1722
  /** A JSON parse failure, kept apart from a schema problem so `apply()` cannot clear it. */
1706
1723
  settingsParseError = null;
@@ -1711,6 +1728,7 @@ var WorkspaceStore = class {
1711
1728
  settingsSchemaVersion = 1;
1712
1729
  serversSchemaVersion = 1;
1713
1730
  listeners = /* @__PURE__ */ new Set();
1731
+ conflictListeners = /* @__PURE__ */ new Set();
1714
1732
  constructor(workspaceId, settingsFile, serversFile, seedSettings = SEED_WORKSPACE_SETTINGS, seedServers = SEED_SERVERS_FILE) {
1715
1733
  this.workspaceId = workspaceId;
1716
1734
  this.settingsFile = settingsFile;
@@ -1780,6 +1798,11 @@ var WorkspaceStore = class {
1780
1798
  this.listeners.add(listener);
1781
1799
  return () => this.listeners.delete(listener);
1782
1800
  }
1801
+ /** Told when a save was refused because a file changed on disk, so its owner can reload it. */
1802
+ onConflict(listener) {
1803
+ this.conflictListeners.add(listener);
1804
+ return () => this.conflictListeners.delete(listener);
1805
+ }
1783
1806
  /** How many listeners are attached; a disposed owner must not add to it. */
1784
1807
  get listenerCount() {
1785
1808
  return this.listeners.size;
@@ -1787,8 +1810,9 @@ var WorkspaceStore = class {
1787
1810
  getServer(id) {
1788
1811
  return this.servers.find((server) => server.id === id);
1789
1812
  }
1790
- load() {
1791
- this.read();
1813
+ /** Reads both files, seeding a missing one; `{ write: false }` reads a missing file as its seed without creating it. */
1814
+ load(options = {}) {
1815
+ this.read(options.write !== false);
1792
1816
  this.apply();
1793
1817
  this.notify();
1794
1818
  }
@@ -1816,29 +1840,28 @@ var WorkspaceStore = class {
1816
1840
  let applied = false;
1817
1841
  for (const side of ["settings", "servers"]) {
1818
1842
  const read = side === "settings" ? settings : servers;
1819
- const lastText = side === "settings" ? this.lastSettingsText : this.lastServersText;
1843
+ const seen = side === "settings" ? this.seenSettingsText : this.seenServersText;
1820
1844
  const file = side === "settings" ? this.settingsFile : this.serversFile;
1821
- if (read.text !== lastText) {
1822
- changed = true;
1823
- if (side === "settings") this.lastSettingsText = read.text;
1824
- else this.lastServersText = read.text;
1825
- }
1845
+ if (read.text === seen) continue;
1846
+ changed = true;
1847
+ if (side === "settings") this.seenSettingsText = read.text;
1848
+ else this.seenServersText = read.text;
1826
1849
  if (read.parseError !== null) {
1827
1850
  const message = `cannot parse ${path.basename(file)}: ${read.parseError}`;
1828
1851
  if (side === "settings") this.settingsParseError = message;
1829
1852
  else this.serversParseError = message;
1830
1853
  continue;
1831
1854
  }
1832
- if (read.text !== lastText) {
1833
- if (side === "settings") {
1834
- this.settingsParseError = null;
1835
- this.liveSettings = read.parsed;
1836
- } else {
1837
- this.serversParseError = null;
1838
- this.liveServers = read.parsed;
1839
- }
1840
- applied = true;
1855
+ if (side === "settings") {
1856
+ this.settingsParseError = null;
1857
+ this.liveSettings = read.parsed;
1858
+ this.liveSettingsText = read.text;
1859
+ } else {
1860
+ this.serversParseError = null;
1861
+ this.liveServers = read.parsed;
1862
+ this.liveServersText = read.text;
1841
1863
  }
1864
+ applied = true;
1842
1865
  }
1843
1866
  if (!changed && !applied && this.configError === null) return {
1844
1867
  changed: false,
@@ -1858,12 +1881,12 @@ var WorkspaceStore = class {
1858
1881
  if (file === this.settingsFile) this.settingsError = message;
1859
1882
  else this.serversError = message;
1860
1883
  }
1861
- read() {
1884
+ read(write = true) {
1862
1885
  let settings = readFile(this.settingsFile);
1863
1886
  if (settings.missing) {
1864
1887
  const seed = stampConfig(structuredClone(this.seedSettings));
1865
1888
  const text = `${JSON.stringify(seed, null, 2)}\n`;
1866
- writeFileAtomic(this.settingsFile, text);
1889
+ if (write) writeFileAtomic(this.settingsFile, text);
1867
1890
  settings = {
1868
1891
  text,
1869
1892
  parsed: seed,
@@ -1875,7 +1898,7 @@ var WorkspaceStore = class {
1875
1898
  if (servers.missing) {
1876
1899
  const seed = stampConfig(structuredClone(this.seedServers));
1877
1900
  const text = `${JSON.stringify(seed, null, 2)}\n`;
1878
- writeFileAtomic(this.serversFile, text);
1901
+ if (write) writeFileAtomic(this.serversFile, text);
1879
1902
  servers = {
1880
1903
  text,
1881
1904
  parsed: seed,
@@ -1883,14 +1906,18 @@ var WorkspaceStore = class {
1883
1906
  parseError: null
1884
1907
  };
1885
1908
  }
1886
- this.lastSettingsText = settings.text;
1887
- this.lastServersText = servers.text;
1888
- this.liveSettings = settings.parsed;
1889
- this.liveServers = servers.parsed;
1909
+ this.seenSettingsText = settings.text;
1910
+ this.seenServersText = servers.text;
1890
1911
  this.settingsParseError = settings.parseError === null ? null : `cannot parse ${path.basename(this.settingsFile)}: ${settings.parseError}`;
1891
1912
  this.serversParseError = servers.parseError === null ? null : `cannot parse ${path.basename(this.serversFile)}: ${servers.parseError}`;
1892
- if (settings.parseError === null) this.liveSettings = settings.parsed;
1893
- if (servers.parseError === null) this.liveServers = servers.parsed;
1913
+ if (settings.parseError === null) {
1914
+ this.liveSettings = settings.parsed;
1915
+ this.liveSettingsText = settings.text;
1916
+ }
1917
+ if (servers.parseError === null) {
1918
+ this.liveServers = servers.parsed;
1919
+ this.liveServersText = servers.text;
1920
+ }
1894
1921
  }
1895
1922
  notify() {
1896
1923
  for (const listener of this.listeners) listener();
@@ -2020,20 +2047,32 @@ var WorkspaceStore = class {
2020
2047
  };
2021
2048
  }
2022
2049
  commitSettings(draft) {
2050
+ assertSaveable(this.settingsFile, {
2051
+ trusted: this.trustedSettingsText,
2052
+ seen: this.seenSettingsText,
2053
+ unusable: this.settingsParseError ?? this.settingsError
2054
+ }, this.conflictListeners);
2023
2055
  const stamped = stampConfig(draft);
2024
2056
  const text = `${JSON.stringify(stamped, null, 2)}\n`;
2025
2057
  writeFileAtomic(this.settingsFile, text);
2026
- this.lastSettingsText = text;
2058
+ this.seenSettingsText = text;
2059
+ this.liveSettingsText = text;
2027
2060
  this.liveSettings = stamped;
2028
2061
  this.settingsParseError = null;
2029
2062
  this.apply();
2030
2063
  this.notify();
2031
2064
  }
2032
2065
  commitServers(draft) {
2066
+ assertSaveable(this.serversFile, {
2067
+ trusted: this.trustedServersText,
2068
+ seen: this.seenServersText,
2069
+ unusable: this.serversParseError ?? this.serversError
2070
+ }, this.conflictListeners);
2033
2071
  const stamped = stampConfig(draft);
2034
2072
  const text = `${JSON.stringify(stamped, null, 2)}\n`;
2035
2073
  writeFileAtomic(this.serversFile, text);
2036
- this.lastServersText = text;
2074
+ this.seenServersText = text;
2075
+ this.liveServersText = text;
2037
2076
  this.liveServers = stamped;
2038
2077
  this.serversParseError = null;
2039
2078
  this.apply();
@@ -2041,8 +2080,9 @@ var WorkspaceStore = class {
2041
2080
  }
2042
2081
  apply() {
2043
2082
  const settings = parseWorkspaceSettings(this.liveSettings);
2044
- const servers = parseServersFile(this.liveServers, settings.config?.defaults ?? {});
2045
2083
  const haveResolved = this.resolvedConfig !== void 0;
2084
+ const defaults = settings.config?.defaults ?? (haveResolved ? this.resolvedConfig.defaults : void 0);
2085
+ const servers = parseServersFile(this.liveServers, defaults ?? {});
2046
2086
  this.settingsError = this.settingsParseError ?? (settings.errors.length > 0 ? settings.errors.join("; ") : null);
2047
2087
  this.serversError = this.serversParseError ?? (servers.errors.length > 0 ? servers.errors.join("; ") : null);
2048
2088
  this.settingsSchemaVersion = settings.schemaVersion;
@@ -2063,8 +2103,14 @@ var WorkspaceStore = class {
2063
2103
  ...settingsConfig,
2064
2104
  servers: nextServers
2065
2105
  };
2066
- if (settings.config !== null) this.rawSettings = structuredClone(this.liveSettings);
2067
- if (servers.errors.length === 0) this.rawServers = structuredClone(this.liveServers);
2106
+ if (settings.config !== null) {
2107
+ this.rawSettings = structuredClone(this.liveSettings);
2108
+ this.trustedSettingsText = this.liveSettingsText;
2109
+ }
2110
+ if (servers.errors.length === 0) {
2111
+ this.rawServers = structuredClone(this.liveServers);
2112
+ this.trustedServersText = this.liveServersText;
2113
+ }
2068
2114
  }
2069
2115
  resolveSettingsFallback() {
2070
2116
  const defaults = defaultsSchema({});
@@ -2311,7 +2357,7 @@ function isLiveHolder(record) {
2311
2357
  */
2312
2358
  function acquireRestoreLock(hhDir, action = "restore") {
2313
2359
  const file = path.join(hhDir, "restore.lock");
2314
- fs.mkdirSync(hhDir, { recursive: true });
2360
+ ensureStateDir(hhDir);
2315
2361
  const mine = {
2316
2362
  pid: process.pid,
2317
2363
  startedAt: Date.now(),
@@ -2471,7 +2517,7 @@ async function runBackupHook(hook, server, dumpDir, options = {}) {
2471
2517
  };
2472
2518
  const cwd = resolveCwd(server.cwd);
2473
2519
  const args = resolveTemplates(hook.args, vars);
2474
- if (options.requireDumpDir !== false) fs.mkdirSync(dumpDir, { recursive: true });
2520
+ if (options.requireDumpDir !== false) ensureStateDir(dumpDir);
2475
2521
  let child;
2476
2522
  try {
2477
2523
  child = spawn(hook.command, args, {
@@ -2577,6 +2623,56 @@ function selectionOf(options) {
2577
2623
  return selects;
2578
2624
  }
2579
2625
  /**
2626
+ * The panel-wide entries, declared once.
2627
+ *
2628
+ * The restore's own item list and the credential guard both read this, so "which item is the
2629
+ * credential file" cannot be answered two ways — which it was: the guard tested the exact id while
2630
+ * the restore also honoured the alias, so `include: ["secrets"]` selected the item and skipped the
2631
+ * guard. A second string literal at the guard would be the same defect one rename later.
2632
+ */
2633
+ var GLOBAL_RESTORE_ITEMS = {
2634
+ settings: {
2635
+ id: "global:settings",
2636
+ aliases: ["config"]
2637
+ },
2638
+ credentials: {
2639
+ id: "global:secrets",
2640
+ aliases: ["secrets"]
2641
+ },
2642
+ tls: {
2643
+ id: "global:tls",
2644
+ aliases: ["tls"]
2645
+ }
2646
+ };
2647
+ /**
2648
+ * The one rule for "does this selection choose this item", aliases included.
2649
+ *
2650
+ * An exclusion beats an alias (`--exclude global:secrets` must not be undone by the item's own
2651
+ * short alias selecting it back in), then any of the item's ids may select it.
2652
+ */
2653
+ function selectedBy(selects, item) {
2654
+ const aliases = item.aliases ?? [];
2655
+ return !(selects.isExcluded(item.id) || aliases.some((alias) => selects.isExcluded(alias))) && (selects(item.id) || aliases.some((alias) => selects(alias)));
2656
+ }
2657
+ /**
2658
+ * Whether a selection reaches anything inside one item: the item itself, an alias, or a leaf of it.
2659
+ *
2660
+ * A leaf counts because selection is downwards only — naming `global:secrets:password` does not
2661
+ * select `global:secrets` — yet the restore still writes that one field of the same file.
2662
+ *
2663
+ * Both spellings of a leaf are recognised (`global:secrets:password` and its alias
2664
+ * `secrets:password`), because an exclusion the person wrote as `--exclude secrets` reaches the
2665
+ * leaves of that item through `selectionOf`'s prefix rule. Answering "the item is untouched" there
2666
+ * while the restore still wrote its leaves was a real bypass: `{"exclude":["secrets"]}` — the
2667
+ * spelling the docs recommend to leave credentials behind — rewrote the password and token hashes.
2668
+ */
2669
+ function selectionTouches(options, item) {
2670
+ const selects = selectionOf(options);
2671
+ const prefixes = [item.id, ...item.aliases ?? []];
2672
+ if ((options.include ?? []).some((id) => prefixes.some((prefix) => id.startsWith(`${prefix}:`)) && selects(id))) return true;
2673
+ return selectedBy(selects, item);
2674
+ }
2675
+ /**
2580
2676
  * Whether a restore selection would write the panel's own credential store.
2581
2677
  *
2582
2678
  * `global:secrets` holds the password hash and the API token hash, so a restore that carries it can
@@ -2589,13 +2685,7 @@ function selectionOf(options) {
2589
2685
  * site. It answers *whether* the store is touched; who may touch it is the route's decision.
2590
2686
  */
2591
2687
  function selectionWritesCredentials(options) {
2592
- const selects = selectionOf(options);
2593
- return selects("global:secrets") || [
2594
- "password",
2595
- "apiToken",
2596
- "telegram",
2597
- "ddns"
2598
- ].some((key) => selects(`global:secrets:${key}`));
2688
+ return selectionTouches(options, GLOBAL_RESTORE_ITEMS.credentials);
2599
2689
  }
2600
2690
  /**
2601
2691
  * Which of `ids` name nothing the panel can capture.
@@ -2729,6 +2819,20 @@ var AUTO_PREFIX = "auto";
2729
2819
  var MANUAL_PREFIX = "backup";
2730
2820
  /** The names `create()` writes; retention counts and prunes only these, never a zip someone else put here. */
2731
2821
  var ARCHIVE_NAME = new RegExp(`^(${AUTO_PREFIX}|${MANUAL_PREFIX})-\\d{4}(?:-\\d{2}){5}-\\d{1,3}\\.zip$`);
2822
+ var ARCHIVE_STAMP = /-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{1,3})\.zip$/;
2823
+ /**
2824
+ * When `create()` wrote an archive, read from its name (UTC, to the millisecond), or null for a name
2825
+ * it did not write. The name survives a copy, a sync tool or a restore from another disk; the mtime
2826
+ * does not, and ordering by it made retention prune the wrong archive.
2827
+ */
2828
+ function archiveStamp(name) {
2829
+ if (!ARCHIVE_NAME.test(name)) return null;
2830
+ const parts = ARCHIVE_STAMP.exec(name)?.slice(1).map(Number);
2831
+ if (parts === void 0 || parts.length !== 7) return null;
2832
+ const [year, month, day, hour, minute, second, ms] = parts;
2833
+ const at = Date.UTC(year, month - 1, day, hour, minute, second, ms);
2834
+ return Number.isFinite(at) ? at : null;
2835
+ }
2732
2836
  /** A workspace leaf that carries state the panel re-reads after a restore. */
2733
2837
  var RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/;
2734
2838
  /**
@@ -2973,6 +3077,38 @@ function buildBackupSources(input) {
2973
3077
  };
2974
3078
  }
2975
3079
  /**
3080
+ * Pairs each archived data path with the declaration that will receive it.
3081
+ *
3082
+ * A **factory**, not a plain function: pairing consumes both lists — one target is claimed by one
3083
+ * archive entry — so the two `used` sets are the state a naive call would lose. A pair of same-origin
3084
+ * declarations is the case that needs it: a `global` include path and a second `backupPaths` value
3085
+ * share one origin, so matching by origin alone would write both onto the first candidate. Pairing by
3086
+ * order instead, because the archive wrote them in the same resolve order.
3087
+ *
3088
+ * Never across a workspace boundary: an archive entry that names a workspace is only matched against
3089
+ * that workspace's declarations. The un-scoped fallbacks exist to survive a re-labelled or re-ordered
3090
+ * config, and letting them cross workspaces wrote one workspace's data over a path another one had
3091
+ * declared. A path only one workspace declares has no candidate in the other, so the entry is
3092
+ * reported rather than guessed at.
3093
+ */
3094
+ function dataTargetMatcher(archiveTargets, instanceTargets) {
3095
+ const usedArchive = /* @__PURE__ */ new Set();
3096
+ const usedInstance = /* @__PURE__ */ new Set();
3097
+ const take = (list, used, test) => {
3098
+ const found = list.find((target) => !used.has(target) && test(target));
3099
+ if (found === void 0) return void 0;
3100
+ used.add(found);
3101
+ return found;
3102
+ };
3103
+ return (origin, workspace, archivedPath) => {
3104
+ const inScope = (target) => workspace === void 0 || target.workspace === workspace;
3105
+ const archive = archiveTargets.filter(inScope);
3106
+ const instance = instanceTargets.filter(inScope);
3107
+ if (origin !== void 0) return take(archive, usedArchive, (target) => target.origin === origin) ?? take(instance, usedInstance, (target) => target.origin === origin) ?? take(archive, usedArchive, (target) => target.path === archivedPath) ?? take(instance, usedInstance, (target) => target.path === archivedPath);
3108
+ return take(archive, usedArchive, (target) => target.path === archivedPath) ?? take(instance, usedInstance, (target) => target.path === archivedPath);
3109
+ };
3110
+ }
3111
+ /**
2976
3112
  * An archived config, lifted to the schema this release reads.
2977
3113
  *
2978
3114
  * An archive is a snapshot, so the release that wrote it is often **older** than the one restoring
@@ -3068,8 +3204,37 @@ function safeSlug(slug) {
3068
3204
  function cacheKey(file) {
3069
3205
  return `${file.sizeBytes}:${file.createdAt}`;
3070
3206
  }
3071
- /** Stable, filesystem-safe name for a data path inside the archive. */
3207
+ /** True when the tree at `root` contains at least one file (stops at the first). */
3208
+ function holdsAnyFile(root) {
3209
+ let stats;
3210
+ try {
3211
+ stats = fs.lstatSync(root);
3212
+ } catch {
3213
+ return false;
3214
+ }
3215
+ if (!stats.isDirectory()) return stats.isFile();
3216
+ let names;
3217
+ try {
3218
+ names = fs.readdirSync(root);
3219
+ } catch {
3220
+ return false;
3221
+ }
3222
+ return names.some((name) => holdsAnyFile(path.join(root, name)));
3223
+ }
3224
+ /**
3225
+ * Stable, filesystem-safe name for a data path inside the archive.
3226
+ *
3227
+ * The readable part alone collided — `/srv/app-data`, `/srv/app/data` and `/srv/app data` all read
3228
+ * `srv-app-data`, and every path after the first was silently left out — so it carries a short hash
3229
+ * of the resolved path. A restore reads the slug from the manifest, so archives written with the
3230
+ * hashless form still restore.
3231
+ */
3072
3232
  function slugifyPath(target) {
3233
+ const hash = createHash("sha256").update(path.resolve(target)).digest("hex").slice(0, 8);
3234
+ return `${legacySlug(target).slice(-71)}-${hash}`;
3235
+ }
3236
+ /** The hashless slug archives were written with before; only a manifest without a slug falls back to it. */
3237
+ function legacySlug(target) {
3073
3238
  const cleaned = target.replace(/[^A-Z0-9]+/gi, "-").replace(/^-+|-+$/g, "");
3074
3239
  return cleaned.length > 0 ? cleaned.slice(-80) : "path";
3075
3240
  }
@@ -3089,6 +3254,23 @@ function readText(file) {
3089
3254
  return null;
3090
3255
  }
3091
3256
  }
3257
+ /** The plan a restore starts from: every field filled, so a refusal is a plan and not a throw. */
3258
+ function newRestorePlan(options) {
3259
+ return {
3260
+ dryRun: !options.confirm,
3261
+ encrypted: false,
3262
+ needsPassword: false,
3263
+ items: [],
3264
+ applied: [],
3265
+ appliedIds: [],
3266
+ skipped: [],
3267
+ skippedItems: [],
3268
+ restartRequired: false,
3269
+ reloaded: false,
3270
+ createdWorkspaces: [],
3271
+ replacedUnderRunning: []
3272
+ };
3273
+ }
3092
3274
  /**
3093
3275
  * Archives of the control plane's own state plus whatever paths the configs
3094
3276
  * declare. Two rules keep restore safe: the archive layout is an allowlist, and
@@ -3118,6 +3300,12 @@ var BackupService = class {
3118
3300
  * long as the failure lasts. This is the in-memory backstop for that case.
3119
3301
  */
3120
3302
  lastAttemptAt = null;
3303
+ /**
3304
+ * The newest automatic archive, remembered rather than re-listed: `tick()` and `view()` run every
3305
+ * second, and each used to `readdir` + `stat` the whole archive directory. Seeded once per
3306
+ * directory, moved forward by `create()`, dropped when an archive is removed.
3307
+ */
3308
+ lastAutomaticSeen = null;
3121
3309
  /** Logs a pass deferred by a running restore once, not on every tick. */
3122
3310
  deferredForRestore = false;
3123
3311
  /** Why the most recent scheduled pass failed, cleared by the next that works. */
@@ -3223,7 +3411,7 @@ var BackupService = class {
3223
3411
  const name = `${options.automatic === true ? AUTO_PREFIX : MANUAL_PREFIX}-${new Date(createdAt).toISOString().replace(/[:T]/g, "-").replace(/\.\d+Z$/, "")}-${createdAt % 1e3}${SUFFIX}`;
3224
3412
  const destination = path.join(dir, name);
3225
3413
  try {
3226
- fs.mkdirSync(staging, { recursive: true });
3414
+ ensureStateDir(staging);
3227
3415
  let captured = 0;
3228
3416
  const copy = async (relative, source, ignoreGenerated = false) => {
3229
3417
  if (await this.copyInto(staging, relative, source, ignoreGenerated)) captured++;
@@ -3261,7 +3449,7 @@ var BackupService = class {
3261
3449
  const chosen = fields === null ? withoutInitialPassword(text) : pickSecrets(parseSecrets(text), fields);
3262
3450
  if (chosen === null) return;
3263
3451
  const target = path.join(staging, relative);
3264
- fs.mkdirSync(path.dirname(target), { recursive: true });
3452
+ ensureStateDir(path.dirname(target));
3265
3453
  fs.writeFileSync(target, chosen.endsWith("\n") ? chosen : `${chosen}\n`, { mode: 384 });
3266
3454
  captured++;
3267
3455
  };
@@ -3305,6 +3493,7 @@ var BackupService = class {
3305
3493
  });
3306
3494
  }
3307
3495
  const data = [];
3496
+ const warnings = [];
3308
3497
  for (const workspace of sources.workspaces) {
3309
3498
  const root = `workspaces/${workspace.id}`;
3310
3499
  if (capturesWorkspace(workspace.id, "settings")) await copy(`${root}/settings.json`, workspace.settingsPath);
@@ -3314,8 +3503,9 @@ var BackupService = class {
3314
3503
  if (!declared.included) continue;
3315
3504
  if (!capturesWorkspace(workspace.id, `data:${declared.path}`)) continue;
3316
3505
  if (!fs.existsSync(declared.path)) continue;
3506
+ const resolved = path.resolve(declared.path);
3507
+ if (data.some((entry) => path.resolve(entry.path) === resolved)) continue;
3317
3508
  const slug = slugifyPath(declared.path);
3318
- if (data.some((entry) => entry.slug === slug)) continue;
3319
3509
  if (!await this.copyInto(staging, path.join("data", slug), declared.path, declared.ignoreGenerated)) continue;
3320
3510
  captured++;
3321
3511
  data.push({
@@ -3324,6 +3514,7 @@ var BackupService = class {
3324
3514
  origin: declared.origin,
3325
3515
  workspace: workspace.id
3326
3516
  });
3517
+ if (!holdsAnyFile(path.join(staging, "data", slug))) warnings.push(`"${declared.path}" was captured but holds no files`);
3327
3518
  }
3328
3519
  }
3329
3520
  if ((wanted !== null || (options.exclude?.length ?? 0) > 0) && captured === 0) {
@@ -3355,9 +3546,16 @@ var BackupService = class {
3355
3546
  this.sweepStaging();
3356
3547
  const stats = fs.statSync(destination);
3357
3548
  this.flags.set(name, {
3358
- key: `${stats.size}:${Math.round(stats.mtimeMs)}`,
3549
+ key: cacheKey({
3550
+ sizeBytes: stats.size,
3551
+ createdAt
3552
+ }),
3359
3553
  encrypted: password !== null
3360
3554
  });
3555
+ if (options.automatic === true && this.lastAutomaticSeen !== null && this.lastAutomaticSeen.dir === dir) this.lastAutomaticSeen = {
3556
+ dir,
3557
+ at: Math.max(this.lastAutomaticSeen.at ?? 0, createdAt)
3558
+ };
3361
3559
  return {
3362
3560
  ok: true,
3363
3561
  file: {
@@ -3365,7 +3563,8 @@ var BackupService = class {
3365
3563
  sizeBytes: stats.size,
3366
3564
  createdAt,
3367
3565
  encrypted: password !== null
3368
- }
3566
+ },
3567
+ ...warnings.length === 0 ? {} : { warnings }
3369
3568
  };
3370
3569
  } catch (error) {
3371
3570
  await fs.promises.rm(staging, {
@@ -3384,6 +3583,7 @@ var BackupService = class {
3384
3583
  if (file === null) return false;
3385
3584
  fs.rmSync(file, { force: true });
3386
3585
  this.flags.delete(name);
3586
+ if (isAutomatic({ name })) this.lastAutomaticSeen = null;
3387
3587
  return true;
3388
3588
  }
3389
3589
  /**
@@ -3406,530 +3606,669 @@ var BackupService = class {
3406
3606
  }
3407
3607
  async applyRestore(archivePath, options) {
3408
3608
  const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
3409
- const plan = {
3410
- dryRun: !options.confirm,
3411
- encrypted: false,
3412
- needsPassword: false,
3413
- items: [],
3414
- applied: [],
3415
- appliedIds: [],
3416
- skipped: [],
3417
- skippedItems: [],
3418
- restartRequired: false,
3419
- reloaded: false,
3420
- createdWorkspaces: [],
3421
- replacedUnderRunning: []
3422
- };
3609
+ const plan = newRestorePlan(options);
3423
3610
  const admitted = await admitArchive(archivePath);
3424
3611
  if (!admitted.ok) return {
3425
3612
  ...plan,
3426
3613
  error: admitted.error
3427
3614
  };
3428
- const entries = admitted.entries;
3429
3615
  const staging = path.join(this.resolveDir(), stagingDirName("restore"));
3430
3616
  try {
3431
- plan.encrypted = entries.some((entry) => entry.encrypted);
3432
- if (plan.encrypted && password === null) return {
3433
- ...plan,
3434
- needsPassword: true,
3435
- error: "this backup is password-protected"
3436
- };
3437
- fs.mkdirSync(staging, { recursive: true });
3438
- const extracted = await extractZip(archivePath, staging, {
3439
- names: entries.map((entry) => entry.name),
3440
- ...password === null ? {} : { password }
3441
- });
3442
- for (const name of extracted.skipped) {
3443
- plan.skipped.push(`${name} (symbolic link, skipped)`);
3444
- plan.skippedItems.push({
3445
- label: name,
3446
- reasonKey: "settings.restore.reasonSymbolicLink"
3447
- });
3617
+ const opened = await this.openArchive(plan, admitted.entries, archivePath, staging, password);
3618
+ if (!("ok" in opened)) return opened;
3619
+ const ctx = this.restoreContext(plan, options, opened.manifest, staging);
3620
+ const global = this.planGlobalItems(ctx);
3621
+ this.planWorkspaceItems(ctx);
3622
+ this.planDataItems(ctx, global);
3623
+ this.noteRestartRequired(ctx, global);
3624
+ if (!options.confirm) {
3625
+ plan.applied = [...ctx.actions.keys()].map((id) => labelOf(plan, id));
3626
+ plan.appliedIds = [...ctx.actions.keys()];
3627
+ return plan;
3448
3628
  }
3449
- const manifestPath = path.join(staging, MANIFEST);
3450
- if (!fs.existsSync(manifestPath)) return {
3451
- ...plan,
3452
- error: "the archive has no manifest"
3453
- };
3454
- const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
3455
- plan.archive = manifestInfo(manifest);
3456
- if (manifest.schema !== void 0 && manifest.schema > 2) return {
3629
+ const failure = await this.runApply(ctx);
3630
+ this.registerCreatedWorkspaces(ctx);
3631
+ if (failure !== null) {
3632
+ this.reloadRestored(plan);
3633
+ throw failure;
3634
+ }
3635
+ await this.stagePendingLoads(ctx);
3636
+ this.reloadRestored(plan);
3637
+ return plan;
3638
+ } catch (error) {
3639
+ if (isInvalidPassword(error)) return {
3457
3640
  ...plan,
3458
- error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 2`
3641
+ encrypted: true,
3642
+ needsPassword: true,
3643
+ error: "the password is wrong"
3459
3644
  };
3460
- if (!(manifest.dumps === void 0 || Array.isArray(manifest.dumps) && manifest.dumps.every((dump) => isRecord(dump) && !(workspaceIdSchema(dump.workspaceId) instanceof type.errors) && !(serverIdSchema(dump.serverId) instanceof type.errors)))) return {
3645
+ const done = plan.applied.length > 0 ? ` — already applied: ${plan.applied.join(", ")}` : "";
3646
+ return {
3461
3647
  ...plan,
3462
- error: "the archive's manifest names a dump with an invalid workspace or server id"
3463
- };
3464
- const sources = this.options.getSources();
3465
- const selects = selectionOf(options);
3466
- const actions = /* @__PURE__ */ new Map();
3467
- /**
3468
- * Writes one archived secrets file, **always** by field.
3469
- *
3470
- * Replacing the live file wholesale when nothing was excluded looked like the identity case, but
3471
- * an archive only carries what its own selection captured: restoring `global:secrets` from an
3472
- * archive taken with `--exclude global:secrets:apiToken` replaced the file with a document that
3473
- * had no `apiToken` in it, silently signing every script out. The live file may also hold a secret
3474
- * the archive predates. `mergeIntoFile` copies exactly the fields the archive carries and leaves
3475
- * every other key of the live file alone, which is the behaviour both cases want — and what every
3476
- * restore did before this rewrite.
3477
- */
3478
- const secretsApply = (scope, entryId, target, archived) => {
3479
- const take = secretParts(scope, presentSecretKeys(parseSecrets(archived))).filter((part) => !selects.isExcluded(`${entryId}:${part.key}`) && !part.fields.some((field) => selects.isExcluded(`${entryId}:${field}`)));
3480
- return () => {
3481
- fs.mkdirSync(path.dirname(target), { recursive: true });
3482
- mergeIntoFile(target, archived, take.flatMap((part) => part.fields));
3483
- };
3648
+ error: `${errorMessage(error)}${done}`
3484
3649
  };
3485
- const addItem = (item, apply, aliases = []) => {
3486
- if (apply === null) {
3487
- plan.items.push({
3488
- ...item,
3489
- selected: false
3490
- });
3491
- plan.skipped.push(`${item.label}${item.note === null ? "" : ` (${item.note})`}`);
3492
- plan.skippedItems.push({
3493
- label: item.label,
3494
- ...item.labelKey === void 0 ? {} : { labelKey: item.labelKey },
3495
- ...item.labelParams === void 0 ? {} : { labelParams: item.labelParams },
3496
- reasonKey: item.noteKey ?? "settings.restore.reasonUnrestorable",
3497
- ...item.noteParams === void 0 ? {} : { reasonParams: item.noteParams }
3498
- });
3499
- return;
3650
+ } finally {
3651
+ fs.rmSync(staging, {
3652
+ recursive: true,
3653
+ force: true
3654
+ });
3655
+ this.sweepStaging();
3656
+ }
3657
+ }
3658
+ /** The state every phase reads and writes, built once from the plan and the live sources. */
3659
+ restoreContext(plan, options, manifest, staging) {
3660
+ return {
3661
+ plan,
3662
+ options,
3663
+ sources: this.options.getSources(),
3664
+ staging,
3665
+ manifest,
3666
+ selects: selectionOf(options),
3667
+ actions: /* @__PURE__ */ new Map(),
3668
+ archivedServers: /* @__PURE__ */ new Map(),
3669
+ createdWorkspaces: /* @__PURE__ */ new Map()
3670
+ };
3671
+ }
3672
+ /**
3673
+ * Unpacks the archive and refuses it before anything is written.
3674
+ *
3675
+ * Everything here answers with a plan rather than throwing, because a refusal at this point has
3676
+ * changed nothing — `applyRestore` passes the answer straight back. The one throw is a wrong
3677
+ * password, which `extractZip` raises and `applyRestore`'s `catch` maps to `needsPassword`.
3678
+ *
3679
+ * Returns null when the archive is usable, after unpacking it into `staging`.
3680
+ */
3681
+ async openArchive(plan, entries, archivePath, staging, password) {
3682
+ plan.encrypted = entries.some((entry) => entry.encrypted);
3683
+ if (plan.encrypted && password === null) return {
3684
+ ...plan,
3685
+ needsPassword: true,
3686
+ error: "this backup is password-protected"
3687
+ };
3688
+ ensureStateDir(staging);
3689
+ const extracted = await extractZip(archivePath, staging, {
3690
+ names: entries.map((entry) => entry.name),
3691
+ ...password === null ? {} : { password }
3692
+ });
3693
+ for (const name of extracted.skipped) {
3694
+ plan.skipped.push(`${name} (symbolic link, skipped)`);
3695
+ plan.skippedItems.push({
3696
+ label: name,
3697
+ reasonKey: "settings.restore.reasonSymbolicLink"
3698
+ });
3699
+ }
3700
+ const manifestPath = path.join(staging, MANIFEST);
3701
+ if (!fs.existsSync(manifestPath)) return {
3702
+ ...plan,
3703
+ error: "the archive has no manifest"
3704
+ };
3705
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
3706
+ plan.archive = manifestInfo(manifest);
3707
+ if (manifest.schema !== void 0 && manifest.schema > 2) return {
3708
+ ...plan,
3709
+ error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 2`
3710
+ };
3711
+ if (!(manifest.dumps === void 0 || Array.isArray(manifest.dumps) && manifest.dumps.every((dump) => isRecord(dump) && !(workspaceIdSchema(dump.workspaceId) instanceof type.errors) && !(serverIdSchema(dump.serverId) instanceof type.errors)))) return {
3712
+ ...plan,
3713
+ error: "the archive's manifest names a dump with an invalid workspace or server id"
3714
+ };
3715
+ return {
3716
+ ok: true,
3717
+ manifest
3718
+ };
3719
+ }
3720
+ /**
3721
+ * The three global slices: settings, secrets (plus one leaf per secret), and the TLS pair.
3722
+ *
3723
+ * Returns the archive's own settings for the later phases, which decide data paths and whether
3724
+ * the listener must restart.
3725
+ */
3726
+ planGlobalItems(ctx) {
3727
+ const { plan, sources, staging, actions } = ctx;
3728
+ const { secretsApply, addItem } = this.itemWriters(ctx);
3729
+ const settingsText = readText(path.join(staging, "global", "settings.json"));
3730
+ const liftedGlobal = readableGlobalSettings(settingsText);
3731
+ const parsedGlobal = liftedGlobal === null ? null : parseGlobalSettings(liftedGlobal).config;
3732
+ if (settingsText !== null && parsedGlobal === null) {
3733
+ plan.skipped.push("Global settings (the archive's settings are not valid)");
3734
+ plan.skippedItems.push({
3735
+ label: "Global settings",
3736
+ labelKey: "settings.backup.entryGlobalSettings",
3737
+ reasonKey: "settings.restore.reasonInvalidSettings"
3738
+ });
3739
+ }
3740
+ if (parsedGlobal !== null && liftedGlobal !== null) {
3741
+ const globalText = `${JSON.stringify(liftedGlobal, null, 2)}\n`;
3742
+ addItem({
3743
+ id: GLOBAL_RESTORE_ITEMS.settings.id,
3744
+ label: "Global settings",
3745
+ labelKey: "settings.backup.entryGlobalSettings",
3746
+ kind: "settings",
3747
+ restorable: true,
3748
+ note: null
3749
+ }, () => {
3750
+ writeFileAtomic(sources.globalSettingsPath, globalText);
3751
+ }, [...GLOBAL_RESTORE_ITEMS.settings.aliases]);
3752
+ }
3753
+ const globalSecrets = readText(path.join(staging, "global", "secrets.json"));
3754
+ if (globalSecrets !== null) {
3755
+ addItem({
3756
+ id: GLOBAL_RESTORE_ITEMS.credentials.id,
3757
+ label: "Global secrets (password, API token)",
3758
+ labelKey: "settings.backup.entryGlobalSecrets",
3759
+ kind: "secrets",
3760
+ restorable: true,
3761
+ note: null
3762
+ }, secretsApply("global", GLOBAL_RESTORE_ITEMS.credentials.id, sources.globalSecretsPath, globalSecrets), [...GLOBAL_RESTORE_ITEMS.credentials.aliases]);
3763
+ for (const part of secretParts("global", presentSecretKeys(parseSecrets(globalSecrets)))) addItem({
3764
+ id: `${GLOBAL_RESTORE_ITEMS.credentials.id}:${part.key}`,
3765
+ label: `Global secrets: ${SECRET_LABELS[part.key]?.en ?? part.key}`,
3766
+ labelKey: "settings.backup.restoreItemLabel",
3767
+ labelParams: {
3768
+ workspace: "global",
3769
+ item: part.key
3770
+ },
3771
+ kind: "secrets",
3772
+ restorable: true,
3773
+ note: null
3774
+ }, () => {
3775
+ if (actions.has(GLOBAL_RESTORE_ITEMS.credentials.id)) return;
3776
+ mergeIntoFile(sources.globalSecretsPath, globalSecrets, part.fields);
3777
+ }, GLOBAL_RESTORE_ITEMS.credentials.aliases.map((alias) => `${alias}:${part.key}`));
3778
+ }
3779
+ const tlsInArchive = path.join(staging, "global", "tls");
3780
+ if (fs.existsSync(tlsInArchive)) {
3781
+ const files = fs.readdirSync(tlsInArchive).filter((file) => fs.statSync(path.join(tlsInArchive, file)).isFile());
3782
+ addItem({
3783
+ id: GLOBAL_RESTORE_ITEMS.tls.id,
3784
+ label: "TLS certificate",
3785
+ labelKey: "settings.backup.entryTlsCertificate",
3786
+ kind: "tls",
3787
+ restorable: true,
3788
+ note: null
3789
+ }, () => {
3790
+ ensureStateDir(sources.tlsDir);
3791
+ for (const file of files) {
3792
+ const mode = file.endsWith(".key.pem") ? { mode: 384 } : {};
3793
+ writeFileAtomic(path.join(sources.tlsDir, file), fs.readFileSync(path.join(tlsInArchive, file), "utf8"), mode);
3500
3794
  }
3501
- const selected = !(selects.isExcluded(item.id) || aliases.some((alias) => selects.isExcluded(alias))) && (selects(item.id) || aliases.some((alias) => selects(alias)));
3795
+ }, [...GLOBAL_RESTORE_ITEMS.tls.aliases]);
3796
+ }
3797
+ return {
3798
+ settingsText,
3799
+ parsedGlobal
3800
+ };
3801
+ }
3802
+ /**
3803
+ * The two closures every planning phase writes through.
3804
+ *
3805
+ * **`addItem` fills `actions` in call order, and `runApply` drains that map in the same order** —
3806
+ * so the sequence of `addItem` calls across the phases *is* the apply order. Splitting the phases
3807
+ * did not change that order; it must not.
3808
+ */
3809
+ itemWriters(ctx) {
3810
+ const { plan, selects, actions } = ctx;
3811
+ /**
3812
+ * Writes one archived secrets file, **always** by field.
3813
+ *
3814
+ * Replacing the live file wholesale when nothing was excluded looked like the identity case, but
3815
+ * an archive only carries what its own selection captured: restoring `global:secrets` from an
3816
+ * archive taken with `--exclude global:secrets:apiToken` replaced the file with a document that
3817
+ * had no `apiToken` in it, silently signing every script out. The live file may also hold a secret
3818
+ * the archive predates. `mergeIntoFile` copies exactly the fields the archive carries and leaves
3819
+ * every other key of the live file alone, which is the behaviour both cases want — and what every
3820
+ * restore did before this rewrite.
3821
+ */
3822
+ const secretsApply = (scope, entryId, target, archived) => {
3823
+ const take = secretParts(scope, presentSecretKeys(parseSecrets(archived))).filter((part) => !selects.isExcluded(`${entryId}:${part.key}`) && !part.fields.some((field) => selects.isExcluded(`${entryId}:${field}`)));
3824
+ return () => {
3825
+ ensureStateDir(path.dirname(target));
3826
+ mergeIntoFile(target, archived, take.flatMap((part) => part.fields));
3827
+ };
3828
+ };
3829
+ const addItem = (item, apply, aliases = []) => {
3830
+ if (apply === null) {
3502
3831
  plan.items.push({
3503
3832
  ...item,
3504
- selected
3833
+ selected: false
3505
3834
  });
3506
- if (selected) actions.set(item.id, apply);
3507
- else {
3508
- plan.skipped.push(`${item.label} (not selected)`);
3509
- plan.skippedItems.push({
3510
- label: item.label,
3511
- ...item.labelKey === void 0 ? {} : { labelKey: item.labelKey },
3512
- ...item.labelParams === void 0 ? {} : { labelParams: item.labelParams },
3513
- reasonKey: "settings.restore.reasonNotSelected"
3514
- });
3515
- }
3516
- };
3517
- const settingsText = readText(path.join(staging, "global", "settings.json"));
3518
- const liftedGlobal = readableGlobalSettings(settingsText);
3519
- const parsedGlobal = liftedGlobal === null ? null : parseGlobalSettings(liftedGlobal).config;
3520
- if (settingsText !== null && parsedGlobal === null) {
3521
- plan.skipped.push("Global settings (the archive's settings are not valid)");
3835
+ plan.skipped.push(`${item.label}${item.note === null ? "" : ` (${item.note})`}`);
3522
3836
  plan.skippedItems.push({
3523
- label: "Global settings",
3524
- labelKey: "settings.backup.entryGlobalSettings",
3525
- reasonKey: "settings.restore.reasonInvalidSettings"
3837
+ label: item.label,
3838
+ ...item.labelKey === void 0 ? {} : { labelKey: item.labelKey },
3839
+ ...item.labelParams === void 0 ? {} : { labelParams: item.labelParams },
3840
+ reasonKey: item.noteKey ?? "settings.restore.reasonUnrestorable",
3841
+ ...item.noteParams === void 0 ? {} : { reasonParams: item.noteParams }
3526
3842
  });
3843
+ return;
3527
3844
  }
3528
- if (parsedGlobal !== null && liftedGlobal !== null) {
3529
- const globalText = `${JSON.stringify(liftedGlobal, null, 2)}\n`;
3530
- addItem({
3531
- id: "global:settings",
3532
- label: "Global settings",
3533
- labelKey: "settings.backup.entryGlobalSettings",
3534
- kind: "settings",
3535
- restorable: true,
3536
- note: null
3537
- }, () => {
3538
- writeFileAtomic(sources.globalSettingsPath, globalText);
3539
- }, ["config"]);
3540
- }
3541
- const globalSecrets = readText(path.join(staging, "global", "secrets.json"));
3542
- if (globalSecrets !== null) {
3543
- addItem({
3544
- id: "global:secrets",
3545
- label: "Global secrets (password, API token)",
3546
- labelKey: "settings.backup.entryGlobalSecrets",
3547
- kind: "secrets",
3548
- restorable: true,
3549
- note: null
3550
- }, secretsApply("global", "global:secrets", sources.globalSecretsPath, globalSecrets), ["secrets"]);
3551
- for (const part of secretParts("global", presentSecretKeys(parseSecrets(globalSecrets)))) addItem({
3552
- id: `global:secrets:${part.key}`,
3553
- label: `Global secrets: ${SECRET_LABELS[part.key]?.en ?? part.key}`,
3554
- labelKey: "settings.backup.restoreItemLabel",
3555
- labelParams: {
3556
- workspace: "global",
3557
- item: part.key
3558
- },
3559
- kind: "secrets",
3560
- restorable: true,
3561
- note: null
3562
- }, () => {
3563
- mergeIntoFile(sources.globalSecretsPath, globalSecrets, part.fields);
3845
+ const selected = selectedBy(selects, aliases.length === 0 ? item : {
3846
+ ...item,
3847
+ aliases
3848
+ });
3849
+ plan.items.push({
3850
+ ...item,
3851
+ selected
3852
+ });
3853
+ if (selected) actions.set(item.id, apply);
3854
+ else {
3855
+ plan.skipped.push(`${item.label} (not selected)`);
3856
+ plan.skippedItems.push({
3857
+ label: item.label,
3858
+ ...item.labelKey === void 0 ? {} : { labelKey: item.labelKey },
3859
+ ...item.labelParams === void 0 ? {} : { labelParams: item.labelParams },
3860
+ reasonKey: "settings.restore.reasonNotSelected"
3564
3861
  });
3565
3862
  }
3566
- const tlsInArchive = path.join(staging, "global", "tls");
3567
- if (fs.existsSync(tlsInArchive)) {
3568
- const files = fs.readdirSync(tlsInArchive).filter((file) => fs.statSync(path.join(tlsInArchive, file)).isFile());
3569
- addItem({
3570
- id: "global:tls",
3571
- label: "TLS certificate",
3572
- labelKey: "settings.backup.entryTlsCertificate",
3573
- kind: "tls",
3574
- restorable: true,
3575
- note: null
3576
- }, () => {
3577
- fs.mkdirSync(sources.tlsDir, { recursive: true });
3578
- for (const file of files) {
3579
- const mode = file.endsWith(".key.pem") ? { mode: 384 } : {};
3580
- writeFileAtomic(path.join(sources.tlsDir, file), fs.readFileSync(path.join(tlsInArchive, file), "utf8"), mode);
3581
- }
3582
- }, ["tls"]);
3583
- }
3584
- /**
3585
- * The workspaces the archive names, from its registry file.
3586
- *
3587
- * Optional: an archive written before the registry was captured carries none, and
3588
- * then every archived workspace is still restorable under its own id — the label is
3589
- * the only thing the registry adds.
3590
- */
3591
- const archivedWorkspaces = /* @__PURE__ */ new Map();
3592
- for (const entry of readArchivedRegistry(path.join(staging, "global", REGISTRY))) archivedWorkspaces.set(entry.id, entry);
3593
- /** Every archived servers file this release can read, selected or not. */
3594
- const archivedServers = /* @__PURE__ */ new Map();
3595
- /**
3596
- * Workspaces the archive names that this host does not have, with the paths a
3597
- * restore will create them under. The directories are made only when one of
3598
- * their leaves is actually applied, so a dry run writes nothing.
3599
- */
3600
- const createdWorkspaces = /* @__PURE__ */ new Map();
3601
- const archiveWorkspaces = path.join(staging, "workspaces");
3602
- if (fs.existsSync(archiveWorkspaces)) for (const entry of fs.readdirSync(archiveWorkspaces, { withFileTypes: true })) {
3603
- if (!entry.isDirectory()) continue;
3604
- const id = entry.name;
3605
- const dir = path.join(archiveWorkspaces, id);
3606
- const settings = readText(path.join(dir, "settings.json"));
3607
- const servers = readText(path.join(dir, "servers.config.json"));
3608
- const secrets = readText(path.join(dir, "secrets.json"));
3609
- const archivedLabel = archivedWorkspaces.get(id)?.label ?? id;
3610
- const workspace = sources.workspaces.find((candidate) => candidate.id === id) ?? createdWorkspaces.get(id) ?? (workspaceIdSchema(id) instanceof type.errors ? void 0 : {
3611
- id,
3612
- label: archivedLabel,
3613
- ...workspacePathsFor(this.options.dataRoot, id),
3614
- servers: []
3863
+ };
3864
+ return {
3865
+ secretsApply,
3866
+ addItem
3867
+ };
3868
+ }
3869
+ /**
3870
+ * One item group per workspace the archive names, plus the archived servers each carries.
3871
+ *
3872
+ * A workspace this host does not have is *created* rather than skipped: an archive is the whole
3873
+ * setup. Its directories are made only when one of its leaves is applied, so a dry run writes
3874
+ * nothing.
3875
+ */
3876
+ planWorkspaceItems(ctx) {
3877
+ const { plan, sources, staging, actions, archivedServers, createdWorkspaces } = ctx;
3878
+ /**
3879
+ * The workspaces the archive names, from its registry file.
3880
+ *
3881
+ * Optional: an archive written before the registry was captured carries none, and then every
3882
+ * archived workspace is still restorable under its own id — the label is all the registry adds.
3883
+ */
3884
+ const archivedWorkspaces = /* @__PURE__ */ new Map();
3885
+ for (const entry of readArchivedRegistry(path.join(staging, "global", REGISTRY))) archivedWorkspaces.set(entry.id, entry);
3886
+ const { secretsApply, addItem } = this.itemWriters(ctx);
3887
+ const archiveWorkspaces = path.join(staging, "workspaces");
3888
+ if (fs.existsSync(archiveWorkspaces)) for (const entry of fs.readdirSync(archiveWorkspaces, { withFileTypes: true })) {
3889
+ if (!entry.isDirectory()) continue;
3890
+ const id = entry.name;
3891
+ const dir = path.join(archiveWorkspaces, id);
3892
+ const settings = readText(path.join(dir, "settings.json"));
3893
+ const servers = readText(path.join(dir, "servers.config.json"));
3894
+ const secrets = readText(path.join(dir, "secrets.json"));
3895
+ const archivedLabel = archivedWorkspaces.get(id)?.label ?? id;
3896
+ const workspace = sources.workspaces.find((candidate) => candidate.id === id) ?? createdWorkspaces.get(id) ?? (workspaceIdSchema(id) instanceof type.errors ? void 0 : {
3897
+ id,
3898
+ label: archivedLabel,
3899
+ ...workspacePathsFor(this.options.dataRoot, id),
3900
+ servers: []
3901
+ });
3902
+ if (workspace === void 0) {
3903
+ plan.skipped.push(`${id} (not a usable workspace id)`);
3904
+ plan.skippedItems.push({
3905
+ label: id,
3906
+ reasonKey: "settings.restore.reasonInvalidWorkspace"
3615
3907
  });
3616
- if (workspace === void 0) {
3617
- plan.skipped.push(`${id} (not a usable workspace id)`);
3618
- plan.skippedItems.push({
3619
- label: id,
3620
- reasonKey: "settings.restore.reasonInvalidWorkspace"
3621
- });
3622
- continue;
3623
- }
3624
- if (!sources.workspaces.some((candidate) => candidate.id === id)) createdWorkspaces.set(id, workspace);
3625
- if (settings !== null) {
3626
- const liftedSettings = readableWorkspaceSettings(settings);
3627
- if (liftedSettings !== null) {
3628
- const settingsText = `${JSON.stringify(liftedSettings, null, 2)}\n`;
3629
- addItem({
3630
- id: `workspace:${id}:settings`,
3631
- label: `${workspace.label}: Settings`,
3632
- labelKey: "settings.backup.restoreItemLabel",
3633
- labelParams: {
3634
- workspace: workspace.label,
3635
- item: "settings"
3636
- },
3637
- kind: "settings",
3638
- workspaceId: id,
3639
- restorable: true,
3640
- note: null
3641
- }, () => {
3642
- fs.mkdirSync(path.dirname(workspace.settingsPath), { recursive: true });
3643
- writeFileAtomic(workspace.settingsPath, settingsText);
3644
- });
3645
- } else {
3646
- plan.skipped.push(`${workspace.label}: Settings (the archive's settings are not valid)`);
3647
- plan.skippedItems.push({
3648
- label: `${workspace.label}: Settings`,
3649
- labelKey: "settings.backup.restoreItemLabel",
3650
- labelParams: {
3651
- workspace: workspace.label,
3652
- item: "settings"
3653
- },
3654
- reasonKey: "settings.restore.reasonInvalidSettings"
3655
- });
3656
- }
3657
- }
3658
- if (servers !== null) {
3659
- const parsed = readableServersFile(servers);
3660
- const liftedServers = parsed === null ? null : liftArchived(JSON.parse(servers));
3661
- if (parsed !== null && liftedServers !== null) {
3662
- const serversText = `${JSON.stringify(liftedServers, null, 2)}\n`;
3663
- archivedServers.set(id, parsed);
3664
- addItem({
3665
- id: `workspace:${id}:servers`,
3666
- label: `${workspace.label}: Servers`,
3667
- labelKey: "settings.backup.restoreItemLabel",
3668
- labelParams: {
3669
- workspace: workspace.label,
3670
- item: "servers"
3671
- },
3672
- kind: "servers",
3673
- workspaceId: id,
3674
- restorable: true,
3675
- note: null
3676
- }, () => {
3677
- fs.mkdirSync(path.dirname(workspace.serversPath), { recursive: true });
3678
- writeFileAtomic(workspace.serversPath, serversText);
3679
- });
3680
- } else {
3681
- plan.skipped.push(`${workspace.label}: Servers (the archive's servers are not valid)`);
3682
- plan.skippedItems.push({
3683
- label: `${workspace.label}: Servers`,
3684
- labelKey: "settings.backup.restoreItemLabel",
3685
- labelParams: {
3686
- workspace: workspace.label,
3687
- item: "servers"
3688
- },
3689
- reasonKey: "settings.restore.reasonInvalidServers"
3690
- });
3691
- }
3692
- }
3693
- if (secrets !== null) {
3908
+ continue;
3909
+ }
3910
+ if (!sources.workspaces.some((candidate) => candidate.id === id)) createdWorkspaces.set(id, workspace);
3911
+ if (settings !== null) {
3912
+ const liftedSettings = readableWorkspaceSettings(settings);
3913
+ if (liftedSettings !== null) {
3914
+ const settingsText = `${JSON.stringify(liftedSettings, null, 2)}\n`;
3694
3915
  addItem({
3695
- id: `workspace:${id}:secrets`,
3696
- label: `${workspace.label}: Secrets`,
3916
+ id: `workspace:${id}:settings`,
3917
+ label: `${workspace.label}: Settings`,
3697
3918
  labelKey: "settings.backup.restoreItemLabel",
3698
3919
  labelParams: {
3699
3920
  workspace: workspace.label,
3700
- item: "secrets"
3921
+ item: "settings"
3701
3922
  },
3702
- kind: "secrets",
3923
+ kind: "settings",
3703
3924
  workspaceId: id,
3704
3925
  restorable: true,
3705
3926
  note: null
3706
- }, secretsApply("workspace", `workspace:${id}:secrets`, workspace.secretsPath, secrets));
3707
- for (const part of secretParts("workspace", presentSecretKeys(parseSecrets(secrets)))) addItem({
3708
- id: `workspace:${id}:secrets:${part.key}`,
3709
- label: `${workspace.label}: ${SECRET_LABELS[part.key]?.en ?? part.key}`,
3927
+ }, () => {
3928
+ ensureStateDir(path.dirname(workspace.settingsPath));
3929
+ writeFileAtomic(workspace.settingsPath, settingsText);
3930
+ });
3931
+ } else {
3932
+ plan.skipped.push(`${workspace.label}: Settings (the archive's settings are not valid)`);
3933
+ plan.skippedItems.push({
3934
+ label: `${workspace.label}: Settings`,
3710
3935
  labelKey: "settings.backup.restoreItemLabel",
3711
3936
  labelParams: {
3712
3937
  workspace: workspace.label,
3713
- item: part.key
3938
+ item: "settings"
3714
3939
  },
3715
- kind: "secrets",
3940
+ reasonKey: "settings.restore.reasonInvalidSettings"
3941
+ });
3942
+ }
3943
+ }
3944
+ if (servers !== null) {
3945
+ const parsed = readableServersFile(servers);
3946
+ const liftedServers = parsed === null ? null : liftArchived(JSON.parse(servers));
3947
+ if (parsed !== null && liftedServers !== null) {
3948
+ const serversText = `${JSON.stringify(liftedServers, null, 2)}\n`;
3949
+ archivedServers.set(id, parsed);
3950
+ addItem({
3951
+ id: `workspace:${id}:servers`,
3952
+ label: `${workspace.label}: Servers`,
3953
+ labelKey: "settings.backup.restoreItemLabel",
3954
+ labelParams: {
3955
+ workspace: workspace.label,
3956
+ item: "servers"
3957
+ },
3958
+ kind: "servers",
3716
3959
  workspaceId: id,
3717
3960
  restorable: true,
3718
3961
  note: null
3719
3962
  }, () => {
3720
- fs.mkdirSync(path.dirname(workspace.secretsPath), { recursive: true });
3721
- mergeIntoFile(workspace.secretsPath, secrets, part.fields);
3963
+ ensureStateDir(path.dirname(workspace.serversPath));
3964
+ writeFileAtomic(workspace.serversPath, serversText);
3965
+ });
3966
+ } else {
3967
+ plan.skipped.push(`${workspace.label}: Servers (the archive's servers are not valid)`);
3968
+ plan.skippedItems.push({
3969
+ label: `${workspace.label}: Servers`,
3970
+ labelKey: "settings.backup.restoreItemLabel",
3971
+ labelParams: {
3972
+ workspace: workspace.label,
3973
+ item: "servers"
3974
+ },
3975
+ reasonKey: "settings.restore.reasonInvalidServers"
3722
3976
  });
3723
3977
  }
3724
3978
  }
3725
- const instanceTargets = [];
3726
- for (const workspace of sources.workspaces) for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
3727
- if (!declared.included) continue;
3728
- instanceTargets.push({
3729
- workspace: workspace.id,
3730
- path: declared.path,
3731
- origin: declared.origin
3732
- });
3733
- }
3734
- const archivedIncludePaths = actions.has("global:settings") && parsedGlobal !== null ? parsedGlobal.backups.includePaths : sources.includePaths;
3735
- const archiveAll = [];
3736
- const archiveTargets = [];
3737
- for (const [id, servers] of archivedServers) for (const declared of this.declaredData(servers, archivedIncludePaths)) {
3738
- if (!declared.included) continue;
3739
- const target = {
3740
- workspace: id,
3741
- path: declared.path,
3742
- origin: declared.origin
3743
- };
3744
- archiveAll.push(target);
3745
- if (actions.has(`workspace:${id}:servers`)) archiveTargets.push(target);
3746
- }
3747
- const usedArchive = /* @__PURE__ */ new Set();
3748
- const usedInstance = /* @__PURE__ */ new Set();
3749
- const take = (list, used, test) => {
3750
- const found = list.find((target) => !used.has(target) && test(target));
3751
- if (found === void 0) return void 0;
3752
- used.add(found);
3753
- return found;
3754
- };
3755
- /**
3756
- * Where one archived data path lands, never across a workspace boundary.
3757
- *
3758
- * An archive that names a workspace is only ever matched against that workspace's
3759
- * declarations: the un-scoped fallbacks below exist to survive a re-labelled or
3760
- * re-ordered config, and letting them cross workspaces wrote one workspace's data
3761
- * over a path another one had declared. A path only one workspace declares has no
3762
- * candidate at all in the other, so the entry is reported instead of guessed at.
3763
- */
3764
- const matchTarget = (origin, workspace, archivedPath) => {
3765
- const inScope = (target) => workspace === void 0 || target.workspace === workspace;
3766
- const archive = archiveTargets.filter(inScope);
3767
- const instance = instanceTargets.filter(inScope);
3768
- if (origin !== void 0) return take(archive, usedArchive, (target) => target.origin === origin) ?? take(instance, usedInstance, (target) => target.origin === origin) ?? take(archive, usedArchive, (target) => target.path === archivedPath) ?? take(instance, usedInstance, (target) => target.path === archivedPath);
3769
- return take(archive, usedArchive, (target) => target.path === archivedPath) ?? take(instance, usedInstance, (target) => target.path === archivedPath);
3770
- };
3771
- /**
3772
- * `workspace:serverId` for every entry running at this moment.
3773
- *
3774
- * Built once, before anything is copied: a data path whose owner is running is about to be
3775
- * replaced under a live process, and the plan has to name it. Read here rather than in the
3776
- * apply closure so a dry run reports the same list the apply would.
3777
- */
3778
- const runningOwners = new Set((sources.runningServers?.() ?? []).map((entry) => `${entry.workspaceId}:${entry.serverId}`));
3779
- for (const dump of manifest.dumps ?? []) {
3780
- const from = path.join(staging, "dumps", dump.workspaceId, dump.serverId);
3781
- if (!fs.existsSync(from)) continue;
3979
+ if (secrets !== null) {
3782
3980
  addItem({
3783
- id: `workspace:${dump.workspaceId}:dump:${dump.serverId}`,
3784
- label: `dump:${dump.serverId}`,
3785
- kind: "data",
3981
+ id: `workspace:${id}:secrets`,
3982
+ label: `${workspace.label}: Secrets`,
3983
+ labelKey: "settings.backup.restoreItemLabel",
3984
+ labelParams: {
3985
+ workspace: workspace.label,
3986
+ item: "secrets"
3987
+ },
3988
+ kind: "secrets",
3989
+ workspaceId: id,
3786
3990
  restorable: true,
3787
- workspaceId: dump.workspaceId,
3788
3991
  note: null
3789
- }, () => {});
3992
+ }, secretsApply("workspace", `workspace:${id}:secrets`, workspace.secretsPath, secrets));
3993
+ for (const part of secretParts("workspace", presentSecretKeys(parseSecrets(secrets)))) addItem({
3994
+ id: `workspace:${id}:secrets:${part.key}`,
3995
+ label: `${workspace.label}: ${SECRET_LABELS[part.key]?.en ?? part.key}`,
3996
+ labelKey: "settings.backup.restoreItemLabel",
3997
+ labelParams: {
3998
+ workspace: workspace.label,
3999
+ item: part.key
4000
+ },
4001
+ kind: "secrets",
4002
+ workspaceId: id,
4003
+ restorable: true,
4004
+ note: null
4005
+ }, () => {
4006
+ if (actions.has(`workspace:${id}:secrets`)) return;
4007
+ ensureStateDir(path.dirname(workspace.secretsPath));
4008
+ mergeIntoFile(workspace.secretsPath, secrets, part.fields);
4009
+ });
3790
4010
  }
3791
- const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : [];
3792
- for (const entry of archivedEntries) {
3793
- const archivedPath = typeof entry.path === "string" ? entry.path : "";
3794
- const origin = typeof entry.origin === "string" ? entry.origin : void 0;
3795
- const workspace = typeof entry.workspace === "string" ? entry.workspace : void 0;
3796
- const from = path.join(staging, "data", safeSlug(entry.slug) ?? slugifyPath(archivedPath));
3797
- const target = matchTarget(origin, workspace, archivedPath);
3798
- const targetWorkspace = target?.workspace ?? workspace;
3799
- const base = {
3800
- id: target === void 0 ? `data:${archivedPath}` : `workspace:${target.workspace}:data:${target.path}`,
3801
- label: target?.path ?? archivedPath,
3802
- kind: "data",
3803
- restorable: false,
3804
- note: null,
3805
- ...targetWorkspace === void 0 ? {} : { workspaceId: targetWorkspace }
3806
- };
3807
- const aliases = [`data:${archivedPath}`];
3808
- if (target === void 0) {
3809
- const declaredByBackup = archiveAll.some((candidate) => candidate.origin === origin && (workspace === void 0 || candidate.workspace === workspace));
3810
- addItem({
3811
- ...base,
3812
- note: declaredByBackup ? "declared by the backup's config, which is not being restored" : "not declared by this config, nor by the backup",
3813
- noteKey: declaredByBackup ? "settings.backup.noteDeclaredByBackup" : "settings.backup.noteNotDeclared"
3814
- }, null, aliases);
3815
- continue;
3816
- }
3817
- if (!fs.existsSync(from)) {
3818
- addItem({
3819
- ...base,
3820
- note: "missing from the archive",
3821
- noteKey: "settings.backup.noteMissingFromArchive"
3822
- }, null, aliases);
3823
- continue;
3824
- }
3825
- const ownerId = target.origin.split(":")[0] ?? "";
3826
- if (!selects.isExcluded(base.id) && (selects(base.id) || aliases.some((alias) => selects(alias))) && runningOwners.has(`${target.workspace}:${ownerId}`)) plan.replacedUnderRunning.push({
3827
- workspaceId: target.workspace,
3828
- serverId: ownerId,
3829
- path: target.path
4011
+ }
4012
+ }
4013
+ /**
4014
+ * Data-path items and dumps.
4015
+ *
4016
+ * A data path is written to a path a *config* declares — this instance's, or the servers file the
4017
+ * archive brings and the restore is about to apply. Nothing here is guessed from the archive's
4018
+ * manifest alone.
4019
+ *
4020
+ * Runs **after** the workspace phase on purpose: it reads `archivedServers` and asks
4021
+ * `actions.has(...)` about the workspace items, both of which that phase fills.
4022
+ */
4023
+ planDataItems(ctx, global) {
4024
+ const { plan, sources, staging, manifest, selects } = ctx;
4025
+ const { addItem } = this.itemWriters(ctx);
4026
+ const { archiveAll, archiveTargets, instanceTargets } = this.collectDataTargets(ctx, global);
4027
+ const matchTarget = dataTargetMatcher(archiveTargets, instanceTargets);
4028
+ /**
4029
+ * `workspace:serverId` for every entry running at this moment.
4030
+ *
4031
+ * Built once, before anything is copied: a data path whose owner is running is about to be
4032
+ * replaced under a live process, and the plan has to name it. Read here rather than in the
4033
+ * apply closure so a dry run reports the same list the apply would.
4034
+ */
4035
+ const runningOwners = new Set((sources.runningServers?.() ?? []).map((entry) => `${entry.workspaceId}:${entry.serverId}`));
4036
+ this.planDumpItems(ctx);
4037
+ const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : [];
4038
+ for (const entry of archivedEntries) {
4039
+ const archivedPath = typeof entry.path === "string" ? entry.path : "";
4040
+ const origin = typeof entry.origin === "string" ? entry.origin : void 0;
4041
+ const workspace = typeof entry.workspace === "string" ? entry.workspace : void 0;
4042
+ const from = path.join(staging, "data", safeSlug(entry.slug) ?? legacySlug(archivedPath));
4043
+ const target = matchTarget(origin, workspace, archivedPath);
4044
+ const targetWorkspace = target?.workspace ?? workspace;
4045
+ const base = {
4046
+ id: target === void 0 ? `data:${archivedPath}` : `workspace:${target.workspace}:data:${target.path}`,
4047
+ label: target?.path ?? archivedPath,
4048
+ kind: "data",
4049
+ restorable: false,
4050
+ note: null,
4051
+ ...targetWorkspace === void 0 ? {} : { workspaceId: targetWorkspace }
4052
+ };
4053
+ const aliases = [`data:${archivedPath}`];
4054
+ if (target === void 0) {
4055
+ this.planUnplacedDataItem(ctx, archiveAll, {
4056
+ base,
4057
+ aliases,
4058
+ origin,
4059
+ workspace
3830
4060
  });
4061
+ continue;
4062
+ }
4063
+ if (!fs.existsSync(from)) {
3831
4064
  addItem({
3832
4065
  ...base,
3833
- restorable: true,
3834
- ...target.path === archivedPath ? { note: null } : {
3835
- note: `restored from ${archivedPath}`,
3836
- noteKey: "settings.backup.noteRestoredFrom",
3837
- noteParams: { path: archivedPath }
3838
- }
3839
- }, () => copyTree(from, target.path, (_source, destination) => isInsideResolved(target.path, destination)), aliases);
3840
- }
3841
- if (parsedGlobal !== null && actions.has("global:settings") && settingsText !== null) {
3842
- const current = readableGlobalSettings(readText(sources.globalSettingsPath));
3843
- plan.restartRequired = JSON.stringify(parsedGlobal.control) !== JSON.stringify(current === null ? null : parseGlobalSettings(current).config?.control ?? null);
3844
- }
3845
- if (!options.confirm) {
3846
- plan.applied = [...actions.keys()].map((id) => labelOf(plan, id));
3847
- plan.appliedIds = [...actions.keys()];
3848
- return plan;
4066
+ note: "missing from the archive",
4067
+ noteKey: "settings.backup.noteMissingFromArchive"
4068
+ }, null, aliases);
4069
+ continue;
3849
4070
  }
3850
- let failure = null;
3851
- for (const [id, apply] of actions) {
3852
- try {
3853
- await apply();
3854
- } catch (error) {
3855
- failure = error;
3856
- break;
4071
+ const ownerId = target.origin.split(":")[0] ?? "";
4072
+ if (selectedBy(selects, {
4073
+ ...base,
4074
+ aliases
4075
+ }) && runningOwners.has(`${target.workspace}:${ownerId}`)) plan.replacedUnderRunning.push({
4076
+ workspaceId: target.workspace,
4077
+ serverId: ownerId,
4078
+ path: target.path
4079
+ });
4080
+ addItem({
4081
+ ...base,
4082
+ restorable: true,
4083
+ ...target.path === archivedPath ? { note: null } : {
4084
+ note: `restored from ${archivedPath}`,
4085
+ noteKey: "settings.backup.noteRestoredFrom",
4086
+ noteParams: { path: archivedPath }
3857
4087
  }
3858
- plan.applied.push(labelOf(plan, id));
3859
- plan.appliedIds.push(id);
3860
- }
3861
- for (const workspace of createdWorkspaces.values()) {
3862
- if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${workspace.id}:`))) continue;
3863
- this.options.ensureWorkspace?.({
3864
- id: workspace.id,
3865
- label: workspace.label
3866
- });
3867
- plan.createdWorkspaces.push(workspace.id);
4088
+ }, () => copyTree(from, target.path, (_source, destination) => isInsideResolved(target.path, destination)), aliases);
4089
+ }
4090
+ }
4091
+ /**
4092
+ * A dump is a restorable item in its own right — it is the thing the engine reads.
4093
+ *
4094
+ * Leaving it out of the plan meant `--all` reported nothing to restore and the `load` hook never
4095
+ * ran. Nothing is written over this host's files when this item applies: the dump is replayed by
4096
+ * that hook after everything has landed, and the item exists so the selection can name it (and so
4097
+ * deselecting it is expressible).
4098
+ */
4099
+ planDumpItems(ctx) {
4100
+ const { staging, manifest } = ctx;
4101
+ const { addItem } = this.itemWriters(ctx);
4102
+ for (const dump of manifest.dumps ?? []) {
4103
+ const from = path.join(staging, "dumps", dump.workspaceId, dump.serverId);
4104
+ if (!fs.existsSync(from)) continue;
4105
+ addItem({
4106
+ id: `workspace:${dump.workspaceId}:dump:${dump.serverId}`,
4107
+ label: `dump:${dump.serverId}`,
4108
+ kind: "data",
4109
+ restorable: true,
4110
+ workspaceId: dump.workspaceId,
4111
+ note: null
4112
+ }, () => {});
4113
+ }
4114
+ }
4115
+ /**
4116
+ * How an archived data path is reported when nothing on this host will receive it.
4117
+ *
4118
+ * Two reasons, and the difference is what the person acts on: "the backup's config declares it but
4119
+ * that config is not being restored" says tick the servers item; "neither config declares it" says
4120
+ * this path has nowhere to go. Both are reported rather than skipped silently — the archive holds
4121
+ * those bytes and a restore that says nothing about them reads as a complete one.
4122
+ */
4123
+ planUnplacedDataItem(ctx, archiveAll, placed) {
4124
+ const { addItem } = this.itemWriters(ctx);
4125
+ const { base, aliases, origin, workspace } = placed;
4126
+ const declaredByBackup = archiveAll.some((candidate) => candidate.origin === origin && (workspace === void 0 || candidate.workspace === workspace));
4127
+ addItem({
4128
+ ...base,
4129
+ note: declaredByBackup ? "declared by the backup's config, which is not being restored" : "not declared by this config, nor by the backup",
4130
+ noteKey: declaredByBackup ? "settings.backup.noteDeclaredByBackup" : "settings.backup.noteNotDeclared"
4131
+ }, null, aliases);
4132
+ }
4133
+ /**
4134
+ * Every data path a restore could write, from both sides of the comparison.
4135
+ *
4136
+ * A data path is only ever written to a path a **config** declares: this instance's, or the servers
4137
+ * file the archive brings and this restore is about to apply. `archivedIncludePaths` follows the
4138
+ * same rule for the archive side — a `global:settings` item that is being applied brings its own
4139
+ * `backups.includePaths`, and using this host's list instead would look for the archive's paths
4140
+ * where *this* config declares them.
4141
+ *
4142
+ * `archiveAll` is the archive's declarations *whether or not* they are applied, because it answers
4143
+ * a different question: "was this path declared by the backup's own config?" is what tells a person
4144
+ * why an entry could not be placed. `archiveTargets` is the narrower list a restore may write to —
4145
+ * only a servers file this restore is actually applying may name a destination.
4146
+ */
4147
+ collectDataTargets(ctx, global) {
4148
+ const { sources, actions, archivedServers } = ctx;
4149
+ const { parsedGlobal } = global;
4150
+ const instanceTargets = [];
4151
+ for (const workspace of sources.workspaces) for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
4152
+ if (!declared.included) continue;
4153
+ instanceTargets.push({
4154
+ workspace: workspace.id,
4155
+ path: declared.path,
4156
+ origin: declared.origin
4157
+ });
4158
+ }
4159
+ const archivedIncludePaths = actions.has("global:settings") && parsedGlobal !== null ? parsedGlobal.backups.includePaths : sources.includePaths;
4160
+ const archiveAll = [];
4161
+ const archiveTargets = [];
4162
+ for (const [id, servers] of archivedServers) for (const declared of this.declaredData(servers, archivedIncludePaths)) {
4163
+ if (!declared.included) continue;
4164
+ const target = {
4165
+ workspace: id,
4166
+ path: declared.path,
4167
+ origin: declared.origin
4168
+ };
4169
+ archiveAll.push(target);
4170
+ if (actions.has(`workspace:${id}:servers`)) archiveTargets.push(target);
4171
+ }
4172
+ return {
4173
+ archiveAll,
4174
+ archiveTargets,
4175
+ instanceTargets
4176
+ };
4177
+ }
4178
+ /**
4179
+ * Whether the plan must say a restart is needed — computed even for a dry run.
4180
+ *
4181
+ * Only the panel's own listener does; its servers are re-read from the file.
4182
+ */
4183
+ noteRestartRequired(ctx, global) {
4184
+ const { plan, sources, actions } = ctx;
4185
+ const { settingsText, parsedGlobal } = global;
4186
+ if (parsedGlobal !== null && actions.has("global:settings") && settingsText !== null) {
4187
+ const current = readableGlobalSettings(readText(sources.globalSettingsPath));
4188
+ plan.restartRequired = JSON.stringify(parsedGlobal.control) !== JSON.stringify(current === null ? null : parseGlobalSettings(current).config?.control ?? null);
4189
+ }
4190
+ }
4191
+ /**
4192
+ * Runs every planned write in order, stopping at the first failure.
4193
+ *
4194
+ * A partial failure records nothing for the item that failed, then hands the error back so the
4195
+ * caller can reload what did land and rethrow — a restore is not transactional, and the plan has
4196
+ * to say so.
4197
+ */
4198
+ async runApply(ctx) {
4199
+ const { plan, actions } = ctx;
4200
+ let failure = null;
4201
+ for (const [id, apply] of actions) {
4202
+ try {
4203
+ await apply();
4204
+ } catch (error) {
4205
+ failure = error;
4206
+ break;
3868
4207
  }
3869
- if (failure !== null) {
3870
- this.reloadRestored(plan);
3871
- throw failure;
4208
+ plan.applied.push(labelOf(plan, id));
4209
+ plan.appliedIds.push(id);
4210
+ }
4211
+ return failure;
4212
+ }
4213
+ /**
4214
+ * Registers the workspaces this restore created, once their leaves have landed.
4215
+ *
4216
+ * Last, and only for a workspace something was applied to: a workspace the panel knows about but
4217
+ * whose files were never written would be a workspace that exists and is empty, which is worse
4218
+ * than one that is plainly absent.
4219
+ */
4220
+ registerCreatedWorkspaces(ctx) {
4221
+ const { plan, createdWorkspaces } = ctx;
4222
+ for (const workspace of createdWorkspaces.values()) {
4223
+ if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${workspace.id}:`))) continue;
4224
+ this.options.ensureWorkspace?.({
4225
+ id: workspace.id,
4226
+ label: workspace.label
4227
+ });
4228
+ plan.createdWorkspaces.push(workspace.id);
4229
+ }
4230
+ }
4231
+ /**
4232
+ * Stages each restored dump where its entry can reach it, for that entry's own `load` hook.
4233
+ *
4234
+ * Staged rather than run: a load hook talks to a server that is answering, and this entry is
4235
+ * stopped at this point. The hook runs on its next `start`, once the port accepts a connection.
4236
+ *
4237
+ * Staged **before** the caller reloads, because the reload reads `pendingLoad` from disk.
4238
+ */
4239
+ async stagePendingLoads(ctx) {
4240
+ const { plan, staging, manifest, actions } = ctx;
4241
+ const archivedDumps = manifest.dumps ?? [];
4242
+ const pendingLoads = [];
4243
+ for (const entry of archivedDumps) {
4244
+ if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${entry.workspaceId}:`))) continue;
4245
+ if (!actions.has(`workspace:${entry.workspaceId}:dump:${entry.serverId}`)) continue;
4246
+ const server = readArchivedServers(staging, entry.workspaceId).find((candidate) => candidate.id === entry.serverId);
4247
+ if (server?.load === void 0 || server.load === null) {
4248
+ plan.skipped.push(`the dump for "${entry.serverId}" was restored but this entry has no load hook`);
4249
+ continue;
3872
4250
  }
3873
- /**
3874
- * The load phase: let each restored entry put its own dump back.
3875
- *
3876
- * After the files landed and before the panel reloads, so the engine reads a config this
3877
- * release has just written rather than the one it replaced. Only the entries the archive
3878
- * actually brought a dump for — an archive taken before the hook existed has none, and running
3879
- * `mongorestore` on a directory that is not there fails the whole restore for no reason.
3880
- */
3881
- const archivedDumps = manifest.dumps ?? [];
3882
- const pendingLoads = [];
3883
- for (const entry of archivedDumps) {
3884
- if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${entry.workspaceId}:`))) continue;
3885
- if (!actions.has(`workspace:${entry.workspaceId}:dump:${entry.serverId}`) && !actions.has(`workspace:${entry.workspaceId}`)) continue;
3886
- const server = readArchivedServers(staging, entry.workspaceId).find((candidate) => candidate.id === entry.serverId);
3887
- if (server?.load === void 0 || server.load === null) {
3888
- plan.skipped.push(`the dump for "${entry.serverId}" was restored but this entry has no load hook`);
3889
- continue;
3890
- }
3891
- const dumpDir = path.join(staging, "dumps", entry.workspaceId, entry.serverId);
3892
- if (!fs.existsSync(dumpDir)) {
3893
- plan.skipped.push(`the dump for "${entry.serverId}" is missing from the archive`);
3894
- continue;
3895
- }
3896
- const staged = path.join(this.options.dataRoot, PENDING_LOAD, entry.workspaceId, entry.serverId);
3897
- await copyTree(dumpDir, staged, () => true);
3898
- pendingLoads.push({
3899
- workspaceId: entry.workspaceId,
3900
- serverId: entry.serverId,
3901
- staged
3902
- });
3903
- plan.hooks = [...plan.hooks ?? [], {
3904
- serverId: entry.serverId,
3905
- workspaceId: entry.workspaceId,
3906
- action: "load",
3907
- ok: true,
3908
- output: "staged — runs when this entry next starts"
3909
- }];
4251
+ const dumpDir = path.join(staging, "dumps", entry.workspaceId, entry.serverId);
4252
+ if (!fs.existsSync(dumpDir)) {
4253
+ plan.skipped.push(`the dump for "${entry.serverId}" is missing from the archive`);
4254
+ continue;
3910
4255
  }
3911
- for (const load of pendingLoads) this.options.onLoadPending?.(load.workspaceId, load.serverId, load.staged);
3912
- this.reloadRestored(plan);
3913
- return plan;
3914
- } catch (error) {
3915
- if (isInvalidPassword(error)) return {
3916
- ...plan,
3917
- encrypted: true,
3918
- needsPassword: true,
3919
- error: "the password is wrong"
3920
- };
3921
- const done = plan.applied.length > 0 ? ` — already applied: ${plan.applied.join(", ")}` : "";
3922
- return {
3923
- ...plan,
3924
- error: `${errorMessage(error)}${done}`
3925
- };
3926
- } finally {
3927
- fs.rmSync(staging, {
3928
- recursive: true,
3929
- force: true
4256
+ const staged = path.join(this.options.dataRoot, PENDING_LOAD, entry.workspaceId, entry.serverId);
4257
+ await copyTree(dumpDir, staged, () => true);
4258
+ pendingLoads.push({
4259
+ workspaceId: entry.workspaceId,
4260
+ serverId: entry.serverId,
4261
+ staged
3930
4262
  });
3931
- this.sweepStaging();
4263
+ plan.hooks = [...plan.hooks ?? [], {
4264
+ serverId: entry.serverId,
4265
+ workspaceId: entry.workspaceId,
4266
+ action: "load",
4267
+ ok: true,
4268
+ output: "staged — runs when this entry next starts"
4269
+ }];
3932
4270
  }
4271
+ for (const load of pendingLoads) this.options.onLoadPending?.(load.workspaceId, load.serverId, load.staged);
3933
4272
  }
3934
4273
  /** The panel re-reads the restored settings and servers, so what the archive brought exists immediately. */
3935
4274
  reloadRestored(plan) {
@@ -4140,7 +4479,7 @@ var BackupService = class {
4140
4479
  return [{
4141
4480
  name,
4142
4481
  sizeBytes: stats.size,
4143
- createdAt: Math.round(stats.mtimeMs)
4482
+ createdAt: archiveStamp(name) ?? Math.round(stats.mtimeMs)
4144
4483
  }];
4145
4484
  } catch {
4146
4485
  return [];
@@ -4183,9 +4522,9 @@ var BackupService = class {
4183
4522
  async copyInto(staging, relative, source, ignoreGenerated = false) {
4184
4523
  if (!fs.existsSync(source)) return false;
4185
4524
  const target = path.join(staging, relative);
4186
- fs.mkdirSync(path.dirname(target), { recursive: true });
4187
- const archiveDir = path.resolve(this.resolveDir());
4188
- const root = path.resolve(source);
4525
+ ensureStateDir(path.dirname(target));
4526
+ const archiveDir = resolveExisting(path.resolve(this.resolveDir()));
4527
+ const root = resolveExisting(path.resolve(source));
4189
4528
  await copyTree(source, target, (from) => {
4190
4529
  const resolved = path.resolve(from);
4191
4530
  if (isInside(archiveDir, resolved)) return false;
@@ -4233,7 +4572,12 @@ var BackupService = class {
4233
4572
  }
4234
4573
  /** When the newest automatic archive was written, or null when there is none. */
4235
4574
  lastAutomatic() {
4236
- return this.list().find(isAutomatic)?.createdAt ?? null;
4575
+ const dir = this.resolveDir();
4576
+ if (this.lastAutomaticSeen?.dir !== dir) this.lastAutomaticSeen = {
4577
+ dir,
4578
+ at: this.scan().find(isAutomatic)?.createdAt ?? null
4579
+ };
4580
+ return this.lastAutomaticSeen.at;
4237
4581
  }
4238
4582
  /**
4239
4583
  * Runs one scheduled pass when it is due. Modelled on the DDNS pass: cheap to call on every
@@ -4261,6 +4605,7 @@ var BackupService = class {
4261
4605
  }).then((result) => {
4262
4606
  if (result.ok) {
4263
4607
  this.scheduleError = null;
4608
+ for (const warning of result.warnings ?? []) logger.warn("the scheduled backup", warning);
4264
4609
  return;
4265
4610
  }
4266
4611
  this.scheduleError = {
@@ -4343,4 +4688,4 @@ function readableWorkspaceSettings(text) {
4343
4688
  //#endregion
4344
4689
  export { normalizeHost as A, expandEnvList as C, ddnsProvider as D, resolveEnvFilePath as E, ddnsProviderInfos as O, targetProblem as S, loadEnvFile as T, entryStatePath as _, unknownBackupIds as a, WorkspaceStore as b, serverTemplateVars as c, isExposed as d, lanAddress as f, clearEntryState as g, resolveTemplates as h, selectionWritesCredentials as i, validateDdnsConfig as k, bindHost as l, resolveTemplate as m, buildBackupSources as n, hookFailure as o, resolveRecord as p, selectionOf as r, runBackupHook as s, BackupService as t, displayHost as u, readEntryState as v, expandEnvRecord as w, sendWebhook as x, writeEntryState as y };
4345
4690
 
4346
- //# sourceMappingURL=backups-Bd2SF2qd.js.map
4691
+ //# sourceMappingURL=backups-twva7x2n.js.map