@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,2952 @@
1
+ import { $i as storageAdminCapability, A as DATABASE_SNAPSHOT_PARTIAL_SUFFIX, Ao as UnknownRecordKindError, Bo as collectSecretMarkerRefs, In as dataStoreProviderCapability, Ln as databaseSnapshotCapability, M as DATABASE_SNAPSHOT_TIMEOUT_MS, Ms as EventCategory, N as DATA_STORE_DATABASES, Oo as TransactRefusedError, Qa as BaseAddon, Uo as customAction, Wo as defineCustomActions, Yr as migrationsCapability, co as InvalidRecordError, ds as normalizeSecretOwner, ga as vectorStoreCapability, ho as RECORD_SWEEP_INTERVAL_MS, io as DeclarationRefusedError, j as DATABASE_SNAPSHOT_SUFFIX, js as errMsg$1, lo as NoCallerError, on as bareAddonId, si as orderMigrations, vn as catalogueIssues, vo as RUNTIME_DEFAULTS, xi as recordsCapability, xo as RecordKindDeclarationSchema, yt as MigrationMetaSchema } from "../../dist-DcMqHB_N.mjs";
2
+ import { r as retiredKeyStoreOf, t as purgeRetiredSettingsKeys } from "../../retired-settings-keys-u6xQA6r7.mjs";
3
+ import { A as callRecords, D as RecordsEngine, E as databaseOfStore, M as controlTargetOf, O as callControl, T as trustResult, _ as rehydrateError, a as WalMaintenance, b as collectTransferables, c as vectorProviderOfOwnedFile, d as callMigrate, f as migrateTargetOf, g as DuplicatePlacementError, h as DatabaseBusyError, j as callVector, k as callData, l as SqliteSettingsBackend, m as CrossDatabaseTransactError, o as createVectorIndex, p as CollectionPlacementError, s as vectorProviderOf, u as HUB_MIGRATIONS, x as isFileHostMessage } from "../../wal-maintenance-Bnb2QzYG.mjs";
4
+ import { r as isSnapshotWorkerMessage } from "../../sqlite-snapshot-protocol-2QaTouWV.mjs";
5
+ import { a as isWorkerMessage, t as WAL_CHECKPOINT_LARGE_PASS_FRAMES } from "../../wal-checkpoint-policy-BahrTtyD.mjs";
6
+ import { createRequire } from "node:module";
7
+ import { z } from "zod";
8
+ import { randomUUID } from "node:crypto";
9
+ import { mkdir } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { existsSync, promises, readFileSync, statSync } from "node:fs";
12
+ import { Worker } from "node:worker_threads";
13
+ //#region src/builtins/sqlite-storage/file-host-client.ts
14
+ /**
15
+ * The main thread's side of a file-host worker: spawns the thread, correlates
16
+ * requests with answers, bounds what is in flight, writes the thread's log
17
+ * lines through the runner's logger, and turns a thread that dies into a dead
18
+ * runner (D5, D6) — never into a half-working one.
19
+ */
20
+ /** Where the built worker entry lives (`dist/file-host-worker.js`, next to the checkpoint worker). */
21
+ function defaultFileHostWorkerPath() {
22
+ const require_ = createRequire(import.meta.url);
23
+ const packageRoot = path.dirname(require_.resolve("@camstack/server/system/package.json"));
24
+ return path.join(packageRoot, "dist", "file-host-worker.js");
25
+ }
26
+ /** How long a stopped thread has to end on its own before it is terminated. */
27
+ var FILE_HOST_EXIT_GRACE_MS = 5e3;
28
+ var FileHostClient = class {
29
+ spec;
30
+ logger;
31
+ onFatal;
32
+ maxInFlight;
33
+ now;
34
+ thread;
35
+ pending = /* @__PURE__ */ new Map();
36
+ nextId = 1;
37
+ lastOp = "(none yet)";
38
+ stopping = false;
39
+ /** Settles when the thread's event loop has ended and its isolate is gone. */
40
+ exited;
41
+ dead = false;
42
+ lastBusyLogAt = -Infinity;
43
+ declared = /* @__PURE__ */ new Set();
44
+ bootSettled = null;
45
+ constructor(options) {
46
+ this.spec = options.spec;
47
+ this.logger = options.logger.child(`Db/${options.spec.databaseId}`);
48
+ this.onFatal = options.onFatal;
49
+ this.maxInFlight = options.maxInFlight ?? 512;
50
+ this.now = options.now ?? (() => Date.now());
51
+ const workerPath = options.workerPath ?? null;
52
+ const execArgv = options.workerExecArgv;
53
+ const spawn = options.threadFactory ?? ((data) => {
54
+ return new Worker(workerPath ?? defaultFileHostWorkerPath(), {
55
+ workerData: data,
56
+ ...execArgv !== void 0 ? { execArgv: [...execArgv] } : {}
57
+ });
58
+ });
59
+ this.thread = spawn({
60
+ kind: "file-host",
61
+ spec: options.spec
62
+ });
63
+ this.thread.on("message", (message) => this.onMessage(message));
64
+ this.thread.on("error", (err) => this.die(`worker error: ${errMsg$1(err)}`));
65
+ this.exited = new Promise((resolve) => {
66
+ this.thread.on("exit", () => resolve());
67
+ });
68
+ this.thread.on("exit", (code) => {
69
+ if (this.stopping) {
70
+ for (const pending of this.pending.values()) if (pending.op === "stop") pending.resolve(void 0);
71
+ return;
72
+ }
73
+ this.die(`worker exited with code ${code}`);
74
+ });
75
+ }
76
+ /** Resolves once the thread has opened its file; rejects if it could not. */
77
+ ready() {
78
+ return new Promise((resolve, reject) => {
79
+ this.bootSettled = {
80
+ resolve,
81
+ reject
82
+ };
83
+ });
84
+ }
85
+ /** The collections this file's own declarations table names (updated as declarations land). */
86
+ declaredCollections() {
87
+ return this.declared;
88
+ }
89
+ noteDeclared(table) {
90
+ this.declared = new Set([...this.declared, table]);
91
+ }
92
+ data(op, input) {
93
+ return this.request({
94
+ kind: "data",
95
+ op,
96
+ input
97
+ });
98
+ }
99
+ vector(op, input) {
100
+ return this.request({
101
+ kind: "vector",
102
+ op,
103
+ input
104
+ });
105
+ }
106
+ records(op, input) {
107
+ return this.request({
108
+ kind: "records",
109
+ op,
110
+ input
111
+ });
112
+ }
113
+ control(op, input) {
114
+ return this.request({
115
+ kind: "control",
116
+ op,
117
+ input
118
+ });
119
+ }
120
+ /** A boot-time migration question (D987), answered by the thread that holds the connection. */
121
+ migrate(op, input) {
122
+ return this.request({
123
+ kind: "migrate",
124
+ op,
125
+ input
126
+ });
127
+ }
128
+ /** Ask the thread to close its connection, then end it. */
129
+ async stop() {
130
+ if (this.dead || this.stopping) return;
131
+ this.stopping = true;
132
+ try {
133
+ await new Promise((resolve, reject) => {
134
+ const id = this.nextId++;
135
+ this.pending.set(id, {
136
+ op: "stop",
137
+ resolve: () => resolve(),
138
+ reject
139
+ });
140
+ this.thread.postMessage({
141
+ id,
142
+ kind: "stop"
143
+ });
144
+ });
145
+ } finally {
146
+ await this.awaitExit();
147
+ }
148
+ }
149
+ /**
150
+ * Let the thread END ITSELF after it answered `stop`: it has closed every
151
+ * statement and the connection and closed its port, so its loop drains and
152
+ * the isolate is disposed from inside. `terminate()` straight after the
153
+ * answer races that disposal and, on macOS, took the whole process down with
154
+ * a SIGSEGV in the isolate's teardown GC. Terminate is only the fallback for
155
+ * a thread that does not leave in time.
156
+ */
157
+ async awaitExit() {
158
+ let timer;
159
+ const timedOut = new Promise((resolve) => {
160
+ timer = setTimeout(() => resolve("timeout"), FILE_HOST_EXIT_GRACE_MS);
161
+ });
162
+ const outcome = await Promise.race([this.exited.then(() => "exited"), timedOut]);
163
+ if (timer !== void 0) clearTimeout(timer);
164
+ if (outcome === "timeout") {
165
+ this.logger.warn("database worker did not leave after stop — terminating it", { tags: { database: this.spec.databaseId } });
166
+ await this.thread.terminate();
167
+ }
168
+ }
169
+ inFlight() {
170
+ return this.pending.size;
171
+ }
172
+ request(body) {
173
+ if (this.dead || this.stopping) return Promise.reject(/* @__PURE__ */ new Error(`database "${this.spec.databaseId}" is not serving`));
174
+ if (this.pending.size >= this.maxInFlight) {
175
+ this.logBusy();
176
+ return Promise.reject(new DatabaseBusyError(this.spec.databaseId, this.pending.size));
177
+ }
178
+ const id = this.nextId++;
179
+ this.lastOp = `${body.kind}:${body.op}`;
180
+ return new Promise((resolve, reject) => {
181
+ this.pending.set(id, {
182
+ op: this.lastOp,
183
+ resolve: (result) => resolve(trustResult(result)),
184
+ reject
185
+ });
186
+ const transfer = body.kind === "vector" ? collectTransferables(body.input) : [];
187
+ this.thread.postMessage({
188
+ id,
189
+ ...body
190
+ }, transfer);
191
+ });
192
+ }
193
+ logBusy() {
194
+ const at = this.now();
195
+ if (at - this.lastBusyLogAt < 6e4) return;
196
+ this.lastBusyLogAt = at;
197
+ this.logger.warn("database refused a call: too many in flight", {
198
+ tags: { database: this.spec.databaseId },
199
+ meta: {
200
+ inFlight: this.pending.size,
201
+ bound: this.maxInFlight,
202
+ lastOp: this.lastOp
203
+ }
204
+ });
205
+ }
206
+ onMessage(raw) {
207
+ if (!isFileHostMessage(raw)) return;
208
+ const message = raw;
209
+ if (message.kind === "log") {
210
+ this.writeLog(message);
211
+ return;
212
+ }
213
+ if (message.kind === "ready") {
214
+ this.declared = new Set(message.declared);
215
+ this.bootSettled?.resolve();
216
+ this.bootSettled = null;
217
+ return;
218
+ }
219
+ if (message.kind === "boot-failed") {
220
+ const err = rehydrateError(message.error);
221
+ this.bootSettled?.reject(err);
222
+ this.bootSettled = null;
223
+ return;
224
+ }
225
+ const pending = this.pending.get(message.id);
226
+ if (pending === void 0) return;
227
+ this.pending.delete(message.id);
228
+ if (message.ok) pending.resolve(message.result);
229
+ else pending.reject(rehydrateError(message.error));
230
+ }
231
+ writeLog(message) {
232
+ const scoped = message.scope === "" ? this.logger : this.logger.child(`Db/${this.spec.databaseId}/${message.scope}`);
233
+ const extras = {
234
+ tags: {
235
+ ...message.tags,
236
+ database: this.spec.databaseId
237
+ },
238
+ ...message.meta !== void 0 ? { meta: message.meta } : {}
239
+ };
240
+ scoped[message.level](message.message, extras);
241
+ }
242
+ /** The thread is gone and nobody asked it to be: say so, fail what waits, fail the runner. */
243
+ die(reason) {
244
+ if (this.dead) return;
245
+ this.dead = true;
246
+ this.logger.error("database worker died — failing the runner", {
247
+ tags: { database: this.spec.databaseId },
248
+ meta: {
249
+ reason,
250
+ lastOp: this.lastOp,
251
+ inFlight: this.pending.size
252
+ }
253
+ });
254
+ const err = /* @__PURE__ */ new Error(`database "${this.spec.databaseId}" worker died: ${reason}`);
255
+ for (const pending of this.pending.values()) pending.reject(err);
256
+ this.pending.clear();
257
+ this.bootSettled?.reject(err);
258
+ this.bootSettled = null;
259
+ this.onFatal(reason);
260
+ }
261
+ };
262
+ /**
263
+ * Parse `/proc/locks`. Line shape:
264
+ * `1: POSIX ADVISORY READ 3490531 08:31:3769403373 128 128`
265
+ * (`id: TYPE MODE ACCESS PID MAJ:MIN:INODE START END`). A blocked waiter is
266
+ * printed as `1: -> POSIX …` and holds nothing, so it is skipped; a line that
267
+ * does not parse is skipped rather than guessed at.
268
+ */
269
+ function parseProcLocks(text) {
270
+ const locks = [];
271
+ for (const line of text.split("\n")) {
272
+ const fields = line.trim().split(/\s+/);
273
+ if (fields.length < 8 || fields[1] === "->") continue;
274
+ const pid = Number(fields[4]);
275
+ const inode = (fields[5]?.split(":"))?.[2];
276
+ const start = Number(fields[6]);
277
+ const endField = fields[7];
278
+ const end = endField === "EOF" ? null : Number(endField);
279
+ if (!Number.isInteger(pid) || inode === void 0 || !/^\d+$/.test(inode)) continue;
280
+ if (!Number.isInteger(start) || end !== null && !Number.isInteger(end)) continue;
281
+ locks.push({
282
+ pid,
283
+ inode,
284
+ start,
285
+ end
286
+ });
287
+ }
288
+ return locks;
289
+ }
290
+ /** Does a lock owned by `pid` on `inode` cover the DMS byte? */
291
+ function holdsDmsLock(locks, pid, inode) {
292
+ return locks.some((l) => l.pid === pid && l.inode === inode && l.start <= 128 && (l.end === null || l.end >= 128));
293
+ }
294
+ var defaultDeps = {
295
+ platform: process.platform,
296
+ pid: process.pid,
297
+ shmInode: (shmPath) => statSync(shmPath, { bigint: true }).ino.toString(),
298
+ readProcLocks: () => readFileSync("/proc/locks", "utf8")
299
+ };
300
+ var ShmLockCanary = class {
301
+ shmPath;
302
+ logger;
303
+ intervalMs;
304
+ deps;
305
+ timer = null;
306
+ last = null;
307
+ lastError = null;
308
+ constructor(options) {
309
+ this.shmPath = `${options.dbPath}-shm`;
310
+ this.logger = options.logger;
311
+ this.intervalMs = options.intervalMs ?? 6e5;
312
+ this.deps = {
313
+ ...defaultDeps,
314
+ ...options.deps
315
+ };
316
+ }
317
+ start() {
318
+ if (this.timer !== null) return;
319
+ if (this.check() === "unavailable") return;
320
+ const timer = setInterval(() => this.check(), this.intervalMs);
321
+ timer.unref?.();
322
+ this.timer = timer;
323
+ }
324
+ stop() {
325
+ if (this.timer !== null) clearInterval(this.timer);
326
+ this.timer = null;
327
+ }
328
+ /** One look. Logs only a change of state. Public for the spec. */
329
+ check() {
330
+ const state = this.observe();
331
+ if (state !== this.last) this.report(state);
332
+ this.last = state;
333
+ return state;
334
+ }
335
+ observe() {
336
+ if (this.deps.platform !== "linux") return "unavailable";
337
+ try {
338
+ const inode = this.deps.shmInode(this.shmPath);
339
+ return holdsDmsLock(parseProcLocks(this.deps.readProcLocks()), this.deps.pid, inode) ? "held" : "missing";
340
+ } catch (err) {
341
+ this.lastError = errMsg$1(err);
342
+ return "unreadable";
343
+ }
344
+ }
345
+ report(state) {
346
+ const meta = {
347
+ shmPath: this.shmPath,
348
+ pid: this.deps.pid,
349
+ byte: 128
350
+ };
351
+ switch (state) {
352
+ case "held":
353
+ this.logger.info("SQLite shm DMS lock held", { meta });
354
+ return;
355
+ case "missing":
356
+ this.logger.warn("SQLite shm DMS lock LOST — a second open of the database will rebuild the wal-index under this process (SIGBUS risk, D679)", { meta });
357
+ return;
358
+ case "unavailable":
359
+ this.logger.info("SQLite shm DMS lock canary cannot look here", { meta: {
360
+ ...meta,
361
+ platform: this.deps.platform
362
+ } });
363
+ return;
364
+ case "unreadable":
365
+ this.logger.warn("SQLite shm DMS lock canary could not look", { meta: {
366
+ ...meta,
367
+ error: this.lastError
368
+ } });
369
+ return;
370
+ }
371
+ }
372
+ };
373
+ /**
374
+ * How long the snapshot thread may run before it is terminated. A minute under
375
+ * the capability's own timeout, so the runner gives up — and says why — before
376
+ * the caller's call does.
377
+ */
378
+ var SNAPSHOT_DEADLINE_MS = DATABASE_SNAPSHOT_TIMEOUT_MS - 6e4;
379
+ /** The directory (beside the live database) that holds pre-migration snapshots. */
380
+ var PRE_MIGRATION_DIR_SUFFIX = ".pre-migration";
381
+ /** A migration id as a file-name part: `hub/2026-10-31-x` becomes `hub_2026-10-31-x`. */
382
+ function snapshotLabelOf(firstId) {
383
+ return firstId.replaceAll(/[^a-z0-9-]/gi, "_");
384
+ }
385
+ /** The least headroom left on the disk AFTER the copy, whatever the database's size. */
386
+ var SNAPSHOT_MIN_RESERVE_BYTES = 256 * 1024 * 1024;
387
+ /**
388
+ * Free bytes a snapshot needs before it may start: the copy (at most the
389
+ * database plus its WAL), then a reserve the size of the database (at least
390
+ * {@link SNAPSHOT_MIN_RESERVE_BYTES}) for the live writes and the WAL growth
391
+ * the pinned read causes while the copy runs.
392
+ */
393
+ function snapshotSpaceNeeded(databaseBytes, walBytes) {
394
+ return databaseBytes + walBytes + Math.max(databaseBytes, SNAPSHOT_MIN_RESERVE_BYTES);
395
+ }
396
+ /**
397
+ * Where the built worker entry lives: `dist/sqlite-snapshot-worker.js` at the
398
+ * package root, next to `wal-checkpoint-worker.js` (see `wal-checkpointer.ts`
399
+ * for why it resolves through the package's own `package.json`).
400
+ */
401
+ function defaultSnapshotWorkerPath() {
402
+ const require_ = createRequire(import.meta.url);
403
+ const packageRoot = path.dirname(require_.resolve("@camstack/server/system/package.json"));
404
+ return path.join(packageRoot, "dist", "sqlite-snapshot-worker.js");
405
+ }
406
+ /** A `stat` size: `0` when the file does not exist, `null` when it could not be read. */
407
+ async function sizeOrAbsent(file) {
408
+ try {
409
+ return (await promises.stat(file)).size;
410
+ } catch (err) {
411
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") return 0;
412
+ return null;
413
+ }
414
+ }
415
+ /** Make a rename in `dir` durable: fsync the directory entry. */
416
+ async function fsyncDirectory(dir) {
417
+ const handle = await promises.open(dir, "r");
418
+ try {
419
+ await handle.sync();
420
+ } finally {
421
+ await handle.close();
422
+ }
423
+ }
424
+ var SqliteSnapshotter = class {
425
+ livePath;
426
+ logger;
427
+ pagesPerStep;
428
+ deadlineMs;
429
+ statfs;
430
+ spawnWorker;
431
+ syncDirectory;
432
+ inFlight = null;
433
+ inFlightPreMigration = null;
434
+ /**
435
+ * Set while a thread the deadline gave up on is still being terminated. A
436
+ * native SQLite call cannot be interrupted, so `terminate()` may take as long
437
+ * as that call — or never settle. Until it does, a new snapshot is refused
438
+ * at once (never joined, never started beside a thread that may still hold
439
+ * a pinned read), and the work directory stays until nobody writes into it.
440
+ */
441
+ draining = null;
442
+ constructor(options) {
443
+ this.livePath = path.resolve(options.livePath);
444
+ this.logger = options.logger;
445
+ this.pagesPerStep = options.pagesPerStep ?? 1024;
446
+ this.deadlineMs = options.deadlineMs ?? SNAPSHOT_DEADLINE_MS;
447
+ this.statfs = options.statfs ?? ((dir) => promises.statfs(dir));
448
+ this.syncDirectory = options.syncDirectory ?? fsyncDirectory;
449
+ const workerPath = options.workerPath ?? null;
450
+ const execArgv = options.workerExecArgv;
451
+ this.spawnWorker = options.spawnWorker ?? ((data) => {
452
+ const worker = new Worker(workerPath ?? defaultSnapshotWorkerPath(), {
453
+ workerData: data,
454
+ ...execArgv !== void 0 ? { execArgv: [...execArgv] } : {}
455
+ });
456
+ return {
457
+ onMessage: (listener) => worker.on("message", listener),
458
+ onError: (listener) => worker.on("error", listener),
459
+ onExit: (listener) => worker.on("exit", listener),
460
+ terminate: () => worker.terminate()
461
+ };
462
+ });
463
+ }
464
+ /** The database this snapshotter copies, absolute. */
465
+ get database() {
466
+ return this.livePath;
467
+ }
468
+ /** Write `<db>.backup-snapshot`. Joins a snapshot already running. */
469
+ write() {
470
+ return this.writeFor({ purpose: "backup" });
471
+ }
472
+ /** Write `<db>.pre-migration/<bootId>-<firstId>.db` (D987). Joins one already running. */
473
+ writePreMigration(bootId, firstId) {
474
+ return this.writeFor({
475
+ purpose: "pre-migration",
476
+ bootId,
477
+ firstId
478
+ });
479
+ }
480
+ writeFor(target) {
481
+ const running = target.purpose === "backup" ? this.inFlight : this.inFlightPreMigration;
482
+ if (running !== null) return running;
483
+ if (this.draining !== null) return Promise.reject(/* @__PURE__ */ new Error("database snapshot refused (failed): the previous snapshot thread is still terminating — it timed out inside a call that has not returned"));
484
+ const run = this.run(target).finally(() => {
485
+ if (target.purpose === "backup") this.inFlight = null;
486
+ else this.inFlightPreMigration = null;
487
+ });
488
+ if (target.purpose === "backup") this.inFlight = run;
489
+ else this.inFlightPreMigration = run;
490
+ return run;
491
+ }
492
+ /**
493
+ * Remove a snapshot nobody collected and a work directory a crash left.
494
+ * Called at boot; {@link write} does the same before it starts.
495
+ */
496
+ async sweep() {
497
+ const snapshotPath = this.livePath + DATABASE_SNAPSHOT_SUFFIX;
498
+ const workDir = this.livePath + DATABASE_SNAPSHOT_PARTIAL_SUFFIX;
499
+ const leftover = await sizeOrAbsent(snapshotPath) !== 0;
500
+ await promises.rm(snapshotPath, { force: true });
501
+ await promises.rm(workDir, {
502
+ recursive: true,
503
+ force: true
504
+ });
505
+ if (leftover) this.logger.info("SQLite snapshot left by an earlier run removed — nobody collected it", { meta: { snapshotPath } });
506
+ }
507
+ refuse(message) {
508
+ this.logger.warn("SQLite snapshot refused — no snapshot written", { meta: {
509
+ livePath: this.livePath,
510
+ reason: message.reason,
511
+ detail: message.detail
512
+ } });
513
+ throw new Error(`database snapshot refused (${message.reason}): ${message.detail}`);
514
+ }
515
+ /** Refuses with `no-space` unless the disk can take the copy and keep its reserve. */
516
+ async checkSpace() {
517
+ const dir = path.dirname(this.livePath);
518
+ const databaseBytes = await sizeOrAbsent(this.livePath);
519
+ const walBytes = await sizeOrAbsent(`${this.livePath}-wal`);
520
+ let freeBytes = null;
521
+ let statfsError = null;
522
+ try {
523
+ const space = await this.statfs(dir);
524
+ freeBytes = Number(space.bavail) * Number(space.bsize);
525
+ } catch (err) {
526
+ statfsError = errMsg$1(err);
527
+ }
528
+ if (databaseBytes === null || walBytes === null || freeBytes === null) this.refuse({
529
+ kind: "refused",
530
+ reason: "no-space",
531
+ detail: `free space on ${dir} is unknown (${statfsError ?? "the database size could not be read"}) — a snapshot is never written onto a disk it cannot measure`
532
+ });
533
+ const needed = snapshotSpaceNeeded(databaseBytes, walBytes);
534
+ if (freeBytes < needed) this.refuse({
535
+ kind: "refused",
536
+ reason: "no-space",
537
+ detail: `${freeBytes} bytes free on ${dir}, ${needed} needed (copy ${databaseBytes + walBytes} + reserve) — the live database shares this disk`
538
+ });
539
+ }
540
+ async run(target) {
541
+ const preDir = this.livePath + PRE_MIGRATION_DIR_SUFFIX;
542
+ const workDir = target.purpose === "backup" ? this.livePath + DATABASE_SNAPSHOT_PARTIAL_SUFFIX : path.join(preDir, ".partial");
543
+ const snapshotPath = target.purpose === "backup" ? this.livePath + DATABASE_SNAPSHOT_SUFFIX : path.join(preDir, `${target.bootId}-${snapshotLabelOf(target.firstId)}.db`);
544
+ const copyPath = path.join(workDir, "copy");
545
+ if (target.purpose === "backup") await this.sweep();
546
+ else await promises.rm(workDir, {
547
+ recursive: true,
548
+ force: true
549
+ });
550
+ await this.checkSpace();
551
+ await promises.mkdir(workDir, { recursive: true });
552
+ try {
553
+ const message = await this.runWorker({
554
+ kind: "sqlite-snapshot",
555
+ livePath: this.livePath,
556
+ copyPath,
557
+ pagesPerStep: this.pagesPerStep
558
+ });
559
+ if (message.kind === "refused") this.refuse(message);
560
+ await promises.rename(copyPath, snapshotPath);
561
+ try {
562
+ await this.syncDirectory(path.dirname(snapshotPath));
563
+ } catch (err) {
564
+ this.logger.warn("SQLite snapshot directory fsync failed — continuing", { meta: {
565
+ dir: path.dirname(snapshotPath),
566
+ error: errMsg$1(err)
567
+ } });
568
+ }
569
+ if (target.purpose === "pre-migration") await this.prunePreMigration(preDir, snapshotPath);
570
+ const { size } = await promises.stat(snapshotPath);
571
+ const { copy } = message;
572
+ const result = {
573
+ livePath: this.livePath,
574
+ snapshotPath,
575
+ sizeBytes: size,
576
+ pageCount: copy.pageCount,
577
+ pageSize: copy.pageSize,
578
+ tables: [...copy.tables],
579
+ copyMs: copy.copyMs,
580
+ verifyMs: copy.verifyMs,
581
+ takenAt: copy.takenAt
582
+ };
583
+ this.logger.info("SQLite snapshot written and verified", { meta: {
584
+ snapshotPath,
585
+ sizeBytes: size,
586
+ pageCount: copy.pageCount,
587
+ tables: copy.tables.length,
588
+ rows: copy.tables.reduce((acc, t) => acc + t.rows, 0),
589
+ copyMs: copy.copyMs,
590
+ verifyMs: copy.verifyMs
591
+ } });
592
+ return result;
593
+ } finally {
594
+ const removeWorkDir = async () => {
595
+ try {
596
+ await promises.rm(workDir, {
597
+ recursive: true,
598
+ force: true
599
+ });
600
+ } catch (err) {
601
+ this.logger.warn("SQLite snapshot work directory could not be removed", { meta: {
602
+ workDir,
603
+ error: errMsg$1(err)
604
+ } });
605
+ }
606
+ };
607
+ if (this.draining !== null) this.draining.then(removeWorkDir);
608
+ else await removeWorkDir();
609
+ }
610
+ }
611
+ /** Keep the newest {@link PRE_MIGRATION_KEEP} snapshots; the one just written always stays. */
612
+ async prunePreMigration(dir, justWritten) {
613
+ try {
614
+ const names = (await promises.readdir(dir)).filter((name) => name.endsWith(".db"));
615
+ const dated = await Promise.all(names.map(async (name) => ({
616
+ file: path.join(dir, name),
617
+ mtimeMs: (await promises.stat(path.join(dir, name))).mtimeMs
618
+ })));
619
+ dated.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.file < b.file ? 1 : -1));
620
+ const keep = new Set([justWritten, ...dated.map((d) => d.file).filter((file) => file !== justWritten)].slice(0, 3));
621
+ for (const { file } of dated) if (!keep.has(file)) await promises.rm(file, { force: true });
622
+ } catch (err) {
623
+ this.logger.warn("pre-migration snapshot retention failed", { meta: {
624
+ dir,
625
+ error: errMsg$1(err)
626
+ } });
627
+ }
628
+ }
629
+ runWorker(data) {
630
+ const worker = this.spawnWorker(data);
631
+ return new Promise((resolve) => {
632
+ let answered = false;
633
+ let terminating = false;
634
+ const answer = (message) => {
635
+ if (answered) return;
636
+ answered = true;
637
+ clearTimeout(deadline);
638
+ resolve(message);
639
+ };
640
+ const deadline = setTimeout(() => {
641
+ terminating = true;
642
+ this.logger.warn("SQLite snapshot thread missed its deadline — terminating it", { meta: {
643
+ livePath: this.livePath,
644
+ deadlineMs: this.deadlineMs
645
+ } });
646
+ const settled = worker.terminate().then(() => void 0, (err) => {
647
+ this.logger.warn("SQLite snapshot thread terminate failed", { meta: {
648
+ livePath: this.livePath,
649
+ error: errMsg$1(err)
650
+ } });
651
+ });
652
+ this.draining = settled.then(() => {
653
+ this.draining = null;
654
+ });
655
+ answer({
656
+ kind: "refused",
657
+ reason: "failed",
658
+ detail: `timed out after ${this.deadlineMs} ms — the snapshot thread is being terminated`
659
+ });
660
+ }, this.deadlineMs);
661
+ worker.onMessage((message) => {
662
+ if (isSnapshotWorkerMessage(message)) answer(message);
663
+ else answer({
664
+ kind: "refused",
665
+ reason: "failed",
666
+ detail: "malformed worker message"
667
+ });
668
+ });
669
+ worker.onError((err) => answer({
670
+ kind: "refused",
671
+ reason: "failed",
672
+ detail: errMsg$1(err)
673
+ }));
674
+ worker.onExit((code) => {
675
+ if (terminating) return;
676
+ answer({
677
+ kind: "refused",
678
+ reason: "failed",
679
+ detail: `worker exited ${code} without an answer`
680
+ });
681
+ });
682
+ });
683
+ }
684
+ };
685
+ var EMPTY_STATS = {
686
+ checkpoints: 0,
687
+ frames: 0,
688
+ slow: 0,
689
+ maxMs: 0,
690
+ totalMs: 0,
691
+ busy: 0,
692
+ large: 0,
693
+ maxAppended: 0
694
+ };
695
+ /**
696
+ * Where the built worker entry lives: `dist/wal-checkpoint-worker.js` at the
697
+ * package root, next to `addon-runner.js`, found through the package's own
698
+ * `exports["./package.json"]` so it resolves the same way from the workspace
699
+ * and from an installed closure.
700
+ */
701
+ function defaultWorkerPath() {
702
+ const require_ = createRequire(import.meta.url);
703
+ const packageRoot = path.dirname(require_.resolve("@camstack/server/system/package.json"));
704
+ return path.join(packageRoot, "dist", "wal-checkpoint-worker.js");
705
+ }
706
+ var WalCheckpointer = class {
707
+ dbPath;
708
+ logger;
709
+ pollMs;
710
+ maxDelayMs;
711
+ slowMs;
712
+ summaryIntervalMs;
713
+ spawn;
714
+ worker = null;
715
+ summaryTimer = null;
716
+ stopping = false;
717
+ statsValue = EMPTY_STATS;
718
+ constructor(options) {
719
+ this.dbPath = options.dbPath;
720
+ this.logger = options.logger;
721
+ this.pollMs = options.pollMs ?? 1e3;
722
+ this.maxDelayMs = options.maxDelayMs ?? 8e3;
723
+ this.slowMs = options.slowMs ?? 1e3;
724
+ this.summaryIntervalMs = options.summaryIntervalMs ?? 6e5;
725
+ const workerPath = options.workerPath ?? defaultWorkerPath();
726
+ const execArgv = options.workerExecArgv;
727
+ this.spawn = options.workerFactory ?? ((workerData) => new Worker(workerPath, {
728
+ workerData,
729
+ ...execArgv !== void 0 ? { execArgv: [...execArgv] } : {}
730
+ }));
731
+ }
732
+ /** Totals since the last summary line. */
733
+ get stats() {
734
+ return this.statsValue;
735
+ }
736
+ isRunning() {
737
+ return this.worker !== null;
738
+ }
739
+ start() {
740
+ if (this.worker !== null) return;
741
+ this.stopping = false;
742
+ const worker = this.spawn({
743
+ dbPath: this.dbPath,
744
+ pollMs: this.pollMs,
745
+ maxDelayMs: this.maxDelayMs
746
+ });
747
+ this.worker = worker;
748
+ worker.on("message", (message) => this.onMessage(message));
749
+ worker.on("error", (err) => {
750
+ this.logger.error("WAL checkpoint worker threw", { meta: { error: errMsg$1(err) } });
751
+ });
752
+ worker.on("exit", (code) => this.onExit(code));
753
+ const summaryTimer = setInterval(() => this.logSummary(), this.summaryIntervalMs);
754
+ summaryTimer.unref?.();
755
+ this.summaryTimer = summaryTimer;
756
+ this.logger.info("WAL checkpoint worker armed", { meta: {
757
+ pollMs: this.pollMs,
758
+ maxDelayMs: this.maxDelayMs,
759
+ slowMs: this.slowMs
760
+ } });
761
+ }
762
+ /** Ask the thread to close its connection and exit; resolves when it has. */
763
+ async stop() {
764
+ const worker = this.worker;
765
+ if (worker === null) return;
766
+ this.stopping = true;
767
+ if (this.summaryTimer !== null) {
768
+ clearInterval(this.summaryTimer);
769
+ this.summaryTimer = null;
770
+ }
771
+ const stop = { kind: "stop" };
772
+ const exited = new Promise((resolve) => worker.once("exit", () => resolve()));
773
+ worker.postMessage(stop);
774
+ await exited;
775
+ this.worker = null;
776
+ }
777
+ /** One message off the port. Public so the spec can feed it directly. */
778
+ onMessage(message) {
779
+ if (!isWorkerMessage(message)) {
780
+ this.logger.warn("WAL checkpoint worker sent an unreadable message", { meta: { message: String(message) } });
781
+ return;
782
+ }
783
+ this.handle(message);
784
+ }
785
+ handle(message) {
786
+ switch (message.kind) {
787
+ case "ready": return;
788
+ case "failed":
789
+ this.logger.warn("WAL checkpoint failed on the worker", { meta: { error: message.error } });
790
+ return;
791
+ case "checkpointed":
792
+ this.record(message);
793
+ return;
794
+ }
795
+ }
796
+ record(report) {
797
+ const slow = report.ms >= this.slowMs;
798
+ const large = report.reason === "scheduled" && report.appendedFrames > 5e3;
799
+ const prev = this.statsValue;
800
+ this.statsValue = {
801
+ checkpoints: prev.checkpoints + 1,
802
+ frames: prev.frames + report.appendedFrames,
803
+ slow: prev.slow + (slow ? 1 : 0),
804
+ maxMs: Math.max(prev.maxMs, report.ms),
805
+ totalMs: prev.totalMs + report.ms,
806
+ busy: prev.busy + (report.busy ? 1 : 0),
807
+ large: prev.large + (large ? 1 : 0),
808
+ maxAppended: Math.max(prev.maxAppended, report.appendedFrames)
809
+ };
810
+ if (large && prev.large === 0) this.logger.warn("WAL checkpoint pass found a large backlog", { meta: {
811
+ appendedFrames: report.appendedFrames,
812
+ thresholdFrames: WAL_CHECKPOINT_LARGE_PASS_FRAMES,
813
+ walFrames: report.walFrames,
814
+ nextDelayMs: report.nextDelayMs,
815
+ maxDelayMs: this.maxDelayMs
816
+ } });
817
+ if (slow) this.logger.warn("WAL checkpoint held the worker", { meta: {
818
+ ms: report.ms,
819
+ reason: report.reason,
820
+ appendedFrames: report.appendedFrames,
821
+ nextDelayMs: report.nextDelayMs,
822
+ walFrames: report.walFrames,
823
+ checkpointedFrames: report.checkpointedFrames,
824
+ busy: report.busy
825
+ } });
826
+ }
827
+ logSummary() {
828
+ const stats = this.statsValue;
829
+ this.statsValue = EMPTY_STATS;
830
+ if (stats.checkpoints === 0) return;
831
+ this.logger.info("WAL checkpoints on the worker", { meta: {
832
+ windowMs: this.summaryIntervalMs,
833
+ checkpoints: stats.checkpoints,
834
+ frames: stats.frames,
835
+ slow: stats.slow,
836
+ maxMs: stats.maxMs,
837
+ totalMs: stats.totalMs,
838
+ busy: stats.busy,
839
+ large: stats.large,
840
+ maxAppended: stats.maxAppended
841
+ } });
842
+ }
843
+ onExit(code) {
844
+ const wasStopping = this.stopping;
845
+ this.worker = null;
846
+ if (this.summaryTimer !== null) {
847
+ clearInterval(this.summaryTimer);
848
+ this.summaryTimer = null;
849
+ }
850
+ if (wasStopping) return;
851
+ this.logger.error("WAL checkpoint worker died — the engine autocheckpoint bound is now the only checkpoint", { meta: {
852
+ exitCode: code,
853
+ dbPath: this.dbPath
854
+ } });
855
+ }
856
+ };
857
+ //#endregion
858
+ //#region src/builtins/sqlite-storage/owned-sqlite-file.ts
859
+ /** The loggers of one file: scope per sub-component, `tags.database` on every line. */
860
+ function fileLoggerFor(base, databaseId) {
861
+ return (scope) => base.child(databaseId === "settings" ? scope : `Db/${databaseId}/${scope}`).withTags({ database: databaseId });
862
+ }
863
+ function realLifecycle(spec, logger) {
864
+ return {
865
+ checkpointer: new WalCheckpointer({
866
+ dbPath: spec.livePath,
867
+ logger: logger("WalCheckpoint")
868
+ }),
869
+ canary: new ShmLockCanary({
870
+ dbPath: spec.livePath,
871
+ logger: logger("ShmLock")
872
+ }),
873
+ snapshotter: new SqliteSnapshotter({
874
+ livePath: spec.livePath,
875
+ logger: logger("Snapshot")
876
+ })
877
+ };
878
+ }
879
+ /** Shared by both thread flavours: the per-file lifecycle. */
880
+ var OwnedFileBase = class {
881
+ spec;
882
+ deps;
883
+ databaseId;
884
+ livePath;
885
+ log;
886
+ lifecycle = null;
887
+ constructor(spec, deps) {
888
+ this.spec = spec;
889
+ this.deps = deps;
890
+ this.databaseId = spec.databaseId;
891
+ this.livePath = spec.livePath;
892
+ this.log = fileLoggerFor(deps.logger, spec.databaseId);
893
+ }
894
+ /**
895
+ * Arm the checkpointer, the canary and the snapshotter. Called after the
896
+ * connection is open and the boot purges have run.
897
+ */
898
+ async armLifecycle() {
899
+ const lifecycle = (this.deps.lifecycle ?? realLifecycle)(this.spec, this.log);
900
+ lifecycle.checkpointer.start();
901
+ lifecycle.canary.start();
902
+ try {
903
+ await lifecycle.snapshotter.sweep();
904
+ } catch (err) {
905
+ this.log("Snapshot").warn("SQLite snapshot sweep failed at boot", { meta: { error: errMsg$1(err) } });
906
+ }
907
+ this.lifecycle = lifecycle;
908
+ }
909
+ async snapshot() {
910
+ if (this.lifecycle === null) throw new Error(`database "${this.databaseId}" is not open`);
911
+ return this.lifecycle.snapshotter.write();
912
+ }
913
+ async stop() {
914
+ this.stopMaintenance();
915
+ this.lifecycle?.canary.stop();
916
+ await this.lifecycle?.checkpointer.stop();
917
+ this.lifecycle = null;
918
+ await this.stopConnection();
919
+ }
920
+ };
921
+ /** `camstack.db`: served in place on the engine's main thread. */
922
+ var InlineOwnedFile = class extends OwnedFileBase {
923
+ backend;
924
+ declared = /* @__PURE__ */ new Set();
925
+ vectorIndex = null;
926
+ vectorProvider = null;
927
+ maintenance = null;
928
+ recordsEngine = null;
929
+ constructor(spec, deps) {
930
+ super(spec, deps);
931
+ this.backend = new SqliteSettingsBackend(spec.livePath, deps.runtimeDefaults === void 0 ? {} : { ...deps.runtimeDefaults }, this.log("Query"), {
932
+ databaseId: spec.databaseId,
933
+ autoVacuum: spec.autoVacuum,
934
+ canonicalKv: spec.databaseId === "settings"
935
+ });
936
+ }
937
+ async open() {
938
+ await this.backend.initialize();
939
+ this.declared = this.backend.declaredCollectionNames();
940
+ if (this.spec.loadVectorExtension) {
941
+ const vectorIndex = createVectorIndex(this.backend, this.log("VectorIndex"));
942
+ await vectorIndex.loadIndexRegistry();
943
+ this.vectorIndex = vectorIndex;
944
+ this.vectorProvider = vectorProviderOf(vectorIndex);
945
+ }
946
+ const handle = this.backend.getDatabase();
947
+ if (handle !== null) this.recordsEngine = new RecordsEngine(handle, {
948
+ databaseId: this.spec.databaseId,
949
+ logger: this.log("Records")
950
+ });
951
+ await this.deps.afterOpen?.(this);
952
+ const db = this.backend.getDatabase();
953
+ if (db !== null) {
954
+ const maintenance = new WalMaintenance({
955
+ db,
956
+ dbPath: this.spec.livePath,
957
+ logger: this.log("WalMaintenance")
958
+ });
959
+ maintenance.start();
960
+ this.maintenance = maintenance;
961
+ }
962
+ await this.armLifecycle();
963
+ }
964
+ getVectorIndex() {
965
+ return this.vectorIndex;
966
+ }
967
+ async call(op, input) {
968
+ const result = await callData(this.backend, op, input);
969
+ if (op === "declareCollection") this.declared = this.backend.declaredCollectionNames();
970
+ return result;
971
+ }
972
+ async records(op, input) {
973
+ if (this.recordsEngine === null) throw new Error(`database "${this.databaseId}" is not open`);
974
+ return callRecords(this.recordsEngine, op, input);
975
+ }
976
+ async vector(op, input) {
977
+ if (this.vectorProvider === null) throw new Error(`database "${this.databaseId}" does not serve vector calls`);
978
+ return callVector(this.vectorProvider, op, input);
979
+ }
980
+ declaredCollections() {
981
+ return this.declared;
982
+ }
983
+ async hasTable(name) {
984
+ return callControl(controlTargetOf(this.backend, 0), "hasTable", { name });
985
+ }
986
+ listPhysicalTables(ownerPrefix) {
987
+ return Promise.resolve(callControl(controlTargetOf(this.backend, 0), "listPhysicalTables", { ownerPrefix }));
988
+ }
989
+ async servingThreadId() {
990
+ return 0;
991
+ }
992
+ async migrate(op, input) {
993
+ const db = this.backend.getDatabase();
994
+ if (db === null) throw new Error(`database "${this.databaseId}" is not open`);
995
+ return callMigrate(migrateTargetOf(db, this.databaseId, this.deps.migrationCatalogue ?? HUB_MIGRATIONS), op, input);
996
+ }
997
+ stopMaintenance() {
998
+ this.maintenance?.stop();
999
+ this.maintenance = null;
1000
+ }
1001
+ async stopConnection() {
1002
+ await this.backend.shutdown();
1003
+ }
1004
+ };
1005
+ /** `events.db`, `history.db`: served by a dedicated worker thread. */
1006
+ var WorkerOwnedFile = class extends OwnedFileBase {
1007
+ client;
1008
+ constructor(spec, deps) {
1009
+ super(spec, deps);
1010
+ this.client = new FileHostClient({
1011
+ spec,
1012
+ logger: deps.logger,
1013
+ onFatal: deps.onFatal,
1014
+ ...deps.workerPath !== void 0 ? { workerPath: deps.workerPath } : {},
1015
+ ...deps.workerExecArgv !== void 0 ? { workerExecArgv: deps.workerExecArgv } : {},
1016
+ ...deps.threadFactory !== void 0 ? { threadFactory: deps.threadFactory } : {},
1017
+ ...deps.maxInFlight !== void 0 ? { maxInFlight: deps.maxInFlight } : {}
1018
+ });
1019
+ }
1020
+ /** A boot-time migration question, answered inside the worker (D987). */
1021
+ migrate(op, input) {
1022
+ return this.client.migrate(op, input);
1023
+ }
1024
+ async open() {
1025
+ await this.client.ready();
1026
+ await this.deps.afterOpen?.(this);
1027
+ await this.armLifecycle();
1028
+ }
1029
+ async call(op, input) {
1030
+ const result = await this.client.data(op, input);
1031
+ if (op === "declareCollection") {
1032
+ const table = tableNameOf(input);
1033
+ if (table !== null) this.client.noteDeclared(table);
1034
+ }
1035
+ return result;
1036
+ }
1037
+ vector(op, input) {
1038
+ return this.client.vector(op, input);
1039
+ }
1040
+ records(op, input) {
1041
+ return this.client.records(op, input);
1042
+ }
1043
+ declaredCollections() {
1044
+ return this.client.declaredCollections();
1045
+ }
1046
+ hasTable(name) {
1047
+ return this.client.control("hasTable", { name });
1048
+ }
1049
+ listPhysicalTables(ownerPrefix) {
1050
+ return this.client.control("listPhysicalTables", { ownerPrefix });
1051
+ }
1052
+ servingThreadId() {
1053
+ return this.client.control("threadId", {});
1054
+ }
1055
+ stopMaintenance() {}
1056
+ async stopConnection() {
1057
+ await this.client.stop();
1058
+ }
1059
+ };
1060
+ /** The table a `declareCollection` input names, from its (possibly absent) namespace. */
1061
+ function tableNameOf(input) {
1062
+ if (typeof input !== "object" || input === null) return null;
1063
+ const collection = "collection" in input ? input.collection : void 0;
1064
+ if (typeof collection !== "string") return null;
1065
+ const namespace = "namespace" in input ? input.namespace : void 0;
1066
+ return typeof namespace === "string" && namespace !== "" ? `${namespace}:${collection}` : collection;
1067
+ }
1068
+ /** Open a file on the thread its spec names. */
1069
+ async function openOwnedSqliteFile(spec, deps) {
1070
+ if (spec.thread === "main") {
1071
+ const file = new InlineOwnedFile(spec, deps);
1072
+ await file.open();
1073
+ return file;
1074
+ }
1075
+ const file = new WorkerOwnedFile(spec, deps);
1076
+ await file.open();
1077
+ return file;
1078
+ }
1079
+ //#endregion
1080
+ //#region src/builtins/sqlite-storage/database-snapshot-provider.ts
1081
+ /**
1082
+ * The `database-snapshot` provider of the SQLite engine: every owned database
1083
+ * file it has open is listed, and each is snapshotted through its OWN
1084
+ * connection (D679, D693) — never by copying files.
1085
+ *
1086
+ * The list is read from the router at CALL time, not at boot: a file created at
1087
+ * runtime (the first declaration that names `events` or `history`) is listed
1088
+ * from the moment it opens, so no backup can leave it out.
1089
+ */
1090
+ var DatabaseSnapshotProvider = class {
1091
+ source;
1092
+ /** Same database asked twice: the second call joins the first. */
1093
+ inFlight = /* @__PURE__ */ new Map();
1094
+ /** Different databases run one after the other: the disk reserve check is per copy. */
1095
+ tail = Promise.resolve();
1096
+ constructor(source) {
1097
+ this.source = source;
1098
+ }
1099
+ async listDatabases() {
1100
+ return { databases: this.source.openFiles().map((file) => ({
1101
+ databaseId: file.databaseId,
1102
+ livePath: path.resolve(file.livePath)
1103
+ })) };
1104
+ }
1105
+ writeSnapshot(input) {
1106
+ const running = this.inFlight.get(input.databaseId);
1107
+ if (running !== void 0) return running;
1108
+ const file = this.source.openFiles().find((f) => f.databaseId === input.databaseId);
1109
+ if (file === void 0) return Promise.reject(/* @__PURE__ */ new Error(`database snapshot refused: database "${input.databaseId}" is not open`));
1110
+ const run = this.tail.catch(() => void 0).then(async () => {
1111
+ return {
1112
+ ...await file.snapshot(),
1113
+ databaseId: file.databaseId
1114
+ };
1115
+ });
1116
+ this.tail = run;
1117
+ const tracked = run.finally(() => {
1118
+ this.inFlight.delete(input.databaseId);
1119
+ });
1120
+ this.inFlight.set(input.databaseId, tracked);
1121
+ return tracked;
1122
+ }
1123
+ };
1124
+ //#endregion
1125
+ //#region src/builtins/sqlite-storage/migrations/migration-hold.ts
1126
+ /**
1127
+ * The hold a restore of a pre-migration snapshot leaves behind (D987).
1128
+ *
1129
+ * The restored database has the ledger of BEFORE the migrations ran, so they
1130
+ * look pending and would simply run again — the bad one first. The operator
1131
+ * asked for the opposite: no rerun until a retry or a new code version. That
1132
+ * decision cannot live inside the database being replaced, so it sits beside
1133
+ * it, in `<db>.migration-hold.json`, written by the owner and read by the owner.
1134
+ *
1135
+ * Reading is three-way, never "absent on error" (D49): a file that exists and
1136
+ * cannot be read holds EVERYTHING pending, and says so.
1137
+ */
1138
+ var MIGRATION_HOLD_SUFFIX = ".migration-hold.json";
1139
+ function holdPathOf(livePath) {
1140
+ return livePath + MIGRATION_HOLD_SUFFIX;
1141
+ }
1142
+ function isHold(value) {
1143
+ return typeof value === "object" && value !== null && "codeVersion" in value && typeof value.codeVersion === "string" && "snapshotId" in value && typeof value.snapshotId === "string" && "ids" in value && Array.isArray(value.ids) && value.ids.every((id) => typeof id === "string");
1144
+ }
1145
+ async function readHold(livePath) {
1146
+ let text;
1147
+ try {
1148
+ text = await promises.readFile(holdPathOf(livePath), "utf8");
1149
+ } catch (err) {
1150
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") return { kind: "absent" };
1151
+ return {
1152
+ kind: "unreadable",
1153
+ error: errMsg$1(err)
1154
+ };
1155
+ }
1156
+ try {
1157
+ const parsed = JSON.parse(text);
1158
+ return isHold(parsed) ? {
1159
+ kind: "present",
1160
+ hold: parsed
1161
+ } : {
1162
+ kind: "unreadable",
1163
+ error: "not a migration hold"
1164
+ };
1165
+ } catch (err) {
1166
+ return {
1167
+ kind: "unreadable",
1168
+ error: errMsg$1(err)
1169
+ };
1170
+ }
1171
+ }
1172
+ /** Atomic: a temp file, then a rename — a hold half written is the unreadable case above. */
1173
+ async function writeHold(livePath, hold) {
1174
+ const file = holdPathOf(livePath);
1175
+ const temp = `${file}.tmp`;
1176
+ await promises.writeFile(temp, JSON.stringify(hold), { mode: 384 });
1177
+ await promises.rename(temp, file);
1178
+ }
1179
+ async function clearHold(livePath) {
1180
+ await promises.rm(holdPathOf(livePath), { force: true });
1181
+ }
1182
+ /** Drop `ids` from the hold; an emptied hold is removed. */
1183
+ async function releaseFromHold(livePath, ids) {
1184
+ const read = await readHold(livePath);
1185
+ if (read.kind !== "present") return;
1186
+ const left = read.hold.ids.filter((id) => !ids.includes(id));
1187
+ if (left.length === 0) await clearHold(livePath);
1188
+ else await writeHold(livePath, {
1189
+ ...read.hold,
1190
+ ids: left
1191
+ });
1192
+ }
1193
+ //#endregion
1194
+ //#region src/builtins/sqlite-storage/migrations/migration-engine.ts
1195
+ /**
1196
+ * The boot-time migration engine of the `sqlite-settings` owner (D987).
1197
+ *
1198
+ * It runs from each owned file's `afterOpen` — BEFORE the engine returns a
1199
+ * single provider, so nothing can read a file whose shape is half moved — and
1200
+ * drives, per file: read what is pending, take the pre-migration snapshot, apply
1201
+ * each migration in its own transaction. The per-file work is
1202
+ * `migration-pass.ts`, executed where the connection lives (here for
1203
+ * `camstack.db`, in the file-host worker for `events.db` and `history.db`); this
1204
+ * class holds what is NOT per file: the boot id, the hold, the snapshotter, the
1205
+ * statuses that order one file's migrations after another's, and the log lines.
1206
+ *
1207
+ * The hub always finishes booting: a pass that cannot run is logged and leaves
1208
+ * the file as it was.
1209
+ */
1210
+ /** The order the files are opened in at boot, and so the order a retry re-runs them. */
1211
+ var FILE_ORDER = [
1212
+ "settings",
1213
+ "events",
1214
+ "history"
1215
+ ];
1216
+ var MigrationEngine = class {
1217
+ options;
1218
+ bootId;
1219
+ files = /* @__PURE__ */ new Map();
1220
+ statuses = /* @__PURE__ */ new Map();
1221
+ /** Addon catalogues offered this boot, by owner (M3): the owner drives, the engine gates. */
1222
+ addonMetas = /* @__PURE__ */ new Map();
1223
+ /** Files whose pre-migration snapshot was refused: nothing runs on them, owner or hub. */
1224
+ snapshotRefused = /* @__PURE__ */ new Map();
1225
+ /** Ids whose `startMigration` said proceed and whose `finishMigration` has not landed yet. */
1226
+ started = /* @__PURE__ */ new Set();
1227
+ /** One pass at a time: a retry must not interleave with a boot pass. */
1228
+ tail = Promise.resolve();
1229
+ constructor(options) {
1230
+ this.options = options;
1231
+ this.bootId = options.bootId ?? randomUUID().slice(0, 8);
1232
+ }
1233
+ /** The hook for one file's `afterOpen`. Never throws. */
1234
+ runFile(access) {
1235
+ this.files.set(access.databaseId, access);
1236
+ return this.serialised(() => this.pass(access));
1237
+ }
1238
+ /** Every registered file again, in boot order — what a retry does after it cleared rows. */
1239
+ runAll() {
1240
+ return this.serialised(async () => {
1241
+ this.statuses.clear();
1242
+ for (const databaseId of FILE_ORDER) {
1243
+ const access = this.files.get(databaseId);
1244
+ if (access !== void 0) await this.pass(access);
1245
+ }
1246
+ });
1247
+ }
1248
+ serialised(work) {
1249
+ const run = this.tail.catch(() => void 0).then(work);
1250
+ this.tail = run;
1251
+ return run;
1252
+ }
1253
+ external() {
1254
+ return Object.fromEntries(this.statuses);
1255
+ }
1256
+ async pass(access) {
1257
+ const log = this.options.logger.withTags({ database: access.databaseId });
1258
+ try {
1259
+ const { held, unreadable } = await this.heldIds(access, log);
1260
+ const prepared = await access.call("prepare", {
1261
+ external: this.external(),
1262
+ held
1263
+ });
1264
+ for (const [id, status] of Object.entries(prepared.statuses)) this.statuses.set(id, status);
1265
+ for (const id of prepared.newer) log.warn("migration ledger names an id this code does not know — skipped-newer, nothing written for it", { tags: {
1266
+ migrationId: id,
1267
+ database: access.databaseId
1268
+ } });
1269
+ const heldNow = unreadable ? prepared.runnable : held;
1270
+ const runnable = unreadable ? [] : prepared.runnable;
1271
+ const heldPending = heldNow.filter((id) => {
1272
+ const status = prepared.statuses[id];
1273
+ return status !== void 0 && status !== "applied" && status !== "held";
1274
+ });
1275
+ if (runnable.length === 0 && heldPending.length === 0) return;
1276
+ let refusal = null;
1277
+ let refusalDetail = null;
1278
+ const first = runnable[0];
1279
+ if (first !== void 0) try {
1280
+ const snapshot = await this.options.snapshotterFor(access.livePath).writePreMigration(this.bootId, first);
1281
+ log.info("pre-migration snapshot written", { meta: {
1282
+ snapshotPath: snapshot.snapshotPath,
1283
+ sizeBytes: snapshot.sizeBytes,
1284
+ first
1285
+ } });
1286
+ } catch (err) {
1287
+ refusal = "snapshot-refused";
1288
+ refusalDetail = errMsg$1(err);
1289
+ log.error("pre-migration snapshot refused — no migration runs on this file, it keeps its old shape", { meta: {
1290
+ error: refusalDetail,
1291
+ pending: runnable
1292
+ } });
1293
+ }
1294
+ const applied = await access.call("apply", {
1295
+ bootId: this.bootId,
1296
+ codeVersion: this.options.codeVersion,
1297
+ external: this.external(),
1298
+ held: heldNow,
1299
+ refusal,
1300
+ refusalDetail
1301
+ });
1302
+ this.record(applied, log);
1303
+ } catch (err) {
1304
+ log.error("migration pass could not run on this file — nothing was changed by it", { meta: { error: errMsg$1(err) } });
1305
+ }
1306
+ }
1307
+ /** The ids a restore holds for THIS code version; another version drops the hold. */
1308
+ async heldIds(access, log) {
1309
+ const read = await readHold(access.livePath);
1310
+ if (read.kind === "absent") return {
1311
+ held: [],
1312
+ unreadable: false
1313
+ };
1314
+ if (read.kind === "unreadable") {
1315
+ log.warn("migration hold file is unreadable — every pending migration of this file is held", { meta: { error: read.error } });
1316
+ return {
1317
+ held: [],
1318
+ unreadable: true
1319
+ };
1320
+ }
1321
+ if (read.hold.codeVersion !== this.options.codeVersion) {
1322
+ log.info("migration hold dropped — it was written for another code version", { meta: {
1323
+ heldFor: read.hold.codeVersion,
1324
+ running: this.options.codeVersion
1325
+ } });
1326
+ await clearHold(access.livePath);
1327
+ return {
1328
+ held: [],
1329
+ unreadable: false
1330
+ };
1331
+ }
1332
+ return {
1333
+ held: read.hold.ids,
1334
+ unreadable: false
1335
+ };
1336
+ }
1337
+ record(applied, log) {
1338
+ for (const [id, status] of Object.entries(applied.statuses)) this.statuses.set(id, status);
1339
+ const failed = [];
1340
+ const changed = [];
1341
+ for (const outcome of applied.outcomes) {
1342
+ this.logOutcome(outcome, log);
1343
+ if (outcome.outcome === "failed" || outcome.reason === "snapshot-refused") failed.push(outcome.id);
1344
+ if (outcome.outcome === "applied") changed.push(outcome.id);
1345
+ }
1346
+ if (failed.length > 0) this.options.announce?.("failed", failed);
1347
+ else if (changed.length > 0) this.options.announce?.("applied", changed);
1348
+ }
1349
+ logOutcome(outcome, log) {
1350
+ const tags = {
1351
+ migrationId: outcome.id,
1352
+ owner: outcome.owner
1353
+ };
1354
+ if (outcome.outcome === "applied") log.info("migration applied", {
1355
+ tags,
1356
+ meta: { rowsChanged: outcome.rowsChanged }
1357
+ });
1358
+ else if (outcome.outcome === "failed") log.error("migration failed", {
1359
+ tags,
1360
+ meta: { error: outcome.error }
1361
+ });
1362
+ else log.warn(`migration ${outcome.outcome}`, {
1363
+ tags,
1364
+ meta: { reason: outcome.reason }
1365
+ });
1366
+ }
1367
+ accessOf(database) {
1368
+ const access = this.files.get(database);
1369
+ if (access === void 0) throw new Error(`database "${database}" is not open`);
1370
+ return access;
1371
+ }
1372
+ async listLedger() {
1373
+ const entries = [];
1374
+ for (const databaseId of FILE_ORDER) {
1375
+ const access = this.files.get(databaseId);
1376
+ if (access !== void 0) entries.push(...await access.call("ledger", {}));
1377
+ }
1378
+ return entries.map((entry) => this.judgeAddonRow(entry));
1379
+ }
1380
+ /** An applied row of a DECLARED owner whose id that owner no longer lists: a newer database. */
1381
+ judgeAddonRow(entry) {
1382
+ const declared = this.addonMetas.get(entry.owner);
1383
+ if (declared === void 0 || entry.status !== "applied") return entry;
1384
+ return declared.some((meta) => meta.id === entry.id) ? entry : {
1385
+ ...entry,
1386
+ status: "skipped-newer"
1387
+ };
1388
+ }
1389
+ async markFailed(id, error) {
1390
+ const addon = this.addonMetaOf(id);
1391
+ if (addon !== void 0) {
1392
+ const entry = await this.accessOf(ledgerFileOf(addon)).call("record", {
1393
+ meta: addon,
1394
+ status: "failed",
1395
+ reason: null,
1396
+ error,
1397
+ summary: null,
1398
+ bootId: this.bootId,
1399
+ codeVersion: this.options.codeVersion
1400
+ });
1401
+ this.options.announce?.("failed", [id]);
1402
+ return entry;
1403
+ }
1404
+ for (const access of this.files.values()) {
1405
+ const entry = await access.call("markFailed", {
1406
+ id,
1407
+ error,
1408
+ bootId: this.bootId
1409
+ });
1410
+ if (entry !== null) {
1411
+ this.options.announce?.("failed", [id]);
1412
+ return entry;
1413
+ }
1414
+ }
1415
+ throw new Error(`migration ${id} is not a hub-store migration`);
1416
+ }
1417
+ /** `id` and everything that depends on it, directly or through its owner's order. */
1418
+ dependentsOf(id) {
1419
+ const ordered = orderMigrations(this.allMetas());
1420
+ const out = new Set([id]);
1421
+ for (const meta of ordered) {
1422
+ const previousInOwner = ordered.filter((candidate) => candidate.owner === meta.owner && candidate.seq < meta.seq).at(-1);
1423
+ if ([...meta.dependsOn, ...previousInOwner === void 0 ? [] : [previousInOwner.id]].some((dep) => out.has(dep))) out.add(meta.id);
1424
+ }
1425
+ return [...out];
1426
+ }
1427
+ async retry(id) {
1428
+ if (!this.allMetas().some((meta) => meta.id === id)) throw new Error(`migration ${id} is not a known migration`);
1429
+ const ids = this.dependentsOf(id);
1430
+ for (const access of this.files.values()) {
1431
+ await access.call("reset", { ids });
1432
+ await releaseFromHold(access.livePath, ids);
1433
+ }
1434
+ await this.runAll();
1435
+ const addonIds = ids.filter((candidate) => this.addonMetaOf(candidate) !== void 0);
1436
+ if (addonIds.length > 0) this.options.logger.info("addon migrations cleared — they run when their owner next boots", { meta: { ids: addonIds } });
1437
+ return (await this.listLedger()).filter((entry) => ids.includes(entry.id));
1438
+ }
1439
+ /**
1440
+ * Schedule the restore of a pre-migration snapshot and hold what it undoes.
1441
+ * The ids held are the ledger rows written under the snapshot's boot id: the
1442
+ * snapshot was taken at the start of that pass, so everything the pass wrote
1443
+ * is what the restore reverts.
1444
+ */
1445
+ async restorePreMigration(database, snapshotId) {
1446
+ if (!/^[A-Za-z0-9_-]+$/.test(snapshotId)) throw new Error(`"${snapshotId}" is not a snapshot id`);
1447
+ const access = this.accessOf(database);
1448
+ const snapshotPath = path.join(path.resolve(access.livePath) + PRE_MIGRATION_DIR_SUFFIX, `${snapshotId}.db`);
1449
+ await promises.stat(snapshotPath);
1450
+ const bootId = snapshotId.split("-")[0];
1451
+ const held = (await access.call("ledger", {})).filter((entry) => entry.bootId === bootId && (entry.status === "applied" || entry.status === "failed" || entry.status === "blocked")).map((entry) => entry.id);
1452
+ if (this.options.scheduleRestore === void 0) throw new Error("restoring a pre-migration snapshot is not available here");
1453
+ await writeHold(access.livePath, {
1454
+ codeVersion: this.options.codeVersion,
1455
+ ids: held,
1456
+ snapshotId
1457
+ });
1458
+ try {
1459
+ await this.options.scheduleRestore({
1460
+ livePath: path.resolve(access.livePath),
1461
+ snapshotPath
1462
+ });
1463
+ } catch (err) {
1464
+ await clearHold(access.livePath);
1465
+ throw err;
1466
+ }
1467
+ this.options.logger.warn("restore of a pre-migration snapshot scheduled for the next restart", { meta: {
1468
+ database,
1469
+ snapshotId,
1470
+ held
1471
+ } });
1472
+ return { held };
1473
+ }
1474
+ async dryRun(id) {
1475
+ if (this.addonMetaOf(id) !== void 0) throw new Error(`migration ${id} is addon-owned: its body runs in its owner, so it has no dry run`);
1476
+ const own = this.options.catalogue.find((m) => m.meta.id === id);
1477
+ if (own === void 0) throw new Error(`migration ${id} is not a hub-store migration`);
1478
+ const database = own.meta.store;
1479
+ if (database !== "settings" && database !== "events" && database !== "history") throw new Error(`migration ${id} does not run on a database file`);
1480
+ return this.accessOf(database).call("dryRun", { id });
1481
+ }
1482
+ /** The catalogued migrations that are not applied, with the state the ledger holds. */
1483
+ async listPending(owner) {
1484
+ const ledger = new Map((await this.listLedger()).map((entry) => [entry.id, entry]));
1485
+ const out = [];
1486
+ for (const meta of this.allMetas()) {
1487
+ if (owner !== void 0 && meta.owner !== owner) continue;
1488
+ const database = meta.owner === "hub" ? databaseOfStore(meta.store) : ledgerFileOf(meta);
1489
+ if (database === null) continue;
1490
+ const row = ledger.get(meta.id);
1491
+ if (row?.status === "applied") continue;
1492
+ const state = row === void 0 ? "pending" : row.status === "failed" || row.status === "blocked" || row.status === "held" ? row.status : "pending";
1493
+ out.push({
1494
+ meta,
1495
+ database,
1496
+ state,
1497
+ reason: row?.reason ?? null
1498
+ });
1499
+ }
1500
+ return out;
1501
+ }
1502
+ hubMetas() {
1503
+ return this.options.catalogue.map((m) => m.meta);
1504
+ }
1505
+ /** Every migration the engine knows this boot: the hub's, then each declared owner's. */
1506
+ allMetas() {
1507
+ return [...this.hubMetas(), ...[...this.addonMetas.values()].flat()];
1508
+ }
1509
+ addonMetaOf(id) {
1510
+ for (const metas of this.addonMetas.values()) {
1511
+ const found = metas.find((meta) => meta.id === id);
1512
+ if (found !== void 0) return found;
1513
+ }
1514
+ }
1515
+ /** An addon drives only its own catalogue: the transport-stamped caller must be the owner. */
1516
+ assertOwnerCaller(owner, caller) {
1517
+ if (caller === null || caller.length === 0) throw new MigrationOwnerRefusal("no-caller-identity", `migrations for "${owner}" refused: no caller identity — an owner is bound to the authenticated addon`);
1518
+ if (caller !== owner) throw new MigrationOwnerRefusal("caller-not-owner", `migrations for "${owner}" refused: caller "${caller}" is not the owner "${owner}"`);
1519
+ }
1520
+ /** Why an owner's catalogue is refused whole, or `null` when it can be taken. */
1521
+ refusalOfCatalogue(owner, metas) {
1522
+ if (owner === "hub") return "the hub catalogue ships with the hub, an addon cannot declare it";
1523
+ for (const meta of metas) {
1524
+ if (meta.owner !== owner) return `${meta.id} is owned by "${meta.owner}", not "${owner}"`;
1525
+ if (meta.level === "hub-store") return `${meta.id}: an addon migration is not level "hub-store"`;
1526
+ if (meta.bodyKind === "sql") return `${meta.id}: "sql" is a hub-only body kind`;
1527
+ if (meta.bodyKind === "plan" && databaseOfStore(meta.store) === null) return `${meta.id}: a plan edits a database file, store "${meta.store}" is not one`;
1528
+ const file = ledgerFileOf(meta);
1529
+ if (!this.files.has(file)) return `${meta.id}: database "${file}" is not open`;
1530
+ }
1531
+ const issues = catalogueIssues([
1532
+ ...this.hubMetas(),
1533
+ ...[...this.addonMetas.entries()].filter(([other]) => other !== owner).flatMap(([, m]) => m),
1534
+ ...metas
1535
+ ]).filter((issue) => !(issue.code === "unknown-dependency" && issue.ids[1] !== void 0 && !issue.ids[1].startsWith(`${owner}/`)));
1536
+ return issues.length === 0 ? null : issues.map((issue) => issue.message).join("; ");
1537
+ }
1538
+ /**
1539
+ * An addon offers its catalogue at ITS boot. The engine checks it with every other
1540
+ * owner's, tells the owner what to run in the framework's order, and takes the
1541
+ * pre-migration snapshot of each file a pending step touches. Refuses a malformed
1542
+ * catalogue whole (throws, writes nothing). A hold from a restore is honoured as for
1543
+ * a hub migration.
1544
+ */
1545
+ declareOwner(owner, offered, caller) {
1546
+ const run = this.tail.catch(() => void 0).then(() => {
1547
+ this.assertOwnerCaller(owner, caller);
1548
+ return this.declare(owner, offered);
1549
+ });
1550
+ this.tail = run;
1551
+ return run;
1552
+ }
1553
+ async declare(owner, offered) {
1554
+ const metas = offered.map((meta) => MigrationMetaSchema.parse(meta));
1555
+ const refusal = this.refusalOfCatalogue(owner, metas);
1556
+ if (refusal !== null) {
1557
+ this.options.logger.error("addon migration catalogue refused — none of it runs", {
1558
+ tags: { owner },
1559
+ meta: { reason: refusal }
1560
+ });
1561
+ throw new Error(`migration catalogue of "${owner}" refused: ${refusal}`);
1562
+ }
1563
+ const ordered = orderMigrations(metas);
1564
+ const rows = new Map((await this.listLedger()).map((entry) => [entry.id, entry]));
1565
+ const steps = [];
1566
+ const firstRunnable = /* @__PURE__ */ new Map();
1567
+ const log = this.options.logger.withTags({ owner });
1568
+ const holds = /* @__PURE__ */ new Map();
1569
+ for (const file of new Set(ordered.map(ledgerFileOf))) holds.set(file, await this.heldIds(this.accessOf(file), log));
1570
+ for (const meta of ordered) {
1571
+ const file = ledgerFileOf(meta);
1572
+ const state = rows.get(meta.id)?.status ?? "pending";
1573
+ const { held, unreadable } = holds.get(file) ?? {
1574
+ held: [],
1575
+ unreadable: false
1576
+ };
1577
+ if (state === "applied") steps.push({
1578
+ id: meta.id,
1579
+ action: "skip",
1580
+ state
1581
+ });
1582
+ else if (unreadable || held.includes(meta.id)) {
1583
+ await this.writeLedgerRow(meta, "held", "restored-pre-migration", null, null);
1584
+ steps.push({
1585
+ id: meta.id,
1586
+ action: "skip",
1587
+ state: "held"
1588
+ });
1589
+ } else {
1590
+ if (!firstRunnable.has(file)) firstRunnable.set(file, meta.id);
1591
+ steps.push({
1592
+ id: meta.id,
1593
+ action: "run",
1594
+ state
1595
+ });
1596
+ }
1597
+ }
1598
+ for (const entry of rows.values()) if (entry.owner === owner && !metas.some((meta) => meta.id === entry.id) && entry.status === "applied") log.warn("migration ledger names an id this addon does not declare — skipped-newer, nothing written for it", { tags: { migrationId: entry.id } });
1599
+ let snapshot = "none";
1600
+ for (const [file, first] of firstRunnable) if (await this.snapshotBefore(file, first, log) === "refused") snapshot = "refused";
1601
+ else if (snapshot === "none") snapshot = "written";
1602
+ this.addonMetas.set(owner, metas);
1603
+ return {
1604
+ bootId: this.bootId,
1605
+ snapshot,
1606
+ steps
1607
+ };
1608
+ }
1609
+ /** The pre-migration snapshot of one file, once per boot of this engine per file and first id. */
1610
+ async snapshotBefore(file, firstId, log) {
1611
+ const access = this.accessOf(file);
1612
+ try {
1613
+ const snapshot = await this.options.snapshotterFor(access.livePath).writePreMigration(this.bootId, firstId);
1614
+ this.snapshotRefused.delete(file);
1615
+ log.info("pre-migration snapshot written", { meta: {
1616
+ snapshotPath: snapshot.snapshotPath,
1617
+ sizeBytes: snapshot.sizeBytes,
1618
+ first: firstId
1619
+ } });
1620
+ return "written";
1621
+ } catch (err) {
1622
+ const detail = errMsg$1(err);
1623
+ this.snapshotRefused.set(file, detail);
1624
+ log.error("pre-migration snapshot refused — no addon migration runs on this file", {
1625
+ tags: { database: file },
1626
+ meta: {
1627
+ error: detail,
1628
+ first: firstId
1629
+ }
1630
+ });
1631
+ return "refused";
1632
+ }
1633
+ }
1634
+ async writeLedgerRow(meta, status, reason, error, summary) {
1635
+ return this.accessOf(ledgerFileOf(meta)).call("record", {
1636
+ meta,
1637
+ status,
1638
+ reason,
1639
+ error,
1640
+ summary,
1641
+ bootId: this.bootId,
1642
+ codeVersion: this.options.codeVersion
1643
+ });
1644
+ }
1645
+ /** The gate before an owner migration runs: the ledger decides, and a refusal is on the record. */
1646
+ startMigration(id, caller) {
1647
+ const run = this.tail.catch(() => void 0).then(() => this.start(id, caller));
1648
+ this.tail = run;
1649
+ return run;
1650
+ }
1651
+ async start(id, caller) {
1652
+ const meta = this.addonMetaOf(id);
1653
+ if (meta === void 0) throw new Error(`migration ${id} was not declared by any owner this boot`);
1654
+ this.assertOwnerCaller(meta.owner, caller);
1655
+ this.started.delete(id);
1656
+ const ledger = new Map((await this.listLedger()).map((entry) => [entry.id, entry.status]));
1657
+ const own = ledger.get(id) ?? "pending";
1658
+ if (own === "applied" || own === "held") return {
1659
+ proceed: false,
1660
+ state: own,
1661
+ reason: null
1662
+ };
1663
+ const refused = this.snapshotRefused.get(ledgerFileOf(meta));
1664
+ if (refused !== void 0) {
1665
+ await this.writeLedgerRow(meta, "blocked", "snapshot-refused", refused, null);
1666
+ return {
1667
+ proceed: false,
1668
+ state: "blocked",
1669
+ reason: "snapshot-refused"
1670
+ };
1671
+ }
1672
+ const unmet = this.predecessorsOf(meta).map((dep) => [dep, ledger.get(dep) ?? "pending"]).find(([, status]) => status !== "applied");
1673
+ if (unmet !== void 0) {
1674
+ const reason = `dependency-${unmet[1]}:${unmet[0]}`;
1675
+ await this.writeLedgerRow(meta, "blocked", reason, null, null);
1676
+ return {
1677
+ proceed: false,
1678
+ state: "blocked",
1679
+ reason
1680
+ };
1681
+ }
1682
+ this.started.add(id);
1683
+ return {
1684
+ proceed: true,
1685
+ state: own,
1686
+ reason: null
1687
+ };
1688
+ }
1689
+ /** `dependsOn` and the previous `seq` of the owner, across every owner's catalogue. */
1690
+ predecessorsOf(meta) {
1691
+ const previous = this.allMetas().filter((other) => other.owner === meta.owner && other.seq < meta.seq).sort((a, b) => a.seq - b.seq).at(-1);
1692
+ return [...meta.dependsOn, ...previous === void 0 ? [] : [previous.id]];
1693
+ }
1694
+ /** The owner's result for one migration, recorded (and, for a plan, applied) atomically. */
1695
+ finishMigration(id, result, caller) {
1696
+ const run = this.tail.catch(() => void 0).then(() => this.finish(id, result, caller));
1697
+ this.tail = run;
1698
+ return run;
1699
+ }
1700
+ /** The gates `start` applied, read again: the ledger may have moved since the owner began. */
1701
+ async assertFinishable(id, meta) {
1702
+ const ledger = new Map((await this.listLedger()).map((entry) => [entry.id, entry.status]));
1703
+ const own = ledger.get(id) ?? "pending";
1704
+ if (own === "applied") throw new Error(`migration ${id} is already applied — nothing recorded`);
1705
+ if (own === "held") throw new Error(`migration ${id} is held by a restore — nothing recorded`);
1706
+ if (!this.started.has(id)) throw new Error(`migration ${id} was not started — call startMigration first, nothing recorded`);
1707
+ if (this.snapshotRefused.get(ledgerFileOf(meta)) !== void 0) throw new Error(`migration ${id}: the pre-migration snapshot was refused — nothing recorded`);
1708
+ const unmet = this.predecessorsOf(meta).map((dep) => [dep, ledger.get(dep) ?? "pending"]).find(([, status]) => status !== "applied");
1709
+ if (unmet !== void 0) throw new Error(`migration ${id}: predecessor ${unmet[0]} is ${unmet[1]}, not applied — nothing recorded`);
1710
+ }
1711
+ async finish(id, result, caller) {
1712
+ const meta = this.addonMetaOf(id);
1713
+ if (meta === void 0) throw new Error(`migration ${id} was not declared by any owner this boot`);
1714
+ this.assertOwnerCaller(meta.owner, caller);
1715
+ await this.assertFinishable(id, meta);
1716
+ const log = this.options.logger.withTags({ owner: meta.owner });
1717
+ const settled = async () => {
1718
+ if (result.kind === "failed") {
1719
+ await this.writeLedgerRow(meta, "failed", null, result.error, null);
1720
+ return {
1721
+ status: "failed",
1722
+ error: result.error,
1723
+ rowsChanged: 0
1724
+ };
1725
+ }
1726
+ if (result.kind === "plan") {
1727
+ if (meta.bodyKind !== "plan") throw new Error(`${id} is a "${meta.bodyKind}" migration, it cannot report a plan`);
1728
+ return await this.accessOf(ledgerFileOf(meta)).call("applyPlan", {
1729
+ meta,
1730
+ plan: result.plan,
1731
+ bootId: this.bootId,
1732
+ codeVersion: this.options.codeVersion
1733
+ });
1734
+ }
1735
+ if (meta.bodyKind !== "procedure") throw new Error(`${id} is a "${meta.bodyKind}" migration, it cannot report a procedure outcome`);
1736
+ await this.writeLedgerRow(meta, "applied", null, null, {
1737
+ outcome: result.result.outcome,
1738
+ ...result.result.summary
1739
+ });
1740
+ return {
1741
+ status: "applied",
1742
+ error: null,
1743
+ rowsChanged: 0
1744
+ };
1745
+ };
1746
+ const outcome = await settled();
1747
+ this.started.delete(id);
1748
+ this.logOutcome({
1749
+ id,
1750
+ owner: meta.owner,
1751
+ outcome: outcome.status,
1752
+ rowsChanged: outcome.rowsChanged,
1753
+ error: outcome.error,
1754
+ reason: null
1755
+ }, log);
1756
+ this.options.announce?.(outcome.status === "failed" ? "failed" : "applied", [id]);
1757
+ return outcome;
1758
+ }
1759
+ };
1760
+ /** A call an addon is not entitled to make: its reason is typed, its message names it. */
1761
+ var MigrationOwnerRefusal = class extends Error {
1762
+ reason;
1763
+ constructor(reason, message) {
1764
+ super(message);
1765
+ this.reason = reason;
1766
+ this.name = "MigrationOwnerRefusal";
1767
+ }
1768
+ };
1769
+ /** The database file an owner migration's ledger row lives in: its store, else `camstack.db`. */
1770
+ function ledgerFileOf(meta) {
1771
+ return databaseOfStore(meta.store) ?? "settings";
1772
+ }
1773
+ //#endregion
1774
+ //#region src/builtins/sqlite-storage/migrations/migration-actions.ts
1775
+ /**
1776
+ * The custom action the Alert Center's "Retry" button invokes (D987): an alert
1777
+ * carries `{ addonId, action, input }`, so a retry is an addon action, not a
1778
+ * route. `auth: 'admin'`, a mutation.
1779
+ */
1780
+ var retryMigrationInput = z.object({ id: z.string().min(1) });
1781
+ var migrationActions = defineCustomActions({ retryMigration: customAction(retryMigrationInput, z.object({ retried: z.array(z.string()) }), {
1782
+ kind: "mutation",
1783
+ auth: "admin"
1784
+ }) });
1785
+ //#endregion
1786
+ //#region src/builtins/sqlite-storage/migrations/migration-restore-marker.ts
1787
+ /**
1788
+ * Writes the marker the launcher reads to promote a pre-migration snapshot
1789
+ * (`server/backend/src/pre-migration-restore.ts`). The launcher has no
1790
+ * `@camstack/*` imports, so the contract is a plain JSON file, written here with
1791
+ * paths relative to the data dir. Requests accumulate: a second restore for
1792
+ * another database must not erase the first.
1793
+ */
1794
+ var PRE_MIGRATION_RESTORE_MARKER = ".pending-migration-restore.json";
1795
+ function isMarkerRequest(value) {
1796
+ return typeof value === "object" && value !== null && "livePath" in value && typeof value.livePath === "string" && "snapshotPath" in value && typeof value.snapshotPath === "string";
1797
+ }
1798
+ async function existingRequests(markerPath) {
1799
+ let raw;
1800
+ try {
1801
+ raw = await promises.readFile(markerPath, "utf-8");
1802
+ } catch {
1803
+ return [];
1804
+ }
1805
+ const parsed = JSON.parse(raw);
1806
+ if (typeof parsed !== "object" || parsed === null || !("requests" in parsed)) return [];
1807
+ const requests = parsed.requests;
1808
+ return Array.isArray(requests) ? requests.filter(isMarkerRequest) : [];
1809
+ }
1810
+ async function scheduleMigrationRestore(dataRoot, request) {
1811
+ const markerPath = path.join(dataRoot, PRE_MIGRATION_RESTORE_MARKER);
1812
+ const live = path.relative(dataRoot, request.livePath);
1813
+ const snapshot = path.relative(dataRoot, request.snapshotPath);
1814
+ const kept = (await existingRequests(markerPath)).filter((entry) => entry.livePath !== live);
1815
+ const body = JSON.stringify({ requests: [...kept, {
1816
+ livePath: live,
1817
+ snapshotPath: snapshot
1818
+ }] });
1819
+ const temp = `${markerPath}.tmp`;
1820
+ await promises.writeFile(temp, body, { mode: 384 });
1821
+ await promises.rename(temp, markerPath);
1822
+ }
1823
+ //#endregion
1824
+ //#region src/builtins/sqlite-storage/migrations/migrations-provider.ts
1825
+ /**
1826
+ * The addon the transport stamped on the call (`callerAddonId`, never in an input
1827
+ * schema, stripped from an HTTP/WS request); `null` for an unstamped call.
1828
+ */
1829
+ function callerOf(input) {
1830
+ const raw = Reflect.get(input, "callerAddonId");
1831
+ return typeof raw === "string" && raw.length > 0 ? raw : null;
1832
+ }
1833
+ var MigrationsProvider = class {
1834
+ engine;
1835
+ constructor(engine) {
1836
+ this.engine = engine;
1837
+ }
1838
+ async listLedger() {
1839
+ return { entries: [...await this.engine.listLedger()] };
1840
+ }
1841
+ async listPending(input) {
1842
+ return { pending: [...await this.engine.listPending(input.owner)] };
1843
+ }
1844
+ dryRun(input) {
1845
+ return this.engine.dryRun(input.id);
1846
+ }
1847
+ markFailed(input) {
1848
+ return this.engine.markFailed(input.id, input.error);
1849
+ }
1850
+ async retry(input) {
1851
+ return { entries: [...await this.engine.retry(input.id)] };
1852
+ }
1853
+ declareOwner(input) {
1854
+ return this.engine.declareOwner(input.owner, input.metas, callerOf(input)).then((out) => ({
1855
+ ...out,
1856
+ steps: [...out.steps]
1857
+ }));
1858
+ }
1859
+ startMigration(input) {
1860
+ return this.engine.startMigration(input.id, callerOf(input));
1861
+ }
1862
+ finishMigration(input) {
1863
+ return this.engine.finishMigration(input.id, input.result, callerOf(input));
1864
+ }
1865
+ async restorePreMigration(input) {
1866
+ const { held } = await this.engine.restorePreMigration(input.database, input.snapshotId);
1867
+ return {
1868
+ scheduled: true,
1869
+ held: [...held],
1870
+ restartRequired: true
1871
+ };
1872
+ }
1873
+ };
1874
+ //#endregion
1875
+ //#region src/builtins/sqlite-storage/placement-router.ts
1876
+ function scopedName(namespace, collection) {
1877
+ return namespace ? `${namespace}:${collection}` : collection;
1878
+ }
1879
+ var PlacementRouter = class {
1880
+ files = /* @__PURE__ */ new Map();
1881
+ opening = /* @__PURE__ */ new Map();
1882
+ /** `events` / `history` collections only; absence means `settings`. */
1883
+ placement = /* @__PURE__ */ new Map();
1884
+ open;
1885
+ logger;
1886
+ constructor(options) {
1887
+ this.open = options.open;
1888
+ this.logger = options.logger;
1889
+ for (const file of options.files) this.files.set(file.databaseId, file);
1890
+ this.rebuildPlacement();
1891
+ }
1892
+ /**
1893
+ * Rebuild `collection → file` from each file's own declarations. A table
1894
+ * declared in two files is refused: nothing downstream could tell which is
1895
+ * the real one.
1896
+ */
1897
+ rebuildPlacement() {
1898
+ this.placement.clear();
1899
+ const owner = /* @__PURE__ */ new Map();
1900
+ for (const databaseId of DATA_STORE_DATABASES) {
1901
+ const file = this.files.get(databaseId);
1902
+ if (file === void 0) continue;
1903
+ for (const name of file.declaredCollections()) {
1904
+ const other = owner.get(name);
1905
+ if (other !== void 0) throw new DuplicatePlacementError(name, other, databaseId);
1906
+ owner.set(name, databaseId);
1907
+ if (databaseId !== "settings") this.placement.set(name, databaseId);
1908
+ }
1909
+ }
1910
+ this.logger.info("placement: database files open", { meta: { files: DATA_STORE_DATABASES.filter((id) => this.files.has(id)).map((id) => ({
1911
+ database: id,
1912
+ collections: this.files.get(id)?.declaredCollections().size ?? 0
1913
+ })) } });
1914
+ }
1915
+ /** The open file of an id; `settings` is always there. */
1916
+ fileOf(databaseId) {
1917
+ const file = this.files.get(databaseId);
1918
+ if (file === void 0) throw new Error(`placement: database "${databaseId}" is not open`);
1919
+ return file;
1920
+ }
1921
+ /** The database a table is served from. */
1922
+ databaseOf(table) {
1923
+ return this.placement.get(table) ?? "settings";
1924
+ }
1925
+ /**
1926
+ * The file that hosts records of `databaseId`, created by the first
1927
+ * declaration that names it (`events`). `history` never hosts records.
1928
+ */
1929
+ async recordsFileFor(databaseId) {
1930
+ if (databaseId === "history") throw new Error("placement: history.db is device-history's and never hosts records");
1931
+ return this.openFile(databaseId);
1932
+ }
1933
+ /** The files currently open, settings first. */
1934
+ openFiles() {
1935
+ return DATA_STORE_DATABASES.flatMap((id) => {
1936
+ const file = this.files.get(id);
1937
+ return file === void 0 ? [] : [file];
1938
+ });
1939
+ }
1940
+ async openFile(databaseId) {
1941
+ const open = this.files.get(databaseId);
1942
+ if (open !== void 0) return open;
1943
+ const inFlight = this.opening.get(databaseId);
1944
+ if (inFlight !== void 0) return inFlight;
1945
+ const opening = this.open(databaseId).then((file) => {
1946
+ this.files.set(databaseId, file);
1947
+ this.opening.delete(databaseId);
1948
+ return file;
1949
+ });
1950
+ this.opening.set(databaseId, opening);
1951
+ try {
1952
+ return await opening;
1953
+ } catch (err) {
1954
+ this.opening.delete(databaseId);
1955
+ throw err;
1956
+ }
1957
+ }
1958
+ route(namespace, collection, op, input) {
1959
+ return this.fileOf(this.databaseOf(scopedName(namespace, collection))).call(op, input);
1960
+ }
1961
+ async declareCollection(input) {
1962
+ const table = scopedName(input.namespace, input.collection);
1963
+ const target = input.database ?? "settings";
1964
+ for (const file of this.openFiles()) {
1965
+ if (file.databaseId === target) continue;
1966
+ if (file.declaredCollections().has(table) || await file.hasTable(table)) {
1967
+ this.logger.error("placement: declaration refused — the table lives in another file", {
1968
+ tags: { database: target },
1969
+ meta: {
1970
+ table,
1971
+ livesIn: file.databaseId,
1972
+ declaredFor: target
1973
+ }
1974
+ });
1975
+ throw new CollectionPlacementError(table, file.databaseId, target);
1976
+ }
1977
+ }
1978
+ await (await this.openFile(target)).call("declareCollection", input);
1979
+ if (target !== "settings") this.placement.set(table, target);
1980
+ }
1981
+ async transact(input) {
1982
+ const targets = /* @__PURE__ */ new Set();
1983
+ if (input.guard !== void 0) targets.add(this.databaseOf(scopedName(input.namespace, input.guard.collection)));
1984
+ for (const op of input.ops) targets.add(this.databaseOf(scopedName(input.namespace, op.collection)));
1985
+ if (targets.size > 1) throw new CrossDatabaseTransactError([...targets]);
1986
+ const [only] = targets;
1987
+ return this.fileOf(only ?? "settings").call("transact", input);
1988
+ }
1989
+ async getEngineInfo() {
1990
+ return {
1991
+ engineId: "sqlite",
1992
+ kind: "relational",
1993
+ displayName: "SQLite (WAL)"
1994
+ };
1995
+ }
1996
+ get(input) {
1997
+ return this.route(input.namespace, input.collection, "get", input);
1998
+ }
1999
+ set(input) {
2000
+ return this.route(input.namespace, input.collection, "set", input);
2001
+ }
2002
+ query(input) {
2003
+ return this.route(input.namespace, input.collection, "query", input);
2004
+ }
2005
+ insert(input) {
2006
+ return this.route(input.namespace, input.collection, "insert", input);
2007
+ }
2008
+ upsert(input) {
2009
+ return this.route(input.namespace, input.collection, "upsert", input);
2010
+ }
2011
+ insertMany(input) {
2012
+ return this.route(input.namespace, input.collection, "insertMany", input);
2013
+ }
2014
+ upsertMany(input) {
2015
+ return this.route(input.namespace, input.collection, "upsertMany", input);
2016
+ }
2017
+ update(input) {
2018
+ return this.route(input.namespace, input.collection, "update", input);
2019
+ }
2020
+ delete(input) {
2021
+ return this.route(input.namespace, input.collection, "delete", input);
2022
+ }
2023
+ deleteWhere(input) {
2024
+ return this.route(input.namespace, input.collection, "deleteWhere", input);
2025
+ }
2026
+ updateWhere(input) {
2027
+ return this.route(input.namespace, input.collection, "updateWhere", input);
2028
+ }
2029
+ count(input) {
2030
+ return this.route(input.namespace, input.collection, "count", input);
2031
+ }
2032
+ aggregate(input) {
2033
+ return this.route(input.namespace, input.collection, "aggregate", input);
2034
+ }
2035
+ histogram(input) {
2036
+ return this.route(input.namespace, input.collection, "histogram", input);
2037
+ }
2038
+ isEmpty(input) {
2039
+ return this.route(input.namespace, input.collection, "isEmpty", input);
2040
+ }
2041
+ };
2042
+ //#endregion
2043
+ //#region src/builtins/sqlite-storage/records/records-provider.ts
2044
+ /**
2045
+ * The `records` capability of the engine (D881): resolves WHO is calling and
2046
+ * WHICH file a kind lives in, then hands the call to that file's records engine.
2047
+ *
2048
+ * - **Owner** = the transport-stamped `callerAddonId` (as device-history's
2049
+ * `not-owner` and the keychain). It is never a field of any input; a call with
2050
+ * no stamp is refused `records/no-caller`.
2051
+ * - **Placement**: a kind's file is its declaration's `database`. The map is
2052
+ * rebuilt from each open file's own `_record_kinds` at boot and updated on
2053
+ * declaration. A kind declared for another file than the one it lives in is
2054
+ * refused (the engine never moves data, D853).
2055
+ * - **No adoption** (D900): the records migration is closed. A declaration
2056
+ * reads no legacy table.
2057
+ */
2058
+ /** The caller the transport stamped, or a refusal. */
2059
+ function recordsCallerOf(input) {
2060
+ const raw = input !== null && typeof input === "object" ? Reflect.get(input, "callerAddonId") : void 0;
2061
+ if (typeof raw !== "string" || raw.length === 0) throw new NoCallerError("the call carries no caller identity; records are reached through ctx.records");
2062
+ return normalizeSecretOwner(raw);
2063
+ }
2064
+ function keyOf(owner, kind) {
2065
+ return `${owner}\u0000${kind}`;
2066
+ }
2067
+ var RecordsProvider = class {
2068
+ router;
2069
+ logger;
2070
+ placement = /* @__PURE__ */ new Map();
2071
+ constructor(router, logger) {
2072
+ this.router = router;
2073
+ this.logger = logger;
2074
+ }
2075
+ /** Rebuild the placement map from every open file's catalog. Call once, after the files are open. */
2076
+ async init() {
2077
+ this.placement.clear();
2078
+ for (const file of this.router.openFiles()) {
2079
+ if (file.databaseId === "history") continue;
2080
+ const kinds = await file.records("listKinds", {});
2081
+ for (const k of kinds) {
2082
+ if (k.state === "dropped") continue;
2083
+ const key = keyOf(k.owner, k.kind);
2084
+ const other = this.placement.get(key);
2085
+ if (other !== void 0 && other !== file.databaseId) throw new DeclarationRefusedError(`kind "${k.kind}" of "${k.owner}" is in both "${other}" and "${file.databaseId}"; the layout is corrupt and is not served`);
2086
+ this.placement.set(key, file.databaseId);
2087
+ }
2088
+ }
2089
+ this.logger.info("records: catalog loaded", { meta: { kinds: this.placement.size } });
2090
+ }
2091
+ fileOf(owner, kind) {
2092
+ const database = this.placement.get(keyOf(owner, kind));
2093
+ if (database === void 0) return Promise.reject(new UnknownRecordKindError(`"${owner}" declared no kind "${kind}"`));
2094
+ return this.router.recordsFileFor(database);
2095
+ }
2096
+ async declareKinds(input) {
2097
+ const owner = recordsCallerOf(input);
2098
+ const byDatabase = /* @__PURE__ */ new Map();
2099
+ const parsed = /* @__PURE__ */ new Map();
2100
+ for (const [kind, raw] of Object.entries(input.kinds)) parsed.set(kind, RecordKindDeclarationSchema.parse(raw));
2101
+ await this.assertFamiliesInOneFile(owner, parsed);
2102
+ for (const [kind, declaration] of parsed) {
2103
+ const known = this.placement.get(keyOf(owner, kind));
2104
+ if (known !== void 0 && known !== declaration.database) throw new DeclarationRefusedError(`kind "${kind}" of "${owner}" lives in "${known}", declared for "${declaration.database}" - the engine never moves data`);
2105
+ const group = byDatabase.get(declaration.database) ?? {};
2106
+ byDatabase.set(declaration.database, {
2107
+ ...group,
2108
+ [kind]: declaration
2109
+ });
2110
+ }
2111
+ const merged = {};
2112
+ for (const [database, kinds] of byDatabase) {
2113
+ const { kinds: results } = await (await this.router.recordsFileFor(database)).records("declareKinds", {
2114
+ owner,
2115
+ kinds
2116
+ });
2117
+ for (const [kind, result] of Object.entries(results)) {
2118
+ this.placement.set(keyOf(owner, kind), database);
2119
+ merged[kind] = result;
2120
+ }
2121
+ }
2122
+ return { kinds: merged };
2123
+ }
2124
+ /**
2125
+ * `transactFamily` (plan risk 8): kinds that must agree through one `transact` sit
2126
+ * in ONE file. A family split across files is refused whole, whether the split is
2127
+ * inside this declaration or against a kind of the same owner declared before.
2128
+ */
2129
+ async assertFamiliesInOneFile(owner, declared) {
2130
+ const families = /* @__PURE__ */ new Map();
2131
+ const note = (family, kind, database) => {
2132
+ const members = families.get(family) ?? /* @__PURE__ */ new Map();
2133
+ members.set(kind, database);
2134
+ families.set(family, members);
2135
+ };
2136
+ for (const file of this.router.openFiles()) {
2137
+ if (file.databaseId === "history") continue;
2138
+ for (const k of await file.records("listKinds", {
2139
+ owner,
2140
+ counts: false
2141
+ })) {
2142
+ if (k.state === "dropped" || declared.has(k.kind)) continue;
2143
+ const family = k.declaration.transactFamily;
2144
+ if (family !== void 0) note(family, k.kind, file.databaseId);
2145
+ }
2146
+ }
2147
+ for (const [kind, declaration] of declared) if (declaration.transactFamily !== void 0) note(declaration.transactFamily, kind, declaration.database);
2148
+ for (const [family, members] of families) {
2149
+ if (new Set(members.values()).size <= 1) continue;
2150
+ throw new DeclarationRefusedError(`transactFamily "${family}" of "${owner}" is split across files (${[...members.entries()].map(([k, db]) => `${k}@${db}`).join(", ")}); a family lives in ONE file`);
2151
+ }
2152
+ }
2153
+ async get(input) {
2154
+ const owner = recordsCallerOf(input);
2155
+ return (await this.fileOf(owner, input.kind)).records("get", {
2156
+ ...input,
2157
+ owner
2158
+ });
2159
+ }
2160
+ async getMany(input) {
2161
+ const owner = recordsCallerOf(input);
2162
+ return (await this.fileOf(owner, input.kind)).records("getMany", {
2163
+ ...input,
2164
+ owner
2165
+ });
2166
+ }
2167
+ async secretRefs(input) {
2168
+ const owner = recordsCallerOf(input);
2169
+ return (await this.fileOf(owner, input.kind)).records("secretRefs", {
2170
+ ...input,
2171
+ owner
2172
+ });
2173
+ }
2174
+ async put(input) {
2175
+ const owner = recordsCallerOf(input);
2176
+ return (await this.fileOf(owner, input.kind)).records("put", {
2177
+ ...input,
2178
+ owner
2179
+ });
2180
+ }
2181
+ async putMany(input) {
2182
+ const owner = recordsCallerOf(input);
2183
+ return (await this.fileOf(owner, input.kind)).records("putMany", {
2184
+ ...input,
2185
+ owner
2186
+ });
2187
+ }
2188
+ async patch(input) {
2189
+ const owner = recordsCallerOf(input);
2190
+ return (await this.fileOf(owner, input.kind)).records("patch", {
2191
+ ...input,
2192
+ owner
2193
+ });
2194
+ }
2195
+ async delete(input) {
2196
+ const owner = recordsCallerOf(input);
2197
+ return (await this.fileOf(owner, input.kind)).records("delete", {
2198
+ ...input,
2199
+ owner
2200
+ });
2201
+ }
2202
+ async deleteMany(input) {
2203
+ const owner = recordsCallerOf(input);
2204
+ return (await this.fileOf(owner, input.kind)).records("deleteMany", {
2205
+ ...input,
2206
+ owner
2207
+ });
2208
+ }
2209
+ async query(input) {
2210
+ const owner = recordsCallerOf(input);
2211
+ return (await this.fileOf(owner, input.kind)).records("query", {
2212
+ ...input,
2213
+ owner
2214
+ });
2215
+ }
2216
+ async count(input) {
2217
+ const owner = recordsCallerOf(input);
2218
+ return (await this.fileOf(owner, input.kind)).records("count", {
2219
+ ...input,
2220
+ owner
2221
+ });
2222
+ }
2223
+ async histogram(input) {
2224
+ const owner = recordsCallerOf(input);
2225
+ return (await this.fileOf(owner, input.kind)).records("histogram", {
2226
+ ...input,
2227
+ owner
2228
+ });
2229
+ }
2230
+ async aggregate(input) {
2231
+ const owner = recordsCallerOf(input);
2232
+ return (await this.fileOf(owner, input.kind)).records("aggregate", {
2233
+ ...input,
2234
+ owner
2235
+ });
2236
+ }
2237
+ async deleteWhere(input) {
2238
+ const owner = recordsCallerOf(input);
2239
+ return (await this.fileOf(owner, input.kind)).records("deleteWhere", {
2240
+ ...input,
2241
+ owner
2242
+ });
2243
+ }
2244
+ /**
2245
+ * All ops must resolve to ONE file (`records/transact-refused` `cross-file`
2246
+ * otherwise); that file's engine then checks the family and runs one SQLite
2247
+ * transaction.
2248
+ */
2249
+ async transact(input) {
2250
+ const owner = recordsCallerOf(input);
2251
+ const files = /* @__PURE__ */ new Map();
2252
+ for (const op of input.ops) {
2253
+ const database = this.placement.get(keyOf(owner, op.kind));
2254
+ if (database === void 0) throw new UnknownRecordKindError(`"${owner}" declared no kind "${op.kind}"`);
2255
+ files.set(database, [...files.get(database) ?? [], op.kind]);
2256
+ }
2257
+ if (files.size > 1) throw new TransactRefusedError(`cross-file: the ops span more than one database file (${[...files.entries()].map(([db, kinds]) => `${[...new Set(kinds)].join("+")}@${db}`).join(", ")}); a transaction lives in ONE file`);
2258
+ const first = input.ops[0];
2259
+ if (first === void 0) throw new InvalidRecordError("transact: no ops");
2260
+ return (await this.fileOf(owner, first.kind)).records("transact", {
2261
+ ...input,
2262
+ owner
2263
+ });
2264
+ }
2265
+ async allocateId(input) {
2266
+ const owner = recordsCallerOf(input);
2267
+ return (await this.fileOf(owner, input.kind)).records("allocateId", {
2268
+ ...input,
2269
+ owner
2270
+ });
2271
+ }
2272
+ /** The D865 hook body: every file that holds kinds of this owner. */
2273
+ async deleteDevice(input) {
2274
+ const owner = recordsCallerOf(input);
2275
+ const deleted = {};
2276
+ const secretRefs = [];
2277
+ const databases = new Set([...this.placement.entries()].filter(([key]) => key.startsWith(`${owner}\u0000`)).map(([, database]) => database));
2278
+ for (const database of databases) {
2279
+ const result = await (await this.router.recordsFileFor(database)).records("deleteDevice", {
2280
+ ...input,
2281
+ owner
2282
+ });
2283
+ Object.assign(deleted, result.deleted);
2284
+ secretRefs.push(...result.secretRefs);
2285
+ }
2286
+ return {
2287
+ deleted,
2288
+ secretRefs
2289
+ };
2290
+ }
2291
+ async listKinds(input) {
2292
+ const kinds = [];
2293
+ for (const file of this.router.openFiles()) {
2294
+ if (file.databaseId === "history") continue;
2295
+ kinds.push(...await file.records("listKinds", input));
2296
+ }
2297
+ return { kinds };
2298
+ }
2299
+ /** Stale-data audit: flag the kinds nobody declared this boot, in whichever file holds them. */
2300
+ async markKindsOrphaned(kinds) {
2301
+ for (const file of this.router.openFiles()) {
2302
+ if (file.databaseId === "history") continue;
2303
+ await file.records("markKindsOrphaned", { kinds });
2304
+ }
2305
+ }
2306
+ /** Operator drop of an orphaned kind; the placement forgets it. Returns the secret refs its rows held. */
2307
+ async dropKind(ref) {
2308
+ const result = await (await this.fileOf(ref.owner, ref.kind)).records("dropKind", ref);
2309
+ this.placement.delete(keyOf(ref.owner, ref.kind));
2310
+ return result;
2311
+ }
2312
+ async readRecords(input) {
2313
+ this.logger.info("records: admin read", { meta: {
2314
+ owner: input.owner,
2315
+ kind: input.kind,
2316
+ limit: input.limit
2317
+ } });
2318
+ return (await this.fileOf(input.owner, input.kind)).records("query", input);
2319
+ }
2320
+ /** Housekeeping: delete rows past `expires_at` in every file that hosts kinds. */
2321
+ async sweepExpired() {
2322
+ let deleted = 0;
2323
+ for (const file of this.router.openFiles()) {
2324
+ if (file.databaseId === "history") continue;
2325
+ deleted += (await file.records("sweepExpired", {})).deleted;
2326
+ }
2327
+ return deleted;
2328
+ }
2329
+ };
2330
+ //#endregion
2331
+ //#region src/builtins/sqlite-storage/storage-admin-provider.ts
2332
+ var StorageAdminProvider = class {
2333
+ backend;
2334
+ logger;
2335
+ records;
2336
+ audit;
2337
+ peerFiles;
2338
+ constructor(backend, logger, records, audit, peerFiles = async () => []) {
2339
+ this.backend = backend;
2340
+ this.logger = logger;
2341
+ this.records = records;
2342
+ this.audit = audit;
2343
+ this.peerFiles = peerFiles;
2344
+ }
2345
+ async staleDataReport() {
2346
+ return this.audit.current();
2347
+ }
2348
+ scanStaleData() {
2349
+ return this.audit.scan("manual");
2350
+ }
2351
+ dropOrphanedKind(input) {
2352
+ return this.audit.dropOrphanedKind({
2353
+ owner: input.owner,
2354
+ kind: input.kind
2355
+ }, input.caller.userId);
2356
+ }
2357
+ unsetStaleSettingsKey(input) {
2358
+ return this.audit.unsetStaleSettingsKey(input.addonId, input.key, input.caller.userId);
2359
+ }
2360
+ listKinds(input) {
2361
+ return this.records.listKinds(input);
2362
+ }
2363
+ readRecords(input) {
2364
+ return this.records.readRecords(input);
2365
+ }
2366
+ async listTables(input) {
2367
+ const tables = [...this.backend.listTables(input.ownerPrefix)];
2368
+ for (const file of await this.peerFiles()) tables.push(...await file.listPhysicalTables(input.ownerPrefix));
2369
+ tables.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
2370
+ this.logger.info("storage-admin: listed tables", { meta: {
2371
+ tables: tables.length,
2372
+ ownerPrefix: input.ownerPrefix ?? null
2373
+ } });
2374
+ return { tables };
2375
+ }
2376
+ };
2377
+ //#endregion
2378
+ //#region src/builtins/sqlite-storage/stale-data/stale-data-audit.ts
2379
+ /**
2380
+ * The stale-data audit (D905): finds data an addon left behind and no longer
2381
+ * uses, and lets an operator remove it.
2382
+ *
2383
+ * DETECTION IS READ-ONLY. A scan reads the addon list, the record catalog and
2384
+ * the stored settings keys, asks each running addon (in its own process) which
2385
+ * keys it still declares, and keeps the verdicts in memory. Nothing is deleted
2386
+ * by a scan; the only write is the `orphaned` flag on a record kind.
2387
+ *
2388
+ * DELETION is a separate, operator-triggered call that re-checks the verdict at
2389
+ * call time and refuses anything not still orphaned / stale.
2390
+ *
2391
+ * Three verdicts, never blurred (D315): `orphaned`/`stale` is proof; `unknown`
2392
+ * is an owner that could not be judged and is never touched.
2393
+ *
2394
+ * Every finding is logged once per scan with owner and key/kind - never values.
2395
+ */
2396
+ /** Owners whose kinds the audit never drops (local-auth's legacy tables go by hand, D902). */
2397
+ var PROTECTED_KIND_OWNERS = ["local-auth"];
2398
+ var StaleDataRefusedError = class extends Error {
2399
+ constructor(message) {
2400
+ super(message);
2401
+ this.name = "StaleDataRefusedError";
2402
+ }
2403
+ };
2404
+ var EMPTY_REPORT = {
2405
+ scannedAt: null,
2406
+ scanning: false,
2407
+ trigger: null,
2408
+ kinds: [],
2409
+ settingsKeys: [],
2410
+ unknown: []
2411
+ };
2412
+ /** `<key>@<nodeId>` is a per-node copy of `<key>`. */
2413
+ function baseKeyOf(key) {
2414
+ const at = key.indexOf("@");
2415
+ return at > 0 ? key.slice(0, at) : key;
2416
+ }
2417
+ function errMsg(err) {
2418
+ return err instanceof Error ? err.message : String(err);
2419
+ }
2420
+ function kindKey(owner, kind) {
2421
+ return `${owner}\u0000${kind}`;
2422
+ }
2423
+ var StaleDataAudit = class {
2424
+ ports;
2425
+ report = EMPTY_REPORT;
2426
+ inFlight = null;
2427
+ constructor(ports) {
2428
+ this.ports = ports;
2429
+ }
2430
+ current() {
2431
+ return this.report;
2432
+ }
2433
+ /** Scan now. A scan already running is joined, not doubled. */
2434
+ scan(trigger) {
2435
+ if (this.inFlight !== null) return this.inFlight;
2436
+ this.report = {
2437
+ ...this.report,
2438
+ scanning: true
2439
+ };
2440
+ const run = this.runScan(trigger).finally(() => {
2441
+ this.inFlight = null;
2442
+ });
2443
+ this.inFlight = run;
2444
+ return run;
2445
+ }
2446
+ async runScan(trigger) {
2447
+ const unknown = [];
2448
+ try {
2449
+ const addons = await this.ports.listAddons();
2450
+ const kinds = await this.judgeKinds(addons);
2451
+ if (kinds.orphaned.length > 0) await this.ports.markOrphaned(kinds.orphaned);
2452
+ const settingsKeys = await this.judgeSettings(addons, unknown);
2453
+ this.report = {
2454
+ scannedAt: this.ports.now(),
2455
+ scanning: false,
2456
+ trigger,
2457
+ kinds: [...kinds.findings],
2458
+ settingsKeys,
2459
+ unknown
2460
+ };
2461
+ this.logFindings(trigger);
2462
+ } catch (err) {
2463
+ this.report = {
2464
+ ...this.report,
2465
+ scanning: false
2466
+ };
2467
+ this.ports.logger.warn("stale-data: scan failed", { meta: {
2468
+ trigger,
2469
+ error: errMsg(err)
2470
+ } });
2471
+ }
2472
+ return this.report;
2473
+ }
2474
+ async judgeKinds(addons) {
2475
+ const kinds = (await this.ports.listKinds()).filter((k) => k.state !== "dropped");
2476
+ const byOwner = /* @__PURE__ */ new Map();
2477
+ for (const a of addons ?? []) byOwner.set(a.id, a.running);
2478
+ const ownersDeclaring = new Set(kinds.filter((k) => k.declaredThisBoot).map((k) => k.owner));
2479
+ const findings = [];
2480
+ const orphaned = [];
2481
+ for (const k of kinds) {
2482
+ const verdict = this.kindVerdict(k, addons === null ? null : byOwner, ownersDeclaring);
2483
+ if (verdict === null) continue;
2484
+ const isProtected = PROTECTED_KIND_OWNERS.includes(k.owner);
2485
+ findings.push({
2486
+ owner: k.owner,
2487
+ kind: k.kind,
2488
+ verdict: verdict.verdict,
2489
+ reason: verdict.reason,
2490
+ rows: k.rows,
2491
+ protected: isProtected
2492
+ });
2493
+ if (verdict.verdict === "orphaned" && !isProtected) orphaned.push({
2494
+ owner: k.owner,
2495
+ kind: k.kind
2496
+ });
2497
+ }
2498
+ return {
2499
+ findings,
2500
+ orphaned
2501
+ };
2502
+ }
2503
+ /** `null` = in use, nothing to report. */
2504
+ kindVerdict(k, owners, ownersDeclaring) {
2505
+ if (owners === null) return {
2506
+ verdict: "unknown",
2507
+ reason: "the addon list could not be read"
2508
+ };
2509
+ const running = owners.get(k.owner);
2510
+ if (running === void 0) return {
2511
+ verdict: "orphaned",
2512
+ reason: "the owner package is not installed"
2513
+ };
2514
+ if (!running) return {
2515
+ verdict: "unknown",
2516
+ reason: "the owner is installed but not running"
2517
+ };
2518
+ if (k.declaredThisBoot) return null;
2519
+ if (!ownersDeclaring.has(k.owner)) return {
2520
+ verdict: "unknown",
2521
+ reason: "the owner is running but declared no kind since the hub started"
2522
+ };
2523
+ return {
2524
+ verdict: "orphaned",
2525
+ reason: "the running owner no longer declares this kind"
2526
+ };
2527
+ }
2528
+ async judgeSettings(addons, unknown) {
2529
+ const out = [];
2530
+ if (addons === null) return out;
2531
+ for (const addon of addons) {
2532
+ if (!addon.running) continue;
2533
+ try {
2534
+ out.push(...await this.staleKeysOf(addon.id, unknown));
2535
+ } catch (err) {
2536
+ unknown.push({
2537
+ subject: addon.id,
2538
+ reason: `audit failed: ${errMsg(err)}`
2539
+ });
2540
+ }
2541
+ }
2542
+ return out;
2543
+ }
2544
+ async staleKeysOf(addonId, unknown) {
2545
+ const stored = await this.ports.storedSettings(addonId);
2546
+ const keys = Object.keys(stored);
2547
+ if (keys.length === 0) return [];
2548
+ const declared = await this.ports.declaredKeys(addonId);
2549
+ if (declared === null) {
2550
+ unknown.push({
2551
+ subject: addonId,
2552
+ reason: "the addon did not answer which keys it declares"
2553
+ });
2554
+ return [];
2555
+ }
2556
+ const declaredSet = new Set(declared);
2557
+ const staleKeys = keys.filter((key) => !declaredSet.has(baseKeyOf(key)));
2558
+ if (staleKeys.length === 0) return [];
2559
+ const live = /* @__PURE__ */ new Set();
2560
+ for (const key of keys) {
2561
+ if (staleKeys.includes(key)) continue;
2562
+ for (const ref of collectSecretMarkerRefs(stored[key])) live.add(ref);
2563
+ }
2564
+ return staleKeys.map((key) => ({
2565
+ addonId,
2566
+ key,
2567
+ secretRefs: [...new Set(collectSecretMarkerRefs(stored[key]))].filter((ref) => !live.has(ref)).toSorted()
2568
+ }));
2569
+ }
2570
+ /** One line per finding, owner and key/kind only - a value never reaches a log. */
2571
+ logFindings(trigger) {
2572
+ const { kinds, settingsKeys, unknown } = this.report;
2573
+ for (const f of kinds) this.ports.logger.info("stale-data: record kind", { meta: {
2574
+ trigger,
2575
+ owner: f.owner,
2576
+ kind: f.kind,
2577
+ verdict: f.verdict,
2578
+ reason: f.reason
2579
+ } });
2580
+ for (const f of settingsKeys) this.ports.logger.info("stale-data: settings key", { meta: {
2581
+ trigger,
2582
+ addonId: f.addonId,
2583
+ key: f.key,
2584
+ secretRefs: f.secretRefs.length
2585
+ } });
2586
+ for (const u of unknown) this.ports.logger.info("stale-data: not judged", { meta: {
2587
+ trigger,
2588
+ subject: u.subject,
2589
+ reason: u.reason
2590
+ } });
2591
+ this.ports.logger.info("stale-data: scan finished", { meta: {
2592
+ trigger,
2593
+ orphanedKinds: kinds.filter((k) => k.verdict === "orphaned").length,
2594
+ unknownKinds: kinds.filter((k) => k.verdict === "unknown").length,
2595
+ staleKeys: settingsKeys.length,
2596
+ notJudged: unknown.length
2597
+ } });
2598
+ }
2599
+ /** Drop an orphaned kind: its rows, their keychain values, then mark it dropped. */
2600
+ async dropOrphanedKind(target, userId) {
2601
+ if (PROTECTED_KIND_OWNERS.includes(target.owner)) throw new StaleDataRefusedError(`"${target.owner}" kinds are never dropped by the audit`);
2602
+ const addons = await this.ports.listAddons();
2603
+ if (!(await this.judgeKinds(addons)).orphaned.some((k) => kindKey(k.owner, k.kind) === kindKey(target.owner, target.kind))) throw new StaleDataRefusedError(`"${target.owner}" kind "${target.kind}" is not orphaned any more - nothing was dropped`);
2604
+ await this.ports.markOrphaned([target]);
2605
+ const result = await this.ports.dropKind(target);
2606
+ const secretsReleased = result.secretRefs.length > 0 ? await this.ports.releaseSecrets(result.secretRefs, userId) : 0;
2607
+ this.ports.logger.warn("stale-data: record kind dropped", { meta: {
2608
+ owner: target.owner,
2609
+ kind: target.kind,
2610
+ deleted: result.deleted,
2611
+ secretsReleased,
2612
+ operator: userId
2613
+ } });
2614
+ this.report = {
2615
+ ...this.report,
2616
+ kinds: this.report.kinds.filter((k) => kindKey(k.owner, k.kind) !== kindKey(target.owner, target.kind))
2617
+ };
2618
+ return {
2619
+ deleted: result.deleted,
2620
+ secretsReleased
2621
+ };
2622
+ }
2623
+ /** Unset one stale settings key on a running addon, with the keychain values it held. */
2624
+ async unsetStaleSettingsKey(addonId, key, userId) {
2625
+ if (!((await this.ports.listAddons())?.find((a) => a.id === addonId)?.running === true)) throw new StaleDataRefusedError(`"${addonId}" is not running - its keys cannot be judged`);
2626
+ if (!(await this.staleKeysOf(addonId, [])).some((s) => s.key === key)) throw new StaleDataRefusedError(`"${addonId}" key "${key}" is not stale any more - nothing was removed`);
2627
+ const outcome = await this.ports.unsetKeys(addonId, [key]);
2628
+ const removed = outcome.removed.includes(key);
2629
+ this.ports.logger.warn("stale-data: settings key unset", { meta: {
2630
+ addonId,
2631
+ key,
2632
+ removed,
2633
+ secretsCleared: outcome.secretsCleared,
2634
+ operator: userId
2635
+ } });
2636
+ if (removed) this.report = {
2637
+ ...this.report,
2638
+ settingsKeys: this.report.settingsKeys.filter((s) => !(s.addonId === addonId && s.key === key))
2639
+ };
2640
+ return {
2641
+ removed,
2642
+ secretsCleared: outcome.secretsCleared
2643
+ };
2644
+ }
2645
+ };
2646
+ //#endregion
2647
+ //#region src/builtins/sqlite-storage/stale-data/stale-data-ports.ts
2648
+ function createStaleDataPorts(deps) {
2649
+ const { api, backend, records, logger } = deps;
2650
+ return {
2651
+ listAddons: async () => {
2652
+ try {
2653
+ return (await api.addons.list.query({})).map((item) => ({
2654
+ id: item.manifest.id,
2655
+ running: item.process?.state === "running"
2656
+ }));
2657
+ } catch (err) {
2658
+ logger.warn("stale-data: the addon list could not be read", { meta: { error: err instanceof Error ? err.message : String(err) } });
2659
+ return null;
2660
+ }
2661
+ },
2662
+ listKinds: async () => (await records.listKinds({})).kinds,
2663
+ markOrphaned: (kinds) => records.markKindsOrphaned(kinds),
2664
+ dropKind: (ref) => records.dropKind(ref),
2665
+ storedSettings: async (addonId) => backend.getAllAddon(addonId),
2666
+ declaredKeys: async (addonId) => {
2667
+ try {
2668
+ const answer = await api.addonSettings.getDeclaredSettingsKeys.query({ addonId });
2669
+ return answer === null ? null : answer.keys;
2670
+ } catch {
2671
+ return null;
2672
+ }
2673
+ },
2674
+ unsetKeys: (addonId, keys) => api.addonSettings.unsetStoredSettingsKeys.mutate({
2675
+ addonId,
2676
+ keys: [...keys]
2677
+ }),
2678
+ releaseSecrets: async (refs, userId) => (await api.keychain.releaseRecordRefs.mutate({
2679
+ refs: [...refs],
2680
+ onBehalfOf: userId
2681
+ })).released,
2682
+ logger,
2683
+ now: () => Date.now()
2684
+ };
2685
+ }
2686
+ //#endregion
2687
+ //#region src/builtins/sqlite-storage/sqlite-settings.addon.ts
2688
+ /** The file name of each database inside the addon's private directory. */
2689
+ var DATABASE_FILE_NAMES = {
2690
+ settings: "camstack.db",
2691
+ events: "events.db",
2692
+ history: "history.db"
2693
+ };
2694
+ /**
2695
+ * SQLite Settings addon — the relational ENGINE behind the data door.
2696
+ *
2697
+ * Capability: `data-store-provider` (collection, internal). It does not
2698
+ * serve `settings-store`: that is the public door, owned by
2699
+ * storage-orchestrator, which dispatches here
2700
+ * ([D44](../../../../../docs/decisions/adr-0044.md)). Callers reach this
2701
+ * engine only through the door — which is the point, because it is what
2702
+ * makes the engine replaceable.
2703
+ *
2704
+ * ONE engine process, SEVERAL owned files ([D851](../../../../../docs/decisions/adr-0851-one-sqlite-engine-serves-several-owned-files-one-thread-per-file.md)):
2705
+ * `camstack.db` (settings) is served on this thread exactly as it always was;
2706
+ * `events.db` and `history.db`, when a collection names them, are each served
2707
+ * by a worker thread. A {@link PlacementRouter} is the provider the door sees.
2708
+ * The layout of the files is documented in `docs/architecture/storage-files.md`.
2709
+ *
2710
+ * It also serves `database-snapshot` (singleton, internal): the verified copy
2711
+ * of its database that the nightly backup archives in place of the live files
2712
+ * (D693).
2713
+ *
2714
+ * It ALSO serves `vector-store` (singleton, internal), from the **events**
2715
+ * file's worker thread (sqlite-vec loaded there). The capability is what keeps
2716
+ * the backend swappable; the package never was.
2717
+ */
2718
+ /** The stale-data audit runs again every 24 h after its boot scan. */
2719
+ var STALE_DATA_SCAN_INTERVAL_MS = 1440 * 6e4;
2720
+ var SqliteSettingsAddon = class extends BaseAddon {
2721
+ settingsFile = null;
2722
+ router = null;
2723
+ sweepTimer = null;
2724
+ sweepStart = null;
2725
+ staleTimer = null;
2726
+ unsubscribeAddonsReady = null;
2727
+ constructor() {
2728
+ super({});
2729
+ }
2730
+ /**
2731
+ * The engine behind `settings-store` cannot read that door during
2732
+ * `initialize()`. `BaseAddon` always `await`s `resolveConfig()` first;
2733
+ * on an isolated sqlite that round-trip is a UDS call to the parent,
2734
+ * and the parent is waiting for THIS child's post-init handshake before
2735
+ * it builds the door (D233). Live 1.2.152: 30 s hang, timeout, every
2736
+ * in-process builtin skipped, then this addon finished one second later.
2737
+ * Constructor defaults (`{}`) are the whole config this addon has.
2738
+ */
2739
+ async resolveConfig() {}
2740
+ async onInitialize() {
2741
+ const addonId = bareAddonId(this.ctx.id);
2742
+ const dir = this.ctx.dataDir ?? path.join("camstack-data", "addons-data", addonId);
2743
+ const pathSource = this.ctx.dataDir ? "dataDir" : "fallback (hardcoded)";
2744
+ const livePathOf = (databaseId) => path.join(dir, DATABASE_FILE_NAMES[databaseId]);
2745
+ const settingsPath = livePathOf("settings");
2746
+ const dbExists = existsSync(settingsPath);
2747
+ if (!dbExists) try {
2748
+ await mkdir(dir, { recursive: true });
2749
+ } catch (err) {
2750
+ this.ctx.logger.warn("Failed to check/create DB directory", { meta: { error: errMsg$1(err) } });
2751
+ }
2752
+ this.ctx.logger.info("DB path resolved", { meta: {
2753
+ pathSource,
2754
+ dbPath: settingsPath
2755
+ } });
2756
+ this.ctx.logger.info("DB file status", { meta: { dbExists } });
2757
+ const engine = new MigrationEngine({
2758
+ logger: this.ctx.logger.child("Migrations"),
2759
+ catalogue: HUB_MIGRATIONS,
2760
+ codeVersion: systemPackageVersion(),
2761
+ snapshotterFor: (livePath) => new SqliteSnapshotter({
2762
+ livePath,
2763
+ logger: this.ctx.logger.child("PreMigrationSnapshot")
2764
+ }),
2765
+ announce: (kind, ids) => this.announceMigrations(kind, ids),
2766
+ scheduleRestore: (request) => scheduleMigrationRestore(path.resolve(dir, "..", ".."), request)
2767
+ });
2768
+ const deps = {
2769
+ logger: this.ctx.logger,
2770
+ onFatal: () => process.exit(1),
2771
+ runtimeDefaults: { ...RUNTIME_DEFAULTS },
2772
+ afterOpen: async (file) => {
2773
+ await engine.runFile(migrationAccessOf(file));
2774
+ await this.purgeBeforeServing(file);
2775
+ }
2776
+ };
2777
+ const settings = await openOwnedSqliteFile({
2778
+ databaseId: "settings",
2779
+ livePath: settingsPath,
2780
+ thread: "main",
2781
+ autoVacuum: "none",
2782
+ loadVectorExtension: false
2783
+ }, deps);
2784
+ if (!(settings instanceof InlineOwnedFile)) throw new Error("sqlite-settings: the settings file must be served on the main thread");
2785
+ this.settingsFile = settings;
2786
+ const open = (databaseId) => openOwnedSqliteFile(workerSpec(databaseId, livePathOf(databaseId)), deps);
2787
+ const existing = [settings];
2788
+ for (const databaseId of ["events", "history"]) if (existsSync(livePathOf(databaseId))) existing.push(await open(databaseId));
2789
+ const router = new PlacementRouter({
2790
+ files: existing,
2791
+ open,
2792
+ logger: this.ctx.logger.child("Placement")
2793
+ });
2794
+ this.router = router;
2795
+ const vectorProvider = vectorProviderOfOwnedFile(() => router.recordsFileFor("events"));
2796
+ const records = new RecordsProvider(router, this.ctx.logger.child("Records"));
2797
+ await records.init();
2798
+ this.startRecordsSweep(records);
2799
+ const audit = new StaleDataAudit(createStaleDataPorts({
2800
+ api: this.ctx.api,
2801
+ backend: settings.backend,
2802
+ records,
2803
+ logger: this.ctx.logger.child("StaleData")
2804
+ }));
2805
+ this.startStaleDataAudit(audit);
2806
+ this.ctx.logger.info("Initialized successfully");
2807
+ return {
2808
+ providers: [
2809
+ {
2810
+ capability: dataStoreProviderCapability,
2811
+ provider: router
2812
+ },
2813
+ {
2814
+ capability: recordsCapability,
2815
+ provider: records
2816
+ },
2817
+ {
2818
+ capability: vectorStoreCapability,
2819
+ provider: vectorProvider
2820
+ },
2821
+ {
2822
+ capability: databaseSnapshotCapability,
2823
+ provider: new DatabaseSnapshotProvider(router)
2824
+ },
2825
+ {
2826
+ capability: storageAdminCapability,
2827
+ provider: new StorageAdminProvider(settings.backend, this.ctx.logger.child("StorageAdmin"), records, audit, async () => router.openFiles().filter((file) => file.databaseId !== "settings"))
2828
+ },
2829
+ {
2830
+ capability: migrationsCapability,
2831
+ provider: new MigrationsProvider(engine)
2832
+ }
2833
+ ],
2834
+ customActions: migrationActions,
2835
+ actionHandlers: { retryMigration: async (input) => {
2836
+ return { retried: (await engine.retry(retryMigrationInput.parse(input).id)).map((entry) => entry.id) };
2837
+ } }
2838
+ };
2839
+ }
2840
+ /** A hint for the Alert Center; the ledger read stays the authority (D11). */
2841
+ announceMigrations(kind, ids) {
2842
+ this.ctx.eventBus.emit({
2843
+ id: randomUUID(),
2844
+ timestamp: /* @__PURE__ */ new Date(),
2845
+ source: {
2846
+ type: "addon",
2847
+ id: this.ctx.id
2848
+ },
2849
+ category: kind === "failed" ? EventCategory.MigrationFailed : EventCategory.MigrationApplied,
2850
+ data: { ids: [...ids] }
2851
+ });
2852
+ }
2853
+ /**
2854
+ * Housekeeping that must happen BEFORE anything can read a file: the
2855
+ * retired-key purge (settings file only).
2856
+ */
2857
+ async purgeBeforeServing(file) {
2858
+ if (file instanceof InlineOwnedFile && file.databaseId === "settings") try {
2859
+ await purgeRetiredSettingsKeys(retiredKeyStoreOf(file.backend), this.ctx.logger.child("RetiredKeys"));
2860
+ } catch (err) {
2861
+ this.ctx.logger.warn("Retired-key purge failed", { meta: { error: errMsg$1(err) } });
2862
+ }
2863
+ }
2864
+ /**
2865
+ * The engine's TTL sweep (D881): every 10 minutes, off the boot path (the
2866
+ * first run a minute after boot), batched and yielding. A failed pass is
2867
+ * warned about and the next one retries; it never blocks anything.
2868
+ */
2869
+ startRecordsSweep(records) {
2870
+ const run = () => {
2871
+ records.sweepExpired().then((deleted) => {
2872
+ if (deleted > 0) this.ctx.logger.info("records: expired rows swept", { meta: { deleted } });
2873
+ }).catch((err) => {
2874
+ this.ctx.logger.warn("records: expiry sweep failed", { meta: { error: errMsg$1(err) } });
2875
+ });
2876
+ };
2877
+ this.sweepStart = setTimeout(() => {
2878
+ run();
2879
+ this.sweepTimer = setInterval(run, RECORD_SWEEP_INTERVAL_MS);
2880
+ this.sweepTimer.unref();
2881
+ }, 6e4);
2882
+ this.sweepStart.unref();
2883
+ }
2884
+ /**
2885
+ * The stale-data scan (D905): once when the registry reports the addons
2886
+ * started (the existing event - no readiness timer, D3), then every 24 h.
2887
+ * Detection only; a failed scan is logged by the audit and the next retries.
2888
+ */
2889
+ startStaleDataAudit(audit) {
2890
+ this.unsubscribeAddonsReady = this.ctx.eventBus.subscribe({ category: EventCategory.SystemAddonsReady }, () => {
2891
+ audit.scan("boot");
2892
+ });
2893
+ this.staleTimer = setInterval(() => void audit.scan("interval"), STALE_DATA_SCAN_INTERVAL_MS);
2894
+ this.staleTimer.unref();
2895
+ }
2896
+ async onShutdown() {
2897
+ this.unsubscribeAddonsReady?.();
2898
+ this.unsubscribeAddonsReady = null;
2899
+ if (this.staleTimer !== null) clearInterval(this.staleTimer);
2900
+ this.staleTimer = null;
2901
+ if (this.sweepStart !== null) clearTimeout(this.sweepStart);
2902
+ if (this.sweepTimer !== null) clearInterval(this.sweepTimer);
2903
+ this.sweepStart = null;
2904
+ this.sweepTimer = null;
2905
+ const files = this.router?.openFiles() ?? [];
2906
+ for (const file of files.toReversed()) try {
2907
+ await file.stop();
2908
+ } catch (err) {
2909
+ this.ctx.logger.warn("Database file did not stop cleanly", {
2910
+ tags: { database: file.databaseId },
2911
+ meta: { error: errMsg$1(err) }
2912
+ });
2913
+ }
2914
+ this.router = null;
2915
+ this.settingsFile = null;
2916
+ }
2917
+ getBackend() {
2918
+ return this.settingsFile?.backend ?? null;
2919
+ }
2920
+ /** The placement router; null before `onInitialize`. */
2921
+ getRouter() {
2922
+ return this.router;
2923
+ }
2924
+ /** Exposed for tests; vectors are served from the events file (P5). */
2925
+ getVectorIndex() {
2926
+ return null;
2927
+ }
2928
+ };
2929
+ /** The engine's view of one owned file: the connection answers where it lives. */
2930
+ function migrationAccessOf(file) {
2931
+ return {
2932
+ databaseId: file.databaseId,
2933
+ livePath: file.livePath,
2934
+ call: (op, input) => file.migrate(op, input)
2935
+ };
2936
+ }
2937
+ function systemPackageVersion() {
2938
+ const parsed = createRequire(import.meta.url)("@camstack/server/system/package.json");
2939
+ return typeof parsed === "object" && parsed !== null && "version" in parsed && typeof parsed.version === "string" ? parsed.version : "0.0.0";
2940
+ }
2941
+ /** How a non-settings file is opened: its own worker; `events` loads sqlite-vec. */
2942
+ function workerSpec(databaseId, livePath) {
2943
+ return {
2944
+ databaseId,
2945
+ livePath,
2946
+ thread: "worker",
2947
+ autoVacuum: "incremental",
2948
+ loadVectorExtension: databaseId === "events"
2949
+ };
2950
+ }
2951
+ //#endregion
2952
+ export { SqliteSettingsAddon, SqliteSettingsAddon as default };