@cosmicdrift/kumiko-framework 0.413.1 → 0.415.0

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 (479) hide show
  1. package/AGENTS.md +5 -2
  2. package/agents/api/framework-db.md +14 -3
  3. package/agents/api/framework-engine.md +69 -13
  4. package/agents/api/framework-errors.md +1 -1
  5. package/agents/api/framework-event-store.md +14 -0
  6. package/agents/api/framework-ui-types.md +158 -21
  7. package/agents/api/renderer-web.md +112 -11
  8. package/agents/api/testing-helpers.md +3 -2
  9. package/agents/api/testing-stack.md +3 -0
  10. package/agents/api/types.md +248 -24
  11. package/agents/api.md +7 -7
  12. package/agents/boot-rules.md +66 -10
  13. package/agents/examples/api-docs.md +2 -6
  14. package/agents/examples/auth-mfa.md +57 -10
  15. package/agents/examples/chat-channels.md +2 -0
  16. package/agents/examples/crypto-shredding-hr.md +63 -1
  17. package/agents/examples/currencies-global.md +1 -0
  18. package/agents/examples/env-composition.md +7 -11
  19. package/agents/examples/managed-pages.md +90 -1
  20. package/agents/examples/pwa-shell.md +210 -0
  21. package/agents/examples/rate-limiting.md +3 -3
  22. package/agents/examples/record-detail-layout.md +1643 -67
  23. package/agents/examples/workflow-engine.md +16 -12
  24. package/agents/examples.md +1 -0
  25. package/agents/features-index.md +4 -2
  26. package/agents/features.md +22 -7
  27. package/agents/widgets.md +26 -1
  28. package/dist/api/api-constants.d.ts +1 -0
  29. package/dist/api/api-constants.js +4 -0
  30. package/dist/api/auth-middleware.js +4 -3
  31. package/dist/api/auth-routes-shared.js +2 -1
  32. package/dist/api/entity-read-access.d.ts +1 -0
  33. package/dist/api/entity-read-access.js +18 -0
  34. package/dist/api/export/export-route.d.ts +6 -1
  35. package/dist/api/export/export-route.js +27 -1
  36. package/dist/api/export/export-rows.js +19 -3
  37. package/dist/api/request-context-internals.d.ts +2 -0
  38. package/dist/api/request-context-scopes.js +9 -2
  39. package/dist/api/request-context.js +1 -1
  40. package/dist/api/routes.d.ts +2 -0
  41. package/dist/api/routes.js +9 -1
  42. package/dist/api/server-event-dispatcher.js +3 -0
  43. package/dist/api/server-extra-routes.js +2 -1
  44. package/dist/api/server-feature-http-routes.d.ts +9 -0
  45. package/dist/api/server-feature-http-routes.js +109 -0
  46. package/dist/api/server-middleware.js +2 -19
  47. package/dist/api/server-pat-rate-limit-guard.d.ts +3 -0
  48. package/dist/api/server-pat-rate-limit-guard.js +19 -0
  49. package/dist/api/server-rate-limit-wiring.d.ts +10 -0
  50. package/dist/api/server-rate-limit-wiring.js +37 -0
  51. package/dist/api/server-routes.d.ts +4 -12
  52. package/dist/api/server-routes.js +12 -171
  53. package/dist/api/server-schema-route.d.ts +3 -0
  54. package/dist/api/server-schema-route.js +58 -0
  55. package/dist/api/server-wiring.js +2 -37
  56. package/dist/api/server.js +3 -1
  57. package/dist/compliance/override-schema.js +5 -5
  58. package/dist/compliance/sub-processors.js +10 -1
  59. package/dist/crypto/index.d.ts +1 -1
  60. package/dist/crypto/index.js +1 -1
  61. package/dist/crypto/pii-field-encryption.d.ts +2 -0
  62. package/dist/crypto/pii-field-encryption.js +16 -1
  63. package/dist/db/apply-entity-event.js +4 -0
  64. package/dist/db/bun-sql-connection-codes.d.ts +1 -0
  65. package/dist/db/bun-sql-connection-codes.js +7 -0
  66. package/dist/db/collect-table-metas.js +4 -1
  67. package/dist/db/config-seed.js +1 -1
  68. package/dist/db/derived-field-sql.js +15 -13
  69. package/dist/db/derived-related-sql.d.ts +2 -2
  70. package/dist/db/derived-related-sql.js +4 -2
  71. package/dist/db/dialect.d.ts +3 -0
  72. package/dist/db/dialect.js +1 -3
  73. package/dist/db/driver-row-coercion.js +2 -2
  74. package/dist/db/driver-value-preparation.js +1 -1
  75. package/dist/db/eagerload.js +15 -12
  76. package/dist/db/entity-table-meta.d.ts +2 -0
  77. package/dist/db/entity-table-meta.js +7 -0
  78. package/dist/db/event-store-executor-context.js +13 -8
  79. package/dist/db/event-store-executor-read-aggregate-currencies.js +2 -2
  80. package/dist/db/event-store-executor-read-aggregate.js +2 -2
  81. package/dist/db/event-store-executor-read-filter.d.ts +4 -0
  82. package/dist/db/event-store-executor-read-filter.js +28 -11
  83. package/dist/db/event-store-executor-read-search.d.ts +1 -0
  84. package/dist/db/event-store-executor-read-search.js +6 -6
  85. package/dist/db/event-store-executor-read-sort.js +3 -3
  86. package/dist/db/event-store-executor-read-where.js +14 -5
  87. package/dist/db/event-store-executor-read.js +7 -7
  88. package/dist/db/event-store-executor-write.js +50 -95
  89. package/dist/db/executor-managed-tables.js +4 -1
  90. package/dist/db/index.d.ts +4 -2
  91. package/dist/db/index.js +4 -2
  92. package/dist/db/known-table-names.d.ts +1 -0
  93. package/dist/db/known-table-names.js +7 -5
  94. package/dist/db/list-aggregate-labels.d.ts +1 -0
  95. package/dist/db/list-aggregate-labels.js +9 -1
  96. package/dist/db/migrate-generator.js +23 -4
  97. package/dist/db/migrate-rls-diff.d.ts +1 -0
  98. package/dist/db/migrate-rls-diff.js +15 -1
  99. package/dist/db/migrate-runner.js +2 -2
  100. package/dist/db/money.d.ts +1 -1
  101. package/dist/db/money.js +1 -4
  102. package/dist/db/parent-ref-clause.d.ts +6 -2
  103. package/dist/db/parent-ref-clause.js +105 -24
  104. package/dist/db/parent-ref-global-hosts.d.ts +23 -0
  105. package/dist/db/parent-ref-global-hosts.js +85 -0
  106. package/dist/db/production-schema-command-hint.d.ts +1 -0
  107. package/dist/db/production-schema-command-hint.js +3 -0
  108. package/dist/db/queries/backfill-pii.js +55 -29
  109. package/dist/db/queries/ddl.js +13 -2
  110. package/dist/db/queries/event-store-open-streams.d.ts +15 -0
  111. package/dist/db/queries/event-store-open-streams.js +33 -0
  112. package/dist/db/queries/event-store-payload-scrub.d.ts +5 -0
  113. package/dist/db/queries/event-store-payload-scrub.js +11 -0
  114. package/dist/db/queries/event-store.js +0 -1
  115. package/dist/db/queries/raw-sql.js +0 -1
  116. package/dist/db/queries/rebuild-rls-guard.d.ts +2 -1
  117. package/dist/db/queries/rebuild-rls-guard.js +24 -11
  118. package/dist/db/queries/rls-boot-catalog.d.ts +1 -0
  119. package/dist/db/queries/rls-boot-catalog.js +13 -9
  120. package/dist/db/queries/rls-shape.d.ts +3 -1
  121. package/dist/db/queries/rls-shape.js +31 -6
  122. package/dist/db/queries/session-advisory-lock.js +2 -1
  123. package/dist/db/queries/test-stack.js +7 -7
  124. package/dist/db/query.js +16 -11
  125. package/dist/db/rebuild-marker.js +11 -2
  126. package/dist/db/render-rls-ddl.d.ts +2 -0
  127. package/dist/db/render-rls-ddl.js +16 -11
  128. package/dist/db/replay-migration-sql.js +1 -1
  129. package/dist/db/row-level-security-boot-check.js +18 -5
  130. package/dist/db/row-level-security-connection.js +25 -12
  131. package/dist/db/row-level-security-scope.d.ts +2 -1
  132. package/dist/db/row-level-security-scope.js +9 -5
  133. package/dist/db/sql-identifier.d.ts +1 -0
  134. package/dist/db/sql-identifier.js +3 -0
  135. package/dist/db/system-tenant-read-db.d.ts +5 -0
  136. package/dist/db/system-tenant-read-db.js +28 -0
  137. package/dist/db/table-builder.d.ts +3 -1
  138. package/dist/db/table-builder.js +18 -8
  139. package/dist/db/table-info.d.ts +1 -2
  140. package/dist/db/table-introspection.d.ts +3 -0
  141. package/dist/db/table-introspection.js +6 -0
  142. package/dist/db/table-push.d.ts +1 -0
  143. package/dist/db/table-push.js +7 -1
  144. package/dist/db/tenant-db-runner.d.ts +3 -0
  145. package/dist/db/tenant-db-runner.js +19 -1
  146. package/dist/db/transaction-serialization.d.ts +1 -0
  147. package/dist/db/transaction-serialization.js +20 -3
  148. package/dist/db/where-clause.js +11 -2
  149. package/dist/db/write-ownership-failures.d.ts +25 -0
  150. package/dist/db/write-ownership-failures.js +82 -0
  151. package/dist/engine/boot-validator/boot-check.js +7 -1
  152. package/dist/engine/boot-validator/boot-phases-app.js +5 -5
  153. package/dist/engine/boot-validator/boot-phases.js +3 -2
  154. package/dist/engine/boot-validator/boot-rules.d.ts +305 -28
  155. package/dist/engine/boot-validator/boot-rules.js +4 -0
  156. package/dist/engine/boot-validator/bundled-lists-table.js +2 -2
  157. package/dist/engine/boot-validator/card-meta-overflow-rules.d.ts +2 -2
  158. package/dist/engine/boot-validator/card-meta-overflow-rules.js +2 -2
  159. package/dist/engine/boot-validator/card-meta-overflow.js +8 -5
  160. package/dist/engine/boot-validator/config-deps.d.ts +0 -1
  161. package/dist/engine/boot-validator/config-deps.js +0 -28
  162. package/dist/engine/boot-validator/config-key-rules.d.ts +0 -15
  163. package/dist/engine/boot-validator/config-key-rules.js +0 -15
  164. package/dist/engine/boot-validator/dashboard-screen-target.d.ts +22 -0
  165. package/dist/engine/boot-validator/dashboard-screen-target.js +20 -0
  166. package/dist/engine/boot-validator/dashboard-stat-navigate.d.ts +1 -0
  167. package/dist/engine/boot-validator/dashboard-stat-navigate.js +25 -17
  168. package/dist/engine/boot-validator/definition-webhook-events-rules.d.ts +5 -0
  169. package/dist/engine/boot-validator/definition-webhook-events-rules.js +5 -0
  170. package/dist/engine/boot-validator/derived-sql-fields.js +1 -2
  171. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +5 -0
  172. package/dist/engine/boot-validator/entity-declaration-rules.js +5 -0
  173. package/dist/engine/boot-validator/entity-list-screens.d.ts +1 -0
  174. package/dist/engine/boot-validator/entity-list-screens.js +35 -13
  175. package/dist/engine/boot-validator/entity-structure-rules.d.ts +5 -0
  176. package/dist/engine/boot-validator/entity-structure-rules.js +5 -0
  177. package/dist/engine/boot-validator/list-column-layout.js +10 -6
  178. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +67 -0
  179. package/dist/engine/boot-validator/list-row-guidance-rules.js +67 -0
  180. package/dist/engine/boot-validator/list-row-guidance.d.ts +20 -0
  181. package/dist/engine/boot-validator/list-row-guidance.js +143 -0
  182. package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +42 -0
  183. package/dist/engine/boot-validator/list-sort-summary-rules.js +42 -0
  184. package/dist/engine/boot-validator/list-sort-summary.d.ts +5 -0
  185. package/dist/engine/boot-validator/list-sort-summary.js +160 -0
  186. package/dist/engine/boot-validator/list-table-options.js +15 -1
  187. package/dist/engine/boot-validator/list-table-rules.d.ts +10 -5
  188. package/dist/engine/boot-validator/list-table-rules.js +10 -5
  189. package/dist/engine/boot-validator/list-toolbar-options.d.ts +10 -0
  190. package/dist/engine/boot-validator/list-toolbar-options.js +30 -0
  191. package/dist/engine/boot-validator/named-filter-rules.d.ts +42 -2
  192. package/dist/engine/boot-validator/named-filter-rules.js +42 -2
  193. package/dist/engine/boot-validator/ownership.js +10 -1
  194. package/dist/engine/boot-validator/parent-ref.js +87 -50
  195. package/dist/engine/boot-validator/projection-list-screens.d.ts +1 -0
  196. package/dist/engine/boot-validator/projection-list-screens.js +32 -1
  197. package/dist/engine/boot-validator/query-output-columns.js +62 -9
  198. package/dist/engine/boot-validator/query-output-guidance.d.ts +7 -0
  199. package/dist/engine/boot-validator/query-output-guidance.js +40 -0
  200. package/dist/engine/boot-validator/query-refs.js +34 -1
  201. package/dist/engine/boot-validator/row-decoration.d.ts +11 -0
  202. package/dist/engine/boot-validator/row-decoration.js +16 -0
  203. package/dist/engine/boot-validator/screens-actions.js +1 -1
  204. package/dist/engine/boot-validator/screens-dashboard-links.d.ts +10 -0
  205. package/dist/engine/boot-validator/screens-dashboard-links.js +36 -0
  206. package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +4 -0
  207. package/dist/engine/boot-validator/screens-dashboard-narrow.js +211 -0
  208. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +84 -4
  209. package/dist/engine/boot-validator/screens-dashboard-rules.js +84 -4
  210. package/dist/engine/boot-validator/screens-dashboard.js +29 -7
  211. package/dist/engine/boot-validator/screens-kind-entity-list.js +32 -27
  212. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.d.ts +3 -0
  213. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.js +46 -0
  214. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +20 -0
  215. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +20 -0
  216. package/dist/engine/boot-validator/screens-kind-projection-detail.js +2 -0
  217. package/dist/engine/boot-validator/screens-kind-projection-list.js +4 -0
  218. package/dist/engine/boot-validator/screens-kind-rules.d.ts +25 -0
  219. package/dist/engine/boot-validator/screens-kind-rules.js +25 -0
  220. package/dist/engine/boot-validator/screens-lists.d.ts +8 -2
  221. package/dist/engine/boot-validator/screens-lists.js +19 -3
  222. package/dist/engine/boot-validator/screens.js +1 -1
  223. package/dist/engine/boot-validator/sort-nulls.d.ts +2 -0
  224. package/dist/engine/boot-validator/sort-nulls.js +15 -0
  225. package/dist/engine/boot-validator/zod-shape.d.ts +2 -1
  226. package/dist/engine/boot-validator/zod-shape.js +19 -1
  227. package/dist/engine/build-app-schema.js +4 -0
  228. package/dist/engine/config-helpers.d.ts +1 -2
  229. package/dist/engine/config-helpers.js +6 -7
  230. package/dist/engine/define-feature.js +1 -0
  231. package/dist/engine/define-handler.d.ts +1 -0
  232. package/dist/engine/define-handler.js +4 -2
  233. package/dist/engine/definition-violations.js +2 -2
  234. package/dist/engine/entity-handlers.js +3 -8
  235. package/dist/engine/entity-list-runtime-options.js +9 -8
  236. package/dist/engine/factories.d.ts +2 -0
  237. package/dist/engine/feature-config-events-jobs.js +1 -0
  238. package/dist/engine/feature-entity-handlers.js +5 -2
  239. package/dist/engine/field-access.d.ts +1 -1
  240. package/dist/engine/field-access.js +7 -10
  241. package/dist/engine/find-entity.js +3 -3
  242. package/dist/engine/form-derivations.js +3 -3
  243. package/dist/engine/index.d.ts +3 -3
  244. package/dist/engine/index.js +2 -2
  245. package/dist/engine/named-filter-roles.d.ts +3 -0
  246. package/dist/engine/named-filter-roles.js +15 -0
  247. package/dist/engine/pipeline.js +0 -1
  248. package/dist/engine/project-app-schema-for-roles.js +17 -2
  249. package/dist/engine/qualified-name.js +0 -1
  250. package/dist/engine/registry-facade.js +1 -2
  251. package/dist/engine/registry-state.d.ts +1 -1
  252. package/dist/engine/registry-state.js +5 -2
  253. package/dist/engine/registry-validate.js +2 -1
  254. package/dist/engine/resolve-named-list-filters.js +5 -2
  255. package/dist/engine/schema-builder.js +9 -11
  256. package/dist/engine/screen-helpers.d.ts +12 -0
  257. package/dist/engine/screen-helpers.js +17 -1
  258. package/dist/engine/soft-delete-cleanup.js +3 -5
  259. package/dist/engine/state-machine.js +0 -1
  260. package/dist/engine/steps/_database-clock.d.ts +2 -0
  261. package/dist/engine/steps/_database-clock.js +6 -0
  262. package/dist/engine/steps/compute.js +1 -1
  263. package/dist/engine/steps/retry.js +5 -1
  264. package/dist/engine/steps/return.js +0 -1
  265. package/dist/engine/steps/wait-for-event.js +2 -1
  266. package/dist/engine/steps/wait.js +2 -1
  267. package/dist/engine/system-user.d.ts +2 -2
  268. package/dist/engine/system-user.js +2 -2
  269. package/dist/engine/types/handlers.d.ts +1 -1
  270. package/dist/engine/types/handlers.js +1 -1
  271. package/dist/engine/types/screen.d.ts +1 -1
  272. package/dist/engine/types/screen.js +1 -1
  273. package/dist/engine/webhook-contracts.d.ts +2 -3
  274. package/dist/engine/webhook-contracts.js +2 -25
  275. package/dist/engine/webhook-events.js +48 -29
  276. package/dist/engine/webhook-payload-strictness.d.ts +7 -0
  277. package/dist/engine/webhook-payload-strictness.js +53 -0
  278. package/dist/env/_zod-introspect.d.ts +1 -0
  279. package/dist/env/dry-run.d.ts +1 -1
  280. package/dist/env/dry-run.js +1 -1
  281. package/dist/env/field-meta.d.ts +4 -0
  282. package/dist/env/field-meta.js +67 -0
  283. package/dist/env/field-rules.d.ts +9 -0
  284. package/dist/env/field-rules.js +46 -0
  285. package/dist/env/index.d.ts +3 -3
  286. package/dist/env/index.js +16 -71
  287. package/dist/env/internals.d.ts +3 -0
  288. package/dist/env/internals.js +1 -2
  289. package/dist/env/required-env.d.ts +3 -1
  290. package/dist/env/required-env.js +5 -2
  291. package/dist/errors/reasons.d.ts +1 -0
  292. package/dist/errors/reasons.js +4 -0
  293. package/dist/errors/serialize.js +2 -2
  294. package/dist/errors/write-error-info.js +0 -2
  295. package/dist/es-ops/operations-schema.js +18 -7
  296. package/dist/event-store/admin-api.js +3 -3
  297. package/dist/event-store/event-store.js +0 -3
  298. package/dist/event-store/index.d.ts +1 -0
  299. package/dist/event-store/index.js +1 -0
  300. package/dist/event-store/transfer.js +1 -1
  301. package/dist/files/assert-file-refs-belong-to-tenant.d.ts +2 -1
  302. package/dist/files/assert-file-refs-belong-to-tenant.js +15 -13
  303. package/dist/files/bind-pending-file-refs.d.ts +3 -1
  304. package/dist/files/bind-pending-file-refs.js +54 -27
  305. package/dist/files/copy-pending-file-refs-to-tenant.js +7 -3
  306. package/dist/files/create-file-ref.d.ts +4 -1
  307. package/dist/files/create-file-ref.js +14 -3
  308. package/dist/files/default-file-guard.js +4 -1
  309. package/dist/files/file-claim.d.ts +6 -0
  310. package/dist/files/file-claim.js +17 -0
  311. package/dist/files/file-field-slots.d.ts +2 -0
  312. package/dist/files/file-field-slots.js +28 -0
  313. package/dist/files/file-ref-entity.d.ts +3 -0
  314. package/dist/files/file-ref-entity.js +2 -0
  315. package/dist/files/file-ref-table.d.ts +3 -0
  316. package/dist/files/file-routes.d.ts +4 -1
  317. package/dist/files/file-routes.js +80 -16
  318. package/dist/files/in-memory-provider.d.ts +1 -1
  319. package/dist/files/in-memory-provider.js +2 -1
  320. package/dist/files/index.d.ts +1 -1
  321. package/dist/files/index.js +1 -1
  322. package/dist/files/invalid-file-ref-error.d.ts +2 -0
  323. package/dist/files/invalid-file-ref-error.js +15 -0
  324. package/dist/files/local-provider.js +9 -2
  325. package/dist/files/provider-resolver.js +1 -1
  326. package/dist/files/rebind-file-ref.d.ts +3 -2
  327. package/dist/files/rebind-file-ref.js +24 -18
  328. package/dist/files/resolve-file-handles.d.ts +13 -0
  329. package/dist/files/resolve-file-handles.js +57 -0
  330. package/dist/files/storage-tracking.d.ts +1 -1
  331. package/dist/files/storage-tracking.js +5 -2
  332. package/dist/files/sweep-stale-pending-file-refs.js +10 -4
  333. package/dist/files/types.d.ts +4 -0
  334. package/dist/files/types.js +10 -0
  335. package/dist/files/upload-field-resolution.d.ts +1 -0
  336. package/dist/files/upload-field-resolution.js +16 -2
  337. package/dist/files/upload-ledger.js +1 -1
  338. package/dist/i18n/required-surface-guidance-keys.d.ts +3 -0
  339. package/dist/i18n/required-surface-guidance-keys.js +9 -0
  340. package/dist/i18n/required-surface-keys.js +21 -5
  341. package/dist/internal/boot-rule-table-expectations.d.ts +2 -0
  342. package/dist/internal/boot-rule-table-expectations.js +29 -0
  343. package/dist/internal/row-level-security.d.ts +1 -0
  344. package/dist/internal/row-level-security.js +1 -0
  345. package/dist/internal/testing.d.ts +1 -0
  346. package/dist/internal/testing.js +1 -0
  347. package/dist/jobs/index.d.ts +1 -0
  348. package/dist/jobs/index.js +1 -0
  349. package/dist/jobs/job-load-events.d.ts +10 -0
  350. package/dist/jobs/job-load-events.js +12 -0
  351. package/dist/jobs/job-runner-context.js +6 -158
  352. package/dist/jobs/job-runner-dispatch.d.ts +7 -0
  353. package/dist/jobs/job-runner-dispatch.js +57 -0
  354. package/dist/jobs/job-runner-event-triggers.js +18 -9
  355. package/dist/jobs/job-runner-execution.js +5 -2
  356. package/dist/jobs/job-runner-facets.d.ts +48 -0
  357. package/dist/jobs/job-runner-facets.js +156 -0
  358. package/dist/jobs/job-runner-gates.js +19 -11
  359. package/dist/jobs/job-runner-helpers.d.ts +5 -1
  360. package/dist/jobs/job-runner-helpers.js +18 -3
  361. package/dist/jobs/job-runner-scope.d.ts +1 -0
  362. package/dist/jobs/job-runner-scope.js +2 -0
  363. package/dist/jobs/job-runner-tenant-cap-lock.d.ts +2 -0
  364. package/dist/jobs/job-runner-tenant-cap-lock.js +30 -0
  365. package/dist/jobs/job-runner-types.d.ts +1 -0
  366. package/dist/jobs/job-runner.js +39 -70
  367. package/dist/jobs/obliterate-job-queues.d.ts +6 -0
  368. package/dist/jobs/obliterate-job-queues.js +23 -0
  369. package/dist/lifecycle/lifecycle.js +1 -1
  370. package/dist/migrations/event-header-scrub.d.ts +11 -0
  371. package/dist/migrations/event-header-scrub.js +33 -0
  372. package/dist/migrations/event-payload-scrub.d.ts +1 -1
  373. package/dist/migrations/event-payload-scrub.js +36 -4
  374. package/dist/migrations/index.d.ts +1 -0
  375. package/dist/migrations/index.js +2 -0
  376. package/dist/migrations/kumiko-drift.d.ts +5 -2
  377. package/dist/migrations/kumiko-drift.js +51 -14
  378. package/dist/migrations/pending-rebuilds.js +4 -5
  379. package/dist/observability/sensitive-filter.js +0 -12
  380. package/dist/pipeline/aggregate-type-removal.js +17 -4
  381. package/dist/pipeline/context-services.d.ts +2 -0
  382. package/dist/pipeline/context-services.js +5 -2
  383. package/dist/pipeline/dispatch-batch.js +4 -3
  384. package/dist/pipeline/dispatch-context-helpers.d.ts +11 -0
  385. package/dist/pipeline/dispatch-context-helpers.js +58 -0
  386. package/dist/pipeline/dispatch-nested-write.d.ts +7 -0
  387. package/dist/pipeline/dispatch-nested-write.js +119 -0
  388. package/dist/pipeline/dispatch-query.js +10 -3
  389. package/dist/pipeline/dispatch-scope.js +4 -3
  390. package/dist/pipeline/dispatch-shared.d.ts +2 -6
  391. package/dist/pipeline/dispatch-shared.js +6 -38
  392. package/dist/pipeline/dispatch-write.d.ts +0 -1
  393. package/dist/pipeline/dispatch-write.js +3 -302
  394. package/dist/pipeline/dispatcher-utils.js +6 -0
  395. package/dist/pipeline/effective-system-scope.d.ts +3 -0
  396. package/dist/pipeline/effective-system-scope.js +22 -0
  397. package/dist/pipeline/event-dispatcher-delivery.d.ts +1 -0
  398. package/dist/pipeline/event-dispatcher-delivery.js +20 -9
  399. package/dist/pipeline/event-dispatcher.d.ts +6 -1
  400. package/dist/pipeline/event-dispatcher.js +6 -7
  401. package/dist/pipeline/handler-context-auth.d.ts +3 -2
  402. package/dist/pipeline/handler-context-auth.js +3 -4
  403. package/dist/pipeline/handler-context-db.js +11 -4
  404. package/dist/pipeline/handler-context-dispatch.js +2 -2
  405. package/dist/pipeline/handler-context-events.d.ts +8 -3
  406. package/dist/pipeline/handler-context-events.js +20 -65
  407. package/dist/pipeline/handler-context-member-resolution.js +16 -8
  408. package/dist/pipeline/handler-context-notify.d.ts +1 -0
  409. package/dist/pipeline/handler-context-notify.js +2 -0
  410. package/dist/pipeline/handler-context-phase-denials.js +3 -2
  411. package/dist/pipeline/handler-context-projection.d.ts +3 -0
  412. package/dist/pipeline/handler-context-projection.js +39 -0
  413. package/dist/pipeline/handler-context-scope.d.ts +1 -1
  414. package/dist/pipeline/handler-context-scope.js +14 -2
  415. package/dist/pipeline/index.d.ts +1 -1
  416. package/dist/pipeline/index.js +1 -1
  417. package/dist/pipeline/irreversible-operation-gate.js +36 -10
  418. package/dist/pipeline/lifecycle-pipeline.d.ts +1 -0
  419. package/dist/pipeline/lifecycle-pipeline.js +7 -4
  420. package/dist/pipeline/member-reader.js +4 -2
  421. package/dist/pipeline/msp-rebuild.js +1 -1
  422. package/dist/pipeline/nested-write-parent-guard.d.ts +5 -0
  423. package/dist/pipeline/nested-write-parent-guard.js +81 -0
  424. package/dist/pipeline/projection-rebuild.d.ts +2 -0
  425. package/dist/pipeline/projection-rebuild.js +16 -7
  426. package/dist/pipeline/projection-state.js +4 -6
  427. package/dist/pipeline/system-hooks.js +36 -6
  428. package/dist/pipeline/write-result-masking.js +31 -3
  429. package/dist/pipeline/write-transition-guard.d.ts +7 -0
  430. package/dist/pipeline/write-transition-guard.js +95 -0
  431. package/dist/schema-cli/shared.d.ts +2 -0
  432. package/dist/schema-cli/shared.js +4 -2
  433. package/dist/schema-cli/validate-command.js +43 -28
  434. package/dist/search/meilisearch-adapter-internals.d.ts +2 -0
  435. package/dist/search/meilisearch-adapter-internals.js +5 -0
  436. package/dist/search/meilisearch-adapter.d.ts +1 -0
  437. package/dist/search/meilisearch-adapter.js +17 -11
  438. package/dist/search/reindex-entity.d.ts +2 -0
  439. package/dist/search/reindex-entity.js +32 -4
  440. package/dist/search/reindex-tenants-search.js +20 -4
  441. package/dist/time/tz-context.js +1 -1
  442. package/dist/ui-types/card-column-roles.d.ts +6 -0
  443. package/dist/ui-types/card-column-roles.js +21 -3
  444. package/dist/ui-types/index.d.ts +3 -3
  445. package/dist/ui-types/index.js +2 -2
  446. package/dist/utils/ids.js +0 -1
  447. package/dist/utils/index.d.ts +1 -0
  448. package/dist/utils/index.js +1 -0
  449. package/dist/utils/return-path-limit.d.ts +1 -0
  450. package/dist/utils/return-path-limit.js +1 -0
  451. package/package.json +5 -3
  452. package/presets/biome-app.json +39 -21
  453. package/presets/biome-plugins/admin-api.grit +10 -0
  454. package/presets/biome-plugins/error-reasons.grit +53 -0
  455. package/presets/biome-plugins/es-literal-writes-tests.grit +18 -0
  456. package/presets/biome-plugins/es-literal-writes.grit +22 -0
  457. package/presets/biome-plugins/i18n-locale-terminology-de.grit +15 -0
  458. package/presets/biome-plugins/i18n-locale-terminology-romance.grit +10 -0
  459. package/presets/biome-plugins/no-create-test-dispatcher.grit +5 -0
  460. package/presets/biome-plugins/no-css-properties-type.grit +7 -0
  461. package/presets/biome-plugins/no-date-api.grit +11 -0
  462. package/presets/biome-plugins/no-direct-fetch.grit +16 -0
  463. package/presets/biome-plugins/no-direct-fs.grit +16 -0
  464. package/presets/biome-plugins/no-external-font-cdn-css.grit +9 -0
  465. package/presets/biome-plugins/no-external-font-cdn.grit +12 -0
  466. package/presets/biome-plugins/no-raw-hooks.grit +10 -0
  467. package/presets/biome-plugins/no-same-folder-barrel-import.grit +11 -0
  468. package/presets/biome-plugins/no-screen-container-classes.grit +7 -0
  469. package/presets/biome-plugins/no-skipped-or-retried-tests.grit +34 -0
  470. package/presets/biome-plugins/no-temporal-polyfill-require.grit +10 -0
  471. package/presets/biome-plugins/raw-html-in-web.grit +40 -0
  472. package/presets/biome-plugins/raw-ui-in-app.grit +142 -0
  473. package/presets/biome-plugins/restricted-event-store-symbols.grit +18 -0
  474. package/presets/biome-plugins/test-title.grit +20 -0
  475. package/presets/biome-plugins/unsafe-json-parse.grit +12 -0
  476. package/presets/biome-rules.json +467 -0
  477. package/src/changes.json +366 -0
  478. package/dist/engine/minor-units.d.ts +0 -2
  479. package/dist/engine/minor-units.js +0 -8
@@ -8,13 +8,13 @@ import { registerStandardMetrics } from "../observability/standard-metrics.js";
8
8
  import { configAccessorFactoryOf } from "../pipeline/config-accessor-factory.js";
9
9
  import { createDispatcher } from "../pipeline/dispatcher.js";
10
10
  import { createLifecycleHooks } from "../pipeline/lifecycle-pipeline.js";
11
- import { createPayloadDigest, createRateLimitResolver } from "../rate-limit/index.js";
12
11
  import { resolveCacheSyncBus } from "../redis/cache-sync-bus.js";
13
12
  import { assertValidTrustedProxyHops, createClientIpResolver, } from "./client-ip.js";
14
13
  import { createJwtHelper } from "./jwt.js";
15
14
  import { createDefaultSseBroker } from "./redis-sse-broker.js";
16
- import { assertFileStorageProviderForFileFields, assertNoPayloadRateLimitsWithoutResolver, resolveServerInstanceId, warnSearchableScreensWithoutSearchAdapter, warnUnlimitedSystemScopeFeatures, } from "./server-boot-checks.js";
15
+ import { assertFileStorageProviderForFileFields, resolveServerInstanceId, warnSearchableScreensWithoutSearchAdapter, } from "./server-boot-checks.js";
17
16
  import { createServerEventDispatcher, registerOwnedShutdownHooks, } from "./server-event-dispatcher.js";
17
+ import { resolveServerRateLimit } from "./server-rate-limit-wiring.js";
18
18
  // The per-tenant file-provider resolver, built once for a registry+context so
19
19
  // a job-runner and the server it runs beside share one instance (and one
20
20
  // per-tenant provider cache). Mirrors buildServer's own resolution exactly —
@@ -174,32 +174,6 @@ function resolveTracedRedis(options, observability) {
174
174
  const redisCtx = options.context.redis;
175
175
  return shouldWrapRedis && redisCtx ? wrapRedisClient(redisCtx, observability.tracer) : redisCtx;
176
176
  }
177
- function resolveServerRateLimit(options, tracedRedis, bootLog) {
178
- // Auto-wire the rate-limit resolver, but ONLY when at least one
179
- // handler actually declared a rateLimit option. Apps that don't use
180
- // L3 pay zero cost: no resolver instance, no Lua-script registration
181
- // on Redis, no AppContext field. Apps that wire L1/L2 middleware can
182
- // pass `context.rateLimit` explicitly — that takes precedence over
183
- // the auto-wire (e.g. middleware-only setup without any L3 handler).
184
- // Auto-build the resolver when L3 handlers declared rateLimit OR when
185
- // the caller asked for L1/L2 middleware. Either path needs a resolver;
186
- // both share the same instance to avoid duplicate Lua-script registration.
187
- const wantsL3 = options.registry.hasRateLimitedHandler();
188
- const wantsL1L2 = options.rateLimit?.global !== undefined || options.rateLimit?.auth !== undefined;
189
- const wantsHttpRouteLimit = [...options.registry.features.values()].some((feature) => Object.values(feature.httpRoutes).some((route) => route.rateLimit !== undefined));
190
- const wantsResolver = wantsL3 || wantsL1L2 || wantsHttpRouteLimit;
191
- // Master for the payload-bucket HMAC: the current signing secret (the
192
- // keyring's signKid for rotation setups). buildServer always has one, so
193
- // the digest is available whenever a handler declares additionalRateLimits.
194
- const payloadDigest = createPayloadDigest(payloadDigestMasterSecret(options.jwtSecret));
195
- const rateLimitResolver = options.context.rateLimit ??
196
- (tracedRedis && wantsResolver ? createRateLimitResolver({ redis: tracedRedis }) : undefined);
197
- if (!rateLimitResolver) {
198
- assertNoPayloadRateLimitsWithoutResolver(options.registry);
199
- warnUnlimitedSystemScopeFeatures(options.registry, bootLog);
200
- }
201
- return { resolver: rateLimitResolver, middlewareRequested: wantsL1L2, payloadDigest };
202
- }
203
177
  function buildServerAppContext(options, parts) {
204
178
  const { contextWithFiles, tracedRedis, rateLimit, cacheSync, observability } = parts;
205
179
  return {
@@ -229,12 +203,3 @@ function createServerDispatcher(options, context, lifecycle, sseBroker, cacheSyn
229
203
  ...(options.auth ? { membershipQuery: options.auth.membershipQuery } : {}),
230
204
  });
231
205
  }
232
- function payloadDigestMasterSecret(jwtSecret) {
233
- if (typeof jwtSecret === "string")
234
- return jwtSecret;
235
- const signingSecret = jwtSecret.keys[jwtSecret.signKid];
236
- if (signingSecret === undefined) {
237
- throw new Error(`[kumiko] jwtSecret.signKid "${jwtSecret.signKid}" not found in jwtSecret.keys`);
238
- }
239
- return signingSecret;
240
- }
@@ -2,8 +2,10 @@ import { Hono } from "hono";
2
2
  import { DEFAULT_MAX_REQUEST_BYTES, registerBodyLimit, registerVersionRoute, } from "./route-registrars.js";
3
3
  import { handleUncaughtRouteError } from "./routes.js";
4
4
  import { compilePublicApiRequestMatcher, mountExtraRoutes } from "./server-extra-routes.js";
5
+ import { mountFeatureHttpRoutes } from "./server-feature-http-routes.js";
5
6
  import { installAuthGuardChain, installObservability, installPiiLeakGuard, installRateLimitMiddleware, installRequestId, installSessionCookies, } from "./server-middleware.js";
6
- import { installNoRouteMatchMarker, mountAuthRoutes, mountClientErrorRoute, mountDispatcherRoutes, mountFeatureHttpRoutes, mountFileRoutes, mountOperationalRoutes, mountSchemaRoute, } from "./server-routes.js";
7
+ import { installNoRouteMatchMarker, mountAuthRoutes, mountClientErrorRoute, mountDispatcherRoutes, mountFileRoutes, mountOperationalRoutes, } from "./server-routes.js";
8
+ import { mountSchemaRoute } from "./server-schema-route.js";
7
9
  import { mountWebSocketRoutes } from "./server-websocket-routes.js";
8
10
  import { resolveServerWiring } from "./server-wiring.js";
9
11
  export function buildServer(options) {
@@ -1,15 +1,15 @@
1
1
  // Zod schema for ComplianceProfileOverride with recursive `.strict()` validation.
2
2
  //
3
- // Previously, set-profile.write.ts checked only top-level keys against
4
- // OVERRIDABLE_PROFILE_KEYS. Sub-level typos (for example,
3
+ // A top-level key whitelist alone would let sub-level typos (for example,
5
4
  // `{ userRights: { weeks: 3 } }` instead of
6
- // `{ userRights: { gracePeriod: { days: 30 } } }`) passed through —
5
+ // `{ userRights: { gracePeriod: { days: 30 } } }`) pass through —
7
6
  // deepMerge spliced the nonsense into the effective profile, and a caller
8
7
  // reading `userRights.gracePeriod.days` crashed with `undefined`.
9
8
  //
10
9
  // The schema maps the ComplianceProfile structure to DeepPartial form and
11
- // uses `.strict()` on every object so unknown keys throw. It is a single
12
- // source of truth like OVERRIDABLE_PROFILE_KEYS, with sub-level coverage.
10
+ // uses `.strict()` on every object so unknown keys throw. It is the single
11
+ // source of truth for the override whitelist; profiles.test.ts checks it
12
+ // against ComplianceProfile.
13
13
  //
14
14
  // Identification fields (`key`, `region`, `label`, `extends`) are excluded
15
15
  // from the schema because overriding them would destroy profile identity.
@@ -64,6 +64,15 @@ export const KUMIKO_SUB_PROCESSORS = [
64
64
  sccRequired: true,
65
65
  status: "active",
66
66
  },
67
+ {
68
+ name: "Scaleway SAS",
69
+ purpose: "Platform key custody (Key Manager)",
70
+ region: "EU (France)",
71
+ dpa: "https://www.scaleway.com/en/contracts/",
72
+ addedAt: "2026-07-04",
73
+ appliesTo: ["all-tiers"],
74
+ status: "active",
75
+ },
67
76
  {
68
77
  name: "ALL-INKL.COM – Neue Medien Münnich",
69
78
  purpose: "Mailbox Hosting (support and contact mailboxes)",
@@ -84,7 +93,7 @@ export const KUMIKO_SUB_PROCESSORS = [
84
93
  },
85
94
  {
86
95
  name: "Scaleway SAS",
87
- purpose: "Platform key custody (Key Manager) and Transactional Email Delivery",
96
+ purpose: "Transactional Email Delivery (TEM)",
88
97
  region: "EU (France)",
89
98
  dpa: "https://www.scaleway.com/en/contracts/",
90
99
  addedAt: "2026-11-01",
@@ -9,5 +9,5 @@ export { type KmsWiring, requireKmsWiring, requireKmsWiringAsync, resolveKmsWiri
9
9
  export { hashOpaqueToken, hashOpaqueTokenSync, opaqueTokenHashMatches, } from "./opaque-token-hash.ts";
10
10
  export { createPgKmsAdapter, rewrapSubjectKeys, } from "./pg-kms-adapter.ts";
11
11
  export { PII_CIPHERTEXT_CORRUPT_CODE, PiiCiphertextCorruptError, } from "./pii-ciphertext-corrupt.ts";
12
- export { configuredPiiSubjectKms, configurePiiSubjectKms, decryptPiiFieldValues, decryptPiiValueForSubject, encryptPiiFieldValues, encryptPiiJsonValueForSubject, encryptPiiValueForSubject, isPiiCiphertext, PII_CIPHERTEXT_PREFIX, PII_ERASED_SENTINEL, } from "./pii-field-encryption.ts";
12
+ export { configuredPiiSubjectKms, configurePiiSubjectKms, decryptPiiFieldValues, decryptPiiValueForSubject, encryptPiiFieldValues, encryptPiiJsonValueForSubject, encryptPiiValueForSubject, isPiiCiphertext, PII_CIPHERTEXT_PREFIX, PII_ERASED_SENTINEL, piiCiphertextMaxLengthFor, } from "./pii-field-encryption.ts";
13
13
  export { collectPiiEncryptedFields, collectPiiSubjectFields, isRecordKeyedField, resolveSubjectForField, SubjectResolutionError, } from "./subject-resolver.ts";
@@ -9,5 +9,5 @@ export { requireKmsWiring, requireKmsWiringAsync, resolveKmsWiring, resolveKmsWi
9
9
  export { hashOpaqueToken, hashOpaqueTokenSync, opaqueTokenHashMatches, } from "./opaque-token-hash.js";
10
10
  export { createPgKmsAdapter, rewrapSubjectKeys, } from "./pg-kms-adapter.js";
11
11
  export { PII_CIPHERTEXT_CORRUPT_CODE, PiiCiphertextCorruptError, } from "./pii-ciphertext-corrupt.js";
12
- export { configuredPiiSubjectKms, configurePiiSubjectKms, decryptPiiFieldValues, decryptPiiValueForSubject, encryptPiiFieldValues, encryptPiiJsonValueForSubject, encryptPiiValueForSubject, isPiiCiphertext, PII_CIPHERTEXT_PREFIX, PII_ERASED_SENTINEL, } from "./pii-field-encryption.js";
12
+ export { configuredPiiSubjectKms, configurePiiSubjectKms, decryptPiiFieldValues, decryptPiiValueForSubject, encryptPiiFieldValues, encryptPiiJsonValueForSubject, encryptPiiValueForSubject, isPiiCiphertext, PII_CIPHERTEXT_PREFIX, PII_ERASED_SENTINEL, piiCiphertextMaxLengthFor, } from "./pii-field-encryption.js";
13
13
  export { collectPiiEncryptedFields, collectPiiSubjectFields, isRecordKeyedField, resolveSubjectForField, SubjectResolutionError, } from "./subject-resolver.js";
@@ -3,6 +3,8 @@ import type { TenantId } from "../engine/types/identifiers.ts";
3
3
  import { type KmsAdapter, type KmsContext, type LocalKeyKmsAdapter, PII_ERASED_SENTINEL, type SubjectId } from "./kms-adapter.ts";
4
4
  import { isPiiCiphertext, PII_CIPHERTEXT_PREFIX, PII_CIPHERTEXT_PREFIX_JSON } from "./pii-ciphertext-format.ts";
5
5
  export { isPiiCiphertext, PII_CIPHERTEXT_PREFIX, PII_CIPHERTEXT_PREFIX_JSON, PII_ERASED_SENTINEL };
6
+ /** Upper bound for the stored length of a PII value whose plaintext is at most `plaintextMax` characters. */
7
+ export declare function piiCiphertextMaxLengthFor(plaintextMax: number): number;
6
8
  export declare function piiCiphertextSubject(value: string): SubjectId;
7
9
  export declare function encryptPiiValueForSubject(kms: LocalKeyKmsAdapter, subject: SubjectId, value: string, kmsCtx: KmsContext, field: string): Promise<string>;
8
10
  export declare function encryptPiiJsonValueForSubject(kms: LocalKeyKmsAdapter, subject: SubjectId, value: unknown, kmsCtx: KmsContext, field: string): Promise<string>;
@@ -17,14 +17,25 @@
17
17
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
18
18
  import { assertIrreversibleOperationAllowed } from "../pipeline/irreversible-operation-gate.js";
19
19
  import { isLocalKeyKmsAdapter, KeyAlreadyExistsError, KeyErasedError, KeyNotFoundError, PII_ERASED_SENTINEL, subjectIdFromKey, subjectIdToKey, } from "./kms-adapter.js";
20
- import { classifyKmsOutage } from "./kms-outage.js";
20
+ import { classifyKmsOutage, EncryptionUnavailableError } from "./kms-outage.js";
21
21
  import { PiiCiphertextCorruptError } from "./pii-ciphertext-corrupt.js";
22
22
  import { isPiiCiphertext, PII_CIPHERTEXT_PREFIX, PII_CIPHERTEXT_PREFIX_JSON, PII_CIPHERTEXT_PREFIX_V1, } from "./pii-ciphertext-format.js";
23
23
  import { resolveSubjectForField } from "./subject-resolver.js";
24
24
  // Spec value (crypto-shredding.md) — renderers show it verbatim.
25
25
  export { isPiiCiphertext, PII_CIPHERTEXT_PREFIX, PII_CIPHERTEXT_PREFIX_JSON, PII_ERASED_SENTINEL };
26
+ const DEK_LENGTH = 32;
26
27
  const IV_LENGTH = 12;
27
28
  const AUTH_TAG_LENGTH = 16;
29
+ // A zod `max` counts UTF-16 units, each of which is at most 3 UTF-8 bytes (a surrogate pair is 2 units, 4 bytes).
30
+ const MAX_UTF8_BYTES_PER_UTF16_UNIT = 3;
31
+ // "tenant:<uuid>" / "user:<uuid>" are 43 / 41 chars; record keys carry a free-form entity name, so leave headroom.
32
+ const SUBJECT_KEY_MAX_LENGTH = 128;
33
+ /** Upper bound for the stored length of a PII value whose plaintext is at most `plaintextMax` characters. */
34
+ export function piiCiphertextMaxLengthFor(plaintextMax) {
35
+ const blobBytes = IV_LENGTH + AUTH_TAG_LENGTH + plaintextMax * MAX_UTF8_BYTES_PER_UTF16_UNIT;
36
+ const base64Length = Math.ceil(blobBytes / 3) * 4;
37
+ return PII_CIPHERTEXT_PREFIX_JSON.length + SUBJECT_KEY_MAX_LENGTH + 1 + base64Length;
38
+ }
28
39
  function buildAad(subject, field, isJson) {
29
40
  return Buffer.from(`${subjectIdToKey(subject)}|${field}${isJson ? "|json" : ""}`, "utf8");
30
41
  }
@@ -59,6 +70,10 @@ function parseCiphertext(value) {
59
70
  };
60
71
  }
61
72
  function decryptValue(dek, blob, subject, field, hasAad, isJson) {
73
+ // A wrong-sized DEK is a key-store fault, not a damaged ciphertext: scrub/export must not wipe intact values for it.
74
+ if (dek.length !== DEK_LENGTH) {
75
+ throw new EncryptionUnavailableError(new Error(`DEK has ${dek.length} bytes, expected ${DEK_LENGTH}`));
76
+ }
62
77
  try {
63
78
  const iv = blob.subarray(0, IV_LENGTH);
64
79
  const tag = blob.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH);
@@ -164,5 +164,9 @@ async function applyEntityEventInScope(event, table, entity, tx) {
164
164
  await deleteMany(tx, table, { id: event.aggregateId });
165
165
  return { kind: "applied", verb, row: null };
166
166
  }
167
+ default: {
168
+ const exhaustiveCheck = verb;
169
+ return exhaustiveCheck;
170
+ }
167
171
  }
168
172
  }
@@ -0,0 +1 @@
1
+ export declare const BUN_SQL_CONNECTION_ERROR_CODES: readonly string[];
@@ -0,0 +1,7 @@
1
+ // Client-side Bun.SQL failures that mean the connection could not be used.
2
+ export const BUN_SQL_CONNECTION_ERROR_CODES = [
3
+ "ERR_POSTGRES_CONNECTION_CLOSED",
4
+ "ERR_POSTGRES_CONNECTION_REFUSED",
5
+ "ERR_POSTGRES_CONNECTION_TIMEOUT",
6
+ "ERR_POSTGRES_CONNECTION_FAILED",
7
+ ];
@@ -2,7 +2,7 @@
2
2
  // (entities, storeTables, projections, multiStreamProjections). One shared
3
3
  // source so the test-DB push and migrations cannot drift apart again.
4
4
  import { compareByCodepoint } from "../utils/compare.js";
5
- import { assertBackingTableSuperset, deriveEntityTableMeta, } from "./entity-table-meta.js";
5
+ import { assertBackingTableSuperset, deriveEntityTableMeta, entityReadsSystemRows, } from "./entity-table-meta.js";
6
6
  import { enumerateFeatureTableSources } from "./feature-table-sources.js";
7
7
  import { asEntityTableMeta } from "./query.js";
8
8
  function canonicalColumnsKey(meta) {
@@ -45,6 +45,9 @@ export function collectTableMetas(features) {
45
45
  assertBackingTableSuperset(name, fieldMeta, tableMeta);
46
46
  meta = tableMeta;
47
47
  }
48
+ if (entityReadsSystemRows(feature, name, ent) && meta.systemRowsReadable !== true) {
49
+ meta = { ...meta, systemRowsReadable: true };
50
+ }
48
51
  registerPass1Meta(metas, byName, meta, `entity "${name}" (${feature.name})`);
49
52
  }
50
53
  for (const entry of Object.values(feature.storeTables)) {
@@ -47,7 +47,7 @@ export async function seedConfigValues(seeds, table, entity, registry, db, ciphe
47
47
  // user-cascade matches the user's actual tenantId, not the SYSTEM
48
48
  // sentinel — a SYSTEM-rooted user row would be unreachable.
49
49
  if (scope === "user" && (!seed.tenantId || !seed.userId)) {
50
- throw new Error(`seedConfigValues: user-scope seed "${seed.key}" requires both tenantId and userId — use createUserSeed({value}, {tenantId, userId}).`);
50
+ throw new Error(`seedConfigValues: user-scope seed "${seed.key}" requires both tenantId and userId — set { value, scope: "user", tenantId, userId }.`);
51
51
  }
52
52
  const tenantId = seed.tenantId ?? SYSTEM_TENANT_ID;
53
53
  const userId = scope === "user" ? (seed.userId ?? null) : null;
@@ -33,7 +33,7 @@ function relatedDefaultCurrency(spec, input) {
33
33
  : undefined;
34
34
  return related?.defaultCurrency ?? FRAMEWORK_DEFAULT_CURRENCY;
35
35
  }
36
- function buildExpression(spec, input, currency = false) {
36
+ function buildExpression(spec, input, moneyPair = false) {
37
37
  if (spec.kind === "coalesce")
38
38
  return buildCoalesceExpression(spec.fields, input);
39
39
  const runtime = input.runtime?.derivedSql;
@@ -52,9 +52,13 @@ function buildExpression(spec, input, currency = false) {
52
52
  db: input.db,
53
53
  runtime,
54
54
  parentVisibility: input.runtime?.parentVisibility,
55
- currency,
55
+ moneyPair,
56
56
  });
57
57
  }
58
+ // The driver hands jsonb back parsed; NULL (hidden or unreadable related field) has no pair.
59
+ function moneyPairOf(raw) {
60
+ return Array.isArray(raw) ? [raw[0], raw[1]] : [null, null];
61
+ }
58
62
  export function buildDerivedSelect(input) {
59
63
  if (input.runtime?.derivedSql === undefined)
60
64
  return undefined;
@@ -69,10 +73,9 @@ export function buildDerivedSelect(input) {
69
73
  valueType: def.valueType,
70
74
  sortable: def.sortable === true,
71
75
  expression: buildExpression(def.sql, input),
72
- currency: def.valueType === "money"
76
+ money: def.valueType === "money"
73
77
  ? {
74
- alias: `${alias}_currency`,
75
- expression: buildExpression(def.sql, input, true),
78
+ pairExpression: buildExpression(def.sql, input, true),
76
79
  fallback: relatedDefaultCurrency(def.sql, input),
77
80
  }
78
81
  : undefined,
@@ -82,10 +85,10 @@ export function buildDerivedSelect(input) {
82
85
  return undefined;
83
86
  return {
84
87
  projections: (params) => plans
85
- .flatMap((plan) => [
86
- { alias: plan.alias, expression: plan.expression },
87
- ...(plan.currency === undefined ? [] : [plan.currency]),
88
- ])
88
+ .map((plan) => ({
89
+ alias: plan.alias,
90
+ expression: plan.money === undefined ? plan.expression : plan.money.pairExpression,
91
+ }))
89
92
  .map(({ alias, expression }) => `, ${expression?.(params) ?? "NULL"} AS "${alias}"`)
90
93
  .join(""),
91
94
  sortExpr: (name) => {
@@ -96,14 +99,13 @@ export function buildDerivedSelect(input) {
96
99
  takeValues: (rawRows) => rawRows.map((raw) => {
97
100
  const values = {};
98
101
  for (const plan of plans) {
99
- if (plan.currency !== undefined) {
100
- const amount = raw[plan.alias];
102
+ if (plan.money !== undefined) {
103
+ const [amount, currency] = moneyPairOf(raw[plan.alias]);
101
104
  // A stored money field without an amount has no key on the row; match that.
102
105
  if (amount !== null && amount !== undefined) {
103
- values[plan.name] = readMoney(plan.name, amount, raw[plan.currency.alias], plan.currency.fallback);
106
+ values[plan.name] = readMoney(plan.name, amount, currency, plan.money.fallback);
104
107
  }
105
108
  delete raw[plan.alias];
106
- delete raw[plan.currency.alias];
107
109
  continue;
108
110
  }
109
111
  values[plan.name] = coerceDriverValueOfPgType(raw[plan.alias], PG_TYPE_OF_VALUE_TYPE[plan.valueType], plan.alias);
@@ -26,6 +26,6 @@ export declare function buildRelatedSubquery(input: {
26
26
  readonly db: TenantDb;
27
27
  readonly runtime: DerivedSqlRuntime;
28
28
  readonly parentVisibility: ParentVisibilityOption | undefined;
29
- /** Select the measured money field's currency column instead of its amount. */
30
- readonly currency?: boolean;
29
+ /** Select the measured money field as [amount, currency] in one subquery. */
30
+ readonly moneyPair?: boolean;
31
31
  }): ((params: unknown[]) => string) | undefined;
@@ -124,8 +124,10 @@ function relatedSelect(measure, column, related, input) {
124
124
  if (measure.kind === "countDistinct")
125
125
  return () => `COUNT(DISTINCT ${column(measure.field)})::int`;
126
126
  if (measure.label !== true) {
127
- const selected = input.currency === true ? `${measure.field}Currency` : measure.field;
128
- return () => column(selected);
127
+ if (input.moneyPair === true) {
128
+ return () => `jsonb_build_array(${column(measure.field)}, ${column(`${measure.field}Currency`)})`;
129
+ }
130
+ return () => column(measure.field);
129
131
  }
130
132
  const def = related.fields[measure.field];
131
133
  if (def?.type !== "reference" || def.labelField === undefined)
@@ -88,6 +88,9 @@ export declare namespace sql {
88
88
  }
89
89
  export type ColumnMap = Record<string, ColumnBuilder<unknown>>;
90
90
  type IndexOrPk = IndexBuilderWithCols | PrimaryKeyDescriptor;
91
+ export declare function table<TCols extends ColumnMap>(tableName: `read_${string}`, cols: TCols, optsFn?: (t: {
92
+ [K in keyof TCols]: ColumnHandle;
93
+ }) => Record<string, IndexOrPk> | ReadonlyArray<IndexOrPk>): SchemaTable;
91
94
  export declare function table<TCols extends ColumnMap>(tableName: string, cols: TCols, optsFn?: (t: {
92
95
  [K in keyof TCols]: ColumnHandle;
93
96
  }) => Record<string, IndexOrPk> | ReadonlyArray<IndexOrPk>): WritableSchemaTable;
@@ -224,11 +224,9 @@ function makeIndex(name, unique) {
224
224
  },
225
225
  };
226
226
  }
227
- // @wrapper-known semantic-alias
228
227
  export function index(name) {
229
228
  return makeIndex(name, false);
230
229
  }
231
- // @wrapper-known semantic-alias
232
230
  export function uniqueIndex(name) {
233
231
  return makeIndex(name, true);
234
232
  }
@@ -304,7 +302,7 @@ export function table(tableName, cols, optsFn) {
304
302
  const handle = {
305
303
  name: final.sqlName,
306
304
  pgType: final.pgType,
307
- getSQLType: () => pgTypeToSqlType(final.pgType), // @wrapper-known semantic-alias
305
+ getSQLType: () => pgTypeToSqlType(final.pgType),
308
306
  };
309
307
  handles[field] = handle;
310
308
  const meta = {
@@ -43,7 +43,7 @@ function instantFromDriver(value) {
43
43
  if (isTemporalInstant(value))
44
44
  return value;
45
45
  // Number coercion via +date — equivalent to .getTime() without a Date-API
46
- // method (guard-no-date-api). Date → epoch milliseconds, then to Temporal.Instant.
46
+ // method (no-date-api plugin). Date → epoch milliseconds, then to Temporal.Instant.
47
47
  if (value instanceof Date)
48
48
  return Temporal.Instant.fromEpochMilliseconds(+value);
49
49
  if (typeof value === "string") {
@@ -65,7 +65,7 @@ function instantFromDriver(value) {
65
65
  // (e.g. America/Los_Angeles reads back the 14th for a stored 15th). Routing
66
66
  // through Instant→ZonedDateTimeISO("UTC")→PlainDate reads the calendar day
67
67
  // back deterministically without ever touching a local Date getter — the
68
- // same +value idiom instantFromDriver uses (guard-no-date-api: no
68
+ // same +value idiom instantFromDriver uses (no-date-api plugin: no
69
69
  // `.getTime()`), just anchored to a fixed zone instead of process-local.
70
70
  // A real `date` column always arrives as a UTC-midnight Date. Anything else means the column is
71
71
  // still timestamptz (declared `date` before its ALTER ran); the UTC anchor then silently shifts
@@ -11,7 +11,7 @@ export function isSqlExpression(v) {
11
11
  // A `date` column takes a plain "yyyy-mm-dd" string (or PlainDate.toString())
12
12
  // as-is — no Instant detour. Postgres parses a DATE literal without ever
13
13
  // consulting the session timezone, so this is TZ-independent by construction
14
- // (verified empirically — see plainDateFromDriver above for the read side).
14
+ // (verified empirically — see plainDateFromDriver in driver-row-coercion.ts for the read side).
15
15
  // Compat cushion: code (this field used to be an Instant) may still
16
16
  // hand a Temporal.Instant into a where-filter or write on a `date` column —
17
17
  // same UTC anchor as plainDateFromDriver's read side, so a filter built with
@@ -19,7 +19,7 @@
19
19
  // never skipped silently.
20
20
  import { requestContext } from "../api/request-context.js";
21
21
  import { collectPiiSubjectFields, configuredPiiSubjectKms, decryptPiiFieldValues, } from "../crypto/index.js";
22
- import { selectMany } from "../db/query.js";
22
+ import { coerceRow, selectMany } from "../db/query.js";
23
23
  import { filterReadFields } from "../engine/field-access.js";
24
24
  import { shiftParams, tableNameOf } from "../engine/ownership.js";
25
25
  import { parseRefTargetEntityName } from "../engine/parse-ref-target.js";
@@ -31,7 +31,8 @@ import { toPostgresArrayLiteral } from "./queries/postgres-array-literal.js";
31
31
  import { executeRawQueryRead } from "./queries/raw-sql.js";
32
32
  import { resolveReadOwnership } from "./read-ownership.js";
33
33
  import { buildEntityTable, physicalColumnName } from "./table-builder.js";
34
- import { tenantDbRunner } from "./tenant-db-runner.js";
34
+ import { extractTableInfo } from "./table-info.js";
35
+ import { tenantDbRunnerForTable } from "./tenant-db-runner.js";
35
36
  const log = createFallbackLogger("eagerload");
36
37
  function isReferenceField(field) {
37
38
  return field.type === "reference";
@@ -67,9 +68,11 @@ async function decryptReferencedRow(row, piiFields, encryptedFields, kms) {
67
68
  }
68
69
  return out;
69
70
  }
70
- // One probe query per ref field: the ids the viewer may read on the target
71
- // entity. Raw SQL because ownership/parentRef clauses are SQL fragments; the
72
- // table is unaliased since where-rules qualify columns with the table name.
71
+ // One lookup per ref field. Unrestricted targets load rows by id later; for
72
+ // restricted ones the access clause is part of this same SELECT so unreadable
73
+ // rows are never loaded. Raw SQL because ownership/parentRef clauses are SQL
74
+ // fragments; the table is unaliased since where-rules qualify columns with the
75
+ // table name.
73
76
  async function resolveRefAccessScope(refEntity, refTable, refTableName, ids, db, viewer) {
74
77
  const access = resolveReadOwnership({ entity: refEntity, table: refTable }, refTableName, viewer.user, db, viewer.parentVisibility, { includeDeleted: false, narrowTypes: undefined });
75
78
  if (access.kind === "empty")
@@ -87,8 +90,11 @@ async function resolveRefAccessScope(refEntity, refTable, refTableName, ids, db,
87
90
  }
88
91
  const shifted = shiftParams({ sqlText: access.sqlText, params: access.params }, params.length);
89
92
  params.push(...shifted.params);
90
- const rows = await executeRawQueryRead(tenantDbRunner(db), `SELECT "id" FROM "${refTableName}" WHERE "id" = ANY($1::uuid[])${tenantClause} AND ${shifted.sqlText}`, params);
91
- return { kind: "restricted", readableIds: new Set(rows.map((r) => r.id)) };
93
+ const rows = await executeRawQueryRead(tenantDbRunnerForTable(db, refTable), `SELECT * FROM "${refTableName}" WHERE "id" = ANY($1::uuid[])${tenantClause} AND ${shifted.sqlText}`, params);
94
+ // The raw SELECT * rows carry driver column names; coerce like selectMany so field-level
95
+ // read rules and PII decryption see the camelCase entity row.
96
+ const info = extractTableInfo(refTable);
97
+ return { kind: "restricted", readableRows: rows.map((row) => coerceRow(row, info)) };
92
98
  }
93
99
  // Per-row, not Promise.all: a single legacy/backfilled row without a valid
94
100
  // envelope (decryptEntityFieldValues throws hard on malformed ciphertext)
@@ -164,12 +170,9 @@ export async function enrichWithReferences(rows, entity, resolveEntity, db, view
164
170
  const scope = await resolveRefAccessScope(refEntity, refTable, refTableName, idArray, db, viewer);
165
171
  if (scope.kind === "none")
166
172
  return emptyLookup;
167
- const lookedUpRows = await selectMany(db, refTable, {
168
- id: idArray,
169
- });
170
173
  const rawRefRows = scope.kind === "restricted"
171
- ? lookedUpRows.filter((r) => scope.readableIds.has(String(r["id"])))
172
- : lookedUpRows;
174
+ ? scope.readableRows
175
+ : await selectMany(db, refTable, { id: idArray });
173
176
  const piiFields = collectPiiSubjectFields(refEntity);
174
177
  const encryptedFields = collectEncryptedFieldNames(refEntity);
175
178
  const kms = configuredPiiSubjectKms();
@@ -1,6 +1,7 @@
1
1
  import type { Writable } from "@cosmicdrift/kumiko-types/executor-brand";
2
2
  import type { EntityDefinition } from "@cosmicdrift/kumiko-types/fields";
3
3
  import type { EntityTenancy, TenancyBrand } from "@cosmicdrift/kumiko-types/tenancy-brand";
4
+ import type { FeatureDefinition } from "../engine/types/index.ts";
4
5
  import type { BuildEntityTableMetaOptions, EntityTableMeta, UnmanagedTableInput } from "./entity-table-meta-types.ts";
5
6
  export type { BuildEntityTableMetaOptions, ColumnMeta, CompositePrimaryKeyMeta, EntityTableMeta, IndexMeta, PgType, UnmanagedTableInput, } from "./entity-table-meta-types.ts";
6
7
  export declare function resolveTableName(entityName: string, entity: EntityDefinition, featureName: string | undefined): string;
@@ -30,3 +31,4 @@ export declare function assertBackingTableSuperset(entityName: string, fieldMeta
30
31
  export declare function defineUnmanagedTable<const T extends EntityTenancy = "tenant">(input: UnmanagedTableInput & {
31
32
  readonly tenancy?: T;
32
33
  }): EntityTableMeta & TenancyBrand<T> & Writable;
34
+ export declare function entityReadsSystemRows(feature: Pick<FeatureDefinition, "referenceData">, entityName: string, entity: EntityDefinition): boolean;
@@ -76,6 +76,7 @@ export function deriveEntityTableMeta(entityName, entity, options) {
76
76
  source,
77
77
  ...(piiSubjectFields.length > 0 && { piiSubjectFields }),
78
78
  ...(entity.tenancy === "global" && { tenancy: "global" }),
79
+ ...(entity.systemRowsReadable === true && { systemRowsReadable: true }),
79
80
  };
80
81
  return source === "unmanaged" ? brandWritable(meta) : meta;
81
82
  }
@@ -248,6 +249,7 @@ export function defineUnmanagedTable(input) {
248
249
  }),
249
250
  source: "unmanaged",
250
251
  ...(input.tenancy === "global" && { tenancy: "global" }),
252
+ ...(input.systemRowsReadable === true && { systemRowsReadable: true }),
251
253
  // @cast-boundary phantom-brand — TenancyBrand<T> is a phantom marker with no runtime representation.
252
254
  });
253
255
  }
@@ -259,3 +261,8 @@ function assertUnmanagedTableName(tableName, via) {
259
261
  `See #1208/#1220.`);
260
262
  }
261
263
  }
264
+ // Reference data rows live on the system tenant by definition, so tenant reads need them.
265
+ export function entityReadsSystemRows(feature, entityName, entity) {
266
+ return (entity.systemRowsReadable === true ||
267
+ (feature.referenceData ?? []).some((def) => def.entityName === entityName));
268
+ }
@@ -10,11 +10,12 @@ import { isStreamArchived } from "../event-store/index.js";
10
10
  import { assertUnreachable } from "../utils/index.js";
11
11
  import { rehydrateCompoundTypes } from "./compound-types.js";
12
12
  import { collectEncryptedFieldNames, decryptEntityFieldValues, encryptEntityFieldValues, logUndecryptableField, resolveEntityFieldEncryption, } from "./entity-field-encryption.js";
13
+ import { withGlobalParentHosts } from "./parent-ref-global-hosts.js";
13
14
  import { constraintOf, isUniqueViolation } from "./pg-error.js";
14
15
  import { resolveReadOwnership } from "./read-ownership.js";
15
16
  import { toSnakeCase } from "./table-builder.js";
16
17
  import { columnHandleName, schemaTableName } from "./table-introspection.js";
17
- import { tenantDbRunner } from "./tenant-db-runner.js";
18
+ import { tenantDbRunnerForTable } from "./tenant-db-runner.js";
18
19
  // Screen filter: maps an operator to a WhereObject condition.
19
20
  // The boot validator checks field existence, filterability, and operator/type compatibility.
20
21
  // `op` is normalized to {eq,ne,lt,gt,lte,gte,in}; "in" with an
@@ -305,7 +306,7 @@ export function buildExecutorContext(table, entity, options) {
305
306
  // re-create onto an archived stream collides on the unique index →
306
307
  // version_conflict, which already blocks the write.
307
308
  async function assertStreamWritable(db, id, tenantId) {
308
- if (await isStreamArchived(tenantDbRunner(db), tenantId, String(id))) {
309
+ if (await isStreamArchived(tenantDbRunnerForTable(db, table), tenantId, String(id))) {
309
310
  throw new ArchivedStreamError(tenantId, String(id));
310
311
  }
311
312
  }
@@ -349,7 +350,7 @@ export function buildExecutorContext(table, entity, options) {
349
350
  params.push(aggregateId, streamTenantId);
350
351
  const sqlText = `SELECT 1 AS "__owned", ${streamVersionSubquerySql(params.length - 1, params.length)} ` +
351
352
  `FROM "${tableName}" WHERE ${whereParts.join(" AND ")} LIMIT 1`;
352
- const rows = await executeRawQueryRead(tenantDbRunner(db), sqlText, params);
353
+ const rows = await executeRawQueryRead(tenantDbRunnerForTable(db, table), sqlText, params);
353
354
  const first = rows[0];
354
355
  if (!first)
355
356
  return { owned: false, streamVersion: 0 };
@@ -361,14 +362,18 @@ export function buildExecutorContext(table, entity, options) {
361
362
  // soft-deleted row; includeDeleted below only concerns the parent host. Writers use it
362
363
  // to treat an unreadable row as nonexistent.
363
364
  async function isRowReadable(id, user, db, parentVisibility) {
364
- const ownership = resolveReadOwnership({ entity, table }, String(schemaTableName(table)), user, db, parentVisibility, { includeDeleted: false, narrowTypes: undefined });
365
+ const gate = { includeDeleted: false, narrowTypes: undefined };
366
+ const tableName = String(schemaTableName(table));
367
+ const ownership = resolveReadOwnership({ entity, table }, tableName, user, db, await withGlobalParentHosts({ entity, table }, user, db, parentVisibility, gate, {
368
+ kind: "row",
369
+ rowId: id,
370
+ }), gate);
365
371
  if (ownership.kind === "pass")
366
372
  return true;
367
373
  if (ownership.kind === "empty")
368
374
  return false;
369
- const tableName = String(schemaTableName(table));
370
375
  const { whereParts, params } = buildRawIdWhere(db, { id }, ownership);
371
- const rows = await executeRawQueryRead(tenantDbRunner(db), `SELECT 1 AS "__readable" FROM "${tableName}" WHERE ${whereParts.join(" AND ")} LIMIT 1`, params);
376
+ const rows = await executeRawQueryRead(tenantDbRunnerForTable(db, table), `SELECT 1 AS "__readable" FROM "${tableName}" WHERE ${whereParts.join(" AND ")} LIMIT 1`, params);
372
377
  return rows.length > 0;
373
378
  }
374
379
  // Row and MAX(version) in ONE statement: two reads can pair a post-write
@@ -382,7 +387,7 @@ export function buildExecutorContext(table, entity, options) {
382
387
  params.push(aggregateId, streamTenantId);
383
388
  const sqlText = `SELECT *, ${streamVersionSubquerySql(params.length - 1, params.length)} ` +
384
389
  `FROM "${tableName}" WHERE ${whereParts.join(" AND ")} LIMIT 1`;
385
- const rows = await executeRawQueryRead(tenantDbRunner(db), sqlText, params);
390
+ const rows = await executeRawQueryRead(tenantDbRunnerForTable(db, table), sqlText, params);
386
391
  const first = rows[0];
387
392
  if (!first)
388
393
  return { row: null, streamVersion: 0 };
@@ -428,7 +433,7 @@ export function buildExecutorContext(table, entity, options) {
428
433
  const sqlText = `SELECT ${selectCols.join(", ")}, ` +
429
434
  `${streamVersionSubquerySql(streamAggregateIdx, streamTenantIdx)} ` +
430
435
  `FROM "${tableName}" WHERE ${whereParts.join(" AND ")} LIMIT 1`;
431
- const rows = await executeRawQueryRead(tenantDbRunner(db), sqlText, params);
436
+ const rows = await executeRawQueryRead(tenantDbRunnerForTable(db, table), sqlText, params);
432
437
  const row = rows[0];
433
438
  if (!row)
434
439
  return { row: null, streamVersion: 0 };
@@ -2,7 +2,7 @@ import { isPerCurrencyMeasure } from "./aggregate-sql.js";
2
2
  import { bindShiftedClause } from "./event-store-executor-read-filter.js";
3
3
  import { executeRawQueryRead } from "./queries/raw-sql.js";
4
4
  import { schemaTableName } from "./table-introspection.js";
5
- import { tenantDbRunner } from "./tenant-db-runner.js";
5
+ import { tenantDbRunnerForTable } from "./tenant-db-runner.js";
6
6
  // Above the ~180 ISO 4217 codes, so the cap only bounds malformed data.
7
7
  const MAX_AGGREGATE_CURRENCIES = 200;
8
8
  export function currencyColumnOf(field) {
@@ -24,7 +24,7 @@ export async function loadMeasureCurrencies(ctx, measures, where, db) {
24
24
  if (m.clause.kind === "sql")
25
25
  conditions.push(`(${bindShiftedClause(params, m.clause)})`);
26
26
  const currencySql = where.colSql(currencyColumnOf(m.field));
27
- const rows = await executeRawQueryRead(tenantDbRunner(db), `SELECT DISTINCT ${currencySql} AS cur FROM "${tableName}" WHERE ${conditions.join(" AND ")} AND ${currencySql} IS NOT NULL ORDER BY 1 LIMIT ${MAX_AGGREGATE_CURRENCIES}`, params);
27
+ const rows = await executeRawQueryRead(tenantDbRunnerForTable(db, ctx.table), `SELECT DISTINCT ${currencySql} AS cur FROM "${tableName}" WHERE ${conditions.join(" AND ")} AND ${currencySql} IS NOT NULL ORDER BY 1 LIMIT ${MAX_AGGREGATE_CURRENCIES}`, params);
28
28
  byField.set(m.field, rows.map((row) => String(row.cur)));
29
29
  }
30
30
  return byField;
@@ -6,7 +6,7 @@ import { appendShiftedClause, bindShiftedClause, } from "./event-store-executor-
6
6
  import { buildListWhere, createFieldReadClause, } from "./event-store-executor-read-where.js";
7
7
  import { executeRawQueryRead } from "./queries/raw-sql.js";
8
8
  import { schemaTableName } from "./table-introspection.js";
9
- import { tenantDbRunner } from "./tenant-db-runner.js";
9
+ import { tenantDbRunnerForTable } from "./tenant-db-runner.js";
10
10
  // One group more than the cap is fetched to tell "exactly 200" from "more".
11
11
  const MAX_AGGREGATE_GROUPS = 200;
12
12
  function rejectAggregate(path, field, hint) {
@@ -121,7 +121,7 @@ export async function aggregateList(ctx, payload, user, db, runtimeOptions) {
121
121
  const whereText = where.whereSql.length > 0 ? ` WHERE ${where.whereSql.join(" AND ")}` : "";
122
122
  const groupText = grouped ? groupedKeyOrderLimitSql(MAX_AGGREGATE_GROUPS + 1) : "";
123
123
  const tableName = String(schemaTableName(ctx.table));
124
- const rows = await executeRawQueryRead(tenantDbRunner(db), `SELECT ${selectList} FROM "${tableName}"${whereText}${groupText}`, where.params);
124
+ const rows = await executeRawQueryRead(tenantDbRunnerForTable(db, ctx.table), `SELECT ${selectList} FROM "${tableName}"${whereText}${groupText}`, where.params);
125
125
  const truncated = rows.length > MAX_AGGREGATE_GROUPS;
126
126
  const groups = rows.slice(0, MAX_AGGREGATE_GROUPS).map((row) => ({
127
127
  key: grouped ? aggregateKeyOf(row["k0"]) : null,