@rocicorp/zero 0.11.2025011402 → 0.11.2025011801

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 (282) hide show
  1. package/out/{chunk-AII6TS5B.js → chunk-QV5ZN4MA.js} +635 -1834
  2. package/out/chunk-QV5ZN4MA.js.map +7 -0
  3. package/out/react.js.map +2 -2
  4. package/out/shared/src/btree-set.d.ts +34 -0
  5. package/out/shared/src/btree-set.d.ts.map +1 -0
  6. package/out/shared/src/btree-set.js +528 -0
  7. package/out/shared/src/btree-set.js.map +1 -0
  8. package/out/shared/src/expand.d.ts +3 -0
  9. package/out/shared/src/expand.d.ts.map +1 -1
  10. package/out/solid.js +7 -2
  11. package/out/solid.js.map +2 -2
  12. package/out/zero-advanced/src/mod.d.ts +1 -1
  13. package/out/zero-advanced/src/mod.d.ts.map +1 -1
  14. package/out/zero-cache/src/auth/load-schema.d.ts +1 -1
  15. package/out/zero-cache/src/auth/load-schema.d.ts.map +1 -1
  16. package/out/zero-cache/src/auth/write-authorizer.d.ts +1 -1
  17. package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
  18. package/out/zero-cache/src/auth/write-authorizer.js +3 -6
  19. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  20. package/out/zero-cache/src/db/lite-tables.d.ts +14 -1
  21. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  22. package/out/zero-cache/src/db/lite-tables.js +89 -6
  23. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  24. package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
  25. package/out/zero-cache/src/db/pg-to-lite.js +3 -1
  26. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  27. package/out/zero-cache/src/db/postgres-replica-identity-enum.d.ts +9 -0
  28. package/out/zero-cache/src/db/postgres-replica-identity-enum.d.ts.map +1 -0
  29. package/out/zero-cache/src/db/postgres-replica-identity-enum.js +7 -0
  30. package/out/zero-cache/src/db/postgres-replica-identity-enum.js.map +1 -0
  31. package/out/zero-cache/src/db/specs.d.ts +39 -10
  32. package/out/zero-cache/src/db/specs.d.ts.map +1 -1
  33. package/out/zero-cache/src/db/specs.js +8 -1
  34. package/out/zero-cache/src/db/specs.js.map +1 -1
  35. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  36. package/out/zero-cache/src/server/change-streamer.js +1 -1
  37. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  38. package/out/zero-cache/src/server/life-cycle.d.ts +2 -2
  39. package/out/zero-cache/src/server/life-cycle.d.ts.map +1 -1
  40. package/out/zero-cache/src/server/life-cycle.js +12 -3
  41. package/out/zero-cache/src/server/life-cycle.js.map +1 -1
  42. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  43. package/out/zero-cache/src/server/main.js +11 -6
  44. package/out/zero-cache/src/server/main.js.map +1 -1
  45. package/out/zero-cache/src/server/multi/config.d.ts +14 -14
  46. package/out/zero-cache/src/server/multi/config.d.ts.map +1 -1
  47. package/out/zero-cache/src/server/multi/config.js +24 -2
  48. package/out/zero-cache/src/server/multi/config.js.map +1 -1
  49. package/out/zero-cache/src/server/multi/main.d.ts.map +1 -1
  50. package/out/zero-cache/src/server/multi/main.js +28 -8
  51. package/out/zero-cache/src/server/multi/main.js.map +1 -1
  52. package/out/zero-cache/src/server/multi/tenant-dispatcher.d.ts +1 -1
  53. package/out/zero-cache/src/server/multi/tenant-dispatcher.d.ts.map +1 -1
  54. package/out/zero-cache/src/server/multi/tenant-dispatcher.js +15 -3
  55. package/out/zero-cache/src/server/multi/tenant-dispatcher.js.map +1 -1
  56. package/out/zero-cache/src/server/replicator.js +2 -3
  57. package/out/zero-cache/src/server/replicator.js.map +1 -1
  58. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +4 -4
  59. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  60. package/out/zero-cache/src/services/change-source/pg/change-source.js +50 -32
  61. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  62. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +45 -25
  63. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  64. package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
  65. package/out/zero-cache/src/services/change-source/pg/schema/init.js +6 -28
  66. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  67. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +18 -10
  68. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
  69. package/out/zero-cache/src/services/change-source/pg/schema/published.js +14 -7
  70. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  71. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +7 -4
  72. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  73. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +29 -1
  74. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  75. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +2 -2
  76. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
  77. package/out/zero-cache/src/services/change-source/pg/schema/validation.js +8 -4
  78. package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
  79. package/out/zero-cache/src/services/change-source/pg/sync-schema.d.ts.map +1 -1
  80. package/out/zero-cache/src/services/change-source/pg/sync-schema.js +1 -0
  81. package/out/zero-cache/src/services/change-source/pg/sync-schema.js.map +1 -1
  82. package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts +10 -10
  83. package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts +17 -15
  84. package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts.map +1 -1
  85. package/out/zero-cache/src/services/change-source/protocol/current/downstream.js +2 -1
  86. package/out/zero-cache/src/services/change-source/protocol/current/downstream.js.map +1 -1
  87. package/out/zero-cache/src/services/change-source/protocol/current/mod.d.ts +1 -0
  88. package/out/zero-cache/src/services/change-source/protocol/current/mod.d.ts.map +1 -1
  89. package/out/zero-cache/src/services/change-source/protocol/current/mod.js +1 -0
  90. package/out/zero-cache/src/services/change-source/protocol/current/mod.js.map +1 -1
  91. package/out/zero-cache/src/services/change-source/protocol/current/status.d.ts +38 -0
  92. package/out/zero-cache/src/services/change-source/protocol/current/status.d.ts.map +1 -0
  93. package/out/zero-cache/src/services/change-source/protocol/current/status.js +14 -0
  94. package/out/zero-cache/src/services/change-source/protocol/current/status.js.map +1 -0
  95. package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts +3 -13
  96. package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts.map +1 -1
  97. package/out/zero-cache/src/services/change-source/protocol/current/upstream.js +3 -10
  98. package/out/zero-cache/src/services/change-source/protocol/current/upstream.js.map +1 -1
  99. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +7 -3
  100. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  101. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +30 -24
  102. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  103. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +6 -4
  104. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  105. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +4 -1
  106. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  107. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +5 -5
  108. package/out/zero-cache/src/services/change-streamer/storer.d.ts +3 -1
  109. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  110. package/out/zero-cache/src/services/change-streamer/storer.js +18 -10
  111. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  112. package/out/zero-cache/src/services/dispatcher/websocket-handoff.d.ts.map +1 -1
  113. package/out/zero-cache/src/services/dispatcher/websocket-handoff.js +2 -16
  114. package/out/zero-cache/src/services/dispatcher/websocket-handoff.js.map +1 -1
  115. package/out/zero-cache/src/services/http-service.d.ts +1 -1
  116. package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
  117. package/out/zero-cache/src/services/http-service.js +1 -0
  118. package/out/zero-cache/src/services/http-service.js.map +1 -1
  119. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  120. package/out/zero-cache/src/services/litestream/commands.js +6 -2
  121. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  122. package/out/zero-cache/src/services/mutagen/mutagen.d.ts +1 -1
  123. package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
  124. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +1 -1
  125. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  126. package/out/zero-cache/src/services/replicator/incremental-sync.js +15 -5
  127. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  128. package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
  129. package/out/zero-cache/src/services/replicator/replicator.js +4 -2
  130. package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
  131. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
  132. package/out/zero-cache/src/services/view-syncer/cvr-store.js +20 -51
  133. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  134. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +0 -5
  135. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  136. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +18 -35
  137. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  138. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +3 -3
  139. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  140. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  141. package/out/zero-cache/src/types/processes.d.ts.map +1 -1
  142. package/out/zero-cache/src/types/processes.js +17 -2
  143. package/out/zero-cache/src/types/processes.js.map +1 -1
  144. package/out/zero-cache/src/types/row-key.d.ts.map +1 -1
  145. package/out/zero-cache/src/types/row-key.js +7 -1
  146. package/out/zero-cache/src/types/row-key.js.map +1 -1
  147. package/out/zero-cache/src/types/ws.d.ts +4 -0
  148. package/out/zero-cache/src/types/ws.d.ts.map +1 -0
  149. package/out/zero-cache/src/types/ws.js +19 -0
  150. package/out/zero-cache/src/types/ws.js.map +1 -0
  151. package/out/zero-client/src/client/context.d.ts.map +1 -1
  152. package/out/zero-client/src/client/crud.d.ts +3 -4
  153. package/out/zero-client/src/client/crud.d.ts.map +1 -1
  154. package/out/zero-client/src/client/keys.d.ts +2 -2
  155. package/out/zero-client/src/client/keys.d.ts.map +1 -1
  156. package/out/zero-client/src/client/zero-poke-handler.d.ts +3 -3
  157. package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
  158. package/out/zero-client/src/client/zero.d.ts +1 -1
  159. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  160. package/out/zero-client/src/mod.d.ts +5 -4
  161. package/out/zero-client/src/mod.d.ts.map +1 -1
  162. package/out/zero-react/src/use-query.d.ts +6 -5
  163. package/out/zero-react/src/use-query.d.ts.map +1 -1
  164. package/out/zero-schema/src/builder/relationship-builder.d.ts +50 -0
  165. package/out/zero-schema/src/builder/relationship-builder.d.ts.map +1 -0
  166. package/out/zero-schema/src/builder/relationship-builder.js +24 -0
  167. package/out/zero-schema/src/builder/relationship-builder.js.map +1 -0
  168. package/out/zero-schema/src/builder/schema-builder.d.ts +40 -0
  169. package/out/zero-schema/src/builder/schema-builder.d.ts.map +1 -0
  170. package/out/zero-schema/src/builder/schema-builder.js +51 -0
  171. package/out/zero-schema/src/builder/schema-builder.js.map +1 -0
  172. package/out/zero-schema/src/builder/table-builder.d.ts +69 -0
  173. package/out/zero-schema/src/builder/table-builder.d.ts.map +1 -0
  174. package/out/zero-schema/src/builder/table-builder.js +102 -0
  175. package/out/zero-schema/src/builder/table-builder.js.map +1 -0
  176. package/out/zero-schema/src/mod.d.ts +2 -2
  177. package/out/zero-schema/src/mod.d.ts.map +1 -1
  178. package/out/zero-schema/src/permissions.d.ts +11 -12
  179. package/out/zero-schema/src/permissions.d.ts.map +1 -1
  180. package/out/zero-schema/src/schema-config.d.ts +2 -4
  181. package/out/zero-schema/src/schema-config.d.ts.map +1 -1
  182. package/out/zero-schema/src/schema-config.js +12 -61
  183. package/out/zero-schema/src/schema-config.js.map +1 -1
  184. package/out/zero-schema/src/table-schema.d.ts +28 -53
  185. package/out/zero-schema/src/table-schema.d.ts.map +1 -1
  186. package/out/zero-schema/src/table-schema.js +6 -13
  187. package/out/zero-schema/src/table-schema.js.map +1 -1
  188. package/out/zero-solid/src/solid-view.d.ts +4 -3
  189. package/out/zero-solid/src/solid-view.d.ts.map +1 -1
  190. package/out/zero-solid/src/use-query.d.ts +5 -4
  191. package/out/zero-solid/src/use-query.d.ts.map +1 -1
  192. package/out/zero.js +17 -7
  193. package/out/zql/src/ivm/exists.d.ts +1 -1
  194. package/out/zql/src/ivm/exists.d.ts.map +1 -1
  195. package/out/zql/src/ivm/exists.js +3 -3
  196. package/out/zql/src/ivm/exists.js.map +1 -1
  197. package/out/zql/src/ivm/fan-in.d.ts +1 -1
  198. package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
  199. package/out/zql/src/ivm/fan-in.js +3 -2
  200. package/out/zql/src/ivm/fan-in.js.map +1 -1
  201. package/out/zql/src/ivm/filter.d.ts +1 -1
  202. package/out/zql/src/ivm/filter.d.ts.map +1 -1
  203. package/out/zql/src/ivm/filter.js +3 -3
  204. package/out/zql/src/ivm/filter.js.map +1 -1
  205. package/out/zql/src/ivm/join.d.ts +1 -1
  206. package/out/zql/src/ivm/join.d.ts.map +1 -1
  207. package/out/zql/src/ivm/join.js +2 -3
  208. package/out/zql/src/ivm/join.js.map +1 -1
  209. package/out/zql/src/ivm/memory-source.js +8 -10
  210. package/out/zql/src/ivm/memory-source.js.map +1 -1
  211. package/out/zql/src/ivm/memory-storage.d.ts.map +1 -1
  212. package/out/zql/src/ivm/operator.d.ts +5 -0
  213. package/out/zql/src/ivm/operator.d.ts.map +1 -1
  214. package/out/zql/src/ivm/operator.js +9 -0
  215. package/out/zql/src/ivm/operator.js.map +1 -1
  216. package/out/zql/src/ivm/skip.d.ts +1 -1
  217. package/out/zql/src/ivm/skip.d.ts.map +1 -1
  218. package/out/zql/src/ivm/skip.js +2 -3
  219. package/out/zql/src/ivm/skip.js.map +1 -1
  220. package/out/zql/src/ivm/take.d.ts +1 -1
  221. package/out/zql/src/ivm/take.d.ts.map +1 -1
  222. package/out/zql/src/ivm/take.js +2 -3
  223. package/out/zql/src/ivm/take.js.map +1 -1
  224. package/out/zql/src/ivm/view.d.ts +3 -3
  225. package/out/zql/src/ivm/view.d.ts.map +1 -1
  226. package/out/zql/src/query/auth-query.d.ts +9 -10
  227. package/out/zql/src/query/auth-query.d.ts.map +1 -1
  228. package/out/zql/src/query/auth-query.js +6 -7
  229. package/out/zql/src/query/auth-query.js.map +1 -1
  230. package/out/zql/src/query/expression.d.ts +11 -13
  231. package/out/zql/src/query/expression.d.ts.map +1 -1
  232. package/out/zql/src/query/expression.js +1 -1
  233. package/out/zql/src/query/expression.js.map +1 -1
  234. package/out/zql/src/query/query-impl.d.ts +26 -25
  235. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  236. package/out/zql/src/query/query-impl.js +76 -52
  237. package/out/zql/src/query/query-impl.js.map +1 -1
  238. package/out/zql/src/query/query-internal.d.ts +5 -5
  239. package/out/zql/src/query/query-internal.d.ts.map +1 -1
  240. package/out/zql/src/query/query.d.ts +37 -80
  241. package/out/zql/src/query/query.d.ts.map +1 -1
  242. package/out/zql/src/query/query.js +0 -1
  243. package/out/zql/src/query/query.js.map +1 -1
  244. package/out/zqlite/src/table-source.d.ts.map +1 -1
  245. package/out/zqlite/src/table-source.js +33 -11
  246. package/out/zqlite/src/table-source.js.map +1 -1
  247. package/package.json +4 -4
  248. package/out/btree/b+tree.d.ts +0 -471
  249. package/out/btree/b+tree.d.ts.map +0 -1
  250. package/out/btree/b+tree.js +0 -1708
  251. package/out/btree/b+tree.js.map +0 -1
  252. package/out/btree/interfaces.d.ts +0 -270
  253. package/out/btree/interfaces.d.ts.map +0 -1
  254. package/out/btree/interfaces.js +0 -3
  255. package/out/btree/interfaces.js.map +0 -1
  256. package/out/btree/src/mod.d.ts +0 -2
  257. package/out/btree/src/mod.d.ts.map +0 -1
  258. package/out/btree/src/mod.js +0 -2
  259. package/out/btree/src/mod.js.map +0 -1
  260. package/out/chunk-AII6TS5B.js.map +0 -7
  261. package/out/shared/src/sorted-entries.d.ts +0 -2
  262. package/out/shared/src/sorted-entries.d.ts.map +0 -1
  263. package/out/shared/src/sorted-entries.js +0 -6
  264. package/out/shared/src/sorted-entries.js.map +0 -1
  265. package/out/zero-cache/src/db/queries.d.ts +0 -24
  266. package/out/zero-cache/src/db/queries.d.ts.map +0 -1
  267. package/out/zero-cache/src/db/queries.js +0 -60
  268. package/out/zero-cache/src/db/queries.js.map +0 -1
  269. package/out/zero-schema/src/column.d.ts +0 -79
  270. package/out/zero-schema/src/column.d.ts.map +0 -1
  271. package/out/zero-schema/src/normalize-table-schema.d.ts +0 -51
  272. package/out/zero-schema/src/normalize-table-schema.d.ts.map +0 -1
  273. package/out/zero-schema/src/normalize-table-schema.js +0 -122
  274. package/out/zero-schema/src/normalize-table-schema.js.map +0 -1
  275. package/out/zero-schema/src/normalized-schema.d.ts +0 -22
  276. package/out/zero-schema/src/normalized-schema.d.ts.map +0 -1
  277. package/out/zero-schema/src/normalized-schema.js +0 -48
  278. package/out/zero-schema/src/normalized-schema.js.map +0 -1
  279. package/out/zero-schema/src/schema.d.ts +0 -9
  280. package/out/zero-schema/src/schema.d.ts.map +0 -1
  281. package/out/zero-schema/src/schema.js +0 -9
  282. package/out/zero-schema/src/schema.js.map +0 -1
@@ -1311,7 +1311,7 @@ function* joinIterables(...iters) {
1311
1311
  yield* iter;
1312
1312
  }
1313
1313
  }
1314
- function* mergeIterables(iterables, comparator, distinct = false) {
1314
+ function* mergeIterables(iterables, comparator2, distinct = false) {
1315
1315
  const iterators = iterables.map((i) => i[Symbol.iterator]());
1316
1316
  try {
1317
1317
  const current = iterators.map((i) => i.next());
@@ -1322,7 +1322,7 @@ function* mergeIterables(iterables, comparator, distinct = false) {
1322
1322
  if (c.done) {
1323
1323
  return acc;
1324
1324
  }
1325
- if (acc === void 0 || comparator(c.value, acc[0]) < 0) {
1325
+ if (acc === void 0 || comparator2(c.value, acc[0]) < 0) {
1326
1326
  return [c.value, i];
1327
1327
  }
1328
1328
  return acc;
@@ -1331,7 +1331,7 @@ function* mergeIterables(iterables, comparator, distinct = false) {
1331
1331
  );
1332
1332
  assert(min !== void 0, "min is undefined");
1333
1333
  current[min[1]] = iterators[min[1]].next();
1334
- if (lastYielded !== void 0 && distinct && comparator(lastYielded, min[0]) === 0) {
1334
+ if (lastYielded !== void 0 && distinct && comparator2(lastYielded, min[0]) === 0) {
1335
1335
  continue;
1336
1336
  }
1337
1337
  lastYielded = min[0];
@@ -8320,312 +8320,6 @@ function getKVStoreProvider(lc, kvStore) {
8320
8320
  // ../replicache/src/mod.ts
8321
8321
  import { consoleLogSink as consoleLogSink3 } from "@rocicorp/logger";
8322
8322
 
8323
- // ../zero-schema/src/column.ts
8324
- var column_exports = {};
8325
- __export(column_exports, {
8326
- boolean: () => boolean3,
8327
- enumeration: () => enumeration,
8328
- json: () => json,
8329
- number: () => number4,
8330
- string: () => string7
8331
- });
8332
- function string7(optional) {
8333
- return {
8334
- type: "string",
8335
- optional: optional ?? false,
8336
- customType: null
8337
- };
8338
- }
8339
- function number4(optional) {
8340
- return {
8341
- type: "number",
8342
- optional: optional ?? false,
8343
- customType: null
8344
- };
8345
- }
8346
- function boolean3(optional) {
8347
- return {
8348
- type: "boolean",
8349
- optional: optional ?? false,
8350
- customType: null
8351
- };
8352
- }
8353
- function json(optional) {
8354
- return {
8355
- type: "json",
8356
- optional: optional ?? false,
8357
- customType: null
8358
- };
8359
- }
8360
- function enumeration(optional) {
8361
- return {
8362
- type: "string",
8363
- kind: "enum",
8364
- customType: null,
8365
- optional: optional ?? false
8366
- };
8367
- }
8368
-
8369
- // ../zero-schema/src/table-schema.ts
8370
- function createTableSchema(schema) {
8371
- return schema;
8372
- }
8373
- function isFieldRelationship(relationship) {
8374
- return !isJunctionRelationship(relationship);
8375
- }
8376
- function isJunctionRelationship(relationship) {
8377
- return Array.isArray(relationship);
8378
- }
8379
-
8380
- // ../shared/src/sorted-entries.ts
8381
- function sortedEntries(object18) {
8382
- return Object.entries(object18).sort((a, b) => stringCompare(a[0], b[0]));
8383
- }
8384
-
8385
- // ../zero-schema/src/normalize-table-schema.ts
8386
- var NormalizedTableSchema = class {
8387
- tableName;
8388
- primaryKey;
8389
- columns;
8390
- relationships;
8391
- constructor(tableSchema, tableSchemaCache, assertFieldRelation) {
8392
- this.tableName = tableSchema.tableName;
8393
- const primaryKey = normalizePrimaryKey(tableSchema.primaryKey);
8394
- this.primaryKey = primaryKey;
8395
- this.columns = normalizeColumns(tableSchema.columns, primaryKey);
8396
- tableSchemaCache.set(tableSchema, this);
8397
- this.relationships = normalizeRelationships(
8398
- this.tableName,
8399
- tableSchema.relationships,
8400
- tableSchemaCache,
8401
- assertFieldRelation
8402
- );
8403
- }
8404
- };
8405
- var noop3 = () => {
8406
- };
8407
- function normalizeTableSchema(tableSchema) {
8408
- return normalizeTableSchemaWithCache(
8409
- tableSchema,
8410
- tableSchema.tableName,
8411
- /* @__PURE__ */ new Map(),
8412
- noop3
8413
- );
8414
- }
8415
- function normalizeTableSchemaWithCache(tableSchema, expectedTableName, tableSchemaCache, assertFieldRelation) {
8416
- if (tableSchema instanceof NormalizedTableSchema) {
8417
- return tableSchema;
8418
- }
8419
- assert(
8420
- tableSchema.tableName === expectedTableName,
8421
- `Table name mismatch: "${tableSchema.tableName}" !== "${expectedTableName}"`
8422
- );
8423
- let normalizedTableSchema = tableSchemaCache.get(tableSchema);
8424
- if (normalizedTableSchema) {
8425
- return normalizedTableSchema;
8426
- }
8427
- normalizedTableSchema = new NormalizedTableSchema(
8428
- tableSchema,
8429
- tableSchemaCache,
8430
- assertFieldRelation
8431
- );
8432
- return normalizedTableSchema;
8433
- }
8434
- function assertNoDuplicates(arr) {
8435
- assert(
8436
- new Set(arr).size === arr.length,
8437
- "Primary key must not contain duplicates"
8438
- );
8439
- }
8440
- function normalizePrimaryKey(primaryKey) {
8441
- if (typeof primaryKey === "string") {
8442
- return [primaryKey];
8443
- }
8444
- assertNoDuplicates(primaryKey);
8445
- return primaryKey;
8446
- }
8447
- function normalizeColumns(columns, primaryKey) {
8448
- const rv = {};
8449
- for (const pk of primaryKey) {
8450
- const schemaValue = columns[pk];
8451
- assert(schemaValue, `Primary key column "${pk}" not found`);
8452
- if (typeof schemaValue !== "string") {
8453
- const { type, optional } = schemaValue;
8454
- assert(!optional, `Primary key column "${pk}" cannot be optional`);
8455
- assert(
8456
- type === "string" || type === "number" || type === "boolean",
8457
- `Primary key column "${pk}" must be a string, number, or boolean. Got ${type}`
8458
- );
8459
- }
8460
- }
8461
- for (const [name, column] of sortedEntries(columns)) {
8462
- rv[name] = normalizeColumn(column);
8463
- }
8464
- return rv;
8465
- }
8466
- function normalizeColumn(value) {
8467
- if (typeof value === "string") {
8468
- return { type: value, optional: false };
8469
- }
8470
- return {
8471
- type: value.type,
8472
- optional: value.optional ?? false
8473
- };
8474
- }
8475
- function normalizeRelationships(tableName, relationships, tableSchemaCache, assertFieldRelation) {
8476
- const rv = {};
8477
- if (relationships) {
8478
- for (const [relationshipName, relationship] of sortedEntries(
8479
- relationships
8480
- )) {
8481
- rv[relationshipName] = normalizeRelationship(
8482
- tableName,
8483
- relationshipName,
8484
- relationship,
8485
- tableSchemaCache,
8486
- assertFieldRelation
8487
- );
8488
- }
8489
- }
8490
- return rv;
8491
- }
8492
- function normalizeRelationship(tableName, relationshipName, relationship, tableSchemaCache, assertFieldRelation) {
8493
- if (isFieldRelationship(relationship)) {
8494
- return normalizeFieldRelationship(
8495
- tableName,
8496
- relationshipName,
8497
- relationship,
8498
- tableSchemaCache,
8499
- assertFieldRelation
8500
- );
8501
- }
8502
- return normalizeJunctionRelationship(
8503
- tableName,
8504
- relationshipName,
8505
- relationship,
8506
- tableSchemaCache,
8507
- assertFieldRelation
8508
- );
8509
- }
8510
- function normalizeFieldRelationship(tableName, relationshipName, relationship, tableSchemaCache, assertFieldRelation) {
8511
- const sourceField = normalizeFieldName(relationship.sourceField);
8512
- const destField = normalizeFieldName(relationship.destField);
8513
- assert(
8514
- sourceField.length === destField.length,
8515
- "Source and destination fields must have the same length"
8516
- );
8517
- const destSchema = normalizeLazyTableSchema(
8518
- relationship.destSchema,
8519
- tableSchemaCache,
8520
- assertFieldRelation
8521
- );
8522
- const normalized = {
8523
- sourceField,
8524
- destField,
8525
- destSchema
8526
- };
8527
- assertFieldRelation(tableName, relationshipName, normalized);
8528
- return normalized;
8529
- }
8530
- function normalizeJunctionRelationship(tableName, relationshipName, relationship, tableSchemaCache, assertFieldRelation) {
8531
- const first2 = normalizeFieldRelationship(
8532
- tableName,
8533
- relationshipName,
8534
- relationship[0],
8535
- tableSchemaCache,
8536
- assertFieldRelation
8537
- );
8538
- const second = normalizeFieldRelationship(
8539
- first2.destSchema.tableName,
8540
- relationshipName,
8541
- relationship[1],
8542
- tableSchemaCache,
8543
- assertFieldRelation
8544
- );
8545
- return [first2, second];
8546
- }
8547
- function normalizeLazyTableSchema(tableSchema, buildCache, assertFieldRelation) {
8548
- const tableSchemaInstance = typeof tableSchema === "function" ? tableSchema() : tableSchema;
8549
- return normalizeTableSchemaWithCache(
8550
- tableSchemaInstance,
8551
- tableSchemaInstance.tableName,
8552
- // Don't care about name here.
8553
- buildCache,
8554
- assertFieldRelation
8555
- );
8556
- }
8557
- function normalizeFieldName(sourceField) {
8558
- if (typeof sourceField === "string") {
8559
- return [sourceField];
8560
- }
8561
- assert(sourceField.length > 0, "Expected at least one field");
8562
- return sourceField;
8563
- }
8564
- function normalizeTables(tables) {
8565
- const result = {};
8566
- const assertFieldRelation = (tableName) => tableName in tables;
8567
- for (const [name, table] of sortedEntries(tables)) {
8568
- result[name] = normalizeTableSchemaWithCache(
8569
- table,
8570
- name,
8571
- /* @__PURE__ */ new Map(),
8572
- assertFieldRelation
8573
- );
8574
- }
8575
- return result;
8576
- }
8577
-
8578
- // ../zero-schema/src/normalized-schema.ts
8579
- var normalizedCache = /* @__PURE__ */ new WeakMap();
8580
- function normalizeSchema(schema) {
8581
- if (schema instanceof NormalizedSchema) {
8582
- return schema;
8583
- }
8584
- let s;
8585
- if (!(s = normalizedCache.get(schema))) {
8586
- normalizedCache.set(schema, s = new NormalizedSchema(schema));
8587
- }
8588
- return s;
8589
- }
8590
- var NormalizedSchema = class {
8591
- version;
8592
- tables;
8593
- constructor(schema) {
8594
- this.version = schema.version;
8595
- this.tables = normalizeTables2(schema.tables);
8596
- }
8597
- };
8598
- function normalizeTables2(tables) {
8599
- const rv = {};
8600
- const tableSchemaCache = /* @__PURE__ */ new Map();
8601
- function assertFieldRelation(tableName, relationShipName, relation) {
8602
- const destTableName = relation.destSchema.tableName;
8603
- assert(
8604
- destTableName in tables,
8605
- `Relationship "${tableName}"."${relationShipName}" destination "${destTableName}" is missing in schema`
8606
- );
8607
- assertColumns(relation.sourceField, tables[tableName]);
8608
- assertColumns(relation.destField, tables[destTableName]);
8609
- }
8610
- function assertColumns(columnNames, table) {
8611
- for (const columnName of columnNames) {
8612
- assert(
8613
- columnName in table.columns,
8614
- `Column "${columnName}" is missing in table "${table.tableName}"`
8615
- );
8616
- }
8617
- }
8618
- for (const [name, table] of sortedEntries(tables)) {
8619
- rv[name] = normalizeTableSchemaWithCache(
8620
- table,
8621
- name,
8622
- tableSchemaCache,
8623
- assertFieldRelation
8624
- );
8625
- }
8626
- return rv;
8627
- }
8628
-
8629
8323
  // ../zero-protocol/src/ast.ts
8630
8324
  import { compareUTF8 as compareUTF83 } from "compare-utf8";
8631
8325
 
@@ -9077,6 +8771,14 @@ function hashOfAST(ast) {
9077
8771
  return hash2;
9078
8772
  }
9079
8773
 
8774
+ // ../zero-schema/src/table-schema.ts
8775
+ function isOneHop(r) {
8776
+ return r.length === 1;
8777
+ }
8778
+ function isTwoHop(r) {
8779
+ return r.length === 2;
8780
+ }
8781
+
9080
8782
  // ../zql/src/ivm/change.ts
9081
8783
  function rowForChange(change) {
9082
8784
  const { type } = change;
@@ -9134,6 +8836,13 @@ function valuesEqual(a, b) {
9134
8836
  return a === b;
9135
8837
  }
9136
8838
 
8839
+ // ../zql/src/ivm/operator.ts
8840
+ var throwOutput = {
8841
+ push(_change) {
8842
+ throw new Error("Output not set");
8843
+ }
8844
+ };
8845
+
9137
8846
  // ../zql/src/ivm/stream.ts
9138
8847
  function* take(stream, limit) {
9139
8848
  if (limit < 1) {
@@ -9162,7 +8871,7 @@ var Exists = class {
9162
8871
  #not;
9163
8872
  #parentJoinKey;
9164
8873
  #skipCache;
9165
- #output;
8874
+ #output = throwOutput;
9166
8875
  constructor(input, storage, relationshipName, parentJoinKey, type) {
9167
8876
  this.#input = input;
9168
8877
  this.#relationshipName = relationshipName;
@@ -9201,7 +8910,6 @@ var Exists = class {
9201
8910
  }
9202
8911
  }
9203
8912
  push(change) {
9204
- assert(this.#output, "Output not set");
9205
8913
  switch (change.type) {
9206
8914
  case "add":
9207
8915
  case "edit": {
@@ -9296,7 +9004,7 @@ var Exists = class {
9296
9004
  #pushWithFilter(change, size) {
9297
9005
  const row = rowForChange(change);
9298
9006
  if (this.#filter(row, size)) {
9299
- must(this.#output).push(change);
9007
+ this.#output.push(change);
9300
9008
  }
9301
9009
  }
9302
9010
  #getSize(row) {
@@ -9389,7 +9097,7 @@ var FanIn = class {
9389
9097
  #inputs;
9390
9098
  #fanOut;
9391
9099
  #schema;
9392
- #output;
9100
+ #output = throwOutput;
9393
9101
  constructor(fanOut, inputs) {
9394
9102
  this.#inputs = inputs;
9395
9103
  this.#schema = fanOut.getSchema();
@@ -9426,7 +9134,7 @@ var FanIn = class {
9426
9134
  }
9427
9135
  push(change) {
9428
9136
  this.#fanOut.onFanInReceivedPush();
9429
- this.#output?.push(change);
9137
+ this.#output.push(change);
9430
9138
  }
9431
9139
  };
9432
9140
 
@@ -9504,7 +9212,7 @@ var Filter = class {
9504
9212
  #input;
9505
9213
  #mode;
9506
9214
  #predicate;
9507
- #output;
9215
+ #output = throwOutput;
9508
9216
  constructor(input, mode, predicate) {
9509
9217
  this.#input = input;
9510
9218
  this.#mode = mode;
@@ -9534,7 +9242,6 @@ var Filter = class {
9534
9242
  }
9535
9243
  }
9536
9244
  push(change) {
9537
- assert(this.#output, "Output not set");
9538
9245
  switch (change.type) {
9539
9246
  case "add":
9540
9247
  case "remove":
@@ -9565,7 +9272,7 @@ var Join = class {
9565
9272
  #childKey;
9566
9273
  #relationshipName;
9567
9274
  #schema;
9568
- #output = null;
9275
+ #output = throwOutput;
9569
9276
  constructor({
9570
9277
  parent,
9571
9278
  child,
@@ -9636,7 +9343,6 @@ var Join = class {
9636
9343
  }
9637
9344
  }
9638
9345
  #pushParent(change) {
9639
- assert(this.#output, "Output not set");
9640
9346
  switch (change.type) {
9641
9347
  case "add":
9642
9348
  this.#output.push({
@@ -9698,7 +9404,6 @@ var Join = class {
9698
9404
  }
9699
9405
  #pushChild(change) {
9700
9406
  const pushChildChange = (childRow, change2) => {
9701
- assert(this.#output, "Output not set");
9702
9407
  const parentNodes = this.#parent.fetch({
9703
9408
  constraint: Object.fromEntries(
9704
9409
  this.#parentKey.map((key, i) => [key, childRow[this.#childKey[i]]])
@@ -9812,7 +9517,7 @@ var Skip = class {
9812
9517
  #input;
9813
9518
  #bound;
9814
9519
  #comparator;
9815
- #output;
9520
+ #output = throwOutput;
9816
9521
  constructor(input, bound) {
9817
9522
  this.#input = input;
9818
9523
  this.#bound = bound;
@@ -9856,7 +9561,6 @@ var Skip = class {
9856
9561
  return cmp2 < 0 || cmp2 === 0 && !this.#bound.exclusive;
9857
9562
  }
9858
9563
  push(change) {
9859
- assert(this.#output, "Output not set");
9860
9564
  const shouldBePresent = (row) => this.#shouldBePresent(row);
9861
9565
  if (change.type === "edit") {
9862
9566
  maybeSplitAndPushEditChange(change, shouldBePresent, this.#output);
@@ -9917,7 +9621,7 @@ var Take = class {
9917
9621
  #limit;
9918
9622
  #partitionKey;
9919
9623
  #partitionKeyComparator;
9920
- #output = null;
9624
+ #output = throwOutput;
9921
9625
  constructor(input, storage, limit, partitionKey) {
9922
9626
  assert(limit >= 0);
9923
9627
  assertOrderingIncludesPK(
@@ -10044,7 +9748,6 @@ var Take = class {
10044
9748
  this.#pushEditChange(change);
10045
9749
  return;
10046
9750
  }
10047
- assert(this.#output, "Output not set");
10048
9751
  const { takeState, takeStateKey, maxBound, constraint } = this.#getStateAndConstraint(rowForChange(change));
10049
9752
  if (!takeState) {
10050
9753
  return;
@@ -10176,7 +9879,6 @@ var Take = class {
10176
9879
  }
10177
9880
  }
10178
9881
  #pushEditChange(change) {
10179
- assert(this.#output, "Output not set");
10180
9882
  if (this.#partitionKeyComparator && this.#partitionKeyComparator(change.oldNode.row, change.node.row) !== 0) {
10181
9883
  this.push({
10182
9884
  type: "remove",
@@ -10973,11 +10675,11 @@ function unwrap(c) {
10973
10675
  }
10974
10676
 
10975
10677
  // ../zql/src/query/query-impl.ts
10976
- function newQuery(delegate, tableSchema) {
10977
- return new QueryImpl(delegate, normalizeTableSchema(tableSchema));
10678
+ function newQuery(delegate, schema, table2) {
10679
+ return new QueryImpl(delegate, schema, table2);
10978
10680
  }
10979
- function newQueryWithDetails(delegate, schema, ast, format) {
10980
- return new QueryImpl(delegate, schema, ast, format);
10681
+ function newQueryWithDetails(delegate, schema, tableName, ast, format) {
10682
+ return new QueryImpl(delegate, schema, tableName, ast, format);
10981
10683
  }
10982
10684
  function staticParam(anchorClass, field) {
10983
10685
  return {
@@ -10991,12 +10693,14 @@ var SUBQ_PREFIX = "zsubq_";
10991
10693
  var AbstractQuery = class {
10992
10694
  #ast;
10993
10695
  #schema;
10696
+ #tableName;
10994
10697
  #format;
10995
10698
  #hash = "";
10996
- constructor(schema, ast, format) {
10699
+ constructor(schema, tableName, ast, format) {
10997
10700
  this.#ast = ast;
10998
10701
  this.#format = format ?? { singular: false, relationships: {} };
10999
10702
  this.#schema = schema;
10703
+ this.#tableName = tableName;
11000
10704
  }
11001
10705
  get format() {
11002
10706
  return this.#format;
@@ -11012,6 +10716,7 @@ var AbstractQuery = class {
11012
10716
  one() {
11013
10717
  return this._newQuery(
11014
10718
  this.#schema,
10719
+ this.#tableName,
11015
10720
  {
11016
10721
  ...this.#ast,
11017
10722
  limit: 1
@@ -11022,31 +10727,49 @@ var AbstractQuery = class {
11022
10727
  }
11023
10728
  );
11024
10729
  }
11025
- whereExists(relationship, cb = (q) => q) {
10730
+ whereExists(relationship, cb) {
11026
10731
  return this.where(({ exists }) => exists(relationship, cb));
11027
10732
  }
11028
- related(relationship, cb = (q) => q) {
10733
+ related(relationship, cb) {
11029
10734
  if (relationship.startsWith(SUBQ_PREFIX)) {
11030
10735
  throw new Error(
11031
10736
  `Relationship names may not start with "${SUBQ_PREFIX}". That is a reserved prefix.`
11032
10737
  );
11033
10738
  }
11034
- const related = this.#schema.relationships[relationship];
10739
+ cb = cb ?? ((q) => q);
10740
+ const related = this.#schema.relationships[this.#tableName][relationship];
11035
10741
  assert(related, "Invalid relationship");
11036
- if (isFieldRelationship(related)) {
11037
- const { destSchema } = related;
10742
+ if (isOneHop(related)) {
10743
+ const { destSchema, destField, sourceField, cardinality } = related[0];
11038
10744
  const sq = cb(
11039
10745
  this._newQuery(
10746
+ this.#schema,
11040
10747
  destSchema,
11041
10748
  {
11042
- table: destSchema.tableName,
10749
+ table: destSchema,
11043
10750
  alias: relationship
11044
10751
  },
11045
- void 0
10752
+ {
10753
+ relationships: {},
10754
+ singular: cardinality === "one"
10755
+ }
11046
10756
  )
11047
10757
  );
10758
+ assert(
10759
+ isCompoundKey(sourceField),
10760
+ "The source of a relationship must specify at last 1 field"
10761
+ );
10762
+ assert(
10763
+ isCompoundKey(destField),
10764
+ "The destination of a relationship must specify at last 1 field"
10765
+ );
10766
+ assert(
10767
+ sourceField.length === destField.length,
10768
+ "The source and destination of a relationship must have the same number of fields"
10769
+ );
11048
10770
  return this._newQuery(
11049
10771
  this.#schema,
10772
+ this.#tableName,
11050
10773
  {
11051
10774
  ...this.#ast,
11052
10775
  related: [
@@ -11054,10 +10777,13 @@ var AbstractQuery = class {
11054
10777
  {
11055
10778
  system: this._system,
11056
10779
  correlation: {
11057
- parentField: related.sourceField,
11058
- childField: related.destField
10780
+ parentField: sourceField,
10781
+ childField: destField
11059
10782
  },
11060
- subquery: addPrimaryKeysToAst(destSchema, sq.#ast)
10783
+ subquery: addPrimaryKeysToAst(
10784
+ this.#schema.tables[destSchema],
10785
+ sq.#ast
10786
+ )
11061
10787
  }
11062
10788
  ]
11063
10789
  },
@@ -11070,23 +10796,32 @@ var AbstractQuery = class {
11070
10796
  }
11071
10797
  );
11072
10798
  }
11073
- if (isJunctionRelationship(related)) {
10799
+ if (isTwoHop(related)) {
11074
10800
  assert(related.length === 2, "Invalid relationship");
11075
10801
  const [firstRelation, secondRelation] = related;
11076
10802
  const { destSchema } = secondRelation;
11077
10803
  const junctionSchema = firstRelation.destSchema;
11078
10804
  const sq = cb(
11079
10805
  this._newQuery(
10806
+ this.#schema,
11080
10807
  destSchema,
11081
10808
  {
11082
- table: destSchema.tableName,
10809
+ table: destSchema,
11083
10810
  alias: relationship
11084
10811
  },
11085
- void 0
10812
+ {
10813
+ relationships: {},
10814
+ singular: secondRelation.cardinality === "one"
10815
+ }
11086
10816
  )
11087
10817
  );
10818
+ assert(isCompoundKey(firstRelation.sourceField), "Invalid relationship");
10819
+ assert(isCompoundKey(firstRelation.destField), "Invalid relationship");
10820
+ assert(isCompoundKey(secondRelation.sourceField), "Invalid relationship");
10821
+ assert(isCompoundKey(secondRelation.destField), "Invalid relationship");
11088
10822
  return this._newQuery(
11089
10823
  this.#schema,
10824
+ this.#tableName,
11090
10825
  {
11091
10826
  ...this.#ast,
11092
10827
  related: [
@@ -11098,9 +10833,12 @@ var AbstractQuery = class {
11098
10833
  childField: firstRelation.destField
11099
10834
  },
11100
10835
  subquery: {
11101
- table: junctionSchema.tableName,
10836
+ table: junctionSchema,
11102
10837
  alias: relationship,
11103
- orderBy: addPrimaryKeys(junctionSchema, void 0),
10838
+ orderBy: addPrimaryKeys(
10839
+ this.#schema.tables[junctionSchema],
10840
+ void 0
10841
+ ),
11104
10842
  related: [
11105
10843
  {
11106
10844
  system: this._system,
@@ -11109,7 +10847,10 @@ var AbstractQuery = class {
11109
10847
  childField: secondRelation.destField
11110
10848
  },
11111
10849
  hidden: true,
11112
- subquery: addPrimaryKeysToAst(destSchema, sq.#ast)
10850
+ subquery: addPrimaryKeysToAst(
10851
+ this.#schema.tables[destSchema],
10852
+ sq.#ast
10853
+ )
11113
10854
  }
11114
10855
  ]
11115
10856
  }
@@ -11141,6 +10882,7 @@ var AbstractQuery = class {
11141
10882
  }
11142
10883
  return this._newQuery(
11143
10884
  this.#schema,
10885
+ this.#tableName,
11144
10886
  {
11145
10887
  ...this.#ast,
11146
10888
  where: dnf(cond)
@@ -11151,6 +10893,7 @@ var AbstractQuery = class {
11151
10893
  start(row, opts) {
11152
10894
  return this._newQuery(
11153
10895
  this.#schema,
10896
+ this.#tableName,
11154
10897
  {
11155
10898
  ...this.#ast,
11156
10899
  start: {
@@ -11170,6 +10913,7 @@ var AbstractQuery = class {
11170
10913
  }
11171
10914
  return this._newQuery(
11172
10915
  this.#schema,
10916
+ this.#tableName,
11173
10917
  {
11174
10918
  ...this.#ast,
11175
10919
  limit
@@ -11180,6 +10924,7 @@ var AbstractQuery = class {
11180
10924
  orderBy(field, direction) {
11181
10925
  return this._newQuery(
11182
10926
  this.#schema,
10927
+ this.#tableName,
11183
10928
  {
11184
10929
  ...this.#ast,
11185
10930
  orderBy: [...this.#ast.orderBy ?? [], [field, direction]]
@@ -11188,15 +10933,18 @@ var AbstractQuery = class {
11188
10933
  );
11189
10934
  }
11190
10935
  _exists = (relationship, cb = (q) => q) => {
11191
- const related = this.#schema.relationships[relationship];
10936
+ const related = this.#schema.relationships[this.#tableName][relationship];
11192
10937
  assert(related, "Invalid relationship");
11193
- if (isFieldRelationship(related)) {
11194
- const { destSchema } = related;
10938
+ if (isOneHop(related)) {
10939
+ const { destSchema, sourceField, destField } = related[0];
10940
+ assert(isCompoundKey(sourceField), "Invalid relationship");
10941
+ assert(isCompoundKey(destField), "Invalid relationship");
11195
10942
  const sq = cb(
11196
10943
  this._newQuery(
10944
+ this.#schema,
11197
10945
  destSchema,
11198
10946
  {
11199
- table: destSchema.tableName,
10947
+ table: destSchema,
11200
10948
  alias: `${SUBQ_PREFIX}${relationship}`
11201
10949
  },
11202
10950
  void 0
@@ -11207,24 +10955,32 @@ var AbstractQuery = class {
11207
10955
  related: {
11208
10956
  system: this._system,
11209
10957
  correlation: {
11210
- parentField: related.sourceField,
11211
- childField: related.destField
10958
+ parentField: sourceField,
10959
+ childField: destField
11212
10960
  },
11213
- subquery: addPrimaryKeysToAst(destSchema, sq.#ast)
10961
+ subquery: addPrimaryKeysToAst(
10962
+ this.#schema.tables[destSchema],
10963
+ sq.#ast
10964
+ )
11214
10965
  },
11215
10966
  op: "EXISTS"
11216
10967
  };
11217
10968
  }
11218
- if (isJunctionRelationship(related)) {
10969
+ if (isTwoHop(related)) {
11219
10970
  assert(related.length === 2, "Invalid relationship");
11220
10971
  const [firstRelation, secondRelation] = related;
10972
+ assert(isCompoundKey(firstRelation.sourceField), "Invalid relationship");
10973
+ assert(isCompoundKey(firstRelation.destField), "Invalid relationship");
10974
+ assert(isCompoundKey(secondRelation.sourceField), "Invalid relationship");
10975
+ assert(isCompoundKey(secondRelation.destField), "Invalid relationship");
11221
10976
  const { destSchema } = secondRelation;
11222
10977
  const junctionSchema = firstRelation.destSchema;
11223
10978
  const queryToDest = cb(
11224
10979
  this._newQuery(
10980
+ this.#schema,
11225
10981
  destSchema,
11226
10982
  {
11227
- table: destSchema.tableName,
10983
+ table: destSchema,
11228
10984
  alias: `${SUBQ_PREFIX}${relationship}`
11229
10985
  },
11230
10986
  void 0
@@ -11239,9 +10995,12 @@ var AbstractQuery = class {
11239
10995
  childField: firstRelation.destField
11240
10996
  },
11241
10997
  subquery: {
11242
- table: junctionSchema.tableName,
10998
+ table: junctionSchema,
11243
10999
  alias: `${SUBQ_PREFIX}${relationship}`,
11244
- orderBy: addPrimaryKeys(junctionSchema, void 0),
11000
+ orderBy: addPrimaryKeys(
11001
+ this.#schema.tables[junctionSchema],
11002
+ void 0
11003
+ ),
11245
11004
  where: {
11246
11005
  type: "correlatedSubquery",
11247
11006
  related: {
@@ -11250,7 +11009,10 @@ var AbstractQuery = class {
11250
11009
  parentField: secondRelation.sourceField,
11251
11010
  childField: secondRelation.destField
11252
11011
  },
11253
- subquery: addPrimaryKeysToAst(destSchema, queryToDest.#ast)
11012
+ subquery: addPrimaryKeysToAst(
11013
+ this.#schema.tables[destSchema],
11014
+ queryToDest.#ast
11015
+ )
11254
11016
  },
11255
11017
  op: "EXISTS"
11256
11018
  }
@@ -11264,7 +11026,10 @@ var AbstractQuery = class {
11264
11026
  #completedAST;
11265
11027
  _completeAst() {
11266
11028
  if (!this.#completedAST) {
11267
- const finalOrderBy = addPrimaryKeys(this.#schema, this.#ast.orderBy);
11029
+ const finalOrderBy = addPrimaryKeys(
11030
+ this.#schema.tables[this.#tableName],
11031
+ this.#ast.orderBy
11032
+ );
11268
11033
  if (this.#ast.start) {
11269
11034
  const { row } = this.#ast.start;
11270
11035
  const narrowedRow = {};
@@ -11282,7 +11047,10 @@ var AbstractQuery = class {
11282
11047
  } else {
11283
11048
  this.#completedAST = {
11284
11049
  ...this.#ast,
11285
- orderBy: addPrimaryKeys(this.#schema, this.#ast.orderBy)
11050
+ orderBy: addPrimaryKeys(
11051
+ this.#schema.tables[this.#tableName],
11052
+ this.#ast.orderBy
11053
+ )
11286
11054
  };
11287
11055
  }
11288
11056
  }
@@ -11294,8 +11062,8 @@ var completedAstSymbol = Symbol();
11294
11062
  var QueryImpl = class extends AbstractQuery {
11295
11063
  #delegate;
11296
11064
  #ast;
11297
- constructor(delegate, schema, ast = { table: schema.tableName }, format) {
11298
- super(schema, ast, format);
11065
+ constructor(delegate, schema, tableName, ast = { table: tableName }, format) {
11066
+ super(schema, tableName, ast, format);
11299
11067
  this.#delegate = delegate;
11300
11068
  this.#ast = ast;
11301
11069
  }
@@ -11307,8 +11075,8 @@ var QueryImpl = class extends AbstractQuery {
11307
11075
  get [completedAstSymbol]() {
11308
11076
  return this._completeAst();
11309
11077
  }
11310
- _newQuery(schema, ast, format) {
11311
- return newQueryWithDetails(this.#delegate, schema, ast, format);
11078
+ _newQuery(schema, tableName, ast, format) {
11079
+ return newQueryWithDetails(this.#delegate, schema, tableName, ast, format);
11312
11080
  }
11313
11081
  materialize(factory) {
11314
11082
  const ast = this._completeAst();
@@ -11390,18 +11158,21 @@ function arrayViewFactory(_query, input, format, onDestroy, onTransactionCommit,
11390
11158
  });
11391
11159
  return v2;
11392
11160
  }
11161
+ function isCompoundKey(field) {
11162
+ return Array.isArray(field) && field.length >= 1;
11163
+ }
11393
11164
 
11394
11165
  // ../zql/src/query/auth-query.ts
11395
11166
  var AuthQuery = class _AuthQuery extends AbstractQuery {
11396
- constructor(schema, ast = { table: schema.tableName }, format) {
11397
- super(schema, ast, format);
11167
+ constructor(schema, tableName, ast = { table: tableName }, format) {
11168
+ super(schema, tableName, ast, format);
11398
11169
  }
11399
11170
  expressionBuilder() {
11400
11171
  return new ExpressionBuilder(this._exists);
11401
11172
  }
11402
11173
  _system = "permissions";
11403
- _newQuery(schema, ast, format) {
11404
- return new _AuthQuery(schema, ast, format);
11174
+ _newQuery(schema, tableName, ast, format) {
11175
+ return new _AuthQuery(schema, tableName, ast, format);
11405
11176
  }
11406
11177
  get ast() {
11407
11178
  return this._completeAst();
@@ -11421,10 +11192,9 @@ var AuthQuery = class _AuthQuery extends AbstractQuery {
11421
11192
  var ANYONE_CAN = void 0;
11422
11193
  var NOBODY_CAN = [];
11423
11194
  async function definePermissions(schema, definer) {
11424
- const normalizedSchema = normalizeSchema(schema);
11425
11195
  const expressionBuilders = {};
11426
- for (const [name, tableSchema] of Object.entries(normalizedSchema.tables)) {
11427
- expressionBuilders[name] = new AuthQuery(tableSchema).expressionBuilder();
11196
+ for (const name of Object.keys(schema.tables)) {
11197
+ expressionBuilders[name] = new AuthQuery(schema, name).expressionBuilder();
11428
11198
  }
11429
11199
  const config = await definer();
11430
11200
  return compilePermissions(config, expressionBuilders);
@@ -11528,10 +11298,160 @@ function baseTracker(anchor) {
11528
11298
  var authDataRef = baseTracker("authData");
11529
11299
  var preMutationRowRef = baseTracker("preMutationRow");
11530
11300
 
11531
- // ../zero-schema/src/schema.ts
11532
- function createSchema(schema) {
11533
- normalizeSchema(schema);
11534
- return schema;
11301
+ // ../zero-schema/src/builder/table-builder.ts
11302
+ function table(name) {
11303
+ return new TableBuilder({
11304
+ name,
11305
+ columns: {},
11306
+ primaryKey: []
11307
+ });
11308
+ }
11309
+ function string8() {
11310
+ return new ColumnBuilder({
11311
+ type: "string",
11312
+ optional: false,
11313
+ customType: null
11314
+ });
11315
+ }
11316
+ function number5() {
11317
+ return new ColumnBuilder({
11318
+ type: "number",
11319
+ optional: false,
11320
+ customType: null
11321
+ });
11322
+ }
11323
+ function boolean4() {
11324
+ return new ColumnBuilder({
11325
+ type: "boolean",
11326
+ optional: false,
11327
+ customType: null
11328
+ });
11329
+ }
11330
+ function json() {
11331
+ return new ColumnBuilder({
11332
+ type: "json",
11333
+ optional: false,
11334
+ customType: null
11335
+ });
11336
+ }
11337
+ function enumeration() {
11338
+ return new ColumnBuilder({
11339
+ type: "string",
11340
+ optional: false,
11341
+ customType: null
11342
+ });
11343
+ }
11344
+ var TableBuilder = class {
11345
+ #schema;
11346
+ constructor(schema) {
11347
+ this.#schema = schema;
11348
+ }
11349
+ columns(columns) {
11350
+ const columnSchemas = Object.fromEntries(
11351
+ Object.entries(columns).map(([k, v2]) => [k, v2.schema])
11352
+ );
11353
+ return new TableBuilderWithColumns({
11354
+ ...this.#schema,
11355
+ columns: columnSchemas
11356
+ });
11357
+ }
11358
+ };
11359
+ var TableBuilderWithColumns = class _TableBuilderWithColumns {
11360
+ #schema;
11361
+ constructor(schema) {
11362
+ this.#schema = schema;
11363
+ }
11364
+ primaryKey(...pkColumnNames) {
11365
+ return new _TableBuilderWithColumns({
11366
+ ...this.#schema,
11367
+ primaryKey: pkColumnNames
11368
+ });
11369
+ }
11370
+ get schema() {
11371
+ return this.#schema;
11372
+ }
11373
+ build() {
11374
+ if (this.#schema.primaryKey.length === 0) {
11375
+ throw new Error(`Table "${this.#schema.name}" is missing a primary key`);
11376
+ }
11377
+ return this.#schema;
11378
+ }
11379
+ };
11380
+ var ColumnBuilder = class _ColumnBuilder {
11381
+ #schema;
11382
+ constructor(schema) {
11383
+ this.#schema = schema;
11384
+ }
11385
+ optional() {
11386
+ return new _ColumnBuilder({
11387
+ ...this.#schema,
11388
+ optional: true
11389
+ });
11390
+ }
11391
+ get schema() {
11392
+ return this.#schema;
11393
+ }
11394
+ };
11395
+
11396
+ // ../zero-schema/src/builder/schema-builder.ts
11397
+ function createSchema(version3, tables, relationships2) {
11398
+ const retTables = {};
11399
+ const retRelationships = {};
11400
+ Object.values(tables).forEach((table2) => {
11401
+ retTables[table2.schema.name] = table2.build();
11402
+ });
11403
+ Object.values(relationships2 ?? {}).forEach((relationship) => {
11404
+ retRelationships[relationship.name] = relationship.relationships;
11405
+ checkRelationship(relationship.relationships, relationship.name, retTables);
11406
+ });
11407
+ return {
11408
+ version: version3,
11409
+ tables: retTables,
11410
+ relationships: retRelationships
11411
+ };
11412
+ }
11413
+ function checkRelationship(relationships2, tableName, tables) {
11414
+ Object.entries(relationships2).forEach(([name, rel]) => {
11415
+ let source = tables[tableName];
11416
+ rel.forEach((connection) => {
11417
+ if (!tables[connection.destSchema]) {
11418
+ throw new Error(
11419
+ `For relationship "${tableName}"."${name}", destination table "${connection.destSchema}" is missing in the schema`
11420
+ );
11421
+ }
11422
+ if (!source.columns[connection.sourceField[0]]) {
11423
+ throw new Error(
11424
+ `For relationship "${tableName}"."${name}", the source field "${connection.sourceField[0]}" is missing in the table schema "${source.name}"`
11425
+ );
11426
+ }
11427
+ source = tables[connection.destSchema];
11428
+ });
11429
+ });
11430
+ }
11431
+
11432
+ // ../zero-schema/src/builder/relationship-builder.ts
11433
+ function relationships(table2, cb) {
11434
+ const relationships2 = cb({ many, one });
11435
+ return {
11436
+ name: table2.schema.name,
11437
+ relationships: relationships2
11438
+ };
11439
+ }
11440
+ function many(...args) {
11441
+ return args.map((arg) => ({
11442
+ sourceField: arg.sourceField,
11443
+ destField: arg.destField,
11444
+ destSchema: arg.destSchema.schema.name,
11445
+ cardinality: "many"
11446
+ }));
11447
+ }
11448
+ function one(...args) {
11449
+ return args.map((arg) => ({
11450
+ sourceField: arg.sourceField,
11451
+ destField: arg.destField,
11452
+ destSchema: arg.destSchema.schema.name,
11453
+ cardinality: "one"
11454
+ }));
11535
11455
  }
11536
11456
 
11537
11457
  // ../zql/src/query/escape-like.ts
@@ -11927,145 +11847,36 @@ var Disconnected = 0;
11927
11847
  var Connecting = 1;
11928
11848
  var Connected = 2;
11929
11849
 
11930
- // ../btree/b+tree.ts
11931
- function defaultComparator(a, b) {
11932
- if (Number.isFinite(a) && Number.isFinite(b)) {
11933
- return a - b;
11934
- }
11935
- let ta = typeof a;
11936
- let tb = typeof b;
11937
- if (ta !== tb) {
11938
- return ta < tb ? -1 : 1;
11939
- }
11940
- if (ta === "object") {
11941
- if (a === null)
11942
- return b === null ? 0 : -1;
11943
- else if (b === null)
11944
- return 1;
11945
- a = a.valueOf();
11946
- b = b.valueOf();
11947
- ta = typeof a;
11948
- tb = typeof b;
11949
- if (ta !== tb) {
11950
- return ta < tb ? -1 : 1;
11850
+ // ../shared/src/btree-set.ts
11851
+ var MAX_NODE_SIZE = 32;
11852
+ var BTreeSet = class {
11853
+ #root = emptyLeaf;
11854
+ size = 0;
11855
+ comparator;
11856
+ constructor(comparator2, entries) {
11857
+ this.comparator = comparator2;
11858
+ if (entries) {
11859
+ for (const key of entries) {
11860
+ this.add(key);
11861
+ }
11951
11862
  }
11952
11863
  }
11953
- if (a < b)
11954
- return -1;
11955
- if (a > b)
11956
- return 1;
11957
- if (a === b)
11958
- return 0;
11959
- if (Number.isNaN(a))
11960
- return Number.isNaN(b) ? 0 : -1;
11961
- else if (Number.isNaN(b))
11962
- return 1;
11963
- return Array.isArray(a) ? 0 : Number.NaN;
11964
- }
11965
- var BTree = class _BTree {
11966
- _root = EmptyLeaf;
11967
- _size = 0;
11968
- _maxNodeSize;
11969
- /**
11970
- * provides a total order over keys (and a strict partial order over the type K)
11971
- * @returns a negative value if a < b, 0 if a === b and a positive value if a > b
11972
- */
11973
- _compare;
11974
- /**
11975
- * Initializes an empty B+ tree.
11976
- * @param compare Custom function to compare pairs of elements in the tree.
11977
- * If not specified, defaultComparator will be used which is valid as long as K extends DefaultComparable.
11978
- * @param entries A set of key-value pairs to initialize the tree
11979
- * @param maxNodeSize Branching factor (maximum items or children per node)
11980
- * Must be in range 4..256. If undefined or <4 then default is used; if >256 then 256.
11981
- */
11982
- constructor(entries, compare, maxNodeSize) {
11983
- this._maxNodeSize = maxNodeSize >= 4 ? Math.min(maxNodeSize, 256) : 32;
11984
- this._compare = compare || defaultComparator;
11985
- if (entries)
11986
- this.setPairs(entries);
11987
- }
11988
- /////////////////////////////////////////////////////////////////////////////
11989
- // ES6 Map<K,V> methods /////////////////////////////////////////////////////
11990
- /** Gets the number of key-value pairs in the tree. */
11991
- get size() {
11992
- return this._size;
11993
- }
11994
- /** Gets the number of key-value pairs in the tree. */
11995
- get length() {
11996
- return this._size;
11997
- }
11998
- /** Returns true iff the tree contains no key-value pairs. */
11999
- get isEmpty() {
12000
- return this._size === 0;
12001
- }
12002
11864
  /** Releases the tree so that its size is 0. */
12003
11865
  clear() {
12004
- this._root = EmptyLeaf;
12005
- this._size = 0;
12006
- }
12007
- /** Runs a function for each key-value pair, in order from smallest to
12008
- * largest key. For compatibility with ES6 Map, the argument order to
12009
- * the callback is backwards: value first, then key. Call forEachPair
12010
- * instead to receive the key as the first argument.
12011
- * @param thisArg If provided, this parameter is assigned as the `this`
12012
- * value for each callback.
12013
- * @returns the number of values that were sent to the callback,
12014
- * or the R value if the callback returned {break:R}. */
12015
- forEach(callback, thisArg) {
12016
- if (thisArg !== void 0)
12017
- callback = callback.bind(thisArg);
12018
- return this.forEachPair((k, v2) => callback(v2, k, this));
12019
- }
12020
- /** Runs a function for each key-value pair, in order from smallest to
12021
- * largest key. The callback can return {break:R} (where R is any value
12022
- * except undefined) to stop immediately and return R from forEachPair.
12023
- * @param onFound A function that is called for each key-value pair. This
12024
- * function can return {break:R} to stop early with result R.
12025
- * The reason that you must return {break:R} instead of simply R
12026
- * itself is for consistency with editRange(), which allows
12027
- * multiple actions, not just breaking.
12028
- * @param initialCounter This is the value of the third argument of
12029
- * `onFound` the first time it is called. The counter increases
12030
- * by one each time `onFound` is called. Default value: 0
12031
- * @returns the number of pairs sent to the callback (plus initialCounter,
12032
- * if you provided one). If the callback returned {break:R} then
12033
- * the R value is returned instead. */
12034
- forEachPair(callback, initialCounter) {
12035
- var low = this.minKey(), high = this.maxKey();
12036
- return this.forRange(low, high, true, callback, initialCounter);
11866
+ this.#root = emptyLeaf;
11867
+ this.size = 0;
12037
11868
  }
12038
- /**
12039
- * Finds a pair in the tree and returns the associated value.
12040
- * @param defaultValue a value to return if the key was not found.
12041
- * @returns the value, or defaultValue if the key was not found.
12042
- * @description Computational complexity: O(log size)
12043
- */
12044
- get(key, defaultValue) {
12045
- return this._root.get(key, defaultValue, this);
11869
+ get(key) {
11870
+ return this.#root.get(key, this);
12046
11871
  }
12047
- /**
12048
- * Adds or overwrites a key-value pair in the B+ tree.
12049
- * @param key the key is used to determine the sort order of
12050
- * data in the tree.
12051
- * @param value data to associate with the key (optional)
12052
- * @param overwrite Whether to overwrite an existing key-value pair
12053
- * (default: true). If this is false and there is an existing
12054
- * key-value pair then this method has no effect.
12055
- * @returns true if a new key-value pair was added.
12056
- * @description Computational complexity: O(log size)
12057
- * Note: when overwriting a previous entry, the key is updated
12058
- * as well as the value. This has no effect unless the new key
12059
- * has data that does not affect its sort order.
12060
- */
12061
- set(key, value, overwrite) {
12062
- if (this._root.isShared)
12063
- this._root = this._root.clone();
12064
- var result = this._root.set(key, value, overwrite, this);
12065
- if (result === true || result === false)
12066
- return result;
12067
- this._root = new BNodeInternal([this._root, result]);
12068
- return true;
11872
+ add(key) {
11873
+ if (this.#root.isShared)
11874
+ this.#root = this.#root.clone();
11875
+ const result = this.#root.set(key, this);
11876
+ if (result === null)
11877
+ return this;
11878
+ this.#root = new BNodeInternal([this.#root, result]);
11879
+ return this;
12069
11880
  }
12070
11881
  /**
12071
11882
  * Returns true if the key exists in the B+ tree, false if not.
@@ -12075,7 +11886,7 @@ var BTree = class _BTree {
12075
11886
  * @description Computational complexity: O(log size)
12076
11887
  */
12077
11888
  has(key) {
12078
- return this.forRange(key, key, true, void 0) !== 0;
11889
+ return this.#root.has(key, this);
12079
11890
  }
12080
11891
  /**
12081
11892
  * Removes a single key-value pair from the B+ tree.
@@ -12084,1111 +11895,240 @@ var BTree = class _BTree {
12084
11895
  * @description Computational complexity: O(log size)
12085
11896
  */
12086
11897
  delete(key) {
12087
- return this.editRange(key, key, true, DeleteRange) !== 0;
12088
- }
12089
- with(key, value, overwrite) {
12090
- let nu = this.clone();
12091
- return nu.set(key, value, overwrite) || overwrite ? nu : this;
12092
- }
12093
- /** Returns a copy of the tree with the specified key-value pairs set. */
12094
- withPairs(pairs, overwrite) {
12095
- let nu = this.clone();
12096
- return nu.setPairs(pairs, overwrite) !== 0 || overwrite ? nu : this;
12097
- }
12098
- /** Returns a copy of the tree with the specified keys present.
12099
- * @param keys The keys to add. If a key is already present in the tree,
12100
- * neither the existing key nor the existing value is modified.
12101
- * @param returnThisIfUnchanged if true, returns this if all keys already
12102
- * existed. Performance note: due to the architecture of this class, all
12103
- * node(s) leading to existing keys are cloned even if the collection is
12104
- * ultimately unchanged.
12105
- */
12106
- withKeys(keys, returnThisIfUnchanged) {
12107
- let nu = this.clone(), changed = false;
12108
- for (var i = 0; i < keys.length; i++)
12109
- changed = nu.set(keys[i], void 0, false) || changed;
12110
- return returnThisIfUnchanged && !changed ? this : nu;
12111
- }
12112
- /** Returns a copy of the tree with the specified key removed.
12113
- * @param returnThisIfUnchanged if true, returns this if the key didn't exist.
12114
- * Performance note: due to the architecture of this class, node(s) leading
12115
- * to where the key would have been stored are cloned even when the key
12116
- * turns out not to exist and the collection is unchanged.
12117
- */
12118
- without(key, returnThisIfUnchanged) {
12119
- return this.withoutRange(key, key, true, returnThisIfUnchanged);
12120
- }
12121
- /** Returns a copy of the tree with the specified keys removed.
12122
- * @param returnThisIfUnchanged if true, returns this if none of the keys
12123
- * existed. Performance note: due to the architecture of this class,
12124
- * node(s) leading to where the key would have been stored are cloned
12125
- * even when the key turns out not to exist.
12126
- */
12127
- withoutKeys(keys, returnThisIfUnchanged) {
12128
- let nu = this.clone();
12129
- return nu.deleteKeys(keys) || !returnThisIfUnchanged ? nu : this;
12130
- }
12131
- /** Returns a copy of the tree with the specified range of keys removed. */
12132
- withoutRange(low, high, includeHigh, returnThisIfUnchanged) {
12133
- let nu = this.clone();
12134
- if (nu.deleteRange(low, high, includeHigh) === 0 && returnThisIfUnchanged)
12135
- return this;
12136
- return nu;
12137
- }
12138
- /** Returns a copy of the tree with pairs removed whenever the callback
12139
- * function returns false. `where()` is a synonym for this method. */
12140
- filter(callback, returnThisIfUnchanged) {
12141
- var nu = this.greedyClone();
12142
- var del;
12143
- nu.editAll((k, v2, i) => {
12144
- if (!callback(k, v2, i))
12145
- return del = Delete;
12146
- return void 0;
12147
- });
12148
- if (!del && returnThisIfUnchanged)
12149
- return this;
12150
- return nu;
12151
- }
12152
- /** Returns a copy of the tree with all values altered by a callback function. */
12153
- mapValues(callback) {
12154
- var tmp = {};
12155
- var nu = this.greedyClone();
12156
- nu.editAll((k, v2, i) => {
12157
- return tmp.value = callback(v2, k, i), tmp;
12158
- });
12159
- return nu;
11898
+ return this.#delete(key);
12160
11899
  }
12161
- reduce(callback, initialValue) {
12162
- let i = 0, p = initialValue;
12163
- var it = this.entries(this.minKey(), ReusedArray), next;
12164
- while (!(next = it.next()).done)
12165
- p = callback(p, next.value, i++, this);
12166
- return p;
11900
+ #delete(key) {
11901
+ let root = this.#root;
11902
+ if (root.isShared) {
11903
+ this.#root = root = root.clone();
11904
+ }
11905
+ try {
11906
+ return root.delete(key, this);
11907
+ } finally {
11908
+ let isShared;
11909
+ while (root.keys.length <= 1 && root.isInternal()) {
11910
+ isShared ||= root.isShared;
11911
+ this.#root = root = root.keys.length === 0 ? emptyLeaf : root.children[0];
11912
+ }
11913
+ if (isShared) {
11914
+ root.isShared = true;
11915
+ }
11916
+ }
12167
11917
  }
12168
- /////////////////////////////////////////////////////////////////////////////
12169
- // Iterator methods /////////////////////////////////////////////////////////
12170
- /** Returns an iterator that provides items in order (ascending order if
12171
- * the collection's comparator uses ascending order, as is the default.)
12172
- * @param lowestKey First key to be iterated, or undefined to start at
12173
- * minKey(). If the specified key doesn't exist then iteration
12174
- * starts at the next higher key (according to the comparator).
12175
- * @param reusedArray Optional array used repeatedly to store key-value
12176
- * pairs, to avoid creating a new array on every iteration.
12177
- */
12178
- entries(lowestKey, reusedArray) {
12179
- var info = this.findPath(lowestKey);
12180
- if (info === void 0)
12181
- return iterator();
12182
- var { nodequeue, nodeindex, leaf } = info;
12183
- var state = reusedArray !== void 0 ? 1 : 0;
12184
- var i = lowestKey === void 0 ? -1 : leaf.indexOf(lowestKey, 0, this._compare) - 1;
12185
- return iterator(() => {
12186
- jump:
12187
- for (; ; ) {
12188
- switch (state) {
12189
- case 0:
12190
- if (++i < leaf.keys.length)
12191
- return { done: false, value: [leaf.keys[i], leaf.values[i]] };
12192
- state = 2;
12193
- continue;
12194
- case 1:
12195
- if (++i < leaf.keys.length) {
12196
- reusedArray[0] = leaf.keys[i], reusedArray[1] = leaf.values[i];
12197
- return { done: false, value: reusedArray };
12198
- }
12199
- state = 2;
12200
- case 2:
12201
- for (var level = -1; ; ) {
12202
- if (++level >= nodequeue.length) {
12203
- state = 3;
12204
- continue jump;
12205
- }
12206
- if (++nodeindex[level] < nodequeue[level].length)
12207
- break;
12208
- }
12209
- for (; level > 0; level--) {
12210
- nodequeue[level - 1] = nodequeue[level][nodeindex[level]].children;
12211
- nodeindex[level - 1] = 0;
12212
- }
12213
- leaf = nodequeue[0][nodeindex[0]];
12214
- i = -1;
12215
- state = reusedArray !== void 0 ? 1 : 0;
12216
- continue;
12217
- case 3:
12218
- return { done: true, value: void 0 };
12219
- }
12220
- }
12221
- });
11918
+ keys() {
11919
+ return valuesFrom(this.#root, this.comparator, void 0, true);
12222
11920
  }
12223
- /** Returns an iterator that provides items in reversed order.
12224
- * @param highestKey Key at which to start iterating, or undefined to
12225
- * start at maxKey(). If the specified key doesn't exist then iteration
12226
- * starts at the next lower key (according to the comparator).
12227
- * @param reusedArray Optional array used repeatedly to store key-value
12228
- * pairs, to avoid creating a new array on every iteration.
12229
- * @param skipHighest Iff this flag is true and the highestKey exists in the
12230
- * collection, the pair matching highestKey is skipped, not iterated.
12231
- */
12232
- entriesReversed(highestKey, reusedArray, skipHighest) {
12233
- if (highestKey === void 0) {
12234
- highestKey = this.maxKey();
12235
- skipHighest = void 0;
12236
- if (highestKey === void 0)
12237
- return iterator();
12238
- }
12239
- var { nodequeue, nodeindex, leaf } = this.findPath(highestKey) || this.findPath(this.maxKey());
12240
- check(!nodequeue[0] || leaf === nodequeue[0][nodeindex[0]], "wat!");
12241
- var i = leaf.indexOf(highestKey, 0, this._compare);
12242
- if (!skipHighest && i < leaf.keys.length && this._compare(leaf.keys[i], highestKey) <= 0)
12243
- i++;
12244
- var state = reusedArray !== void 0 ? 1 : 0;
12245
- return iterator(() => {
12246
- jump:
12247
- for (; ; ) {
12248
- switch (state) {
12249
- case 0:
12250
- if (--i >= 0)
12251
- return { done: false, value: [leaf.keys[i], leaf.values[i]] };
12252
- state = 2;
12253
- continue;
12254
- case 1:
12255
- if (--i >= 0) {
12256
- reusedArray[0] = leaf.keys[i], reusedArray[1] = leaf.values[i];
12257
- return { done: false, value: reusedArray };
12258
- }
12259
- state = 2;
12260
- case 2:
12261
- for (var level = -1; ; ) {
12262
- if (++level >= nodequeue.length) {
12263
- state = 3;
12264
- continue jump;
12265
- }
12266
- if (--nodeindex[level] >= 0)
12267
- break;
12268
- }
12269
- for (; level > 0; level--) {
12270
- nodequeue[level - 1] = nodequeue[level][nodeindex[level]].children;
12271
- nodeindex[level - 1] = nodequeue[level - 1].length - 1;
12272
- }
12273
- leaf = nodequeue[0][nodeindex[0]];
12274
- i = leaf.keys.length;
12275
- state = reusedArray !== void 0 ? 1 : 0;
12276
- continue;
12277
- case 3:
12278
- return { done: true, value: void 0 };
12279
- }
12280
- }
12281
- });
11921
+ values() {
11922
+ return valuesFrom(this.#root, this.comparator, void 0, true);
12282
11923
  }
12283
- /* Used by entries() and entriesReversed() to prepare to start iterating.
12284
- * It develops a "node queue" for each non-leaf level of the tree.
12285
- * Levels are numbered "bottom-up" so that level 0 is a list of leaf
12286
- * nodes from a low-level non-leaf node. The queue at a given level L
12287
- * consists of nodequeue[L] which is the children of a BNodeInternal,
12288
- * and nodeindex[L], the current index within that child list, such
12289
- * such that nodequeue[L-1] === nodequeue[L][nodeindex[L]].children.
12290
- * (However inside this function the order is reversed.)
12291
- */
12292
- findPath(key) {
12293
- var nextnode = this._root;
12294
- var nodequeue, nodeindex;
12295
- if (nextnode.isLeaf) {
12296
- nodequeue = EmptyArray, nodeindex = EmptyArray;
12297
- } else {
12298
- nodequeue = [], nodeindex = [];
12299
- for (var d = 0; !nextnode.isLeaf; d++) {
12300
- nodequeue[d] = nextnode.children;
12301
- nodeindex[d] = key === void 0 ? 0 : nextnode.indexOf(key, 0, this._compare);
12302
- if (nodeindex[d] >= nodequeue[d].length)
12303
- return;
12304
- nextnode = nodequeue[d][nodeindex[d]];
12305
- }
12306
- nodequeue.reverse();
12307
- nodeindex.reverse();
12308
- }
12309
- return { nodequeue, nodeindex, leaf: nextnode };
11924
+ valuesFrom(lowestKey, inclusive = true) {
11925
+ return valuesFrom(this.#root, this.comparator, lowestKey, inclusive);
12310
11926
  }
12311
- /**
12312
- * Computes the differences between `this` and `other`.
12313
- * For efficiency, the diff is returned via invocations of supplied handlers.
12314
- * The computation is optimized for the case in which the two trees have large amounts
12315
- * of shared data (obtained by calling the `clone` or `with` APIs) and will avoid
12316
- * any iteration of shared state.
12317
- * The handlers can cause computation to early exit by returning {break: R}.
12318
- * Neither of the collections should be changed during the comparison process (in your callbacks), as this method assumes they will not be mutated.
12319
- * @param other The tree to compute a diff against.
12320
- * @param onlyThis Callback invoked for all keys only present in `this`.
12321
- * @param onlyOther Callback invoked for all keys only present in `other`.
12322
- * @param different Callback invoked for all keys with differing values.
12323
- */
12324
- diffAgainst(other, onlyThis, onlyOther, different) {
12325
- if (other._compare !== this._compare) {
12326
- throw new Error("Tree comparators are not the same.");
12327
- }
12328
- if (this.isEmpty || other.isEmpty) {
12329
- if (this.isEmpty && other.isEmpty)
12330
- return void 0;
12331
- if (this.isEmpty)
12332
- return onlyOther === void 0 ? void 0 : _BTree.stepToEnd(_BTree.makeDiffCursor(other), onlyOther);
12333
- return onlyThis === void 0 ? void 0 : _BTree.stepToEnd(_BTree.makeDiffCursor(this), onlyThis);
12334
- }
12335
- const { _compare } = this;
12336
- const thisCursor = _BTree.makeDiffCursor(this);
12337
- const otherCursor = _BTree.makeDiffCursor(other);
12338
- let thisSuccess = true, otherSuccess = true, prevCursorOrder = _BTree.compare(thisCursor, otherCursor, _compare);
12339
- while (thisSuccess && otherSuccess) {
12340
- const cursorOrder = _BTree.compare(thisCursor, otherCursor, _compare);
12341
- const {
12342
- leaf: thisLeaf,
12343
- internalSpine: thisInternalSpine,
12344
- levelIndices: thisLevelIndices
12345
- } = thisCursor;
12346
- const {
12347
- leaf: otherLeaf,
12348
- internalSpine: otherInternalSpine,
12349
- levelIndices: otherLevelIndices
12350
- } = otherCursor;
12351
- if (thisLeaf || otherLeaf) {
12352
- if (prevCursorOrder !== 0) {
12353
- if (cursorOrder === 0) {
12354
- if (thisLeaf && otherLeaf && different) {
12355
- const valThis = thisLeaf.values[thisLevelIndices[thisLevelIndices.length - 1]];
12356
- const valOther = otherLeaf.values[otherLevelIndices[otherLevelIndices.length - 1]];
12357
- if (!Object.is(valThis, valOther)) {
12358
- const result = different(
12359
- thisCursor.currentKey,
12360
- valThis,
12361
- valOther
12362
- );
12363
- if (result && result.break)
12364
- return result.break;
12365
- }
12366
- }
12367
- } else if (cursorOrder > 0) {
12368
- if (otherLeaf && onlyOther) {
12369
- const otherVal = otherLeaf.values[otherLevelIndices[otherLevelIndices.length - 1]];
12370
- const result = onlyOther(otherCursor.currentKey, otherVal);
12371
- if (result && result.break)
12372
- return result.break;
12373
- }
12374
- } else if (onlyThis) {
12375
- if (thisLeaf && prevCursorOrder !== 0) {
12376
- const valThis = thisLeaf.values[thisLevelIndices[thisLevelIndices.length - 1]];
12377
- const result = onlyThis(thisCursor.currentKey, valThis);
12378
- if (result && result.break)
12379
- return result.break;
12380
- }
12381
- }
12382
- }
12383
- } else if (!thisLeaf && !otherLeaf && cursorOrder === 0) {
12384
- const lastThis = thisInternalSpine.length - 1;
12385
- const lastOther = otherInternalSpine.length - 1;
12386
- const nodeThis = thisInternalSpine[lastThis][thisLevelIndices[lastThis]];
12387
- const nodeOther = otherInternalSpine[lastOther][otherLevelIndices[lastOther]];
12388
- if (nodeOther === nodeThis) {
12389
- prevCursorOrder = 0;
12390
- thisSuccess = _BTree.step(thisCursor, true);
12391
- otherSuccess = _BTree.step(otherCursor, true);
12392
- continue;
12393
- }
12394
- }
12395
- prevCursorOrder = cursorOrder;
12396
- if (cursorOrder < 0) {
12397
- thisSuccess = _BTree.step(thisCursor);
12398
- } else {
12399
- otherSuccess = _BTree.step(otherCursor);
12400
- }
12401
- }
12402
- if (thisSuccess && onlyThis)
12403
- return _BTree.finishCursorWalk(
12404
- thisCursor,
12405
- otherCursor,
12406
- _compare,
12407
- onlyThis
12408
- );
12409
- if (otherSuccess && onlyOther)
12410
- return _BTree.finishCursorWalk(
12411
- otherCursor,
12412
- thisCursor,
12413
- _compare,
12414
- onlyOther
12415
- );
12416
- return void 0;
11927
+ valuesReversed() {
11928
+ return valuesFromReversed(
11929
+ this.#maxKey(),
11930
+ this.#root,
11931
+ this.comparator,
11932
+ void 0,
11933
+ true
11934
+ );
12417
11935
  }
12418
- ///////////////////////////////////////////////////////////////////////////
12419
- // Helper methods for diffAgainst /////////////////////////////////////////
12420
- static finishCursorWalk(cursor, cursorFinished, compareKeys, callback) {
12421
- const compared = _BTree.compare(cursor, cursorFinished, compareKeys);
12422
- if (compared === 0) {
12423
- if (!_BTree.step(cursor))
12424
- return void 0;
12425
- } else if (compared < 0) {
12426
- check(false, "cursor walk terminated early");
12427
- }
12428
- return _BTree.stepToEnd(cursor, callback);
11936
+ valuesFromReversed(highestKey, inclusive = true) {
11937
+ return valuesFromReversed(
11938
+ this.#maxKey(),
11939
+ this.#root,
11940
+ this.comparator,
11941
+ highestKey,
11942
+ inclusive
11943
+ );
12429
11944
  }
12430
- static stepToEnd(cursor, callback) {
12431
- let canStep = true;
12432
- while (canStep) {
12433
- const { leaf, levelIndices, currentKey } = cursor;
12434
- if (leaf) {
12435
- const value = leaf.values[levelIndices[levelIndices.length - 1]];
12436
- const result = callback(currentKey, value);
12437
- if (result && result.break)
12438
- return result.break;
12439
- }
12440
- canStep = _BTree.step(cursor);
12441
- }
12442
- return void 0;
11945
+ /** Gets the highest key in the tree. Complexity: O(1) */
11946
+ #maxKey() {
11947
+ return this.#root.maxKey();
12443
11948
  }
12444
- static makeDiffCursor(tree) {
12445
- const { _root, height } = tree;
12446
- return {
12447
- height,
12448
- internalSpine: [[_root]],
12449
- levelIndices: [0],
12450
- leaf: void 0,
12451
- currentKey: _root.maxKey()
12452
- };
11949
+ [Symbol.iterator]() {
11950
+ return this.keys();
12453
11951
  }
12454
- /**
12455
- * Advances the cursor to the next step in the walk of its tree.
12456
- * Cursors are walked backwards in sort order, as this allows them to leverage maxKey() in order to be compared in O(1).
12457
- * @param cursor The cursor to step
12458
- * @param stepToNode If true, the cursor will be advanced to the next node (skipping values)
12459
- * @returns true if the step was completed and false if the step would have caused the cursor to move beyond the end of the tree.
12460
- */
12461
- static step(cursor, stepToNode) {
12462
- const { internalSpine, levelIndices, leaf } = cursor;
12463
- if (stepToNode === true || leaf) {
12464
- const levelsLength = levelIndices.length;
12465
- if (stepToNode === true || levelIndices[levelsLength - 1] === 0) {
12466
- const spineLength = internalSpine.length;
12467
- if (spineLength === 0)
12468
- return false;
12469
- const nodeLevelIndex = spineLength - 1;
12470
- let levelIndexWalkBack = nodeLevelIndex;
12471
- while (levelIndexWalkBack >= 0) {
12472
- if (levelIndices[levelIndexWalkBack] > 0) {
12473
- if (levelIndexWalkBack < levelsLength - 1) {
12474
- cursor.leaf = void 0;
12475
- levelIndices.pop();
12476
- }
12477
- if (levelIndexWalkBack < nodeLevelIndex)
12478
- cursor.internalSpine = internalSpine.slice(
12479
- 0,
12480
- levelIndexWalkBack + 1
12481
- );
12482
- cursor.currentKey = internalSpine[levelIndexWalkBack][--levelIndices[levelIndexWalkBack]].maxKey();
12483
- return true;
12484
- }
12485
- levelIndexWalkBack--;
11952
+ };
11953
+ function valuesFrom(root, comparator2, lowestKey, inclusive) {
11954
+ const info = findPath(lowestKey, root, comparator2);
11955
+ if (info === void 0) {
11956
+ return iterator(() => ({ done: true, value: void 0 }));
11957
+ }
11958
+ let [nodeQueue, nodeIndex, leaf] = info;
11959
+ let i = lowestKey === void 0 ? -1 : indexOf(lowestKey, leaf.keys, 0, comparator2) - 1;
11960
+ if (!inclusive && i < leaf.keys.length && // +1 because we did -1 above.
11961
+ comparator2(leaf.keys[i + 1], lowestKey) === 0) {
11962
+ i++;
11963
+ }
11964
+ return iterator(() => {
11965
+ for (; ; ) {
11966
+ if (++i < leaf.keys.length) {
11967
+ return { done: false, value: leaf.keys[i] };
11968
+ }
11969
+ let level = -1;
11970
+ for (; ; ) {
11971
+ if (++level >= nodeQueue.length) {
11972
+ return { done: true, value: void 0 };
11973
+ }
11974
+ if (++nodeIndex[level] < nodeQueue[level].length) {
11975
+ break;
12486
11976
  }
12487
- return false;
12488
- } else {
12489
- const valueIndex = --levelIndices[levelsLength - 1];
12490
- cursor.currentKey = leaf.keys[valueIndex];
12491
- return true;
12492
11977
  }
12493
- } else {
12494
- const nextLevel = internalSpine.length;
12495
- const currentLevel = nextLevel - 1;
12496
- const node = internalSpine[currentLevel][levelIndices[currentLevel]];
12497
- if (node.isLeaf) {
12498
- cursor.leaf = node;
12499
- const valueIndex = levelIndices[nextLevel] = node.values.length - 1;
12500
- cursor.currentKey = node.keys[valueIndex];
12501
- } else {
12502
- const children = node.children;
12503
- internalSpine[nextLevel] = children;
12504
- const childIndex = children.length - 1;
12505
- levelIndices[nextLevel] = childIndex;
12506
- cursor.currentKey = children[childIndex].maxKey();
11978
+ for (; level > 0; level--) {
11979
+ nodeQueue[level - 1] = nodeQueue[level][nodeIndex[level]].children;
11980
+ nodeIndex[level - 1] = 0;
12507
11981
  }
12508
- return true;
11982
+ leaf = nodeQueue[0][nodeIndex[0]];
11983
+ i = -1;
12509
11984
  }
11985
+ });
11986
+ }
11987
+ function valuesFromReversed(maxKey, root, comparator2, highestKey, inclusive) {
11988
+ if (highestKey === void 0) {
11989
+ highestKey = maxKey;
11990
+ if (highestKey === void 0)
11991
+ return iterator(() => ({ done: true, value: void 0 }));
12510
11992
  }
12511
- /**
12512
- * Compares the two cursors. Returns a value indicating which cursor is ahead in a walk.
12513
- * Note that cursors are advanced in reverse sorting order.
12514
- */
12515
- static compare(cursorA, cursorB, compareKeys) {
12516
- const {
12517
- height: heightA,
12518
- currentKey: currentKeyA,
12519
- levelIndices: levelIndicesA
12520
- } = cursorA;
12521
- const {
12522
- height: heightB,
12523
- currentKey: currentKeyB,
12524
- levelIndices: levelIndicesB
12525
- } = cursorB;
12526
- const keyComparison = compareKeys(currentKeyB, currentKeyA);
12527
- if (keyComparison !== 0) {
12528
- return keyComparison;
12529
- }
12530
- const heightMin = heightA < heightB ? heightA : heightB;
12531
- const depthANormalized = levelIndicesA.length - (heightA - heightMin);
12532
- const depthBNormalized = levelIndicesB.length - (heightB - heightMin);
12533
- return depthANormalized - depthBNormalized;
12534
- }
12535
- // End of helper methods for diffAgainst //////////////////////////////////
12536
- ///////////////////////////////////////////////////////////////////////////
12537
- /** Returns a new iterator for iterating the keys of each pair in ascending order.
12538
- * @param firstKey: Minimum key to include in the output. */
12539
- keys(firstKey) {
12540
- var it = this.entries(firstKey, ReusedArray);
12541
- return iterator(() => {
12542
- var n = it.next();
12543
- if (n.value)
12544
- n.value = n.value[0];
12545
- return n;
12546
- });
12547
- }
12548
- /** Returns a new iterator for iterating the values of each pair in order by key.
12549
- * @param firstKey: Minimum key whose associated value is included in the output. */
12550
- values(firstKey) {
12551
- var it = this.entries(firstKey, ReusedArray);
12552
- return iterator(() => {
12553
- var n = it.next();
12554
- if (n.value)
12555
- n.value = n.value[1];
12556
- return n;
12557
- });
12558
- }
12559
- /////////////////////////////////////////////////////////////////////////////
12560
- // Additional methods ///////////////////////////////////////////////////////
12561
- /** Returns the maximum number of children/values before nodes will split. */
12562
- get maxNodeSize() {
12563
- return this._maxNodeSize;
12564
- }
12565
- /** Gets the lowest key in the tree. Complexity: O(log size) */
12566
- minKey() {
12567
- return this._root.minKey();
12568
- }
12569
- /** Gets the highest key in the tree. Complexity: O(1) */
12570
- maxKey() {
12571
- return this._root.maxKey();
12572
- }
12573
- /** Quickly clones the tree by marking the root node as shared.
12574
- * Both copies remain editable. When you modify either copy, any
12575
- * nodes that are shared (or potentially shared) between the two
12576
- * copies are cloned so that the changes do not affect other copies.
12577
- * This is known as copy-on-write behavior, or "lazy copying". */
12578
- clone() {
12579
- this._root.isShared = true;
12580
- var result = new _BTree(void 0, this._compare, this._maxNodeSize);
12581
- result._root = this._root;
12582
- result._size = this._size;
12583
- return result;
12584
- }
12585
- /** Performs a greedy clone, immediately duplicating any nodes that are
12586
- * not currently marked as shared, in order to avoid marking any
12587
- * additional nodes as shared.
12588
- * @param force Clone all nodes, even shared ones.
12589
- */
12590
- greedyClone(force) {
12591
- var result = new _BTree(void 0, this._compare, this._maxNodeSize);
12592
- result._root = this._root.greedyClone(force);
12593
- result._size = this._size;
12594
- return result;
11993
+ let [nodeQueue, nodeIndex, leaf] = findPath(highestKey, root, comparator2) || findPath(maxKey, root, comparator2);
11994
+ assert(!nodeQueue[0] || leaf === nodeQueue[0][nodeIndex[0]]);
11995
+ let i = indexOf(highestKey, leaf.keys, 0, comparator2);
11996
+ if (inclusive && i < leaf.keys.length && comparator2(leaf.keys[i], highestKey) <= 0) {
11997
+ i++;
12595
11998
  }
12596
- /** Gets an array filled with the contents of the tree, sorted by key */
12597
- toArray(maxLength = 2147483647) {
12598
- let min = this.minKey(), max = this.maxKey();
12599
- if (min !== void 0)
12600
- return this.getRange(min, max, true, maxLength);
12601
- return [];
12602
- }
12603
- /** Gets an array of all keys, sorted */
12604
- keysArray() {
12605
- var results = [];
12606
- this._root.forRange(
12607
- this.minKey(),
12608
- this.maxKey(),
12609
- true,
12610
- false,
12611
- this,
12612
- 0,
12613
- (k, _v) => {
12614
- results.push(k);
12615
- }
12616
- );
12617
- return results;
12618
- }
12619
- /** Gets an array of all values, sorted by key */
12620
- valuesArray() {
12621
- var results = [];
12622
- this._root.forRange(
12623
- this.minKey(),
12624
- this.maxKey(),
12625
- true,
12626
- false,
12627
- this,
12628
- 0,
12629
- (_k, v2) => {
12630
- results.push(v2);
11999
+ return iterator(() => {
12000
+ for (; ; ) {
12001
+ if (--i >= 0) {
12002
+ return { done: false, value: leaf.keys[i] };
12631
12003
  }
12632
- );
12633
- return results;
12634
- }
12635
- /** Gets a string representing the tree's data based on toArray(). */
12636
- toString() {
12637
- return this.toArray().toString();
12638
- }
12639
- /** Stores a key-value pair only if the key doesn't already exist in the tree.
12640
- * @returns true if a new key was added
12641
- */
12642
- setIfNotPresent(key, value) {
12643
- return this.set(key, value, false);
12644
- }
12645
- /** Returns the next pair whose key is larger than the specified key (or undefined if there is none).
12646
- * If key === undefined, this function returns the lowest pair.
12647
- * @param key The key to search for.
12648
- * @param reusedArray Optional array used repeatedly to store key-value pairs, to
12649
- * avoid creating a new array on every iteration.
12650
- */
12651
- nextHigherPair(key, reusedArray) {
12652
- reusedArray = reusedArray || [];
12653
- if (key === void 0) {
12654
- return this._root.minPair(reusedArray);
12655
- }
12656
- return this._root.getPairOrNextHigher(
12657
- key,
12658
- this._compare,
12659
- false,
12660
- reusedArray
12661
- );
12662
- }
12663
- /** Returns the next key larger than the specified key, or undefined if there is none.
12664
- * Also, nextHigherKey(undefined) returns the lowest key.
12665
- */
12666
- nextHigherKey(key) {
12667
- var p = this.nextHigherPair(key, ReusedArray);
12668
- return p && p[0];
12669
- }
12670
- /** Returns the next pair whose key is smaller than the specified key (or undefined if there is none).
12671
- * If key === undefined, this function returns the highest pair.
12672
- * @param key The key to search for.
12673
- * @param reusedArray Optional array used repeatedly to store key-value pairs, to
12674
- * avoid creating a new array each time you call this method.
12675
- */
12676
- nextLowerPair(key, reusedArray) {
12677
- reusedArray = reusedArray || [];
12678
- if (key === void 0) {
12679
- return this._root.maxPair(reusedArray);
12680
- }
12681
- return this._root.getPairOrNextLower(
12682
- key,
12683
- this._compare,
12684
- false,
12685
- reusedArray
12686
- );
12687
- }
12688
- /** Returns the next key smaller than the specified key, or undefined if there is none.
12689
- * Also, nextLowerKey(undefined) returns the highest key.
12690
- */
12691
- nextLowerKey(key) {
12692
- var p = this.nextLowerPair(key, ReusedArray);
12693
- return p && p[0];
12694
- }
12695
- /** Returns the key-value pair associated with the supplied key if it exists
12696
- * or the pair associated with the next lower pair otherwise. If there is no
12697
- * next lower pair, undefined is returned.
12698
- * @param key The key to search for.
12699
- * @param reusedArray Optional array used repeatedly to store key-value pairs, to
12700
- * avoid creating a new array each time you call this method.
12701
- * */
12702
- getPairOrNextLower(key, reusedArray) {
12703
- return this._root.getPairOrNextLower(
12704
- key,
12705
- this._compare,
12706
- true,
12707
- reusedArray || []
12708
- );
12709
- }
12710
- /** Returns the key-value pair associated with the supplied key if it exists
12711
- * or the pair associated with the next lower pair otherwise. If there is no
12712
- * next lower pair, undefined is returned.
12713
- * @param key The key to search for.
12714
- * @param reusedArray Optional array used repeatedly to store key-value pairs, to
12715
- * avoid creating a new array each time you call this method.
12716
- * */
12717
- getPairOrNextHigher(key, reusedArray) {
12718
- return this._root.getPairOrNextHigher(
12719
- key,
12720
- this._compare,
12721
- true,
12722
- reusedArray || []
12723
- );
12724
- }
12725
- /** Edits the value associated with a key in the tree, if it already exists.
12726
- * @returns true if the key existed, false if not.
12727
- */
12728
- changeIfPresent(key, value) {
12729
- return this.editRange(key, key, true, (_k, _v) => ({ value })) !== 0;
12730
- }
12731
- /**
12732
- * Builds an array of pairs from the specified range of keys, sorted by key.
12733
- * Each returned pair is also an array: pair[0] is the key, pair[1] is the value.
12734
- * @param low The first key in the array will be greater than or equal to `low`.
12735
- * @param high This method returns when a key larger than this is reached.
12736
- * @param includeHigh If the `high` key is present, its pair will be included
12737
- * in the output if and only if this parameter is true. Note: if the
12738
- * `low` key is present, it is always included in the output.
12739
- * @param maxLength Length limit. getRange will stop scanning the tree when
12740
- * the array reaches this size.
12741
- * @description Computational complexity: O(result.length + log size)
12742
- */
12743
- getRange(low, high, includeHigh, maxLength = 67108863) {
12744
- var results = [];
12745
- this._root.forRange(low, high, includeHigh, false, this, 0, (k, v2) => {
12746
- results.push([k, v2]);
12747
- return results.length > maxLength ? Break : void 0;
12748
- });
12749
- return results;
12750
- }
12751
- /** Adds all pairs from a list of key-value pairs.
12752
- * @param pairs Pairs to add to this tree. If there are duplicate keys,
12753
- * later pairs currently overwrite earlier ones (e.g. [[0,1],[0,7]]
12754
- * associates 0 with 7.)
12755
- * @param overwrite Whether to overwrite pairs that already exist (if false,
12756
- * pairs[i] is ignored when the key pairs[i][0] already exists.)
12757
- * @returns The number of pairs added to the collection.
12758
- * @description Computational complexity: O(pairs.length * log(size + pairs.length))
12759
- */
12760
- setPairs(pairs, overwrite) {
12761
- var added = 0;
12762
- for (var i = 0; i < pairs.length; i++)
12763
- if (this.set(pairs[i][0], pairs[i][1], overwrite))
12764
- added++;
12765
- return added;
12766
- }
12767
- /**
12768
- * Scans the specified range of keys, in ascending order by key.
12769
- * Note: the callback `onFound` must not insert or remove items in the
12770
- * collection. Doing so may cause incorrect data to be sent to the
12771
- * callback afterward.
12772
- * @param low The first key scanned will be greater than or equal to `low`.
12773
- * @param high Scanning stops when a key larger than this is reached.
12774
- * @param includeHigh If the `high` key is present, `onFound` is called for
12775
- * that final pair if and only if this parameter is true.
12776
- * @param onFound A function that is called for each key-value pair. This
12777
- * function can return {break:R} to stop early with result R.
12778
- * @param initialCounter Initial third argument of onFound. This value
12779
- * increases by one each time `onFound` is called. Default: 0
12780
- * @returns The number of values found, or R if the callback returned
12781
- * `{break:R}` to stop early.
12782
- * @description Computational complexity: O(number of items scanned + log size)
12783
- */
12784
- forRange(low, high, includeHigh, onFound, initialCounter) {
12785
- var r = this._root.forRange(
12786
- low,
12787
- high,
12788
- includeHigh,
12789
- false,
12790
- this,
12791
- initialCounter || 0,
12792
- onFound
12793
- );
12794
- return typeof r === "number" ? r : r.break;
12795
- }
12796
- /**
12797
- * Scans and potentially modifies values for a subsequence of keys.
12798
- * Note: the callback `onFound` should ideally be a pure function.
12799
- * Specfically, it must not insert items, call clone(), or change
12800
- * the collection except via return value; out-of-band editing may
12801
- * cause an exception or may cause incorrect data to be sent to
12802
- * the callback (duplicate or missed items). It must not cause a
12803
- * clone() of the collection, otherwise the clone could be modified
12804
- * by changes requested by the callback.
12805
- * @param low The first key scanned will be greater than or equal to `low`.
12806
- * @param high Scanning stops when a key larger than this is reached.
12807
- * @param includeHigh If the `high` key is present, `onFound` is called for
12808
- * that final pair if and only if this parameter is true.
12809
- * @param onFound A function that is called for each key-value pair. This
12810
- * function can return `{value:v}` to change the value associated
12811
- * with the current key, `{delete:true}` to delete the current pair,
12812
- * `{break:R}` to stop early with result R, or it can return nothing
12813
- * (undefined or {}) to cause no effect and continue iterating.
12814
- * `{break:R}` can be combined with one of the other two commands.
12815
- * The third argument `counter` is the number of items iterated
12816
- * previously; it equals 0 when `onFound` is called the first time.
12817
- * @returns The number of values scanned, or R if the callback returned
12818
- * `{break:R}` to stop early.
12819
- * @description
12820
- * Computational complexity: O(number of items scanned + log size)
12821
- * Note: if the tree has been cloned with clone(), any shared
12822
- * nodes are copied before `onFound` is called. This takes O(n) time
12823
- * where n is proportional to the amount of shared data scanned.
12824
- */
12825
- editRange(low, high, includeHigh, onFound, initialCounter) {
12826
- var root = this._root;
12827
- if (root.isShared)
12828
- this._root = root = root.clone();
12829
- try {
12830
- var r = root.forRange(
12831
- low,
12832
- high,
12833
- includeHigh,
12834
- true,
12835
- this,
12836
- initialCounter || 0,
12837
- onFound
12838
- );
12839
- return typeof r === "number" ? r : r.break;
12840
- } finally {
12841
- let isShared;
12842
- while (root.keys.length <= 1 && !root.isLeaf) {
12843
- isShared ||= root.isShared;
12844
- this._root = root = root.keys.length === 0 ? EmptyLeaf : root.children[0];
12004
+ let level;
12005
+ for (level = -1; ; ) {
12006
+ if (++level >= nodeQueue.length) {
12007
+ return { done: true, value: void 0 };
12008
+ }
12009
+ if (--nodeIndex[level] >= 0) {
12010
+ break;
12011
+ }
12845
12012
  }
12846
- if (isShared) {
12847
- root.isShared = true;
12013
+ for (; level > 0; level--) {
12014
+ nodeQueue[level - 1] = nodeQueue[level][nodeIndex[level]].children;
12015
+ nodeIndex[level - 1] = nodeQueue[level - 1].length - 1;
12848
12016
  }
12017
+ leaf = nodeQueue[0][nodeIndex[0]];
12018
+ i = leaf.keys.length;
12849
12019
  }
12020
+ });
12021
+ }
12022
+ function findPath(key, root, comparator2) {
12023
+ let nextNode = root;
12024
+ const nodeQueue = [];
12025
+ const nodeIndex = [];
12026
+ if (nextNode.isInternal()) {
12027
+ for (let d = 0; nextNode.isInternal(); d++) {
12028
+ nodeQueue[d] = nextNode.children;
12029
+ nodeIndex[d] = key === void 0 ? 0 : indexOf(key, nextNode.keys, 0, comparator2);
12030
+ if (nodeIndex[d] >= nodeQueue[d].length)
12031
+ return;
12032
+ nextNode = nodeQueue[d][nodeIndex[d]];
12033
+ }
12034
+ nodeQueue.reverse();
12035
+ nodeIndex.reverse();
12850
12036
  }
12851
- /** Same as `editRange` except that the callback is called for all pairs. */
12852
- editAll(onFound, initialCounter) {
12853
- return this.editRange(
12854
- this.minKey(),
12855
- this.maxKey(),
12856
- true,
12857
- onFound,
12858
- initialCounter
12859
- );
12860
- }
12861
- /**
12862
- * Removes a range of key-value pairs from the B+ tree.
12863
- * @param low The first key scanned will be greater than or equal to `low`.
12864
- * @param high Scanning stops when a key larger than this is reached.
12865
- * @param includeHigh Specifies whether the `high` key, if present, is deleted.
12866
- * @returns The number of key-value pairs that were deleted.
12867
- * @description Computational complexity: O(log size + number of items deleted)
12868
- */
12869
- deleteRange(low, high, includeHigh) {
12870
- return this.editRange(low, high, includeHigh, DeleteRange);
12871
- }
12872
- /** Deletes a series of keys from the collection. */
12873
- deleteKeys(keys) {
12874
- for (var i = 0, r = 0; i < keys.length; i++)
12875
- if (this.delete(keys[i]))
12876
- r++;
12877
- return r;
12878
- }
12879
- /** Gets the height of the tree: the number of internal nodes between the
12880
- * BTree object and its leaf nodes (zero if there are no internal nodes). */
12881
- get height() {
12882
- let node = this._root;
12883
- let height = -1;
12884
- while (node) {
12885
- height++;
12886
- node = node.isLeaf ? void 0 : node.children[0];
12887
- }
12888
- return height;
12889
- }
12890
- /** Makes the object read-only to ensure it is not accidentally modified.
12891
- * Freezing does not have to be permanent; unfreeze() reverses the effect.
12892
- * This is accomplished by replacing mutator functions with a function
12893
- * that throws an Error. Compared to using a property (e.g. this.isFrozen)
12894
- * this implementation gives better performance in non-frozen BTrees.
12895
- */
12896
- freeze() {
12897
- var t2 = this;
12898
- t2.clear = t2.set = t2.editRange = function() {
12899
- throw new Error("Attempted to modify a frozen BTree");
12900
- };
12901
- }
12902
- /** Ensures mutations are allowed, reversing the effect of freeze(). */
12903
- unfreeze() {
12904
- delete this.clear;
12905
- delete this.set;
12906
- delete this.editRange;
12907
- }
12908
- /** Returns true if the tree appears to be frozen. */
12909
- get isFrozen() {
12910
- return this.hasOwnProperty("editRange");
12911
- }
12912
- /** Scans the tree for signs of serious bugs (e.g. this.size doesn't match
12913
- * number of elements, internal nodes not caching max element properly...)
12914
- * Computational complexity: O(number of nodes), i.e. O(size). This method
12915
- * skips the most expensive test - whether all keys are sorted - but it
12916
- * does check that maxKey() of the children of internal nodes are sorted. */
12917
- checkValid() {
12918
- var size = this._root.checkValid(0, this, 0);
12919
- check(
12920
- size === this.size,
12921
- "size mismatch: counted ",
12922
- size,
12923
- "but stored",
12924
- this.size
12925
- );
12926
- }
12927
- [Symbol.iterator] = this.entries.bind(this);
12928
- where = this.filter.bind(this);
12929
- setRange = this.setPairs.bind(this);
12930
- add = this.set.bind(this);
12931
- // for compatibility with ISetSink<K>
12932
- };
12933
- function iterator(next = () => ({ done: true, value: void 0 })) {
12934
- var result = { next };
12935
- if (Symbol && Symbol.iterator)
12936
- result[Symbol.iterator] = function() {
12037
+ return [nodeQueue, nodeIndex, nextNode];
12038
+ }
12039
+ function iterator(next) {
12040
+ return {
12041
+ next,
12042
+ [Symbol.iterator]() {
12937
12043
  return this;
12938
- };
12939
- return result;
12044
+ }
12045
+ };
12940
12046
  }
12941
12047
  var BNode = class _BNode {
12942
12048
  // If this is an internal node, _keys[i] is the highest key in children[i].
12943
12049
  keys;
12944
- values;
12945
12050
  // True if this node might be within multiple `BTree`s (or have multiple parents).
12946
12051
  // If so, it must be cloned before being mutated to avoid changing an unrelated tree.
12947
12052
  // This is transitive: if it's true, children are also shared even if `isShared!=true`
12948
12053
  // in those children. (Certain operations will propagate isShared=true to children.)
12949
12054
  isShared;
12950
- get isLeaf() {
12951
- return this.children === void 0;
12952
- }
12953
- constructor(keys = [], values) {
12055
+ constructor(keys) {
12954
12056
  this.keys = keys;
12955
- this.values = values || undefVals;
12956
12057
  this.isShared = void 0;
12957
12058
  }
12958
- ///////////////////////////////////////////////////////////////////////////
12959
- // Shared methods /////////////////////////////////////////////////////////
12059
+ isInternal() {
12060
+ return false;
12061
+ }
12960
12062
  maxKey() {
12961
12063
  return this.keys[this.keys.length - 1];
12962
12064
  }
12963
- // If key not found, returns i^failXor where i is the insertion index.
12964
- // Callers that don't care whether there was a match will set failXor=0.
12965
- indexOf(key, failXor, cmp2) {
12966
- const keys = this.keys;
12967
- var lo = 0, hi = keys.length, mid = hi >> 1;
12968
- while (lo < hi) {
12969
- var c = cmp2(keys[mid], key);
12970
- if (c < 0)
12971
- lo = mid + 1;
12972
- else if (c > 0)
12973
- hi = mid;
12974
- else if (c === 0)
12975
- return mid;
12976
- else {
12977
- if (key === key)
12978
- return keys.length;
12979
- else
12980
- throw new Error("BTree: NaN was used as a key");
12981
- }
12982
- mid = lo + hi >> 1;
12983
- }
12984
- return mid ^ failXor;
12985
- }
12986
- /////////////////////////////////////////////////////////////////////////////
12987
- // Leaf Node: misc //////////////////////////////////////////////////////////
12988
12065
  minKey() {
12989
12066
  return this.keys[0];
12990
12067
  }
12991
- minPair(reusedArray) {
12992
- if (this.keys.length === 0)
12993
- return void 0;
12994
- reusedArray[0] = this.keys[0];
12995
- reusedArray[1] = this.values[0];
12996
- return reusedArray;
12997
- }
12998
- maxPair(reusedArray) {
12999
- if (this.keys.length === 0)
13000
- return void 0;
13001
- const lastIndex = this.keys.length - 1;
13002
- reusedArray[0] = this.keys[lastIndex];
13003
- reusedArray[1] = this.values[lastIndex];
13004
- return reusedArray;
13005
- }
13006
12068
  clone() {
13007
- var v2 = this.values;
13008
- return new _BNode(
13009
- this.keys.slice(0),
13010
- v2 === undefVals ? v2 : v2.slice(0)
13011
- );
13012
- }
13013
- greedyClone(force) {
13014
- return this.isShared && !force ? this : this.clone();
13015
- }
13016
- get(key, defaultValue, tree) {
13017
- var i = this.indexOf(key, -1, tree._compare);
13018
- return i < 0 ? defaultValue : this.values[i];
12069
+ return new _BNode(this.keys.slice(0));
13019
12070
  }
13020
- getPairOrNextLower(key, compare, inclusive, reusedArray) {
13021
- var i = this.indexOf(key, -1, compare);
13022
- const indexOrLower = i < 0 ? ~i - 1 : inclusive ? i : i - 1;
13023
- if (indexOrLower >= 0) {
13024
- reusedArray[0] = this.keys[indexOrLower];
13025
- reusedArray[1] = this.values[indexOrLower];
13026
- return reusedArray;
13027
- }
13028
- return void 0;
12071
+ get(key, tree) {
12072
+ const i = indexOf(key, this.keys, -1, tree.comparator);
12073
+ return i < 0 ? void 0 : this.keys[i];
13029
12074
  }
13030
- getPairOrNextHigher(key, compare, inclusive, reusedArray) {
13031
- var i = this.indexOf(key, -1, compare);
13032
- const indexOrLower = i < 0 ? ~i : inclusive ? i : i + 1;
13033
- const keys = this.keys;
13034
- if (indexOrLower < keys.length) {
13035
- reusedArray[0] = keys[indexOrLower];
13036
- reusedArray[1] = this.values[indexOrLower];
13037
- return reusedArray;
13038
- }
13039
- return void 0;
12075
+ has(key, tree) {
12076
+ const i = indexOf(key, this.keys, -1, tree.comparator);
12077
+ return i >= 0 && i < this.keys.length;
13040
12078
  }
13041
- checkValid(depth, _tree, baseIndex) {
13042
- var kL = this.keys.length, vL = this.values.length;
13043
- check(
13044
- this.values === undefVals ? kL <= vL : kL === vL,
13045
- "keys/values length mismatch: depth",
13046
- depth,
13047
- "with lengths",
13048
- kL,
13049
- vL,
13050
- "and baseIndex",
13051
- baseIndex
13052
- );
13053
- check(
13054
- depth == 0 || kL > 0,
13055
- "empty leaf at depth",
13056
- depth,
13057
- "and baseIndex",
13058
- baseIndex
13059
- );
13060
- return kL;
13061
- }
13062
- /////////////////////////////////////////////////////////////////////////////
13063
- // Leaf Node: set & node splitting //////////////////////////////////////////
13064
- set(key, value, overwrite, tree) {
13065
- var i = this.indexOf(key, -1, tree._compare);
12079
+ set(key, tree) {
12080
+ let i = indexOf(key, this.keys, -1, tree.comparator);
13066
12081
  if (i < 0) {
13067
12082
  i = ~i;
13068
- tree._size++;
13069
- if (this.keys.length < tree._maxNodeSize) {
13070
- return this.insertInLeaf(i, key, value, tree);
13071
- } else {
13072
- var newRightSibling = this.splitOffRightSide(), target = this;
13073
- if (i > this.keys.length) {
13074
- i -= this.keys.length;
13075
- target = newRightSibling;
13076
- }
13077
- target.insertInLeaf(i, key, value, tree);
13078
- return newRightSibling;
13079
- }
13080
- } else {
13081
- if (overwrite !== false) {
13082
- if (value !== void 0)
13083
- this.reifyValues();
13084
- this.keys[i] = key;
13085
- this.values[i] = value;
13086
- }
13087
- return false;
13088
- }
13089
- }
13090
- reifyValues() {
13091
- if (this.values === undefVals)
13092
- return this.values = this.values.slice(0, this.keys.length);
13093
- return this.values;
13094
- }
13095
- insertInLeaf(i, key, value, tree) {
13096
- this.keys.splice(i, 0, key);
13097
- if (this.values === undefVals) {
13098
- while (undefVals.length < tree._maxNodeSize)
13099
- undefVals.push(void 0);
13100
- if (value === void 0) {
13101
- return true;
13102
- } else {
13103
- this.values = undefVals.slice(0, this.keys.length - 1);
12083
+ tree.size++;
12084
+ if (this.keys.length < MAX_NODE_SIZE) {
12085
+ this.keys.splice(i, 0, key);
12086
+ return null;
12087
+ }
12088
+ const newRightSibling = this.splitOffRightSide();
12089
+ let target = this;
12090
+ if (i > this.keys.length) {
12091
+ i -= this.keys.length;
12092
+ target = newRightSibling;
13104
12093
  }
12094
+ target.keys.splice(i, 0, key);
12095
+ return newRightSibling;
13105
12096
  }
13106
- this.values.splice(i, 0, value);
13107
- return true;
12097
+ this.keys[i] = key;
12098
+ return null;
13108
12099
  }
13109
12100
  takeFromRight(rhs) {
13110
- var v2 = this.values;
13111
- if (rhs.values === undefVals) {
13112
- if (v2 !== undefVals)
13113
- v2.push(void 0);
13114
- } else {
13115
- v2 = this.reifyValues();
13116
- v2.push(rhs.values.shift());
13117
- }
13118
12101
  this.keys.push(rhs.keys.shift());
13119
12102
  }
13120
12103
  takeFromLeft(lhs) {
13121
- var v2 = this.values;
13122
- if (lhs.values === undefVals) {
13123
- if (v2 !== undefVals)
13124
- v2.unshift(void 0);
13125
- } else {
13126
- v2 = this.reifyValues();
13127
- v2.unshift(lhs.values.pop());
13128
- }
13129
12104
  this.keys.unshift(lhs.keys.pop());
13130
12105
  }
13131
12106
  splitOffRightSide() {
13132
- var half = this.keys.length >> 1, keys = this.keys.splice(half);
13133
- var values = this.values === undefVals ? undefVals : this.values.splice(half);
13134
- return new _BNode(keys, values);
13135
- }
13136
- /////////////////////////////////////////////////////////////////////////////
13137
- // Leaf Node: scanning & deletions //////////////////////////////////////////
13138
- forRange(low, high, includeHigh, editMode, tree, count, onFound) {
13139
- var cmp2 = tree._compare;
13140
- var iLow, iHigh;
13141
- if (high === low) {
13142
- if (!includeHigh)
13143
- return count;
13144
- iHigh = (iLow = this.indexOf(low, -1, cmp2)) + 1;
13145
- if (iLow < 0)
13146
- return count;
13147
- } else {
13148
- iLow = this.indexOf(low, 0, cmp2);
13149
- iHigh = this.indexOf(high, -1, cmp2);
13150
- if (iHigh < 0)
13151
- iHigh = ~iHigh;
13152
- else if (includeHigh === true)
13153
- iHigh++;
13154
- }
13155
- var keys = this.keys, values = this.values;
13156
- if (onFound !== void 0) {
13157
- for (var i = iLow; i < iHigh; i++) {
13158
- var key = keys[i];
13159
- var result = onFound(key, values[i], count++);
13160
- if (result !== void 0) {
13161
- if (editMode === true) {
13162
- if (key !== keys[i] || this.isShared === true)
13163
- throw new Error("BTree illegally changed or cloned in editRange");
13164
- if (result.delete) {
13165
- this.keys.splice(i, 1);
13166
- if (this.values !== undefVals)
13167
- this.values.splice(i, 1);
13168
- tree._size--;
13169
- i--;
13170
- iHigh--;
13171
- } else if (result.hasOwnProperty("value")) {
13172
- values[i] = result.value;
13173
- }
13174
- }
13175
- if (result.break !== void 0)
13176
- return result;
13177
- }
12107
+ const half = this.keys.length >> 1;
12108
+ const keys = this.keys.splice(half);
12109
+ return new _BNode(keys);
12110
+ }
12111
+ delete(key, tree) {
12112
+ const cmp2 = tree.comparator;
12113
+ const iLow = indexOf(key, this.keys, -1, cmp2);
12114
+ const iHigh = iLow + 1;
12115
+ if (iLow < 0) {
12116
+ return false;
12117
+ }
12118
+ const { keys } = this;
12119
+ for (let i = iLow; i < iHigh; i++) {
12120
+ const key2 = keys[i];
12121
+ if (key2 !== keys[i] || this.isShared === true) {
12122
+ throw new Error("BTree illegally changed or cloned in delete");
13178
12123
  }
13179
- } else
13180
- count += iHigh - iLow;
13181
- return count;
12124
+ this.keys.splice(i, 1);
12125
+ tree.size--;
12126
+ return true;
12127
+ }
12128
+ return false;
13182
12129
  }
13183
- /** Adds entire contents of right-hand sibling (rhs is left unchanged) */
13184
12130
  mergeSibling(rhs, _) {
13185
- this.keys.push.apply(this.keys, rhs.keys);
13186
- if (this.values === undefVals) {
13187
- if (rhs.values === undefVals)
13188
- return;
13189
- this.values = this.values.slice(0, this.keys.length);
13190
- }
13191
- this.values.push.apply(this.values, rhs.reifyValues());
12131
+ this.keys.push(...rhs.keys);
13192
12132
  }
13193
12133
  };
13194
12134
  var BNodeInternal = class _BNodeInternal extends BNode {
@@ -13203,187 +12143,75 @@ var BNodeInternal = class _BNodeInternal extends BNode {
13203
12143
  constructor(children, keys) {
13204
12144
  if (!keys) {
13205
12145
  keys = [];
13206
- for (var i = 0; i < children.length; i++)
12146
+ for (let i = 0; i < children.length; i++) {
13207
12147
  keys[i] = children[i].maxKey();
12148
+ }
13208
12149
  }
13209
12150
  super(keys);
13210
12151
  this.children = children;
13211
12152
  }
12153
+ isInternal() {
12154
+ return true;
12155
+ }
13212
12156
  clone() {
13213
- var children = this.children.slice(0);
13214
- for (var i = 0; i < children.length; i++)
12157
+ const children = this.children.slice(0);
12158
+ for (let i = 0; i < children.length; i++) {
13215
12159
  children[i].isShared = true;
12160
+ }
13216
12161
  return new _BNodeInternal(children, this.keys.slice(0));
13217
12162
  }
13218
- greedyClone(force) {
13219
- if (this.isShared && !force)
13220
- return this;
13221
- var nu = new _BNodeInternal(
13222
- this.children.slice(0),
13223
- this.keys.slice(0)
13224
- );
13225
- for (var i = 0; i < nu.children.length; i++)
13226
- nu.children[i] = nu.children[i].greedyClone(force);
13227
- return nu;
13228
- }
13229
12163
  minKey() {
13230
12164
  return this.children[0].minKey();
13231
12165
  }
13232
- minPair(reusedArray) {
13233
- return this.children[0].minPair(reusedArray);
13234
- }
13235
- maxPair(reusedArray) {
13236
- return this.children[this.children.length - 1].maxPair(reusedArray);
13237
- }
13238
- get(key, defaultValue, tree) {
13239
- var i = this.indexOf(key, 0, tree._compare), children = this.children;
13240
- return i < children.length ? children[i].get(key, defaultValue, tree) : void 0;
13241
- }
13242
- getPairOrNextLower(key, compare, inclusive, reusedArray) {
13243
- var i = this.indexOf(key, 0, compare), children = this.children;
13244
- if (i >= children.length)
13245
- return this.maxPair(reusedArray);
13246
- const result = children[i].getPairOrNextLower(
13247
- key,
13248
- compare,
13249
- inclusive,
13250
- reusedArray
13251
- );
13252
- if (result === void 0 && i > 0) {
13253
- return children[i - 1].maxPair(reusedArray);
13254
- }
13255
- return result;
13256
- }
13257
- getPairOrNextHigher(key, compare, inclusive, reusedArray) {
13258
- var i = this.indexOf(key, 0, compare), children = this.children, length = children.length;
13259
- if (i >= length)
13260
- return void 0;
13261
- const result = children[i].getPairOrNextHigher(
13262
- key,
13263
- compare,
13264
- inclusive,
13265
- reusedArray
13266
- );
13267
- if (result === void 0 && i < length - 1) {
13268
- return children[i + 1].minPair(reusedArray);
13269
- }
13270
- return result;
13271
- }
13272
- checkValid(depth, tree, baseIndex) {
13273
- let kL = this.keys.length, cL = this.children.length;
13274
- check(
13275
- kL === cL,
13276
- "keys/children length mismatch: depth",
13277
- depth,
13278
- "lengths",
13279
- kL,
13280
- cL,
13281
- "baseIndex",
13282
- baseIndex
13283
- );
13284
- check(
13285
- kL > 1 || depth > 0,
13286
- "internal node has length",
13287
- kL,
13288
- "at depth",
13289
- depth,
13290
- "baseIndex",
13291
- baseIndex
13292
- );
13293
- let size = 0, c = this.children, k = this.keys, childSize = 0;
13294
- for (var i = 0; i < cL; i++) {
13295
- size += c[i].checkValid(depth + 1, tree, baseIndex + size);
13296
- childSize += c[i].keys.length;
13297
- check(size >= childSize, "wtf", baseIndex);
13298
- check(
13299
- i === 0 || c[i - 1].constructor === c[i].constructor,
13300
- "type mismatch, baseIndex:",
13301
- baseIndex
13302
- );
13303
- if (c[i].maxKey() != k[i])
13304
- check(
13305
- false,
13306
- "keys[",
13307
- i,
13308
- "] =",
13309
- k[i],
13310
- "is wrong, should be ",
13311
- c[i].maxKey(),
13312
- "at depth",
13313
- depth,
13314
- "baseIndex",
13315
- baseIndex
13316
- );
13317
- if (!(i === 0 || tree._compare(k[i - 1], k[i]) < 0))
13318
- check(
13319
- false,
13320
- "sort violation at depth",
13321
- depth,
13322
- "index",
13323
- i,
13324
- "keys",
13325
- k[i - 1],
13326
- k[i]
13327
- );
13328
- }
13329
- let toofew = childSize === 0;
13330
- if (toofew || childSize > tree.maxNodeSize * cL)
13331
- check(
13332
- false,
13333
- toofew ? "too few" : "too many",
13334
- "children (",
13335
- childSize,
13336
- size,
13337
- ") at depth",
13338
- depth,
13339
- "maxNodeSize:",
13340
- tree.maxNodeSize,
13341
- "children.length:",
13342
- cL,
13343
- "baseIndex:",
13344
- baseIndex
13345
- );
13346
- return size;
13347
- }
13348
- /////////////////////////////////////////////////////////////////////////////
13349
- // Internal Node: set & node splitting //////////////////////////////////////
13350
- set(key, value, overwrite, tree) {
13351
- var c = this.children, max = tree._maxNodeSize, cmp2 = tree._compare;
13352
- var i = Math.min(this.indexOf(key, 0, cmp2), c.length - 1), child = c[i];
13353
- if (child.isShared)
12166
+ get(key, tree) {
12167
+ const i = indexOf(key, this.keys, 0, tree.comparator);
12168
+ const { children } = this;
12169
+ return i < children.length ? children[i].get(key, tree) : void 0;
12170
+ }
12171
+ has(key, tree) {
12172
+ const i = indexOf(key, this.keys, 0, tree.comparator);
12173
+ const { children } = this;
12174
+ return i < children.length ? children[i].has(key, tree) : false;
12175
+ }
12176
+ set(key, tree) {
12177
+ const c = this.children;
12178
+ const cmp2 = tree.comparator;
12179
+ let i = Math.min(indexOf(key, this.keys, 0, cmp2), c.length - 1);
12180
+ let child = c[i];
12181
+ if (child.isShared) {
13354
12182
  c[i] = child = child.clone();
13355
- if (child.keys.length >= max) {
13356
- var other;
13357
- if (i > 0 && (other = c[i - 1]).keys.length < max && cmp2(child.keys[0], key) < 0) {
13358
- if (other.isShared)
12183
+ }
12184
+ if (child.keys.length >= MAX_NODE_SIZE) {
12185
+ let other;
12186
+ if (i > 0 && (other = c[i - 1]).keys.length < MAX_NODE_SIZE && cmp2(child.keys[0], key) < 0) {
12187
+ if (other.isShared) {
13359
12188
  c[i - 1] = other = other.clone();
12189
+ }
13360
12190
  other.takeFromRight(child);
13361
12191
  this.keys[i - 1] = other.maxKey();
13362
- } else if ((other = c[i + 1]) !== void 0 && other.keys.length < max && cmp2(child.maxKey(), key) < 0) {
12192
+ } else if ((other = c[i + 1]) !== void 0 && other.keys.length < MAX_NODE_SIZE && cmp2(child.maxKey(), key) < 0) {
13363
12193
  if (other.isShared)
13364
12194
  c[i + 1] = other = other.clone();
13365
12195
  other.takeFromLeft(child);
13366
12196
  this.keys[i] = c[i].maxKey();
13367
12197
  }
13368
12198
  }
13369
- var result = child.set(key, value, overwrite, tree);
13370
- if (result === false)
13371
- return false;
12199
+ const result = child.set(key, tree);
13372
12200
  this.keys[i] = child.maxKey();
13373
- if (result === true)
13374
- return true;
13375
- if (this.keys.length < max) {
12201
+ if (result === null)
12202
+ return null;
12203
+ if (this.keys.length < MAX_NODE_SIZE) {
13376
12204
  this.insert(i + 1, result);
13377
- return true;
13378
- } else {
13379
- var newRightSibling = this.splitOffRightSide(), target = this;
13380
- if (cmp2(result.maxKey(), this.maxKey()) > 0) {
13381
- target = newRightSibling;
13382
- i -= this.keys.length;
13383
- }
13384
- target.insert(i + 1, result);
13385
- return newRightSibling;
12205
+ return null;
13386
12206
  }
12207
+ const newRightSibling = this.splitOffRightSide();
12208
+ let target = this;
12209
+ if (cmp2(result.maxKey(), this.maxKey()) > 0) {
12210
+ target = newRightSibling;
12211
+ i -= this.keys.length;
12212
+ }
12213
+ target.insert(i + 1, result);
12214
+ return newRightSibling;
13387
12215
  }
13388
12216
  /**
13389
12217
  * Inserts `child` at index `i`.
@@ -13399,7 +12227,7 @@ var BNodeInternal = class _BNodeInternal extends BNode {
13399
12227
  * Modifies this to remove the second half of the items, returning a separate node containing them.
13400
12228
  */
13401
12229
  splitOffRightSide() {
13402
- var half = this.children.length >> 1;
12230
+ const half = this.children.length >> 1;
13403
12231
  return new _BNodeInternal(
13404
12232
  this.children.splice(half),
13405
12233
  this.keys.splice(half)
@@ -13413,76 +12241,42 @@ var BNodeInternal = class _BNodeInternal extends BNode {
13413
12241
  this.keys.unshift(lhs.keys.pop());
13414
12242
  this.children.unshift(lhs.children.pop());
13415
12243
  }
13416
- /////////////////////////////////////////////////////////////////////////////
13417
- // Internal Node: scanning & deletions //////////////////////////////////////
13418
- // Note: `count` is the next value of the third argument to `onFound`.
13419
- // A leaf node's `forRange` function returns a new value for this counter,
13420
- // unless the operation is to stop early.
13421
- forRange(low, high, includeHigh, editMode, tree, count, onFound) {
13422
- var cmp2 = tree._compare;
13423
- var keys = this.keys, children = this.children;
13424
- var iLow = this.indexOf(low, 0, cmp2), i = iLow;
13425
- var iHigh = Math.min(
13426
- high === low ? iLow : this.indexOf(high, 0, cmp2),
13427
- keys.length - 1
13428
- );
13429
- if (!editMode) {
13430
- for (; i <= iHigh; i++) {
13431
- var result = children[i].forRange(
13432
- low,
13433
- high,
13434
- includeHigh,
13435
- editMode,
13436
- tree,
13437
- count,
13438
- onFound
13439
- );
13440
- if (typeof result !== "number")
13441
- return result;
13442
- count = result;
13443
- }
13444
- } else if (i <= iHigh) {
12244
+ delete(key, tree) {
12245
+ const cmp2 = tree.comparator;
12246
+ const { keys } = this;
12247
+ const { children } = this;
12248
+ let iLow = indexOf(key, this.keys, 0, cmp2);
12249
+ let i = iLow;
12250
+ const iHigh = Math.min(iLow, keys.length - 1);
12251
+ if (i <= iHigh) {
13445
12252
  try {
13446
- for (; i <= iHigh; i++) {
13447
- if (children[i].isShared)
13448
- children[i] = children[i].clone();
13449
- var result = children[i].forRange(
13450
- low,
13451
- high,
13452
- includeHigh,
13453
- editMode,
13454
- tree,
13455
- count,
13456
- onFound
13457
- );
13458
- keys[i] = children[i].maxKey();
13459
- if (typeof result !== "number")
13460
- return result;
13461
- count = result;
12253
+ if (children[i].isShared) {
12254
+ children[i] = children[i].clone();
13462
12255
  }
12256
+ const result = children[i].delete(key, tree);
12257
+ keys[i] = children[i].maxKey();
12258
+ return result;
13463
12259
  } finally {
13464
- var half = tree._maxNodeSize >> 1;
12260
+ const half = MAX_NODE_SIZE >> 1;
13465
12261
  if (iLow > 0)
13466
12262
  iLow--;
13467
12263
  for (i = iHigh; i >= iLow; i--) {
13468
12264
  if (children[i].keys.length <= half) {
13469
12265
  if (children[i].keys.length !== 0) {
13470
- this.tryMerge(i, tree._maxNodeSize);
12266
+ this.tryMerge(i, MAX_NODE_SIZE);
13471
12267
  } else {
13472
12268
  keys.splice(i, 1);
13473
12269
  children.splice(i, 1);
13474
12270
  }
13475
12271
  }
13476
12272
  }
13477
- if (children.length !== 0 && children[0].keys.length === 0)
13478
- check(false, "emptiness bug");
13479
12273
  }
13480
12274
  }
13481
- return count;
12275
+ return false;
13482
12276
  }
13483
12277
  /** Merges child i with child i+1 if their combined size is not too large */
13484
12278
  tryMerge(i, maxSize) {
13485
- var children = this.children;
12279
+ const { children } = this;
13486
12280
  if (i >= 0 && i + 1 < children.length) {
13487
12281
  if (children[i].keys.length + children[i + 1].keys.length <= maxSize) {
13488
12282
  if (children[i].isShared)
@@ -13502,39 +12296,42 @@ var BNodeInternal = class _BNodeInternal extends BNode {
13502
12296
  * (otherwise isShared for its children could be incorrect).
13503
12297
  */
13504
12298
  mergeSibling(rhs, maxNodeSize) {
13505
- var oldLength = this.keys.length;
13506
- this.keys.push.apply(this.keys, rhs.keys);
12299
+ const oldLength = this.keys.length;
12300
+ this.keys.push(...rhs.keys);
13507
12301
  const rhsChildren = rhs.children;
13508
- this.children.push.apply(this.children, rhsChildren);
12302
+ this.children.push(...rhsChildren);
13509
12303
  if (rhs.isShared && !this.isShared) {
13510
- for (var i = 0; i < rhsChildren.length; i++)
12304
+ for (let i = 0; i < rhsChildren.length; i++) {
13511
12305
  rhsChildren[i].isShared = true;
12306
+ }
13512
12307
  }
13513
12308
  this.tryMerge(oldLength - 1, maxNodeSize);
13514
12309
  }
13515
12310
  };
13516
- var undefVals = [];
13517
- var Delete = { delete: true };
13518
- var DeleteRange = () => Delete;
13519
- var Break = { break: true };
13520
- var EmptyLeaf = function() {
13521
- var n = new BNode();
13522
- n.isShared = true;
13523
- return n;
13524
- }();
13525
- var EmptyArray = [];
13526
- var ReusedArray = [];
13527
- function check(fact, ...args) {
13528
- if (!fact) {
13529
- args.unshift("B+ tree");
13530
- throw new Error(args.join(" "));
13531
- }
13532
- }
13533
- var EmptyBTree = (() => {
13534
- let t2 = new BTree();
13535
- t2.freeze();
13536
- return t2;
13537
- })();
12311
+ function indexOf(key, keys, failXor, comparator2) {
12312
+ let lo = 0;
12313
+ let hi = keys.length;
12314
+ let mid = hi >> 1;
12315
+ while (lo < hi) {
12316
+ const c = comparator2(keys[mid], key);
12317
+ if (c < 0) {
12318
+ lo = mid + 1;
12319
+ } else if (c > 0) {
12320
+ hi = mid;
12321
+ } else if (c === 0) {
12322
+ return mid;
12323
+ } else {
12324
+ if (key === key) {
12325
+ return keys.length;
12326
+ }
12327
+ throw new Error("NaN was used as a key");
12328
+ }
12329
+ mid = lo + hi >> 1;
12330
+ }
12331
+ return mid ^ failXor;
12332
+ }
12333
+ var emptyLeaf = new BNode([]);
12334
+ emptyLeaf.isShared = true;
13538
12335
 
13539
12336
  // ../zql/src/ivm/constraint.ts
13540
12337
  function constraintMatchesRow(constraint, row) {
@@ -13573,10 +12370,10 @@ var MemorySource = class {
13573
12370
  this.#columns = columns;
13574
12371
  this.#primaryKey = primaryKey;
13575
12372
  this.#primaryIndexSort = primaryKey.map((k) => [k, "asc"]);
13576
- const comparator = makeBoundComparator(this.#primaryIndexSort);
12373
+ const comparator2 = makeBoundComparator(this.#primaryIndexSort);
13577
12374
  this.#indexes.set(JSON.stringify(this.#primaryIndexSort), {
13578
- comparator,
13579
- data: new BTree([], comparator),
12375
+ comparator: comparator2,
12376
+ data: new BTreeSet(comparator2),
13580
12377
  usedBy: /* @__PURE__ */ new Set()
13581
12378
  });
13582
12379
  assertOrderingIncludesPK(this.#primaryIndexSort, this.#primaryKey);
@@ -13658,12 +12455,12 @@ var MemorySource = class {
13658
12455
  index.usedBy.add(usedBy);
13659
12456
  return index;
13660
12457
  }
13661
- const comparator = makeBoundComparator(sort);
13662
- const data = new BTree([], comparator);
13663
- for (const row of this.#getPrimaryIndex().data.keys()) {
13664
- data.add(row, void 0);
12458
+ const comparator2 = makeBoundComparator(sort);
12459
+ const data = new BTreeSet(comparator2);
12460
+ for (const row of this.#getPrimaryIndex().data) {
12461
+ data.add(row);
13665
12462
  }
13666
- const newIndex = { comparator, data, usedBy: /* @__PURE__ */ new Set([usedBy]) };
12463
+ const newIndex = { comparator: comparator2, data, usedBy: /* @__PURE__ */ new Set([usedBy]) };
13667
12464
  this.#indexes.set(key, newIndex);
13668
12465
  return newIndex;
13669
12466
  }
@@ -13688,7 +12485,7 @@ var MemorySource = class {
13688
12485
  }
13689
12486
  const index = this.#getOrCreateIndex(indexSort, from);
13690
12487
  const { data, comparator: compare } = index;
13691
- const comparator = (r1, r2) => compare(r1, r2) * (req.reverse ? -1 : 1);
12488
+ const comparator2 = (r1, r2) => compare(r1, r2) * (req.reverse ? -1 : 1);
13692
12489
  if (this.#overlay) {
13693
12490
  if (callingConnectionNum <= this.#overlay.outputIndex) {
13694
12491
  overlay = this.#overlay;
@@ -13717,11 +12514,11 @@ var MemorySource = class {
13717
12514
  generateRows(data, scanStart, req.reverse),
13718
12515
  req.constraint,
13719
12516
  overlay,
13720
- comparator,
12517
+ comparator2,
13721
12518
  conn.filters?.predicate
13722
12519
  );
13723
12520
  const withConstraint = generateWithConstraint(
13724
- generateWithStart(withOverlay, req.start, comparator),
12521
+ generateWithStart(withOverlay, req.start, comparator2),
13725
12522
  req.constraint
13726
12523
  );
13727
12524
  yield* conn.filters ? generateWithFilter(withConstraint, conn.filters.predicate) : withConstraint;
@@ -13786,7 +12583,7 @@ var MemorySource = class {
13786
12583
  for (const { data: data2 } of this.#indexes.values()) {
13787
12584
  switch (change.type) {
13788
12585
  case "add": {
13789
- const added = data2.add(change.row, void 0);
12586
+ const added = data2.add(change.row);
13790
12587
  assert(added);
13791
12588
  break;
13792
12589
  }
@@ -13798,7 +12595,7 @@ var MemorySource = class {
13798
12595
  case "edit": {
13799
12596
  const removed = data2.delete(change.oldRow);
13800
12597
  assert(removed);
13801
- data2.add(change.row, void 0);
12598
+ data2.add(change.row);
13802
12599
  break;
13803
12600
  }
13804
12601
  default:
@@ -13969,40 +12766,43 @@ function compareBounds(a, b) {
13969
12766
  return compareValues(a, b);
13970
12767
  }
13971
12768
  function* generateRows(data, scanStart, reverse) {
13972
- for (const entry of data[reverse ? "entriesReversed" : "entries"](
13973
- scanStart,
13974
- []
13975
- )) {
13976
- yield entry[0];
13977
- }
12769
+ yield* data[reverse ? "valuesFromReversed" : "valuesFrom"](
12770
+ scanStart
12771
+ );
13978
12772
  }
13979
12773
 
13980
12774
  // ../zql/src/ivm/memory-storage.ts
12775
+ import { compareUTF8 as compareUTF85 } from "compare-utf8";
12776
+ function comparator(a, b) {
12777
+ return compareUTF85(a[0], b[0]);
12778
+ }
13981
12779
  var MemoryStorage = class {
13982
- #data = new BTree();
12780
+ #data = new BTreeSet(comparator);
13983
12781
  set(key, value) {
13984
- this.#data.add(key, value);
12782
+ this.#data.add([key, value]);
13985
12783
  }
13986
12784
  get(key, def) {
13987
- const r = this.#data.get(key);
12785
+ const r = this.#data.get([key, null]);
13988
12786
  if (r !== void 0) {
13989
- return r;
12787
+ return r[1];
13990
12788
  }
13991
12789
  return def;
13992
12790
  }
13993
12791
  del(key) {
13994
- this.#data.delete(key);
12792
+ this.#data.delete([key, null]);
13995
12793
  }
13996
12794
  *scan(options) {
13997
- for (const [key, value] of this.#data.entries(options?.prefix)) {
13998
- if (options && !key.startsWith(options.prefix)) {
12795
+ for (const entry of this.#data.valuesFrom(
12796
+ options && [options.prefix, null]
12797
+ )) {
12798
+ if (options && !entry[0].startsWith(options.prefix)) {
13999
12799
  return;
14000
12800
  }
14001
- yield [key, value];
12801
+ yield entry;
14002
12802
  }
14003
12803
  }
14004
12804
  cloneData() {
14005
- return structuredClone(Object.fromEntries(this.#data.entries()));
12805
+ return structuredClone(Object.fromEntries(this.#data.values()));
14006
12806
  }
14007
12807
  };
14008
12808
 
@@ -14046,7 +12846,7 @@ var ZeroContext = class {
14046
12846
  #commitListeners = /* @__PURE__ */ new Set();
14047
12847
  staticQueryParameters = void 0;
14048
12848
  constructor(tables, addQuery, batchViewUpdates) {
14049
- this.#tables = normalizeTables(tables);
12849
+ this.#tables = tables;
14050
12850
  this.#addQuery = addQuery;
14051
12851
  this.#batchViewUpdates = batchViewUpdates;
14052
12852
  }
@@ -14597,7 +13397,7 @@ function makeMessage(message, context, logLevel) {
14597
13397
  }
14598
13398
 
14599
13399
  // ../zero-client/src/client/version.ts
14600
- var version2 = "0.11.2025011402+73df1d";
13400
+ var version2 = "0.11.2025011801+0c3f2d";
14601
13401
 
14602
13402
  // ../zero-client/src/client/log-options.ts
14603
13403
  var LevelFilterLogSink = class {
@@ -15656,15 +14456,14 @@ var Zero = class {
15656
14456
  enableAnalytics: this.#enableAnalytics
15657
14457
  });
15658
14458
  const logOptions = this.#logOptions;
15659
- const normalizedSchema = normalizeSchema(schema);
15660
14459
  const replicacheMutators = {
15661
- ["_zero_crud"]: makeCRUDMutator(normalizedSchema)
14460
+ ["_zero_crud"]: makeCRUDMutator(schema)
15662
14461
  };
15663
14462
  this.storageKey = storageKey ?? "";
15664
14463
  const replicacheOptions = {
15665
14464
  // The schema stored in IDB is dependent upon both the application schema
15666
14465
  // and the AST schema (i.e. PROTOCOL_VERSION).
15667
- schemaVersion: `${normalizedSchema.version}.${PROTOCOL_VERSION}`,
14466
+ schemaVersion: `${schema.version}.${PROTOCOL_VERSION}`,
15668
14467
  logLevel: logOptions.logLevel,
15669
14468
  logSinks: [logOptions.logSink],
15670
14469
  mutators: replicacheMutators,
@@ -15715,10 +14514,7 @@ var Zero = class {
15715
14514
  });
15716
14515
  this.#onClientStateNotFound = onClientStateNotFoundCallback;
15717
14516
  this.#rep.onClientStateNotFound = onClientStateNotFoundCallback;
15718
- const { mutate, mutateBatch } = makeCRUDMutate(
15719
- normalizedSchema,
15720
- rep.mutate
15721
- );
14517
+ const { mutate, mutateBatch } = makeCRUDMutate(schema, rep.mutate);
15722
14518
  this.mutate = mutate;
15723
14519
  this.mutateBatch = mutateBatch;
15724
14520
  this.#queryManager = new QueryManager(
@@ -15728,7 +14524,7 @@ var Zero = class {
15728
14524
  maxRecentQueries
15729
14525
  );
15730
14526
  this.#zeroContext = new ZeroContext(
15731
- normalizedSchema.tables,
14527
+ schema.tables,
15732
14528
  (ast, gotCallback) => this.#queryManager.add(ast, gotCallback),
15733
14529
  batchViewUpdates
15734
14530
  );
@@ -15739,7 +14535,7 @@ var Zero = class {
15739
14535
  initialValuesInFirstDiff: true
15740
14536
  }
15741
14537
  );
15742
- this.query = this.#registerQueries(normalizedSchema);
14538
+ this.query = this.#registerQueries(schema);
15743
14539
  reportReloadReason(this.#lc);
15744
14540
  this.#metrics = new MetricManager({
15745
14541
  reportIntervalMs: REPORT_INTERVAL_MS,
@@ -15753,7 +14549,7 @@ var Zero = class {
15753
14549
  (poke) => this.#rep.poke(poke),
15754
14550
  () => this.#onPokeError(),
15755
14551
  rep.clientID,
15756
- normalizedSchema,
14552
+ schema,
15757
14553
  this.#lc
15758
14554
  );
15759
14555
  this.#visibilityWatcher = getDocumentVisibilityWatcher(
@@ -16559,8 +15355,8 @@ var Zero = class {
16559
15355
  #registerQueries(schema) {
16560
15356
  const rv = {};
16561
15357
  const context = this.#zeroContext;
16562
- for (const [name, table] of Object.entries(schema.tables)) {
16563
- rv[name] = newQuery(context, table);
15358
+ for (const name of Object.keys(schema.tables)) {
15359
+ rv[name] = newQuery(context, schema, name);
16564
15360
  }
16565
15361
  return rv;
16566
15362
  }
@@ -16628,13 +15424,18 @@ export {
16628
15424
  makeIDBName,
16629
15425
  dropDatabase,
16630
15426
  dropAllDatabases,
16631
- column_exports,
16632
- createTableSchema,
16633
15427
  ANYONE_CAN,
16634
15428
  NOBODY_CAN,
16635
15429
  definePermissions,
15430
+ table,
15431
+ string8 as string,
15432
+ number5 as number,
15433
+ boolean4 as boolean,
15434
+ json,
15435
+ enumeration,
16636
15436
  createSchema,
15437
+ relationships,
16637
15438
  escapeLike,
16638
15439
  Zero
16639
15440
  };
16640
- //# sourceMappingURL=chunk-AII6TS5B.js.map
15441
+ //# sourceMappingURL=chunk-QV5ZN4MA.js.map