@tanstack/db 0.5.32 → 0.6.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 (287) hide show
  1. package/dist/cjs/collection/change-events.cjs.map +1 -1
  2. package/dist/cjs/collection/change-events.d.cts +3 -2
  3. package/dist/cjs/collection/changes.cjs +13 -4
  4. package/dist/cjs/collection/changes.cjs.map +1 -1
  5. package/dist/cjs/collection/changes.d.cts +10 -1
  6. package/dist/cjs/collection/cleanup-queue.cjs +89 -0
  7. package/dist/cjs/collection/cleanup-queue.cjs.map +1 -0
  8. package/dist/cjs/collection/cleanup-queue.d.cts +30 -0
  9. package/dist/cjs/collection/events.cjs +14 -0
  10. package/dist/cjs/collection/events.cjs.map +1 -1
  11. package/dist/cjs/collection/events.d.cts +39 -1
  12. package/dist/cjs/collection/index.cjs +66 -28
  13. package/dist/cjs/collection/index.cjs.map +1 -1
  14. package/dist/cjs/collection/index.d.cts +49 -36
  15. package/dist/cjs/collection/indexes.cjs +211 -62
  16. package/dist/cjs/collection/indexes.cjs.map +1 -1
  17. package/dist/cjs/collection/indexes.d.cts +27 -17
  18. package/dist/cjs/collection/lifecycle.cjs +5 -22
  19. package/dist/cjs/collection/lifecycle.cjs.map +1 -1
  20. package/dist/cjs/collection/lifecycle.d.cts +0 -1
  21. package/dist/cjs/collection/mutations.cjs +18 -0
  22. package/dist/cjs/collection/mutations.cjs.map +1 -1
  23. package/dist/cjs/collection/mutations.d.cts +1 -0
  24. package/dist/cjs/collection/state.cjs +381 -53
  25. package/dist/cjs/collection/state.cjs.map +1 -1
  26. package/dist/cjs/collection/state.d.cts +65 -1
  27. package/dist/cjs/collection/subscription.cjs +6 -0
  28. package/dist/cjs/collection/subscription.cjs.map +1 -1
  29. package/dist/cjs/collection/subscription.d.cts +4 -0
  30. package/dist/cjs/collection/sync.cjs +108 -1
  31. package/dist/cjs/collection/sync.cjs.map +1 -1
  32. package/dist/cjs/collection/sync.d.cts +2 -0
  33. package/dist/cjs/collection/transaction-metadata.cjs +5 -0
  34. package/dist/cjs/collection/transaction-metadata.cjs.map +1 -0
  35. package/dist/cjs/collection/transaction-metadata.d.cts +1 -0
  36. package/dist/cjs/errors.cjs +8 -0
  37. package/dist/cjs/errors.cjs.map +1 -1
  38. package/dist/cjs/errors.d.cts +3 -0
  39. package/dist/cjs/index.cjs +24 -4
  40. package/dist/cjs/index.cjs.map +1 -1
  41. package/dist/cjs/index.d.cts +12 -3
  42. package/dist/cjs/indexes/auto-index.cjs +13 -6
  43. package/dist/cjs/indexes/auto-index.cjs.map +1 -1
  44. package/dist/cjs/indexes/base-index.cjs +0 -3
  45. package/dist/cjs/indexes/base-index.cjs.map +1 -1
  46. package/dist/cjs/indexes/base-index.d.cts +2 -6
  47. package/dist/cjs/indexes/basic-index.cjs +361 -0
  48. package/dist/cjs/indexes/basic-index.cjs.map +1 -0
  49. package/dist/cjs/indexes/basic-index.d.cts +102 -0
  50. package/dist/cjs/indexes/btree-index.cjs.map +1 -1
  51. package/dist/cjs/indexes/btree-index.d.cts +1 -1
  52. package/dist/cjs/indexes/index-options.d.cts +8 -9
  53. package/dist/cjs/indexes/index-registry.cjs +89 -0
  54. package/dist/cjs/indexes/index-registry.cjs.map +1 -0
  55. package/dist/cjs/indexes/index-registry.d.cts +61 -0
  56. package/dist/cjs/local-only.cjs +5 -0
  57. package/dist/cjs/local-only.cjs.map +1 -1
  58. package/dist/cjs/query/builder/functions.cjs +27 -11
  59. package/dist/cjs/query/builder/functions.cjs.map +1 -1
  60. package/dist/cjs/query/builder/functions.d.cts +25 -3
  61. package/dist/cjs/query/builder/index.cjs +200 -39
  62. package/dist/cjs/query/builder/index.cjs.map +1 -1
  63. package/dist/cjs/query/builder/index.d.cts +4 -3
  64. package/dist/cjs/query/builder/ref-proxy.cjs.map +1 -1
  65. package/dist/cjs/query/builder/ref-proxy.d.cts +14 -3
  66. package/dist/cjs/query/builder/types.d.cts +84 -19
  67. package/dist/cjs/query/compiler/evaluators.cjs +51 -0
  68. package/dist/cjs/query/compiler/evaluators.cjs.map +1 -1
  69. package/dist/cjs/query/compiler/group-by.cjs +100 -28
  70. package/dist/cjs/query/compiler/group-by.cjs.map +1 -1
  71. package/dist/cjs/query/compiler/group-by.d.cts +4 -2
  72. package/dist/cjs/query/compiler/index.cjs +283 -11
  73. package/dist/cjs/query/compiler/index.cjs.map +1 -1
  74. package/dist/cjs/query/compiler/index.d.cts +30 -2
  75. package/dist/cjs/query/compiler/order-by.cjs +29 -10
  76. package/dist/cjs/query/compiler/order-by.cjs.map +1 -1
  77. package/dist/cjs/query/compiler/order-by.d.cts +1 -1
  78. package/dist/cjs/query/compiler/select.cjs +8 -0
  79. package/dist/cjs/query/compiler/select.cjs.map +1 -1
  80. package/dist/cjs/query/effect.cjs +602 -0
  81. package/dist/cjs/query/effect.cjs.map +1 -0
  82. package/dist/cjs/query/effect.d.cts +94 -0
  83. package/dist/cjs/query/index.d.cts +2 -1
  84. package/dist/cjs/query/ir.cjs +18 -1
  85. package/dist/cjs/query/ir.cjs.map +1 -1
  86. package/dist/cjs/query/ir.d.cts +21 -1
  87. package/dist/cjs/query/live/collection-config-builder.cjs +493 -66
  88. package/dist/cjs/query/live/collection-config-builder.cjs.map +1 -1
  89. package/dist/cjs/query/live/collection-config-builder.d.cts +7 -0
  90. package/dist/cjs/query/live/collection-subscriber.cjs +33 -100
  91. package/dist/cjs/query/live/collection-subscriber.cjs.map +1 -1
  92. package/dist/cjs/query/live/collection-subscriber.d.cts +0 -1
  93. package/dist/cjs/query/live/types.d.cts +3 -3
  94. package/dist/cjs/query/live/utils.cjs +219 -0
  95. package/dist/cjs/query/live/utils.cjs.map +1 -0
  96. package/dist/cjs/query/live/utils.d.cts +110 -0
  97. package/dist/cjs/query/live-query-collection.cjs.map +1 -1
  98. package/dist/cjs/query/live-query-collection.d.cts +9 -6
  99. package/dist/cjs/query/query-once.cjs.map +1 -1
  100. package/dist/cjs/query/query-once.d.cts +7 -5
  101. package/dist/cjs/query/subset-dedupe.cjs +9 -3
  102. package/dist/cjs/query/subset-dedupe.cjs.map +1 -1
  103. package/dist/cjs/types.d.cts +42 -8
  104. package/dist/cjs/utils/array-utils.cjs +27 -0
  105. package/dist/cjs/utils/array-utils.cjs.map +1 -0
  106. package/dist/cjs/utils/array-utils.d.cts +16 -0
  107. package/dist/cjs/utils/comparison.cjs +11 -0
  108. package/dist/cjs/utils/comparison.cjs.map +1 -1
  109. package/dist/cjs/utils/index-optimization.cjs +4 -0
  110. package/dist/cjs/utils/index-optimization.cjs.map +1 -1
  111. package/dist/cjs/utils.cjs +7 -9
  112. package/dist/cjs/utils.cjs.map +1 -1
  113. package/dist/cjs/utils.d.cts +6 -1
  114. package/dist/cjs/virtual-props.cjs +33 -0
  115. package/dist/cjs/virtual-props.cjs.map +1 -0
  116. package/dist/cjs/virtual-props.d.cts +196 -0
  117. package/dist/esm/collection/change-events.d.ts +3 -2
  118. package/dist/esm/collection/change-events.js.map +1 -1
  119. package/dist/esm/collection/changes.d.ts +10 -1
  120. package/dist/esm/collection/changes.js +13 -4
  121. package/dist/esm/collection/changes.js.map +1 -1
  122. package/dist/esm/collection/cleanup-queue.d.ts +30 -0
  123. package/dist/esm/collection/cleanup-queue.js +89 -0
  124. package/dist/esm/collection/cleanup-queue.js.map +1 -0
  125. package/dist/esm/collection/events.d.ts +39 -1
  126. package/dist/esm/collection/events.js +14 -0
  127. package/dist/esm/collection/events.js.map +1 -1
  128. package/dist/esm/collection/index.d.ts +49 -36
  129. package/dist/esm/collection/index.js +67 -29
  130. package/dist/esm/collection/index.js.map +1 -1
  131. package/dist/esm/collection/indexes.d.ts +27 -17
  132. package/dist/esm/collection/indexes.js +211 -62
  133. package/dist/esm/collection/indexes.js.map +1 -1
  134. package/dist/esm/collection/lifecycle.d.ts +0 -1
  135. package/dist/esm/collection/lifecycle.js +5 -22
  136. package/dist/esm/collection/lifecycle.js.map +1 -1
  137. package/dist/esm/collection/mutations.d.ts +1 -0
  138. package/dist/esm/collection/mutations.js +18 -0
  139. package/dist/esm/collection/mutations.js.map +1 -1
  140. package/dist/esm/collection/state.d.ts +65 -1
  141. package/dist/esm/collection/state.js +381 -53
  142. package/dist/esm/collection/state.js.map +1 -1
  143. package/dist/esm/collection/subscription.d.ts +4 -0
  144. package/dist/esm/collection/subscription.js +6 -0
  145. package/dist/esm/collection/subscription.js.map +1 -1
  146. package/dist/esm/collection/sync.d.ts +2 -0
  147. package/dist/esm/collection/sync.js +108 -1
  148. package/dist/esm/collection/sync.js.map +1 -1
  149. package/dist/esm/collection/transaction-metadata.d.ts +1 -0
  150. package/dist/esm/collection/transaction-metadata.js +5 -0
  151. package/dist/esm/collection/transaction-metadata.js.map +1 -0
  152. package/dist/esm/errors.d.ts +3 -0
  153. package/dist/esm/errors.js +8 -0
  154. package/dist/esm/errors.js.map +1 -1
  155. package/dist/esm/index.d.ts +12 -3
  156. package/dist/esm/index.js +27 -7
  157. package/dist/esm/index.js.map +1 -1
  158. package/dist/esm/indexes/auto-index.js +13 -6
  159. package/dist/esm/indexes/auto-index.js.map +1 -1
  160. package/dist/esm/indexes/base-index.d.ts +2 -6
  161. package/dist/esm/indexes/base-index.js +1 -4
  162. package/dist/esm/indexes/base-index.js.map +1 -1
  163. package/dist/esm/indexes/basic-index.d.ts +102 -0
  164. package/dist/esm/indexes/basic-index.js +361 -0
  165. package/dist/esm/indexes/basic-index.js.map +1 -0
  166. package/dist/esm/indexes/btree-index.d.ts +1 -1
  167. package/dist/esm/indexes/btree-index.js.map +1 -1
  168. package/dist/esm/indexes/index-options.d.ts +8 -9
  169. package/dist/esm/indexes/index-registry.d.ts +61 -0
  170. package/dist/esm/indexes/index-registry.js +89 -0
  171. package/dist/esm/indexes/index-registry.js.map +1 -0
  172. package/dist/esm/local-only.js +5 -0
  173. package/dist/esm/local-only.js.map +1 -1
  174. package/dist/esm/query/builder/functions.d.ts +25 -3
  175. package/dist/esm/query/builder/functions.js +27 -11
  176. package/dist/esm/query/builder/functions.js.map +1 -1
  177. package/dist/esm/query/builder/index.d.ts +4 -3
  178. package/dist/esm/query/builder/index.js +201 -40
  179. package/dist/esm/query/builder/index.js.map +1 -1
  180. package/dist/esm/query/builder/ref-proxy.d.ts +14 -3
  181. package/dist/esm/query/builder/ref-proxy.js.map +1 -1
  182. package/dist/esm/query/builder/types.d.ts +84 -19
  183. package/dist/esm/query/compiler/evaluators.js +51 -0
  184. package/dist/esm/query/compiler/evaluators.js.map +1 -1
  185. package/dist/esm/query/compiler/group-by.d.ts +4 -2
  186. package/dist/esm/query/compiler/group-by.js +101 -29
  187. package/dist/esm/query/compiler/group-by.js.map +1 -1
  188. package/dist/esm/query/compiler/index.d.ts +30 -2
  189. package/dist/esm/query/compiler/index.js +285 -13
  190. package/dist/esm/query/compiler/index.js.map +1 -1
  191. package/dist/esm/query/compiler/order-by.d.ts +1 -1
  192. package/dist/esm/query/compiler/order-by.js +30 -11
  193. package/dist/esm/query/compiler/order-by.js.map +1 -1
  194. package/dist/esm/query/compiler/select.js +8 -0
  195. package/dist/esm/query/compiler/select.js.map +1 -1
  196. package/dist/esm/query/effect.d.ts +94 -0
  197. package/dist/esm/query/effect.js +602 -0
  198. package/dist/esm/query/effect.js.map +1 -0
  199. package/dist/esm/query/index.d.ts +2 -1
  200. package/dist/esm/query/ir.d.ts +21 -1
  201. package/dist/esm/query/ir.js +18 -1
  202. package/dist/esm/query/ir.js.map +1 -1
  203. package/dist/esm/query/live/collection-config-builder.d.ts +7 -0
  204. package/dist/esm/query/live/collection-config-builder.js +492 -65
  205. package/dist/esm/query/live/collection-config-builder.js.map +1 -1
  206. package/dist/esm/query/live/collection-subscriber.d.ts +0 -1
  207. package/dist/esm/query/live/collection-subscriber.js +31 -98
  208. package/dist/esm/query/live/collection-subscriber.js.map +1 -1
  209. package/dist/esm/query/live/types.d.ts +3 -3
  210. package/dist/esm/query/live/utils.d.ts +110 -0
  211. package/dist/esm/query/live/utils.js +219 -0
  212. package/dist/esm/query/live/utils.js.map +1 -0
  213. package/dist/esm/query/live-query-collection.d.ts +9 -6
  214. package/dist/esm/query/live-query-collection.js.map +1 -1
  215. package/dist/esm/query/query-once.d.ts +7 -5
  216. package/dist/esm/query/query-once.js.map +1 -1
  217. package/dist/esm/query/subset-dedupe.js +9 -3
  218. package/dist/esm/query/subset-dedupe.js.map +1 -1
  219. package/dist/esm/types.d.ts +42 -8
  220. package/dist/esm/utils/array-utils.d.ts +16 -0
  221. package/dist/esm/utils/array-utils.js +27 -0
  222. package/dist/esm/utils/array-utils.js.map +1 -0
  223. package/dist/esm/utils/comparison.js +11 -0
  224. package/dist/esm/utils/comparison.js.map +1 -1
  225. package/dist/esm/utils/index-optimization.js +4 -0
  226. package/dist/esm/utils/index-optimization.js.map +1 -1
  227. package/dist/esm/utils.d.ts +6 -1
  228. package/dist/esm/utils.js +7 -9
  229. package/dist/esm/utils.js.map +1 -1
  230. package/dist/esm/virtual-props.d.ts +196 -0
  231. package/dist/esm/virtual-props.js +33 -0
  232. package/dist/esm/virtual-props.js.map +1 -0
  233. package/package.json +2 -2
  234. package/skills/db-core/collection-setup/references/electric-adapter.md +1 -1
  235. package/src/collection/change-events.ts +13 -9
  236. package/src/collection/changes.ts +30 -7
  237. package/src/collection/cleanup-queue.ts +105 -0
  238. package/src/collection/events.ts +65 -0
  239. package/src/collection/index.ts +110 -45
  240. package/src/collection/indexes.ts +283 -76
  241. package/src/collection/lifecycle.ts +5 -26
  242. package/src/collection/mutations.ts +21 -0
  243. package/src/collection/state.ts +545 -71
  244. package/src/collection/subscription.ts +7 -0
  245. package/src/collection/sync.ts +137 -0
  246. package/src/collection/transaction-metadata.ts +1 -0
  247. package/src/errors.ts +9 -0
  248. package/src/index.ts +57 -3
  249. package/src/indexes/auto-index.ts +18 -8
  250. package/src/indexes/base-index.ts +2 -10
  251. package/src/indexes/basic-index.ts +507 -0
  252. package/src/indexes/btree-index.ts +1 -1
  253. package/src/indexes/index-options.ts +17 -37
  254. package/src/indexes/index-registry.ts +174 -0
  255. package/src/local-only.ts +7 -0
  256. package/src/query/builder/functions.ts +84 -7
  257. package/src/query/builder/index.ts +329 -9
  258. package/src/query/builder/ref-proxy.ts +22 -4
  259. package/src/query/builder/types.ts +257 -62
  260. package/src/query/compiler/evaluators.ts +57 -0
  261. package/src/query/compiler/group-by.ts +156 -35
  262. package/src/query/compiler/index.ts +445 -15
  263. package/src/query/compiler/order-by.ts +51 -12
  264. package/src/query/compiler/select.ts +9 -0
  265. package/src/query/effect.ts +1119 -0
  266. package/src/query/index.ts +7 -0
  267. package/src/query/ir.ts +23 -2
  268. package/src/query/live/collection-config-builder.ts +778 -104
  269. package/src/query/live/collection-subscriber.ts +40 -156
  270. package/src/query/live/types.ts +10 -4
  271. package/src/query/live/utils.ts +417 -0
  272. package/src/query/live-query-collection.ts +43 -18
  273. package/src/query/query-once.ts +31 -12
  274. package/src/query/subset-dedupe.ts +11 -7
  275. package/src/types.ts +49 -9
  276. package/src/utils/array-utils.ts +49 -0
  277. package/src/utils/comparison.ts +14 -0
  278. package/src/utils/index-optimization.ts +4 -0
  279. package/src/utils.ts +12 -9
  280. package/src/virtual-props.ts +282 -0
  281. package/dist/cjs/indexes/lazy-index.cjs +0 -190
  282. package/dist/cjs/indexes/lazy-index.cjs.map +0 -1
  283. package/dist/cjs/indexes/lazy-index.d.cts +0 -96
  284. package/dist/esm/indexes/lazy-index.d.ts +0 -96
  285. package/dist/esm/indexes/lazy-index.js +0 -190
  286. package/dist/esm/indexes/lazy-index.js.map +0 -1
  287. package/src/indexes/lazy-index.ts +0 -251
@@ -4,6 +4,7 @@ const index = require("../../collection/index.cjs");
4
4
  const ir = require("../ir.cjs");
5
5
  const errors = require("../../errors.cjs");
6
6
  const refProxy = require("./ref-proxy.cjs");
7
+ const functions = require("./functions.cjs");
7
8
  class BaseQueryBuilder {
8
9
  constructor(query = {}) {
9
10
  this.query = {};
@@ -283,45 +284,15 @@ class BaseQueryBuilder {
283
284
  having: [...existingHaving, expression]
284
285
  });
285
286
  }
286
- /**
287
- * Select specific columns or computed values from the query
288
- *
289
- * @param callback - A function that receives table references and returns an object with selected fields or expressions
290
- * @returns A QueryBuilder that returns only the selected fields
291
- *
292
- * @example
293
- * ```ts
294
- * // Select specific columns
295
- * query
296
- * .from({ users: usersCollection })
297
- * .select(({users}) => ({
298
- * name: users.name,
299
- * email: users.email
300
- * }))
301
- *
302
- * // Select with computed values
303
- * query
304
- * .from({ users: usersCollection })
305
- * .select(({users}) => ({
306
- * fullName: concat(users.firstName, ' ', users.lastName),
307
- * ageInMonths: mul(users.age, 12)
308
- * }))
309
- *
310
- * // Select with aggregates (requires GROUP BY)
311
- * query
312
- * .from({ posts: postsCollection })
313
- * .groupBy(({posts}) => posts.userId)
314
- * .select(({posts, count}) => ({
315
- * userId: posts.userId,
316
- * postCount: count(posts.id)
317
- * }))
318
- * ```
319
- */
320
287
  select(callback) {
321
288
  const aliases = this._getCurrentAliases();
322
289
  const refProxy$1 = refProxy.createRefProxy(aliases);
323
- const selectObject = callback(refProxy$1);
324
- const select = buildNestedSelect(selectObject);
290
+ let selectObject = callback(refProxy$1);
291
+ if (refProxy.isRefProxy(selectObject) && selectObject.__path.length === 1) {
292
+ const sentinelKey = `__SPREAD_SENTINEL__${selectObject.__path[0]}__0`;
293
+ selectObject = { [sentinelKey]: true };
294
+ }
295
+ const select = buildNestedSelect(selectObject, aliases);
325
296
  return new BaseQueryBuilder({
326
297
  ...this.query,
327
298
  select,
@@ -473,7 +444,7 @@ class BaseQueryBuilder {
473
444
  * // Get countries our users are from
474
445
  * query
475
446
  * .from({ users: usersCollection })
476
- * .select(({users}) => users.country)
447
+ * .select(({users}) => ({ country: users.country }))
477
448
  * .distinct()
478
449
  * ```
479
450
  */
@@ -634,7 +605,7 @@ function toExpr(value) {
634
605
  function isPlainObject(value) {
635
606
  return value !== null && typeof value === `object` && !ir.isExpressionLike(value) && !value.__refProxy;
636
607
  }
637
- function buildNestedSelect(obj) {
608
+ function buildNestedSelect(obj, parentAliases = []) {
638
609
  if (!isPlainObject(obj)) return toExpr(obj);
639
610
  const out = {};
640
611
  for (const [k, v] of Object.entries(obj)) {
@@ -642,10 +613,200 @@ function buildNestedSelect(obj) {
642
613
  out[k] = v;
643
614
  continue;
644
615
  }
645
- out[k] = buildNestedSelect(v);
616
+ if (v instanceof BaseQueryBuilder) {
617
+ out[k] = buildIncludesSubquery(v, k, parentAliases, `collection`);
618
+ continue;
619
+ }
620
+ if (v instanceof functions.ToArrayWrapper) {
621
+ if (!(v.query instanceof BaseQueryBuilder)) {
622
+ throw new Error(`toArray() must wrap a subquery builder`);
623
+ }
624
+ out[k] = buildIncludesSubquery(v.query, k, parentAliases, `array`);
625
+ continue;
626
+ }
627
+ if (v instanceof functions.ConcatToArrayWrapper) {
628
+ if (!(v.query instanceof BaseQueryBuilder)) {
629
+ throw new Error(`concat(toArray(...)) must wrap a subquery builder`);
630
+ }
631
+ out[k] = buildIncludesSubquery(v.query, k, parentAliases, `concat`);
632
+ continue;
633
+ }
634
+ out[k] = buildNestedSelect(v, parentAliases);
646
635
  }
647
636
  return out;
648
637
  }
638
+ function collectRefsFromExpression(expr) {
639
+ const refs = [];
640
+ switch (expr.type) {
641
+ case `ref`:
642
+ refs.push(expr);
643
+ break;
644
+ case `func`:
645
+ for (const arg of expr.args ?? []) {
646
+ refs.push(...collectRefsFromExpression(arg));
647
+ }
648
+ break;
649
+ }
650
+ return refs;
651
+ }
652
+ function referencesParent(where, parentAliases) {
653
+ const expr = typeof where === `object` && `expression` in where ? where.expression : where;
654
+ return collectRefsFromExpression(expr).some(
655
+ (ref) => ref.path[0] != null && parentAliases.includes(ref.path[0])
656
+ );
657
+ }
658
+ function buildIncludesSubquery(childBuilder, fieldName, parentAliases, materialization) {
659
+ const childQuery = childBuilder._getQuery();
660
+ const childAliases = [childQuery.from.alias];
661
+ if (childQuery.join) {
662
+ for (const j of childQuery.join) {
663
+ childAliases.push(j.from.alias);
664
+ }
665
+ }
666
+ let parentRef;
667
+ let childRef;
668
+ let correlationWhereIndex = -1;
669
+ let correlationAndArgIndex = -1;
670
+ if (childQuery.where) {
671
+ for (let i = 0; i < childQuery.where.length; i++) {
672
+ const where = childQuery.where[i];
673
+ const expr = typeof where === `object` && `expression` in where ? where.expression : where;
674
+ if (expr.type === `func` && expr.name === `eq` && expr.args.length === 2) {
675
+ const result = extractCorrelation(
676
+ expr.args[0],
677
+ expr.args[1],
678
+ parentAliases,
679
+ childAliases
680
+ );
681
+ if (result) {
682
+ parentRef = result.parentRef;
683
+ childRef = result.childRef;
684
+ correlationWhereIndex = i;
685
+ break;
686
+ }
687
+ }
688
+ if (expr.type === `func` && expr.name === `and` && expr.args.length >= 2) {
689
+ for (let j = 0; j < expr.args.length; j++) {
690
+ const arg = expr.args[j];
691
+ if (arg.type === `func` && arg.name === `eq` && arg.args.length === 2) {
692
+ const result = extractCorrelation(
693
+ arg.args[0],
694
+ arg.args[1],
695
+ parentAliases,
696
+ childAliases
697
+ );
698
+ if (result) {
699
+ parentRef = result.parentRef;
700
+ childRef = result.childRef;
701
+ correlationWhereIndex = i;
702
+ correlationAndArgIndex = j;
703
+ break;
704
+ }
705
+ }
706
+ }
707
+ if (parentRef) break;
708
+ }
709
+ }
710
+ }
711
+ if (!parentRef || !childRef || correlationWhereIndex === -1) {
712
+ throw new Error(
713
+ `Includes subquery for "${fieldName}" must have a WHERE clause with an eq() condition that correlates a parent field with a child field. Example: .where(({child}) => eq(child.parentId, parent.id))`
714
+ );
715
+ }
716
+ const modifiedWhere = [...childQuery.where];
717
+ if (correlationAndArgIndex >= 0) {
718
+ const where = modifiedWhere[correlationWhereIndex];
719
+ const expr = typeof where === `object` && `expression` in where ? where.expression : where;
720
+ const remainingArgs = expr.args.filter(
721
+ (_, idx) => idx !== correlationAndArgIndex
722
+ );
723
+ if (remainingArgs.length === 1) {
724
+ const isResidual = typeof where === `object` && `expression` in where && where.residual;
725
+ modifiedWhere[correlationWhereIndex] = isResidual ? { expression: remainingArgs[0], residual: true } : remainingArgs[0];
726
+ } else {
727
+ const newAnd = new ir.Func(`and`, remainingArgs);
728
+ const isResidual = typeof where === `object` && `expression` in where && where.residual;
729
+ modifiedWhere[correlationWhereIndex] = isResidual ? { expression: newAnd, residual: true } : newAnd;
730
+ }
731
+ } else {
732
+ modifiedWhere.splice(correlationWhereIndex, 1);
733
+ }
734
+ const pureChildWhere = [];
735
+ const parentFilters = [];
736
+ for (const w of modifiedWhere) {
737
+ if (referencesParent(w, parentAliases)) {
738
+ parentFilters.push(w);
739
+ } else {
740
+ pureChildWhere.push(w);
741
+ }
742
+ }
743
+ let parentProjection;
744
+ if (parentFilters.length > 0) {
745
+ const seen = /* @__PURE__ */ new Set();
746
+ parentProjection = [];
747
+ for (const w of parentFilters) {
748
+ const expr = typeof w === `object` && `expression` in w ? w.expression : w;
749
+ for (const ref of collectRefsFromExpression(expr)) {
750
+ if (ref.path[0] != null && parentAliases.includes(ref.path[0]) && !seen.has(ref.path.join(`.`))) {
751
+ seen.add(ref.path.join(`.`));
752
+ parentProjection.push(ref);
753
+ }
754
+ }
755
+ }
756
+ }
757
+ const modifiedQuery = {
758
+ ...childQuery,
759
+ where: pureChildWhere.length > 0 ? pureChildWhere : void 0
760
+ };
761
+ const rawChildSelect = modifiedQuery.select;
762
+ const hasObjectSelect = rawChildSelect === void 0 || isPlainObject(rawChildSelect);
763
+ let includesQuery = modifiedQuery;
764
+ let scalarField;
765
+ if (materialization === `concat`) {
766
+ if (rawChildSelect === void 0 || hasObjectSelect) {
767
+ throw new Error(
768
+ `concat(toArray(...)) for "${fieldName}" requires the subquery to select a scalar value`
769
+ );
770
+ }
771
+ }
772
+ if (!hasObjectSelect) {
773
+ if (materialization === `collection`) {
774
+ throw new Error(
775
+ `Includes subquery for "${fieldName}" must select an object when materializing as a Collection`
776
+ );
777
+ }
778
+ scalarField = ir.INCLUDES_SCALAR_FIELD;
779
+ includesQuery = {
780
+ ...modifiedQuery,
781
+ select: {
782
+ [scalarField]: rawChildSelect
783
+ }
784
+ };
785
+ }
786
+ return new ir.IncludesSubquery(
787
+ includesQuery,
788
+ parentRef,
789
+ childRef,
790
+ fieldName,
791
+ parentFilters.length > 0 ? parentFilters : void 0,
792
+ parentProjection,
793
+ materialization,
794
+ scalarField
795
+ );
796
+ }
797
+ function extractCorrelation(argA, argB, parentAliases, childAliases) {
798
+ if (argA.type === `ref` && argB.type === `ref`) {
799
+ const aAlias = argA.path[0];
800
+ const bAlias = argB.path[0];
801
+ if (aAlias && bAlias && parentAliases.includes(aAlias) && childAliases.includes(bAlias)) {
802
+ return { parentRef: argA, childRef: argB };
803
+ }
804
+ if (aAlias && bAlias && parentAliases.includes(bAlias) && childAliases.includes(aAlias)) {
805
+ return { parentRef: argB, childRef: argA };
806
+ }
807
+ }
808
+ return void 0;
809
+ }
649
810
  function buildQuery(fn) {
650
811
  const result = fn(new BaseQueryBuilder());
651
812
  return getQueryIR(result);
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../../../src/query/builder/index.ts"],"sourcesContent":["import { CollectionImpl } from '../../collection/index.js'\nimport {\n Aggregate as AggregateExpr,\n CollectionRef,\n Func as FuncExpr,\n PropRef,\n QueryRef,\n Value as ValueExpr,\n isExpressionLike,\n} from '../ir.js'\nimport {\n InvalidSourceError,\n InvalidSourceTypeError,\n InvalidWhereExpressionError,\n JoinConditionMustBeEqualityError,\n OnlyOneSourceAllowedError,\n QueryMustHaveFromClauseError,\n SubQueryMustHaveFromClauseError,\n} from '../../errors.js'\nimport {\n createRefProxy,\n createRefProxyWithSelected,\n isRefProxy,\n toExpression,\n} from './ref-proxy.js'\nimport type { NamespacedRow, SingleResult } from '../../types.js'\nimport type {\n Aggregate,\n BasicExpression,\n JoinClause,\n OrderBy,\n OrderByDirection,\n QueryIR,\n} from '../ir.js'\nimport type {\n CompareOptions,\n Context,\n FunctionalHavingRow,\n GetResult,\n GroupByCallback,\n JoinOnCallback,\n MergeContextForJoinCallback,\n MergeContextWithJoinType,\n OrderByCallback,\n OrderByOptions,\n RefsForContext,\n ResultTypeFromSelect,\n SchemaFromSource,\n SelectObject,\n Source,\n WhereCallback,\n WithResult,\n} from './types.js'\n\nexport class BaseQueryBuilder<TContext extends Context = Context> {\n private readonly query: Partial<QueryIR> = {}\n\n constructor(query: Partial<QueryIR> = {}) {\n this.query = { ...query }\n }\n\n /**\n * Creates a CollectionRef or QueryRef from a source object\n * @param source - An object with a single key-value pair\n * @param context - Context string for error messages (e.g., \"from clause\", \"join clause\")\n * @returns A tuple of [alias, ref] where alias is the source key and ref is the created reference\n */\n private _createRefForSource<TSource extends Source>(\n source: TSource,\n context: string,\n ): [string, CollectionRef | QueryRef] {\n // Validate source is a plain object (not null, array, string, etc.)\n // We use try-catch to handle null/undefined gracefully\n let keys: Array<string>\n try {\n keys = Object.keys(source)\n } catch {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const type = source === null ? `null` : `undefined`\n throw new InvalidSourceTypeError(context, type)\n }\n\n // Check if it's an array (arrays pass Object.keys but aren't valid sources)\n if (Array.isArray(source)) {\n throw new InvalidSourceTypeError(context, `array`)\n }\n\n // Validate exactly one key\n if (keys.length !== 1) {\n if (keys.length === 0) {\n throw new InvalidSourceTypeError(context, `empty object`)\n }\n // Check if it looks like a string was passed (has numeric keys)\n if (keys.every((k) => !isNaN(Number(k)))) {\n throw new InvalidSourceTypeError(context, `string`)\n }\n throw new OnlyOneSourceAllowedError(context)\n }\n\n const alias = keys[0]!\n const sourceValue = source[alias]\n\n // Validate the value is a Collection or QueryBuilder\n let ref: CollectionRef | QueryRef\n\n if (sourceValue instanceof CollectionImpl) {\n ref = new CollectionRef(sourceValue, alias)\n } else if (sourceValue instanceof BaseQueryBuilder) {\n const subQuery = sourceValue._getQuery()\n if (!(subQuery as Partial<QueryIR>).from) {\n throw new SubQueryMustHaveFromClauseError(context)\n }\n ref = new QueryRef(subQuery, alias)\n } else {\n throw new InvalidSourceError(alias)\n }\n\n return [alias, ref]\n }\n\n /**\n * Specify the source table or subquery for the query\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @returns A QueryBuilder with the specified source\n *\n * @example\n * ```ts\n * // Query from a collection\n * query.from({ users: usersCollection })\n *\n * // Query from a subquery\n * const activeUsers = query.from({ u: usersCollection }).where(({u}) => u.active)\n * query.from({ activeUsers })\n * ```\n */\n from<TSource extends Source>(\n source: TSource,\n ): QueryBuilder<{\n baseSchema: SchemaFromSource<TSource>\n schema: SchemaFromSource<TSource>\n fromSourceName: keyof TSource & string\n hasJoins: false\n }> {\n const [, from] = this._createRefForSource(source, `from clause`)\n\n return new BaseQueryBuilder({\n ...this.query,\n from,\n }) as any\n }\n\n /**\n * Join another table or subquery to the current query\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @param type - The type of join: 'inner', 'left', 'right', or 'full' (defaults to 'left')\n * @returns A QueryBuilder with the joined table available\n *\n * @example\n * ```ts\n * // Left join users with posts\n * query\n * .from({ users: usersCollection })\n * .join({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n *\n * // Inner join with explicit type\n * query\n * .from({ u: usersCollection })\n * .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId), 'inner')\n * ```\n *\n * // Join with a subquery\n * const activeUsers = query.from({ u: usersCollection }).where(({u}) => u.active)\n * query\n * .from({ activeUsers })\n * .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId))\n */\n join<\n TSource extends Source,\n TJoinType extends `inner` | `left` | `right` | `full` = `left`,\n >(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n type: TJoinType = `left` as TJoinType,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, TJoinType>\n > {\n const [alias, from] = this._createRefForSource(source, `join clause`)\n\n // Create a temporary context for the callback\n const currentAliases = this._getCurrentAliases()\n const newAliases = [...currentAliases, alias]\n const refProxy = createRefProxy(newAliases) as RefsForContext<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >\n\n // Get the join condition expression\n const onExpression = onCallback(refProxy)\n\n // Extract left and right from the expression\n // For now, we'll assume it's an eq function with two arguments\n let left: BasicExpression\n let right: BasicExpression\n\n if (\n onExpression.type === `func` &&\n onExpression.name === `eq` &&\n onExpression.args.length === 2\n ) {\n left = onExpression.args[0]!\n right = onExpression.args[1]!\n } else {\n throw new JoinConditionMustBeEqualityError()\n }\n\n const joinClause: JoinClause = {\n from,\n type,\n left,\n right,\n }\n\n const existingJoins = this.query.join || []\n\n return new BaseQueryBuilder({\n ...this.query,\n join: [...existingJoins, joinClause],\n }) as any\n }\n\n /**\n * Perform a LEFT JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the left joined table available\n *\n * @example\n * ```ts\n * // Left join users with posts\n * query\n * .from({ users: usersCollection })\n * .leftJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n leftJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `left`>\n > {\n return this.join(source, onCallback, `left`)\n }\n\n /**\n * Perform a RIGHT JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the right joined table available\n *\n * @example\n * ```ts\n * // Right join users with posts\n * query\n * .from({ users: usersCollection })\n * .rightJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n rightJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `right`>\n > {\n return this.join(source, onCallback, `right`)\n }\n\n /**\n * Perform an INNER JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the inner joined table available\n *\n * @example\n * ```ts\n * // Inner join users with posts\n * query\n * .from({ users: usersCollection })\n * .innerJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n innerJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `inner`>\n > {\n return this.join(source, onCallback, `inner`)\n }\n\n /**\n * Perform a FULL JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the full joined table available\n *\n * @example\n * ```ts\n * // Full join users with posts\n * query\n * .from({ users: usersCollection })\n * .fullJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n fullJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `full`>\n > {\n return this.join(source, onCallback, `full`)\n }\n\n /**\n * Filter rows based on a condition\n *\n * @param callback - A function that receives table references and returns an expression\n * @returns A QueryBuilder with the where condition applied\n *\n * @example\n * ```ts\n * // Simple condition\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => gt(users.age, 18))\n *\n * // Multiple conditions\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => and(\n * gt(users.age, 18),\n * eq(users.active, true)\n * ))\n *\n * // Multiple where calls are ANDed together\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => gt(users.age, 18))\n * .where(({users}) => eq(users.active, true))\n * ```\n */\n where(callback: WhereCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const rawExpression = callback(refProxy)\n\n // Allow bare boolean column references like `.where(({ u }) => u.active)`\n // by converting ref proxies to PropRef expressions, the same way helper\n // functions like `not()` and `eq()` do via `toExpression()`.\n const expression = isRefProxy(rawExpression)\n ? toExpression(rawExpression)\n : rawExpression\n\n // Validate that the callback returned a valid expression\n // This catches common mistakes like using JavaScript comparison operators (===, !==, etc.)\n // which return boolean primitives instead of expression objects\n if (!isExpressionLike(expression)) {\n throw new InvalidWhereExpressionError(getValueTypeName(expression))\n }\n\n const existingWhere = this.query.where || []\n\n return new BaseQueryBuilder({\n ...this.query,\n where: [...existingWhere, expression],\n }) as any\n }\n\n /**\n * Filter grouped rows based on aggregate conditions\n *\n * @param callback - A function that receives table references and returns an expression\n * @returns A QueryBuilder with the having condition applied\n *\n * @example\n * ```ts\n * // Filter groups by count\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .having(({posts}) => gt(count(posts.id), 5))\n *\n * // Filter by average\n * query\n * .from({ orders: ordersCollection })\n * .groupBy(({orders}) => orders.customerId)\n * .having(({orders}) => gt(avg(orders.total), 100))\n *\n * // Multiple having calls are ANDed together\n * query\n * .from({ orders: ordersCollection })\n * .groupBy(({orders}) => orders.customerId)\n * .having(({orders}) => gt(count(orders.id), 5))\n * .having(({orders}) => gt(avg(orders.total), 100))\n * ```\n */\n having(callback: WhereCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n // Add $selected namespace if SELECT clause exists (either regular or functional)\n const refProxy = (\n this.query.select || this.query.fnSelect\n ? createRefProxyWithSelected(aliases)\n : createRefProxy(aliases)\n ) as RefsForContext<TContext>\n const rawExpression = callback(refProxy)\n\n // Allow bare boolean column references like `.having(({ $selected }) => $selected.isActive)`\n // by converting ref proxies to PropRef expressions, the same way helper\n // functions like `not()` and `eq()` do via `toExpression()`.\n const expression = isRefProxy(rawExpression)\n ? toExpression(rawExpression)\n : rawExpression\n\n // Validate that the callback returned a valid expression\n // This catches common mistakes like using JavaScript comparison operators (===, !==, etc.)\n // which return boolean primitives instead of expression objects\n if (!isExpressionLike(expression)) {\n throw new InvalidWhereExpressionError(getValueTypeName(expression))\n }\n\n const existingHaving = this.query.having || []\n\n return new BaseQueryBuilder({\n ...this.query,\n having: [...existingHaving, expression],\n }) as any\n }\n\n /**\n * Select specific columns or computed values from the query\n *\n * @param callback - A function that receives table references and returns an object with selected fields or expressions\n * @returns A QueryBuilder that returns only the selected fields\n *\n * @example\n * ```ts\n * // Select specific columns\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({\n * name: users.name,\n * email: users.email\n * }))\n *\n * // Select with computed values\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({\n * fullName: concat(users.firstName, ' ', users.lastName),\n * ageInMonths: mul(users.age, 12)\n * }))\n *\n * // Select with aggregates (requires GROUP BY)\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts, count}) => ({\n * userId: posts.userId,\n * postCount: count(posts.id)\n * }))\n * ```\n */\n select<TSelectObject extends SelectObject>(\n callback: (refs: RefsForContext<TContext>) => TSelectObject,\n ): QueryBuilder<WithResult<TContext, ResultTypeFromSelect<TSelectObject>>> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const selectObject = callback(refProxy)\n const select = buildNestedSelect(selectObject)\n\n return new BaseQueryBuilder({\n ...this.query,\n select: select,\n fnSelect: undefined, // remove the fnSelect clause if it exists\n }) as any\n }\n\n /**\n * Sort the query results by one or more columns\n *\n * @param callback - A function that receives table references and returns the field to sort by\n * @param direction - Sort direction: 'asc' for ascending, 'desc' for descending (defaults to 'asc')\n * @returns A QueryBuilder with the ordering applied\n *\n * @example\n * ```ts\n * // Sort by a single column\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.name)\n *\n * // Sort descending\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.createdAt, 'desc')\n *\n * // Multiple sorts (chain orderBy calls)\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.lastName)\n * .orderBy(({users}) => users.firstName)\n * ```\n */\n orderBy(\n callback: OrderByCallback<TContext>,\n options: OrderByDirection | OrderByOptions = `asc`,\n ): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n // Add $selected namespace if SELECT clause exists (either regular or functional)\n const refProxy = (\n this.query.select || this.query.fnSelect\n ? createRefProxyWithSelected(aliases)\n : createRefProxy(aliases)\n ) as RefsForContext<TContext>\n const result = callback(refProxy)\n\n const opts: CompareOptions =\n typeof options === `string`\n ? { direction: options, nulls: `first` }\n : {\n direction: options.direction ?? `asc`,\n nulls: options.nulls ?? `first`,\n stringSort: options.stringSort,\n locale:\n options.stringSort === `locale` ? options.locale : undefined,\n localeOptions:\n options.stringSort === `locale`\n ? options.localeOptions\n : undefined,\n }\n\n const makeOrderByClause = (res: any) => {\n return {\n expression: toExpression(res),\n compareOptions: opts,\n }\n }\n\n // Create the new OrderBy structure with expression and direction\n const orderByClauses = Array.isArray(result)\n ? result.map((r) => makeOrderByClause(r))\n : [makeOrderByClause(result)]\n\n const existingOrderBy: OrderBy = this.query.orderBy || []\n\n return new BaseQueryBuilder({\n ...this.query,\n orderBy: [...existingOrderBy, ...orderByClauses],\n }) as any\n }\n\n /**\n * Group rows by one or more columns for aggregation\n *\n * @param callback - A function that receives table references and returns the field(s) to group by\n * @returns A QueryBuilder with grouping applied (enables aggregate functions in SELECT and HAVING)\n *\n * @example\n * ```ts\n * // Group by a single column\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts, count}) => ({\n * userId: posts.userId,\n * postCount: count()\n * }))\n *\n * // Group by multiple columns\n * query\n * .from({ sales: salesCollection })\n * .groupBy(({sales}) => [sales.region, sales.category])\n * .select(({sales, sum}) => ({\n * region: sales.region,\n * category: sales.category,\n * totalSales: sum(sales.amount)\n * }))\n * ```\n */\n groupBy(callback: GroupByCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const result = callback(refProxy)\n\n const newExpressions = Array.isArray(result)\n ? result.map((r) => toExpression(r))\n : [toExpression(result)]\n\n // Extend existing groupBy expressions (multiple groupBy calls should accumulate)\n const existingGroupBy = this.query.groupBy || []\n return new BaseQueryBuilder({\n ...this.query,\n groupBy: [...existingGroupBy, ...newExpressions],\n }) as any\n }\n\n /**\n * Limit the number of rows returned by the query\n * `orderBy` is required for `limit`\n *\n * @param count - Maximum number of rows to return\n * @returns A QueryBuilder with the limit applied\n *\n * @example\n * ```ts\n * // Get top 5 posts by likes\n * query\n * .from({ posts: postsCollection })\n * .orderBy(({posts}) => posts.likes, 'desc')\n * .limit(5)\n * ```\n */\n limit(count: number): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n limit: count,\n }) as any\n }\n\n /**\n * Skip a number of rows before returning results\n * `orderBy` is required for `offset`\n *\n * @param count - Number of rows to skip\n * @returns A QueryBuilder with the offset applied\n *\n * @example\n * ```ts\n * // Get second page of results\n * query\n * .from({ posts: postsCollection })\n * .orderBy(({posts}) => posts.createdAt, 'desc')\n * .offset(page * pageSize)\n * .limit(pageSize)\n * ```\n */\n offset(count: number): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n offset: count,\n }) as any\n }\n\n /**\n * Specify that the query should return distinct rows.\n * Deduplicates rows based on the selected columns.\n * @returns A QueryBuilder with distinct enabled\n *\n * @example\n * ```ts\n * // Get countries our users are from\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => users.country)\n * .distinct()\n * ```\n */\n distinct(): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n distinct: true,\n }) as any\n }\n\n /**\n * Specify that the query should return a single result\n * @returns A QueryBuilder that returns the first result\n *\n * @example\n * ```ts\n * // Get the user matching the query\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => eq(users.id, 1))\n * .findOne()\n *```\n */\n findOne(): QueryBuilder<TContext & SingleResult> {\n return new BaseQueryBuilder({\n ...this.query,\n // TODO: enforcing return only one result with also a default orderBy if none is specified\n // limit: 1,\n singleResult: true,\n })\n }\n\n // Helper methods\n private _getCurrentAliases(): Array<string> {\n const aliases: Array<string> = []\n\n // Add the from alias\n if (this.query.from) {\n aliases.push(this.query.from.alias)\n }\n\n // Add join aliases\n if (this.query.join) {\n for (const join of this.query.join) {\n aliases.push(join.from.alias)\n }\n }\n\n return aliases\n }\n\n /**\n * Functional variants of the query builder\n * These are imperative function that are called for ery row.\n * Warning: that these cannot be optimized by the query compiler, and may prevent\n * some type of optimizations being possible.\n * @example\n * ```ts\n * q.fn.select((row) => ({\n * name: row.user.name.toUpperCase(),\n * age: row.user.age + 1,\n * }))\n * ```\n */\n get fn() {\n const builder = this\n return {\n /**\n * Select fields using a function that operates on each row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives a row and returns the selected value\n * @returns A QueryBuilder with functional selection applied\n *\n * @example\n * ```ts\n * // Functional select (not optimized)\n * query\n * .from({ users: usersCollection })\n * .fn.select(row => ({\n * name: row.users.name.toUpperCase(),\n * age: row.users.age + 1,\n * }))\n * ```\n */\n select<TFuncSelectResult>(\n callback: (row: TContext[`schema`]) => TFuncSelectResult,\n ): QueryBuilder<WithResult<TContext, TFuncSelectResult>> {\n return new BaseQueryBuilder({\n ...builder.query,\n select: undefined, // remove the select clause if it exists\n fnSelect: callback,\n })\n },\n /**\n * Filter rows using a function that operates on each row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives a row and returns a boolean\n * @returns A QueryBuilder with functional filtering applied\n *\n * @example\n * ```ts\n * // Functional where (not optimized)\n * query\n * .from({ users: usersCollection })\n * .fn.where(row => row.users.name.startsWith('A'))\n * ```\n */\n where(\n callback: (row: TContext[`schema`]) => any,\n ): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...builder.query,\n fnWhere: [\n ...(builder.query.fnWhere || []),\n callback as (row: NamespacedRow) => any,\n ],\n })\n },\n /**\n * Filter grouped rows using a function that operates on each aggregated row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives an aggregated row (with $selected when select() was called) and returns a boolean\n * @returns A QueryBuilder with functional having filter applied\n *\n * @example\n * ```ts\n * // Functional having (not optimized)\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts}) => ({ userId: posts.userId, count: count(posts.id) }))\n * .fn.having(({ $selected }) => $selected.count > 5)\n * ```\n */\n having(\n callback: (row: FunctionalHavingRow<TContext>) => any,\n ): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...builder.query,\n fnHaving: [\n ...(builder.query.fnHaving || []),\n callback as (row: NamespacedRow) => any,\n ],\n })\n },\n }\n }\n\n _getQuery(): QueryIR {\n if (!this.query.from) {\n throw new QueryMustHaveFromClauseError()\n }\n return this.query as QueryIR\n }\n}\n\n// Helper to get a descriptive type name for error messages\nfunction getValueTypeName(value: unknown): string {\n if (value === null) return `null`\n if (value === undefined) return `undefined`\n if (typeof value === `object`) return `object`\n return typeof value\n}\n\n// Helper to ensure we have a BasicExpression/Aggregate for a value\nfunction toExpr(value: any): BasicExpression | Aggregate {\n if (value === undefined) return toExpression(null)\n if (\n value instanceof AggregateExpr ||\n value instanceof FuncExpr ||\n value instanceof PropRef ||\n value instanceof ValueExpr\n ) {\n return value as BasicExpression | Aggregate\n }\n return toExpression(value)\n}\n\nfunction isPlainObject(value: any): value is Record<string, any> {\n return (\n value !== null &&\n typeof value === `object` &&\n !isExpressionLike(value) &&\n !value.__refProxy\n )\n}\n\nfunction buildNestedSelect(obj: any): any {\n if (!isPlainObject(obj)) return toExpr(obj)\n const out: Record<string, any> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (typeof k === `string` && k.startsWith(`__SPREAD_SENTINEL__`)) {\n // Preserve sentinel key and its value (value is unimportant at compile time)\n out[k] = v\n continue\n }\n out[k] = buildNestedSelect(v)\n }\n return out\n}\n\n// Internal function to build a query from a callback\n// used by liveQueryCollectionOptions.query\nexport function buildQuery<TContext extends Context>(\n fn: (builder: InitialQueryBuilder) => QueryBuilder<TContext>,\n): QueryIR {\n const result = fn(new BaseQueryBuilder())\n return getQueryIR(result)\n}\n\n// Internal function to get the QueryIR from a builder\nexport function getQueryIR(\n builder: BaseQueryBuilder | QueryBuilder<any> | InitialQueryBuilder,\n): QueryIR {\n return (builder as unknown as BaseQueryBuilder)._getQuery()\n}\n\n// Type-only exports for the query builder\nexport type InitialQueryBuilder = Pick<BaseQueryBuilder<Context>, `from`>\n\nexport type InitialQueryBuilderConstructor = new () => InitialQueryBuilder\n\nexport type QueryBuilder<TContext extends Context> = Omit<\n BaseQueryBuilder<TContext>,\n `from` | `_getQuery`\n>\n\n// Main query builder class alias with the constructor type modified to hide all\n// but the from method on the initial instance\nexport const Query: InitialQueryBuilderConstructor = BaseQueryBuilder\n\n// Helper type to extract context from a QueryBuilder\nexport type ExtractContext<T> =\n T extends BaseQueryBuilder<infer TContext>\n ? TContext\n : T extends QueryBuilder<infer TContext>\n ? TContext\n : never\n\n// Helper type to extract the result type from a QueryBuilder (similar to Zod's z.infer)\nexport type QueryResult<T> = GetResult<ExtractContext<T>>\n\n// Export the types from types.ts for convenience\nexport type {\n Context,\n ContextSchema,\n Source,\n GetResult,\n RefLeaf as Ref,\n InferResultType,\n // Types used in public method signatures that must be exported\n // for declaration emit to work (see https://github.com/TanStack/db/issues/1012)\n SchemaFromSource,\n InferCollectionType,\n MergeContextWithJoinType,\n MergeContextForJoinCallback,\n ApplyJoinOptionalityToMergedSchema,\n ResultTypeFromSelect,\n WithResult,\n JoinOnCallback,\n RefsForContext,\n WhereCallback,\n OrderByCallback,\n GroupByCallback,\n SelectObject,\n FunctionalHavingRow,\n Prettify,\n} from './types.js'\n"],"names":["InvalidSourceTypeError","OnlyOneSourceAllowedError","CollectionImpl","CollectionRef","SubQueryMustHaveFromClauseError","QueryRef","InvalidSourceError","refProxy","createRefProxy","JoinConditionMustBeEqualityError","isRefProxy","toExpression","isExpressionLike","InvalidWhereExpressionError","createRefProxyWithSelected","QueryMustHaveFromClauseError","AggregateExpr","FuncExpr","PropRef","ValueExpr"],"mappings":";;;;;;AAsDO,MAAM,iBAAqD;AAAA,EAGhE,YAAY,QAA0B,IAAI;AAF1C,SAAiB,QAA0B,CAAA;AAGzC,SAAK,QAAQ,EAAE,GAAG,MAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,oBACN,QACA,SACoC;AAGpC,QAAI;AACJ,QAAI;AACF,aAAO,OAAO,KAAK,MAAM;AAAA,IAC3B,QAAQ;AAEN,YAAM,OAAO,WAAW,OAAO,SAAS;AACxC,YAAM,IAAIA,OAAAA,uBAAuB,SAAS,IAAI;AAAA,IAChD;AAGA,QAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,YAAM,IAAIA,OAAAA,uBAAuB,SAAS,OAAO;AAAA,IACnD;AAGA,QAAI,KAAK,WAAW,GAAG;AACrB,UAAI,KAAK,WAAW,GAAG;AACrB,cAAM,IAAIA,OAAAA,uBAAuB,SAAS,cAAc;AAAA,MAC1D;AAEA,UAAI,KAAK,MAAM,CAAC,MAAM,CAAC,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG;AACxC,cAAM,IAAIA,OAAAA,uBAAuB,SAAS,QAAQ;AAAA,MACpD;AACA,YAAM,IAAIC,OAAAA,0BAA0B,OAAO;AAAA,IAC7C;AAEA,UAAM,QAAQ,KAAK,CAAC;AACpB,UAAM,cAAc,OAAO,KAAK;AAGhC,QAAI;AAEJ,QAAI,uBAAuBC,MAAAA,gBAAgB;AACzC,YAAM,IAAIC,GAAAA,cAAc,aAAa,KAAK;AAAA,IAC5C,WAAW,uBAA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M,YAAY,EAAE,WAAW,qBAAqB,GAAG;AAEhE,UAAI,CAAC,IAAI;AACT;AAAA,IACF;AACA,QAAI,CAAC,IAAI,kBAAkB,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;AAIO,SAAS,WACd,IACS;AACT,QAAM,SAAS,GAAG,IAAI,kBAAkB;AACxC,SAAO,WAAW,MAAM;AAC1B;AAGO,SAAS,WACd,SACS;AACT,SAAQ,QAAwC,UAAA;AAClD;AAcO,MAAM,QAAwC;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../../../../src/query/builder/index.ts"],"sourcesContent":["import { CollectionImpl } from '../../collection/index.js'\nimport {\n Aggregate as AggregateExpr,\n CollectionRef,\n Func as FuncExpr,\n INCLUDES_SCALAR_FIELD,\n IncludesSubquery,\n PropRef,\n QueryRef,\n Value as ValueExpr,\n isExpressionLike,\n} from '../ir.js'\nimport {\n InvalidSourceError,\n InvalidSourceTypeError,\n InvalidWhereExpressionError,\n JoinConditionMustBeEqualityError,\n OnlyOneSourceAllowedError,\n QueryMustHaveFromClauseError,\n SubQueryMustHaveFromClauseError,\n} from '../../errors.js'\nimport {\n createRefProxy,\n createRefProxyWithSelected,\n isRefProxy,\n toExpression,\n} from './ref-proxy.js'\nimport { ConcatToArrayWrapper, ToArrayWrapper } from './functions.js'\nimport type { NamespacedRow, SingleResult } from '../../types.js'\nimport type {\n Aggregate,\n BasicExpression,\n IncludesMaterialization,\n JoinClause,\n OrderBy,\n OrderByDirection,\n QueryIR,\n Where,\n} from '../ir.js'\nimport type {\n CompareOptions,\n Context,\n FunctionalHavingRow,\n GetResult,\n GroupByCallback,\n JoinOnCallback,\n MergeContextForJoinCallback,\n MergeContextWithJoinType,\n NonScalarSelectObject,\n OrderByCallback,\n OrderByOptions,\n RefsForContext,\n ResultTypeFromSelect,\n ResultTypeFromSelectValue,\n ScalarSelectValue,\n SchemaFromSource,\n SelectObject,\n Source,\n WhereCallback,\n WithResult,\n} from './types.js'\n\nexport class BaseQueryBuilder<TContext extends Context = Context> {\n private readonly query: Partial<QueryIR> = {}\n\n constructor(query: Partial<QueryIR> = {}) {\n this.query = { ...query }\n }\n\n /**\n * Creates a CollectionRef or QueryRef from a source object\n * @param source - An object with a single key-value pair\n * @param context - Context string for error messages (e.g., \"from clause\", \"join clause\")\n * @returns A tuple of [alias, ref] where alias is the source key and ref is the created reference\n */\n private _createRefForSource<TSource extends Source>(\n source: TSource,\n context: string,\n ): [string, CollectionRef | QueryRef] {\n // Validate source is a plain object (not null, array, string, etc.)\n // We use try-catch to handle null/undefined gracefully\n let keys: Array<string>\n try {\n keys = Object.keys(source)\n } catch {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const type = source === null ? `null` : `undefined`\n throw new InvalidSourceTypeError(context, type)\n }\n\n // Check if it's an array (arrays pass Object.keys but aren't valid sources)\n if (Array.isArray(source)) {\n throw new InvalidSourceTypeError(context, `array`)\n }\n\n // Validate exactly one key\n if (keys.length !== 1) {\n if (keys.length === 0) {\n throw new InvalidSourceTypeError(context, `empty object`)\n }\n // Check if it looks like a string was passed (has numeric keys)\n if (keys.every((k) => !isNaN(Number(k)))) {\n throw new InvalidSourceTypeError(context, `string`)\n }\n throw new OnlyOneSourceAllowedError(context)\n }\n\n const alias = keys[0]!\n const sourceValue = source[alias]\n\n // Validate the value is a Collection or QueryBuilder\n let ref: CollectionRef | QueryRef\n\n if (sourceValue instanceof CollectionImpl) {\n ref = new CollectionRef(sourceValue, alias)\n } else if (sourceValue instanceof BaseQueryBuilder) {\n const subQuery = sourceValue._getQuery()\n if (!(subQuery as Partial<QueryIR>).from) {\n throw new SubQueryMustHaveFromClauseError(context)\n }\n ref = new QueryRef(subQuery, alias)\n } else {\n throw new InvalidSourceError(alias)\n }\n\n return [alias, ref]\n }\n\n /**\n * Specify the source table or subquery for the query\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @returns A QueryBuilder with the specified source\n *\n * @example\n * ```ts\n * // Query from a collection\n * query.from({ users: usersCollection })\n *\n * // Query from a subquery\n * const activeUsers = query.from({ u: usersCollection }).where(({u}) => u.active)\n * query.from({ activeUsers })\n * ```\n */\n from<TSource extends Source>(\n source: TSource,\n ): QueryBuilder<{\n baseSchema: SchemaFromSource<TSource>\n schema: SchemaFromSource<TSource>\n fromSourceName: keyof TSource & string\n hasJoins: false\n }> {\n const [, from] = this._createRefForSource(source, `from clause`)\n\n return new BaseQueryBuilder({\n ...this.query,\n from,\n }) as any\n }\n\n /**\n * Join another table or subquery to the current query\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @param type - The type of join: 'inner', 'left', 'right', or 'full' (defaults to 'left')\n * @returns A QueryBuilder with the joined table available\n *\n * @example\n * ```ts\n * // Left join users with posts\n * query\n * .from({ users: usersCollection })\n * .join({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n *\n * // Inner join with explicit type\n * query\n * .from({ u: usersCollection })\n * .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId), 'inner')\n * ```\n *\n * // Join with a subquery\n * const activeUsers = query.from({ u: usersCollection }).where(({u}) => u.active)\n * query\n * .from({ activeUsers })\n * .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId))\n */\n join<\n TSource extends Source,\n TJoinType extends `inner` | `left` | `right` | `full` = `left`,\n >(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n type: TJoinType = `left` as TJoinType,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, TJoinType>\n > {\n const [alias, from] = this._createRefForSource(source, `join clause`)\n\n // Create a temporary context for the callback\n const currentAliases = this._getCurrentAliases()\n const newAliases = [...currentAliases, alias]\n const refProxy = createRefProxy(newAliases) as RefsForContext<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >\n\n // Get the join condition expression\n const onExpression = onCallback(refProxy)\n\n // Extract left and right from the expression\n // For now, we'll assume it's an eq function with two arguments\n let left: BasicExpression\n let right: BasicExpression\n\n if (\n onExpression.type === `func` &&\n onExpression.name === `eq` &&\n onExpression.args.length === 2\n ) {\n left = onExpression.args[0]!\n right = onExpression.args[1]!\n } else {\n throw new JoinConditionMustBeEqualityError()\n }\n\n const joinClause: JoinClause = {\n from,\n type,\n left,\n right,\n }\n\n const existingJoins = this.query.join || []\n\n return new BaseQueryBuilder({\n ...this.query,\n join: [...existingJoins, joinClause],\n }) as any\n }\n\n /**\n * Perform a LEFT JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the left joined table available\n *\n * @example\n * ```ts\n * // Left join users with posts\n * query\n * .from({ users: usersCollection })\n * .leftJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n leftJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `left`>\n > {\n return this.join(source, onCallback, `left`)\n }\n\n /**\n * Perform a RIGHT JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the right joined table available\n *\n * @example\n * ```ts\n * // Right join users with posts\n * query\n * .from({ users: usersCollection })\n * .rightJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n rightJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `right`>\n > {\n return this.join(source, onCallback, `right`)\n }\n\n /**\n * Perform an INNER JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the inner joined table available\n *\n * @example\n * ```ts\n * // Inner join users with posts\n * query\n * .from({ users: usersCollection })\n * .innerJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n innerJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `inner`>\n > {\n return this.join(source, onCallback, `inner`)\n }\n\n /**\n * Perform a FULL JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the full joined table available\n *\n * @example\n * ```ts\n * // Full join users with posts\n * query\n * .from({ users: usersCollection })\n * .fullJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n fullJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `full`>\n > {\n return this.join(source, onCallback, `full`)\n }\n\n /**\n * Filter rows based on a condition\n *\n * @param callback - A function that receives table references and returns an expression\n * @returns A QueryBuilder with the where condition applied\n *\n * @example\n * ```ts\n * // Simple condition\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => gt(users.age, 18))\n *\n * // Multiple conditions\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => and(\n * gt(users.age, 18),\n * eq(users.active, true)\n * ))\n *\n * // Multiple where calls are ANDed together\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => gt(users.age, 18))\n * .where(({users}) => eq(users.active, true))\n * ```\n */\n where(callback: WhereCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const rawExpression = callback(refProxy)\n\n // Allow bare boolean column references like `.where(({ u }) => u.active)`\n // by converting ref proxies to PropRef expressions, the same way helper\n // functions like `not()` and `eq()` do via `toExpression()`.\n const expression = isRefProxy(rawExpression)\n ? toExpression(rawExpression)\n : rawExpression\n\n // Validate that the callback returned a valid expression\n // This catches common mistakes like using JavaScript comparison operators (===, !==, etc.)\n // which return boolean primitives instead of expression objects\n if (!isExpressionLike(expression)) {\n throw new InvalidWhereExpressionError(getValueTypeName(expression))\n }\n\n const existingWhere = this.query.where || []\n\n return new BaseQueryBuilder({\n ...this.query,\n where: [...existingWhere, expression],\n }) as any\n }\n\n /**\n * Filter grouped rows based on aggregate conditions\n *\n * @param callback - A function that receives table references and returns an expression\n * @returns A QueryBuilder with the having condition applied\n *\n * @example\n * ```ts\n * // Filter groups by count\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .having(({posts}) => gt(count(posts.id), 5))\n *\n * // Filter by average\n * query\n * .from({ orders: ordersCollection })\n * .groupBy(({orders}) => orders.customerId)\n * .having(({orders}) => gt(avg(orders.total), 100))\n *\n * // Multiple having calls are ANDed together\n * query\n * .from({ orders: ordersCollection })\n * .groupBy(({orders}) => orders.customerId)\n * .having(({orders}) => gt(count(orders.id), 5))\n * .having(({orders}) => gt(avg(orders.total), 100))\n * ```\n */\n having(callback: WhereCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n // Add $selected namespace if SELECT clause exists (either regular or functional)\n const refProxy = (\n this.query.select || this.query.fnSelect\n ? createRefProxyWithSelected(aliases)\n : createRefProxy(aliases)\n ) as RefsForContext<TContext>\n const rawExpression = callback(refProxy)\n\n // Allow bare boolean column references like `.having(({ $selected }) => $selected.isActive)`\n // by converting ref proxies to PropRef expressions, the same way helper\n // functions like `not()` and `eq()` do via `toExpression()`.\n const expression = isRefProxy(rawExpression)\n ? toExpression(rawExpression)\n : rawExpression\n\n // Validate that the callback returned a valid expression\n // This catches common mistakes like using JavaScript comparison operators (===, !==, etc.)\n // which return boolean primitives instead of expression objects\n if (!isExpressionLike(expression)) {\n throw new InvalidWhereExpressionError(getValueTypeName(expression))\n }\n\n const existingHaving = this.query.having || []\n\n return new BaseQueryBuilder({\n ...this.query,\n having: [...existingHaving, expression],\n }) as any\n }\n\n /**\n * Select specific columns or computed values from the query\n *\n * @param callback - A function that receives table references and returns an object with selected fields or expressions\n * @returns A QueryBuilder that returns only the selected fields\n *\n * @example\n * ```ts\n * // Select specific columns\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({\n * name: users.name,\n * email: users.email\n * }))\n *\n * // Select with computed values\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({\n * fullName: concat(users.firstName, ' ', users.lastName),\n * ageInMonths: mul(users.age, 12)\n * }))\n *\n * // Select with aggregates (requires GROUP BY)\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts, count}) => ({\n * userId: posts.userId,\n * postCount: count(posts.id)\n * }))\n * ```\n */\n select<TSelectObject extends SelectObject>(\n callback: (\n refs: RefsForContext<TContext>,\n ) => NonScalarSelectObject<TSelectObject>,\n ): QueryBuilder<WithResult<TContext, ResultTypeFromSelect<TSelectObject>>>\n select<TSelectValue extends ScalarSelectValue>(\n callback: (refs: RefsForContext<TContext>) => TSelectValue,\n ): QueryBuilder<WithResult<TContext, ResultTypeFromSelectValue<TSelectValue>>>\n select(\n callback: (\n refs: RefsForContext<TContext>,\n ) => SelectObject | ScalarSelectValue,\n ) {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n let selectObject = callback(refProxy)\n\n // Returning a top-level alias directly is equivalent to spreading it.\n // Leaf refs like `row.name` must remain scalar selections.\n if (isRefProxy(selectObject) && selectObject.__path.length === 1) {\n const sentinelKey = `__SPREAD_SENTINEL__${selectObject.__path[0]}__0`\n selectObject = { [sentinelKey]: true }\n }\n\n const select = buildNestedSelect(selectObject, aliases)\n\n return new BaseQueryBuilder({\n ...this.query,\n select: select,\n fnSelect: undefined, // remove the fnSelect clause if it exists\n }) as any\n }\n\n /**\n * Sort the query results by one or more columns\n *\n * @param callback - A function that receives table references and returns the field to sort by\n * @param direction - Sort direction: 'asc' for ascending, 'desc' for descending (defaults to 'asc')\n * @returns A QueryBuilder with the ordering applied\n *\n * @example\n * ```ts\n * // Sort by a single column\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.name)\n *\n * // Sort descending\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.createdAt, 'desc')\n *\n * // Multiple sorts (chain orderBy calls)\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.lastName)\n * .orderBy(({users}) => users.firstName)\n * ```\n */\n orderBy(\n callback: OrderByCallback<TContext>,\n options: OrderByDirection | OrderByOptions = `asc`,\n ): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n // Add $selected namespace if SELECT clause exists (either regular or functional)\n const refProxy = (\n this.query.select || this.query.fnSelect\n ? createRefProxyWithSelected(aliases)\n : createRefProxy(aliases)\n ) as RefsForContext<TContext>\n const result = callback(refProxy)\n\n const opts: CompareOptions =\n typeof options === `string`\n ? { direction: options, nulls: `first` }\n : {\n direction: options.direction ?? `asc`,\n nulls: options.nulls ?? `first`,\n stringSort: options.stringSort,\n locale:\n options.stringSort === `locale` ? options.locale : undefined,\n localeOptions:\n options.stringSort === `locale`\n ? options.localeOptions\n : undefined,\n }\n\n const makeOrderByClause = (res: any) => {\n return {\n expression: toExpression(res),\n compareOptions: opts,\n }\n }\n\n // Create the new OrderBy structure with expression and direction\n const orderByClauses = Array.isArray(result)\n ? result.map((r) => makeOrderByClause(r))\n : [makeOrderByClause(result)]\n\n const existingOrderBy: OrderBy = this.query.orderBy || []\n\n return new BaseQueryBuilder({\n ...this.query,\n orderBy: [...existingOrderBy, ...orderByClauses],\n }) as any\n }\n\n /**\n * Group rows by one or more columns for aggregation\n *\n * @param callback - A function that receives table references and returns the field(s) to group by\n * @returns A QueryBuilder with grouping applied (enables aggregate functions in SELECT and HAVING)\n *\n * @example\n * ```ts\n * // Group by a single column\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts, count}) => ({\n * userId: posts.userId,\n * postCount: count()\n * }))\n *\n * // Group by multiple columns\n * query\n * .from({ sales: salesCollection })\n * .groupBy(({sales}) => [sales.region, sales.category])\n * .select(({sales, sum}) => ({\n * region: sales.region,\n * category: sales.category,\n * totalSales: sum(sales.amount)\n * }))\n * ```\n */\n groupBy(callback: GroupByCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const result = callback(refProxy)\n\n const newExpressions = Array.isArray(result)\n ? result.map((r) => toExpression(r))\n : [toExpression(result)]\n\n // Extend existing groupBy expressions (multiple groupBy calls should accumulate)\n const existingGroupBy = this.query.groupBy || []\n return new BaseQueryBuilder({\n ...this.query,\n groupBy: [...existingGroupBy, ...newExpressions],\n }) as any\n }\n\n /**\n * Limit the number of rows returned by the query\n * `orderBy` is required for `limit`\n *\n * @param count - Maximum number of rows to return\n * @returns A QueryBuilder with the limit applied\n *\n * @example\n * ```ts\n * // Get top 5 posts by likes\n * query\n * .from({ posts: postsCollection })\n * .orderBy(({posts}) => posts.likes, 'desc')\n * .limit(5)\n * ```\n */\n limit(count: number): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n limit: count,\n }) as any\n }\n\n /**\n * Skip a number of rows before returning results\n * `orderBy` is required for `offset`\n *\n * @param count - Number of rows to skip\n * @returns A QueryBuilder with the offset applied\n *\n * @example\n * ```ts\n * // Get second page of results\n * query\n * .from({ posts: postsCollection })\n * .orderBy(({posts}) => posts.createdAt, 'desc')\n * .offset(page * pageSize)\n * .limit(pageSize)\n * ```\n */\n offset(count: number): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n offset: count,\n }) as any\n }\n\n /**\n * Specify that the query should return distinct rows.\n * Deduplicates rows based on the selected columns.\n * @returns A QueryBuilder with distinct enabled\n *\n * @example\n * ```ts\n * // Get countries our users are from\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({ country: users.country }))\n * .distinct()\n * ```\n */\n distinct(): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n distinct: true,\n }) as any\n }\n\n /**\n * Specify that the query should return a single result\n * @returns A QueryBuilder that returns the first result\n *\n * @example\n * ```ts\n * // Get the user matching the query\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => eq(users.id, 1))\n * .findOne()\n *```\n */\n findOne(): QueryBuilder<TContext & SingleResult> {\n return new BaseQueryBuilder({\n ...this.query,\n // TODO: enforcing return only one result with also a default orderBy if none is specified\n // limit: 1,\n singleResult: true,\n }) as any\n }\n\n // Helper methods\n private _getCurrentAliases(): Array<string> {\n const aliases: Array<string> = []\n\n // Add the from alias\n if (this.query.from) {\n aliases.push(this.query.from.alias)\n }\n\n // Add join aliases\n if (this.query.join) {\n for (const join of this.query.join) {\n aliases.push(join.from.alias)\n }\n }\n\n return aliases\n }\n\n /**\n * Functional variants of the query builder\n * These are imperative function that are called for ery row.\n * Warning: that these cannot be optimized by the query compiler, and may prevent\n * some type of optimizations being possible.\n * @example\n * ```ts\n * q.fn.select((row) => ({\n * name: row.user.name.toUpperCase(),\n * age: row.user.age + 1,\n * }))\n * ```\n */\n get fn() {\n const builder = this\n return {\n /**\n * Select fields using a function that operates on each row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives a row and returns the selected value\n * @returns A QueryBuilder with functional selection applied\n *\n * @example\n * ```ts\n * // Functional select (not optimized)\n * query\n * .from({ users: usersCollection })\n * .fn.select(row => ({\n * name: row.users.name.toUpperCase(),\n * age: row.users.age + 1,\n * }))\n * ```\n */\n select<TFuncSelectResult>(\n callback: (row: TContext[`schema`]) => TFuncSelectResult,\n ): QueryBuilder<WithResult<TContext, TFuncSelectResult>> {\n return new BaseQueryBuilder({\n ...builder.query,\n select: undefined, // remove the select clause if it exists\n fnSelect: callback,\n }) as any\n },\n /**\n * Filter rows using a function that operates on each row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives a row and returns a boolean\n * @returns A QueryBuilder with functional filtering applied\n *\n * @example\n * ```ts\n * // Functional where (not optimized)\n * query\n * .from({ users: usersCollection })\n * .fn.where(row => row.users.name.startsWith('A'))\n * ```\n */\n where(\n callback: (row: TContext[`schema`]) => any,\n ): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...builder.query,\n fnWhere: [\n ...(builder.query.fnWhere || []),\n callback as (row: NamespacedRow) => any,\n ],\n })\n },\n /**\n * Filter grouped rows using a function that operates on each aggregated row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives an aggregated row (with $selected when select() was called) and returns a boolean\n * @returns A QueryBuilder with functional having filter applied\n *\n * @example\n * ```ts\n * // Functional having (not optimized)\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts}) => ({ userId: posts.userId, count: count(posts.id) }))\n * .fn.having(({ $selected }) => $selected.count > 5)\n * ```\n */\n having(\n callback: (row: FunctionalHavingRow<TContext>) => any,\n ): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...builder.query,\n fnHaving: [\n ...(builder.query.fnHaving || []),\n callback as (row: NamespacedRow) => any,\n ],\n })\n },\n }\n }\n\n _getQuery(): QueryIR {\n if (!this.query.from) {\n throw new QueryMustHaveFromClauseError()\n }\n return this.query as QueryIR\n }\n}\n\n// Helper to get a descriptive type name for error messages\nfunction getValueTypeName(value: unknown): string {\n if (value === null) return `null`\n if (value === undefined) return `undefined`\n if (typeof value === `object`) return `object`\n return typeof value\n}\n\n// Helper to ensure we have a BasicExpression/Aggregate for a value\nfunction toExpr(value: any): BasicExpression | Aggregate {\n if (value === undefined) return toExpression(null)\n if (\n value instanceof AggregateExpr ||\n value instanceof FuncExpr ||\n value instanceof PropRef ||\n value instanceof ValueExpr\n ) {\n return value as BasicExpression | Aggregate\n }\n return toExpression(value)\n}\n\nfunction isPlainObject(value: any): value is Record<string, any> {\n return (\n value !== null &&\n typeof value === `object` &&\n !isExpressionLike(value) &&\n !value.__refProxy\n )\n}\n\nfunction buildNestedSelect(obj: any, parentAliases: Array<string> = []): any {\n if (!isPlainObject(obj)) return toExpr(obj)\n const out: Record<string, any> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (typeof k === `string` && k.startsWith(`__SPREAD_SENTINEL__`)) {\n // Preserve sentinel key and its value (value is unimportant at compile time)\n out[k] = v\n continue\n }\n if (v instanceof BaseQueryBuilder) {\n out[k] = buildIncludesSubquery(v, k, parentAliases, `collection`)\n continue\n }\n if (v instanceof ToArrayWrapper) {\n if (!(v.query instanceof BaseQueryBuilder)) {\n throw new Error(`toArray() must wrap a subquery builder`)\n }\n out[k] = buildIncludesSubquery(v.query, k, parentAliases, `array`)\n continue\n }\n if (v instanceof ConcatToArrayWrapper) {\n if (!(v.query instanceof BaseQueryBuilder)) {\n throw new Error(`concat(toArray(...)) must wrap a subquery builder`)\n }\n out[k] = buildIncludesSubquery(v.query, k, parentAliases, `concat`)\n continue\n }\n out[k] = buildNestedSelect(v, parentAliases)\n }\n return out\n}\n\n/**\n * Recursively collects all PropRef nodes from an expression tree.\n */\nfunction collectRefsFromExpression(expr: BasicExpression): Array<PropRef> {\n const refs: Array<PropRef> = []\n switch (expr.type) {\n case `ref`:\n refs.push(expr)\n break\n case `func`:\n for (const arg of (expr as any).args ?? []) {\n refs.push(...collectRefsFromExpression(arg))\n }\n break\n default:\n break\n }\n return refs\n}\n\n/**\n * Checks whether a WHERE clause references any parent alias.\n */\nfunction referencesParent(where: Where, parentAliases: Array<string>): boolean {\n const expr =\n typeof where === `object` && `expression` in where\n ? where.expression\n : where\n return collectRefsFromExpression(expr).some(\n (ref) => ref.path[0] != null && parentAliases.includes(ref.path[0]),\n )\n}\n\n/**\n * Builds an IncludesSubquery IR node from a child query builder.\n * Extracts the correlation condition from the child's WHERE clauses by finding\n * an eq() predicate that references both a parent alias and a child alias.\n */\nfunction buildIncludesSubquery(\n childBuilder: BaseQueryBuilder,\n fieldName: string,\n parentAliases: Array<string>,\n materialization: IncludesMaterialization,\n): IncludesSubquery {\n const childQuery = childBuilder._getQuery()\n\n // Collect child's own aliases\n const childAliases: Array<string> = [childQuery.from.alias]\n if (childQuery.join) {\n for (const j of childQuery.join) {\n childAliases.push(j.from.alias)\n }\n }\n\n // Walk child's WHERE clauses to find the correlation condition.\n // The correlation eq() may be a standalone WHERE or nested inside a top-level and().\n let parentRef: PropRef | undefined\n let childRef: PropRef | undefined\n let correlationWhereIndex = -1\n let correlationAndArgIndex = -1 // >= 0 when found inside an and()\n\n if (childQuery.where) {\n for (let i = 0; i < childQuery.where.length; i++) {\n const where = childQuery.where[i]!\n const expr =\n typeof where === `object` && `expression` in where\n ? where.expression\n : where\n\n // Try standalone eq()\n if (\n expr.type === `func` &&\n expr.name === `eq` &&\n expr.args.length === 2\n ) {\n const result = extractCorrelation(\n expr.args[0]!,\n expr.args[1]!,\n parentAliases,\n childAliases,\n )\n if (result) {\n parentRef = result.parentRef\n childRef = result.childRef\n correlationWhereIndex = i\n break\n }\n }\n\n // Try inside top-level and()\n if (\n expr.type === `func` &&\n expr.name === `and` &&\n expr.args.length >= 2\n ) {\n for (let j = 0; j < expr.args.length; j++) {\n const arg = expr.args[j]!\n if (\n arg.type === `func` &&\n arg.name === `eq` &&\n arg.args.length === 2\n ) {\n const result = extractCorrelation(\n arg.args[0]!,\n arg.args[1]!,\n parentAliases,\n childAliases,\n )\n if (result) {\n parentRef = result.parentRef\n childRef = result.childRef\n correlationWhereIndex = i\n correlationAndArgIndex = j\n break\n }\n }\n }\n if (parentRef) break\n }\n }\n }\n\n if (!parentRef || !childRef || correlationWhereIndex === -1) {\n throw new Error(\n `Includes subquery for \"${fieldName}\" must have a WHERE clause with an eq() condition ` +\n `that correlates a parent field with a child field. ` +\n `Example: .where(({child}) => eq(child.parentId, parent.id))`,\n )\n }\n\n // Remove the correlation eq() from the child query's WHERE clauses.\n // If it was inside an and(), remove just that arg (collapsing the and() if needed).\n const modifiedWhere = [...childQuery.where!]\n if (correlationAndArgIndex >= 0) {\n const where = modifiedWhere[correlationWhereIndex]!\n const expr =\n typeof where === `object` && `expression` in where\n ? where.expression\n : where\n const remainingArgs = (expr as any).args.filter(\n (_: any, idx: number) => idx !== correlationAndArgIndex,\n )\n if (remainingArgs.length === 1) {\n // Collapse and() with single remaining arg to just that expression\n const isResidual =\n typeof where === `object` && `expression` in where && where.residual\n modifiedWhere[correlationWhereIndex] = isResidual\n ? { expression: remainingArgs[0], residual: true }\n : remainingArgs[0]\n } else {\n // Rebuild and() without the extracted arg\n const newAnd = new FuncExpr(`and`, remainingArgs)\n const isResidual =\n typeof where === `object` && `expression` in where && where.residual\n modifiedWhere[correlationWhereIndex] = isResidual\n ? { expression: newAnd, residual: true }\n : newAnd\n }\n } else {\n modifiedWhere.splice(correlationWhereIndex, 1)\n }\n\n // Separate remaining WHEREs into pure-child vs parent-referencing\n const pureChildWhere: Array<Where> = []\n const parentFilters: Array<Where> = []\n for (const w of modifiedWhere) {\n if (referencesParent(w, parentAliases)) {\n parentFilters.push(w)\n } else {\n pureChildWhere.push(w)\n }\n }\n\n // Collect distinct parent PropRefs from parent-referencing filters\n let parentProjection: Array<PropRef> | undefined\n if (parentFilters.length > 0) {\n const seen = new Set<string>()\n parentProjection = []\n for (const w of parentFilters) {\n const expr = typeof w === `object` && `expression` in w ? w.expression : w\n for (const ref of collectRefsFromExpression(expr)) {\n if (\n ref.path[0] != null &&\n parentAliases.includes(ref.path[0]) &&\n !seen.has(ref.path.join(`.`))\n ) {\n seen.add(ref.path.join(`.`))\n parentProjection.push(ref)\n }\n }\n }\n }\n\n const modifiedQuery: QueryIR = {\n ...childQuery,\n where: pureChildWhere.length > 0 ? pureChildWhere : undefined,\n }\n\n const rawChildSelect = modifiedQuery.select as any\n const hasObjectSelect =\n rawChildSelect === undefined || isPlainObject(rawChildSelect)\n let includesQuery = modifiedQuery\n let scalarField: string | undefined\n\n if (materialization === `concat`) {\n if (rawChildSelect === undefined || hasObjectSelect) {\n throw new Error(\n `concat(toArray(...)) for \"${fieldName}\" requires the subquery to select a scalar value`,\n )\n }\n }\n\n if (!hasObjectSelect) {\n if (materialization === `collection`) {\n throw new Error(\n `Includes subquery for \"${fieldName}\" must select an object when materializing as a Collection`,\n )\n }\n\n scalarField = INCLUDES_SCALAR_FIELD\n includesQuery = {\n ...modifiedQuery,\n select: {\n [scalarField]: rawChildSelect,\n },\n }\n }\n\n return new IncludesSubquery(\n includesQuery,\n parentRef,\n childRef,\n fieldName,\n parentFilters.length > 0 ? parentFilters : undefined,\n parentProjection,\n materialization,\n scalarField,\n )\n}\n\n/**\n * Checks if two eq() arguments form a parent-child correlation.\n * Returns the parent and child PropRefs if found, undefined otherwise.\n */\nfunction extractCorrelation(\n argA: BasicExpression,\n argB: BasicExpression,\n parentAliases: Array<string>,\n childAliases: Array<string>,\n): { parentRef: PropRef; childRef: PropRef } | undefined {\n if (argA.type === `ref` && argB.type === `ref`) {\n const aAlias = argA.path[0]\n const bAlias = argB.path[0]\n\n if (\n aAlias &&\n bAlias &&\n parentAliases.includes(aAlias) &&\n childAliases.includes(bAlias)\n ) {\n return { parentRef: argA, childRef: argB }\n }\n\n if (\n aAlias &&\n bAlias &&\n parentAliases.includes(bAlias) &&\n childAliases.includes(aAlias)\n ) {\n return { parentRef: argB, childRef: argA }\n }\n }\n\n return undefined\n}\n\n// Internal function to build a query from a callback\n// used by liveQueryCollectionOptions.query\nexport function buildQuery<TContext extends Context>(\n fn: (builder: InitialQueryBuilder) => QueryBuilder<TContext>,\n): QueryIR {\n const result = fn(new BaseQueryBuilder())\n return getQueryIR(result)\n}\n\n// Internal function to get the QueryIR from a builder\nexport function getQueryIR(\n builder: BaseQueryBuilder | QueryBuilder<any> | InitialQueryBuilder,\n): QueryIR {\n return (builder as unknown as BaseQueryBuilder)._getQuery()\n}\n\n// Type-only exports for the query builder\nexport type InitialQueryBuilder = Pick<BaseQueryBuilder<Context>, `from`>\n\nexport type InitialQueryBuilderConstructor = new () => InitialQueryBuilder\n\nexport type QueryBuilder<TContext extends Context> = Omit<\n BaseQueryBuilder<TContext>,\n `from` | `_getQuery`\n>\n\n// Main query builder class alias with the constructor type modified to hide all\n// but the from method on the initial instance\nexport const Query: InitialQueryBuilderConstructor = BaseQueryBuilder\n\n// Helper type to extract context from a QueryBuilder\nexport type ExtractContext<T> =\n T extends BaseQueryBuilder<infer TContext>\n ? TContext\n : T extends QueryBuilder<infer TContext>\n ? TContext\n : never\n\n// Helper type to extract the result type from a QueryBuilder (similar to Zod's z.infer)\nexport type QueryResult<T> = GetResult<ExtractContext<T>>\n\n// Export the types from types.ts for convenience\nexport type {\n Context,\n ContextSchema,\n Source,\n GetResult,\n RefLeaf as Ref,\n InferResultType,\n // Types used in public method signatures that must be exported\n // for declaration emit to work (see https://github.com/TanStack/db/issues/1012)\n SchemaFromSource,\n InferCollectionType,\n MergeContextWithJoinType,\n MergeContextForJoinCallback,\n ApplyJoinOptionalityToMergedSchema,\n ResultTypeFromSelect,\n WithResult,\n JoinOnCallback,\n RefsForContext,\n WhereCallback,\n OrderByCallback,\n GroupByCallback,\n SelectObject,\n FunctionalHavingRow,\n Prettify,\n} from './types.js'\n"],"names":["InvalidSourceTypeError","OnlyOneSourceAllowedError","CollectionImpl","CollectionRef","SubQueryMustHaveFromClauseError","QueryRef","InvalidSourceError","refProxy","createRefProxy","JoinConditionMustBeEqualityError","isRefProxy","toExpression","isExpressionLike","InvalidWhereExpressionError","createRefProxyWithSelected","QueryMustHaveFromClauseError","AggregateExpr","FuncExpr","PropRef","ValueExpr","ToArrayWrapper","ConcatToArrayWrapper","INCLUDES_SCALAR_FIELD","IncludesSubquery"],"mappings":";;;;;;;AA8DO,MAAM,iBAAqD;AAAA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S;AACT,SAAQ,QAAwC,UAAA;AAClD;AAcO,MAAM,QAAwC;;;;;"}
@@ -1,6 +1,6 @@
1
1
  import { SingleResult } from '../../types.js';
2
2
  import { OrderByDirection, QueryIR } from '../ir.js';
3
- import { Context, FunctionalHavingRow, GetResult, GroupByCallback, JoinOnCallback, MergeContextForJoinCallback, MergeContextWithJoinType, OrderByCallback, OrderByOptions, RefsForContext, ResultTypeFromSelect, SchemaFromSource, SelectObject, Source, WhereCallback, WithResult } from './types.js';
3
+ import { Context, FunctionalHavingRow, GetResult, GroupByCallback, JoinOnCallback, MergeContextForJoinCallback, MergeContextWithJoinType, NonScalarSelectObject, OrderByCallback, OrderByOptions, RefsForContext, ResultTypeFromSelect, ResultTypeFromSelectValue, ScalarSelectValue, SchemaFromSource, SelectObject, Source, WhereCallback, WithResult } from './types.js';
4
4
  export declare class BaseQueryBuilder<TContext extends Context = Context> {
5
5
  private readonly query;
6
6
  constructor(query?: Partial<QueryIR>);
@@ -217,7 +217,8 @@ export declare class BaseQueryBuilder<TContext extends Context = Context> {
217
217
  * }))
218
218
  * ```
219
219
  */
220
- select<TSelectObject extends SelectObject>(callback: (refs: RefsForContext<TContext>) => TSelectObject): QueryBuilder<WithResult<TContext, ResultTypeFromSelect<TSelectObject>>>;
220
+ select<TSelectObject extends SelectObject>(callback: (refs: RefsForContext<TContext>) => NonScalarSelectObject<TSelectObject>): QueryBuilder<WithResult<TContext, ResultTypeFromSelect<TSelectObject>>>;
221
+ select<TSelectValue extends ScalarSelectValue>(callback: (refs: RefsForContext<TContext>) => TSelectValue): QueryBuilder<WithResult<TContext, ResultTypeFromSelectValue<TSelectValue>>>;
221
222
  /**
222
223
  * Sort the query results by one or more columns
223
224
  *
@@ -319,7 +320,7 @@ export declare class BaseQueryBuilder<TContext extends Context = Context> {
319
320
  * // Get countries our users are from
320
321
  * query
321
322
  * .from({ users: usersCollection })
322
- * .select(({users}) => users.country)
323
+ * .select(({users}) => ({ country: users.country }))
323
324
  * .distinct()
324
325
  * ```
325
326
  */
@@ -1 +1 @@
1
- {"version":3,"file":"ref-proxy.cjs","sources":["../../../../src/query/builder/ref-proxy.ts"],"sourcesContent":["import { PropRef, Value } from '../ir.js'\nimport type { BasicExpression } from '../ir.js'\nimport type { RefLeaf } from './types.js'\n\nexport interface RefProxy<T = any> {\n /** @internal */\n readonly __refProxy: true\n /** @internal */\n readonly __path: Array<string>\n /** @internal */\n readonly __type: T\n}\n\n/**\n * Type for creating a RefProxy for a single row/type without namespacing\n * Used in collection indexes and where clauses\n */\nexport type SingleRowRefProxy<T> =\n T extends Record<string, any>\n ? {\n [K in keyof T]: T[K] extends Record<string, any>\n ? SingleRowRefProxy<T[K]> & RefProxy<T[K]>\n : RefLeaf<T[K]>\n } & RefProxy<T>\n : RefProxy<T>\n\n/**\n * Creates a proxy object that records property access paths for a single row\n * Used in collection indexes and where clauses\n */\nexport function createSingleRowRefProxy<\n T extends Record<string, any>,\n>(): SingleRowRefProxy<T> {\n const cache = new Map<string, any>()\n\n function createProxy(path: Array<string>): any {\n const pathKey = path.join(`.`)\n if (cache.has(pathKey)) {\n return cache.get(pathKey)\n }\n\n const proxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return path\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const newPath = [...path, String(prop)]\n return createProxy(newPath)\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n })\n\n cache.set(pathKey, proxy)\n return proxy\n }\n\n // Return the root proxy that starts with an empty path\n return createProxy([]) as SingleRowRefProxy<T>\n}\n\n/**\n * Creates a proxy object that records property access paths\n * Used in callbacks like where, select, etc. to create type-safe references\n */\nexport function createRefProxy<T extends Record<string, any>>(\n aliases: Array<string>,\n): RefProxy<T> & T {\n const cache = new Map<string, any>()\n let accessId = 0 // Monotonic counter to record evaluation order\n\n function createProxy(path: Array<string>): any {\n const pathKey = path.join(`.`)\n if (cache.has(pathKey)) {\n return cache.get(pathKey)\n }\n\n const proxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return path\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const newPath = [...path, String(prop)]\n return createProxy(newPath)\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n const id = ++accessId\n const sentinelKey = `__SPREAD_SENTINEL__${path.join(`.`)}__${id}`\n if (!Object.prototype.hasOwnProperty.call(target, sentinelKey)) {\n Object.defineProperty(target, sentinelKey, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n }\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n })\n\n cache.set(pathKey, proxy)\n return proxy\n }\n\n // Create the root proxy with all aliases as top-level properties\n const rootProxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return []\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const propStr = String(prop)\n if (aliases.includes(propStr)) {\n return createProxy([propStr])\n }\n\n return undefined\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n if (typeof prop === `string` && aliases.includes(prop)) return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(_target) {\n return [...aliases, `__refProxy`, `__path`, `__type`]\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n if (typeof prop === `string` && aliases.includes(prop)) {\n return { enumerable: true, configurable: true }\n }\n return undefined\n },\n })\n\n return rootProxy\n}\n\n/**\n * Creates a ref proxy with $selected namespace for SELECT fields\n *\n * Adds a $selected property that allows accessing SELECT fields via $selected.fieldName syntax.\n * The $selected proxy creates paths like ['$selected', 'fieldName'] which directly reference\n * the $selected property on the namespaced row.\n *\n * @param aliases - Array of table aliases to create proxies for\n * @returns A ref proxy with table aliases and $selected namespace\n */\nexport function createRefProxyWithSelected<T extends Record<string, any>>(\n aliases: Array<string>,\n): RefProxy<T> & T & { $selected: SingleRowRefProxy<any> } {\n const baseProxy = createRefProxy(aliases)\n\n // Create a proxy for $selected that prefixes all paths with '$selected'\n const cache = new Map<string, any>()\n\n function createSelectedProxy(path: Array<string>): any {\n const pathKey = path.join(`.`)\n if (cache.has(pathKey)) {\n return cache.get(pathKey)\n }\n\n const proxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return [`$selected`, ...path]\n if (prop === `__type`) return undefined\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const newPath = [...path, String(prop)]\n return createSelectedProxy(newPath)\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n })\n\n cache.set(pathKey, proxy)\n return proxy\n }\n\n const wrappedSelectedProxy = createSelectedProxy([])\n\n // Wrap the base proxy to also handle $selected access\n return new Proxy(baseProxy, {\n get(target, prop, receiver) {\n if (prop === `$selected`) {\n return wrappedSelectedProxy\n }\n return Reflect.get(target, prop, receiver)\n },\n\n has(target, prop) {\n if (prop === `$selected`) return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n return [...Reflect.ownKeys(target), `$selected`]\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `$selected`) {\n return {\n enumerable: true,\n configurable: true,\n value: wrappedSelectedProxy,\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n }) as RefProxy<T> & T & { $selected: SingleRowRefProxy<any> }\n}\n\n/**\n * Converts a value to an Expression\n * If it's a RefProxy, creates a Ref, otherwise creates a Value\n */\nexport function toExpression<T = any>(value: T): BasicExpression<T>\nexport function toExpression(value: RefProxy<any>): BasicExpression<any>\nexport function toExpression(value: any): BasicExpression<any> {\n if (isRefProxy(value)) {\n return new PropRef(value.__path)\n }\n // If it's already an Expression (Func, Ref, Value) or Agg, return it directly\n if (\n value &&\n typeof value === `object` &&\n `type` in value &&\n (value.type === `func` ||\n value.type === `ref` ||\n value.type === `val` ||\n value.type === `agg`)\n ) {\n return value\n }\n return new Value(value)\n}\n\n/**\n * Type guard to check if a value is a RefProxy\n */\nexport function isRefProxy(value: any): value is RefProxy {\n return value && typeof value === `object` && value.__refProxy === true\n}\n\n/**\n * Helper to create a Value expression from a literal\n */\nexport function val<T>(value: T): BasicExpression<T> {\n return new Value(value)\n}\n"],"names":["PropRef","Value"],"mappings":";;;AA8BO,SAAS,0BAEU;AACxB,QAAM,4BAAY,IAAA;AAElB,WAAS,YAAY,MAA0B;AAC7C,UAAM,UAAU,KAAK,KAAK,GAAG;AAC7B,QAAI,MAAM,IAAI,OAAO,GAAG;AACtB,aAAO,MAAM,IAAI,OAAO;AAAA,IAC1B;AAEA,UAAM,QAAQ,IAAI,MAAM,IAAW;AAAA,MACjC,IAAI,QAAQ,MAAM,UAAU;AAC1B,YAAI,SAAS,aAAc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O,IAAIC,GAAAA,MAAM,KAAK;AACxB;AAKO,SAAS,WAAW,OAA+B;AACxD,SAAO,SAAS,OAAO,UAAU,YAAY,MAAM,eAAe;AACpE;;;;;;"}
1
+ {"version":3,"file":"ref-proxy.cjs","sources":["../../../../src/query/builder/ref-proxy.ts"],"sourcesContent":["import { PropRef, Value } from '../ir.js'\nimport type { BasicExpression } from '../ir.js'\nimport type { RefLeaf } from './types.js'\nimport type { VirtualRowProps } from '../../virtual-props.js'\n\nexport interface RefProxy<T = any> {\n /** @internal */\n readonly __refProxy: true\n /** @internal */\n readonly __path: Array<string>\n /** @internal */\n readonly __type: T\n}\n\n/**\n * Virtual properties available on all row ref proxies.\n * These allow querying on sync status, origin, key, and collection ID.\n */\nexport type VirtualPropsRefProxy<\n TKey extends string | number = string | number,\n> = {\n readonly [K in keyof VirtualRowProps<TKey>]: RefLeaf<VirtualRowProps<TKey>[K]>\n}\n\n/**\n * Type for creating a RefProxy for a single row/type without namespacing\n * Used in collection indexes and where clauses\n *\n * Includes virtual properties ($synced, $origin, $key, $collectionId) for\n * querying on sync status and row metadata.\n */\nexport type SingleRowRefProxy<\n T,\n TKey extends string | number = string | number,\n> =\n T extends Record<string, any>\n ? {\n [K in keyof T]: T[K] extends Record<string, any>\n ? SingleRowRefProxy<T[K], TKey> & RefProxy<T[K]>\n : RefLeaf<T[K]>\n } & RefProxy<T> &\n VirtualPropsRefProxy<TKey>\n : RefProxy<T> & VirtualPropsRefProxy<TKey>\n\n/**\n * Creates a proxy object that records property access paths for a single row\n * Used in collection indexes and where clauses\n */\nexport function createSingleRowRefProxy<\n T extends Record<string, any>,\n>(): SingleRowRefProxy<T> {\n const cache = new Map<string, any>()\n\n function createProxy(path: Array<string>): any {\n const pathKey = path.join(`.`)\n if (cache.has(pathKey)) {\n return cache.get(pathKey)\n }\n\n const proxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return path\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const newPath = [...path, String(prop)]\n return createProxy(newPath)\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n })\n\n cache.set(pathKey, proxy)\n return proxy\n }\n\n // Return the root proxy that starts with an empty path\n return createProxy([]) as SingleRowRefProxy<T>\n}\n\n/**\n * Creates a proxy object that records property access paths\n * Used in callbacks like where, select, etc. to create type-safe references\n */\nexport function createRefProxy<T extends Record<string, any>>(\n aliases: Array<string>,\n): RefProxy<T> & T {\n const cache = new Map<string, any>()\n let accessId = 0 // Monotonic counter to record evaluation order\n\n function createProxy(path: Array<string>): any {\n const pathKey = path.join(`.`)\n if (cache.has(pathKey)) {\n return cache.get(pathKey)\n }\n\n const proxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return path\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const newPath = [...path, String(prop)]\n return createProxy(newPath)\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n const id = ++accessId\n const sentinelKey = `__SPREAD_SENTINEL__${path.join(`.`)}__${id}`\n if (!Object.prototype.hasOwnProperty.call(target, sentinelKey)) {\n Object.defineProperty(target, sentinelKey, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n }\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n })\n\n cache.set(pathKey, proxy)\n return proxy\n }\n\n // Create the root proxy with all aliases as top-level properties\n const rootProxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return []\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const propStr = String(prop)\n if (aliases.includes(propStr)) {\n return createProxy([propStr])\n }\n\n return undefined\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n if (typeof prop === `string` && aliases.includes(prop)) return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(_target) {\n return [...aliases, `__refProxy`, `__path`, `__type`]\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n if (typeof prop === `string` && aliases.includes(prop)) {\n return { enumerable: true, configurable: true }\n }\n return undefined\n },\n })\n\n return rootProxy\n}\n\n/**\n * Creates a ref proxy with $selected namespace for SELECT fields\n *\n * Adds a $selected property that allows accessing SELECT fields via $selected.fieldName syntax.\n * The $selected proxy creates paths like ['$selected', 'fieldName'] which directly reference\n * the $selected property on the namespaced row.\n *\n * @param aliases - Array of table aliases to create proxies for\n * @returns A ref proxy with table aliases and $selected namespace\n */\nexport function createRefProxyWithSelected<T extends Record<string, any>>(\n aliases: Array<string>,\n): RefProxy<T> & T & { $selected: SingleRowRefProxy<any> } {\n const baseProxy = createRefProxy(aliases)\n\n // Create a proxy for $selected that prefixes all paths with '$selected'\n const cache = new Map<string, any>()\n\n function createSelectedProxy(path: Array<string>): any {\n const pathKey = path.join(`.`)\n if (cache.has(pathKey)) {\n return cache.get(pathKey)\n }\n\n const proxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return [`$selected`, ...path]\n if (prop === `__type`) return undefined\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const newPath = [...path, String(prop)]\n return createSelectedProxy(newPath)\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n })\n\n cache.set(pathKey, proxy)\n return proxy\n }\n\n const wrappedSelectedProxy = createSelectedProxy([])\n\n // Wrap the base proxy to also handle $selected access\n return new Proxy(baseProxy, {\n get(target, prop, receiver) {\n if (prop === `$selected`) {\n return wrappedSelectedProxy\n }\n return Reflect.get(target, prop, receiver)\n },\n\n has(target, prop) {\n if (prop === `$selected`) return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n return [...Reflect.ownKeys(target), `$selected`]\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `$selected`) {\n return {\n enumerable: true,\n configurable: true,\n value: wrappedSelectedProxy,\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n }) as RefProxy<T> & T & { $selected: SingleRowRefProxy<any> }\n}\n\n/**\n * Converts a value to an Expression\n * If it's a RefProxy, creates a Ref, otherwise creates a Value\n */\nexport function toExpression<T = any>(value: T): BasicExpression<T>\nexport function toExpression(value: RefProxy<any>): BasicExpression<any>\nexport function toExpression(value: any): BasicExpression<any> {\n if (isRefProxy(value)) {\n return new PropRef(value.__path)\n }\n // If it's already an Expression (Func, Ref, Value) or Agg, return it directly\n if (\n value &&\n typeof value === `object` &&\n `type` in value &&\n (value.type === `func` ||\n value.type === `ref` ||\n value.type === `val` ||\n value.type === `agg`)\n ) {\n return value\n }\n return new Value(value)\n}\n\n/**\n * Type guard to check if a value is a RefProxy\n */\nexport function isRefProxy(value: any): value is RefProxy {\n return value && typeof value === `object` && value.__refProxy === true\n}\n\n/**\n * Helper to create a Value expression from a literal\n */\nexport function val<T>(value: T): BasicExpression<T> {\n return new Value(value)\n}\n"],"names":["PropRef","Value"],"mappings":";;;AAgDO,SAAS,0BAEU;AACxB,QAAM,4BAAY,IAAA;AAElB,WAAS,YAAY,MAA0B;AAC7C,UAAM,UAAU,KAAK,KAAK,GAAG;AAC7B,QAAI,MAAM,IAAI,OAAO,GAAG;AACtB,aAAO,MAAM,IAAI,OAAO;AAAA,IAC1B;AAEA,UAAM,QAAQ,IAAI,MAAM,IAAW;AAAA,MACjC,IAAI,QAAQ,MAAM,UAAU;AAC1B,YAAI,SAAS,aAAc,QAAO;AAClC,YAAI,SAAS,SAAU,QAAO;AAC9B,YAAI,SAAS,SAAU,QAAO;AAC9B,YAAI,OAAO,SAAS,SAAU,QAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;AAEvE,cAAM,UAAU,CAAC,GAAG,MAAM,OAAO,IAAI,CAAC;AACtC,eAAO,YAAY,OAAO;AAAA,MAC5B;AAAA,MAEA,IAAI,QAAQ,MAAM;AAChB,YAAI,SAAS,gBAAgB,SAAS,YAAY,SAAS;AACzD,iBAAO;AACT,eAAO,QAAQ,IAAI,QAAQ,IAAI;AAAA,MACjC;AAAA,MAEA,QAAQ,QAAQ;AACd,eAAO,QAAQ,QAAQ,MAAM;AAAA,MAC/B;AAAA,MAEA,yBAAyB,QAAQ,MAAM;AACrC,YAAI,SAAS,gBAAgB,SAAS,YAAY,SAAS,UAAU;AACnE,iBAAO,EAAE,YAAY,OAAO,cAAc,KAAA;AAAA,QAC5C;AACA,eAAO,QAAQ,yBAAyB,QAAQ,IAAI;AAAA,MACtD;AAAA,IAAA,CACD;AAED,UAAM,IAAI,SAAS,KAAK;AACxB,WAAO;AAAA,EACT;AAGA,SAAO,YAAY,CAAA,CAAE;AACvB;AAMO,SAAS,eACd,SACiB;AACjB,QAAM,4BAAY,IAAA;AAClB,MAAI,WAAW;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S,aAAa;AACxB,eAAO;AAAA,UACL,YAAY;AAAA,UACZ,cAAc;AAAA,UACd,OAAO;AAAA,QAAA;AAAA,MAEX;AACA,aAAO,QAAQ,yBAAyB,QAAQ,IAAI;AAAA,IACtD;AAAA,EAAA,CACD;AACH;AAQO,SAAS,aAAa,OAAkC;AAC7D,MAAI,WAAW,KAAK,GAAG;AACrB,WAAO,IAAIA,GAAAA,QAAQ,MAAM,MAAM;AAAA,EACjC;AAEA,MACE,SACA,OAAO,UAAU,YACjB,UAAU,UACT,MAAM,SAAS,UACd,MAAM,SAAS,SACf,MAAM,SAAS,SACf,MAAM,SAAS,QACjB;AACA,WAAO;AAAA,EACT;AACA,SAAO,IAAIC,GAAAA,MAAM,KAAK;AACxB;AAKO,SAAS,WAAW,OAA+B;AACxD,SAAO,SAAS,OAAO,UAAU,YAAY,MAAM,eAAe;AACpE;;;;;;"}
@@ -1,5 +1,6 @@
1
1
  import { BasicExpression } from '../ir.js';
2
2
  import { RefLeaf } from './types.js';
3
+ import { VirtualRowProps } from '../../virtual-props.js';
3
4
  export interface RefProxy<T = any> {
4
5
  /** @internal */
5
6
  readonly __refProxy: true;
@@ -8,13 +9,23 @@ export interface RefProxy<T = any> {
8
9
  /** @internal */
9
10
  readonly __type: T;
10
11
  }
12
+ /**
13
+ * Virtual properties available on all row ref proxies.
14
+ * These allow querying on sync status, origin, key, and collection ID.
15
+ */
16
+ export type VirtualPropsRefProxy<TKey extends string | number = string | number> = {
17
+ readonly [K in keyof VirtualRowProps<TKey>]: RefLeaf<VirtualRowProps<TKey>[K]>;
18
+ };
11
19
  /**
12
20
  * Type for creating a RefProxy for a single row/type without namespacing
13
21
  * Used in collection indexes and where clauses
22
+ *
23
+ * Includes virtual properties ($synced, $origin, $key, $collectionId) for
24
+ * querying on sync status and row metadata.
14
25
  */
15
- export type SingleRowRefProxy<T> = T extends Record<string, any> ? {
16
- [K in keyof T]: T[K] extends Record<string, any> ? SingleRowRefProxy<T[K]> & RefProxy<T[K]> : RefLeaf<T[K]>;
17
- } & RefProxy<T> : RefProxy<T>;
26
+ export type SingleRowRefProxy<T, TKey extends string | number = string | number> = T extends Record<string, any> ? {
27
+ [K in keyof T]: T[K] extends Record<string, any> ? SingleRowRefProxy<T[K], TKey> & RefProxy<T[K]> : RefLeaf<T[K]>;
28
+ } & RefProxy<T> & VirtualPropsRefProxy<TKey> : RefProxy<T> & VirtualPropsRefProxy<TKey>;
18
29
  /**
19
30
  * Creates a proxy object that records property access paths for a single row
20
31
  * Used in collection indexes and where clauses