cvx-kit 0.1.35 → 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 (327) hide show
  1. package/README.md +92 -49
  2. package/dist/agent-tools.d.mts +21 -25
  3. package/dist/agent-tools.mjs +1 -1
  4. package/dist/agent-tools.mjs.map +1 -1
  5. package/dist/auth.d.mts +20 -14
  6. package/dist/auth.mjs +1 -1
  7. package/dist/auth.mjs.map +1 -1
  8. package/dist/components/approvals/_generated/api.d.mts +4 -5
  9. package/dist/components/approvals/_generated/api.mjs.map +1 -1
  10. package/dist/components/approvals/_generated/component.d.mts +0 -2
  11. package/dist/components/approvals/_generated/dataModel.d.mts +1 -3
  12. package/dist/components/approvals/_generated/server.d.mts +0 -2
  13. package/dist/components/approvals/_generated/server.mjs.map +1 -1
  14. package/dist/components/approvals/audit.d.mts +0 -1
  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 +0 -1
  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 +0 -1
  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 +1 -4
  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 +0 -1
  28. package/dist/components/approvals/functions.mjs.map +1 -1
  29. package/dist/components/approvals/health.d.mts +0 -1
  30. package/dist/components/approvals/health.mjs.map +1 -1
  31. package/dist/components/approvals/requests.d.mts +106 -123
  32. package/dist/components/approvals/requests.mjs +1 -1
  33. package/dist/components/approvals/requests.mjs.map +1 -1
  34. package/dist/components/approvals/schema.d.ts +106 -315
  35. package/dist/components/approvals/schema.js +1 -1
  36. package/dist/components/approvals/validators.d.mts +321 -393
  37. package/dist/components/approvals/validators.mjs +1 -1
  38. package/dist/components/approvals/validators.mjs.map +1 -1
  39. package/dist/components/approvals/workflow.d.mts +0 -1
  40. package/dist/components/approvals/workflow.mjs +1 -1
  41. package/dist/components/approvals/workflow.mjs.map +1 -1
  42. package/dist/components/approvals/workflow_steps.d.mts +1 -2
  43. package/dist/components/approvals/workflow_steps.mjs.map +1 -1
  44. package/dist/components/foundation/_generated/api.d.mts +3 -4
  45. package/dist/components/foundation/_generated/api.mjs.map +1 -1
  46. package/dist/components/foundation/_generated/component.d.mts +0 -2
  47. package/dist/components/foundation/_generated/dataModel.d.mts +1 -3
  48. package/dist/components/foundation/_generated/server.d.mts +0 -2
  49. package/dist/components/foundation/_generated/server.mjs.map +1 -1
  50. package/dist/components/foundation/client.d.mts +0 -1
  51. package/dist/components/foundation/client.mjs +1 -1
  52. package/dist/components/foundation/client.mjs.map +1 -1
  53. package/dist/components/foundation/convex.config.d.mts +0 -2
  54. package/dist/components/foundation/convex.config.mjs.map +1 -1
  55. package/dist/components/foundation/functions.d.mts +0 -1
  56. package/dist/components/foundation/functions.mjs.map +1 -1
  57. package/dist/components/foundation/modules/command/command.d.mts +0 -1
  58. package/dist/components/foundation/modules/command/command.mjs.map +1 -1
  59. package/dist/components/foundation/modules/command/lifecycle.d.mts +0 -2
  60. package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -1
  61. package/dist/components/foundation/modules/observability/observability.d.mts +0 -1
  62. package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
  63. package/dist/components/foundation/modules/query/query.d.mts +0 -1
  64. package/dist/components/foundation/modules/query/query.mjs.map +1 -1
  65. package/dist/components/foundation/operation.d.mts +2 -3
  66. package/dist/components/foundation/operation.mjs.map +1 -1
  67. package/dist/components/foundation/result.d.mts +0 -1
  68. package/dist/components/foundation/result.mjs.map +1 -1
  69. package/dist/components/foundation/schema.d.ts +0 -2
  70. package/dist/components/foundation/telemetry.d.mts +0 -1
  71. package/dist/components/foundation/telemetry.mjs +1 -1
  72. package/dist/components/foundation/telemetry.mjs.map +1 -1
  73. package/dist/contracts.d.mts +2 -2
  74. package/dist/contracts.mjs +1 -1
  75. package/dist/crud.d.mts +93 -97
  76. package/dist/crud.mjs +1 -1
  77. package/dist/crud.mjs.map +1 -1
  78. package/dist/effect.d.mts +2 -3
  79. package/dist/effect.mjs +1 -1
  80. package/dist/errors.d.mts +2 -4
  81. package/dist/errors.mjs +1 -1
  82. package/dist/errors.mjs.map +1 -1
  83. package/dist/filters.d.mts +1 -1
  84. package/dist/filters.mjs +1 -1
  85. package/dist/idempotency.mjs +1 -1
  86. package/dist/index.d.mts +10 -7
  87. package/dist/index.mjs +1 -1
  88. package/dist/json-schema.d.mts +40 -0
  89. package/dist/json-schema.mjs +2 -0
  90. package/dist/json-schema.mjs.map +1 -0
  91. package/dist/k/compile.d.mts +17 -0
  92. package/dist/k/compile.mjs +2 -0
  93. package/dist/k/compile.mjs.map +1 -0
  94. package/dist/k/dates.d.mts +23 -0
  95. package/dist/k/dates.mjs +2 -0
  96. package/dist/k/dates.mjs.map +1 -0
  97. package/dist/k/formats.d.mts +24 -0
  98. package/dist/k/formats.mjs +2 -0
  99. package/dist/k/formats.mjs.map +1 -0
  100. package/dist/k/index.d.mts +32 -0
  101. package/dist/k/index.mjs +2 -0
  102. package/dist/k/index.mjs.map +1 -0
  103. package/dist/k/issues.d.mts +31 -0
  104. package/dist/k/issues.mjs +2 -0
  105. package/dist/k/issues.mjs.map +1 -0
  106. package/dist/k/kinds.d.mts +81 -0
  107. package/dist/k/kinds.mjs +2 -0
  108. package/dist/k/kinds.mjs.map +1 -0
  109. package/dist/k/object.d.mts +43 -0
  110. package/dist/k/object.mjs +2 -0
  111. package/dist/k/object.mjs.map +1 -0
  112. package/dist/k/parse.d.mts +29 -0
  113. package/dist/k/parse.mjs +2 -0
  114. package/dist/k/parse.mjs.map +1 -0
  115. package/dist/k/schema.d.mts +100 -0
  116. package/dist/k/schema.mjs +2 -0
  117. package/dist/k/schema.mjs.map +1 -0
  118. package/dist/k/standard.d.mts +8 -0
  119. package/dist/k/standard.mjs +2 -0
  120. package/dist/k/standard.mjs.map +1 -0
  121. package/dist/k/types.d.mts +64 -0
  122. package/dist/k/types.mjs +1 -0
  123. package/dist/k.d.mts +8 -0
  124. package/dist/k.mjs +1 -0
  125. package/dist/middleware.d.mts +0 -2
  126. package/dist/middleware.mjs +1 -1
  127. package/dist/middleware.mjs.map +1 -1
  128. package/dist/modules/contracts/binding.d.mts +1 -2
  129. package/dist/modules/contracts/binding.mjs.map +1 -1
  130. package/dist/modules/contracts/contract.d.mts +0 -2
  131. package/dist/modules/contracts/contract.mjs.map +1 -1
  132. package/dist/modules/contracts/convex.d.mts +1 -3
  133. package/dist/modules/contracts/convex.mjs.map +1 -1
  134. package/dist/modules/contracts/domain.d.mts +1 -2
  135. package/dist/modules/contracts/domain.mjs.map +1 -1
  136. package/dist/modules/contracts/errors.d.mts +161 -2
  137. package/dist/modules/contracts/errors.mjs +1 -1
  138. package/dist/modules/contracts/errors.mjs.map +1 -1
  139. package/dist/modules/contracts/exposure.d.mts +1 -2
  140. package/dist/modules/contracts/exposure.mjs.map +1 -1
  141. package/dist/modules/contracts/idempotency.d.mts +1 -2
  142. package/dist/modules/contracts/idempotency.mjs +1 -1
  143. package/dist/modules/contracts/idempotency.mjs.map +1 -1
  144. package/dist/modules/contracts/lazy.d.mts +0 -2
  145. package/dist/modules/contracts/lazy.mjs.map +1 -1
  146. package/dist/modules/contracts/standard.d.mts +7 -5
  147. package/dist/modules/contracts/standard.mjs +1 -1
  148. package/dist/modules/contracts/standard.mjs.map +1 -1
  149. package/dist/modules/contracts/workflow.d.mts +1 -2
  150. package/dist/modules/contracts/workflow.mjs.map +1 -1
  151. package/dist/modules/effect/action.d.mts +6 -7
  152. package/dist/modules/effect/action.mjs +1 -1
  153. package/dist/modules/effect/action.mjs.map +1 -1
  154. package/dist/modules/effect/agent-tools.mjs +1 -1
  155. package/dist/modules/effect/api-runtime.d.mts +1 -2
  156. package/dist/modules/effect/api-runtime.mjs +1 -1
  157. package/dist/modules/effect/api-runtime.mjs.map +1 -1
  158. package/dist/modules/effect/api.d.mts +41 -15
  159. package/dist/modules/effect/api.mjs +1 -1
  160. package/dist/modules/effect/api.mjs.map +1 -1
  161. package/dist/modules/effect/auth.d.mts +5 -6
  162. package/dist/modules/effect/auth.mjs +1 -1
  163. package/dist/modules/effect/auth.mjs.map +1 -1
  164. package/dist/modules/effect/client.d.mts +7 -8
  165. package/dist/modules/effect/client.mjs +1 -1
  166. package/dist/modules/effect/command.d.mts +7 -5
  167. package/dist/modules/effect/command.mjs +1 -1
  168. package/dist/modules/effect/command.mjs.map +1 -1
  169. package/dist/modules/effect/crud.d.mts +272 -206
  170. package/dist/modules/effect/crud.mjs +1 -1
  171. package/dist/modules/effect/crud.mjs.map +1 -1
  172. package/dist/modules/effect/domain.d.mts +5 -6
  173. package/dist/modules/effect/domain.mjs.map +1 -1
  174. package/dist/modules/effect/errors.d.mts +4 -2
  175. package/dist/modules/effect/errors.mjs +1 -1
  176. package/dist/modules/effect/errors.mjs.map +1 -1
  177. package/dist/modules/effect/failure-audit.d.mts +2 -2
  178. package/dist/modules/effect/failure-audit.mjs +1 -1
  179. package/dist/modules/effect/failure-audit.mjs.map +1 -1
  180. package/dist/modules/effect/failures.d.mts +1 -2
  181. package/dist/modules/effect/failures.mjs.map +1 -1
  182. package/dist/modules/effect/foundation.d.mts +0 -2
  183. package/dist/modules/effect/foundation.mjs.map +1 -1
  184. package/dist/modules/effect/idempotency.d.mts +2 -3
  185. package/dist/modules/effect/idempotency.mjs +1 -1
  186. package/dist/modules/effect/idempotency.mjs.map +1 -1
  187. package/dist/modules/effect/input.d.mts +10 -0
  188. package/dist/modules/effect/input.mjs +2 -0
  189. package/dist/modules/effect/input.mjs.map +1 -0
  190. package/dist/modules/effect/normalize.d.mts +0 -2
  191. package/dist/modules/effect/normalize.mjs.map +1 -1
  192. package/dist/modules/effect/operation.d.mts +2 -3
  193. package/dist/modules/effect/operation.mjs.map +1 -1
  194. package/dist/modules/effect/query.d.mts +6 -4
  195. package/dist/modules/effect/query.mjs +1 -1
  196. package/dist/modules/effect/query.mjs.map +1 -1
  197. package/dist/modules/effect/schema.d.mts +0 -2
  198. package/dist/modules/effect/schema.mjs.map +1 -1
  199. package/dist/modules/effect/scope.d.mts +0 -2
  200. package/dist/modules/effect/scope.mjs.map +1 -1
  201. package/dist/modules/effect/workflow.d.mts +4 -5
  202. package/dist/modules/effect/workflow.mjs +1 -1
  203. package/dist/modules/effect/workflow.mjs.map +1 -1
  204. package/dist/modules/foundation/foundation.d.mts +4 -5
  205. package/dist/modules/foundation/foundation.mjs +1 -1
  206. package/dist/modules/foundation/foundation.mjs.map +1 -1
  207. package/dist/modules/foundation/operation.d.mts +2 -3
  208. package/dist/modules/foundation/operation.mjs.map +1 -1
  209. package/dist/namespace.d.mts +104 -0
  210. package/dist/namespace.mjs +2 -0
  211. package/dist/namespace.mjs.map +1 -0
  212. package/dist/oxlint/architecture.d.mts +0 -2
  213. package/dist/oxlint/architecture.mjs +1 -1
  214. package/dist/oxlint/architecture.mjs.map +1 -1
  215. package/dist/oxlint/ast.d.mts +16 -8
  216. package/dist/oxlint/ast.mjs +1 -1
  217. package/dist/oxlint/ast.mjs.map +1 -1
  218. package/dist/oxlint/components.d.mts +0 -2
  219. package/dist/oxlint/components.mjs.map +1 -1
  220. package/dist/oxlint/ownership.d.mts +0 -2
  221. package/dist/oxlint/ownership.mjs +1 -1
  222. package/dist/oxlint/ownership.mjs.map +1 -1
  223. package/dist/oxlint/reserved-files.d.mts +0 -2
  224. package/dist/oxlint/reserved-files.mjs +1 -1
  225. package/dist/oxlint/reserved-files.mjs.map +1 -1
  226. package/dist/oxlint.d.mts +0 -2
  227. package/dist/oxlint.mjs +1 -1
  228. package/dist/oxlint.mjs.map +1 -1
  229. package/dist/querying/cursors.d.mts +27 -9
  230. package/dist/querying/cursors.mjs +1 -1
  231. package/dist/querying/cursors.mjs.map +1 -1
  232. package/dist/querying/execution.d.mts +6 -7
  233. package/dist/querying/execution.mjs +1 -1
  234. package/dist/querying/execution.mjs.map +1 -1
  235. package/dist/querying/failures.d.mts +0 -2
  236. package/dist/querying/failures.mjs +1 -1
  237. package/dist/querying/failures.mjs.map +1 -1
  238. package/dist/querying/filter-boundary.d.mts +18 -9
  239. package/dist/querying/filter-boundary.mjs +1 -1
  240. package/dist/querying/filter-boundary.mjs.map +1 -1
  241. package/dist/querying/filters.d.mts +71 -35
  242. package/dist/querying/filters.mjs +1 -1
  243. package/dist/querying/filters.mjs.map +1 -1
  244. package/dist/querying/planner.d.mts +16 -20
  245. package/dist/querying/planner.mjs +1 -1
  246. package/dist/querying/planner.mjs.map +1 -1
  247. package/dist/querying/relationships.d.mts +6 -6
  248. package/dist/querying/relationships.mjs +1 -1
  249. package/dist/querying/relationships.mjs.map +1 -1
  250. package/dist/querying/search.d.mts +12 -12
  251. package/dist/querying/search.mjs +1 -1
  252. package/dist/querying/search.mjs.map +1 -1
  253. package/dist/querying/security.d.mts +2 -3
  254. package/dist/querying/security.mjs.map +1 -1
  255. package/dist/querying/shared/ast.d.mts +0 -2
  256. package/dist/querying/shared/ast.mjs.map +1 -1
  257. package/dist/querying/shared/contract.d.mts +17 -23
  258. package/dist/querying/shared/contract.mjs +1 -1
  259. package/dist/querying/shared/contract.mjs.map +1 -1
  260. package/dist/querying/shared/evaluate.d.mts +0 -2
  261. package/dist/querying/shared/evaluate.mjs.map +1 -1
  262. package/dist/querying/shared/filters.d.mts +47 -29
  263. package/dist/querying/shared/filters.mjs +1 -1
  264. package/dist/querying/shared/filters.mjs.map +1 -1
  265. package/dist/querying/shared/native-json.d.mts +7 -0
  266. package/dist/querying/shared/native-json.mjs +2 -0
  267. package/dist/querying/shared/native-json.mjs.map +1 -0
  268. package/dist/querying/shared/page.d.mts +19 -22
  269. package/dist/querying/shared/page.mjs +1 -1
  270. package/dist/querying/shared/page.mjs.map +1 -1
  271. package/dist/querying.d.mts +6 -9
  272. package/dist/querying.mjs +1 -1
  273. package/dist/querying.mjs.map +1 -1
  274. package/dist/react/failures.d.mts +0 -2
  275. package/dist/react/failures.mjs.map +1 -1
  276. package/dist/react/optimistic.d.mts +2 -3
  277. package/dist/react/optimistic.mjs.map +1 -1
  278. package/dist/react/pagination-state.d.mts +1 -2
  279. package/dist/react/pagination-state.mjs.map +1 -1
  280. package/dist/react/use-command.d.mts +0 -2
  281. package/dist/react/use-command.mjs.map +1 -1
  282. package/dist/react/use-paginated-list.d.mts +1 -3
  283. package/dist/react/use-paginated-list.mjs +1 -1
  284. package/dist/react/use-paginated-list.mjs.map +1 -1
  285. package/dist/react.d.mts +1 -1
  286. package/dist/react.mjs +1 -1
  287. package/dist/registration.d.mts +65 -0
  288. package/dist/registration.mjs +2 -0
  289. package/dist/registration.mjs.map +1 -0
  290. package/dist/relations-public.d.mts +2 -2
  291. package/dist/relations-public.mjs +1 -1
  292. package/dist/relations.d.mts +55 -46
  293. package/dist/relations.mjs +1 -1
  294. package/dist/relations.mjs.map +1 -1
  295. package/dist/state-machine.d.mts +0 -2
  296. package/dist/state-machine.mjs.map +1 -1
  297. package/dist/table.d.mts +222 -0
  298. package/dist/table.mjs +2 -0
  299. package/dist/table.mjs.map +1 -0
  300. package/dist/tenancy.d.mts +0 -2
  301. package/dist/tenancy.mjs.map +1 -1
  302. package/dist/triggers.d.mts +2 -4
  303. package/dist/triggers.mjs +1 -1
  304. package/dist/triggers.mjs.map +1 -1
  305. package/dist/webhooks.d.mts +9 -9
  306. package/dist/webhooks.mjs +1 -1
  307. package/dist/webhooks.mjs.map +1 -1
  308. package/dist/workflow.mjs +1 -1
  309. package/dist/zod.d.mts +30 -0
  310. package/dist/zod.mjs +2 -0
  311. package/dist/zod.mjs.map +1 -0
  312. package/package.json +51 -29
  313. package/dist/modules/effect/api-zod.d.mts +0 -34
  314. package/dist/modules/effect/api-zod.mjs +0 -2
  315. package/dist/modules/effect/api-zod.mjs.map +0 -1
  316. package/dist/querying/schema-snapshot.d.mts +0 -49
  317. package/dist/querying/schema-snapshot.mjs +0 -2
  318. package/dist/querying/schema-snapshot.mjs.map +0 -1
  319. package/dist/zod-convex.d.mts +0 -10
  320. package/dist/zod-convex.mjs +0 -2
  321. package/dist/zod-convex.mjs.map +0 -1
  322. package/dist/zod-registration.d.mts +0 -15
  323. package/dist/zod-registration.mjs +0 -2
  324. package/dist/zod-registration.mjs.map +0 -1
  325. package/dist/zod-table.d.mts +0 -351
  326. package/dist/zod-table.mjs +0 -2
  327. package/dist/zod-table.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"planner.mjs","names":["createPlanner","owned","getRelationExecutor","relations","schema","metadata","getRelationMetadata","inputs","versions","registryVersion","tables","scope","edges","walk","edge","table","name","select","nested","selection","target","group","groups","filter","ast","child","key","version","digest","document","permitted","scalarMatches","residual","validator","where","constraints","parseFilterPlan","input","traversal","ordering","conditions","compiled","client","server","empty","clientIdentity","serverIdentity","evaluateFilter","text","byte"],"sources":["../../src/querying/planner.ts"],"sourcesContent":["import { evaluateFilter } from './shared/evaluate'\nimport type { z } from 'zod'\nimport type { SchemaDefinition, GenericSchema } from 'convex/server'\nimport { type Value } from 'convex/values'\nimport {\n\tgetRelationExecutor,\n\tgetRelationMetadata,\n\ttype RelationRegistryIdentity,\n} from '../relations'\nimport { parseFilterPlan, type FilterAst, type IndexCondition } from './filters'\n\ninterface SelectionTree {\n\t[name: string]: true | SelectionTree\n}\ninterface GroupTree {\n\trelations: Record<string, GroupTree>\n}\n/** What one cursor binding can depend on: a root, the path to its table and what it reads there. */\nexport interface RegistryScope {\n\treadonly root: string\n\treadonly path: readonly string[]\n\treadonly selection: SelectionTree\n\treadonly groups: GroupTree\n\treadonly filters: readonly FilterAst[]\n}\n\nexport type QueryInput = z.input<ReturnType<ReturnType<typeof getRelationExecutor>['pagination']>>\nexport type StoredConstraint = NonNullable<QueryInput['filters']>\n\nexport function createPlanner(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trelations: RelationRegistryIdentity,\n) {\n\tconst owned = getRelationExecutor(relations)\n\towned.assertSchema(schema.tables)\n\tconst metadata = getRelationMetadata(relations)\n\t// Build each immutable filter grammar only when that table is queried. Engine\n\t// declarations also load in mutations, which never need pagination validators.\n\tconst inputs = new Map<string, ReturnType<typeof owned.pagination>>()\n\t// Digests per used scope; a scope is a few sorted names, so the cap only bounds abuse.\n\tconst versions = new Map<string, Promise<string>>()\n\t/**\n\t * The registry version a cursor binds: a digest of the identity of every table\n\t * and edge the query can read. That is its table, the path edges to it, and\n\t * every edge its selection, field groups and relation filters walk, with the\n\t * tables those edges touch. Nothing else can change what such a cursor means.\n\t */\n\tfunction registryVersion(scope: RegistryScope): Promise<string> {\n\t\tconst tables = new Set([scope.root])\n\t\tconst edges = new Map<string, readonly [string, string]>()\n\t\tfunction walk(table: string, name: string): string {\n\t\t\tconst edge = metadata.declarations[table]?.[name]\n\t\t\tif (!edge) throw new Error('INVALID_RELATION')\n\t\t\tedges.set(JSON.stringify([table, name]), [table, name])\n\t\t\treturn edge.target\n\t\t}\n\t\tfunction select(table: string, selection: SelectionTree): void {\n\t\t\tfor (const [name, nested] of Object.entries(selection)) {\n\t\t\t\tconst target = walk(table, name)\n\t\t\t\tif (nested !== true) select(target, nested)\n\t\t\t}\n\t\t}\n\t\tfunction group(table: string, groups: GroupTree): void {\n\t\t\tfor (const [name, nested] of Object.entries(groups.relations))\n\t\t\t\tgroup(walk(table, name), nested)\n\t\t}\n\t\tfunction filter(table: string, ast: FilterAst): void {\n\t\t\tif (ast.kind === 'and' || ast.kind === 'or')\n\t\t\t\tfor (const child of ast.children) filter(table, child)\n\t\t\telse if (ast.kind === 'not' || ast.kind === 'variant') filter(table, ast.child)\n\t\t\telse if (ast.kind === 'relation') {\n\t\t\t\tconst target = walk(table, ast.name)\n\t\t\t\tif (ast.predicate) filter(target, ast.predicate)\n\t\t\t}\n\t\t}\n\t\tlet table = scope.root\n\t\tfor (const name of scope.path) table = walk(table, name)\n\t\ttables.add(table)\n\t\tselect(table, scope.selection)\n\t\tgroup(table, scope.groups)\n\t\tfor (const ast of scope.filters) filter(table, ast)\n\t\tconst key = JSON.stringify([[...tables].sort(), [...edges.keys()].sort()])\n\t\tlet version = versions.get(key)\n\t\tif (!version) {\n\t\t\tversion = digest(owned.scopedIdentity([...tables], [...edges.values()]))\n\t\t\tif (versions.size >= 256) versions.clear()\n\t\t\tversions.set(key, version)\n\t\t}\n\t\treturn version\n\t}\n\treturn {\n\t\tmetadata,\n\t\tselect: owned.select,\n\t\tgroups: owned.groups,\n\t\tvalidateDocument: owned.validateDocument,\n\t\tstreamSchema: owned.streamSchema,\n\t\tregistryVersion,\n\t\tbeforeLeaf(table: string) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t},\n\t\tcomplete(\n\t\t\ttable: string,\n\t\t\tdocument: Record<string, Value>,\n\t\t\tpermitted: boolean,\n\t\t\tresidual: FilterAst,\n\t\t\tgroups: readonly string[] = [],\n\t\t) {\n\t\t\treturn owned.project(\n\t\t\t\ttable,\n\t\t\t\tdocument,\n\t\t\t\t() => permitted && scalarMatches(residual, document),\n\t\t\t\tgroups,\n\t\t\t)\n\t\t},\n\t\tplan(\n\t\t\ttable: string,\n\t\t\tinput: QueryInput,\n\t\t\tconditions: readonly IndexCondition[],\n\t\t\tconstraints: readonly StoredConstraint[],\n\t\t\tordering?: string,\n\t\t\ttraversal: 'root' | 'relation' = 'root',\n\t\t) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t\tlet validator = inputs.get(table)\n\t\t\tif (!validator) {\n\t\t\t\tvalidator = owned.pagination(table)\n\t\t\t\tinputs.set(table, validator)\n\t\t\t}\n\t\t\t// Server constraints are independently validated against stored fields,\n\t\t\t// not the endpoint's public input/filter mask. Client values cannot replace them.\n\t\t\tconst where =\n\t\t\t\tconstraints.length === 1\n\t\t\t\t\t? constraints[0]\n\t\t\t\t\t: constraints.length\n\t\t\t\t\t\t? { and: constraints }\n\t\t\t\t\t\t: undefined\n\t\t\tconst { args, compiled } = parseFilterPlan(\n\t\t\t\tvalidator,\n\t\t\t\tinput,\n\t\t\t\ttraversal === 'relation' && ordering === undefined ? [] : metadata.tables[table].indexes,\n\t\t\t\tconditions,\n\t\t\t\twhere,\n\t\t\t\tordering,\n\t\t\t)\n\t\t\tif (compiled.residual.kind !== 'and') throw new Error('Invalid compiled filter root')\n\t\t\tconst [client, server] = compiled.residual.children\n\t\t\tconst empty: FilterAst = { kind: 'and', children: [] }\n\t\t\tconst clientIdentity = { kind: 'and', children: [client, empty] }\n\t\t\tconst serverIdentity = compiled.sets.size\n\t\t\t\t? {\n\t\t\t\t\t\tkind: 'and',\n\t\t\t\t\t\tchildren: [server, empty],\n\t\t\t\t\t\ttraversal: { version: 2, expansion: compiled.expansion },\n\t\t\t\t\t}\n\t\t\t\t: { kind: 'and', children: [server, empty] }\n\t\t\t// SAFETY: normalized AST nodes contain only validated native scalar Values.\n\t\t\treturn {\n\t\t\t\t...compiled,\n\t\t\t\targs,\n\t\t\t\tclientIdentity: clientIdentity as Value,\n\t\t\t\tserverIdentity: serverIdentity as Value,\n\t\t\t}\n\t\t},\n\t}\n}\n\nexport function scalarMatches(\n\tast: FilterAst,\n\tdocument: Record<string, Value | undefined>,\n): boolean {\n\treturn evaluateFilter(ast, document) === true\n}\n\n/** Lowercase hex SHA-256 of the UTF-8 text. */\nexport async function digest(text: string): Promise<string> {\n\treturn Array.from(\n\t\tnew Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))),\n\t\t(byte) => byte.toString(16).padStart(2, '0'),\n\t).join('')\n}\n"],"mappings":"6MA6BA,SAAgBA,EACf,EACA,EACC,CACD,IAAMC,EAAQC,EAAoBC,CAAS,EAC3CF,EAAM,aAAaG,EAAO,MAAM,EAChC,IAAMC,EAAWC,EAAoBH,CAAS,E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S,OAAOU,EAAM,CAAC,QACjFyB,EACAN,EACAK,CACD,EACA,GAAIE,EAAS,SAAS,OAAS,MAAO,MAAU,MAAM,8BAA8B,EACpF,GAAM,CAACC,EAAQC,GAAUF,EAAS,SAAS,SACrCG,EAAmB,CAAE,KAAM,MAAO,SAAU,CAAC,CAAE,EAC/CC,EAAiB,CAAE,KAAM,MAAO,SAAU,CAACH,EAAQE,CAAK,CAAE,EAC1DE,EAAiBL,EAAS,KAAK,KAClC,CACA,KAAM,MACN,SAAU,CAACE,EAAQC,CAAK,EACxB,UAAW,CAAE,QAAS,EAAG,UAAWH,EAAS,SAAU,CACxD,EACC,CAAE,KAAM,MAAO,SAAU,CAACE,EAAQC,CAAK,CAAE,EAE5C,MAAO,CACN,GAAGH,EACH,OACgB,iBACA,gBACjB,CACD,CACD,CACD,CAEA,SAAgBV,EACf,EACA,EACU,CACV,OAAOgB,EAAevB,EAAKK,CAAQ,IAAM,EAC1C,CAGA,eAAsBD,EAAO,EAA+B,CAC3D,OAAO,MAAM,KACZ,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,UAAW,IAAI,YAAY,CAAC,CAAC,OAAOoB,CAAI,CAAC,CAAC,EACnF,GAASC,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAC5C,CAAC,CAAC,KAAK,EAAE,CACV"}
1
+ {"version":3,"file":"planner.mjs","names":["createPlanner","owned","getRelationExecutor","relations","schema","metadata","getRelationMetadata","inputs","versions","registryVersion","tables","scope","edges","walk","edge","table","name","select","nested","selection","target","group","groups","filter","ast","child","key","version","digest","document","permitted","scalarMatches","residual","validator","paginationSchema","where","constraints","parseFilterPlan","input","traversal","ordering","conditions","compiled","client","server","empty","clientIdentity","serverIdentity","evaluateFilter","text","byte"],"sources":["../../src/querying/planner.ts"],"sourcesContent":["import { evaluateFilter } from './shared/evaluate'\nimport type { SchemaDefinition, GenericSchema } from 'convex/server'\nimport type { PropertyValidators, Value, VObject } from 'convex/values'\nimport type { KSchema, KType } from '../k'\nimport {\n\tgetRelationExecutor,\n\tgetRelationMetadata,\n\ttype RelationRegistryIdentity,\n} from '../relations'\nimport {\n\tparseFilterPlan,\n\ttype FilterAst,\n\ttype IndexCondition,\n\ttype NativePagination,\n} from './filters'\nimport type { FilterTree } from './shared/filters'\n\ninterface SelectionTree {\n\t[name: string]: true | SelectionTree\n}\ninterface GroupTree {\n\trelations: Record<string, GroupTree>\n}\n/** What one cursor binding can depend on: a root, the path to its table and what it reads there. */\nexport interface RegistryScope {\n\treadonly root: string\n\treadonly path: readonly string[]\n\treadonly selection: SelectionTree\n\treadonly groups: GroupTree\n\treadonly filters: readonly FilterAst[]\n}\n\n/** The engine's pagination input: Convex's options, bounded, plus filters and order. */\nexport type QueryInput = NativePagination & { filters?: FilterTree; order?: 'asc' | 'desc' }\nexport type StoredConstraint = NonNullable<QueryInput['filters']>\n\nexport function createPlanner(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trelations: RelationRegistryIdentity,\n) {\n\tconst owned = getRelationExecutor(relations)\n\towned.assertSchema(schema.tables)\n\tconst metadata = getRelationMetadata(relations)\n\t// Build each immutable filter grammar only when that table is queried. Engine\n\t// declarations also load in mutations, which never need pagination validators.\n\tconst inputs = new Map<string, PaginationSchema>()\n\t// Digests per used scope; a scope is a few sorted names, so the cap only bounds abuse.\n\tconst versions = new Map<string, Promise<string>>()\n\t/**\n\t * The registry version a cursor binds: a digest of the identity of every table\n\t * and edge the query can read. That is its table, the path edges to it, and\n\t * every edge its selection, field groups and relation filters walk, with the\n\t * tables those edges touch. Nothing else can change what such a cursor means.\n\t */\n\tfunction registryVersion(scope: RegistryScope): Promise<string> {\n\t\tconst tables = new Set([scope.root])\n\t\tconst edges = new Map<string, readonly [string, string]>()\n\t\tfunction walk(table: string, name: string): string {\n\t\t\tconst edge = metadata.declarations[table]?.[name]\n\t\t\tif (!edge) throw new Error('INVALID_RELATION')\n\t\t\tedges.set(JSON.stringify([table, name]), [table, name])\n\t\t\treturn edge.target\n\t\t}\n\t\tfunction select(table: string, selection: SelectionTree): void {\n\t\t\tfor (const [name, nested] of Object.entries(selection)) {\n\t\t\t\tconst target = walk(table, name)\n\t\t\t\tif (nested !== true) select(target, nested)\n\t\t\t}\n\t\t}\n\t\tfunction group(table: string, groups: GroupTree): void {\n\t\t\tfor (const [name, nested] of Object.entries(groups.relations))\n\t\t\t\tgroup(walk(table, name), nested)\n\t\t}\n\t\tfunction filter(table: string, ast: FilterAst): void {\n\t\t\tif (ast.kind === 'and' || ast.kind === 'or')\n\t\t\t\tfor (const child of ast.children) filter(table, child)\n\t\t\telse if (ast.kind === 'not' || ast.kind === 'variant') filter(table, ast.child)\n\t\t\telse if (ast.kind === 'relation') {\n\t\t\t\tconst target = walk(table, ast.name)\n\t\t\t\tif (ast.predicate) filter(target, ast.predicate)\n\t\t\t}\n\t\t}\n\t\tlet table = scope.root\n\t\tfor (const name of scope.path) table = walk(table, name)\n\t\ttables.add(table)\n\t\tselect(table, scope.selection)\n\t\tgroup(table, scope.groups)\n\t\tfor (const ast of scope.filters) filter(table, ast)\n\t\tconst key = JSON.stringify([[...tables].sort(), [...edges.keys()].sort()])\n\t\tlet version = versions.get(key)\n\t\tif (!version) {\n\t\t\tversion = digest(owned.scopedIdentity([...tables], [...edges.values()]))\n\t\t\tif (versions.size >= 256) versions.clear()\n\t\t\tversions.set(key, version)\n\t\t}\n\t\treturn version\n\t}\n\treturn {\n\t\tmetadata,\n\t\tselect: owned.select,\n\t\tgroups: owned.groups,\n\t\tvalidateDocument: owned.validateDocument,\n\t\tstreamSchema: owned.streamSchema,\n\t\tregistryVersion,\n\t\tbeforeLeaf(table: string) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t},\n\t\tcomplete(\n\t\t\ttable: string,\n\t\t\tdocument: Record<string, Value>,\n\t\t\tpermitted: boolean,\n\t\t\tresidual: FilterAst,\n\t\t\tgroups: readonly string[] = [],\n\t\t) {\n\t\t\treturn owned.project(\n\t\t\t\ttable,\n\t\t\t\tdocument,\n\t\t\t\t() => permitted && scalarMatches(residual, document),\n\t\t\t\tgroups,\n\t\t\t)\n\t\t},\n\t\tplan(\n\t\t\ttable: string,\n\t\t\tinput: QueryInput,\n\t\t\tconditions: readonly IndexCondition[],\n\t\t\tconstraints: readonly StoredConstraint[],\n\t\t\tordering?: string,\n\t\t\ttraversal: 'root' | 'relation' = 'root',\n\t\t) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t\tlet validator = inputs.get(table)\n\t\t\tif (!validator) {\n\t\t\t\tvalidator = paginationSchema(owned.pagination(table))\n\t\t\t\tinputs.set(table, validator)\n\t\t\t}\n\t\t\t// Server constraints are independently validated against stored fields,\n\t\t\t// not the endpoint's public input/filter mask. Client values cannot replace them.\n\t\t\tconst where: FilterTree =\n\t\t\t\tconstraints.length === 1\n\t\t\t\t\t? constraints[0]\n\t\t\t\t\t: constraints.length\n\t\t\t\t\t\t? { and: [...constraints] }\n\t\t\t\t\t\t: undefined\n\t\t\tconst { args, compiled } = parseFilterPlan(\n\t\t\t\tvalidator,\n\t\t\t\tinput,\n\t\t\t\ttraversal === 'relation' && ordering === undefined ? [] : metadata.tables[table].indexes,\n\t\t\t\tconditions,\n\t\t\t\twhere,\n\t\t\t\tordering,\n\t\t\t)\n\t\t\tif (compiled.residual.kind !== 'and') throw new Error('Invalid compiled filter root')\n\t\t\tconst [client, server] = compiled.residual.children\n\t\t\tconst empty: FilterAst = { kind: 'and', children: [] }\n\t\t\tconst clientIdentity = { kind: 'and', children: [client, empty] }\n\t\t\tconst serverIdentity = compiled.sets.size\n\t\t\t\t? {\n\t\t\t\t\t\tkind: 'and',\n\t\t\t\t\t\tchildren: [server, empty],\n\t\t\t\t\t\ttraversal: { version: 2, expansion: compiled.expansion },\n\t\t\t\t\t}\n\t\t\t\t: { kind: 'and', children: [server, empty] }\n\t\t\t// SAFETY: normalized AST nodes contain only validated native scalar Values.\n\t\t\treturn {\n\t\t\t\t...compiled,\n\t\t\t\targs,\n\t\t\t\tclientIdentity: clientIdentity as Value,\n\t\t\t\tserverIdentity: serverIdentity as Value,\n\t\t\t}\n\t\t},\n\t}\n}\n\n/** The pagination boundary the planner parses with; its input and output are both `QueryInput`. */\ntype PaginationSchema = KSchema<QueryInput, VObject<QueryInput, PropertyValidators>>\n\nexport function scalarMatches(\n\tast: FilterAst,\n\tdocument: Record<string, Value | undefined>,\n): boolean {\n\treturn evaluateFilter(ast, document) === true\n}\n\n/** Lowercase hex SHA-256 of the UTF-8 text. */\nexport async function digest(text: string): Promise<string> {\n\treturn Array.from(\n\t\tnew Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))),\n\t\t(byte) => byte.toString(16).padStart(2, '0'),\n\t).join('')\n}\n\nfunction paginationSchema(schema: KType): PaginationSchema {\n\t// SAFETY: the relation executor builds the engine pagination object, whose parse yields QueryInput.\n\treturn schema as PaginationSchema\n}\n"],"mappings":"A,uLAoCA,SAAgBA,EACf,EACA,EACC,CACD,IAAMC,EAAQC,EAAoBC,CAAS,EAC3CF,EAAM,aAAaG,EAAO,MAAM,EAChC,IAAMC,EAAWC,EAAoBH,CAAS,EAGxCI,kBAAS,IAAI,IAEbC,kBAAW,IAAI,IAOrB,SAASC,EAAgB,EAAuC,CAC/D,IAAMC,kBAAS,IAAI,IAAI,CAACC,EAAM,IAAI,CAAC,EAC7BC,kBAAQ,IAAI,IAClB,SAASC,EAAK,EAAe,EAAsB,CAClD,IAAMC,EAAOT,EAAS,aAAaU,EAAM,GAAGC,GAC5C,GAAI,CAACF,EAAM,MAAU,MAAM,kBAAkB,EAE7C,OADAF,EAAM,IAAI,KAAK,UAAU,CAACG,EAAOC,CAAI,CAAC,EAAG,CAACD,EAAOC,CAAI,CAAC,EAC/CF,EAAK,MACb,CACA,SAASG,EAAO,EAAe,EAAgC,CAC9D,IAAK,GAAM,CAACD,EAAME,KAAW,OAAO,QAAQC,CAAS,EAAG,CACvD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5C,MAAO,CACN,GAAGH,EACH,OACgB,iBACA,gBACjB,CACD,CACD,CACD,CAKA,SAAgBX,EACf,EACA,EACU,CACV,OAAOiB,EAAexB,EAAKK,CAAQ,IAAM,EAC1C,CAGA,eAAsBD,EAAO,EAA+B,CAC3D,OAAO,MAAM,KACZ,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,UAAW,IAAI,YAAY,CAAC,CAAC,OAAOqB,CAAI,CAAC,CAAC,EACnF,GAASC,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAC5C,CAAC,CAAC,KAAK,EAAE,CACV,CAEA,SAAShB,EAAiB,EAAiC,CAE1D,OAAO9B,CACR,C"}
@@ -1,13 +1,13 @@
1
1
  import { FilterAst } from "./shared/ast.mjs";
2
- import { IndexCondition, NativePagination } from "./filters.mjs";
3
- import { PageCompleteness } from "../zod-table.mjs";
2
+ import "../index.mjs";
3
+ import { PageCompleteness } from "../table.mjs";
4
4
  import { RelationEdge } from "../relations.mjs";
5
5
  import { QueryInput, StoredConstraint, createPlanner } from "./planner.mjs";
6
- import { CursorBinding, createCursorCodec } from "./cursors.mjs";
6
+ import { IndexCondition, NativePagination } from "./filters.mjs";
7
7
  import { ExecutionRequest } from "./execution.mjs";
8
- import { GenericSchema, SchemaDefinition } from "convex/server";
8
+ import { CursorBinding, createCursorCodec } from "./cursors.mjs";
9
9
  import { GenericId, Value } from "convex/values";
10
- //#region src/querying/relationships.d.ts
10
+ import { GenericSchema, SchemaDefinition } from "convex/server";
11
11
  export interface OutputSelection {
12
12
  [name: string]: true | OutputSelection;
13
13
  }
@@ -54,5 +54,5 @@ export declare function relationshipExecutor(schema: SchemaDefinition<GenericSch
54
54
  edge: (table: string, name: string) => Edge;
55
55
  preflight: (table: string, selection: OutputSelection, input: QueryInput, path?: readonly string[]) => void;
56
56
  };
57
- //#endregion
57
+ export {};
58
58
  //# sourceMappingURL=relationships.d.mts.map
@@ -1,2 +1,2 @@
1
- import{expansionForIndex as e,rangeForIndex as t,withinRange as n}from"./filters.mjs";import{scalarMatches as r}from"./planner.mjs";import{CursorError as i}from"./cursors.mjs";import{executeStream as a,nativeIndexRange as o,rethrowQueryError as s}from"./execution.mjs";import{z as c}from"zod";import{compareValues as l}from"convex/values";import{EmptyStream as u,getIndexFields as d,stream as f}from"convex-helpers/server/stream";const p={fieldGroups:{},relations:{}},m=c.object({cursor:c.string(),ancestors:c.array(c.string()).max(3)}).strict();var h=class extends Error{code;constructor(e){super(e),this.code=e,this.name=`RelationshipError`}};function g(e,t){for(let n of Object.values(e)){if(t>=4)throw new h(`INVALID_RELATION`);n!==!0&&g(n,t+1)}}function _(_,y,b,x,S,C){let w=b.metadata,T=e=>`base`in e?e.base:e;function E(e,t){let n=w.declarations[e]?.[t];if(!n)throw new h(`INVALID_RELATION`);return n}let D=(e,t)=>!t||e[t.discriminator]===t.tag,O=c.string();function k(e,t){if(!t)return!0;let n=O.safeParse(e);return n.success&&y.db.normalizeId(t.table,n.data)!==null}function A(e,t){if(!t||!D(t,e.sourceGuard))return;let n=t[T(e.from).field];return k(n,e.sourceMember)&&k(n,e.targetMember)?n:void 0}function j(e,t,n){let r=t===`_id`?{name:`by_id`,fields:[`_id`]}:w.tables[e].indexes.find(e=>{let r=e.fields.indexOf(t);return r>=0&&e.fields.slice(0,r).every(e=>e===n?.discriminator)});if(!r)throw new h(`INVALID_RELATION`);return r}function M(e,t){function n(e,t,n,r){C?.checkOrder(e,j(e,t,n).fields.filter(e=>e!==t&&e!==n?.discriminator),r)}`base`in e.from&&`base`in e.to?(n(e.from.junction.table,e.from.junction.field,e.junctionGuard),n(e.target,e.to.base.field,e.targetGuard,t)):n(e.target,T(e.to).field,e.targetGuard,t)}function N(e,t,n,r,i){let a=t===`_id`?[{name:`by_id`,fields:[`_id`]}]:w.tables[e].indexes,o=e=>e===t||e===i?.discriminator||n.bindings.has(e),s=e=>e.fields.includes(t)&&e.fields.slice(0,e.fields.indexOf(t)).every(o),c=e=>{let t=0;for(let n of e.fields){if(!o(n))break;t++}return t},l=r.find(e=>e.value!==null&&e.value!==void 0);if(l){let e=a.find(e=>e.name===l.index&&s(e));if(!e)throw Error(`Explicit index "${l.index}" is incompatible with declared relationship lookup`);return e}let u=a.filter(s).sort((e,t)=>c(t)-c(e)||Number(n.sets.has(t.fields[c(t)]))-Number(n.sets.has(e.fields[c(e)]))||Number(n.ranges.has(t.fields[c(t)]))-Number(n.ranges.has(e.fields[c(e)]))||e.name.localeCompare(t.name)||e.fields.join(`\0`).localeCompare(t.fields.join(`\0`)));if(!u.length)throw new h(`INVALID_RELATION`);return u[0]}function P(e,t,n,r,i){let a=[];for(let o of e.fields)if(o===t)a.push({field:o,value:n});else if(o===i?.discriminator)a.push({field:o,value:i.tag});else if(r?.bindings.has(o))a.push({field:o,value:r.bindings.get(o)});else break;return a}async function F(e,t){if(b.beforeLeaf(e),t==null||!y.db.normalizeId(e,t))return null;let n=await y.db.get(e,t);return n&&b.validateDocument(e,n),n}async function*I(e,t,n,r,i,a){if(y.expand(r,0),n==null||!k(n,a))return;if(t===`_id`){let o=await F(e,n);o&&D(o,i)&&k(o[t],a)&&(y.expand(r),yield o);return}b.beforeLeaf(e);let o=j(e,t,i),s=y.leafQuery(e).withIndex(o.name,e=>{let r=e;for(let e of P(o,t,n,void 0,i))r=r.eq(e.field,e.value);return r})[Symbol.asyncIterator]();try{for(;;){b.beforeLeaf(e);let n=await s.next();if(n.done)return;await y.authorize(e,n.value)&&(b.validateDocument(e,n.value),D(n.value,i)&&k(n.value[t],a)&&(y.expand(r),yield n.value))}}finally{await s.return?.()}}async function*L(e,t,n){y.expand(n,0);let r=A(e,t);if(r!=null){if(`base`in e.from&&`base`in e.to)for await(let t of I(e.from.junction.table,e.from.junction.field,r,n,e.junctionGuard))yield*I(e.target,e.to.base.field,t[e.to.junction.field],n,e.targetGuard);else yield*I(e.target,T(e.to).field,r,n,e.targetGuard,e.targetMember)}}async function R(e,t,n){let r=null;for await(let i of L(e,t,n)){if(r)throw new h(`AMBIGUOUS_RELATION`);r=i}return r}async function z(e,t,n,i=0){if(y.expand(i,0),w.tables[e].variant&&b.validateDocument(e,t),v(n))return r(n,t);if(n.kind===`variant`)return t[n.discriminator]===n.tag&&z(e,t,n.child,i);if(n.kind===`scalar`)return r(n,t);if(n.kind===`not`)return!await z(e,t,n.child,i);if(n.kind===`and`||n.kind===`or`){for(let r of n.children){let a=await z(e,t,r,i);if(n.kind===`and`&&!a)return!1;if(n.kind===`or`&&a)return!0}return n.kind===`and`}if(n.kind!==`relation`)throw new h(`INVALID_RELATION`);let a=E(e,n.name);if(n.mode===`one`){let e=await R(a,t,i+1);return n.predicate===null?e===null:e!==null&&await z(a.target,e,n.predicate,i+1)}for await(let e of L(a,t,i+1))if(await z(a.target,e,n.predicate,i+1))return n.mode===`some`;return n.mode===`none`}async function B(e,t,n,r,i=[],a=0,o=[]){y.expand(a,0);let s=b.complete(e,t,!0,{kind:`and`,children:[]},C?.allowed(i));for(let[c,l]of Object.entries(n)){let n=E(e,c),u=l===!0?{}:l;if(n.cardinality===`one`){let e=await R(n,t,a+1);s[c]=e?await B(n.target,e,u,r,[...i,c],a+1,[...o,t._id]):null}else s[c]=await H(e,t,c,u,{numItems:r.numItems,cursor:null,order:r.order},[],[],[...i,c],a+1,[...o,t._id])}return s}function V(t,n,r,a,o,s,c,l,u){if(u!==void 0&&o.some(e=>e.value!==null&&e.value!==void 0))throw Error(`orderBy cannot be combined with an active when selector`);b.select(E(t,n).target,r),g(r,c.length);let d=E(t,n);if(d.cardinality!==`many`)throw new h(`INVALID_RELATION`);let f=d.targetGuard?{fields:{[d.targetGuard.discriminator]:d.targetGuard.tag}}:void 0,_=b.plan(d.target,a,[],f?[...s,f]:s,u,`relation`),v=d.from,w=d.to,D=`base`in v&&`base`in w?{table:v.junction.table,field:v.junction.field,targetField:w.base.field,targetReference:w.junction.field}:null;if(u!==void 0&&D)throw Error(`orderBy is unsupported for junction relationships`);let O=D?D.table:d.target,k=D?D.field:T(w).field,A=N(d.target,D?D.targetField:k,_,u===void 0?o:[{value:!0,index:u}],d.targetGuard);C?.checkOrder(d.target,A.fields.filter(e=>e!==(D?D.targetField:k)&&e!==d.targetGuard?.discriminator&&!_.bindings.has(e)),c);let M=D?j(O,k,d.junctionGuard):A;D&&C?.checkOrder(O,M.fields.filter(e=>e!==k&&e!==d.junctionGuard?.discriminator));let F=D||_.unsatisfiable?null:e(M,P(M,k,null,_,d.targetGuard),_.sets,u!==void 0||o.some(e=>e.value!==null&&e.value!==void 0)),I={},L=C?.at(c);L&&(Object.keys(L.fieldGroups).length||Object.keys(L.relations).length)&&(I.fieldGroups=L);let R={...S,table:O,index:M.name,order:_.args.order??`asc`,clientFilters:_.clientIdentity,serverFilters:{predicates:_.sets.size?{predicates:_.serverIdentity,traversal:{version:2,expansion:F?{...F}:null}}:_.serverIdentity,selection:r,...I,scope:{...y.scope},rootTable:S.table,lookupIndex:A.name,guards:{source:d.sourceGuard?{...d.sourceGuard}:null,target:d.targetGuard?{...d.targetGuard}:null,junction:d.junctionGuard?{...d.junctionGuard}:null},...(d.sourceMember||d.targetMember)&&{members:{source:d.sourceMember?{...d.sourceMember}:null,target:d.targetMember?{...d.targetMember}:null}}},relationPath:c,parent:l},z;function B(){return z??=b.registryVersion({root:S.table,path:c,selection:r,groups:L??p,filters:[_.residual]}).then(e=>({...R,registryVersion:e})),z}async function V(e){try{return m.parse(JSON.parse(x.open(e,await B())))}catch{throw new i}}return{declared:d,plan:_,through:D,sourceTable:O,field:k,index:M,targetIndex:A,bind:B,open:V,expansion:F}}async function H(e,r,i,s,c,p=[],m=[],h=[i],g=1,v=[],S=V(e,i,s,c,p,m,h,v[0]??r._id),C){y.expand(g,0);let{declared:w,plan:E,through:O,sourceTable:j,field:M,index:N,targetIndex:I,expansion:L}=S,R=await S.bind(),H=A(w,r),U={...E.args,...C??{cursor:null}},W={...E,expansion:L,index:N,prefix:H==null?[]:O?P(N,M,H,void 0,w.junctionGuard):P(N,M,H,E,w.targetGuard),unsatisfiable:H==null||E.unsatisfiable};if(W.range=O?null:t(N,W.prefix,E.ranges),!O)for(let e of W.prefix){let t=E.ranges.get(e.field);E.bindings.has(e.field)&&l(e.value,E.bindings.get(e.field))!==0&&(W.unsatisfiable=!0),t&&!n(e.value,t)&&(W.unsatisfiable=!0)}let G=O&&O.targetField!==`_id`;return await a(_,y,j,W,b,x,R,U,async(e,t)=>{if(t&&b.validateDocument(G?w.target:j,e),!t||O&&!G&&!D(e,w.junctionGuard))return null;y.expand(g);let n;return n=O&&!G?await F(w.target,e[O.targetReference]):e,!n||!D(n,w.targetGuard)||!k(n[T(w.to).field],w.targetMember)||!await z(w.target,n,E.residual,g)?null:B(w.target,n,s,E.args,h,g,v)},e=>x.seal(JSON.stringify({cursor:e,ancestors:v.slice(1)}),R),G?(e,n)=>{let r=_,i=d(w.target,I.name,r);return e.flatMap(async e=>{y.expand(g);let a=await y.authorize(j,e);a&&b.validateDocument(j,e);let s=e[O.targetReference];return!a||!D(e,w.junctionGuard)||s==null?new u(E.args.order??`asc`,i):f(n,r).query(w.target).withIndex(I.name,e=>{let n=P(I,O.targetField,s,E,w.targetGuard);return o(e,n,t(I,n,E.ranges))}).order(E.args.order??`asc`)},i)}:void 0,G?w.target:j)}async function U(e,t,n,r,a,o,c,u){if(!n.length||n.length>4||!y.db.normalizeId(e,t))throw new h(`INVALID_RELATION`);let d=e,f=n.map(e=>{let t=E(d,e);return d=t.target,t});if(u!==void 0&&f.some(e=>`base`in e.from||`base`in e.to))throw Error(`orderBy is unsupported for junction relationships`);let p=f.at(-1);for(let e of f.slice(0,-1))(e.cardinality===`one`||`base`in e.from||`base`in e.to)&&M(e);let m=V(p.source,n.at(-1),r,a,o,c,n,t,u),g=a.cursor===null?null:await m.open(a.cursor),_=a.endCursor==null?null:await m.open(a.endCursor),v=g?.ancestors??_?.ancestors??[];if(v.length!==n.length-1||g&&_&&JSON.stringify(g.ancestors)!==JSON.stringify(_.ancestors)||v.some((e,t)=>!y.db.normalizeId(f[t].target,e)))throw new i;try{let i=await F(e,t);for(let e=0;i&&e<v.length;e++){let t=f[e],n=null;if(t.cardinality===`many`&&!(`base`in t.from)&&!(`base`in t.to)){y.expand(e+1,0);let r=A(t,i),a=r==null?null:await F(t.target,v[e]),o=t.to.field;r!=null&&a&&D(a,t.targetGuard)&&k(a[o],t.targetMember)&&a[o]!==void 0&&l(r,a[o])===0&&(y.expand(e+1),n=a)}else if(t.cardinality===`one`){let r=await R(t,i,e+1);r?._id===v[e]&&(n=r)}else for await(let r of L(t,i,e+1))if(r._id===v[e]){n=r;break}i=n}return await H(p.source,i,n.at(-1),r,a,o,c,n,n.length,[t,...v],m,{cursor:g?.cursor??null,endCursor:_?.cursor??a.endCursor})}catch(e){s(e)}}function W(e,t,n,r=[]){for(let[i,a]of Object.entries(t)){let t=E(e,i),o=a===!0?{}:a,s=[...r,i];t.cardinality===`many`?V(e,i,o,{numItems:n.numItems,cursor:null,order:n.order},[],[],s,``):M(t,s),W(t.target,o,n,s)}}return{matches:z,output:B,continuation:U,edge:E,preflight:W}}function v(e){return e.kind===`relation`?!1:e.kind===`and`||e.kind===`or`?e.children.every(v):e.kind===`not`||e.kind===`variant`?v(e.child):!0}export{h as RelationshipError,g as assertRelationshipDepth,_ as relationshipExecutor};
1
+ import{scalarMatches as e}from"./planner.mjs";import{expansionForIndex as t,rangeForIndex as n,withinRange as r}from"./filters.mjs";import{executeStream as i,nativeIndexRange as a,rethrowQueryError as o}from"./execution.mjs";import{CursorError as s,prepareCursorBinding as c}from"./cursors.mjs";import{k as l}from"../k/index.mjs";import{compareValues as u}from"convex/values";import{EmptyStream as d,getIndexFields as f,stream as p}from"convex-helpers/server/stream";const m={fieldGroups:{},relations:{}},h={kind:`and`,children:[]};var g=class extends Error{code;constructor(e){super(e),this.code=e,this.name=`RelationshipError`}};function _(e,t){for(let n of Object.values(e)){if(t>=4)throw new g(`INVALID_RELATION`);n!==!0&&_(n,t+1)}}function v(l,v,y,x,S,C){let w=y.metadata,T=/* @__PURE__ */ new Map,E=/* @__PURE__ */ new WeakMap;function D(e){let t=E.get(e);if(t!==void 0)return t;let n=e.kind===`and`||e.kind===`or`?e.children.every(D):e.kind===`not`||e.kind===`variant`?D(e.child):e.kind===`scalar`;return E.set(e,n),n}let O=e=>`base`in e?e.base:e;function k(e,t){let n=w.declarations[e]?.[t];if(!n)throw new g(`INVALID_RELATION`);return n}let A=(e,t)=>!t||e[t.discriminator]===t.tag;function j(e,t){return!t||typeof e==`string`&&v.db.normalizeId(t.table,e)!==null}function M(e,t){if(!t||!A(t,e.sourceGuard))return;let n=t[O(e.from).field];return j(n,e.sourceMember)&&j(n,e.targetMember)?n:void 0}function N(e,t,n){let r=t===`_id`?{name:`by_id`,fields:[`_id`]}:w.tables[e].indexes.find(e=>{let r=e.fields.indexOf(t);return r>=0&&e.fields.slice(0,r).every(e=>e===n?.discriminator)});if(!r)throw new g(`INVALID_RELATION`);return r}function P(e,t){function n(e,t,n,r){C?.checkOrder(e,N(e,t,n).fields.filter(e=>e!==t&&e!==n?.discriminator),r)}`base`in e.from&&`base`in e.to?(n(e.from.junction.table,e.from.junction.field,e.junctionGuard),n(e.target,e.to.base.field,e.targetGuard,t)):n(e.target,O(e.to).field,e.targetGuard,t)}function F(e,t,n,r,i){let a=t===`_id`?[{name:`by_id`,fields:[`_id`]}]:w.tables[e].indexes,o=e=>e===t||e===i?.discriminator||n.bindings.has(e),s=e=>e.fields.includes(t)&&e.fields.slice(0,e.fields.indexOf(t)).every(o),c=e=>{let t=0;for(let n of e.fields){if(!o(n))break;t++}return t},l=r.find(e=>e.value!==null&&e.value!==void 0);if(l){let e=a.find(e=>e.name===l.index&&s(e));if(!e)throw Error(`Explicit index "${l.index}" is incompatible with declared relationship lookup`);return e}let u=a.filter(s).sort((e,t)=>c(t)-c(e)||Number(n.sets.has(t.fields[c(t)]))-Number(n.sets.has(e.fields[c(e)]))||Number(n.ranges.has(t.fields[c(t)]))-Number(n.ranges.has(e.fields[c(e)]))||e.name.localeCompare(t.name)||e.fields.join(`\0`).localeCompare(t.fields.join(`\0`)));if(!u.length)throw new g(`INVALID_RELATION`);return u[0]}function I(e,t,n,r,i){let a=[];for(let o of e.fields)if(o===t)a.push({field:o,value:n});else if(o===i?.discriminator)a.push({field:o,value:i.tag});else if(r?.bindings.has(o))a.push({field:o,value:r.bindings.get(o)});else break;return a}async function L(e,t){if(y.beforeLeaf(e),t==null||!v.db.normalizeId(e,t))return null;let n=await v.db.get(e,t);return n&&y.validateDocument(e,n),n}async function*R(e,t,n,r,i,a){if(v.expand(r,0),n==null||!j(n,a))return;if(t===`_id`){let o=await L(e,n);o&&A(o,i)&&j(o[t],a)&&(v.expand(r),yield o);return}y.beforeLeaf(e);let o=N(e,t,i),s=v.leafQuery(e).withIndex(o.name,e=>{let r=e;for(let e of I(o,t,n,void 0,i))r=r.eq(e.field,e.value);return r})[Symbol.asyncIterator]();try{for(;;){y.beforeLeaf(e);let n=await s.next();if(n.done)return;await v.authorize(e,n.value)&&(y.validateDocument(e,n.value),A(n.value,i)&&j(n.value[t],a)&&(v.expand(r),yield n.value))}}finally{await s.return?.()}}async function*z(e,t,n){v.expand(n,0);let r=M(e,t);if(r!=null){if(`base`in e.from&&`base`in e.to)for await(let t of R(e.from.junction.table,e.from.junction.field,r,n,e.junctionGuard))yield*R(e.target,e.to.base.field,t[e.to.junction.field],n,e.targetGuard);else yield*R(e.target,O(e.to).field,r,n,e.targetGuard,e.targetMember)}}async function B(e,t,n){let r=null;for await(let i of z(e,t,n)){if(r)throw new g(`AMBIGUOUS_RELATION`);r=i}return r}async function V(t,n,r,i=0){if(v.expand(i,0),w.tables[t].variant&&y.validateDocument(t,n),D(r))return e(r,n);if(r.kind===`variant`)return n[r.discriminator]===r.tag&&V(t,n,r.child,i);if(r.kind===`scalar`)return e(r,n);if(r.kind===`not`)return!await V(t,n,r.child,i);if(r.kind===`and`||r.kind===`or`){for(let e of r.children){let a=await V(t,n,e,i);if(r.kind===`and`&&!a)return!1;if(r.kind===`or`&&a)return!0}return r.kind===`and`}if(r.kind!==`relation`)throw new g(`INVALID_RELATION`);let a=k(t,r.name);if(r.mode===`one`){let e=await B(a,n,i+1);return r.predicate===null?e===null:e!==null&&await V(a.target,e,r.predicate,i+1)}for await(let e of z(a,n,i+1))if(await V(a.target,e,r.predicate,i+1))return r.mode===`some`;return r.mode===`none`}async function H(e,t,n,r,i=[],a=0,o=[]){v.expand(a,0);let s=y.complete(e,t,!0,h,C?.allowed(i));for(let[c,l]of Object.entries(n)){let n=k(e,c),u=l===!0?{}:l;if(n.cardinality===`one`){let e=await B(n,t,a+1);s[c]=e?await H(n.target,e,u,r,[...i,c],a+1,[...o,t._id]):null}else{let n=[...i,c],l=[...o,t._id],d=T.get(JSON.stringify(n))??U(e,c,u,{numItems:r.numItems,cursor:null,order:r.order},[],[],n);s[c]=await W(t,u,n,a+1,l,d,()=>d.bind(l[0]))}}return s}function U(e,n,r,i,a,o,s,c){if(c!==void 0&&a.some(e=>e.value!==null&&e.value!==void 0))throw Error(`orderBy cannot be combined with an active when selector`);y.select(k(e,n).target,r),_(r,s.length);let l=k(e,n);if(l.cardinality!==`many`)throw new g(`INVALID_RELATION`);let u=l.targetGuard?{fields:{[l.targetGuard.discriminator]:l.targetGuard.tag}}:void 0,d=y.plan(l.target,i,[],u?[...o,u]:o,c,`relation`),f=l.from,p=l.to,h=`base`in f&&`base`in p?{table:f.junction.table,field:f.junction.field,targetField:p.base.field,targetReference:p.junction.field}:null;if(c!==void 0&&h)throw Error(`orderBy is unsupported for junction relationships`);let b=h?h.table:l.target,x=h?h.field:O(p).field,w=F(l.target,h?h.targetField:x,d,c===void 0?a:[{value:!0,index:c}],l.targetGuard);C?.checkOrder(l.target,w.fields.filter(e=>e!==(h?h.targetField:x)&&e!==l.targetGuard?.discriminator&&!d.bindings.has(e)),s);let T=h?N(b,x,l.junctionGuard):w;h&&C?.checkOrder(b,T.fields.filter(e=>e!==x&&e!==l.junctionGuard?.discriminator));let E=h||d.unsatisfiable?null:t(T,I(T,x,null,d,l.targetGuard),d.sets,c!==void 0||a.some(e=>e.value!==null&&e.value!==void 0)),D={},A=C?.at(s);A&&(Object.keys(A.fieldGroups).length||Object.keys(A.relations).length)&&(D.fieldGroups=A);let j={...S,table:b,index:T.name,order:d.args.order??`asc`,clientFilters:d.clientIdentity,serverFilters:{predicates:d.sets.size?{predicates:d.serverIdentity,traversal:{version:2,expansion:E?{...E}:null}}:d.serverIdentity,selection:r,...D,scope:{...v.scope},rootTable:S.table,lookupIndex:w.name,guards:{source:l.sourceGuard?{...l.sourceGuard}:null,target:l.targetGuard?{...l.targetGuard}:null,junction:l.junctionGuard?{...l.junctionGuard}:null},...(l.sourceMember||l.targetMember)&&{members:{source:l.sourceMember?{...l.sourceMember}:null,target:l.targetMember?{...l.targetMember}:null}}},relationPath:s},M;async function P(e){return M??=y.registryVersion({root:S.table,path:s,selection:r,groups:A??m,filters:[d.residual]}),{...j,parent:e,registryVersion:await M}}return{declared:l,plan:d,through:h,sourceTable:b,field:x,index:T,targetIndex:w,bind:P,expansion:E}}async function W(e,t,o,s,c,m,h,g){v.expand(s,0);let{declared:_,plan:b,through:S,sourceTable:C,field:w,index:T,targetIndex:E,expansion:D}=m,k=await h(),N=M(_,e),P={...b.args,...g??{cursor:null}},F={...b,expansion:D,index:T,prefix:N==null?[]:S?I(T,w,N,void 0,_.junctionGuard):I(T,w,N,b,_.targetGuard),unsatisfiable:N==null||b.unsatisfiable};if(F.range=S?null:n(T,F.prefix,b.ranges),!S)for(let e of F.prefix){let t=b.ranges.get(e.field);b.bindings.has(e.field)&&u(e.value,b.bindings.get(e.field))!==0&&(F.unsatisfiable=!0),t&&!r(e.value,t)&&(F.unsatisfiable=!0)}let R=S&&S.targetField!==`_id`;return await i(l,v,C,F,y,x,k,P,async(e,n)=>{if(n&&y.validateDocument(R?_.target:C,e),!n||S&&!R&&!A(e,_.junctionGuard))return null;v.expand(s);let r;return r=S&&!R?await L(_.target,e[S.targetReference]):e,!r||!A(r,_.targetGuard)||!j(r[O(_.to).field],_.targetMember)||!await V(_.target,r,b.residual,s)?null:H(_.target,r,t,b.args,o,s,c)},(e,t)=>x.seal(JSON.stringify({cursor:e,ancestors:c.slice(1)}),t),R?(e,t)=>{let r=l,i=f(_.target,E.name,r);return e.flatMap(async e=>{v.expand(s);let o=await v.authorize(C,e);o&&y.validateDocument(C,e);let c=e[S.targetReference];return!o||!A(e,_.junctionGuard)||c==null?new d(b.args.order??`asc`,i):p(t,r).query(_.target).withIndex(E.name,e=>{let t=I(E,S.targetField,c,b,_.targetGuard);return a(e,t,n(E,t,b.ranges))}).order(b.args.order??`asc`)},i)}:void 0,R?_.target:C)}async function G(e,t,n,r,i,a,l,d){if(!n.length||n.length>4||!v.db.normalizeId(e,t))throw new g(`INVALID_RELATION`);let f=e,p=n.map(e=>{let t=k(f,e);return f=t.target,t});if(d!==void 0&&p.some(e=>`base`in e.from||`base`in e.to))throw Error(`orderBy is unsupported for junction relationships`);let m=p.at(-1);for(let e of p.slice(0,-1))(e.cardinality===`one`||`base`in e.from||`base`in e.to)&&P(e);let h=U(m.source,n.at(-1),r,i,a,l,n,d),_,y=()=>_??=h.bind(t).then(e=>i.cursor!==null||i.endCursor!=null?c(e):e);async function S(e){try{return b().parse(JSON.parse(x.open(e,await y())))}catch{throw new s}}let C=i.cursor===null?null:await S(i.cursor),w=i.endCursor==null?null:await S(i.endCursor),T=C?.ancestors??w?.ancestors??[];if(T.length!==n.length-1||C&&w&&JSON.stringify(C.ancestors)!==JSON.stringify(w.ancestors)||T.some((e,t)=>!v.db.normalizeId(p[t].target,e)))throw new s;try{let a=await L(e,t);for(let e=0;a&&e<T.length;e++){let t=p[e],n=null;if(t.cardinality===`many`&&!(`base`in t.from)&&!(`base`in t.to)){v.expand(e+1,0);let r=M(t,a),i=r==null?null:await L(t.target,T[e]),o=t.to.field;r!=null&&i&&A(i,t.targetGuard)&&j(i[o],t.targetMember)&&i[o]!==void 0&&u(r,i[o])===0&&(v.expand(e+1),n=i)}else if(t.cardinality===`one`){let r=await B(t,a,e+1);r?._id===T[e]&&(n=r)}else for await(let r of z(t,a,e+1))if(r._id===T[e]){n=r;break}a=n}return await W(a,r,n,n.length,[t,...T],h,y,{cursor:C?.cursor??null,endCursor:w?.cursor??i.endCursor})}catch(e){o(e)}}function K(e,t,n,r=[]){for(let[i,a]of Object.entries(t)){let t=k(e,i),o=a===!0?{}:a,s=[...r,i];if(t.cardinality===`many`){let t=U(e,i,o,{numItems:n.numItems,cursor:null,order:n.order},[],[],s);T.set(JSON.stringify(s),t)}else P(t,s);K(t.target,o,n,s)}}return{matches:V,output:H,continuation:G,edge:k,preflight:K}}let y;function b(){return y??=x()}function x(){return l.object({cursor:l.string(),ancestors:l.array(l.string()).max(3)})}export{g as RelationshipError,_ as assertRelationshipDepth,v as relationshipExecutor};
2
2
  //# sourceMappingURL=relationships.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"relationships.mjs","names":["emptyGroups","navigation","z","RelationshipError","code","assertRelationshipDepth","nested","selection","depth","relationshipExecutor","metadata","planner","base","leg","edge","declared","table","name","guarded","guard","row","memberIdSchema","memberMatches","member","id","value","request","sourceValue","parent","lookup","index","field","position","i","key","checkTraversal","check","groups","targetPath","path","relationIndex","indexes","bound","plan","usable","length","size","condition","conditions","c","chosen","candidates","b","a","relationPrefix","prefix","get","result","targets","target","iterator","range","q","binding","next","traverse","junction","one","match","matches","scalarOnly","ast","scalarMatches","child","output","dto","selected","args","parents","pageRelation","prepare","ordering","guardConstraint","input","constraints","from","to","through","sourceTable","targetIndex","expansion","expansionForIndex","groupBinding","resolved","rootBinding","rootId","bind","open","codec","token","CursorError","prepared","opened","lookupPlan","rangeForIndex","compareValues","withinRange","indexedTarget","executeStream","schema","permitted","raw","nativeSchema","fields","getIndexFields","source","reference","EmptyStream","stream","db","nativeIndexRange","continuation","rootTable","declarations","declaration","d","final","start","end","ancestors","found","error","rethrowQueryError","preflight","nestedPath"],"sources":["../../src/querying/relationships.ts"],"sourcesContent":["import type { GenericSchema, SchemaDefinition, IndexRangeBuilder } from 'convex/server'\nimport { compareValues, type GenericId, type Value } from 'convex/values'\nimport type { RelationEdge, RelationGuard } from '../relations'\nimport type { createPlanner, QueryInput, StoredConstraint } from './planner'\nimport { scalarMatches } from './planner'\nimport type {\n\tFilterAst,\n\tFilterScalar,\n\tIndexCondition,\n\tNativePagination,\n\tQueryIndex,\n} from './filters'\nimport { expansionForIndex, rangeForIndex, withinRange } from './filters'\nimport {\n\texecuteStream,\n\tnativeIndexRange,\n\trethrowQueryError,\n\ttype ExecutionRequest,\n} from './execution'\nimport type { createCursorCodec, CursorBinding } from './cursors'\nimport { CursorError } from './cursors'\nimport { z } from 'zod'\nimport { stream, EmptyStream, getIndexFields } from 'convex-helpers/server/stream'\n\nexport interface OutputSelection {\n\t[name: string]: true | OutputSelection\n}\nexport type ResolvedGroups = {\n\tfieldGroups: Record<string, { mode: 'required' | 'if-permitted'; allowed: boolean }>\n\trelations: Record<string, ResolvedGroups>\n}\nexport interface GroupAccess {\n\tat(path: readonly string[]): ResolvedGroups\n\tallowed(path: readonly string[]): readonly string[]\n\tcheckOrder(table: string, fields: readonly string[], path?: readonly string[]): void\n}\ntype Edge = RelationEdge<string, string, 'one' | 'many', any, any>\nconst emptyGroups: ResolvedGroups = { fieldGroups: {}, relations: {} }\nexport type RelationDocument = Record<string, Value> & {\n\t_id: GenericId<string>\n\t_creationTime: number\n}\ntype Document = RelationDocument\ntype Planner = ReturnType<typeof createPlanner>\nconst navigation = z.object({ cursor: z.string(), ancestors: z.array(z.string()).max(3) }).strict()\n\nexport class RelationshipError extends Error {\n\tconstructor(readonly code: 'AMBIGUOUS_RELATION' | 'INVALID_RELATION') {\n\t\tsuper(code)\n\t\tthis.name = 'RelationshipError'\n\t}\n}\n\n/** The selection has already passed the registry validator; count leaf edges too. */\nexport function assertRelationshipDepth(selection: OutputSelection, depth: number): void {\n\tfor (const nested of Object.values(selection)) {\n\t\tif (depth >= 4) throw new RelationshipError('INVALID_RELATION')\n\t\tif (nested !== true) assertRelationshipDepth(nested, depth + 1)\n\t}\n}\n\n/** One request owns all traversal and authorized ID memoization. No raw reader escapes. */\nexport function relationshipExecutor(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trequest: ExecutionRequest,\n\tplanner: Planner,\n\tcodec: ReturnType<typeof createCursorCodec>,\n\trootBinding: CursorBinding,\n\tgroups?: GroupAccess,\n) {\n\tconst metadata = planner.metadata\n\tconst base = (leg: Edge['from']) => ('base' in leg ? leg.base : leg)\n\tfunction edge(table: string, name: string): Edge {\n\t\tconst declared = metadata.declarations[table]?.[name]\n\t\tif (!declared) throw new RelationshipError('INVALID_RELATION')\n\t\treturn declared\n\t}\n\tconst guarded = (row: Document | Record<string, Value>, guard?: RelationGuard) =>\n\t\t!guard || row[guard.discriminator] === guard.tag\n\tconst memberIdSchema = z.string()\n\tfunction memberMatches(value: Value | undefined, member: Edge['sourceMember']): boolean {\n\t\tif (!member) return true\n\t\tconst id = memberIdSchema.safeParse(value)\n\t\treturn id.success && request.db.normalizeId(member.table, id.data) !== null\n\t}\n\tfunction sourceValue(declared: Edge, parent: Document | null): Value | undefined {\n\t\tif (!parent || !guarded(parent, declared.sourceGuard)) return undefined\n\t\tconst value = parent[base(declared.from).field]\n\t\treturn memberMatches(value, declared.sourceMember) &&\n\t\t\tmemberMatches(value, declared.targetMember)\n\t\t\t? value\n\t\t\t: undefined\n\t}\n\tfunction lookup(table: string, field: string, guard?: RelationGuard) {\n\t\tconst index =\n\t\t\tfield === '_id'\n\t\t\t\t? { name: 'by_id', fields: ['_id'] }\n\t\t\t\t: metadata.tables[table].indexes.find((i) => {\n\t\t\t\t\t\tconst position = i.fields.indexOf(field)\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tposition >= 0 &&\n\t\t\t\t\t\t\ti.fields.slice(0, position).every((key) => key === guard?.discriminator)\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\tif (!index) throw new RelationshipError('INVALID_RELATION')\n\t\treturn index\n\t}\n\tfunction checkTraversal(declared: Edge, path?: readonly string[]) {\n\t\tfunction check(\n\t\t\ttable: string,\n\t\t\tfield: string,\n\t\t\tguard?: RelationGuard,\n\t\t\ttargetPath?: readonly string[],\n\t\t) {\n\t\t\tgroups?.checkOrder(\n\t\t\t\ttable,\n\t\t\t\tlookup(table, field, guard).fields.filter(\n\t\t\t\t\t(key) => key !== field && key !== guard?.discriminator,\n\t\t\t\t),\n\t\t\t\ttargetPath,\n\t\t\t)\n\t\t}\n\t\tif ('base' in declared.from && 'base' in declared.to) {\n\t\t\tcheck(declared.from.junction.table, declared.from.junction.field, declared.junctionGuard)\n\t\t\tcheck(declared.target, declared.to.base.field, declared.targetGuard, path)\n\t\t} else check(declared.target, base(declared.to).field, declared.targetGuard, path)\n\t}\n\tfunction relationIndex(\n\t\ttable: string,\n\t\tfield: string,\n\t\tplan: ReturnType<Planner['plan']>,\n\t\tconditions: readonly IndexCondition[],\n\t\tguard?: RelationGuard,\n\t): QueryIndex {\n\t\tconst indexes =\n\t\t\tfield === '_id' ? [{ name: 'by_id', fields: ['_id'] }] : metadata.tables[table].indexes\n\t\tconst bound = (key: string) =>\n\t\t\tkey === field || key === guard?.discriminator || plan.bindings.has(key)\n\t\tconst usable = (index: QueryIndex) =>\n\t\t\tindex.fields.includes(field) &&\n\t\t\tindex.fields.slice(0, index.fields.indexOf(field)).every(bound)\n\t\tconst length = (index: QueryIndex) => {\n\t\t\tlet size = 0\n\t\t\tfor (const key of index.fields) {\n\t\t\t\tif (!bound(key)) break\n\t\t\t\tsize++\n\t\t\t}\n\t\t\treturn size\n\t\t}\n\t\tconst condition = conditions.find((c) => c.value !== null && c.value !== undefined)\n\t\tif (condition) {\n\t\t\tconst chosen = indexes.find((i) => i.name === condition.index && usable(i))\n\t\t\tif (!chosen)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Explicit index \"${condition.index}\" is incompatible with declared relationship lookup`,\n\t\t\t\t)\n\t\t\treturn chosen\n\t\t}\n\t\tconst candidates = indexes\n\t\t\t.filter(usable)\n\t\t\t.sort(\n\t\t\t\t(a, b) =>\n\t\t\t\t\tlength(b) - length(a) ||\n\t\t\t\t\tNumber(plan.sets.has(b.fields[length(b)])) - Number(plan.sets.has(a.fields[length(a)])) ||\n\t\t\t\t\tNumber(plan.ranges.has(b.fields[length(b)])) -\n\t\t\t\t\t\tNumber(plan.ranges.has(a.fields[length(a)])) ||\n\t\t\t\t\ta.name.localeCompare(b.name) ||\n\t\t\t\t\ta.fields.join('\\0').localeCompare(b.fields.join('\\0')),\n\t\t\t)\n\t\tif (!candidates.length) throw new RelationshipError('INVALID_RELATION')\n\t\treturn candidates[0]\n\t}\n\tfunction relationPrefix(\n\t\tindex: QueryIndex,\n\t\tfield: string,\n\t\tvalue: FilterScalar,\n\t\tplan?: ReturnType<Planner['plan']>,\n\t\tguard?: RelationGuard,\n\t) {\n\t\tconst prefix: { field: string; value: FilterScalar }[] = []\n\t\tfor (const key of index.fields) {\n\t\t\tif (key === field) prefix.push({ field: key, value })\n\t\t\telse if (key === guard?.discriminator) prefix.push({ field: key, value: guard.tag })\n\t\t\telse if (plan?.bindings.has(key)) prefix.push({ field: key, value: plan.bindings.get(key)! })\n\t\t\telse break\n\t\t}\n\t\treturn prefix\n\t}\n\n\tasync function get(table: string, id: Value | undefined): Promise<Document | null> {\n\t\tplanner.beforeLeaf(table)\n\t\t// SAFETY: native normalization rejects non-string/non-table IDs before any read.\n\t\tif (id == null || !request.db.normalizeId(table, id as string)) return null\n\t\t// SAFETY: normalizeId verifies the declared native table before the authorized metered get.\n\t\tconst result = await request.db.get(table, id as GenericId<string>)\n\t\tif (result) planner.validateDocument(table, result)\n\t\t// SAFETY: normalizeId checked the table; the authorized native get retains system fields.\n\t\treturn result as Document | null\n\t}\n\tasync function* targets(\n\t\ttable: string,\n\t\tfield: string,\n\t\tvalue: Value | undefined,\n\t\tdepth: number,\n\t\tguard?: RelationGuard,\n\t\tmember?: Edge['targetMember'],\n\t): AsyncGenerator<Document> {\n\t\trequest.expand(depth, 0)\n\t\tif (value == null || !memberMatches(value, member)) return\n\t\tif (field === '_id') {\n\t\t\tconst target = await get(table, value)\n\t\t\tif (target && guarded(target, guard) && memberMatches(target[field], member)) {\n\t\t\t\trequest.expand(depth)\n\t\t\t\tyield target\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tplanner.beforeLeaf(table)\n\t\tconst index = lookup(table, field, guard)\n\t\t// SAFETY: registry validates the indexed native lookup prefix and compatible values.\n\t\tconst source = request.leafQuery(table).withIndex(index.name, (q) => {\n\t\t\t// SAFETY: registration checks the mandatory join and every preceding guard equality.\n\t\t\tlet range = q as IndexRangeBuilder<any, string[], number>\n\t\t\t// SAFETY: registered relation fields are native scalars; each equality advances the consecutive checked prefix.\n\t\t\tfor (const binding of relationPrefix(index, field, value as FilterScalar, undefined, guard)) {\n\t\t\t\t// SAFETY: the prefix comes from the declared index and registry-owned guard.\n\t\t\t\trange = range.eq(binding.field, binding.value) as IndexRangeBuilder<any, string[], number>\n\t\t\t}\n\t\t\treturn range\n\t\t})\n\t\tconst iterator = source[Symbol.asyncIterator]()\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tplanner.beforeLeaf(table)\n\t\t\t\tconst next = await iterator.next()\n\t\t\t\tif (next.done) return\n\t\t\t\tconst permitted = await request.authorize(table, next.value)\n\t\t\t\t// Denials are an await boundary too; never hide them inside an authorized iterator.\n\t\t\t\tif (!permitted) continue\n\t\t\t\tplanner.validateDocument(table, next.value)\n\t\t\t\tif (!guarded(next.value, guard) || !memberMatches(next.value[field], member)) continue\n\t\t\t\trequest.expand(depth)\n\t\t\t\t// SAFETY: native rows include system fields and explicit authorization just completed.\n\t\t\t\tyield next.value as Document\n\t\t\t}\n\t\t} finally {\n\t\t\tawait iterator.return?.()\n\t\t}\n\t}\n\tasync function* traverse(\n\t\tdeclared: Edge,\n\t\tparent: Document,\n\t\tdepth: number,\n\t): AsyncGenerator<Document> {\n\t\trequest.expand(depth, 0)\n\t\tconst value = sourceValue(declared, parent)\n\t\tif (value == null) return\n\t\tif ('base' in declared.from && 'base' in declared.to) {\n\t\t\tfor await (const junction of targets(\n\t\t\t\tdeclared.from.junction.table,\n\t\t\t\tdeclared.from.junction.field,\n\t\t\t\tvalue,\n\t\t\t\tdepth,\n\t\t\t\tdeclared.junctionGuard,\n\t\t\t))\n\t\t\t\tyield* targets(\n\t\t\t\t\tdeclared.target,\n\t\t\t\t\tdeclared.to.base.field,\n\t\t\t\t\tjunction[declared.to.junction.field],\n\t\t\t\t\tdepth,\n\t\t\t\t\tdeclared.targetGuard,\n\t\t\t\t)\n\t\t} else\n\t\t\tyield* targets(\n\t\t\t\tdeclared.target,\n\t\t\t\tbase(declared.to).field,\n\t\t\t\tvalue,\n\t\t\t\tdepth,\n\t\t\t\tdeclared.targetGuard,\n\t\t\t\tdeclared.targetMember,\n\t\t\t)\n\t}\n\tasync function one(declared: Edge, parent: Document, depth: number) {\n\t\tlet match: Document | null = null\n\t\tfor await (const target of traverse(declared, parent, depth)) {\n\t\t\tif (match) throw new RelationshipError('AMBIGUOUS_RELATION')\n\t\t\tmatch = target\n\t\t}\n\t\treturn match\n\t}\n\tasync function matches(\n\t\ttable: string,\n\t\tparent: Document,\n\t\tast: FilterAst,\n\t\tdepth = 0,\n\t): Promise<boolean> {\n\t\trequest.expand(depth, 0)\n\t\t// Variant rows must satisfy the captured stored branch before predicates\n\t\t// inspect branch fields. Ordinary output rows are validated by projection.\n\t\tif (metadata.tables[table].variant) planner.validateDocument(table, parent)\n\t\tif (scalarOnly(ast)) return scalarMatches(ast, parent)\n\t\tif (ast.kind === 'variant')\n\t\t\treturn parent[ast.discriminator] === ast.tag && matches(table, parent, ast.child, depth)\n\t\tif (ast.kind === 'scalar') return scalarMatches(ast, parent)\n\t\tif (ast.kind === 'not') return !(await matches(table, parent, ast.child, depth))\n\t\tif (ast.kind === 'and' || ast.kind === 'or') {\n\t\t\tfor (const child of ast.children) {\n\t\t\t\tconst result = await matches(table, parent, child, depth)\n\t\t\t\tif (ast.kind === 'and' && !result) return false\n\t\t\t\tif (ast.kind === 'or' && result) return true\n\t\t\t}\n\t\t\treturn ast.kind === 'and'\n\t\t}\n\t\tif (ast.kind !== 'relation') throw new RelationshipError('INVALID_RELATION')\n\t\tconst declared = edge(table, ast.name)\n\t\tif (ast.mode === 'one') {\n\t\t\tconst target = await one(declared, parent, depth + 1)\n\t\t\treturn ast.predicate === null\n\t\t\t\t? target === null\n\t\t\t\t: target !== null && (await matches(declared.target, target, ast.predicate, depth + 1))\n\t\t}\n\t\tfor await (const target of traverse(declared, parent, depth + 1))\n\t\t\tif (await matches(declared.target, target, ast.predicate!, depth + 1))\n\t\t\t\treturn ast.mode === 'some'\n\t\t// Only actual authorized traversal exhaustion proves none.\n\t\treturn ast.mode === 'none'\n\t}\n\tasync function output(\n\t\ttable: string,\n\t\tparent: Document,\n\t\tselection: OutputSelection,\n\t\targs: NativePagination & { order?: 'asc' | 'desc' },\n\t\tpath: readonly string[] = [],\n\t\tdepth = 0,\n\t\tparents: readonly string[] = [],\n\t): Promise<Record<string, Value>> {\n\t\trequest.expand(depth, 0)\n\t\t// SAFETY: the registry strictly validates this public native DTO projection.\n\t\tconst dto = planner.complete(\n\t\t\ttable,\n\t\t\tparent,\n\t\t\ttrue,\n\t\t\t{ kind: 'and', children: [] },\n\t\t\tgroups?.allowed(path),\n\t\t) as Record<string, Value>\n\t\tfor (const [name, selected] of Object.entries(selection)) {\n\t\t\tconst declared = edge(table, name),\n\t\t\t\tnested = selected === true ? {} : selected\n\t\t\tif (declared.cardinality === 'one') {\n\t\t\t\tconst target = await one(declared, parent, depth + 1)\n\t\t\t\tdto[name] = target\n\t\t\t\t\t? await output(declared.target, target, nested, args, [...path, name], depth + 1, [\n\t\t\t\t\t\t\t...parents,\n\t\t\t\t\t\t\tparent._id,\n\t\t\t\t\t\t])\n\t\t\t\t\t: null\n\t\t\t} else {\n\t\t\t\tconst page = await pageRelation(\n\t\t\t\t\ttable,\n\t\t\t\t\tparent,\n\t\t\t\t\tname,\n\t\t\t\t\tnested,\n\t\t\t\t\t{ numItems: args.numItems, cursor: null, order: args.order },\n\t\t\t\t\t[],\n\t\t\t\t\t[],\n\t\t\t\t\t[...path, name],\n\t\t\t\t\tdepth + 1,\n\t\t\t\t\t[...parents, parent._id],\n\t\t\t\t)\n\t\t\t\t// SAFETY: pageRelation projects and validates each nested DTO row.\n\t\t\t\tdto[name] = page as Value\n\t\t\t}\n\t\t}\n\t\treturn dto\n\t}\n\tfunction prepare(\n\t\ttable: string,\n\t\tname: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[],\n\t\tconstraints: readonly StoredConstraint[],\n\t\tpath: readonly string[],\n\t\trootId: string,\n\t\tordering?: string,\n\t) {\n\t\tif (ordering !== undefined && conditions.some((c) => c.value !== null && c.value !== undefined))\n\t\t\tthrow new Error('orderBy cannot be combined with an active when selector')\n\t\tplanner.select(edge(table, name).target, selection)\n\t\tassertRelationshipDepth(selection, path.length)\n\t\tconst declared = edge(table, name)\n\t\tif (declared.cardinality !== 'many') throw new RelationshipError('INVALID_RELATION')\n\t\tconst guardConstraint = declared.targetGuard\n\t\t\t? { fields: { [declared.targetGuard.discriminator]: declared.targetGuard.tag } }\n\t\t\t: undefined\n\t\tconst plan = planner.plan(\n\t\t\tdeclared.target,\n\t\t\tinput,\n\t\t\t[],\n\t\t\tguardConstraint ? [...constraints, guardConstraint] : constraints,\n\t\t\tordering,\n\t\t\t'relation',\n\t\t)\n\t\tconst from = declared.from,\n\t\t\tto = declared.to\n\t\tconst through =\n\t\t\t'base' in from && 'base' in to\n\t\t\t\t? {\n\t\t\t\t\t\ttable: from.junction.table,\n\t\t\t\t\t\tfield: from.junction.field,\n\t\t\t\t\t\ttargetField: to.base.field,\n\t\t\t\t\t\ttargetReference: to.junction.field,\n\t\t\t\t\t}\n\t\t\t\t: null\n\t\tif (ordering !== undefined && through)\n\t\t\tthrow new Error('orderBy is unsupported for junction relationships')\n\t\tconst sourceTable = through ? through.table : declared.target\n\t\tconst field = through ? through.field : base(to).field\n\t\tconst targetIndex = relationIndex(\n\t\t\tdeclared.target,\n\t\t\tthrough ? through.targetField : field,\n\t\t\tplan,\n\t\t\tordering === undefined ? conditions : [{ value: true, index: ordering }],\n\t\t\tdeclared.targetGuard,\n\t\t)\n\t\tgroups?.checkOrder(\n\t\t\tdeclared.target,\n\t\t\ttargetIndex.fields.filter(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey !== (through ? through.targetField : field) &&\n\t\t\t\t\tkey !== declared.targetGuard?.discriminator &&\n\t\t\t\t\t!plan.bindings.has(key),\n\t\t\t),\n\t\t\tpath,\n\t\t)\n\t\tconst index = through ? lookup(sourceTable, field, declared.junctionGuard) : targetIndex\n\t\tif (through)\n\t\t\tgroups?.checkOrder(\n\t\t\t\tsourceTable,\n\t\t\t\tindex.fields.filter(\n\t\t\t\t\t(key) => key !== field && key !== declared.junctionGuard?.discriminator,\n\t\t\t\t),\n\t\t\t)\n\t\t// The lookup value changes only values, not prefix positions or comparator.\n\t\tconst expansion =\n\t\t\tthrough || plan.unsatisfiable\n\t\t\t\t? null\n\t\t\t\t: expansionForIndex(\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\trelationPrefix(index, field, null, plan, declared.targetGuard),\n\t\t\t\t\t\tplan.sets,\n\t\t\t\t\t\tordering !== undefined ||\n\t\t\t\t\t\t\tconditions.some((c) => c.value !== null && c.value !== undefined),\n\t\t\t\t\t)\n\t\tconst groupBinding: Record<string, Value> = {}\n\t\tconst resolved = groups?.at(path)\n\t\tif (\n\t\t\tresolved &&\n\t\t\t(Object.keys(resolved.fieldGroups).length || Object.keys(resolved.relations).length)\n\t\t)\n\t\t\tgroupBinding.fieldGroups = resolved\n\t\t// SAFETY: planner.page validated the complete output mask before cursor binding.\n\t\tconst binding: CursorBinding = {\n\t\t\t...rootBinding,\n\t\t\ttable: sourceTable,\n\t\t\tindex: index.name,\n\t\t\torder: plan.args.order ?? 'asc',\n\t\t\tclientFilters: plan.clientIdentity,\n\t\t\tserverFilters: {\n\t\t\t\tpredicates: plan.sets.size\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpredicates: plan.serverIdentity,\n\t\t\t\t\t\t\ttraversal: { version: 2, expansion: expansion ? { ...expansion } : null },\n\t\t\t\t\t\t}\n\t\t\t\t\t: plan.serverIdentity,\n\t\t\t\tselection: selection as Value,\n\t\t\t\t...groupBinding,\n\t\t\t\tscope: { ...request.scope },\n\t\t\t\trootTable: rootBinding.table,\n\t\t\t\tlookupIndex: targetIndex.name,\n\t\t\t\tguards: {\n\t\t\t\t\tsource: declared.sourceGuard ? { ...declared.sourceGuard } : null,\n\t\t\t\t\ttarget: declared.targetGuard ? { ...declared.targetGuard } : null,\n\t\t\t\t\tjunction: declared.junctionGuard ? { ...declared.junctionGuard } : null,\n\t\t\t\t},\n\t\t\t\t...((declared.sourceMember || declared.targetMember) && {\n\t\t\t\t\tmembers: {\n\t\t\t\t\t\tsource: declared.sourceMember ? { ...declared.sourceMember } : null,\n\t\t\t\t\t\ttarget: declared.targetMember ? { ...declared.targetMember } : null,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t\trelationPath: path,\n\t\t\tparent: rootId,\n\t\t}\n\t\t// Each child path binds the registry scope it reads. A relation route from\n\t\t// the same root computes the same scope, so it can open this path's cursors.\n\t\tlet bound: Promise<CursorBinding> | undefined\n\t\tfunction bind() {\n\t\t\tbound ??= planner\n\t\t\t\t.registryVersion({\n\t\t\t\t\troot: rootBinding.table,\n\t\t\t\t\tpath,\n\t\t\t\t\tselection,\n\t\t\t\t\tgroups: resolved ?? emptyGroups,\n\t\t\t\t\tfilters: [plan.residual],\n\t\t\t\t})\n\t\t\t\t.then((registryVersion) => ({ ...binding, registryVersion }))\n\t\t\treturn bound\n\t\t}\n\t\tasync function open(token: string) {\n\t\t\ttry {\n\t\t\t\treturn navigation.parse(JSON.parse(codec.open(token, await bind())))\n\t\t\t} catch {\n\t\t\t\tthrow new CursorError()\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tdeclared,\n\t\t\tplan,\n\t\t\tthrough,\n\t\t\tsourceTable,\n\t\t\tfield,\n\t\t\tindex,\n\t\t\ttargetIndex,\n\t\t\tbind,\n\t\t\topen,\n\t\t\texpansion,\n\t\t}\n\t}\n\tasync function pageRelation(\n\t\ttable: string,\n\t\tparent: Document | null,\n\t\tname: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[] = [],\n\t\tconstraints: readonly StoredConstraint[] = [],\n\t\tpath: readonly string[] = [name],\n\t\tdepth = 1,\n\t\tparents: readonly string[] = [],\n\t\tprepared = prepare(\n\t\t\ttable,\n\t\t\tname,\n\t\t\tselection,\n\t\t\tinput,\n\t\t\tconditions,\n\t\t\tconstraints,\n\t\t\tpath,\n\t\t\tparents[0] ?? parent!._id,\n\t\t),\n\t\topened?: { cursor: string | null; endCursor?: string | null },\n\t) {\n\t\trequest.expand(depth, 0)\n\t\tconst { declared, plan, through, sourceTable, field, index, targetIndex, expansion } = prepared\n\t\tconst binding = await prepared.bind()\n\t\tconst value = sourceValue(declared, parent)\n\t\tconst args = { ...plan.args, ...(opened ?? { cursor: null }) }\n\t\t// SAFETY: declarations accept only native scalar lookup values; nullish references are absence.\n\t\tconst lookupPlan = {\n\t\t\t...plan,\n\t\t\texpansion,\n\t\t\tindex,\n\t\t\tprefix:\n\t\t\t\tvalue == null\n\t\t\t\t\t? []\n\t\t\t\t\t: through\n\t\t\t\t\t\t? relationPrefix(index, field, value as FilterScalar, undefined, declared.junctionGuard)\n\t\t\t\t\t\t: relationPrefix(index, field, value as FilterScalar, plan, declared.targetGuard),\n\t\t\tunsatisfiable: value == null || plan.unsatisfiable,\n\t\t}\n\t\tlookupPlan.range = through ? null : rangeForIndex(index, lookupPlan.prefix, plan.ranges)\n\t\tif (!through)\n\t\t\tfor (const binding of lookupPlan.prefix) {\n\t\t\t\tconst range = plan.ranges.get(binding.field)\n\t\t\t\tif (\n\t\t\t\t\tplan.bindings.has(binding.field) &&\n\t\t\t\t\tcompareValues(binding.value, plan.bindings.get(binding.field)!) !== 0\n\t\t\t\t)\n\t\t\t\t\tlookupPlan.unsatisfiable = true\n\t\t\t\tif (range && !withinRange(binding.value, range)) lookupPlan.unsatisfiable = true\n\t\t\t}\n\t\tconst indexedTarget = through && through.targetField !== '_id'\n\t\tconst result = await executeStream(\n\t\t\tschema,\n\t\t\trequest,\n\t\t\tsourceTable,\n\t\t\tlookupPlan,\n\t\t\tplanner,\n\t\t\tcodec,\n\t\t\tbinding,\n\t\t\targs,\n\t\t\tasync (row, permitted) => {\n\t\t\t\tif (permitted) planner.validateDocument(indexedTarget ? declared.target : sourceTable, row)\n\t\t\t\tif (!permitted || (through && !indexedTarget && !guarded(row, declared.junctionGuard)))\n\t\t\t\t\treturn null\n\t\t\t\trequest.expand(depth)\n\t\t\t\tlet target: Document | null\n\t\t\t\tif (through && !indexedTarget)\n\t\t\t\t\ttarget = await get(declared.target, row[through.targetReference])\n\t\t\t\telse {\n\t\t\t\t\t// SAFETY: native direct/flattened target streams retain validated system fields.\n\t\t\t\t\ttarget = row as Document\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!target ||\n\t\t\t\t\t!guarded(target, declared.targetGuard) ||\n\t\t\t\t\t!memberMatches(target[base(declared.to).field], declared.targetMember) ||\n\t\t\t\t\t!(await matches(declared.target, target, plan.residual, depth))\n\t\t\t\t)\n\t\t\t\t\treturn null\n\t\t\t\treturn output(declared.target, target, selection, plan.args, path, depth, parents)\n\t\t\t},\n\t\t\t(raw) => codec.seal(JSON.stringify({ cursor: raw, ancestors: parents.slice(1) }), binding),\n\t\t\tindexedTarget\n\t\t\t\t? (source, db) => {\n\t\t\t\t\t\t// SAFETY: the registry owns the native schema/index descriptors. Public\n\t\t\t\t\t\t// helper flatMap concatenates native outer/inner keys and paginates them.\n\t\t\t\t\t\tconst nativeSchema = schema as SchemaDefinition<\n\t\t\t\t\t\t\tRecord<\n\t\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\t\timport('convex/server').TableDefinition<any, Record<string, string[]>>\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\tboolean\n\t\t\t\t\t\t>\n\t\t\t\t\t\tconst fields = getIndexFields(declared.target, targetIndex.name, nativeSchema)\n\t\t\t\t\t\treturn source.flatMap(async (junction) => {\n\t\t\t\t\t\t\trequest.expand(depth)\n\t\t\t\t\t\t\tconst permitted = await request.authorize(sourceTable, junction)\n\t\t\t\t\t\t\tif (permitted) planner.validateDocument(sourceTable, junction)\n\t\t\t\t\t\t\tconst reference = junction[through.targetReference]\n\t\t\t\t\t\t\tif (!permitted || !guarded(junction, declared.junctionGuard) || reference == null)\n\t\t\t\t\t\t\t\treturn new EmptyStream(plan.args.order ?? 'asc', fields)\n\t\t\t\t\t\t\treturn stream(db, nativeSchema)\n\t\t\t\t\t\t\t\t.query(declared.target)\n\t\t\t\t\t\t\t\t.withIndex(targetIndex.name, (q) => {\n\t\t\t\t\t\t\t\t\t// SAFETY: registry-owned lookup bindings are native scalar index values.\n\t\t\t\t\t\t\t\t\tconst prefix = relationPrefix(\n\t\t\t\t\t\t\t\t\t\ttargetIndex,\n\t\t\t\t\t\t\t\t\t\tthrough.targetField,\n\t\t\t\t\t\t\t\t\t\treference as FilterScalar,\n\t\t\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t\t\tdeclared.targetGuard,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\treturn nativeIndexRange(\n\t\t\t\t\t\t\t\t\t\tq,\n\t\t\t\t\t\t\t\t\t\tprefix,\n\t\t\t\t\t\t\t\t\t\trangeForIndex(targetIndex, prefix, plan.ranges),\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\t.order(plan.args.order ?? 'asc')\n\t\t\t\t\t\t}, fields)\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tindexedTarget ? declared.target : sourceTable,\n\t\t)\n\t\treturn result\n\t}\n\tasync function continuation(\n\t\trootTable: string,\n\t\trootId: string,\n\t\tpath: readonly string[],\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[],\n\t\tconstraints: readonly StoredConstraint[],\n\t\tordering?: string,\n\t) {\n\t\tif (!path.length || path.length > 4 || !request.db.normalizeId(rootTable, rootId))\n\t\t\tthrow new RelationshipError('INVALID_RELATION')\n\t\tlet table = rootTable\n\t\tconst declarations = path.map((name) => {\n\t\t\tconst declaration = edge(table, name)\n\t\t\ttable = declaration.target\n\t\t\treturn declaration\n\t\t})\n\t\tif (ordering !== undefined && declarations.some((d) => 'base' in d.from || 'base' in d.to))\n\t\t\tthrow new Error('orderBy is unsupported for junction relationships')\n\t\tconst final = declarations.at(-1)!\n\t\tfor (const declaration of declarations.slice(0, -1))\n\t\t\tif (\n\t\t\t\tdeclaration.cardinality === 'one' ||\n\t\t\t\t'base' in declaration.from ||\n\t\t\t\t'base' in declaration.to\n\t\t\t)\n\t\t\t\tcheckTraversal(declaration)\n\t\tconst prepared = prepare(\n\t\t\tfinal.source,\n\t\t\tpath.at(-1)!,\n\t\t\tselection,\n\t\t\tinput,\n\t\t\tconditions,\n\t\t\tconstraints,\n\t\t\tpath,\n\t\t\trootId,\n\t\t\tordering,\n\t\t)\n\t\t// Authenticate both slots and native ancestor IDs before ANY parent/traversal read.\n\t\tconst start = input.cursor === null ? null : await prepared.open(input.cursor)\n\t\tconst end = input.endCursor == null ? null : await prepared.open(input.endCursor)\n\t\tconst ancestors = start?.ancestors ?? end?.ancestors ?? []\n\t\tif (\n\t\t\tancestors.length !== path.length - 1 ||\n\t\t\t(start && end && JSON.stringify(start.ancestors) !== JSON.stringify(end.ancestors)) ||\n\t\t\tancestors.some((id, i) => !request.db.normalizeId(declarations[i].target, id))\n\t\t)\n\t\t\tthrow new CursorError()\n\t\t// Declarative input/index/cursor validation above retains its pre-read errors,\n\t\t// just as on the root path. Every awaited read, ancestry proof and page is protected.\n\t\ttry {\n\t\t\tlet parent = await get(rootTable, rootId)\n\t\t\tfor (let i = 0; parent && i < ancestors.length; i++) {\n\t\t\t\tconst declared = declarations[i]\n\t\t\t\tlet found: Document | null = null\n\t\t\t\tif (\n\t\t\t\t\tdeclared.cardinality === 'many' &&\n\t\t\t\t\t!('base' in declared.from) &&\n\t\t\t\t\t!('base' in declared.to)\n\t\t\t\t) {\n\t\t\t\t\t// A cursor names this ancestor. Prove its current authorized membership\n\t\t\t\t\t// by ID instead of replaying an ordering that is not part of this page.\n\t\t\t\t\trequest.expand(i + 1, 0)\n\t\t\t\t\tconst value = sourceValue(declared, parent)\n\t\t\t\t\tconst target = value == null ? null : await get(declared.target, ancestors[i])\n\t\t\t\t\tconst key = declared.to.field\n\t\t\t\t\tif (\n\t\t\t\t\t\tvalue != null &&\n\t\t\t\t\t\ttarget &&\n\t\t\t\t\t\tguarded(target, declared.targetGuard) &&\n\t\t\t\t\t\tmemberMatches(target[key], declared.targetMember) &&\n\t\t\t\t\t\ttarget[key] !== undefined &&\n\t\t\t\t\t\tcompareValues(value, target[key]) === 0\n\t\t\t\t\t) {\n\t\t\t\t\t\trequest.expand(i + 1)\n\t\t\t\t\t\tfound = target\n\t\t\t\t\t}\n\t\t\t\t} else if (declared.cardinality === 'one') {\n\t\t\t\t\tconst target = await one(declared, parent, i + 1)\n\t\t\t\t\tif (target?._id === ancestors[i]) found = target\n\t\t\t\t} else\n\t\t\t\t\tfor await (const target of traverse(declared, parent, i + 1)) {\n\t\t\t\t\t\tif (target._id === ancestors[i]) {\n\t\t\t\t\t\t\tfound = target\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tparent = found\n\t\t\t}\n\t\t\treturn await pageRelation(\n\t\t\t\tfinal.source,\n\t\t\t\tparent,\n\t\t\t\tpath.at(-1)!,\n\t\t\t\tselection,\n\t\t\t\tinput,\n\t\t\t\tconditions,\n\t\t\t\tconstraints,\n\t\t\t\tpath,\n\t\t\t\tpath.length,\n\t\t\t\t[rootId, ...ancestors],\n\t\t\t\tprepared,\n\t\t\t\t{ cursor: start?.cursor ?? null, endCursor: end?.cursor ?? input.endCursor },\n\t\t\t)\n\t\t} catch (error) {\n\t\t\trethrowQueryError(error)\n\t\t}\n\t}\n\t/** Admit the complete output tree even when a parent query produces no rows. */\n\tfunction preflight(\n\t\ttable: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tpath: readonly string[] = [],\n\t) {\n\t\tfor (const [name, selected] of Object.entries(selection)) {\n\t\t\tconst declared = edge(table, name)\n\t\t\tconst nested = selected === true ? {} : selected\n\t\t\tconst nestedPath = [...path, name]\n\t\t\tif (declared.cardinality === 'many')\n\t\t\t\tprepare(\n\t\t\t\t\ttable,\n\t\t\t\t\tname,\n\t\t\t\t\tnested,\n\t\t\t\t\t{ numItems: input.numItems, cursor: null, order: input.order },\n\t\t\t\t\t[],\n\t\t\t\t\t[],\n\t\t\t\t\tnestedPath,\n\t\t\t\t\t'',\n\t\t\t\t)\n\t\t\telse checkTraversal(declared, nestedPath)\n\t\t\tpreflight(declared.target, nested, input, nestedPath)\n\t\t}\n\t}\n\treturn { matches, output, continuation, edge, preflight }\n}\n\nfunction scalarOnly(ast: FilterAst): boolean {\n\tif (ast.kind === 'relation') return false\n\tif (ast.kind === 'and' || ast.kind === 'or') return ast.children.every(scalarOnly)\n\tif (ast.kind === 'not' || ast.kind === 'variant') return scalarOnly(ast.child)\n\treturn true\n}\n"],"mappings":"8aAqCA,MAAMA,EAA8B,CAAE,YAAa,CAAC,EAAG,UAAW,CAAC,CAAE,EAO/DC,EAAaC,EAAE,OAAO,CAAE,OAAQA,EAAE,OAAO,EAAG,UAAWA,EAAE,MAAMA,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAE,CAAC,CAAC,CAAC,OAA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AAShE,EAAW,EAAyB,CAI5C,OAHIC,EAAI,OAAS,WAAmB,GAChCA,EAAI,OAAS,OAASA,EAAI,OAAS,KAAaA,EAAI,SAAS,MAAMD,CAAU,EAC7EC,EAAI,OAAS,OAASA,EAAI,OAAS,UAAkBD,EAAWC,EAAI,KAAK,EACtE,EACR"}
1
+ {"version":3,"file":"relationships.mjs","names":["emptyGroups","noPredicate","RelationshipError","code","assertRelationshipDepth","nested","selection","depth","relationshipExecutor","metadata","planner","childPlans","scalarPredicates","scalarOnly","cached","ast","result","base","leg","edge","declared","table","name","guarded","guard","row","memberMatches","member","value","request","sourceValue","parent","lookup","index","field","position","i","key","checkTraversal","check","groups","targetPath","path","relationIndex","indexes","bound","plan","usable","length","size","condition","conditions","c","chosen","candidates","b","a","relationPrefix","prefix","get","id","targets","target","iterator","range","q","binding","next","traverse","junction","one","match","matches","scalarMatches","child","output","dto","selected","args","parents","childPath","childParents","prepared","prepare","pageRelation","ordering","guardConstraint","input","constraints","from","to","through","sourceTable","targetIndex","expansion","expansionForIndex","groupBinding","resolved","rootBinding","version","bind","rootId","opened","lookupPlan","rangeForIndex","compareValues","withinRange","indexedTarget","executeStream","schema","codec","permitted","raw","nativeSchema","fields","getIndexFields","source","reference","EmptyStream","stream","db","nativeIndexRange","continuation","rootTable","declarations","declaration","d","final","prepareCursorBinding","open","navigation","token","CursorError","start","end","ancestors","found","error","rethrowQueryError","preflight","nestedPath","navigationSchema","buildNavigation","k"],"sources":["../../src/querying/relationships.ts"],"sourcesContent":["import type { GenericSchema, SchemaDefinition, IndexRangeBuilder } from 'convex/server'\nimport { compareValues, type GenericId, type Value } from 'convex/values'\nimport type { RelationEdge, RelationGuard } from '../relations'\nimport type { createPlanner, QueryInput, StoredConstraint } from './planner'\nimport { scalarMatches } from './planner'\nimport type {\n\tFilterAst,\n\tFilterScalar,\n\tIndexCondition,\n\tNativePagination,\n\tQueryIndex,\n} from './filters'\nimport { expansionForIndex, rangeForIndex, withinRange } from './filters'\nimport {\n\texecuteStream,\n\tnativeIndexRange,\n\trethrowQueryError,\n\ttype ExecutionRequest,\n} from './execution'\nimport type { createCursorCodec, CursorBinding } from './cursors'\nimport { CursorError, prepareCursorBinding } from './cursors'\nimport { k } from '../k'\nimport { stream, EmptyStream, getIndexFields } from 'convex-helpers/server/stream'\n\nexport interface OutputSelection {\n\t[name: string]: true | OutputSelection\n}\nexport type ResolvedGroups = {\n\tfieldGroups: Record<string, { mode: 'required' | 'if-permitted'; allowed: boolean }>\n\trelations: Record<string, ResolvedGroups>\n}\nexport interface GroupAccess {\n\tat(path: readonly string[]): ResolvedGroups\n\tallowed(path: readonly string[]): readonly string[]\n\tcheckOrder(table: string, fields: readonly string[], path?: readonly string[]): void\n}\ntype Edge = RelationEdge<string, string, 'one' | 'many', any, any>\nconst emptyGroups: ResolvedGroups = { fieldGroups: {}, relations: {} }\nconst noPredicate: FilterAst = { kind: 'and', children: [] }\nexport type RelationDocument = Record<string, Value> & {\n\t_id: GenericId<string>\n\t_creationTime: number\n}\ntype Document = RelationDocument\ntype Planner = ReturnType<typeof createPlanner>\n\nexport class RelationshipError extends Error {\n\tconstructor(readonly code: 'AMBIGUOUS_RELATION' | 'INVALID_RELATION') {\n\t\tsuper(code)\n\t\tthis.name = 'RelationshipError'\n\t}\n}\n\n/** The selection has already passed the registry validator; count leaf edges too. */\nexport function assertRelationshipDepth(selection: OutputSelection, depth: number): void {\n\tfor (const nested of Object.values(selection)) {\n\t\tif (depth >= 4) throw new RelationshipError('INVALID_RELATION')\n\t\tif (nested !== true) assertRelationshipDepth(nested, depth + 1)\n\t}\n}\n\n/** One request owns all traversal and authorized ID memoization. No raw reader escapes. */\nexport function relationshipExecutor(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trequest: ExecutionRequest,\n\tplanner: Planner,\n\tcodec: ReturnType<typeof createCursorCodec>,\n\trootBinding: CursorBinding,\n\tgroups?: GroupAccess,\n) {\n\tconst metadata = planner.metadata\n\tconst childPlans = new Map<string, ReturnType<typeof prepare>>()\n\tconst scalarPredicates = new WeakMap<FilterAst, boolean>()\n\tfunction scalarOnly(ast: FilterAst): boolean {\n\t\tconst cached = scalarPredicates.get(ast)\n\t\tif (cached !== undefined) return cached\n\t\tconst result =\n\t\t\tast.kind === 'and' || ast.kind === 'or'\n\t\t\t\t? ast.children.every(scalarOnly)\n\t\t\t\t: ast.kind === 'not' || ast.kind === 'variant'\n\t\t\t\t\t? scalarOnly(ast.child)\n\t\t\t\t\t: ast.kind === 'scalar'\n\t\tscalarPredicates.set(ast, result)\n\t\treturn result\n\t}\n\tconst base = (leg: Edge['from']) => ('base' in leg ? leg.base : leg)\n\tfunction edge(table: string, name: string): Edge {\n\t\tconst declared = metadata.declarations[table]?.[name]\n\t\tif (!declared) throw new RelationshipError('INVALID_RELATION')\n\t\treturn declared\n\t}\n\tconst guarded = (row: Document | Record<string, Value>, guard?: RelationGuard) =>\n\t\t!guard || row[guard.discriminator] === guard.tag\n\tfunction memberMatches(value: Value | undefined, member: Edge['sourceMember']): boolean {\n\t\tif (!member) return true\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- A stored member ID is a string Convex value.\n\t\treturn typeof value === 'string' && request.db.normalizeId(member.table, value) !== null\n\t}\n\tfunction sourceValue(declared: Edge, parent: Document | null): Value | undefined {\n\t\tif (!parent || !guarded(parent, declared.sourceGuard)) return undefined\n\t\tconst value = parent[base(declared.from).field]\n\t\treturn memberMatches(value, declared.sourceMember) &&\n\t\t\tmemberMatches(value, declared.targetMember)\n\t\t\t? value\n\t\t\t: undefined\n\t}\n\tfunction lookup(table: string, field: string, guard?: RelationGuard) {\n\t\tconst index =\n\t\t\tfield === '_id'\n\t\t\t\t? { name: 'by_id', fields: ['_id'] }\n\t\t\t\t: metadata.tables[table].indexes.find((i) => {\n\t\t\t\t\t\tconst position = i.fields.indexOf(field)\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tposition >= 0 &&\n\t\t\t\t\t\t\ti.fields.slice(0, position).every((key) => key === guard?.discriminator)\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\tif (!index) throw new RelationshipError('INVALID_RELATION')\n\t\treturn index\n\t}\n\tfunction checkTraversal(declared: Edge, path?: readonly string[]) {\n\t\tfunction check(\n\t\t\ttable: string,\n\t\t\tfield: string,\n\t\t\tguard?: RelationGuard,\n\t\t\ttargetPath?: readonly string[],\n\t\t) {\n\t\t\tgroups?.checkOrder(\n\t\t\t\ttable,\n\t\t\t\tlookup(table, field, guard).fields.filter(\n\t\t\t\t\t(key) => key !== field && key !== guard?.discriminator,\n\t\t\t\t),\n\t\t\t\ttargetPath,\n\t\t\t)\n\t\t}\n\t\tif ('base' in declared.from && 'base' in declared.to) {\n\t\t\tcheck(declared.from.junction.table, declared.from.junction.field, declared.junctionGuard)\n\t\t\tcheck(declared.target, declared.to.base.field, declared.targetGuard, path)\n\t\t} else check(declared.target, base(declared.to).field, declared.targetGuard, path)\n\t}\n\tfunction relationIndex(\n\t\ttable: string,\n\t\tfield: string,\n\t\tplan: ReturnType<Planner['plan']>,\n\t\tconditions: readonly IndexCondition[],\n\t\tguard?: RelationGuard,\n\t): QueryIndex {\n\t\tconst indexes =\n\t\t\tfield === '_id' ? [{ name: 'by_id', fields: ['_id'] }] : metadata.tables[table].indexes\n\t\tconst bound = (key: string) =>\n\t\t\tkey === field || key === guard?.discriminator || plan.bindings.has(key)\n\t\tconst usable = (index: QueryIndex) =>\n\t\t\tindex.fields.includes(field) &&\n\t\t\tindex.fields.slice(0, index.fields.indexOf(field)).every(bound)\n\t\tconst length = (index: QueryIndex) => {\n\t\t\tlet size = 0\n\t\t\tfor (const key of index.fields) {\n\t\t\t\tif (!bound(key)) break\n\t\t\t\tsize++\n\t\t\t}\n\t\t\treturn size\n\t\t}\n\t\tconst condition = conditions.find((c) => c.value !== null && c.value !== undefined)\n\t\tif (condition) {\n\t\t\tconst chosen = indexes.find((i) => i.name === condition.index && usable(i))\n\t\t\tif (!chosen)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Explicit index \"${condition.index}\" is incompatible with declared relationship lookup`,\n\t\t\t\t)\n\t\t\treturn chosen\n\t\t}\n\t\tconst candidates = indexes\n\t\t\t.filter(usable)\n\t\t\t.sort(\n\t\t\t\t(a, b) =>\n\t\t\t\t\tlength(b) - length(a) ||\n\t\t\t\t\tNumber(plan.sets.has(b.fields[length(b)])) - Number(plan.sets.has(a.fields[length(a)])) ||\n\t\t\t\t\tNumber(plan.ranges.has(b.fields[length(b)])) -\n\t\t\t\t\t\tNumber(plan.ranges.has(a.fields[length(a)])) ||\n\t\t\t\t\ta.name.localeCompare(b.name) ||\n\t\t\t\t\ta.fields.join('\\0').localeCompare(b.fields.join('\\0')),\n\t\t\t)\n\t\tif (!candidates.length) throw new RelationshipError('INVALID_RELATION')\n\t\treturn candidates[0]\n\t}\n\tfunction relationPrefix(\n\t\tindex: QueryIndex,\n\t\tfield: string,\n\t\tvalue: FilterScalar,\n\t\tplan?: ReturnType<Planner['plan']>,\n\t\tguard?: RelationGuard,\n\t) {\n\t\tconst prefix: { field: string; value: FilterScalar }[] = []\n\t\tfor (const key of index.fields) {\n\t\t\tif (key === field) prefix.push({ field: key, value })\n\t\t\telse if (key === guard?.discriminator) prefix.push({ field: key, value: guard.tag })\n\t\t\telse if (plan?.bindings.has(key)) prefix.push({ field: key, value: plan.bindings.get(key)! })\n\t\t\telse break\n\t\t}\n\t\treturn prefix\n\t}\n\n\tasync function get(table: string, id: Value | undefined): Promise<Document | null> {\n\t\tplanner.beforeLeaf(table)\n\t\t// SAFETY: native normalization rejects non-string/non-table IDs before any read.\n\t\tif (id == null || !request.db.normalizeId(table, id as string)) return null\n\t\t// SAFETY: normalizeId verifies the declared native table before the authorized metered get.\n\t\tconst result = await request.db.get(table, id as GenericId<string>)\n\t\tif (result) planner.validateDocument(table, result)\n\t\t// SAFETY: normalizeId checked the table; the authorized native get retains system fields.\n\t\treturn result as Document | null\n\t}\n\tasync function* targets(\n\t\ttable: string,\n\t\tfield: string,\n\t\tvalue: Value | undefined,\n\t\tdepth: number,\n\t\tguard?: RelationGuard,\n\t\tmember?: Edge['targetMember'],\n\t): AsyncGenerator<Document> {\n\t\trequest.expand(depth, 0)\n\t\tif (value == null || !memberMatches(value, member)) return\n\t\tif (field === '_id') {\n\t\t\tconst target = await get(table, value)\n\t\t\tif (target && guarded(target, guard) && memberMatches(target[field], member)) {\n\t\t\t\trequest.expand(depth)\n\t\t\t\tyield target\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tplanner.beforeLeaf(table)\n\t\tconst index = lookup(table, field, guard)\n\t\t// SAFETY: registry validates the indexed native lookup prefix and compatible values.\n\t\tconst source = request.leafQuery(table).withIndex(index.name, (q) => {\n\t\t\t// SAFETY: registration checks the mandatory join and every preceding guard equality.\n\t\t\tlet range = q as IndexRangeBuilder<any, string[], number>\n\t\t\t// SAFETY: registered relation fields are native scalars; each equality advances the consecutive checked prefix.\n\t\t\tfor (const binding of relationPrefix(index, field, value as FilterScalar, undefined, guard)) {\n\t\t\t\t// SAFETY: the prefix comes from the declared index and registry-owned guard.\n\t\t\t\trange = range.eq(binding.field, binding.value) as IndexRangeBuilder<any, string[], number>\n\t\t\t}\n\t\t\treturn range\n\t\t})\n\t\tconst iterator = source[Symbol.asyncIterator]()\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tplanner.beforeLeaf(table)\n\t\t\t\tconst next = await iterator.next()\n\t\t\t\tif (next.done) return\n\t\t\t\tconst permitted = await request.authorize(table, next.value)\n\t\t\t\t// Denials are an await boundary too; never hide them inside an authorized iterator.\n\t\t\t\tif (!permitted) continue\n\t\t\t\tplanner.validateDocument(table, next.value)\n\t\t\t\tif (!guarded(next.value, guard) || !memberMatches(next.value[field], member)) continue\n\t\t\t\trequest.expand(depth)\n\t\t\t\t// SAFETY: native rows include system fields and explicit authorization just completed.\n\t\t\t\tyield next.value as Document\n\t\t\t}\n\t\t} finally {\n\t\t\tawait iterator.return?.()\n\t\t}\n\t}\n\tasync function* traverse(\n\t\tdeclared: Edge,\n\t\tparent: Document,\n\t\tdepth: number,\n\t): AsyncGenerator<Document> {\n\t\trequest.expand(depth, 0)\n\t\tconst value = sourceValue(declared, parent)\n\t\tif (value == null) return\n\t\tif ('base' in declared.from && 'base' in declared.to) {\n\t\t\tfor await (const junction of targets(\n\t\t\t\tdeclared.from.junction.table,\n\t\t\t\tdeclared.from.junction.field,\n\t\t\t\tvalue,\n\t\t\t\tdepth,\n\t\t\t\tdeclared.junctionGuard,\n\t\t\t))\n\t\t\t\tyield* targets(\n\t\t\t\t\tdeclared.target,\n\t\t\t\t\tdeclared.to.base.field,\n\t\t\t\t\tjunction[declared.to.junction.field],\n\t\t\t\t\tdepth,\n\t\t\t\t\tdeclared.targetGuard,\n\t\t\t\t)\n\t\t} else\n\t\t\tyield* targets(\n\t\t\t\tdeclared.target,\n\t\t\t\tbase(declared.to).field,\n\t\t\t\tvalue,\n\t\t\t\tdepth,\n\t\t\t\tdeclared.targetGuard,\n\t\t\t\tdeclared.targetMember,\n\t\t\t)\n\t}\n\tasync function one(declared: Edge, parent: Document, depth: number) {\n\t\tlet match: Document | null = null\n\t\tfor await (const target of traverse(declared, parent, depth)) {\n\t\t\tif (match) throw new RelationshipError('AMBIGUOUS_RELATION')\n\t\t\tmatch = target\n\t\t}\n\t\treturn match\n\t}\n\tasync function matches(\n\t\ttable: string,\n\t\tparent: Document,\n\t\tast: FilterAst,\n\t\tdepth = 0,\n\t): Promise<boolean> {\n\t\trequest.expand(depth, 0)\n\t\t// Variant rows must satisfy the captured stored branch before predicates\n\t\t// inspect branch fields. Ordinary output rows are validated by projection.\n\t\tif (metadata.tables[table].variant) planner.validateDocument(table, parent)\n\t\tif (scalarOnly(ast)) return scalarMatches(ast, parent)\n\t\tif (ast.kind === 'variant')\n\t\t\treturn parent[ast.discriminator] === ast.tag && matches(table, parent, ast.child, depth)\n\t\tif (ast.kind === 'scalar') return scalarMatches(ast, parent)\n\t\tif (ast.kind === 'not') return !(await matches(table, parent, ast.child, depth))\n\t\tif (ast.kind === 'and' || ast.kind === 'or') {\n\t\t\tfor (const child of ast.children) {\n\t\t\t\tconst result = await matches(table, parent, child, depth)\n\t\t\t\tif (ast.kind === 'and' && !result) return false\n\t\t\t\tif (ast.kind === 'or' && result) return true\n\t\t\t}\n\t\t\treturn ast.kind === 'and'\n\t\t}\n\t\tif (ast.kind !== 'relation') throw new RelationshipError('INVALID_RELATION')\n\t\tconst declared = edge(table, ast.name)\n\t\tif (ast.mode === 'one') {\n\t\t\tconst target = await one(declared, parent, depth + 1)\n\t\t\treturn ast.predicate === null\n\t\t\t\t? target === null\n\t\t\t\t: target !== null && (await matches(declared.target, target, ast.predicate, depth + 1))\n\t\t}\n\t\tfor await (const target of traverse(declared, parent, depth + 1))\n\t\t\tif (await matches(declared.target, target, ast.predicate!, depth + 1))\n\t\t\t\treturn ast.mode === 'some'\n\t\t// Only actual authorized traversal exhaustion proves none.\n\t\treturn ast.mode === 'none'\n\t}\n\tasync function output(\n\t\ttable: string,\n\t\tparent: Document,\n\t\tselection: OutputSelection,\n\t\targs: NativePagination & { order?: 'asc' | 'desc' },\n\t\tpath: readonly string[] = [],\n\t\tdepth = 0,\n\t\tparents: readonly string[] = [],\n\t): Promise<Record<string, Value>> {\n\t\trequest.expand(depth, 0)\n\t\t// SAFETY: the registry strictly validates this public native DTO projection.\n\t\tconst dto = planner.complete(table, parent, true, noPredicate, groups?.allowed(path)) as Record<\n\t\t\tstring,\n\t\t\tValue\n\t\t>\n\t\tfor (const [name, selected] of Object.entries(selection)) {\n\t\t\tconst declared = edge(table, name),\n\t\t\t\tnested = selected === true ? {} : selected\n\t\t\tif (declared.cardinality === 'one') {\n\t\t\t\tconst target = await one(declared, parent, depth + 1)\n\t\t\t\tdto[name] = target\n\t\t\t\t\t? await output(declared.target, target, nested, args, [...path, name], depth + 1, [\n\t\t\t\t\t\t\t...parents,\n\t\t\t\t\t\t\tparent._id,\n\t\t\t\t\t\t])\n\t\t\t\t\t: null\n\t\t\t} else {\n\t\t\t\tconst childPath = [...path, name]\n\t\t\t\tconst childParents = [...parents, parent._id]\n\t\t\t\tconst prepared =\n\t\t\t\t\tchildPlans.get(JSON.stringify(childPath)) ??\n\t\t\t\t\tprepare(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tnested,\n\t\t\t\t\t\t{ numItems: args.numItems, cursor: null, order: args.order },\n\t\t\t\t\t\t[],\n\t\t\t\t\t\t[],\n\t\t\t\t\t\tchildPath,\n\t\t\t\t\t)\n\t\t\t\tconst page = await pageRelation(\n\t\t\t\t\tparent,\n\t\t\t\t\tnested,\n\t\t\t\t\tchildPath,\n\t\t\t\t\tdepth + 1,\n\t\t\t\t\tchildParents,\n\t\t\t\t\tprepared,\n\t\t\t\t\t() => prepared.bind(childParents[0]),\n\t\t\t\t)\n\t\t\t\t// SAFETY: pageRelation projects and validates each nested DTO row.\n\t\t\t\tdto[name] = page as Value\n\t\t\t}\n\t\t}\n\t\treturn dto\n\t}\n\tfunction prepare(\n\t\ttable: string,\n\t\tname: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[],\n\t\tconstraints: readonly StoredConstraint[],\n\t\tpath: readonly string[],\n\t\tordering?: string,\n\t) {\n\t\tif (ordering !== undefined && conditions.some((c) => c.value !== null && c.value !== undefined))\n\t\t\tthrow new Error('orderBy cannot be combined with an active when selector')\n\t\tplanner.select(edge(table, name).target, selection)\n\t\tassertRelationshipDepth(selection, path.length)\n\t\tconst declared = edge(table, name)\n\t\tif (declared.cardinality !== 'many') throw new RelationshipError('INVALID_RELATION')\n\t\tconst guardConstraint = declared.targetGuard\n\t\t\t? { fields: { [declared.targetGuard.discriminator]: declared.targetGuard.tag } }\n\t\t\t: undefined\n\t\tconst plan = planner.plan(\n\t\t\tdeclared.target,\n\t\t\tinput,\n\t\t\t[],\n\t\t\tguardConstraint ? [...constraints, guardConstraint] : constraints,\n\t\t\tordering,\n\t\t\t'relation',\n\t\t)\n\t\tconst from = declared.from,\n\t\t\tto = declared.to\n\t\tconst through =\n\t\t\t'base' in from && 'base' in to\n\t\t\t\t? {\n\t\t\t\t\t\ttable: from.junction.table,\n\t\t\t\t\t\tfield: from.junction.field,\n\t\t\t\t\t\ttargetField: to.base.field,\n\t\t\t\t\t\ttargetReference: to.junction.field,\n\t\t\t\t\t}\n\t\t\t\t: null\n\t\tif (ordering !== undefined && through)\n\t\t\tthrow new Error('orderBy is unsupported for junction relationships')\n\t\tconst sourceTable = through ? through.table : declared.target\n\t\tconst field = through ? through.field : base(to).field\n\t\tconst targetIndex = relationIndex(\n\t\t\tdeclared.target,\n\t\t\tthrough ? through.targetField : field,\n\t\t\tplan,\n\t\t\tordering === undefined ? conditions : [{ value: true, index: ordering }],\n\t\t\tdeclared.targetGuard,\n\t\t)\n\t\tgroups?.checkOrder(\n\t\t\tdeclared.target,\n\t\t\ttargetIndex.fields.filter(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey !== (through ? through.targetField : field) &&\n\t\t\t\t\tkey !== declared.targetGuard?.discriminator &&\n\t\t\t\t\t!plan.bindings.has(key),\n\t\t\t),\n\t\t\tpath,\n\t\t)\n\t\tconst index = through ? lookup(sourceTable, field, declared.junctionGuard) : targetIndex\n\t\tif (through)\n\t\t\tgroups?.checkOrder(\n\t\t\t\tsourceTable,\n\t\t\t\tindex.fields.filter(\n\t\t\t\t\t(key) => key !== field && key !== declared.junctionGuard?.discriminator,\n\t\t\t\t),\n\t\t\t)\n\t\t// The lookup value changes only values, not prefix positions or comparator.\n\t\tconst expansion =\n\t\t\tthrough || plan.unsatisfiable\n\t\t\t\t? null\n\t\t\t\t: expansionForIndex(\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\trelationPrefix(index, field, null, plan, declared.targetGuard),\n\t\t\t\t\t\tplan.sets,\n\t\t\t\t\t\tordering !== undefined ||\n\t\t\t\t\t\t\tconditions.some((c) => c.value !== null && c.value !== undefined),\n\t\t\t\t\t)\n\t\tconst groupBinding: Record<string, Value> = {}\n\t\tconst resolved = groups?.at(path)\n\t\tif (\n\t\t\tresolved &&\n\t\t\t(Object.keys(resolved.fieldGroups).length || Object.keys(resolved.relations).length)\n\t\t)\n\t\t\tgroupBinding.fieldGroups = resolved\n\t\t// SAFETY: planner.page validated the complete output mask before cursor binding.\n\t\tconst binding: CursorBinding = {\n\t\t\t...rootBinding,\n\t\t\ttable: sourceTable,\n\t\t\tindex: index.name,\n\t\t\torder: plan.args.order ?? 'asc',\n\t\t\tclientFilters: plan.clientIdentity,\n\t\t\tserverFilters: {\n\t\t\t\tpredicates: plan.sets.size\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpredicates: plan.serverIdentity,\n\t\t\t\t\t\t\ttraversal: { version: 2, expansion: expansion ? { ...expansion } : null },\n\t\t\t\t\t\t}\n\t\t\t\t\t: plan.serverIdentity,\n\t\t\t\tselection: selection as Value,\n\t\t\t\t...groupBinding,\n\t\t\t\tscope: { ...request.scope },\n\t\t\t\trootTable: rootBinding.table,\n\t\t\t\tlookupIndex: targetIndex.name,\n\t\t\t\tguards: {\n\t\t\t\t\tsource: declared.sourceGuard ? { ...declared.sourceGuard } : null,\n\t\t\t\t\ttarget: declared.targetGuard ? { ...declared.targetGuard } : null,\n\t\t\t\t\tjunction: declared.junctionGuard ? { ...declared.junctionGuard } : null,\n\t\t\t\t},\n\t\t\t\t...((declared.sourceMember || declared.targetMember) && {\n\t\t\t\t\tmembers: {\n\t\t\t\t\t\tsource: declared.sourceMember ? { ...declared.sourceMember } : null,\n\t\t\t\t\t\ttarget: declared.targetMember ? { ...declared.targetMember } : null,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t\trelationPath: path,\n\t\t}\n\t\t// Each child path binds the registry scope it reads. A relation route from\n\t\t// the same root computes the same scope, so it can open this path's cursors.\n\t\tlet version: Promise<string> | undefined\n\t\tasync function bind(rootId: string): Promise<CursorBinding> {\n\t\t\tversion ??= planner.registryVersion({\n\t\t\t\troot: rootBinding.table,\n\t\t\t\tpath,\n\t\t\t\tselection,\n\t\t\t\tgroups: resolved ?? emptyGroups,\n\t\t\t\tfilters: [plan.residual],\n\t\t\t})\n\t\t\treturn { ...binding, parent: rootId, registryVersion: await version }\n\t\t}\n\t\treturn {\n\t\t\tdeclared,\n\t\t\tplan,\n\t\t\tthrough,\n\t\t\tsourceTable,\n\t\t\tfield,\n\t\t\tindex,\n\t\t\ttargetIndex,\n\t\t\tbind,\n\t\t\texpansion,\n\t\t}\n\t}\n\tasync function pageRelation(\n\t\tparent: Document | null,\n\t\tselection: OutputSelection,\n\t\tpath: readonly string[],\n\t\tdepth: number,\n\t\tparents: readonly string[],\n\t\tprepared: ReturnType<typeof prepare>,\n\t\tbind: () => Promise<CursorBinding>,\n\t\topened?: { cursor: string | null; endCursor?: string | null },\n\t) {\n\t\trequest.expand(depth, 0)\n\t\tconst { declared, plan, through, sourceTable, field, index, targetIndex, expansion } = prepared\n\t\tconst binding = await bind()\n\t\tconst value = sourceValue(declared, parent)\n\t\tconst args = { ...plan.args, ...(opened ?? { cursor: null }) }\n\t\t// SAFETY: declarations accept only native scalar lookup values; nullish references are absence.\n\t\tconst lookupPlan = {\n\t\t\t...plan,\n\t\t\texpansion,\n\t\t\tindex,\n\t\t\tprefix:\n\t\t\t\tvalue == null\n\t\t\t\t\t? []\n\t\t\t\t\t: through\n\t\t\t\t\t\t? relationPrefix(index, field, value as FilterScalar, undefined, declared.junctionGuard)\n\t\t\t\t\t\t: relationPrefix(index, field, value as FilterScalar, plan, declared.targetGuard),\n\t\t\tunsatisfiable: value == null || plan.unsatisfiable,\n\t\t}\n\t\tlookupPlan.range = through ? null : rangeForIndex(index, lookupPlan.prefix, plan.ranges)\n\t\tif (!through)\n\t\t\tfor (const binding of lookupPlan.prefix) {\n\t\t\t\tconst range = plan.ranges.get(binding.field)\n\t\t\t\tif (\n\t\t\t\t\tplan.bindings.has(binding.field) &&\n\t\t\t\t\tcompareValues(binding.value, plan.bindings.get(binding.field)!) !== 0\n\t\t\t\t)\n\t\t\t\t\tlookupPlan.unsatisfiable = true\n\t\t\t\tif (range && !withinRange(binding.value, range)) lookupPlan.unsatisfiable = true\n\t\t\t}\n\t\tconst indexedTarget = through && through.targetField !== '_id'\n\t\tconst result = await executeStream(\n\t\t\tschema,\n\t\t\trequest,\n\t\t\tsourceTable,\n\t\t\tlookupPlan,\n\t\t\tplanner,\n\t\t\tcodec,\n\t\t\tbinding,\n\t\t\targs,\n\t\t\tasync (row, permitted) => {\n\t\t\t\tif (permitted) planner.validateDocument(indexedTarget ? declared.target : sourceTable, row)\n\t\t\t\tif (!permitted || (through && !indexedTarget && !guarded(row, declared.junctionGuard)))\n\t\t\t\t\treturn null\n\t\t\t\trequest.expand(depth)\n\t\t\t\tlet target: Document | null\n\t\t\t\tif (through && !indexedTarget)\n\t\t\t\t\ttarget = await get(declared.target, row[through.targetReference])\n\t\t\t\telse {\n\t\t\t\t\t// SAFETY: native direct/flattened target streams retain validated system fields.\n\t\t\t\t\ttarget = row as Document\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!target ||\n\t\t\t\t\t!guarded(target, declared.targetGuard) ||\n\t\t\t\t\t!memberMatches(target[base(declared.to).field], declared.targetMember) ||\n\t\t\t\t\t!(await matches(declared.target, target, plan.residual, depth))\n\t\t\t\t)\n\t\t\t\t\treturn null\n\t\t\t\treturn output(declared.target, target, selection, plan.args, path, depth, parents)\n\t\t\t},\n\t\t\t(raw, bound) =>\n\t\t\t\tcodec.seal(JSON.stringify({ cursor: raw, ancestors: parents.slice(1) }), bound),\n\t\t\tindexedTarget\n\t\t\t\t? (source, db) => {\n\t\t\t\t\t\t// SAFETY: the registry owns the native schema/index descriptors. Public\n\t\t\t\t\t\t// helper flatMap concatenates native outer/inner keys and paginates them.\n\t\t\t\t\t\tconst nativeSchema = schema as SchemaDefinition<\n\t\t\t\t\t\t\tRecord<\n\t\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\t\timport('convex/server').TableDefinition<any, Record<string, string[]>>\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\tboolean\n\t\t\t\t\t\t>\n\t\t\t\t\t\tconst fields = getIndexFields(declared.target, targetIndex.name, nativeSchema)\n\t\t\t\t\t\treturn source.flatMap(async (junction) => {\n\t\t\t\t\t\t\trequest.expand(depth)\n\t\t\t\t\t\t\tconst permitted = await request.authorize(sourceTable, junction)\n\t\t\t\t\t\t\tif (permitted) planner.validateDocument(sourceTable, junction)\n\t\t\t\t\t\t\tconst reference = junction[through.targetReference]\n\t\t\t\t\t\t\tif (!permitted || !guarded(junction, declared.junctionGuard) || reference == null)\n\t\t\t\t\t\t\t\treturn new EmptyStream(plan.args.order ?? 'asc', fields)\n\t\t\t\t\t\t\treturn stream(db, nativeSchema)\n\t\t\t\t\t\t\t\t.query(declared.target)\n\t\t\t\t\t\t\t\t.withIndex(targetIndex.name, (q) => {\n\t\t\t\t\t\t\t\t\t// SAFETY: registry-owned lookup bindings are native scalar index values.\n\t\t\t\t\t\t\t\t\tconst prefix = relationPrefix(\n\t\t\t\t\t\t\t\t\t\ttargetIndex,\n\t\t\t\t\t\t\t\t\t\tthrough.targetField,\n\t\t\t\t\t\t\t\t\t\treference as FilterScalar,\n\t\t\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t\t\tdeclared.targetGuard,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\treturn nativeIndexRange(\n\t\t\t\t\t\t\t\t\t\tq,\n\t\t\t\t\t\t\t\t\t\tprefix,\n\t\t\t\t\t\t\t\t\t\trangeForIndex(targetIndex, prefix, plan.ranges),\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\t.order(plan.args.order ?? 'asc')\n\t\t\t\t\t\t}, fields)\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tindexedTarget ? declared.target : sourceTable,\n\t\t)\n\t\treturn result\n\t}\n\tasync function continuation(\n\t\trootTable: string,\n\t\trootId: string,\n\t\tpath: readonly string[],\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[],\n\t\tconstraints: readonly StoredConstraint[],\n\t\tordering?: string,\n\t) {\n\t\tif (!path.length || path.length > 4 || !request.db.normalizeId(rootTable, rootId))\n\t\t\tthrow new RelationshipError('INVALID_RELATION')\n\t\tlet table = rootTable\n\t\tconst declarations = path.map((name) => {\n\t\t\tconst declaration = edge(table, name)\n\t\t\ttable = declaration.target\n\t\t\treturn declaration\n\t\t})\n\t\tif (ordering !== undefined && declarations.some((d) => 'base' in d.from || 'base' in d.to))\n\t\t\tthrow new Error('orderBy is unsupported for junction relationships')\n\t\tconst final = declarations.at(-1)!\n\t\tfor (const declaration of declarations.slice(0, -1))\n\t\t\tif (\n\t\t\t\tdeclaration.cardinality === 'one' ||\n\t\t\t\t'base' in declaration.from ||\n\t\t\t\t'base' in declaration.to\n\t\t\t)\n\t\t\t\tcheckTraversal(declaration)\n\t\tconst prepared = prepare(\n\t\t\tfinal.source,\n\t\t\tpath.at(-1)!,\n\t\t\tselection,\n\t\t\tinput,\n\t\t\tconditions,\n\t\t\tconstraints,\n\t\t\tpath,\n\t\t\tordering,\n\t\t)\n\t\tlet bound: Promise<CursorBinding> | undefined\n\t\tconst bind = () =>\n\t\t\t(bound ??= prepared\n\t\t\t\t.bind(rootId)\n\t\t\t\t.then((binding) =>\n\t\t\t\t\tinput.cursor !== null || input.endCursor != null\n\t\t\t\t\t\t? prepareCursorBinding(binding)\n\t\t\t\t\t\t: binding,\n\t\t\t\t))\n\t\tasync function open(token: string) {\n\t\t\ttry {\n\t\t\t\treturn navigation().parse(JSON.parse(codec.open(token, await bind())))\n\t\t\t} catch {\n\t\t\t\tthrow new CursorError()\n\t\t\t}\n\t\t}\n\t\t// Authenticate both slots and native ancestor IDs before ANY parent/traversal read.\n\t\tconst start = input.cursor === null ? null : await open(input.cursor)\n\t\tconst end = input.endCursor == null ? null : await open(input.endCursor)\n\t\tconst ancestors = start?.ancestors ?? end?.ancestors ?? []\n\t\tif (\n\t\t\tancestors.length !== path.length - 1 ||\n\t\t\t(start && end && JSON.stringify(start.ancestors) !== JSON.stringify(end.ancestors)) ||\n\t\t\tancestors.some((id, i) => !request.db.normalizeId(declarations[i].target, id))\n\t\t)\n\t\t\tthrow new CursorError()\n\t\t// Declarative input/index/cursor validation above retains its pre-read errors,\n\t\t// just as on the root path. Every awaited read, ancestry proof and page is protected.\n\t\ttry {\n\t\t\tlet parent = await get(rootTable, rootId)\n\t\t\tfor (let i = 0; parent && i < ancestors.length; i++) {\n\t\t\t\tconst declared = declarations[i]\n\t\t\t\tlet found: Document | null = null\n\t\t\t\tif (\n\t\t\t\t\tdeclared.cardinality === 'many' &&\n\t\t\t\t\t!('base' in declared.from) &&\n\t\t\t\t\t!('base' in declared.to)\n\t\t\t\t) {\n\t\t\t\t\t// A cursor names this ancestor. Prove its current authorized membership\n\t\t\t\t\t// by ID instead of replaying an ordering that is not part of this page.\n\t\t\t\t\trequest.expand(i + 1, 0)\n\t\t\t\t\tconst value = sourceValue(declared, parent)\n\t\t\t\t\tconst target = value == null ? null : await get(declared.target, ancestors[i])\n\t\t\t\t\tconst key = declared.to.field\n\t\t\t\t\tif (\n\t\t\t\t\t\tvalue != null &&\n\t\t\t\t\t\ttarget &&\n\t\t\t\t\t\tguarded(target, declared.targetGuard) &&\n\t\t\t\t\t\tmemberMatches(target[key], declared.targetMember) &&\n\t\t\t\t\t\ttarget[key] !== undefined &&\n\t\t\t\t\t\tcompareValues(value, target[key]) === 0\n\t\t\t\t\t) {\n\t\t\t\t\t\trequest.expand(i + 1)\n\t\t\t\t\t\tfound = target\n\t\t\t\t\t}\n\t\t\t\t} else if (declared.cardinality === 'one') {\n\t\t\t\t\tconst target = await one(declared, parent, i + 1)\n\t\t\t\t\tif (target?._id === ancestors[i]) found = target\n\t\t\t\t} else\n\t\t\t\t\tfor await (const target of traverse(declared, parent, i + 1)) {\n\t\t\t\t\t\tif (target._id === ancestors[i]) {\n\t\t\t\t\t\t\tfound = target\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tparent = found\n\t\t\t}\n\t\t\treturn await pageRelation(\n\t\t\t\tparent,\n\t\t\t\tselection,\n\t\t\t\tpath,\n\t\t\t\tpath.length,\n\t\t\t\t[rootId, ...ancestors],\n\t\t\t\tprepared,\n\t\t\t\tbind,\n\t\t\t\t{ cursor: start?.cursor ?? null, endCursor: end?.cursor ?? input.endCursor },\n\t\t\t)\n\t\t} catch (error) {\n\t\t\trethrowQueryError(error)\n\t\t}\n\t}\n\t/** Admit the complete output tree even when a parent query produces no rows. */\n\tfunction preflight(\n\t\ttable: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tpath: readonly string[] = [],\n\t) {\n\t\tfor (const [name, selected] of Object.entries(selection)) {\n\t\t\tconst declared = edge(table, name)\n\t\t\tconst nested = selected === true ? {} : selected\n\t\t\tconst nestedPath = [...path, name]\n\t\t\tif (declared.cardinality === 'many') {\n\t\t\t\tconst plan = prepare(\n\t\t\t\t\ttable,\n\t\t\t\t\tname,\n\t\t\t\t\tnested,\n\t\t\t\t\t{ numItems: input.numItems, cursor: null, order: input.order },\n\t\t\t\t\t[],\n\t\t\t\t\t[],\n\t\t\t\t\tnestedPath,\n\t\t\t\t)\n\t\t\t\tchildPlans.set(JSON.stringify(nestedPath), plan)\n\t\t\t} else checkTraversal(declared, nestedPath)\n\t\t\tpreflight(declared.target, nested, input, nestedPath)\n\t\t}\n\t}\n\treturn { matches, output, continuation, edge, preflight }\n}\n\nlet navigationSchema: ReturnType<typeof buildNavigation> | undefined\n\n/** The sealed relation navigation payload, built on the first nested continuation. */\nfunction navigation(): ReturnType<typeof buildNavigation> {\n\treturn (navigationSchema ??= buildNavigation())\n}\n\nfunction buildNavigation() {\n\treturn k.object({ cursor: k.string(), ancestors: k.array(k.string()).max(3) })\n}\n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,CACzD,IAAMc,EAAWD,EAAKE,EAAOC,CAAI,EAC3BjB,EAASwE,IAAa,GAAO,CAAC,EAAIA,EAClC+D,EAAa,CAAC,GAAGlG,EAAMpB,CAAI,EACjC,GAAIF,EAAS,cAAgB,OAAQ,CACpC,IAAM0B,EAAOqC,EACZ9D,EACAC,EACAjB,EACA,CAAE,SAAUkF,EAAM,SAAU,OAAQ,KAAM,MAAOA,EAAM,KAAM,EAC7D,CAAC,EACD,CAAC,EACDqD,CACD,EACAjI,EAAW,IAAI,KAAK,UAAUiI,CAAU,EAAG9F,CAAI,CAChD,MAAOR,EAAelB,EAAUwH,CAAU,EAC1CD,EAAUvH,EAAS,OAAQf,EAAQkF,EAAOqD,CAAU,CACrD,CACD,CACA,MAAO,CAAE,UAAS,SAAQ,eAAc,OAAM,WAAU,CACzD,CAEA,IAAIC,EAGJ,SAASX,GAAiD,CACzD,MAAQ,KAAqBY,EAAgB,CAC9C,CAEA,SAASA,GAAkB,CAC1B,OAAOC,EAAE,OAAO,CAAE,OAAQA,EAAE,OAAO,EAAG,UAAWA,EAAE,MAAMA,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAE,CAAC,CAC9E,C"}
@@ -1,13 +1,13 @@
1
1
  import { FilterAst, FilterScalar } from "./shared/ast.mjs";
2
+ import { EnginePaginationResult } from "../table.mjs";
2
3
  import { FieldRange, IndexExpansion, NativeRange, QueryIndex } from "./filters.mjs";
3
- import { EnginePaginationResult } from "../zod-table.mjs";
4
+ import { FilterTree } from "./shared/filters.mjs";
4
5
  import { SearchIndexMetadata } from "../relations.mjs";
5
- import { ManagedReadRequest } from "./security.mjs";
6
6
  import { QueryInput, StoredConstraint, createPlanner } from "./planner.mjs";
7
7
  import { CursorBinding, createCursorCodec } from "./cursors.mjs";
8
- import { GenericDataModel, GenericDocument } from "convex/server";
8
+ import { ManagedReadRequest } from "./security.mjs";
9
9
  import { Value } from "convex/values";
10
- //#region src/querying/search.d.ts
10
+ import { GenericDataModel, GenericDocument } from "convex/server";
11
11
  export type SearchErrorCode = 'SEARCH_TEXT_REQUIRED' | 'SEARCH_END_CURSOR_UNSUPPORTED' | 'SEARCH_ORDER_UNSUPPORTED' | 'SEARCH_RELATION_UNSUPPORTED' | 'SEARCH_OPTIONS_UNSUPPORTED' | 'SEARCH_PROTOCOL_UNSUPPORTED';
12
12
  export declare class SearchError extends Error {
13
13
  readonly code: SearchErrorCode;
@@ -44,13 +44,13 @@ export declare function planSearch(planner: ReturnType<typeof createPlanner>, ta
44
44
  serverIdentity: Value;
45
45
  args: {
46
46
  cursor: string | null;
47
- endCursor?: string | null | undefined;
48
- id?: number | undefined;
49
- onEmptyBudget?: "split" | undefined;
50
- maximumRowsRead?: number | undefined;
51
- maximumBytesRead?: number | undefined;
52
- filters?: unknown;
53
- order?: "asc" | "desc" | undefined;
47
+ endCursor?: string | null;
48
+ id?: number;
49
+ maximumRowsRead?: number;
50
+ maximumBytesRead?: number;
51
+ onEmptyBudget?: 'split';
52
+ filters?: FilterTree;
53
+ order?: 'asc' | 'desc';
54
54
  numItems: number;
55
55
  };
56
56
  };
@@ -65,5 +65,5 @@ export declare function planSearch(planner: ReturnType<typeof createPlanner>, ta
65
65
  type SearchPlan = ReturnType<typeof planSearch>;
66
66
  /** One complete native window. No result token is minted until all descendants finish. */
67
67
  export declare function executeSearch(request: ManagedReadRequest<GenericDataModel>, table: string, search: SearchPlan, codec: ReturnType<typeof createCursorCodec>, binding: CursorBinding, maxPageSize: number, complete: (document: GenericDocument) => Promise<Record<string, Value> | null>): Promise<SearchPaginationResult<Record<string, Value>>>;
68
- //#endregion
68
+ export {};
69
69
  //# sourceMappingURL=search.d.mts.map
@@ -1,2 +1,2 @@
1
- import"./filters.mjs";import{CursorError as e}from"./cursors.mjs";import{rethrowQueryError as t}from"./execution.mjs";import{z as n}from"zod";var r=class extends Error{code;constructor(e){super(e),this.code=e,this.name=`SearchError`}};const i=n.strictObject({numItems:n.number().int().positive(),cursor:n.string().nullable(),id:n.number().optional(),scanLimit:n.number().int().positive().max(2**53-1).optional(),filters:n.any().optional(),endCursor:n.null().optional()}),a=n.looseObject({endCursor:n.any().optional(),order:n.any().optional(),maximumRowsRead:n.any().optional(),maximumBytesRead:n.any().optional(),onEmptyBudget:n.any().optional()}),o=n.object({page:n.array(n.any()),isDone:n.boolean(),continueCursor:n.string(),splitCursor:n.null().optional(),pageStatus:n.null().optional(),completeness:n.literal(`complete`).optional()});function s(e,t,o,s,c,l){if(!n.string().safeParse(s).success||!s.trim())throw new r(`SEARCH_TEXT_REQUIRED`);let u=a.safeParse(c);if(!u.success)throw new r(`SEARCH_OPTIONS_UNSUPPORTED`);let d=u.data;if(d.endCursor!=null)throw new r(`SEARCH_END_CURSOR_UNSUPPORTED`);if(Object.hasOwn(d,`order`))throw new r(`SEARCH_ORDER_UNSUPPORTED`);if([`maximumRowsRead`,`maximumBytesRead`,`onEmptyBudget`].some(e=>Object.hasOwn(d,e)))throw new r(`SEARCH_OPTIONS_UNSUPPORTED`);let f=i.safeParse(c);if(!f.success)throw new r(`SEARCH_OPTIONS_UNSUPPORTED`);let p=e.metadata.tables[t]?.searchIndexes.find(e=>e.name===o&&!e.staged);if(!p)throw new r(`SEARCH_OPTIONS_UNSUPPORTED`);let{scanLimit:m,endCursor:h,...g}=f.data,_=e.plan(t,{...g,numItems:Math.min(g.numItems,100)},[],l,void 0,`relation`),v={..._,args:{..._.args,numItems:g.numItems}},y=/* @__PURE__ */ new Map;function b(e){if(e.kind===`and`)for(let t of e.children)b(t);else e.kind===`scalar`&&e.operator===`eq`&&!Array.isArray(e.value)&&y.set(e.field,e.value)}return b(v.residual),{plan:v,text:s.trim(),metadata:p,scanLimit:m,equalities:p.filterFields.filter(e=>y.has(e)).map(e=>({field:e,value:y.get(e)}))}}const c=n.strictObject({v:n.literal(1),mode:n.literal(`search`),nativeCursor:n.string().nullable(),seen:n.number().int().nonnegative().max(2**53-1)});async function l(n,i,a,s,l,u,d){let f={v:1,mode:`search`,nativeCursor:null,seen:0};if(a.plan.args.cursor!==null)try{f=c.parse(JSON.parse(s.open(a.plan.args.cursor,l)))}catch{throw new e}let p=a.scanLimit,m=p!==void 0&&f.seen>=p,h=(e,t,n,r)=>({page:e,isDone:r,continueCursor:s.seal(JSON.stringify({v:1,mode:`search`,nativeCursor:t,seen:n}),l),completeness:p!==void 0&&n>=p?`result-cap`:`complete`,paginationMode:`native-search`,splitCursor:null,pageStatus:null});if(m||a.plan.unsatisfiable)return h([],f.nativeCursor,f.seen,!0);try{let e={cursor:f.nativeCursor,numItems:Math.min(a.plan.args.numItems,u,n.budgets.searchCandidates,p===void 0?1/0:p-f.seen),id:a.plan.args.id},t=await n.search(i,a.metadata,a.text,a.equalities,e);if(!o.safeParse(t).success||!t.isDone&&t.continueCursor===f.nativeCursor)throw new r(`SEARCH_PROTOCOL_UNSUPPORTED`);let s=f.seen+t.page.length;if(!Number.isSafeInteger(s))throw new r(`SEARCH_PROTOCOL_UNSUPPORTED`);let c=[];for(let e of t.page){let t=await d(e);t!==null&&c.push(t)}return h(c,t.continueCursor,s,t.isDone||p!==void 0&&s>=p)}catch(e){if(e instanceof r)throw e;t(e)}}export{r as SearchError,l as executeSearch,s as planSearch};
1
+ import{k as e}from"../k/index.mjs";import"./filters.mjs";import{CursorError as t}from"./cursors.mjs";import{rethrowQueryError as n}from"./execution.mjs";var r=class extends Error{code;constructor(e){super(e),this.code=e,this.name=`SearchError`}};function i(e,t,n,i,a,o){if(typeof i!=`string`||!i.trim())throw new r(`SEARCH_TEXT_REQUIRED`);if(a===null||Object(a)!==a||Array.isArray(a))throw new r(`SEARCH_OPTIONS_UNSUPPORTED`);let c=a;if(c.endCursor!=null)throw new r(`SEARCH_END_CURSOR_UNSUPPORTED`);if(Object.hasOwn(c,`order`))throw new r(`SEARCH_ORDER_UNSUPPORTED`);if([`maximumRowsRead`,`maximumBytesRead`,`onEmptyBudget`].some(e=>Object.hasOwn(c,e)))throw new r(`SEARCH_OPTIONS_UNSUPPORTED`);let l={data:s().parse(a)},u=e.metadata.tables[t]?.searchIndexes.find(e=>e.name===n&&!e.staged);if(!u)throw new r(`SEARCH_OPTIONS_UNSUPPORTED`);let{scanLimit:d,endCursor:f,...p}=l.data,m=e.plan(t,{...p,numItems:Math.min(p.numItems,100)},[],o,void 0,`relation`),h={...m,args:{...m.args,numItems:p.numItems}},g=/* @__PURE__ */ new Map;function _(e){if(e.kind===`and`)for(let t of e.children)_(t);else e.kind===`scalar`&&e.operator===`eq`&&!Array.isArray(e.value)&&g.set(e.field,e.value)}return _(h.residual),{plan:h,text:i.trim(),metadata:u,scanLimit:d,equalities:u.filterFields.filter(e=>g.has(e)).map(e=>({field:e,value:g.get(e)}))}}async function a(e,i,a,o,s,u,d){let f={v:1,mode:`search`,nativeCursor:null,seen:0};if(a.plan.args.cursor!==null)try{f=c().parse(JSON.parse(o.open(a.plan.args.cursor,s)))}catch{throw new t}let p=a.scanLimit,m=p!==void 0&&f.seen>=p,h=(e,t,n,r)=>({page:e,isDone:r,continueCursor:o.seal(JSON.stringify({v:1,mode:`search`,nativeCursor:t,seen:n}),s),completeness:p!==void 0&&n>=p?`result-cap`:`complete`,paginationMode:`native-search`,splitCursor:null,pageStatus:null});if(m||a.plan.unsatisfiable)return h([],f.nativeCursor,f.seen,!0);try{let t={cursor:f.nativeCursor,numItems:Math.min(a.plan.args.numItems,u,e.budgets.searchCandidates,p===void 0?1/0:p-f.seen),id:a.plan.args.id},n=await e.search(i,a.metadata,a.text,a.equalities,t);if(!l().safeParse(n).success||!n.isDone&&n.continueCursor===f.nativeCursor)throw new r(`SEARCH_PROTOCOL_UNSUPPORTED`);let o=f.seen+n.page.length;if(!Number.isSafeInteger(o))throw new r(`SEARCH_PROTOCOL_UNSUPPORTED`);let s=[];for(let e of n.page){let t=await d(e);t!==null&&s.push(t)}return h(s,n.continueCursor,o,n.isDone||p!==void 0&&o>=p)}catch(e){if(e instanceof r)throw e;n(e)}}function o(e){let t;return()=>t??=e()}const s=o(()=>e.object({numItems:e.int().min(1).max(2**53-1),cursor:e.string().nullable(),id:e.number().refine(Number.isFinite,`Invalid input: expected a finite number`).optional(),scanLimit:e.int().min(1).max(2**53-1).optional(),filters:e.any().optional(),endCursor:e.null().optional()})),c=o(()=>e.object({v:e.literal(1),mode:e.literal(`search`),nativeCursor:e.string().nullable(),seen:e.int().min(0).max(2**53-1)})),l=o(()=>e.object({page:e.array(e.any()),isDone:e.boolean(),continueCursor:e.string(),splitCursor:e.null().optional(),pageStatus:e.null().optional(),completeness:e.literal(`complete`).optional()}).strip());export{r as SearchError,a as executeSearch,i as planSearch};
2
2
  //# sourceMappingURL=search.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"search.mjs","names":["SearchError","code","searchInput","z","optionEnvelope","nativePage","planSearch","text","envelope","input","raw","key","parsed","metadata","planner","table","candidate","index","_endCursor","args","planned","constraints","plan","values","equalities","ast","child","field","payload","executeSearch","start","search","codec","binding","CursorError","cap","terminal","finish","seen","options","maxPageSize","request","result","page","document","projected","complete","error","rethrowQueryError"],"sources":["../../src/querying/search.ts"],"sourcesContent":["import { z } from 'zod'\nimport type { createPlanner, QueryInput, StoredConstraint } from './planner'\nimport type { FilterAst, FilterScalar } from './filters'\nimport { MAX_PAGE_SIZE } from './filters'\n\nexport type SearchErrorCode =\n\t| 'SEARCH_TEXT_REQUIRED'\n\t| 'SEARCH_END_CURSOR_UNSUPPORTED'\n\t| 'SEARCH_ORDER_UNSUPPORTED'\n\t| 'SEARCH_RELATION_UNSUPPORTED'\n\t| 'SEARCH_OPTIONS_UNSUPPORTED'\n\t| 'SEARCH_PROTOCOL_UNSUPPORTED'\nexport class SearchError extends Error {\n\tconstructor(readonly code: SearchErrorCode) {\n\t\tsuper(code)\n\t\tthis.name = 'SearchError'\n\t}\n}\nexport type SearchPaginationResult<Row> = Omit<\n\timport('../zod-table').EnginePaginationResult<Row>,\n\t'splitCursor' | 'pageStatus'\n> & { paginationMode: 'native-search'; splitCursor: null; pageStatus: null }\nexport interface SearchInput {\n\tnumItems: number\n\tcursor: string | null\n\tid?: number\n\tscanLimit?: number\n\tfilters?: QueryInput['filters']\n}\nconst searchInput = z.strictObject({\n\tnumItems: z.number().int().positive(),\n\tcursor: z.string().nullable(),\n\tid: z.number().optional(),\n\tscanLimit: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),\n\tfilters: z.any().optional(),\n\tendCursor: z.null().optional(),\n})\nconst optionEnvelope = z.looseObject({\n\tendCursor: z.any().optional(),\n\torder: z.any().optional(),\n\tmaximumRowsRead: z.any().optional(),\n\tmaximumBytesRead: z.any().optional(),\n\tonEmptyBudget: z.any().optional(),\n})\nconst nativePage = z.object({\n\tpage: z.array(z.any()),\n\tisDone: z.boolean(),\n\tcontinueCursor: z.string(),\n\tsplitCursor: z.null().optional(),\n\tpageStatus: z.null().optional(),\n\tcompleteness: z.literal('complete').optional(),\n})\n\n/** Search compilation deliberately supplies no browse indexes or expansion directives. */\nexport function planSearch(\n\tplanner: ReturnType<typeof createPlanner>,\n\ttable: string,\n\tindex: string,\n\ttext: string,\n\tinput: SearchInput,\n\tconstraints: readonly StoredConstraint[],\n) {\n\tif (!z.string().safeParse(text).success || !text.trim())\n\t\tthrow new SearchError('SEARCH_TEXT_REQUIRED')\n\tconst envelope = optionEnvelope.safeParse(input)\n\tif (!envelope.success) throw new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\tconst raw = envelope.data\n\tif (raw.endCursor != null) throw new SearchError('SEARCH_END_CURSOR_UNSUPPORTED')\n\tif (Object.hasOwn(raw, 'order')) throw new SearchError('SEARCH_ORDER_UNSUPPORTED')\n\tif (\n\t\t['maximumRowsRead', 'maximumBytesRead', 'onEmptyBudget'].some((key) => Object.hasOwn(raw, key))\n\t)\n\t\tthrow new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\tconst parsed = searchInput.safeParse(input)\n\tif (!parsed.success) throw new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\tconst metadata = planner.metadata.tables[table]?.searchIndexes.find(\n\t\t(candidate) => candidate.name === index && !candidate.staged,\n\t)\n\tif (!metadata) throw new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\tconst { scanLimit, endCursor: _endCursor, ...args } = parsed.data\n\t// Relation planning with no ordering uses the existing grammar with no browse index selection.\n\t// The shared filter grammar enforces browse page limits; search owns a soft target.\n\tconst planned = planner.plan(\n\t\ttable,\n\t\t{ ...args, numItems: Math.min(args.numItems, MAX_PAGE_SIZE) },\n\t\t[],\n\t\tconstraints,\n\t\tundefined,\n\t\t'relation',\n\t)\n\tconst plan = { ...planned, args: { ...planned.args, numItems: args.numItems } }\n\tconst values = new Map<string, FilterScalar>()\n\tfunction equalities(ast: FilterAst): void {\n\t\tif (ast.kind === 'and') for (const child of ast.children) equalities(child)\n\t\telse if (ast.kind === 'scalar' && ast.operator === 'eq' && !Array.isArray(ast.value))\n\t\t\tvalues.set(ast.field, ast.value)\n\t}\n\tequalities(plan.residual)\n\treturn {\n\t\tplan,\n\t\ttext: text.trim(),\n\t\tmetadata,\n\t\tscanLimit,\n\t\tequalities: metadata.filterFields\n\t\t\t.filter((field) => values.has(field))\n\t\t\t.map((field) => ({ field, value: values.get(field)! })),\n\t}\n}\n\nimport type { GenericDataModel, GenericDocument } from 'convex/server'\nimport type { Value } from 'convex/values'\nimport { CursorError, type CursorBinding, type createCursorCodec } from './cursors'\nimport type { ManagedReadRequest } from './security'\nimport { rethrowQueryError } from './execution'\n\nconst payload = z.strictObject({\n\tv: z.literal(1),\n\tmode: z.literal('search'),\n\tnativeCursor: z.string().nullable(),\n\tseen: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),\n})\ntype SearchPlan = ReturnType<typeof planSearch>\n/** One complete native window. No result token is minted until all descendants finish. */\nexport async function executeSearch(\n\trequest: ManagedReadRequest<GenericDataModel>,\n\ttable: string,\n\tsearch: SearchPlan,\n\tcodec: ReturnType<typeof createCursorCodec>,\n\tbinding: CursorBinding,\n\tmaxPageSize: number,\n\tcomplete: (document: GenericDocument) => Promise<Record<string, Value> | null>,\n): Promise<SearchPaginationResult<Record<string, Value>>> {\n\tlet start: z.output<typeof payload> = {\n\t\tv: 1,\n\t\tmode: 'search',\n\t\tnativeCursor: null,\n\t\tseen: 0,\n\t}\n\tif (search.plan.args.cursor !== null) {\n\t\ttry {\n\t\t\tstart = payload.parse(JSON.parse(codec.open(search.plan.args.cursor, binding)))\n\t\t} catch {\n\t\t\tthrow new CursorError()\n\t\t}\n\t}\n\tconst cap = search.scanLimit\n\tconst terminal = cap !== undefined && start.seen >= cap\n\tconst finish = (\n\t\tpage: Record<string, Value>[],\n\t\tnativeCursor: string | null,\n\t\tseen: number,\n\t\tisDone: boolean,\n\t): SearchPaginationResult<Record<string, Value>> => ({\n\t\tpage,\n\t\tisDone,\n\t\tcontinueCursor: codec.seal(\n\t\t\tJSON.stringify({ v: 1, mode: 'search', nativeCursor, seen }),\n\t\t\tbinding,\n\t\t),\n\t\tcompleteness: cap !== undefined && seen >= cap ? 'result-cap' : 'complete',\n\t\tpaginationMode: 'native-search',\n\t\tsplitCursor: null,\n\t\tpageStatus: null,\n\t})\n\tif (terminal || search.plan.unsatisfiable) return finish([], start.nativeCursor, start.seen, true)\n\ttry {\n\t\tconst options = {\n\t\t\tcursor: start.nativeCursor,\n\t\t\tnumItems: Math.min(\n\t\t\t\tsearch.plan.args.numItems,\n\t\t\t\tmaxPageSize,\n\t\t\t\trequest.budgets.searchCandidates,\n\t\t\t\tcap === undefined ? Infinity : cap - start.seen,\n\t\t\t),\n\t\t\tid: search.plan.args.id,\n\t\t}\n\t\tconst result = await request.search(\n\t\t\ttable,\n\t\t\tsearch.metadata,\n\t\t\tsearch.text,\n\t\t\tsearch.equalities,\n\t\t\toptions,\n\t\t)\n\t\tif (!nativePage.safeParse(result).success) throw new SearchError('SEARCH_PROTOCOL_UNSUPPORTED')\n\t\tif (!result.isDone && result.continueCursor === start.nativeCursor)\n\t\t\tthrow new SearchError('SEARCH_PROTOCOL_UNSUPPORTED')\n\t\tconst seen = start.seen + result.page.length\n\t\tif (!Number.isSafeInteger(seen)) throw new SearchError('SEARCH_PROTOCOL_UNSUPPORTED')\n\t\tconst page: Record<string, Value>[] = []\n\t\tfor (const document of result.page) {\n\t\t\tconst projected = await complete(document)\n\t\t\tif (projected !== null) page.push(projected)\n\t\t}\n\t\treturn finish(\n\t\t\tpage,\n\t\t\tresult.continueCursor,\n\t\t\tseen,\n\t\t\tresult.isDone || (cap !== undefined && seen >= cap),\n\t\t)\n\t} catch (error) {\n\t\tif (error instanceof SearchError) throw error\n\t\trethrowQueryError(error)\n\t}\n}\n"],"mappings":"8IAYA,IAAaA,EAAb,cAAiC,KAAM,CACjB,KAArB,YAAY,EAAgC,CAC3C,MAAMC,CAAI,EADU,KAAA,KAAAA,EAEpB,KAAK,KAAO,aACb,CACD,EAYA,MAAMC,EAAcC,EAAE,aAAa,CAClC,SAAUA,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EACpC,OAAQA,EAAE,OAAO,CAAC,CAAC,SAAS,EAC5B,GAAIA,EAAE,OAAO,CAAC,CAAC,SAAS,EACxB,UAAWA,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,WAA2B,CAAC,CAAC,SAAS,EAC7E,QAASA,EAAE,IAAI,CAAC,CAAC,SAAS,EAC1B,UAAWA,EAAE,KAAK,CAAC,CAAC,SAAS,CAC9B,CAAC,EACKC,EAAiBD,EAAE,YAAY,CACpC,UAAWA,EAAE,IAAI,CAAC,CAAC,SAAS,EAC5B,MAAOA,EAAE,IAAI,CAAC,CAAC,SAAS,EACxB,gBAAiBA,EAAE,IAAI,CAAC,CAAC,SAAS,EAClC,iBAAkBA,EAAE,IAAI,CAAC,CAAC,SAAS,EACnC,cAAeA,EAAE,IAAI,CAAC,CAAC,SAAS,CACjC,CAAC,EACKE,EAAaF,EAAE,OAAO,CAC3B,KAAMA,EAAE,MAAMA,EAAE,IAAI,CAAC,EACrB,OA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ACrB,KAAK,UAAU,CAAE,EAAG,EAAG,KAAM,SAAU,eAAc,MAAK,CAAC,EAC3DC,CACD,EACA,aAAcE,IAAQ,IAAA,IAAaG,GAAQH,EAAM,aAAe,WAChE,eAAgB,gBAChB,YAAa,KACb,WAAY,IACb,GACA,GAAIC,GAAYL,EAAO,KAAK,cAAe,OAAOM,EAAO,CAAC,EAAGP,EAAM,aAAcA,EAAM,KAAM,EAAI,EACjG,GAAI,CACH,IAAMS,EAAU,CACf,OAAQT,EAAM,aACd,SAAU,KAAK,IACdC,EAAO,KAAK,KAAK,SACjBS,EACAC,EAAQ,QAAQ,iBAChBN,IAAQ,IAAA,GAAY,IAAWA,EAAML,EAAM,IAC5C,EACA,GAAIC,EAAO,KAAK,KAAK,EACtB,EACMW,EAAS,MAAMD,EAAQ,OAC5B1B,EACAgB,EAAO,SACPA,EAAO,KACPA,EAAO,WACPQ,CACD,EAEA,GADI,CAAClC,EAAW,UAAUqC,CAAM,CAAC,CAAC,SAC9B,CAACA,EAAO,QAAUA,EAAO,iBAAmBZ,EAAM,aACrD,MAAM,IAAI9B,EAAY,6BAA6B,EACpD,IAAMsC,EAAOR,EAAM,KAAOY,EAAO,KAAK,OACtC,GAAI,CAAC,OAAO,cAAcJ,CAAI,EAAG,MAAM,IAAItC,EAAY,6BAA6B,EACpF,IAAM2C,EAAgC,CAAC,EACvC,IAAK,IAAMC,KAAYF,EAAO,KAAM,CACnC,IAAMG,EAAY,MAAMC,EAASF,CAAQ,EACrCC,IAAc,MAAMF,EAAK,KAAKE,CAAS,CAC5C,CACA,OAAOR,EACNM,EACAD,EAAO,eACPJ,EACAI,EAAO,QAAWP,IAAQ,IAAA,IAAaG,GAAQH,CAChD,CACD,OAASY,EAAO,CACf,GAAIA,aAAiB/C,EAAa,MAAM+C,EACxCC,EAAkBD,CAAK,CACxB,CACD"}
1
+ {"version":3,"file":"search.mjs","names":["SearchError","code","planSearch","text","input","raw","key","parsed","searchInput","metadata","planner","table","candidate","index","_endCursor","args","planned","constraints","plan","values","equalities","ast","child","field","executeSearch","start","search","searchCursor","codec","binding","CursorError","cap","terminal","finish","seen","options","maxPageSize","request","result","nativePage","page","document","projected","complete","error","rethrowQueryError","once","value","build","k"],"sources":["../../src/querying/search.ts"],"sourcesContent":["import { k } from '../k'\nimport type { createPlanner, QueryInput, StoredConstraint } from './planner'\nimport type { FilterAst, FilterScalar } from './filters'\nimport { MAX_PAGE_SIZE } from './filters'\n\nexport type SearchErrorCode =\n\t| 'SEARCH_TEXT_REQUIRED'\n\t| 'SEARCH_END_CURSOR_UNSUPPORTED'\n\t| 'SEARCH_ORDER_UNSUPPORTED'\n\t| 'SEARCH_RELATION_UNSUPPORTED'\n\t| 'SEARCH_OPTIONS_UNSUPPORTED'\n\t| 'SEARCH_PROTOCOL_UNSUPPORTED'\nexport class SearchError extends Error {\n\tconstructor(readonly code: SearchErrorCode) {\n\t\tsuper(code)\n\t\tthis.name = 'SearchError'\n\t}\n}\nexport type SearchPaginationResult<Row> = Omit<\n\timport('../table').EnginePaginationResult<Row>,\n\t'splitCursor' | 'pageStatus'\n> & { paginationMode: 'native-search'; splitCursor: null; pageStatus: null }\nexport interface SearchInput {\n\tnumItems: number\n\tcursor: string | null\n\tid?: number\n\tscanLimit?: number\n\tfilters?: QueryInput['filters']\n}\n\n/** Search compilation deliberately supplies no browse indexes or expansion directives. */\nexport function planSearch(\n\tplanner: ReturnType<typeof createPlanner>,\n\ttable: string,\n\tindex: string,\n\ttext: string,\n\tinput: SearchInput,\n\tconstraints: readonly StoredConstraint[],\n) {\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Search text arrives from untyped callers.\n\tif (typeof text !== 'string' || !text.trim()) throw new SearchError('SEARCH_TEXT_REQUIRED')\n\tif (input === null || Object(input) !== input || Array.isArray(input))\n\t\tthrow new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\tconst raw: SearchInput & { endCursor?: unknown } = input\n\tif (raw.endCursor != null) throw new SearchError('SEARCH_END_CURSOR_UNSUPPORTED')\n\tif (Object.hasOwn(raw, 'order')) throw new SearchError('SEARCH_ORDER_UNSUPPORTED')\n\tif (\n\t\t['maximumRowsRead', 'maximumBytesRead', 'onEmptyBudget'].some((key) => Object.hasOwn(raw, key))\n\t)\n\t\tthrow new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\t// Out-of-range or malformed options are validation failures in the KTD6 shape.\n\tconst parsed = { data: searchInput().parse(input) }\n\tconst metadata = planner.metadata.tables[table]?.searchIndexes.find(\n\t\t(candidate) => candidate.name === index && !candidate.staged,\n\t)\n\tif (!metadata) throw new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\tconst { scanLimit, endCursor: _endCursor, ...args } = parsed.data\n\t// Relation planning with no ordering uses the existing grammar with no browse index selection.\n\t// The shared filter grammar enforces browse page limits; search owns a soft target.\n\tconst planned = planner.plan(\n\t\ttable,\n\t\t{ ...args, numItems: Math.min(args.numItems, MAX_PAGE_SIZE) },\n\t\t[],\n\t\tconstraints,\n\t\tundefined,\n\t\t'relation',\n\t)\n\tconst plan = { ...planned, args: { ...planned.args, numItems: args.numItems } }\n\tconst values = new Map<string, FilterScalar>()\n\tfunction equalities(ast: FilterAst): void {\n\t\tif (ast.kind === 'and') for (const child of ast.children) equalities(child)\n\t\telse if (ast.kind === 'scalar' && ast.operator === 'eq' && !Array.isArray(ast.value))\n\t\t\tvalues.set(ast.field, ast.value)\n\t}\n\tequalities(plan.residual)\n\treturn {\n\t\tplan,\n\t\ttext: text.trim(),\n\t\tmetadata,\n\t\tscanLimit,\n\t\tequalities: metadata.filterFields\n\t\t\t.filter((field) => values.has(field))\n\t\t\t.map((field) => ({ field, value: values.get(field)! })),\n\t}\n}\n\nimport type { GenericDataModel, GenericDocument } from 'convex/server'\nimport type { Value } from 'convex/values'\nimport { CursorError, type CursorBinding, type createCursorCodec } from './cursors'\nimport type { ManagedReadRequest } from './security'\nimport { rethrowQueryError } from './execution'\n\ntype SearchPlan = ReturnType<typeof planSearch>\n/** One complete native window. No result token is minted until all descendants finish. */\nexport async function executeSearch(\n\trequest: ManagedReadRequest<GenericDataModel>,\n\ttable: string,\n\tsearch: SearchPlan,\n\tcodec: ReturnType<typeof createCursorCodec>,\n\tbinding: CursorBinding,\n\tmaxPageSize: number,\n\tcomplete: (document: GenericDocument) => Promise<Record<string, Value> | null>,\n): Promise<SearchPaginationResult<Record<string, Value>>> {\n\tlet start: SearchCursor = {\n\t\tv: 1,\n\t\tmode: 'search',\n\t\tnativeCursor: null,\n\t\tseen: 0,\n\t}\n\tif (search.plan.args.cursor !== null) {\n\t\ttry {\n\t\t\tstart = searchCursor().parse(JSON.parse(codec.open(search.plan.args.cursor, binding)))\n\t\t} catch {\n\t\t\tthrow new CursorError()\n\t\t}\n\t}\n\tconst cap = search.scanLimit\n\tconst terminal = cap !== undefined && start.seen >= cap\n\tconst finish = (\n\t\tpage: Record<string, Value>[],\n\t\tnativeCursor: string | null,\n\t\tseen: number,\n\t\tisDone: boolean,\n\t): SearchPaginationResult<Record<string, Value>> => ({\n\t\tpage,\n\t\tisDone,\n\t\tcontinueCursor: codec.seal(\n\t\t\tJSON.stringify({ v: 1, mode: 'search', nativeCursor, seen }),\n\t\t\tbinding,\n\t\t),\n\t\tcompleteness: cap !== undefined && seen >= cap ? 'result-cap' : 'complete',\n\t\tpaginationMode: 'native-search',\n\t\tsplitCursor: null,\n\t\tpageStatus: null,\n\t})\n\tif (terminal || search.plan.unsatisfiable) return finish([], start.nativeCursor, start.seen, true)\n\ttry {\n\t\tconst options = {\n\t\t\tcursor: start.nativeCursor,\n\t\t\tnumItems: Math.min(\n\t\t\t\tsearch.plan.args.numItems,\n\t\t\t\tmaxPageSize,\n\t\t\t\trequest.budgets.searchCandidates,\n\t\t\t\tcap === undefined ? Infinity : cap - start.seen,\n\t\t\t),\n\t\t\tid: search.plan.args.id,\n\t\t}\n\t\tconst result = await request.search(\n\t\t\ttable,\n\t\t\tsearch.metadata,\n\t\t\tsearch.text,\n\t\t\tsearch.equalities,\n\t\t\toptions,\n\t\t)\n\t\tif (!nativePage().safeParse(result).success)\n\t\t\tthrow new SearchError('SEARCH_PROTOCOL_UNSUPPORTED')\n\t\tif (!result.isDone && result.continueCursor === start.nativeCursor)\n\t\t\tthrow new SearchError('SEARCH_PROTOCOL_UNSUPPORTED')\n\t\tconst seen = start.seen + result.page.length\n\t\tif (!Number.isSafeInteger(seen)) throw new SearchError('SEARCH_PROTOCOL_UNSUPPORTED')\n\t\tconst page: Record<string, Value>[] = []\n\t\tfor (const document of result.page) {\n\t\t\tconst projected = await complete(document)\n\t\t\tif (projected !== null) page.push(projected)\n\t\t}\n\t\treturn finish(\n\t\t\tpage,\n\t\t\tresult.continueCursor,\n\t\t\tseen,\n\t\t\tresult.isDone || (cap !== undefined && seen >= cap),\n\t\t)\n\t} catch (error) {\n\t\tif (error instanceof SearchError) throw error\n\t\trethrowQueryError(error)\n\t}\n}\n\ninterface SearchCursor {\n\tv: 1\n\tmode: 'search'\n\tnativeCursor: string | null\n\tseen: number\n}\n\nfunction once<T>(build: () => T): () => T {\n\tlet value: T | undefined\n\treturn () => (value ??= build())\n}\n\n/** Built on the first search, never at import. */\nconst searchInput = once(() =>\n\tk.object({\n\t\tnumItems: k.int().min(1).max(Number.MAX_SAFE_INTEGER),\n\t\tcursor: k.string().nullable(),\n\t\tid: k.number().refine(Number.isFinite, 'Invalid input: expected a finite number').optional(),\n\t\tscanLimit: k.int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),\n\t\tfilters: k.any().optional(),\n\t\tendCursor: k.null().optional(),\n\t}),\n)\n\nconst searchCursor = once(() =>\n\tk.object({\n\t\tv: k.literal(1),\n\t\tmode: k.literal('search'),\n\t\tnativeCursor: k.string().nullable(),\n\t\tseen: k.int().min(0).max(Number.MAX_SAFE_INTEGER),\n\t}),\n)\n\nconst nativePage = once(() =>\n\tk\n\t\t.object({\n\t\t\tpage: k.array(k.any()),\n\t\t\tisDone: k.boolean(),\n\t\t\tcontinueCursor: k.string(),\n\t\t\tsplitCursor: k.null().optional(),\n\t\t\tpageStatus: k.null().optional(),\n\t\t\tcompleteness: k.literal('complete').optional(),\n\t\t})\n\t\t.strip(),\n)\n"],"mappings":"A,yJAYA,IAAaA,EAAb,cAAiC,KAAM,CACjB,KAArB,YAAY,EAAgC,CAC3C,MAAMC,CAAI,EADU,KAAA,KAAAA,EAEpB,KAAK,KAAO,aACb,CACD,EAcA,SAAgBC,EACf,EACA,EACA,EACA,EACA,EACA,EACC,CAED,GAAI,OAAOC,GAAS,UAAY,CAACA,EAAK,KAAK,EAAG,MAAM,IAAIH,EAAY,sBAAsB,EAC1F,GAAII,IAAU,MAAQ,OAAOA,CAAK,IAAMA,GAAS,MAAM,QAAQA,CAAK,EACnE,MAAM,IAAIJ,EAAY,4BAA4B,EACnD,IAAMK,EAA6CD,EACnD,GAAIC,EAAI,WAAa,KAAM,MAAM,IAAIL,EAAY,+BAA+B,EAChF,GAAI,OAAO,OAAOK,EAAK,OAAO,EAAG,MAAM,IAAIL,EAAY,0BAA0B,EACjF,GACC,CAAC,kBAAmB,mBAAoB,eAAe,CAAC,CAAC,KAAM,GAAQ,OAAO,OAAOK,EAAKC,CAAG,CAAC,EAE9F,MAAM,IAAIN,EAAY,4BAA4B,EAEnD,IAAMO,EAAS,CAAE,KAAMC,EAAY,CAAC,CAAC,MAAMJ,CAAK,CAAE,EAC5CK,EAAWC,EAAQ,SAAS,OAAOC,EAAM,EAAE,cAAc,KAC7D,GAAcC,EAAU,OAASC,GAAS,CAACD,EAAU,MACvD,EACA,GAAI,CAACH,EAAU,MAAM,IAAIT,EAAY,4BAA4B,EACjE,GAAM,CAAE,YAAW,UAAWc,EAAY,GAAGC,GAASR,EAAO,KAGvDS,EAAUN,EAAQ,KACvBC,EACA,CAAE,GAAGI,EAAM,SAAU,KAAK,IAAIA,EAAK,SAAA,GAAuB,CAAE,EAC5D,CAAC,EACDE,EACA,IAAA,GACA,UACD,EACMC,EAAO,CAAE,GAAGF,EAAS,KAAM,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,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,WAA2B,CAAC,CAAC,SAAS,EAChE,QAASA,EAAE,IAAI,CAAC,CAAC,SAAS,EAC1B,UAAWA,EAAE,KAAK,CAAC,CAAC,SAAS,CAC9B,CAAC,CACF,EAEMtB,EAAemB,MACpBG,EAAE,OAAO,CACR,EAAGA,EAAE,QAAQ,CAAC,EACd,KAAMA,EAAE,QAAQ,QAAQ,EACxB,aAAcA,EAAE,OAAO,CAAC,CAAC,SAAS,EAClC,KAAMA,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,WAA2B,CACjD,CAAC,CACF,EAEMV,EAAaO,MAClBG,EACE,OAAO,CACP,KAAMA,EAAE,MAAMA,EAAE,IAAI,CAAC,EACrB,OAAQA,EAAE,QAAQ,EAClB,eAAgBA,EAAE,OAAO,EACzB,YAAaA,EAAE,KAAK,CAAC,CAAC,SAAS,EAC/B,WAAYA,EAAE,KAAK,CAAC,CAAC,SAAS,EAC9B,aAAcA,EAAE,QAAQ,UAAU,CAAC,CAAC,SAAS,CAC9C,CAAC,CAAC,CACD,MAAM,CACT,E"}
@@ -1,9 +1,8 @@
1
1
  import { FilterScalar } from "./shared/ast.mjs";
2
- import "./filters.mjs";
3
2
  import { SearchIndexMetadata } from "../relations.mjs";
3
+ import "./filters.mjs";
4
4
  import { Rules } from "../tenancy.mjs";
5
5
  import { GenericDataModel, GenericDatabaseReader, GenericDocument, PaginationOptions, PaginationResult, QueryInitializer } from "convex/server";
6
- //#region src/querying/security.d.ts
7
6
  export declare const MAX_DOCUMENT_BYTES: number;
8
7
  /** Additive context supplied to existing read/insert/modify rules on BOTH paths.
9
8
  * Reads through db are authorized and bounded. collect, native paginate/filter,
@@ -120,5 +119,5 @@ export declare function createManagedSecurity<DM extends GenericDataModel = Gene
120
119
  * Mutation insert/modify receive the same supplied contract as read callbacks.
121
120
  */
122
121
  export declare function suppliedPolicyRules<DM extends GenericDataModel>(raw: GenericDatabaseReader<DM>, rules: Rules<SecurityPolicyContext<DM>, DM>, defaultPolicy: 'allow' | 'deny'): Rules<SecurityPolicyContext<DM>, DM>;
123
- //#endregion
122
+ export {};
124
123
  //# sourceMappingURL=security.d.mts.map