@sidekickdb/core 0.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (583) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +16 -0
  3. package/.tshy/esm.json +15 -0
  4. package/LICENSE.md +202 -0
  5. package/NOTICE +27 -0
  6. package/README.md +25 -2
  7. package/__example__/standalone.esm.html +23 -0
  8. package/__example__/standalone.umd.html +21 -0
  9. package/__tests__/src/Reactor.test.ts +480 -0
  10. package/__tests__/src/auth-extra-fields.e2e.test.ts +160 -0
  11. package/__tests__/src/cookieSync.e2e.test.ts +165 -0
  12. package/__tests__/src/data/movies/attrs.json +145 -0
  13. package/__tests__/src/data/movies/triples.json +1507 -0
  14. package/__tests__/src/data/zeneca/attrs.json +251 -0
  15. package/__tests__/src/data/zeneca/triples.json +15854 -0
  16. package/__tests__/src/dataForQueryMemo.test.ts +136 -0
  17. package/__tests__/src/datalog.test.ts +175 -0
  18. package/__tests__/src/devtool.test.ts +48 -0
  19. package/__tests__/src/endpoints.test.ts +228 -0
  20. package/__tests__/src/infiniteQuery.e2e.test.ts +454 -0
  21. package/__tests__/src/instaml.test.ts +1593 -0
  22. package/__tests__/src/instaql.bench.ts +34 -0
  23. package/__tests__/src/instaql.test.ts +1388 -0
  24. package/__tests__/src/instaqlInference.test.ts +243 -0
  25. package/__tests__/src/notifyScope.test.ts +1145 -0
  26. package/__tests__/src/queryValidation.test.ts +1033 -0
  27. package/__tests__/src/schema.test.ts +641 -0
  28. package/__tests__/src/serializeSchema.test.ts +123 -0
  29. package/__tests__/src/simple.e2e.test.ts +10 -0
  30. package/__tests__/src/storageUpload.test.ts +70 -0
  31. package/__tests__/src/store.test.ts +718 -0
  32. package/__tests__/src/transactionValidation.test.ts +450 -0
  33. package/__tests__/src/typeUtils.ts +39 -0
  34. package/__tests__/src/utils/PersistedObject.test.ts +529 -0
  35. package/__tests__/src/utils/dates.test.ts +82 -0
  36. package/__tests__/src/utils/e2e.ts +95 -0
  37. package/__tests__/src/utils/msw.ts +3 -0
  38. package/__tests__/src/utils/object.test.ts +78 -0
  39. package/__tests__/src/utils/weakHash.test.ts +68 -0
  40. package/__tests__/src/utils/weakHashLegacy.test.ts +22 -0
  41. package/__tests__/src/vite.env.d.ts +1 -0
  42. package/dist/commonjs/Connection.d.ts +93 -0
  43. package/dist/commonjs/Connection.d.ts.map +1 -0
  44. package/dist/commonjs/Connection.js +194 -0
  45. package/dist/commonjs/Connection.js.map +1 -0
  46. package/dist/commonjs/InMemoryStorage.d.ts +11 -0
  47. package/dist/commonjs/InMemoryStorage.d.ts.map +1 -0
  48. package/dist/commonjs/InMemoryStorage.js +29 -0
  49. package/dist/commonjs/InMemoryStorage.js.map +1 -0
  50. package/dist/commonjs/IndexedDBStorage.d.ts +18 -0
  51. package/dist/commonjs/IndexedDBStorage.d.ts.map +1 -0
  52. package/dist/commonjs/IndexedDBStorage.js +341 -0
  53. package/dist/commonjs/IndexedDBStorage.js.map +1 -0
  54. package/dist/commonjs/InstantError.d.ts +7 -0
  55. package/dist/commonjs/InstantError.d.ts.map +1 -0
  56. package/dist/commonjs/InstantError.js +28 -0
  57. package/dist/commonjs/InstantError.js.map +1 -0
  58. package/dist/commonjs/Reactor.d.ts +445 -0
  59. package/dist/commonjs/Reactor.d.ts.map +1 -0
  60. package/dist/commonjs/Reactor.js +2471 -0
  61. package/dist/commonjs/Reactor.js.map +1 -0
  62. package/dist/commonjs/StorageAPI.d.ts +40 -0
  63. package/dist/commonjs/StorageAPI.d.ts.map +1 -0
  64. package/dist/commonjs/StorageAPI.js +82 -0
  65. package/dist/commonjs/StorageAPI.js.map +1 -0
  66. package/dist/commonjs/Stream.d.ts +121 -0
  67. package/dist/commonjs/Stream.d.ts.map +1 -0
  68. package/dist/commonjs/Stream.js +819 -0
  69. package/dist/commonjs/Stream.js.map +1 -0
  70. package/dist/commonjs/SyncTable.d.ts +145 -0
  71. package/dist/commonjs/SyncTable.d.ts.map +1 -0
  72. package/dist/commonjs/SyncTable.js +564 -0
  73. package/dist/commonjs/SyncTable.js.map +1 -0
  74. package/dist/commonjs/WindowNetworkListener.d.ts +5 -0
  75. package/dist/commonjs/WindowNetworkListener.d.ts.map +1 -0
  76. package/dist/commonjs/WindowNetworkListener.js +23 -0
  77. package/dist/commonjs/WindowNetworkListener.js.map +1 -0
  78. package/dist/commonjs/__types__/fieldsTypeTest.d.ts +2 -0
  79. package/dist/commonjs/__types__/fieldsTypeTest.d.ts.map +1 -0
  80. package/dist/commonjs/__types__/fieldsTypeTest.js +68 -0
  81. package/dist/commonjs/__types__/fieldsTypeTest.js.map +1 -0
  82. package/dist/commonjs/__types__/typeUtils.d.ts +20 -0
  83. package/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
  84. package/dist/commonjs/__types__/typeUtils.js +5 -0
  85. package/dist/commonjs/__types__/typeUtils.js.map +1 -0
  86. package/dist/commonjs/__types__/useDatesTypeTest.d.ts +2 -0
  87. package/dist/commonjs/__types__/useDatesTypeTest.d.ts.map +1 -0
  88. package/dist/commonjs/__types__/useDatesTypeTest.js +55 -0
  89. package/dist/commonjs/__types__/useDatesTypeTest.js.map +1 -0
  90. package/dist/commonjs/attrTypes.d.ts +26 -0
  91. package/dist/commonjs/attrTypes.d.ts.map +1 -0
  92. package/dist/commonjs/attrTypes.js +3 -0
  93. package/dist/commonjs/attrTypes.js.map +1 -0
  94. package/dist/commonjs/authAPI.d.ts +65 -0
  95. package/dist/commonjs/authAPI.d.ts.map +1 -0
  96. package/dist/commonjs/authAPI.js +114 -0
  97. package/dist/commonjs/authAPI.js.map +1 -0
  98. package/dist/commonjs/clientTypes.d.ts +41 -0
  99. package/dist/commonjs/clientTypes.d.ts.map +1 -0
  100. package/dist/commonjs/clientTypes.js +3 -0
  101. package/dist/commonjs/clientTypes.js.map +1 -0
  102. package/dist/commonjs/coreTypes.d.ts +34 -0
  103. package/dist/commonjs/coreTypes.d.ts.map +1 -0
  104. package/dist/commonjs/coreTypes.js +3 -0
  105. package/dist/commonjs/coreTypes.js.map +1 -0
  106. package/dist/commonjs/createRouteHandler.d.ts +8 -0
  107. package/dist/commonjs/createRouteHandler.d.ts.map +1 -0
  108. package/dist/commonjs/createRouteHandler.js +56 -0
  109. package/dist/commonjs/createRouteHandler.js.map +1 -0
  110. package/dist/commonjs/datalog.d.ts +8 -0
  111. package/dist/commonjs/datalog.d.ts.map +1 -0
  112. package/dist/commonjs/datalog.js +106 -0
  113. package/dist/commonjs/datalog.js.map +1 -0
  114. package/dist/commonjs/devtool.d.ts +4 -0
  115. package/dist/commonjs/devtool.d.ts.map +1 -0
  116. package/dist/commonjs/devtool.js +191 -0
  117. package/dist/commonjs/devtool.js.map +1 -0
  118. package/dist/commonjs/endpoints.d.ts +35 -0
  119. package/dist/commonjs/endpoints.d.ts.map +1 -0
  120. package/dist/commonjs/endpoints.js +80 -0
  121. package/dist/commonjs/endpoints.js.map +1 -0
  122. package/dist/commonjs/framework.d.ts +81 -0
  123. package/dist/commonjs/framework.d.ts.map +1 -0
  124. package/dist/commonjs/framework.js +284 -0
  125. package/dist/commonjs/framework.js.map +1 -0
  126. package/dist/commonjs/helperTypes.d.ts +76 -0
  127. package/dist/commonjs/helperTypes.d.ts.map +1 -0
  128. package/dist/commonjs/helperTypes.js +3 -0
  129. package/dist/commonjs/helperTypes.js.map +1 -0
  130. package/dist/commonjs/index.d.ts +614 -0
  131. package/dist/commonjs/index.d.ts.map +1 -0
  132. package/dist/commonjs/index.js +677 -0
  133. package/dist/commonjs/index.js.map +1 -0
  134. package/dist/commonjs/infiniteQuery.d.ts +26 -0
  135. package/dist/commonjs/infiniteQuery.d.ts.map +1 -0
  136. package/dist/commonjs/infiniteQuery.js +438 -0
  137. package/dist/commonjs/infiniteQuery.js.map +1 -0
  138. package/dist/commonjs/instaml.d.ts +18 -0
  139. package/dist/commonjs/instaml.d.ts.map +1 -0
  140. package/dist/commonjs/instaml.js +584 -0
  141. package/dist/commonjs/instaml.js.map +1 -0
  142. package/dist/commonjs/instaql.d.ts +13 -0
  143. package/dist/commonjs/instaql.d.ts.map +1 -0
  144. package/dist/commonjs/instaql.js +670 -0
  145. package/dist/commonjs/instaql.js.map +1 -0
  146. package/dist/commonjs/instatx.d.ts +128 -0
  147. package/dist/commonjs/instatx.d.ts.map +1 -0
  148. package/dist/commonjs/instatx.js +102 -0
  149. package/dist/commonjs/instatx.js.map +1 -0
  150. package/dist/commonjs/model/instaqlResult.d.ts +8 -0
  151. package/dist/commonjs/model/instaqlResult.d.ts.map +1 -0
  152. package/dist/commonjs/model/instaqlResult.js +28 -0
  153. package/dist/commonjs/model/instaqlResult.js.map +1 -0
  154. package/dist/commonjs/notifyScope.d.ts +32 -0
  155. package/dist/commonjs/notifyScope.d.ts.map +1 -0
  156. package/dist/commonjs/notifyScope.js +306 -0
  157. package/dist/commonjs/notifyScope.js.map +1 -0
  158. package/dist/commonjs/package.json +3 -0
  159. package/dist/commonjs/parseSchemaFromJSON.d.ts +3 -0
  160. package/dist/commonjs/parseSchemaFromJSON.d.ts.map +1 -0
  161. package/dist/commonjs/parseSchemaFromJSON.js +147 -0
  162. package/dist/commonjs/parseSchemaFromJSON.js.map +1 -0
  163. package/dist/commonjs/presence.d.ts +51 -0
  164. package/dist/commonjs/presence.d.ts.map +1 -0
  165. package/dist/commonjs/presence.js +55 -0
  166. package/dist/commonjs/presence.js.map +1 -0
  167. package/dist/commonjs/presenceTypes.d.ts +10 -0
  168. package/dist/commonjs/presenceTypes.d.ts.map +1 -0
  169. package/dist/commonjs/presenceTypes.js +5 -0
  170. package/dist/commonjs/presenceTypes.js.map +1 -0
  171. package/dist/commonjs/queryTypes.d.ts +272 -0
  172. package/dist/commonjs/queryTypes.d.ts.map +1 -0
  173. package/dist/commonjs/queryTypes.js +5 -0
  174. package/dist/commonjs/queryTypes.js.map +1 -0
  175. package/dist/commonjs/queryValidation.d.ts +6 -0
  176. package/dist/commonjs/queryValidation.d.ts.map +1 -0
  177. package/dist/commonjs/queryValidation.js +293 -0
  178. package/dist/commonjs/queryValidation.js.map +1 -0
  179. package/dist/commonjs/reactorTypes.d.ts +30 -0
  180. package/dist/commonjs/reactorTypes.d.ts.map +1 -0
  181. package/dist/commonjs/reactorTypes.js +3 -0
  182. package/dist/commonjs/reactorTypes.js.map +1 -0
  183. package/dist/commonjs/routeHandlerProtocol.d.ts +20 -0
  184. package/dist/commonjs/routeHandlerProtocol.d.ts.map +1 -0
  185. package/dist/commonjs/routeHandlerProtocol.js +3 -0
  186. package/dist/commonjs/routeHandlerProtocol.js.map +1 -0
  187. package/dist/commonjs/rulesTypes.d.ts +86 -0
  188. package/dist/commonjs/rulesTypes.d.ts.map +1 -0
  189. package/dist/commonjs/rulesTypes.js +3 -0
  190. package/dist/commonjs/rulesTypes.js.map +1 -0
  191. package/dist/commonjs/sanityCheckQueries.d.ts +19 -0
  192. package/dist/commonjs/sanityCheckQueries.d.ts.map +1 -0
  193. package/dist/commonjs/sanityCheckQueries.js +156 -0
  194. package/dist/commonjs/sanityCheckQueries.js.map +1 -0
  195. package/dist/commonjs/schema.d.ts +73 -0
  196. package/dist/commonjs/schema.d.ts.map +1 -0
  197. package/dist/commonjs/schema.js +132 -0
  198. package/dist/commonjs/schema.js.map +1 -0
  199. package/dist/commonjs/schemaTypes.d.ts +245 -0
  200. package/dist/commonjs/schemaTypes.d.ts.map +1 -0
  201. package/dist/commonjs/schemaTypes.js +116 -0
  202. package/dist/commonjs/schemaTypes.js.map +1 -0
  203. package/dist/commonjs/store.d.ts +90 -0
  204. package/dist/commonjs/store.d.ts.map +1 -0
  205. package/dist/commonjs/store.js +745 -0
  206. package/dist/commonjs/store.js.map +1 -0
  207. package/dist/commonjs/transactionValidation.d.ts +8 -0
  208. package/dist/commonjs/transactionValidation.d.ts.map +1 -0
  209. package/dist/commonjs/transactionValidation.js +137 -0
  210. package/dist/commonjs/transactionValidation.js.map +1 -0
  211. package/dist/commonjs/utils/Deferred.d.ts +9 -0
  212. package/dist/commonjs/utils/Deferred.d.ts.map +1 -0
  213. package/dist/commonjs/utils/Deferred.js +22 -0
  214. package/dist/commonjs/utils/Deferred.js.map +1 -0
  215. package/dist/commonjs/utils/PersistedObject.d.ts +81 -0
  216. package/dist/commonjs/utils/PersistedObject.d.ts.map +1 -0
  217. package/dist/commonjs/utils/PersistedObject.js +469 -0
  218. package/dist/commonjs/utils/PersistedObject.js.map +1 -0
  219. package/dist/commonjs/utils/dates.d.ts +2 -0
  220. package/dist/commonjs/utils/dates.d.ts.map +1 -0
  221. package/dist/commonjs/utils/dates.js +215 -0
  222. package/dist/commonjs/utils/dates.js.map +1 -0
  223. package/dist/commonjs/utils/error.d.ts +3 -0
  224. package/dist/commonjs/utils/error.d.ts.map +1 -0
  225. package/dist/commonjs/utils/error.js +13 -0
  226. package/dist/commonjs/utils/error.js.map +1 -0
  227. package/dist/commonjs/utils/fetch.d.ts +126 -0
  228. package/dist/commonjs/utils/fetch.d.ts.map +1 -0
  229. package/dist/commonjs/utils/fetch.js +37 -0
  230. package/dist/commonjs/utils/fetch.js.map +1 -0
  231. package/dist/commonjs/utils/flags.d.ts +5 -0
  232. package/dist/commonjs/utils/flags.d.ts.map +1 -0
  233. package/dist/commonjs/utils/flags.js +16 -0
  234. package/dist/commonjs/utils/flags.js.map +1 -0
  235. package/dist/commonjs/utils/id.d.ts +4 -0
  236. package/dist/commonjs/utils/id.d.ts.map +1 -0
  237. package/dist/commonjs/utils/id.js +29 -0
  238. package/dist/commonjs/utils/id.js.map +1 -0
  239. package/dist/commonjs/utils/linkIndex.d.ts +8 -0
  240. package/dist/commonjs/utils/linkIndex.d.ts.map +1 -0
  241. package/dist/commonjs/utils/linkIndex.js +21 -0
  242. package/dist/commonjs/utils/linkIndex.js.map +1 -0
  243. package/dist/commonjs/utils/log.d.ts +7 -0
  244. package/dist/commonjs/utils/log.d.ts.map +1 -0
  245. package/dist/commonjs/utils/log.js +17 -0
  246. package/dist/commonjs/utils/log.js.map +1 -0
  247. package/dist/commonjs/utils/object.d.ts +17 -0
  248. package/dist/commonjs/utils/object.d.ts.map +1 -0
  249. package/dist/commonjs/utils/object.js +157 -0
  250. package/dist/commonjs/utils/object.js.map +1 -0
  251. package/dist/commonjs/utils/pgtime.d.ts +198 -0
  252. package/dist/commonjs/utils/pgtime.d.ts.map +1 -0
  253. package/dist/commonjs/utils/pgtime.js +201 -0
  254. package/dist/commonjs/utils/pgtime.js.map +1 -0
  255. package/dist/commonjs/utils/pick.d.ts +2 -0
  256. package/dist/commonjs/utils/pick.d.ts.map +1 -0
  257. package/dist/commonjs/utils/pick.js +13 -0
  258. package/dist/commonjs/utils/pick.js.map +1 -0
  259. package/dist/commonjs/utils/strings.d.ts +2 -0
  260. package/dist/commonjs/utils/strings.d.ts.map +1 -0
  261. package/dist/commonjs/utils/strings.js +19 -0
  262. package/dist/commonjs/utils/strings.js.map +1 -0
  263. package/dist/commonjs/utils/weakHash.d.ts +16 -0
  264. package/dist/commonjs/utils/weakHash.d.ts.map +1 -0
  265. package/dist/commonjs/utils/weakHash.js +75 -0
  266. package/dist/commonjs/utils/weakHash.js.map +1 -0
  267. package/dist/commonjs/utils/weakHashLegacy.d.ts +8 -0
  268. package/dist/commonjs/utils/weakHashLegacy.d.ts.map +1 -0
  269. package/dist/commonjs/utils/weakHashLegacy.js +76 -0
  270. package/dist/commonjs/utils/weakHashLegacy.js.map +1 -0
  271. package/dist/commonjs/version.d.ts +3 -0
  272. package/dist/commonjs/version.d.ts.map +1 -0
  273. package/dist/commonjs/version.js +5 -0
  274. package/dist/commonjs/version.js.map +1 -0
  275. package/dist/commonjs/warningToggle.d.ts +3 -0
  276. package/dist/commonjs/warningToggle.d.ts.map +1 -0
  277. package/dist/commonjs/warningToggle.js +9 -0
  278. package/dist/commonjs/warningToggle.js.map +1 -0
  279. package/dist/esm/Connection.d.ts +93 -0
  280. package/dist/esm/Connection.d.ts.map +1 -0
  281. package/dist/esm/Connection.js +189 -0
  282. package/dist/esm/Connection.js.map +1 -0
  283. package/dist/esm/InMemoryStorage.d.ts +11 -0
  284. package/dist/esm/InMemoryStorage.d.ts.map +1 -0
  285. package/dist/esm/InMemoryStorage.js +26 -0
  286. package/dist/esm/InMemoryStorage.js.map +1 -0
  287. package/dist/esm/IndexedDBStorage.d.ts +18 -0
  288. package/dist/esm/IndexedDBStorage.d.ts.map +1 -0
  289. package/dist/esm/IndexedDBStorage.js +338 -0
  290. package/dist/esm/IndexedDBStorage.js.map +1 -0
  291. package/dist/esm/InstantError.d.ts +7 -0
  292. package/dist/esm/InstantError.d.ts.map +1 -0
  293. package/dist/esm/InstantError.js +24 -0
  294. package/dist/esm/InstantError.js.map +1 -0
  295. package/dist/esm/Reactor.d.ts +445 -0
  296. package/dist/esm/Reactor.d.ts.map +1 -0
  297. package/dist/esm/Reactor.js +2431 -0
  298. package/dist/esm/Reactor.js.map +1 -0
  299. package/dist/esm/StorageAPI.d.ts +40 -0
  300. package/dist/esm/StorageAPI.d.ts.map +1 -0
  301. package/dist/esm/StorageAPI.js +75 -0
  302. package/dist/esm/StorageAPI.js.map +1 -0
  303. package/dist/esm/Stream.d.ts +121 -0
  304. package/dist/esm/Stream.d.ts.map +1 -0
  305. package/dist/esm/Stream.js +812 -0
  306. package/dist/esm/Stream.js.map +1 -0
  307. package/dist/esm/SyncTable.d.ts +145 -0
  308. package/dist/esm/SyncTable.d.ts.map +1 -0
  309. package/dist/esm/SyncTable.js +524 -0
  310. package/dist/esm/SyncTable.js.map +1 -0
  311. package/dist/esm/WindowNetworkListener.d.ts +5 -0
  312. package/dist/esm/WindowNetworkListener.d.ts.map +1 -0
  313. package/dist/esm/WindowNetworkListener.js +20 -0
  314. package/dist/esm/WindowNetworkListener.js.map +1 -0
  315. package/dist/esm/__types__/fieldsTypeTest.d.ts +2 -0
  316. package/dist/esm/__types__/fieldsTypeTest.d.ts.map +1 -0
  317. package/dist/esm/__types__/fieldsTypeTest.js +66 -0
  318. package/dist/esm/__types__/fieldsTypeTest.js.map +1 -0
  319. package/dist/esm/__types__/typeUtils.d.ts +20 -0
  320. package/dist/esm/__types__/typeUtils.d.ts.map +1 -0
  321. package/dist/esm/__types__/typeUtils.js +4 -0
  322. package/dist/esm/__types__/typeUtils.js.map +1 -0
  323. package/dist/esm/__types__/useDatesTypeTest.d.ts +2 -0
  324. package/dist/esm/__types__/useDatesTypeTest.d.ts.map +1 -0
  325. package/dist/esm/__types__/useDatesTypeTest.js +53 -0
  326. package/dist/esm/__types__/useDatesTypeTest.js.map +1 -0
  327. package/dist/esm/attrTypes.d.ts +26 -0
  328. package/dist/esm/attrTypes.d.ts.map +1 -0
  329. package/dist/esm/attrTypes.js +2 -0
  330. package/dist/esm/attrTypes.js.map +1 -0
  331. package/dist/esm/authAPI.d.ts +65 -0
  332. package/dist/esm/authAPI.d.ts.map +1 -0
  333. package/dist/esm/authAPI.js +104 -0
  334. package/dist/esm/authAPI.js.map +1 -0
  335. package/dist/esm/clientTypes.d.ts +41 -0
  336. package/dist/esm/clientTypes.d.ts.map +1 -0
  337. package/dist/esm/clientTypes.js +2 -0
  338. package/dist/esm/clientTypes.js.map +1 -0
  339. package/dist/esm/coreTypes.d.ts +34 -0
  340. package/dist/esm/coreTypes.d.ts.map +1 -0
  341. package/dist/esm/coreTypes.js +2 -0
  342. package/dist/esm/coreTypes.js.map +1 -0
  343. package/dist/esm/createRouteHandler.d.ts +8 -0
  344. package/dist/esm/createRouteHandler.d.ts.map +1 -0
  345. package/dist/esm/createRouteHandler.js +52 -0
  346. package/dist/esm/createRouteHandler.js.map +1 -0
  347. package/dist/esm/datalog.d.ts +8 -0
  348. package/dist/esm/datalog.d.ts.map +1 -0
  349. package/dist/esm/datalog.js +100 -0
  350. package/dist/esm/datalog.js.map +1 -0
  351. package/dist/esm/devtool.d.ts +4 -0
  352. package/dist/esm/devtool.d.ts.map +1 -0
  353. package/dist/esm/devtool.js +154 -0
  354. package/dist/esm/devtool.js.map +1 -0
  355. package/dist/esm/endpoints.d.ts +35 -0
  356. package/dist/esm/endpoints.d.ts.map +1 -0
  357. package/dist/esm/endpoints.js +73 -0
  358. package/dist/esm/endpoints.js.map +1 -0
  359. package/dist/esm/framework.d.ts +81 -0
  360. package/dist/esm/framework.d.ts.map +1 -0
  361. package/dist/esm/framework.js +244 -0
  362. package/dist/esm/framework.js.map +1 -0
  363. package/dist/esm/helperTypes.d.ts +76 -0
  364. package/dist/esm/helperTypes.d.ts.map +1 -0
  365. package/dist/esm/helperTypes.js +2 -0
  366. package/dist/esm/helperTypes.js.map +1 -0
  367. package/dist/esm/index.d.ts +614 -0
  368. package/dist/esm/index.d.ts.map +1 -0
  369. package/dist/esm/index.js +655 -0
  370. package/dist/esm/index.js.map +1 -0
  371. package/dist/esm/infiniteQuery.d.ts +26 -0
  372. package/dist/esm/infiniteQuery.d.ts.map +1 -0
  373. package/dist/esm/infiniteQuery.js +433 -0
  374. package/dist/esm/infiniteQuery.js.map +1 -0
  375. package/dist/esm/instaml.d.ts +18 -0
  376. package/dist/esm/instaml.d.ts.map +1 -0
  377. package/dist/esm/instaml.js +577 -0
  378. package/dist/esm/instaml.js.map +1 -0
  379. package/dist/esm/instaql.d.ts +13 -0
  380. package/dist/esm/instaql.d.ts.map +1 -0
  381. package/dist/esm/instaql.js +633 -0
  382. package/dist/esm/instaql.js.map +1 -0
  383. package/dist/esm/instatx.d.ts +128 -0
  384. package/dist/esm/instatx.d.ts.map +1 -0
  385. package/dist/esm/instatx.js +94 -0
  386. package/dist/esm/instatx.js.map +1 -0
  387. package/dist/esm/model/instaqlResult.d.ts +8 -0
  388. package/dist/esm/model/instaqlResult.d.ts.map +1 -0
  389. package/dist/esm/model/instaqlResult.js +25 -0
  390. package/dist/esm/model/instaqlResult.js.map +1 -0
  391. package/dist/esm/notifyScope.d.ts +32 -0
  392. package/dist/esm/notifyScope.d.ts.map +1 -0
  393. package/dist/esm/notifyScope.js +300 -0
  394. package/dist/esm/notifyScope.js.map +1 -0
  395. package/dist/esm/package.json +3 -0
  396. package/dist/esm/parseSchemaFromJSON.d.ts +3 -0
  397. package/dist/esm/parseSchemaFromJSON.d.ts.map +1 -0
  398. package/dist/esm/parseSchemaFromJSON.js +143 -0
  399. package/dist/esm/parseSchemaFromJSON.js.map +1 -0
  400. package/dist/esm/presence.d.ts +51 -0
  401. package/dist/esm/presence.d.ts.map +1 -0
  402. package/dist/esm/presence.js +51 -0
  403. package/dist/esm/presence.js.map +1 -0
  404. package/dist/esm/presenceTypes.d.ts +10 -0
  405. package/dist/esm/presenceTypes.d.ts.map +1 -0
  406. package/dist/esm/presenceTypes.js +4 -0
  407. package/dist/esm/presenceTypes.js.map +1 -0
  408. package/dist/esm/queryTypes.d.ts +272 -0
  409. package/dist/esm/queryTypes.d.ts.map +1 -0
  410. package/dist/esm/queryTypes.js +4 -0
  411. package/dist/esm/queryTypes.js.map +1 -0
  412. package/dist/esm/queryValidation.d.ts +6 -0
  413. package/dist/esm/queryValidation.d.ts.map +1 -0
  414. package/dist/esm/queryValidation.js +288 -0
  415. package/dist/esm/queryValidation.js.map +1 -0
  416. package/dist/esm/reactorTypes.d.ts +30 -0
  417. package/dist/esm/reactorTypes.d.ts.map +1 -0
  418. package/dist/esm/reactorTypes.js +2 -0
  419. package/dist/esm/reactorTypes.js.map +1 -0
  420. package/dist/esm/routeHandlerProtocol.d.ts +20 -0
  421. package/dist/esm/routeHandlerProtocol.d.ts.map +1 -0
  422. package/dist/esm/routeHandlerProtocol.js +2 -0
  423. package/dist/esm/routeHandlerProtocol.js.map +1 -0
  424. package/dist/esm/rulesTypes.d.ts +86 -0
  425. package/dist/esm/rulesTypes.d.ts.map +1 -0
  426. package/dist/esm/rulesTypes.js +2 -0
  427. package/dist/esm/rulesTypes.js.map +1 -0
  428. package/dist/esm/sanityCheckQueries.d.ts +19 -0
  429. package/dist/esm/sanityCheckQueries.d.ts.map +1 -0
  430. package/dist/esm/sanityCheckQueries.js +153 -0
  431. package/dist/esm/sanityCheckQueries.js.map +1 -0
  432. package/dist/esm/schema.d.ts +73 -0
  433. package/dist/esm/schema.d.ts.map +1 -0
  434. package/dist/esm/schema.js +129 -0
  435. package/dist/esm/schema.js.map +1 -0
  436. package/dist/esm/schemaTypes.d.ts +245 -0
  437. package/dist/esm/schemaTypes.d.ts.map +1 -0
  438. package/dist/esm/schemaTypes.js +107 -0
  439. package/dist/esm/schemaTypes.js.map +1 -0
  440. package/dist/esm/store.d.ts +90 -0
  441. package/dist/esm/store.d.ts.map +1 -0
  442. package/dist/esm/store.js +723 -0
  443. package/dist/esm/store.js.map +1 -0
  444. package/dist/esm/transactionValidation.d.ts +8 -0
  445. package/dist/esm/transactionValidation.d.ts.map +1 -0
  446. package/dist/esm/transactionValidation.js +131 -0
  447. package/dist/esm/transactionValidation.js.map +1 -0
  448. package/dist/esm/utils/Deferred.d.ts +9 -0
  449. package/dist/esm/utils/Deferred.d.ts.map +1 -0
  450. package/dist/esm/utils/Deferred.js +18 -0
  451. package/dist/esm/utils/Deferred.js.map +1 -0
  452. package/dist/esm/utils/PersistedObject.d.ts +81 -0
  453. package/dist/esm/utils/PersistedObject.d.ts.map +1 -0
  454. package/dist/esm/utils/PersistedObject.js +464 -0
  455. package/dist/esm/utils/PersistedObject.js.map +1 -0
  456. package/dist/esm/utils/dates.d.ts +2 -0
  457. package/dist/esm/utils/dates.d.ts.map +1 -0
  458. package/dist/esm/utils/dates.js +212 -0
  459. package/dist/esm/utils/dates.js.map +1 -0
  460. package/dist/esm/utils/error.d.ts +3 -0
  461. package/dist/esm/utils/error.d.ts.map +1 -0
  462. package/dist/esm/utils/error.js +9 -0
  463. package/dist/esm/utils/error.js.map +1 -0
  464. package/dist/esm/utils/fetch.d.ts +126 -0
  465. package/dist/esm/utils/fetch.d.ts.map +1 -0
  466. package/dist/esm/utils/fetch.js +32 -0
  467. package/dist/esm/utils/fetch.js.map +1 -0
  468. package/dist/esm/utils/flags.d.ts +5 -0
  469. package/dist/esm/utils/flags.d.ts.map +1 -0
  470. package/dist/esm/utils/flags.js +11 -0
  471. package/dist/esm/utils/flags.js.map +1 -0
  472. package/dist/esm/utils/id.d.ts +4 -0
  473. package/dist/esm/utils/id.d.ts.map +1 -0
  474. package/dist/esm/utils/id.js +26 -0
  475. package/dist/esm/utils/id.js.map +1 -0
  476. package/dist/esm/utils/linkIndex.d.ts +8 -0
  477. package/dist/esm/utils/linkIndex.d.ts.map +1 -0
  478. package/dist/esm/utils/linkIndex.js +18 -0
  479. package/dist/esm/utils/linkIndex.js.map +1 -0
  480. package/dist/esm/utils/log.d.ts +7 -0
  481. package/dist/esm/utils/log.d.ts.map +1 -0
  482. package/dist/esm/utils/log.js +14 -0
  483. package/dist/esm/utils/log.js.map +1 -0
  484. package/dist/esm/utils/object.d.ts +17 -0
  485. package/dist/esm/utils/object.d.ts.map +1 -0
  486. package/dist/esm/utils/object.js +144 -0
  487. package/dist/esm/utils/object.js.map +1 -0
  488. package/dist/esm/utils/pgtime.d.ts +198 -0
  489. package/dist/esm/utils/pgtime.d.ts.map +1 -0
  490. package/dist/esm/utils/pgtime.js +198 -0
  491. package/dist/esm/utils/pgtime.js.map +1 -0
  492. package/dist/esm/utils/pick.d.ts +2 -0
  493. package/dist/esm/utils/pick.d.ts.map +1 -0
  494. package/dist/esm/utils/pick.js +10 -0
  495. package/dist/esm/utils/pick.js.map +1 -0
  496. package/dist/esm/utils/strings.d.ts +2 -0
  497. package/dist/esm/utils/strings.d.ts.map +1 -0
  498. package/dist/esm/utils/strings.js +16 -0
  499. package/dist/esm/utils/strings.js.map +1 -0
  500. package/dist/esm/utils/weakHash.d.ts +16 -0
  501. package/dist/esm/utils/weakHash.d.ts.map +1 -0
  502. package/dist/esm/utils/weakHash.js +72 -0
  503. package/dist/esm/utils/weakHash.js.map +1 -0
  504. package/dist/esm/utils/weakHashLegacy.d.ts +8 -0
  505. package/dist/esm/utils/weakHashLegacy.d.ts.map +1 -0
  506. package/dist/esm/utils/weakHashLegacy.js +73 -0
  507. package/dist/esm/utils/weakHashLegacy.js.map +1 -0
  508. package/dist/esm/version.d.ts +3 -0
  509. package/dist/esm/version.d.ts.map +1 -0
  510. package/dist/esm/version.js +3 -0
  511. package/dist/esm/version.js.map +1 -0
  512. package/dist/esm/warningToggle.d.ts +3 -0
  513. package/dist/esm/warningToggle.d.ts.map +1 -0
  514. package/dist/esm/warningToggle.js +5 -0
  515. package/dist/esm/warningToggle.js.map +1 -0
  516. package/dist/standalone/index.js +8740 -0
  517. package/dist/standalone/index.umd.cjs +7 -0
  518. package/package.json +81 -3
  519. package/src/Connection.ts +277 -0
  520. package/src/InMemoryStorage.ts +34 -0
  521. package/src/IndexedDBStorage.ts +387 -0
  522. package/src/InstantError.ts +28 -0
  523. package/src/Reactor.js +2921 -0
  524. package/src/StorageAPI.ts +156 -0
  525. package/src/Stream.ts +1164 -0
  526. package/src/SyncTable.ts +919 -0
  527. package/src/WindowNetworkListener.js +19 -0
  528. package/src/__types__/fieldsTypeTest.ts +113 -0
  529. package/src/__types__/typeUtils.ts +39 -0
  530. package/src/__types__/useDatesTypeTest.ts +69 -0
  531. package/src/attrTypes.ts +29 -0
  532. package/src/authAPI.ts +205 -0
  533. package/src/clientTypes.ts +28 -0
  534. package/src/coreTypes.ts +58 -0
  535. package/src/createRouteHandler.ts +66 -0
  536. package/src/datalog.js +116 -0
  537. package/src/devtool.ts +186 -0
  538. package/src/endpoints.ts +101 -0
  539. package/src/framework.ts +395 -0
  540. package/src/helperTypes.ts +115 -0
  541. package/src/index.ts +1283 -0
  542. package/src/infiniteQuery.ts +602 -0
  543. package/src/instaml.ts +714 -0
  544. package/src/instaql.ts +952 -0
  545. package/src/instatx.ts +265 -0
  546. package/src/model/instaqlResult.js +25 -0
  547. package/src/notifyScope.ts +343 -0
  548. package/src/parseSchemaFromJSON.ts +176 -0
  549. package/src/presence.ts +123 -0
  550. package/src/presenceTypes.ts +19 -0
  551. package/src/queryTypes.ts +721 -0
  552. package/src/queryValidation.ts +535 -0
  553. package/src/reactorTypes.ts +33 -0
  554. package/src/routeHandlerProtocol.ts +24 -0
  555. package/src/rulesTypes.ts +122 -0
  556. package/src/sanityCheckQueries.ts +189 -0
  557. package/src/schema.ts +194 -0
  558. package/src/schemaTypes.ts +642 -0
  559. package/src/store.ts +949 -0
  560. package/src/transactionValidation.ts +204 -0
  561. package/src/utils/Deferred.ts +20 -0
  562. package/src/utils/PersistedObject.ts +589 -0
  563. package/src/utils/dates.ts +258 -0
  564. package/src/utils/error.ts +9 -0
  565. package/src/utils/fetch.ts +129 -0
  566. package/src/utils/flags.ts +14 -0
  567. package/src/utils/id.ts +28 -0
  568. package/src/utils/linkIndex.ts +33 -0
  569. package/src/utils/log.ts +23 -0
  570. package/src/utils/object.js +176 -0
  571. package/src/utils/pgtime.ts +199 -0
  572. package/src/utils/pick.js +9 -0
  573. package/src/utils/strings.ts +19 -0
  574. package/src/utils/weakHash.ts +77 -0
  575. package/src/utils/weakHashLegacy.ts +75 -0
  576. package/src/version.ts +3 -0
  577. package/src/warningToggle.ts +5 -0
  578. package/tsconfig.cjs.dev.json +15 -0
  579. package/tsconfig.dev.json +14 -0
  580. package/tsconfig.json +13 -0
  581. package/tsconfig.test.json +5 -0
  582. package/vite.config.ts +19 -0
  583. package/vitest.config.ts +75 -0
@@ -0,0 +1,1145 @@
1
+ // https://www.npmjs.com/package/fake-indexeddb
2
+ import 'fake-indexeddb/auto';
3
+ import { beforeAll, describe, expect, it, test, vi } from 'vitest';
4
+ import { setTimeout as sleep } from 'timers/promises';
5
+
6
+ import IndexedDBStorage from '../../src/IndexedDBStorage';
7
+ import Reactor from '../../src/Reactor';
8
+ import * as instaml from '../../src/instaml';
9
+ import { tx, lookup } from '../../src/instatx';
10
+ import instaql from '../../src/instaql';
11
+ import { AttrsStoreClass, createStore } from '../../src/store';
12
+ import {
13
+ mutationFootprint,
14
+ queryFootprint,
15
+ footprintsIntersect,
16
+ } from '../../src/notifyScope';
17
+ import zenecaAttrs from './data/zeneca/attrs.json';
18
+ import zenecaTriples from './data/zeneca/triples.json';
19
+ import uuid from '../../src/utils/id';
20
+ import { weakHash } from '../../src';
21
+
22
+ // After a local write, the Reactor re-runs only the queries the write can
23
+ // affect. Most tests here run each scenario twice, with `_scopedNotify` on and
24
+ // off, and check that every subscriber received the identical sequence of
25
+ // payloads both ways, and which queries were recomputed.
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Fixtures
29
+
30
+ /** Deterministic uuids, so two reactors built from one spec share ids. */
31
+ function idFactory(prefix) {
32
+ let n = 0;
33
+ return () => {
34
+ const hex = (n++).toString(16).padStart(12, '0');
35
+ return `${prefix.padEnd(8, '0').slice(0, 8)}-0000-4000-8000-${hex}`;
36
+ };
37
+ }
38
+
39
+ const nextAttrId = idFactory('a0000000');
40
+
41
+ function idAttr(etype) {
42
+ return {
43
+ id: nextAttrId(),
44
+ 'forward-identity': [nextAttrId(), etype, 'id'],
45
+ 'value-type': 'blob',
46
+ cardinality: 'one',
47
+ 'unique?': true,
48
+ 'index?': false,
49
+ 'primary?': true,
50
+ };
51
+ }
52
+
53
+ function blobAttr(etype, label, extra = {}) {
54
+ return {
55
+ id: nextAttrId(),
56
+ 'forward-identity': [nextAttrId(), etype, label],
57
+ 'value-type': 'blob',
58
+ cardinality: 'one',
59
+ 'unique?': false,
60
+ 'index?': false,
61
+ ...extra,
62
+ };
63
+ }
64
+
65
+ function refAttr([fwdEtype, fwdLabel], [revEtype, revLabel], cardinality) {
66
+ return {
67
+ id: nextAttrId(),
68
+ 'forward-identity': [nextAttrId(), fwdEtype, fwdLabel],
69
+ 'reverse-identity': [nextAttrId(), revEtype, revLabel],
70
+ 'value-type': 'ref',
71
+ cardinality,
72
+ 'unique?': false,
73
+ 'index?': false,
74
+ };
75
+ }
76
+
77
+ const ATTRS = [
78
+ idAttr('A'),
79
+ blobAttr('A', 'x'),
80
+ blobAttr('A', 'y'),
81
+ blobAttr('A', 'z', { 'unique?': true, 'index?': true }),
82
+ blobAttr('A', 'meta'),
83
+ idAttr('B'),
84
+ blobAttr('B', 'name'),
85
+ blobAttr('B', 'deletedAt'),
86
+ idAttr('$users'),
87
+ blobAttr('$users', 'email', { 'unique?': true, 'index?': true }),
88
+ refAttr(['A', 'bs'], ['B', 'as'], 'many'),
89
+ refAttr(['A', 'owner'], ['B', 'owned'], 'one'),
90
+ refAttr(['B', 'user'], ['$users', 'bs'], 'one'),
91
+ // An etype whose primary key is not the attribute labelled `id`.
92
+ { ...blobAttr('P', 'pk', { 'unique?': true }), 'primary?': true },
93
+ blobAttr('P', 'id'),
94
+ blobAttr('P', 'v'),
95
+ ];
96
+
97
+ function attrIdOf(etype, label) {
98
+ const attr = ATTRS.find(
99
+ (a) =>
100
+ a['forward-identity'][1] === etype && a['forward-identity'][2] === label,
101
+ );
102
+ if (!attr) throw new Error(`no attr ${etype}.${label}`);
103
+ return attr.id;
104
+ }
105
+
106
+ function entityTriples(etype, id, values = {}) {
107
+ return [
108
+ [id, attrIdOf(etype, 'id'), id, 1],
109
+ ...Object.entries(values).map(([label, v]) => [
110
+ id,
111
+ attrIdOf(etype, label),
112
+ v,
113
+ 1,
114
+ ]),
115
+ ];
116
+ }
117
+
118
+ function linkTriple(etype, label, from, to) {
119
+ return [from, attrIdOf(etype, label), to, 1];
120
+ }
121
+
122
+ const eid = idFactory('e0000000');
123
+ const [A0, A1, A2, B0, B1, B2, U0, U1] = Array.from({ length: 8 }, eid);
124
+
125
+ const TRIPLES = [
126
+ ...entityTriples('A', A0, { x: 0, y: 0, z: 'z0', meta: { k: 0 } }),
127
+ ...entityTriples('A', A1, { x: 1, y: 1, z: 'z1', meta: { k: 1 } }),
128
+ ...entityTriples('A', A2, { x: 2, y: 2, z: 'z2', meta: { k: 2 } }),
129
+ ...entityTriples('B', B0, { name: 'b0' }),
130
+ ...entityTriples('B', B1, { name: 'b1' }),
131
+ ...entityTriples('B', B2, { name: 'b2', deletedAt: 5 }),
132
+ ...entityTriples('$users', U0, { email: 'u0@x' }),
133
+ ...entityTriples('$users', U1, { email: 'u1@x' }),
134
+ linkTriple('A', 'bs', A0, B0),
135
+ linkTriple('A', 'owner', A1, B1),
136
+ linkTriple('B', 'user', B0, U0),
137
+ linkTriple('B', 'user', B1, U1),
138
+ ];
139
+
140
+ const attrsMap = (attrs) => Object.fromEntries(attrs.map((a) => [a.id, a]));
141
+
142
+ // ---------------------------------------------------------------------------
143
+ // A real Reactor, with every delivery and recompute recorded
144
+
145
+ async function waitForLoaded(reactor) {
146
+ await reactor.querySubs.waitForMetaToLoad();
147
+ await reactor.kv.waitForMetaToLoad();
148
+ await reactor.kv.waitForKeyToLoad('pendingMutations');
149
+ await reactor.querySubs.flush();
150
+ await reactor.kv.flush();
151
+ }
152
+
153
+ class Harness {
154
+ reactor;
155
+ /** Every payload delivered to each hash's subscriber. */
156
+ deliveries = new Map();
157
+ notifyOne;
158
+ applyOptimisticUpdates;
159
+
160
+ static async create({ scoped, attrs = ATTRS }) {
161
+ const h = new Harness();
162
+ const reactor = new Reactor({ appId: uuid() });
163
+ reactor._initStorage(IndexedDBStorage);
164
+ reactor._setAttrs(attrs);
165
+ reactor._scopedNotify = scoped;
166
+ h.reactor = reactor;
167
+ await waitForLoaded(reactor);
168
+ h.notifyOne = vi.spyOn(reactor, 'notifyOne');
169
+ h.applyOptimisticUpdates = vi.spyOn(reactor, '_applyOptimisticUpdates');
170
+ return h;
171
+ }
172
+
173
+ /** Subscribes `q`, and delivers it a server result of `triples`. */
174
+ async subscribe(q, triples = TRIPLES, opts?) {
175
+ const delivered: any[] = [];
176
+ this.reactor.subscribeQuery(
177
+ q,
178
+ (data) => delivered.push(structuredClone(data)),
179
+ opts,
180
+ );
181
+ const fullQ =
182
+ opts && 'ruleParams' in opts
183
+ ? { $$ruleParams: opts.ruleParams, ...q }
184
+ : q;
185
+ const hash = weakHash(fullQ);
186
+ this.deliveries.set(hash, delivered);
187
+ this.reactor._handleReceive(0, {
188
+ op: 'add-query-ok',
189
+ q: fullQ,
190
+ 'processed-tx-id': 0,
191
+ result: [
192
+ {
193
+ data: {
194
+ 'datalog-result': { 'join-rows': [triples.map((t) => [...t])] },
195
+ },
196
+ 'child-nodes': [],
197
+ },
198
+ ],
199
+ });
200
+ await this.flush();
201
+ return hash;
202
+ }
203
+
204
+ write(chunks) {
205
+ this.reactor.pushTx(chunks).catch(() => {});
206
+ }
207
+
208
+ /** A local write of raw tx-steps, as `pushOps` receives them. */
209
+ writeSteps(steps) {
210
+ this.reactor.pushOps(steps).catch(() => {});
211
+ }
212
+
213
+ /** Pending mutation event ids, in the order the Reactor applies them. */
214
+ pendingEventIds() {
215
+ return [...this.reactor._pendingMutations().entries()]
216
+ .sort(([ka, a], [kb, b]) =>
217
+ (a.order || 0) === (b.order || 0)
218
+ ? ka < kb
219
+ ? -1
220
+ : ka > kb
221
+ ? 1
222
+ : 0
223
+ : (a.order || 0) - (b.order || 0),
224
+ )
225
+ .map(([k]) => k);
226
+ }
227
+
228
+ /** The server rejects, or the client times out, the `index`th pending mutation. */
229
+ reject(index, status = 'error') {
230
+ const eventId = this.pendingEventIds()[index];
231
+ if (!eventId) return;
232
+ // The write's promise already resolved as `enqueued`, so the reactor
233
+ // logs the failure for want of a listener.
234
+ const error = console.error;
235
+ console.error = () => {};
236
+ try {
237
+ this.reactor._handleMutationError(status, eventId, {
238
+ message: 'rejected in test',
239
+ });
240
+ } finally {
241
+ console.error = error;
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Waits until the reactor is quiet. A notify is delivered through
247
+ * `querySubs.waitForKeyToLoad(hash).then(...)`, which can resolve after
248
+ * a single tick when storage is slow, so wait for the persisted objects to
249
+ * flush and for the notify count to hold still across several ticks.
250
+ */
251
+ async flush() {
252
+ let last = -1;
253
+ let quietTicks = 0;
254
+ for (let i = 0; i < 100 && quietTicks < 3; i++) {
255
+ await this.reactor.querySubs.flush();
256
+ await this.reactor.kv.flush();
257
+ await sleep(0);
258
+ const n = this.notifyOne.mock.calls.length;
259
+ quietTicks = n === last ? quietTicks + 1 : 0;
260
+ last = n;
261
+ }
262
+ }
263
+
264
+ resetCounts() {
265
+ this.notifyOne.mockClear();
266
+ this.applyOptimisticUpdates.mockClear();
267
+ }
268
+
269
+ recomputes(hash) {
270
+ return this.notifyOne.mock.calls.filter(([h]) => h === hash).length;
271
+ }
272
+
273
+ lastDelivered(hash) {
274
+ return this.deliveries.get(hash).at(-1);
275
+ }
276
+
277
+ /** A fresh evaluation of `hash` over its store with every pending mutation applied. */
278
+ truth(hash) {
279
+ const { q, result } = this.reactor.querySubs.currentValue[hash];
280
+ const muts = this.reactor._rewriteMutationsSorted(
281
+ result.attrsStore,
282
+ this.reactor._pendingMutations(),
283
+ );
284
+ const { store, attrsStore } =
285
+ Reactor.prototype._applyOptimisticUpdates.call(
286
+ this.reactor,
287
+ result.store,
288
+ result.attrsStore,
289
+ muts,
290
+ result.processedTxId,
291
+ );
292
+ return structuredClone(
293
+ instaql(
294
+ {
295
+ store,
296
+ attrsStore,
297
+ pageInfo: result.pageInfo,
298
+ aggregate: result.aggregate,
299
+ },
300
+ q,
301
+ ),
302
+ );
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Runs `act` against a scoped and an unscoped reactor with the same queries,
308
+ * and asserts that every subscriber saw the identical payload sequence both
309
+ * ways, ending on the true data.
310
+ */
311
+ async function bothWays(queries, act) {
312
+ const run = async (scoped) => {
313
+ const h = await Harness.create({ scoped });
314
+ const hash = {};
315
+ for (const [name, q] of Object.entries(queries)) {
316
+ hash[name] = await h.subscribe(q);
317
+ }
318
+ h.resetCounts();
319
+ await act(h);
320
+ await h.flush();
321
+ return { h, hash };
322
+ };
323
+ const s = await run(true);
324
+ const u = await run(false);
325
+ for (const name of Object.keys(queries)) {
326
+ expect(
327
+ s.h.deliveries.get(s.hash[name]),
328
+ `${name}: scoped deliveries differ from unscoped`,
329
+ ).toEqual(u.h.deliveries.get(u.hash[name]));
330
+ expect(
331
+ s.h.lastDelivered(s.hash[name]),
332
+ `${name}: scoped data is not the true data`,
333
+ ).toEqual(s.h.truth(s.hash[name]));
334
+ }
335
+ const recomputed = (h) =>
336
+ Object.keys(queries)
337
+ .filter((name) => h.recomputes(s.hash[name]) > 0)
338
+ .sort();
339
+ return {
340
+ scoped: s.h,
341
+ unscoped: u.h,
342
+ hash: s.hash,
343
+ recomputed: recomputed(s.h),
344
+ unscopedRecomputed: recomputed(u.h),
345
+ };
346
+ }
347
+
348
+ // ---------------------------------------------------------------------------
349
+ // The classifier
350
+
351
+ describe('notifyScope footprints', () => {
352
+ const attrs = new AttrsStoreClass(attrsMap(ATTRS), null);
353
+ const serverStore = createStore(
354
+ new AttrsStoreClass(attrsMap(ATTRS), null),
355
+ TRIPLES as any,
356
+ true,
357
+ false,
358
+ );
359
+
360
+ /** The tx-steps the client builds for `chunks`, with A0...U1 in its store. */
361
+ const steps = (chunks): any[] =>
362
+ instaml.transform({ attrsStore: attrs, stores: [serverStore] }, chunks);
363
+ const writeKeys = (chunks) => {
364
+ const fp = mutationFootprint(steps(chunks), attrs);
365
+ return (
366
+ fp &&
367
+ Object.fromEntries(
368
+ [...fp].map(([k, v]) => [
369
+ k,
370
+ v.eids === true ? 'ANY' : [...v.eids].sort(),
371
+ ]),
372
+ )
373
+ );
374
+ };
375
+ const queryFp = (q) => {
376
+ const fp = queryFootprint(q, attrs);
377
+ return (
378
+ fp && {
379
+ keys: [...fp.keys].sort(),
380
+ wild: [...fp.wild].sort(),
381
+ pins: Object.fromEntries(
382
+ [...fp.pins].map(([k, v]) => [k, [...v].sort()]),
383
+ ),
384
+ }
385
+ );
386
+ };
387
+ const intersects = (chunks, q) => {
388
+ const w = mutationFootprint(steps(chunks), attrs);
389
+ const qf = queryFootprint(q, attrs);
390
+ if (!w || !qf) throw new Error('expected both footprints to classify');
391
+ return footprintsIntersect(w, qf);
392
+ };
393
+
394
+ describe('of a write', () => {
395
+ test("an update of an existing entity is its attributes only: the mode:'update' id triple changes nothing", () => {
396
+ expect(steps(tx.A[A0].update({ x: 5 }))[0][4]).toEqual({
397
+ mode: 'update',
398
+ });
399
+ expect(writeKeys(tx.A[A0].update({ x: 5 }))).toEqual({ 'a|A|x': [A0] });
400
+ });
401
+
402
+ test('an update of an entity the client does not hold is an upsert, so a membership change', () => {
403
+ const fresh = eid();
404
+ expect(writeKeys(tx.A[fresh].update({ x: 5 }))).toEqual({
405
+ 'm|A': [fresh],
406
+ 'a|A|id': [fresh],
407
+ 'a|A|x': [fresh],
408
+ });
409
+ });
410
+
411
+ test('a create is a membership change', () => {
412
+ const fresh = eid();
413
+ expect(writeKeys(tx.A[fresh].create({ y: 1 }))).toEqual({
414
+ 'm|A': [fresh],
415
+ 'a|A|id': [fresh],
416
+ 'a|A|y': [fresh],
417
+ });
418
+ });
419
+
420
+ test('a merge is the merged attribute', () => {
421
+ expect(writeKeys(tx.A[A0].merge({ meta: { k: 9 } }))).toMatchObject({
422
+ 'a|A|meta': [A0],
423
+ });
424
+ });
425
+
426
+ test('a link or unlink is the ref attribute under both its names, for any entity', () => {
427
+ const expected = { 'r|A|bs': 'ANY', 'r|B|as': 'ANY' };
428
+ expect(writeKeys(tx.A[A0].link({ bs: B1 }))).toEqual(expected);
429
+ expect(writeKeys(tx.A[A0].unlink({ bs: B0 }))).toEqual(expected);
430
+ // Written from the reverse side: the same pair of names.
431
+ expect(writeKeys(tx.B[B1].link({ as: A2 }))).toEqual(expected);
432
+ });
433
+
434
+ test('a lookup matches any entity', () => {
435
+ const keys = writeKeys(tx.A[lookup('z', 'z1')].update({ x: 3 }));
436
+ expect(keys?.['a|A|x']).toBe('ANY');
437
+ });
438
+
439
+ test('rule-params steps change nothing', () => {
440
+ expect(
441
+ mutationFootprint([['rule-params', A0, 'A', { k: 1 }]], attrs),
442
+ ).toEqual(new Map());
443
+ });
444
+
445
+ test('a write to a non-`id` primary key, or to the attribute labelled `id`, is a membership change', () => {
446
+ const pk = attrIdOf('P', 'pk');
447
+ const idLabelled = attrIdOf('P', 'id');
448
+ const p = eid();
449
+ const keys = (step) => [
450
+ ...(mutationFootprint([step], attrs)?.keys() ?? []),
451
+ ];
452
+ expect(keys(['add-triple', p, pk, p])).toContain('m|P');
453
+ expect(keys(['add-triple', p, idLabelled, p])).toContain('m|P');
454
+ // mode:'update' is skipped only on the primary key itself.
455
+ expect(keys(['add-triple', p, pk, p, { mode: 'update' }])).toEqual([]);
456
+ expect(
457
+ keys(['add-triple', p, idLabelled, p, { mode: 'update' }]),
458
+ ).toContain('m|P');
459
+ });
460
+
461
+ test.each([
462
+ ['delete-entity', () => steps(tx.A[A0].delete())],
463
+ ['add-attr', () => steps(tx.A[A0].update({ brandNew: 1 }))],
464
+ ['update-attr', () => [['update-attr', { id: attrIdOf('A', 'x') }]]],
465
+ ['delete-attr', () => [['delete-attr', attrIdOf('A', 'x')]]],
466
+ ['restore-attr', () => [['restore-attr', attrIdOf('A', 'x')]]],
467
+ [
468
+ 'an attribute id the client does not know',
469
+ () => [['add-triple', A0, uuid(), 1]],
470
+ ],
471
+ ['an unrecognised action', () => [['frobnicate', A0]]],
472
+ ])('%s is unknown', (_name, makeSteps) => {
473
+ expect(mutationFootprint(makeSteps(), attrs)).toBeNull();
474
+ });
475
+
476
+ test('is unknown before the client has attrs', () => {
477
+ expect(
478
+ mutationFootprint(steps(tx.A[A0].update({ x: 1 })), undefined),
479
+ ).toBeNull();
480
+ });
481
+ });
482
+
483
+ describe('of a query', () => {
484
+ test('reads membership, `fields` and id, and no wildcard', () => {
485
+ expect(queryFp({ A: { $: { fields: ['x'] } } })).toEqual({
486
+ keys: ['a|A|id', 'a|A|x', 'm|A'],
487
+ wild: [],
488
+ pins: {},
489
+ });
490
+ });
491
+
492
+ test('reads every blob attribute when it has no `fields`', () => {
493
+ expect(queryFp({ A: {} })).toEqual({
494
+ keys: ['m|A'],
495
+ wild: ['A'],
496
+ pins: {},
497
+ });
498
+ });
499
+
500
+ test('adds a nested label’s ref and the next level, forward and reverse', () => {
501
+ const fwd = queryFp({ A: { $: { fields: ['x'] }, bs: {} } });
502
+ expect(fwd?.keys).toEqual(expect.arrayContaining(['r|A|bs', 'm|B']));
503
+ expect(fwd?.wild).toEqual(['B']);
504
+ expect(queryFp({ B: { as: { $: { fields: ['y'] } } } })?.keys).toEqual(
505
+ expect.arrayContaining(['r|B|as', 'm|A', 'a|A|y']),
506
+ );
507
+ });
508
+
509
+ test('adds filtered attributes, dotted paths, $isNull, $not and and/or clauses', () => {
510
+ const fp = queryFp({
511
+ B: {
512
+ $: {
513
+ fields: ['name'],
514
+ where: {
515
+ deletedAt: { $isNull: true },
516
+ 'user.email': 'u0@x',
517
+ or: [{ name: { $not: 'b0' } }, { and: [{ 'as.y': { $gt: 1 } }] }],
518
+ },
519
+ },
520
+ },
521
+ });
522
+ expect(fp?.keys).toEqual(
523
+ expect.arrayContaining([
524
+ 'a|B|deletedAt',
525
+ 'r|B|user',
526
+ 'm|$users',
527
+ 'a|$users|email',
528
+ 'a|B|name',
529
+ 'r|B|as',
530
+ 'm|A',
531
+ 'a|A|y',
532
+ ]),
533
+ );
534
+ });
535
+
536
+ test('a filter on a ref label reads the ref and the other side’s membership', () => {
537
+ expect(
538
+ queryFp({ A: { $: { fields: ['x'], where: { owner: B1 } } } })?.keys,
539
+ ).toEqual(expect.arrayContaining(['r|A|owner', 'm|B']));
540
+ });
541
+
542
+ test.each([
543
+ ['order', { A: { $: { order: { x: 'asc' } } } }],
544
+ ['limit', { A: { $: { limit: 2 } } }],
545
+ ['first', { A: { $: { first: 2 } } }],
546
+ ['offset', { A: { $: { offset: 1 } } }],
547
+ ['aggregate', { A: { $: { aggregate: 'count' } } }],
548
+ ['$$ruleParams', { $$ruleParams: { k: 1 }, A: {} }],
549
+ [
550
+ 'an unknown where operator',
551
+ { A: { $: { where: { x: { $foo: 1 } } } } },
552
+ ],
553
+ ['an unknown where label', { A: { $: { where: { nope: 1 } } } }],
554
+ ['an unknown nested label', { A: { nope: {} } }],
555
+ ['a nested blob label', { A: { x: {} } }],
556
+ ['a dotted path through a blob', { A: { $: { where: { 'x.y': 1 } } } }],
557
+ ['a non-array or', { A: { $: { where: { or: { x: 1 } } } } }],
558
+ ['non-array fields', { A: { $: { fields: 'x' } } }],
559
+ ])('%s is unknown', (_name, q) => {
560
+ expect(queryFootprint(q, attrs)).toBeNull();
561
+ });
562
+
563
+ test('is unknown before the client has attrs', () => {
564
+ expect(queryFootprint({ A: {} }, undefined)).toBeNull();
565
+ });
566
+
567
+ test('pins a top-level etype filtered by `id` or `id: {$in}`', () => {
568
+ expect(queryFp({ A: { $: { where: { id: A0 } } } })?.pins).toEqual({
569
+ A: [A0],
570
+ });
571
+ expect(
572
+ queryFp({
573
+ A: { $: { where: { id: { $in: [A2, A1] } }, fields: ['x'] }, bs: {} },
574
+ })?.pins,
575
+ ).toEqual({ A: [A1, A2].sort() });
576
+ });
577
+
578
+ test('does not pin an etype read elsewhere in the query, a nested level, or a non-plain id filter', () => {
579
+ expect(
580
+ queryFp({ A: { $: { where: { id: A0 } }, bs: { as: {} } } })?.pins,
581
+ ).toEqual({});
582
+ expect(
583
+ queryFp({ A: { $: { where: { id: A0, 'bs.as.x': 1 } } } })?.pins,
584
+ ).toEqual({});
585
+ expect(
586
+ queryFp({ B: { as: { $: { where: { id: A0 } } } } })?.pins,
587
+ ).toEqual({});
588
+ expect(
589
+ queryFp({ A: { $: { where: { id: { $not: A0 } } } } })?.pins,
590
+ ).toEqual({});
591
+ expect(
592
+ queryFp({ A: { $: { where: { or: [{ id: A0 }] } } } })?.pins,
593
+ ).toEqual({});
594
+ });
595
+ });
596
+
597
+ describe('intersection', () => {
598
+ test('a write to type A misses a query that reads only type B', () => {
599
+ expect(intersects(tx.A[A0].update({ x: 1 }), { B: {} })).toBe(false);
600
+ });
601
+
602
+ test('a write outside `fields` misses; inside, or with no fields, hits', () => {
603
+ const fieldsX = { A: { $: { fields: ['x'] } } };
604
+ expect(intersects(tx.A[A0].update({ y: 1 }), fieldsX)).toBe(false);
605
+ expect(intersects(tx.A[A0].update({ x: 1 }), fieldsX)).toBe(true);
606
+ expect(intersects(tx.A[A0].update({ y: 1 }), { A: {} })).toBe(true);
607
+ });
608
+
609
+ test('a write to a filtered attribute hits even when it is not in `fields`', () => {
610
+ expect(
611
+ intersects(tx.A[A0].update({ y: 1 }), {
612
+ A: { $: { fields: ['x'], where: { y: 1 } } },
613
+ }),
614
+ ).toBe(true);
615
+ });
616
+
617
+ test('a link hits every query reading the link, from either side, and misses plain reads of its types', () => {
618
+ const link = tx.A[A0].link({ bs: B1 });
619
+ expect(intersects(link, { A: { bs: {} } })).toBe(true);
620
+ expect(intersects(link, { B: { as: {} } })).toBe(true);
621
+ expect(intersects(link, { $users: { bs: { as: {} } } })).toBe(true);
622
+ expect(intersects(link, { B: { $: { where: { 'as.x': 1 } } } })).toBe(
623
+ true,
624
+ );
625
+ expect(intersects(link, { A: {} })).toBe(false);
626
+ expect(intersects(link, { B: {} })).toBe(false);
627
+ expect(intersects(link, { A: { owner: {} } })).toBe(false);
628
+ });
629
+
630
+ test('a pinned query misses writes to other entities of its type, and hits its own and every link', () => {
631
+ const pinned = { A: { $: { where: { id: A0 } }, bs: {} } };
632
+ expect(intersects(tx.A[A1].update({ x: 1 }), pinned)).toBe(false);
633
+ expect(intersects(tx.A[eid()].update({ x: 1 }), pinned)).toBe(false);
634
+ expect(intersects(tx.A[A0].update({ x: 1 }), pinned)).toBe(true);
635
+ expect(intersects(tx.A[A1].link({ bs: B1 }), pinned)).toBe(true);
636
+ expect(intersects(tx.A[lookup('z', 'z1')].update({ x: 1 }), pinned)).toBe(
637
+ true,
638
+ );
639
+ expect(intersects(tx.B[B0].update({ name: 'n' }), pinned)).toBe(true);
640
+ });
641
+ });
642
+ });
643
+
644
+ // ---------------------------------------------------------------------------
645
+ // The Reactor
646
+
647
+ describe('scoped notify after a local write', () => {
648
+ test('is on by default', () => {
649
+ expect(new Reactor({ appId: uuid() })._scopedNotify).toBe(true);
650
+ });
651
+
652
+ test('a write to type A does not recompute a query on type B', async () => {
653
+ const r = await bothWays(
654
+ { onA: { A: { $: { fields: ['x'] } } }, onB: { B: {} } },
655
+ (h) => h.write(tx.A[A0].update({ x: 5 })),
656
+ );
657
+ expect(r.recomputed).toEqual(['onA']);
658
+ expect(r.unscopedRecomputed).toEqual(['onA', 'onB']);
659
+ // The skipped query re-applied no pending mutations.
660
+ expect(r.scoped.applyOptimisticUpdates).toHaveBeenCalledTimes(1);
661
+ expect(r.unscoped.applyOptimisticUpdates).toHaveBeenCalledTimes(2);
662
+ expect(r.scoped.lastDelivered(r.hash.onA)).toMatchObject({
663
+ data: { A: expect.arrayContaining([{ id: A0, x: 5 }]) },
664
+ });
665
+ });
666
+
667
+ test('a write outside a query’s fields and filters does not recompute it', async () => {
668
+ const r = await bothWays(
669
+ {
670
+ fieldsX: { A: { $: { fields: ['x'] } } },
671
+ filtersY: { A: { $: { fields: ['x'], where: { y: 9 } } } },
672
+ wildcard: { A: {} },
673
+ },
674
+ (h) => h.write(tx.A[A0].update({ y: 9 })),
675
+ );
676
+ expect(r.recomputed).toEqual(['filtersY', 'wildcard']);
677
+ });
678
+
679
+ test('a link recomputes the queries that read it, on both types and from either side', async () => {
680
+ const r = await bothWays(
681
+ {
682
+ aToBs: { A: { $: { fields: ['x'] }, bs: { $: { fields: ['name'] } } } },
683
+ bToAs: { B: { $: { fields: ['name'] }, as: { $: { fields: ['x'] } } } },
684
+ plainA: { A: { $: { fields: ['x'] } } },
685
+ plainB: { B: { $: { fields: ['name'] } } },
686
+ owner: { A: { owner: {} } },
687
+ },
688
+ (h) => h.write(tx.A[A0].link({ bs: B1 })),
689
+ );
690
+ // instaql reads a link only through its ref attribute, so plain reads of
691
+ // A and B cannot see it.
692
+ expect(r.recomputed).toEqual(['aToBs', 'bToAs']);
693
+ });
694
+
695
+ test('an unlink, and a has-one relink that implicitly drops the old value', async () => {
696
+ const r = await bothWays(
697
+ {
698
+ aToBs: { A: { bs: {} } },
699
+ owned: { B: { owned: {} } },
700
+ plainB: { B: {} },
701
+ },
702
+ async (h) => {
703
+ h.write(tx.A[A0].unlink({ bs: B0 }));
704
+ await h.flush();
705
+ h.write(tx.A[A1].link({ owner: B2 }));
706
+ },
707
+ );
708
+ expect(r.recomputed).toEqual(['aToBs', 'owned']);
709
+ });
710
+
711
+ test('delete-entity recomputes every query', async () => {
712
+ const r = await bothWays(
713
+ {
714
+ onA: { A: { $: { fields: ['x'] } } },
715
+ onB: { B: {} },
716
+ linked: { B: { as: {} } },
717
+ },
718
+ (h) => h.write(tx.A[A0].delete()),
719
+ );
720
+ expect(r.recomputed).toEqual(['linked', 'onA', 'onB']);
721
+ });
722
+
723
+ test('creating an entity recomputes every unpinned query on its type, whatever its fields', async () => {
724
+ const fresh = eid();
725
+ const r = await bothWays(
726
+ {
727
+ fieldsY: { A: { $: { fields: ['y'] } } },
728
+ onB: { B: {} },
729
+ pinned: { A: { $: { where: { id: A0 } } } },
730
+ },
731
+ (h) => h.write(tx.A[fresh].update({ x: 1 })),
732
+ );
733
+ expect(r.recomputed).toEqual(['fieldsY']);
734
+ });
735
+
736
+ test('a pinned query recomputes for its own entity and skips the others', async () => {
737
+ const r = await bothWays(
738
+ {
739
+ pinA0: { A: { $: { where: { id: A0 } } } },
740
+ pinA1: { A: { $: { where: { id: { $in: [A1] } } } } },
741
+ },
742
+ (h) => h.write(tx.A[A0].update({ x: 7 })),
743
+ );
744
+ expect(r.recomputed).toEqual(['pinA0']);
745
+ });
746
+
747
+ test('a pinned query recomputes for a link written from the other side', async () => {
748
+ // `B.user` is forward on B, so the step's eid is B2 and U0 is only its
749
+ // value: a pin must never discount a ref step.
750
+ const r = await bothWays(
751
+ {
752
+ pinU0: {
753
+ $users: { $: { where: { id: U0 } }, bs: { $: { fields: ['name'] } } },
754
+ },
755
+ },
756
+ (h) => h.write(tx.B[B2].link({ user: U0 })),
757
+ );
758
+ expect(r.recomputed).toEqual(['pinU0']);
759
+ expect(r.scoped.lastDelivered(r.hash.pinU0)).toMatchObject({
760
+ data: {
761
+ $users: [
762
+ { id: U0, bs: expect.arrayContaining([{ id: B2, name: 'b2' }]) },
763
+ ],
764
+ },
765
+ });
766
+ });
767
+
768
+ test('a dotted filter recomputes when the far attribute changes', async () => {
769
+ const r = await bothWays(
770
+ {
771
+ byEmail: {
772
+ B: { $: { fields: ['name'], where: { 'user.email': 'new@x' } } },
773
+ },
774
+ bName: { B: { $: { fields: ['name'] } } },
775
+ },
776
+ (h) => h.write(tx.$users[U1].update({ email: 'new@x' })),
777
+ );
778
+ expect(r.recomputed).toEqual(['byEmail']);
779
+ expect(r.scoped.lastDelivered(r.hash.byEmail)).toEqual({
780
+ data: { B: [{ id: B1, name: 'b1' }] },
781
+ });
782
+ });
783
+
784
+ test('a ruleParams query recomputes on any write', async () => {
785
+ const run = async (scoped) => {
786
+ const h = await Harness.create({ scoped });
787
+ const rp = await h.subscribe({ A: { $: { fields: ['x'] } } }, TRIPLES, {
788
+ ruleParams: { k: 1 },
789
+ });
790
+ const onA = await h.subscribe({ A: { $: { fields: ['x'] } } });
791
+ h.resetCounts();
792
+ h.write(tx.B[B0].update({ name: 'n' }));
793
+ await h.flush();
794
+ return { rp: h.recomputes(rp), onA: h.recomputes(onA) };
795
+ };
796
+ expect(await run(true)).toEqual({ rp: 1, onA: 0 });
797
+ expect(await run(false)).toEqual({ rp: 1, onA: 1 });
798
+ });
799
+
800
+ test.each([
801
+ [
802
+ 'a new attribute (add-attr)',
803
+ (h) => h.write(tx.B[B0].update({ brandNew: 1 })),
804
+ ],
805
+ [
806
+ 'update-attr',
807
+ (h) => h.writeSteps([['update-attr', { id: attrIdOf('B', 'name') }]]),
808
+ ],
809
+ [
810
+ 'restore-attr',
811
+ (h) => h.writeSteps([['restore-attr', attrIdOf('B', 'name')]]),
812
+ ],
813
+ [
814
+ 'an attribute id the client does not know',
815
+ (h) => h.writeSteps([['add-triple', B0, uuid(), 1]]),
816
+ ],
817
+ ])('%s recomputes every query', async (_name, act) => {
818
+ const r = await bothWays(
819
+ {
820
+ onA: { A: { $: { fields: ['x'] } } },
821
+ onB: { B: { $: { fields: ['name'] } } },
822
+ },
823
+ act,
824
+ );
825
+ expect(r.recomputed).toEqual(['onA', 'onB']);
826
+ });
827
+
828
+ test('a mutation whose attribute id the client rewrites recomputes every query, and shows the write', async () => {
829
+ const xAttr = ATTRS.find((a) => a.id === attrIdOf('A', 'x'));
830
+ const localId = uuid();
831
+ const r = await bothWays(
832
+ { onA: { A: { $: { fields: ['x'] } } }, onB: { B: {} } },
833
+ (h) =>
834
+ // A locally created attr the server already has under another id.
835
+ h.writeSteps([
836
+ ['add-attr', { ...xAttr, id: localId }],
837
+ ['add-triple', A0, localId, 42],
838
+ ]),
839
+ );
840
+ expect(r.recomputed).toEqual(['onA', 'onB']);
841
+ expect(r.scoped.lastDelivered(r.hash.onA)).toMatchObject({
842
+ data: { A: expect.arrayContaining([{ id: A0, x: 42 }]) },
843
+ });
844
+ });
845
+
846
+ test('the deep-compare still gates callbacks', async () => {
847
+ const r = await bothWays(
848
+ { onA: { A: { $: { fields: ['x'] } } }, onB: { B: {} } },
849
+ // The value it already has.
850
+ (h) => h.write(tx.A[A0].update({ x: 0 })),
851
+ );
852
+ expect(r.recomputed).toEqual(['onA']);
853
+ // Only the first delivery, from subscribing.
854
+ expect(r.scoped.deliveries.get(r.hash.onA)).toHaveLength(1);
855
+ expect(r.scoped.deliveries.get(r.hash.onB)).toHaveLength(1);
856
+ });
857
+
858
+ test.each(['error', 'timeout'])(
859
+ 'a rejected write (%s) recomputes what it touched and rolls back',
860
+ async (status) => {
861
+ const r = await bothWays(
862
+ { onA: { A: { $: { fields: ['x'] } } }, onB: { B: {} } },
863
+ async (h) => {
864
+ h.write(tx.A[A0].update({ x: 5 }));
865
+ await h.flush();
866
+ h.resetCounts();
867
+ h.reject(0, status);
868
+ },
869
+ );
870
+ expect(r.recomputed).toEqual(['onA']);
871
+ const xs = r.scoped.deliveries
872
+ .get(r.hash.onA)
873
+ .map((d) => d.data.A.find((a) => a.id === A0).x);
874
+ expect(xs).toEqual([0, 5, 0]);
875
+ },
876
+ );
877
+
878
+ test('rejecting a write also recomputes what the later pending writes touch', async () => {
879
+ const r = await bothWays(
880
+ {
881
+ fieldsY: { A: { $: { fields: ['y'] } } },
882
+ pinnedA1: { A: { $: { where: { id: A1 }, fields: ['y'] } } },
883
+ onB: { B: {} },
884
+ },
885
+ async (h) => {
886
+ h.write(tx.A[A1].update({ z: 'k' }));
887
+ // Resolves its lookup against the write above.
888
+ h.write(tx.A[lookup('z', 'k')].update({ y: 3 }));
889
+ await h.flush();
890
+ h.resetCounts();
891
+ h.reject(0);
892
+ },
893
+ );
894
+ expect(r.recomputed).toEqual(['fieldsY', 'pinnedA1']);
895
+ });
896
+
897
+ test('a write that fails to build recomputes nothing already delivered', async () => {
898
+ const r = await bothWays({ onA: { A: {} } }, (h) => {
899
+ h.reactor.pushOps([], new Error('bad tx')).catch(() => {});
900
+ });
901
+ expect(r.recomputed).toEqual([]);
902
+ });
903
+
904
+ test('several writes in one tick recompute the union of what they touch', async () => {
905
+ const r = await bothWays(
906
+ {
907
+ fieldsX: { A: { $: { fields: ['x'] } } },
908
+ fieldsY: { A: { $: { fields: ['y'] } } },
909
+ onB: { B: { $: { fields: ['name'] } } },
910
+ },
911
+ (h) => {
912
+ h.write(tx.A[A0].update({ x: 1 }));
913
+ h.write(tx.B[B0].update({ name: 'n' }));
914
+ h.write(tx.A[A1].update({ x: 9 }));
915
+ },
916
+ );
917
+ expect(r.recomputed).toEqual(['fieldsX', 'onB']);
918
+ });
919
+
920
+ test('a query subscribed after writes computes with every pending write, and is then scoped', async () => {
921
+ for (const scoped of [true, false]) {
922
+ const h = await Harness.create({ scoped });
923
+ await h.subscribe({ B: {} });
924
+ h.write(tx.A[A0].update({ x: 11 }));
925
+ await h.flush();
926
+ const late = await h.subscribe({ A: { $: { fields: ['x'] } } });
927
+ expect(h.lastDelivered(late)).toEqual(h.truth(late));
928
+ expect(h.lastDelivered(late)).toMatchObject({
929
+ data: { A: expect.arrayContaining([{ id: A0, x: 11 }]) },
930
+ });
931
+ h.resetCounts();
932
+ h.write(tx.B[B0].update({ name: 'n' }));
933
+ await h.flush();
934
+ expect(h.recomputes(late) > 0).toBe(!scoped);
935
+ expect(h.lastDelivered(late)).toEqual(h.truth(late));
936
+ }
937
+ });
938
+
939
+ test('a query cleared by notifyQueryError is re-delivered by the next write', async () => {
940
+ const r = await bothWays({ onA: { A: { $: { fields: ['x'] } } } }, (h) => {
941
+ h.reactor.notifyQueryError(
942
+ weakHash({ A: { $: { fields: ['x'] } } }),
943
+ 'boom',
944
+ );
945
+ h.write(tx.B[B0].update({ name: 'n' }));
946
+ });
947
+ expect(r.recomputed).toEqual(['onA']);
948
+ const d = r.scoped.deliveries.get(r.hash.onA);
949
+ expect(d).toHaveLength(3);
950
+ expect(d[1]).toEqual({ error: 'boom' });
951
+ expect(d[2]).toEqual(d[0]);
952
+ });
953
+
954
+ test('notifyAll is unchanged: it recomputes every query', async () => {
955
+ const r = await bothWays({ onA: { A: {} }, onB: { B: {} } }, (h) =>
956
+ h.reactor.notifyAll(),
957
+ );
958
+ expect(r.recomputed).toEqual(['onA', 'onB']);
959
+ });
960
+
961
+ test('caches a query footprint while its form and the attrs are unchanged, and drops it on cleanup', async () => {
962
+ const h = await Harness.create({ scoped: true });
963
+ const q = { A: { $: { fields: ['x'] } } };
964
+ const hash = await h.subscribe(q);
965
+ h.write(tx.B[B0].update({ name: 'n' }));
966
+ const first = h.reactor._queryFootprints.get(hash);
967
+ expect(first.fp).not.toBeNull();
968
+ h.write(tx.B[B0].update({ name: 'm' }));
969
+ expect(h.reactor._queryFootprints.get(hash)).toBe(first);
970
+
971
+ h.reactor._setAttrs(ATTRS);
972
+ h.write(tx.B[B0].update({ name: 'o' }));
973
+ const second = h.reactor._queryFootprints.get(hash);
974
+ expect(second).not.toBe(first);
975
+ expect(second.attrs).toBe(h.reactor.attrs);
976
+
977
+ h.reactor.queryCbs[hash] = [];
978
+ h.reactor._cleanupQuery(q, hash);
979
+ expect(h.reactor._queryFootprints.has(hash)).toBe(false);
980
+ await h.flush();
981
+ });
982
+
983
+ test('zeneca: a write to users skips a bookshelves query', async () => {
984
+ const joeId = 'ce942051-2d74-404a-9c7d-4aa3f2d54ae4';
985
+ const run = async (scoped) => {
986
+ const h = await Harness.create({ scoped, attrs: zenecaAttrs });
987
+ const users = await h.subscribe({ users: {} }, zenecaTriples);
988
+ const shelves = await h.subscribe({ bookshelves: {} }, zenecaTriples);
989
+ h.resetCounts();
990
+ h.write(tx.users[joeId].update({ handle: 'joe2' }));
991
+ await h.flush();
992
+ expect(
993
+ h.lastDelivered(users).data.users.find((u) => u.id === joeId).handle,
994
+ ).toBe('joe2');
995
+ return { users: h.recomputes(users), shelves: h.recomputes(shelves) };
996
+ };
997
+ expect(await run(true)).toEqual({ users: 1, shelves: 0 });
998
+ expect(await run(false)).toEqual({ users: 1, shelves: 1 });
999
+ });
1000
+ });
1001
+
1002
+ // ---------------------------------------------------------------------------
1003
+ // Seeded fuzz
1004
+
1005
+ function mulberry32(seed) {
1006
+ let a = seed;
1007
+ return () => {
1008
+ a |= 0;
1009
+ a = (a + 0x6d2b79f5) | 0;
1010
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
1011
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
1012
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
1013
+ };
1014
+ }
1015
+
1016
+ describe('scoped notify, seeded fuzz', () => {
1017
+ const QUERIES = {
1018
+ wildA: { A: {} },
1019
+ fieldsX: { A: { $: { fields: ['x'] } } },
1020
+ liveB: {
1021
+ B: { $: { where: { deletedAt: { $isNull: true } }, fields: ['name'] } },
1022
+ },
1023
+ nested: { A: { $: { fields: ['y'] }, bs: { $: { fields: ['name'] } } } },
1024
+ reverse: { B: { as: {} } },
1025
+ pinned: {
1026
+ A: { $: { where: { id: A0 } }, owner: { $: { fields: ['name'] } } },
1027
+ },
1028
+ pinnedIn: {
1029
+ A: { $: { where: { id: { $in: [A1, A2] } }, fields: ['meta'] } },
1030
+ },
1031
+ // Pinned on the value side of `B.user`, so B-side link writes reach it
1032
+ // with a B eid.
1033
+ pinnedUser: {
1034
+ $users: { $: { where: { id: U0 } }, bs: { $: { fields: ['name'] } } },
1035
+ },
1036
+ dotted: { B: { $: { where: { 'user.email': 'u1@x' }, fields: ['name'] } } },
1037
+ notName: {
1038
+ B: { $: { where: { name: { $not: 'b0' } }, fields: ['deletedAt'] } },
1039
+ },
1040
+ users: { $users: { bs: { $: { fields: ['name'] } } } },
1041
+ byLookupAttr: { A: { $: { where: { z: 'k' }, fields: ['y'] } } },
1042
+ };
1043
+
1044
+ it('matches unscoped notify and the true data after every step of 200 random writes and rejections', async () => {
1045
+ const run = async (scoped) => {
1046
+ const rand = mulberry32(42);
1047
+ const pick = (xs) => xs[Math.floor(rand() * xs.length)];
1048
+ const ids = idFactory('f0000000');
1049
+ const as = [A0, A1, A2];
1050
+ const bs = [B0, B1, B2];
1051
+ const us = [U0, U1];
1052
+ const h = await Harness.create({ scoped });
1053
+ // Each query's store holds a random subset of the server's entities,
1054
+ // always including the ones it pins.
1055
+ const PINNED = { pinned: [A0], pinnedIn: [A1, A2], pinnedUser: [U0] };
1056
+ const hash = {};
1057
+ for (const [name, q] of Object.entries(QUERIES)) {
1058
+ const keep = new Set(
1059
+ [...as, ...bs, ...us].filter(
1060
+ (e) => rand() < 0.8 || PINNED[name]?.includes(e),
1061
+ ),
1062
+ );
1063
+ hash[name] = await h.subscribe(
1064
+ q,
1065
+ TRIPLES.filter(
1066
+ ([e, , v]) =>
1067
+ keep.has(e) &&
1068
+ (typeof v !== 'string' ||
1069
+ !v.startsWith('e0000000') ||
1070
+ keep.has(v)),
1071
+ ),
1072
+ );
1073
+ }
1074
+ const snapshots: number[][] = [];
1075
+ let recomputes = 0;
1076
+ for (let step = 0; step < 200; step++) {
1077
+ h.resetCounts();
1078
+ const r = rand();
1079
+ const n = () => Math.floor(rand() * 3);
1080
+ if (r < 0.15) h.write(tx.A[pick(as)].update({ x: n() }));
1081
+ else if (r < 0.25) h.write(tx.A[pick(as)].update({ y: n() }));
1082
+ else if (r < 0.3) h.write(tx.A[pick(as)].merge({ meta: { k: n() } }));
1083
+ else if (r < 0.4)
1084
+ h.write(tx.B[pick(bs)].update({ name: pick(['b0', 'b1', 'n']) }));
1085
+ else if (r < 0.45)
1086
+ h.write(tx.B[pick(bs)].update({ deletedAt: pick([null, 7]) }));
1087
+ else if (r < 0.5)
1088
+ h.write(
1089
+ tx.$users[pick(us)].update({
1090
+ email: pick(['u0@x', 'u1@x', 'v@x']),
1091
+ }),
1092
+ );
1093
+ else if (r < 0.55) {
1094
+ const a = ids();
1095
+ as.push(a);
1096
+ h.write(tx.A[a].update({ x: 1, y: 1 }).link({ bs: pick(bs) }));
1097
+ } else if (r < 0.58) {
1098
+ const b = ids();
1099
+ bs.push(b);
1100
+ h.write(tx.B[b].update({ name: 'new' }).link({ user: pick(us) }));
1101
+ } else if (r < 0.66) h.write(tx.A[pick(as)].link({ bs: pick(bs) }));
1102
+ else if (r < 0.7) h.write(tx.A[pick(as)].unlink({ bs: pick(bs) }));
1103
+ else if (r < 0.74) h.write(tx.A[pick(as)].link({ owner: pick(bs) }));
1104
+ else if (r < 0.77) h.write(tx.B[pick(bs)].link({ user: pick(us) }));
1105
+ else if (r < 0.8)
1106
+ h.write(tx.A[pick(as)].update({ z: pick(['k', 'z1']) }));
1107
+ else if (r < 0.83) h.write(tx.A[lookup('z', 'k')].update({ y: n() }));
1108
+ else if (r < 0.85)
1109
+ h.write(tx[pick(['A', 'B'])][pick([...as, ...bs])].delete());
1110
+ else {
1111
+ const pending = h.pendingEventIds().length;
1112
+ if (pending) {
1113
+ h.reject(Math.floor(rand() * pending), pick(['error', 'timeout']));
1114
+ }
1115
+ }
1116
+ await h.flush();
1117
+ if (scoped) {
1118
+ for (const name of Object.keys(QUERIES)) {
1119
+ expect(
1120
+ h.lastDelivered(hash[name]),
1121
+ `step ${step}, ${name}`,
1122
+ ).toEqual(h.truth(hash[name]));
1123
+ }
1124
+ }
1125
+ snapshots.push(
1126
+ Object.keys(QUERIES).map(
1127
+ (name) => h.deliveries.get(hash[name]).length,
1128
+ ),
1129
+ );
1130
+ recomputes += h.notifyOne.mock.calls.length;
1131
+ }
1132
+ return { h, hash, snapshots, recomputes };
1133
+ };
1134
+
1135
+ const s = await run(true);
1136
+ const u = await run(false);
1137
+ for (const name of Object.keys(QUERIES)) {
1138
+ expect(s.h.deliveries.get(s.hash[name]), name).toEqual(
1139
+ u.h.deliveries.get(u.hash[name]),
1140
+ );
1141
+ }
1142
+ expect(s.snapshots).toEqual(u.snapshots);
1143
+ expect(s.recomputes).toBeLessThan(u.recomputes);
1144
+ }, 60_000);
1145
+ });