@rocicorp/zero 1.3.0 → 1.4.0-canary.1

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 (332) hide show
  1. package/out/analyze-query/src/analyze-cli.d.ts +24 -0
  2. package/out/analyze-query/src/analyze-cli.d.ts.map +1 -0
  3. package/out/analyze-query/src/analyze-cli.js +289 -0
  4. package/out/analyze-query/src/analyze-cli.js.map +1 -0
  5. package/out/analyze-query/src/bin-analyze.js +6 -6
  6. package/out/analyze-query/src/bin-transform.js +2 -2
  7. package/out/ast-to-zql/src/bin.js +1 -1
  8. package/out/shared/src/logging.d.ts.map +1 -1
  9. package/out/shared/src/logging.js +1 -1
  10. package/out/shared/src/logging.js.map +1 -1
  11. package/out/shared/src/options.d.ts.map +1 -1
  12. package/out/shared/src/options.js +1 -1
  13. package/out/shared/src/options.js.map +1 -1
  14. package/out/z2s/src/compiler.d.ts.map +1 -1
  15. package/out/z2s/src/compiler.js +4 -1
  16. package/out/z2s/src/compiler.js.map +1 -1
  17. package/out/z2s/src/sql.d.ts.map +1 -1
  18. package/out/z2s/src/sql.js +1 -0
  19. package/out/z2s/src/sql.js.map +1 -1
  20. package/out/zero/package.js +95 -89
  21. package/out/zero/package.js.map +1 -1
  22. package/out/zero/src/analyze.d.ts +2 -0
  23. package/out/zero/src/analyze.d.ts.map +1 -0
  24. package/out/zero/src/analyze.js +2 -0
  25. package/out/zero/src/bindings.js +1 -1
  26. package/out/zero/src/zero-cache-dev.js +1 -1
  27. package/out/zero/src/zero-cache-dev.js.map +1 -1
  28. package/out/zero/src/zero-out.js +1 -1
  29. package/out/zero-cache/src/auth/auth.d.ts.map +1 -1
  30. package/out/zero-cache/src/auth/auth.js.map +1 -1
  31. package/out/zero-cache/src/auth/load-permissions.js +2 -2
  32. package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
  33. package/out/zero-cache/src/auth/write-authorizer.js +5 -14
  34. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  35. package/out/zero-cache/src/config/network.d.ts +1 -1
  36. package/out/zero-cache/src/config/network.d.ts.map +1 -1
  37. package/out/zero-cache/src/config/network.js +1 -1
  38. package/out/zero-cache/src/config/network.js.map +1 -1
  39. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  40. package/out/zero-cache/src/config/normalize.js.map +1 -1
  41. package/out/zero-cache/src/config/zero-config.d.ts +5 -0
  42. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  43. package/out/zero-cache/src/config/zero-config.js +16 -3
  44. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  45. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  46. package/out/zero-cache/src/db/lite-tables.js +3 -3
  47. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  48. package/out/zero-cache/src/db/transaction-pool.d.ts +43 -40
  49. package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
  50. package/out/zero-cache/src/db/transaction-pool.js +76 -56
  51. package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
  52. package/out/zero-cache/src/observability/events.d.ts.map +1 -1
  53. package/out/zero-cache/src/observability/events.js +1 -1
  54. package/out/zero-cache/src/observability/events.js.map +1 -1
  55. package/out/zero-cache/src/scripts/decommission.js +1 -1
  56. package/out/zero-cache/src/scripts/deploy-permissions.js +2 -2
  57. package/out/zero-cache/src/scripts/permissions.js +1 -1
  58. package/out/zero-cache/src/server/anonymous-otel-start.d.ts.map +1 -1
  59. package/out/zero-cache/src/server/anonymous-otel-start.js +4 -4
  60. package/out/zero-cache/src/server/anonymous-otel-start.js.map +1 -1
  61. package/out/zero-cache/src/server/change-streamer.d.ts +1 -1
  62. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  63. package/out/zero-cache/src/server/change-streamer.js +27 -12
  64. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  65. package/out/zero-cache/src/server/logging.d.ts +1 -3
  66. package/out/zero-cache/src/server/logging.d.ts.map +1 -1
  67. package/out/zero-cache/src/server/logging.js +6 -3
  68. package/out/zero-cache/src/server/logging.js.map +1 -1
  69. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  70. package/out/zero-cache/src/server/main.js +26 -26
  71. package/out/zero-cache/src/server/main.js.map +1 -1
  72. package/out/zero-cache/src/server/mutator.js +4 -2
  73. package/out/zero-cache/src/server/mutator.js.map +1 -1
  74. package/out/zero-cache/src/server/otel-log-sink.d.ts.map +1 -1
  75. package/out/zero-cache/src/server/otel-log-sink.js +0 -2
  76. package/out/zero-cache/src/server/otel-log-sink.js.map +1 -1
  77. package/out/zero-cache/src/server/otel-start.d.ts +1 -1
  78. package/out/zero-cache/src/server/otel-start.d.ts.map +1 -1
  79. package/out/zero-cache/src/server/otel-start.js +7 -3
  80. package/out/zero-cache/src/server/otel-start.js.map +1 -1
  81. package/out/zero-cache/src/server/reaper.js +6 -6
  82. package/out/zero-cache/src/server/reaper.js.map +1 -1
  83. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  84. package/out/zero-cache/src/server/replicator.js +5 -3
  85. package/out/zero-cache/src/server/replicator.js.map +1 -1
  86. package/out/zero-cache/src/server/runner/run-worker.js +2 -2
  87. package/out/zero-cache/src/server/runner/run-worker.js.map +1 -1
  88. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  89. package/out/zero-cache/src/server/syncer.js +13 -12
  90. package/out/zero-cache/src/server/syncer.js.map +1 -1
  91. package/out/zero-cache/src/server/worker-dispatcher.js +1 -1
  92. package/out/zero-cache/src/services/analyze.js +1 -1
  93. package/out/zero-cache/src/services/change-source/common/backfill-manager.js +1 -1
  94. package/out/zero-cache/src/services/change-source/common/replica-schema.js +1 -1
  95. package/out/zero-cache/src/services/change-source/custom/change-source.js +2 -2
  96. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +4 -1
  97. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  98. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  99. package/out/zero-cache/src/services/change-source/pg/change-source.js +19 -23
  100. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  101. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +58 -3
  102. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  103. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +209 -52
  104. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  105. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +2 -2
  106. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +24 -15
  107. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  108. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +35 -58
  109. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  110. package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
  111. package/out/zero-cache/src/services/change-source/pg/schema/init.js +2 -2
  112. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  113. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -2
  114. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
  115. package/out/zero-cache/src/services/change-source/pg/schema/published.js +15 -18
  116. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  117. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +1 -1
  118. package/out/zero-cache/src/services/change-source/protocol/current/data.js +1 -1
  119. package/out/zero-cache/src/services/change-streamer/backup-monitor.js +1 -1
  120. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +1 -1
  121. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  122. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +1 -1
  123. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  124. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +5 -1
  125. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  126. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +10 -7
  127. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  128. package/out/zero-cache/src/services/change-streamer/replica-monitor.js +2 -2
  129. package/out/zero-cache/src/services/change-streamer/storer.d.ts +19 -2
  130. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  131. package/out/zero-cache/src/services/change-streamer/storer.js +70 -6
  132. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  133. package/out/zero-cache/src/services/heapz.d.ts.map +1 -1
  134. package/out/zero-cache/src/services/heapz.js +1 -1
  135. package/out/zero-cache/src/services/heapz.js.map +1 -1
  136. package/out/zero-cache/src/services/life-cycle.d.ts +2 -1
  137. package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
  138. package/out/zero-cache/src/services/life-cycle.js +10 -7
  139. package/out/zero-cache/src/services/life-cycle.js.map +1 -1
  140. package/out/zero-cache/src/services/litestream/commands.d.ts +15 -4
  141. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  142. package/out/zero-cache/src/services/litestream/commands.js +40 -34
  143. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  144. package/out/zero-cache/src/services/mutagen/mutagen.js +3 -3
  145. package/out/zero-cache/src/services/mutagen/pusher.d.ts +28 -28
  146. package/out/zero-cache/src/services/replicator/change-processor.js +2 -2
  147. package/out/zero-cache/src/services/replicator/incremental-sync.js +1 -1
  148. package/out/zero-cache/src/services/replicator/schema/replication-state.js +1 -1
  149. package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
  150. package/out/zero-cache/src/services/replicator/write-worker.js +3 -3
  151. package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
  152. package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
  153. package/out/zero-cache/src/services/run-ast.js +3 -3
  154. package/out/zero-cache/src/services/run-ast.js.map +1 -1
  155. package/out/zero-cache/src/services/statz.d.ts.map +1 -1
  156. package/out/zero-cache/src/services/statz.js +3 -3
  157. package/out/zero-cache/src/services/statz.js.map +1 -1
  158. package/out/zero-cache/src/services/view-syncer/active-users-gauge.js +1 -1
  159. package/out/zero-cache/src/services/view-syncer/connection-context-manager.d.ts +2 -2
  160. package/out/zero-cache/src/services/view-syncer/connection-context-manager.d.ts.map +1 -1
  161. package/out/zero-cache/src/services/view-syncer/connection-context-manager.js.map +1 -1
  162. package/out/zero-cache/src/services/view-syncer/cvr-purger.js +1 -1
  163. package/out/zero-cache/src/services/view-syncer/cvr-store.js +3 -3
  164. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  165. package/out/zero-cache/src/services/view-syncer/cvr.js +1 -1
  166. package/out/zero-cache/src/services/view-syncer/inspect-handler.js +2 -2
  167. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +6 -16
  168. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  169. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +31 -39
  170. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  171. package/out/zero-cache/src/services/view-syncer/row-record-cache.d.ts.map +1 -1
  172. package/out/zero-cache/src/services/view-syncer/row-record-cache.js +4 -4
  173. package/out/zero-cache/src/services/view-syncer/row-record-cache.js.map +1 -1
  174. package/out/zero-cache/src/services/view-syncer/snapshotter.js +2 -2
  175. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  176. package/out/zero-cache/src/services/view-syncer/view-syncer.js +6 -6
  177. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  178. package/out/zero-cache/src/types/profiler.d.ts.map +1 -1
  179. package/out/zero-cache/src/types/profiler.js.map +1 -1
  180. package/out/zero-cache/src/types/row-key.d.ts.map +1 -1
  181. package/out/zero-cache/src/types/row-key.js.map +1 -1
  182. package/out/zero-cache/src/types/streams.d.ts +1 -1
  183. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  184. package/out/zero-cache/src/types/streams.js.map +1 -1
  185. package/out/zero-cache/src/types/websocket-handoff.d.ts +1 -1
  186. package/out/zero-cache/src/types/websocket-handoff.d.ts.map +1 -1
  187. package/out/zero-cache/src/types/websocket-handoff.js +1 -1
  188. package/out/zero-cache/src/types/websocket-handoff.js.map +1 -1
  189. package/out/zero-cache/src/workers/connection.d.ts +1 -1
  190. package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
  191. package/out/zero-cache/src/workers/connection.js.map +1 -1
  192. package/out/zero-cache/src/workers/mutator.js.map +1 -1
  193. package/out/zero-cache/src/workers/syncer.d.ts +1 -1
  194. package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
  195. package/out/zero-cache/src/workers/syncer.js +3 -3
  196. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  197. package/out/zero-client/src/client/bindings.js +1 -1
  198. package/out/zero-client/src/client/crud-impl.d.ts.map +1 -1
  199. package/out/zero-client/src/client/crud-impl.js +4 -13
  200. package/out/zero-client/src/client/crud-impl.js.map +1 -1
  201. package/out/zero-client/src/client/inspector/inspector.d.ts +24 -0
  202. package/out/zero-client/src/client/inspector/inspector.d.ts.map +1 -1
  203. package/out/zero-client/src/client/inspector/inspector.js +28 -0
  204. package/out/zero-client/src/client/inspector/inspector.js.map +1 -1
  205. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts +9 -0
  206. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts.map +1 -1
  207. package/out/zero-client/src/client/inspector/lazy-inspector.js +28 -1
  208. package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
  209. package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
  210. package/out/zero-client/src/client/ivm-branch.js +4 -13
  211. package/out/zero-client/src/client/ivm-branch.js.map +1 -1
  212. package/out/zero-client/src/client/log-options.d.ts +1 -0
  213. package/out/zero-client/src/client/log-options.d.ts.map +1 -1
  214. package/out/zero-client/src/client/log-options.js +3 -2
  215. package/out/zero-client/src/client/log-options.js.map +1 -1
  216. package/out/zero-client/src/client/options.d.ts +13 -1
  217. package/out/zero-client/src/client/options.d.ts.map +1 -1
  218. package/out/zero-client/src/client/options.js.map +1 -1
  219. package/out/zero-client/src/client/version.js +1 -1
  220. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  221. package/out/zero-client/src/client/zero.js +2 -1
  222. package/out/zero-client/src/client/zero.js.map +1 -1
  223. package/out/zero-protocol/src/error.d.ts.map +1 -1
  224. package/out/zero-protocol/src/error.js +1 -1
  225. package/out/zero-protocol/src/error.js.map +1 -1
  226. package/out/zero-react/src/bindings.js +1 -1
  227. package/out/zero-solid/src/bindings.js +1 -1
  228. package/out/zero-solid/src/solid-view.d.ts.map +1 -1
  229. package/out/zero-solid/src/solid-view.js +14 -14
  230. package/out/zero-solid/src/solid-view.js.map +1 -1
  231. package/out/zql/src/builder/builder.d.ts.map +1 -1
  232. package/out/zql/src/builder/builder.js.map +1 -1
  233. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  234. package/out/zql/src/ivm/array-view.js +27 -2
  235. package/out/zql/src/ivm/array-view.js.map +1 -1
  236. package/out/zql/src/ivm/change-index-enum.d.ts +9 -0
  237. package/out/zql/src/ivm/change-index-enum.d.ts.map +1 -0
  238. package/out/zql/src/ivm/change-index.d.ts +5 -0
  239. package/out/zql/src/ivm/change-index.d.ts.map +1 -0
  240. package/out/zql/src/ivm/change-type-enum.d.ts +9 -0
  241. package/out/zql/src/ivm/change-type-enum.d.ts.map +1 -0
  242. package/out/zql/src/ivm/change-type.d.ts +5 -0
  243. package/out/zql/src/ivm/change-type.d.ts.map +1 -0
  244. package/out/zql/src/ivm/change.d.ts +20 -22
  245. package/out/zql/src/ivm/change.d.ts.map +1 -1
  246. package/out/zql/src/ivm/change.js +33 -0
  247. package/out/zql/src/ivm/change.js.map +1 -0
  248. package/out/zql/src/ivm/exists.d.ts.map +1 -1
  249. package/out/zql/src/ivm/exists.js +27 -38
  250. package/out/zql/src/ivm/exists.js.map +1 -1
  251. package/out/zql/src/ivm/fan-in.d.ts +3 -2
  252. package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
  253. package/out/zql/src/ivm/fan-in.js.map +1 -1
  254. package/out/zql/src/ivm/fan-out.d.ts +1 -1
  255. package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
  256. package/out/zql/src/ivm/fan-out.js +1 -1
  257. package/out/zql/src/ivm/fan-out.js.map +1 -1
  258. package/out/zql/src/ivm/filter-operators.d.ts +3 -3
  259. package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
  260. package/out/zql/src/ivm/filter-operators.js.map +1 -1
  261. package/out/zql/src/ivm/filter-push.d.ts.map +1 -1
  262. package/out/zql/src/ivm/filter-push.js +7 -7
  263. package/out/zql/src/ivm/filter-push.js.map +1 -1
  264. package/out/zql/src/ivm/filter.d.ts +1 -1
  265. package/out/zql/src/ivm/filter.d.ts.map +1 -1
  266. package/out/zql/src/ivm/filter.js.map +1 -1
  267. package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
  268. package/out/zql/src/ivm/flipped-join.js +49 -58
  269. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  270. package/out/zql/src/ivm/join-utils.d.ts +2 -6
  271. package/out/zql/src/ivm/join-utils.d.ts.map +1 -1
  272. package/out/zql/src/ivm/join-utils.js +25 -25
  273. package/out/zql/src/ivm/join-utils.js.map +1 -1
  274. package/out/zql/src/ivm/join.d.ts.map +1 -1
  275. package/out/zql/src/ivm/join.js +32 -51
  276. package/out/zql/src/ivm/join.js.map +1 -1
  277. package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts +1 -1
  278. package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts.map +1 -1
  279. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +5 -10
  280. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
  281. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  282. package/out/zql/src/ivm/memory-source.js +52 -60
  283. package/out/zql/src/ivm/memory-source.js.map +1 -1
  284. package/out/zql/src/ivm/operator.d.ts +1 -1
  285. package/out/zql/src/ivm/operator.d.ts.map +1 -1
  286. package/out/zql/src/ivm/operator.js +2 -4
  287. package/out/zql/src/ivm/operator.js.map +1 -1
  288. package/out/zql/src/ivm/push-accumulated.d.ts +3 -2
  289. package/out/zql/src/ivm/push-accumulated.d.ts.map +1 -1
  290. package/out/zql/src/ivm/push-accumulated.js +98 -122
  291. package/out/zql/src/ivm/push-accumulated.js.map +1 -1
  292. package/out/zql/src/ivm/skip-yields.d.ts +4 -0
  293. package/out/zql/src/ivm/skip-yields.d.ts.map +1 -0
  294. package/out/zql/src/ivm/skip-yields.js +33 -0
  295. package/out/zql/src/ivm/skip-yields.js.map +1 -0
  296. package/out/zql/src/ivm/skip.d.ts +1 -1
  297. package/out/zql/src/ivm/skip.d.ts.map +1 -1
  298. package/out/zql/src/ivm/skip.js +2 -2
  299. package/out/zql/src/ivm/skip.js.map +1 -1
  300. package/out/zql/src/ivm/source-change-index-enum.d.ts +7 -0
  301. package/out/zql/src/ivm/source-change-index-enum.d.ts.map +1 -0
  302. package/out/zql/src/ivm/source-change-index.d.ts +5 -0
  303. package/out/zql/src/ivm/source-change-index.d.ts.map +1 -0
  304. package/out/zql/src/ivm/source.d.ts +11 -13
  305. package/out/zql/src/ivm/source.d.ts.map +1 -1
  306. package/out/zql/src/ivm/source.js +26 -0
  307. package/out/zql/src/ivm/source.js.map +1 -0
  308. package/out/zql/src/ivm/take.d.ts.map +1 -1
  309. package/out/zql/src/ivm/take.js +27 -50
  310. package/out/zql/src/ivm/take.js.map +1 -1
  311. package/out/zql/src/ivm/union-fan-in.d.ts +2 -1
  312. package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
  313. package/out/zql/src/ivm/union-fan-in.js +3 -3
  314. package/out/zql/src/ivm/union-fan-in.js.map +1 -1
  315. package/out/zql/src/ivm/union-fan-out.d.ts.map +1 -1
  316. package/out/zql/src/ivm/union-fan-out.js +1 -1
  317. package/out/zql/src/ivm/union-fan-out.js.map +1 -1
  318. package/out/zql/src/ivm/view-apply-change.js +1 -1
  319. package/out/zql/src/planner/planner-debug.d.ts +2 -2
  320. package/out/zql/src/planner/planner-debug.d.ts.map +1 -1
  321. package/out/zql/src/planner/planner-debug.js.map +1 -1
  322. package/out/zql/src/planner/planner-graph.d.ts +1 -1
  323. package/out/zql/src/planner/planner-graph.d.ts.map +1 -1
  324. package/out/zql/src/planner/planner-graph.js.map +1 -1
  325. package/out/zqlite/src/internal/sql-inline.d.ts.map +1 -1
  326. package/out/zqlite/src/internal/sql-inline.js.map +1 -1
  327. package/out/zqlite/src/query-builder.d.ts.map +1 -1
  328. package/out/zqlite/src/query-builder.js.map +1 -1
  329. package/out/zqlite/src/table-source.d.ts.map +1 -1
  330. package/out/zqlite/src/table-source.js +11 -11
  331. package/out/zqlite/src/table-source.js.map +1 -1
  332. package/package.json +99 -93
@@ -1,9 +1,9 @@
1
1
  import { literalUnion, valita_exports } from "../../shared/src/valita.js";
2
2
  import { jsonSchema } from "../../shared/src/json-schema.js";
3
- import { mutationIDSchema } from "./mutation-id.js";
4
3
  import { AuthInvalidated, ClientNotFound, Internal, InvalidConnectionRequest, InvalidConnectionRequestBaseCookie, InvalidConnectionRequestClientDeleted, InvalidConnectionRequestLastMutationID, InvalidMessage, InvalidPush, MutationFailed, MutationRateLimited, PushFailed, Rebalance, Rehome, SchemaVersionNotSupported, ServerOverloaded, TransformFailed, Unauthorized, VersionNotSupported } from "./error-kind-enum.js";
5
4
  import { Server, ZeroCache } from "./error-origin-enum.js";
6
5
  import { Database, HTTP, Internal as Internal$1, OutOfOrderMutation, Parse, Timeout, UnsupportedPushVersion } from "./error-reason-enum.js";
6
+ import { mutationIDSchema } from "./mutation-id.js";
7
7
  //#region ../zero-protocol/src/error.ts
8
8
  var basicErrorKindSchema = literalUnion(AuthInvalidated, ClientNotFound, InvalidConnectionRequest, InvalidConnectionRequestBaseCookie, InvalidConnectionRequestLastMutationID, InvalidConnectionRequestClientDeleted, InvalidMessage, InvalidPush, MutationRateLimited, MutationFailed, Unauthorized, VersionNotSupported, SchemaVersionNotSupported, Internal);
9
9
  var basicErrorBodySchema = valita_exports.object({
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","names":[],"sources":["../../../../zero-protocol/src/error.ts"],"sourcesContent":["import {jsonSchema} from '../../shared/src/json-schema.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport {mutationIDSchema} from './mutation-id.ts';\nimport {ErrorKind} from './error-kind.ts';\nimport {ErrorOrigin} from './error-origin.ts';\nimport {ErrorReason} from './error-reason.ts';\n\nconst basicErrorKindSchema = v.literalUnion(\n ErrorKind.AuthInvalidated,\n ErrorKind.ClientNotFound,\n ErrorKind.InvalidConnectionRequest,\n ErrorKind.InvalidConnectionRequestBaseCookie,\n ErrorKind.InvalidConnectionRequestLastMutationID,\n ErrorKind.InvalidConnectionRequestClientDeleted,\n ErrorKind.InvalidMessage,\n ErrorKind.InvalidPush,\n ErrorKind.MutationRateLimited,\n ErrorKind.MutationFailed,\n ErrorKind.Unauthorized,\n ErrorKind.VersionNotSupported,\n ErrorKind.SchemaVersionNotSupported,\n ErrorKind.Internal,\n);\n\nconst basicErrorBodySchema = v.object({\n kind: basicErrorKindSchema,\n message: v.string(),\n // this is optional for backwards compatibility\n origin: v.literalUnion(ErrorOrigin.Server, ErrorOrigin.ZeroCache).optional(),\n});\n\nconst backoffErrorKindSchema = v.literalUnion(\n ErrorKind.Rebalance,\n ErrorKind.Rehome,\n ErrorKind.ServerOverloaded,\n);\n\nconst backoffBodySchema = v.object({\n kind: backoffErrorKindSchema,\n message: v.string(),\n minBackoffMs: v.number().optional(),\n maxBackoffMs: v.number().optional(),\n // Query parameters to send in the next reconnect. In the event of\n // a conflict, these will be overridden by the parameters used by\n // the client; it is the responsibility of the server to avoid\n // parameter name conflicts.\n //\n // The parameters will only be added to the immediately following\n // reconnect, and not after that.\n reconnectParams: v.record(v.string()).optional(),\n origin: v.literal(ErrorOrigin.ZeroCache).optional(),\n});\n\nconst pushFailedErrorKindSchema = v.literal(ErrorKind.PushFailed);\nconst transformFailedErrorKindSchema = v.literal(ErrorKind.TransformFailed);\n\nexport const errorKindSchema: v.Type<ErrorKind> = v.union(\n basicErrorKindSchema,\n backoffErrorKindSchema,\n pushFailedErrorKindSchema,\n transformFailedErrorKindSchema,\n);\n\nconst pushFailedBaseSchema = v.object({\n kind: pushFailedErrorKindSchema,\n details: jsonSchema.optional(),\n /**\n * The mutationIDs of the mutations that failed to process.\n * This can be a subset of the mutationIDs in the request.\n */\n mutationIDs: v.array(mutationIDSchema),\n message: v.string(),\n});\n\nexport const pushFailedBodySchema = v.union(\n pushFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.Server),\n reason: v.literalUnion(\n ErrorReason.Database,\n ErrorReason.Parse,\n ErrorReason.OutOfOrderMutation,\n ErrorReason.UnsupportedPushVersion,\n ErrorReason.Internal,\n ),\n }),\n pushFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.ZeroCache),\n reason: v.literal(ErrorReason.HTTP),\n status: v.number(),\n bodyPreview: v.string().optional(),\n }),\n pushFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.ZeroCache),\n reason: v.literalUnion(\n ErrorReason.Timeout,\n ErrorReason.Parse,\n ErrorReason.Internal,\n ),\n }),\n);\n\nconst transformFailedBaseSchema = v.object({\n kind: transformFailedErrorKindSchema,\n details: jsonSchema.optional(),\n /**\n * The queryIDs of the queries that failed to transform.\n */\n queryIDs: v.array(v.string()),\n message: v.string(),\n});\n\nexport const transformFailedBodySchema = v.union(\n transformFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.Server),\n reason: v.literalUnion(\n ErrorReason.Database,\n ErrorReason.Parse,\n ErrorReason.Internal,\n ),\n }),\n transformFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.ZeroCache),\n reason: v.literal(ErrorReason.HTTP),\n status: v.number(),\n bodyPreview: v.string().optional(),\n }),\n transformFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.ZeroCache),\n reason: v.literalUnion(\n ErrorReason.Timeout,\n ErrorReason.Parse,\n ErrorReason.Internal,\n ),\n }),\n);\n\nexport const errorBodySchema = v.union(\n basicErrorBodySchema,\n backoffBodySchema,\n pushFailedBodySchema,\n transformFailedBodySchema,\n);\n\nexport type BackoffBody = v.Infer<typeof backoffBodySchema>;\nexport type PushFailedBody = v.Infer<typeof pushFailedBodySchema>;\nexport type TransformFailedBody = v.Infer<typeof transformFailedBodySchema>;\nexport type ErrorBody = v.Infer<typeof errorBodySchema>;\n\nexport const errorMessageSchema: v.Type<ErrorMessage> = v.tuple([\n v.literal('error'),\n errorBodySchema,\n]);\n\nexport type ErrorMessage = ['error', ErrorBody];\n\n/**\n * Represents an error used across zero-client, zero-cache, and zero-server.\n */\nexport class ProtocolError<\n const T extends ErrorBody = ErrorBody,\n> extends Error {\n readonly errorBody: T;\n\n constructor(errorBody: T, options?: ErrorOptions) {\n super(errorBody.message, options);\n this.name = 'ProtocolError';\n this.errorBody = errorBody;\n }\n\n get kind(): T['kind'] {\n return this.errorBody.kind;\n }\n}\n\nexport function isProtocolError(error: unknown): error is ProtocolError {\n return error instanceof ProtocolError;\n}\n"],"mappings":";;;;;;;AAOA,IAAM,uBAAuB,aAC3B,iBACA,gBACA,0BACA,oCACA,wCACA,uCACA,gBACA,aACA,qBACA,gBACA,cACA,qBACA,2BACA,SACD;AAED,IAAM,uBAAuB,eAAE,OAAO;CACpC,MAAM;CACN,SAAS,eAAE,QAAQ;CAEnB,QAAQ,aAAe,QAAoB,UAAsB,CAAC,UAAU;CAC7E,CAAC;AAEF,IAAM,yBAAyB,aAC7B,WACA,QACA,iBACD;AAED,IAAM,oBAAoB,eAAE,OAAO;CACjC,MAAM;CACN,SAAS,eAAE,QAAQ;CACnB,cAAc,eAAE,QAAQ,CAAC,UAAU;CACnC,cAAc,eAAE,QAAQ,CA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;CACnC,CAAC,EACF,0BAA0B,OAAO;CAC/B,QAAQ,eAAE,QAAQ,UAAsB;CACxC,QAAQ,aACN,SACA,OACA,WACD;CACF,CAAC,CACH;AAED,IAAa,kBAAkB,eAAE,MAC/B,sBACA,mBACA,sBACA,0BACD;AAOD,IAAa,qBAA2C,eAAE,MAAM,CAC9D,eAAE,QAAQ,QAAQ,EAClB,gBACD,CAAC;;;;AAOF,IAAa,gBAAb,cAEU,MAAM;CACd;CAEA,YAAY,WAAc,SAAwB;AAChD,QAAM,UAAU,SAAS,QAAQ;AACjC,OAAK,OAAO;AACZ,OAAK,YAAY;;CAGnB,IAAI,OAAkB;AACpB,SAAO,KAAK,UAAU;;;AAI1B,SAAgB,gBAAgB,OAAwC;AACtE,QAAO,iBAAiB"}
1
+ {"version":3,"file":"error.js","names":[],"sources":["../../../../zero-protocol/src/error.ts"],"sourcesContent":["import {jsonSchema} from '../../shared/src/json-schema.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport {ErrorKind} from './error-kind.ts';\nimport {ErrorOrigin} from './error-origin.ts';\nimport {ErrorReason} from './error-reason.ts';\nimport {mutationIDSchema} from './mutation-id.ts';\n\nconst basicErrorKindSchema = v.literalUnion(\n ErrorKind.AuthInvalidated,\n ErrorKind.ClientNotFound,\n ErrorKind.InvalidConnectionRequest,\n ErrorKind.InvalidConnectionRequestBaseCookie,\n ErrorKind.InvalidConnectionRequestLastMutationID,\n ErrorKind.InvalidConnectionRequestClientDeleted,\n ErrorKind.InvalidMessage,\n ErrorKind.InvalidPush,\n ErrorKind.MutationRateLimited,\n ErrorKind.MutationFailed,\n ErrorKind.Unauthorized,\n ErrorKind.VersionNotSupported,\n ErrorKind.SchemaVersionNotSupported,\n ErrorKind.Internal,\n);\n\nconst basicErrorBodySchema = v.object({\n kind: basicErrorKindSchema,\n message: v.string(),\n // this is optional for backwards compatibility\n origin: v.literalUnion(ErrorOrigin.Server, ErrorOrigin.ZeroCache).optional(),\n});\n\nconst backoffErrorKindSchema = v.literalUnion(\n ErrorKind.Rebalance,\n ErrorKind.Rehome,\n ErrorKind.ServerOverloaded,\n);\n\nconst backoffBodySchema = v.object({\n kind: backoffErrorKindSchema,\n message: v.string(),\n minBackoffMs: v.number().optional(),\n maxBackoffMs: v.number().optional(),\n // Query parameters to send in the next reconnect. In the event of\n // a conflict, these will be overridden by the parameters used by\n // the client; it is the responsibility of the server to avoid\n // parameter name conflicts.\n //\n // The parameters will only be added to the immediately following\n // reconnect, and not after that.\n reconnectParams: v.record(v.string()).optional(),\n origin: v.literal(ErrorOrigin.ZeroCache).optional(),\n});\n\nconst pushFailedErrorKindSchema = v.literal(ErrorKind.PushFailed);\nconst transformFailedErrorKindSchema = v.literal(ErrorKind.TransformFailed);\n\nexport const errorKindSchema: v.Type<ErrorKind> = v.union(\n basicErrorKindSchema,\n backoffErrorKindSchema,\n pushFailedErrorKindSchema,\n transformFailedErrorKindSchema,\n);\n\nconst pushFailedBaseSchema = v.object({\n kind: pushFailedErrorKindSchema,\n details: jsonSchema.optional(),\n /**\n * The mutationIDs of the mutations that failed to process.\n * This can be a subset of the mutationIDs in the request.\n */\n mutationIDs: v.array(mutationIDSchema),\n message: v.string(),\n});\n\nexport const pushFailedBodySchema = v.union(\n pushFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.Server),\n reason: v.literalUnion(\n ErrorReason.Database,\n ErrorReason.Parse,\n ErrorReason.OutOfOrderMutation,\n ErrorReason.UnsupportedPushVersion,\n ErrorReason.Internal,\n ),\n }),\n pushFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.ZeroCache),\n reason: v.literal(ErrorReason.HTTP),\n status: v.number(),\n bodyPreview: v.string().optional(),\n }),\n pushFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.ZeroCache),\n reason: v.literalUnion(\n ErrorReason.Timeout,\n ErrorReason.Parse,\n ErrorReason.Internal,\n ),\n }),\n);\n\nconst transformFailedBaseSchema = v.object({\n kind: transformFailedErrorKindSchema,\n details: jsonSchema.optional(),\n /**\n * The queryIDs of the queries that failed to transform.\n */\n queryIDs: v.array(v.string()),\n message: v.string(),\n});\n\nexport const transformFailedBodySchema = v.union(\n transformFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.Server),\n reason: v.literalUnion(\n ErrorReason.Database,\n ErrorReason.Parse,\n ErrorReason.Internal,\n ),\n }),\n transformFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.ZeroCache),\n reason: v.literal(ErrorReason.HTTP),\n status: v.number(),\n bodyPreview: v.string().optional(),\n }),\n transformFailedBaseSchema.extend({\n origin: v.literal(ErrorOrigin.ZeroCache),\n reason: v.literalUnion(\n ErrorReason.Timeout,\n ErrorReason.Parse,\n ErrorReason.Internal,\n ),\n }),\n);\n\nexport const errorBodySchema = v.union(\n basicErrorBodySchema,\n backoffBodySchema,\n pushFailedBodySchema,\n transformFailedBodySchema,\n);\n\nexport type BackoffBody = v.Infer<typeof backoffBodySchema>;\nexport type PushFailedBody = v.Infer<typeof pushFailedBodySchema>;\nexport type TransformFailedBody = v.Infer<typeof transformFailedBodySchema>;\nexport type ErrorBody = v.Infer<typeof errorBodySchema>;\n\nexport const errorMessageSchema: v.Type<ErrorMessage> = v.tuple([\n v.literal('error'),\n errorBodySchema,\n]);\n\nexport type ErrorMessage = ['error', ErrorBody];\n\n/**\n * Represents an error used across zero-client, zero-cache, and zero-server.\n */\nexport class ProtocolError<\n const T extends ErrorBody = ErrorBody,\n> extends Error {\n readonly errorBody: T;\n\n constructor(errorBody: T, options?: ErrorOptions) {\n super(errorBody.message, options);\n this.name = 'ProtocolError';\n this.errorBody = errorBody;\n }\n\n get kind(): T['kind'] {\n return this.errorBody.kind;\n }\n}\n\nexport function isProtocolError(error: unknown): error is ProtocolError {\n return error instanceof ProtocolError;\n}\n"],"mappings":";;;;;;;AAOA,IAAM,uBAAuB,aAC3B,iBACA,gBACA,0BACA,oCACA,wCACA,uCACA,gBACA,aACA,qBACA,gBACA,cACA,qBACA,2BACA,SACD;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S,eAAE,QAAQ;CACpB,CAAC;AAEF,IAAa,4BAA4B,eAAE,MACzC,0BAA0B,OAAO;CAC/B,QAAQ,eAAE,QAAQ,OAAmB;CACrC,QAAQ,aACN,UACA,OACA,WACD;CACF,CAAC,EACF,0BAA0B,OAAO;CAC/B,QAAQ,eAAE,QAAQ,UAAsB;CACxC,QAAQ,eAAE,QAAQ,KAAiB;CACnC,QAAQ,eAAE,QAAQ;CAClB,aAAa,eAAE,QAAQ,CAAC,UAAU;CACnC,CAAC,EACF,0BAA0B,OAAO;CAC/B,QAAQ,eAAE,QAAQ,UAAsB;CACxC,QAAQ,aACN,SACA,OACA,WACD;CACF,CAAC,CACH;AAED,IAAa,kBAAkB,eAAE,MAC/B,sBACA,mBACA,sBACA,0BACD;AAOD,IAAa,qBAA2C,eAAE,MAAM,CAC9D,eAAE,QAAQ,QAAQ,EAClB,gBACD,CAAC;;;;AAOF,IAAa,gBAAb,cAEU,MAAM;CACd;CAEA,YAAY,WAAc,SAAwB;AAChD,QAAM,UAAU,SAAS,QAAQ;AACjC,OAAK,OAAO;AACZ,OAAK,YAAY;;CAGnB,IAAI,OAAkB;AACpB,SAAO,KAAK,UAAU;;;AAI1B,SAAgB,gBAAgB,OAAwC;AACtE,QAAO,iBAAiB"}
@@ -3,7 +3,7 @@ import "../../shared/src/must.js";
3
3
  import "../../zql/src/query/query-internals.js";
4
4
  import "../../zql/src/query/query-impl.js";
5
5
  import "../../zql/src/query/query-registry.js";
6
- import "../../zql/src/ivm/operator.js";
6
+ import "../../zql/src/ivm/skip-yields.js";
7
7
  import "../../zql/src/ivm/stream.js";
8
8
  import "../../zql/src/ivm/view-apply-change.js";
9
9
  import "../../zql/src/query/ttl.js";
@@ -3,7 +3,7 @@ import "../../shared/src/must.js";
3
3
  import "../../zql/src/query/query-internals.js";
4
4
  import "../../zql/src/query/query-impl.js";
5
5
  import "../../zql/src/query/query-registry.js";
6
- import "../../zql/src/ivm/operator.js";
6
+ import "../../zql/src/ivm/skip-yields.js";
7
7
  import "../../zql/src/ivm/stream.js";
8
8
  import "../../zql/src/ivm/view-apply-change.js";
9
9
  import "../../zql/src/query/ttl.js";
@@ -1 +1 @@
1
- {"version":3,"file":"solid-view.d.ts","sourceRoot":"","sources":["../../../../zero-solid/src/solid-view.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,gBAAgB,EAAC,MAAM,gBAAgB,CAAC;AAQzE,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,KAAK,EACV,KAAK,YAAY,EACjB,KAAK,MAAM,EACX,KAAK,KAAK,EAEV,KAAK,MAAM,EACX,KAAK,KAAK,EAEV,KAAK,kBAAkB,EACvB,KAAK,MAAM,EAEX,KAAK,GAAG,EACT,MAAM,WAAW,CAAC;AAEnB,MAAM,MAAM,KAAK,GAAG,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;AAEhD,eAAO,MAAM,QAAQ,EAAE,kBAAsD,CAAC;AAC9E,eAAO,MAAM,OAAO,EAAE,kBAAqD,CAAC;AAE5E,qBAAa,SAAU,YAAW,MAAM;;gBAqBpC,KAAK,EAAE,KAAK,EACZ,mBAAmB,EAAE,CAAC,EAAE,EAAE,MAAM,IAAI,KAAK,IAAI,EAC7C,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,IAAI,EACrB,aAAa,EAAE,IAAI,GAAG,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,EAClD,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EAC7B,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACjC,KAAK,EAAE,MAAM,IAAI;IAiEnB,OAAO,IAAI,IAAI;IA2Bf,IAAI,CAAC,MAAM,EAAE,MAAM;IAqDnB,SAAS,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI;CAG1B;AA8CD,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACjC,KAAK,CAAC,EAAE,MAAM,IAAI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AAE,MAAM,IAAI;IAiEnB,OAAO,IAAI,IAAI;IA2Bf,IAAI,CAAC,MAAM,EAAE,MAAM;IAwDnB,SAAS,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI;CAG1B;AAsDD,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACjC,KAAK,CAAC,EAAE,MAAM,IAAI,IAGhB,MAAM,SAAS,MAAM,OAAO,CAAC,QAAQ,CAAC,GAAG,MAAM,EAC/C,OAAO,SAAS,MAAM,EACtB,OAAO,UAEC,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,SAChC,KAAK,UACJ,MAAM,aACH,MAAM,IAAI,uBACA,CAAC,EAAE,EAAE,MAAM,IAAI,KAAK,IAAI,iBAC9B,IAAI,GAAG,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,aACvC,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,eAiBhC"}
@@ -1,5 +1,5 @@
1
1
  import { emptyArray } from "../../shared/src/sentinels.js";
2
- import { skipYields } from "../../zql/src/ivm/operator.js";
2
+ import { skipYields } from "../../zql/src/ivm/skip-yields.js";
3
3
  import { applyChange, idSymbol } from "../../zql/src/ivm/view-apply-change.js";
4
4
  import "./zero.js";
5
5
  import "./bindings.js";
@@ -69,7 +69,7 @@ var SolidView = class {
69
69
  }
70
70
  };
71
71
  push(change) {
72
- if (this.#builderRoot) this.#applyChangeToRoot(change, this.#builderRoot);
72
+ if (this.#builderRoot) this.#applyChangeToRoot(materializeRelationships(change), this.#builderRoot);
73
73
  else this.#pendingChanges.push(materializeRelationships(change));
74
74
  return emptyArray;
75
75
  }
@@ -93,27 +93,27 @@ var SolidView = class {
93
93
  }
94
94
  };
95
95
  function materializeRelationships(change) {
96
- switch (change.type) {
97
- case "add": return {
96
+ switch (change[0]) {
97
+ case 0: return {
98
98
  type: "add",
99
- node: materializeNodeRelationships(change.node)
99
+ node: materializeNodeRelationships(change[1])
100
100
  };
101
- case "remove": return {
101
+ case 1: return {
102
102
  type: "remove",
103
- node: materializeNodeRelationships(change.node)
103
+ node: materializeNodeRelationships(change[1])
104
104
  };
105
- case "child": return {
105
+ case 3: return {
106
106
  type: "child",
107
- node: { row: change.node.row },
107
+ node: { row: change[1].row },
108
108
  child: {
109
- relationshipName: change.child.relationshipName,
110
- change: materializeRelationships(change.child.change)
109
+ relationshipName: change[2].relationshipName,
110
+ change: materializeRelationships(change[2].change)
111
111
  }
112
112
  };
113
- case "edit": return {
113
+ case 2: return {
114
114
  type: "edit",
115
- node: { row: change.node.row },
116
- oldNode: { row: change.oldNode.row }
115
+ node: { row: change[1].row },
116
+ oldNode: { row: change[2].row }
117
117
  };
118
118
  }
119
119
  }
@@ -1 +1 @@
1
- {"version":3,"file":"solid-view.js","names":["#input","#format","#onDestroy","#retry","#updateTTL","#onTransactionCommit","#createEmptyRoot","#applyChangesToRoot","#setState","#makeError","#builderRoot","#applyChanges","#pendingChanges","#applyChangeToRoot"],"sources":["../../../../zero-solid/src/solid-view.ts"],"sourcesContent":["import {produce, reconcile, type SetStoreFunction} from 'solid-js/store';\nimport {emptyArray} from '../../shared/src/sentinels.ts';\nimport {\n applyChange,\n idSymbol,\n skipYields,\n type ViewChange,\n} from './bindings.ts';\nimport {\n type AnyViewFactory,\n type Change,\n type Entry,\n type ErroredQuery,\n type Format,\n type Input,\n type Node,\n type Output,\n type Query,\n type QueryErrorDetails,\n type QueryResultDetails,\n type Schema,\n type Stream,\n type TTL,\n} from './zero.ts';\n\nexport type State = [Entry, QueryResultDetails];\n\nexport const COMPLETE: QueryResultDetails = Object.freeze({type: 'complete'});\nexport const UNKNOWN: QueryResultDetails = Object.freeze({type: 'unknown'});\n\nexport class SolidView implements Output {\n readonly #input: Input;\n readonly #format: Format;\n readonly #onDestroy: () => void;\n readonly #retry: () => void;\n\n #setState: SetStoreFunction<State>;\n\n // Optimization: if the store is currently empty we build up\n // the view on a plain old JS object stored at #builderRoot, and return\n // that for the new state on transaction commit. This avoids building up\n // large views from scratch via solid produce. The proxy object used by\n // solid produce is slow and in this case we don't care about solid tracking\n // the fine grained changes (everything has changed, it's all new). For a\n // test case with a view with 3000 rows, each row having 2 children, this\n // optimization reduced #applyChanges time from 743ms to 133ms.\n #builderRoot: Entry | undefined;\n #pendingChanges: ViewChange[] = [];\n readonly #updateTTL: (ttl: TTL) => void;\n\n constructor(\n input: Input,\n onTransactionCommit: (cb: () => void) => void,\n format: Format,\n onDestroy: () => void,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n setState: SetStoreFunction<State>,\n retry: () => void,\n ) {\n this.#input = input;\n onTransactionCommit(this.#onTransactionCommit);\n this.#format = format;\n this.#onDestroy = onDestroy;\n this.#updateTTL = updateTTL;\n this.#retry = retry;\n\n input.setOutput(this);\n\n const initialRoot = this.#createEmptyRoot();\n this.#applyChangesToRoot(\n skipYields(input.fetch({})),\n node => ({type: 'add', node}),\n initialRoot,\n );\n\n this.#setState = setState;\n this.#setState(\n reconcile(\n [\n initialRoot,\n queryComplete === true\n ? COMPLETE\n : 'error' in queryComplete\n ? this.#makeError(queryComplete)\n : UNKNOWN,\n ],\n {\n // solidjs's types want a string, but a symbol works\n key: idSymbol as unknown as string,\n },\n ),\n );\n\n if (isEmptyRoot(initialRoot)) {\n this.#builderRoot = this.#createEmptyRoot();\n }\n\n if (queryComplete !== true && !('error' in queryComplete)) {\n void queryComplete\n .then(() => {\n this.#setState(prev => [prev[0], COMPLETE]);\n })\n .catch((error: ErroredQuery) => {\n this.#setState(prev => [prev[0], this.#makeError(error)]);\n });\n }\n }\n\n #makeError(error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry: this.#retry,\n refetch: this.#retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n }\n\n destroy(): void {\n this.#onDestroy();\n }\n\n #onTransactionCommit = () => {\n const builderRoot = this.#builderRoot;\n if (builderRoot) {\n if (!isEmptyRoot(builderRoot)) {\n this.#setState(\n 0,\n reconcile(builderRoot, {\n // solidjs's types want a string, but a symbol works\n key: idSymbol as unknown as string,\n }),\n );\n this.#setState(prev => [builderRoot, prev[1]]);\n this.#builderRoot = undefined;\n }\n } else {\n try {\n this.#applyChanges(this.#pendingChanges, c => c);\n } finally {\n this.#pendingChanges = [];\n }\n }\n };\n\n push(change: Change) {\n // Delay updating the solid store state until the transaction commit\n // (because each update of the solid store is quite expensive). If\n // this.#builderRoot is defined apply the changes to it (we are building\n // from an empty root), otherwise queue the changes to be applied\n // using produce at the end of the transaction but read the relationships\n // now as they are only valid to read when the push is received.\n if (this.#builderRoot) {\n this.#applyChangeToRoot(change, this.#builderRoot);\n } else {\n this.#pendingChanges.push(materializeRelationships(change));\n }\n return emptyArray;\n }\n\n #applyChanges<T>(changes: Iterable<T>, mapper: (v: T) => ViewChange): void {\n this.#setState(\n produce((draftState: State) => {\n this.#applyChangesToRoot<T>(changes, mapper, draftState[0]);\n if (isEmptyRoot(draftState[0])) {\n this.#builderRoot = this.#createEmptyRoot();\n }\n }),\n );\n }\n\n #applyChangesToRoot<T>(\n changes: Iterable<T>,\n mapper: (v: T) => ViewChange,\n root: Entry,\n ) {\n for (const change of changes) {\n this.#applyChangeToRoot(mapper(change), root);\n }\n }\n\n #applyChangeToRoot(change: ViewChange, root: Entry) {\n applyChange(\n root,\n change,\n this.#input.getSchema(),\n '',\n this.#format,\n true /* withIDs */,\n );\n }\n\n #createEmptyRoot(): Entry {\n return {\n '': this.#format.singular ? undefined : [],\n };\n }\n\n updateTTL(ttl: TTL): void {\n this.#updateTTL(ttl);\n }\n}\n\nfunction materializeRelationships(change: Change): ViewChange {\n switch (change.type) {\n case 'add':\n return {type: 'add', node: materializeNodeRelationships(change.node)};\n case 'remove':\n return {type: 'remove', node: materializeNodeRelationships(change.node)};\n case 'child':\n return {\n type: 'child',\n node: {row: change.node.row},\n child: {\n relationshipName: change.child.relationshipName,\n change: materializeRelationships(change.child.change),\n },\n };\n case 'edit':\n return {\n type: 'edit',\n node: {row: change.node.row},\n oldNode: {row: change.oldNode.row},\n };\n }\n}\n\nfunction materializeNodeRelationships(node: Node): Node {\n const relationships: Record<string, () => Stream<Node>> = {};\n for (const relationship in node.relationships) {\n const materialized: Node[] = [];\n for (const n of skipYields(node.relationships[relationship]())) {\n materialized.push(materializeNodeRelationships(n));\n }\n relationships[relationship] = () => materialized;\n }\n return {\n row: node.row,\n relationships,\n };\n}\n\nfunction isEmptyRoot(entry: Entry) {\n const data = entry[''];\n return data === undefined || (Array.isArray(data) && data.length === 0);\n}\n\nexport function createSolidViewFactory(\n setState: SetStoreFunction<State>,\n retry?: () => void,\n) {\n function solidViewFactory<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n _query: Query<TTable, TSchema, TReturn>,\n input: Input,\n format: Format,\n onDestroy: () => void,\n onTransactionCommit: (cb: () => void) => void,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n return new SolidView(\n input,\n onTransactionCommit,\n format,\n onDestroy,\n queryComplete,\n updateTTL,\n setState,\n retry || (() => {}),\n );\n }\n\n solidViewFactory satisfies AnyViewFactory;\n\n return solidViewFactory;\n}\n"],"mappings":";;;;;;;AA2BA,IAAa,WAA+B,OAAO,OAAO,EAAC,MAAM,YAAW,CAAC;AAC7E,IAAa,UAA8B,OAAO,OAAO,EAAC,MAAM,WAAU,CAAC;AAE3E,IAAa,YAAb,MAAyC;CACvC;CACA;CACA;CACA;CAEA;CAUA;CACA,kBAAgC,EAAE;CAClC;CAEA,YACE,OACA,qBACA,QACA,WACA,eACA,WACA,UACA,OACA;AACA,QAAA,QAAc;AACd,sBAAoB,MAAA,oBAA0B;AAC9C,QAAA,SAAe;AACf,QAAA,YAAkB;AAClB,QAAA,YAAkB;AAClB,QAAA,QAAc;AAEd,QAAM,UAAU,KAAK;EAErB,MAAM,cAAc,MAAA,iB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B;;AAEtC,QAAO;EACL,KAAK,KAAK;EACV;EACD;;AAGH,SAAS,YAAY,OAAc;CACjC,MAAM,OAAO,MAAM;AACnB,QAAO,SAAS,KAAA,KAAc,MAAM,QAAQ,KAAK,IAAI,KAAK,WAAW;;AAGvE,SAAgB,uBACd,UACA,OACA;CACA,SAAS,iBAKP,QACA,OACA,QACA,WACA,qBACA,eACA,WACA;AACA,SAAO,IAAI,UACT,OACA,qBACA,QACA,WACA,eACA,WACA,UACA,gBAAgB,IACjB;;AAKH,QAAO"}
1
+ {"version":3,"file":"solid-view.js","names":["#input","#format","#onDestroy","#retry","#updateTTL","#onTransactionCommit","#createEmptyRoot","#applyChangesToRoot","#setState","#makeError","#builderRoot","#applyChanges","#pendingChanges","#applyChangeToRoot"],"sources":["../../../../zero-solid/src/solid-view.ts"],"sourcesContent":["import {produce, reconcile, type SetStoreFunction} from 'solid-js/store';\nimport {emptyArray} from '../../shared/src/sentinels.ts';\nimport {ChangeIndex} from '../../zql/src/ivm/change-index.ts';\nimport {ChangeType} from '../../zql/src/ivm/change-type.ts';\nimport {\n applyChange,\n idSymbol,\n skipYields,\n type ViewChange,\n} from './bindings.ts';\nimport {\n type AnyViewFactory,\n type Change,\n type Entry,\n type ErroredQuery,\n type Format,\n type Input,\n type Node,\n type Output,\n type Query,\n type QueryErrorDetails,\n type QueryResultDetails,\n type Schema,\n type Stream,\n type TTL,\n} from './zero.ts';\n\nexport type State = [Entry, QueryResultDetails];\n\nexport const COMPLETE: QueryResultDetails = Object.freeze({type: 'complete'});\nexport const UNKNOWN: QueryResultDetails = Object.freeze({type: 'unknown'});\n\nexport class SolidView implements Output {\n readonly #input: Input;\n readonly #format: Format;\n readonly #onDestroy: () => void;\n readonly #retry: () => void;\n\n #setState: SetStoreFunction<State>;\n\n // Optimization: if the store is currently empty we build up\n // the view on a plain old JS object stored at #builderRoot, and return\n // that for the new state on transaction commit. This avoids building up\n // large views from scratch via solid produce. The proxy object used by\n // solid produce is slow and in this case we don't care about solid tracking\n // the fine grained changes (everything has changed, it's all new). For a\n // test case with a view with 3000 rows, each row having 2 children, this\n // optimization reduced #applyChanges time from 743ms to 133ms.\n #builderRoot: Entry | undefined;\n #pendingChanges: ViewChange[] = [];\n readonly #updateTTL: (ttl: TTL) => void;\n\n constructor(\n input: Input,\n onTransactionCommit: (cb: () => void) => void,\n format: Format,\n onDestroy: () => void,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n setState: SetStoreFunction<State>,\n retry: () => void,\n ) {\n this.#input = input;\n onTransactionCommit(this.#onTransactionCommit);\n this.#format = format;\n this.#onDestroy = onDestroy;\n this.#updateTTL = updateTTL;\n this.#retry = retry;\n\n input.setOutput(this);\n\n const initialRoot = this.#createEmptyRoot();\n this.#applyChangesToRoot(\n skipYields(input.fetch({})),\n node => ({type: 'add', node}),\n initialRoot,\n );\n\n this.#setState = setState;\n this.#setState(\n reconcile(\n [\n initialRoot,\n queryComplete === true\n ? COMPLETE\n : 'error' in queryComplete\n ? this.#makeError(queryComplete)\n : UNKNOWN,\n ],\n {\n // solidjs's types want a string, but a symbol works\n key: idSymbol as unknown as string,\n },\n ),\n );\n\n if (isEmptyRoot(initialRoot)) {\n this.#builderRoot = this.#createEmptyRoot();\n }\n\n if (queryComplete !== true && !('error' in queryComplete)) {\n void queryComplete\n .then(() => {\n this.#setState(prev => [prev[0], COMPLETE]);\n })\n .catch((error: ErroredQuery) => {\n this.#setState(prev => [prev[0], this.#makeError(error)]);\n });\n }\n }\n\n #makeError(error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry: this.#retry,\n refetch: this.#retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n }\n\n destroy(): void {\n this.#onDestroy();\n }\n\n #onTransactionCommit = () => {\n const builderRoot = this.#builderRoot;\n if (builderRoot) {\n if (!isEmptyRoot(builderRoot)) {\n this.#setState(\n 0,\n reconcile(builderRoot, {\n // solidjs's types want a string, but a symbol works\n key: idSymbol as unknown as string,\n }),\n );\n this.#setState(prev => [builderRoot, prev[1]]);\n this.#builderRoot = undefined;\n }\n } else {\n try {\n this.#applyChanges(this.#pendingChanges, c => c);\n } finally {\n this.#pendingChanges = [];\n }\n }\n };\n\n push(change: Change) {\n // Delay updating the solid store state until the transaction commit\n // (because each update of the solid store is quite expensive). If\n // this.#builderRoot is defined apply the changes to it (we are building\n // from an empty root), otherwise queue the changes to be applied\n // using produce at the end of the transaction but read the relationships\n // now as they are only valid to read when the push is received.\n if (this.#builderRoot) {\n this.#applyChangeToRoot(\n materializeRelationships(change),\n this.#builderRoot,\n );\n } else {\n this.#pendingChanges.push(materializeRelationships(change));\n }\n return emptyArray;\n }\n\n #applyChanges<T>(changes: Iterable<T>, mapper: (v: T) => ViewChange): void {\n this.#setState(\n produce((draftState: State) => {\n this.#applyChangesToRoot<T>(changes, mapper, draftState[0]);\n if (isEmptyRoot(draftState[0])) {\n this.#builderRoot = this.#createEmptyRoot();\n }\n }),\n );\n }\n\n #applyChangesToRoot<T>(\n changes: Iterable<T>,\n mapper: (v: T) => ViewChange,\n root: Entry,\n ) {\n for (const change of changes) {\n this.#applyChangeToRoot(mapper(change), root);\n }\n }\n\n #applyChangeToRoot(change: ViewChange, root: Entry) {\n applyChange(\n root,\n change,\n this.#input.getSchema(),\n '',\n this.#format,\n true /* withIDs */,\n );\n }\n\n #createEmptyRoot(): Entry {\n return {\n '': this.#format.singular ? undefined : [],\n };\n }\n\n updateTTL(ttl: TTL): void {\n this.#updateTTL(ttl);\n }\n}\n\nfunction materializeRelationships(change: Change): ViewChange {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n return {\n type: 'add',\n node: materializeNodeRelationships(change[ChangeIndex.NODE]),\n };\n case ChangeType.REMOVE:\n return {\n type: 'remove',\n node: materializeNodeRelationships(change[ChangeIndex.NODE]),\n };\n case ChangeType.CHILD:\n return {\n type: 'child',\n node: {row: change[ChangeIndex.NODE].row},\n child: {\n relationshipName: change[ChangeIndex.CHILD_DATA].relationshipName,\n change: materializeRelationships(\n change[ChangeIndex.CHILD_DATA].change,\n ),\n },\n };\n case ChangeType.EDIT:\n return {\n type: 'edit',\n node: {row: change[ChangeIndex.NODE].row},\n oldNode: {row: change[ChangeIndex.OLD_NODE].row},\n };\n }\n}\n\nfunction materializeNodeRelationships(node: Node): Node {\n const relationships: Record<string, () => Stream<Node>> = {};\n for (const relationship in node.relationships) {\n const materialized: Node[] = [];\n for (const n of skipYields(node.relationships[relationship]())) {\n materialized.push(materializeNodeRelationships(n));\n }\n relationships[relationship] = () => materialized;\n }\n return {\n row: node.row,\n relationships,\n };\n}\n\nfunction isEmptyRoot(entry: Entry) {\n const data = entry[''];\n return data === undefined || (Array.isArray(data) && data.length === 0);\n}\n\nexport function createSolidViewFactory(\n setState: SetStoreFunction<State>,\n retry?: () => void,\n) {\n function solidViewFactory<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n _query: Query<TTable, TSchema, TReturn>,\n input: Input,\n format: Format,\n onDestroy: () => void,\n onTransactionCommit: (cb: () => void) => void,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n return new SolidView(\n input,\n onTransactionCommit,\n format,\n onDestroy,\n queryComplete,\n updateTTL,\n setState,\n retry || (() => {}),\n );\n }\n\n solidViewFactory satisfies AnyViewFactory;\n\n return solidViewFactory;\n}\n"],"mappings":";;;;;;;AA6BA,IAAa,WAA+B,OAAO,OAAO,EAAC,MAAM,YAAW,CAAC;AAC7E,IAAa,UAA8B,OAAO,OAAO,EAAC,MAAM,WAAU,CAAC;AAE3E,IAAa,YAAb,MAAyC;CACvC;CACA;CACA;CACA;CAEA;CAUA;CACA,kBAAgC,EAAE;CAClC;CAEA,YACE,OACA,qBACA,QACA,WACA,eACA,WACA,UACA,OACA;AACA,QAAA,QAAc;AACd,sBAAoB,MAAA,oBAA0B;AA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AO,EAAE,MAAM,GAAG,KAAK,CAAC;IAEhE;;;;;OAKG;IACH,MAAM,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG,CAAC,GAAG,SAAS,CAAC;CAC1C;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,aAAa,CAC3B,GAAG,EAAE,GAAG,EACR,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,mBAAmB,EAC/B,EAAE,CAAC,EAAE,UAAU,EACf,YAAY,CAAC,EAAE,YAAY,GAC1B,KAAK,CAWP;AAED,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,GAAG,EACR,qBAAqB,EAAE,qBAAqB,GAAG,SAAS,OAsDzD;AAyBD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI,CAsB5D;AAqQD,wBAAgB,OAAO,CACrB,KAAK,EAAE,WAAW,EAClB,SAAS,EAAE,WAAW,EACtB,QAAQ,EAAE,eAAe,EACzB,IAAI,EAAE,MAAM,GACX,WAAW,CAsCb;AAED,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,WAAW,6EAa7D;AAED,wBAAgB,8BAA8B,CAC5C,SAAS,EAAE,SAAS,GACnB,SAAS,IAAI,mBAAmB,CAQlC;AAsHD,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,QAAQ,EAClB,EAAE,EAAE,UAAU,GACb,IAAI,CAgBN;AA8CD,wBAAgB,0CAA0C,CACxD,IAAI,EAAE,SAAS,GACd,OAAO,CAWT;AAED,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,SAAS,SAAS,EAAE,EAChC,SAAS,EAAE,CAAC,CAAC,EAAE,SAAS,KAAK,OAAO,uCAYrC"}
@@ -1 +1 @@
1
- {"version":3,"file":"builder.js","names":[],"sources":["../../../../../zql/src/builder/builder.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {JSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {\n AST,\n ColumnReference,\n CompoundKey,\n Condition,\n Conjunction,\n CorrelatedSubquery,\n CorrelatedSubqueryCondition,\n Disjunction,\n LiteralValue,\n Ordering,\n Parameter,\n SimpleCondition,\n ValuePosition,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {Exists} from '../ivm/exists.ts';\nimport {FanIn} from '../ivm/fan-in.ts';\nimport {FanOut} from '../ivm/fan-out.ts';\nimport {\n buildFilterPipeline,\n type FilterInput,\n} from '../ivm/filter-operators.ts';\nimport {Filter} from '../ivm/filter.ts';\nimport {FlippedJoin} from '../ivm/flipped-join.ts';\nimport {Join} from '../ivm/join.ts';\nimport type {Input, InputBase, Storage} from '../ivm/operator.ts';\nimport {Skip} from '../ivm/skip.ts';\nimport type {Source, SourceInput} from '../ivm/source.ts';\nimport {Take} from '../ivm/take.ts';\nimport {UnionFanIn} from '../ivm/union-fan-in.ts';\nimport {UnionFanOut} from '../ivm/union-fan-out.ts';\nimport {planQuery} from '../planner/planner-builder.ts';\nimport type {ConnectionCostModel} from '../planner/planner-connection.ts';\nimport {completeOrdering} from '../query/complete-ordering.ts';\nimport type {PlanDebugger} from '../planner/planner-debug.ts';\nimport type {DebugDelegate} from './debug-delegate.ts';\nimport {createPredicate, type NoSubqueryCondition} from './filter.ts';\n\nexport type StaticQueryParameters = {\n authData: Record<string, JSONValue>;\n preMutationRow?: Row | undefined;\n};\n\n/**\n * Interface required of caller to buildPipeline. Connects to constructed\n * pipeline to delegate environment to provide sources and storage.\n */\nexport interface BuilderDelegate {\n readonly applyFiltersAnyway?: boolean | undefined;\n debug?: DebugDelegate | undefined;\n\n /**\n * When true, allows NOT EXISTS conditions in queries.\n * Defaults to false.\n *\n * We only set this to true on the server.\n * The client-side query engine cannot support NOT EXISTS because:\n * 1. Zero only syncs a subset of data to the client\n * 2. On the client, we can't distinguish between a row not existing vs.\n * a row not being synced to the client\n * 3. NOT EXISTS requires complete knowledge of what doesn't exist\n */\n readonly enableNotExists?: boolean | undefined;\n\n /**\n * Called once for each source needed by the AST.\n * Might be called multiple times with same tableName. It is OK to return\n * same storage instance in that case.\n */\n getSource(tableName: string): Source | undefined;\n\n /**\n * Called once for each operator that requires storage. Should return a new\n * unique storage object for each call.\n */\n createStorage(name: string): Storage;\n\n decorateInput(input: Input, name: string): Input;\n\n addEdge(source: InputBase, dest: InputBase): void;\n\n decorateFilterInput(input: FilterInput, name: string): FilterInput;\n\n decorateSourceInput(input: SourceInput, queryID: string): Input;\n\n /**\n * The AST is mapped on-the-wire between client and server names.\n *\n * There is no \"wire\" for zqlite tests so this function is provided\n * to allow tests to remap the AST.\n */\n mapAst?: ((ast: AST) => AST) | undefined;\n}\n\n/**\n * Builds a pipeline from an AST. Caller must provide a delegate to create source\n * and storage interfaces as necessary.\n *\n * Usage:\n *\n * ```ts\n * class MySink implements Output {\n * readonly #input: Input;\n *\n * constructor(input: Input) {\n * this.#input = input;\n * input.setOutput(this);\n * }\n *\n * push(change: Change, _: Operator) {\n * console.log(change);\n * }\n * }\n *\n * const input = buildPipeline(ast, myDelegate, hash(ast));\n * const sink = new MySink(input);\n * ```\n */\nexport function buildPipeline(\n ast: AST,\n delegate: BuilderDelegate,\n queryID: string,\n costModel?: ConnectionCostModel,\n lc?: LogContext,\n planDebugger?: PlanDebugger,\n): Input {\n ast = delegate.mapAst ? delegate.mapAst(ast) : ast;\n ast = completeOrdering(\n ast,\n tableName => must(delegate.getSource(tableName)).tableSchema.primaryKey,\n );\n\n if (costModel) {\n ast = planQuery(ast, costModel, planDebugger, lc);\n }\n return buildPipelineInternal(ast, delegate, queryID, '');\n}\n\nexport function bindStaticParameters(\n ast: AST,\n staticQueryParameters: StaticQueryParameters | undefined,\n) {\n const visit = (node: AST): AST => ({\n ...node,\n where: node.where ? bindCondition(node.where) : undefined,\n related: node.related?.map(sq => ({\n ...sq,\n subquery: visit(sq.subquery),\n })),\n });\n\n function bindCondition(condition: Condition): Condition {\n if (condition.type === 'simple') {\n return {\n ...condition,\n left: bindValue(condition.left),\n right: bindValue(condition.right) as Exclude<\n ValuePosition,\n ColumnReference\n >,\n };\n }\n if (condition.type === 'correlatedSubquery') {\n return {\n ...condition,\n related: {\n ...condition.related,\n subquery: visit(condition.related.subquery),\n },\n };\n }\n\n return {\n ...condition,\n conditions: condition.conditions.map(bindCondition),\n };\n }\n\n const bindValue = (value: ValuePosition): ValuePosition => {\n if (isParameter(value)) {\n const anchor = must(\n staticQueryParameters,\n 'Static query params do not exist',\n )[value.anchor];\n const resolvedValue = resolveField(anchor, value.field);\n return {\n type: 'literal',\n value: resolvedValue as LiteralValue,\n };\n }\n return value;\n };\n\n return visit(ast);\n}\n\nfunction resolveField(\n anchor: Record<string, JSONValue> | Row | undefined,\n field: string | string[],\n): unknown {\n if (anchor === undefined) {\n return null;\n }\n\n if (Array.isArray(field)) {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return field.reduce((acc, f) => (acc as any)?.[f], anchor) ?? null;\n }\n\n return anchor[field] ?? null;\n}\n\nfunction isParameter(value: ValuePosition): value is Parameter {\n return value.type === 'static';\n}\n\nconst EXISTS_LIMIT = 3;\nconst PERMISSIONS_EXISTS_LIMIT = 1;\n\n/**\n * Checks if a condition tree contains any NOT EXISTS operations.\n * Recursively checks AND/OR branches but does not recurse into nested subqueries\n * (those are checked when buildPipelineInternal processes them).\n */\nexport function assertNoNotExists(condition: Condition): void {\n switch (condition.type) {\n case 'simple':\n return;\n\n case 'correlatedSubquery':\n if (condition.op === 'NOT EXISTS') {\n throw new Error(\n 'not(exists()) is not supported on the client - see https://bugs.rocicorp.dev/issue/3438',\n );\n }\n return;\n\n case 'and':\n case 'or':\n for (const c of condition.conditions) {\n assertNoNotExists(c);\n }\n return;\n default:\n unreachable(condition);\n }\n}\n\nfunction buildPipelineInternal(\n ast: AST,\n delegate: BuilderDelegate,\n queryID: string,\n name: string,\n partitionKey?: CompoundKey,\n): Input {\n const source = delegate.getSource(ast.table);\n if (!source) {\n throw new Error(`Source not found: ${ast.table}`);\n }\n\n ast = uniquifyCorrelatedSubqueryConditionAliases(ast);\n\n if (!delegate.enableNotExists && ast.where) {\n assertNoNotExists(ast.where);\n }\n\n const csqConditions = gatherCorrelatedSubqueryQueryConditions(ast.where);\n const splitEditKeys: Set<string> = partitionKey\n ? new Set(partitionKey)\n : new Set();\n const aliases = new Set<string>();\n for (const csq of csqConditions) {\n aliases.add(csq.related.subquery.alias || '');\n for (const key of csq.related.correlation.parentField) {\n splitEditKeys.add(key);\n }\n }\n if (ast.related) {\n for (const csq of ast.related) {\n for (const key of csq.correlation.parentField) {\n splitEditKeys.add(key);\n }\n }\n }\n const conn = source.connect(\n must(ast.orderBy),\n ast.where,\n splitEditKeys,\n delegate.debug,\n );\n\n let end: Input = delegate.decorateSourceInput(conn, queryID);\n end = delegate.decorateInput(end, `${name}:source(${ast.table})`);\n const {fullyAppliedFilters} = conn;\n\n if (ast.start) {\n const skip = new Skip(end, ast.start);\n delegate.addEdge(end, skip);\n end = delegate.decorateInput(skip, `${name}:skip)`);\n }\n\n for (const csqCondition of csqConditions) {\n // flipped EXISTS are handled in applyWhere\n if (!csqCondition.flip) {\n end = applyCorrelatedSubQuery(\n {\n ...csqCondition.related,\n subquery: {\n ...csqCondition.related.subquery,\n limit:\n csqCondition.related.system === 'permissions'\n ? PERMISSIONS_EXISTS_LIMIT\n : EXISTS_LIMIT,\n },\n },\n delegate,\n queryID,\n end,\n name,\n true,\n );\n }\n }\n\n if (ast.where && (!fullyAppliedFilters || delegate.applyFiltersAnyway)) {\n end = applyWhere(end, ast.where, delegate, name);\n }\n\n if (ast.limit !== undefined) {\n const takeName = `${name}:take`;\n const take = new Take(\n end,\n delegate.createStorage(takeName),\n ast.limit,\n partitionKey,\n );\n delegate.addEdge(end, take);\n end = delegate.decorateInput(take, takeName);\n }\n\n if (ast.related) {\n // Dedupe by alias - last one wins (LWW), like limit(5).limit(10)\n const byAlias = new Map<string, CorrelatedSubquery>();\n for (const csq of ast.related) {\n byAlias.set(csq.subquery.alias ?? '', csq);\n }\n for (const csq of byAlias.values()) {\n end = applyCorrelatedSubQuery(csq, delegate, queryID, end, name, false);\n }\n }\n\n return end;\n}\n\nfunction applyWhere(\n input: Input,\n condition: Condition,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n if (!conditionIncludesFlippedSubqueryAtAnyLevel(condition)) {\n return buildFilterPipeline(input, delegate, filterInput =>\n applyFilter(filterInput, condition, delegate, name),\n );\n }\n\n return applyFilterWithFlips(input, condition, delegate, name);\n}\n\nfunction applyFilterWithFlips(\n input: Input,\n condition: Condition,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n let end = input;\n assert(condition.type !== 'simple', 'Simple conditions cannot have flips');\n\n switch (condition.type) {\n case 'and': {\n const [withFlipped, withoutFlipped] = partitionBranches(\n condition.conditions,\n conditionIncludesFlippedSubqueryAtAnyLevel,\n );\n if (withoutFlipped.length > 0) {\n end = buildFilterPipeline(input, delegate, filterInput =>\n applyAnd(\n filterInput,\n {\n type: 'and',\n conditions: withoutFlipped,\n },\n delegate,\n name,\n ),\n );\n }\n assert(withFlipped.length > 0, 'Impossible to have no flips here');\n for (const cond of withFlipped) {\n end = applyFilterWithFlips(end, cond, delegate, name);\n }\n break;\n }\n case 'or': {\n const [withFlipped, withoutFlipped] = partitionBranches(\n condition.conditions,\n conditionIncludesFlippedSubqueryAtAnyLevel,\n );\n assert(withFlipped.length > 0, 'Impossible to have no flips here');\n\n const ufo = new UnionFanOut(end);\n delegate.addEdge(end, ufo);\n end = delegate.decorateInput(ufo, `${name}:ufo`);\n\n const branches: Input[] = [];\n if (withoutFlipped.length > 0) {\n branches.push(\n buildFilterPipeline(end, delegate, filterInput =>\n applyOr(\n filterInput,\n {\n type: 'or',\n conditions: withoutFlipped,\n },\n delegate,\n name,\n ),\n ),\n );\n }\n\n for (const cond of withFlipped) {\n branches.push(applyFilterWithFlips(end, cond, delegate, name));\n }\n\n const ufi = new UnionFanIn(ufo, branches);\n for (const branch of branches) {\n delegate.addEdge(branch, ufi);\n }\n end = delegate.decorateInput(ufi, `${name}:ufi`);\n\n break;\n }\n case 'correlatedSubquery': {\n const sq = condition.related;\n const child = buildPipelineInternal(\n sq.subquery,\n delegate,\n '',\n `${name}.${sq.subquery.alias}`,\n sq.correlation.childField,\n );\n const flippedJoin = new FlippedJoin({\n parent: end,\n child,\n parentKey: sq.correlation.parentField,\n childKey: sq.correlation.childField,\n relationshipName: must(\n sq.subquery.alias,\n 'Subquery must have an alias',\n ),\n hidden: sq.hidden ?? false,\n system: sq.system ?? 'client',\n });\n delegate.addEdge(end, flippedJoin);\n delegate.addEdge(child, flippedJoin);\n end = delegate.decorateInput(\n flippedJoin,\n `${name}:flipped-join(${sq.subquery.alias})`,\n );\n break;\n }\n }\n\n return end;\n}\n\nfunction applyFilter(\n input: FilterInput,\n condition: Condition,\n delegate: BuilderDelegate,\n name: string,\n): FilterInput {\n switch (condition.type) {\n case 'and':\n return applyAnd(input, condition, delegate, name);\n case 'or':\n return applyOr(input, condition, delegate, name);\n case 'correlatedSubquery':\n return applyCorrelatedSubqueryCondition(input, condition, delegate, name);\n case 'simple':\n return applySimpleCondition(input, delegate, condition);\n }\n}\n\nfunction applyAnd(\n input: FilterInput,\n condition: Conjunction,\n delegate: BuilderDelegate,\n name: string,\n): FilterInput {\n for (const subCondition of condition.conditions) {\n input = applyFilter(input, subCondition, delegate, name);\n }\n return input;\n}\n\nexport function applyOr(\n input: FilterInput,\n condition: Disjunction,\n delegate: BuilderDelegate,\n name: string,\n): FilterInput {\n const [subqueryConditions, otherConditions] =\n groupSubqueryConditions(condition);\n // if there are no subquery conditions, no fan-in / fan-out is needed\n if (subqueryConditions.length === 0) {\n const filter = new Filter(\n input,\n createPredicate({\n type: 'or',\n conditions: otherConditions,\n }),\n );\n delegate.addEdge(input, filter);\n return filter;\n }\n\n const fanOut = new FanOut(input);\n delegate.addEdge(input, fanOut);\n const branches = subqueryConditions.map(subCondition =>\n applyFilter(fanOut, subCondition, delegate, name),\n );\n if (otherConditions.length > 0) {\n const filter = new Filter(\n fanOut,\n createPredicate({\n type: 'or',\n conditions: otherConditions,\n }),\n );\n delegate.addEdge(fanOut, filter);\n branches.push(filter);\n }\n const ret = new FanIn(fanOut, branches);\n for (const branch of branches) {\n delegate.addEdge(branch, ret);\n }\n fanOut.setFanIn(ret);\n return ret;\n}\n\nexport function groupSubqueryConditions(condition: Disjunction) {\n const partitioned: [\n subqueryConditions: Condition[],\n otherConditions: NoSubqueryCondition[],\n ] = [[], []];\n for (const subCondition of condition.conditions) {\n if (isNotAndDoesNotContainSubquery(subCondition)) {\n partitioned[1].push(subCondition);\n } else {\n partitioned[0].push(subCondition);\n }\n }\n return partitioned;\n}\n\nexport function isNotAndDoesNotContainSubquery(\n condition: Condition,\n): condition is NoSubqueryCondition {\n if (condition.type === 'correlatedSubquery') {\n return false;\n }\n if (condition.type === 'simple') {\n return true;\n }\n return condition.conditions.every(isNotAndDoesNotContainSubquery);\n}\n\nfunction applySimpleCondition(\n input: FilterInput,\n delegate: BuilderDelegate,\n condition: SimpleCondition,\n): FilterInput {\n const filter = new Filter(input, createPredicate(condition));\n delegate.decorateFilterInput(\n filter,\n `${valuePosName(condition.left)}:${condition.op}:${valuePosName(condition.right)}`,\n );\n delegate.addEdge(input, filter);\n return filter;\n}\n\nfunction valuePosName(left: ValuePosition) {\n switch (left.type) {\n case 'static':\n return left.field;\n case 'literal':\n return left.value;\n case 'column':\n return left.name;\n }\n}\n\nfunction applyCorrelatedSubQuery(\n sq: CorrelatedSubquery,\n delegate: BuilderDelegate,\n queryID: string,\n end: Input,\n name: string,\n fromCondition: boolean,\n) {\n // TODO: we only omit the join if the CSQ if from a condition since\n // we want to create an empty array for `related` fields that are `limit(0)`\n if (sq.subquery.limit === 0 && fromCondition) {\n return end;\n }\n\n assert(sq.subquery.alias, 'Subquery must have an alias');\n const child = buildPipelineInternal(\n sq.subquery,\n delegate,\n queryID,\n `${name}.${sq.subquery.alias}`,\n sq.correlation.childField,\n );\n\n const joinName = `${name}:join(${sq.subquery.alias})`;\n const join = new Join({\n parent: end,\n child,\n parentKey: sq.correlation.parentField,\n childKey: sq.correlation.childField,\n relationshipName: sq.subquery.alias,\n hidden: sq.hidden ?? false,\n system: sq.system ?? 'client',\n });\n delegate.addEdge(end, join);\n delegate.addEdge(child, join);\n return delegate.decorateInput(join, joinName);\n}\n\nfunction applyCorrelatedSubqueryCondition(\n input: FilterInput,\n condition: CorrelatedSubqueryCondition,\n delegate: BuilderDelegate,\n name: string,\n): FilterInput {\n assert(\n condition.op === 'EXISTS' || condition.op === 'NOT EXISTS',\n 'Expected EXISTS or NOT EXISTS operator',\n );\n if (condition.related.subquery.limit === 0) {\n if (condition.op === 'EXISTS') {\n const filter = new Filter(input, () => false);\n delegate.addEdge(input, filter);\n return filter;\n }\n const filter = new Filter(input, () => true);\n delegate.addEdge(input, filter);\n return filter;\n }\n const existsName = `${name}:exists(${condition.related.subquery.alias})`;\n const exists = new Exists(\n input,\n must(condition.related.subquery.alias),\n condition.related.correlation.parentField,\n condition.op,\n );\n delegate.addEdge(input, exists);\n return delegate.decorateFilterInput(exists, existsName);\n}\n\nfunction gatherCorrelatedSubqueryQueryConditions(\n condition: Condition | undefined,\n) {\n const csqs: CorrelatedSubqueryCondition[] = [];\n const gather = (condition: Condition) => {\n if (condition.type === 'correlatedSubquery') {\n csqs.push(condition);\n return;\n }\n if (condition.type === 'and' || condition.type === 'or') {\n for (const c of condition.conditions) {\n gather(c);\n }\n return;\n }\n };\n if (condition) {\n gather(condition);\n }\n return csqs;\n}\n\nexport function assertOrderingIncludesPK(\n ordering: Ordering,\n pk: PrimaryKey,\n): void {\n // oxlint-disable-next-line unicorn/prefer-set-has -- Array is more appropriate here for small collections\n const orderingFields = ordering.map(([field]) => field);\n const missingFields = pk.filter(pkField => !orderingFields.includes(pkField));\n\n if (missingFields.length > 0) {\n throw new Error(\n `Ordering must include all primary key fields. Missing: ${missingFields.join(\n ', ',\n )}. ZQL automatically appends primary key fields to the ordering if they are missing \n so a common cause of this error is a casing mismatch between Postgres and ZQL.\n E.g., \"userid\" vs \"userID\".\n You may want to add double-quotes around your Postgres column names to prevent Postgres from lower-casing them:\n https://www.postgresql.org/docs/current/sql-syntax-lexical.htm`,\n );\n }\n}\n\nfunction uniquifyCorrelatedSubqueryConditionAliases(ast: AST): AST {\n if (!ast.where) {\n return ast;\n }\n const {where} = ast;\n if (where.type !== 'and' && where.type !== 'or') {\n return ast;\n }\n\n let count = 0;\n const uniquifyCorrelatedSubquery = (csqc: CorrelatedSubqueryCondition) => ({\n ...csqc,\n related: {\n ...csqc.related,\n subquery: {\n ...csqc.related.subquery,\n alias: (csqc.related.subquery.alias ?? '') + '_' + count++,\n },\n },\n });\n\n const uniquify = (cond: Condition): Condition => {\n if (cond.type === 'simple') {\n return cond;\n } else if (cond.type === 'correlatedSubquery') {\n return uniquifyCorrelatedSubquery(cond);\n }\n const conditions = [];\n for (const c of cond.conditions) {\n conditions.push(uniquify(c));\n }\n return {\n type: cond.type,\n conditions,\n };\n };\n\n const result = {\n ...ast,\n where: uniquify(where),\n };\n return result;\n}\n\nexport function conditionIncludesFlippedSubqueryAtAnyLevel(\n cond: Condition,\n): boolean {\n if (cond.type === 'correlatedSubquery') {\n return !!cond.flip;\n }\n if (cond.type === 'and' || cond.type === 'or') {\n return cond.conditions.some(c =>\n conditionIncludesFlippedSubqueryAtAnyLevel(c),\n );\n }\n // simple conditions don't have flips\n return false;\n}\n\nexport function partitionBranches(\n conditions: readonly Condition[],\n predicate: (c: Condition) => boolean,\n) {\n const matched: Condition[] = [];\n const notMatched: Condition[] = [];\n for (const c of conditions) {\n if (predicate(c)) {\n matched.push(c);\n } else {\n notMatched.push(c);\n }\n }\n return [matched, notMatched] as const;\n}\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,GAAG,KAAK;GACR,UAAU;IACR,GAAG,KAAK,QAAQ;IAChB,QAAQ,KAAK,QAAQ,SAAS,SAAS,MAAM,MAAM;IACpD;GACF;EACF;CAED,MAAM,YAAY,SAA+B;AAC/C,MAAI,KAAK,SAAS,SAChB,QAAO;WACE,KAAK,SAAS,qBACvB,QAAO,2BAA2B,KAAK;EAEzC,MAAM,aAAa,EAAE;AACrB,OAAK,MAAM,KAAK,KAAK,WACnB,YAAW,KAAK,SAAS,EAAE,CAAC;AAE9B,SAAO;GACL,MAAM,KAAK;GACX;GACD;;AAOH,QAJe;EACb,GAAG;EACH,OAAO,SAAS,MAAM;EACvB;;AAIH,SAAgB,2CACd,MACS;AACT,KAAI,KAAK,SAAS,qBAChB,QAAO,CAAC,CAAC,KAAK;AAEhB,KAAI,KAAK,SAAS,SAAS,KAAK,SAAS,KACvC,QAAO,KAAK,WAAW,MAAK,MAC1B,2CAA2C,EAAE,CAC9C;AAGH,QAAO;;AAGT,SAAgB,kBACd,YACA,WACA;CACA,MAAM,UAAuB,EAAE;CAC/B,MAAM,aAA0B,EAAE;AAClC,MAAK,MAAM,KAAK,WACd,KAAI,UAAU,EAAE,CACd,SAAQ,KAAK,EAAE;KAEf,YAAW,KAAK,EAAE;AAGtB,QAAO,CAAC,SAAS,WAAW"}
1
+ {"version":3,"file":"builder.js","names":[],"sources":["../../../../../zql/src/builder/builder.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {JSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {\n AST,\n ColumnReference,\n CompoundKey,\n Condition,\n Conjunction,\n CorrelatedSubquery,\n CorrelatedSubqueryCondition,\n Disjunction,\n LiteralValue,\n Ordering,\n Parameter,\n SimpleCondition,\n ValuePosition,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {Exists} from '../ivm/exists.ts';\nimport {FanIn} from '../ivm/fan-in.ts';\nimport {FanOut} from '../ivm/fan-out.ts';\nimport {\n buildFilterPipeline,\n type FilterInput,\n} from '../ivm/filter-operators.ts';\nimport {Filter} from '../ivm/filter.ts';\nimport {FlippedJoin} from '../ivm/flipped-join.ts';\nimport {Join} from '../ivm/join.ts';\nimport type {Input, InputBase, Storage} from '../ivm/operator.ts';\nimport {Skip} from '../ivm/skip.ts';\nimport type {Source, SourceInput} from '../ivm/source.ts';\nimport {Take} from '../ivm/take.ts';\nimport {UnionFanIn} from '../ivm/union-fan-in.ts';\nimport {UnionFanOut} from '../ivm/union-fan-out.ts';\nimport {planQuery} from '../planner/planner-builder.ts';\nimport type {ConnectionCostModel} from '../planner/planner-connection.ts';\nimport type {PlanDebugger} from '../planner/planner-debug.ts';\nimport {completeOrdering} from '../query/complete-ordering.ts';\nimport type {DebugDelegate} from './debug-delegate.ts';\nimport {createPredicate, type NoSubqueryCondition} from './filter.ts';\n\nexport type StaticQueryParameters = {\n authData: Record<string, JSONValue>;\n preMutationRow?: Row | undefined;\n};\n\n/**\n * Interface required of caller to buildPipeline. Connects to constructed\n * pipeline to delegate environment to provide sources and storage.\n */\nexport interface BuilderDelegate {\n readonly applyFiltersAnyway?: boolean | undefined;\n debug?: DebugDelegate | undefined;\n\n /**\n * When true, allows NOT EXISTS conditions in queries.\n * Defaults to false.\n *\n * We only set this to true on the server.\n * The client-side query engine cannot support NOT EXISTS because:\n * 1. Zero only syncs a subset of data to the client\n * 2. On the client, we can't distinguish between a row not existing vs.\n * a row not being synced to the client\n * 3. NOT EXISTS requires complete knowledge of what doesn't exist\n */\n readonly enableNotExists?: boolean | undefined;\n\n /**\n * Called once for each source needed by the AST.\n * Might be called multiple times with same tableName. It is OK to return\n * same storage instance in that case.\n */\n getSource(tableName: string): Source | undefined;\n\n /**\n * Called once for each operator that requires storage. Should return a new\n * unique storage object for each call.\n */\n createStorage(name: string): Storage;\n\n decorateInput(input: Input, name: string): Input;\n\n addEdge(source: InputBase, dest: InputBase): void;\n\n decorateFilterInput(input: FilterInput, name: string): FilterInput;\n\n decorateSourceInput(input: SourceInput, queryID: string): Input;\n\n /**\n * The AST is mapped on-the-wire between client and server names.\n *\n * There is no \"wire\" for zqlite tests so this function is provided\n * to allow tests to remap the AST.\n */\n mapAst?: ((ast: AST) => AST) | undefined;\n}\n\n/**\n * Builds a pipeline from an AST. Caller must provide a delegate to create source\n * and storage interfaces as necessary.\n *\n * Usage:\n *\n * ```ts\n * class MySink implements Output {\n * readonly #input: Input;\n *\n * constructor(input: Input) {\n * this.#input = input;\n * input.setOutput(this);\n * }\n *\n * push(change: Change, _: Operator) {\n * console.log(change);\n * }\n * }\n *\n * const input = buildPipeline(ast, myDelegate, hash(ast));\n * const sink = new MySink(input);\n * ```\n */\nexport function buildPipeline(\n ast: AST,\n delegate: BuilderDelegate,\n queryID: string,\n costModel?: ConnectionCostModel,\n lc?: LogContext,\n planDebugger?: PlanDebugger,\n): Input {\n ast = delegate.mapAst ? delegate.mapAst(ast) : ast;\n ast = completeOrdering(\n ast,\n tableName => must(delegate.getSource(tableName)).tableSchema.primaryKey,\n );\n\n if (costModel) {\n ast = planQuery(ast, costModel, planDebugger, lc);\n }\n return buildPipelineInternal(ast, delegate, queryID, '');\n}\n\nexport function bindStaticParameters(\n ast: AST,\n staticQueryParameters: StaticQueryParameters | undefined,\n) {\n const visit = (node: AST): AST => ({\n ...node,\n where: node.where ? bindCondition(node.where) : undefined,\n related: node.related?.map(sq => ({\n ...sq,\n subquery: visit(sq.subquery),\n })),\n });\n\n function bindCondition(condition: Condition): Condition {\n if (condition.type === 'simple') {\n return {\n ...condition,\n left: bindValue(condition.left),\n right: bindValue(condition.right) as Exclude<\n ValuePosition,\n ColumnReference\n >,\n };\n }\n if (condition.type === 'correlatedSubquery') {\n return {\n ...condition,\n related: {\n ...condition.related,\n subquery: visit(condition.related.subquery),\n },\n };\n }\n\n return {\n ...condition,\n conditions: condition.conditions.map(bindCondition),\n };\n }\n\n const bindValue = (value: ValuePosition): ValuePosition => {\n if (isParameter(value)) {\n const anchor = must(\n staticQueryParameters,\n 'Static query params do not exist',\n )[value.anchor];\n const resolvedValue = resolveField(anchor, value.field);\n return {\n type: 'literal',\n value: resolvedValue as LiteralValue,\n };\n }\n return value;\n };\n\n return visit(ast);\n}\n\nfunction resolveField(\n anchor: Record<string, JSONValue> | Row | undefined,\n field: string | string[],\n): unknown {\n if (anchor === undefined) {\n return null;\n }\n\n if (Array.isArray(field)) {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return field.reduce((acc, f) => (acc as any)?.[f], anchor) ?? null;\n }\n\n return anchor[field] ?? null;\n}\n\nfunction isParameter(value: ValuePosition): value is Parameter {\n return value.type === 'static';\n}\n\nconst EXISTS_LIMIT = 3;\nconst PERMISSIONS_EXISTS_LIMIT = 1;\n\n/**\n * Checks if a condition tree contains any NOT EXISTS operations.\n * Recursively checks AND/OR branches but does not recurse into nested subqueries\n * (those are checked when buildPipelineInternal processes them).\n */\nexport function assertNoNotExists(condition: Condition): void {\n switch (condition.type) {\n case 'simple':\n return;\n\n case 'correlatedSubquery':\n if (condition.op === 'NOT EXISTS') {\n throw new Error(\n 'not(exists()) is not supported on the client - see https://bugs.rocicorp.dev/issue/3438',\n );\n }\n return;\n\n case 'and':\n case 'or':\n for (const c of condition.conditions) {\n assertNoNotExists(c);\n }\n return;\n default:\n unreachable(condition);\n }\n}\n\nfunction buildPipelineInternal(\n ast: AST,\n delegate: BuilderDelegate,\n queryID: string,\n name: string,\n partitionKey?: CompoundKey,\n): Input {\n const source = delegate.getSource(ast.table);\n if (!source) {\n throw new Error(`Source not found: ${ast.table}`);\n }\n\n ast = uniquifyCorrelatedSubqueryConditionAliases(ast);\n\n if (!delegate.enableNotExists && ast.where) {\n assertNoNotExists(ast.where);\n }\n\n const csqConditions = gatherCorrelatedSubqueryQueryConditions(ast.where);\n const splitEditKeys: Set<string> = partitionKey\n ? new Set(partitionKey)\n : new Set();\n const aliases = new Set<string>();\n for (const csq of csqConditions) {\n aliases.add(csq.related.subquery.alias || '');\n for (const key of csq.related.correlation.parentField) {\n splitEditKeys.add(key);\n }\n }\n if (ast.related) {\n for (const csq of ast.related) {\n for (const key of csq.correlation.parentField) {\n splitEditKeys.add(key);\n }\n }\n }\n const conn = source.connect(\n must(ast.orderBy),\n ast.where,\n splitEditKeys,\n delegate.debug,\n );\n\n let end: Input = delegate.decorateSourceInput(conn, queryID);\n end = delegate.decorateInput(end, `${name}:source(${ast.table})`);\n const {fullyAppliedFilters} = conn;\n\n if (ast.start) {\n const skip = new Skip(end, ast.start);\n delegate.addEdge(end, skip);\n end = delegate.decorateInput(skip, `${name}:skip)`);\n }\n\n for (const csqCondition of csqConditions) {\n // flipped EXISTS are handled in applyWhere\n if (!csqCondition.flip) {\n end = applyCorrelatedSubQuery(\n {\n ...csqCondition.related,\n subquery: {\n ...csqCondition.related.subquery,\n limit:\n csqCondition.related.system === 'permissions'\n ? PERMISSIONS_EXISTS_LIMIT\n : EXISTS_LIMIT,\n },\n },\n delegate,\n queryID,\n end,\n name,\n true,\n );\n }\n }\n\n if (ast.where && (!fullyAppliedFilters || delegate.applyFiltersAnyway)) {\n end = applyWhere(end, ast.where, delegate, name);\n }\n\n if (ast.limit !== undefined) {\n const takeName = `${name}:take`;\n const take = new Take(\n end,\n delegate.createStorage(takeName),\n ast.limit,\n partitionKey,\n );\n delegate.addEdge(end, take);\n end = delegate.decorateInput(take, takeName);\n }\n\n if (ast.related) {\n // Dedupe by alias - last one wins (LWW), like limit(5).limit(10)\n const byAlias = new Map<string, CorrelatedSubquery>();\n for (const csq of ast.related) {\n byAlias.set(csq.subquery.alias ?? '', csq);\n }\n for (const csq of byAlias.values()) {\n end = applyCorrelatedSubQuery(csq, delegate, queryID, end, name, false);\n }\n }\n\n return end;\n}\n\nfunction applyWhere(\n input: Input,\n condition: Condition,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n if (!conditionIncludesFlippedSubqueryAtAnyLevel(condition)) {\n return buildFilterPipeline(input, delegate, filterInput =>\n applyFilter(filterInput, condition, delegate, name),\n );\n }\n\n return applyFilterWithFlips(input, condition, delegate, name);\n}\n\nfunction applyFilterWithFlips(\n input: Input,\n condition: Condition,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n let end = input;\n assert(condition.type !== 'simple', 'Simple conditions cannot have flips');\n\n switch (condition.type) {\n case 'and': {\n const [withFlipped, withoutFlipped] = partitionBranches(\n condition.conditions,\n conditionIncludesFlippedSubqueryAtAnyLevel,\n );\n if (withoutFlipped.length > 0) {\n end = buildFilterPipeline(input, delegate, filterInput =>\n applyAnd(\n filterInput,\n {\n type: 'and',\n conditions: withoutFlipped,\n },\n delegate,\n name,\n ),\n );\n }\n assert(withFlipped.length > 0, 'Impossible to have no flips here');\n for (const cond of withFlipped) {\n end = applyFilterWithFlips(end, cond, delegate, name);\n }\n break;\n }\n case 'or': {\n const [withFlipped, withoutFlipped] = partitionBranches(\n condition.conditions,\n conditionIncludesFlippedSubqueryAtAnyLevel,\n );\n assert(withFlipped.length > 0, 'Impossible to have no flips here');\n\n const ufo = new UnionFanOut(end);\n delegate.addEdge(end, ufo);\n end = delegate.decorateInput(ufo, `${name}:ufo`);\n\n const branches: Input[] = [];\n if (withoutFlipped.length > 0) {\n branches.push(\n buildFilterPipeline(end, delegate, filterInput =>\n applyOr(\n filterInput,\n {\n type: 'or',\n conditions: withoutFlipped,\n },\n delegate,\n name,\n ),\n ),\n );\n }\n\n for (const cond of withFlipped) {\n branches.push(applyFilterWithFlips(end, cond, delegate, name));\n }\n\n const ufi = new UnionFanIn(ufo, branches);\n for (const branch of branches) {\n delegate.addEdge(branch, ufi);\n }\n end = delegate.decorateInput(ufi, `${name}:ufi`);\n\n break;\n }\n case 'correlatedSubquery': {\n const sq = condition.related;\n const child = buildPipelineInternal(\n sq.subquery,\n delegate,\n '',\n `${name}.${sq.subquery.alias}`,\n sq.correlation.childField,\n );\n const flippedJoin = new FlippedJoin({\n parent: end,\n child,\n parentKey: sq.correlation.parentField,\n childKey: sq.correlation.childField,\n relationshipName: must(\n sq.subquery.alias,\n 'Subquery must have an alias',\n ),\n hidden: sq.hidden ?? false,\n system: sq.system ?? 'client',\n });\n delegate.addEdge(end, flippedJoin);\n delegate.addEdge(child, flippedJoin);\n end = delegate.decorateInput(\n flippedJoin,\n `${name}:flipped-join(${sq.subquery.alias})`,\n );\n break;\n }\n }\n\n return end;\n}\n\nfunction applyFilter(\n input: FilterInput,\n condition: Condition,\n delegate: BuilderDelegate,\n name: string,\n): FilterInput {\n switch (condition.type) {\n case 'and':\n return applyAnd(input, condition, delegate, name);\n case 'or':\n return applyOr(input, condition, delegate, name);\n case 'correlatedSubquery':\n return applyCorrelatedSubqueryCondition(input, condition, delegate, name);\n case 'simple':\n return applySimpleCondition(input, delegate, condition);\n }\n}\n\nfunction applyAnd(\n input: FilterInput,\n condition: Conjunction,\n delegate: BuilderDelegate,\n name: string,\n): FilterInput {\n for (const subCondition of condition.conditions) {\n input = applyFilter(input, subCondition, delegate, name);\n }\n return input;\n}\n\nexport function applyOr(\n input: FilterInput,\n condition: Disjunction,\n delegate: BuilderDelegate,\n name: string,\n): FilterInput {\n const [subqueryConditions, otherConditions] =\n groupSubqueryConditions(condition);\n // if there are no subquery conditions, no fan-in / fan-out is needed\n if (subqueryConditions.length === 0) {\n const filter = new Filter(\n input,\n createPredicate({\n type: 'or',\n conditions: otherConditions,\n }),\n );\n delegate.addEdge(input, filter);\n return filter;\n }\n\n const fanOut = new FanOut(input);\n delegate.addEdge(input, fanOut);\n const branches = subqueryConditions.map(subCondition =>\n applyFilter(fanOut, subCondition, delegate, name),\n );\n if (otherConditions.length > 0) {\n const filter = new Filter(\n fanOut,\n createPredicate({\n type: 'or',\n conditions: otherConditions,\n }),\n );\n delegate.addEdge(fanOut, filter);\n branches.push(filter);\n }\n const ret = new FanIn(fanOut, branches);\n for (const branch of branches) {\n delegate.addEdge(branch, ret);\n }\n fanOut.setFanIn(ret);\n return ret;\n}\n\nexport function groupSubqueryConditions(condition: Disjunction) {\n const partitioned: [\n subqueryConditions: Condition[],\n otherConditions: NoSubqueryCondition[],\n ] = [[], []];\n for (const subCondition of condition.conditions) {\n if (isNotAndDoesNotContainSubquery(subCondition)) {\n partitioned[1].push(subCondition);\n } else {\n partitioned[0].push(subCondition);\n }\n }\n return partitioned;\n}\n\nexport function isNotAndDoesNotContainSubquery(\n condition: Condition,\n): condition is NoSubqueryCondition {\n if (condition.type === 'correlatedSubquery') {\n return false;\n }\n if (condition.type === 'simple') {\n return true;\n }\n return condition.conditions.every(isNotAndDoesNotContainSubquery);\n}\n\nfunction applySimpleCondition(\n input: FilterInput,\n delegate: BuilderDelegate,\n condition: SimpleCondition,\n): FilterInput {\n const filter = new Filter(input, createPredicate(condition));\n delegate.decorateFilterInput(\n filter,\n `${valuePosName(condition.left)}:${condition.op}:${valuePosName(condition.right)}`,\n );\n delegate.addEdge(input, filter);\n return filter;\n}\n\nfunction valuePosName(left: ValuePosition) {\n switch (left.type) {\n case 'static':\n return left.field;\n case 'literal':\n return left.value;\n case 'column':\n return left.name;\n }\n}\n\nfunction applyCorrelatedSubQuery(\n sq: CorrelatedSubquery,\n delegate: BuilderDelegate,\n queryID: string,\n end: Input,\n name: string,\n fromCondition: boolean,\n) {\n // TODO: we only omit the join if the CSQ if from a condition since\n // we want to create an empty array for `related` fields that are `limit(0)`\n if (sq.subquery.limit === 0 && fromCondition) {\n return end;\n }\n\n assert(sq.subquery.alias, 'Subquery must have an alias');\n const child = buildPipelineInternal(\n sq.subquery,\n delegate,\n queryID,\n `${name}.${sq.subquery.alias}`,\n sq.correlation.childField,\n );\n\n const joinName = `${name}:join(${sq.subquery.alias})`;\n const join = new Join({\n parent: end,\n child,\n parentKey: sq.correlation.parentField,\n childKey: sq.correlation.childField,\n relationshipName: sq.subquery.alias,\n hidden: sq.hidden ?? false,\n system: sq.system ?? 'client',\n });\n delegate.addEdge(end, join);\n delegate.addEdge(child, join);\n return delegate.decorateInput(join, joinName);\n}\n\nfunction applyCorrelatedSubqueryCondition(\n input: FilterInput,\n condition: CorrelatedSubqueryCondition,\n delegate: BuilderDelegate,\n name: string,\n): FilterInput {\n assert(\n condition.op === 'EXISTS' || condition.op === 'NOT EXISTS',\n 'Expected EXISTS or NOT EXISTS operator',\n );\n if (condition.related.subquery.limit === 0) {\n if (condition.op === 'EXISTS') {\n const filter = new Filter(input, () => false);\n delegate.addEdge(input, filter);\n return filter;\n }\n const filter = new Filter(input, () => true);\n delegate.addEdge(input, filter);\n return filter;\n }\n const existsName = `${name}:exists(${condition.related.subquery.alias})`;\n const exists = new Exists(\n input,\n must(condition.related.subquery.alias),\n condition.related.correlation.parentField,\n condition.op,\n );\n delegate.addEdge(input, exists);\n return delegate.decorateFilterInput(exists, existsName);\n}\n\nfunction gatherCorrelatedSubqueryQueryConditions(\n condition: Condition | undefined,\n) {\n const csqs: CorrelatedSubqueryCondition[] = [];\n const gather = (condition: Condition) => {\n if (condition.type === 'correlatedSubquery') {\n csqs.push(condition);\n return;\n }\n if (condition.type === 'and' || condition.type === 'or') {\n for (const c of condition.conditions) {\n gather(c);\n }\n return;\n }\n };\n if (condition) {\n gather(condition);\n }\n return csqs;\n}\n\nexport function assertOrderingIncludesPK(\n ordering: Ordering,\n pk: PrimaryKey,\n): void {\n // oxlint-disable-next-line unicorn/prefer-set-has -- Array is more appropriate here for small collections\n const orderingFields = ordering.map(([field]) => field);\n const missingFields = pk.filter(pkField => !orderingFields.includes(pkField));\n\n if (missingFields.length > 0) {\n throw new Error(\n `Ordering must include all primary key fields. Missing: ${missingFields.join(\n ', ',\n )}. ZQL automatically appends primary key fields to the ordering if they are missing \n so a common cause of this error is a casing mismatch between Postgres and ZQL.\n E.g., \"userid\" vs \"userID\".\n You may want to add double-quotes around your Postgres column names to prevent Postgres from lower-casing them:\n https://www.postgresql.org/docs/current/sql-syntax-lexical.htm`,\n );\n }\n}\n\nfunction uniquifyCorrelatedSubqueryConditionAliases(ast: AST): AST {\n if (!ast.where) {\n return ast;\n }\n const {where} = ast;\n if (where.type !== 'and' && where.type !== 'or') {\n return ast;\n }\n\n let count = 0;\n const uniquifyCorrelatedSubquery = (csqc: CorrelatedSubqueryCondition) => ({\n ...csqc,\n related: {\n ...csqc.related,\n subquery: {\n ...csqc.related.subquery,\n alias: (csqc.related.subquery.alias ?? '') + '_' + count++,\n },\n },\n });\n\n const uniquify = (cond: Condition): Condition => {\n if (cond.type === 'simple') {\n return cond;\n } else if (cond.type === 'correlatedSubquery') {\n return uniquifyCorrelatedSubquery(cond);\n }\n const conditions = [];\n for (const c of cond.conditions) {\n conditions.push(uniquify(c));\n }\n return {\n type: cond.type,\n conditions,\n };\n };\n\n const result = {\n ...ast,\n where: uniquify(where),\n };\n return result;\n}\n\nexport function conditionIncludesFlippedSubqueryAtAnyLevel(\n cond: Condition,\n): boolean {\n if (cond.type === 'correlatedSubquery') {\n return !!cond.flip;\n }\n if (cond.type === 'and' || cond.type === 'or') {\n return cond.conditions.some(c =>\n conditionIncludesFlippedSubqueryAtAnyLevel(c),\n );\n }\n // simple conditions don't have flips\n return false;\n}\n\nexport function partitionBranches(\n conditions: readonly Condition[],\n predicate: (c: Condition) => boolean,\n) {\n const matched: Condition[] = [];\n const notMatched: Condition[] = [];\n for (const c of conditions) {\n if (predicate(c)) {\n matched.push(c);\n } else {\n notMatched.push(c);\n }\n }\n return [matched, notMatched] as const;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4HA,SAAgB,cACd,KACA,UACA,SACA,WACA,IACA,cACO;AACP,OAAM,SAAS,SAAS,SAAS,OAAO,IAAI,GAAG;AAC/C,OAAM,iBACJ,MACA,cAAa,KAAK,SAAS,UAAU,UAAU,CAAC,CAAC,YAAY,WAC9D;AAED,KAAI,UACF,OAAM,UAAU,KAAK,WAAW,cAAc,GAAG;AAEnD,QAAO,sBAAsB,KAAK,UAAU,SAAS,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AM;IAYnB,KAAK;IAQL,SAAS,CAAC,GAAG,EAAE,GAAG;CAGnB"}
@@ -1,8 +1,33 @@
1
1
  import { assert } from "../../../shared/src/asserts.js";
2
2
  import { emptyArray } from "../../../shared/src/sentinels.js";
3
- import { skipYields } from "./operator.js";
3
+ import { skipYields } from "./skip-yields.js";
4
4
  import { applyChange } from "./view-apply-change.js";
5
5
  //#region ../zql/src/ivm/array-view.ts
6
+ function changeToViewChange(change) {
7
+ switch (change[0]) {
8
+ case 0: return {
9
+ type: "add",
10
+ node: change[1]
11
+ };
12
+ case 1: return {
13
+ type: "remove",
14
+ node: change[1]
15
+ };
16
+ case 3: return {
17
+ type: "child",
18
+ node: change[1],
19
+ child: {
20
+ relationshipName: change[2].relationshipName,
21
+ change: changeToViewChange(change[2].change)
22
+ }
23
+ };
24
+ case 2: return {
25
+ type: "edit",
26
+ node: change[1],
27
+ oldNode: change[2]
28
+ };
29
+ }
30
+ }
6
31
  /**
7
32
  * Implements a materialized view of the output of an operator.
8
33
  *
@@ -76,7 +101,7 @@ var ArrayView = class {
76
101
  }
77
102
  push(change) {
78
103
  this.#dirty = true;
79
- applyChange(this.#root, change, this.#schema, "", this.#format);
104
+ applyChange(this.#root, changeToViewChange(change), this.#schema, "", this.#format);
80
105
  return emptyArray;
81
106
  }
82
107
  flush() {
@@ -1 +1 @@
1
- {"version":3,"file":"array-view.js","names":["#input","#listeners","#schema","#format","#root","#updateTTL","#resultType","#error","#fireListeners","#hydrate","#fireListener","#dirty"],"sources":["../../../../../zql/src/ivm/array-view.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Immutable} from '../../../shared/src/immutable.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {ErroredQuery} from '../../../zero-protocol/src/custom-queries.ts';\nimport type {TTL} from '../query/ttl.ts';\nimport type {Listener, ResultType, TypedView} from '../query/typed-view.ts';\nimport type {Change} from './change.ts';\nimport {skipYields, type Input, type Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {applyChange} from './view-apply-change.ts';\nimport type {Entry, Format, View} from './view.ts';\n\n/**\n * Implements a materialized view of the output of an operator.\n *\n * It might seem more efficient to use an immutable b-tree for the\n * materialization, but it's not so clear. Inserts in the middle are\n * asymptotically slower in an array, but can often be done with zero\n * allocations, where changes to the b-tree will often require several allocs.\n *\n * Also the plain array view is more convenient for consumers since you can dump\n * it into console to see what it is, rather than having to iterate it.\n */\nexport class ArrayView<V extends View> implements Output, TypedView<V> {\n readonly #input: Input;\n readonly #listeners = new Set<Listener<V>>();\n readonly #schema: SourceSchema;\n readonly #format: Format;\n\n // Synthetic \"root\" entry that has a single \"\" relationship, so that we can\n // treat all changes, including the root change, generically.\n readonly #root: Entry;\n\n onDestroy: (() => void) | undefined;\n\n #dirty = false;\n #resultType: ResultType = 'unknown';\n #error: ErroredQuery | undefined;\n readonly #updateTTL: (ttl: TTL) => void;\n\n constructor(\n input: Input,\n format: Format,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n this.#input = input;\n this.#schema = input.getSchema();\n this.#format = format;\n this.#updateTTL = updateTTL;\n this.#root = {'': format.singular ? undefined : []};\n input.setOutput(this);\n\n if (queryComplete === true) {\n this.#resultType = 'complete';\n } else if ('error' in queryComplete) {\n this.#resultType = 'error';\n this.#error = queryComplete;\n } else {\n void queryComplete\n .then(() => {\n this.#resultType = 'complete';\n this.#fireListeners();\n })\n .catch(e => {\n this.#resultType = 'error';\n this.#error = e;\n this.#fireListeners();\n });\n }\n this.#hydrate();\n }\n\n get data() {\n return this.#root[''] as V;\n }\n\n addListener(listener: Listener<V>) {\n assert(!this.#listeners.has(listener), 'Listener already registered');\n this.#listeners.add(listener);\n\n this.#fireListener(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #fireListeners() {\n for (const listener of this.#listeners) {\n this.#fireListener(listener);\n }\n }\n\n #fireListener(listener: Listener<V>) {\n listener(this.data as Immutable<V>, this.#resultType, this.#error);\n }\n\n destroy() {\n this.onDestroy?.();\n }\n\n #hydrate() {\n this.#dirty = true;\n for (const node of skipYields(this.#input.fetch({}))) {\n applyChange(\n this.#root,\n {type: 'add', node},\n this.#schema,\n '',\n this.#format,\n );\n }\n this.flush();\n }\n\n push(change: Change) {\n this.#dirty = true;\n applyChange(this.#root, change, this.#schema, '', this.#format);\n return emptyArray;\n }\n\n flush() {\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n this.#fireListeners();\n }\n\n updateTTL(ttl: TTL) {\n this.#updateTTL(ttl);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,IAAa,YAAb,MAAuE;CACrE;CACA,6BAAsB,IAAI,KAAkB;CAC5C;CACA;CAIA;CAEA;CAEA,SAAS;CACT,cAA0B;CAC1B;CACA;CAEA,YACE,OACA,QACA,eACA,WACA;AACA,QAAA,QAAc;AACd,QAAA,SAAe,MAAM,WAAW;AAChC,QAAA,SAAe;AACf,QAAA,YAAkB;AAClB,QAAA,OAAa,EAAC,IAAI,OAAO,WAAW,KAAA,IAAY,EAAE,EAAC;AACnD,QAAM,UAAU,KAAK;AAErB,MAAI,kBAAkB,KACpB,OAAA,aAAmB;WACV,WAAW,eAAe;AACnC,SAAA,aAAmB;AACnB,SAAA,QAAc;QAET,eACF,WAAW;AACV,SAAA,aAAmB;AACnB,SAAA,eAAqB;IACrB,CACD,OAAM,MAAK;AACV,SAAA,aAAmB;AACnB,SAAA,QAAc;AACd,SAAA,eAAqB;IACrB;AAEN,QAAA,SAAe;;CAGjB,IAAI,OAAO;AACT,SAAO,MAAA,KAAW;;CAGpB,YAAY,UAAuB;AACjC,SAAO,CAAC,MAAA,UAAgB,IAAI,SAAS,EAAE,8BAA8B;AACrE,QAAA,UAAgB,IAAI,SAAS;AAE7B,QAAA,aAAmB,SAAS;AAE5B,eAAa;AACX,SAAA,UAAgB,OAAO,SAAS;;;CAIpC,iBAAiB;AACf,OAAK,MAAM,YAAY,MAAA,UACrB,OAAA,aAAmB,SAAS;;CAIhC,cAAc,UAAuB;AACnC,WAAS,KAAK,MAAsB,MAAA,YAAkB,MAAA,MAAY;;CAGpE,UAAU;AACR,OAAK,aAAa;;CAGpB,WAAW;AACT,QAAA,QAAc;AACd,OAAK,MAAM,QAAQ,WAAW,MAAA,MAAY,MAAM,EAAE,CAAC,CAAC,CAClD,aACE,MAAA,MACA;GAAC,MAAM;GAAO;GAAK,EACnB,MAAA,QACA,IACA,MAAA,OACD;AAEH,OAAK,OAAO;;CAGd,KAAK,QAAgB;AACnB,QAAA,QAAc;AACd,cAAY,MAAA,MAAY,QAAQ,MAAA,QAAc,IAAI,MAAA,OAAa;AAC/D,SAAO;;CAGT,QAAQ;AACN,MAAI,CAAC,MAAA,MACH;AAEF,QAAA,QAAc;AACd,QAAA,eAAqB;;CAGvB,UAAU,KAAU;AAClB,QAAA,UAAgB,IAAI"}
1
+ {"version":3,"file":"array-view.js","names":["#input","#listeners","#schema","#format","#root","#updateTTL","#resultType","#error","#fireListeners","#hydrate","#fireListener","#dirty"],"sources":["../../../../../zql/src/ivm/array-view.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Immutable} from '../../../shared/src/immutable.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {ErroredQuery} from '../../../zero-protocol/src/custom-queries.ts';\nimport type {TTL} from '../query/ttl.ts';\nimport type {Listener, ResultType, TypedView} from '../query/typed-view.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport {skipYields, type Input, type Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {applyChange, type ViewChange} from './view-apply-change.ts';\nimport type {Entry, Format, View} from './view.ts';\n\nfunction changeToViewChange(change: Change): ViewChange {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n return {type: 'add', node: change[ChangeIndex.NODE]};\n case ChangeType.REMOVE:\n return {type: 'remove', node: change[ChangeIndex.NODE]};\n case ChangeType.CHILD:\n return {\n type: 'child',\n node: change[ChangeIndex.NODE],\n child: {\n relationshipName: change[ChangeIndex.CHILD_DATA].relationshipName,\n change: changeToViewChange(change[ChangeIndex.CHILD_DATA].change),\n },\n };\n case ChangeType.EDIT:\n return {\n type: 'edit',\n node: change[ChangeIndex.NODE],\n oldNode: change[ChangeIndex.OLD_NODE],\n };\n }\n}\n\n/**\n * Implements a materialized view of the output of an operator.\n *\n * It might seem more efficient to use an immutable b-tree for the\n * materialization, but it's not so clear. Inserts in the middle are\n * asymptotically slower in an array, but can often be done with zero\n * allocations, where changes to the b-tree will often require several allocs.\n *\n * Also the plain array view is more convenient for consumers since you can dump\n * it into console to see what it is, rather than having to iterate it.\n */\nexport class ArrayView<V extends View> implements Output, TypedView<V> {\n readonly #input: Input;\n readonly #listeners = new Set<Listener<V>>();\n readonly #schema: SourceSchema;\n readonly #format: Format;\n\n // Synthetic \"root\" entry that has a single \"\" relationship, so that we can\n // treat all changes, including the root change, generically.\n readonly #root: Entry;\n\n onDestroy: (() => void) | undefined;\n\n #dirty = false;\n #resultType: ResultType = 'unknown';\n #error: ErroredQuery | undefined;\n readonly #updateTTL: (ttl: TTL) => void;\n\n constructor(\n input: Input,\n format: Format,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n this.#input = input;\n this.#schema = input.getSchema();\n this.#format = format;\n this.#updateTTL = updateTTL;\n this.#root = {'': format.singular ? undefined : []};\n input.setOutput(this);\n\n if (queryComplete === true) {\n this.#resultType = 'complete';\n } else if ('error' in queryComplete) {\n this.#resultType = 'error';\n this.#error = queryComplete;\n } else {\n void queryComplete\n .then(() => {\n this.#resultType = 'complete';\n this.#fireListeners();\n })\n .catch(e => {\n this.#resultType = 'error';\n this.#error = e;\n this.#fireListeners();\n });\n }\n this.#hydrate();\n }\n\n get data() {\n return this.#root[''] as V;\n }\n\n addListener(listener: Listener<V>) {\n assert(!this.#listeners.has(listener), 'Listener already registered');\n this.#listeners.add(listener);\n\n this.#fireListener(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #fireListeners() {\n for (const listener of this.#listeners) {\n this.#fireListener(listener);\n }\n }\n\n #fireListener(listener: Listener<V>) {\n listener(this.data as Immutable<V>, this.#resultType, this.#error);\n }\n\n destroy() {\n this.onDestroy?.();\n }\n\n #hydrate() {\n this.#dirty = true;\n for (const node of skipYields(this.#input.fetch({}))) {\n applyChange(\n this.#root,\n {type: 'add', node},\n this.#schema,\n '',\n this.#format,\n );\n }\n this.flush();\n }\n\n push(change: Change) {\n this.#dirty = true;\n applyChange(\n this.#root,\n changeToViewChange(change),\n this.#schema,\n '',\n this.#format,\n );\n return emptyArray;\n }\n\n flush() {\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n this.#fireListeners();\n }\n\n updateTTL(ttl: TTL) {\n this.#updateTTL(ttl);\n }\n}\n"],"mappings":";;;;;AAcA,SAAS,mBAAmB,QAA4B;AACtD,SAAQ,OAAO,IAAf;EACE,KAAK,EACH,QAAO;GAAC,MAAM;GAAO,MAAM,OAAO;GAAkB;EACtD,KAAK,EACH,QAAO;GAAC,MAAM;GAAU,MAAM,OAAO;GAAkB;EACzD,KAAK,EACH,QAAO;GACL,MAAM;GACN,MAAM,OAAO;GACb,OAAO;IACL,kBAAkB,OAAO,GAAwB;IACjD,QAAQ,mBAAmB,OAAO,GAAwB,OAAO;IAClE;GACF;EACH,KAAK,EACH,QAAO;GACL,MAAM;GACN,MAAM,OAAO;GACb,SAAS,OAAO;GACjB;;;;;;;;;;;;;;AAeP,IAAa,YAAb,MAAuE;CACrE;CACA,6BAAsB,IAAI,KAAkB;CAC5C;CACA;CAIA;CAEA;CAEA,SAAS;CACT,cAA0B;CAC1B;CACA;CAEA,YACE,OACA,QACA,eACA,WACA;AACA,QAAA,QAAc;AACd,QAAA,SAAe,MAAM,WAAW;AAChC,QAAA,SAAe;AACf,QAAA,YAAkB;AAClB,Q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export declare const OLD_NODE = 2;
4
+ export declare const CHILD_DATA = 2;
5
+ export type TYPE = typeof TYPE;
6
+ export type NODE = typeof NODE;
7
+ export type OLD_NODE = typeof OLD_NODE;
8
+ export type CHILD_DATA = typeof CHILD_DATA;
9
+ //# sourceMappingURL=change-index-enum.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"change-index-enum.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/change-index-enum.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,IAAI,IAAI,CAAC;AACtB,eAAO,MAAM,IAAI,IAAI,CAAC;AACtB,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,UAAU,IAAI,CAAC;AAE5B,MAAM,MAAM,IAAI,GAAG,OAAO,IAAI,CAAC;AAC/B,MAAM,MAAM,IAAI,GAAG,OAAO,IAAI,CAAC;AAC/B,MAAM,MAAM,QAAQ,GAAG,OAAO,QAAQ,CAAC;AACvC,MAAM,MAAM,UAAU,GAAG,OAAO,UAAU,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { Enum } from '../../../shared/src/enum.ts';
2
+ import * as ChangeIndexEnum from './change-index-enum.ts';
3
+ export { ChangeIndexEnum as ChangeIndex };
4
+ export type ChangeIndex = Enum<typeof ChangeIndexEnum>;
5
+ //# sourceMappingURL=change-index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"change-index.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/change-index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,6BAA6B,CAAC;AACtD,OAAO,KAAK,eAAe,MAAM,wBAAwB,CAAC;AAE1D,OAAO,EAAC,eAAe,IAAI,WAAW,EAAC,CAAC;AACxC,MAAM,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,eAAe,CAAC,CAAC"}
@@ -0,0 +1,9 @@
1
+ export declare const ADD = 0;
2
+ export declare const REMOVE = 1;
3
+ export declare const EDIT = 2;
4
+ export declare const CHILD = 3;
5
+ export type ADD = typeof ADD;
6
+ export type REMOVE = typeof REMOVE;
7
+ export type EDIT = typeof EDIT;
8
+ export type CHILD = typeof CHILD;
9
+ //# sourceMappingURL=change-type-enum.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"change-type-enum.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/change-type-enum.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,GAAG,IAAI,CAAC;AACrB,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,IAAI,IAAI,CAAC;AACtB,eAAO,MAAM,KAAK,IAAI,CAAC;AAEvB,MAAM,MAAM,GAAG,GAAG,OAAO,GAAG,CAAC;AAC7B,MAAM,MAAM,MAAM,GAAG,OAAO,MAAM,CAAC;AACnC,MAAM,MAAM,IAAI,GAAG,OAAO,IAAI,CAAC;AAC/B,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { Enum } from '../../../shared/src/enum.ts';
2
+ import * as ChangeTypeEnum from './change-type-enum.ts';
3
+ export { ChangeTypeEnum as ChangeType };
4
+ export type ChangeType = Enum<typeof ChangeTypeEnum>;
5
+ //# sourceMappingURL=change-type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"change-type.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/change-type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,6BAA6B,CAAC;AACtD,OAAO,KAAK,cAAc,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAC,cAAc,IAAI,UAAU,EAAC,CAAC;AACtC,MAAM,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,cAAc,CAAC,CAAC"}
@@ -1,33 +1,31 @@
1
+ import { ChangeType } from './change-type.ts';
1
2
  import type { Node } from './data.ts';
3
+ /**
4
+ * The `child` payload carried by a {@linkcode ChildChange}.
5
+ */
6
+ export type ChildData = {
7
+ relationshipName: string;
8
+ change: Change;
9
+ };
2
10
  export type Change = AddChange | RemoveChange | ChildChange | EditChange;
3
- export type ChangeType = Change['type'];
4
11
  /**
5
12
  * Represents a node (and all its children) getting added to the result.
6
13
  */
7
- export type AddChange = {
8
- type: 'add';
9
- node: Node;
10
- };
14
+ export type AddChange = [type: ChangeType.ADD, node: Node, extra: null];
11
15
  /**
12
16
  * Represents a node (and all its children) getting removed from the result.
13
17
  */
14
- export type RemoveChange = {
15
- type: 'remove';
16
- node: Node;
17
- };
18
+ export type RemoveChange = [type: ChangeType.REMOVE, node: Node, extra: null];
18
19
  /**
19
20
  * The node's row is unchanged, but one of its descendants has changed.
20
21
  * The node's relationships will reflect the change, `child` specifies the
21
22
  * specific descendant change.
22
23
  */
23
- export type ChildChange = {
24
- type: 'child';
25
- node: Node;
26
- child: {
27
- relationshipName: string;
28
- change: Change;
29
- };
30
- };
24
+ export type ChildChange = [
25
+ type: ChangeType.CHILD,
26
+ node: Node,
27
+ child: ChildData
28
+ ];
31
29
  /**
32
30
  * The row changed (in a way that the {@linkcode Source} determines). Most
33
31
  * likely the PK stayed the same but there is really no restriction in how it
@@ -50,9 +48,9 @@ export type ChildChange = {
50
48
  * the add. This cleanup could be done if we move to multi-use Streams
51
49
  * for relationships.
52
50
  */
53
- export type EditChange = {
54
- type: 'edit';
55
- node: Node;
56
- oldNode: Node;
57
- };
51
+ export type EditChange = [type: ChangeType.EDIT, node: Node, oldNode: Node];
52
+ export declare function makeAddChange(node: Node): AddChange;
53
+ export declare function makeRemoveChange(node: Node): RemoveChange;
54
+ export declare function makeChildChange(node: Node, child: ChildData): ChildChange;
55
+ export declare function makeEditChange(node: Node, oldNode: Node): EditChange;
58
56
  //# sourceMappingURL=change.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"change.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/change.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,IAAI,EAAC,MAA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,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;AAExE;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;AAE9E;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,IAAI,EAAE,UAAU,CAAC,KAAK;IACtB,IAAI,EAAE,IAAI;IACV,KAAK,EAAE,SAAS;CACjB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;AAI5E,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,CAEnD;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,IAAI,GAAG,YAAY,CAEzD;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,GAAG,WAAW,CAEzE;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,GAAG,UAAU,CAEpE"}
@@ -0,0 +1,33 @@
1
+ //#region ../zql/src/ivm/change.ts
2
+ function makeAddChange(node) {
3
+ return [
4
+ 0,
5
+ node,
6
+ null
7
+ ];
8
+ }
9
+ function makeRemoveChange(node) {
10
+ return [
11
+ 1,
12
+ node,
13
+ null
14
+ ];
15
+ }
16
+ function makeChildChange(node, child) {
17
+ return [
18
+ 3,
19
+ node,
20
+ child
21
+ ];
22
+ }
23
+ function makeEditChange(node, oldNode) {
24
+ return [
25
+ 2,
26
+ node,
27
+ oldNode
28
+ ];
29
+ }
30
+ //#endregion
31
+ export { makeAddChange, makeChildChange, makeEditChange, makeRemoveChange };
32
+
33
+ //# sourceMappingURL=change.js.map