@sidekickdb/core 0.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
package/src/Reactor.js ADDED
@@ -0,0 +1,2921 @@
1
+ // @ts-check
2
+ import weakHash from './utils/weakHash.ts';
3
+ import weakHashLegacy from './utils/weakHashLegacy.ts';
4
+ import instaql from './instaql.ts';
5
+ import * as instaml from './instaml.ts';
6
+ import * as s from './store.ts';
7
+ import uuid from './utils/id.ts';
8
+ import IndexedDBStorage from './IndexedDBStorage.ts';
9
+ import WindowNetworkListener from './WindowNetworkListener.js';
10
+ import * as authAPI from './authAPI.ts';
11
+ import * as StorageApi from './StorageAPI.ts';
12
+ import * as flags from './utils/flags.ts';
13
+ import { buildPresenceSlice, hasPresenceResponseChanged } from './presence.ts';
14
+ import { Deferred } from './utils/Deferred.ts';
15
+ import { PersistedObject, StoreInterface } from './utils/PersistedObject.ts';
16
+
17
+ import { extractTriples } from './model/instaqlResult.js';
18
+ import {
19
+ areObjectsDeepEqual,
20
+ assocInMutative,
21
+ dissocInMutative,
22
+ insertInMutative,
23
+ } from './utils/object.js';
24
+ import { createLinkIndex } from './utils/linkIndex.ts';
25
+ import version from './version.ts';
26
+ import { create } from 'mutative';
27
+ import createLogger from './utils/log.ts';
28
+ import { validateQuery } from './queryValidation.ts';
29
+ import { validateTransactions } from './transactionValidation.ts';
30
+ import {
31
+ mutationFootprint,
32
+ queryFootprint,
33
+ footprintsIntersect,
34
+ } from './notifyScope.ts';
35
+ import { InstantError } from './InstantError.ts';
36
+ import { InstantAPIError } from './utils/fetch.ts';
37
+ import { validate as validateUUID } from 'uuid';
38
+ import { WSConnection, SSEConnection } from './Connection.ts';
39
+ import { SyncTable } from './SyncTable.ts';
40
+ import { InstantStream } from './Stream.ts';
41
+
42
+ /** @typedef {import('./utils/log.ts').Logger} Logger */
43
+ /** @typedef {import('./Connection.ts').Connection} Connection */
44
+ /** @typedef {import('./Connection.ts').TransportType} TransportType */
45
+ /** @typedef {import('./Connection.ts').EventSourceConstructor} EventSourceConstructor */
46
+ /** @typedef {import('./reactorTypes.ts').QuerySub} QuerySub */
47
+ /** @typedef {import('./reactorTypes.ts').QuerySubInStorage} QuerySubInStorage */
48
+ /** @typedef {import('./clientTypes.ts').User} User */
49
+ /** @typedef {import('./clientTypes.ts').AuthState} AuthState */
50
+ /** @typedef {import('./framework.ts').FrameworkClient} FrameworkClient */
51
+
52
+ export const STATUS = {
53
+ CONNECTING: 'connecting',
54
+ OPENED: 'opened',
55
+ AUTHENTICATED: 'authenticated',
56
+ CLOSED: 'closed',
57
+ ERRORED: 'errored',
58
+ };
59
+
60
+ const QUERY_ONCE_TIMEOUT = 30_000;
61
+ const PENDING_TX_CLEANUP_TIMEOUT = 30_000;
62
+ const PENDING_MUTATION_CLEANUP_THRESHOLD = 200;
63
+ const ONE_MIN_MS = 1_000 * 60;
64
+ const ONE_DAY_MS = ONE_MIN_MS * 60 * 24;
65
+
66
+ export const COOKIE_SYNC_LAST_UPDATED_KEY = 'lastSyncedUserCookie';
67
+
68
+ // Param that the backend adds if this is an oauth redirect
69
+ const OAUTH_REDIRECT_PARAM = '_instant_oauth_redirect';
70
+ const OAUTH_EXTRA_FIELDS_ID_PARAM = '_instant_extra_fields_id';
71
+
72
+ const oauthExtraFieldsKey = 'oauthExtraFields';
73
+
74
+ const currentUserKey = `currentUser`;
75
+
76
+ /**
77
+ * @param {Object} config
78
+ * @param {TransportType} config.transportType
79
+ * @param {string} config.appId
80
+ * @param {string} config.apiURI
81
+ * @param {string} config.wsURI
82
+ * @param {EventSourceConstructor} config.EventSourceImpl
83
+ * @returns {WSConnection | SSEConnection}
84
+ */
85
+ function createTransport({
86
+ transportType,
87
+ appId,
88
+ apiURI,
89
+ wsURI,
90
+ EventSourceImpl,
91
+ }) {
92
+ if (!EventSourceImpl) {
93
+ return new WSConnection(`${wsURI}?app_id=${appId}`);
94
+ }
95
+ switch (transportType) {
96
+ case 'ws':
97
+ return new WSConnection(`${wsURI}?app_id=${appId}`);
98
+ case 'sse':
99
+ return new SSEConnection(
100
+ EventSourceImpl,
101
+ `${apiURI}/runtime/sse?app_id=${appId}`,
102
+ );
103
+ default:
104
+ throw new Error('Unknown transport type ' + transportType);
105
+ }
106
+ }
107
+
108
+ function isClient() {
109
+ const hasWindow = typeof window !== 'undefined';
110
+ // this checks if we are running in a chrome extension
111
+ // @ts-expect-error
112
+ const isChrome = typeof chrome !== 'undefined';
113
+
114
+ return hasWindow || isChrome;
115
+ }
116
+
117
+ const ignoreLogging = {
118
+ 'set-presence': true,
119
+ 'set-presence-ok': true,
120
+ 'refresh-presence': true,
121
+ 'patch-presence': true,
122
+ };
123
+
124
+ /**
125
+ * @param {QuerySubInStorage} x
126
+ * @param {boolean | null} useDateObjects
127
+ * @returns {QuerySub}
128
+ */
129
+ function querySubFromStorage(x, useDateObjects) {
130
+ const v = typeof x === 'string' ? JSON.parse(x) : x;
131
+
132
+ if (v?.result?.store) {
133
+ const attrsStore = s.attrsStoreFromJSON(
134
+ v.result.attrsStore,
135
+ v.result.store,
136
+ );
137
+ if (attrsStore) {
138
+ const storeJSON = v.result.store;
139
+ v.result.store = s.fromJSON(attrsStore, {
140
+ ...storeJSON,
141
+ useDateObjects: useDateObjects,
142
+ });
143
+ v.result.attrsStore = attrsStore;
144
+ }
145
+ }
146
+
147
+ return v;
148
+ }
149
+
150
+ /**
151
+ *
152
+ * @param {string} _key
153
+ * @param {QuerySub} sub
154
+ * @returns QuerySubInStorage
155
+ */
156
+ function querySubToStorage(_key, sub) {
157
+ const { result, ...rest } = sub;
158
+ const jsonSub = /** @type {import('./reactorTypes.ts').QuerySubInStorage} */ (
159
+ rest
160
+ );
161
+ if (result) {
162
+ /** @type {import('./reactorTypes.ts').QuerySubResultInStorage} */
163
+ const jsonResult = {
164
+ ...result,
165
+ store: s.toJSON(result.store),
166
+ attrsStore: result.attrsStore.toJSON(),
167
+ };
168
+
169
+ jsonSub.result = jsonResult;
170
+ }
171
+ return jsonSub;
172
+ }
173
+
174
+ function kvFromStorage(key, x) {
175
+ switch (key) {
176
+ case 'pendingMutations':
177
+ return new Map(typeof x === 'string' ? JSON.parse(x) : x);
178
+ default:
179
+ return x;
180
+ }
181
+ }
182
+
183
+ function kvToStorage(key, x) {
184
+ switch (key) {
185
+ case 'pendingMutations':
186
+ return [...x.entries()];
187
+ default:
188
+ return x;
189
+ }
190
+ }
191
+
192
+ function onMergeQuerySub(_k, storageSub, inMemorySub) {
193
+ const storageResult = storageSub?.result;
194
+ const memoryResult = inMemorySub?.result;
195
+ if (storageResult && !memoryResult && inMemorySub) {
196
+ inMemorySub.result = storageResult;
197
+ }
198
+ return inMemorySub || storageSub;
199
+ }
200
+
201
+ function sortedMutationEntries(entries) {
202
+ return [...entries].sort((a, b) => {
203
+ const [ka, muta] = a;
204
+ const [kb, mutb] = b;
205
+ const a_order = muta.order || 0;
206
+ const b_order = mutb.order || 0;
207
+ if (a_order == b_order) {
208
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
209
+ }
210
+ return a_order - b_order;
211
+ });
212
+ }
213
+
214
+ /**
215
+ * @template {import('./presence.ts').RoomSchemaShape} [RoomSchema = {}]
216
+ */
217
+ export default class Reactor {
218
+ /** @type {s.AttrsStore | undefined} */
219
+ attrs;
220
+ _isOnline = true;
221
+ _isShutdown = false;
222
+ status = STATUS.CONNECTING;
223
+
224
+ /** @type {PersistedObject<string, QuerySub, QuerySubInStorage>} */
225
+ querySubs;
226
+
227
+ /** @type {PersistedObject} */
228
+ kv;
229
+
230
+ /** @type {SyncTable} */
231
+ _syncTable;
232
+ /** @type {InstantStream} */
233
+ _instantStream;
234
+
235
+ /** @type {Record<string, Array<{ q: any, cb: (data: any) => any }>>} */
236
+ queryCbs = {};
237
+ /** @type {Record<string, Array<{ q: any, eventId: string, dfd: Deferred }>>} */
238
+ queryOnceDfds = {};
239
+ authCbs = [];
240
+ attrsCbs = [];
241
+ mutationErrorCbs = [];
242
+ connectionStatusCbs = [];
243
+ appStatusCbs = [];
244
+ /**
245
+ * Carries the raw server status off the public type: `disabled` is an
246
+ * operator-level state we don't surface to apps.
247
+ * @type {import('./clientTypes.ts').AppStatusState & { status?: 'active' | 'read-only' | 'disabled' }}
248
+ */
249
+ _appStatusState = { isLoading: true, isReadOnly: undefined };
250
+ config;
251
+ mutationDeferredStore = new Map();
252
+ _reconnectTimeoutId = null;
253
+ _reconnectTimeoutMs = 0;
254
+ /** @type {Connection} */
255
+ _transport;
256
+ /** @type {TransportType} */
257
+ _transportType = 'ws';
258
+
259
+ /** @type {EventSourceConstructor} */
260
+ _EventSource;
261
+ /** @type {boolean | null} */
262
+ _wsOk = null;
263
+ _localIdPromises = {};
264
+ _errorMessage = null;
265
+ /** @type {Promise<null | {error: {message: string}}> | null}**/
266
+ _oauthCallbackResponse = null;
267
+
268
+ /** @type {null | import('./utils/linkIndex.ts').LinkIndex}} */
269
+ _linkIndex = null;
270
+
271
+ /** @type BroadcastChannel | undefined */
272
+ _broadcastChannel;
273
+
274
+ /** @type {Record<string, {roomType: string; isConnected: boolean; error: any}>} */
275
+ _rooms = {};
276
+ /** @type {Record<string, boolean>} */
277
+ _roomsPendingLeave = {};
278
+ _presence = {};
279
+ _broadcastQueue = [];
280
+ _broadcastSubs = {};
281
+ /** @type {{isLoading: boolean; error: any | undefined, user: any | undefined}} */
282
+ _currentUserCached = { isLoading: true, error: undefined, user: undefined };
283
+ _beforeUnloadCbs = [];
284
+ _dataForQueryCache = {};
285
+ // Memoises dataForQuery between notifies. Separate from _dataForQueryCache,
286
+ // which notifyOne uses as its last-notified value for deduping.
287
+ _dataForQueryMemo = {};
288
+ /** @type {Logger} */
289
+ _log;
290
+ _pendingTxCleanupTimeout;
291
+ _pendingMutationCleanupThreshold;
292
+ _inFlightMutationEventIds = new Set();
293
+ /** @type FrameworkClient | null */
294
+ _frameworkClient = null;
295
+ /**
296
+ * When false, a local write notifies every query rather than only the ones
297
+ * its footprint can affect. Used by tests to compare the two.
298
+ */
299
+ _scopedNotify = true;
300
+ /** @type {Map<string, {q: any, attrs: any, fp: import('./notifyScope.ts').QueryFootprint | null}>} */
301
+ _queryFootprints = new Map();
302
+
303
+ constructor(
304
+ config,
305
+ Storage = IndexedDBStorage,
306
+ NetworkListener = WindowNetworkListener,
307
+ versions,
308
+ EventSourceConstructor,
309
+ ) {
310
+ this._EventSource = EventSourceConstructor;
311
+
312
+ this.config = { ...config };
313
+ this.queryCacheLimit = this.config.queryCacheLimit ?? 10;
314
+ this._pendingTxCleanupTimeout =
315
+ this.config.pendingTxCleanupTimeout ?? PENDING_TX_CLEANUP_TIMEOUT;
316
+ this._pendingMutationCleanupThreshold =
317
+ this.config.pendingMutationCleanupThreshold ??
318
+ PENDING_MUTATION_CLEANUP_THRESHOLD;
319
+
320
+ this._log = createLogger(
321
+ config.verbose || flags.devBackend || flags.instantLogs,
322
+ () => this._reactorStats(),
323
+ config.logger,
324
+ );
325
+
326
+ this.versions = { ...(versions || {}), '@instantdb/core': version };
327
+
328
+ if (this.config.schema) {
329
+ this._linkIndex = createLinkIndex(this.config.schema);
330
+ }
331
+
332
+ // This is to protect us against running
333
+ // server-side.
334
+ if (!isClient()) {
335
+ return;
336
+ }
337
+
338
+ if (!config.appId) {
339
+ throw new Error('SidekickDB must be initialized with an appId.');
340
+ }
341
+
342
+ if (!validateUUID(config.appId)) {
343
+ throw new Error(
344
+ `SidekickDB must be initialized with a valid appId. \`${config.appId}\` is not a valid uuid.`,
345
+ );
346
+ }
347
+
348
+ if (typeof BroadcastChannel === 'function') {
349
+ this._broadcastChannel = new BroadcastChannel('@instantdb');
350
+ this._broadcastChannel.addEventListener('message', async (e) => {
351
+ try {
352
+ if (e.data?.type === 'auth') {
353
+ const res = await this.getCurrentUser({
354
+ forceReadFromStorage: true,
355
+ });
356
+ await this.updateUser(res.user).catch((error) => {
357
+ this._log.error('[error] update user', error);
358
+ });
359
+ }
360
+ } catch (e) {
361
+ this._log.error('[error] handle broadcast channel', e);
362
+ }
363
+ });
364
+ }
365
+
366
+ this._initStorage(Storage);
367
+
368
+ this._syncTable = new SyncTable(
369
+ this._trySendAuthed.bind(this),
370
+ new Storage(this.config.appId, 'syncSubs'),
371
+ {
372
+ useDateObjects: this.config.useDateObjects,
373
+ },
374
+ this._log,
375
+ (triples) => {
376
+ return s.createStore(
377
+ this.ensureAttrs(),
378
+ triples,
379
+ this.config.enableCardinalityInference,
380
+ this.config.useDateObjects,
381
+ );
382
+ },
383
+ () => this.ensureAttrs(),
384
+ );
385
+
386
+ this._instantStream = new InstantStream({
387
+ WStream: this.config.WritableStream || WritableStream,
388
+ RStream: this.config.ReadableStream || ReadableStream,
389
+ trySend: this._trySendAuthed.bind(this),
390
+ log: this._log,
391
+ });
392
+
393
+ this._oauthCallbackResponse = this._oauthLoginInit();
394
+ this.setupUserSyncTimer();
395
+
396
+ NetworkListener.getIsOnline().then((isOnline) => {
397
+ this._isOnline = isOnline;
398
+ this._startSocket();
399
+ NetworkListener.listen((isOnline) => {
400
+ // We do this because react native's NetInfo
401
+ // fires multiple online events.
402
+ // We only want to handle one state change
403
+ if (isOnline === this._isOnline) {
404
+ return;
405
+ }
406
+ this._log.info('[network] online =', isOnline);
407
+ this._isOnline = isOnline;
408
+ if (this._isOnline) {
409
+ this._startSocket();
410
+ } else {
411
+ this._log.info(
412
+ 'Changing status from',
413
+ this.status,
414
+ 'to',
415
+ STATUS.CLOSED,
416
+ );
417
+ this._setStatus(STATUS.CLOSED);
418
+ }
419
+ });
420
+ });
421
+
422
+ if (typeof addEventListener !== 'undefined') {
423
+ this._beforeUnload = this._beforeUnload.bind(this);
424
+ addEventListener('beforeunload', this._beforeUnload);
425
+ }
426
+ }
427
+
428
+ getFrameworkClient() {
429
+ return this._frameworkClient;
430
+ }
431
+
432
+ /** @param {FrameworkClient} client */
433
+ setFrameworkClient(client) {
434
+ this._frameworkClient = client;
435
+ }
436
+
437
+ ensureAttrs() {
438
+ if (!this.attrs) {
439
+ throw new Error('attrs have not loaded.');
440
+ }
441
+ return this.attrs;
442
+ }
443
+
444
+ updateSchema(schema) {
445
+ this.config = {
446
+ ...this.config,
447
+ schema: schema,
448
+ cardinalityInference: Boolean(schema),
449
+ };
450
+ this._linkIndex = schema ? createLinkIndex(this.config.schema) : null;
451
+ }
452
+
453
+ _reactorStats() {
454
+ return {
455
+ inFlightMutationCount: this._inFlightMutationEventIds.size,
456
+ storedMutationCount: this._pendingMutations().size,
457
+ transportType: this._transportType,
458
+ };
459
+ }
460
+
461
+ _onQuerySubLoaded(hash) {
462
+ this.kv
463
+ .waitForKeyToLoad('pendingMutations')
464
+ .then(() => this.notifyOne(hash));
465
+ }
466
+
467
+ _initStorage(Storage) {
468
+ this.querySubs = new PersistedObject({
469
+ persister: new Storage(this.config.appId, 'querySubs'),
470
+ merge: onMergeQuerySub,
471
+ serialize: querySubToStorage,
472
+ parse: (_key, x) => querySubFromStorage(x, this.config.useDateObjects),
473
+ // objectSize
474
+ objectSize: (x) => x?.result?.store?.triples?.length ?? 0,
475
+ logger: this._log,
476
+ preloadEntryCount: 10,
477
+ gc: {
478
+ maxAgeMs: 1000 * 60 * 60 * 24 * 7 * 52, // 1 year
479
+ maxEntries: 1000,
480
+ // Size of each query is the number of triples
481
+ maxSize: 1_000_000, // 1 million triples
482
+ },
483
+ });
484
+ this.querySubs.onKeyLoaded = (k) => this._onQuerySubLoaded(k);
485
+ this.kv = new PersistedObject({
486
+ persister: new Storage(this.config.appId, 'kv'),
487
+ merge: this._onMergeKv,
488
+ serialize: kvToStorage,
489
+ parse: kvFromStorage,
490
+ objectSize: () => 0,
491
+ logger: this._log,
492
+ saveThrottleMs: 100,
493
+ idleCallbackMaxWaitMs: 100,
494
+ // Don't GC the kv store
495
+ gc: null,
496
+ });
497
+ this.kv.onKeyLoaded = (k) => {
498
+ if (k === 'pendingMutations') {
499
+ this.notifyAll();
500
+ }
501
+ };
502
+ // Trigger immediate load for pendingMutations and currentUser
503
+ this.kv.waitForKeyToLoad('pendingMutations');
504
+ this.kv.waitForKeyToLoad(currentUserKey);
505
+ this._beforeUnloadCbs.push(() => {
506
+ this.kv.flush();
507
+ this.querySubs.flush();
508
+ });
509
+ }
510
+
511
+ _beforeUnload() {
512
+ for (const cb of this._beforeUnloadCbs) {
513
+ cb();
514
+ }
515
+ this._syncTable.beforeUnload();
516
+ }
517
+
518
+ /**
519
+ * @param {'enqueued' | 'pending' | 'synced' | 'timeout' | 'error' } status
520
+ * @param {string} eventId
521
+ * @param {{message?: string, type?: string, status?: number, hint?: unknown, traceId?: string}} [errorMsg]
522
+ */
523
+ _finishTransaction(status, eventId, errorMsg) {
524
+ const dfd = this.mutationDeferredStore.get(eventId);
525
+ this.mutationDeferredStore.delete(eventId);
526
+ const ok = status !== 'error' && status !== 'timeout';
527
+
528
+ if (!dfd && !ok) {
529
+ // console.erroring here, as there are no listeners to let know
530
+ console.error('Mutation failed', { status, eventId, ...errorMsg });
531
+ }
532
+ if (!dfd) {
533
+ return;
534
+ }
535
+ if (ok) {
536
+ dfd.resolve({ status, eventId });
537
+ } else {
538
+ // Check if error comes from server or client
539
+ if (errorMsg?.type) {
540
+ const { status, ...body } = errorMsg;
541
+ dfd.reject(
542
+ new InstantAPIError({
543
+ // @ts-expect-error body.type is not constant typed
544
+ body,
545
+ status: status ?? 0,
546
+ }),
547
+ );
548
+ } else {
549
+ dfd.reject(
550
+ new InstantError(
551
+ errorMsg?.message || 'Unknown error',
552
+ errorMsg?.hint,
553
+ errorMsg?.traceId,
554
+ ),
555
+ );
556
+ }
557
+ }
558
+ }
559
+
560
+ _setStatus(status, err) {
561
+ this.status = status;
562
+ this._errorMessage = err;
563
+ this.notifyConnectionStatusSubs(status);
564
+ this._instantStream.onConnectionStatusChange(status);
565
+ }
566
+
567
+ _onMergeKv = (key, storageV, inMemoryV) => {
568
+ switch (key) {
569
+ case 'pendingMutations': {
570
+ const storageEntries = storageV?.entries() ?? [];
571
+ const inMemoryEntries = inMemoryV?.entries() ?? [];
572
+ const muts = new Map([...storageEntries, ...inMemoryEntries]);
573
+ const rewrittenStorageMuts = storageV
574
+ ? this._rewriteMutationsSorted(this.attrs, storageV)
575
+ : [];
576
+ rewrittenStorageMuts.forEach(([k, mut]) => {
577
+ if (!inMemoryV?.pendingMutations?.has(k) && !mut['tx-id']) {
578
+ this._sendMutation(k, mut);
579
+ }
580
+ });
581
+ return muts;
582
+ }
583
+ default:
584
+ return inMemoryV || storageV;
585
+ }
586
+ };
587
+
588
+ _flushEnqueuedRoomData(roomId) {
589
+ const enqueuedUserPresence = this._presence[roomId]?.result?.user;
590
+ const enqueuedBroadcasts = this._broadcastQueue[roomId];
591
+
592
+ this._broadcastQueue[roomId] = [];
593
+
594
+ if (enqueuedUserPresence) {
595
+ this._trySetPresence(roomId, enqueuedUserPresence);
596
+ }
597
+
598
+ if (enqueuedBroadcasts) {
599
+ for (const item of enqueuedBroadcasts) {
600
+ const { topic, roomType, data } = item;
601
+ this._tryBroadcast(roomId, roomType, topic, data);
602
+ }
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Does the same thing as add-query-ok
608
+ * but called as a result of receiving query info from ssr
609
+ * @param {any} q
610
+ * @param {{ triples: any; pageInfo: any; }} result
611
+ * @param {boolean} enableCardinalityInference
612
+ */
613
+ _addQueryData(q, result, enableCardinalityInference) {
614
+ if (!this.attrs) {
615
+ throw new Error('Attrs in reactor have not been set');
616
+ }
617
+ const queryHash = weakHash(q);
618
+ const attrsStore = this.ensureAttrs();
619
+ const store = s.createStore(
620
+ this.attrs,
621
+ result.triples,
622
+ enableCardinalityInference,
623
+ this.config.useDateObjects,
624
+ );
625
+ this.querySubs.updateInPlace((prev) => {
626
+ prev[queryHash] = {
627
+ result: {
628
+ store,
629
+ attrsStore,
630
+ pageInfo: result.pageInfo,
631
+ processedTxId: undefined,
632
+ isExternal: true,
633
+ },
634
+ q,
635
+ };
636
+ });
637
+ this._cleanupPendingMutationsQueries();
638
+ this.notifyOne(queryHash);
639
+ this.notifyOneQueryOnce(queryHash);
640
+ this._cleanupPendingMutationsTimeout();
641
+ }
642
+
643
+ _handleReceive(connId, msg) {
644
+ // opt-out, enabled by default if schema
645
+ const enableCardinalityInference =
646
+ Boolean(this.config.schema) &&
647
+ ('cardinalityInference' in this.config
648
+ ? Boolean(this.config.cardinalityInference)
649
+ : true);
650
+ if (!ignoreLogging[msg.op]) {
651
+ this._log.info('[receive]', connId, msg.op, msg);
652
+ }
653
+ switch (msg.op) {
654
+ case 'init-ok': {
655
+ this._setStatus(STATUS.AUTHENTICATED);
656
+ this._reconnectTimeoutMs = 0;
657
+ this._setAppStatus(msg['app-status']?.status ?? 'active');
658
+ this._setAttrs(msg.attrs);
659
+ this._flushPendingMessages();
660
+ // (EPH): set session-id, so we know
661
+ // which item is us
662
+ this._sessionId = msg['session-id'];
663
+
664
+ for (const roomId of Object.keys(this._rooms)) {
665
+ const enqueuedUserPresence = this._presence[roomId]?.result?.user;
666
+ const roomType = this._rooms[roomId]?.roomType;
667
+ this._tryJoinRoom(roomType, roomId, enqueuedUserPresence);
668
+ }
669
+ break;
670
+ }
671
+ case 'add-query-exists': {
672
+ this.notifyOneQueryOnce(weakHash(msg.q));
673
+ break;
674
+ }
675
+ case 'add-query-ok': {
676
+ const { q, result } = msg;
677
+ const hash = weakHash(q);
678
+ if (!this._hasQueryListeners() && !this.querySubs.currentValue[hash]) {
679
+ break;
680
+ }
681
+ const pageInfo = result?.[0]?.data?.['page-info'];
682
+ const aggregate = result?.[0]?.data?.['aggregate'];
683
+ const triples = extractTriples(result);
684
+ const attrsStore = this.ensureAttrs();
685
+ const store = s.createStore(
686
+ attrsStore,
687
+ triples,
688
+ enableCardinalityInference,
689
+ this.config.useDateObjects,
690
+ );
691
+
692
+ this.querySubs.updateInPlace((prev) => {
693
+ if (!prev[hash]) {
694
+ this._log.info('Missing value in querySubs', { hash, q });
695
+ return;
696
+ }
697
+ prev[hash].result = {
698
+ store,
699
+ attrsStore,
700
+ pageInfo,
701
+ aggregate,
702
+ processedTxId: msg['processed-tx-id'],
703
+ };
704
+ });
705
+ this._cleanupPendingMutationsQueries();
706
+ this.notifyOne(hash);
707
+ this.notifyOneQueryOnce(hash);
708
+ this._cleanupPendingMutationsTimeout();
709
+ break;
710
+ }
711
+ case 'start-sync-ok': {
712
+ this._syncTable.onStartSyncOk(msg);
713
+ break;
714
+ }
715
+ case 'sync-load-batch': {
716
+ this._syncTable.onSyncLoadBatch(msg);
717
+ break;
718
+ }
719
+ case 'sync-init-finish': {
720
+ this._syncTable.onSyncInitFinish(msg);
721
+ break;
722
+ }
723
+ case 'sync-update-triples': {
724
+ this._syncTable.onSyncUpdateTriples(msg);
725
+ break;
726
+ }
727
+ case 'start-stream-ok': {
728
+ this._instantStream.onStartStreamOk(msg);
729
+ break;
730
+ }
731
+ case 'stream-flushed': {
732
+ this._instantStream.onStreamFlushed(msg);
733
+ break;
734
+ }
735
+ case 'append-failed': {
736
+ this._instantStream.onAppendFailed(msg);
737
+ break;
738
+ }
739
+ case 'stream-append': {
740
+ this._instantStream.onStreamAppend(msg);
741
+ break;
742
+ }
743
+ case 'refresh-ok': {
744
+ const { computations, attrs } = msg;
745
+ const processedTxId = msg['processed-tx-id'];
746
+ if (attrs) {
747
+ this._setAttrs(attrs);
748
+ }
749
+
750
+ this._cleanupPendingMutationsTimeout();
751
+
752
+ const rewrittenMutations = this._rewriteMutations(
753
+ this.ensureAttrs(),
754
+ this._pendingMutations(),
755
+ processedTxId,
756
+ );
757
+
758
+ if (rewrittenMutations !== this._pendingMutations()) {
759
+ // We know we've changed the mutations to fix the attr ids and removed
760
+ // processed attrs, so we'll persist those changes to prevent optimisticAttrs
761
+ // from using old attr definitions
762
+ this.kv.updateInPlace((prev) => {
763
+ prev.pendingMutations = rewrittenMutations;
764
+ });
765
+ }
766
+
767
+ const mutations = sortedMutationEntries(rewrittenMutations.entries());
768
+
769
+ const updates = computations.map((x) => {
770
+ const q = x['instaql-query'];
771
+ const result = x['instaql-result'];
772
+ const hash = weakHash(q);
773
+ const triples = extractTriples(result);
774
+ const attrsStore = this.ensureAttrs();
775
+ const store = s.createStore(
776
+ attrsStore,
777
+ triples,
778
+ enableCardinalityInference,
779
+ this.config.useDateObjects,
780
+ );
781
+ const { store: newStore, attrsStore: newAttrsStore } =
782
+ this._applyOptimisticUpdates(
783
+ store,
784
+ attrsStore,
785
+ mutations,
786
+ processedTxId,
787
+ );
788
+ const pageInfo = result?.[0]?.data?.['page-info'];
789
+ const aggregate = result?.[0]?.data?.['aggregate'];
790
+ return {
791
+ q,
792
+ hash,
793
+ store: newStore,
794
+ attrsStore: newAttrsStore,
795
+ pageInfo,
796
+ aggregate,
797
+ };
798
+ });
799
+
800
+ updates.forEach(
801
+ ({ hash, q, store, attrsStore, pageInfo, aggregate }) => {
802
+ this.querySubs.updateInPlace((prev) => {
803
+ if (!prev[hash]) {
804
+ this._log.error('Missing value in querySubs', { hash, q });
805
+ return;
806
+ }
807
+ prev[hash].result = {
808
+ store,
809
+ attrsStore,
810
+ pageInfo,
811
+ aggregate,
812
+ processedTxId,
813
+ };
814
+ });
815
+ },
816
+ );
817
+
818
+ this._cleanupPendingMutationsQueries();
819
+
820
+ updates.forEach(({ hash }) => {
821
+ this.notifyOne(hash);
822
+ });
823
+ break;
824
+ }
825
+ case 'transact-ok': {
826
+ const { 'client-event-id': eventId, 'tx-id': txId } = msg;
827
+
828
+ this._inFlightMutationEventIds.delete(eventId);
829
+
830
+ const muts = this._rewriteMutations(
831
+ this.ensureAttrs(),
832
+ this._pendingMutations(),
833
+ );
834
+ const prevMutation = muts.get(eventId);
835
+ if (!prevMutation) {
836
+ break;
837
+ }
838
+
839
+ // update pendingMutation with server-side tx-id
840
+ this._updatePendingMutations((prev) => {
841
+ prev.set(eventId, {
842
+ ...prev.get(eventId),
843
+ 'tx-id': txId,
844
+ confirmed: Date.now(),
845
+ });
846
+ });
847
+
848
+ const newAttrs = [];
849
+ for (const step of prevMutation['tx-steps']) {
850
+ if (step[0] === 'add-attr') {
851
+ const attr = step[1];
852
+ newAttrs.push(attr);
853
+ }
854
+ }
855
+ if (newAttrs.length) {
856
+ const existingAttrs = Object.values(this.ensureAttrs().attrs);
857
+ this._setAttrs([...existingAttrs, ...newAttrs]);
858
+ }
859
+
860
+ this._finishTransaction('synced', eventId);
861
+
862
+ this._cleanupPendingMutationsTimeout();
863
+
864
+ break;
865
+ }
866
+ case 'patch-presence': {
867
+ const roomId = msg['room-id'];
868
+ this._trySetRoomConnected(roomId, true);
869
+ this._patchPresencePeers(roomId, msg['edits']);
870
+ this._notifyPresenceSubs(roomId);
871
+ break;
872
+ }
873
+ case 'refresh-presence': {
874
+ const roomId = msg['room-id'];
875
+ this._trySetRoomConnected(roomId, true);
876
+ this._setPresencePeers(roomId, msg['data']);
877
+ this._notifyPresenceSubs(roomId);
878
+ break;
879
+ }
880
+ case 'server-broadcast': {
881
+ const room = msg['room-id'];
882
+ const topic = msg.topic;
883
+ this._trySetRoomConnected(room, true);
884
+ this._notifyBroadcastSubs(room, topic, msg);
885
+ break;
886
+ }
887
+ case 'join-room-ok': {
888
+ const loadingRoomId = msg['room-id'];
889
+ const joinedRoom = this._rooms[loadingRoomId];
890
+
891
+ if (!joinedRoom) {
892
+ if (this._roomsPendingLeave[loadingRoomId]) {
893
+ this._tryLeaveRoom(loadingRoomId);
894
+ delete this._roomsPendingLeave[loadingRoomId];
895
+ }
896
+
897
+ break;
898
+ }
899
+
900
+ this._trySetRoomConnected(loadingRoomId, true);
901
+ this._flushEnqueuedRoomData(loadingRoomId);
902
+ break;
903
+ }
904
+ case 'leave-room-ok': {
905
+ const roomId = msg['room-id'];
906
+ this._trySetRoomConnected(roomId, false);
907
+ break;
908
+ }
909
+ case 'app-status-changed': {
910
+ const prevStatus = this._appStatusState.status;
911
+ this._setAppStatus(msg.status);
912
+ if (msg.status === 'disabled' && prevStatus !== 'disabled') {
913
+ // The server has stopped serving reads; surface the typed error on
914
+ // every registered query immediately instead of waiting for the
915
+ // next round trip.
916
+ const error = {
917
+ message: 'This app is currently disabled.',
918
+ hint: { status: 'disabled' },
919
+ };
920
+ Object.keys(this.queryCbs).forEach((hash) =>
921
+ this.notifyQueryError(hash, error),
922
+ );
923
+ }
924
+ if (prevStatus === 'disabled' && msg.status !== 'disabled') {
925
+ // Leaving `disabled`: refreshes were paused server-side, so restart
926
+ // the socket to re-add every query and get fresh results.
927
+ this._startSocket();
928
+ }
929
+ break;
930
+ }
931
+ case 'join-room-error':
932
+ const errorRoomId = msg['room-id'];
933
+ const errorRoom = this._rooms[errorRoomId];
934
+ if (errorRoom) {
935
+ errorRoom.error = msg['error'];
936
+ }
937
+ this._notifyPresenceSubs(errorRoomId);
938
+ break;
939
+ case 'error':
940
+ this._handleReceiveError(msg);
941
+ break;
942
+ default:
943
+ this._log.info('Unknown op', msg.op, msg);
944
+ break;
945
+ }
946
+ }
947
+
948
+ createWriteStream(opts) {
949
+ return this._instantStream.createWriteStream(opts);
950
+ }
951
+
952
+ createReadStream(opts) {
953
+ return this._instantStream.createReadStream(opts);
954
+ }
955
+
956
+ _pendingMutations() {
957
+ return this.kv.currentValue.pendingMutations ?? new Map();
958
+ }
959
+
960
+ _updatePendingMutations(f) {
961
+ this.kv.updateInPlace((prev) => {
962
+ const muts = prev.pendingMutations ?? new Map();
963
+ prev.pendingMutations = muts;
964
+ f(muts);
965
+ });
966
+ }
967
+
968
+ /**
969
+ * @param {'timeout' | 'error'} status
970
+ * @param {string} eventId
971
+ * @param {{message?: string, type?: string, status?: number, hint?: unknown, traceId?: string}} errorMsg
972
+ */
973
+ _handleMutationError(status, eventId, errorMsg) {
974
+ const mut = this._pendingMutations().get(eventId);
975
+
976
+ if (mut && (status !== 'timeout' || !mut['tx-id'])) {
977
+ // Read before the delete below.
978
+ const affected = this._mutationsFrom(eventId);
979
+ this._updatePendingMutations((prev) => {
980
+ prev.delete(eventId);
981
+ return prev;
982
+ });
983
+ this._inFlightMutationEventIds.delete(eventId);
984
+ const errDetails = {
985
+ message: errorMsg.message,
986
+ hint: errorMsg.hint,
987
+ traceId: errorMsg.traceId,
988
+ };
989
+ this._notifyForMutations(affected);
990
+ this.notifyAttrsSubs();
991
+ this.notifyMutationErrorSubs(errDetails);
992
+ this._finishTransaction(status, eventId, errorMsg);
993
+ }
994
+ }
995
+
996
+ _handleReceiveError(msg) {
997
+ this._log.info('error', msg);
998
+ const eventId = msg['client-event-id'];
999
+ // This might not be a mutation, but it can't hurt to delete it
1000
+ this._inFlightMutationEventIds.delete(eventId);
1001
+ const prevMutation = this._pendingMutations().get(eventId);
1002
+ const errorMessage = {
1003
+ message: msg.message || 'Uh-oh, something went wrong. Ping Joe & Stopa.',
1004
+ };
1005
+
1006
+ if (msg.hint) {
1007
+ errorMessage.hint = msg.hint;
1008
+ }
1009
+
1010
+ if (msg['trace-id'] || msg['original-event']?.['trace-id']) {
1011
+ const traceIds = [msg['trace-id'], msg['original-event']?.['trace-id']];
1012
+ const traceId = traceIds.filter(Boolean).join(',');
1013
+ errorMessage.traceId = traceId;
1014
+ }
1015
+
1016
+ if (prevMutation) {
1017
+ this._handleMutationError('error', eventId, errorMessage);
1018
+ return;
1019
+ }
1020
+
1021
+ if (
1022
+ msg['original-event']?.hasOwnProperty('q') &&
1023
+ msg['original-event']?.op === 'add-query'
1024
+ ) {
1025
+ const q = msg['original-event']?.q;
1026
+ const hash = weakHash(q);
1027
+ this.notifyQueryError(weakHash(q), errorMessage);
1028
+ this.notifyQueryOnceError(q, hash, eventId, errorMessage);
1029
+ return;
1030
+ }
1031
+
1032
+ const isInitError = msg['original-event']?.op === 'init';
1033
+ if (isInitError) {
1034
+ if (
1035
+ msg.type === 'record-not-found' &&
1036
+ msg.hint?.['record-type'] === 'app-user'
1037
+ ) {
1038
+ // User has been logged out
1039
+ this.changeCurrentUser(null);
1040
+ return;
1041
+ }
1042
+
1043
+ // We failed to init
1044
+
1045
+ this._setStatus(STATUS.ERRORED, errorMessage);
1046
+ this.notifyAll();
1047
+ return;
1048
+ }
1049
+
1050
+ switch (msg['original-event']?.op) {
1051
+ case 'resync-table': {
1052
+ this._syncTable.onResyncError(msg);
1053
+ return;
1054
+ }
1055
+ case 'start-sync': {
1056
+ this._syncTable.onStartSyncError(msg);
1057
+ return;
1058
+ }
1059
+ case 'start-stream':
1060
+ case 'append-stream':
1061
+ case 'subscribe-stream':
1062
+ case 'unsubscribe-stream': {
1063
+ this._instantStream.onRecieveError(msg);
1064
+ return;
1065
+ }
1066
+ }
1067
+ // We've caught some error which has no corresponding listener.
1068
+ // Let's console.error to let the user know.
1069
+ const errorObj = { ...msg };
1070
+ delete errorObj.message;
1071
+ delete errorObj.hint;
1072
+ console.error(msg.message, errorObj);
1073
+ if (msg.hint) {
1074
+ console.error(
1075
+ 'This error comes with some debugging information. Here it is: \n',
1076
+ msg.hint,
1077
+ );
1078
+ }
1079
+ }
1080
+
1081
+ notifyQueryOnceError(q, hash, eventId, e) {
1082
+ const r = this.queryOnceDfds[hash]?.find((r) => r.eventId === eventId);
1083
+ if (!r) return;
1084
+ r.dfd.reject(e);
1085
+ this._completeQueryOnce(q, hash, r.dfd);
1086
+ }
1087
+
1088
+ _setAttrs(attrs) {
1089
+ this.attrs = new s.AttrsStoreClass(
1090
+ attrs.reduce((acc, attr) => {
1091
+ acc[attr.id] = attr;
1092
+ return acc;
1093
+ }, {}),
1094
+ this._linkIndex,
1095
+ );
1096
+
1097
+ this.notifyAttrsSubs();
1098
+ }
1099
+
1100
+ // ---------------------------
1101
+ // Queries
1102
+
1103
+ getPreviousResult = (q) => {
1104
+ const hash = weakHash(q);
1105
+ return this.dataForQuery(hash)?.data;
1106
+ };
1107
+
1108
+ _startQuerySub(q, hash) {
1109
+ const eventId = uuid();
1110
+ this.querySubs.updateInPlace((prev) => {
1111
+ if (!prev[hash]) {
1112
+ // Legacy hash migration (sync): if a preloaded entry sits under the
1113
+ // old hash, move it to the new key so the placeholder line below
1114
+ // becomes a no-op and currentValue[hash] keeps its cached result.
1115
+ const legacyHash = weakHashLegacy(q);
1116
+ if (legacyHash !== hash && prev[legacyHash]) {
1117
+ prev[hash] = prev[legacyHash];
1118
+ delete prev[legacyHash];
1119
+ }
1120
+ }
1121
+ prev[hash] = prev[hash] || { q, result: null, eventId };
1122
+ prev[hash].lastAccessed = Date.now();
1123
+ });
1124
+ this._tryMigrateLegacyQuerySub(q, hash);
1125
+ this._trySendAuthed(eventId, { op: 'add-query', q });
1126
+
1127
+ return eventId;
1128
+ }
1129
+
1130
+ // Legacy hash migration (async): covers entries that weren't preloaded
1131
+ // into currentValue. Actively loads the legacy key from storage, moves
1132
+ // its result onto the new key, and notifies subscribers. Safe to remove
1133
+ // a few releases after v1.0.39.
1134
+ async _tryMigrateLegacyQuerySub(q, newHash) {
1135
+ const legacyHash = weakHashLegacy(q);
1136
+ if (legacyHash === newHash) return;
1137
+ await this.querySubs.waitForKeyToLoad(legacyHash);
1138
+ const legacy = this.querySubs.currentValue[legacyHash];
1139
+ if (!legacy) return;
1140
+ let migratedResult = false;
1141
+ this.querySubs.updateInPlace((prev) => {
1142
+ const existing = prev[newHash];
1143
+ if (existing && !existing.result && legacy.result) {
1144
+ existing.result = legacy.result;
1145
+ migratedResult = true;
1146
+ } else if (!existing) {
1147
+ prev[newHash] = legacy;
1148
+ migratedResult = !!legacy.result;
1149
+ }
1150
+ delete prev[legacyHash];
1151
+ });
1152
+ if (migratedResult) this.notifyOne(newHash);
1153
+ }
1154
+
1155
+ subscribeTable(q, cb) {
1156
+ return this._syncTable.subscribe(q, cb);
1157
+ }
1158
+
1159
+ /**
1160
+ * When a user subscribes to a query the following side effects occur:
1161
+ *
1162
+ * - We update querySubs to include the new query
1163
+ * - We update queryCbs to include the new cb
1164
+ * - If we already have a result for the query we call cb immediately
1165
+ * - We send the server an `add-query` message
1166
+ *
1167
+ * Returns an unsubscribe function
1168
+ */
1169
+ subscribeQuery(q, cb, opts) {
1170
+ if (!this.config.disableValidation) {
1171
+ validateQuery(q, this.config.schema);
1172
+ }
1173
+ if (opts && 'ruleParams' in opts) {
1174
+ q = { $$ruleParams: opts['ruleParams'], ...q };
1175
+ }
1176
+
1177
+ const hash = weakHash(q);
1178
+
1179
+ const prevResult = this.getPreviousResult(q);
1180
+ if (prevResult) {
1181
+ cb(prevResult);
1182
+ }
1183
+
1184
+ this.queryCbs[hash] = this.queryCbs[hash] ?? [];
1185
+ this.queryCbs[hash].push({ q, cb });
1186
+
1187
+ this._startQuerySub(q, hash);
1188
+
1189
+ return () => {
1190
+ this._unsubQuery(q, hash, cb);
1191
+ };
1192
+ }
1193
+
1194
+ queryOnce(q, opts) {
1195
+ if (!this.config.disableValidation) {
1196
+ validateQuery(q, this.config.schema);
1197
+ }
1198
+
1199
+ if (opts && 'ruleParams' in opts) {
1200
+ q = { $$ruleParams: opts['ruleParams'], ...q };
1201
+ }
1202
+
1203
+ const dfd = new Deferred();
1204
+
1205
+ if (!this._isOnline) {
1206
+ dfd.reject(
1207
+ new Error("We can't run `queryOnce`, because the device is offline."),
1208
+ );
1209
+ return dfd.promise;
1210
+ }
1211
+
1212
+ if (!this.querySubs) {
1213
+ dfd.reject(
1214
+ new Error(
1215
+ "We can't run `queryOnce` on the backend. Use adminAPI.query instead: https://sidekickdb.co/docs/backend#query",
1216
+ ),
1217
+ );
1218
+ return dfd.promise;
1219
+ }
1220
+
1221
+ const hash = weakHash(q);
1222
+
1223
+ const eventId = this._startQuerySub(q, hash);
1224
+
1225
+ this.queryOnceDfds[hash] = this.queryOnceDfds[hash] ?? [];
1226
+ this.queryOnceDfds[hash].push({ q, dfd, eventId });
1227
+
1228
+ setTimeout(
1229
+ () => dfd.reject(new Error('Query timed out')),
1230
+ QUERY_ONCE_TIMEOUT,
1231
+ );
1232
+
1233
+ return dfd.promise;
1234
+ }
1235
+
1236
+ _completeQueryOnce(q, hash, dfd) {
1237
+ if (!this.queryOnceDfds[hash]) return;
1238
+
1239
+ this.queryOnceDfds[hash] = this.queryOnceDfds[hash].filter(
1240
+ (r) => r.dfd !== dfd,
1241
+ );
1242
+
1243
+ this._cleanupQuery(q, hash);
1244
+ }
1245
+
1246
+ _unsubQuery(q, hash, cb) {
1247
+ if (!this.queryCbs[hash]) return;
1248
+
1249
+ this.queryCbs[hash] = this.queryCbs[hash].filter((r) => r.cb !== cb);
1250
+
1251
+ this._cleanupQuery(q, hash);
1252
+ }
1253
+
1254
+ _hasQueryListeners(hash) {
1255
+ return !!(this.queryCbs[hash]?.length || this.queryOnceDfds[hash]?.length);
1256
+ }
1257
+
1258
+ _cleanupQuery(q, hash) {
1259
+ const hasListeners = this._hasQueryListeners(hash);
1260
+ if (hasListeners) return;
1261
+ delete this.queryCbs[hash];
1262
+ delete this.queryOnceDfds[hash];
1263
+ delete this._dataForQueryCache[hash];
1264
+ delete this._dataForQueryMemo[hash];
1265
+ delete this._dataForQueryMemo['!' + hash];
1266
+ this._queryFootprints.delete(hash);
1267
+ this.querySubs.unloadKey(hash);
1268
+
1269
+ this._trySendAuthed(uuid(), { op: 'remove-query', q });
1270
+ }
1271
+
1272
+ // When we `pushTx`, it's possible that we don't yet have `this.attrs`
1273
+ // This means that `tx-steps` in `pendingMutations` will include `add-attr`
1274
+ // commands for attrs that already exist.
1275
+ //
1276
+ // This will also affect `add-triple` and `retract-triple` which
1277
+ // reference attr-ids that do not match the server.
1278
+ //
1279
+ // We fix this by rewriting `tx-steps` in each `pendingMutation`.
1280
+ // We remove `add-attr` commands for attrs that already exist.
1281
+ // We update `add-triple` and `retract-triple` commands to use the
1282
+ // server attr-ids.
1283
+ /**
1284
+ *
1285
+ * @param {s.AttrsStore} attrs
1286
+ * @param {any} muts
1287
+ * @param {number} [processedTxId]
1288
+ */
1289
+ _rewriteMutations(attrs, muts, processedTxId) {
1290
+ if (!attrs) return muts;
1291
+ if (!muts) return new Map();
1292
+ const findExistingAttr = (attr) => {
1293
+ const [_, etype, label] = attr['forward-identity'];
1294
+ const existing = s.getAttrByFwdIdentName(attrs, etype, label);
1295
+ return existing;
1296
+ };
1297
+ const findReverseAttr = (attr) => {
1298
+ const [_, etype, label] = attr['forward-identity'];
1299
+ const revAttr = s.getAttrByReverseIdentName(attrs, etype, label);
1300
+ return revAttr;
1301
+ };
1302
+ const mapping = { attrIdMap: {}, refSwapAttrIds: new Set() };
1303
+ let mappingChanged = false;
1304
+
1305
+ const rewriteTxSteps = (txSteps, txId) => {
1306
+ const retTxSteps = [];
1307
+ for (const txStep of txSteps) {
1308
+ const [action] = txStep;
1309
+
1310
+ // Handles add-attr
1311
+ // If existing, we drop it, and track it
1312
+ // to update add/retract triples
1313
+ if (action === 'add-attr') {
1314
+ const [_action, attr] = txStep;
1315
+ const existing = findExistingAttr(attr);
1316
+ if (existing && attr.id !== existing.id) {
1317
+ mapping.attrIdMap[attr.id] = existing.id;
1318
+ mappingChanged = true;
1319
+ continue;
1320
+ }
1321
+ if (attr['value-type'] === 'ref') {
1322
+ const revAttr = findReverseAttr(attr);
1323
+ if (revAttr) {
1324
+ mapping.attrIdMap[attr.id] = revAttr.id;
1325
+ mapping.refSwapAttrIds.add(attr.id);
1326
+ mappingChanged = true;
1327
+ continue;
1328
+ }
1329
+ }
1330
+ }
1331
+
1332
+ if (
1333
+ (processedTxId &&
1334
+ txId &&
1335
+ processedTxId >= txId &&
1336
+ action === 'add-attr') ||
1337
+ action === 'update-attr' ||
1338
+ action === 'delete-attr'
1339
+ ) {
1340
+ mappingChanged = true;
1341
+ // Don't add this step because we already have the newer attrs
1342
+ continue;
1343
+ }
1344
+ // Handles add-triple|retract-triple
1345
+ // If in mapping, we update the attr-id
1346
+ const newTxStep = mappingChanged
1347
+ ? instaml.rewriteStep(mapping, txStep)
1348
+ : txStep;
1349
+
1350
+ retTxSteps.push(newTxStep);
1351
+ }
1352
+
1353
+ return mappingChanged ? retTxSteps : txSteps;
1354
+ };
1355
+
1356
+ const rewritten = new Map();
1357
+ for (const [k, mut] of muts.entries()) {
1358
+ rewritten.set(k, {
1359
+ ...mut,
1360
+ 'tx-steps': rewriteTxSteps(mut['tx-steps'], mut['tx-id']),
1361
+ });
1362
+ }
1363
+ if (!mappingChanged) {
1364
+ return muts;
1365
+ }
1366
+ return rewritten;
1367
+ }
1368
+
1369
+ _rewriteMutationsSorted(attrs, muts) {
1370
+ return sortedMutationEntries(this._rewriteMutations(attrs, muts).entries());
1371
+ }
1372
+
1373
+ // ---------------------------
1374
+ // Transact
1375
+
1376
+ /**
1377
+ * @returns {s.AttrsStore}
1378
+ */
1379
+ optimisticAttrs() {
1380
+ const pendingMutationSteps = [...this._pendingMutations().values()] // hack due to Map()
1381
+ .flatMap((x) => x['tx-steps']);
1382
+
1383
+ const deletedAttrIds = new Set(
1384
+ pendingMutationSteps
1385
+ .filter(([action, _attr]) => action === 'delete-attr')
1386
+ .map(([_action, id]) => id),
1387
+ );
1388
+
1389
+ const pendingAttrs = [];
1390
+ for (const [_action, attr] of pendingMutationSteps) {
1391
+ if (_action === 'add-attr') {
1392
+ pendingAttrs.push(attr);
1393
+ } else if (
1394
+ _action === 'update-attr' &&
1395
+ attr.id &&
1396
+ this.attrs?.getAttr(attr.id)
1397
+ ) {
1398
+ const fullAttr = { ...this.attrs.getAttr(attr.id), ...attr };
1399
+ pendingAttrs.push(fullAttr);
1400
+ }
1401
+ }
1402
+
1403
+ if (!deletedAttrIds.size && !pendingAttrs.length) {
1404
+ return this.attrs || new s.AttrsStoreClass({}, this._linkIndex);
1405
+ }
1406
+
1407
+ const attrs = { ...(this.attrs?.attrs || {}) };
1408
+ for (const attr of pendingAttrs) {
1409
+ attrs[attr.id] = attr;
1410
+ }
1411
+ for (const id of deletedAttrIds) {
1412
+ delete attrs[id];
1413
+ }
1414
+
1415
+ return new s.AttrsStoreClass(attrs, this._linkIndex);
1416
+ }
1417
+
1418
+ /** Runs instaql on a query and a store */
1419
+ dataForQuery(hash, applyOptimistic = true) {
1420
+ const errorMessage = this._errorMessage;
1421
+ if (errorMessage) {
1422
+ return { error: errorMessage };
1423
+ }
1424
+ if (!this.querySubs) return;
1425
+ if (!this.kv.currentValue.pendingMutations) return;
1426
+ const querySubVersion = this.querySubs.version();
1427
+ const querySubs = this.querySubs.currentValue;
1428
+ const pendingMutationsVersion = this.kv.version();
1429
+ const pendingMutations = this._pendingMutations();
1430
+
1431
+ const { q, result } = querySubs[hash] || {};
1432
+ if (!result) return;
1433
+
1434
+ // getPreviousResult (called on every useQuery render) reaches here between
1435
+ // notifies, so memoise rather than re-apply every pending mutation.
1436
+ const memoKey = applyOptimistic ? hash : '!' + hash;
1437
+ const memo = this._dataForQueryMemo[memoKey];
1438
+ if (
1439
+ memo &&
1440
+ memo.result === result &&
1441
+ memo.resp.querySubVersion === querySubVersion &&
1442
+ memo.resp.pendingMutationsVersion === pendingMutationsVersion
1443
+ ) {
1444
+ return memo.resp;
1445
+ }
1446
+
1447
+ // notifyOne only ever stores optimistic results here.
1448
+ const cached = applyOptimistic && this._dataForQueryCache[hash];
1449
+ if (
1450
+ cached &&
1451
+ querySubVersion === cached.querySubVersion &&
1452
+ pendingMutationsVersion === cached.pendingMutationsVersion
1453
+ ) {
1454
+ return cached;
1455
+ }
1456
+
1457
+ let store = result.store;
1458
+ let attrsStore = result.attrsStore;
1459
+ const { pageInfo, aggregate, processedTxId } = result;
1460
+ const mutations = this._rewriteMutationsSorted(
1461
+ attrsStore,
1462
+ pendingMutations,
1463
+ );
1464
+ if (applyOptimistic) {
1465
+ const optimisticResult = this._applyOptimisticUpdates(
1466
+ store,
1467
+ attrsStore,
1468
+ mutations,
1469
+ processedTxId,
1470
+ );
1471
+
1472
+ store = optimisticResult.store;
1473
+ attrsStore = optimisticResult.attrsStore;
1474
+ }
1475
+ const resp = instaql(
1476
+ { store: store, attrsStore: attrsStore, pageInfo, aggregate },
1477
+ q,
1478
+ );
1479
+
1480
+ const out = { data: resp, querySubVersion, pendingMutationsVersion };
1481
+ this._dataForQueryMemo[memoKey] = { result, resp: out };
1482
+ return out;
1483
+ }
1484
+
1485
+ _applyOptimisticUpdates(store, attrsStore, mutations, processedTxId) {
1486
+ for (const [_, mut] of mutations) {
1487
+ if (!mut['tx-id'] || (processedTxId && mut['tx-id'] > processedTxId)) {
1488
+ const result = s.transact(store, attrsStore, mut['tx-steps']);
1489
+ store = result.store;
1490
+ attrsStore = result.attrsStore;
1491
+ }
1492
+ }
1493
+ return { store, attrsStore };
1494
+ }
1495
+
1496
+ /** Re-run instaql and call all callbacks with new data */
1497
+ notifyOne = (hash) => {
1498
+ const cbs = this.queryCbs[hash] ?? [];
1499
+ const prevData = this._dataForQueryCache[hash]?.data;
1500
+ const resp = this.dataForQuery(hash);
1501
+
1502
+ if (!resp?.data) return;
1503
+ this._dataForQueryCache[hash] = resp;
1504
+ if (areObjectsDeepEqual(resp.data, prevData)) return;
1505
+
1506
+ cbs.forEach((r) => r.cb(resp.data));
1507
+ };
1508
+
1509
+ notifyOneQueryOnce = (hash) => {
1510
+ const dfds = this.queryOnceDfds[hash] ?? [];
1511
+ const data = this.dataForQuery(hash)?.data;
1512
+
1513
+ dfds.forEach((r) => {
1514
+ this._completeQueryOnce(r.q, hash, r.dfd);
1515
+ r.dfd.resolve(data);
1516
+ });
1517
+ };
1518
+
1519
+ notifyQueryError = (hash, error) => {
1520
+ // Clear the dedupe cache so the next successful result re-notifies
1521
+ // subscribers even if the data is unchanged from before the error
1522
+ delete this._dataForQueryCache[hash];
1523
+ const cbs = this.queryCbs[hash] || [];
1524
+ cbs.forEach((r) => r.cb({ error }));
1525
+ };
1526
+
1527
+ /** Re-compute all subscriptions */
1528
+ notifyAll() {
1529
+ Object.keys(this.queryCbs).forEach((hash) => {
1530
+ this.querySubs
1531
+ .waitForKeyToLoad(hash)
1532
+ .then(() => this.notifyOne(hash))
1533
+ .catch(() => this.notifyOne(hash));
1534
+ });
1535
+ }
1536
+
1537
+ /**
1538
+ * The pending mutation `eventId` and every pending mutation applied after
1539
+ * it. Removing one can change how a later one applies (a lookup it
1540
+ * resolved, an update of an entity it created), so rolling one back
1541
+ * re-runs the queries any of them could affect.
1542
+ */
1543
+ _mutationsFrom(eventId) {
1544
+ const sorted = sortedMutationEntries(this._pendingMutations().entries());
1545
+ const i = sorted.findIndex(([k]) => k === eventId);
1546
+ return i < 0 ? null : sorted.slice(i).map(([_k, mut]) => mut);
1547
+ }
1548
+
1549
+ /**
1550
+ * Like `notifyAll`, but only for the queries `muts` can affect. Anything
1551
+ * it can't classify notifies every query.
1552
+ */
1553
+ _notifyForMutations(muts) {
1554
+ let writeFp = null;
1555
+ if (this._scopedNotify && muts) {
1556
+ writeFp = new Map();
1557
+ for (const mut of muts) {
1558
+ writeFp = mutationFootprint(mut['tx-steps'], this.attrs, writeFp);
1559
+ if (!writeFp) break;
1560
+ }
1561
+ }
1562
+ if (!writeFp) {
1563
+ this.notifyAll();
1564
+ return;
1565
+ }
1566
+ Object.keys(this.queryCbs).forEach((hash) => {
1567
+ if (!this._mutationMayAffect(hash, writeFp)) return;
1568
+ this.querySubs
1569
+ .waitForKeyToLoad(hash)
1570
+ .then(() => this.notifyOne(hash))
1571
+ .catch(() => this.notifyOne(hash));
1572
+ });
1573
+ }
1574
+
1575
+ _mutationMayAffect(hash, writeFp) {
1576
+ // Never delivered, or cleared by notifyQueryError: always deliver.
1577
+ if (!this._dataForQueryCache[hash]) return true;
1578
+ const q = this.querySubs.currentValue?.[hash]?.q;
1579
+ if (!q) return true;
1580
+ // Cached while the query form and the attrs it was resolved against are
1581
+ // the same objects.
1582
+ let entry = this._queryFootprints.get(hash);
1583
+ if (!entry || entry.q !== q || entry.attrs !== this.attrs) {
1584
+ entry = { q, attrs: this.attrs, fp: queryFootprint(q, this.attrs) };
1585
+ this._queryFootprints.set(hash, entry);
1586
+ }
1587
+ return !entry.fp || footprintsIntersect(writeFp, entry.fp);
1588
+ }
1589
+
1590
+ loadedNotifyAll() {
1591
+ this.kv
1592
+ .waitForKeyToLoad('pendingMutations')
1593
+ .then(() => this.notifyAll())
1594
+ .catch(() => this.notifyAll());
1595
+ }
1596
+
1597
+ /** Applies transactions locally and sends transact message to server */
1598
+ pushTx = (chunks) => {
1599
+ // The server rejects every write while read-only or disabled, so reject
1600
+ // locally instead of applying an optimistic update
1601
+ if (this._appStatusState.isReadOnly) {
1602
+ return Promise.reject(
1603
+ this._appStatusState.status === 'disabled'
1604
+ ? new InstantError('This app is currently disabled.', {
1605
+ status: 'disabled',
1606
+ })
1607
+ : new InstantError('This app is in read-only mode.', {
1608
+ status: 'read-only',
1609
+ }),
1610
+ );
1611
+ }
1612
+ // Throws if transactions are invalid
1613
+ if (!this.config.disableValidation) {
1614
+ validateTransactions(chunks, this.config.schema);
1615
+ }
1616
+ try {
1617
+ const txSteps = instaml.transform(
1618
+ {
1619
+ attrsStore: this.optimisticAttrs(),
1620
+ schema: this.config.schema,
1621
+ stores: Object.values(this.querySubs.currentValue).map(
1622
+ (sub) => sub?.result?.store,
1623
+ ),
1624
+ useDateObjects: this.config.useDateObjects,
1625
+ },
1626
+ chunks,
1627
+ );
1628
+ return this.pushOps(txSteps);
1629
+ } catch (e) {
1630
+ return this.pushOps([], e);
1631
+ }
1632
+ };
1633
+
1634
+ /**
1635
+ * @param {*} txSteps
1636
+ * @param {*} [error]
1637
+ * @returns
1638
+ */
1639
+ pushOps = (txSteps, error) => {
1640
+ const eventId = uuid();
1641
+ const mutations = [...this._pendingMutations().values()];
1642
+ const order = Math.max(0, ...mutations.map((mut) => mut.order || 0)) + 1;
1643
+ const mutation = {
1644
+ op: 'transact',
1645
+ 'tx-steps': txSteps,
1646
+ created: Date.now(),
1647
+ error,
1648
+ order,
1649
+ };
1650
+ this._updatePendingMutations((prev) => {
1651
+ prev.set(eventId, mutation);
1652
+ });
1653
+
1654
+ const dfd = new Deferred();
1655
+ this.mutationDeferredStore.set(eventId, dfd);
1656
+ this._sendMutation(eventId, mutation);
1657
+
1658
+ this._notifyForMutations([mutation]);
1659
+
1660
+ return dfd.promise;
1661
+ };
1662
+
1663
+ shutdown() {
1664
+ this._log.info('[shutdown]', this.config.appId);
1665
+ this._isShutdown = true;
1666
+ this._transport?.close();
1667
+ }
1668
+
1669
+ /**
1670
+ * Sends mutation to server and schedules a timeout to cancel it if
1671
+ * we don't hear back in time.
1672
+ * Note: If we're offline we don't schedule a timeout, we'll schedule it
1673
+ * later once we're back online and send the mutation again
1674
+ *
1675
+ */
1676
+ _sendMutation(eventId, mutation) {
1677
+ if (mutation.error) {
1678
+ this._handleMutationError('error', eventId, {
1679
+ message: mutation.error.message,
1680
+ });
1681
+ return;
1682
+ }
1683
+ if (this.status !== STATUS.AUTHENTICATED) {
1684
+ this._finishTransaction('enqueued', eventId);
1685
+ return;
1686
+ }
1687
+ const timeoutMs = Math.max(
1688
+ 6000,
1689
+ Math.min(
1690
+ this._inFlightMutationEventIds.size + 1,
1691
+ // Defensive code in case we don't clean up in flight mutation event ids
1692
+ this._pendingMutations().size + 1,
1693
+ ) * 6000,
1694
+ );
1695
+
1696
+ if (!this._isOnline) {
1697
+ this._finishTransaction('enqueued', eventId);
1698
+ } else {
1699
+ this._trySend(eventId, mutation);
1700
+
1701
+ setTimeout(() => {
1702
+ if (!this._isOnline) {
1703
+ return;
1704
+ }
1705
+ // If we are here, this means that we have sent this mutation, we are online
1706
+ // but we have not received a response. If it's this long, something must be wrong,
1707
+ // so we error with a timeout.
1708
+ this._handleMutationError('timeout', eventId, {
1709
+ message: 'transaction timed out',
1710
+ });
1711
+ }, timeoutMs);
1712
+ }
1713
+ }
1714
+
1715
+ // ---------------------------
1716
+ // Websocket
1717
+
1718
+ /** Send messages we accumulated while we were connecting */
1719
+ _flushPendingMessages() {
1720
+ const subs = Object.keys(this.queryCbs).map((hash) => {
1721
+ return this.querySubs.currentValue[hash];
1722
+ });
1723
+ // Note: we should not have any nulls in subs, but we're
1724
+ // doing this defensively just in case.
1725
+ const safeSubs = subs.filter((x) => x);
1726
+ safeSubs.forEach(({ eventId, q }) => {
1727
+ this._trySendAuthed(eventId, { op: 'add-query', q });
1728
+ });
1729
+
1730
+ Object.values(this.queryOnceDfds)
1731
+ .flat()
1732
+ .forEach(({ eventId, q }) => {
1733
+ this._trySendAuthed(eventId, { op: 'add-query', q });
1734
+ });
1735
+
1736
+ const rewrittenMutations = this._rewriteMutations(
1737
+ this.ensureAttrs(),
1738
+ this._pendingMutations(),
1739
+ );
1740
+ if (rewrittenMutations !== this._pendingMutations()) {
1741
+ // Persist rewritten mutations to avoid stale attr ids in future txs.
1742
+ this.kv.updateInPlace((prev) => {
1743
+ prev.pendingMutations = rewrittenMutations;
1744
+ });
1745
+ }
1746
+
1747
+ const muts = sortedMutationEntries(rewrittenMutations.entries());
1748
+ muts.forEach(([eventId, mut]) => {
1749
+ if (!mut['tx-id']) {
1750
+ this._sendMutation(eventId, mut);
1751
+ }
1752
+ });
1753
+
1754
+ this._syncTable.flushPending();
1755
+ }
1756
+
1757
+ /**
1758
+ * Clean up pendingMutations that all queries have seen
1759
+ */
1760
+ _cleanupPendingMutationsQueries() {
1761
+ let minProcessedTxId = Number.MAX_SAFE_INTEGER;
1762
+ for (const { result } of Object.values(this.querySubs.currentValue)) {
1763
+ if (result?.processedTxId) {
1764
+ minProcessedTxId = Math.min(minProcessedTxId, result?.processedTxId);
1765
+ }
1766
+ }
1767
+
1768
+ this._updatePendingMutations((prev) => {
1769
+ for (const [eventId, mut] of Array.from(prev.entries())) {
1770
+ if (mut['tx-id'] && mut['tx-id'] <= minProcessedTxId) {
1771
+ prev.delete(eventId);
1772
+ }
1773
+ }
1774
+ });
1775
+ }
1776
+
1777
+ /**
1778
+ * After mutations is confirmed by server, we give each query 30 sec
1779
+ * to update its results. If that doesn't happen, we assume query is
1780
+ * unaffected by this mutation and it’s safe to delete it from local queue
1781
+ */
1782
+ _cleanupPendingMutationsTimeout() {
1783
+ if (this._pendingMutations().size < this._pendingMutationCleanupThreshold) {
1784
+ return;
1785
+ }
1786
+
1787
+ const now = Date.now();
1788
+
1789
+ this._updatePendingMutations((prev) => {
1790
+ for (const [eventId, mut] of Array.from(prev.entries())) {
1791
+ if (
1792
+ mut.confirmed &&
1793
+ mut.confirmed + this._pendingTxCleanupTimeout < now
1794
+ ) {
1795
+ prev.delete(eventId);
1796
+ }
1797
+ }
1798
+ });
1799
+ }
1800
+
1801
+ _trySendAuthed(...args) {
1802
+ if (this.status !== STATUS.AUTHENTICATED) {
1803
+ return;
1804
+ }
1805
+ this._trySend(...args);
1806
+ }
1807
+
1808
+ _trySend(eventId, msg, opts) {
1809
+ if (!this._transport.isOpen()) {
1810
+ return;
1811
+ }
1812
+ if (!ignoreLogging[msg.op]) {
1813
+ this._log.info('[send]', this._transport.id, msg.op, {
1814
+ 'client-event-id': eventId,
1815
+ ...msg,
1816
+ });
1817
+ }
1818
+ switch (msg.op) {
1819
+ case 'transact': {
1820
+ this._inFlightMutationEventIds.add(eventId);
1821
+ break;
1822
+ }
1823
+ case 'init': {
1824
+ // New connection, so we can't have any mutations in flight
1825
+ this._inFlightMutationEventIds.clear();
1826
+ }
1827
+ }
1828
+ this._transport.send({ 'client-event-id': eventId, ...msg });
1829
+ }
1830
+
1831
+ _transportOnOpen = (e) => {
1832
+ const targetTransport = e.target;
1833
+ if (this._transport !== targetTransport) {
1834
+ this._log.info(
1835
+ '[socket][open]',
1836
+ targetTransport.id,
1837
+ 'skip; this is no longer the current transport',
1838
+ );
1839
+ return;
1840
+ }
1841
+ this._log.info('[socket][open]', this._transport.id);
1842
+ this._setStatus(STATUS.OPENED);
1843
+
1844
+ this.getCurrentUser()
1845
+ .then((resp) => {
1846
+ this._trySend(uuid(), {
1847
+ op: 'init',
1848
+ 'app-id': this.config.appId,
1849
+ 'refresh-token': resp.user?.['refresh_token'],
1850
+ versions: this.versions,
1851
+ // If an admin token is provided for an app, we will
1852
+ // skip all permission checks. This is an advanced feature,
1853
+ // to let users write internal tools
1854
+ // This option is not exposed in `Config`, as it's
1855
+ // not ready for prime time
1856
+ '__admin-token': this.config.__adminToken,
1857
+ });
1858
+ })
1859
+ .catch((e) => {
1860
+ this._log.error('[socket][error]', targetTransport.id, e);
1861
+ });
1862
+ };
1863
+
1864
+ _transportOnMessage = (e) => {
1865
+ const targetTransport = e.target;
1866
+ const m = e.message;
1867
+ if (this._transport !== targetTransport) {
1868
+ this._log.info(
1869
+ '[socket][message]',
1870
+ targetTransport.id,
1871
+ m,
1872
+ 'skip; this is no longer the current transport',
1873
+ );
1874
+ return;
1875
+ }
1876
+
1877
+ if (!this._wsOk && targetTransport.type === 'ws') {
1878
+ this._wsOk = true;
1879
+ }
1880
+ // Try to reconnect via websocket the next time we connect
1881
+ this._transportType = 'ws';
1882
+ if (Array.isArray(e.message)) {
1883
+ for (const msg of e.message) {
1884
+ this._handleReceive(targetTransport.id, msg);
1885
+ }
1886
+ } else {
1887
+ this._handleReceive(targetTransport.id, e.message);
1888
+ }
1889
+ };
1890
+
1891
+ _transportOnError = (e) => {
1892
+ const targetTransport = e.target;
1893
+ if (this._transport !== targetTransport) {
1894
+ this._log.info(
1895
+ '[socket][error]',
1896
+ targetTransport.id,
1897
+ 'skip; this is no longer the current transport',
1898
+ );
1899
+ return;
1900
+ }
1901
+ this._log.error('[socket][error]', targetTransport.id, e);
1902
+ };
1903
+
1904
+ _scheduleReconnect = () => {
1905
+ // If we couldn't connect with a websocket last time, try sse
1906
+ if (!this._wsOk && this._transportType !== 'sse') {
1907
+ this._transportType = 'sse';
1908
+ this._reconnectTimeoutMs = 0;
1909
+ }
1910
+ setTimeout(() => {
1911
+ this._reconnectTimeoutMs = Math.min(
1912
+ this._reconnectTimeoutMs + 1000,
1913
+ 10000,
1914
+ );
1915
+ if (!this._isOnline) {
1916
+ this._log.info(
1917
+ '[socket][close]',
1918
+ this._transport.id,
1919
+ 'we are offline, no need to start socket',
1920
+ );
1921
+ return;
1922
+ }
1923
+
1924
+ this._startSocket();
1925
+ }, this._reconnectTimeoutMs);
1926
+ };
1927
+
1928
+ _transportOnClose = (e) => {
1929
+ const targetTransport = e.target;
1930
+ if (this._transport !== targetTransport) {
1931
+ this._log.info(
1932
+ '[socket][close]',
1933
+ targetTransport.id,
1934
+ 'skip; this is no longer the current transport',
1935
+ );
1936
+ return;
1937
+ }
1938
+
1939
+ this._setStatus(STATUS.CLOSED);
1940
+
1941
+ for (const room of Object.values(this._rooms)) {
1942
+ room.isConnected = false;
1943
+ }
1944
+
1945
+ if (this._isShutdown) {
1946
+ this._log.info(
1947
+ '[socket][close]',
1948
+ targetTransport.id,
1949
+ 'Reactor has been shut down and will not reconnect',
1950
+ );
1951
+ return;
1952
+ }
1953
+ this._log.info(
1954
+ '[socket][close]',
1955
+ targetTransport.id,
1956
+ 'schedule reconnect, ms =',
1957
+ this._reconnectTimeoutMs,
1958
+ );
1959
+ this._scheduleReconnect();
1960
+ };
1961
+
1962
+ _startSocket() {
1963
+ // Reset whether we support websockets each time we connect
1964
+ // new networks may not support websockets
1965
+ this._wsOk = null;
1966
+ if (this._isShutdown) {
1967
+ this._log.info(
1968
+ '[socket][start]',
1969
+ this.config.appId,
1970
+ 'Reactor has been shut down and will not start a new socket',
1971
+ );
1972
+ return;
1973
+ }
1974
+ if (this._transport && this._transport.isConnecting()) {
1975
+ // Our current websocket is in a 'connecting' state.
1976
+ // There's no need to start another one, as the socket is
1977
+ // effectively fresh.
1978
+ this._log.info(
1979
+ '[socket][start]',
1980
+ this._transport.id,
1981
+ 'maintained as current transport, we were still in a connecting state',
1982
+ );
1983
+ return;
1984
+ }
1985
+ const prevTransport = this._transport;
1986
+ this._transport = createTransport({
1987
+ transportType: this._transportType,
1988
+ appId: this.config.appId,
1989
+ apiURI: this.config.apiURI,
1990
+ wsURI: this.config.websocketURI,
1991
+ EventSourceImpl: this._EventSource,
1992
+ });
1993
+ this._transport.onopen = this._transportOnOpen;
1994
+ this._transport.onmessage = this._transportOnMessage;
1995
+ this._transport.onclose = this._transportOnClose;
1996
+ this._transport.onerror = this._transportOnError;
1997
+ this._log.info('[socket][start]', this._transport.id);
1998
+ if (prevTransport?.isOpen()) {
1999
+ // When the network dies, it doesn't always mean that our
2000
+ // socket connection will fire a close event.
2001
+ //
2002
+ // We _could_ re-use the old socket, if the network drop was a
2003
+ // few seconds. But, to be safe right now we always create a new socket.
2004
+ //
2005
+ // This means that we have to make sure to kill the previous one ourselves.
2006
+ // c.f https://issues.chromium.org/issues/41343684
2007
+ this._log.info(
2008
+ '[socket][start]',
2009
+ this._transport.id,
2010
+ 'close previous transport id = ',
2011
+ prevTransport.id,
2012
+ );
2013
+ prevTransport.close();
2014
+ }
2015
+ }
2016
+
2017
+ /**
2018
+ * Given a key, returns a stable local id, unique to this device and app.
2019
+ *
2020
+ * This can be useful if you want to create guest ids for example.
2021
+ *
2022
+ * Note: If the user deletes their local storage, this id will change.
2023
+ *
2024
+ */
2025
+ async getLocalId(name) {
2026
+ const k = `localToken_${name}`;
2027
+ if (this.kv.currentValue[k]) {
2028
+ return this.kv.currentValue[k];
2029
+ }
2030
+
2031
+ const current = await this.kv.waitForKeyToLoad(k);
2032
+ if (current) {
2033
+ return current;
2034
+ }
2035
+ const newId = uuid();
2036
+ this.kv.updateInPlace((prev) => {
2037
+ if (prev[k]) return;
2038
+ prev[k] = newId;
2039
+ });
2040
+ return await this.kv.waitForKeyToLoad(k);
2041
+ }
2042
+
2043
+ // ----
2044
+ // Auth
2045
+ _replaceUrlAfterOAuth() {
2046
+ if (typeof URL === 'undefined') {
2047
+ return;
2048
+ }
2049
+ const url = new URL(window.location.href);
2050
+ if (url.searchParams.get(OAUTH_REDIRECT_PARAM)) {
2051
+ const startUrl = url.toString();
2052
+ url.searchParams.delete(OAUTH_REDIRECT_PARAM);
2053
+ url.searchParams.delete(OAUTH_EXTRA_FIELDS_ID_PARAM);
2054
+ url.searchParams.delete('code');
2055
+ url.searchParams.delete('error');
2056
+ const newPath =
2057
+ url.pathname +
2058
+ (url.searchParams.size ? '?' + url.searchParams : '') +
2059
+ url.hash;
2060
+ // Note: In next.js, this will revert to the old state if user navigates
2061
+ // back. We would need to allow framework specific routing to work
2062
+ // around that problem.
2063
+ history.replaceState(history.state, '', newPath);
2064
+
2065
+ // navigation is part of the HTML spec, but not supported by Safari
2066
+ // or Firefox yet:
2067
+ // https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API#browser_compatibility
2068
+ if (
2069
+ // @ts-ignore (waiting for ts support)
2070
+ typeof navigation === 'object' &&
2071
+ // @ts-ignore (waiting for ts support)
2072
+ typeof navigation.addEventListener === 'function' &&
2073
+ // @ts-ignore (waiting for ts support)
2074
+ typeof navigation.removeEventListener === 'function'
2075
+ ) {
2076
+ let ran = false;
2077
+
2078
+ // The next.js app router will reset the URL when the router loads.
2079
+ // This puts it back after the router loads.
2080
+ const listener = (e) => {
2081
+ if (!ran) {
2082
+ ran = true;
2083
+ // @ts-ignore (waiting for ts support)
2084
+ navigation.removeEventListener('navigate', listener);
2085
+ if (
2086
+ !e.userInitiated &&
2087
+ e.navigationType === 'replace' &&
2088
+ e.destination?.url === startUrl
2089
+ ) {
2090
+ history.replaceState(history.state, '', newPath);
2091
+ }
2092
+ }
2093
+ };
2094
+ // @ts-ignore (waiting for ts support)
2095
+ navigation.addEventListener('navigate', listener);
2096
+ }
2097
+ }
2098
+ }
2099
+
2100
+ /**
2101
+ *
2102
+ * @returns Promise<null | {error: {message: string}}>
2103
+ */
2104
+ async _oauthLoginInit() {
2105
+ if (
2106
+ typeof window === 'undefined' ||
2107
+ typeof window.location === 'undefined' ||
2108
+ typeof URLSearchParams === 'undefined'
2109
+ ) {
2110
+ return null;
2111
+ }
2112
+ const params = new URLSearchParams(window.location.search);
2113
+ if (!params.get(OAUTH_REDIRECT_PARAM)) {
2114
+ return null;
2115
+ }
2116
+
2117
+ const error = params.get('error');
2118
+ if (error) {
2119
+ this._replaceUrlAfterOAuth();
2120
+ return { error: { message: error } };
2121
+ }
2122
+ const code = params.get('code');
2123
+ if (!code) {
2124
+ return null;
2125
+ }
2126
+ const extraFieldsId = params.get(OAUTH_EXTRA_FIELDS_ID_PARAM);
2127
+ this._replaceUrlAfterOAuth();
2128
+ try {
2129
+ let extraFields;
2130
+ const stored = await this.kv.waitForKeyToLoad(oauthExtraFieldsKey);
2131
+ if (extraFieldsId && stored) {
2132
+ extraFields = stored[extraFieldsId];
2133
+ }
2134
+ // Clean up all stored extraFields after login
2135
+ if (stored) {
2136
+ this.kv.updateInPlace((prev) => {
2137
+ delete prev[oauthExtraFieldsKey];
2138
+ });
2139
+ }
2140
+ const currentUser = await this._getCurrentUser();
2141
+ const isGuest = currentUser?.type === 'guest';
2142
+ const { user } = await authAPI.exchangeCodeForToken({
2143
+ apiURI: this.config.apiURI,
2144
+ appId: this.config.appId,
2145
+ code,
2146
+ refreshToken: isGuest ? currentUser.refresh_token : undefined,
2147
+ extraFields,
2148
+ });
2149
+ this.setCurrentUser(user);
2150
+ return null;
2151
+ } catch (e) {
2152
+ if (
2153
+ e?.body?.type === 'record-not-found' &&
2154
+ e?.body?.hint?.['record-type'] === 'app-oauth-code' &&
2155
+ (await this._hasCurrentUser())
2156
+ ) {
2157
+ // We probably just weren't able to clean up the URL, so
2158
+ // let's just ignore this error
2159
+ return null;
2160
+ }
2161
+ const message = e?.body?.message || 'Error logging in.';
2162
+ return { error: { message } };
2163
+ }
2164
+ }
2165
+
2166
+ async _waitForOAuthCallbackResponse() {
2167
+ return await this._oauthCallbackResponse;
2168
+ }
2169
+
2170
+ __subscribeMutationErrors(cb) {
2171
+ this.mutationErrorCbs.push(cb);
2172
+
2173
+ return () => {
2174
+ this.mutationErrorCbs = this.mutationErrorCbs.filter((x) => x !== cb);
2175
+ };
2176
+ }
2177
+
2178
+ subscribeAuth(cb) {
2179
+ this.authCbs.push(cb);
2180
+ const currUserCached = this._currentUserCached;
2181
+ if (!currUserCached.isLoading) {
2182
+ cb(this._currentUserCached);
2183
+ }
2184
+ let unsubbed = false;
2185
+ this.getCurrentUser().then((resp) => {
2186
+ if (unsubbed) return;
2187
+ if (areObjectsDeepEqual(resp, currUserCached)) return;
2188
+ cb(resp);
2189
+ });
2190
+ return () => {
2191
+ unsubbed = true;
2192
+ this.authCbs = this.authCbs.filter((x) => x !== cb);
2193
+ };
2194
+ }
2195
+
2196
+ async getAuth() {
2197
+ const { user, error } = await this.getCurrentUser();
2198
+ if (error) {
2199
+ throw new InstantError('Could not get current user: ' + error.message);
2200
+ }
2201
+ return user ?? null;
2202
+ }
2203
+
2204
+ subscribeConnectionStatus(cb) {
2205
+ this.connectionStatusCbs.push(cb);
2206
+
2207
+ return () => {
2208
+ this.connectionStatusCbs = this.connectionStatusCbs.filter(
2209
+ (x) => x !== cb,
2210
+ );
2211
+ };
2212
+ }
2213
+
2214
+ /**
2215
+ * @param {'active' | 'read-only' | 'disabled' | undefined} status
2216
+ */
2217
+ _setAppStatus(status) {
2218
+ if (!status || status === this._appStatusState.status) return;
2219
+ this._appStatusState = {
2220
+ isLoading: false,
2221
+ isReadOnly: status !== 'active',
2222
+ status,
2223
+ };
2224
+ this.notifyAppStatusSubs(this._appStatusState);
2225
+ }
2226
+
2227
+ subscribeAppStatus(cb) {
2228
+ this.appStatusCbs.push(cb);
2229
+ cb(this._appStatusState);
2230
+
2231
+ return () => {
2232
+ this.appStatusCbs = this.appStatusCbs.filter((x) => x !== cb);
2233
+ };
2234
+ }
2235
+
2236
+ subscribeAttrs(cb) {
2237
+ this.attrsCbs.push(cb);
2238
+
2239
+ if (this.attrs) {
2240
+ cb(this.attrs.attrs);
2241
+ }
2242
+
2243
+ return () => {
2244
+ this.attrsCbs = this.attrsCbs.filter((x) => x !== cb);
2245
+ };
2246
+ }
2247
+
2248
+ notifyAuthSubs(user) {
2249
+ this.authCbs.forEach((cb) => cb(user));
2250
+ }
2251
+
2252
+ notifyMutationErrorSubs(error) {
2253
+ this.mutationErrorCbs.forEach((cb) => cb(error));
2254
+ }
2255
+
2256
+ notifyAttrsSubs() {
2257
+ if (!this.attrs) return;
2258
+ const oas = this.optimisticAttrs();
2259
+ this.attrsCbs.forEach((cb) => cb(oas.attrs));
2260
+ }
2261
+
2262
+ notifyConnectionStatusSubs(status) {
2263
+ this.connectionStatusCbs.forEach((cb) => cb(status));
2264
+ }
2265
+
2266
+ notifyAppStatusSubs(state) {
2267
+ this.appStatusCbs.forEach((cb) => cb(state));
2268
+ }
2269
+
2270
+ async setCurrentUser(user) {
2271
+ this.kv.updateInPlace((prev) => {
2272
+ prev[currentUserKey] = user;
2273
+ });
2274
+ await this.kv.waitForKeyToLoad(currentUserKey);
2275
+ }
2276
+
2277
+ getCurrentUserCached() {
2278
+ return this._currentUserCached;
2279
+ }
2280
+
2281
+ /**
2282
+ * @param {{ forceReadFromStorage?: boolean }} [opts]
2283
+ * @returns {Promise<User | undefined>}
2284
+ */
2285
+ async _getCurrentUser(opts) {
2286
+ if (opts?.forceReadFromStorage) {
2287
+ await this.kv.unloadKey(currentUserKey);
2288
+ }
2289
+ const user = await this.kv.waitForKeyToLoad(currentUserKey);
2290
+ return typeof user === 'string' ? JSON.parse(user) : user;
2291
+ }
2292
+
2293
+ /**
2294
+ * @param {{ forceReadFromStorage?: boolean }} [opts]
2295
+ * @returns {Promise<AuthState>}
2296
+ */
2297
+ async getCurrentUser(opts) {
2298
+ const oauthResp = await this._waitForOAuthCallbackResponse();
2299
+ if (oauthResp?.error) {
2300
+ const errorV = { error: oauthResp.error, user: undefined };
2301
+ this._currentUserCached = { isLoading: false, ...errorV };
2302
+ return this._currentUserCached;
2303
+ }
2304
+ try {
2305
+ const user = await this._getCurrentUser(opts);
2306
+ const userV = { user: user, error: undefined };
2307
+ this._currentUserCached = {
2308
+ isLoading: false,
2309
+ ...userV,
2310
+ };
2311
+ return this._currentUserCached;
2312
+ } catch (e) {
2313
+ return {
2314
+ user: undefined,
2315
+ isLoading: false,
2316
+ error: { message: e?.message || 'Error loading user' },
2317
+ };
2318
+ }
2319
+ }
2320
+
2321
+ async _hasCurrentUser() {
2322
+ const user = await this.kv.waitForKeyToLoad(currentUserKey);
2323
+ return typeof user === 'string' ? JSON.parse(user) != null : user != null;
2324
+ }
2325
+
2326
+ async changeCurrentUser(newUser) {
2327
+ const { user: oldUser } = await this.getCurrentUser();
2328
+ if (areObjectsDeepEqual(oldUser, newUser)) {
2329
+ // We were already logged in as the newUser, don't
2330
+ // bother updating
2331
+ return;
2332
+ }
2333
+
2334
+ // Clear any data in the framework client
2335
+ this._frameworkClient = null;
2336
+ await this.setCurrentUser(newUser);
2337
+ // We need to remove all `result` from querySubs,
2338
+ // as they are no longer valid for the new user
2339
+ await this.updateUser(newUser);
2340
+
2341
+ try {
2342
+ // Make sure everything is written to storage before we tell the
2343
+ // other tab to refetch
2344
+ await this.kv.flush();
2345
+ this._broadcastChannel?.postMessage({ type: 'auth' });
2346
+ } catch (error) {
2347
+ console.error('Error posting message to broadcast channel', error);
2348
+ }
2349
+ }
2350
+
2351
+ async setupUserSyncTimer() {
2352
+ if (!this.config.firstPartyPath) return;
2353
+ try {
2354
+ const lastSynced = await this.kv.waitForKeyToLoad(
2355
+ COOKIE_SYNC_LAST_UPDATED_KEY,
2356
+ );
2357
+ const lastSyncTime = lastSynced ? new Date(lastSynced).getTime() : 0;
2358
+ const shouldSync =
2359
+ !Number.isFinite(lastSyncTime) ||
2360
+ Date.now() - lastSyncTime >= ONE_DAY_MS;
2361
+ if (!shouldSync) return;
2362
+
2363
+ const { user } = await this.getCurrentUser();
2364
+ await this.syncUserToEndpoint(user ?? null);
2365
+ } catch (error) {
2366
+ this._log.error('Error syncing user cookie on startup', error);
2367
+ }
2368
+ }
2369
+
2370
+ async syncUserToEndpoint(user) {
2371
+ if (!this.config.firstPartyPath) return;
2372
+ try {
2373
+ const response = await fetch(this.config.firstPartyPath + '/', {
2374
+ method: 'POST',
2375
+ body: JSON.stringify({
2376
+ type: 'sync-user',
2377
+ appId: this.config.appId,
2378
+ user: user,
2379
+ }),
2380
+ headers: {
2381
+ 'Content-Type': 'application/json',
2382
+ },
2383
+ });
2384
+ if (!response.ok) {
2385
+ throw new Error(`HTTP error! status: ${response.status}`);
2386
+ }
2387
+ } catch (error) {
2388
+ this._log.error('Error syncing user with external endpoint', error);
2389
+ }
2390
+
2391
+ this.kv.updateInPlace((prev) => {
2392
+ prev[COOKIE_SYNC_LAST_UPDATED_KEY] = new Date().toISOString();
2393
+ });
2394
+ }
2395
+
2396
+ async updateUser(newUser) {
2397
+ const newV = { error: undefined, user: newUser };
2398
+ this._currentUserCached = { isLoading: false, ...newV };
2399
+ this._dataForQueryCache = {};
2400
+ this._dataForQueryMemo = {};
2401
+ this.querySubs.updateInPlace((prev) => {
2402
+ Object.keys(prev).forEach((k) => {
2403
+ delete prev[k].result;
2404
+ });
2405
+ });
2406
+ this.querySubs.clearUnloadedKeys();
2407
+ this._updatePendingMutations((prev) => {
2408
+ // Mark all pending mutations with an error, since we won't be able to
2409
+ // deliver the result
2410
+ for (const [eventId, _v] of prev.entries()) {
2411
+ if (this.mutationDeferredStore.get(eventId)) {
2412
+ this._finishTransaction('error', eventId, {
2413
+ message: 'User changed while transaction was in progress.',
2414
+ type: 'user-changed',
2415
+ });
2416
+ }
2417
+ }
2418
+
2419
+ prev.clear();
2420
+ });
2421
+
2422
+ this._reconnectTimeoutMs = 0;
2423
+ this._transport.close();
2424
+ this._oauthCallbackResponse = null;
2425
+ this.notifyAuthSubs(newV);
2426
+ try {
2427
+ await this.syncUserToEndpoint(newUser);
2428
+ } catch (error) {
2429
+ this._log.error('Error syncing user with external endpoint', error);
2430
+ }
2431
+ }
2432
+
2433
+ sendMagicCode({ email }) {
2434
+ return authAPI.sendMagicCode({
2435
+ apiURI: this.config.apiURI,
2436
+ appId: this.config.appId,
2437
+ email: email,
2438
+ });
2439
+ }
2440
+
2441
+ async signInWithMagicCode(params) {
2442
+ const currentUser = await this.getCurrentUser();
2443
+ const isGuest = currentUser?.user?.type === 'guest';
2444
+ const res = await authAPI.checkMagicCode({
2445
+ apiURI: this.config.apiURI,
2446
+ appId: this.config.appId,
2447
+ email: params.email,
2448
+ code: params.code,
2449
+ refreshToken: isGuest ? currentUser?.user?.refresh_token : undefined,
2450
+ extraFields: params.extraFields,
2451
+ });
2452
+ await this.changeCurrentUser(res.user);
2453
+ return res;
2454
+ }
2455
+
2456
+ async signInWithCustomToken(authToken) {
2457
+ const res = await authAPI.verifyRefreshToken({
2458
+ apiURI: this.config.apiURI,
2459
+ appId: this.config.appId,
2460
+ refreshToken: authToken,
2461
+ });
2462
+ await this.changeCurrentUser(res.user);
2463
+ return res;
2464
+ }
2465
+
2466
+ async signInAsGuest(params) {
2467
+ const res = await authAPI.signInAsGuest({
2468
+ apiURI: this.config.apiURI,
2469
+ appId: this.config.appId,
2470
+ extraFields: params?.extraFields,
2471
+ });
2472
+ await this.changeCurrentUser(res.user);
2473
+ return res;
2474
+ }
2475
+
2476
+ potentiallyInvalidateToken(currentUser, opts) {
2477
+ const refreshToken = currentUser?.user?.refresh_token;
2478
+ if (!refreshToken) {
2479
+ return;
2480
+ }
2481
+ const wantsToSkip = opts.invalidateToken === false;
2482
+ if (wantsToSkip) {
2483
+ this._log.info('[auth-invalidate] skipped invalidateToken');
2484
+ return;
2485
+ }
2486
+ authAPI
2487
+ .signOut({
2488
+ apiURI: this.config.apiURI,
2489
+ appId: this.config.appId,
2490
+ refreshToken,
2491
+ })
2492
+ .then(() => {
2493
+ this._log.info('[auth-invalidate] completed invalidateToken');
2494
+ })
2495
+ .catch((e) => {});
2496
+ }
2497
+
2498
+ async signOut(opts) {
2499
+ const currentUser = await this.getCurrentUser();
2500
+ this.potentiallyInvalidateToken(currentUser, opts);
2501
+ await this.changeCurrentUser(null);
2502
+ }
2503
+
2504
+ /**
2505
+ * Creates an OAuth authorization URL.
2506
+ *
2507
+ * @param {Object} params - The parameters to create the authorization URL.
2508
+ * @param {string} params.clientName - The name of the client requesting authorization.
2509
+ * @param {string} params.redirectURL - The URL to redirect users to after authorization.
2510
+ * @param {Record<string, any>} [params.extraFields] - Extra fields to write to $users on creation
2511
+ * @returns {string} The created authorization URL.
2512
+ */
2513
+ createAuthorizationURL({ clientName, redirectURL, extraFields }) {
2514
+ const { apiURI, appId } = this.config;
2515
+ let finalRedirectURL = redirectURL;
2516
+ if (extraFields) {
2517
+ // Store extraFields under a unique ID so multiple
2518
+ // createAuthorizationURL calls don't overwrite each other.
2519
+ // The ID is passed through the redirect URL and used
2520
+ // by _oauthLoginInit to retrieve the right extraFields.
2521
+ // All entries are cleaned up after login.
2522
+ const extraFieldsId = `${Math.random().toString(36).slice(2)}`;
2523
+ this.kv.updateInPlace((prev) => {
2524
+ const stored = prev[oauthExtraFieldsKey] || {};
2525
+ stored[extraFieldsId] = extraFields;
2526
+ prev[oauthExtraFieldsKey] = stored;
2527
+ });
2528
+ finalRedirectURL = `${redirectURL}${redirectURL.includes('?') ? '&' : '?'}${OAUTH_EXTRA_FIELDS_ID_PARAM}=${extraFieldsId}`;
2529
+ }
2530
+ return `${apiURI}/runtime/oauth/start?app_id=${appId}&client_name=${clientName}&redirect_uri=${encodeURIComponent(finalRedirectURL)}`;
2531
+ }
2532
+
2533
+ /**
2534
+ * @param {Object} params
2535
+ * @param {string} params.code - The code received from the OAuth service.
2536
+ * @param {string} [params.codeVerifier] - The code verifier used to generate the code challenge.
2537
+ * @param {Record<string, any>} [params.extraFields] - Extra fields to write to $users on creation
2538
+ */
2539
+ async exchangeCodeForToken({ code, codeVerifier, extraFields }) {
2540
+ const currentUser = await this.getCurrentUser();
2541
+ const isGuest = currentUser?.user?.type === 'guest';
2542
+ const res = await authAPI.exchangeCodeForToken({
2543
+ apiURI: this.config.apiURI,
2544
+ appId: this.config.appId,
2545
+ code: code,
2546
+ codeVerifier,
2547
+ refreshToken: isGuest ? currentUser?.user?.refresh_token : undefined,
2548
+ extraFields,
2549
+ });
2550
+ await this.changeCurrentUser(res.user);
2551
+ return res;
2552
+ }
2553
+
2554
+ issuerURI() {
2555
+ const { apiURI, appId } = this.config;
2556
+ return `${apiURI}/runtime/${appId}`;
2557
+ }
2558
+
2559
+ /**
2560
+ * @param {Object} params
2561
+ * @param {string} params.clientName - The name of the client requesting authorization.
2562
+ * @param {string} params.idToken - The id_token from the external service
2563
+ * @param {string | null | undefined} [params.nonce] - The nonce used when requesting the id_token from the external service
2564
+ * @param {Record<string, any>} [params.extraFields] - Extra fields to write to $users on creation
2565
+ */
2566
+ async signInWithIdToken(params) {
2567
+ const currentUser = await this.getCurrentUser();
2568
+ const refreshToken = currentUser?.user?.refresh_token;
2569
+
2570
+ const res = await authAPI.signInWithIdToken({
2571
+ apiURI: this.config.apiURI,
2572
+ appId: this.config.appId,
2573
+ idToken: params.idToken,
2574
+ clientName: params.clientName,
2575
+ nonce: params.nonce,
2576
+ refreshToken,
2577
+ extraFields: params.extraFields,
2578
+ });
2579
+ await this.changeCurrentUser(res.user);
2580
+ return res;
2581
+ }
2582
+
2583
+ // --------
2584
+ // Rooms
2585
+
2586
+ /**
2587
+ * @param {string} roomType
2588
+ * @param {string} roomId
2589
+ * @param {any | null | undefined} [initialPresence] -- initial presence data to send when joining the room
2590
+ * @returns () => void
2591
+ */
2592
+ joinRoom(roomType, roomId, initialPresence) {
2593
+ let needsToSendJoin = false;
2594
+ if (!this._rooms[roomId]) {
2595
+ needsToSendJoin = true;
2596
+ this._rooms[roomId] = {
2597
+ roomType,
2598
+ isConnected: false,
2599
+ error: undefined,
2600
+ };
2601
+ }
2602
+
2603
+ this._presence[roomId] = this._presence[roomId] || {};
2604
+ const previousResult = this._presence[roomId].result;
2605
+ if (initialPresence && !previousResult) {
2606
+ this._presence[roomId].result = this._presence[roomId].result || {};
2607
+ this._presence[roomId].result.user = initialPresence;
2608
+ this._notifyPresenceSubs(roomId);
2609
+ }
2610
+
2611
+ if (needsToSendJoin) {
2612
+ this._tryJoinRoom(roomType, roomId, initialPresence);
2613
+ }
2614
+
2615
+ return () => {
2616
+ this._cleanupRoom(roomId);
2617
+ };
2618
+ }
2619
+
2620
+ _cleanupRoom(roomId) {
2621
+ if (
2622
+ !this._presence[roomId]?.handlers?.length &&
2623
+ !Object.keys(this._broadcastSubs[roomId] ?? {}).length
2624
+ ) {
2625
+ const isConnected = this._rooms[roomId]?.isConnected;
2626
+
2627
+ delete this._rooms[roomId];
2628
+ delete this._presence[roomId];
2629
+ delete this._broadcastSubs[roomId];
2630
+
2631
+ if (isConnected) {
2632
+ this._tryLeaveRoom(roomId);
2633
+ } else {
2634
+ this._roomsPendingLeave[roomId] = true;
2635
+ }
2636
+ }
2637
+ }
2638
+
2639
+ // --------
2640
+ // Presence
2641
+
2642
+ // TODO: look into typing again
2643
+ getPresence(roomType, roomId, opts = {}) {
2644
+ const room = this._rooms[roomId];
2645
+ const presence = this._presence[roomId];
2646
+ if (!room || !presence || !presence.result) return null;
2647
+
2648
+ return {
2649
+ ...buildPresenceSlice(presence.result, opts, this._sessionId),
2650
+ isLoading: !room.isConnected,
2651
+ error: room.error,
2652
+ };
2653
+ }
2654
+
2655
+ // TODO: look into typing again
2656
+ publishPresence(roomType, roomId, partialData) {
2657
+ const room = this._rooms[roomId];
2658
+ const presence = this._presence[roomId];
2659
+
2660
+ if (!room || !presence) {
2661
+ return;
2662
+ }
2663
+
2664
+ presence.result = presence.result || {};
2665
+ const data = {
2666
+ ...presence.result.user,
2667
+ ...partialData,
2668
+ };
2669
+
2670
+ presence.result.user = data;
2671
+
2672
+ if (!room.isConnected) {
2673
+ return;
2674
+ }
2675
+
2676
+ this._trySetPresence(roomId, data);
2677
+ this._notifyPresenceSubs(roomId);
2678
+ }
2679
+
2680
+ _trySetPresence(roomId, data) {
2681
+ this._trySendAuthed(uuid(), {
2682
+ op: 'set-presence',
2683
+ 'room-id': roomId,
2684
+ data,
2685
+ });
2686
+ }
2687
+
2688
+ _tryJoinRoom(roomType, roomId, data) {
2689
+ this._trySendAuthed(uuid(), {
2690
+ op: 'join-room',
2691
+ 'room-type': roomType,
2692
+ 'room-id': roomId,
2693
+ data,
2694
+ });
2695
+ delete this._roomsPendingLeave[roomId];
2696
+ }
2697
+
2698
+ _tryLeaveRoom(roomId) {
2699
+ this._trySendAuthed(uuid(), { op: 'leave-room', 'room-id': roomId });
2700
+ }
2701
+
2702
+ _trySetRoomConnected(roomId, isConnected) {
2703
+ const room = this._rooms[roomId];
2704
+ if (room) {
2705
+ room.isConnected = isConnected;
2706
+ }
2707
+ }
2708
+
2709
+ // TODO: look into typing again
2710
+ subscribePresence(roomType, roomId, opts, cb) {
2711
+ const leaveRoom = this.joinRoom(
2712
+ roomType,
2713
+ roomId,
2714
+ // Oct 28, 2025
2715
+ // Note: initialData is deprecated.
2716
+ // Keeping here for backwards compatibility
2717
+ opts.initialPresence || opts.initialData,
2718
+ );
2719
+
2720
+ const handler = { ...opts, roomId, cb, prev: null };
2721
+
2722
+ this._presence[roomId] = this._presence[roomId] || {};
2723
+ this._presence[roomId].handlers = this._presence[roomId].handlers || [];
2724
+ this._presence[roomId].handlers.push(handler);
2725
+
2726
+ this._notifyPresenceSub(roomId, handler);
2727
+
2728
+ return () => {
2729
+ this._presence[roomId].handlers =
2730
+ this._presence[roomId]?.handlers?.filter((x) => x !== handler) ?? [];
2731
+
2732
+ leaveRoom();
2733
+ };
2734
+ }
2735
+
2736
+ _notifyPresenceSubs(roomId) {
2737
+ this._presence[roomId]?.handlers?.forEach((handler) => {
2738
+ this._notifyPresenceSub(roomId, handler);
2739
+ });
2740
+ }
2741
+
2742
+ _notifyPresenceSub(roomId, handler) {
2743
+ const slice = this.getPresence('', roomId, handler);
2744
+
2745
+ if (!slice) {
2746
+ return;
2747
+ }
2748
+
2749
+ if (handler.prev && !hasPresenceResponseChanged(slice, handler.prev)) {
2750
+ return;
2751
+ }
2752
+
2753
+ handler.prev = slice;
2754
+ handler.cb(slice);
2755
+ }
2756
+
2757
+ _patchPresencePeers(roomId, edits) {
2758
+ const peers = this._presence[roomId]?.result?.peers || {};
2759
+ let sessions = Object.fromEntries(
2760
+ Object.entries(peers).map(([k, v]) => [k, { data: v }]),
2761
+ );
2762
+ const myPresence = this._presence[roomId]?.result;
2763
+ const newSessions = create(sessions, (draft) => {
2764
+ for (let [path, op, value] of edits) {
2765
+ switch (op) {
2766
+ case '+':
2767
+ insertInMutative(draft, path, value);
2768
+ break;
2769
+ case 'r':
2770
+ assocInMutative(draft, path, value);
2771
+ break;
2772
+ case '-':
2773
+ dissocInMutative(draft, path);
2774
+ break;
2775
+ }
2776
+ }
2777
+ // Ignore our own edits
2778
+ delete draft[this._sessionId];
2779
+ });
2780
+
2781
+ this._setPresencePeers(roomId, newSessions);
2782
+ }
2783
+
2784
+ _setPresencePeers(roomId, data) {
2785
+ const sessions = { ...data };
2786
+ // no need to keep track of `user`
2787
+ delete sessions[this._sessionId];
2788
+ const peers = Object.fromEntries(
2789
+ Object.entries(sessions).map(([k, v]) => [k, v.data]),
2790
+ );
2791
+
2792
+ this._presence = create(this._presence, (draft) => {
2793
+ assocInMutative(draft, [roomId, 'result', 'peers'], peers);
2794
+ });
2795
+ }
2796
+
2797
+ // --------
2798
+ // Broadcast
2799
+
2800
+ publishTopic({ roomType, roomId, topic, data }) {
2801
+ const room = this._rooms[roomId];
2802
+
2803
+ if (!room) {
2804
+ return;
2805
+ }
2806
+
2807
+ if (!room.isConnected) {
2808
+ this._broadcastQueue[roomId] = this._broadcastQueue[roomId] ?? [];
2809
+ this._broadcastQueue[roomId].push({ topic, roomType, data });
2810
+
2811
+ return;
2812
+ }
2813
+
2814
+ this._tryBroadcast(roomId, roomType, topic, data);
2815
+ }
2816
+
2817
+ _tryBroadcast(roomId, roomType, topic, data) {
2818
+ this._trySendAuthed(uuid(), {
2819
+ op: 'client-broadcast',
2820
+ 'room-id': roomId,
2821
+ roomType,
2822
+ topic,
2823
+ data,
2824
+ });
2825
+ }
2826
+
2827
+ subscribeTopic(roomType, roomId, topic, cb) {
2828
+ const leaveRoom = this.joinRoom(roomType, roomId);
2829
+
2830
+ this._broadcastSubs[roomId] = this._broadcastSubs[roomId] || {};
2831
+ this._broadcastSubs[roomId][topic] =
2832
+ this._broadcastSubs[roomId][topic] || [];
2833
+ this._broadcastSubs[roomId][topic].push(cb);
2834
+ this._presence[roomId] = this._presence[roomId] || {};
2835
+
2836
+ return () => {
2837
+ this._broadcastSubs[roomId][topic] = this._broadcastSubs[roomId][
2838
+ topic
2839
+ ].filter((x) => x !== cb);
2840
+
2841
+ if (!this._broadcastSubs[roomId][topic].length) {
2842
+ delete this._broadcastSubs[roomId][topic];
2843
+ }
2844
+
2845
+ leaveRoom();
2846
+ };
2847
+ }
2848
+
2849
+ _notifyBroadcastSubs(room, topic, msg) {
2850
+ this._broadcastSubs?.[room]?.[topic]?.forEach((cb) => {
2851
+ const data = msg.data?.data;
2852
+
2853
+ const peer =
2854
+ msg.data['peer-id'] === this._sessionId
2855
+ ? this._presence[room]?.result?.user
2856
+ : this._presence[room]?.result?.peers?.[msg.data['peer-id']];
2857
+
2858
+ return cb(data, peer);
2859
+ });
2860
+ }
2861
+
2862
+ // --------
2863
+ // Storage
2864
+
2865
+ async uploadFile(path, file, opts) {
2866
+ const currentUser = await this.getCurrentUser();
2867
+ const refreshToken = currentUser?.user?.refresh_token;
2868
+ return StorageApi.uploadFile({
2869
+ ...opts,
2870
+ apiURI: this.config.apiURI,
2871
+ appId: this.config.appId,
2872
+ path: path,
2873
+ file,
2874
+ refreshToken: refreshToken,
2875
+ });
2876
+ }
2877
+
2878
+ async deleteFile(path) {
2879
+ const currentUser = await this.getCurrentUser();
2880
+ const refreshToken = currentUser?.user?.refresh_token;
2881
+ const result = await StorageApi.deleteFile({
2882
+ apiURI: this.config.apiURI,
2883
+ appId: this.config.appId,
2884
+ path,
2885
+ refreshToken: refreshToken,
2886
+ });
2887
+
2888
+ return result;
2889
+ }
2890
+
2891
+ // Deprecated Storage API (Jan 2025)
2892
+ // ---------------------------------
2893
+
2894
+ async upload(path, file) {
2895
+ const currentUser = await this.getCurrentUser();
2896
+ const refreshToken = currentUser?.user?.refresh_token;
2897
+ const fileName = path || file.name;
2898
+ const url = await StorageApi.getSignedUploadUrl({
2899
+ apiURI: this.config.apiURI,
2900
+ appId: this.config.appId,
2901
+ fileName: fileName,
2902
+ refreshToken: refreshToken,
2903
+ });
2904
+ const isSuccess = await StorageApi.upload(url, file);
2905
+
2906
+ return isSuccess;
2907
+ }
2908
+
2909
+ async getDownloadUrl(path) {
2910
+ const currentUser = await this.getCurrentUser();
2911
+ const refreshToken = currentUser?.user?.refresh_token;
2912
+ const url = await StorageApi.getDownloadUrl({
2913
+ apiURI: this.config.apiURI,
2914
+ appId: this.config.appId,
2915
+ path: path,
2916
+ refreshToken: refreshToken,
2917
+ });
2918
+
2919
+ return url;
2920
+ }
2921
+ }