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