@camstack/server 1.2.718 → 1.2.720

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 (970) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/addon-root-inventory.js +1 -1
  3. package/dist/agent/addon-scan.js +11 -7
  4. package/dist/agent/agent-addon-updates.js +1 -1
  5. package/dist/agent/agent-cap-dispatch-service.js +1 -1
  6. package/dist/agent/agent-heap-watch.js +1 -1
  7. package/dist/agent/agent-http.js +1 -1
  8. package/dist/agent/agent-hub-addon-update.js +1 -1
  9. package/dist/agent/agent-hub-registration.js +1 -1
  10. package/dist/agent/agent-infra-capabilities.js +2 -2
  11. package/dist/agent/agent-mesh-gate.js +1 -1
  12. package/dist/agent/agent-node-certificates.js +1 -1
  13. package/dist/agent/agent-pairing-routes.js +1 -1
  14. package/dist/agent/agent-pairing-store.js +1 -1
  15. package/dist/agent/agent-service.js +6 -2
  16. package/dist/agent/agent-update-service.js +3 -1
  17. package/dist/agent/hub-membership-client.js +1 -1
  18. package/dist/agent/infra-boot-guard.js +2 -2
  19. package/dist/agent/main.js +9 -9
  20. package/dist/api/addon-upload.js +1 -1
  21. package/dist/api/core/addon-settings.router.js +1 -1
  22. package/dist/api/core/agent-pairing.router.js +1 -1
  23. package/dist/api/core/auth-device-cert.procedures.js +1 -1
  24. package/dist/api/core/cap-providers.js +6 -6
  25. package/dist/api/core/certificates.router.js +1 -1
  26. package/dist/api/core/lifecycle-job-runner.js +1 -1
  27. package/dist/api/core/logging-settings.js +1 -1
  28. package/dist/api/core/logs.router.js +2 -2
  29. package/dist/api/core/notifications.router.js +1 -1
  30. package/dist/api/core/preferences.router.js +1 -1
  31. package/dist/api/core/repl.router.js +1 -1
  32. package/dist/api/cors/cors-policy.js +1 -1
  33. package/dist/api/mesh-membership-routes.js +1 -1
  34. package/dist/api/model-distributor.js +1 -1
  35. package/dist/api/trpc/cap-route-error-formatter.js +1 -1
  36. package/dist/api/trpc/cap-router-runtime.js +2 -2
  37. package/dist/api/trpc/core-cap-bridge.js +1 -1
  38. package/dist/api/trpc/device-collection-dispatch.js +1 -1
  39. package/dist/api/trpc/generated-cap-routers.js +1 -1
  40. package/dist/api/trpc/principal-authorization.js +1 -1
  41. package/dist/api/trpc/principal-visibility.js +1 -1
  42. package/dist/api/trpc/scope-access.js +1 -1
  43. package/dist/api/trpc/trpc.context.js +1 -1
  44. package/dist/api/trpc/trpc.middleware.js +1 -1
  45. package/dist/api/trpc/trpc.router.js +3 -3
  46. package/dist/auth/auth-network-policy.js +1 -1
  47. package/dist/auth/client-address.js +1 -1
  48. package/dist/auth/hub-sessions.js +1 -1
  49. package/dist/auth/session-lifetimes.js +1 -1
  50. package/dist/auth/sso-finish-deps.js +1 -1
  51. package/dist/boot/boot-config.js +53 -133
  52. package/dist/boot/platform-keychain-key.js +1 -1
  53. package/dist/boot/post-boot.service.js +1 -1
  54. package/dist/bootstrap-packages.js +3 -3
  55. package/dist/core/addon/addon-call-gateway.js +1 -1
  56. package/dist/core/addon/addon-package.service.js +140 -21
  57. package/dist/core/addon/addon-registry.service.js +36 -32
  58. package/dist/core/addon/addon-requirements.js +81 -0
  59. package/dist/core/addon/hub-addon-api.js +1 -1
  60. package/dist/core/addon/installed-addon-versions.js +82 -0
  61. package/dist/core/addon/package-dir-utils.js +11 -1
  62. package/dist/core/addon/settings-door-wiring.js +1 -1
  63. package/dist/core/addon-bridge/addon-bridge.service.js +3 -3
  64. package/dist/core/addon-pages/addon-pages.service.js +1 -1
  65. package/dist/core/agent/agent-desired-set.js +1 -1
  66. package/dist/core/agent/agent-pairing-http.js +1 -1
  67. package/dist/core/agent/agent-registry.service.js +41 -7
  68. package/dist/core/agent/cluster-node-history-store.js +1 -1
  69. package/dist/core/agent/delivery-requirements.js +36 -0
  70. package/dist/core/agent/forgotten-node-revoker.js +1 -1
  71. package/dist/core/agent/node-removal-hooks.js +6 -2
  72. package/dist/core/auth/auth.service.js +1 -1
  73. package/dist/core/config/config.schema.js +2 -2
  74. package/dist/core/config/config.service.js +1 -1
  75. package/dist/core/events/event-bus.service.js +1 -1
  76. package/dist/core/feature/feature.service.js +1 -1
  77. package/dist/core/lifecycle/lifecycle-state-machine.js +2 -2
  78. package/dist/core/logging/log-history.js +1 -1
  79. package/dist/core/logging/log-ring-buffer.js +2 -2
  80. package/dist/core/logging/logging.service.js +2 -2
  81. package/dist/core/logging/scoped-logger.js +2 -2
  82. package/dist/core/moleculer/cap-route-authority.js +2 -2
  83. package/dist/core/moleculer/hub-mesh-guard.js +1 -1
  84. package/dist/core/moleculer/moleculer.service.js +1 -1
  85. package/dist/core/network/network-quality.service.js +1 -1
  86. package/dist/core/notification/notification-wrapper.service.js +1 -1
  87. package/dist/core/notification/toast-wrapper.service.js +1 -1
  88. package/dist/core/repl/repl-engine.service.js +1 -1
  89. package/dist/core/server-update/server-update.service.js +3 -0
  90. package/dist/core/server-update/system-ensure-prebuilds.js +3 -3
  91. package/dist/core/server-update/system-exec-npm.js +2 -2
  92. package/dist/core/storage/fs-storage-backend.js +2 -2
  93. package/dist/core/storage/storage-location-manager.js +2 -2
  94. package/dist/core/storage/storage.service.js +1 -1
  95. package/dist/framework-nodepath.js +14 -1
  96. package/dist/launcher.js +23 -23
  97. package/dist/legacy-package-names.js +15 -0
  98. package/dist/main.js +2 -2
  99. package/dist/manual-boot.js +4 -3
  100. package/dist/package-inventory.js +6 -3
  101. package/dist/server-root/index.js +182 -30
  102. package/dist/single-copy-cleanup-runner.js +3 -3
  103. package/dist/single-copy-cleanup.js +19 -14
  104. package/package.json +53 -19
  105. package/scripts/closure-postinstall.mjs +1 -1
  106. package/system/assets/addon-pages-aggregator/icon.svg +5 -0
  107. package/system/assets/addon-widgets-aggregator/icon.svg +6 -0
  108. package/system/assets/alert-center/icon.svg +5 -0
  109. package/system/assets/autotrack/icon.svg +5 -0
  110. package/system/assets/backup-orchestrator/icon.svg +5 -0
  111. package/system/assets/calendars/icon.svg +5 -0
  112. package/system/assets/camera-grid/icon.svg +10 -0
  113. package/system/assets/composer/icon.svg +7 -0
  114. package/system/assets/console-logging/icon.svg +4 -0
  115. package/system/assets/core-blocks/icon.svg +6 -0
  116. package/system/assets/device-history/icon.svg +4 -0
  117. package/system/assets/device-manager/icon.svg +6 -0
  118. package/system/assets/filesystem-storage/icon.svg +6 -0
  119. package/system/assets/hub-forwarder/icon.svg +7 -0
  120. package/system/assets/keychain/icon.svg +6 -0
  121. package/system/assets/liveness-monitor/icon.svg +4 -0
  122. package/system/assets/local-auth/icon.svg +5 -0
  123. package/system/assets/local-network/icon.svg +7 -0
  124. package/system/assets/loki-logging/icon.svg +7 -0
  125. package/system/assets/metrics-native/icon.svg +3 -0
  126. package/system/assets/platform-probe/icon.svg +5 -0
  127. package/system/assets/record-entries/icon.svg +8 -0
  128. package/system/assets/remote-access-orchestrator/icon.svg +5 -0
  129. package/system/assets/snapshot/icon.svg +4 -0
  130. package/system/assets/sqlite-settings/icon.svg +5 -0
  131. package/system/assets/storage-orchestrator/icon.svg +8 -0
  132. package/system/assets/system-config/icon.svg +4 -0
  133. package/system/assets/winston-logging/icon.svg +6 -0
  134. package/system/dist/addon/addon-api-factory.d.ts +35 -0
  135. package/system/dist/addon-routes/addon-route-registry.d.ts +37 -0
  136. package/system/dist/addon-runner.js +11894 -0
  137. package/system/dist/addon-runner.mjs +11840 -0
  138. package/system/dist/addon-utils.d.ts +23 -0
  139. package/system/dist/addon-utils.js +27 -0
  140. package/system/dist/addon-utils.mjs +3 -0
  141. package/system/dist/agent-https-BMbnmX5u.mjs +1042 -0
  142. package/system/dist/agent-https-DslXCDRW.js +1289 -0
  143. package/system/dist/amd-accelerators-CEuPFBBK.js +36 -0
  144. package/system/dist/amd-accelerators-U_RsoEDd.mjs +35 -0
  145. package/system/dist/auth/auth-audit-log.d.ts +45 -0
  146. package/system/dist/auth/auth-manager.d.ts +155 -0
  147. package/system/dist/auth/cidr.d.ts +22 -0
  148. package/system/dist/auth/device-ca-store.d.ts +57 -0
  149. package/system/dist/auth/device-ca.d.ts +65 -0
  150. package/system/dist/auth/device-credential-manager.d.ts +158 -0
  151. package/system/dist/auth/external-identity-manager.d.ts +42 -0
  152. package/system/dist/auth/jwt-signing-key.d.ts +42 -0
  153. package/system/dist/auth/legacy-token-tables.d.ts +16 -0
  154. package/system/dist/auth/login-session-manager.d.ts +140 -0
  155. package/system/dist/auth/origin.d.ts +34 -0
  156. package/system/dist/auth/parse-record.d.ts +18 -0
  157. package/system/dist/auth/scope-matcher.d.ts +8 -0
  158. package/system/dist/auth/session-revocation-bus.d.ts +32 -0
  159. package/system/dist/auth/token-expiry.d.ts +62 -0
  160. package/system/dist/auth/totp-manager.d.ts +107 -0
  161. package/system/dist/auth/user-management-internal.d.ts +90 -0
  162. package/system/dist/auth/user-manager.d.ts +69 -0
  163. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.d.ts +57 -0
  164. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +271 -0
  165. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +263 -0
  166. package/system/dist/builtins/addon-pages-aggregator/dedupe-pages.d.ts +24 -0
  167. package/system/dist/builtins/addon-pages-aggregator/index.d.ts +1 -0
  168. package/system/dist/builtins/addon-pages-aggregator/index.js +8 -0
  169. package/system/dist/builtins/addon-pages-aggregator/index.mjs +2 -0
  170. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.d.ts +57 -0
  171. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +257 -0
  172. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +249 -0
  173. package/system/dist/builtins/addon-widgets-aggregator/index.d.ts +1 -0
  174. package/system/dist/builtins/addon-widgets-aggregator/index.js +8 -0
  175. package/system/dist/builtins/addon-widgets-aggregator/index.mjs +2 -0
  176. package/system/dist/builtins/alerts/alert-episode-policy.d.ts +39 -0
  177. package/system/dist/builtins/alerts/alert-store.d.ts +32 -0
  178. package/system/dist/builtins/alerts/alerts.addon.d.ts +148 -0
  179. package/system/dist/builtins/alerts/alerts.addon.js +1566 -0
  180. package/system/dist/builtins/alerts/alerts.addon.mjs +1559 -0
  181. package/system/dist/builtins/alerts/device-label.d.ts +8 -0
  182. package/system/dist/builtins/alerts/emit-alert-policy.d.ts +15 -0
  183. package/system/dist/builtins/alerts/index.d.ts +1 -0
  184. package/system/dist/builtins/alerts/index.js +4 -0
  185. package/system/dist/builtins/alerts/index.mjs +2 -0
  186. package/system/dist/builtins/alerts/migration-alerts.d.ts +13 -0
  187. package/system/dist/builtins/alerts/prune-policy.d.ts +44 -0
  188. package/system/dist/builtins/alerts/record-kinds.d.ts +15 -0
  189. package/system/dist/builtins/alerts/runner-alert.d.ts +58 -0
  190. package/system/dist/builtins/autotrack/autotrack-cameras.d.ts +125 -0
  191. package/system/dist/builtins/autotrack/autotrack-config.d.ts +89 -0
  192. package/system/dist/builtins/autotrack/autotrack-decision.d.ts +86 -0
  193. package/system/dist/builtins/autotrack/autotrack-loop.d.ts +95 -0
  194. package/system/dist/builtins/autotrack/autotrack.addon.d.ts +108 -0
  195. package/system/dist/builtins/autotrack/frame-error.d.ts +50 -0
  196. package/system/dist/builtins/autotrack/frame-measurements.d.ts +97 -0
  197. package/system/dist/builtins/autotrack/index.d.ts +2 -0
  198. package/system/dist/builtins/autotrack/index.js +1018 -0
  199. package/system/dist/builtins/autotrack/index.mjs +1012 -0
  200. package/system/dist/builtins/autotrack/ptz-mirror.d.ts +54 -0
  201. package/system/dist/builtins/autotrack/target-selection.d.ts +46 -0
  202. package/system/dist/builtins/backup-orchestrator/backup-databases.d.ts +51 -0
  203. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.d.ts +291 -0
  204. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +3213 -0
  205. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +3204 -0
  206. package/system/dist/builtins/backup-orchestrator/cron-helpers.d.ts +23 -0
  207. package/system/dist/builtins/backup-orchestrator/destination-policy.d.ts +91 -0
  208. package/system/dist/builtins/backup-orchestrator/download-helpers.d.ts +12 -0
  209. package/system/dist/builtins/backup-orchestrator/encryption-key-store.d.ts +49 -0
  210. package/system/dist/builtins/backup-orchestrator/index.d.ts +2 -0
  211. package/system/dist/builtins/backup-orchestrator/index.js +8 -0
  212. package/system/dist/builtins/backup-orchestrator/index.mjs +2 -0
  213. package/system/dist/builtins/backup-orchestrator/manifest-store.d.ts +134 -0
  214. package/system/dist/builtins/backup-orchestrator/record-kinds.d.ts +56 -0
  215. package/system/dist/builtins/backup-orchestrator/restore-archive.d.ts +24 -0
  216. package/system/dist/builtins/backup-orchestrator/run-queue.d.ts +106 -0
  217. package/system/dist/builtins/backup-orchestrator/schedule-store.d.ts +59 -0
  218. package/system/dist/builtins/backup-orchestrator/seed-marker-store.d.ts +26 -0
  219. package/system/dist/builtins/backup-orchestrator/staging-paths.d.ts +36 -0
  220. package/system/dist/builtins/backup-orchestrator/write-targets.d.ts +63 -0
  221. package/system/dist/builtins/calendars/calendar-color.d.ts +9 -0
  222. package/system/dist/builtins/calendars/calendar-prefs-store.d.ts +34 -0
  223. package/system/dist/builtins/calendars/calendars.addon.d.ts +19 -0
  224. package/system/dist/builtins/calendars/calendars.addon.js +227 -0
  225. package/system/dist/builtins/calendars/calendars.addon.mjs +220 -0
  226. package/system/dist/builtins/calendars/index.d.ts +1 -0
  227. package/system/dist/builtins/calendars/index.js +8 -0
  228. package/system/dist/builtins/calendars/index.mjs +2 -0
  229. package/system/dist/builtins/calendars/record-kinds.d.ts +18 -0
  230. package/system/dist/builtins/camera-grid/acquire-retry.d.ts +30 -0
  231. package/system/dist/builtins/camera-grid/addon.d.ts +205 -0
  232. package/system/dist/builtins/camera-grid/flv-join.d.ts +40 -0
  233. package/system/dist/builtins/camera-grid/grid-activity-mirror.d.ts +42 -0
  234. package/system/dist/builtins/camera-grid/grid-activity.d.ts +91 -0
  235. package/system/dist/builtins/camera-grid/grid-camera-declarations.d.ts +59 -0
  236. package/system/dist/builtins/camera-grid/grid-camera-device.d.ts +68 -0
  237. package/system/dist/builtins/camera-grid/grid-canvas-derivation.d.ts +54 -0
  238. package/system/dist/builtins/camera-grid/grid-canvas-seed.d.ts +112 -0
  239. package/system/dist/builtins/camera-grid/grid-canvas.d.ts +85 -0
  240. package/system/dist/builtins/camera-grid/grid-child.d.ts +32 -0
  241. package/system/dist/builtins/camera-grid/grid-compositor-child.d.ts +3 -0
  242. package/system/dist/builtins/camera-grid/grid-compositor-invocation.d.ts +47 -0
  243. package/system/dist/builtins/camera-grid/grid-compositor.d.ts +54 -0
  244. package/system/dist/builtins/camera-grid/grid-detection-mapping.d.ts +61 -0
  245. package/system/dist/builtins/camera-grid/grid-device-settings.d.ts +35 -0
  246. package/system/dist/builtins/camera-grid/grid-filter-graph.d.ts +53 -0
  247. package/system/dist/builtins/camera-grid/grid-frame-sample.d.ts +53 -0
  248. package/system/dist/builtins/camera-grid/grid-instances.d.ts +22 -0
  249. package/system/dist/builtins/camera-grid/grid-last-frame-store.d.ts +58 -0
  250. package/system/dist/builtins/camera-grid/grid-layout-native-provider.d.ts +34 -0
  251. package/system/dist/builtins/camera-grid/grid-plan.d.ts +34 -0
  252. package/system/dist/builtins/camera-grid/grid-profiles.d.ts +104 -0
  253. package/system/dist/builtins/camera-grid/grid-row-normalization.d.ts +10 -0
  254. package/system/dist/builtins/camera-grid/grid-sentry-sources.d.ts +64 -0
  255. package/system/dist/builtins/camera-grid/grid-snapshot.d.ts +62 -0
  256. package/system/dist/builtins/camera-grid/grid-stream-descriptor.d.ts +53 -0
  257. package/system/dist/builtins/camera-grid/grid-stream-invocation.d.ts +44 -0
  258. package/system/dist/builtins/camera-grid/grid-stream-relay.d.ts +35 -0
  259. package/system/dist/builtins/camera-grid/grid-stream-session.d.ts +143 -0
  260. package/system/dist/builtins/camera-grid/grid-tile-feed.d.ts +50 -0
  261. package/system/dist/builtins/camera-grid/grid-tile-plan.d.ts +66 -0
  262. package/system/dist/builtins/camera-grid/grid-wire-format.d.ts +30 -0
  263. package/system/dist/builtins/camera-grid/index.d.ts +45 -0
  264. package/system/dist/builtins/camera-grid/index.js +3994 -0
  265. package/system/dist/builtins/camera-grid/index.mjs +3961 -0
  266. package/system/dist/builtins/camera-grid/silence-analysis.d.ts +37 -0
  267. package/system/dist/builtins/cluster-agent/record-kinds.d.ts +49 -0
  268. package/system/dist/builtins/composer/actuator-dispatch.d.ts +13 -0
  269. package/system/dist/builtins/composer/actuator-groups.d.ts +68 -0
  270. package/system/dist/builtins/composer/actuator-invoke.d.ts +32 -0
  271. package/system/dist/builtins/composer/claim-gate.d.ts +59 -0
  272. package/system/dist/builtins/composer/composed-device-set.d.ts +52 -0
  273. package/system/dist/builtins/composer/composed-device.d.ts +57 -0
  274. package/system/dist/builtins/composer/composer-apply-waits.d.ts +28 -0
  275. package/system/dist/builtins/composer/composer-grafts.d.ts +73 -0
  276. package/system/dist/builtins/composer/composer-live-set.d.ts +30 -0
  277. package/system/dist/builtins/composer/composer-plan.d.ts +112 -0
  278. package/system/dist/builtins/composer/composer-runtime-factory.d.ts +30 -0
  279. package/system/dist/builtins/composer/composer-seeds.d.ts +28 -0
  280. package/system/dist/builtins/composer/composer-verdict.d.ts +33 -0
  281. package/system/dist/builtins/composer/composer.addon.d.ts +26 -0
  282. package/system/dist/builtins/composer/composer.addon.js +6229 -0
  283. package/system/dist/builtins/composer/composer.addon.mjs +6223 -0
  284. package/system/dist/builtins/composer/composer.d.ts +208 -0
  285. package/system/dist/builtins/composer/composition-declarations.d.ts +64 -0
  286. package/system/dist/builtins/composer/composition-evaluation.d.ts +53 -0
  287. package/system/dist/builtins/composer/composition-runtime.d.ts +203 -0
  288. package/system/dist/builtins/composer/composition-target.d.ts +60 -0
  289. package/system/dist/builtins/composer/confirmed-seed.d.ts +44 -0
  290. package/system/dist/builtins/composer/deadline-timer.d.ts +18 -0
  291. package/system/dist/builtins/composer/existing-target.d.ts +131 -0
  292. package/system/dist/builtins/composer/field-record.d.ts +64 -0
  293. package/system/dist/builtins/composer/forward-commands.d.ts +61 -0
  294. package/system/dist/builtins/composer/graft-host.d.ts +71 -0
  295. package/system/dist/builtins/composer/held-claims.d.ts +29 -0
  296. package/system/dist/builtins/composer/history-helpers.d.ts +67 -0
  297. package/system/dist/builtins/composer/index.d.ts +1 -0
  298. package/system/dist/builtins/composer/index.js +8 -0
  299. package/system/dist/builtins/composer/index.mjs +2 -0
  300. package/system/dist/builtins/composer/math-quantity.d.ts +20 -0
  301. package/system/dist/builtins/composer/own-field-reads.d.ts +30 -0
  302. package/system/dist/builtins/composer/owned-fields-target.d.ts +95 -0
  303. package/system/dist/builtins/composer/pulse-seed-resolve.d.ts +59 -0
  304. package/system/dist/builtins/composer/pulse-seed.d.ts +75 -0
  305. package/system/dist/builtins/composer/slice-assembler.d.ts +26 -0
  306. package/system/dist/builtins/composer/source-readings.d.ts +128 -0
  307. package/system/dist/builtins/composer/source-tracker.d.ts +135 -0
  308. package/system/dist/builtins/console-logging/console-destination.d.ts +19 -0
  309. package/system/dist/builtins/console-logging/console-logging.addon.d.ts +26 -0
  310. package/system/dist/builtins/console-logging/index.d.ts +3 -0
  311. package/system/dist/builtins/console-logging/index.js +108 -0
  312. package/system/dist/builtins/console-logging/index.mjs +99 -0
  313. package/system/dist/builtins/core-blocks/actions-service.d.ts +113 -0
  314. package/system/dist/builtins/core-blocks/actions-store.d.ts +32 -0
  315. package/system/dist/builtins/core-blocks/actions-wiring.d.ts +32 -0
  316. package/system/dist/builtins/core-blocks/block-package.d.ts +54 -0
  317. package/system/dist/builtins/core-blocks/block-settings-store.d.ts +93 -0
  318. package/system/dist/builtins/core-blocks/block-supervisor.d.ts +176 -0
  319. package/system/dist/builtins/core-blocks/block-type-defs.d.ts +29 -0
  320. package/system/dist/builtins/core-blocks/blocks-integration.d.ts +89 -0
  321. package/system/dist/builtins/core-blocks/compile-block.d.ts +52 -0
  322. package/system/dist/builtins/core-blocks/composition-api.d.ts +50 -0
  323. package/system/dist/builtins/core-blocks/composition-peers.d.ts +31 -0
  324. package/system/dist/builtins/core-blocks/composition-sources.d.ts +40 -0
  325. package/system/dist/builtins/core-blocks/core-block-store.d.ts +120 -0
  326. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +108 -0
  327. package/system/dist/builtins/core-blocks/core-blocks.addon.js +6374 -0
  328. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +6355 -0
  329. package/system/dist/builtins/core-blocks/extract-settings-schema.d.ts +6 -0
  330. package/system/dist/builtins/core-blocks/index.d.ts +8 -0
  331. package/system/dist/builtins/core-blocks/index.js +21 -0
  332. package/system/dist/builtins/core-blocks/index.mjs +2 -0
  333. package/system/dist/builtins/core-blocks/lock-door-gate.d.ts +31 -0
  334. package/system/dist/builtins/core-blocks/lock-door-sensor.d.ts +35 -0
  335. package/system/dist/builtins/core-blocks/power-source-service.d.ts +70 -0
  336. package/system/dist/builtins/core-blocks/record-kinds.d.ts +83 -0
  337. package/system/dist/builtins/core-blocks/remote-call-redirect.d.ts +23 -0
  338. package/system/dist/builtins/core-blocks/remote-components-service.d.ts +10 -0
  339. package/system/dist/builtins/core-blocks/remote-service.d.ts +85 -0
  340. package/system/dist/builtins/core-blocks/remote-wiring.d.ts +49 -0
  341. package/system/dist/builtins/core-blocks/runs-api.d.ts +30 -0
  342. package/system/dist/builtins/core-blocks/runs-ledger.d.ts +64 -0
  343. package/system/dist/builtins/core-blocks/scheduler/scheduler-engine.d.ts +91 -0
  344. package/system/dist/builtins/core-blocks/scheduler/scheduler-holds.d.ts +54 -0
  345. package/system/dist/builtins/core-blocks/scheduler/scheduler-service.d.ts +76 -0
  346. package/system/dist/builtins/core-blocks/scheduler/scheduler-store.d.ts +23 -0
  347. package/system/dist/builtins/core-blocks/scheduler/scheduler-timeline.d.ts +53 -0
  348. package/system/dist/builtins/core-blocks/scheduler/scheduler-trace.d.ts +17 -0
  349. package/system/dist/builtins/core-blocks/scheduler/scheduler-types.d.ts +20 -0
  350. package/system/dist/builtins/core-blocks/scheduler/scheduler-wiring.d.ts +41 -0
  351. package/system/dist/builtins/core-blocks/templates-service.d.ts +24 -0
  352. package/system/dist/builtins/device-history/capture/capture-engine.d.ts +113 -0
  353. package/system/dist/builtins/device-history/capture/capture-filter.d.ts +37 -0
  354. package/system/dist/builtins/device-history/capture/device-directory.d.ts +47 -0
  355. package/system/dist/builtins/device-history/capture/field-path.d.ts +10 -0
  356. package/system/dist/builtins/device-history/capture/point-writer.d.ts +63 -0
  357. package/system/dist/builtins/device-history/device-history.addon.d.ts +53 -0
  358. package/system/dist/builtins/device-history/device-history.addon.js +2885 -0
  359. package/system/dist/builtins/device-history/device-history.addon.mjs +2878 -0
  360. package/system/dist/builtins/device-history/index.d.ts +3 -0
  361. package/system/dist/builtins/device-history/ingest/producer-ingest.d.ts +99 -0
  362. package/system/dist/builtins/device-history/query/history-query.d.ts +116 -0
  363. package/system/dist/builtins/device-history/query/point-shape.d.ts +31 -0
  364. package/system/dist/builtins/device-history/retention/departure-tracker.d.ts +33 -0
  365. package/system/dist/builtins/device-history/retention/orphans.d.ts +50 -0
  366. package/system/dist/builtins/device-history/retention/retention.d.ts +74 -0
  367. package/system/dist/builtins/device-history/rollup/rollup-engine.d.ts +74 -0
  368. package/system/dist/builtins/device-history/rollup/rollup-math.d.ts +50 -0
  369. package/system/dist/builtins/device-history/runtime/history-runtime.d.ts +118 -0
  370. package/system/dist/builtins/device-history/status/counters.d.ts +55 -0
  371. package/system/dist/builtins/device-history/store/history-door.d.ts +7 -0
  372. package/system/dist/builtins/device-history/store/history-schema.d.ts +28 -0
  373. package/system/dist/builtins/device-history/store/history-store.d.ts +109 -0
  374. package/system/dist/builtins/device-history/store/row-readers.d.ts +11 -0
  375. package/system/dist/builtins/device-history/store/series-registry.d.ts +64 -0
  376. package/system/dist/builtins/device-history/store/series-scale.d.ts +37 -0
  377. package/system/dist/builtins/device-history/time/bucket-time.d.ts +25 -0
  378. package/system/dist/builtins/device-manager/adoption-job-engine.d.ts +153 -0
  379. package/system/dist/builtins/device-manager/claimed-status-overlay.d.ts +45 -0
  380. package/system/dist/builtins/device-manager/contribution-cache.d.ts +85 -0
  381. package/system/dist/builtins/device-manager/day-night-config-schema.d.ts +30 -0
  382. package/system/dist/builtins/device-manager/device-aggregation-merge.d.ts +22 -0
  383. package/system/dist/builtins/device-manager/device-aggregation.d.ts +335 -0
  384. package/system/dist/builtins/device-manager/device-bindings-store.d.ts +278 -0
  385. package/system/dist/builtins/device-manager/device-config-contribution.d.ts +45 -0
  386. package/system/dist/builtins/device-manager/device-config-secrets.d.ts +40 -0
  387. package/system/dist/builtins/device-manager/device-event-propagator.d.ts +26 -0
  388. package/system/dist/builtins/device-manager/device-extension-linked-slot.d.ts +27 -0
  389. package/system/dist/builtins/device-manager/device-form-secrets.d.ts +25 -0
  390. package/system/dist/builtins/device-manager/device-linked-devices.d.ts +201 -0
  391. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +234 -0
  392. package/system/dist/builtins/device-manager/device-manager.addon.js +11369 -0
  393. package/system/dist/builtins/device-manager/device-manager.addon.mjs +11358 -0
  394. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +338 -0
  395. package/system/dist/builtins/device-manager/device-meta-store.d.ts +103 -0
  396. package/system/dist/builtins/device-manager/device-meta-types.d.ts +277 -0
  397. package/system/dist/builtins/device-manager/device-online-fallback.d.ts +35 -0
  398. package/system/dist/builtins/device-manager/device-projection.d.ts +71 -0
  399. package/system/dist/builtins/device-manager/device-provider-context.d.ts +126 -0
  400. package/system/dist/builtins/device-manager/device-queries.d.ts +67 -0
  401. package/system/dist/builtins/device-manager/device-removal-hooks.d.ts +92 -0
  402. package/system/dist/builtins/device-manager/device-row-store.d.ts +449 -0
  403. package/system/dist/builtins/device-manager/device-source-activation.d.ts +103 -0
  404. package/system/dist/builtins/device-manager/device-state-claim-views.d.ts +92 -0
  405. package/system/dist/builtins/device-manager/device-state-claims.d.ts +66 -0
  406. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +267 -0
  407. package/system/dist/builtins/device-manager/device-sync-resolvers.d.ts +30 -0
  408. package/system/dist/builtins/device-manager/device-tombstone-store.d.ts +29 -0
  409. package/system/dist/builtins/device-manager/discovery-orchestrator.d.ts +45 -0
  410. package/system/dist/builtins/device-manager/field-claims-index.d.ts +96 -0
  411. package/system/dist/builtins/device-manager/field-ownership.d.ts +71 -0
  412. package/system/dist/builtins/device-manager/fleet-read-census.d.ts +104 -0
  413. package/system/dist/builtins/device-manager/image-settings-config-schema.d.ts +22 -0
  414. package/system/dist/builtins/device-manager/index.d.ts +2 -0
  415. package/system/dist/builtins/device-manager/index.js +8 -0
  416. package/system/dist/builtins/device-manager/index.mjs +2 -0
  417. package/system/dist/builtins/device-manager/linked-devices-manual-backfill.d.ts +27 -0
  418. package/system/dist/builtins/device-manager/location-alignment.d.ts +61 -0
  419. package/system/dist/builtins/device-manager/migrate-device.d.ts +192 -0
  420. package/system/dist/builtins/device-manager/migrate-guard.d.ts +78 -0
  421. package/system/dist/builtins/device-manager/migrate-hardware-state.d.ts +79 -0
  422. package/system/dist/builtins/device-manager/migrate-reload.d.ts +46 -0
  423. package/system/dist/builtins/device-manager/migration-refused.d.ts +23 -0
  424. package/system/dist/builtins/device-manager/mirror-row-writer.d.ts +222 -0
  425. package/system/dist/builtins/device-manager/record-kinds.d.ts +14 -0
  426. package/system/dist/builtins/device-manager/recording-onboard-config-schema.d.ts +65 -0
  427. package/system/dist/builtins/device-manager/removal-cleanup.d.ts +50 -0
  428. package/system/dist/builtins/device-manager/removal-fence.d.ts +58 -0
  429. package/system/dist/builtins/device-manager/running-flip.d.ts +11 -0
  430. package/system/dist/builtins/device-manager/runtime-state-persist-gate.d.ts +64 -0
  431. package/system/dist/builtins/device-manager/secret-config-paths.d.ts +24 -0
  432. package/system/dist/builtins/device-manager/stale-wrapper-activations.d.ts +59 -0
  433. package/system/dist/builtins/device-manager/write-lock.d.ts +17 -0
  434. package/system/dist/builtins/hub-forwarder/hub-forwarder-destination.d.ts +43 -0
  435. package/system/dist/builtins/hub-forwarder/hub-forwarder.addon.d.ts +16 -0
  436. package/system/dist/builtins/hub-forwarder/index.d.ts +3 -0
  437. package/system/dist/builtins/hub-forwarder/index.js +151 -0
  438. package/system/dist/builtins/hub-forwarder/index.mjs +142 -0
  439. package/system/dist/builtins/keychain/index.d.ts +1 -0
  440. package/system/dist/builtins/keychain/index.js +2059 -0
  441. package/system/dist/builtins/keychain/index.mjs +2052 -0
  442. package/system/dist/builtins/keychain/key-sources.d.ts +37 -0
  443. package/system/dist/builtins/keychain/keychain-crypto.d.ts +28 -0
  444. package/system/dist/builtins/keychain/keychain-reset-trigger.d.ts +25 -0
  445. package/system/dist/builtins/keychain/keychain-service.d.ts +180 -0
  446. package/system/dist/builtins/keychain/keychain-store.d.ts +125 -0
  447. package/system/dist/builtins/keychain/keychain-usage.d.ts +17 -0
  448. package/system/dist/builtins/keychain/keychain.addon.d.ts +36 -0
  449. package/system/dist/builtins/keychain/platform-key-source.d.ts +24 -0
  450. package/system/dist/builtins/keychain/record-kinds.d.ts +16 -0
  451. package/system/dist/builtins/keychain/system-held-secrets.d.ts +25 -0
  452. package/system/dist/builtins/liveness-monitor/index.d.ts +2 -0
  453. package/system/dist/builtins/liveness-monitor/index.js +6 -0
  454. package/system/dist/builtins/liveness-monitor/index.mjs +2 -0
  455. package/system/dist/builtins/liveness-monitor/liveness-checks.d.ts +85 -0
  456. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.d.ts +46 -0
  457. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +443 -0
  458. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +437 -0
  459. package/system/dist/builtins/liveness-monitor/liveness-reporter.d.ts +28 -0
  460. package/system/dist/builtins/liveness-monitor/storage-root-access.d.ts +53 -0
  461. package/system/dist/builtins/local-auth/admin-account-boot.d.ts +27 -0
  462. package/system/dist/builtins/local-auth/auth-config-reader.d.ts +39 -0
  463. package/system/dist/builtins/local-auth/auth-schema.d.ts +93 -0
  464. package/system/dist/builtins/local-auth/index.d.ts +1 -0
  465. package/system/dist/builtins/local-auth/index.js +4 -0
  466. package/system/dist/builtins/local-auth/index.mjs +2 -0
  467. package/system/dist/builtins/local-auth/jwt-signing-key-keeper.d.ts +30 -0
  468. package/system/dist/builtins/local-auth/local-auth.addon.d.ts +48 -0
  469. package/system/dist/builtins/local-auth/local-auth.addon.js +12418 -0
  470. package/system/dist/builtins/local-auth/local-auth.addon.mjs +12388 -0
  471. package/system/dist/builtins/local-auth/oauth-grants.d.ts +71 -0
  472. package/system/dist/builtins/local-auth/oauth-session-manager.d.ts +44 -0
  473. package/system/dist/builtins/local-auth/person-scopes.d.ts +7 -0
  474. package/system/dist/builtins/local-auth/preferences-record-kinds.d.ts +27 -0
  475. package/system/dist/builtins/local-auth/record-kinds.d.ts +137 -0
  476. package/system/dist/builtins/local-auth/user-preferences-store.d.ts +56 -0
  477. package/system/dist/builtins/local-network/address-book.d.ts +128 -0
  478. package/system/dist/builtins/local-network/agent-mdns.d.ts +56 -0
  479. package/system/dist/builtins/local-network/hub-mdns-ciao.d.ts +7 -0
  480. package/system/dist/builtins/local-network/hub-mdns.d.ts +58 -0
  481. package/system/dist/builtins/local-network/index.d.ts +1 -0
  482. package/system/dist/builtins/local-network/index.js +10 -0
  483. package/system/dist/builtins/local-network/index.mjs +2 -0
  484. package/system/dist/builtins/local-network/ipv6-lan.d.ts +21 -0
  485. package/system/dist/builtins/local-network/local-hostname.d.ts +15 -0
  486. package/system/dist/builtins/local-network/local-network.addon.d.ts +334 -0
  487. package/system/dist/builtins/local-network/local-network.addon.js +2487 -0
  488. package/system/dist/builtins/local-network/local-network.addon.mjs +2466 -0
  489. package/system/dist/builtins/local-network/scan/dns-wire.d.ts +17 -0
  490. package/system/dist/builtins/local-network/scan/scan-engine.d.ts +31 -0
  491. package/system/dist/builtins/local-network/scan/scan-io-node.d.ts +2 -0
  492. package/system/dist/builtins/local-network/scan/scan-io.d.ts +56 -0
  493. package/system/dist/builtins/local-network/scan/subnets.d.ts +57 -0
  494. package/system/dist/builtins/loki-logging/index.d.ts +4 -0
  495. package/system/dist/builtins/loki-logging/index.js +915 -0
  496. package/system/dist/builtins/loki-logging/index.mjs +901 -0
  497. package/system/dist/builtins/loki-logging/loki-destination.d.ts +142 -0
  498. package/system/dist/builtins/loki-logging/loki-logging.addon.d.ts +66 -0
  499. package/system/dist/builtins/loki-logging/loki-payload.d.ts +100 -0
  500. package/system/dist/builtins/loki-logging/loki-read.d.ts +51 -0
  501. package/system/dist/builtins/loki-logging/retire-enabled-flag.d.ts +48 -0
  502. package/system/dist/builtins/native-metrics/cgroup-memory.d.ts +240 -0
  503. package/system/dist/builtins/native-metrics/cgroup-pids.d.ts +159 -0
  504. package/system/dist/builtins/native-metrics/container-memory-ring.d.ts +18 -0
  505. package/system/dist/builtins/native-metrics/darwin-memory.d.ts +26 -0
  506. package/system/dist/builtins/native-metrics/gpu-probe.d.ts +18 -0
  507. package/system/dist/builtins/native-metrics/index.d.ts +2 -0
  508. package/system/dist/builtins/native-metrics/load-series-config.d.ts +83 -0
  509. package/system/dist/builtins/native-metrics/load-series-reader.d.ts +63 -0
  510. package/system/dist/builtins/native-metrics/load-series-types.d.ts +14 -0
  511. package/system/dist/builtins/native-metrics/native-metrics-provider.d.ts +49 -0
  512. package/system/dist/builtins/native-metrics/native-metrics.addon.d.ts +233 -0
  513. package/system/dist/builtins/native-metrics/native-metrics.addon.js +3116 -0
  514. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +3106 -0
  515. package/system/dist/builtins/native-metrics/node-load-ring.d.ts +212 -0
  516. package/system/dist/builtins/native-metrics/node-metrics-history-recorder.d.ts +155 -0
  517. package/system/dist/builtins/native-metrics/proc-process-table.d.ts +25 -0
  518. package/system/dist/builtins/native-metrics/process-classification.d.ts +110 -0
  519. package/system/dist/builtins/native-metrics/thread-cpu-sampler.d.ts +116 -0
  520. package/system/dist/builtins/platform-probe/accelerator-facts-probe.d.ts +24 -0
  521. package/system/dist/builtins/platform-probe/accelerator-reprobe.d.ts +23 -0
  522. package/system/dist/builtins/platform-probe/amd-accelerators.d.ts +15 -0
  523. package/system/dist/builtins/platform-probe/amd-npu.d.ts +35 -0
  524. package/system/dist/builtins/platform-probe/coral-accelerators.d.ts +87 -0
  525. package/system/dist/builtins/platform-probe/index.d.ts +57 -0
  526. package/system/dist/builtins/platform-probe/index.js +1151 -0
  527. package/system/dist/builtins/platform-probe/index.mjs +1140 -0
  528. package/system/dist/builtins/platform-probe/inference-config-resolver.d.ts +29 -0
  529. package/system/dist/builtins/platform-probe/intel-accelerators.d.ts +14 -0
  530. package/system/dist/builtins/platform-probe/intel-npu.d.ts +38 -0
  531. package/system/dist/builtins/platform-probe/platform-scorer.d.ts +66 -0
  532. package/system/dist/builtins/platform-probe/runtime-packages.d.ts +6 -0
  533. package/system/dist/builtins/platform-probe/windows-hardware.d.ts +77 -0
  534. package/system/dist/builtins/record-entries/entries-service.d.ts +42 -0
  535. package/system/dist/builtins/record-entries/index.d.ts +1 -0
  536. package/system/dist/builtins/record-entries/index.js +162 -0
  537. package/system/dist/builtins/record-entries/index.mjs +156 -0
  538. package/system/dist/builtins/record-entries/record-entries.addon.d.ts +13 -0
  539. package/system/dist/builtins/records-isolated.d.ts +10 -0
  540. package/system/dist/builtins/remote-access-orchestrator/enabled-providers-reconcile.d.ts +96 -0
  541. package/system/dist/builtins/remote-access-orchestrator/index.d.ts +1 -0
  542. package/system/dist/builtins/remote-access-orchestrator/index.js +8 -0
  543. package/system/dist/builtins/remote-access-orchestrator/index.mjs +2 -0
  544. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.d.ts +71 -0
  545. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +214 -0
  546. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +208 -0
  547. package/system/dist/builtins/shared/device-state-changed.d.ts +16 -0
  548. package/system/dist/builtins/shared/settle-sources.d.ts +22 -0
  549. package/system/dist/builtins/snapshot/index.d.ts +2 -0
  550. package/system/dist/builtins/snapshot/index.js +2720 -0
  551. package/system/dist/builtins/snapshot/index.mjs +2713 -0
  552. package/system/dist/builtins/snapshot/snapshot-cache.d.ts +108 -0
  553. package/system/dist/builtins/snapshot/snapshot-coalescing.d.ts +135 -0
  554. package/system/dist/builtins/snapshot/snapshot-courtesy.d.ts +68 -0
  555. package/system/dist/builtins/snapshot/snapshot-durable-store.d.ts +36 -0
  556. package/system/dist/builtins/snapshot/snapshot-fatigue.d.ts +41 -0
  557. package/system/dist/builtins/snapshot/snapshot-grab-pick.d.ts +20 -0
  558. package/system/dist/builtins/snapshot/snapshot-link-url.d.ts +66 -0
  559. package/system/dist/builtins/snapshot/snapshot-media-handler.d.ts +121 -0
  560. package/system/dist/builtins/snapshot/snapshot-resize.d.ts +75 -0
  561. package/system/dist/builtins/snapshot/snapshot.addon.d.ts +581 -0
  562. package/system/dist/builtins/sqlite-storage/analyze-stats.d.ts +83 -0
  563. package/system/dist/builtins/sqlite-storage/config-store.d.ts +8 -0
  564. package/system/dist/builtins/sqlite-storage/database-snapshot-provider.d.ts +18 -0
  565. package/system/dist/builtins/sqlite-storage/device-store.d.ts +23 -0
  566. package/system/dist/builtins/sqlite-storage/file-host-client.d.ts +75 -0
  567. package/system/dist/builtins/sqlite-storage/file-host-handlers.d.ts +27 -0
  568. package/system/dist/builtins/sqlite-storage/file-host-protocol.d.ts +167 -0
  569. package/system/dist/builtins/sqlite-storage/file-host-worker.d.ts +1 -0
  570. package/system/dist/builtins/sqlite-storage/filesystem-browse-provider.d.ts +25 -0
  571. package/system/dist/builtins/sqlite-storage/filesystem-storage-provider.d.ts +83 -0
  572. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.d.ts +33 -0
  573. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +419 -0
  574. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +411 -0
  575. package/system/dist/builtins/sqlite-storage/filter-compiler.d.ts +126 -0
  576. package/system/dist/builtins/sqlite-storage/index.d.ts +12 -0
  577. package/system/dist/builtins/sqlite-storage/index.js +82 -0
  578. package/system/dist/builtins/sqlite-storage/index.mjs +50 -0
  579. package/system/dist/builtins/sqlite-storage/integration-record-kinds.d.ts +31 -0
  580. package/system/dist/builtins/sqlite-storage/integration-registry.d.ts +34 -0
  581. package/system/dist/builtins/sqlite-storage/migrations/migration-actions.d.ts +12 -0
  582. package/system/dist/builtins/sqlite-storage/migrations/migration-edits.d.ts +35 -0
  583. package/system/dist/builtins/sqlite-storage/migrations/migration-engine.d.ts +125 -0
  584. package/system/dist/builtins/sqlite-storage/migrations/migration-hold.d.ts +23 -0
  585. package/system/dist/builtins/sqlite-storage/migrations/migration-pass.d.ts +48 -0
  586. package/system/dist/builtins/sqlite-storage/migrations/migration-restore-marker.d.ts +3 -0
  587. package/system/dist/builtins/sqlite-storage/migrations/migration-types.d.ts +151 -0
  588. package/system/dist/builtins/sqlite-storage/migrations/migrations-provider.d.ts +61 -0
  589. package/system/dist/builtins/sqlite-storage/owned-sqlite-file.d.ts +173 -0
  590. package/system/dist/builtins/sqlite-storage/path-guard.d.ts +11 -0
  591. package/system/dist/builtins/sqlite-storage/placement-errors.d.ts +60 -0
  592. package/system/dist/builtins/sqlite-storage/placement-router.d.ts +85 -0
  593. package/system/dist/builtins/sqlite-storage/prefix-range.d.ts +50 -0
  594. package/system/dist/builtins/sqlite-storage/query-bounds.d.ts +110 -0
  595. package/system/dist/builtins/sqlite-storage/query-profiler.d.ts +242 -0
  596. package/system/dist/builtins/sqlite-storage/records/records-catalog.d.ts +27 -0
  597. package/system/dist/builtins/sqlite-storage/records/records-engine-types.d.ts +48 -0
  598. package/system/dist/builtins/sqlite-storage/records/records-engine.d.ts +115 -0
  599. package/system/dist/builtins/sqlite-storage/records/records-explain.d.ts +18 -0
  600. package/system/dist/builtins/sqlite-storage/records/records-plan.d.ts +95 -0
  601. package/system/dist/builtins/sqlite-storage/records/records-probe.d.ts +33 -0
  602. package/system/dist/builtins/sqlite-storage/records/records-provider.d.ts +72 -0
  603. package/system/dist/builtins/sqlite-storage/records/records-rows.d.ts +46 -0
  604. package/system/dist/builtins/sqlite-storage/records/records-sql.d.ts +39 -0
  605. package/system/dist/builtins/sqlite-storage/retired-settings-keys.d.ts +276 -0
  606. package/system/dist/builtins/sqlite-storage/shm-lock-canary.d.ts +60 -0
  607. package/system/dist/builtins/sqlite-storage/sqlite-pragmas.d.ts +191 -0
  608. package/system/dist/builtins/sqlite-storage/sqlite-settings-backend.d.ts +583 -0
  609. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.d.ts +52 -0
  610. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2960 -0
  611. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2952 -0
  612. package/system/dist/builtins/sqlite-storage/sqlite-snapshot-protocol.d.ts +54 -0
  613. package/system/dist/builtins/sqlite-storage/sqlite-snapshot-worker.d.ts +33 -0
  614. package/system/dist/builtins/sqlite-storage/sqlite-snapshotter.d.ts +118 -0
  615. package/system/dist/builtins/sqlite-storage/stale-data/stale-data-audit.d.ts +81 -0
  616. package/system/dist/builtins/sqlite-storage/stale-data/stale-data-ports.d.ts +17 -0
  617. package/system/dist/builtins/sqlite-storage/statement-shape.d.ts +64 -0
  618. package/system/dist/builtins/sqlite-storage/storage-admin-provider.d.ts +33 -0
  619. package/system/dist/builtins/sqlite-storage/table-sizes.d.ts +95 -0
  620. package/system/dist/builtins/sqlite-storage/vector-index-shared.d.ts +81 -0
  621. package/system/dist/builtins/sqlite-storage/vector-index-vec.d.ts +143 -0
  622. package/system/dist/builtins/sqlite-storage/vector-provider.d.ts +30 -0
  623. package/system/dist/builtins/sqlite-storage/wal-checkpoint-policy.d.ts +196 -0
  624. package/system/dist/builtins/sqlite-storage/wal-checkpoint-worker.d.ts +1 -0
  625. package/system/dist/builtins/sqlite-storage/wal-checkpointer.d.ts +76 -0
  626. package/system/dist/builtins/sqlite-storage/wal-maintenance.d.ts +130 -0
  627. package/system/dist/builtins/storage-orchestrator/access-guards.d.ts +43 -0
  628. package/system/dist/builtins/storage-orchestrator/data-store-dispatch.d.ts +39 -0
  629. package/system/dist/builtins/storage-orchestrator/drain-ratchet.d.ts +104 -0
  630. package/system/dist/builtins/storage-orchestrator/drain-state-store.d.ts +26 -0
  631. package/system/dist/builtins/storage-orchestrator/hub-settings-forward.d.ts +128 -0
  632. package/system/dist/builtins/storage-orchestrator/index.d.ts +7 -0
  633. package/system/dist/builtins/storage-orchestrator/index.js +11 -0
  634. package/system/dist/builtins/storage-orchestrator/index.mjs +2 -0
  635. package/system/dist/builtins/storage-orchestrator/location-class-paths.d.ts +13 -0
  636. package/system/dist/builtins/storage-orchestrator/location-history-recorder.d.ts +76 -0
  637. package/system/dist/builtins/storage-orchestrator/location-occupancy-slice.d.ts +71 -0
  638. package/system/dist/builtins/storage-orchestrator/location-occupancy.d.ts +19 -0
  639. package/system/dist/builtins/storage-orchestrator/location-protection.d.ts +20 -0
  640. package/system/dist/builtins/storage-orchestrator/location-repoint-move.d.ts +57 -0
  641. package/system/dist/builtins/storage-orchestrator/location-repointer.d.ts +97 -0
  642. package/system/dist/builtins/storage-orchestrator/location-root-collision.d.ts +80 -0
  643. package/system/dist/builtins/storage-orchestrator/location-secrets.d.ts +114 -0
  644. package/system/dist/builtins/storage-orchestrator/location-store.d.ts +82 -0
  645. package/system/dist/builtins/storage-orchestrator/location-volume-capacity.d.ts +58 -0
  646. package/system/dist/builtins/storage-orchestrator/provider-discovery.d.ts +24 -0
  647. package/system/dist/builtins/storage-orchestrator/record-kinds.d.ts +43 -0
  648. package/system/dist/builtins/storage-orchestrator/storage-cleanup-coordinator.d.ts +68 -0
  649. package/system/dist/builtins/storage-orchestrator/storage-location-band-monitor.d.ts +77 -0
  650. package/system/dist/builtins/storage-orchestrator/storage-migration-coordinator.d.ts +241 -0
  651. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.d.ts +318 -0
  652. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +5280 -0
  653. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +5264 -0
  654. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.service.d.ts +475 -0
  655. package/system/dist/builtins/storage-orchestrator/storage-pressure-manager.d.ts +115 -0
  656. package/system/dist/builtins/system-backup/backup-encryption.d.ts +94 -0
  657. package/system/dist/builtins/system-backup/system-backup.service.d.ts +308 -0
  658. package/system/dist/builtins/system-config/index.d.ts +2 -0
  659. package/system/dist/builtins/system-config/index.js +10 -0
  660. package/system/dist/builtins/system-config/index.mjs +2 -0
  661. package/system/dist/builtins/system-config/mesh-actions.d.ts +3 -0
  662. package/system/dist/builtins/system-config/record-kinds.d.ts +32 -0
  663. package/system/dist/builtins/system-config/system-config.addon.d.ts +56 -0
  664. package/system/dist/builtins/system-config/system-config.addon.js +89334 -0
  665. package/system/dist/builtins/system-config/system-config.addon.mjs +89233 -0
  666. package/system/dist/builtins/winston-logging/index.d.ts +3 -0
  667. package/system/dist/builtins/winston-logging/index.js +324 -0
  668. package/system/dist/builtins/winston-logging/index.mjs +313 -0
  669. package/system/dist/builtins/winston-logging/log-file-cursor.d.ts +12 -0
  670. package/system/dist/builtins/winston-logging/log-file-index-store.d.ts +11 -0
  671. package/system/dist/builtins/winston-logging/log-file-index.d.ts +77 -0
  672. package/system/dist/builtins/winston-logging/log-file-read-client.d.ts +44 -0
  673. package/system/dist/builtins/winston-logging/log-file-read-protocol.d.ts +41 -0
  674. package/system/dist/builtins/winston-logging/log-file-read-worker.d.ts +1 -0
  675. package/system/dist/builtins/winston-logging/log-file-reader.d.ts +51 -0
  676. package/system/dist/builtins/winston-logging/winston-destination.d.ts +39 -0
  677. package/system/dist/builtins/winston-logging/winston-logging.addon.d.ts +20 -0
  678. package/system/dist/chunk-CNf5ZN-e.mjs +37 -0
  679. package/system/dist/chunk-Cek0wNdY.js +64 -0
  680. package/system/dist/composition-sources-C14epb_m.js +155 -0
  681. package/system/dist/composition-sources-EXNuxmGQ.mjs +132 -0
  682. package/system/dist/constants-DIGWBiNC.mjs +20 -0
  683. package/system/dist/constants-M7NtSiRo.js +66 -0
  684. package/system/dist/coral-accelerators-BSVsBVzt.js +250 -0
  685. package/system/dist/coral-accelerators-DBlgWB8k.mjs +231 -0
  686. package/system/dist/custom-action-registry-JuMHGKEc.js +1638 -0
  687. package/system/dist/custom-action-registry-oHl1xltx.mjs +1482 -0
  688. package/system/dist/device-ca-3vmBP1i0.js +474 -0
  689. package/system/dist/device-ca-DZlvNBWU.mjs +367 -0
  690. package/system/dist/dist-DcMqHB_N.mjs +108095 -0
  691. package/system/dist/dist-M9yHiIY7.js +110554 -0
  692. package/system/dist/download/hosted-model-revisions.d.ts +10 -0
  693. package/system/dist/download/model-download-service.d.ts +35 -0
  694. package/system/dist/download/model-downloader.d.ts +156 -0
  695. package/system/dist/events/event-bus.d.ts +10 -0
  696. package/system/dist/events/system-event-bus.d.ts +14 -0
  697. package/system/dist/feature/feature-manager.d.ts +11 -0
  698. package/system/dist/file-host-worker.js +160 -0
  699. package/system/dist/file-host-worker.mjs +160 -0
  700. package/system/dist/formatter-DkYZ4LXp.mjs +162 -0
  701. package/system/dist/formatter-xbxeV4GD.js +167 -0
  702. package/system/dist/framework-resolver-hook.mjs +49 -0
  703. package/system/dist/http/asset-compression.d.ts +55 -0
  704. package/system/dist/http/authenticated-file-server.d.ts +53 -0
  705. package/system/dist/http/data-plane-registry.d.ts +58 -0
  706. package/system/dist/http/file-data-plane.d.ts +18 -0
  707. package/system/dist/http/lan-http-bind.d.ts +41 -0
  708. package/system/dist/http/reverse-proxy.d.ts +42 -0
  709. package/system/dist/hub-mdns-ciao-CpCKuQnK.js +1163 -0
  710. package/system/dist/hub-mdns-ciao-Czz2ssit.mjs +942 -0
  711. package/system/dist/i18n/catalog-registry.d.ts +35 -0
  712. package/system/dist/i18n/index.d.ts +2 -0
  713. package/system/dist/index.d.ts +156 -0
  714. package/system/dist/index.js +28736 -0
  715. package/system/dist/index.mjs +28065 -0
  716. package/system/dist/intel-accelerators-BvBjZn4j.js +16 -0
  717. package/system/dist/intel-accelerators-idEumqk1.mjs +15 -0
  718. package/system/dist/intel-npu-C8HKvRQF.mjs +27 -0
  719. package/system/dist/intel-npu-DYF5hO5K.js +28 -0
  720. package/system/dist/kernel/addon-class-resolver.d.ts +4 -0
  721. package/system/dist/kernel/addon-engine-manager.d.ts +22 -0
  722. package/system/dist/kernel/addon-health-monitor.d.ts +163 -0
  723. package/system/dist/kernel/addon-installer.d.ts +651 -0
  724. package/system/dist/kernel/addon-loader.d.ts +144 -0
  725. package/system/dist/kernel/addon-manifest.d.ts +128 -0
  726. package/system/dist/kernel/addon-refused-error.d.ts +30 -0
  727. package/system/dist/kernel/addon-residue.d.ts +45 -0
  728. package/system/dist/kernel/addon-settings-store.d.ts +43 -0
  729. package/system/dist/kernel/addon-version-policy.d.ts +34 -0
  730. package/system/dist/kernel/anon-rss.d.ts +12 -0
  731. package/system/dist/kernel/array-buffer-census.d.ts +118 -0
  732. package/system/dist/kernel/bootstrap-config.d.ts +7 -0
  733. package/system/dist/kernel/cap-router-builder.d.ts +180 -0
  734. package/system/dist/kernel/capability-handle.d.ts +46 -0
  735. package/system/dist/kernel/capability-registry.d.ts +621 -0
  736. package/system/dist/kernel/config-manager.d.ts +174 -0
  737. package/system/dist/kernel/config-schema.d.ts +37 -0
  738. package/system/dist/kernel/custom-action-registry.d.ts +32 -0
  739. package/system/dist/kernel/deps/addon-deps-manager.d.ts +28 -0
  740. package/system/dist/kernel/deps/closure-dedupe.d.ts +105 -0
  741. package/system/dist/kernel/deps/ensure-addon-natives.d.ts +41 -0
  742. package/system/dist/kernel/deps/ensure-native-prebuilds.d.ts +40 -0
  743. package/system/dist/kernel/deps/manifest-native-deps.d.ts +42 -0
  744. package/system/dist/kernel/deps/manifest-python-deps.d.ts +20 -0
  745. package/system/dist/kernel/deps/manifest-system-deps.d.ts +18 -0
  746. package/system/dist/kernel/deps/npm-command.d.ts +60 -0
  747. package/system/dist/kernel/deps/system-package-allowlist.d.ts +12 -0
  748. package/system/dist/kernel/deps/system-package-broker.d.ts +31 -0
  749. package/system/dist/kernel/deps/system-package-client.d.ts +9 -0
  750. package/system/dist/kernel/device-call-redirect.d.ts +18 -0
  751. package/system/dist/kernel/device-registry.d.ts +29 -0
  752. package/system/dist/kernel/device-settings-store.d.ts +74 -0
  753. package/system/dist/kernel/event-loop-stall-monitor.d.ts +41 -0
  754. package/system/dist/kernel/event-plane-report.d.ts +225 -0
  755. package/system/dist/kernel/fs-utils.d.ts +88 -0
  756. package/system/dist/kernel/gc-census.d.ts +161 -0
  757. package/system/dist/kernel/heap-spaces.d.ts +112 -0
  758. package/system/dist/kernel/heap-watch.d.ts +816 -0
  759. package/system/dist/kernel/host-externals.d.ts +12 -0
  760. package/system/dist/kernel/hwaccel/hwaccel-resolver.d.ts +56 -0
  761. package/system/dist/kernel/hwaccel/vaapi-init-probe.d.ts +29 -0
  762. package/system/dist/kernel/index.d.ts +116 -0
  763. package/system/dist/kernel/inference/inference-resolver.d.ts +22 -0
  764. package/system/dist/kernel/inference/local-python-runtimes.d.ts +2 -0
  765. package/system/dist/kernel/infra-capabilities.d.ts +13 -0
  766. package/system/dist/kernel/isolated-builtin-phase.d.ts +57 -0
  767. package/system/dist/kernel/lifecycle/job-journal.d.ts +19 -0
  768. package/system/dist/kernel/lifecycle/lifecycle-job-engine.d.ts +106 -0
  769. package/system/dist/kernel/lifecycle/staging-area.d.ts +31 -0
  770. package/system/dist/kernel/moleculer/accessory-prune-gate.d.ts +55 -0
  771. package/system/dist/kernel/moleculer/addon-context-factory.d.ts +104 -0
  772. package/system/dist/kernel/moleculer/addon-data-plane-facility.d.ts +19 -0
  773. package/system/dist/kernel/moleculer/addon-deploy-source.d.ts +16 -0
  774. package/system/dist/kernel/moleculer/addon-peer-bytes-facility.d.ts +25 -0
  775. package/system/dist/kernel/moleculer/addon-runner.d.ts +1 -0
  776. package/system/dist/kernel/moleculer/addon-service-factory.d.ts +50 -0
  777. package/system/dist/kernel/moleculer/agent-event-scope.d.ts +49 -0
  778. package/system/dist/kernel/moleculer/agent-ui-unlock.d.ts +67 -0
  779. package/system/dist/kernel/moleculer/broker-factory.d.ts +95 -0
  780. package/system/dist/kernel/moleculer/broker-transport-swap.d.ts +60 -0
  781. package/system/dist/kernel/moleculer/cap-usage-registry.d.ts +126 -0
  782. package/system/dist/kernel/moleculer/capabilities-access.d.ts +21 -0
  783. package/system/dist/kernel/moleculer/child-addon-call-dispatch.d.ts +53 -0
  784. package/system/dist/kernel/moleculer/child-cap-descriptors.d.ts +34 -0
  785. package/system/dist/kernel/moleculer/child-cap-dispatch.d.ts +59 -0
  786. package/system/dist/kernel/moleculer/children-batch-loader.d.ts +98 -0
  787. package/system/dist/kernel/moleculer/core-cap-service.d.ts +65 -0
  788. package/system/dist/kernel/moleculer/crash-supervisor.d.ts +50 -0
  789. package/system/dist/kernel/moleculer/device-cap-proxy.d.ts +70 -0
  790. package/system/dist/kernel/moleculer/device-event-ring.d.ts +155 -0
  791. package/system/dist/kernel/moleculer/event-bus-core.d.ts +198 -0
  792. package/system/dist/kernel/moleculer/event-bus.d.ts +106 -0
  793. package/system/dist/kernel/moleculer/hub-log-forwarder.d.ts +36 -0
  794. package/system/dist/kernel/moleculer/hub-service.d.ts +39 -0
  795. package/system/dist/kernel/moleculer/init-watchdog.d.ts +60 -0
  796. package/system/dist/kernel/moleculer/mesh-access-middleware.d.ts +42 -0
  797. package/system/dist/kernel/moleculer/mesh-identity.d.ts +57 -0
  798. package/system/dist/kernel/moleculer/mesh-mtls/constants.d.ts +17 -0
  799. package/system/dist/kernel/moleculer/mesh-mtls/index.d.ts +12 -0
  800. package/system/dist/kernel/moleculer/mesh-mtls/mesh-ca-keeper.d.ts +60 -0
  801. package/system/dist/kernel/moleculer/mesh-mtls/mesh-ca.d.ts +49 -0
  802. package/system/dist/kernel/moleculer/mesh-mtls/mesh-certificate-registry.d.ts +105 -0
  803. package/system/dist/kernel/moleculer/mesh-mtls/mesh-crl.d.ts +16 -0
  804. package/system/dist/kernel/moleculer/mesh-mtls/mesh-membership.d.ts +64 -0
  805. package/system/dist/kernel/moleculer/mesh-mtls/mesh-peer-transport.d.ts +47 -0
  806. package/system/dist/kernel/moleculer/mesh-mtls/mesh-renewal.d.ts +135 -0
  807. package/system/dist/kernel/moleculer/mesh-mtls/mesh-tls-enabler.d.ts +9 -0
  808. package/system/dist/kernel/moleculer/mesh-mtls/mesh-tls-gate.d.ts +40 -0
  809. package/system/dist/kernel/moleculer/mesh-mtls/pairing/agent-pairing.d.ts +214 -0
  810. package/system/dist/kernel/moleculer/mesh-mtls/pairing/hub-pairing.d.ts +115 -0
  811. package/system/dist/kernel/moleculer/mesh-mtls/pairing/index.d.ts +3 -0
  812. package/system/dist/kernel/moleculer/mesh-mtls/pairing/pairing-protocol.d.ts +107 -0
  813. package/system/dist/kernel/moleculer/mesh-mtls/tls-tcp-transporter.d.ts +242 -0
  814. package/system/dist/kernel/moleculer/mesh-queue-report.d.ts +51 -0
  815. package/system/dist/kernel/moleculer/node-registry.d.ts +146 -0
  816. package/system/dist/kernel/moleculer/process-context.d.ts +4 -0
  817. package/system/dist/kernel/moleculer/process-service.d.ts +92 -0
  818. package/system/dist/kernel/moleculer/provider-registry.d.ts +28 -0
  819. package/system/dist/kernel/moleculer/readiness-context.d.ts +67 -0
  820. package/system/dist/kernel/moleculer/readiness-service.d.ts +37 -0
  821. package/system/dist/kernel/moleculer/records-api-transport.d.ts +9 -0
  822. package/system/dist/kernel/moleculer/register-framework-resolver.d.ts +8 -0
  823. package/system/dist/kernel/moleculer/register-node-client.d.ts +49 -0
  824. package/system/dist/kernel/moleculer/remote-logger.d.ts +43 -0
  825. package/system/dist/kernel/moleculer/resilient-cap-call.d.ts +28 -0
  826. package/system/dist/kernel/moleculer/runner-addon-settings.d.ts +29 -0
  827. package/system/dist/kernel/moleculer/runner-device-settings.d.ts +39 -0
  828. package/system/dist/kernel/moleculer/runner-heap-flags.d.ts +228 -0
  829. package/system/dist/kernel/moleculer/runner-native-allocator.d.ts +107 -0
  830. package/system/dist/kernel/moleculer/runner-process-group.d.ts +96 -0
  831. package/system/dist/kernel/moleculer/runner-refusal.d.ts +27 -0
  832. package/system/dist/kernel/moleculer/runtime-state-load.d.ts +29 -0
  833. package/system/dist/kernel/moleculer/settings-read-guard.d.ts +49 -0
  834. package/system/dist/kernel/moleculer/stream-probe-service.d.ts +28 -0
  835. package/system/dist/kernel/moleculer/trpc-links.d.ts +244 -0
  836. package/system/dist/kernel/moleculer/typed-array-serde.d.ts +14 -0
  837. package/system/dist/kernel/moleculer/worker-device-restore.d.ts +10 -0
  838. package/system/dist/kernel/outbound-queue-watch.d.ts +94 -0
  839. package/system/dist/kernel/prefix-walk.d.ts +39 -0
  840. package/system/dist/kernel/process-cpu-census.d.ts +74 -0
  841. package/system/dist/kernel/provider-kind-drift.d.ts +21 -0
  842. package/system/dist/kernel/restart-coordinator.d.ts +90 -0
  843. package/system/dist/kernel/sections-store.d.ts +20 -0
  844. package/system/dist/kernel/settings-door-view.d.ts +41 -0
  845. package/system/dist/kernel/settings-read-error.d.ts +35 -0
  846. package/system/dist/kernel/settings-view-types.d.ts +80 -0
  847. package/system/dist/kernel/socket-plane-report.d.ts +268 -0
  848. package/system/dist/kernel/status-overlay.d.ts +38 -0
  849. package/system/dist/kernel/storage-location-registry.d.ts +55 -0
  850. package/system/dist/kernel/store-settings-view.d.ts +14 -0
  851. package/system/dist/kernel/system-settings-mirror.d.ts +46 -0
  852. package/system/dist/kernel/system-settings-policy.d.ts +28 -0
  853. package/system/dist/kernel/transport/cap-action-census.d.ts +218 -0
  854. package/system/dist/kernel/transport/cap-action-name.d.ts +100 -0
  855. package/system/dist/kernel/transport/cap-child-index.d.ts +49 -0
  856. package/system/dist/kernel/transport/cap-route-resolver.d.ts +231 -0
  857. package/system/dist/kernel/transport/cap-route.d.ts +168 -0
  858. package/system/dist/kernel/transport/cap-routing-hints.d.ts +42 -0
  859. package/system/dist/kernel/transport/child-cap-protocol.d.ts +307 -0
  860. package/system/dist/kernel/transport/claimed-get-status.d.ts +39 -0
  861. package/system/dist/kernel/transport/create-local-transport.d.ts +7 -0
  862. package/system/dist/kernel/transport/device-call-redirect.d.ts +39 -0
  863. package/system/dist/kernel/transport/frame-codec.d.ts +122 -0
  864. package/system/dist/kernel/transport/hub-cap-forward.d.ts +96 -0
  865. package/system/dist/kernel/transport/index.d.ts +38 -0
  866. package/system/dist/kernel/transport/local-child-client.d.ts +199 -0
  867. package/system/dist/kernel/transport/local-child-registry.d.ts +654 -0
  868. package/system/dist/kernel/transport/local-endpoint-path.d.ts +6 -0
  869. package/system/dist/kernel/transport/local-transport.d.ts +122 -0
  870. package/system/dist/kernel/transport/parent-unowned-call.d.ts +283 -0
  871. package/system/dist/kernel/transport/peer-answered-error.d.ts +21 -0
  872. package/system/dist/kernel/transport/socket-channel.d.ts +116 -0
  873. package/system/dist/kernel/transport/socket-traffic.d.ts +118 -0
  874. package/system/dist/kernel/transport/uds-event-bridge.d.ts +85 -0
  875. package/system/dist/kernel/transport/uds-event-bus.d.ts +93 -0
  876. package/system/dist/kernel/transport/uds-local-transport.d.ts +18 -0
  877. package/system/dist/kernel/transport/uds-log-ingest.d.ts +43 -0
  878. package/system/dist/kernel/transport/uds-logger.d.ts +44 -0
  879. package/system/dist/kernel/utils/ring-buffer.d.ts +15 -0
  880. package/system/dist/kernel/workspace-detect.d.ts +9 -0
  881. package/system/dist/lib-5THG9eKz.mjs +15545 -0
  882. package/system/dist/lib-C3U1yluo.js +7110 -0
  883. package/system/dist/lib-CZ3g2WTS.js +15549 -0
  884. package/system/dist/lib-DFZblCIu.mjs +7106 -0
  885. package/system/dist/lifecycle/lifecycle-state-machine.d.ts +28 -0
  886. package/system/dist/log-file-read-protocol-B7M3X3bT.mjs +785 -0
  887. package/system/dist/log-file-read-protocol-D0WcLbIV.js +817 -0
  888. package/system/dist/log-file-read-worker.js +64 -0
  889. package/system/dist/log-file-read-worker.mjs +64 -0
  890. package/system/dist/log-read-filter-Bi066jwU.js +134 -0
  891. package/system/dist/log-read-filter-D7Ev3zm-.mjs +93 -0
  892. package/system/dist/logging/formatter.d.ts +57 -0
  893. package/system/dist/logging/log-manager.d.ts +145 -0
  894. package/system/dist/logging/log-read-filter.d.ts +43 -0
  895. package/system/dist/logging/log-redactor.d.ts +30 -0
  896. package/system/dist/logging/log-ring-buffer.d.ts +62 -0
  897. package/system/dist/logging/logging-gate.d.ts +76 -0
  898. package/system/dist/logging/logging-gate.singleton.d.ts +16 -0
  899. package/system/dist/logging/partitioned-log-buffer.d.ts +169 -0
  900. package/system/dist/logging/scoped-logger.d.ts +17 -0
  901. package/system/dist/migrations/hub/index.d.ts +11 -0
  902. package/system/dist/ms-CgH2OFlD.mjs +120 -0
  903. package/system/dist/ms-LB3giGoU.js +124 -0
  904. package/system/dist/network/network-quality.d.ts +11 -0
  905. package/system/dist/notification/notification-service.d.ts +43 -0
  906. package/system/dist/notification/toast-service.d.ts +22 -0
  907. package/system/dist/pipeline/engine-manager-resolver.d.ts +15 -0
  908. package/system/dist/pipeline/pipeline-runner.d.ts +8 -0
  909. package/system/dist/pipeline/pipeline-validator.d.ts +13 -0
  910. package/system/dist/platform-key-source-BWlq0jjn.mjs +23 -0
  911. package/system/dist/platform-key-source-Di7HrlGR.js +40 -0
  912. package/system/dist/prefix-range-D_KueXbQ.js +27 -0
  913. package/system/dist/prefix-range-Dl0znowN.mjs +22 -0
  914. package/system/dist/prefix-walk-DAOBSyH1.mjs +88 -0
  915. package/system/dist/prefix-walk-Dv6MLZlM.js +99 -0
  916. package/system/dist/process/proc-stat.d.ts +75 -0
  917. package/system/dist/process/resource-monitor.d.ts +28 -0
  918. package/system/dist/python/python-env-manager.d.ts +12 -0
  919. package/system/dist/read-all-rows-CVoO1ONM.js +29 -0
  920. package/system/dist/read-all-rows-TaPqdWNF.mjs +25 -0
  921. package/system/dist/records/read-all-rows.d.ts +6 -0
  922. package/system/dist/repl/interfaces.d.ts +31 -0
  923. package/system/dist/repl/repl-engine.d.ts +8 -0
  924. package/system/dist/resource-monitor-Di9daRwI.mjs +96 -0
  925. package/system/dist/resource-monitor-mio9dSCT.js +113 -0
  926. package/system/dist/restore-archive-Cy7jGqiD.js +4325 -0
  927. package/system/dist/restore-archive-DS4nvQ43.mjs +4213 -0
  928. package/system/dist/retention-Dqm_EiVq.mjs +893 -0
  929. package/system/dist/retention-Ufa2fci-.js +1024 -0
  930. package/system/dist/retired-settings-keys-C8nOOr5H.js +381 -0
  931. package/system/dist/retired-settings-keys-u6xQA6r7.mjs +364 -0
  932. package/system/dist/safe-buffer-B1OjL1I9.mjs +42 -0
  933. package/system/dist/safe-buffer-D3aoa-7X.js +46 -0
  934. package/system/dist/settle-sources-Bhsy57y-.js +38 -0
  935. package/system/dist/settle-sources-CDtNC8ub.mjs +33 -0
  936. package/system/dist/snapshot-courtesy-CyFs1M3I.mjs +167 -0
  937. package/system/dist/snapshot-courtesy-D_C5-nC0.js +192 -0
  938. package/system/dist/sqlite-snapshot-protocol-2QaTouWV.mjs +34 -0
  939. package/system/dist/sqlite-snapshot-protocol-B9OndqZv.js +51 -0
  940. package/system/dist/sqlite-snapshot-worker.js +185 -0
  941. package/system/dist/sqlite-snapshot-worker.mjs +179 -0
  942. package/system/dist/src-CnAqG6EF.js +714 -0
  943. package/system/dist/src-hG4grMU4.mjs +709 -0
  944. package/system/dist/storage/fs-storage-backend.d.ts +40 -0
  945. package/system/dist/storage/storage-location-manager.d.ts +23 -0
  946. package/system/dist/storage/storage-manager.d.ts +83 -0
  947. package/system/dist/tls/agent-https-names.d.ts +25 -0
  948. package/system/dist/tls/agent-https.d.ts +111 -0
  949. package/system/dist/tls/boot-tls.d.ts +35 -0
  950. package/system/dist/tls/cert-backdate.d.ts +10 -0
  951. package/system/dist/tls/cert-evaluation.d.ts +41 -0
  952. package/system/dist/tls/cert-identity.d.ts +60 -0
  953. package/system/dist/tls/cert-issue.d.ts +57 -0
  954. package/system/dist/tls/cert-manager.d.ts +124 -0
  955. package/system/dist/tls/cert-name-constraints.d.ts +53 -0
  956. package/system/dist/tls/cert-utc-time.d.ts +1 -0
  957. package/system/dist/tls/https-listener.d.ts +30 -0
  958. package/system/dist/tls/index.d.ts +12 -0
  959. package/system/dist/tls/tls-actions.d.ts +49 -0
  960. package/system/dist/tls/tls-status.d.ts +57 -0
  961. package/system/dist/tls/uploaded-cert.d.ts +46 -0
  962. package/system/dist/wal-checkpoint-policy-BahrTtyD.mjs +186 -0
  963. package/system/dist/wal-checkpoint-policy-d2z2qPqx.js +233 -0
  964. package/system/dist/wal-checkpoint-worker.js +144 -0
  965. package/system/dist/wal-checkpoint-worker.mjs +143 -0
  966. package/system/dist/wal-maintenance-BmugbgS7.js +0 -0
  967. package/system/dist/wal-maintenance-Bnb2QzYG.mjs +0 -0
  968. package/system/dist/x509.es-BRiJgOvu.mjs +11939 -0
  969. package/system/dist/x509.es-WtnRNyYS.js +12076 -0
  970. package/system/package.json +516 -0
@@ -0,0 +1,3204 @@
1
+ import { Cs as toNodeId, Ms as EventCategory, Qa as BaseAddon, Wr as mayWriteToLocation, an as backupCapability, ls as nodePin, na as storageOccupancyCapability } from "../../dist-DcMqHB_N.mjs";
2
+ import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
+ import { _ as backupRecordStoresOf, a as BackupSnapshotRefusedError, d as ENCRYPTED_BACKUP_SUFFIX, f as generateBackupKeyPair, g as backupOrchestratorRecordKinds, i as BackupCancelledError, l as BackupKeyFormatError, m as parseBackupSecretKey, n as precheckRestoreKey, o as DEFAULT_BACKUP_DATABASES, p as parseBackupPublicKey, r as prepareRestoreArchive, s as SystemBackupService } from "../../restore-archive-DS4nvQ43.mjs";
4
+ import { randomUUID } from "node:crypto";
5
+ import * as fsp from "node:fs/promises";
6
+ import * as path$1 from "node:path";
7
+ import * as fs$1 from "node:fs";
8
+ //#region src/builtins/backup-orchestrator/backup-databases.ts
9
+ /** Stable id of the seeded weekly schedule. */
10
+ var WEEKLY_SCHEDULE_ID = "weekly-events-history";
11
+ var WEEKLY_SCHEDULE_LABEL = "Weekly — events & history";
12
+ /** Sundays 04:00 — an hour after the nightly settings run. */
13
+ var WEEKLY_SCHEDULE_CRON = "0 4 * * 0";
14
+ /**
15
+ * Events and history ONLY: a run that does not select settings carries no
16
+ * data-root walk either, so the weekly archive is just the two snapshots.
17
+ */
18
+ var WEEKLY_SCHEDULE_DATABASES = ["events", "history"];
19
+ /** What a schedule carries: its own list, else the minimum (D382). */
20
+ function databasesOfSchedule(schedule) {
21
+ return schedule.databases !== void 0 && schedule.databases.length > 0 ? schedule.databases : DEFAULT_BACKUP_DATABASES;
22
+ }
23
+ /**
24
+ * True when a run asks for a database beyond settings and the owner has none
25
+ * of them open: the run would only repeat the nightly archive. A settings-only
26
+ * run is never nothing-to-carry.
27
+ */
28
+ function hasNothingBeyondSettings(requested, owned) {
29
+ const extra = requested.filter((id) => id !== "settings");
30
+ if (extra.length === 0) return false;
31
+ return !extra.some((id) => owned.includes(id));
32
+ }
33
+ /**
34
+ * The weekly schedule to seed, or null. Created only when NO schedule carries
35
+ * `events` (a seed never overwrites, D728 — an operator's own weekly schedule,
36
+ * or an edited seed, is left alone), and only when there is a nightly schedule
37
+ * to take the destinations from: a hub that backs up nowhere gets no weekly
38
+ * archive either.
39
+ */
40
+ function planWeeklySeed(existing) {
41
+ if (existing.some((s) => s.id === "weekly-events-history")) return null;
42
+ if (existing.some((s) => databasesOfSchedule(s).includes("events"))) return null;
43
+ const destinations = /* @__PURE__ */ new Set();
44
+ for (const s of existing) {
45
+ if (!s.enabled) continue;
46
+ for (const id of s.locationIds) destinations.add(id);
47
+ }
48
+ if (destinations.size === 0) return null;
49
+ return {
50
+ id: WEEKLY_SCHEDULE_ID,
51
+ label: WEEKLY_SCHEDULE_LABEL,
52
+ cron: WEEKLY_SCHEDULE_CRON,
53
+ enabled: true,
54
+ locationIds: [...destinations].toSorted(),
55
+ retentionCount: 4,
56
+ databases: WEEKLY_SCHEDULE_DATABASES
57
+ };
58
+ }
59
+ /**
60
+ * Seed the weekly schedule if {@link planWeeklySeed} says so; returns what it
61
+ * wrote. Exactly once ever: the marker is written after the row, and a marker
62
+ * that exists ends the seed for good — an operator who disabled or deleted the
63
+ * weekly is never second-guessed. A weekly row found with no marker (seeded
64
+ * before the marker existed) is marked, not re-created.
65
+ */
66
+ async function seedWeeklySchedule(store, markers) {
67
+ if (await markers.has("weekly-events-history")) return null;
68
+ const existing = await store.list();
69
+ if (existing.some((s) => s.id === "weekly-events-history")) {
70
+ await markers.mark(WEEKLY_SCHEDULE_ID);
71
+ return null;
72
+ }
73
+ const seed = planWeeklySeed(existing);
74
+ if (seed === null) return null;
75
+ await store.upsert(seed);
76
+ await markers.mark(WEEKLY_SCHEDULE_ID);
77
+ return seed;
78
+ }
79
+ //#endregion
80
+ //#region src/builtins/backup-orchestrator/seed-marker-store.ts
81
+ /**
82
+ * One `seed-markers` row per seed id (D902: no `backup_seed_markers` table).
83
+ * Written once, never updated; deleting one lets that seed run once more.
84
+ */
85
+ var BackupSeedMarkerStore = class {
86
+ markersKind;
87
+ now;
88
+ constructor(markersKind, now = Date.now) {
89
+ this.markersKind = markersKind;
90
+ this.now = now;
91
+ }
92
+ async has(seedId) {
93
+ return await this.markersKind.get(seedId) !== null;
94
+ }
95
+ async mark(seedId) {
96
+ if (await this.has(seedId)) return;
97
+ const body = { seededAt: this.now() };
98
+ const data = backupOrchestratorRecordKinds["seed-markers"].schema.parse(body);
99
+ await this.markersKind.put({
100
+ id: seedId,
101
+ data
102
+ });
103
+ }
104
+ };
105
+ //#endregion
106
+ //#region ../../node_modules/croner/dist/croner.js
107
+ function T(s) {
108
+ return Date.UTC(s.y, s.m - 1, s.d, s.h, s.i, s.s);
109
+ }
110
+ function D(s, e) {
111
+ return s.y === e.y && s.m === e.m && s.d === e.d && s.h === e.h && s.i === e.i && s.s === e.s;
112
+ }
113
+ function A(s, e) {
114
+ let t = new Date(Date.parse(s));
115
+ if (isNaN(t)) throw new Error("Invalid ISO8601 passed to timezone parser.");
116
+ let r = s.substring(9);
117
+ return r.includes("Z") || r.includes("+") || r.includes("-") ? b(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds(), "Etc/UTC") : b(t.getFullYear(), t.getMonth() + 1, t.getDate(), t.getHours(), t.getMinutes(), t.getSeconds(), e);
118
+ }
119
+ function v(s, e, t) {
120
+ return k(A(s, e), t);
121
+ }
122
+ function k(s, e) {
123
+ let t = new Date(T(s)), r = g(t, s.tz), a = T(s) - T(r), o = new Date(t.getTime() + a), h = g(o, s.tz);
124
+ if (D(h, s)) {
125
+ let u = /* @__PURE__ */ new Date(o.getTime() - 36e5);
126
+ return D(g(u, s.tz), s) ? u : o;
127
+ }
128
+ let l = new Date(o.getTime() + T(s) - T(h));
129
+ if (D(g(l, s.tz), s)) return l;
130
+ if (e) throw new Error("Invalid date passed to fromTZ()");
131
+ return o.getTime() > l.getTime() ? o : l;
132
+ }
133
+ function g(s, e) {
134
+ let t, r;
135
+ try {
136
+ t = new Intl.DateTimeFormat("en-US", {
137
+ timeZone: e,
138
+ year: "numeric",
139
+ month: "numeric",
140
+ day: "numeric",
141
+ hour: "numeric",
142
+ minute: "numeric",
143
+ second: "numeric",
144
+ hour12: !1
145
+ }), r = t.formatToParts(s);
146
+ } catch (i) {
147
+ let a = i instanceof Error ? i.message : String(i);
148
+ throw new RangeError(`toTZ: Invalid timezone '${e}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${a}`);
149
+ }
150
+ let n = {
151
+ year: 0,
152
+ month: 0,
153
+ day: 0,
154
+ hour: 0,
155
+ minute: 0,
156
+ second: 0
157
+ };
158
+ for (let i of r) (i.type === "year" || i.type === "month" || i.type === "day" || i.type === "hour" || i.type === "minute" || i.type === "second") && (n[i.type] = parseInt(i.value, 10));
159
+ if (isNaN(n.year) || isNaN(n.month) || isNaN(n.day) || isNaN(n.hour) || isNaN(n.minute) || isNaN(n.second)) throw new Error(`toTZ: Failed to parse all date components from timezone '${e}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(n)}`);
160
+ return n.hour === 24 && (n.hour = 0), {
161
+ y: n.year,
162
+ m: n.month,
163
+ d: n.day,
164
+ h: n.hour,
165
+ i: n.minute,
166
+ s: n.second,
167
+ tz: e
168
+ };
169
+ }
170
+ function b(s, e, t, r, n, i, a) {
171
+ return {
172
+ y: s,
173
+ m: e,
174
+ d: t,
175
+ h: r,
176
+ i: n,
177
+ s: i,
178
+ tz: a
179
+ };
180
+ }
181
+ var O = [
182
+ 1,
183
+ 2,
184
+ 4,
185
+ 8,
186
+ 16
187
+ ], C = class {
188
+ pattern;
189
+ timezone;
190
+ mode;
191
+ alternativeWeekdays;
192
+ sloppyRanges;
193
+ second;
194
+ minute;
195
+ hour;
196
+ day;
197
+ month;
198
+ dayOfWeek;
199
+ year;
200
+ lastDayOfMonth;
201
+ lastWeekday;
202
+ nearestWeekdays;
203
+ starDOM;
204
+ starDOW;
205
+ starYear;
206
+ useAndLogic;
207
+ constructor(e, t, r) {
208
+ this.pattern = e, this.timezone = t, this.mode = r?.mode ?? "auto", this.alternativeWeekdays = r?.alternativeWeekdays ?? !1, this.sloppyRanges = r?.sloppyRanges ?? !1, this.second = Array(60).fill(0), this.minute = Array(60).fill(0), this.hour = Array(24).fill(0), this.day = Array(31).fill(0), this.month = Array(12).fill(0), this.dayOfWeek = Array(7).fill(0), this.year = Array(1e4).fill(0), this.lastDayOfMonth = !1, this.lastWeekday = !1, this.nearestWeekdays = Array(31).fill(0), this.starDOM = !1, this.starDOW = !1, this.starYear = !1, this.useAndLogic = !1, this.parse();
209
+ }
210
+ parse() {
211
+ if (!(typeof this.pattern == "string" || this.pattern instanceof String)) throw new TypeError("CronPattern: Pattern has to be of type string.");
212
+ this.pattern.indexOf("@") >= 0 && (this.pattern = this.handleNicknames(this.pattern).trim());
213
+ let e = this.pattern.match(/\S+/g) || [""], t = e.length;
214
+ if (e.length < 5 || e.length > 7) throw new TypeError("CronPattern: invalid configuration format ('" + this.pattern + "'), exactly five, six, or seven space separated parts are required.");
215
+ if (this.mode !== "auto") {
216
+ let n;
217
+ switch (this.mode) {
218
+ case "5-part":
219
+ n = 5;
220
+ break;
221
+ case "6-part":
222
+ n = 6;
223
+ break;
224
+ case "7-part":
225
+ n = 7;
226
+ break;
227
+ case "5-or-6-parts":
228
+ n = [5, 6];
229
+ break;
230
+ case "6-or-7-parts":
231
+ n = [6, 7];
232
+ break;
233
+ default: n = 0;
234
+ }
235
+ if (!(Array.isArray(n) ? n.includes(t) : t === n)) {
236
+ let a = Array.isArray(n) ? n.join(" or ") : n.toString();
237
+ throw new TypeError(`CronPattern: mode '${this.mode}' requires exactly ${a} parts, but pattern '${this.pattern}' has ${t} parts.`);
238
+ }
239
+ }
240
+ if (e.length === 5 && e.unshift("0"), e.length === 6 && e.push("*"), e[3].toUpperCase() === "LW" ? (this.lastWeekday = !0, e[3] = "") : e[3].toUpperCase().indexOf("L") >= 0 && (e[3] = e[3].replace(/L/gi, ""), this.lastDayOfMonth = !0), e[3] == "*" && (this.starDOM = !0), e[6] == "*" && (this.starYear = !0), e[4].length >= 3 && (e[4] = this.replaceAlphaMonths(e[4])), e[5].length >= 3 && (e[5] = this.alternativeWeekdays ? this.replaceAlphaDaysQuartz(e[5]) : this.replaceAlphaDays(e[5])), e[5].startsWith("+") && (this.useAndLogic = !0, e[5] = e[5].substring(1), e[5] === "")) throw new TypeError("CronPattern: Day-of-week field cannot be empty after '+' modifier.");
241
+ switch (e[5] == "*" && (this.starDOW = !0), this.pattern.indexOf("?") >= 0 && (e[0] = e[0].replace(/\?/g, "*"), e[1] = e[1].replace(/\?/g, "*"), e[2] = e[2].replace(/\?/g, "*"), e[3] = e[3].replace(/\?/g, "*"), e[4] = e[4].replace(/\?/g, "*"), e[5] = e[5].replace(/\?/g, "*"), e[6] && (e[6] = e[6].replace(/\?/g, "*"))), this.mode) {
242
+ case "5-part":
243
+ e[0] = "0", e[6] = "*";
244
+ break;
245
+ case "6-part":
246
+ e[6] = "*";
247
+ break;
248
+ case "5-or-6-parts":
249
+ e[6] = "*";
250
+ break;
251
+ case "6-or-7-parts": break;
252
+ case "7-part":
253
+ case "auto": break;
254
+ }
255
+ this.throwAtIllegalCharacters(e), this.partToArray("second", e[0], 0, 1), this.partToArray("minute", e[1], 0, 1), this.partToArray("hour", e[2], 0, 1), this.partToArray("day", e[3], -1, 1), this.partToArray("month", e[4], -1, 1);
256
+ let r = this.alternativeWeekdays ? -1 : 0;
257
+ this.partToArray("dayOfWeek", e[5], r, 63), this.partToArray("year", e[6], 0, 1), !this.alternativeWeekdays && this.dayOfWeek[7] && (this.dayOfWeek[0] = this.dayOfWeek[7]);
258
+ }
259
+ partToArray(e, t, r, n) {
260
+ let i = this[e], a = e === "day" && this.lastDayOfMonth, o = e === "day" && this.lastWeekday;
261
+ if (t === "" && !a && !o) throw new TypeError("CronPattern: configuration entry " + e + " (" + t + ") is empty, check for trailing spaces.");
262
+ if (t === "*") return i.fill(n);
263
+ let h = t.split(",");
264
+ if (h.length > 1) for (let l = 0; l < h.length; l++) this.partToArray(e, h[l], r, n);
265
+ else t.indexOf("-") !== -1 && t.indexOf("/") !== -1 ? this.handleRangeWithStepping(t, e, r, n) : t.indexOf("-") !== -1 ? this.handleRange(t, e, r, n) : t.indexOf("/") !== -1 ? this.handleStepping(t, e, r, n) : t !== "" && this.handleNumber(t, e, r, n);
266
+ }
267
+ throwAtIllegalCharacters(e) {
268
+ for (let t = 0; t < e.length; t++) if ((t === 3 ? /[^/*0-9,\-WwLl]+/ : t === 5 ? /[^/*0-9,\-#Ll]+/ : /[^/*0-9,\-]+/).test(e[t])) throw new TypeError("CronPattern: configuration entry " + t + " (" + e[t] + ") contains illegal characters.");
269
+ }
270
+ handleNumber(e, t, r, n) {
271
+ let i = this.extractNth(e, t), a = e.toUpperCase().includes("W");
272
+ if (t !== "day" && a) throw new TypeError("CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.");
273
+ a && (t = "nearestWeekdays");
274
+ let o = parseInt(i[0], 10) + r;
275
+ if (isNaN(o)) throw new TypeError("CronPattern: " + t + " is not a number: '" + e + "'");
276
+ this.setPart(t, o, i[1] || n);
277
+ }
278
+ setPart(e, t, r) {
279
+ if (!Object.prototype.hasOwnProperty.call(this, e)) throw new TypeError("CronPattern: Invalid part specified: " + e);
280
+ if (e === "dayOfWeek") {
281
+ if (t === 7 && (t = 0), t < 0 || t > 6) throw new RangeError("CronPattern: Invalid value for dayOfWeek: " + t);
282
+ this.setNthWeekdayOfMonth(t, r);
283
+ return;
284
+ }
285
+ if (e === "second" || e === "minute") {
286
+ if (t < 0 || t >= 60) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
287
+ } else if (e === "hour") {
288
+ if (t < 0 || t >= 24) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
289
+ } else if (e === "day" || e === "nearestWeekdays") {
290
+ if (t < 0 || t >= 31) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
291
+ } else if (e === "month") {
292
+ if (t < 0 || t >= 12) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
293
+ } else if (e === "year" && (t < 1 || t >= 1e4)) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t + " (supported range: 1-9999)");
294
+ this[e][t] = r;
295
+ }
296
+ validateNotNaN(e, t) {
297
+ if (isNaN(e)) throw new TypeError(t);
298
+ }
299
+ validateRange(e, t, r, n, i) {
300
+ if (e > t) throw new TypeError("CronPattern: From value is larger than to value: '" + i + "'");
301
+ if (r !== void 0) {
302
+ if (r === 0) throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");
303
+ if (r > this[n].length) throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part (" + this[n].length + ")");
304
+ }
305
+ }
306
+ handleRangeWithStepping(e, t, r, n) {
307
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in ranges with stepping.");
308
+ let i = this.extractNth(e, t), a = i[0].match(/^(\d+)-(\d+)\/(\d+)$/);
309
+ if (a === null) throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '" + e + "'");
310
+ let [, o, h, l] = a, y = parseInt(o, 10) + r, u = parseInt(h, 10) + r, d = parseInt(l, 10);
311
+ this.validateNotNaN(y, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(u, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateNotNaN(d, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(y, u, d, t, e);
312
+ for (let c = y; c <= u; c += d) this.setPart(t, c, i[1] || n);
313
+ }
314
+ extractNth(e, t) {
315
+ let r = e, n;
316
+ if (r.includes("#")) {
317
+ if (t !== "dayOfWeek") throw new Error("CronPattern: nth (#) only allowed in day-of-week field");
318
+ n = r.split("#")[1], r = r.split("#")[0];
319
+ } else if (r.toUpperCase().endsWith("L")) {
320
+ if (t !== "dayOfWeek") throw new Error("CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)");
321
+ n = "L", r = r.slice(0, -1);
322
+ }
323
+ return [r, n];
324
+ }
325
+ handleRange(e, t, r, n) {
326
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in a range.");
327
+ let i = this.extractNth(e, t), a = i[0].split("-");
328
+ if (a.length !== 2) throw new TypeError("CronPattern: Syntax error, illegal range: '" + e + "'");
329
+ let o = parseInt(a[0], 10) + r, h = parseInt(a[1], 10) + r;
330
+ this.validateNotNaN(o, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(h, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateRange(o, h, void 0, t, e);
331
+ for (let l = o; l <= h; l++) this.setPart(t, l, i[1] || n);
332
+ }
333
+ handleStepping(e, t, r, n) {
334
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in parts with stepping.");
335
+ let i = this.extractNth(e, t), a = i[0].split("/");
336
+ if (a.length !== 2) throw new TypeError("CronPattern: Syntax error, illegal stepping: '" + e + "'");
337
+ if (this.sloppyRanges) a[0] === "" && (a[0] = "*");
338
+ else {
339
+ if (a[0] === "") throw new TypeError("CronPattern: Syntax error, stepping with missing prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
340
+ if (a[0] !== "*") throw new TypeError("CronPattern: Syntax error, stepping with numeric prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
341
+ }
342
+ let o = 0;
343
+ a[0] !== "*" && (o = parseInt(a[0], 10) + r);
344
+ let h = parseInt(a[1], 10);
345
+ this.validateNotNaN(h, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(0, this[t].length - 1, h, t, e);
346
+ for (let l = o; l < this[t].length; l += h) this.setPart(t, l, i[1] || n);
347
+ }
348
+ replaceAlphaDays(e) {
349
+ return e.replace(/-sun/gi, "-7").replace(/sun/gi, "0").replace(/mon/gi, "1").replace(/tue/gi, "2").replace(/wed/gi, "3").replace(/thu/gi, "4").replace(/fri/gi, "5").replace(/sat/gi, "6");
350
+ }
351
+ replaceAlphaDaysQuartz(e) {
352
+ return e.replace(/sun/gi, "1").replace(/mon/gi, "2").replace(/tue/gi, "3").replace(/wed/gi, "4").replace(/thu/gi, "5").replace(/fri/gi, "6").replace(/sat/gi, "7");
353
+ }
354
+ replaceAlphaMonths(e) {
355
+ return e.replace(/jan/gi, "1").replace(/feb/gi, "2").replace(/mar/gi, "3").replace(/apr/gi, "4").replace(/may/gi, "5").replace(/jun/gi, "6").replace(/jul/gi, "7").replace(/aug/gi, "8").replace(/sep/gi, "9").replace(/oct/gi, "10").replace(/nov/gi, "11").replace(/dec/gi, "12");
356
+ }
357
+ handleNicknames(e) {
358
+ let t = e.trim().toLowerCase();
359
+ if (t === "@yearly" || t === "@annually") return "0 0 1 1 *";
360
+ if (t === "@monthly") return "0 0 1 * *";
361
+ if (t === "@weekly") return "0 0 * * 0";
362
+ if (t === "@daily" || t === "@midnight") return "0 0 * * *";
363
+ if (t === "@hourly") return "0 * * * *";
364
+ if (t === "@reboot") throw new TypeError("CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.");
365
+ return e;
366
+ }
367
+ setNthWeekdayOfMonth(e, t) {
368
+ if (typeof t != "number" && t.toUpperCase() === "L") this.dayOfWeek[e] = this.dayOfWeek[e] | 32;
369
+ else if (t === 63) this.dayOfWeek[e] = 63;
370
+ else if (t < 6 && t > 0) this.dayOfWeek[e] = this.dayOfWeek[e] | O[t - 1];
371
+ else throw new TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`);
372
+ }
373
+ };
374
+ var P = [
375
+ 31,
376
+ 28,
377
+ 31,
378
+ 30,
379
+ 31,
380
+ 30,
381
+ 31,
382
+ 31,
383
+ 30,
384
+ 31,
385
+ 30,
386
+ 31
387
+ ], f = [
388
+ [
389
+ "month",
390
+ "year",
391
+ 0
392
+ ],
393
+ [
394
+ "day",
395
+ "month",
396
+ -1
397
+ ],
398
+ [
399
+ "hour",
400
+ "day",
401
+ 0
402
+ ],
403
+ [
404
+ "minute",
405
+ "hour",
406
+ 0
407
+ ],
408
+ [
409
+ "second",
410
+ "minute",
411
+ 0
412
+ ]
413
+ ], m = class s {
414
+ tz;
415
+ ms;
416
+ second;
417
+ minute;
418
+ hour;
419
+ day;
420
+ month;
421
+ year;
422
+ constructor(e, t) {
423
+ if (this.tz = t, e && e instanceof Date) if (!isNaN(e)) this.fromDate(e);
424
+ else throw new TypeError("CronDate: Invalid date passed to CronDate constructor");
425
+ else if (e == null) this.fromDate(/* @__PURE__ */ new Date());
426
+ else if (e && typeof e == "string") this.fromString(e);
427
+ else if (e instanceof s) this.fromCronDate(e);
428
+ else throw new TypeError("CronDate: Invalid type (" + typeof e + ") passed to CronDate constructor");
429
+ }
430
+ getLastDayOfMonth(e, t) {
431
+ return t !== 1 ? P[t] : new Date(Date.UTC(e, t + 1, 0)).getUTCDate();
432
+ }
433
+ getLastWeekday(e, t) {
434
+ let r = this.getLastDayOfMonth(e, t), i = new Date(Date.UTC(e, t, r)).getUTCDay();
435
+ return i === 0 ? r - 2 : i === 6 ? r - 1 : r;
436
+ }
437
+ getNearestWeekday(e, t, r) {
438
+ let n = this.getLastDayOfMonth(e, t);
439
+ if (r > n) return -1;
440
+ let a = new Date(Date.UTC(e, t, r)).getUTCDay();
441
+ return a === 0 ? r === n ? r - 2 : r + 1 : a === 6 ? r === 1 ? r + 2 : r - 1 : r;
442
+ }
443
+ isNthWeekdayOfMonth(e, t, r, n) {
444
+ let a = new Date(Date.UTC(e, t, r)).getUTCDay(), o = 0;
445
+ for (let h = 1; h <= r; h++) new Date(Date.UTC(e, t, h)).getUTCDay() === a && o++;
446
+ if (n & 63 && O[o - 1] & n) return !0;
447
+ if (n & 32) {
448
+ let h = this.getLastDayOfMonth(e, t);
449
+ for (let l = r + 1; l <= h; l++) if (new Date(Date.UTC(e, t, l)).getUTCDay() === a) return !1;
450
+ return !0;
451
+ }
452
+ return !1;
453
+ }
454
+ fromDate(e) {
455
+ if (this.tz !== void 0) if (typeof this.tz == "number") this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes() + this.tz, this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), this.apply();
456
+ else try {
457
+ let t = g(e, this.tz);
458
+ this.ms = e.getMilliseconds(), this.second = t.s, this.minute = t.i, this.hour = t.h, this.day = t.d, this.month = t.m - 1, this.year = t.y;
459
+ } catch (t) {
460
+ let r = t instanceof Error ? t.message : String(t);
461
+ throw new TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${r}`);
462
+ }
463
+ else this.ms = e.getMilliseconds(), this.second = e.getSeconds(), this.minute = e.getMinutes(), this.hour = e.getHours(), this.day = e.getDate(), this.month = e.getMonth(), this.year = e.getFullYear();
464
+ }
465
+ fromCronDate(e) {
466
+ this.tz = e.tz, this.year = e.year, this.month = e.month, this.day = e.day, this.hour = e.hour, this.minute = e.minute, this.second = e.second, this.ms = e.ms;
467
+ }
468
+ apply() {
469
+ if (this.month > 11 || this.month < 0 || this.day > P[this.month] || this.day < 1 || this.hour > 59 || this.minute > 59 || this.second > 59 || this.hour < 0 || this.minute < 0 || this.second < 0) {
470
+ let e = new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms));
471
+ return this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes(), this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), !0;
472
+ } else return !1;
473
+ }
474
+ fromString(e) {
475
+ if (typeof this.tz == "number") {
476
+ let t = v(e);
477
+ this.ms = t.getUTCMilliseconds(), this.second = t.getUTCSeconds(), this.minute = t.getUTCMinutes(), this.hour = t.getUTCHours(), this.day = t.getUTCDate(), this.month = t.getUTCMonth(), this.year = t.getUTCFullYear(), this.apply();
478
+ } else return this.fromDate(v(e, this.tz));
479
+ }
480
+ findNext(e, t, r, n) {
481
+ return this._findMatch(e, t, r, n, 1);
482
+ }
483
+ _findMatch(e, t, r, n, i) {
484
+ let a = this[t], o;
485
+ r.lastDayOfMonth && (o = this.getLastDayOfMonth(this.year, this.month));
486
+ let h = !r.starDOW && t == "day" ? new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay() : void 0, l = this[t] + n, y = i === 1 ? (u) => u < r[t].length : (u) => u >= 0;
487
+ for (let u = l; y(u); u += i) {
488
+ let d = r[t][u];
489
+ if (t === "day" && !d) {
490
+ for (let c = 0; c < r.nearestWeekdays.length; c++) if (r.nearestWeekdays[c]) {
491
+ let M = this.getNearestWeekday(this.year, this.month, c - n);
492
+ if (M === -1) continue;
493
+ if (M === u - n) {
494
+ d = 1;
495
+ break;
496
+ }
497
+ }
498
+ }
499
+ if (t === "day" && r.lastWeekday) {
500
+ let c = this.getLastWeekday(this.year, this.month);
501
+ u - n === c && (d = 1);
502
+ }
503
+ if (t === "day" && r.lastDayOfMonth && u - n == o && (d = 1), t === "day" && !r.starDOW) {
504
+ let c = r.dayOfWeek[(h + (u - n - 1)) % 7];
505
+ if (c && c & 63) c = this.isNthWeekdayOfMonth(this.year, this.month, u - n, c) ? 1 : 0;
506
+ else if (c) throw new Error(`CronDate: Invalid value for dayOfWeek encountered. ${c}`);
507
+ r.useAndLogic ? d = d && c : !e.domAndDow && !r.starDOM ? d = d || c : d = d && c;
508
+ }
509
+ if (d) return this[t] = u - n, a !== this[t] ? 2 : 1;
510
+ }
511
+ return 3;
512
+ }
513
+ recurse(e, t, r) {
514
+ if (r === 0 && !e.starYear) {
515
+ if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
516
+ let i = -1;
517
+ for (let a = this.year + 1; a < e.year.length && a < 1e4; a++) if (e.year[a] === 1) {
518
+ i = a;
519
+ break;
520
+ }
521
+ if (i === -1) return null;
522
+ this.year = i, this.month = 0, this.day = 1, this.hour = 0, this.minute = 0, this.second = 0, this.ms = 0;
523
+ }
524
+ if (this.year >= 1e4) return null;
525
+ }
526
+ let n = this.findNext(t, f[r][0], e, f[r][2]);
527
+ if (n > 1) {
528
+ let i = r + 1;
529
+ for (; i < f.length;) this[f[i][0]] = -f[i][2], i++;
530
+ if (n === 3) {
531
+ if (this[f[r][1]]++, this[f[r][0]] = -f[r][2], this.apply(), r === 0 && !e.starYear) {
532
+ for (; this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0 && this.year < 1e4;) this.year++;
533
+ if (this.year >= 1e4 || this.year >= e.year.length) return null;
534
+ }
535
+ return this.recurse(e, t, 0);
536
+ } else if (this.apply()) return this.recurse(e, t, r - 1);
537
+ }
538
+ return r += 1, r >= f.length ? this : (e.starYear ? this.year >= 3e3 : this.year >= 1e4) ? null : this.recurse(e, t, r);
539
+ }
540
+ increment(e, t, r) {
541
+ return this.second += t.interval !== void 0 && t.interval > 1 && r ? t.interval : 1, this.ms = 0, this.apply(), this.recurse(e, t, 0);
542
+ }
543
+ decrement(e, t) {
544
+ return this.second -= t.interval !== void 0 && t.interval > 1 ? t.interval : 1, this.ms = 0, this.apply(), this.recurseBackward(e, t, 0, 0);
545
+ }
546
+ recurseBackward(e, t, r, n = 0) {
547
+ if (n > 1e4) return null;
548
+ if (r === 0 && !e.starYear) {
549
+ if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
550
+ let a = -1;
551
+ for (let o = this.year - 1; o >= 0; o--) if (e.year[o] === 1) {
552
+ a = o;
553
+ break;
554
+ }
555
+ if (a === -1) return null;
556
+ this.year = a, this.month = 11, this.day = 31, this.hour = 23, this.minute = 59, this.second = 59, this.ms = 0;
557
+ }
558
+ if (this.year < 0) return null;
559
+ }
560
+ let i = this.findPrevious(t, f[r][0], e, f[r][2]);
561
+ if (i > 1) {
562
+ let a = r + 1;
563
+ for (; a < f.length;) {
564
+ let o = f[a][0], h = f[a][2], l = this.getMaxPatternValue(o, e, h);
565
+ this[o] = l, a++;
566
+ }
567
+ if (i === 3) {
568
+ if (this[f[r][1]]--, r === 0) {
569
+ let y = this.getLastDayOfMonth(this.year, this.month);
570
+ this.day > y && (this.day = y);
571
+ }
572
+ if (r === 1) if (this.day <= 0) this.day = 1;
573
+ else {
574
+ let y = this.year, u = this.month;
575
+ for (; u < 0;) u += 12, y--;
576
+ for (; u > 11;) u -= 12, y++;
577
+ let d = u !== 1 ? P[u] : new Date(Date.UTC(y, u + 1, 0)).getUTCDate();
578
+ this.day > d && (this.day = d);
579
+ }
580
+ this.apply();
581
+ let o = f[r][0], h = f[r][2], l = this.getMaxPatternValue(o, e, h);
582
+ if (o === "day") {
583
+ let y = this.getLastDayOfMonth(this.year, this.month);
584
+ this[o] = Math.min(l, y);
585
+ } else this[o] = l;
586
+ if (this.apply(), r === 0) {
587
+ let y = f[1][2], u = this.getMaxPatternValue("day", e, y), d = this.getLastDayOfMonth(this.year, this.month), c = Math.min(u, d);
588
+ c !== this.day && (this.day = c, this.hour = this.getMaxPatternValue("hour", e, f[2][2]), this.minute = this.getMaxPatternValue("minute", e, f[3][2]), this.second = this.getMaxPatternValue("second", e, f[4][2]));
589
+ }
590
+ if (r === 0 && !e.starYear) {
591
+ for (; this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0;) this.year--;
592
+ if (this.year < 0) return null;
593
+ }
594
+ return this.recurseBackward(e, t, 0, n + 1);
595
+ } else if (this.apply()) return this.recurseBackward(e, t, r - 1, n + 1);
596
+ }
597
+ return r += 1, r >= f.length ? this : this.year < 0 ? null : this.recurseBackward(e, t, r, n + 1);
598
+ }
599
+ getMaxPatternValue(e, t, r) {
600
+ if (e === "day" && t.lastDayOfMonth) return this.getLastDayOfMonth(this.year, this.month);
601
+ if (e === "day" && !t.starDOW) return this.getLastDayOfMonth(this.year, this.month);
602
+ for (let n = t[e].length - 1; n >= 0; n--) if (t[e][n]) return n - r;
603
+ return t[e].length - 1 - r;
604
+ }
605
+ findPrevious(e, t, r, n) {
606
+ return this._findMatch(e, t, r, n, -1);
607
+ }
608
+ getDate(e) {
609
+ return e || this.tz === void 0 ? new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms) : typeof this.tz == "number" ? new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute - this.tz, this.second, this.ms)) : k(b(this.year, this.month + 1, this.day, this.hour, this.minute, this.second, this.tz), !1);
610
+ }
611
+ getTime() {
612
+ return this.getDate(!1).getTime();
613
+ }
614
+ match(e, t) {
615
+ if (!e.starYear && (this.year < 0 || this.year >= e.year.length || e.year[this.year] === 0)) return !1;
616
+ for (let r = 0; r < f.length; r++) {
617
+ let n = f[r][0], i = f[r][2], a = this[n];
618
+ if (a + i < 0 || a + i >= e[n].length) return !1;
619
+ let o = e[n][a + i];
620
+ if (n === "day") {
621
+ if (!o) {
622
+ for (let h = 0; h < e.nearestWeekdays.length; h++) if (e.nearestWeekdays[h]) {
623
+ let l = this.getNearestWeekday(this.year, this.month, h - i);
624
+ if (l !== -1 && l === a) {
625
+ o = 1;
626
+ break;
627
+ }
628
+ }
629
+ }
630
+ if (e.lastWeekday) a === this.getLastWeekday(this.year, this.month) && (o = 1);
631
+ if (e.lastDayOfMonth) a === this.getLastDayOfMonth(this.year, this.month) && (o = 1);
632
+ if (!e.starDOW) {
633
+ let h = new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay(), l = e.dayOfWeek[(h + (a - 1)) % 7];
634
+ l && l & 63 && (l = this.isNthWeekdayOfMonth(this.year, this.month, a, l) ? 1 : 0), e.useAndLogic ? o = o && l : !t.domAndDow && !e.starDOM ? o = o || l : o = o && l;
635
+ }
636
+ }
637
+ if (!o) return !1;
638
+ }
639
+ return !0;
640
+ }
641
+ };
642
+ function R(s) {
643
+ if (s === void 0 && (s = {}), delete s.name, s.legacyMode !== void 0 && s.domAndDow === void 0 ? s.domAndDow = !s.legacyMode : s.domAndDow === void 0 && (s.domAndDow = !1), s.legacyMode = !s.domAndDow, s.paused = s.paused === void 0 ? !1 : s.paused, s.maxRuns = s.maxRuns === void 0 ? Infinity : s.maxRuns, s.catch = s.catch === void 0 ? !1 : s.catch, s.interval = s.interval === void 0 ? 0 : parseInt(s.interval.toString(), 10), s.utcOffset = s.utcOffset === void 0 ? void 0 : parseInt(s.utcOffset.toString(), 10), s.dayOffset = s.dayOffset === void 0 ? 0 : parseInt(s.dayOffset.toString(), 10), s.unref = s.unref === void 0 ? !1 : s.unref, s.mode = s.mode === void 0 ? "auto" : s.mode, s.alternativeWeekdays = s.alternativeWeekdays === void 0 ? !1 : s.alternativeWeekdays, s.sloppyRanges = s.sloppyRanges === void 0 ? !1 : s.sloppyRanges, ![
644
+ "auto",
645
+ "5-part",
646
+ "6-part",
647
+ "7-part",
648
+ "5-or-6-parts",
649
+ "6-or-7-parts"
650
+ ].includes(s.mode)) throw new Error("CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.");
651
+ if (s.startAt && (s.startAt = new m(s.startAt, s.timezone)), s.stopAt && (s.stopAt = new m(s.stopAt, s.timezone)), s.interval !== null) {
652
+ if (isNaN(s.interval)) throw new Error("CronOptions: Supplied value for interval is not a number");
653
+ if (s.interval < 0) throw new Error("CronOptions: Supplied value for interval can not be negative");
654
+ }
655
+ if (s.utcOffset !== void 0) {
656
+ if (isNaN(s.utcOffset)) throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");
657
+ if (s.utcOffset < -870 || s.utcOffset > 870) throw new Error("CronOptions: utcOffset out of bounds.");
658
+ if (s.utcOffset !== void 0 && s.timezone) throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.");
659
+ }
660
+ if (s.unref !== !0 && s.unref !== !1) throw new Error("CronOptions: Unref should be either true, false or undefined(false).");
661
+ if (s.dayOffset !== void 0 && s.dayOffset !== 0 && isNaN(s.dayOffset)) throw new Error("CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.");
662
+ return s;
663
+ }
664
+ function p(s) {
665
+ return Object.prototype.toString.call(s) === "[object Function]" || typeof s == "function" || s instanceof Function;
666
+ }
667
+ function _(s) {
668
+ return p(s);
669
+ }
670
+ function x(s) {
671
+ typeof Deno < "u" && typeof Deno.unrefTimer < "u" ? Deno.unrefTimer(s) : s && typeof s.unref < "u" && s.unref();
672
+ }
673
+ var W = 30 * 1e3, w = [], E = class {
674
+ name;
675
+ options;
676
+ _states;
677
+ fn;
678
+ getTz() {
679
+ return this.options.timezone || this.options.utcOffset;
680
+ }
681
+ applyDayOffset(e) {
682
+ if (this.options.dayOffset !== void 0 && this.options.dayOffset !== 0) {
683
+ let t = this.options.dayOffset * 24 * 60 * 60 * 1e3;
684
+ return new Date(e.getTime() + t);
685
+ }
686
+ return e;
687
+ }
688
+ constructor(e, t, r) {
689
+ let n, i;
690
+ if (p(t)) i = t;
691
+ else if (typeof t == "object") n = t;
692
+ else if (t !== void 0) throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");
693
+ if (p(r)) i = r;
694
+ else if (typeof r == "object") n = r;
695
+ else if (r !== void 0) throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");
696
+ if (this.name = n?.name, this.options = R(n), this._states = {
697
+ kill: !1,
698
+ blocking: !1,
699
+ previousRun: void 0,
700
+ currentRun: void 0,
701
+ once: void 0,
702
+ currentTimeout: void 0,
703
+ maxRuns: n ? n.maxRuns : void 0,
704
+ paused: n ? n.paused : !1,
705
+ pattern: new C("* * * * *", void 0, { mode: "auto" })
706
+ }, e && (e instanceof Date || typeof e == "string" && e.indexOf(":") > 0) ? this._states.once = new m(e, this.getTz()) : this._states.pattern = new C(e, this.options.timezone, {
707
+ mode: this.options.mode,
708
+ alternativeWeekdays: this.options.alternativeWeekdays,
709
+ sloppyRanges: this.options.sloppyRanges
710
+ }), this.name) {
711
+ if (w.find((o) => o.name === this.name)) throw new Error("Cron: Tried to initialize new named job '" + this.name + "', but name already taken.");
712
+ w.push(this);
713
+ }
714
+ return i !== void 0 && _(i) && (this.fn = i, this.schedule()), this;
715
+ }
716
+ nextRun(e) {
717
+ let t = this._next(e);
718
+ return t ? this.applyDayOffset(t.getDate(!1)) : null;
719
+ }
720
+ nextRuns(e, t) {
721
+ this._states.maxRuns !== void 0 && e > this._states.maxRuns && (e = this._states.maxRuns);
722
+ let r = t || this._states.currentRun || void 0;
723
+ return this._enumerateRuns(e, r, "next");
724
+ }
725
+ previousRuns(e, t) {
726
+ return this._enumerateRuns(e, t || void 0, "previous");
727
+ }
728
+ _enumerateRuns(e, t, r) {
729
+ let n = [], i = t ? new m(t, this.getTz()) : null, a = r === "next" ? this._next : this._previous;
730
+ for (; e--;) {
731
+ let o = a.call(this, i);
732
+ if (!o) break;
733
+ let h = o.getDate(!1);
734
+ n.push(this.applyDayOffset(h)), i = o;
735
+ }
736
+ return n;
737
+ }
738
+ match(e) {
739
+ if (this._states.once) {
740
+ let r = new m(e, this.getTz());
741
+ r.ms = 0;
742
+ let n = new m(this._states.once, this.getTz());
743
+ return n.ms = 0, r.getTime() === n.getTime();
744
+ }
745
+ let t = new m(e, this.getTz());
746
+ return t.ms = 0, t.match(this._states.pattern, this.options);
747
+ }
748
+ getPattern() {
749
+ if (!this._states.once) return this._states.pattern ? this._states.pattern.pattern : void 0;
750
+ }
751
+ getOnce() {
752
+ return this._states.once ? this._states.once.getDate() : null;
753
+ }
754
+ isRunning() {
755
+ let e = this.nextRun(this._states.currentRun), t = !this._states.paused, r = this.fn !== void 0, n = !this._states.kill;
756
+ return t && r && n && e !== null;
757
+ }
758
+ isStopped() {
759
+ return this._states.kill;
760
+ }
761
+ isBusy() {
762
+ return this._states.blocking;
763
+ }
764
+ currentRun() {
765
+ return this._states.currentRun ? this._states.currentRun.getDate() : null;
766
+ }
767
+ previousRun() {
768
+ return this._states.previousRun ? this._states.previousRun.getDate() : null;
769
+ }
770
+ msToNext(e) {
771
+ let t = this._next(e);
772
+ return t ? e instanceof m || e instanceof Date ? t.getTime() - e.getTime() : t.getTime() - new m(e).getTime() : null;
773
+ }
774
+ stop() {
775
+ this._states.kill = !0, this._states.currentTimeout && clearTimeout(this._states.currentTimeout);
776
+ let e = w.indexOf(this);
777
+ e >= 0 && w.splice(e, 1);
778
+ }
779
+ pause() {
780
+ return this._states.paused = !0, !this._states.kill;
781
+ }
782
+ resume() {
783
+ return this._states.paused = !1, !this._states.kill;
784
+ }
785
+ schedule(e) {
786
+ if (e && this.fn) throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");
787
+ e && (this.fn = e);
788
+ let t = this.msToNext(), r = this.nextRun(this._states.currentRun);
789
+ return t == null || isNaN(t) || r === null ? this : (t > W && (t = W), this._states.currentTimeout = setTimeout(() => this._checkTrigger(r), t), this._states.currentTimeout && this.options.unref && x(this._states.currentTimeout), this);
790
+ }
791
+ async _trigger(e) {
792
+ this._states.blocking = !0, this._states.currentRun = new m(void 0, this.getTz());
793
+ try {
794
+ if (this.options.catch) try {
795
+ this.fn !== void 0 && await this.fn(this, this.options.context);
796
+ } catch (t) {
797
+ if (p(this.options.catch)) try {
798
+ this.options.catch(t, this);
799
+ } catch {}
800
+ }
801
+ else this.fn !== void 0 && await this.fn(this, this.options.context);
802
+ } finally {
803
+ this._states.previousRun = new m(e, this.getTz()), this._states.blocking = !1;
804
+ }
805
+ }
806
+ async trigger() {
807
+ await this._trigger();
808
+ }
809
+ runsLeft() {
810
+ return this._states.maxRuns;
811
+ }
812
+ _checkTrigger(e) {
813
+ let t = /* @__PURE__ */ new Date(), r = !this._states.paused && t.getTime() >= e.getTime(), n = this._states.blocking && this.options.protect;
814
+ r && !n ? (this._states.maxRuns !== void 0 && this._states.maxRuns--, this._trigger()) : r && n && p(this.options.protect) && setTimeout(() => this.options.protect(this), 0), this.schedule();
815
+ }
816
+ _next(e) {
817
+ let t = !!(e || this._states.currentRun), r = !1;
818
+ !e && this.options.startAt && this.options.interval && ([e, t] = this._calculatePreviousRun(e, t), r = !e), e = new m(e, this.getTz()), this.options.startAt && e && e.getTime() < this.options.startAt.getTime() && (e = this.options.startAt);
819
+ let n = this._states.once || new m(e, this.getTz());
820
+ return !r && n !== this._states.once && (n = n.increment(this._states.pattern, this.options, t)), this._states.once && this._states.once.getTime() <= e.getTime() || n === null || this._states.maxRuns !== void 0 && this._states.maxRuns <= 0 || this._states.kill || this.options.stopAt && n.getTime() >= this.options.stopAt.getTime() ? null : n;
821
+ }
822
+ _previous(e) {
823
+ let t = new m(e, this.getTz());
824
+ this.options.stopAt && t.getTime() > this.options.stopAt.getTime() && (t = this.options.stopAt);
825
+ let r = new m(t, this.getTz());
826
+ return this._states.once ? this._states.once.getTime() < t.getTime() ? this._states.once : null : (r = r.decrement(this._states.pattern, this.options), r === null || this.options.startAt && r.getTime() < this.options.startAt.getTime() ? null : r);
827
+ }
828
+ _calculatePreviousRun(e, t) {
829
+ let r = new m(void 0, this.getTz()), n = e;
830
+ if (this.options.startAt.getTime() <= r.getTime()) {
831
+ n = this.options.startAt;
832
+ let i = n.getTime() + this.options.interval * 1e3;
833
+ for (; i <= r.getTime();) n = new m(n, this.getTz()).increment(this._states.pattern, this.options, !0), i = n.getTime() + this.options.interval * 1e3;
834
+ t = !0;
835
+ }
836
+ return n === null && (n = void 0), [n, t];
837
+ }
838
+ };
839
+ //#endregion
840
+ //#region src/builtins/backup-orchestrator/cron-helpers.ts
841
+ /**
842
+ * Cron helpers — wraps `croner` so the orchestrator + the `previewNextRuns`
843
+ * cap method share one validation + next-run-computation surface.
844
+ *
845
+ * `croner` is the opinionated node cron library we standardize on
846
+ * server-side: pure JS, native TypeScript types, supports the full
847
+ * 5-field POSIX cron grammar plus seconds (6-field), DST-aware, and
848
+ * exposes `nextRun()` / `nextRuns(N)` for peeking without scheduling.
849
+ * The orchestrator uses the peeking API (it has its own polling
850
+ * loop); future surfaces (e.g. event-driven retention sweeps) can
851
+ * register an actual scheduled `Cron(pattern, fn)` and let croner
852
+ * own the timer.
853
+ */
854
+ /**
855
+ * Validate a cron expression and return its next firing time strictly
856
+ * after `after`, expressed as ms-epoch. Returns `null` when the
857
+ * expression has no future runs (croner returns null e.g. for
858
+ * fully-bounded patterns that have already elapsed). Throws when the
859
+ * expression is syntactically invalid — callers are expected to
860
+ * surface that to the operator.
861
+ */
862
+ function computeNextDue(cron, after) {
863
+ const next = new E(cron, { paused: true }).nextRun(new Date(after));
864
+ return next ? next.getTime() : null;
865
+ }
866
+ /**
867
+ * Validate without computing — returns true when `cron` parses, false
868
+ * otherwise. Used by the cap-router input zod schema's `.refine`
869
+ * callback to reject malformed expressions at the boundary instead
870
+ * of at scheduler-tick time.
871
+ */
872
+ function isValidCron(cron) {
873
+ try {
874
+ new E(cron, { paused: true });
875
+ return true;
876
+ } catch {
877
+ return false;
878
+ }
879
+ }
880
+ /**
881
+ * Peek the next N firing times after `after` (default: now). Used by
882
+ * the admin UI's CronEditor preview pane — operators see the next
883
+ * 3–5 runs as they edit the expression so a wrong pattern is
884
+ * obvious before save.
885
+ */
886
+ function previewNextRuns(cron, count, after) {
887
+ const job = new E(cron, { paused: true });
888
+ const baseline = after !== void 0 ? new Date(after) : /* @__PURE__ */ new Date();
889
+ const out = [];
890
+ let cursor = baseline;
891
+ for (let i = 0; i < count; i++) {
892
+ cursor = job.nextRun(cursor);
893
+ if (!cursor) break;
894
+ out.push(cursor.getTime());
895
+ }
896
+ return out;
897
+ }
898
+ //#endregion
899
+ //#region src/builtins/backup-orchestrator/destination-policy.ts
900
+ var import_read_all_rows = require_read_all_rows();
901
+ var BackupDestinationPolicyService = class {
902
+ policiesKind;
903
+ constructor(policiesKind) {
904
+ this.policiesKind = policiesKind;
905
+ }
906
+ async list() {
907
+ const rows = await (0, import_read_all_rows.readAllRows)(this.policiesKind);
908
+ rows.sort((a, b) => a.id.localeCompare(b.id));
909
+ const out = [];
910
+ for (const row of rows) {
911
+ const mapped = bodyToPolicy(row.id, row.data);
912
+ if (mapped) out.push(mapped);
913
+ }
914
+ return out;
915
+ }
916
+ async get(locationId) {
917
+ const row = await this.policiesKind.get(locationId);
918
+ return row === null ? null : bodyToPolicy(locationId, row.data);
919
+ }
920
+ /** Replace-or-insert: one full `put` of the row. */
921
+ async upsert(p) {
922
+ const data = backupOrchestratorRecordKinds["destination-policies"].schema.parse(policyToBody(p));
923
+ await this.policiesKind.put({
924
+ id: p.locationId,
925
+ data
926
+ });
927
+ }
928
+ async delete(locationId) {
929
+ await this.policiesKind.delete(locationId);
930
+ }
931
+ /**
932
+ * Auto-create a default policy for a `backups` location seen for the
933
+ * first time (returns the existing policy unchanged when present).
934
+ * The orchestrator calls this lazily on the first `listDestinations`
935
+ * pass so newly-added storage locations are surfaced as enabled
936
+ * destinations without an explicit configuration step.
937
+ *
938
+ * Defaults are passed by the orchestrator (currently `retentionCount=7`).
939
+ * A fresh destination is enabled and keeps 7 archives; it gets NO cadence
940
+ * of its own — a destination runs when a schedule fans out to it, and
941
+ * seeding a cron here would advertise a nightly run nothing performs
942
+ * (D384).
943
+ */
944
+ async ensureDefault(locationId, defaults) {
945
+ const existing = await this.get(locationId);
946
+ if (existing) return existing;
947
+ const fresh = {
948
+ locationId,
949
+ enabled: true,
950
+ retentionCount: defaults.retentionCount
951
+ };
952
+ await this.upsert(fresh);
953
+ return fresh;
954
+ }
955
+ /**
956
+ * Stamp the outcome of ONE attempted write to this destination.
957
+ *
958
+ * Read-modify-write on the policy row so the operator's `enabled`,
959
+ * `retentionCount` and `label` survive. A destination with no row yet
960
+ * gets one — an attempt on an unseen location must still be recorded, or
961
+ * the failure disappears with the process (which is exactly how a 03:00
962
+ * SMB refusal stayed invisible until the operator went looking).
963
+ */
964
+ async recordAttempt(locationId, outcome, defaults) {
965
+ const { lastError: _cleared, ...carried } = await this.get(locationId) ?? {
966
+ locationId,
967
+ enabled: true,
968
+ retentionCount: defaults.retentionCount
969
+ };
970
+ await this.upsert({
971
+ ...carried,
972
+ lastAttemptAt: outcome.attemptAt,
973
+ ...outcome.error !== void 0 ? { lastError: outcome.error } : {}
974
+ });
975
+ }
976
+ };
977
+ function policyToBody(p) {
978
+ return {
979
+ enabled: p.enabled,
980
+ retentionCount: p.retentionCount,
981
+ ...p.label !== void 0 ? { label: p.label } : {},
982
+ ...p.lastAttemptAt !== void 0 ? { lastAttemptAt: p.lastAttemptAt } : {},
983
+ ...p.lastError !== void 0 ? { lastError: p.lastError } : {}
984
+ };
985
+ }
986
+ function bodyToPolicy(locationId, body) {
987
+ if (!locationId) return null;
988
+ return {
989
+ locationId,
990
+ enabled: body.enabled,
991
+ retentionCount: body.retentionCount,
992
+ ...body.label !== void 0 ? { label: body.label } : {},
993
+ ...body.lastAttemptAt !== void 0 ? { lastAttemptAt: body.lastAttemptAt } : {},
994
+ ...body.lastError !== void 0 ? { lastError: body.lastError } : {}
995
+ };
996
+ }
997
+ //#endregion
998
+ //#region src/builtins/backup-orchestrator/download-helpers.ts
999
+ /**
1000
+ * Chunked-download helper for the backup orchestrator (Task 12 of
1001
+ * the storage-unification refactor).
1002
+ *
1003
+ * Streams an archive from a destination `StorageLocation` into a
1004
+ * local filesystem path via the consumer-facing `storage` cap. Pulled
1005
+ * out of `backup-orchestrator.addon.ts` so it can be unit-tested with
1006
+ * an in-memory fake `AddonApi['storage']` slice — the addon is hard
1007
+ * to bootstrap in vitest because of the BaseAddon ceremony.
1008
+ *
1009
+ * Cleanup contract:
1010
+ * - Successful run leaves the cache file in place + calls
1011
+ * `endDownload`.
1012
+ * - Mid-stream failure destroys the writeStream, removes the
1013
+ * partial cache file, and best-effort calls `endDownload` so the
1014
+ * storage provider's session bookkeeping doesn't leak.
1015
+ */
1016
+ async function downloadArchiveToCache(input) {
1017
+ const { downloadId, sizeBytes } = await input.api.beginDownload.mutate({
1018
+ location: input.locationId,
1019
+ relativePath: input.filename
1020
+ });
1021
+ const writeStream = fs$1.createWriteStream(input.cachePath);
1022
+ let offset = 0;
1023
+ try {
1024
+ while (offset < sizeBytes) {
1025
+ const remaining = sizeBytes - offset;
1026
+ const length = Math.min(input.chunkBytes, remaining);
1027
+ const chunk = await input.api.readChunk.query({
1028
+ downloadId,
1029
+ offset,
1030
+ length
1031
+ });
1032
+ if (chunk.byteLength === 0) throw new Error(`backup restore: empty chunk at offset ${offset}/${sizeBytes} from "${input.locationId}/${input.filename}"`);
1033
+ writeStream.write(chunk);
1034
+ offset += chunk.byteLength;
1035
+ }
1036
+ await new Promise((resolve, reject) => {
1037
+ writeStream.end((err) => {
1038
+ if (err) reject(err);
1039
+ else resolve();
1040
+ });
1041
+ });
1042
+ try {
1043
+ await input.api.endDownload.mutate({ downloadId });
1044
+ } catch (err) {
1045
+ input.logger.warn("backup restore: endDownload failed (ignoring)", { meta: {
1046
+ downloadId,
1047
+ error: err instanceof Error ? err.message : String(err)
1048
+ } });
1049
+ }
1050
+ } catch (err) {
1051
+ await new Promise((resolve) => {
1052
+ writeStream.once("close", () => resolve());
1053
+ writeStream.destroy();
1054
+ });
1055
+ try {
1056
+ await fsp.rm(input.cachePath, { force: true });
1057
+ } catch {}
1058
+ try {
1059
+ await input.api.endDownload.mutate({ downloadId });
1060
+ } catch {}
1061
+ throw err;
1062
+ }
1063
+ }
1064
+ //#endregion
1065
+ //#region src/builtins/backup-orchestrator/encryption-key-store.ts
1066
+ /**
1067
+ * @durable class=config owner=backup-orchestrator
1068
+ * write="`setupEncryption` inserts one row per generated key and retires the
1069
+ * previous active row; `disableEncryption` retires the active row"
1070
+ * retention="none — one small row per key ever generated; a retired row
1071
+ * names the key older archives need"
1072
+ */
1073
+ var BACKUP_ENCRYPTION_KEYS_COLLECTION = "backup_encryption_keys";
1074
+ var COLUMNS = [
1075
+ {
1076
+ name: "key_id",
1077
+ type: "TEXT",
1078
+ primaryKey: true
1079
+ },
1080
+ {
1081
+ name: "public_key",
1082
+ type: "TEXT",
1083
+ notNull: true
1084
+ },
1085
+ {
1086
+ name: "created_at",
1087
+ type: "INTEGER",
1088
+ notNull: true
1089
+ },
1090
+ {
1091
+ name: "retired_at",
1092
+ type: "INTEGER"
1093
+ }
1094
+ ];
1095
+ var BackupEncryptionKeyStore = class {
1096
+ store;
1097
+ now;
1098
+ declared = false;
1099
+ keysKind;
1100
+ constructor(store, now = Date.now, keysKind = null) {
1101
+ this.store = store;
1102
+ this.now = now;
1103
+ this.keysKind = keysKind;
1104
+ }
1105
+ async ensureDeclared() {
1106
+ if (this.keysKind !== null) return;
1107
+ if (this.declared) return;
1108
+ await this.store.declareCollection({
1109
+ collection: BACKUP_ENCRYPTION_KEYS_COLLECTION,
1110
+ columns: COLUMNS
1111
+ });
1112
+ this.declared = true;
1113
+ }
1114
+ /** Every key, newest first. */
1115
+ async list() {
1116
+ await this.ensureDeclared();
1117
+ const kind = this.keysKind;
1118
+ if (kind !== null) {
1119
+ const rows = await (0, import_read_all_rows.readAllRows)(kind);
1120
+ rows.sort((a, b) => b.data.createdAt - a.data.createdAt);
1121
+ const out = [];
1122
+ for (const row of rows) {
1123
+ const record = bodyToRecord(row.id, row.data);
1124
+ if (record !== null) out.push(record);
1125
+ }
1126
+ return out;
1127
+ }
1128
+ const rows = await this.store.query({
1129
+ collection: BACKUP_ENCRYPTION_KEYS_COLLECTION,
1130
+ filter: { orderBy: {
1131
+ field: "created_at",
1132
+ direction: "desc"
1133
+ } }
1134
+ });
1135
+ const out = [];
1136
+ for (const row of rows) {
1137
+ const record = toRecord(row.data);
1138
+ if (record !== null) out.push(record);
1139
+ }
1140
+ return out;
1141
+ }
1142
+ /** The key new archives are encrypted to; `null` = encryption off. */
1143
+ async active() {
1144
+ return (await this.list()).find((k) => k.retiredAt === null) ?? null;
1145
+ }
1146
+ /** Make `publicKey` the active key; the previous one is retired, kept listed. */
1147
+ async activate(input) {
1148
+ const parsed = parseBackupPublicKey(input.publicKey);
1149
+ const t = this.now();
1150
+ await this.retireActive(t);
1151
+ const record = {
1152
+ keyId: parsed.keyId,
1153
+ publicKey: input.publicKey.trim(),
1154
+ createdAt: t,
1155
+ retiredAt: null
1156
+ };
1157
+ await this.write(record);
1158
+ return record;
1159
+ }
1160
+ /** Encryption off: the active key is retired. Archives already made keep needing it. */
1161
+ async disable() {
1162
+ await this.retireActive(this.now());
1163
+ }
1164
+ async retireActive(at) {
1165
+ for (const key of await this.list()) if (key.retiredAt === null) await this.write({
1166
+ ...key,
1167
+ retiredAt: at
1168
+ });
1169
+ }
1170
+ async write(record) {
1171
+ await this.ensureDeclared();
1172
+ const kind = this.keysKind;
1173
+ if (kind !== null) {
1174
+ const body = {
1175
+ keyId: record.keyId,
1176
+ publicKey: record.publicKey,
1177
+ createdAt: record.createdAt,
1178
+ retiredAt: record.retiredAt
1179
+ };
1180
+ const data = backupOrchestratorRecordKinds["encryption-keys"].schema.parse(body);
1181
+ await kind.put({
1182
+ id: record.keyId,
1183
+ data
1184
+ });
1185
+ return;
1186
+ }
1187
+ await this.store.deleteWhere({
1188
+ collection: BACKUP_ENCRYPTION_KEYS_COLLECTION,
1189
+ filter: { where: { key_id: record.keyId } }
1190
+ });
1191
+ await this.store.insert({
1192
+ collection: BACKUP_ENCRYPTION_KEYS_COLLECTION,
1193
+ record: {
1194
+ id: record.keyId,
1195
+ data: {
1196
+ key_id: record.keyId,
1197
+ public_key: record.publicKey,
1198
+ created_at: record.createdAt,
1199
+ retired_at: record.retiredAt
1200
+ }
1201
+ }
1202
+ });
1203
+ }
1204
+ };
1205
+ function bodyToRecord(keyId, body) {
1206
+ if (!keyId) return null;
1207
+ return {
1208
+ keyId: body.keyId,
1209
+ publicKey: body.publicKey,
1210
+ createdAt: body.createdAt,
1211
+ retiredAt: body.retiredAt
1212
+ };
1213
+ }
1214
+ function toRecord(row) {
1215
+ const keyId = row["key_id"];
1216
+ const publicKey = row["public_key"];
1217
+ const createdAt = row["created_at"];
1218
+ if (typeof keyId !== "string" || typeof publicKey !== "string") return null;
1219
+ const retired = row["retired_at"];
1220
+ return {
1221
+ keyId,
1222
+ publicKey,
1223
+ createdAt: typeof createdAt === "number" ? createdAt : Number(createdAt ?? 0),
1224
+ retiredAt: typeof retired === "number" ? retired : null
1225
+ };
1226
+ }
1227
+ //#endregion
1228
+ //#region src/builtins/backup-orchestrator/manifest-store.ts
1229
+ /** File path (relative to the location root) where the index lives. */
1230
+ var MANIFESTS_FILENAME = "manifests.json";
1231
+ /**
1232
+ * Read the per-location manifest. Returns an empty manifest on first
1233
+ * use (when `manifests.json` doesn't exist) or when the file is
1234
+ * unreadable / corrupt — operators see destination state degrade
1235
+ * gracefully rather than the orchestrator crashing.
1236
+ */
1237
+ async function readLocationManifest(api, locationId) {
1238
+ if (!await api.exists.query({
1239
+ location: locationId,
1240
+ relativePath: "manifests.json"
1241
+ }).catch(() => false)) return EMPTY_MANIFEST;
1242
+ let bytes;
1243
+ try {
1244
+ bytes = await api.read.query({
1245
+ location: locationId,
1246
+ relativePath: MANIFESTS_FILENAME
1247
+ });
1248
+ } catch {
1249
+ return EMPTY_MANIFEST;
1250
+ }
1251
+ return parseManifestBytes(bytes);
1252
+ }
1253
+ async function writeLocationManifest(api, locationId, manifest) {
1254
+ const json = JSON.stringify(manifest, null, 2);
1255
+ const bytes = new TextEncoder().encode(json);
1256
+ await api.write.mutate({
1257
+ location: locationId,
1258
+ relativePath: MANIFESTS_FILENAME,
1259
+ data: bytes
1260
+ });
1261
+ }
1262
+ /**
1263
+ * Decode the raw bytes of `manifests.json`. Falls back to an empty
1264
+ * manifest on JSON-parse / shape-validation failure — same defensive
1265
+ * stance as the legacy `LocalBackupService.ensureManifestsLoaded`.
1266
+ */
1267
+ function parseManifestBytes(bytes) {
1268
+ try {
1269
+ const text = new TextDecoder().decode(bytes);
1270
+ if (text.trim().length === 0) return EMPTY_MANIFEST;
1271
+ return normalizeManifest(JSON.parse(text));
1272
+ } catch {
1273
+ return EMPTY_MANIFEST;
1274
+ }
1275
+ }
1276
+ /**
1277
+ * Coerce an arbitrary parsed JSON shape into the canonical manifest
1278
+ * type. Bogus archive entries are silently dropped (a corrupt row
1279
+ * shouldn't lock the whole location out of operator visibility).
1280
+ */
1281
+ function normalizeManifest(raw) {
1282
+ if (typeof raw !== "object" || raw == null) return EMPTY_MANIFEST;
1283
+ const obj = raw;
1284
+ const archives = [];
1285
+ if (Array.isArray(obj.archives)) for (const a of obj.archives) {
1286
+ if (typeof a !== "object" || a == null) continue;
1287
+ const cand = a;
1288
+ if (typeof cand["id"] !== "string" || typeof cand["filename"] !== "string") continue;
1289
+ if (typeof cand["createdAt"] !== "number" || typeof cand["sizeBytes"] !== "number") continue;
1290
+ const manifest = cand["manifest"];
1291
+ if (typeof manifest !== "object" || manifest == null) continue;
1292
+ const entry = {
1293
+ id: String(cand["id"]),
1294
+ filename: String(cand["filename"]),
1295
+ createdAt: Number(cand["createdAt"]),
1296
+ sizeBytes: Number(cand["sizeBytes"]),
1297
+ ...typeof cand["label"] === "string" ? { label: cand["label"] } : {},
1298
+ manifest,
1299
+ ...encryptionOf(cand["encryption"]),
1300
+ ...databasesOf(cand["databases"])
1301
+ };
1302
+ archives.push(entry);
1303
+ }
1304
+ return {
1305
+ version: 1,
1306
+ archives
1307
+ };
1308
+ }
1309
+ var EMPTY_MANIFEST = {
1310
+ version: 1,
1311
+ archives: []
1312
+ };
1313
+ function databasesOf(raw) {
1314
+ if (!Array.isArray(raw)) return {};
1315
+ const known = [];
1316
+ const unknown = [];
1317
+ for (const item of raw) if (item === "settings" || item === "events" || item === "history") known.push(item);
1318
+ else if (typeof item === "string") unknown.push(item);
1319
+ if (known.length > 0) return { databases: known };
1320
+ return unknown.length > 0 ? { unrecognisedDatabases: unknown } : {};
1321
+ }
1322
+ function encryptionOf(raw) {
1323
+ if (typeof raw !== "object" || raw === null) return {};
1324
+ const scheme = Reflect.get(raw, "scheme");
1325
+ const keyId = Reflect.get(raw, "keyId");
1326
+ if (typeof scheme !== "string" || typeof keyId !== "string") return {};
1327
+ return { encryption: {
1328
+ scheme,
1329
+ keyId
1330
+ } };
1331
+ }
1332
+ /**
1333
+ * What the destination's clear-text index may say about an encrypted archive:
1334
+ * the outline a restore needs (locations, sizes, the snapshot promise) — not
1335
+ * the list of files, which stays inside the ciphertext.
1336
+ */
1337
+ function outlineOfManifest(manifest) {
1338
+ return {
1339
+ archiveVersion: manifest.archiveVersion,
1340
+ createdAt: manifest.createdAt,
1341
+ dataDir: manifest.dataDir,
1342
+ locations: [...manifest.locations],
1343
+ entries: [],
1344
+ totalBytes: manifest.totalBytes,
1345
+ totalFiles: manifest.totalFiles,
1346
+ ...manifest.omittedDatabases !== void 0 ? { omittedDatabases: [...manifest.omittedDatabases] } : {}
1347
+ };
1348
+ }
1349
+ /**
1350
+ * Build a `ManifestArchiveEntry` from the raw inputs collected during
1351
+ * a successful upload. Pure transform — no I/O — kept here so the
1352
+ * triggerBackup path stays terse.
1353
+ */
1354
+ function buildArchiveEntry(input) {
1355
+ return {
1356
+ id: input.id,
1357
+ filename: input.filename,
1358
+ createdAt: input.createdAt,
1359
+ sizeBytes: input.sizeBytes,
1360
+ ...input.label !== void 0 ? { label: input.label } : {},
1361
+ manifest: input.encryption !== void 0 ? outlineOfManifest(input.manifest) : input.manifest,
1362
+ ...input.encryption !== void 0 ? { encryption: input.encryption } : {},
1363
+ ...input.databases !== void 0 ? { databases: [...input.databases] } : {}
1364
+ };
1365
+ }
1366
+ /** The key under which archives of one cadence prune each other. */
1367
+ function retentionClassOf(entry) {
1368
+ if (entry.databases === void 0 && entry.unrecognisedDatabases !== void 0) return `?${[...entry.unrecognisedDatabases].toSorted().join("+")}`;
1369
+ return [...entry.databases ?? DEFAULT_BACKUP_DATABASES].toSorted().join("+");
1370
+ }
1371
+ /**
1372
+ * Pure retention split: given an archive list and the operator's
1373
+ * `retentionCount`, return `{ keep, drop }` where `keep` is the most-
1374
+ * recent N archives (newest first) and `drop` is the older overflow.
1375
+ *
1376
+ * `retentionCount <= 0` is treated as "no pruning" — defensive against
1377
+ * a config value that would otherwise wipe every archive on the next
1378
+ * write.
1379
+ *
1380
+ * `cadence` (see {@link retentionClassOf}) restricts the count to archives of
1381
+ * the run that was just written: nightly archives (settings) and weekly ones
1382
+ * (settings + events + history) are retained separately.
1383
+ */
1384
+ function applyRetention(archives, retentionCount, cadence) {
1385
+ if (retentionCount <= 0) return {
1386
+ keep: archives,
1387
+ drop: []
1388
+ };
1389
+ const sorted = [...archives].toSorted((a, b) => b.createdAt - a.createdAt);
1390
+ const inCadence = cadence === void 0 ? sorted : sorted.filter((a) => retentionClassOf(a) === cadence);
1391
+ if (inCadence.length <= retentionCount) return {
1392
+ keep: sorted,
1393
+ drop: []
1394
+ };
1395
+ const drop = inCadence.slice(retentionCount);
1396
+ const dropped = new Set(drop);
1397
+ return {
1398
+ keep: sorted.filter((a) => !dropped.has(a)),
1399
+ drop
1400
+ };
1401
+ }
1402
+ /**
1403
+ * Per-location async mutex. The orchestrator owns one instance and
1404
+ * funnels every read-modify-write of `manifests.json` through it so
1405
+ * parallel destination uploads (within the same location) commit in
1406
+ * arrival order. Across locations the operations run in parallel —
1407
+ * each location keys its own promise chain.
1408
+ */
1409
+ var LocationManifestLock = class {
1410
+ chains = /* @__PURE__ */ new Map();
1411
+ async run(locationId, fn) {
1412
+ const previous = this.chains.get(locationId) ?? Promise.resolve();
1413
+ let resolveNext;
1414
+ const next = new Promise((res) => {
1415
+ resolveNext = res;
1416
+ });
1417
+ this.chains.set(locationId, previous.then(() => next));
1418
+ try {
1419
+ await previous;
1420
+ return await fn();
1421
+ } finally {
1422
+ resolveNext();
1423
+ const tail = this.chains.get(locationId);
1424
+ if (tail) Promise.resolve(tail).then(() => {
1425
+ if (this.chains.get(locationId) === tail) this.chains.delete(locationId);
1426
+ }).catch(() => {});
1427
+ }
1428
+ }
1429
+ };
1430
+ //#endregion
1431
+ //#region src/builtins/backup-orchestrator/run-queue.ts
1432
+ /**
1433
+ * Backup run queue + per-run tracking (D342).
1434
+ *
1435
+ * Why a GLOBAL queue (concurrency 1), not per-destination: every run
1436
+ * walks the same `<nodeDataDir>` source tree and stages its tar.gz on
1437
+ * the same disk. On 2026-09-04 two schedule ticks built two multi-GB
1438
+ * archives concurrently — staging went 5.1 GB → 18 GB in ~12 minutes
1439
+ * with host load 62, and each run archived the other's growing tar
1440
+ * (pre-D338 staging placement). A per-destination lock would still
1441
+ * allow two concurrent walks of the same tree and two staged archives;
1442
+ * the destination write is the CHEAP half. One run at a time bounds
1443
+ * peak staging disk to a single archive and the walk cost to one
1444
+ * traversal.
1445
+ *
1446
+ * This subsumes the earlier single-flight `buildLock`
1447
+ * (`LocationManifestLock.run('archive-build', …)`): that lock
1448
+ * serialised builds but was invisible (nothing reported a waiting
1449
+ * run), unjoinable and uncancellable. The queue is the one
1450
+ * serialisation authority for archive builds — do not reintroduce a
1451
+ * second lock around the executor.
1452
+ *
1453
+ * Every run is OBSERVABLE while it exists: id, state, phase, byte
1454
+ * counters, per-destination outcome. The registry keeps queued +
1455
+ * active + a bounded tail of finished runs so `backup.listRuns` can
1456
+ * answer "what is running, how far along, how big" without `du`.
1457
+ */
1458
+ /** Finished runs kept for `listRuns` history. Older ones are dropped. */
1459
+ var DEFAULT_MAX_FINISHED = 20;
1460
+ /**
1461
+ * FIFO queue with concurrency 1. `submit` never starts a second
1462
+ * executor while one is in flight; an identical request already
1463
+ * WAITING (same destinations/locations/label/retention) is joined
1464
+ * instead of queued twice — two schedule ticks due on the same minute
1465
+ * produce one run, not two.
1466
+ */
1467
+ var BackupRunQueue = class {
1468
+ executor;
1469
+ runs = /* @__PURE__ */ new Map();
1470
+ pending = [];
1471
+ finished = [];
1472
+ activeId = null;
1473
+ maxFinished;
1474
+ now;
1475
+ constructor(executor, opts) {
1476
+ this.executor = executor;
1477
+ this.maxFinished = opts?.maxFinished ?? DEFAULT_MAX_FINISHED;
1478
+ this.now = opts?.now ?? Date.now;
1479
+ }
1480
+ submit(request) {
1481
+ const signature = requestSignature(request);
1482
+ const busy = this.activeId !== null || this.pending.length > 0;
1483
+ for (const id of this.pending) {
1484
+ const existing = this.runs.get(id);
1485
+ if (existing && existing.signature === signature) return {
1486
+ runId: id,
1487
+ queued: true,
1488
+ joined: true,
1489
+ result: existing.resultPromise
1490
+ };
1491
+ }
1492
+ const record = this.createRecord(request, signature);
1493
+ this.runs.set(record.snapshot.id, record);
1494
+ this.pending.push(record.snapshot.id);
1495
+ this.pump();
1496
+ return {
1497
+ runId: record.snapshot.id,
1498
+ queued: busy,
1499
+ joined: false,
1500
+ result: record.resultPromise
1501
+ };
1502
+ }
1503
+ /**
1504
+ * Cancel a run. Queued: removed before it ever starts (its result
1505
+ * rejects `BackupCancelledError`). Running: the abort signal fires —
1506
+ * the executor's tar/upload streams stop and its cleanup runs.
1507
+ * Unknown or already terminal: `false`.
1508
+ */
1509
+ cancel(runId) {
1510
+ const record = this.runs.get(runId);
1511
+ if (!record) return false;
1512
+ if (record.snapshot.state === "queued") {
1513
+ const idx = this.pending.indexOf(runId);
1514
+ if (idx >= 0) this.pending.splice(idx, 1);
1515
+ this.finish(record, "cancelled");
1516
+ record.rejectResult(new BackupCancelledError(`backup run ${runId} cancelled while queued`));
1517
+ return true;
1518
+ }
1519
+ if (record.snapshot.state === "running") {
1520
+ record.controller.abort();
1521
+ return true;
1522
+ }
1523
+ return false;
1524
+ }
1525
+ /**
1526
+ * EXECUTION order, not timestamp order: the running run first, then
1527
+ * every queued run in the exact order the pump will start them (each
1528
+ * stamped with `queuePosition`, 1 = next), then the bounded finished
1529
+ * history newest-first. The queued section is read straight off
1530
+ * `this.pending` — a consumer sorting by `requestedAt` descending
1531
+ * would put the run that starts NEXT at the BOTTOM, which is
1532
+ * backwards exactly when the queue matters (more than one waiter).
1533
+ */
1534
+ listRuns() {
1535
+ const running = [];
1536
+ const finished = [];
1537
+ for (const record of this.runs.values()) {
1538
+ const snap = record.snapshot;
1539
+ if (snap.state === "running") running.push(snap);
1540
+ else if (snap.state !== "queued") finished.push(snap);
1541
+ }
1542
+ const queued = [];
1543
+ for (const [index, id] of this.pending.entries()) {
1544
+ const record = this.runs.get(id);
1545
+ if (record) queued.push({
1546
+ ...record.snapshot,
1547
+ queuePosition: index + 1
1548
+ });
1549
+ }
1550
+ finished.sort((a, b) => b.requestedAt - a.requestedAt);
1551
+ return [
1552
+ ...running,
1553
+ ...queued,
1554
+ ...finished
1555
+ ];
1556
+ }
1557
+ getRun(runId) {
1558
+ const record = this.runs.get(runId);
1559
+ if (!record) return void 0;
1560
+ const pendingIndex = this.pending.indexOf(runId);
1561
+ return pendingIndex >= 0 ? {
1562
+ ...record.snapshot,
1563
+ queuePosition: pendingIndex + 1
1564
+ } : record.snapshot;
1565
+ }
1566
+ createRecord(request, signature) {
1567
+ let resolveResult;
1568
+ let rejectResult;
1569
+ const resultPromise = new Promise((res, rej) => {
1570
+ resolveResult = res;
1571
+ rejectResult = rej;
1572
+ });
1573
+ resultPromise.catch(() => void 0);
1574
+ return {
1575
+ snapshot: {
1576
+ id: randomUUID(),
1577
+ state: "queued",
1578
+ phase: "queued",
1579
+ destinationIds: request.destinations ?? [],
1580
+ ...request.label !== void 0 ? { label: request.label } : {},
1581
+ requestedAt: this.now(),
1582
+ stagedBytes: 0,
1583
+ uploadedBytes: 0,
1584
+ completedDestinationIds: [],
1585
+ failedDestinationIds: []
1586
+ },
1587
+ request,
1588
+ signature,
1589
+ controller: new AbortController(),
1590
+ resultPromise,
1591
+ resolveResult,
1592
+ rejectResult
1593
+ };
1594
+ }
1595
+ pump() {
1596
+ if (this.activeId !== null) return;
1597
+ const nextId = this.pending.shift();
1598
+ if (nextId === void 0) return;
1599
+ const record = this.runs.get(nextId);
1600
+ if (!record) {
1601
+ this.pump();
1602
+ return;
1603
+ }
1604
+ this.activeId = nextId;
1605
+ this.patch(record, {
1606
+ state: "running",
1607
+ phase: "building",
1608
+ startedAt: this.now()
1609
+ });
1610
+ this.execute(record);
1611
+ }
1612
+ async execute(record) {
1613
+ const progress = this.progressFor(record);
1614
+ try {
1615
+ const value = await this.executor(record.request, record.controller.signal, progress);
1616
+ if (record.controller.signal.aborted) this.finish(record, "cancelled");
1617
+ else {
1618
+ const { destinationIds, completedDestinationIds, failedDestinationIds } = record.snapshot;
1619
+ if (destinationIds.length > 0 && completedDestinationIds.length === 0) this.finish(record, "failed", `no destination accepted the archive (${(failedDestinationIds.length > 0 ? failedDestinationIds : destinationIds).join(", ")})`);
1620
+ else this.finish(record, "succeeded");
1621
+ }
1622
+ record.resolveResult(value);
1623
+ } catch (err) {
1624
+ if (err instanceof BackupCancelledError || record.controller.signal.aborted) {
1625
+ this.finish(record, "cancelled");
1626
+ record.rejectResult(err instanceof BackupCancelledError ? err : new BackupCancelledError());
1627
+ } else {
1628
+ this.finish(record, "failed", err instanceof Error ? err.message : String(err));
1629
+ record.rejectResult(err);
1630
+ }
1631
+ } finally {
1632
+ this.activeId = null;
1633
+ this.pump();
1634
+ }
1635
+ }
1636
+ progressFor(record) {
1637
+ return {
1638
+ setPhase: (phase) => this.patch(record, { phase }),
1639
+ setDestinations: (ids) => this.patch(record, { destinationIds: [...ids] }),
1640
+ setStagedBytes: (bytes) => this.patch(record, { stagedBytes: bytes }),
1641
+ setArchiveSize: (bytes) => this.patch(record, { archiveSizeBytes: bytes }),
1642
+ setUploadedBytes: (bytes) => this.patch(record, { uploadedBytes: bytes }),
1643
+ destinationCompleted: (id) => this.patch(record, {
1644
+ completedDestinationIds: [...record.snapshot.completedDestinationIds, id],
1645
+ uploadedBytes: 0
1646
+ }),
1647
+ destinationFailed: (id) => this.patch(record, {
1648
+ failedDestinationIds: [...record.snapshot.failedDestinationIds, id],
1649
+ uploadedBytes: 0
1650
+ })
1651
+ };
1652
+ }
1653
+ patch(record, patch) {
1654
+ record.snapshot = {
1655
+ ...record.snapshot,
1656
+ ...patch
1657
+ };
1658
+ }
1659
+ finish(record, state, error) {
1660
+ this.patch(record, {
1661
+ state,
1662
+ phase: "done",
1663
+ finishedAt: this.now(),
1664
+ ...error !== void 0 ? { error } : {}
1665
+ });
1666
+ this.finished.push(record.snapshot.id);
1667
+ while (this.finished.length > this.maxFinished) {
1668
+ const evicted = this.finished.shift();
1669
+ if (evicted !== void 0) this.runs.delete(evicted);
1670
+ }
1671
+ }
1672
+ };
1673
+ /**
1674
+ * Canonical signature for join-detection. Order-normalised so
1675
+ * `{ destinations: [a, b] }` and `{ destinations: [b, a] }` — the same
1676
+ * fan-out set — coalesce.
1677
+ */
1678
+ function requestSignature(request) {
1679
+ return JSON.stringify({
1680
+ destinations: [...request.destinations ?? []].toSorted(),
1681
+ locations: [...request.locations ?? []].toSorted(),
1682
+ label: request.label ?? null,
1683
+ retentionCount: request.retentionCount ?? null,
1684
+ databases: [...request.databases ?? []].toSorted()
1685
+ });
1686
+ }
1687
+ //#endregion
1688
+ //#region src/builtins/backup-orchestrator/schedule-store.ts
1689
+ var BackupScheduleService = class {
1690
+ schedulesKind;
1691
+ constructor(schedulesKind) {
1692
+ this.schedulesKind = schedulesKind;
1693
+ }
1694
+ async list() {
1695
+ const rows = await (0, import_read_all_rows.readAllRows)(this.schedulesKind);
1696
+ rows.sort((a, b) => a.id.localeCompare(b.id));
1697
+ const out = [];
1698
+ for (const row of rows) {
1699
+ const mapped = bodyToSchedule(row.id, row.data);
1700
+ if (mapped) out.push(mapped);
1701
+ }
1702
+ return out;
1703
+ }
1704
+ async get(id) {
1705
+ const row = await this.schedulesKind.get(id);
1706
+ return row === null ? null : bodyToSchedule(id, row.data);
1707
+ }
1708
+ /** Replace-or-insert: one full `put` of the row. */
1709
+ async upsert(s) {
1710
+ const data = backupOrchestratorRecordKinds.schedules.schema.parse(scheduleToBody(s));
1711
+ await this.schedulesKind.put({
1712
+ id: s.id,
1713
+ data
1714
+ });
1715
+ }
1716
+ async delete(id) {
1717
+ await this.schedulesKind.delete(id);
1718
+ }
1719
+ };
1720
+ function scheduleToBody(s) {
1721
+ return {
1722
+ label: s.label,
1723
+ cron: s.cron,
1724
+ enabled: s.enabled,
1725
+ locationIds: [...s.locationIds],
1726
+ retentionCount: s.retentionCount,
1727
+ ...s.dataSources !== void 0 ? { dataSources: [...s.dataSources] } : {},
1728
+ ...s.databases !== void 0 ? { databases: [...s.databases] } : {},
1729
+ ...s.lastAttemptAt !== void 0 ? { lastAttemptAt: s.lastAttemptAt } : {},
1730
+ ...s.lastSuccessAt !== void 0 ? { lastSuccessAt: s.lastSuccessAt } : {},
1731
+ ...s.lastError !== void 0 ? { lastError: s.lastError } : {}
1732
+ };
1733
+ }
1734
+ function bodyToSchedule(id, body) {
1735
+ if (!id) return null;
1736
+ return {
1737
+ id,
1738
+ label: body.label,
1739
+ cron: body.cron,
1740
+ enabled: body.enabled,
1741
+ locationIds: [...body.locationIds],
1742
+ retentionCount: body.retentionCount,
1743
+ ...body.dataSources !== void 0 ? { dataSources: [...body.dataSources] } : {},
1744
+ ...body.databases !== void 0 && body.databases.length > 0 ? { databases: [...body.databases] } : {},
1745
+ ...body.lastAttemptAt !== void 0 ? { lastAttemptAt: body.lastAttemptAt } : {},
1746
+ ...body.lastSuccessAt !== void 0 ? { lastSuccessAt: body.lastSuccessAt } : {},
1747
+ ...body.lastError !== void 0 ? { lastError: body.lastError } : {}
1748
+ };
1749
+ }
1750
+ //#endregion
1751
+ //#region src/builtins/backup-orchestrator/staging-paths.ts
1752
+ /** Basename of the staging dir under the node data root. */
1753
+ var STAGING_DIR_NAME = "backup-staging";
1754
+ /** Canonical staging dir for a node data root. */
1755
+ function resolveStagingDir(nodeDataDir) {
1756
+ return path$1.join(nodeDataDir, STAGING_DIR_NAME);
1757
+ }
1758
+ /**
1759
+ * Delete every top-level entry of `stagingDir` except those whose
1760
+ * resolved path appears in `keepPaths`. Per-entry failures are logged
1761
+ * and skipped — a locked file must not abort the sweep. A missing
1762
+ * staging dir is a clean no-op.
1763
+ */
1764
+ async function sweepStagingDir(input) {
1765
+ const keep = new Set(input.keepPaths.map((p) => path$1.resolve(p)));
1766
+ let entries;
1767
+ try {
1768
+ entries = await fsp.readdir(input.stagingDir);
1769
+ } catch {
1770
+ return {
1771
+ removedCount: 0,
1772
+ freedBytes: 0,
1773
+ keptCount: 0
1774
+ };
1775
+ }
1776
+ let removedCount = 0;
1777
+ let freedBytes = 0;
1778
+ let keptCount = 0;
1779
+ for (const name of entries) {
1780
+ const abs = path$1.join(input.stagingDir, name);
1781
+ if (keep.has(path$1.resolve(abs))) {
1782
+ keptCount++;
1783
+ continue;
1784
+ }
1785
+ try {
1786
+ const footprint = await measureDirectoryFootprint(abs);
1787
+ await fsp.rm(abs, {
1788
+ recursive: true,
1789
+ force: true
1790
+ });
1791
+ removedCount++;
1792
+ freedBytes += footprint.totalBytes;
1793
+ } catch (err) {
1794
+ input.logger.warn("backup staging sweep: entry removal failed — skipping", { meta: {
1795
+ path: abs,
1796
+ error: err instanceof Error ? err.message : String(err)
1797
+ } });
1798
+ }
1799
+ }
1800
+ return {
1801
+ removedCount,
1802
+ freedBytes,
1803
+ keptCount
1804
+ };
1805
+ }
1806
+ /**
1807
+ * Recursive size + file count of a path (file or directory). Absent
1808
+ * path → `present: false` with zeros. Used by the sweep to report
1809
+ * reclaimed bytes and by the orchestrator to surface the legacy
1810
+ * staging dir's footprint without touching it.
1811
+ */
1812
+ async function measureDirectoryFootprint(dir) {
1813
+ let stat;
1814
+ try {
1815
+ stat = await fsp.stat(dir);
1816
+ } catch {
1817
+ return {
1818
+ present: false,
1819
+ totalBytes: 0,
1820
+ fileCount: 0
1821
+ };
1822
+ }
1823
+ if (!stat.isDirectory()) return {
1824
+ present: true,
1825
+ totalBytes: stat.size,
1826
+ fileCount: 1
1827
+ };
1828
+ let totalBytes = 0;
1829
+ let fileCount = 0;
1830
+ let children;
1831
+ try {
1832
+ children = await fsp.readdir(dir);
1833
+ } catch {
1834
+ return {
1835
+ present: true,
1836
+ totalBytes: 0,
1837
+ fileCount: 0
1838
+ };
1839
+ }
1840
+ for (const child of children) {
1841
+ const nested = await measureDirectoryFootprint(path$1.join(dir, child));
1842
+ totalBytes += nested.totalBytes;
1843
+ fileCount += nested.fileCount;
1844
+ }
1845
+ return {
1846
+ present: true,
1847
+ totalBytes,
1848
+ fileCount
1849
+ };
1850
+ }
1851
+ //#endregion
1852
+ //#region src/builtins/backup-orchestrator/write-targets.ts
1853
+ /**
1854
+ * Pick the destinations an archive may be fanned out to.
1855
+ *
1856
+ * An explicit `requested` list selects from the candidates by id and bypasses
1857
+ * the policy flag (that is today's behaviour and it is right: naming a
1858
+ * destination IS the opt-in). A requested id that is not a `backups` location
1859
+ * at all is simply absent from the candidates and drops out here, exactly as
1860
+ * before.
1861
+ *
1862
+ * The location flag is applied LAST and to both paths, so there is one place
1863
+ * where "disabled" is honoured rather than one per caller.
1864
+ */
1865
+ function selectBackupTargets(input) {
1866
+ const requested = input.requested;
1867
+ const pool = requested && requested.length > 0 ? input.candidates.filter((c) => requested.includes(c.id)) : input.candidates.filter((c) => c.policyEnabled);
1868
+ return {
1869
+ targets: pool.filter((c) => c.locationEnabled),
1870
+ skippedDisabled: pool.filter((c) => !c.locationEnabled).map((c) => c.id)
1871
+ };
1872
+ }
1873
+ //#endregion
1874
+ //#region src/builtins/backup-orchestrator/backup-orchestrator.addon.ts
1875
+ /**
1876
+ * `backup-orchestrator` builtin — singleton owner of the `backup` cap.
1877
+ *
1878
+ * Responsibilities:
1879
+ * - Schedule (cron-like timer at top of hour, daily/weekly cadence)
1880
+ * - Per-destination policy (enable/disable, retention count, label)
1881
+ * persisted in the `destination-policies` records kind (this builtin
1882
+ * owns the kind).
1883
+ * - Archive build (one tar.gz with embedded manifest, fanned out to
1884
+ * every selected `backups`-typed `StorageLocation` via the
1885
+ * consumer-facing `storage` cap's chunked upload protocol).
1886
+ * - Aggregate listing/restore/delete across destinations — operates
1887
+ * on the per-location `manifests.json` index file, not the
1888
+ * archives directly.
1889
+ *
1890
+ * Storage routing: destinations are
1891
+ * `api.storage.listLocations({ type: 'backups' })` — every operator-
1892
+ * visible `backups` location IS a destination. The orchestrator joins
1893
+ * that list with the `destination-policies` records to surface
1894
+ * `enabled` / `retentionCount` / `label`. The actual archive bytes
1895
+ * travel through `api.storage.beginUpload` / `writeChunk` /
1896
+ * `finalizeUpload`, with the staging archive built into
1897
+ * `<nodeDataDir>/backup-staging` (outside every backed-up location —
1898
+ * see staging-paths.ts).
1899
+ */
1900
+ /**
1901
+ * Hardcoded seed for newly-discovered `backups` locations. Operators
1902
+ * tune retention per-destination after creation via the destinations
1903
+ * table. Promoted from a configurable global to a constant when the
1904
+ * orchestrator's settings panel was retired (per-destination cron +
1905
+ * inline retention input on the destinations row replaces every knob
1906
+ * the panel used to expose).
1907
+ */
1908
+ var DEFAULT_RETENTION_COUNT = 7;
1909
+ var SCHEDULE_TICK_MS = 6e4;
1910
+ /**
1911
+ * Build the human-facing archive label. Every archive always carries
1912
+ * the destination id and the creation date — useful in restore wizards
1913
+ * + cross-destination listings where UUIDs are unreadable.
1914
+ *
1915
+ * Format: `${destinationId} · ${YYYY-MM-DD HH:mm}[${suffix}]`. Suffix is
1916
+ * an optional operator-provided tag (e.g. "before-migration") appended
1917
+ * after another middot. UTC is intentional — labels are also written
1918
+ * into the per-location manifest which travels across timezones with
1919
+ * the backup.
1920
+ */
1921
+ function formatArchiveLabel(destinationId, createdAt, suffix) {
1922
+ const d = new Date(createdAt);
1923
+ const pad = (n) => String(n).padStart(2, "0");
1924
+ const stamp = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;
1925
+ const trimmed = suffix?.trim();
1926
+ return trimmed ? `${destinationId} · ${stamp} · ${trimmed}` : `${destinationId} · ${stamp}`;
1927
+ }
1928
+ /**
1929
+ * Chunk size for the read-stream that feeds the chunked upload pipe.
1930
+ * 8 MiB is well under the WS frame limit (16 MiB on tRPC) with headroom.
1931
+ */
1932
+ var UPLOAD_CHUNK_BYTES = 8 * 1024 * 1024;
1933
+ /** Manifest id this addon registers under (must match `package.json`). */
1934
+ var ORCHESTRATOR_ADDON_ID = "backup-orchestrator";
1935
+ var BackupOrchestratorAddon = class extends BaseAddon {
1936
+ systemBackup = null;
1937
+ backupRecords = null;
1938
+ policies = null;
1939
+ schedules = null;
1940
+ /** Backup encryption keys — PUBLIC keys only (see encryption-key-store.ts). */
1941
+ encryptionKeys = null;
1942
+ warnedNoEncryptionStore = false;
1943
+ dataDir = "";
1944
+ /**
1945
+ * Transient build buffer for archive fan-out. The tar is built here
1946
+ * ONCE, streamed to every destination via the storage cap's chunked
1947
+ * upload, then removed. Lives at `<nodeDataDir>/backup-staging` —
1948
+ * OUTSIDE every backed-up location, so a backup can never contain a
1949
+ * backup (the old `ctx.dataDir/staging` sat inside `addons-data` and
1950
+ * compounded 175M → 4.5G before Jul 28), and distinct from
1951
+ * `<nodeDataDir>/backups` where the default `backups` destination
1952
+ * seeds when `CAMSTACK_BACKUP_ROOT` is unset. See staging-paths.ts.
1953
+ */
1954
+ stagingDir = "";
1955
+ scheduleTimer = null;
1956
+ /** Guards the disarmed-scheduler complaint to once per process. */
1957
+ warnedSchedulerDisarmed = false;
1958
+ /**
1959
+ * Baseline used as the "after" anchor when a schedule has a cron but
1960
+ * has never fired yet (no `lastAttemptAt`). Set on orchestrator boot so a
1961
+ * pattern that fires every minute doesn't immediately replay every
1962
+ * historical "missed" run from epoch 0.
1963
+ */
1964
+ scheduleBaselineAt = Date.now();
1965
+ manifestLock = new LocationManifestLock();
1966
+ /**
1967
+ * Global execution queue — at most ONE archive build at a time,
1968
+ * cluster-node-wide (D342). Replaces the earlier invisible
1969
+ * single-flight `buildLock`: same serialisation guarantee (two
1970
+ * schedules due one tick apart built 8.2 GB + 3.7 GB side by side on
1971
+ * the hub, 2026-09-04), but every run is now observable via
1972
+ * `listRuns`, joinable when identical, and cancellable mid-stream.
1973
+ */
1974
+ runQueue = null;
1975
+ constructor() {
1976
+ super({});
1977
+ }
1978
+ async onInitialize() {
1979
+ const records = this.ctx.records;
1980
+ if (records !== void 0) {
1981
+ await records.declare(backupOrchestratorRecordKinds);
1982
+ this.backupRecords = backupRecordStoresOf(records);
1983
+ }
1984
+ this.dataDir = this.ctx.nodeDataDir;
1985
+ this.stagingDir = resolveStagingDir(this.ctx.nodeDataDir);
1986
+ this.systemBackup = new SystemBackupService(this.dataDir, this.ctx.logger);
1987
+ this.runQueue = new BackupRunQueue((request, signal, progress) => this.runBackupBuild(request, signal, progress));
1988
+ await this.cleanStagingArea();
1989
+ const backupRecords = this.backupRecords;
1990
+ if (backupRecords === null) this.ctx.logger.warn("backup-orchestrator: no ctx.records — schedules and destination policies will not persist");
1991
+ else {
1992
+ this.policies = new BackupDestinationPolicyService(backupRecords.destinationPolicies);
1993
+ this.schedules = new BackupScheduleService(backupRecords.schedules);
1994
+ }
1995
+ await this.seedWeekly();
1996
+ const settingsStore = this.ctx.kernel.capabilityRegistry?.getSingleton("settings-store");
1997
+ this.encryptionKeys = settingsStore ? new BackupEncryptionKeyStore(settingsStore, Date.now, this.backupRecords?.encryptionKeys ?? null) : null;
1998
+ const provider = {
1999
+ listDestinations: () => this.listDestinations(),
2000
+ list: () => this.aggregatedList(),
2001
+ listLocations: () => this.systemBackup.statLocations(),
2002
+ trigger: (input) => this.triggerBackup(input),
2003
+ listRuns: () => this.listRuns(),
2004
+ cancel: (input) => this.cancelRun(input),
2005
+ getEntries: (input) => this.getEntries(input),
2006
+ restore: (input) => this.scheduleRestore(input),
2007
+ getEncryption: () => this.getEncryption(),
2008
+ setupEncryption: () => this.setupEncryption(),
2009
+ disableEncryption: () => this.disableEncryption(),
2010
+ checkBackupKey: (input) => this.checkBackupKey(input),
2011
+ delete: (input) => this.deleteArchive(input),
2012
+ listArchives: (input) => this.listArchives(input),
2013
+ upsertDestinationPolicy: (input) => this.upsertDestinationPolicy(input),
2014
+ previewSchedule: (input) => this.previewSchedule(input),
2015
+ listSchedules: () => this.listSchedules(),
2016
+ listAvailableDatabases: () => this.listAvailableDatabases(),
2017
+ upsertSchedule: (input) => this.upsertSchedule(input),
2018
+ deleteSchedule: (input) => this.deleteSchedule(input)
2019
+ };
2020
+ this.startScheduleTimer();
2021
+ this.ctx.logger.info("Backup orchestrator initialized", { meta: {
2022
+ dataDir: this.dataDir,
2023
+ policies: this.policies !== null
2024
+ } });
2025
+ return [{
2026
+ capability: backupCapability,
2027
+ provider
2028
+ }, {
2029
+ capability: storageOccupancyCapability,
2030
+ provider: { getOccupancy: async (input) => this.backupOccupancy(input.locationIds) }
2031
+ }];
2032
+ }
2033
+ async onShutdown() {
2034
+ this.stopScheduleTimer();
2035
+ if (this.runQueue) {
2036
+ for (const run of this.runQueue.listRuns()) if (run.state === "queued" || run.state === "running") this.runQueue.cancel(run.id);
2037
+ }
2038
+ this.runQueue = null;
2039
+ this.systemBackup = null;
2040
+ this.policies = null;
2041
+ this.schedules = null;
2042
+ }
2043
+ /**
2044
+ * Aggregate destinations from `api.storage.listLocations({ type: 'backups' })`
2045
+ * joined with the per-destination policy table. New locations get an
2046
+ * `ensureDefault` policy seeded transparently (enabled=true,
2047
+ * retentionCount=defaultRetentionCount). Pre-existing operator-edited
2048
+ * policies are preserved by the `ensureDefault` idempotency.
2049
+ */
2050
+ async listDestinations() {
2051
+ const locations = await this.fetchBackupLocations();
2052
+ const policies = await this.loadPoliciesIndexed(locations.map((l) => l.id));
2053
+ const lastSuccess = await Promise.all(locations.map(async (loc) => {
2054
+ try {
2055
+ const manifest = await readLocationManifest(this.storageApi(), loc.id);
2056
+ return [loc.id, latestArchiveOf(manifest)];
2057
+ } catch {
2058
+ return [loc.id, void 0];
2059
+ }
2060
+ }));
2061
+ const lastSuccessByLoc = new Map(lastSuccess);
2062
+ const cadence = await this.cadenceByLocation();
2063
+ return locations.map((loc) => this.toDestinationWire(loc, policies.get(loc.id), lastSuccessByLoc.get(loc.id), cadence.get(loc.id)));
2064
+ }
2065
+ /**
2066
+ * Join the enabled schedules by the locations they fan out to.
2067
+ * Comma-joined crons (a location can be targeted by several schedules),
2068
+ * earliest next firing. Computed from `Date.now()` — an operator asking
2069
+ * "when next" means from now, never from a stale run cursor.
2070
+ */
2071
+ async cadenceByLocation() {
2072
+ const out = /* @__PURE__ */ new Map();
2073
+ if (!this.schedules) return out;
2074
+ const schedules = await this.schedules.list().catch((err) => {
2075
+ this.ctx.logger.warn("backup-orchestrator: schedule list failed — cadence unknown", { meta: { error: err instanceof Error ? err.message : String(err) } });
2076
+ return [];
2077
+ });
2078
+ const now = Date.now();
2079
+ for (const s of schedules) {
2080
+ if (!s.enabled || s.cron.trim().length === 0) continue;
2081
+ const next = this.safeNextDue(s.cron, now);
2082
+ for (const id of s.locationIds) {
2083
+ const prev = out.get(id);
2084
+ const crons = prev ? [...prev.crons, s.cron] : [s.cron];
2085
+ const nextRunAt = next === void 0 ? prev?.nextRunAt : prev?.nextRunAt === void 0 ? next : Math.min(prev.nextRunAt, next);
2086
+ out.set(id, {
2087
+ crons,
2088
+ ...nextRunAt !== void 0 ? { nextRunAt } : {}
2089
+ });
2090
+ }
2091
+ }
2092
+ return out;
2093
+ }
2094
+ async fetchBackupLocations() {
2095
+ try {
2096
+ return await this.ctx.api.storage.listLocations.query({ type: "backups" });
2097
+ } catch (err) {
2098
+ this.ctx.logger.error("backup-orchestrator: listLocations failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
2099
+ return [];
2100
+ }
2101
+ }
2102
+ /**
2103
+ * Load every persisted policy and key it by `locationId`, while
2104
+ * lazily seeding a default for any `locationId` we haven't seen
2105
+ * before. Idempotent — `ensureDefault` no-ops on already-persisted
2106
+ * rows. Falls back to the in-memory default policy when the policy
2107
+ * service isn't wired (no `ctx.records`).
2108
+ */
2109
+ async loadPoliciesIndexed(locationIds) {
2110
+ const out = /* @__PURE__ */ new Map();
2111
+ if (!this.policies) {
2112
+ for (const id of locationIds) out.set(id, this.fallbackPolicy(id));
2113
+ return out;
2114
+ }
2115
+ const persisted = await this.policies.list().catch((err) => {
2116
+ this.ctx.logger.warn("backup-orchestrator: policy list failed — using defaults", { meta: { error: err instanceof Error ? err.message : String(err) } });
2117
+ return [];
2118
+ });
2119
+ for (const p of persisted) out.set(p.locationId, p);
2120
+ for (const id of locationIds) {
2121
+ if (out.has(id)) continue;
2122
+ try {
2123
+ const fresh = await this.policies.ensureDefault(id, { retentionCount: DEFAULT_RETENTION_COUNT });
2124
+ out.set(id, fresh);
2125
+ } catch (err) {
2126
+ this.ctx.logger.warn("backup-orchestrator: ensureDefault failed", { meta: {
2127
+ locationId: id,
2128
+ error: err instanceof Error ? err.message : String(err)
2129
+ } });
2130
+ out.set(id, this.fallbackPolicy(id));
2131
+ }
2132
+ }
2133
+ return out;
2134
+ }
2135
+ fallbackPolicy(locationId) {
2136
+ return {
2137
+ locationId,
2138
+ enabled: true,
2139
+ retentionCount: DEFAULT_RETENTION_COUNT
2140
+ };
2141
+ }
2142
+ toDestinationWire(loc, policy, latest, cadence) {
2143
+ const effective = policy ?? this.fallbackPolicy(loc.id);
2144
+ const subId = extractSlug(loc.id);
2145
+ const displayName = effective.label && effective.label.length > 0 ? effective.label : loc.displayName;
2146
+ return {
2147
+ id: loc.id,
2148
+ addonId: ORCHESTRATOR_ADDON_ID,
2149
+ subId,
2150
+ displayName,
2151
+ kind: kindFromProviderId(loc.providerId),
2152
+ triggerSupported: effective.enabled && mayWriteToLocation(loc),
2153
+ restoreSupported: true,
2154
+ enabled: effective.enabled,
2155
+ retentionCount: effective.retentionCount,
2156
+ ...effective.label !== void 0 ? { label: effective.label } : {},
2157
+ ...latest !== void 0 ? { lastSuccessAt: latest.createdAt } : {},
2158
+ ...latest !== void 0 ? { lastSuccessSizeBytes: latest.sizeBytes } : {},
2159
+ ...cadence !== void 0 ? { cron: cadence.crons.join(", ") } : {},
2160
+ ...cadence?.nextRunAt !== void 0 ? { nextRunAt: cadence.nextRunAt } : {},
2161
+ ...effective.lastAttemptAt !== void 0 ? { lastAttemptAt: effective.lastAttemptAt } : {},
2162
+ ...effective.lastError !== void 0 ? { lastError: effective.lastError } : {}
2163
+ };
2164
+ }
2165
+ /**
2166
+ * Compute next-due ms-epoch for a cron, or `undefined` on parse error.
2167
+ * Catches so a single malformed cron doesn't blank out the whole
2168
+ * destinations list at the cap surface.
2169
+ */
2170
+ safeNextDue(cron, after) {
2171
+ try {
2172
+ return computeNextDue(cron, after ?? this.scheduleBaselineAt) ?? void 0;
2173
+ } catch {
2174
+ return;
2175
+ }
2176
+ }
2177
+ /**
2178
+ * Aggregate listing — read every `backups` location's `manifests.json`
2179
+ * and return one wire entry per archive, tagged with `destinationId`.
2180
+ * Failures on individual locations are logged and skipped so a single
2181
+ * unreachable destination doesn't blank out the whole UI.
2182
+ */
2183
+ /**
2184
+ * Bytes the archives occupy on each named location (D388).
2185
+ *
2186
+ * Summed from each location's own manifest — the record the uploader writes
2187
+ * — so this never walks a filesystem and never stats a remote destination.
2188
+ * A manifest that cannot be read contributes NOTHING and is logged: a
2189
+ * destination that is temporarily unreachable must read back as unknown, not
2190
+ * as an empty disk. A location holding no archives is omitted for the same
2191
+ * reason it is omitted everywhere else — only the orchestrator can tell
2192
+ * "nobody reported" from "reported nothing".
2193
+ */
2194
+ async backupOccupancy(locationIds) {
2195
+ const measuredAtMs = Date.now();
2196
+ const out = [];
2197
+ for (const locationId of locationIds) {
2198
+ let manifest;
2199
+ try {
2200
+ manifest = await readLocationManifest(this.storageApi(), locationId);
2201
+ } catch {
2202
+ continue;
2203
+ }
2204
+ const ownedBytes = manifest.archives.reduce((sum, a) => sum + a.sizeBytes, 0);
2205
+ if (ownedBytes <= 0) continue;
2206
+ out.push({
2207
+ locationId,
2208
+ ownedBytes,
2209
+ measuredAtMs
2210
+ });
2211
+ }
2212
+ return out;
2213
+ }
2214
+ async aggregatedList() {
2215
+ const locations = await this.fetchBackupLocations();
2216
+ const out = [];
2217
+ for (const loc of locations) {
2218
+ let manifest;
2219
+ try {
2220
+ manifest = await readLocationManifest(this.storageApi(), loc.id);
2221
+ } catch (err) {
2222
+ this.ctx.logger.warn("backup list: manifest read failed", { meta: {
2223
+ locationId: loc.id,
2224
+ error: err instanceof Error ? err.message : String(err)
2225
+ } });
2226
+ continue;
2227
+ }
2228
+ for (const a of manifest.archives) {
2229
+ const entry = {
2230
+ id: a.id,
2231
+ destinationId: loc.id,
2232
+ createdAt: a.createdAt,
2233
+ sizeBytes: a.sizeBytes,
2234
+ ...a.label !== void 0 ? { label: a.label } : {},
2235
+ locations: [...a.manifest.locations],
2236
+ ...a.encryption !== void 0 ? { encryption: a.encryption } : {}
2237
+ };
2238
+ out.push(entry);
2239
+ }
2240
+ }
2241
+ return out;
2242
+ }
2243
+ async stagingPath(filename) {
2244
+ await fsp.mkdir(this.stagingDir, { recursive: true });
2245
+ return path$1.join(this.stagingDir, filename);
2246
+ }
2247
+ /**
2248
+ * Boot-time staging hygiene. Sweeps the staging dir (sparing an
2249
+ * archive a pending-restore marker references — the boot hook has
2250
+ * not consumed it yet), then reports — without touching — the LEGACY
2251
+ * staging dir inside `addons-data`, where pre-move leaks live. The
2252
+ * legacy dir held 5.1 GB on the hub; deleting operator-visible
2253
+ * gigabytes silently is not this addon's call, so it warns with the
2254
+ * footprint instead.
2255
+ */
2256
+ async cleanStagingArea() {
2257
+ const marker = this.systemBackup?.readPendingMarker() ?? null;
2258
+ const keepPaths = marker ? [marker.archivePath] : [];
2259
+ try {
2260
+ const swept = await sweepStagingDir({
2261
+ stagingDir: this.stagingDir,
2262
+ keepPaths,
2263
+ logger: this.ctx.logger
2264
+ });
2265
+ if (swept.removedCount > 0) this.ctx.logger.info("backup staging swept — leaked transient files removed", { meta: {
2266
+ stagingDir: this.stagingDir,
2267
+ removedCount: swept.removedCount,
2268
+ freedBytes: swept.freedBytes,
2269
+ keptForPendingRestore: swept.keptCount
2270
+ } });
2271
+ } catch (err) {
2272
+ this.ctx.logger.warn("backup staging sweep failed — continuing", { meta: {
2273
+ stagingDir: this.stagingDir,
2274
+ error: err instanceof Error ? err.message : String(err)
2275
+ } });
2276
+ }
2277
+ const legacyDir = path$1.join(this.ctx.dataDir, "staging");
2278
+ try {
2279
+ const legacy = await measureDirectoryFootprint(legacyDir);
2280
+ if (legacy.present && legacy.fileCount > 0) this.ctx.logger.warn("legacy backup staging dir still holds files inside addons-data — excluded from archives, but the disk space is only reclaimed by deleting it", { meta: {
2281
+ legacyDir,
2282
+ fileCount: legacy.fileCount,
2283
+ totalBytes: legacy.totalBytes
2284
+ } });
2285
+ } catch {}
2286
+ }
2287
+ /**
2288
+ * Trigger a backup run through the global execution queue (D342):
2289
+ * at most one archive build at a time, a trigger that arrives while
2290
+ * one is in flight WAITS (or joins an identical queued run), and the
2291
+ * result says which happened. The call still resolves when the run
2292
+ * terminates; a cancelled run resolves with `cancelled: true` and
2293
+ * whatever entries landed before the stop — a deliberate operator
2294
+ * cancel is an outcome, not an error.
2295
+ */
2296
+ async triggerBackup(input) {
2297
+ if (!this.runQueue) throw new Error("orchestrator not initialized");
2298
+ const request = {
2299
+ ...input?.destinations ? { destinations: input.destinations } : {},
2300
+ ...input?.locations ? { locations: input.locations } : {},
2301
+ ...input?.label !== void 0 ? { label: input.label } : {},
2302
+ ...input?.retentionCount !== void 0 ? { retentionCount: input.retentionCount } : {},
2303
+ ...input?.databases ? { databases: input.databases } : {}
2304
+ };
2305
+ const submitted = this.runQueue.submit(request);
2306
+ if (submitted.queued) this.ctx.logger.info(submitted.joined ? "backup trigger: identical run already queued — joined it" : "backup trigger: a run is in flight — enqueued behind it", { meta: { runId: submitted.runId } });
2307
+ let entries;
2308
+ try {
2309
+ entries = await submitted.result;
2310
+ } catch (err) {
2311
+ if (!(err instanceof BackupCancelledError)) throw err;
2312
+ entries = [];
2313
+ }
2314
+ const finalState = this.runQueue?.getRun(submitted.runId)?.state;
2315
+ return {
2316
+ runId: submitted.runId,
2317
+ queued: submitted.queued,
2318
+ joined: submitted.joined,
2319
+ cancelled: finalState === "cancelled",
2320
+ entries
2321
+ };
2322
+ }
2323
+ /** Wire `backup.listRuns` — queued + active + bounded history. */
2324
+ async listRuns() {
2325
+ return this.runQueue?.listRuns() ?? [];
2326
+ }
2327
+ /**
2328
+ * Wire `backup.cancel`. Delegates to the queue: a queued run is
2329
+ * removed before it starts; the running run's abort signal fires and
2330
+ * `runBackupBuild` stops the tar/upload streams and deletes its
2331
+ * staging archive on the way out.
2332
+ */
2333
+ async cancelRun(input) {
2334
+ const cancelled = this.runQueue?.cancel(input.runId) ?? false;
2335
+ if (cancelled) this.ctx.logger.info("backup run cancel requested", { meta: { runId: input.runId } });
2336
+ else this.ctx.logger.warn("backup cancel: run unknown or already terminal", { meta: { runId: input.runId } });
2337
+ return { cancelled };
2338
+ }
2339
+ /**
2340
+ * Execute ONE backup run — only ever called by the queue, never
2341
+ * directly (the queue is the single serialisation authority).
2342
+ * Builds the archive in the private staging dir, then pushes it to
2343
+ * every selected destination via the storage cap's chunked upload
2344
+ * protocol. Per-destination errors are logged and recorded on the
2345
+ * run — one bad sink doesn't kill the run.
2346
+ *
2347
+ * Cleanup contract (D342): the staging file is deleted in `finally`,
2348
+ * which covers success, per-destination failure, build failure AND
2349
+ * cancellation alike. The only leak this cannot cover — the process
2350
+ * dying inside the run — is reclaimed by the boot sweep in
2351
+ * `cleanStagingArea`.
2352
+ */
2353
+ async runBackupBuild(input, signal, progress) {
2354
+ if (!this.systemBackup) throw new Error("orchestrator not initialized");
2355
+ const targets = await this.resolveTargets(input.destinations !== void 0 ? [...input.destinations] : void 0);
2356
+ if (targets.length === 0) {
2357
+ this.ctx.logger.warn("backup trigger: no destinations selected — this archive is being dropped", { meta: {
2358
+ requestedDestinationIds: input.destinations !== void 0 ? [...input.destinations] : [],
2359
+ label: input.label ?? null
2360
+ } });
2361
+ return [];
2362
+ }
2363
+ progress.setDestinations(targets.map((t) => t.id));
2364
+ const policies = await this.loadPoliciesIndexed(targets.map((t) => t.id));
2365
+ const encryptTo = await this.activeEncryptionKey();
2366
+ const archiveId = randomUUID();
2367
+ const archiveFilename = encryptTo === null ? `${archiveId}.tar.gz` : `${archiveId}.tar.gz${ENCRYPTED_BACKUP_SUFFIX}`;
2368
+ const cachePath = await this.stagingPath(archiveFilename);
2369
+ let result;
2370
+ try {
2371
+ result = await this.systemBackup.createArchive({
2372
+ archivePath: cachePath,
2373
+ ...input.locations ? { locations: [...input.locations] } : {},
2374
+ signal,
2375
+ onArchiveBytes: (bytes) => progress.setStagedBytes(bytes),
2376
+ owner: this.databaseOwner(),
2377
+ ...input.databases ? { databases: input.databases } : {},
2378
+ ...encryptTo !== null ? { encryptTo: encryptTo.publicKey } : {}
2379
+ });
2380
+ } catch (err) {
2381
+ if (err instanceof BackupSnapshotRefusedError) for (const dest of targets) {
2382
+ progress.destinationFailed(dest.id);
2383
+ await this.recordDestinationOutcome(dest.id, Date.now(), err.message);
2384
+ }
2385
+ throw err;
2386
+ }
2387
+ progress.setArchiveSize(result.sizeBytes);
2388
+ progress.setPhase("uploading");
2389
+ try {
2390
+ const entries = [];
2391
+ const createdAt = Date.now();
2392
+ for (const dest of targets) {
2393
+ if (signal.aborted) {
2394
+ this.ctx.logger.info("backup run cancelled — skipping remaining destinations", { meta: {
2395
+ runCancelledAfter: entries.length,
2396
+ skippedDestinationIds: targets.slice(targets.indexOf(dest)).map((t) => t.id)
2397
+ } });
2398
+ break;
2399
+ }
2400
+ try {
2401
+ const policy = policies.get(dest.id) ?? this.fallbackPolicy(dest.id);
2402
+ const stored = await this.uploadAndIndex({
2403
+ locationId: dest.id,
2404
+ archiveId,
2405
+ archiveFilename,
2406
+ cachePath,
2407
+ sizeBytes: result.sizeBytes,
2408
+ archiveManifest: result.manifest,
2409
+ retentionCount: input.retentionCount ?? policy.retentionCount,
2410
+ databases: input.databases ?? DEFAULT_BACKUP_DATABASES,
2411
+ createdAt,
2412
+ label: formatArchiveLabel(dest.id, createdAt, input.label),
2413
+ ...result.encryption !== void 0 ? { encryption: result.encryption } : {},
2414
+ signal,
2415
+ onUploadedBytes: (bytes) => progress.setUploadedBytes(bytes)
2416
+ });
2417
+ entries.push(stored);
2418
+ progress.destinationCompleted(dest.id);
2419
+ await this.recordDestinationOutcome(dest.id, createdAt);
2420
+ this.ctx.eventBus.emit({
2421
+ id: randomUUID(),
2422
+ timestamp: /* @__PURE__ */ new Date(),
2423
+ source: {
2424
+ type: "addon",
2425
+ id: "backup-orchestrator"
2426
+ },
2427
+ category: EventCategory.BackupCompleted,
2428
+ data: {
2429
+ destinationId: dest.id,
2430
+ backupId: stored.id,
2431
+ sizeMB: Math.round((stored.sizeBytes ?? 0) / (1024 * 1024))
2432
+ }
2433
+ });
2434
+ } catch (err) {
2435
+ if (err instanceof BackupCancelledError) continue;
2436
+ progress.destinationFailed(dest.id);
2437
+ const message = err instanceof Error ? err.message : String(err);
2438
+ this.ctx.logger.error("backup trigger: destination failed", { meta: {
2439
+ destinationId: dest.id,
2440
+ error: message
2441
+ } });
2442
+ await this.recordDestinationOutcome(dest.id, Date.now(), message);
2443
+ }
2444
+ }
2445
+ this.ctx.eventBus.emit({
2446
+ id: randomUUID(),
2447
+ timestamp: /* @__PURE__ */ new Date(),
2448
+ source: {
2449
+ type: "addon",
2450
+ id: "backup-orchestrator"
2451
+ },
2452
+ category: EventCategory.BackupRunCompleted,
2453
+ data: {
2454
+ destinationsOk: entries.length,
2455
+ destinationsFailed: Math.max(0, targets.length - entries.length),
2456
+ destinationsTotal: targets.length,
2457
+ sizeMB: Math.round(entries.reduce((acc, e) => acc + (e.sizeBytes ?? 0), 0) / (1024 * 1024)),
2458
+ ...entries[0]?.id === void 0 ? {} : { backupId: entries[0].id }
2459
+ }
2460
+ });
2461
+ return entries;
2462
+ } finally {
2463
+ try {
2464
+ await fsp.rm(cachePath, { force: true });
2465
+ } catch {}
2466
+ }
2467
+ }
2468
+ /**
2469
+ * THIS node's database owner (D693), reached through `database-snapshot`
2470
+ * pinned to the local node: the paths it answers must be on this host,
2471
+ * because this process archives them. No local node id means no pin, and an
2472
+ * unpinned singleton call could be answered by another host — refuse.
2473
+ */
2474
+ databaseOwner() {
2475
+ const pin = () => {
2476
+ const localNodeId = this.ctx.kernel.localNodeId;
2477
+ if (localNodeId === void 0 || localNodeId.length === 0) throw new Error("no local node id — the database owner cannot be pinned to this host");
2478
+ return nodePin(toNodeId(localNodeId));
2479
+ };
2480
+ return {
2481
+ listDatabases: async () => {
2482
+ return (await this.ctx.api.databaseSnapshot.listDatabases.query({}, pin())).databases;
2483
+ },
2484
+ writeSnapshot: async (databaseId) => this.ctx.api.databaseSnapshot.writeSnapshot.mutate({ databaseId }, pin())
2485
+ };
2486
+ }
2487
+ /**
2488
+ * Push the staged archive to a single destination via chunked
2489
+ * upload, then update the per-location manifest. Applies the
2490
+ * destination's retention policy as part of the same lock-protected
2491
+ * manifest mutation so the deletes never race with a concurrent
2492
+ * append.
2493
+ *
2494
+ * Throws on upload / manifest failure — caller logs and continues to
2495
+ * the next destination so a single bad sink doesn't fail the run.
2496
+ */
2497
+ async uploadAndIndex(input) {
2498
+ const { uploadId } = await this.ctx.api.storage.beginUpload.mutate({
2499
+ location: input.locationId,
2500
+ relativePath: input.archiveFilename,
2501
+ sizeBytes: input.sizeBytes
2502
+ });
2503
+ try {
2504
+ let offset = 0;
2505
+ const stream = fs$1.createReadStream(input.cachePath, { highWaterMark: UPLOAD_CHUNK_BYTES });
2506
+ for await (const rawChunk of stream) {
2507
+ if (input.signal?.aborted) {
2508
+ stream.destroy();
2509
+ throw new BackupCancelledError(`backup upload to ${input.locationId} cancelled mid-stream`);
2510
+ }
2511
+ const chunk = toBufferChunk(rawChunk);
2512
+ const data = new Uint8Array(chunk.byteLength);
2513
+ data.set(chunk);
2514
+ await this.ctx.api.storage.writeChunk.mutate({
2515
+ uploadId,
2516
+ offset,
2517
+ data
2518
+ });
2519
+ offset += data.byteLength;
2520
+ input.onUploadedBytes?.(offset);
2521
+ }
2522
+ await this.ctx.api.storage.finalizeUpload.mutate({ uploadId });
2523
+ } catch (err) {
2524
+ try {
2525
+ await this.ctx.api.storage.abortUpload.mutate({ uploadId });
2526
+ } catch {}
2527
+ throw err;
2528
+ }
2529
+ const entry = buildArchiveEntry({
2530
+ id: input.archiveId,
2531
+ filename: input.archiveFilename,
2532
+ createdAt: input.createdAt,
2533
+ sizeBytes: input.sizeBytes,
2534
+ label: input.label,
2535
+ manifest: input.archiveManifest,
2536
+ ...input.encryption !== void 0 ? { encryption: input.encryption } : {},
2537
+ databases: input.databases
2538
+ });
2539
+ await this.manifestLock.run(input.locationId, async () => {
2540
+ const { keep, drop } = applyRetention([...(await readLocationManifest(this.storageApi(), input.locationId)).archives, entry], input.retentionCount, retentionClassOf(entry));
2541
+ for (const stale of drop) try {
2542
+ await this.ctx.api.storage.delete.mutate({
2543
+ location: input.locationId,
2544
+ relativePath: stale.filename
2545
+ });
2546
+ } catch (err) {
2547
+ this.ctx.logger.warn("backup retention: storage delete failed (continuing)", { meta: {
2548
+ destinationId: input.locationId,
2549
+ backupId: stale.id,
2550
+ filename: stale.filename,
2551
+ error: err instanceof Error ? err.message : String(err)
2552
+ } });
2553
+ }
2554
+ const next = {
2555
+ version: 1,
2556
+ archives: keep
2557
+ };
2558
+ await writeLocationManifest(this.storageApi(), input.locationId, next);
2559
+ });
2560
+ return {
2561
+ id: input.archiveId,
2562
+ destinationId: input.locationId,
2563
+ createdAt: input.createdAt,
2564
+ sizeBytes: input.sizeBytes,
2565
+ label: input.label,
2566
+ locations: [...input.archiveManifest.locations],
2567
+ ...input.encryption !== void 0 ? { encryption: input.encryption } : {}
2568
+ };
2569
+ }
2570
+ /**
2571
+ * List archives at a single destination — newest-first. Reads only
2572
+ * the per-location `manifests.json` (no per-archive tarball read);
2573
+ * the orchestrator already snapshots each archive's locations into
2574
+ * the manifest at upload time.
2575
+ */
2576
+ async listArchives(input) {
2577
+ let manifest;
2578
+ try {
2579
+ manifest = await readLocationManifest(this.storageApi(), input.destinationId);
2580
+ } catch (err) {
2581
+ this.ctx.logger.warn("backup listArchives: manifest read failed", { meta: {
2582
+ destinationId: input.destinationId,
2583
+ error: err instanceof Error ? err.message : String(err)
2584
+ } });
2585
+ return [];
2586
+ }
2587
+ return [...manifest.archives].toSorted((a, b) => b.createdAt - a.createdAt).map((a) => ({
2588
+ id: a.id,
2589
+ filename: a.filename,
2590
+ createdAt: a.createdAt,
2591
+ sizeBytes: a.sizeBytes,
2592
+ ...a.label !== void 0 ? { label: a.label } : {},
2593
+ locations: [...a.manifest.locations],
2594
+ ...a.encryption !== void 0 ? { encryption: a.encryption } : {},
2595
+ ...a.databases !== void 0 ? { databases: [...a.databases] } : {}
2596
+ }));
2597
+ }
2598
+ /**
2599
+ * Upsert the per-destination policy row. Used by the admin-UI
2600
+ * destinations table — toggle enabled / change retention / set
2601
+ * label. No-ops with a logged warning if the
2602
+ * settings backend lacks structured-table support (no persistence
2603
+ * available).
2604
+ *
2605
+ * There is deliberately NO cadence here. A destination does not run on
2606
+ * its own timer — a schedule fans out to it — and the `cron` this method
2607
+ * used to accept had scheduled nothing since 2026-07-28 while still being
2608
+ * rendered as "daily at 03:00" (D384, and D62's "a switch that writes a
2609
+ * store nobody reads").
2610
+ */
2611
+ async upsertDestinationPolicy(input) {
2612
+ if (!this.policies) {
2613
+ this.ctx.logger.warn("backup upsertDestinationPolicy: no ctx.records — change will not persist", { meta: { locationId: input.locationId } });
2614
+ return;
2615
+ }
2616
+ const existing = await this.policies.get(input.locationId).catch(() => null);
2617
+ await this.policies.upsert({
2618
+ locationId: input.locationId,
2619
+ enabled: input.enabled,
2620
+ retentionCount: input.retentionCount,
2621
+ ...input.label !== void 0 ? { label: input.label } : {},
2622
+ ...existing?.lastAttemptAt !== void 0 ? { lastAttemptAt: existing.lastAttemptAt } : {},
2623
+ ...existing?.lastError !== void 0 ? { lastError: existing.lastError } : {}
2624
+ });
2625
+ }
2626
+ /**
2627
+ * Validate a cron expression and peek the next N firing times. The
2628
+ * admin UI's CronEditor calls this on every keystroke (debounced)
2629
+ * to render a live "next-run" preview — invalid expressions surface
2630
+ * the parse error inline instead of waiting for save.
2631
+ */
2632
+ async previewSchedule(input) {
2633
+ const trimmed = input.cron.trim();
2634
+ if (trimmed.length === 0) return {
2635
+ ok: false,
2636
+ error: "Cron expression is empty",
2637
+ nextRuns: []
2638
+ };
2639
+ try {
2640
+ return {
2641
+ ok: true,
2642
+ nextRuns: previewNextRuns(trimmed, input.count ?? 5)
2643
+ };
2644
+ } catch (err) {
2645
+ return {
2646
+ ok: false,
2647
+ error: err instanceof Error ? err.message : "Invalid cron expression",
2648
+ nextRuns: []
2649
+ };
2650
+ }
2651
+ }
2652
+ async getEntries(input) {
2653
+ try {
2654
+ return (await readLocationManifest(this.storageApi(), input.destinationId)).archives.find((a) => a.id === input.backupId)?.manifest ?? null;
2655
+ } catch (err) {
2656
+ this.ctx.logger.warn("backup getEntries: manifest read failed", { meta: {
2657
+ destinationId: input.destinationId,
2658
+ backupId: input.backupId,
2659
+ error: err instanceof Error ? err.message : String(err)
2660
+ } });
2661
+ return null;
2662
+ }
2663
+ }
2664
+ async deleteArchive(input) {
2665
+ await this.manifestLock.run(input.destinationId, async () => {
2666
+ const manifest = await readLocationManifest(this.storageApi(), input.destinationId);
2667
+ const target = manifest.archives.find((a) => a.id === input.backupId);
2668
+ if (!target) throw new Error(`backup delete: backup "${input.backupId}" not found at "${input.destinationId}"`);
2669
+ try {
2670
+ await this.ctx.api.storage.delete.mutate({
2671
+ location: input.destinationId,
2672
+ relativePath: target.filename
2673
+ });
2674
+ } catch (err) {
2675
+ this.ctx.logger.warn("backup delete: storage delete failed (continuing manifest cleanup)", { meta: {
2676
+ destinationId: input.destinationId,
2677
+ filename: target.filename,
2678
+ error: err instanceof Error ? err.message : String(err)
2679
+ } });
2680
+ }
2681
+ const next = {
2682
+ version: 1,
2683
+ archives: manifest.archives.filter((a) => a.id !== input.backupId)
2684
+ };
2685
+ await writeLocationManifest(this.storageApi(), input.destinationId, next);
2686
+ });
2687
+ }
2688
+ /**
2689
+ * Schedule a restore for the next boot. Pulls the archive bytes
2690
+ * down from the destination's storage location via the chunked-
2691
+ * download protocol into the private staging dir, then writes the
2692
+ * usual restore marker against the staged path so the boot-time
2693
+ * apply hook (in server-backend launcher) extracts before any
2694
+ * addon starts.
2695
+ *
2696
+ * `locations` (optional) is propagated into the marker as a
2697
+ * whitelist — only those top-level locations get extracted.
2698
+ */
2699
+ async scheduleRestore(input) {
2700
+ if (!this.systemBackup) throw new Error("orchestrator not initialized");
2701
+ const entry = (await readLocationManifest(this.storageApi(), input.destinationId)).archives.find((a) => a.id === input.backupId);
2702
+ if (!entry) throw new Error(`backup restore: backup "${input.backupId}" not found at location "${input.destinationId}"`);
2703
+ precheckRestoreKey(entry.encryption?.keyId, input.backupSecretKey);
2704
+ const downloaded = await this.stagingPath(`restore-${input.backupId}.download`);
2705
+ const cachePath = await this.stagingPath(`restore-${input.backupId}.tar.gz`);
2706
+ await downloadArchiveToCache({
2707
+ api: this.ctx.api.storage,
2708
+ locationId: input.destinationId,
2709
+ filename: entry.filename,
2710
+ cachePath: downloaded,
2711
+ chunkBytes: UPLOAD_CHUNK_BYTES,
2712
+ logger: this.ctx.logger
2713
+ });
2714
+ const prepared = await prepareRestoreArchive({
2715
+ downloaded,
2716
+ target: cachePath,
2717
+ ...input.backupSecretKey !== void 0 ? { secretKey: input.backupSecretKey } : {}
2718
+ });
2719
+ if (prepared.encrypted) this.ctx.logger.info("backup restore: encrypted archive decrypted into staging", { meta: {
2720
+ backupId: input.backupId,
2721
+ keyId: prepared.keyId
2722
+ } });
2723
+ this.systemBackup.scheduleRestoreMarker({
2724
+ archivePath: cachePath,
2725
+ source: input.backupId,
2726
+ ...input.locations ? { locations: input.locations } : {}
2727
+ });
2728
+ this.ctx.eventBus.emit({
2729
+ id: randomUUID(),
2730
+ timestamp: /* @__PURE__ */ new Date(),
2731
+ source: {
2732
+ type: "addon",
2733
+ id: "backup-orchestrator"
2734
+ },
2735
+ category: EventCategory.BackupRestored,
2736
+ data: {
2737
+ backupId: input.backupId,
2738
+ destinationId: input.destinationId
2739
+ }
2740
+ });
2741
+ }
2742
+ requireEncryptionKeys() {
2743
+ if (this.encryptionKeys === null) throw new Error("backup encryption: no settings-store — the setting cannot be read or saved");
2744
+ return this.encryptionKeys;
2745
+ }
2746
+ /**
2747
+ * The key a run encrypts to; `null` = encryption off. THROWS when the
2748
+ * setting cannot be read — a run must fail rather than ship a plain archive
2749
+ * an operator asked to be encrypted.
2750
+ */
2751
+ async activeEncryptionKey() {
2752
+ const store = this.encryptionKeys;
2753
+ if (store === null) {
2754
+ if (!this.warnedNoEncryptionStore) {
2755
+ this.warnedNoEncryptionStore = true;
2756
+ this.ctx.logger.warn("backup encryption unavailable on this node (no settings-store) — archives are plain");
2757
+ }
2758
+ return null;
2759
+ }
2760
+ try {
2761
+ const active = await store.active();
2762
+ return active === null ? null : {
2763
+ keyId: active.keyId,
2764
+ publicKey: active.publicKey
2765
+ };
2766
+ } catch (err) {
2767
+ const message = err instanceof Error ? err.message : String(err);
2768
+ throw new Error(`backup encryption setting unreadable — no archive built, so none leaves unencrypted: ${message}`, { cause: err });
2769
+ }
2770
+ }
2771
+ async getEncryption() {
2772
+ const keys = await this.requireEncryptionKeys().list();
2773
+ const active = keys.find((k) => k.retiredAt === null) ?? null;
2774
+ return {
2775
+ enabled: active !== null,
2776
+ active: active === null ? null : {
2777
+ keyId: active.keyId,
2778
+ publicKey: active.publicKey,
2779
+ createdAt: active.createdAt
2780
+ },
2781
+ keys: keys.map((k) => ({
2782
+ keyId: k.keyId,
2783
+ createdAt: k.createdAt,
2784
+ retiredAt: k.retiredAt
2785
+ }))
2786
+ };
2787
+ }
2788
+ async setupEncryption() {
2789
+ const store = this.requireEncryptionKeys();
2790
+ const previous = await store.active();
2791
+ const pair = generateBackupKeyPair();
2792
+ const record = await store.activate({ publicKey: pair.publicKey });
2793
+ this.ctx.logger.warn("backup encryption key generated — new archives are encrypted to it", { meta: {
2794
+ keyId: record.keyId,
2795
+ replacedKeyId: previous?.keyId ?? null
2796
+ } });
2797
+ return {
2798
+ keyId: record.keyId,
2799
+ secretKey: pair.secretKey,
2800
+ publicKey: record.publicKey,
2801
+ createdAt: record.createdAt,
2802
+ replacedKeyId: previous?.keyId ?? null
2803
+ };
2804
+ }
2805
+ async disableEncryption() {
2806
+ const store = this.requireEncryptionKeys();
2807
+ const previous = await store.active();
2808
+ await store.disable();
2809
+ if (previous !== null) this.ctx.logger.warn("backup encryption turned OFF — new archives are plain", { meta: { disabledKeyId: previous.keyId } });
2810
+ return { disabledKeyId: previous?.keyId ?? null };
2811
+ }
2812
+ async checkBackupKey(input) {
2813
+ let keyId;
2814
+ try {
2815
+ keyId = parseBackupSecretKey(input.backupSecretKey).keyId;
2816
+ } catch (err) {
2817
+ if (!(err instanceof BackupKeyFormatError)) throw err;
2818
+ return {
2819
+ valid: false,
2820
+ keyId: null,
2821
+ known: false,
2822
+ active: false,
2823
+ error: err.message
2824
+ };
2825
+ }
2826
+ const match = (await this.requireEncryptionKeys().list()).find((k) => k.keyId === keyId);
2827
+ return {
2828
+ valid: true,
2829
+ keyId,
2830
+ known: match !== void 0,
2831
+ active: match !== void 0 && match.retiredAt === null
2832
+ };
2833
+ }
2834
+ /**
2835
+ * Resolve a target destination set — see {@link selectBackupTargets} for the
2836
+ * rule. Caller-provided list wins over the per-destination policy flag;
2837
+ * NEITHER wins over `StorageLocation.enabled`, which is the operator's
2838
+ * switch on the storage screen and the only one that means "this disk takes
2839
+ * no writes" (D62).
2840
+ *
2841
+ * Reads locations + policies directly rather than going through
2842
+ * `listDestinations()`: that method also reads every destination's
2843
+ * `manifests.json` to hydrate `lastSuccess`, which target resolution has no
2844
+ * use for and which cost one round-trip per destination on every trigger.
2845
+ */
2846
+ async resolveTargets(requested) {
2847
+ const locations = await this.fetchBackupLocations();
2848
+ const policies = await this.loadPoliciesIndexed(locations.map((l) => l.id));
2849
+ const selection = selectBackupTargets({
2850
+ candidates: locations.map((l) => ({
2851
+ id: l.id,
2852
+ locationEnabled: mayWriteToLocation(l),
2853
+ policyEnabled: (policies.get(l.id) ?? this.fallbackPolicy(l.id)).enabled
2854
+ })),
2855
+ ...requested && requested.length > 0 ? { requested: [...requested] } : {}
2856
+ });
2857
+ if (selection.skippedDisabled.length > 0) this.ctx.logger.warn("backup: destination skipped — its storage location is disabled by the operator", { meta: {
2858
+ destinationIds: [...selection.skippedDisabled],
2859
+ requestedExplicitly: requested !== void 0 && requested.length > 0
2860
+ } });
2861
+ if (selection.targets.length === 0 && selection.skippedDisabled.length > 0) throw new Error(`every selected backup destination is disabled (${selection.skippedDisabled.join(", ")}) — enable its storage location on the Storage screen, or choose another destination. Refusing to write an archive to a location the operator turned off.`);
2862
+ return selection.targets.map((t) => ({ id: t.id }));
2863
+ }
2864
+ /**
2865
+ * Persist the outcome of one attempted write to one destination.
2866
+ *
2867
+ * Best-effort by design: an unavailable settings backend must not turn a
2868
+ * successful backup into a failed one. But it is LOGGED when it cannot be
2869
+ * written — a status field that silently stops being updated is the whole
2870
+ * defect this method exists to close.
2871
+ */
2872
+ async recordDestinationOutcome(destinationId, attemptAt, error) {
2873
+ if (!this.policies) return;
2874
+ try {
2875
+ await this.policies.recordAttempt(destinationId, {
2876
+ attemptAt,
2877
+ ...error !== void 0 ? { error } : {}
2878
+ }, { retentionCount: DEFAULT_RETENTION_COUNT });
2879
+ } catch (err) {
2880
+ this.ctx.logger.warn("backup: could not persist the destination outcome", { meta: {
2881
+ destinationId,
2882
+ outcome: error === void 0 ? "succeeded" : "failed",
2883
+ error: err instanceof Error ? err.message : String(err)
2884
+ } });
2885
+ }
2886
+ }
2887
+ startScheduleTimer() {
2888
+ if (this.scheduleTimer) return;
2889
+ this.scheduleTimer = setInterval(() => {
2890
+ this.onScheduleTick();
2891
+ }, SCHEDULE_TICK_MS);
2892
+ }
2893
+ stopScheduleTimer() {
2894
+ if (!this.scheduleTimer) return;
2895
+ clearInterval(this.scheduleTimer);
2896
+ this.scheduleTimer = null;
2897
+ }
2898
+ /**
2899
+ * Schedule-driven backup scheduling. Walks every enabled backup
2900
+ * SCHEDULE (the N:M entry), computes the next due time after
2901
+ * `lastAttemptAt` (or the orchestrator's first-tick baseline if never
2902
+ * run), and fires a SINGLE archive fanned out to ALL of the
2903
+ * schedule's `locationIds` when due — with the schedule's per-entry
2904
+ * retention applied to each. Each schedule keeps its own cadence.
2905
+ *
2906
+ * Errors per schedule are isolated; one misconfigured cron doesn't
2907
+ * block the others. The schedule's `lastAttemptAt` is updated BEFORE the
2908
+ * trigger to dedupe (the tick runs every SCHEDULE_TICK_MS — without
2909
+ * the up-front update a long-running upload could overlap with the
2910
+ * next tick's same-due check).
2911
+ */
2912
+ async onScheduleTick() {
2913
+ if (!this.schedules) {
2914
+ if (!this.warnedSchedulerDisarmed) {
2915
+ this.warnedSchedulerDisarmed = true;
2916
+ this.ctx.logger.error("backup scheduler is DISARMED — no settings backend, so no schedule can fire");
2917
+ }
2918
+ return;
2919
+ }
2920
+ const schedules = await this.schedules.list();
2921
+ const now = Date.now();
2922
+ for (const s of schedules) {
2923
+ if (!s.enabled || !s.cron || s.cron.trim().length === 0) continue;
2924
+ if (s.locationIds.length === 0) continue;
2925
+ let due;
2926
+ try {
2927
+ due = computeNextDue(s.cron, s.lastAttemptAt ?? this.scheduleBaselineAt);
2928
+ } catch (err) {
2929
+ this.ctx.logger.warn("Invalid cron — skipping schedule", { meta: {
2930
+ scheduleId: s.id,
2931
+ cron: s.cron,
2932
+ error: err instanceof Error ? err.message : String(err)
2933
+ } });
2934
+ continue;
2935
+ }
2936
+ if (due === null || due > now) continue;
2937
+ const stamped = {
2938
+ ...s,
2939
+ lastAttemptAt: now
2940
+ };
2941
+ try {
2942
+ await this.schedules.upsert(stamped);
2943
+ } catch (err) {
2944
+ this.ctx.logger.warn("Failed to persist scheduled-run timestamp", { meta: {
2945
+ scheduleId: s.id,
2946
+ scheduleLabel: s.label,
2947
+ destinationIds: [...s.locationIds],
2948
+ error: err instanceof Error ? err.message : String(err)
2949
+ } });
2950
+ }
2951
+ this.ctx.logger.info("Scheduled backup firing", { meta: {
2952
+ scheduleId: s.id,
2953
+ label: s.label,
2954
+ destinationIds: [...s.locationIds],
2955
+ cron: s.cron,
2956
+ dueAt: due
2957
+ } });
2958
+ await this.runScheduledBackup(stamped, now);
2959
+ }
2960
+ }
2961
+ /**
2962
+ * A schedule that asks for events/history while the owner has neither open
2963
+ * would only repeat the nightly archive (D852: the weekly schedule has
2964
+ * nothing to carry until those files exist). Said on the record, no archive
2965
+ * built, no outcome stamped. An owner that cannot answer never skips: the
2966
+ * run goes ahead and fails — or succeeds — in the open.
2967
+ */
2968
+ async nothingToCarry(schedule) {
2969
+ const requested = databasesOfSchedule(schedule);
2970
+ if (!requested.some((id) => id !== "settings")) return false;
2971
+ let owned;
2972
+ try {
2973
+ owned = (await this.databaseOwner().listDatabases()).map((d) => d.databaseId);
2974
+ } catch (err) {
2975
+ this.ctx.logger.warn("Scheduled backup: the database owner did not answer — running anyway", { meta: {
2976
+ scheduleId: schedule.id,
2977
+ label: schedule.label,
2978
+ error: err instanceof Error ? err.message : String(err)
2979
+ } });
2980
+ return false;
2981
+ }
2982
+ if (!hasNothingBeyondSettings(requested, owned)) return false;
2983
+ this.ctx.logger.info("Scheduled backup skipped — no database it carries exists yet", { meta: {
2984
+ scheduleId: schedule.id,
2985
+ label: schedule.label,
2986
+ requested: [...requested],
2987
+ owned
2988
+ } });
2989
+ return true;
2990
+ }
2991
+ /**
2992
+ * Seed the weekly "events & history" schedule (D852) — once, and never over
2993
+ * anything the operator has: see `planWeeklySeed`.
2994
+ */
2995
+ async seedWeekly() {
2996
+ const markers = this.backupRecords?.seedMarkers;
2997
+ if (!this.schedules || markers === void 0) return;
2998
+ try {
2999
+ const seed = await seedWeeklySchedule(this.schedules, new BackupSeedMarkerStore(markers));
3000
+ if (seed === null) return;
3001
+ this.ctx.logger.info("backup: seeded the weekly events & history schedule", { meta: {
3002
+ scheduleId: seed.id,
3003
+ destinationIds: [...seed.locationIds]
3004
+ } });
3005
+ } catch (err) {
3006
+ this.ctx.logger.warn("backup: the weekly schedule could not be seeded", { meta: { error: err instanceof Error ? err.message : String(err) } });
3007
+ }
3008
+ }
3009
+ /**
3010
+ * Fire one schedule and RECORD what happened to it, naming every
3011
+ * destination. Three outcomes, three different persisted states —
3012
+ * because "fired" and "backed up" were the same field until D384:
3013
+ *
3014
+ * - archive landed somewhere → `lastSuccessAt`, `lastError` cleared;
3015
+ * - the run threw, or landed nowhere → `lastError`, no success stamp;
3016
+ * - the stamp could not be written → logged, named, not swallowed.
3017
+ */
3018
+ async runScheduledBackup(schedule, firedAt) {
3019
+ const destinationIds = [...schedule.locationIds];
3020
+ if (await this.nothingToCarry(schedule)) return;
3021
+ let failure;
3022
+ try {
3023
+ const result = await this.triggerBackup({
3024
+ destinations: destinationIds,
3025
+ ...schedule.dataSources && schedule.dataSources.length > 0 ? { locations: [...schedule.dataSources] } : {},
3026
+ label: schedule.label,
3027
+ retentionCount: schedule.retentionCount,
3028
+ ...schedule.databases ? { databases: [...schedule.databases] } : {}
3029
+ });
3030
+ if (result.entries.length === 0 && !result.cancelled) failure = `no destination accepted the archive (${destinationIds.join(", ")})`;
3031
+ } catch (err) {
3032
+ failure = err instanceof Error ? err.message : String(err);
3033
+ }
3034
+ if (failure === void 0) this.ctx.logger.info("Scheduled backup completed", { meta: {
3035
+ scheduleId: schedule.id,
3036
+ label: schedule.label,
3037
+ destinationIds
3038
+ } });
3039
+ else this.ctx.logger.error("Scheduled backup failed", { meta: {
3040
+ scheduleId: schedule.id,
3041
+ label: schedule.label,
3042
+ destinationIds,
3043
+ error: failure
3044
+ } });
3045
+ if (!this.schedules) return;
3046
+ const { lastError: _cleared, ...carried } = schedule;
3047
+ try {
3048
+ await this.schedules.upsert({
3049
+ ...carried,
3050
+ ...failure === void 0 ? { lastSuccessAt: firedAt } : { lastError: failure }
3051
+ });
3052
+ } catch (err) {
3053
+ this.ctx.logger.warn("Failed to persist the scheduled-run outcome", { meta: {
3054
+ scheduleId: schedule.id,
3055
+ label: schedule.label,
3056
+ destinationIds,
3057
+ error: err instanceof Error ? err.message : String(err)
3058
+ } });
3059
+ }
3060
+ }
3061
+ /**
3062
+ * The database files the owner has open right now, for the selection UI. An
3063
+ * owner that cannot answer is `answered: false` — never an empty list, which
3064
+ * the UI would read as "none exists yet".
3065
+ */
3066
+ async listAvailableDatabases() {
3067
+ try {
3068
+ return {
3069
+ answered: true,
3070
+ databases: (await this.databaseOwner().listDatabases()).map((d) => d.databaseId)
3071
+ };
3072
+ } catch (err) {
3073
+ this.ctx.logger.warn("Backup database list: the database owner did not answer", { meta: { error: err instanceof Error ? err.message : String(err) } });
3074
+ return {
3075
+ answered: false,
3076
+ databases: []
3077
+ };
3078
+ }
3079
+ }
3080
+ async listSchedules() {
3081
+ if (!this.schedules) return [];
3082
+ return (await this.schedules.list()).map((s) => {
3083
+ let nextRunAt;
3084
+ if (s.enabled && s.cron.trim().length > 0) try {
3085
+ const next = computeNextDue(s.cron, Date.now());
3086
+ if (next !== null) nextRunAt = next;
3087
+ } catch {}
3088
+ return {
3089
+ id: s.id,
3090
+ label: s.label,
3091
+ cron: s.cron,
3092
+ enabled: s.enabled,
3093
+ locationIds: [...s.locationIds],
3094
+ retentionCount: s.retentionCount,
3095
+ ...s.dataSources !== void 0 ? { dataSources: [...s.dataSources] } : {},
3096
+ ...s.databases !== void 0 ? { databases: [...s.databases] } : {},
3097
+ ...s.lastAttemptAt !== void 0 ? { lastAttemptAt: s.lastAttemptAt } : {},
3098
+ ...s.lastSuccessAt !== void 0 ? { lastSuccessAt: s.lastSuccessAt } : {},
3099
+ ...s.lastError !== void 0 ? { lastError: s.lastError } : {},
3100
+ ...nextRunAt !== void 0 ? { nextRunAt } : {}
3101
+ };
3102
+ });
3103
+ }
3104
+ async upsertSchedule(input) {
3105
+ if (!this.schedules) throw new Error("backup upsertSchedule: no ctx.records — schedule cannot be persisted");
3106
+ const cron = input.cron.trim();
3107
+ if (cron.length > 0 && !isValidCron(cron)) throw new Error(`Invalid cron expression: "${cron}"`);
3108
+ const id = input.id && input.id.length > 0 ? input.id : randomUUID();
3109
+ const existing = await this.schedules.get(id).catch(() => null);
3110
+ const next = {
3111
+ id,
3112
+ label: input.label,
3113
+ cron,
3114
+ enabled: input.enabled,
3115
+ locationIds: [...input.locationIds],
3116
+ retentionCount: input.retentionCount,
3117
+ ...input.dataSources && input.dataSources.length > 0 ? { dataSources: [...input.dataSources] } : {},
3118
+ ...input.databases && input.databases.length > 0 ? { databases: [...input.databases] } : {},
3119
+ ...existing?.lastAttemptAt !== void 0 ? { lastAttemptAt: existing.lastAttemptAt } : {},
3120
+ ...existing?.lastSuccessAt !== void 0 ? { lastSuccessAt: existing.lastSuccessAt } : {},
3121
+ ...existing?.lastError !== void 0 ? { lastError: existing.lastError } : {}
3122
+ };
3123
+ await this.schedules.upsert(next);
3124
+ let nextRunAt;
3125
+ if (next.enabled && cron.length > 0) try {
3126
+ const due = computeNextDue(cron, Date.now());
3127
+ if (due !== null) nextRunAt = due;
3128
+ } catch {}
3129
+ return {
3130
+ id: next.id,
3131
+ label: next.label,
3132
+ cron: next.cron,
3133
+ enabled: next.enabled,
3134
+ locationIds: [...next.locationIds],
3135
+ retentionCount: next.retentionCount,
3136
+ ...next.dataSources !== void 0 ? { dataSources: [...next.dataSources] } : {},
3137
+ ...next.databases !== void 0 ? { databases: [...next.databases] } : {},
3138
+ ...next.lastAttemptAt !== void 0 ? { lastAttemptAt: next.lastAttemptAt } : {},
3139
+ ...next.lastSuccessAt !== void 0 ? { lastSuccessAt: next.lastSuccessAt } : {},
3140
+ ...next.lastError !== void 0 ? { lastError: next.lastError } : {},
3141
+ ...nextRunAt !== void 0 ? { nextRunAt } : {}
3142
+ };
3143
+ }
3144
+ async deleteSchedule(input) {
3145
+ if (!this.schedules) return;
3146
+ await this.schedules.delete(input.id);
3147
+ }
3148
+ /**
3149
+ * Narrow `ctx.api.storage` to the subset the manifest helpers need.
3150
+ * Lets the helpers be unit-tested with a Map-backed fake without
3151
+ * pulling in the full `AddonApi` shape.
3152
+ */
3153
+ storageApi() {
3154
+ return this.ctx.api.storage;
3155
+ }
3156
+ };
3157
+ /**
3158
+ * Map a `storage-provider` providerId to an operator-friendly `kind`
3159
+ * the admin UI uses for destination cards. Falls back to the raw
3160
+ * provider id so unknown providers still surface (operator sees
3161
+ * `webdav-storage` instead of a blank slot).
3162
+ */
3163
+ function kindFromProviderId(providerId) {
3164
+ switch (providerId) {
3165
+ case "filesystem-storage": return "local";
3166
+ case "s3-storage": return "s3";
3167
+ case "sftp-storage": return "sftp";
3168
+ case "webdav-storage": return "webdav";
3169
+ default: return providerId;
3170
+ }
3171
+ }
3172
+ /**
3173
+ * Extract the slug part of a `<type>:<slug>` storage-location id.
3174
+ * Defensive: if the id doesn't contain a colon (shouldn't happen given
3175
+ * the regex on `StorageLocationSchema.id`) we return the whole string.
3176
+ */
3177
+ function extractSlug(id) {
3178
+ const colon = id.indexOf(":");
3179
+ return colon < 0 ? id : id.slice(colon + 1);
3180
+ }
3181
+ /**
3182
+ * Narrow a `for await` chunk from `fs.createReadStream` to a
3183
+ * `Buffer`. The stream yields `string | Buffer` per its public type
3184
+ * even though the no-encoding overload always emits `Buffer`. The
3185
+ * runtime check + clear error keeps eslint's no-unsafe-* rules happy
3186
+ * without resorting to `as Buffer`.
3187
+ */
3188
+ function toBufferChunk(value) {
3189
+ if (Buffer.isBuffer(value)) return value;
3190
+ if (value instanceof Uint8Array) return value;
3191
+ throw new Error("backup upload: unexpected non-binary chunk from read stream");
3192
+ }
3193
+ /**
3194
+ * Return the most-recent archive in a location manifest, or undefined
3195
+ * when the location has no archives yet. Pure transform — no I/O.
3196
+ */
3197
+ function latestArchiveOf(manifest) {
3198
+ if (manifest.archives.length === 0) return void 0;
3199
+ let newest = manifest.archives[0];
3200
+ for (const a of manifest.archives) if (a.createdAt > newest.createdAt) newest = a;
3201
+ return newest;
3202
+ }
3203
+ //#endregion
3204
+ export { BackupOrchestratorAddon, BackupOrchestratorAddon as default };