cvx-kit 0.2.0 → 2.0.0-beta.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 (372) hide show
  1. package/README.md +556 -99
  2. package/dist/agent-tools.d.mts +39 -26
  3. package/dist/agent-tools.mjs +1 -1
  4. package/dist/agent-tools.mjs.map +1 -1
  5. package/dist/auth.d.mts +120 -308
  6. package/dist/auth.mjs +1 -1
  7. package/dist/auth.mjs.map +1 -1
  8. package/dist/components/approvals/_generated/api.d.mts +7 -9
  9. package/dist/components/approvals/_generated/api.mjs.map +1 -1
  10. package/dist/components/approvals/_generated/component.d.mts +1 -4
  11. package/dist/components/approvals/_generated/dataModel.d.mts +5 -8
  12. package/dist/components/approvals/_generated/server.d.mts +12 -15
  13. package/dist/components/approvals/_generated/server.mjs.map +1 -1
  14. package/dist/components/approvals/audit.d.mts +8 -9
  15. package/dist/components/approvals/audit.mjs +1 -1
  16. package/dist/components/approvals/audit.mjs.map +1 -1
  17. package/dist/components/approvals/client.d.mts +11 -12
  18. package/dist/components/approvals/client.mjs +1 -1
  19. package/dist/components/approvals/client.mjs.map +1 -1
  20. package/dist/components/approvals/constants.d.mts +30 -31
  21. package/dist/components/approvals/constants.mjs.map +1 -1
  22. package/dist/components/approvals/convex.config.d.mts +0 -2
  23. package/dist/components/approvals/convex.config.mjs.map +1 -1
  24. package/dist/components/approvals/decisions.d.mts +13 -17
  25. package/dist/components/approvals/decisions.mjs +1 -1
  26. package/dist/components/approvals/decisions.mjs.map +1 -1
  27. package/dist/components/approvals/functions.d.mts +3 -4
  28. package/dist/components/approvals/functions.mjs +1 -1
  29. package/dist/components/approvals/functions.mjs.map +1 -1
  30. package/dist/components/approvals/health.d.mts +2 -3
  31. package/dist/components/approvals/health.mjs.map +1 -1
  32. package/dist/components/approvals/requests.d.mts +114 -131
  33. package/dist/components/approvals/requests.mjs +1 -1
  34. package/dist/components/approvals/requests.mjs.map +1 -1
  35. package/dist/components/approvals/schema.d.ts +106 -315
  36. package/dist/components/approvals/schema.js +1 -1
  37. package/dist/components/approvals/validators.d.mts +323 -395
  38. package/dist/components/approvals/validators.mjs +1 -1
  39. package/dist/components/approvals/validators.mjs.map +1 -1
  40. package/dist/components/approvals/workflow.d.mts +4 -5
  41. package/dist/components/approvals/workflow.mjs +1 -1
  42. package/dist/components/approvals/workflow.mjs.map +1 -1
  43. package/dist/components/approvals/workflow_steps.d.mts +16 -17
  44. package/dist/components/approvals/workflow_steps.mjs +1 -1
  45. package/dist/components/approvals/workflow_steps.mjs.map +1 -1
  46. package/dist/components/foundation/_generated/api.d.mts +6 -8
  47. package/dist/components/foundation/_generated/api.mjs.map +1 -1
  48. package/dist/components/foundation/_generated/component.d.mts +1 -4
  49. package/dist/components/foundation/_generated/dataModel.d.mts +5 -8
  50. package/dist/components/foundation/_generated/server.d.mts +12 -15
  51. package/dist/components/foundation/_generated/server.mjs.map +1 -1
  52. package/dist/components/foundation/client.d.mts +45 -38
  53. package/dist/components/foundation/client.mjs +1 -1
  54. package/dist/components/foundation/client.mjs.map +1 -1
  55. package/dist/components/foundation/convex.config.d.mts +0 -2
  56. package/dist/components/foundation/convex.config.mjs.map +1 -1
  57. package/dist/components/foundation/functions.d.mts +2 -3
  58. package/dist/components/foundation/functions.mjs.map +1 -1
  59. package/dist/components/foundation/modules/command/command.d.mts +65 -17
  60. package/dist/components/foundation/modules/command/command.mjs +1 -1
  61. package/dist/components/foundation/modules/command/command.mjs.map +1 -1
  62. package/dist/components/foundation/modules/command/lifecycle.d.mts +78 -0
  63. package/dist/components/foundation/modules/command/lifecycle.mjs +2 -0
  64. package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -0
  65. package/dist/components/foundation/modules/observability/observability.d.mts +13 -6
  66. package/dist/components/foundation/modules/observability/observability.mjs +1 -1
  67. package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
  68. package/dist/components/foundation/modules/query/query.d.mts +11 -12
  69. package/dist/components/foundation/modules/query/query.mjs +1 -1
  70. package/dist/components/foundation/modules/query/query.mjs.map +1 -1
  71. package/dist/components/foundation/operation.d.mts +72 -0
  72. package/dist/components/foundation/operation.mjs +2 -0
  73. package/dist/components/foundation/operation.mjs.map +1 -0
  74. package/dist/components/foundation/result.d.mts +7 -8
  75. package/dist/components/foundation/result.mjs.map +1 -1
  76. package/dist/components/foundation/schema.d.ts +0 -2
  77. package/dist/components/foundation/telemetry.d.mts +2 -3
  78. package/dist/components/foundation/telemetry.mjs +1 -1
  79. package/dist/components/foundation/telemetry.mjs.map +1 -1
  80. package/dist/contracts.d.mts +5 -0
  81. package/dist/contracts.mjs +1 -0
  82. package/dist/crud.d.mts +185 -27
  83. package/dist/crud.mjs +1 -1
  84. package/dist/crud.mjs.map +1 -1
  85. package/dist/effect.d.mts +16 -0
  86. package/dist/effect.mjs +1 -0
  87. package/dist/errors.d.mts +6 -6
  88. package/dist/errors.mjs +1 -1
  89. package/dist/errors.mjs.map +1 -1
  90. package/dist/filters.d.mts +4 -0
  91. package/dist/filters.mjs +1 -0
  92. package/dist/idempotency.d.mts +2 -0
  93. package/dist/idempotency.mjs +1 -0
  94. package/dist/index.d.mts +14 -7
  95. package/dist/index.mjs +1 -1
  96. package/dist/json-schema.d.mts +40 -0
  97. package/dist/json-schema.mjs +2 -0
  98. package/dist/json-schema.mjs.map +1 -0
  99. package/dist/k/compile.d.mts +17 -0
  100. package/dist/k/compile.mjs +2 -0
  101. package/dist/k/compile.mjs.map +1 -0
  102. package/dist/k/dates.d.mts +23 -0
  103. package/dist/k/dates.mjs +2 -0
  104. package/dist/k/dates.mjs.map +1 -0
  105. package/dist/k/formats.d.mts +24 -0
  106. package/dist/k/formats.mjs +2 -0
  107. package/dist/k/formats.mjs.map +1 -0
  108. package/dist/k/index.d.mts +32 -0
  109. package/dist/k/index.mjs +2 -0
  110. package/dist/k/index.mjs.map +1 -0
  111. package/dist/k/issues.d.mts +31 -0
  112. package/dist/k/issues.mjs +2 -0
  113. package/dist/k/issues.mjs.map +1 -0
  114. package/dist/k/kinds.d.mts +81 -0
  115. package/dist/k/kinds.mjs +2 -0
  116. package/dist/k/kinds.mjs.map +1 -0
  117. package/dist/k/object.d.mts +43 -0
  118. package/dist/k/object.mjs +2 -0
  119. package/dist/k/object.mjs.map +1 -0
  120. package/dist/k/parse.d.mts +29 -0
  121. package/dist/k/parse.mjs +2 -0
  122. package/dist/k/parse.mjs.map +1 -0
  123. package/dist/k/schema.d.mts +100 -0
  124. package/dist/k/schema.mjs +2 -0
  125. package/dist/k/schema.mjs.map +1 -0
  126. package/dist/k/standard.d.mts +8 -0
  127. package/dist/k/standard.mjs +2 -0
  128. package/dist/k/standard.mjs.map +1 -0
  129. package/dist/k/types.d.mts +64 -0
  130. package/dist/k/types.mjs +1 -0
  131. package/dist/k.d.mts +8 -0
  132. package/dist/k.mjs +1 -0
  133. package/dist/middleware.d.mts +8 -11
  134. package/dist/middleware.mjs +1 -1
  135. package/dist/middleware.mjs.map +1 -1
  136. package/dist/modules/contracts/binding.d.mts +23 -0
  137. package/dist/modules/contracts/binding.mjs +2 -0
  138. package/dist/modules/contracts/binding.mjs.map +1 -0
  139. package/dist/modules/contracts/contract.d.mts +67 -0
  140. package/dist/modules/contracts/contract.mjs +2 -0
  141. package/dist/modules/contracts/contract.mjs.map +1 -0
  142. package/dist/modules/contracts/convex.d.mts +18 -0
  143. package/dist/modules/contracts/convex.mjs +2 -0
  144. package/dist/modules/contracts/convex.mjs.map +1 -0
  145. package/dist/modules/contracts/domain.d.mts +62 -0
  146. package/dist/modules/contracts/domain.mjs +2 -0
  147. package/dist/modules/contracts/domain.mjs.map +1 -0
  148. package/dist/modules/contracts/errors.d.mts +737 -0
  149. package/dist/modules/contracts/errors.mjs +2 -0
  150. package/dist/modules/contracts/errors.mjs.map +1 -0
  151. package/dist/modules/contracts/exposure.d.mts +103 -0
  152. package/dist/modules/contracts/exposure.mjs +2 -0
  153. package/dist/modules/contracts/exposure.mjs.map +1 -0
  154. package/dist/modules/contracts/idempotency.d.mts +85 -0
  155. package/dist/modules/contracts/idempotency.mjs +2 -0
  156. package/dist/modules/contracts/idempotency.mjs.map +1 -0
  157. package/dist/modules/contracts/lazy.d.mts +6 -0
  158. package/dist/modules/contracts/lazy.mjs +2 -0
  159. package/dist/modules/contracts/lazy.mjs.map +1 -0
  160. package/dist/modules/contracts/standard.d.mts +17 -0
  161. package/dist/modules/contracts/standard.mjs +2 -0
  162. package/dist/modules/contracts/standard.mjs.map +1 -0
  163. package/dist/modules/contracts/workflow.d.mts +165 -0
  164. package/dist/modules/contracts/workflow.mjs +2 -0
  165. package/dist/modules/contracts/workflow.mjs.map +1 -0
  166. package/dist/modules/effect/action.d.mts +63 -0
  167. package/dist/modules/effect/action.mjs +2 -0
  168. package/dist/modules/effect/action.mjs.map +1 -0
  169. package/dist/modules/effect/agent-tools.d.mts +2 -0
  170. package/dist/modules/effect/agent-tools.mjs +1 -0
  171. package/dist/modules/effect/api-runtime.d.mts +36 -0
  172. package/dist/modules/effect/api-runtime.mjs +2 -0
  173. package/dist/modules/effect/api-runtime.mjs.map +1 -0
  174. package/dist/modules/effect/api.d.mts +46 -0
  175. package/dist/modules/effect/api.mjs +2 -0
  176. package/dist/modules/effect/api.mjs.map +1 -0
  177. package/dist/modules/effect/auth.d.mts +46 -0
  178. package/dist/modules/effect/auth.mjs +2 -0
  179. package/dist/modules/effect/auth.mjs.map +1 -0
  180. package/dist/modules/effect/client.d.mts +15 -0
  181. package/dist/modules/effect/client.mjs +1 -0
  182. package/dist/modules/effect/command.d.mts +108 -0
  183. package/dist/modules/effect/command.mjs +2 -0
  184. package/dist/modules/effect/command.mjs.map +1 -0
  185. package/dist/modules/effect/crud.d.mts +885 -0
  186. package/dist/modules/effect/crud.mjs +2 -0
  187. package/dist/modules/effect/crud.mjs.map +1 -0
  188. package/dist/modules/effect/domain.d.mts +82 -0
  189. package/dist/modules/effect/domain.mjs +2 -0
  190. package/dist/modules/effect/domain.mjs.map +1 -0
  191. package/dist/modules/effect/errors.d.mts +13 -0
  192. package/dist/modules/effect/errors.mjs +2 -0
  193. package/dist/modules/effect/errors.mjs.map +1 -0
  194. package/dist/modules/effect/failure-audit.d.mts +48 -0
  195. package/dist/modules/effect/failure-audit.mjs +2 -0
  196. package/dist/modules/effect/failure-audit.mjs.map +1 -0
  197. package/dist/modules/effect/failures.d.mts +21 -0
  198. package/dist/modules/effect/failures.mjs +2 -0
  199. package/dist/modules/effect/failures.mjs.map +1 -0
  200. package/dist/modules/effect/foundation.d.mts +23 -0
  201. package/dist/modules/effect/foundation.mjs +2 -0
  202. package/dist/modules/effect/foundation.mjs.map +1 -0
  203. package/dist/modules/effect/idempotency.d.mts +29 -0
  204. package/dist/modules/effect/idempotency.mjs +2 -0
  205. package/dist/modules/effect/idempotency.mjs.map +1 -0
  206. package/dist/modules/effect/input.d.mts +10 -0
  207. package/dist/modules/effect/input.mjs +2 -0
  208. package/dist/modules/effect/input.mjs.map +1 -0
  209. package/dist/modules/effect/normalize.d.mts +7 -0
  210. package/dist/modules/effect/normalize.mjs +2 -0
  211. package/dist/modules/effect/normalize.mjs.map +1 -0
  212. package/dist/modules/effect/operation.d.mts +148 -0
  213. package/dist/modules/effect/operation.mjs +2 -0
  214. package/dist/modules/effect/operation.mjs.map +1 -0
  215. package/dist/modules/effect/query.d.mts +90 -0
  216. package/dist/modules/effect/query.mjs +2 -0
  217. package/dist/modules/effect/query.mjs.map +1 -0
  218. package/dist/modules/effect/schema.d.mts +30 -0
  219. package/dist/modules/effect/schema.mjs +2 -0
  220. package/dist/modules/effect/schema.mjs.map +1 -0
  221. package/dist/modules/effect/scope.d.mts +25 -0
  222. package/dist/modules/effect/scope.mjs +2 -0
  223. package/dist/modules/effect/scope.mjs.map +1 -0
  224. package/dist/modules/effect/workflow.d.mts +75 -0
  225. package/dist/modules/effect/workflow.mjs +2 -0
  226. package/dist/modules/effect/workflow.mjs.map +1 -0
  227. package/dist/modules/foundation/foundation.d.mts +108 -0
  228. package/dist/modules/foundation/foundation.mjs +2 -0
  229. package/dist/modules/foundation/foundation.mjs.map +1 -0
  230. package/dist/modules/foundation/operation.d.mts +139 -0
  231. package/dist/modules/foundation/operation.mjs +2 -0
  232. package/dist/modules/foundation/operation.mjs.map +1 -0
  233. package/dist/namespace.d.mts +104 -0
  234. package/dist/namespace.mjs +2 -0
  235. package/dist/namespace.mjs.map +1 -0
  236. package/dist/oxlint/architecture.d.mts +23 -0
  237. package/dist/oxlint/architecture.mjs +2 -0
  238. package/dist/oxlint/architecture.mjs.map +1 -0
  239. package/dist/oxlint/ast.d.mts +51 -0
  240. package/dist/oxlint/ast.mjs +2 -0
  241. package/dist/oxlint/ast.mjs.map +1 -0
  242. package/dist/oxlint/components.d.mts +4 -0
  243. package/dist/oxlint/components.mjs +2 -0
  244. package/dist/oxlint/components.mjs.map +1 -0
  245. package/dist/oxlint/ownership.d.mts +59 -0
  246. package/dist/oxlint/ownership.mjs +2 -0
  247. package/dist/oxlint/ownership.mjs.map +1 -0
  248. package/dist/oxlint/reserved-files.d.mts +4 -0
  249. package/dist/oxlint/reserved-files.mjs +2 -0
  250. package/dist/oxlint/reserved-files.mjs.map +1 -0
  251. package/dist/oxlint.d.mts +9 -0
  252. package/dist/oxlint.mjs +2 -0
  253. package/dist/oxlint.mjs.map +1 -0
  254. package/dist/querying/cursors.d.mts +94 -0
  255. package/dist/querying/cursors.mjs +2 -0
  256. package/dist/querying/cursors.mjs.map +1 -0
  257. package/dist/querying/execution.d.mts +40 -0
  258. package/dist/querying/execution.mjs +2 -0
  259. package/dist/querying/execution.mjs.map +1 -0
  260. package/dist/querying/failures.d.mts +11 -0
  261. package/dist/querying/failures.mjs +2 -0
  262. package/dist/querying/failures.mjs.map +1 -0
  263. package/dist/querying/filter-boundary.d.mts +25 -0
  264. package/dist/querying/filter-boundary.mjs +2 -0
  265. package/dist/querying/filter-boundary.mjs.map +1 -0
  266. package/dist/querying/filters.d.mts +180 -0
  267. package/dist/querying/filters.mjs +2 -0
  268. package/dist/querying/filters.mjs.map +1 -0
  269. package/dist/querying/planner.d.mts +61 -0
  270. package/dist/querying/planner.mjs +2 -0
  271. package/dist/querying/planner.mjs.map +1 -0
  272. package/dist/querying/relationships.d.mts +58 -0
  273. package/dist/querying/relationships.mjs +2 -0
  274. package/dist/querying/relationships.mjs.map +1 -0
  275. package/dist/querying/search.d.mts +69 -0
  276. package/dist/querying/search.mjs +2 -0
  277. package/dist/querying/search.mjs.map +1 -0
  278. package/dist/querying/security.d.mts +123 -0
  279. package/dist/querying/security.mjs +2 -0
  280. package/dist/querying/security.mjs.map +1 -0
  281. package/dist/querying/shared/ast.d.mts +26 -0
  282. package/dist/querying/shared/ast.mjs +2 -0
  283. package/dist/querying/shared/ast.mjs.map +1 -0
  284. package/dist/querying/shared/contract.d.mts +98 -0
  285. package/dist/querying/shared/contract.mjs +2 -0
  286. package/dist/querying/shared/contract.mjs.map +1 -0
  287. package/dist/querying/shared/evaluate.d.mts +5 -0
  288. package/dist/querying/shared/evaluate.mjs +2 -0
  289. package/dist/querying/shared/evaluate.mjs.map +1 -0
  290. package/dist/querying/shared/filters.d.mts +65 -0
  291. package/dist/querying/shared/filters.mjs +2 -0
  292. package/dist/querying/shared/filters.mjs.map +1 -0
  293. package/dist/querying/shared/native-json.d.mts +7 -0
  294. package/dist/querying/shared/native-json.mjs +2 -0
  295. package/dist/querying/shared/native-json.mjs.map +1 -0
  296. package/dist/querying/shared/page.d.mts +20 -0
  297. package/dist/querying/shared/page.mjs +2 -0
  298. package/dist/querying/shared/page.mjs.map +1 -0
  299. package/dist/querying.d.mts +82 -0
  300. package/dist/querying.mjs +2 -0
  301. package/dist/querying.mjs.map +1 -0
  302. package/dist/react/failures.d.mts +24 -0
  303. package/dist/react/failures.mjs +2 -0
  304. package/dist/react/failures.mjs.map +1 -0
  305. package/dist/react/optimistic.d.mts +46 -0
  306. package/dist/react/optimistic.mjs +2 -0
  307. package/dist/react/optimistic.mjs.map +1 -0
  308. package/dist/react/pagination-state.d.mts +39 -0
  309. package/dist/react/pagination-state.mjs +2 -0
  310. package/dist/react/pagination-state.mjs.map +1 -0
  311. package/dist/react/use-command.d.mts +22 -0
  312. package/dist/react/use-command.mjs +2 -0
  313. package/dist/react/use-command.mjs.map +1 -0
  314. package/dist/react/use-paginated-list.d.mts +34 -0
  315. package/dist/react/use-paginated-list.mjs +2 -0
  316. package/dist/react/use-paginated-list.mjs.map +1 -0
  317. package/dist/react.d.mts +6 -0
  318. package/dist/react.mjs +1 -0
  319. package/dist/registration.d.mts +65 -0
  320. package/dist/registration.mjs +2 -0
  321. package/dist/registration.mjs.map +1 -0
  322. package/dist/relations-public.d.mts +2 -0
  323. package/dist/relations-public.mjs +1 -0
  324. package/dist/relations.d.mts +274 -0
  325. package/dist/relations.mjs +2 -0
  326. package/dist/relations.mjs.map +1 -0
  327. package/dist/state-machine.d.mts +1 -4
  328. package/dist/state-machine.mjs.map +1 -1
  329. package/dist/table.d.mts +222 -0
  330. package/dist/table.mjs +2 -0
  331. package/dist/table.mjs.map +1 -0
  332. package/dist/tenancy.d.mts +6 -8
  333. package/dist/tenancy.mjs +1 -1
  334. package/dist/tenancy.mjs.map +1 -1
  335. package/dist/triggers.d.mts +12 -10
  336. package/dist/triggers.mjs +1 -1
  337. package/dist/triggers.mjs.map +1 -1
  338. package/dist/webhooks.d.mts +22 -112
  339. package/dist/webhooks.mjs +1 -1
  340. package/dist/webhooks.mjs.map +1 -1
  341. package/dist/workflow.d.mts +2 -0
  342. package/dist/workflow.mjs +1 -0
  343. package/dist/zod.d.mts +30 -0
  344. package/dist/zod.mjs +2 -0
  345. package/dist/zod.mjs.map +1 -0
  346. package/package.json +145 -33
  347. package/src/test.ts +9 -17
  348. package/CHANGELOG.md +0 -145
  349. package/ROADMAP.md +0 -126
  350. package/dist/zod-table.d.mts +0 -175
  351. package/dist/zod-table.mjs +0 -2
  352. package/dist/zod-table.mjs.map +0 -1
  353. package/docs/agent-tools.md +0 -41
  354. package/docs/approvals.md +0 -200
  355. package/docs/architecture.md +0 -124
  356. package/docs/auth.md +0 -218
  357. package/docs/commands.md +0 -278
  358. package/docs/conventions.md +0 -291
  359. package/docs/crud.md +0 -62
  360. package/docs/llms.md +0 -220
  361. package/docs/maintainability.md +0 -124
  362. package/docs/migration.md +0 -351
  363. package/docs/plans/2026-08-14-001-feat-v0.1.0-feature-set-plan.md +0 -461
  364. package/docs/plans/2026-08-21-0930-feat-resolve-organization-hook-plan.md +0 -178
  365. package/docs/tenancy.md +0 -179
  366. package/docs/triggers.md +0 -75
  367. package/docs/upgrading.md +0 -175
  368. package/docs/webhooks.md +0 -58
  369. package/docs/zod-table.md +0 -173
  370. package/scripts/convex-config-bridge.mjs +0 -55
  371. package/scripts/extract-changelog.mjs +0 -29
  372. package/scripts/smoke-packed-components.mjs +0 -374
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relations.mjs","names":["fieldBrand","edgeBrand","registries","executorRegistries","refs","memberRefs","throughRefs","throughChecks","edgeRefs","reservedEdgeNames","defineRelations","sources","name","table","tables","tableSource","names","nativeTables","metadata","states","pending","storedTier","state","known","captureStoredTier","error","ready","finishTable","materializeTable","native","checks","check","defer","ownRefs","throughPending","tableRefs","branchRefs","branchTables","fieldValidator","data","fields","guard","field","makeReferences","result","makeReference","ref","selected","once","validator","resolve","nativeIdMembers","id","hasNull","v","member","junction","compatible","reference","referencesFor","one","many","references","makeEdge","spec","supplied","declare","key","tag","skeleton","branches","branch","discriminator","edges","source","declared","edge","base","assertPathLegs","declarations","view","validatePath","used","use","internal","helpers","pages","options","expected","contract","actual","nativeJson","nativePagination","k","assertSelection","selection","settings","relationFilterSchema","filterGrammar","assertGroups","groups","pageResult","rowSchema","identity","tableEntries","registryIdentity","a","b","tableEntry","sourceEntry","scopedIdentity","reached","chosen","legTables","only","serializeLeg","entry","canonicalNative","registry","snapshots","snapshot","snapshotTable","streamTables","streamTable","defineSchema","verifyRelations","withFieldGroups","fieldGroups","group","memberOf","target","getRelationExecutor","owned","assertSchema","descriptor","branchValidators","projectionKeys","groupDtos","scalarFields","grammars","filterNodes","validateDocument","row","cached","fieldKeys","entries","values","kFromNative","schemaOf","grammar","grammarKey","depth","cacheKey","scalarValidator","scalarPredicateSchema","relationGrammars","relations","relation","declaration","lazyRelationFilterSchema","visit","mask","eligible","projection","found","KDiscriminatedUnion","projectionBranch","KObject","dto","variants","composed","groupValidators","keys","getRelationMetadata","declaredGroups","preflightNative","schemaSkeleton","captureBoundary","valuePreserving","exportStored","exported","nativeTableExport","nativeTable","assertNativeValidation","captureIndexes","captured","indexExport","index","assertActiveIndexes","tier","schema","normalizeStored","boundary","completeTable","normalizeTable","stored","dtos","checkDtoBoundary","attachDtos","groupFields","definitions","publicBranches","members","normalized","validators","sameNative","indexes","searchIndexes","capturedIndexes","searchIndexList","defineTable","first","rest","system","objects","option","optionsOf","literalOf","common","commonCompatible","compute","assertGroupData","value","prototype","input","parsed","groupSelection","nested","kObjectFromNative","modes","nodes","ancestors","property","leg","own","junctionGuard","left","from","right","to","leftDomain","domain","requireIndex","position","assertFilterScalar","deferFilterField","relationFields","compose","document","documents","variantOptions","union","assertStoredDocument","object","storage","assertSystemFields","nativePrototypes","sample","seen","active","inherited","trusted","currentKeys","current","before","container","child","_id","_creationTime","idTables","frozenNative","next","searchIndex","groupDefinitions","VALUE_CHANGING_OPS","objectFieldsOf","membersOf","required","requiredFromNative","unionOf","out","root"],"sources":["../src/relations.ts"],"sourcesContent":["import { defineSchema, defineTable, type TableDefinition } from 'convex/server'\nimport {\n\tv,\n\ttype GenericId,\n\ttype GenericValidator,\n\ttype ValidatorJSON,\n\ttype JSONValue,\n\ttype Value,\n} from 'convex/values'\nimport { k, type KSchema, type KType } from './k'\nimport { KDiscriminatedUnion } from './k/kinds'\nimport { KObject } from './k/object'\nimport {\n\tnativePagination,\n\trelationFilterSchema,\n\tscalarPredicateSchema,\n\ttype FieldSchemas,\n\ttype FilterGrammar,\n\ttype PaginationOptionsSchema,\n\ttype ScalarSelection,\n\ttype ScalarPredicate,\n} from './querying/filters'\nimport type { FilterContract, SharedFilters } from './querying/shared/contract'\nimport {\n\tlazyRelationFilterSchema,\n\tdeferFilterField,\n\tunionOf,\n\ttype PaginationValidatorOptions,\n} from './querying/shared/filters'\nimport { canonicalNative, sameNative } from './querying/shared/native-json'\nimport { pageResult } from './querying/shared/page'\nimport type { EnginePaginationResult } from './table'\n\n/**\n * The filters a browser or untyped caller may build for `Schema`: the native filter type with ID\n * brands relaxed to plain strings. It is deliberately broader than the native function arguments,\n * which keep each ID's table brand.\n */\nexport type PaginationFiltersInput<Schema extends KType> = Schema['validator']['type'] extends {\n\tfilters?: infer Filters\n}\n\t? InputView<Exclude<Filters, undefined>>\n\t: never\ntype InputView<T> =\n\tT extends GenericId<string>\n\t\t? string\n\t\t: T extends readonly (infer E)[]\n\t\t\t? InputView<E>[]\n\t\t\t: T extends object\n\t\t\t\t? { [K in keyof T]: InputView<T[K]> }\n\t\t\t\t: T\n\n/** Generated object or discriminated-union boundaries. */\nexport interface RelationTable {\n\treadonly tableName: string\n\t/** A `k.object` or `k.discriminatedUnion` of objects, checked on first use. */\n\treadonly schema: KType\n\treadonly publicDto: KType\n\t/** Read on the table's first use, never at declaration. */\n\treadonly table: TableDefinition\n\tdto(includeId: true): KType\n\t/** Whole stored fields; schemas are captured from the native table, never a DTO transform. */\n\tfieldGroups?: Readonly<Record<string, readonly string[]>>\n}\nexport type RelationTables = Record<string, RelationTable>\nexport type FieldGroupMode = 'if-permitted' | 'required'\nexport type FieldGroupRequest<T extends RelationTable> = {\n\t[K in keyof NonNullable<T['fieldGroups']>]?: FieldGroupMode\n}\n/** Separate from relation keys so existing selection syntax remains unambiguous. */\nexport type RelationGroupSelection<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tL extends readonly 1[] = readonly [1, 1, 1, 1],\n> = {\n\tfieldGroups?: FieldGroupRequest<Tables[T]>\n\trelations?: L extends readonly []\n\t\t? never\n\t\t: {\n\t\t\t\t[K in keyof Edges<D, T>]?: RelationGroupSelection<\n\t\t\t\t\tTables,\n\t\t\t\t\tD,\n\t\t\t\t\tExtract<Target<Edges<D, T>[K]>, keyof Tables>,\n\t\t\t\t\tTail<L>\n\t\t\t\t>\n\t\t\t}\n}\n/** Internal admitted runtime tree, independent of user relation names. */\nexport interface GroupSelection {\n\tfieldGroups?: Readonly<Record<string, FieldGroupMode>>\n\trelations?: Readonly<Record<string, GroupSelection>>\n}\nexport type ExactGroupSelection<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tG,\n> = G & {\n\t[K in keyof G]: K extends 'fieldGroups'\n\t\t? G[K] & {\n\t\t\t\t[N in keyof G[K]]: N extends keyof FieldGroupRequest<Tables[T]> ? FieldGroupMode : never\n\t\t\t}\n\t\t: K extends 'relations'\n\t\t\t? G[K] & {\n\t\t\t\t\t[N in keyof G[K]]: N extends keyof Edges<D, T>\n\t\t\t\t\t\t? ExactGroupSelection<Tables, D, Extract<Target<Edges<D, T>[N]>, keyof Tables>, G[K][N]>\n\t\t\t\t\t\t: never\n\t\t\t\t}\n\t\t\t: never\n}\ntype StoredValue<V extends GenericValidator> = GenericValidator extends V\n\t? V['type']\n\t: V extends {\n\t\t\t\tkind: 'object'\n\t\t\t\tfields: infer F extends Record<string, GenericValidator>\n\t\t }\n\t\t? { [K in keyof F as F[K]['isOptional'] extends 'optional' ? never : K]: StoredValue<F[K]> } & {\n\t\t\t\t[K in keyof F as F[K]['isOptional'] extends 'optional' ? K : never]?: StoredValue<F[K]>\n\t\t\t}\n\t\t: V extends { kind: 'array'; element: infer E extends GenericValidator }\n\t\t\t? StoredValue<E>[]\n\t\t\t: V extends { kind: 'union'; members: infer M extends GenericValidator[] }\n\t\t\t\t? StoredValue<M[number]>\n\t\t\t\t: V extends {\n\t\t\t\t\t\t\tkind: 'record'\n\t\t\t\t\t\t\tkey: infer K extends GenericValidator\n\t\t\t\t\t\t\tvalue: infer E extends GenericValidator\n\t\t\t\t\t }\n\t\t\t\t\t? Record<Extract<K['type'], string>, StoredValue<E>>\n\t\t\t\t\t: V['type']\ntype GroupStoredRow<\n\tT extends RelationTable,\n\tRow,\n\tStored = StoredValue<T['schema']['validator']>,\n> = [Tags<T>] extends [never]\n\t? Stored\n\t: Extract<Stored, Pick<Row, Extract<Discriminator<T>, keyof Row>>>\ntype GroupFields<T extends RelationTable, G, Row> = T extends {\n\tfieldGroups: infer Definitions extends Readonly<Record<string, readonly string[]>>\n}\n\t? {\n\t\t\t[K in keyof G & keyof Definitions]: Pick<\n\t\t\t\tGroupStoredRow<T, Row>,\n\t\t\t\tExtract<Definitions[K][number], keyof GroupStoredRow<T, Row>>\n\t\t\t>\n\t\t}\n\t: {}\ntype UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends (\n\tx: infer I,\n) => void\n\t? I\n\t: never\ntype IncludedFields<T extends RelationTable, G, Row> = G extends { fieldGroups: infer Requests }\n\t? UnionToIntersection<\n\t\t\t{\n\t\t\t\t[K in keyof Requests & keyof GroupFields<T, Requests, Row>]: Requests[K] extends 'required'\n\t\t\t\t\t? GroupFields<T, Requests, Row>[K]\n\t\t\t\t\t: Partial<GroupFields<T, Requests, Row>[K]>\n\t\t\t}[keyof Requests & keyof GroupFields<T, Requests, Row>]\n\t\t>\n\t: {}\ntype NestedGroups<G, K extends PropertyKey> = G extends { relations: infer R }\n\t? K extends keyof R\n\t\t? R[K]\n\t\t: {}\n\t: {}\n/** Internal named declaration dependency; excluded from the supported relations facade. */\nexport interface SelectionMask {\n\t[key: string]: true | SelectionMask\n}\ntype DocumentFields<S> =\n\tS extends KDiscriminatedUnion<infer _Key, infer O>\n\t\t? O[number] extends infer B\n\t\t\t? B extends KObject<infer F>\n\t\t\t\t? F\n\t\t\t\t: never\n\t\t\t: never\n\t\t: S extends KObject<infer F>\n\t\t\t? F\n\t\t\t: never\ntype AllKeys<F> = F extends unknown ? keyof F : never\ntype FieldAt<F, K extends PropertyKey> = F extends unknown\n\t? K extends keyof F\n\t\t? F[K]\n\t\t: never\n\t: never\ntype NativeDomain<V> = V extends {\n\tkind: 'union'\n\tmembers: infer M extends GenericValidator[]\n}\n\t? NativeDomain<M[number]>\n\t: V extends { kind: 'null' }\n\t\t? never\n\t\t: V extends { kind: infer K; type: infer Value }\n\t\t\t? readonly [K, Exclude<Value, undefined>]\n\t\t\t: never\ntype DomainAt<F, K extends PropertyKey> = F extends unknown\n\t? K extends keyof F\n\t\t? F[K] extends KType\n\t\t\t? NativeDomain<F[K]['validator']>\n\t\t\t: never\n\t\t: never\n\t: never\ntype CompatibleBranches<F, K extends keyof F, Domain = DomainAt<F, K>> = F extends unknown\n\t? Same<DomainAt<F, K>, Domain>\n\t: never\ntype Discriminator<T extends RelationTable> = DiscriminatorOf<T['schema']>\ntype DiscriminatorOf<S> = S extends KDiscriminatedUnion<infer Key, infer _Options> ? Key : never\ntype Fields<\n\tT extends RelationTable,\n\tF = DocumentFields<T['schema']>,\n> = string extends T['tableName']\n\t? FieldSchemas\n\t: [Discriminator<T>] extends [never]\n\t\t? T['schema'] extends KObject<infer ObjectFields>\n\t\t\t? { [K in keyof ObjectFields]: Extract<ObjectFields[K], KType> }\n\t\t\t: never\n\t\t: {\n\t\t\t\t[\n\t\t\t\t\tK in Extract<keyof F, string> as K extends Discriminator<T>\n\t\t\t\t\t\t? K\n\t\t\t\t\t\t: false extends CompatibleBranches<F, K>\n\t\t\t\t\t\t\t? never\n\t\t\t\t\t\t\t: K\n\t\t\t\t]: Extract<FieldAt<F, K>, KType>\n\t\t\t}\ntype BranchFields<T extends RelationTable, Tag extends string> =\n\tDocumentFields<T['schema']> extends infer F\n\t\t? F extends Record<Discriminator<T>, KType>\n\t\t\t? Tag extends F[Discriminator<T>]['_output']\n\t\t\t\t? F\n\t\t\t\t: never\n\t\t\t: never\n\t\t: never\ntype Tags<T extends RelationTable> = [Discriminator<T>] extends [never]\n\t? never\n\t: Extract<T['schema']['_output'][Discriminator<T>], string>\ntype Native<T extends RelationTable, K extends keyof Fields<T>> = Fields<T>[K]['validator']['type']\nconst fieldBrand: unique symbol = Symbol('relationField')\nconst edgeBrand: unique symbol = Symbol('relationEdge')\ntype Comparable<Value> = Exclude<Value, null | undefined>\ntype IdMembers<Value, Registered extends string> = [Comparable<Value>] extends [never]\n\t? never\n\t: [Comparable<Value>] extends [GenericId<string>]\n\t\t? Extract<Comparable<Value>, GenericId<string>>['__tableName'] & Registered\n\t\t: never\ntype Same<A, B> = [Comparable<A> | Comparable<B>] extends [never]\n\t? false\n\t: [Comparable<A>] extends [Comparable<B>]\n\t\t? [Comparable<B>] extends [Comparable<A>]\n\t\t\t? true\n\t\t\t: false\n\t\t: false\n\nexport interface FieldReference<\n\tTable extends string,\n\tField extends string,\n\tValue,\n\tScope extends string = never,\n\tRegistered extends string = string,\n\tMember extends string = never,\n> {\n\treadonly guard?: RelationGuard<Scope>\n\treadonly [fieldBrand]: Value\n\treadonly table: Table\n\treadonly field: Field\n\t/** Select a registered native-ID member, retaining this field's nullish wrappers. */\n\tforTable<const T extends ([Scope] extends [never] ? IdMembers<Value, Registered> : never)>(\n\t\ttable: T,\n\t): FieldReference<\n\t\tTable,\n\t\tField,\n\t\tExtract<Value, GenericId<T> | null | undefined>,\n\t\tScope,\n\t\tRegistered,\n\t\tT\n\t>\n\tthrough<J extends AnyField>(\n\t\tjunction: J &\n\t\t\t([Member] extends [never] ? {} : never) &\n\t\t\t(J extends FieldReference<string, string, any, any, any, infer M>\n\t\t\t\t? [M] extends [never]\n\t\t\t\t\t? {}\n\t\t\t\t\t: never\n\t\t\t\t: never) &\n\t\t\t(Same<Value, J[typeof fieldBrand]> extends true ? {} : never),\n\t): ThroughReference<Table, Field, Value, J, Scope>\n}\nexport interface RelationGuard<Tag extends string = string> {\n\treadonly discriminator: string\n\treadonly tag: Tag\n}\ntype AnyField = FieldReference<string, string, any, any, any, any>\nexport interface ThroughReference<\n\tTable extends string,\n\tField extends string,\n\tValue,\n\tJunction extends AnyField,\n\tScope extends string = never,\n> {\n\treadonly base: FieldReference<Table, Field, Value, Scope>\n\treadonly junction: Junction\n}\ntype AnyThrough = ThroughReference<string, string, any, AnyField, any>\ntype Leg = AnyField | AnyThrough\ntype Base<L extends Leg> = L extends AnyThrough ? L['base'] : L\ntype JunctionTable<L extends Leg> = L extends AnyThrough ? L['junction']['table'] : never\ntype CompatibleLegs<F extends Leg, T extends Leg> = F extends AnyThrough\n\t? T extends AnyThrough\n\t\t? Same<JunctionTable<F>, JunctionTable<T>> extends true\n\t\t\t? {}\n\t\t\t: never\n\t\t: never\n\t: T extends AnyThrough\n\t\t? never\n\t\t: Same<Base<F>[typeof fieldBrand], Base<T>[typeof fieldBrand]> extends true\n\t\t\t? {}\n\t\t\t: never\n\nexport interface RelationEdge<\n\tSource extends string,\n\tTarget extends string,\n\tCardinality extends 'one' | 'many',\n\tSourceScope extends string = never,\n\tTargetScope extends string = never,\n> {\n\treadonly sourceGuard?: RelationGuard<SourceScope>\n\treadonly targetGuard?: RelationGuard<TargetScope>\n\treadonly junctionGuard?: RelationGuard\n\treadonly sourceMember?: RelationMember\n\treadonly targetMember?: RelationMember\n\treadonly [edgeBrand]: true\n\treadonly source: Source\n\treadonly target: Target\n\treadonly cardinality: Cardinality\n\treadonly from: Leg\n\treadonly to: Leg\n}\ninterface RelationMember {\n\treadonly table: string\n}\ntype AnyEdge = RelationEdge<string, string, 'one' | 'many', any, any>\ntype FieldReferences<Tables extends RelationTables> = {\n\t[T in keyof Tables]: {\n\t\t[K in Extract<keyof Fields<Tables[T]>, string>]: FieldReference<\n\t\t\tExtract<T, string>,\n\t\t\tK,\n\t\t\tNative<Tables[T], K>,\n\t\t\tnever,\n\t\t\tExtract<keyof Tables, string>\n\t\t>\n\t}\n}\nexport type BranchBuilder<Tables extends RelationTables> = <\n\tconst T extends keyof Tables & string,\n\tconst Tag extends Tags<Tables[T]>,\n>(\n\ttable: T,\n\ttag: Tag,\n) => {\n\t[K in keyof BranchFields<Tables[T], Tag> & string]: FieldReference<\n\t\tT,\n\t\tK,\n\t\tExtract<BranchFields<Tables[T], Tag>[K], KType>['validator']['type'],\n\t\tTag\n\t>\n}\ntype Scope<L extends Leg> = NonNullable<Base<L>['guard']>['tag']\ntype AllReferences<Tables extends RelationTables> = {\n\t[T in keyof Tables]: FieldReferences<Tables>[T][Extract<keyof FieldReferences<Tables>[T], string>]\n}[keyof Tables]\ntype Builders<Tables extends RelationTables, C extends 'one' | 'many'> = {\n\t[T in keyof Tables]: <\n\t\tF extends AllReferences<Tables> | AnyField | AnyThrough,\n\t\tTo extends\n\t\t\t| FieldReferences<Tables>[T][Extract<keyof FieldReferences<Tables>[T], string>]\n\t\t\t| AnyField\n\t\t\t| AnyThrough,\n\t>(\n\t\tspec: { from: F; to: To } & CompatibleLegs<F, To> & (Base<To>['table'] extends T ? {} : never),\n\t) => RelationEdge<Base<F>['table'], Extract<T, string>, C, Scope<F>, Scope<To>>\n}\nexport type RelationBuilder<Tables extends RelationTables> = FieldReferences<Tables> & {\n\tone: Builders<Tables, 'one'>\n\tmany: Builders<Tables, 'many'>\n}\nexport type RelationDeclarations = Record<string, Record<string, AnyEdge>>\ntype ExactDeclarations<Tables extends RelationTables, D extends RelationDeclarations> = {\n\t[T in keyof D]: T extends keyof Tables\n\t\t? {\n\t\t\t\t[K in keyof D[T]]: K extends\n\t\t\t\t\t| AllKeys<DocumentFields<Tables[T]['schema']>>\n\t\t\t\t\t| 'and'\n\t\t\t\t\t| 'or'\n\t\t\t\t\t| 'not'\n\t\t\t\t\t| 'fields'\n\t\t\t\t\t| 'then'\n\t\t\t\t\t| ([Tags<Tables[T]>] extends [never] ? never : 'variant' | 'variants')\n\t\t\t\t\t| '__proto__'\n\t\t\t\t\t| 'constructor'\n\t\t\t\t\t| 'prototype'\n\t\t\t\t\t? never\n\t\t\t\t\t: D[T][K]['source'] extends T\n\t\t\t\t\t\t? D[T][K]\n\t\t\t\t\t\t: never\n\t\t\t}\n\t\t: never\n}\ntype Depth = readonly [1, 1, 1, 1]\ntype Tail<D extends readonly 1[]> = D extends readonly [1, ...infer R extends 1[]] ? R : []\ntype Edges<D, T> = T extends keyof D ? D[T] : {}\ntype Target<E> = E extends AnyEdge ? E['target'] : never\nexport type RelationSelection<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tLevel extends readonly 1[] = Depth,\n> = Level extends readonly []\n\t? Record<string, never>\n\t: {\n\t\t\t[K in keyof Edges<D, T>]?:\n\t\t\t\t| true\n\t\t\t\t| RelationSelection<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, Tail<Level>>\n\t\t}\ntype BranchTables<Tables extends RelationTables, T extends keyof Tables, Tag extends string> = {\n\t[K in keyof Tables]: K extends T\n\t\t? Omit<Tables[K], 'schema'> & { schema: KObject<BranchFields<Tables[T], Tag>> }\n\t\t: Tables[K]\n}\ntype VariantSelections<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tLevel extends readonly 1[],\n> = {\n\t[Tag in Tags<Tables[T]>]?: RelationFilterSelection<BranchTables<Tables, T, Tag>, D, T, Level>\n}\nexport type RelationFilterSelection<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tLevel extends readonly 1[] = Depth,\n> = ([Tags<Tables[T]>] extends [never]\n\t? ScalarSelection<Fields<Tables[T]>>\n\t: Omit<ScalarSelection<Fields<Tables[T]>>, 'variants'> & {\n\t\t\tvariants?:\n\t\t\t\t| ('variants' extends keyof ScalarSelection<Fields<Tables[T]>> ? true : never)\n\t\t\t\t| VariantSelections<Tables, D, T, Level>\n\t\t}) &\n\t(Level extends readonly []\n\t\t? {}\n\t\t: {\n\t\t\t\t[K in keyof Edges<D, T>]?: RelationFilterSelection<\n\t\t\t\t\tTables,\n\t\t\t\t\tD,\n\t\t\t\t\tExtract<Target<Edges<D, T>[K]>, keyof Tables>,\n\t\t\t\t\tTail<Level>\n\t\t\t\t>\n\t\t\t})\ntype ExactOutputMask<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS,\n\tL extends readonly 1[] = Depth,\n> = S & {\n\t[K in keyof S]: L extends readonly []\n\t\t? never\n\t\t: K extends keyof Edges<D, T>\n\t\t\t? S[K] extends true\n\t\t\t\t? true\n\t\t\t\t: ExactOutputMask<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, S[K], Tail<L>>\n\t\t\t: never\n}\ntype ExactFilterMask<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS,\n\tL extends readonly 1[] = Depth,\n> = S & {\n\t[K in keyof S]: K extends ([Tags<Tables[T]>] extends [never] ? never : 'variants')\n\t\t? S[K] extends true\n\t\t\t? K extends keyof ScalarSelection<Fields<Tables[T]>>\n\t\t\t\t? true\n\t\t\t\t: never\n\t\t\t: S[K] & {\n\t\t\t\t\t[Tag in keyof S[K]]: Tag extends Tags<Tables[T]>\n\t\t\t\t\t\t? ExactFilterMask<\n\t\t\t\t\t\t\t\tBranchTables<Tables, T, Extract<Tag, string>>,\n\t\t\t\t\t\t\t\tD,\n\t\t\t\t\t\t\t\tT,\n\t\t\t\t\t\t\t\tS[K][Tag],\n\t\t\t\t\t\t\t\tTail<L>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t: never\n\t\t\t\t}\n\t\t: K extends keyof ScalarSelection<Fields<Tables[T]>>\n\t\t\t? S[K] extends true\n\t\t\t\t? true\n\t\t\t\t: never\n\t\t\t: L extends readonly []\n\t\t\t\t? never\n\t\t\t\t: K extends keyof Edges<D, T>\n\t\t\t\t\t? S[K] extends true\n\t\t\t\t\t\t? never\n\t\t\t\t\t\t: ExactFilterMask<\n\t\t\t\t\t\t\t\tTables,\n\t\t\t\t\t\t\t\tD,\n\t\t\t\t\t\t\t\tExtract<Target<Edges<D, T>[K]>, keyof Tables>,\n\t\t\t\t\t\t\t\tS[K],\n\t\t\t\t\t\t\t\tTail<L>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t: never\n}\ntype ScalarValues<T extends RelationTable, S, Side extends 'input' | 'output'> = {\n\t[K in Extract<keyof S, keyof Fields<T>>]?: ScalarPredicate<Fields<T>[K], Side>\n}\nexport type RelationFilters<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS,\n\tSide extends 'input' | 'output' = 'output',\n\tLevel extends readonly 1[] = Depth,\n> = Omit<\n\tScalarValues<Tables[T], S, Side>,\n\t'and' | 'or' | 'not' | 'fields' | ([Tags<Tables[T]>] extends [never] ? never : 'variant')\n> & {\n\tfields?: ScalarValues<Tables[T], S, Side>\n} & VariantFilters<Tables, D, T, S, Side, Level> &\n\t(Level extends readonly []\n\t\t? {}\n\t\t: {\n\t\t\t\t[K in Extract<keyof S, keyof Edges<D, T>>]?: Edges<D, T>[K] extends RelationEdge<\n\t\t\t\t\tstring,\n\t\t\t\t\tinfer Target,\n\t\t\t\t\tinfer C,\n\t\t\t\t\tany,\n\t\t\t\t\tany\n\t\t\t\t>\n\t\t\t\t\t? C extends 'one'\n\t\t\t\t\t\t? RelationFilters<\n\t\t\t\t\t\t\t\tTables,\n\t\t\t\t\t\t\t\tD,\n\t\t\t\t\t\t\t\tExtract<Target, keyof Tables>,\n\t\t\t\t\t\t\t\tS[K],\n\t\t\t\t\t\t\t\tSide,\n\t\t\t\t\t\t\t\tTail<Level>\n\t\t\t\t\t\t\t> | null\n\t\t\t\t\t\t:\n\t\t\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\t\t\tsome: RelationFilters<\n\t\t\t\t\t\t\t\t\t\t\tTables,\n\t\t\t\t\t\t\t\t\t\t\tD,\n\t\t\t\t\t\t\t\t\t\t\tExtract<Target, keyof Tables>,\n\t\t\t\t\t\t\t\t\t\t\tS[K],\n\t\t\t\t\t\t\t\t\t\t\tSide,\n\t\t\t\t\t\t\t\t\t\t\tTail<Level>\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\t\t\tnone: RelationFilters<\n\t\t\t\t\t\t\t\t\t\t\tTables,\n\t\t\t\t\t\t\t\t\t\t\tD,\n\t\t\t\t\t\t\t\t\t\t\tExtract<Target, keyof Tables>,\n\t\t\t\t\t\t\t\t\t\t\tS[K],\n\t\t\t\t\t\t\t\t\t\t\tSide,\n\t\t\t\t\t\t\t\t\t\t\tTail<Level>\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t }\n\t\t\t\t\t: never\n\t\t\t} & {\n\t\t\t\tand?: readonly RelationFilters<Tables, D, T, S, Side, Tail<Level>>[]\n\t\t\t\tor?: readonly RelationFilters<Tables, D, T, S, Side, Tail<Level>>[]\n\t\t\t\tnot?: RelationFilters<Tables, D, T, S, Side, Tail<Level>>\n\t\t\t})\ntype VariantFilters<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS,\n\tSide extends 'input' | 'output',\n\tL extends readonly 1[],\n> = L extends readonly []\n\t? {}\n\t: S extends { variants: infer V }\n\t\t? V extends true\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tvariant?: {\n\t\t\t\t\t\t[Tag in keyof V]: Tag extends Tags<Tables[T]>\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\ttag: Tag\n\t\t\t\t\t\t\t\t\tfilters: RelationFilters<\n\t\t\t\t\t\t\t\t\t\tBranchTables<Tables, T, Extract<Tag, string>>,\n\t\t\t\t\t\t\t\t\t\tD,\n\t\t\t\t\t\t\t\t\t\tT,\n\t\t\t\t\t\t\t\t\t\tV[Tag] & Omit<S, 'variants'>,\n\t\t\t\t\t\t\t\t\t\tSide,\n\t\t\t\t\t\t\t\t\t\tTail<L>\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: never\n\t\t\t\t\t}[keyof V]\n\t\t\t\t}\n\t\t: {}\ntype PublicRow<T extends RelationTable> = T['publicDto']['_output'] & {\n\t_id: GenericId<T['tableName']>\n}\nexport type ScopedRelationRow<Row, Scope extends string, Key extends PropertyKey> = [\n\tScope,\n] extends [never]\n\t? Row\n\t: Extract<Row, Record<Key, Scope>>\ntype ComposeRelationRow<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS,\n\tLevel extends readonly 1[],\n\tRow,\n\tG = {},\n> = Row extends unknown\n\t? Row &\n\t\t\tIncludedFields<Tables[T], G, Row> &\n\t\t\t(Level extends readonly []\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\t[K in keyof S]: K extends keyof Edges<D, T>\n\t\t\t\t\t\t\t? Edges<D, T>[K] extends RelationEdge<\n\t\t\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\t\t\tinfer Target,\n\t\t\t\t\t\t\t\t\tinfer C,\n\t\t\t\t\t\t\t\t\tinfer SourceScope,\n\t\t\t\t\t\t\t\t\tinfer TargetScope\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t? C extends 'one'\n\t\t\t\t\t\t\t\t\t? (\n\t\t\t\t\t\t\t\t\t\t\t[SourceScope] extends [never]\n\t\t\t\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t\t\t\t: Row extends ScopedRelationRow<Row, SourceScope, Discriminator<Tables[T]>>\n\t\t\t\t\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t\t\t\t\t: false\n\t\t\t\t\t\t\t\t\t\t) extends true\n\t\t\t\t\t\t\t\t\t\t? ScopedRelationRow<\n\t\t\t\t\t\t\t\t\t\t\t\tRelationRow<\n\t\t\t\t\t\t\t\t\t\t\t\t\tTables,\n\t\t\t\t\t\t\t\t\t\t\t\t\tD,\n\t\t\t\t\t\t\t\t\t\t\t\t\tExtract<Target, keyof Tables>,\n\t\t\t\t\t\t\t\t\t\t\t\t\tS[K] extends true ? {} : S[K],\n\t\t\t\t\t\t\t\t\t\t\t\t\tTail<Level>,\n\t\t\t\t\t\t\t\t\t\t\t\t\tNestedGroups<G, K>\n\t\t\t\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\t\t\t\tTargetScope,\n\t\t\t\t\t\t\t\t\t\t\t\tDiscriminator<Tables[Extract<Target, keyof Tables>]>\n\t\t\t\t\t\t\t\t\t\t\t> | null\n\t\t\t\t\t\t\t\t\t\t: null\n\t\t\t\t\t\t\t\t\t: EnginePaginationResult<\n\t\t\t\t\t\t\t\t\t\t\tScopedRelationRow<\n\t\t\t\t\t\t\t\t\t\t\t\tRelationRow<\n\t\t\t\t\t\t\t\t\t\t\t\t\tTables,\n\t\t\t\t\t\t\t\t\t\t\t\t\tD,\n\t\t\t\t\t\t\t\t\t\t\t\t\tExtract<Target, keyof Tables>,\n\t\t\t\t\t\t\t\t\t\t\t\t\tS[K] extends true ? {} : S[K],\n\t\t\t\t\t\t\t\t\t\t\t\t\tTail<Level>,\n\t\t\t\t\t\t\t\t\t\t\t\t\tNestedGroups<G, K>\n\t\t\t\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\t\t\t\tTargetScope,\n\t\t\t\t\t\t\t\t\t\t\t\tDiscriminator<Tables[Extract<Target, keyof Tables>]>\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t: never\n\t\t\t\t\t\t\t: never\n\t\t\t\t\t})\n\t: never\nexport type RelationRow<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS,\n\tLevel extends readonly 1[] = Depth,\n\tG = {},\n> = ComposeRelationRow<Tables, D, T, S, Level, PublicRow<Tables[T]>, G>\nexport type RelationQueryRow<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS,\n\tScope extends string = never,\n\tG = {},\n> = ScopedRelationRow<RelationRow<Tables, D, T, S, Depth, G>, Scope, Discriminator<Tables[T]>>\nexport interface RelationTableHelpers<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n> {\n\tfilters<F extends Record<string, GenericValidator>>(\n\t\tcontract: FilterContract<F>,\n\t): PaginationOptionsSchema<SharedFilters<F>>\n\tpaginationOpts<const S extends RelationFilterSelection<Tables, D, T>>(\n\t\tselection: ExactFilterMask<Tables, D, T, S>,\n\t\toptions?: PaginationValidatorOptions,\n\t): PaginationOptionsSchema<RelationFilters<Tables, D, T, S>>\n\tpageDto<\n\t\tconst S extends RelationSelection<Tables, D, T>,\n\t\tconst G extends RelationGroupSelection<Tables, D, T> = {},\n\t>(\n\t\tselection: ExactOutputMask<Tables, D, T, S>,\n\t\tgroups?: ExactGroupSelection<Tables, D, T, G>,\n\t): KSchema<EnginePaginationResult<RelationRow<Tables, D, T, S, Depth, G>>>\n}\nexport interface RelationRegistryIdentity {\n\treadonly identity: string\n\treadonly version: 1\n}\nexport interface RelationRegistry<Tables extends RelationTables, D extends RelationDeclarations> {\n\treadonly identity: string\n\treadonly version: 1\n\treadonly tables: { [T in keyof Tables]: RelationTableHelpers<Tables, D, T> }\n}\n\nexport interface RelationFieldMetadata {\n\treadonly kind: string\n\treadonly optional: boolean\n\treadonly nullable: boolean\n\treadonly idTables: readonly string[]\n\treadonly native: Readonly<ValidatorJSON>\n}\nexport interface SearchIndexMetadata {\n\treadonly name: string\n\treadonly searchField: string\n\treadonly filterFields: readonly string[]\n\treadonly staged: boolean\n}\nexport interface RelationTableMetadata {\n\treadonly searchIndexes: readonly SearchIndexMetadata[]\n\treadonly fieldGroups: Readonly<Record<string, readonly string[]>>\n\treadonly fields: Readonly<Record<string, RelationFieldMetadata>>\n\treadonly variant?: {\n\t\treadonly discriminator: string\n\t\treadonly tags: readonly string[]\n\t}\n\treadonly indexes: readonly {\n\t\treadonly name: string\n\t\treadonly fields: readonly string[]\n\t}[]\n}\ninterface TableMetadata {\n\tsearchIndexes: readonly SearchIndexMetadata[]\n\tfieldGroups: Readonly<Record<string, readonly string[]>>\n\t/** Stored validators of each group, by `[group, tag]`; their strict objects build on first use. */\n\tgroupFields: Readonly<Record<string, Readonly<Record<string, GenericValidator>>>>\n\tgroupSchemas: Map<string, KObject<any>>\n\tfields: Record<string, GenericValidator>\n\t/** Sorted by name on first read; order-free checks use `capturedIndexes`. */\n\tindexes: { name: string; fields: string[] }[]\n\tcapturedIndexes: readonly { name: string; fields: string[] }[]\n\tsearchIndexList: SearchIndexMetadata[]\n\tdto: KObject<any> | KDiscriminatedUnion<string, any>\n\tbranches?: {\n\t\tdiscriminator: string\n\t\toptions: Record<string, { fields: Record<string, GenericValidator>; dto?: KObject<any> }>\n\t}\n\tallFields: ReadonlySet<string>\n}\ninterface RegistryMetadata {\n\tmetadata: Record<string, TableMetadata>\n\tdeclarations: RelationDeclarations\n}\nexport interface RelationMetadata {\n\treadonly tables: Readonly<Record<string, RelationTableMetadata>>\n\treadonly declarations: Readonly<Record<string, Readonly<Record<string, AnyEdge>>>>\n}\n\nconst registries = new WeakMap<RelationRegistryIdentity, RelationMetadata>()\n// Private executor state retains validators and projection, never a database reader.\nconst executorRegistries = new WeakMap<\n\tRelationRegistryIdentity,\n\t{\n\t\tinternal: RegistryMetadata\n\t\tnativeTables: Readonly<Record<string, TableDefinition>>\n\t\tstreamSchema: ReturnType<typeof defineSchema>\n\t\tuse(table: string): void\n\t\tscopedIdentity(\n\t\t\ttables: readonly string[],\n\t\t\tedges: readonly (readonly [source: string, name: string])[],\n\t\t): string\n\t}\n>()\n// Field validators resolve on first use of their table; resolvers memoize results and errors.\nconst refs = new WeakMap<AnyField, () => GenericValidator>()\nconst memberRefs = new WeakMap<AnyField, RelationMember>()\nconst throughRefs = new WeakSet<AnyThrough>()\nconst throughChecks = new WeakMap<AnyThrough, () => void>()\nconst edgeRefs = new WeakSet<AnyEdge>()\nconst reservedEdgeNames = [\n\t'and',\n\t'or',\n\t'not',\n\t'fields',\n\t'then',\n\t'__proto__',\n\t'constructor',\n\t'prototype',\n]\n\n/** No ID-field inference and no readers: this registry owns declarations/schema helpers only.\n * Registration checks table names, native table identity and edge structure. Every other\n * per-table check (preflight, schema capture, indexes, field groups, edge field types and\n * indexes) runs once, on the table's first use. `verifyRelations` runs all of them eagerly.\n */\nexport function defineRelations<\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\ttables: Tables,\n\tdeclare: (\n\t\tr: RelationBuilder<Tables>,\n\t\tbranch: BranchBuilder<Tables>,\n\t) => D & ExactDeclarations<Tables, D>,\n): RelationRegistry<Tables, D> {\n\t// Declaration reads only each table's name. Its native table, schema and skeleton are read on\n\t// the table's first use (R22); the native preflight runs before any export or conversion.\n\tconst sources: Record<string, TableSource> = Object.create(null)\n\tfor (const [name, table] of Object.entries(tables)) {\n\t\tif (\n\t\t\ttable.tableName !== name ||\n\t\t\t['one', 'many', '__proto__', 'constructor', 'prototype'].includes(name)\n\t\t)\n\t\t\tthrow new Error(`Invalid relation table \"${name}\"`)\n\t\tsources[name] = tableSource(table)\n\t}\n\tconst names = Object.keys(sources)\n\tconst nativeTables: Record<string, TableDefinition> = {}\n\tfor (const name of names)\n\t\tObject.defineProperty(nativeTables, name, {\n\t\t\tenumerable: true,\n\t\t\tget: () => sources[name].native(),\n\t\t})\n\n\tconst metadata: Record<string, TableMetadata> = {}\n\t// Each table materializes at most once, in two tiers: `storedTier` (stored side,\n\t// enough to validate edges that target it) and `ready` (everything). A\n\t// failure is cached and rethrown on every later use.\n\tconst states: Record<\n\t\tstring,\n\t\t{ stored?: StoredCapture; data?: TableMetadata; failure?: { error: unknown }; busy?: boolean }\n\t> = Object.create(null)\n\tconst pending: Record<string, (() => void)[]> = Object.create(null)\n\tfunction storedTier(name: string): StoredTier {\n\t\tconst state = (states[name] ??= {})\n\t\tif (state.failure) throw state.failure.error\n\t\tconst known = state.data ?? state.stored\n\t\tif (known) return known\n\t\tif (state.busy) throw new Error(`Cyclic relation table materialization \"${name}\"`)\n\t\tstate.busy = true\n\t\ttry {\n\t\t\treturn (state.stored = captureStoredTier(name, sources[name].table, sources[name].native()))\n\t\t} catch (error) {\n\t\t\tstate.failure = { error }\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tstate.busy = false\n\t\t}\n\t}\n\tfunction ready(name: string): TableMetadata {\n\t\tconst state = (states[name] ??= {})\n\t\tif (state.failure) throw state.failure.error\n\t\t// Field checks below may read their own table again.\n\t\tif (state.data) return state.data\n\t\tif (state.busy) throw new Error(`Cyclic relation table materialization \"${name}\"`)\n\t\tstate.busy = true\n\t\ttry {\n\t\t\tconst { table, native } = sources[name]\n\t\t\tstate.data = state.stored\n\t\t\t\t? finishTable(name, table, state.stored)\n\t\t\t\t: materializeTable(name, table, native())\n\t\t\tconst checks = pending[name] ?? []\n\t\t\tdelete pending[name]\n\t\t\tfor (const check of checks) check()\n\t\t\treturn state.data\n\t\t} catch (error) {\n\t\t\tstate.data = undefined\n\t\t\tstate.failure = { error }\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tstate.busy = false\n\t\t}\n\t}\n\t// Checks owned by a table run when it materializes, or now if it already has.\n\tfunction defer(name: string, check: () => void): void {\n\t\tif (states[name]?.data && !states[name].busy) check()\n\t\telse (pending[name] ??= []).push(check)\n\t}\n\tfor (const name of names)\n\t\tObject.defineProperty(metadata, name, { enumerable: true, get: () => ready(name) })\n\n\tconst ownRefs = new Set<AnyField>()\n\tconst throughPending: (() => void)[] = []\n\tconst tableRefs: Record<string, Readonly<Record<string, AnyField>>> = Object.create(null)\n\tconst branchRefs = new Map<string, Record<string, AnyField>>()\n\tconst branchTables = new Set<string>()\n\tfunction fieldValidator(name: string, field: string, guard?: RelationGuard): GenericValidator {\n\t\tconst data = storedTier(name)\n\t\tconst fields = guard ? data.branches?.options[guard.tag]?.fields : data.fields\n\t\tif (!fields || !Object.hasOwn(fields, field))\n\t\t\tthrow new Error(`Native stored document disagrees with boundary \"${name}\"`)\n\t\treturn fields[field]\n\t}\n\tconst makeReferences = (name: string, fields: readonly string[], guard?: RelationGuard) => {\n\t\tconst result: Record<string, AnyField> = Object.create(null)\n\t\tfunction makeReference(\n\t\t\tfield: string,\n\t\t\tresolve: () => GenericValidator,\n\t\t\tmember?: RelationMember,\n\t\t): AnyField {\n\t\t\tconst ref: AnyField = {\n\t\t\t\t[fieldBrand]: undefined,\n\t\t\t\ttable: name,\n\t\t\t\tfield,\n\t\t\t\tguard,\n\t\t\t\tforTable(table: string) {\n\t\t\t\t\tif (guard) throw new Error('forTable on branch-scoped fields is unsupported')\n\t\t\t\t\tif (!Object.hasOwn(metadata, table))\n\t\t\t\t\t\tthrow new Error('Native ID member table is not registered')\n\t\t\t\t\tconst selected = once(() => {\n\t\t\t\t\t\tconst validator = resolve()\n\t\t\t\t\t\tconst members = nativeIdMembers(validator)\n\t\t\t\t\t\tif (!members?.includes(table)) throw new Error('Invalid native ID member selection')\n\t\t\t\t\t\tconst id = hasNull(validator) ? v.union(v.id(table), v.null()) : v.id(table)\n\t\t\t\t\t\treturn validator.isOptional === 'optional' ? v.optional(id) : id\n\t\t\t\t\t})\n\t\t\t\t\tdefer(name, selected)\n\t\t\t\t\treturn makeReference(field, selected, Object.freeze({ table }))\n\t\t\t\t},\n\t\t\t\tthrough<J extends AnyField>(junction: J): ThroughReference<string, string, any, J, any> {\n\t\t\t\t\tif (member || memberRefs.has(junction))\n\t\t\t\t\t\tthrow new Error('forTable with through is unsupported')\n\t\t\t\t\tif (!ownRefs.has(junction)) throw new Error('Invalid junction field or registry')\n\t\t\t\t\tconst result = Object.freeze({ base: ref, junction })\n\t\t\t\t\tconst check = once(() => {\n\t\t\t\t\t\tif (!compatible(resolve(), refs.get(junction)!()))\n\t\t\t\t\t\t\tthrow new Error('Invalid junction field or registry')\n\t\t\t\t\t})\n\t\t\t\t\tthroughRefs.add(result)\n\t\t\t\t\tthroughChecks.set(result, check)\n\t\t\t\t\t// Needs the junction's stored tier: runs when an edge uses it, or on verification.\n\t\t\t\t\tthroughPending.push(check)\n\t\t\t\t\treturn result\n\t\t\t\t},\n\t\t\t}\n\t\t\trefs.set(ref, resolve)\n\t\t\tif (member) memberRefs.set(ref, member)\n\t\t\townRefs.add(ref)\n\t\t\treturn Object.freeze(ref)\n\t\t}\n\t\t// A table exposes every field name, but builds a field's reference on its first read.\n\t\tfor (const field of fields) {\n\t\t\tconst reference = once(() =>\n\t\t\t\tmakeReference(\n\t\t\t\t\tfield,\n\t\t\t\t\tonce(() => fieldValidator(name, field, guard)),\n\t\t\t\t),\n\t\t\t)\n\t\t\tObject.defineProperty(result, field, { enumerable: true, get: reference })\n\t\t}\n\t\treturn Object.freeze(result)\n\t}\n\t// Field names come from the native skeleton; without one, the table materializes.\n\tfunction referencesFor(name: string) {\n\t\treturn (tableRefs[name] ??= makeReferences(\n\t\t\tname,\n\t\t\tsources[name].skeleton()?.common ?? Object.keys(ready(name).fields),\n\t\t))\n\t}\n\ttype EdgeFactory = (spec: { from: Leg; to: Leg }) => AnyEdge\n\tconst one: Record<string, EdgeFactory> = {}\n\tconst many: Record<string, EdgeFactory> = {}\n\tconst references: Record<\n\t\tstring,\n\t\tReadonly<Record<string, AnyField>> | Readonly<Record<string, EdgeFactory>>\n\t> = {}\n\tfor (const name of names) {\n\t\tObject.defineProperty(references, name, { enumerable: true, get: () => referencesFor(name) })\n\t\tone[name] = (spec) => makeEdge(name, 'one', spec, ownRefs)\n\t\tmany[name] = (spec) => makeEdge(name, 'many', spec, ownRefs)\n\t}\n\treferences.one = Object.freeze(one)\n\treferences.many = Object.freeze(many)\n\t// SAFETY: every native field has a branded reference; mapped builders retain the literal names.\n\tconst builder = Object.freeze(references) as RelationBuilder<Tables>\n\t// SAFETY: branch references are created only for validated table/tag pairs and retain literal native field types.\n\tconst branch = ((table: string, tag: string) => {\n\t\tconst key = JSON.stringify([table, tag])\n\t\tif (!branchRefs.has(key) && names.includes(table) && !branchTables.has(table)) {\n\t\t\tbranchTables.add(table)\n\t\t\tconst skeleton = sources[table].skeleton()\n\t\t\t// Object tables have no branches; an unknown skeleton materializes the table.\n\t\t\tconst branches = skeleton\n\t\t\t\t? (skeleton.branches ?? [])\n\t\t\t\t: Object.entries(ready(table).branches?.options ?? {}).map(\n\t\t\t\t\t\t([tag, branch]) => [tag, Object.keys(branch.fields)] as const,\n\t\t\t\t\t)\n\t\t\tconst discriminator = skeleton ? skeleton.discriminator : ready(table).branches?.discriminator\n\t\t\tfor (const [tag, fields] of branches)\n\t\t\t\tbranchRefs.set(\n\t\t\t\t\tJSON.stringify([table, tag]),\n\t\t\t\t\tmakeReferences(table, fields, Object.freeze({ discriminator: discriminator!, tag })),\n\t\t\t\t)\n\t\t}\n\t\tconst result = branchRefs.get(key)\n\t\tif (!result) throw new Error(`Unknown variant scope \"${table}.${tag}\"`)\n\t\treturn result\n\t}) as BranchBuilder<Tables>\n\tconst supplied = declare(builder, branch)\n\tconst edges: Record<string, Readonly<Record<string, AnyEdge>>> = Object.fromEntries(\n\t\tObject.entries(supplied).map(([name, edges]) => [name, Object.freeze({ ...edges })]),\n\t)\n\tfor (const [source, declared] of Object.entries(edges)) {\n\t\tif (!Object.hasOwn(metadata, source)) throw new Error(`Unknown source table \"${source}\"`)\n\t\tconst skeleton = sources[source].skeleton()\n\t\tfor (const [name, edge] of Object.entries(declared)) {\n\t\t\t// Field-name collisions are rechecked against normalized fields on first use.\n\t\t\tif (\n\t\t\t\treservedEdgeNames.includes(name) ||\n\t\t\t\t(skeleton &&\n\t\t\t\t\t(skeleton.fields.includes(name) ||\n\t\t\t\t\t\t(skeleton.variant && ['variant', 'variants'].includes(name))))\n\t\t\t)\n\t\t\t\tthrow new Error(`Relation name collision \"${name}\"`)\n\t\t\tif (\n\t\t\t\t!edgeRefs.has(edge) ||\n\t\t\t\t!ownRefs.has(base(edge.from)) ||\n\t\t\t\t!ownRefs.has(base(edge.to)) ||\n\t\t\t\tedge.source !== source\n\t\t\t)\n\t\t\t\tthrow new Error('Relation source bucket mismatch')\n\t\t\tassertPathLegs(edge)\n\t\t}\n\t}\n\t// Each edge validates on its first read: name collisions against the source's\n\t// normalized fields, then field types and indexes, which need only the stored\n\t// tier of the tables the edge reaches. Reading every edge validates them all.\n\tconst declarations: RelationDeclarations = {}\n\tfor (const [source, declared] of Object.entries(edges)) {\n\t\tconst view: Record<string, AnyEdge> = {}\n\t\tfor (const [name, edge] of Object.entries(declared)) {\n\t\t\tconst check = once(() => {\n\t\t\t\tconst data = ready(source)\n\t\t\t\tif (\n\t\t\t\t\tdata.allFields.has(name) ||\n\t\t\t\t\t(data.branches && ['variant', 'variants'].includes(name)) ||\n\t\t\t\t\treservedEdgeNames.includes(name)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(`Relation name collision \"${name}\"`)\n\t\t\t\tvalidatePath(edge, storedTier)\n\t\t\t\t// A selected through relation reads the junction's rows: it is a first use.\n\t\t\t\tif ('base' in edge.from) ready(edge.from.junction.table)\n\t\t\t})\n\t\t\tObject.defineProperty(view, name, {\n\t\t\t\tenumerable: true,\n\t\t\t\tget: () => {\n\t\t\t\t\tcheck()\n\t\t\t\t\treturn edge\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tdeclarations[source] = Object.freeze(view)\n\t}\n\tObject.freeze(declarations)\n\tconst used = new Set<string>()\n\t// First use of a table runs its own checks. Its edges validate as they are read.\n\tfunction use(name: string): void {\n\t\tif (used.has(name) || !names.includes(name)) return\n\t\tready(name)\n\t\tused.add(name)\n\t}\n\tconst internal: RegistryMetadata = { metadata, declarations }\n\tconst helpers: Record<\n\t\tstring,\n\t\t{\n\t\t\tfilters<F extends Record<string, GenericValidator>>(contract: FilterContract<F>): KType\n\t\t\tpaginationOpts(selection: SelectionMask, options?: PaginationValidatorOptions): KType\n\t\t\tpageDto(selection: SelectionMask, groups?: GroupSelection): KType\n\t\t}\n\t> = {}\n\tfor (const table of names) {\n\t\t// k records are immutable and their native validators memoised, so a repeated request reuses\n\t\t// the boundary it built the first time.\n\t\tconst pages = new Map<string, KType>()\n\t\tconst options = new Map<string, KType>()\n\t\thelpers[table] = {\n\t\t\tfilters<F extends Record<string, GenericValidator>>(contract: FilterContract<F>) {\n\t\t\t\tuse(table)\n\t\t\t\tif (metadata[table].branches)\n\t\t\t\t\tthrow new Error('Shared scalar contracts do not support variant tables')\n\t\t\t\tfor (const [field, expected] of Object.entries(contract.native)) {\n\t\t\t\t\tconst actual = metadata[table].fields[field]\n\t\t\t\t\tif (\n\t\t\t\t\t\t!actual ||\n\t\t\t\t\t\tJSON.stringify(nativeJson(actual)) !== JSON.stringify(expected.json) ||\n\t\t\t\t\t\t(actual.isOptional === 'optional') !== expected.optional\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(`Shared filter field mismatch \"${field}\"`)\n\t\t\t\t}\n\t\t\t\treturn nativePagination().extend({\n\t\t\t\t\tfilters: contract.schema.optional(),\n\t\t\t\t\torder: k.enum(['asc', 'desc']).optional(),\n\t\t\t\t})\n\t\t\t},\n\t\t\tpaginationOpts(selection: SelectionMask, settings?: PaginationValidatorOptions): KType {\n\t\t\t\tuse(table)\n\t\t\t\tassertSelection(selection)\n\t\t\t\tconst key = JSON.stringify([selection, settings?.validator ?? null])\n\t\t\t\tlet result = options.get(key)\n\t\t\t\tif (!result) {\n\t\t\t\t\tresult = nativePagination().extend({\n\t\t\t\t\t\tfilters: relationFilterSchema(\n\t\t\t\t\t\t\tfilterGrammar(internal, table, selection),\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tsettings,\n\t\t\t\t\t\t).optional(),\n\t\t\t\t\t\torder: k.enum(['asc', 'desc']).optional(),\n\t\t\t\t\t})\n\t\t\t\t\toptions.set(key, result)\n\t\t\t\t}\n\t\t\t\treturn result\n\t\t\t},\n\t\t\tpageDto(selection: SelectionMask, groups: GroupSelection = {}): KType {\n\t\t\t\tuse(table)\n\t\t\t\tassertSelection(selection)\n\t\t\t\tassertGroups(internal, table, groups)\n\t\t\t\tconst key = JSON.stringify([selection, groups])\n\t\t\t\tlet result = pages.get(key)\n\t\t\t\tif (!result) {\n\t\t\t\t\tresult = pageResult(rowSchema(internal, table, selection, 0, groups))\n\t\t\t\t\tpages.set(key, result)\n\t\t\t\t}\n\t\t\t\treturn result\n\t\t\t},\n\t\t}\n\t}\n\n\tlet identity: string | undefined\n\tconst tableEntries = new Map<string, unknown[]>()\n\t// Stable, collision-free canonical metadata encoding. It is an identity, not a secret/hash.\n\t// Computed on first read; it requires and validates every table and edge.\n\tfunction registryIdentity(): string {\n\t\tfor (const name of names) use(name)\n\t\tfor (const check of throughPending) check()\n\t\treturn JSON.stringify([\n\t\t\t2,\n\t\t\tObject.keys(metadata)\n\t\t\t\t.sort((a, b) => a.localeCompare(b))\n\t\t\t\t.map(tableEntry),\n\t\t\tObject.keys(declarations)\n\t\t\t\t.sort((a, b) => a.localeCompare(b))\n\t\t\t\t.map((source) => sourceEntry(source)),\n\t\t])\n\t}\n\t// The same encoding restricted to the given tables and edges, plus every table\n\t// those edges touch. Engine cursors bind it for exactly what one query uses,\n\t// so a change elsewhere cannot affect them. Validates and materializes only that.\n\tfunction scopedIdentity(\n\t\ttables: readonly string[],\n\t\tedges: readonly (readonly [source: string, name: string])[],\n\t): string {\n\t\tconst reached = new Set<string>()\n\t\tconst chosen = new Map<string, Set<string>>()\n\t\tfor (const name of tables) {\n\t\t\tif (!names.includes(name)) throw new Error('Unknown query table')\n\t\t\treached.add(name)\n\t\t}\n\t\tfor (const [source, name] of edges) {\n\t\t\tif (!Object.hasOwn(declarations, source) || !Object.hasOwn(declarations[source], name))\n\t\t\t\tthrow new Error('Unknown relation')\n\t\t\tconst edge = declarations[source][name]\n\t\t\tfor (const table of [source, edge.target, ...legTables(edge.from), ...legTables(edge.to)])\n\t\t\t\treached.add(table)\n\t\t\tconst selected = chosen.get(source) ?? new Set<string>()\n\t\t\tchosen.set(source, selected.add(name))\n\t\t}\n\t\tfor (const name of reached) use(name)\n\t\treturn JSON.stringify([\n\t\t\t3,\n\t\t\t[...reached].sort((a, b) => a.localeCompare(b)).map(tableEntry),\n\t\t\t[...chosen.keys()]\n\t\t\t\t.sort((a, b) => a.localeCompare(b))\n\t\t\t\t.map((source) => sourceEntry(source, chosen.get(source))),\n\t\t])\n\t}\n\tfunction sourceEntry(source: string, only?: ReadonlySet<string>): unknown[] {\n\t\treturn [\n\t\t\tsource,\n\t\t\tObject.keys(declarations[source])\n\t\t\t\t.filter((name) => !only || only.has(name))\n\t\t\t\t.sort((a, b) => a.localeCompare(b))\n\t\t\t\t.map((name) => {\n\t\t\t\t\tconst edge = declarations[source][name]\n\t\t\t\t\treturn [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tedge.cardinality,\n\t\t\t\t\t\tedge.target,\n\t\t\t\t\t\tserializeLeg(edge.from),\n\t\t\t\t\t\tserializeLeg(edge.to),\n\t\t\t\t\t]\n\t\t\t\t}),\n\t\t]\n\t}\n\tfunction tableEntry(name: string): unknown[] {\n\t\tlet entry = tableEntries.get(name)\n\t\tif (!entry) {\n\t\t\tconst data = metadata[name]\n\t\t\tentry = [\n\t\t\t\tname,\n\t\t\t\tObject.entries(data.fields)\n\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t.map(([field, validator]) => [field, validator.isOptional, nativeJson(validator)]),\n\t\t\t\tdata.branches\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tdata.branches.discriminator,\n\t\t\t\t\t\t\tObject.entries(data.branches.options)\n\t\t\t\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t\t\t\t.map(([tag, branch]) => [\n\t\t\t\t\t\t\t\t\ttag,\n\t\t\t\t\t\t\t\t\tObject.entries(branch.fields)\n\t\t\t\t\t\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t\t\t\t\t\t.map(([field, validator]) => [\n\t\t\t\t\t\t\t\t\t\t\tfield,\n\t\t\t\t\t\t\t\t\t\t\tvalidator.isOptional,\n\t\t\t\t\t\t\t\t\t\t\tnativeJson(validator),\n\t\t\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t]\n\t\t\t\t\t: null,\n\t\t\t\tdata.indexes,\n\t\t\t\tcanonicalNative(nativeJson(data.dto.validator)),\n\t\t\t\t...(Object.keys(data.fieldGroups).length ? [data.fieldGroups] : []),\n\t\t\t\t...(data.searchIndexes.length ? [{ searchIndexes: data.searchIndexes }] : []),\n\t\t\t]\n\t\t\ttableEntries.set(name, entry)\n\t\t}\n\t\treturn entry\n\t}\n\t// SAFETY: helpers are assembled for every validated literal table and mask; schemas derive matching native fields/public DTOs.\n\tconst registry = Object.freeze({\n\t\tget identity() {\n\t\t\treturn (identity ??= registryIdentity())\n\t\t},\n\t\tversion: 1,\n\t\ttables: Object.freeze(helpers),\n\t}) as RelationRegistry<Tables, D>\n\tconst snapshots: Record<string, RelationTableMetadata> = {}\n\tfor (const name of names) {\n\t\tlet snapshot: RelationTableMetadata | undefined\n\t\tObject.defineProperty(snapshots, name, {\n\t\t\tenumerable: true,\n\t\t\tget: () => {\n\t\t\t\tuse(name)\n\t\t\t\treturn (snapshot ??= snapshotTable(metadata[name]))\n\t\t\t},\n\t\t})\n\t}\n\tregistries.set(registry, Object.freeze({ tables: Object.freeze(snapshots), declarations }))\n\t// convex-helpers reads schema.tables[table].indexes live. Supply a genuine\n\t// private Convex schema whose only purpose is stable stream index metadata.\n\tconst streamTables: Record<string, TableDefinition> = {}\n\tfor (const name of names) {\n\t\tlet table: TableDefinition | undefined\n\t\tObject.defineProperty(streamTables, name, {\n\t\t\tenumerable: true,\n\t\t\tget: () => {\n\t\t\t\tuse(name)\n\t\t\t\treturn (table ??= streamTable(metadata[name]))\n\t\t\t},\n\t\t})\n\t}\n\texecutorRegistries.set(registry, {\n\t\tinternal,\n\t\tnativeTables: Object.freeze(nativeTables),\n\t\tstreamSchema: defineSchema(Object.freeze(streamTables)),\n\t\tuse,\n\t\tscopedIdentity,\n\t})\n\treturn registry\n}\n\n/** Runs every deferred registration check now, for example in a test that should fail CI. */\nexport function verifyRelations(registry: RelationRegistryIdentity): void {\n\tif (!executorRegistries.has(registry)) throw new Error('Unknown relation registry')\n\tvoid registry.identity\n}\n\n/**\n * A table entry with field groups: whole stored fields a query may request beside the public DTO.\n * Every other member reads through to `table`, so its boundaries stay lazy.\n */\nexport function withFieldGroups<\n\tT extends RelationTable,\n\tconst G extends Readonly<Record<string, readonly string[]>>,\n>(table: T, fieldGroups: G): T & { readonly fieldGroups: G } {\n\t// Copied and frozen per table: later edits to the caller's map or arrays cannot reach the engine.\n\t// SAFETY: the copy has exactly the caller's keys and field-name arrays, so it is a G.\n\tconst groups = Object.freeze(\n\t\tObject.fromEntries(\n\t\t\tObject.entries(fieldGroups).map(([group, fields]) => [group, Object.freeze([...fields])]),\n\t\t),\n\t) as G\n\tconst view = new Proxy(table, {\n\t\tget: (target, key) => (key === 'fieldGroups' ? groups : memberOf(target, key)),\n\t\thas: (target, key) => key === 'fieldGroups' || key in target,\n\t\tgetOwnPropertyDescriptor: (target, key) =>\n\t\t\tkey === 'fieldGroups'\n\t\t\t\t? { value: groups, enumerable: true, configurable: true, writable: false }\n\t\t\t\t: Object.getOwnPropertyDescriptor(target, key),\n\t})\n\t// SAFETY: the proxy answers fieldGroups itself and forwards every other member to `table`.\n\treturn view as T & { readonly fieldGroups: G }\n}\n\n/** Internal owned executor bridge. Source ownership is checked once by each engine. */\nexport function getRelationExecutor(registry: RelationRegistryIdentity) {\n\tconst owned = executorRegistries.get(registry)\n\tif (!owned) throw new Error('Unknown relation registry')\n\tconst assertSchema = (tables: Readonly<Record<string, TableDefinition>>) => {\n\t\tconst names = Object.keys(owned.nativeTables)\n\t\tif (\n\t\t\tnames.length !== Reflect.ownKeys(tables).length ||\n\t\t\tnames.some((name) => {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(tables, name)\n\t\t\t\treturn (\n\t\t\t\t\t!descriptor || !('value' in descriptor) || descriptor.value !== owned.nativeTables[name]\n\t\t\t\t)\n\t\t\t})\n\t\t)\n\t\t\tthrow new Error('Native schema/table ownership disagrees with relation registry')\n\t}\n\tconst branchValidators = new WeakMap<object, { validator: KType; fieldKeys: readonly string[] }>()\n\tconst projectionKeys = new WeakMap<KObject<any>, readonly string[]>()\n\tconst groupDtos = new WeakMap<KObject<any>, Map<string, KObject<any>>>()\n\tconst scalarFields = new Map<string, FieldSchemas>()\n\tconst grammars = new Map<string, FilterGrammar>()\n\tconst filterNodes = new WeakMap<FilterGrammar, Map<number, KType>>()\n\tfunction validateDocument(table: string, row: Record<string, Value>): void {\n\t\towned!.use(table)\n\t\tconst data = owned!.internal.metadata[table]\n\t\tif (!data) throw new Error('Unknown query table')\n\t\tif (!data.branches) return\n\t\tconst tag = row[data.branches.discriminator]\n\t\tconst branch =\n\t\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Native discriminator admission precedes the captured branch parser.\n\t\t\ttypeof tag === 'string' && Object.hasOwn(data.branches.options, tag)\n\t\t\t\t? data.branches.options[tag]\n\t\t\t\t: undefined\n\t\tif (!branch) throw new Error('Invalid variant document')\n\t\tlet cached = branchValidators.get(branch)\n\t\tconst fieldKeys = cached?.fieldKeys ?? Object.keys(branch.fields)\n\t\tconst entries: [string, Value | undefined][] = []\n\t\t// Snapshot ownership before reading getters, as filter().map() did.\n\t\tfor (const key of fieldKeys) if (Object.hasOwn(row, key)) entries.push([key, undefined])\n\t\tfor (const entry of entries) entry[1] = row[entry[0]]\n\t\tconst values = Object.fromEntries(entries)\n\t\tif (!cached) {\n\t\t\tcached = { validator: kFromNative(v.object(branch.fields)), fieldKeys }\n\t\t\tbranchValidators.set(branch, cached)\n\t\t}\n\t\tschemaOf(cached.validator).parse(values)\n\t}\n\treturn Object.freeze({\n\t\tstreamSchema: owned.streamSchema,\n\t\tscopedIdentity: owned.scopedIdentity,\n\t\tgroups(table: string, groups: GroupSelection) {\n\t\t\towned.use(table)\n\t\t\treturn assertGroups(owned.internal, table, groups)\n\t\t},\n\t\tvalidateDocument,\n\t\tassertSchema,\n\t\tpagination(table: string) {\n\t\t\towned.use(table)\n\t\t\tconst internal = owned.internal\n\t\t\tfunction grammar(name: string, depth: number, tag?: string): FilterGrammar {\n\t\t\t\tconst grammarKey = JSON.stringify([name, depth, tag ?? null])\n\t\t\t\tconst cached = grammars.get(grammarKey)\n\t\t\t\tif (cached) return cached\n\t\t\t\tconst data = internal.metadata[name]\n\t\t\t\tif (!data) throw new Error('Unknown query table')\n\t\t\t\tconst cacheKey = JSON.stringify([name, tag ?? null])\n\t\t\t\tlet fields = scalarFields.get(cacheKey)\n\t\t\t\tif (!fields) {\n\t\t\t\t\tfields = {}\n\t\t\t\t\tfor (const [name, validator] of Object.entries(\n\t\t\t\t\t\ttag === undefined ? data.fields : data.branches!.options[tag].fields,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// Unsupported stored containers are not scalar-queryable. No validators\n\t\t\t\t\t\t// are reconstructed from JSON; these are the actual native validators.\n\t\t\t\t\t\tif (scalarValidator(validator))\n\t\t\t\t\t\t\tfields[name] = schemaOf(scalarPredicateSchema(validator)).optional()\n\t\t\t\t\t}\n\t\t\t\t\tscalarFields.set(cacheKey, fields)\n\t\t\t\t}\n\t\t\t\tconst result: FilterGrammar = {\n\t\t\t\t\tfields,\n\t\t\t\t\tvariants:\n\t\t\t\t\t\tdata.branches && tag === undefined && depth < 4\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tdiscriminator: data.branches.discriminator,\n\t\t\t\t\t\t\t\t\toptions: Object.fromEntries(\n\t\t\t\t\t\t\t\t\t\tObject.keys(data.branches.options).map((tag) => [\n\t\t\t\t\t\t\t\t\t\t\ttag,\n\t\t\t\t\t\t\t\t\t\t\tgrammar(name, depth + 1, tag),\n\t\t\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\trelations: depth >= 4 ? {} : relationGrammars(name, depth),\n\t\t\t\t}\n\t\t\t\tgrammars.set(grammarKey, result)\n\t\t\t\treturn result\n\t\t\t}\n\t\t\t// A filter that names a relation is a use of that edge and its target.\n\t\t\tfunction relationGrammars(name: string, depth: number): FilterGrammar['relations'] {\n\t\t\t\tconst relations: FilterGrammar['relations'] = {}\n\t\t\t\tfor (const edge of Object.keys(internal.declarations[name] ?? {})) {\n\t\t\t\t\tlet relation: FilterGrammar['relations'][string] | undefined\n\t\t\t\t\tObject.defineProperty(relations, edge, {\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tget: () => {\n\t\t\t\t\t\t\tif (!relation) {\n\t\t\t\t\t\t\t\tconst declaration = internal.declarations[name][edge]\n\t\t\t\t\t\t\t\towned!.use(declaration.target)\n\t\t\t\t\t\t\t\trelation = Object.freeze({\n\t\t\t\t\t\t\t\t\tcardinality: declaration.cardinality,\n\t\t\t\t\t\t\t\t\ttarget: grammar(declaration.target, depth + 1),\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn relation\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn Object.freeze(relations)\n\t\t\t}\n\t\t\treturn nativePagination().extend({\n\t\t\t\tfilters: lazyRelationFilterSchema(grammar(table, 0), filterNodes).optional(),\n\t\t\t\torder: k.enum(['asc', 'desc']).optional(),\n\t\t\t})\n\t\t},\n\t\tselect(table: string, selection: SelectionMask) {\n\t\t\towned.use(table)\n\t\t\tassertSelection(selection)\n\t\t\tfunction visit(table: string, selected: SelectionMask, depth: number): void {\n\t\t\t\tif (!Object.hasOwn(owned!.internal.metadata, table)) throw new Error('Unknown query table')\n\t\t\t\tfor (const [name, mask] of Object.entries(selected)) {\n\t\t\t\t\tconst edge = owned!.internal.declarations[table]?.[name]\n\t\t\t\t\tif (!edge || depth >= 4)\n\t\t\t\t\t\tthrow new Error(`Unknown or too deep relation \"${table}.${name}\"`)\n\t\t\t\t\tif (mask !== true) visit(edge.target, mask, depth + 1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tvisit(table, selection, 0)\n\t\t},\n\t\tproject(\n\t\t\ttable: string,\n\t\t\trow: Record<string, Value>,\n\t\t\teligible: () => boolean,\n\t\t\tgroups: readonly string[] = [],\n\t\t) {\n\t\t\tif (!eligible()) return null\n\t\t\towned.use(table)\n\t\t\tconst data = owned.internal.metadata[table]\n\t\t\tif (!data) throw new Error('Unknown query table')\n\t\t\tconst branch = data.branches\n\t\t\t\t? data.branches.options[String(row[data.branches.discriminator])]\n\t\t\t\t: undefined\n\t\t\tif (data.branches && !branch) throw new Error('Invalid variant document')\n\t\t\tconst projection = data.dto\n\t\t\tconst found: KType | undefined =\n\t\t\t\tbranch?.dto ??\n\t\t\t\t(projection instanceof KDiscriminatedUnion\n\t\t\t\t\t? projectionBranch(projection, data.branches!.discriminator, row)\n\t\t\t\t\t: projection)\n\t\t\tif (!(found instanceof KObject)) throw new Error('Invalid variant DTO')\n\t\t\tlet dto: KObject<any> = found\n\t\t\tif (groups.length) {\n\t\t\t\tlet variants = groupDtos.get(dto)\n\t\t\t\tif (!variants) {\n\t\t\t\t\tvariants = new Map()\n\t\t\t\t\tgroupDtos.set(dto, variants)\n\t\t\t\t}\n\t\t\t\tconst key = JSON.stringify([...groups].sort())\n\t\t\t\tlet composed = variants.get(key)\n\t\t\t\tif (!composed) {\n\t\t\t\t\tcomposed = dto.extend(\n\t\t\t\t\t\tgroupValidators(\n\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\tgroups,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tdata.branches ? String(row[data.branches.discriminator]) : undefined,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\tvariants.set(key, composed)\n\t\t\t\t}\n\t\t\t\tdto = composed\n\t\t\t}\n\t\t\tvalidateDocument(table, row)\n\t\t\tlet keys = projectionKeys.get(dto)\n\t\t\tif (!keys) {\n\t\t\t\tkeys = Object.keys(dto.shape)\n\t\t\t\tprojectionKeys.set(dto, keys)\n\t\t\t}\n\t\t\t// The strict DTO remains the authority. Pick its fields before parsing,\n\t\t\t// matching table projection without spreading any storage-only fields.\n\t\t\treturn dto.parse(\n\t\t\t\tObject.fromEntries(\n\t\t\t\t\tkeys.filter((key) => Object.hasOwn(row, key)).map((key) => [key, row[key]]),\n\t\t\t\t),\n\t\t\t)\n\t\t},\n\t})\n}\n/** Internal compiler/engine adapter. Registry identity alone cannot forge a registry. */\nexport function getRelationMetadata(registry: RelationRegistryIdentity): RelationMetadata {\n\tconst metadata = registries.get(registry)\n\tif (!metadata) throw new Error('Unknown relation registry')\n\treturn metadata\n}\n\n/** Stored-side registration data: what edge validation needs from a target table. */\ninterface StoredTier extends Pick<TableMetadata, 'fields' | 'branches' | 'allFields'> {\n\tcapturedIndexes: readonly { name: string; fields: string[] }[]\n\tsearchIndexList: SearchIndexMetadata[]\n}\ninterface StoredCapture extends StoredTier {\n\tschema: RelationTable['schema']\n}\ninterface BoundaryCapture {\n\tdto: KObject<any> | KDiscriminatedUnion<string, any>\n}\n\n/** One table as declared: its native table and field-name skeleton are read on first use. */\ninterface TableSource {\n\treadonly table: RelationTable\n\tnative(): TableDefinition\n\tskeleton(): NativeSkeleton | undefined\n}\n\nfunction tableSource(table: RelationTable): TableSource {\n\treturn {\n\t\ttable,\n\t\tnative: once(() => {\n\t\t\t// Field-group declarations are checked first, by descriptor, before any member is read.\n\t\t\tdeclaredGroups(table)\n\t\t\tconst native = table.table\n\t\t\t// Rejects accessors before native export or conversion. Stored parsers never run.\n\t\t\tpreflightNative(native)\n\t\t\treturn native\n\t\t}),\n\t\tskeleton: once(() => schemaSkeleton(table)),\n\t}\n}\n\n/** The DTO with its id: an immutable `k` object or variant union that only validates. */\nfunction captureBoundary(table: RelationTable): BoundaryCapture {\n\tconst dto = table.dto(true)\n\tif (!(dto instanceof KObject) && !(dto instanceof KDiscriminatedUnion))\n\t\tthrow new Error('Expected object or discriminated union DTO')\n\tif (!valuePreserving(dto)) throw new Error('Unsupported DTO schema: DTOs only validate')\n\treturn { dto }\n}\n\nfunction exportStored(nativeTable: TableDefinition): NativeTableExport {\n\tconst exported = nativeTableExport(nativeTable)\n\tassertNativeValidation(exported.documentType)\n\treturn exported\n}\n\nfunction captureIndexes(\n\texported: NativeTableExport,\n): Pick<StoredTier, 'capturedIndexes' | 'searchIndexList'> {\n\tconst captured = indexExport().parse(exported)\n\treturn {\n\t\tsearchIndexList: [\n\t\t\t...captured.searchIndexes.map((index) => ({ ...index, staged: false })),\n\t\t\t...captured.stagedSearchIndexes.map((index) => ({\n\t\t\t\t...index,\n\t\t\t\tstaged: true,\n\t\t\t})),\n\t\t].map((index) =>\n\t\t\tObject.freeze({\n\t\t\t\tname: index.indexDescriptor,\n\t\t\t\tsearchField: index.searchField,\n\t\t\t\tfilterFields: Object.freeze([...index.filterFields].sort()),\n\t\t\t\tstaged: index.staged,\n\t\t\t}),\n\t\t),\n\t\tcapturedIndexes: captured.indexes.map((index) => ({\n\t\t\tname: index.indexDescriptor,\n\t\t\tfields: [...index.fields],\n\t\t})),\n\t}\n}\n\nfunction assertActiveIndexes(tier: Pick<StoredTier, 'capturedIndexes'>): void {\n\tif (tier.capturedIndexes.some((index) => index.fields.length === 0))\n\t\tthrow new Error('Invalid empty active index')\n}\n\n/** The stored tier alone: native and stored preflight, export, stored normalization, indexes. */\nfunction captureStoredTier(\n\tname: string,\n\ttable: RelationTable,\n\tnativeTable: TableDefinition,\n): StoredCapture {\n\tconst schema = table.schema\n\tconst exported = exportStored(nativeTable)\n\tconst tier = {\n\t\t...normalizeStored(name, schema, exported.documentType),\n\t\t...captureIndexes(exported),\n\t\tschema,\n\t}\n\tassertActiveIndexes(tier)\n\treturn tier\n}\n\n/** One table's full registration preflight, capture and normalization, in the\n * original check order; run on first use. */\nfunction materializeTable(\n\tname: string,\n\ttable: RelationTable,\n\tnativeTable: TableDefinition,\n): TableMetadata {\n\tconst schema = table.schema\n\tconst boundary = captureBoundary(table)\n\tconst exported = exportStored(nativeTable)\n\tconst normalized = normalizeTable(name, schema, boundary.dto, exported.documentType)\n\treturn completeTable(table, { ...normalized, ...captureIndexes(exported) }, boundary)\n}\n\n/** Completes a table whose stored tier already passed; only DTO-side checks remain. */\nfunction finishTable(name: string, table: RelationTable, stored: StoredCapture): TableMetadata {\n\tconst boundary = captureBoundary(table)\n\t// Use the same stored schema the stored tier normalized; k records are immutable.\n\tconst { schema, ...tier } = stored\n\tconst dtos = checkDtoBoundary(name, schema, boundary.dto)\n\treturn completeTable(table, { ...tier, branches: attachDtos(tier.branches, dtos) }, boundary)\n}\n\nfunction completeTable(\n\ttable: RelationTable,\n\tnormalized: StoredTier,\n\t{ dto }: BoundaryCapture,\n): TableMetadata {\n\tassertNativeValidation(nativeJson(dto.validator))\n\tconst fieldGroups: Record<string, readonly string[]> = Object.create(null)\n\tconst groupFields: Record<string, Readonly<Record<string, GenericValidator>>> = Object.create(\n\t\tnull,\n\t)\n\tconst definitions = declaredGroups(table)\n\tconst used = new Set<string>()\n\tconst publicBranches: readonly KType[] = dto instanceof KObject ? [dto] : dto.options\n\tfor (const [group, members] of Object.entries(definitions)) {\n\t\tif (!group || ['__proto__', 'constructor', 'prototype'].includes(group))\n\t\t\tthrow new Error('Invalid field groups')\n\t\tfor (const field of members) {\n\t\t\tif (\n\t\t\t\t!normalized.allFields.has(field) ||\n\t\t\t\tfield.startsWith('_') ||\n\t\t\t\tused.has(field) ||\n\t\t\t\tpublicBranches.some(\n\t\t\t\t\t(branch) => !(branch instanceof KObject) || Object.hasOwn(branch.shape, field),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new Error('Conflicting or incompatible field groups')\n\t\t\tconst validators = normalized.branches\n\t\t\t\t? Object.values(normalized.branches.options)\n\t\t\t\t\t\t.map((branch) => branch.fields[field])\n\t\t\t\t\t\t.filter((validator) => validator !== undefined)\n\t\t\t\t: [normalized.fields[field]]\n\t\t\tif (\n\t\t\t\t!validators.every(\n\t\t\t\t\t(validator) =>\n\t\t\t\t\t\tsameNative(nativeJson(validator), nativeJson(validators[0])) &&\n\t\t\t\t\t\tvalidator.isOptional === validators[0].isOptional,\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new Error('Conflicting or incompatible field groups')\n\t\t\tused.add(field)\n\t\t}\n\t\tfieldGroups[group] = Object.freeze([...members].sort())\n\t\tfor (const [tag, fields] of normalized.branches\n\t\t\t? Object.entries(normalized.branches.options).map(\n\t\t\t\t\t([tag, branch]) => [tag, branch.fields] as const,\n\t\t\t\t)\n\t\t\t: [[null, normalized.fields] as const]) {\n\t\t\tgroupFields[JSON.stringify([group, tag])] = Object.freeze(\n\t\t\t\tObject.fromEntries(\n\t\t\t\t\tmembers\n\t\t\t\t\t\t.filter((field) => Object.hasOwn(fields, field))\n\t\t\t\t\t\t.map((field) => [field, fields[field]]),\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\tassertActiveIndexes(normalized)\n\tconst { capturedIndexes, searchIndexList, fields, branches, allFields } = normalized\n\t// The first locale-aware comparison loads collation data (~4 ms without JIT);\n\t// only identity, snapshots and the engine need these orders.\n\tlet indexes: { name: string; fields: string[] }[] | undefined\n\tlet searchIndexes: readonly SearchIndexMetadata[] | undefined\n\tconst metadata: TableMetadata = {\n\t\tfields,\n\t\tallFields,\n\t\tcapturedIndexes,\n\t\tsearchIndexList,\n\t\tget indexes() {\n\t\t\treturn (indexes ??= [...capturedIndexes].sort((a, b) => a.name.localeCompare(b.name)))\n\t\t},\n\t\tget searchIndexes() {\n\t\t\treturn (searchIndexes ??= Object.freeze(\n\t\t\t\t[...searchIndexList].sort((a, b) => a.name.localeCompare(b.name)),\n\t\t\t))\n\t\t},\n\t\tdto,\n\t\tfieldGroups: Object.freeze(fieldGroups),\n\t\tgroupFields: Object.freeze(groupFields),\n\t\tgroupSchemas: new Map(),\n\t}\n\tif (branches) metadata.branches = branches\n\treturn metadata\n}\n\nfunction streamTable(data: TableMetadata): TableDefinition {\n\tconst table: TableDefinition = defineTable({})\n\tfor (const index of data.indexes) {\n\t\tconst [first, ...rest] = index.fields\n\t\tif (first === undefined) throw new Error('Invalid empty active index')\n\t\ttable.index(index.name, [first, ...rest])\n\t}\n\tconst indexes = Object.getOwnPropertyDescriptor(table, 'indexes')!.value\n\tfor (const index of indexes) {\n\t\tObject.freeze(index.fields)\n\t\tObject.freeze(index)\n\t}\n\tObject.freeze(indexes)\n\tObject.freeze(table)\n\treturn table\n}\n\ninterface NativeSkeleton {\n\t/** Every stored and system field name, for name-collision checks. */\n\tfields: readonly string[]\n\t/** Names `r.<table>` exposes: all fields, or a variant's common fields. */\n\tcommon: readonly string[]\n\tvariant: boolean\n\tdiscriminator?: string\n\tbranches?: readonly (readonly [string, readonly string[]])[]\n}\n/** Field names of an object or variant table from its `k` schema, without building any native\n * validator for an object table. A variant table compares its branch fields natively, as\n * normalizeStored does, for the common-field rule. Anything unexpected returns undefined, and the\n * table then materializes when its references are first requested.\n */\nfunction schemaSkeleton(table: RelationTable): NativeSkeleton | undefined {\n\tconst system = ['_id', '_creationTime']\n\tconst schema = table.schema\n\tif (schema instanceof KObject) {\n\t\tconst names = [...new Set([...Object.keys(schema.shape), ...system])]\n\t\treturn { fields: names, common: names, variant: false }\n\t}\n\tif (!(schema instanceof KDiscriminatedUnion)) return undefined\n\tconst discriminator = schema.discriminator\n\tconst branches: (readonly [string, readonly string[]])[] = []\n\tconst objects: KObject<any>[] = []\n\tfor (const option of optionsOf(schema)) {\n\t\tif (!(option instanceof KObject)) return undefined\n\t\tconst tag = literalOf(option.shape[discriminator])\n\t\tif (tag === undefined) return undefined\n\t\tobjects.push(option)\n\t\tbranches.push([tag, [...new Set([...Object.keys(option.shape), ...system])]])\n\t}\n\tif (!objects.length) return undefined\n\t// The common fields compare branch validators natively, so they are computed only when\n\t// `r.<table>` is first read; branch scopes and name checks need field names alone.\n\tconst common = once(() => {\n\t\tconst stored = objects.map((option) => {\n\t\t\tconst { _id, _creationTime, ...fields } = option.validator.fields\n\t\t\treturn fields\n\t\t})\n\t\t// Mirrors normalizeTable: system fields are identical in every branch.\n\t\treturn [\n\t\t\t...new Set([\n\t\t\t\t...Object.keys(stored[0]).filter(\n\t\t\t\t\t(key) =>\n\t\t\t\t\t\tstored.every((member) => Object.hasOwn(member, key)) &&\n\t\t\t\t\t\t(key === discriminator ||\n\t\t\t\t\t\t\tstored.every((member) => commonCompatible(member[key], stored[0][key]))),\n\t\t\t\t),\n\t\t\t\t...system,\n\t\t\t]),\n\t\t]\n\t})\n\treturn {\n\t\tfields: [...new Set(branches.flatMap(([, fields]) => fields))],\n\t\tget common() {\n\t\t\treturn common()\n\t\t},\n\t\tvariant: true,\n\t\tdiscriminator,\n\t\tbranches,\n\t}\n}\n\nfunction once<T>(compute: () => T): () => T {\n\tlet result: { value: T } | { error: unknown } | undefined\n\treturn () => {\n\t\tif (!result)\n\t\t\ttry {\n\t\t\t\tresult = { value: compute() }\n\t\t\t} catch (error) {\n\t\t\t\tresult = { error }\n\t\t\t}\n\t\tif ('error' in result) throw result.error\n\t\treturn result.value\n\t}\n}\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Registration preflight inspects descriptors before parsing can invoke caller getters; typed parsing follows immediately.\nfunction assertGroupData(value: unknown, depth = 0): void {\n\tif (depth > 16) throw new Error('Invalid field groups')\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Descriptor preflight must distinguish primitive leaves without invoking caller-owned accessors.\n\tif (value === null || typeof value !== 'object') return\n\tconst prototype = Object.getPrototypeOf(value)\n\tif (prototype !== Object.prototype && prototype !== null && prototype !== Array.prototype)\n\t\tthrow new Error('Invalid field groups')\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key)!\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Own keys are classified by representation before any value is read.\n\t\tif (typeof key !== 'string' || !('value' in descriptor)) throw new Error('Invalid field groups')\n\t\tassertGroupData(descriptor.value, depth + 1)\n\t}\n}\n\nfunction assertGroups(\n\tregistry: RegistryMetadata,\n\ttable: string,\n\tinput: GroupSelection,\n): GroupSelection {\n\tassertGroupData(input)\n\tfunction visit(table: string, input: GroupSelection, depth: number): GroupSelection {\n\t\tconst parsed = groupSelection().parse(input)\n\t\tconst data = registry.metadata[table]\n\t\tif (!data) throw new Error('Unknown query table')\n\t\tfor (const name of Object.keys(parsed.fieldGroups ?? {}))\n\t\t\tif (!Object.hasOwn(data.fieldGroups, name)) throw new Error('Unknown field group')\n\t\tconst relations: Record<string, GroupSelection> = {}\n\t\tfor (const [name, nested] of Object.entries(parsed.relations ?? {})) {\n\t\t\tconst edge = registry.declarations[table]?.[name]\n\t\t\tif (!edge || depth >= 4) throw new Error('Invalid field group relation')\n\t\t\t// SAFETY: the recursive visitor validates each unknown node before using it.\n\t\t\trelations[name] = visit(edge.target, nested as GroupSelection, depth + 1)\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tfieldGroups: Object.freeze(parsed.fieldGroups ?? {}),\n\t\t\trelations: Object.freeze(relations),\n\t\t})\n\t}\n\treturn visit(table, input, 0)\n}\n\nfunction groupValidators(\n\tdata: TableMetadata,\n\tgroups: readonly string[],\n\tmodes?: GroupSelection['fieldGroups'],\n\ttag?: string,\n): FieldSchemas {\n\tconst fields: FieldSchemas = {}\n\tfor (const name of groups) {\n\t\tconst key = JSON.stringify([name, tag ?? null])\n\t\tif (!Object.hasOwn(data.groupFields, key)) throw new Error('Unknown field group')\n\t\tlet schema = data.groupSchemas.get(key)\n\t\tif (!schema) {\n\t\t\tschema = kObjectFromNative(data.groupFields[key])\n\t\t\tdata.groupSchemas.set(key, schema)\n\t\t}\n\t\tfor (const [field, validator] of Object.entries<KType>(schema.shape))\n\t\t\tfields[field] = modes?.[name] === 'if-permitted' ? schemaOf(validator).optional() : validator\n\t}\n\treturn fields\n}\n\nfunction scalarValidator(validator: GenericValidator): boolean {\n\treturn (\n\t\t['id', 'string', 'float64', 'int64', 'boolean', 'null', 'literal'].includes(validator.kind) ||\n\t\t(validator.kind === 'union' && validator.members.every(scalarValidator))\n\t)\n}\n\nfunction assertSelection(selection: SelectionMask): void {\n\tconst pending: {\n\t\tvalue: SelectionMask\n\t\tdepth: number\n\t\tancestors: readonly SelectionMask[]\n\t}[] = [{ value: selection, depth: 0, ancestors: [] }]\n\tlet nodes = 0\n\twhile (pending.length) {\n\t\tconst { value, depth, ancestors } = pending.pop()!\n\t\tif (++nodes > 256 || depth > 4 || ancestors.includes(value))\n\t\t\tthrow new Error('Selection cycle or depth/node budget exceeded')\n\t\tconst prototype = Object.getPrototypeOf(value)\n\t\tif (prototype !== Object.prototype && prototype !== null) throw new Error('Invalid selection')\n\t\tconst keys = Reflect.ownKeys(value)\n\t\tif (keys.length + nodes + pending.length > 256)\n\t\t\tthrow new Error('Selection node budget exceeded')\n\t\tfor (const key of keys) {\n\t\t\tconst property = Object.getOwnPropertyDescriptor(value, key)!\n\t\t\tif (!property.enumerable || !('value' in property) || String(key) !== key)\n\t\t\t\tthrow new Error('Invalid selection property')\n\t\t\tif (property.value !== true)\n\t\t\t\tpending.push({\n\t\t\t\t\tvalue: property.value,\n\t\t\t\t\tdepth: depth + 1,\n\t\t\t\t\tancestors: [...ancestors, value],\n\t\t\t\t})\n\t\t\telse if (++nodes > 256) throw new Error('Selection node budget exceeded')\n\t\t}\n\t}\n}\nfunction base(leg: Leg): AnyField {\n\treturn 'base' in leg ? leg.base : leg\n}\nfunction makeEdge(\n\ttarget: string,\n\tcardinality: 'one' | 'many',\n\tspec: { from: Leg; to: Leg },\n\town: Set<AnyField>,\n): AnyEdge {\n\tfor (const leg of [spec.from, spec.to]) {\n\t\tif (!own.has(base(leg)) || ('base' in leg && (!throughRefs.has(leg) || !own.has(leg.junction))))\n\t\t\tthrow new Error('Foreign registry or invalid field reference')\n\t}\n\tif (base(spec.to).table !== target) throw new Error('Wrong relation target table')\n\tconst result: AnyEdge = Object.freeze({\n\t\t[edgeBrand]: true as const,\n\t\tsource: base(spec.from).table,\n\t\ttarget,\n\t\tcardinality,\n\t\tfrom: spec.from,\n\t\tto: spec.to,\n\t\tsourceGuard: base(spec.from).guard,\n\t\ttargetGuard: base(spec.to).guard,\n\t\tjunctionGuard: junctionGuard(spec.from, spec.to),\n\t\tsourceMember: memberRefs.get(base(spec.from)),\n\t\ttargetMember: memberRefs.get(base(spec.to)),\n\t})\n\tedgeRefs.add(result)\n\treturn result\n}\nfunction junctionGuard(from: Leg, to: Leg): RelationGuard | undefined {\n\tconst left = 'base' in from ? from.junction.guard : undefined\n\tconst right = 'base' in to ? to.junction.guard : undefined\n\tif (left && right && (left.discriminator !== right.discriminator || left.tag !== right.tag))\n\t\tthrow new Error('Contradictory junction scopes')\n\treturn left ?? right\n}\nfunction nativeIdMembers(validator: GenericValidator): string[] | null {\n\tif (validator.kind === 'id') return [validator.tableName]\n\tif (validator.kind === 'null') return []\n\tif (validator.kind !== 'union') return null\n\tconst members = validator.members.map(nativeIdMembers)\n\treturn members.some((member) => member === null)\n\t\t? null\n\t\t: [...new Set(members.flatMap((member) => member!))].sort()\n}\nfunction compatible(left: GenericValidator, right: GenericValidator): boolean {\n\tconst leftDomain = domain(left)\n\treturn leftDomain.length > 0 && JSON.stringify(leftDomain) === JSON.stringify(domain(right))\n}\nfunction domain(validator: GenericValidator): string[] {\n\tif (validator.kind === 'union') return [...new Set(validator.members.flatMap(domain))].sort()\n\tif (validator.kind === 'null') return []\n\tif (!['id', 'string', 'float64', 'int64', 'boolean', 'literal'].includes(validator.kind))\n\t\tthrow new Error('Unsupported relation field kind')\n\treturn [JSON.stringify(nativeJson(validator))]\n}\n/** Structural leg checks; registration runs these eagerly. */\nfunction assertPathLegs(edge: AnyEdge): void {\n\tconst from = edge.from\n\tconst to = edge.to\n\tif ('base' in from !== 'base' in to) throw new Error('Both relation legs must use through')\n\tif ('base' in from && 'base' in to && from.junction.table !== to.junction.table)\n\t\tthrow new Error('Different junction tables')\n}\n/** Field-type and index checks; these run on first use of the edge's source table\n * and need only the stored tier of the tables they reach. */\nfunction validatePath(edge: AnyEdge, stored: (table: string) => StoredTier): void {\n\tconst from = edge.from\n\tconst to = edge.to\n\tassertPathLegs(edge)\n\tif ('base' in from && 'base' in to) {\n\t\tthroughChecks.get(from)!()\n\t\tthroughChecks.get(to)!()\n\t\trequireIndex(\n\t\t\tstored(from.junction.table),\n\t\t\tfrom.junction.table,\n\t\t\tfrom.junction.field,\n\t\t\tedge.junctionGuard,\n\t\t)\n\t\trequireIndex(stored(edge.target), edge.target, to.base.field, edge.targetGuard)\n\t\treturn\n\t}\n\tif (!compatible(refs.get(base(from))!(), refs.get(base(to))!()))\n\t\tthrow new Error('Incompatible relation field types')\n\trequireIndex(stored(edge.target), edge.target, base(to).field, edge.targetGuard)\n}\nfunction requireIndex(\n\tdata: Pick<StoredTier, 'capturedIndexes'>,\n\ttable: string,\n\tfield: string,\n\tguard?: RelationGuard,\n): void {\n\tif (\n\t\tfield !== '_id' &&\n\t\t!data.capturedIndexes.some((index) => {\n\t\t\tconst position = index.fields.indexOf(field)\n\t\t\treturn (\n\t\t\t\tposition >= 0 &&\n\t\t\t\tindex.fields.slice(0, position).every((key) => key === guard?.discriminator)\n\t\t\t)\n\t\t})\n\t)\n\t\tthrow new Error(`No active index begins with or has a guarded prefix for \"${table}.${field}\"`)\n}\nfunction legTables(leg: Leg): string[] {\n\treturn 'base' in leg ? [leg.base.table, leg.junction.table] : [leg.table]\n}\nfunction serializeLeg(leg: Leg): unknown[] {\n\treturn 'base' in leg\n\t\t? [\n\t\t\t\tleg.base.table,\n\t\t\t\tleg.base.field,\n\t\t\t\tleg.base.guard ?? null,\n\t\t\t\tleg.junction.table,\n\t\t\t\tleg.junction.field,\n\t\t\t\tleg.junction.guard ?? null,\n\t\t\t]\n\t\t: memberRefs.has(leg)\n\t\t\t? [leg.table, leg.field, leg.guard ?? null, memberRefs.get(leg)]\n\t\t\t: [leg.table, leg.field, leg.guard ?? null]\n}\n/** Validate selected scalar kinds now, in the same order the predicate compiler visits them. */\nfunction assertFilterScalar(validator: GenericValidator): void {\n\tif (validator.kind === 'union') {\n\t\tfor (const member of validator.members) assertFilterScalar(member)\n\t} else if (!scalarValidator(validator))\n\t\tthrow new Error(`Unsupported scalar filter kind \"${validator.kind}\"`)\n}\n\nfunction filterGrammar(\n\tregistry: RegistryMetadata,\n\ttable: string,\n\tselection: SelectionMask,\n\tdepth: number = 0,\n\ttag?: string,\n): FilterGrammar {\n\tconst fields: FieldSchemas = {}\n\tconst relations: FilterGrammar['relations'] = {}\n\tconst data = registry.metadata[table]\n\tconst variants: Record<string, FilterGrammar> = {}\n\tfor (const [key, mask] of Object.entries(selection)) {\n\t\tif (key === 'variants' && mask !== true && data.branches && tag === undefined) {\n\t\t\tif (depth >= 4) throw new Error('Invalid variant selection')\n\t\t\tfor (const [tag, selected] of Object.entries(mask)) {\n\t\t\t\tif (!Object.hasOwn(data.branches.options, tag) || selected === true)\n\t\t\t\t\tthrow new Error('Unknown variant filter selection')\n\t\t\t\tconst common = Object.fromEntries(\n\t\t\t\t\tObject.entries(selection).filter(([key]) => key !== 'variants'),\n\t\t\t\t)\n\t\t\t\tvariants[tag] = filterGrammar(registry, table, { ...common, ...selected }, depth + 1, tag)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tconst validator = (tag === undefined ? data.fields : data.branches!.options[tag].fields)[key]\n\t\tconst edge = registry.declarations[table]?.[key]\n\t\tif (mask === true && validator) {\n\t\t\tassertFilterScalar(validator)\n\t\t\tdeferFilterField(fields, key, () => schemaOf(scalarPredicateSchema(validator)).optional())\n\t\t} else if (mask !== true && edge && depth < 4)\n\t\t\trelations[key] = {\n\t\t\t\tcardinality: edge.cardinality,\n\t\t\t\ttarget: filterGrammar(registry, edge.target, mask, depth + 1),\n\t\t\t}\n\t\telse throw new Error(`Invalid relation filter selection \"${table}.${key}\"`)\n\t}\n\treturn {\n\t\tfields,\n\t\trelations,\n\t\tvariants:\n\t\t\tdata.branches && tag === undefined\n\t\t\t\t? { discriminator: data.branches.discriminator, options: variants }\n\t\t\t\t: undefined,\n\t}\n}\nfunction rowSchema(\n\tregistry: RegistryMetadata,\n\ttable: string,\n\tselection: SelectionMask,\n\tdepth: number = 0,\n\tgroups: GroupSelection = {},\n): KType {\n\tconst relationFields: Record<string, KType> = {}\n\tfor (const [name, mask] of Object.entries(selection)) {\n\t\tconst edge = registry.declarations[table]?.[name]\n\t\tif (!edge || depth >= 4) throw new Error(`Unknown or too deep relation \"${table}.${name}\"`)\n\t\tlet target = rowSchema(\n\t\t\tregistry,\n\t\t\tedge.target,\n\t\t\tmask === true ? {} : mask,\n\t\t\tdepth + 1,\n\t\t\tgroups.relations?.[name],\n\t\t)\n\t\tif (edge.targetGuard) {\n\t\t\tif (!(target instanceof KDiscriminatedUnion)) throw new Error('Invalid target scope')\n\t\t\tconst guard = edge.targetGuard\n\t\t\ttarget = optionsOf(target).find(\n\t\t\t\t(option) =>\n\t\t\t\t\toption instanceof KObject && literalOf(option.shape[guard.discriminator]) === guard.tag,\n\t\t\t)!\n\t\t}\n\t\trelationFields[name] =\n\t\t\tedge.cardinality === 'one' ? schemaOf(target).nullable() : pageResult(target)\n\t}\n\tconst data = registry.metadata[table]\n\tconst dto = data.dto\n\tfunction compose(dto: KObject<any>, tag?: string) {\n\t\tconst selected = { ...relationFields }\n\t\tfor (const name of Object.keys(selected)) {\n\t\t\tconst edge = registry.declarations[table][name]\n\t\t\tif (edge.sourceGuard && tag !== edge.sourceGuard.tag && edge.cardinality === 'one')\n\t\t\t\tselected[name] = k.null()\n\t\t}\n\t\treturn dto.extend({\n\t\t\t...groupValidators(data, Object.keys(groups.fieldGroups ?? {}), groups.fieldGroups, tag),\n\t\t\t...selected,\n\t\t})\n\t}\n\tif (data.branches) {\n\t\tif (!(dto instanceof KDiscriminatedUnion)) throw new Error('Invalid variant DTO')\n\t\tconst options = optionsOf(dto).map((option) => {\n\t\t\tif (!(option instanceof KObject)) throw new Error('Invalid variant DTO')\n\t\t\tconst tag = literalOf(option.shape[data.branches!.discriminator])\n\t\t\tif (tag === undefined) throw new Error('Invalid variant tag')\n\t\t\treturn compose(option, tag)\n\t\t})\n\t\tconst [first, ...rest] = options\n\t\treturn k.discriminatedUnion(data.branches.discriminator, [first, ...rest])\n\t}\n\tif (!(dto instanceof KObject)) throw new Error('Expected object DTO')\n\treturn compose(dto)\n}\n\nfunction normalizeTable(\n\tname: string,\n\tschema: RelationTable['schema'],\n\tdto: BoundaryCapture['dto'],\n\tdocument: ValidatorJSON,\n): Pick<TableMetadata, 'fields' | 'branches' | 'allFields'> {\n\tconst dtos = checkDtoBoundary(name, schema, dto)\n\tconst stored = normalizeStored(name, schema, document)\n\treturn { ...stored, branches: attachDtos(stored.branches, dtos) }\n}\n/** Boundary-kind agreement between the stored schema and the DTO. Returns the\n * DTO variant branches, which normalization attaches to the stored branches. */\nfunction checkDtoBoundary(\n\tname: string,\n\tschema: RelationTable['schema'],\n\tdto: BoundaryCapture['dto'],\n): VariantBranches | undefined {\n\tif (schema instanceof KObject && dto instanceof KObject) return undefined\n\tif (!(schema instanceof KDiscriminatedUnion) || !(dto instanceof KDiscriminatedUnion))\n\t\tthrow new Error(`Expected matching discriminated union boundaries \"${name}\"`)\n\tconst discriminator = schema.discriminator\n\tif (dto.discriminator !== discriminator) throw new Error('DTO discriminator mismatch')\n\tconst documents = variantOptions(schema, discriminator),\n\t\tdtos = variantOptions(dto, discriminator)\n\tif (Object.keys(documents).sort().join('\\0') !== Object.keys(dtos).sort().join('\\0'))\n\t\tthrow new Error('DTO variant tags mismatch')\n\treturn dtos\n}\n/** Captured DTO branch objects by tag. */\ntype VariantBranches = Readonly<Record<string, KObject<any>>>\nfunction attachDtos(\n\tbranches: TableMetadata['branches'],\n\tdtos: VariantBranches | undefined,\n): TableMetadata['branches'] {\n\tif (!branches) return undefined\n\tconst options: NonNullable<TableMetadata['branches']>['options'] = Object.create(null)\n\tfor (const [tag, branch] of Object.entries(branches.options))\n\t\toptions[tag] = { fields: branch.fields, dto: dtos?.[tag] }\n\treturn { discriminator: branches.discriminator, options }\n}\nfunction variantOptions(\n\tunion: KDiscriminatedUnion<string, any>,\n\tdiscriminator: string,\n): Record<string, KObject<any>> {\n\tconst result: Record<string, KObject<any>> = Object.create(null)\n\tfor (const option of optionsOf(union)) {\n\t\tif (!(option instanceof KObject)) throw new Error('Variant branches must be objects')\n\t\tconst tag = literalOf(option.shape[discriminator])\n\t\tif (tag === undefined || Object.hasOwn(result, tag))\n\t\t\tthrow new Error('Variant tags must be unique required string literals')\n\t\tresult[tag] = option\n\t}\n\tif (Object.keys(result).length === 0) throw new Error('Expected at least one variant branch')\n\treturn result\n}\n/** Stored fields from the stored schema, checked against the native document. */\nfunction normalizeStored(\n\tname: string,\n\tschema: RelationTable['schema'],\n\tdocument: ValidatorJSON,\n): Pick<TableMetadata, 'fields' | 'branches' | 'allFields'> {\n\tif (schema instanceof KObject) {\n\t\tconst fields = schema.validator.fields\n\t\tassertStoredDocument(name, fields, document)\n\t\treturn { fields, allFields: new Set(Object.keys(fields)) }\n\t}\n\tif (!(schema instanceof KDiscriminatedUnion))\n\t\tthrow new Error(`Expected matching discriminated union boundaries \"${name}\"`)\n\tconst discriminator = schema.discriminator\n\tconst documents = variantOptions(schema, discriminator)\n\tconst branches: NonNullable<TableMetadata['branches']> = {\n\t\tdiscriminator,\n\t\toptions: Object.create(null),\n\t}\n\tconst stored: GenericValidator[] = []\n\tfor (const [tag, object] of Object.entries(documents)) {\n\t\tconst fields = object.validator.fields\n\t\tconst { _id, _creationTime, ...storage } = fields\n\t\t// The union comparison below checks each branch's stored fields.\n\t\tassertSystemFields(name, fields)\n\t\tstored.push(v.object(storage))\n\t\tbranches.options[tag] = { fields }\n\t}\n\tif (!sameNative(document, nativeJson(v.union(...stored))))\n\t\tthrow new Error(`Native stored document disagrees with boundary \"${name}\"`)\n\tconst members = Object.values(branches.options).map((branch) => branch.fields)\n\tconst fields: Record<string, GenericValidator> = {}\n\tfor (const key of Object.keys(members[0])) {\n\t\tif (!members.every((member) => Object.hasOwn(member, key))) continue\n\t\tif (\n\t\t\tkey !== discriminator &&\n\t\t\t!members.every((member) => commonCompatible(member[key], members[0][key]))\n\t\t)\n\t\t\tcontinue\n\t\tconst validators = members.map((member) => member[key])\n\t\tconst union = v.union(...validators)\n\t\tfields[key] = validators.some((validator) => validator.isOptional === 'optional')\n\t\t\t? v.optional(union)\n\t\t\t: union\n\t}\n\treturn {\n\t\tfields,\n\t\tbranches,\n\t\tallFields: new Set(members.flatMap((member) => Object.keys(member))),\n\t}\n}\nfunction commonCompatible(left: GenericValidator, right: GenericValidator): boolean {\n\ttry {\n\t\treturn compatible(left, right)\n\t} catch {\n\t\treturn sameNative(nativeJson(left), nativeJson(right))\n\t}\n}\n\ninterface NativeTableExport {\n\tindexes: { indexDescriptor: string; fields: string[] }[]\n\tdocumentType: ValidatorJSON\n}\n// Capture the installed peer's prototypes before accepting caller-owned instances.\n// Native json getters are trusted only on these prototypes; own accessors and\n// custom prototypes fail closed without evaluating them.\nconst nativePrototypes = new Map<object, PropertyDescriptorMap>()\nfor (const sample of [\n\tdefineTable(v.object({})),\n\tv.id('sample'),\n\tv.null(),\n\tv.number(),\n\tv.int64(),\n\tv.commitTs(),\n\tv.boolean(),\n\tv.string(),\n\tv.bytes(),\n\tv.any(),\n\tv.object({}),\n\tv.literal('sample'),\n\tv.array(v.string()),\n\tv.record(v.string(), v.string()),\n\tv.union(v.string(), v.null()),\n]) {\n\tlet prototype = Object.getPrototypeOf(sample)\n\twhile (prototype && prototype !== Object.prototype) {\n\t\tif (!nativePrototypes.has(prototype))\n\t\t\tnativePrototypes.set(prototype, Object.getOwnPropertyDescriptors(prototype))\n\t\tprototype = Object.getPrototypeOf(prototype)\n\t}\n}\n\n/** Registration-only descriptor preflight; caller accessors are never invoked. */\nfunction preflightNative(table: TableDefinition): void {\n\tconst seen = new Set<object>()\n\tconst active = new Set<object>()\n\t// oxlint-disable-next-line anti-slop/no-object-parameters -- This descriptor-only boundary admits arbitrary native graph nodes without invoking them.\n\tfunction visit(object: object, depth: number, trusted = false): void {\n\t\tif (active.has(object)) throw new Error('Unsupported cyclic native schema')\n\t\tif (seen.has(object)) return\n\t\tif (depth > 64 || seen.size >= 8192) throw new Error('Native schema graph budget exceeded')\n\t\tseen.add(object)\n\t\tactive.add(object)\n\t\tconst prototype = Object.getPrototypeOf(object)\n\t\tconst inherited = prototype && nativePrototypes.get(prototype)\n\t\tif (\n\t\t\tprototype !== null &&\n\t\t\tprototype !== Object.prototype &&\n\t\t\tprototype !== Array.prototype &&\n\t\t\t!inherited\n\t\t)\n\t\t\tthrow new Error('Unsupported native schema prototype')\n\t\tif (Object.getOwnPropertySymbols(object).length)\n\t\t\tthrow new Error('Unsupported native schema symbol')\n\t\tconst keys = Object.getOwnPropertyNames(object)\n\t\tconst values = keys.map((key) => Object.getOwnPropertyDescriptor(object, key)!)\n\t\tif (\n\t\t\t!trusted &&\n\t\t\tvalues.some((property) => !('value' in property) || property.value instanceof Function)\n\t\t)\n\t\t\tthrow new Error('Unsupported native schema accessor or method')\n\t\tif (inherited) {\n\t\t\t// Compare the trusted prototype before any native export can invoke it.\n\t\t\tconst currentKeys = Object.getOwnPropertyNames(prototype)\n\t\t\tif (\n\t\t\t\tcurrentKeys.length !== Object.getOwnPropertyNames(inherited).length ||\n\t\t\t\tcurrentKeys.some((key) => {\n\t\t\t\t\tconst current = Object.getOwnPropertyDescriptor(prototype, key)!\n\t\t\t\t\tconst before = Object.getOwnPropertyDescriptor(inherited, key)?.value\n\t\t\t\t\treturn (\n\t\t\t\t\t\t!before ||\n\t\t\t\t\t\t!Object.is(current.value, before.value) ||\n\t\t\t\t\t\tcurrent.get !== before.get ||\n\t\t\t\t\t\tcurrent.set !== before.set\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t)\n\t\t\t\tthrow new Error('Unsupported native schema prototype mutation')\n\t\t\tvisit(prototype, depth + 1, true)\n\t\t}\n\t\tif (!trusted)\n\t\t\tfor (const property of values) {\n\t\t\t\tif (property.value !== null && Object(property.value) === property.value)\n\t\t\t\t\tvisit(property.value, depth + 1)\n\t\t\t}\n\t\tactive.delete(object)\n\t}\n\tvisit(table, 0)\n}\n\nfunction nativeTableExport(table: TableDefinition): NativeTableExport {\n\t// SAFETY: Convex exposes export at runtime but strips its internal signature from declarations.\n\treturn (table as TableDefinition & { export(): NativeTableExport }).export()\n}\nfunction nativeJson(validator: GenericValidator): ValidatorJSON {\n\t// SAFETY: native validators expose converter metadata at runtime; Convex strips json from declarations.\n\treturn (validator as GenericValidator & { json: ValidatorJSON }).json\n}\n\nfunction assertNativeValidation(value: JSONValue): void {\n\tif (value === null || Object(value) !== value) return\n\t// SAFETY: native converter metadata contains only JSON containers and primitives.\n\tconst container = value as { [key: string]: JSONValue }\n\tif (container.type === 'any') throw new Error('Unsupported native validation form')\n\tfor (const child of Object.values(container)) assertNativeValidation(child)\n}\n\nfunction assertStoredDocument(\n\ttable: string,\n\tfields: Record<string, GenericValidator>,\n\tdocument: ValidatorJSON,\n): void {\n\tconst { _id, _creationTime, ...stored } = fields\n\tassertSystemFields(table, fields)\n\tif (!sameNative(document, nativeJson(v.object(stored))))\n\t\tthrow new Error(`Native stored document disagrees with boundary \"${table}\"`)\n}\nfunction assertSystemFields(table: string, fields: Record<string, GenericValidator>): void {\n\tconst { _id, _creationTime } = fields\n\tif (\n\t\t!_id ||\n\t\t!_creationTime ||\n\t\t!sameNative(nativeJson(_id), nativeJson(v.id(table))) ||\n\t\t!sameNative(nativeJson(_creationTime), nativeJson(v.number())) ||\n\t\t_id.isOptional !== 'required' ||\n\t\t_creationTime.isOptional !== 'required'\n\t)\n\t\tthrow new Error(`Native stored document disagrees with boundary \"${table}\"`)\n}\n\nfunction snapshotTable(data: TableMetadata): RelationTableMetadata {\n\tconst fields: Record<string, RelationFieldMetadata> = {}\n\tfor (const [field, validator] of Object.entries(data.fields))\n\t\tfields[field] = Object.freeze({\n\t\t\tkind: validator.kind,\n\t\t\toptional: validator.isOptional === 'optional',\n\t\t\tnullable: hasNull(validator),\n\t\t\tidTables: Object.freeze(idTables(validator)),\n\t\t\tnative: frozenNative(nativeJson(validator)),\n\t\t})\n\treturn Object.freeze({\n\t\tfieldGroups: data.fieldGroups,\n\t\tsearchIndexes: data.searchIndexes,\n\t\tfields: Object.freeze(fields),\n\t\tvariant: data.branches\n\t\t\t? Object.freeze({\n\t\t\t\t\tdiscriminator: data.branches.discriminator,\n\t\t\t\t\ttags: Object.freeze(Object.keys(data.branches.options)),\n\t\t\t\t})\n\t\t\t: undefined,\n\t\tindexes: Object.freeze(\n\t\t\tdata.indexes.map((index) =>\n\t\t\t\tObject.freeze({\n\t\t\t\t\tname: index.name,\n\t\t\t\t\tfields: Object.freeze([...index.fields]),\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t})\n}\nfunction hasNull(validator: GenericValidator): boolean {\n\treturn (\n\t\tvalidator.kind === 'null' || (validator.kind === 'union' && validator.members.some(hasNull))\n\t)\n}\nfunction idTables(validator: GenericValidator): string[] {\n\treturn validator.kind === 'id'\n\t\t? [validator.tableName]\n\t\t: validator.kind === 'union'\n\t\t\t? [...new Set(validator.members.flatMap(idTables))].sort()\n\t\t\t: []\n}\nfunction frozenNative(native: ValidatorJSON): Readonly<ValidatorJSON> {\n\tconst snapshot = structuredClone(native)\n\tconst pending: JSONValue[] = [snapshot]\n\twhile (pending.length) {\n\t\tconst next = pending.pop()!\n\t\tif (Object(next) !== next) continue\n\t\t// SAFETY: native JSON metadata contains ordinary arrays/objects; the boxing test excludes primitives.\n\t\tconst container = next as JSONValue[] | { [key: string]: JSONValue }\n\t\tObject.freeze(container)\n\t\tpending.push(...Object.values(container))\n\t}\n\treturn snapshot\n}\n\n// oxlint-disable-next-line anti-slop/no-unknown-returns -- The field-group view forwards any member unchanged.\nfunction memberOf(target: RelationTable, key: PropertyKey): unknown {\n\t// oxlint-disable-next-line anti-slop/no-reflect-get -- The table itself is the receiver, so its private state stays reachable.\n\treturn Reflect.get(target, key, target)\n}\n\n/** The options of a discriminated union schema, as `k` records. */\nfunction optionsOf(union: KType): readonly KType[] {\n\t// SAFETY: callers pass k.discriminatedUnion records, whose options are k schemas.\n\treturn (union as KDiscriminatedUnion<string, readonly KType[]>).options\n}\n\n/** A table export's index lists, read with unknown export keys stripped. */\nconst indexExport = once(() => {\n\tconst searchIndex = k\n\t\t.object({\n\t\t\tindexDescriptor: k.string(),\n\t\t\tsearchField: k.string(),\n\t\t\tfilterFields: k.array(k.string()),\n\t\t})\n\t\t.strip()\n\treturn k\n\t\t.object({\n\t\t\tsearchIndexes: k.array(searchIndex),\n\t\t\tstagedSearchIndexes: k.array(searchIndex),\n\t\t\tindexes: k.array(\n\t\t\t\tk.object({ indexDescriptor: k.string(), fields: k.array(k.string()) }).strip(),\n\t\t\t),\n\t\t})\n\t\t.strip()\n})\n\nconst groupDefinitions = once(() => k.record(k.string(), k.array(k.string()).min(1)))\n\n/** A table's own field-group data, read by descriptor so no caller accessor runs. */\nfunction declaredGroups(table: RelationTable): Readonly<Record<string, string[]>> {\n\tconst descriptor = Object.getOwnPropertyDescriptor(table, 'fieldGroups')\n\tif ((!descriptor && 'fieldGroups' in table) || (descriptor && !('value' in descriptor)))\n\t\tthrow new Error('Invalid field groups')\n\tconst declared: unknown = descriptor?.value ?? {}\n\tassertGroupData(declared)\n\treturn groupDefinitions().parse(declared)\n}\n\nconst groupSelection = once(() =>\n\tk.object({\n\t\tfieldGroups: k.record(k.string(), k.enum(['required', 'if-permitted'])).optional(),\n\t\trelations: k.record(k.string(), k.any()).optional(),\n\t}),\n)\n\n/** Ops that change a value; a DTO only validates. */\nconst VALUE_CHANGING_OPS: ReadonlySet<string> = new Set([\n\t'default',\n\t'trim',\n\t'lower',\n\t'upper',\n\t'overwrite',\n\t'transform',\n\t'pipe',\n\t'strip',\n])\n\n/** Whether a schema only validates, at every depth. */\nfunction valuePreserving(schema: KType): boolean {\n\tlet current = schema\n\twhile (current.prev !== null) {\n\t\tif (VALUE_CHANGING_OPS.has(current.op)) return false\n\t\tcurrent = schemaOf(current.prev)\n\t}\n\tswitch (current.op) {\n\t\tcase 'object':\n\t\t\treturn Object.values(objectFieldsOf(current)).every(valuePreserving)\n\t\tcase 'array':\n\t\t\treturn valuePreserving(schemaOf(current.arg))\n\t\tcase 'record':\n\t\tcase 'union':\n\t\t\treturn membersOf(current).every(valuePreserving)\n\t\tcase 'discriminatedUnion':\n\t\t\treturn optionsOf(schemaOf(current)).every(valuePreserving)\n\t\tdefault:\n\t\t\treturn true\n\t}\n}\n\n/** The string value of a bare `k.literal('...')` field (a description may sit on it). */\nfunction literalOf(field: KType | undefined): string | undefined {\n\tlet current = field\n\twhile (current && current.prev !== null) {\n\t\tif (current.op !== 'describe') return undefined\n\t\tcurrent = schemaOf(current.prev)\n\t}\n\tif (current?.op !== 'literal') return undefined\n\tconst value = current.arg\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- A literal root stores its value as the record argument.\n\treturn typeof value === 'string' ? value : undefined\n}\n\n/** The DTO branch whose literal tag equals the row's discriminator. */\nfunction projectionBranch(\n\tprojection: KDiscriminatedUnion<string, any>,\n\tdiscriminator: string,\n\trow: Record<string, Value>,\n): KType | undefined {\n\treturn optionsOf(projection).find(\n\t\t(option) =>\n\t\t\toption instanceof KObject && literalOf(option.shape[discriminator]) === row[discriminator],\n\t)\n}\n\n/**\n * The `k` schema a stored native validator describes, for whole stored fields (field groups and\n * variant branch documents). Numbers are finite, as v1's conversion required.\n */\nfunction kFromNative(validator: GenericValidator): KType {\n\tconst required = requiredFromNative(validator)\n\treturn validator.isOptional === 'optional' ? schemaOf(required).optional() : required\n}\n\nfunction requiredFromNative(validator: GenericValidator): KType {\n\tswitch (validator.kind) {\n\t\tcase 'id':\n\t\t\treturn k.id(validator.tableName)\n\t\tcase 'string':\n\t\t\treturn k.string()\n\t\tcase 'float64':\n\t\t\treturn k.number().refine(Number.isFinite, 'Invalid input: expected a finite number')\n\t\tcase 'int64':\n\t\t\treturn k.int64()\n\t\tcase 'boolean':\n\t\t\treturn k.boolean()\n\t\tcase 'null':\n\t\t\treturn k.null()\n\t\tcase 'bytes':\n\t\t\treturn k.bytes()\n\t\tcase 'any':\n\t\t\treturn k.any()\n\t\tcase 'literal':\n\t\t\treturn k.literal(validator.value)\n\t\tcase 'array':\n\t\t\treturn k.array(kFromNative(validator.element))\n\t\tcase 'record':\n\t\t\treturn k.record(\n\t\t\t\t// SAFETY: a native record key validator is a string kind, so its k schema is a record key.\n\t\t\t\tschemaOf(kFromNative(validator.key)) as KObjectKey,\n\t\t\t\tkFromNative(validator.value),\n\t\t\t)\n\t\tcase 'object':\n\t\t\treturn kObjectFromNative(validator.fields)\n\t\tcase 'union':\n\t\t\treturn unionOf(validator.members.map(kFromNative))\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported stored field kind \"${validator.kind}\"`)\n\t}\n}\n\nfunction kObjectFromNative(fields: Readonly<Record<string, GenericValidator>>): KObject<any> {\n\tconst out: Record<string, KType> = {}\n\tfor (const [key, validator] of Object.entries(fields)) out[key] = kFromNative(validator)\n\treturn k.object(out)\n}\n\ntype KObjectKey = Parameters<typeof k.record>[0]\n\nfunction objectFieldsOf(root: KType): Readonly<Record<string, KType>> {\n\t// SAFETY: k.object stores its field map as the root argument.\n\treturn root.arg as Readonly<Record<string, KType>>\n}\n\nfunction membersOf(root: KType): readonly KType[] {\n\t// SAFETY: k.record stores its key and value schemas, and k.union its members, as the root argument.\n\treturn root.arg as readonly KType[]\n}\n\nfunction schemaOf(schema: KType | KType['prev'] | KType['arg']): KSchema<any, any, any, any, any> {\n\t// SAFETY: every KType at runtime is a KSchema record created by a k factory.\n\treturn schema as KSchema<any, any, any, any, any>\n}\n"],"mappings":"A,skBA+OA,MAAMA,GAA4B,OAAO,eAAe,EAClDC,EAA2B,OAAO,cAAc,EAwhBhDC,kBAAa,IAAI,QAEjBC,mBAAqB,IAAI,QAczBC,kBAAO,IAAI,QACXC,kBAAa,IAAI,QACjBC,mBAAc,IAAI,QAClBC,kBAAgB,IAAI,QACpBC,mBAAW,IAAI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AAK,QACJ,OAAOA,EAAE,MAAM,EAChB,IAAK,MACJ,OAAOA,EAAE,IAAI,EACd,IAAK,UACJ,OAAOA,EAAE,QAAQ5C,EAAU,KAAK,EACjC,IAAK,QACJ,OAAO4C,EAAE,MAAMsD,EAAYlG,EAAU,OAAO,CAAC,EAC9C,IAAK,SACJ,OAAO4C,EAAE,OAERuD,EAASD,EAAYlG,EAAU,GAAG,CAAC,EACnCkG,EAAYlG,EAAU,KAAK,CAC5B,EACD,IAAK,SACJ,OAAOmL,GAAkBnL,EAAU,MAAM,EAC1C,IAAK,QACJ,OAAOsO,EAAQtO,EAAU,QAAQ,IAAIkG,CAAW,CAAC,EAClD,QACC,MAAU,MAAM,kCAAkClG,EAAU,KAAK,EAAE,CACrE,CACD,CAEA,SAASmL,GAAkB,EAAkE,CAC5F,IAAMoD,EAA6B,CAAC,EACpC,IAAK,GAAM,CAACrN,EAAKlB,KAAc,OAAO,QAAQT,CAAM,EAAG,EAAI2B,GAAOgF,EAAYlG,CAAS,EACvF,OAAO4C,EAAE,OAAO2L,CAAG,CACpB,CAIA,SAASL,GAAe,EAA8C,CAErE,OAAOM,EAAK,GACb,CAEA,SAASL,GAAU,EAA+B,CAEjD,OAAOK,EAAK,GACb,CAEA,SAASrI,EAAS,EAAgF,CAEjG,OAAO0C,CACR,C"}
@@ -1,18 +1,15 @@
1
1
  import { ErrorFactory } from "./errors.mjs";
2
- //#region src/state-machine.d.ts
3
2
  /**
4
3
  * Typed transition legality from a constants tuple (the conventions.md
5
4
  * vocabulary pattern). The transition map is typed against the tuple, so an
6
5
  * invalid literal cannot compile; `assert` throws via the injected
7
6
  * ErrorFactory so it drops straight into a command guard.
8
7
  */
9
- declare function createStateMachine<const State extends string>(states: readonly State[], transitions: Partial<Record<NoInfer<State>, readonly NoInfer<State>[]>>, options?: {
8
+ export declare function createStateMachine<const State extends string>(states: readonly State[], transitions: Partial<Record<NoInfer<State>, readonly NoInfer<State>[]>>, options?: {
10
9
  errors?: ErrorFactory;
11
10
  }): Readonly<{
12
11
  states: readonly State[];
13
12
  can: (from: State, to: State) => boolean;
14
13
  assert: (from: State, to: State) => void;
15
14
  }>;
16
- //#endregion
17
- export { createStateMachine };
18
15
  //# sourceMappingURL=state-machine.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"state-machine.mjs","names":[],"sources":["../src/state-machine.ts"],"sourcesContent":["import { defaultErrors, type ErrorFactory } from './errors'\n\n/**\n * Typed transition legality from a constants tuple (the conventions.md\n * vocabulary pattern). The transition map is typed against the tuple, so an\n * invalid literal cannot compile; `assert` throws via the injected\n * ErrorFactory so it drops straight into a command guard.\n */\nexport function createStateMachine<const State extends string>(\n\tstates: readonly State[],\n\t// NoInfer: the vocabulary comes from the tuple; a stray literal in the\n\t// transition map must fail to compile, not widen the state union.\n\ttransitions: Partial<Record<NoInfer<State>, readonly NoInfer<State>[]>>,\n\toptions?: { errors?: ErrorFactory },\n) {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst legal = new Map<State, ReadonlySet<State>>(\n\t\tstates.map((state) => [state, new Set(transitions[state] ?? [])]),\n\t)\n\n\tfunction can(from: State, to: State): boolean {\n\t\treturn legal.get(from)?.has(to) ?? false\n\t}\n\n\tfunction assert(from: State, to: State): void {\n\t\tif (!can(from, to)) {\n\t\t\terrors.throw({\n\t\t\t\tcode: 'INVALID_TRANSITION',\n\t\t\t\tmessage: `Transition \"${from}\" → \"${to}\" is not legal`,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn Object.freeze({ states, can, assert })\n}\n"],"mappings":"6CAQA,SAAgB,EACf,EAGA,EACA,EACC,CACD,IAAM,EAAS,GAAS,QAAU,EAC5B,EAAQ,IAAI,IACjB,EAAO,IAAK,GAAU,CAAC,EAAO,IAAI,IAAI,EAAY,IAAU,CAAC,CAAC,CAAC,CAAC,CACjE,EAEA,SAAS,EAAI,EAAa,EAAoB,CAC7C,OAAO,EAAM,IAAI,CAAI,CAAC,EAAE,IAAI,CAAE,GAAK,EACpC,CAEA,SAAS,EAAO,EAAa,EAAiB,CACxC,EAAI,EAAM,CAAE,GAChB,EAAO,MAAM,CACZ,KAAM,qBACN,QAAS,eAAe,EAAK,OAAO,EAAG,eACxC,CAAC,CAEH,CAEA,OAAO,OAAO,OAAO,CAAE,SAAQ,MAAK,QAAO,CAAC,CAC7C"}
1
+ {"version":3,"file":"state-machine.mjs","names":["createStateMachine","errors","options","defaultErrors","legal","states","state","transitions","can","from","to","assert"],"sources":["../src/state-machine.ts"],"sourcesContent":["import { defaultErrors, type ErrorFactory } from './errors'\n\n/**\n * Typed transition legality from a constants tuple (the conventions.md\n * vocabulary pattern). The transition map is typed against the tuple, so an\n * invalid literal cannot compile; `assert` throws via the injected\n * ErrorFactory so it drops straight into a command guard.\n */\nexport function createStateMachine<const State extends string>(\n\tstates: readonly State[],\n\t// NoInfer: the vocabulary comes from the tuple; a stray literal in the\n\t// transition map must fail to compile, not widen the state union.\n\ttransitions: Partial<Record<NoInfer<State>, readonly NoInfer<State>[]>>,\n\toptions?: { errors?: ErrorFactory },\n) {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst legal = new Map<State, ReadonlySet<State>>(\n\t\tstates.map((state) => [state, new Set(transitions[state] ?? [])]),\n\t)\n\n\tfunction can(from: State, to: State): boolean {\n\t\treturn legal.get(from)?.has(to) ?? false\n\t}\n\n\tfunction assert(from: State, to: State): void {\n\t\tif (!can(from, to)) {\n\t\t\terrors.throw({\n\t\t\t\tcode: 'INVALID_TRANSITION',\n\t\t\t\tmessage: `Transition \"${from}\" → \"${to}\" is not legal`,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn Object.freeze({ states, can, assert })\n}\n"],"mappings":"A,6CAQA,SAAgBA,EACf,EAGA,EACA,EACC,CACD,IAAMC,EAASC,GAAS,QAAUC,EAC5BC,EAAQ,IAAI,IACjBC,EAAO,IAAK,GAAU,CAACC,EAAO,IAAI,IAAIC,EAAYD,IAAU,CAAC,CAAC,CAAC,CAAC,CACjE,EAEA,SAASE,EAAI,EAAa,EAAoB,CAC7C,OAAOJ,EAAM,IAAIK,CAAI,CAAC,EAAE,IAAIC,CAAE,GAAK,EACpC,CAEA,SAASC,EAAO,EAAa,EAAiB,CACxCH,EAAIC,EAAMC,CAAE,GAChBT,EAAO,MAAM,CACZ,KAAM,qBACN,QAAS,eAAeQ,EAAK,OAAOC,EAAG,eACxC,CAAC,CAEH,CAEA,OAAO,OAAO,OAAO,CAAE,SAAQ,MAAK,QAAO,CAAC,CAC7C,C"}