@multiplatform.one/frappe 9.17.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (597) hide show
  1. package/dist/cjs/auth.cjs +34 -44
  2. package/dist/cjs/auth.native.cjs +97 -0
  3. package/dist/cjs/auth.native.js +77 -82
  4. package/dist/cjs/auth.native.js.map +1 -1
  5. package/dist/cjs/call.cjs +31 -35
  6. package/dist/cjs/call.native.cjs +92 -0
  7. package/dist/cjs/call.native.js +72 -71
  8. package/dist/cjs/call.native.js.map +1 -1
  9. package/dist/cjs/collection.cjs +243 -287
  10. package/dist/cjs/collection.native.cjs +461 -0
  11. package/dist/cjs/collection.native.js +436 -499
  12. package/dist/cjs/collection.native.js.map +1 -1
  13. package/dist/cjs/common/types.cjs +9 -11
  14. package/dist/cjs/common/types.native.cjs +18 -0
  15. package/dist/cjs/common/types.native.js +9 -10
  16. package/dist/cjs/common/types.native.js.map +1 -1
  17. package/dist/cjs/connectionKey.cjs +18 -22
  18. package/dist/cjs/connectionKey.native.cjs +32 -0
  19. package/dist/cjs/connectionKey.native.js +19 -22
  20. package/dist/cjs/connectionKey.native.js.map +1 -1
  21. package/dist/cjs/core/http.cjs +404 -407
  22. package/dist/cjs/core/http.native.cjs +659 -0
  23. package/dist/cjs/core/http.native.js +611 -615
  24. package/dist/cjs/core/http.native.js.map +1 -1
  25. package/dist/cjs/core/serverMessages.cjs +48 -43
  26. package/dist/cjs/core/serverMessages.native.cjs +89 -0
  27. package/dist/cjs/core/serverMessages.native.js +69 -70
  28. package/dist/cjs/core/serverMessages.native.js.map +1 -1
  29. package/dist/cjs/core/sessionGate.cjs +94 -97
  30. package/dist/cjs/core/sessionGate.native.cjs +270 -0
  31. package/dist/cjs/core/sessionGate.native.js +220 -232
  32. package/dist/cjs/core/sessionGate.native.js.map +1 -1
  33. package/dist/cjs/core/types.cjs +37 -39
  34. package/dist/cjs/core/types.native.cjs +169 -0
  35. package/dist/cjs/core/types.native.js +129 -136
  36. package/dist/cjs/core/types.native.js.map +1 -1
  37. package/dist/cjs/core/wire.cjs +28 -30
  38. package/dist/cjs/core/wire.native.cjs +53 -0
  39. package/dist/cjs/core/wire.native.js +28 -29
  40. package/dist/cjs/core/wire.native.js.map +1 -1
  41. package/dist/cjs/db.cjs +434 -449
  42. package/dist/cjs/db.native.cjs +625 -0
  43. package/dist/cjs/db.native.js +583 -590
  44. package/dist/cjs/db.native.js.map +1 -1
  45. package/dist/cjs/devtools/FrappeDevtoolsPanel.cjs +774 -799
  46. package/dist/cjs/devtools/FrappeDevtoolsPanel.native.cjs +878 -0
  47. package/dist/cjs/devtools/FrappeDevtoolsPanel.native.js +821 -862
  48. package/dist/cjs/devtools/FrappeDevtoolsPanel.native.js.map +1 -1
  49. package/dist/cjs/devtools/index.cjs +15 -17
  50. package/dist/cjs/devtools/index.native.cjs +30 -0
  51. package/dist/cjs/devtools/index.native.js +15 -16
  52. package/dist/cjs/devtools/index.native.js.map +1 -1
  53. package/dist/cjs/devtools/plugin.cjs +22 -26
  54. package/dist/cjs/devtools/plugin.native.cjs +46 -0
  55. package/dist/cjs/devtools/plugin.native.js +27 -35
  56. package/dist/cjs/devtools/plugin.native.js.map +1 -1
  57. package/dist/cjs/devtools/theme.cjs +40 -44
  58. package/dist/cjs/devtools/theme.native.cjs +53 -0
  59. package/dist/cjs/devtools/theme.native.js +40 -43
  60. package/dist/cjs/devtools/theme.native.js.map +1 -1
  61. package/dist/cjs/doctype.cjs +493 -440
  62. package/dist/cjs/doctype.native.cjs +631 -0
  63. package/dist/cjs/doctype.native.js +587 -563
  64. package/dist/cjs/doctype.native.js.map +1 -1
  65. package/dist/cjs/file.cjs +27 -31
  66. package/dist/cjs/file.native.cjs +78 -0
  67. package/dist/cjs/file.native.js +58 -62
  68. package/dist/cjs/file.native.js.map +1 -1
  69. package/dist/cjs/fixtureDb.cjs +187 -209
  70. package/dist/cjs/fixtureDb.native.cjs +313 -0
  71. package/dist/cjs/fixtureDb.native.js +291 -300
  72. package/dist/cjs/fixtureDb.native.js.map +1 -1
  73. package/dist/cjs/fixtures.cjs +173 -192
  74. package/dist/cjs/fixtures.native.cjs +379 -0
  75. package/dist/cjs/fixtures.native.js +359 -381
  76. package/dist/cjs/fixtures.native.js.map +1 -1
  77. package/dist/cjs/frappeApp.cjs +94 -101
  78. package/dist/cjs/frappeApp.native.cjs +181 -0
  79. package/dist/cjs/frappeApp.native.js +153 -152
  80. package/dist/cjs/frappeApp.native.js.map +1 -1
  81. package/dist/cjs/frappeReact.cjs +555 -528
  82. package/dist/cjs/frappeReact.native.cjs +710 -0
  83. package/dist/cjs/frappeReact.native.js +637 -632
  84. package/dist/cjs/frappeReact.native.js.map +1 -1
  85. package/dist/cjs/index.cjs +128 -135
  86. package/dist/cjs/index.gnome.cjs +61 -63
  87. package/dist/cjs/index.gnome.native.cjs +87 -0
  88. package/dist/cjs/index.gnome.native.js +61 -62
  89. package/dist/cjs/index.gnome.native.js.map +1 -1
  90. package/dist/cjs/index.native.cjs +171 -0
  91. package/dist/cjs/index.native.js +130 -136
  92. package/dist/cjs/index.native.js.map +1 -1
  93. package/dist/cjs/optimistic.cjs +35 -39
  94. package/dist/cjs/optimistic.native.cjs +59 -0
  95. package/dist/cjs/optimistic.native.js +38 -41
  96. package/dist/cjs/optimistic.native.js.map +1 -1
  97. package/dist/cjs/pacer.cjs +170 -176
  98. package/dist/cjs/pacer.native.cjs +263 -0
  99. package/dist/cjs/pacer.native.js +234 -245
  100. package/dist/cjs/pacer.native.js.map +1 -1
  101. package/dist/cjs/plugin/index.cjs +104 -112
  102. package/dist/cjs/plugin/index.native.cjs +178 -0
  103. package/dist/cjs/plugin/index.native.js +164 -177
  104. package/dist/cjs/plugin/index.native.js.map +1 -1
  105. package/dist/cjs/realtime.cjs +581 -610
  106. package/dist/cjs/realtime.native.cjs +945 -0
  107. package/dist/cjs/realtime.native.js +918 -928
  108. package/dist/cjs/realtime.native.js.map +1 -1
  109. package/dist/cjs/serverLoaders.cjs +60 -78
  110. package/dist/cjs/serverLoaders.native.cjs +103 -0
  111. package/dist/cjs/serverLoaders.native.js +73 -95
  112. package/dist/cjs/serverLoaders.native.js.map +1 -1
  113. package/dist/cjs/sync/backfill.cjs +281 -301
  114. package/dist/cjs/sync/backfill.native.cjs +475 -0
  115. package/dist/cjs/sync/backfill.native.js +449 -465
  116. package/dist/cjs/sync/backfill.native.js.map +1 -1
  117. package/dist/cjs/sync/filters.cjs +309 -267
  118. package/dist/cjs/sync/filters.native.cjs +472 -0
  119. package/dist/cjs/sync/filters.native.js +426 -398
  120. package/dist/cjs/sync/filters.native.js.map +1 -1
  121. package/dist/cjs/sync/index.cjs +476 -496
  122. package/dist/cjs/sync/index.native.cjs +771 -0
  123. package/dist/cjs/sync/index.native.js +738 -737
  124. package/dist/cjs/sync/index.native.js.map +1 -1
  125. package/dist/cjs/sync/merge.cjs +392 -393
  126. package/dist/cjs/sync/merge.native.cjs +681 -0
  127. package/dist/cjs/sync/merge.native.js +642 -673
  128. package/dist/cjs/sync/merge.native.js.map +1 -1
  129. package/dist/cjs/sync/mutationEngine.cjs +785 -829
  130. package/dist/cjs/sync/mutationEngine.native.cjs +1190 -0
  131. package/dist/cjs/sync/mutationEngine.native.js +1162 -1216
  132. package/dist/cjs/sync/mutationEngine.native.js.map +1 -1
  133. package/dist/cjs/sync/mutationJournal.cjs +147 -149
  134. package/dist/cjs/sync/mutationJournal.native.cjs +302 -0
  135. package/dist/cjs/sync/mutationJournal.native.js +278 -269
  136. package/dist/cjs/sync/mutationJournal.native.js.map +1 -1
  137. package/dist/cjs/sync/normalizedCache.cjs +127 -134
  138. package/dist/cjs/sync/normalizedCache.native.cjs +232 -0
  139. package/dist/cjs/sync/normalizedCache.native.js +212 -212
  140. package/dist/cjs/sync/normalizedCache.native.js.map +1 -1
  141. package/dist/cjs/sync/persistence.cjs +649 -661
  142. package/dist/cjs/sync/persistence.native.cjs +996 -0
  143. package/dist/cjs/sync/persistence.native.js +967 -965
  144. package/dist/cjs/sync/persistence.native.js.map +1 -1
  145. package/dist/cjs/sync/realtime.cjs +307 -315
  146. package/dist/cjs/sync/realtime.native.cjs +486 -0
  147. package/dist/cjs/sync/realtime.native.js +465 -461
  148. package/dist/cjs/sync/realtime.native.js.map +1 -1
  149. package/dist/cjs/sync/rehydration.cjs +279 -321
  150. package/dist/cjs/sync/rehydration.native.cjs +495 -0
  151. package/dist/cjs/sync/rehydration.native.js +473 -515
  152. package/dist/cjs/sync/rehydration.native.js.map +1 -1
  153. package/dist/cjs/sync/storage.cjs +127 -129
  154. package/dist/cjs/sync/storage.native.cjs +211 -0
  155. package/dist/cjs/sync/storage.native.js +188 -184
  156. package/dist/cjs/sync/storage.native.js.map +1 -1
  157. package/dist/cjs/sync/subscriptionManager.cjs +686 -708
  158. package/dist/cjs/sync/subscriptionManager.native.cjs +1205 -0
  159. package/dist/cjs/sync/subscriptionManager.native.js +1179 -1220
  160. package/dist/cjs/sync/subscriptionManager.native.js.map +1 -1
  161. package/dist/cjs/sync/types.cjs +79 -81
  162. package/dist/cjs/sync/types.native.cjs +103 -0
  163. package/dist/cjs/sync/types.native.js +89 -90
  164. package/dist/cjs/sync/types.native.js.map +1 -1
  165. package/dist/cjs/sync/virtualPageManager.cjs +762 -806
  166. package/dist/cjs/sync/virtualPageManager.native.cjs +1097 -0
  167. package/dist/cjs/sync/virtualPageManager.native.js +1072 -1097
  168. package/dist/cjs/sync/virtualPageManager.native.js.map +1 -1
  169. package/dist/cjs/syncOptionsKey.cjs +38 -45
  170. package/dist/cjs/syncOptionsKey.native.cjs +69 -0
  171. package/dist/cjs/syncOptionsKey.native.js +51 -63
  172. package/dist/cjs/syncOptionsKey.native.js.map +1 -1
  173. package/dist/cjs/useLiveQuery.cjs +14 -18
  174. package/dist/cjs/useLiveQuery.native.cjs +26 -0
  175. package/dist/cjs/useLiveQuery.native.js +14 -17
  176. package/dist/cjs/useLiveQuery.native.js.map +1 -1
  177. package/dist/cjs/util.cjs +22 -24
  178. package/dist/cjs/util.native.cjs +40 -0
  179. package/dist/cjs/util.native.js +22 -28
  180. package/dist/cjs/util.native.js.map +1 -1
  181. package/dist/esm/auth.mjs +22 -27
  182. package/dist/esm/auth.mjs.map +1 -1
  183. package/dist/esm/auth.native.js +64 -65
  184. package/dist/esm/auth.native.js.map +1 -1
  185. package/dist/esm/call.mjs +19 -18
  186. package/dist/esm/call.mjs.map +1 -1
  187. package/dist/esm/call.native.js +59 -54
  188. package/dist/esm/call.native.js.map +1 -1
  189. package/dist/esm/collection.mjs +228 -268
  190. package/dist/esm/collection.mjs.map +1 -1
  191. package/dist/esm/collection.native.js +421 -481
  192. package/dist/esm/collection.native.js.map +1 -1
  193. package/dist/esm/common/types.mjs +0 -2
  194. package/dist/esm/common/types.native.js +0 -2
  195. package/dist/esm/connectionKey.mjs +5 -4
  196. package/dist/esm/connectionKey.mjs.map +1 -1
  197. package/dist/esm/connectionKey.native.js +6 -5
  198. package/dist/esm/connectionKey.native.js.map +1 -1
  199. package/dist/esm/core/http.mjs +383 -382
  200. package/dist/esm/core/http.mjs.map +1 -1
  201. package/dist/esm/core/http.native.js +590 -591
  202. package/dist/esm/core/http.native.js.map +1 -1
  203. package/dist/esm/core/serverMessages.mjs +34 -26
  204. package/dist/esm/core/serverMessages.mjs.map +1 -1
  205. package/dist/esm/core/serverMessages.native.js +55 -54
  206. package/dist/esm/core/serverMessages.native.js.map +1 -1
  207. package/dist/esm/core/sessionGate.mjs +79 -79
  208. package/dist/esm/core/sessionGate.mjs.map +1 -1
  209. package/dist/esm/core/sessionGate.native.js +205 -215
  210. package/dist/esm/core/sessionGate.native.js.map +1 -1
  211. package/dist/esm/core/types.mjs +23 -22
  212. package/dist/esm/core/types.mjs.map +1 -1
  213. package/dist/esm/core/types.native.js +114 -119
  214. package/dist/esm/core/types.native.js.map +1 -1
  215. package/dist/esm/core/wire.mjs +10 -9
  216. package/dist/esm/core/wire.mjs.map +1 -1
  217. package/dist/esm/core/wire.native.js +10 -9
  218. package/dist/esm/core/wire.native.js.map +1 -1
  219. package/dist/esm/db.mjs +421 -432
  220. package/dist/esm/db.mjs.map +1 -1
  221. package/dist/esm/db.native.js +570 -574
  222. package/dist/esm/db.native.js.map +1 -1
  223. package/dist/esm/devtools/FrappeDevtoolsPanel.mjs +762 -781
  224. package/dist/esm/devtools/FrappeDevtoolsPanel.mjs.map +1 -1
  225. package/dist/esm/devtools/FrappeDevtoolsPanel.native.js +808 -839
  226. package/dist/esm/devtools/FrappeDevtoolsPanel.native.js.map +1 -1
  227. package/dist/esm/devtools/index.mjs +2 -2
  228. package/dist/esm/devtools/index.native.js +2 -2
  229. package/dist/esm/devtools/plugin.mjs +10 -8
  230. package/dist/esm/devtools/plugin.mjs.map +1 -1
  231. package/dist/esm/devtools/plugin.native.js +14 -12
  232. package/dist/esm/devtools/plugin.native.js.map +1 -1
  233. package/dist/esm/devtools/theme.mjs +27 -26
  234. package/dist/esm/devtools/theme.mjs.map +1 -1
  235. package/dist/esm/devtools/theme.native.js +27 -26
  236. package/dist/esm/devtools/theme.native.js.map +1 -1
  237. package/dist/esm/doctype.mjs +473 -416
  238. package/dist/esm/doctype.mjs.map +1 -1
  239. package/dist/esm/doctype.native.js +566 -539
  240. package/dist/esm/doctype.native.js.map +1 -1
  241. package/dist/esm/file.mjs +15 -14
  242. package/dist/esm/file.mjs.map +1 -1
  243. package/dist/esm/file.native.js +45 -45
  244. package/dist/esm/file.native.js.map +1 -1
  245. package/dist/esm/fixtureDb.mjs +175 -191
  246. package/dist/esm/fixtureDb.mjs.map +1 -1
  247. package/dist/esm/fixtureDb.native.js +279 -283
  248. package/dist/esm/fixtureDb.native.js.map +1 -1
  249. package/dist/esm/fixtures.mjs +161 -175
  250. package/dist/esm/fixtures.mjs.map +1 -1
  251. package/dist/esm/fixtures.native.js +346 -364
  252. package/dist/esm/fixtures.native.js.map +1 -1
  253. package/dist/esm/frappeApp.mjs +82 -83
  254. package/dist/esm/frappeApp.mjs.map +1 -1
  255. package/dist/esm/frappeApp.native.js +141 -135
  256. package/dist/esm/frappeApp.native.js.map +1 -1
  257. package/dist/esm/frappeReact.mjs +535 -504
  258. package/dist/esm/frappeReact.mjs.map +1 -1
  259. package/dist/esm/frappeReact.native.js +615 -607
  260. package/dist/esm/frappeReact.native.js.map +1 -1
  261. package/dist/esm/index.gnome.mjs +5 -5
  262. package/dist/esm/index.gnome.native.js +5 -5
  263. package/dist/esm/index.mjs +17 -18
  264. package/dist/esm/index.native.js +17 -18
  265. package/dist/esm/optimistic.mjs +19 -19
  266. package/dist/esm/optimistic.mjs.map +1 -1
  267. package/dist/esm/optimistic.native.js +22 -22
  268. package/dist/esm/optimistic.native.js.map +1 -1
  269. package/dist/esm/pacer.mjs +156 -158
  270. package/dist/esm/pacer.mjs.map +1 -1
  271. package/dist/esm/pacer.native.js +220 -228
  272. package/dist/esm/pacer.native.js.map +1 -1
  273. package/dist/esm/plugin/index.mjs +91 -94
  274. package/dist/esm/plugin/index.mjs.map +1 -1
  275. package/dist/esm/plugin/index.native.js +151 -160
  276. package/dist/esm/plugin/index.native.js.map +1 -1
  277. package/dist/esm/realtime.mjs +569 -594
  278. package/dist/esm/realtime.mjs.map +1 -1
  279. package/dist/esm/realtime.native.js +905 -912
  280. package/dist/esm/realtime.native.js.map +1 -1
  281. package/dist/esm/serverLoaders.mjs +47 -61
  282. package/dist/esm/serverLoaders.mjs.map +1 -1
  283. package/dist/esm/serverLoaders.native.js +56 -75
  284. package/dist/esm/serverLoaders.native.js.map +1 -1
  285. package/dist/esm/sync/backfill.mjs +268 -284
  286. package/dist/esm/sync/backfill.mjs.map +1 -1
  287. package/dist/esm/sync/backfill.native.js +435 -448
  288. package/dist/esm/sync/backfill.native.js.map +1 -1
  289. package/dist/esm/sync/filters.mjs +286 -241
  290. package/dist/esm/sync/filters.mjs.map +1 -1
  291. package/dist/esm/sync/filters.native.js +403 -373
  292. package/dist/esm/sync/filters.native.js.map +1 -1
  293. package/dist/esm/sync/index.mjs +465 -479
  294. package/dist/esm/sync/index.mjs.map +1 -1
  295. package/dist/esm/sync/index.native.js +726 -720
  296. package/dist/esm/sync/index.native.js.map +1 -1
  297. package/dist/esm/sync/merge.mjs +368 -366
  298. package/dist/esm/sync/merge.mjs.map +1 -1
  299. package/dist/esm/sync/merge.native.js +618 -647
  300. package/dist/esm/sync/merge.native.js.map +1 -1
  301. package/dist/esm/sync/mutationEngine.mjs +775 -814
  302. package/dist/esm/sync/mutationEngine.mjs.map +1 -1
  303. package/dist/esm/sync/mutationEngine.native.js +1152 -1202
  304. package/dist/esm/sync/mutationEngine.native.js.map +1 -1
  305. package/dist/esm/sync/mutationJournal.mjs +135 -133
  306. package/dist/esm/sync/mutationJournal.mjs.map +1 -1
  307. package/dist/esm/sync/mutationJournal.native.js +265 -253
  308. package/dist/esm/sync/mutationJournal.native.js.map +1 -1
  309. package/dist/esm/sync/normalizedCache.mjs +115 -117
  310. package/dist/esm/sync/normalizedCache.mjs.map +1 -1
  311. package/dist/esm/sync/normalizedCache.native.js +199 -195
  312. package/dist/esm/sync/normalizedCache.native.js.map +1 -1
  313. package/dist/esm/sync/persistence.mjs +637 -645
  314. package/dist/esm/sync/persistence.mjs.map +1 -1
  315. package/dist/esm/sync/persistence.native.js +954 -949
  316. package/dist/esm/sync/persistence.native.js.map +1 -1
  317. package/dist/esm/sync/realtime.mjs +296 -298
  318. package/dist/esm/sync/realtime.mjs.map +1 -1
  319. package/dist/esm/sync/realtime.native.js +453 -444
  320. package/dist/esm/sync/realtime.native.js.map +1 -1
  321. package/dist/esm/sync/rehydration.mjs +268 -304
  322. package/dist/esm/sync/rehydration.mjs.map +1 -1
  323. package/dist/esm/sync/rehydration.native.js +461 -498
  324. package/dist/esm/sync/rehydration.native.js.map +1 -1
  325. package/dist/esm/sync/storage.mjs +115 -113
  326. package/dist/esm/sync/storage.mjs.map +1 -1
  327. package/dist/esm/sync/storage.native.js +175 -168
  328. package/dist/esm/sync/storage.native.js.map +1 -1
  329. package/dist/esm/sync/subscriptionManager.mjs +675 -691
  330. package/dist/esm/sync/subscriptionManager.mjs.map +1 -1
  331. package/dist/esm/sync/subscriptionManager.native.js +1168 -1204
  332. package/dist/esm/sync/subscriptionManager.native.js.map +1 -1
  333. package/dist/esm/sync/types.mjs +56 -55
  334. package/dist/esm/sync/types.mjs.map +1 -1
  335. package/dist/esm/sync/types.native.js +66 -65
  336. package/dist/esm/sync/types.native.js.map +1 -1
  337. package/dist/esm/sync/virtualPageManager.mjs +749 -789
  338. package/dist/esm/sync/virtualPageManager.mjs.map +1 -1
  339. package/dist/esm/sync/virtualPageManager.native.js +1058 -1080
  340. package/dist/esm/sync/virtualPageManager.native.js.map +1 -1
  341. package/dist/esm/syncOptionsKey.mjs +25 -27
  342. package/dist/esm/syncOptionsKey.mjs.map +1 -1
  343. package/dist/esm/syncOptionsKey.native.js +38 -46
  344. package/dist/esm/syncOptionsKey.native.js.map +1 -1
  345. package/dist/esm/useLiveQuery.mjs +2 -2
  346. package/dist/esm/useLiveQuery.native.js +2 -2
  347. package/dist/esm/util.mjs +9 -7
  348. package/dist/esm/util.mjs.map +1 -1
  349. package/dist/esm/util.native.js +8 -11
  350. package/dist/esm/util.native.js.map +1 -1
  351. package/dist/jsx/auth.mjs +22 -27
  352. package/dist/jsx/auth.mjs.map +1 -1
  353. package/dist/jsx/auth.native.cjs +97 -0
  354. package/dist/jsx/auth.native.js +77 -82
  355. package/dist/jsx/auth.native.js.map +1 -1
  356. package/dist/jsx/call.mjs +19 -18
  357. package/dist/jsx/call.mjs.map +1 -1
  358. package/dist/jsx/call.native.cjs +92 -0
  359. package/dist/jsx/call.native.js +72 -71
  360. package/dist/jsx/call.native.js.map +1 -1
  361. package/dist/jsx/collection.mjs +228 -268
  362. package/dist/jsx/collection.mjs.map +1 -1
  363. package/dist/jsx/collection.native.cjs +461 -0
  364. package/dist/jsx/collection.native.js +436 -499
  365. package/dist/jsx/collection.native.js.map +1 -1
  366. package/dist/jsx/common/types.mjs +0 -2
  367. package/dist/jsx/common/types.native.cjs +18 -0
  368. package/dist/jsx/common/types.native.js +9 -10
  369. package/dist/jsx/common/types.native.js.map +1 -1
  370. package/dist/jsx/connectionKey.mjs +5 -4
  371. package/dist/jsx/connectionKey.mjs.map +1 -1
  372. package/dist/jsx/connectionKey.native.cjs +32 -0
  373. package/dist/jsx/connectionKey.native.js +19 -22
  374. package/dist/jsx/connectionKey.native.js.map +1 -1
  375. package/dist/jsx/core/http.mjs +383 -382
  376. package/dist/jsx/core/http.mjs.map +1 -1
  377. package/dist/jsx/core/http.native.cjs +659 -0
  378. package/dist/jsx/core/http.native.js +611 -615
  379. package/dist/jsx/core/http.native.js.map +1 -1
  380. package/dist/jsx/core/serverMessages.mjs +34 -26
  381. package/dist/jsx/core/serverMessages.mjs.map +1 -1
  382. package/dist/jsx/core/serverMessages.native.cjs +89 -0
  383. package/dist/jsx/core/serverMessages.native.js +69 -70
  384. package/dist/jsx/core/serverMessages.native.js.map +1 -1
  385. package/dist/jsx/core/sessionGate.mjs +79 -79
  386. package/dist/jsx/core/sessionGate.mjs.map +1 -1
  387. package/dist/jsx/core/sessionGate.native.cjs +270 -0
  388. package/dist/jsx/core/sessionGate.native.js +220 -232
  389. package/dist/jsx/core/sessionGate.native.js.map +1 -1
  390. package/dist/jsx/core/types.mjs +23 -22
  391. package/dist/jsx/core/types.mjs.map +1 -1
  392. package/dist/jsx/core/types.native.cjs +169 -0
  393. package/dist/jsx/core/types.native.js +129 -136
  394. package/dist/jsx/core/types.native.js.map +1 -1
  395. package/dist/jsx/core/wire.mjs +10 -9
  396. package/dist/jsx/core/wire.mjs.map +1 -1
  397. package/dist/jsx/core/wire.native.cjs +53 -0
  398. package/dist/jsx/core/wire.native.js +28 -29
  399. package/dist/jsx/core/wire.native.js.map +1 -1
  400. package/dist/jsx/db.mjs +421 -432
  401. package/dist/jsx/db.mjs.map +1 -1
  402. package/dist/jsx/db.native.cjs +625 -0
  403. package/dist/jsx/db.native.js +583 -590
  404. package/dist/jsx/db.native.js.map +1 -1
  405. package/dist/jsx/devtools/FrappeDevtoolsPanel.mjs +762 -781
  406. package/dist/jsx/devtools/FrappeDevtoolsPanel.mjs.map +1 -1
  407. package/dist/jsx/devtools/FrappeDevtoolsPanel.native.cjs +878 -0
  408. package/dist/jsx/devtools/FrappeDevtoolsPanel.native.js +821 -862
  409. package/dist/jsx/devtools/FrappeDevtoolsPanel.native.js.map +1 -1
  410. package/dist/jsx/devtools/index.mjs +2 -2
  411. package/dist/jsx/devtools/index.native.cjs +30 -0
  412. package/dist/jsx/devtools/index.native.js +15 -16
  413. package/dist/jsx/devtools/index.native.js.map +1 -1
  414. package/dist/jsx/devtools/plugin.mjs +10 -8
  415. package/dist/jsx/devtools/plugin.mjs.map +1 -1
  416. package/dist/jsx/devtools/plugin.native.cjs +46 -0
  417. package/dist/jsx/devtools/plugin.native.js +27 -35
  418. package/dist/jsx/devtools/plugin.native.js.map +1 -1
  419. package/dist/jsx/devtools/theme.mjs +27 -26
  420. package/dist/jsx/devtools/theme.mjs.map +1 -1
  421. package/dist/jsx/devtools/theme.native.cjs +53 -0
  422. package/dist/jsx/devtools/theme.native.js +40 -43
  423. package/dist/jsx/devtools/theme.native.js.map +1 -1
  424. package/dist/jsx/doctype.mjs +473 -416
  425. package/dist/jsx/doctype.mjs.map +1 -1
  426. package/dist/jsx/doctype.native.cjs +631 -0
  427. package/dist/jsx/doctype.native.js +587 -563
  428. package/dist/jsx/doctype.native.js.map +1 -1
  429. package/dist/jsx/file.mjs +15 -14
  430. package/dist/jsx/file.mjs.map +1 -1
  431. package/dist/jsx/file.native.cjs +78 -0
  432. package/dist/jsx/file.native.js +58 -62
  433. package/dist/jsx/file.native.js.map +1 -1
  434. package/dist/jsx/fixtureDb.mjs +175 -191
  435. package/dist/jsx/fixtureDb.mjs.map +1 -1
  436. package/dist/jsx/fixtureDb.native.cjs +313 -0
  437. package/dist/jsx/fixtureDb.native.js +291 -300
  438. package/dist/jsx/fixtureDb.native.js.map +1 -1
  439. package/dist/jsx/fixtures.mjs +161 -175
  440. package/dist/jsx/fixtures.mjs.map +1 -1
  441. package/dist/jsx/fixtures.native.cjs +379 -0
  442. package/dist/jsx/fixtures.native.js +359 -381
  443. package/dist/jsx/fixtures.native.js.map +1 -1
  444. package/dist/jsx/frappeApp.mjs +82 -83
  445. package/dist/jsx/frappeApp.mjs.map +1 -1
  446. package/dist/jsx/frappeApp.native.cjs +181 -0
  447. package/dist/jsx/frappeApp.native.js +153 -152
  448. package/dist/jsx/frappeApp.native.js.map +1 -1
  449. package/dist/jsx/frappeReact.mjs +535 -504
  450. package/dist/jsx/frappeReact.mjs.map +1 -1
  451. package/dist/jsx/frappeReact.native.cjs +710 -0
  452. package/dist/jsx/frappeReact.native.js +636 -631
  453. package/dist/jsx/frappeReact.native.js.map +1 -1
  454. package/dist/jsx/index.gnome.mjs +5 -5
  455. package/dist/jsx/index.gnome.native.cjs +87 -0
  456. package/dist/jsx/index.gnome.native.js +61 -62
  457. package/dist/jsx/index.gnome.native.js.map +1 -1
  458. package/dist/jsx/index.js +17 -18
  459. package/dist/jsx/index.mjs +17 -18
  460. package/dist/jsx/index.native.cjs +171 -0
  461. package/dist/jsx/index.native.js +128 -134
  462. package/dist/jsx/index.native.js.map +1 -1
  463. package/dist/jsx/optimistic.mjs +19 -19
  464. package/dist/jsx/optimistic.mjs.map +1 -1
  465. package/dist/jsx/optimistic.native.cjs +59 -0
  466. package/dist/jsx/optimistic.native.js +38 -41
  467. package/dist/jsx/optimistic.native.js.map +1 -1
  468. package/dist/jsx/pacer.mjs +156 -158
  469. package/dist/jsx/pacer.mjs.map +1 -1
  470. package/dist/jsx/pacer.native.cjs +263 -0
  471. package/dist/jsx/pacer.native.js +234 -245
  472. package/dist/jsx/pacer.native.js.map +1 -1
  473. package/dist/jsx/plugin/index.mjs +91 -94
  474. package/dist/jsx/plugin/index.mjs.map +1 -1
  475. package/dist/jsx/plugin/index.native.cjs +178 -0
  476. package/dist/jsx/plugin/index.native.js +164 -177
  477. package/dist/jsx/plugin/index.native.js.map +1 -1
  478. package/dist/jsx/realtime.mjs +569 -594
  479. package/dist/jsx/realtime.mjs.map +1 -1
  480. package/dist/jsx/realtime.native.cjs +945 -0
  481. package/dist/jsx/realtime.native.js +918 -928
  482. package/dist/jsx/realtime.native.js.map +1 -1
  483. package/dist/jsx/serverLoaders.mjs +47 -61
  484. package/dist/jsx/serverLoaders.mjs.map +1 -1
  485. package/dist/jsx/serverLoaders.native.cjs +103 -0
  486. package/dist/jsx/serverLoaders.native.js +73 -95
  487. package/dist/jsx/serverLoaders.native.js.map +1 -1
  488. package/dist/jsx/sync/backfill.mjs +268 -284
  489. package/dist/jsx/sync/backfill.mjs.map +1 -1
  490. package/dist/jsx/sync/backfill.native.cjs +475 -0
  491. package/dist/jsx/sync/backfill.native.js +449 -465
  492. package/dist/jsx/sync/backfill.native.js.map +1 -1
  493. package/dist/jsx/sync/filters.mjs +286 -241
  494. package/dist/jsx/sync/filters.mjs.map +1 -1
  495. package/dist/jsx/sync/filters.native.cjs +472 -0
  496. package/dist/jsx/sync/filters.native.js +426 -398
  497. package/dist/jsx/sync/filters.native.js.map +1 -1
  498. package/dist/jsx/sync/index.mjs +465 -479
  499. package/dist/jsx/sync/index.mjs.map +1 -1
  500. package/dist/jsx/sync/index.native.cjs +771 -0
  501. package/dist/jsx/sync/index.native.js +738 -737
  502. package/dist/jsx/sync/index.native.js.map +1 -1
  503. package/dist/jsx/sync/merge.mjs +368 -366
  504. package/dist/jsx/sync/merge.mjs.map +1 -1
  505. package/dist/jsx/sync/merge.native.cjs +681 -0
  506. package/dist/jsx/sync/merge.native.js +642 -673
  507. package/dist/jsx/sync/merge.native.js.map +1 -1
  508. package/dist/jsx/sync/mutationEngine.mjs +775 -814
  509. package/dist/jsx/sync/mutationEngine.mjs.map +1 -1
  510. package/dist/jsx/sync/mutationEngine.native.cjs +1190 -0
  511. package/dist/jsx/sync/mutationEngine.native.js +1162 -1216
  512. package/dist/jsx/sync/mutationEngine.native.js.map +1 -1
  513. package/dist/jsx/sync/mutationJournal.mjs +135 -133
  514. package/dist/jsx/sync/mutationJournal.mjs.map +1 -1
  515. package/dist/jsx/sync/mutationJournal.native.cjs +302 -0
  516. package/dist/jsx/sync/mutationJournal.native.js +278 -269
  517. package/dist/jsx/sync/mutationJournal.native.js.map +1 -1
  518. package/dist/jsx/sync/normalizedCache.mjs +115 -117
  519. package/dist/jsx/sync/normalizedCache.mjs.map +1 -1
  520. package/dist/jsx/sync/normalizedCache.native.cjs +232 -0
  521. package/dist/jsx/sync/normalizedCache.native.js +212 -212
  522. package/dist/jsx/sync/normalizedCache.native.js.map +1 -1
  523. package/dist/jsx/sync/persistence.mjs +637 -645
  524. package/dist/jsx/sync/persistence.mjs.map +1 -1
  525. package/dist/jsx/sync/persistence.native.cjs +996 -0
  526. package/dist/jsx/sync/persistence.native.js +967 -965
  527. package/dist/jsx/sync/persistence.native.js.map +1 -1
  528. package/dist/jsx/sync/realtime.mjs +296 -298
  529. package/dist/jsx/sync/realtime.mjs.map +1 -1
  530. package/dist/jsx/sync/realtime.native.cjs +486 -0
  531. package/dist/jsx/sync/realtime.native.js +465 -461
  532. package/dist/jsx/sync/realtime.native.js.map +1 -1
  533. package/dist/jsx/sync/rehydration.mjs +268 -304
  534. package/dist/jsx/sync/rehydration.mjs.map +1 -1
  535. package/dist/jsx/sync/rehydration.native.cjs +495 -0
  536. package/dist/jsx/sync/rehydration.native.js +473 -515
  537. package/dist/jsx/sync/rehydration.native.js.map +1 -1
  538. package/dist/jsx/sync/storage.mjs +115 -113
  539. package/dist/jsx/sync/storage.mjs.map +1 -1
  540. package/dist/jsx/sync/storage.native.cjs +211 -0
  541. package/dist/jsx/sync/storage.native.js +188 -184
  542. package/dist/jsx/sync/storage.native.js.map +1 -1
  543. package/dist/jsx/sync/subscriptionManager.mjs +675 -691
  544. package/dist/jsx/sync/subscriptionManager.mjs.map +1 -1
  545. package/dist/jsx/sync/subscriptionManager.native.cjs +1205 -0
  546. package/dist/jsx/sync/subscriptionManager.native.js +1179 -1220
  547. package/dist/jsx/sync/subscriptionManager.native.js.map +1 -1
  548. package/dist/jsx/sync/types.mjs +56 -55
  549. package/dist/jsx/sync/types.mjs.map +1 -1
  550. package/dist/jsx/sync/types.native.cjs +103 -0
  551. package/dist/jsx/sync/types.native.js +89 -90
  552. package/dist/jsx/sync/types.native.js.map +1 -1
  553. package/dist/jsx/sync/virtualPageManager.mjs +749 -789
  554. package/dist/jsx/sync/virtualPageManager.mjs.map +1 -1
  555. package/dist/jsx/sync/virtualPageManager.native.cjs +1097 -0
  556. package/dist/jsx/sync/virtualPageManager.native.js +1072 -1097
  557. package/dist/jsx/sync/virtualPageManager.native.js.map +1 -1
  558. package/dist/jsx/syncOptionsKey.mjs +25 -27
  559. package/dist/jsx/syncOptionsKey.mjs.map +1 -1
  560. package/dist/jsx/syncOptionsKey.native.cjs +69 -0
  561. package/dist/jsx/syncOptionsKey.native.js +51 -63
  562. package/dist/jsx/syncOptionsKey.native.js.map +1 -1
  563. package/dist/jsx/useLiveQuery.mjs +2 -2
  564. package/dist/jsx/useLiveQuery.native.cjs +26 -0
  565. package/dist/jsx/useLiveQuery.native.js +14 -17
  566. package/dist/jsx/useLiveQuery.native.js.map +1 -1
  567. package/dist/jsx/util.mjs +9 -7
  568. package/dist/jsx/util.mjs.map +1 -1
  569. package/dist/jsx/util.native.cjs +40 -0
  570. package/dist/jsx/util.native.js +22 -28
  571. package/dist/jsx/util.native.js.map +1 -1
  572. package/package.json +10 -10
  573. package/src/devtools/FrappeDevtoolsPanel.stories.tsx +16 -16
  574. package/src/devtools/plugin.stories.tsx +4 -4
  575. package/src/useFrappeCollection.stories.tsx +14 -14
  576. package/src/useFrappeInfiniteList.stories.tsx +11 -11
  577. package/src/useFrappePendingMutations.stories.tsx +12 -12
  578. package/types/devtools/FrappeDevtoolsPanel.d.ts +2 -1
  579. package/types/devtools/FrappeDevtoolsPanel.d.ts.map +1 -1
  580. package/types/devtools/plugin.d.ts +2 -1
  581. package/types/devtools/plugin.d.ts.map +1 -1
  582. package/dist/esm/common/types.mjs.map +0 -1
  583. package/dist/esm/common/types.native.js.map +0 -1
  584. package/dist/esm/devtools/index.mjs.map +0 -1
  585. package/dist/esm/devtools/index.native.js.map +0 -1
  586. package/dist/esm/index.gnome.mjs.map +0 -1
  587. package/dist/esm/index.gnome.native.js.map +0 -1
  588. package/dist/esm/index.mjs.map +0 -1
  589. package/dist/esm/index.native.js.map +0 -1
  590. package/dist/esm/useLiveQuery.mjs.map +0 -1
  591. package/dist/esm/useLiveQuery.native.js.map +0 -1
  592. package/dist/jsx/common/types.mjs.map +0 -1
  593. package/dist/jsx/devtools/index.mjs.map +0 -1
  594. package/dist/jsx/index.gnome.mjs.map +0 -1
  595. package/dist/jsx/index.js.map +0 -1
  596. package/dist/jsx/index.mjs.map +0 -1
  597. package/dist/jsx/useLiveQuery.mjs.map +0 -1
@@ -3,27 +3,23 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
5
  var __export = (target, all) => {
6
- for (var name in all) __defProp(target, name, {
7
- get: all[name],
8
- enumerable: true
9
- });
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
10
  };
11
11
  var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
- get: () => from[key],
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- return to;
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: () => from[key],
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
19
  };
20
- var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
21
- value: true
22
- }), mod);
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
21
  var mutationEngine_exports = {};
24
- __export(mutationEngine_exports, {
25
- MutationEngine: () => MutationEngine
26
- });
22
+ __export(mutationEngine_exports, { MutationEngine: () => MutationEngine });
27
23
  module.exports = __toCommonJS(mutationEngine_exports);
28
24
  var import_pacer = require("@tanstack/pacer");
29
25
  var import_filters = require("./filters.cjs");
@@ -31,817 +27,777 @@ var import_merge = require("./merge.cjs");
31
27
  var import_types = require("./types.cjs");
32
28
  var import_types2 = require("./types.cjs");
33
29
  function toJournalError(err) {
34
- if (err instanceof Error) return {
35
- message: err.message
36
- };
37
- const message = err?.message;
38
- return {
39
- message: message ?? String(err)
40
- };
41
- }
42
- class MutationEngine {
43
- temporaryIdToRealNameMap = /* @__PURE__ */new Map();
44
- globalOptimisticDocIds = /* @__PURE__ */new Map();
45
- /** Pending mutations waiting to be batched */
46
- pendingBatch = [];
47
- /** Debouncer for batch processing */
48
- batchDebouncer;
49
- db;
50
- realtime;
51
- normalizedCache;
52
- mutationJournal;
53
- subscriptionManager;
54
- rehydrationManager;
55
- options;
56
- constructor(db, realtime, normalizedCache, mutationJournal, subscriptionManager, rehydrationManager, options = {}) {
57
- this.db = db;
58
- this.realtime = realtime;
59
- this.normalizedCache = normalizedCache;
60
- this.mutationJournal = mutationJournal;
61
- this.subscriptionManager = subscriptionManager;
62
- this.rehydrationManager = rehydrationManager;
63
- this.options = options;
64
- const batchDelay = options.batchDelay ?? 100;
65
- this.batchDebouncer = new import_pacer.Debouncer(() => this.flushBatch(), {
66
- wait: batchDelay
67
- });
68
- }
69
- /**
70
- * Queue a mutation for batch processing.
71
- * Returns a promise that resolves when the batch is processed.
72
- */
73
- queueForBatch(mutation) {
74
- return new Promise((resolve, reject) => {
75
- this.pendingBatch.push({
76
- mutation,
77
- resolve,
78
- reject
79
- });
80
- const maxSize = this.options.batchMaxSize ?? 50;
81
- if (this.pendingBatch.length >= maxSize) {
82
- this.flushBatch();
83
- } else {
84
- this.batchDebouncer.maybeExecute();
85
- }
86
- });
87
- }
88
- /**
89
- * Flush pending mutations as a batch.
90
- */
91
- async flushBatch() {
92
- if (this.pendingBatch.length === 0) return;
93
- const batch = [...this.pendingBatch];
94
- this.pendingBatch = [];
95
- try {
96
- const batchMutations = batch.map(({
97
- mutation
98
- }) => {
99
- const operationMap = {
100
- [import_types2.Operation.Create]: "create",
101
- [import_types2.Operation.Update]: "update",
102
- [import_types2.Operation.Delete]: "delete"
103
- };
104
- return {
105
- type: operationMap[mutation.operation],
106
- doctype: mutation.doc.doctype,
107
- name: mutation.doc.name,
108
- data: mutation.operation === import_types2.Operation.Delete ? void 0 : mutation.doc
109
- };
110
- });
111
- const results = await this.db.batchMutations({
112
- mutations: batchMutations,
113
- atomic: this.options.batchAtomic ?? false
114
- });
115
- for (let i = 0; i < batch.length; i++) {
116
- const {
117
- mutation,
118
- resolve,
119
- reject
120
- } = batch[i];
121
- const result = results[i];
122
- if (result.success) {
123
- this.mutationJournal.confirm(mutation.mutationId);
124
- if (result.data) {
125
- this.normalizedCache.upsert(result.data);
126
- if (mutation.operation === import_types2.Operation.Create) {
127
- const temporaryName = mutation.temporaryName ?? mutation.doc.name;
128
- if (temporaryName && result.data.name && temporaryName !== result.data.name) {
129
- this.handleTemporaryToRealMapping(mutation.doc.doctype, temporaryName, result.data.name);
130
- this.rehydrationManager.registerTempIdMapping(temporaryName, result.data.name);
131
- } else if (temporaryName) {
132
- this.globalOptimisticDocIds.get(mutation.doc.doctype)?.delete(temporaryName);
133
- }
134
- }
135
- }
136
- if (this.options.onMutationSuccess) {
137
- this.options.onMutationSuccess(mutation);
138
- }
139
- resolve(result.data);
140
- } else {
141
- const error = new Error(result.error || "Batch mutation failed");
142
- this.mutationJournal.fail(mutation.mutationId, toJournalError(error));
143
- reject(error);
144
- }
145
- }
146
- } catch (err) {
147
- for (const {
148
- mutation,
149
- reject
150
- } of batch) {
151
- this.mutationJournal.fail(mutation.mutationId, toJournalError(err));
152
- reject(err);
153
- }
154
- }
155
- }
156
- /**
157
- * Force flush any pending batched mutations.
158
- */
159
- async forceBatchFlush() {
160
- this.batchDebouncer.cancel();
161
- await this.flushBatch();
162
- }
163
- async mutate(mutation) {
164
- if (this.options.onMutationStart) this.options.onMutationStart(mutation);
165
- const {
166
- doc
167
- } = mutation;
168
- if ((mutation.operation === import_types2.Operation.Update || mutation.operation === import_types2.Operation.Delete) && !doc.name) {
169
- throw new Error("docname is required for update/delete operations");
170
- }
171
- let version = mutation.version;
172
- let cachedDoc = void 0;
173
- if (doc.name) {
174
- cachedDoc = this.normalizedCache.get({
175
- doctype: doc.doctype,
176
- name: doc.name
177
- });
178
- }
179
- if (version === void 0 && doc.name) {
180
- const versionField = this.options.versionFields?.[doc.doctype] || this.options.versionField || "modified";
181
- const cachedVersion = cachedDoc ? cachedDoc[versionField] : void 0;
182
- if (typeof cachedVersion === "string") version = cachedVersion;
183
- }
184
- if (mutation.operation === import_types2.Operation.Update && doc.name) {
185
- await this.handleOptimisticUpdate(mutation, cachedDoc);
186
- this.options.onStoreChange?.();
187
- }
188
- if (mutation.operation === import_types2.Operation.Create) {
189
- await this.handleOptimisticCreate(mutation);
190
- this.options.onStoreChange?.();
191
- }
192
- if (version === void 0 && doc.name && (mutation.operation === import_types2.Operation.Update || mutation.operation === import_types2.Operation.Delete) && !cachedDoc) {
193
- try {
194
- cachedDoc = await this.db.getDoc(doc.doctype, doc.name);
195
- const versionField = this.options.versionFields?.[doc.doctype] || this.options.versionField || "modified";
196
- const cachedVersion = cachedDoc ? cachedDoc[versionField] : void 0;
197
- if (typeof cachedVersion === "string") version = cachedVersion;
198
- this.normalizedCache.upsert(cachedDoc);
199
- } catch (err) {
200
- if (this.options.onTrace) {
201
- this.options.onTrace({
202
- event: "version-fetch-failed",
203
- details: {
204
- doctype: doc.doctype,
205
- name: doc.name,
206
- error: err
207
- }
208
- });
209
- }
210
- }
211
- }
212
- const values = mutation.operation === import_types2.Operation.Delete ? void 0 : mutation.operation === import_types2.Operation.Create ? mutation.doc : mutation.doc;
213
- this.mutationJournal.add(mutation.mutationId, {
214
- doctype: doc.doctype,
215
- // Creates journal the optimistic identity (consumer placeholder or
216
- // engine-generated temp id) so page refreshes keep the pending row
217
- // and rollback can evict it even when doc.name was never set.
218
- docname: mutation.operation === import_types2.Operation.Create ? mutation.temporaryName ?? doc.name : doc.name,
219
- values,
220
- operation: mutation.operation,
221
- version,
222
- status: import_types2.Status.Pending,
223
- snapshot: doc.name ? cachedDoc : void 0
224
- });
225
- if (mutation.operation === import_types2.Operation.Delete && doc.name) {
226
- this.applyOptimisticDelete(doc.doctype, doc.name);
227
- this.options.onStoreChange?.();
228
- }
229
- if (this.options.enableBatching && !mutation.execute) {
230
- try {
231
- await this.queueForBatch(mutation);
232
- if (mutation.operation === import_types2.Operation.Create) {
233
- for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
234
- if (subscription.query.doctype === mutation.doc.doctype) {
235
- this.rehydrationManager.scheduleRehydration(subscription, import_types2.RehydrationReason.Create);
236
- }
237
- }
238
- }
239
- } catch (err) {
240
- await this.handleMutationError(mutation, err);
241
- throw err;
242
- }
243
- return;
244
- }
245
- try {
246
- if (mutation.operation === import_types2.Operation.Create) {
247
- await this.handleServerCreate(mutation);
248
- } else if (mutation.operation === import_types2.Operation.Update && doc.name) {
249
- await this.handleServerUpdate(mutation, version);
250
- } else if (mutation.operation === import_types2.Operation.Delete && doc.name) {
251
- await this.handleServerDelete(mutation, version);
252
- }
253
- this.mutationJournal.confirm(mutation.mutationId);
254
- if (this.options.onMutationSuccess) {
255
- this.options.onMutationSuccess(mutation);
256
- }
257
- if (mutation.operation === import_types2.Operation.Create) {
258
- for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
259
- if (subscription.query.doctype === mutation.doc.doctype) {
260
- this.rehydrationManager.scheduleRehydration(subscription, import_types2.RehydrationReason.Create);
261
- }
262
- }
263
- }
264
- if (!this.realtime?.isHealthy()) {
265
- await this.refetchAffectedDocs(mutation);
266
- }
267
- } catch (err) {
268
- await this.handleMutationError(mutation, err);
269
- throw err;
270
- }
271
- }
272
- async handleOptimisticUpdate(mutation, cachedDoc) {
273
- const doc = cachedDoc ? {
274
- ...cachedDoc,
275
- ...mutation.doc
276
- } : mutation.doc;
277
- this.normalizedCache.upsert(doc);
278
- if (this.options.onOptimisticApply) {
279
- this.options.onOptimisticApply({
280
- doctype: mutation.doc.doctype,
281
- name: mutation.doc.name,
282
- operation: mutation.operation
283
- });
284
- }
285
- this.subscriptionManager.updateSubscriptionMembership(doc);
286
- }
287
- async handleOptimisticCreate(mutation) {
288
- const temporaryName = mutation.doc.name || `tmp_${cryptoRandomId()}`;
289
- mutation.temporaryName = temporaryName;
290
- const optimisticDoc = {
291
- ...mutation.doc,
292
- name: temporaryName
293
- };
294
- this.normalizedCache.upsert(optimisticDoc);
295
- if (!this.globalOptimisticDocIds.has(mutation.doc.doctype)) {
296
- this.globalOptimisticDocIds.set(mutation.doc.doctype, /* @__PURE__ */new Set());
297
- }
298
- const globalDocIds = this.globalOptimisticDocIds.get(mutation.doc.doctype);
299
- for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
300
- if (subscription.query.doctype !== mutation.doc.doctype) continue;
301
- const matches = (0, import_filters.matchesFilters)(optimisticDoc, subscription.query.filters);
302
- if (!matches) continue;
303
- if (globalDocIds.has(temporaryName)) {
304
- continue;
305
- }
306
- if (subscription.query.orderBy && typeof subscription.query.limit === "number" && subscription.query.limit > 0 && subscription.docIds.length > 0) {
307
- const placement = this.determineOptimisticPlacement(subscription, optimisticDoc);
308
- switch (placement) {
309
- case import_types2.PlacementType.Before:
310
- if (subscription.metadata) {
311
- subscription.metadata.itemsBeforePage = (subscription.metadata.itemsBeforePage || 0) + 1;
312
- }
313
- continue;
314
- case import_types2.PlacementType.After:
315
- if (subscription.metadata) {
316
- subscription.metadata.itemsAfterPage = (subscription.metadata.itemsAfterPage || 0) + 1;
317
- }
318
- continue;
319
- case import_types2.PlacementType.Unknown:
320
- subscription.pendingRehydration = import_types2.PendingRehydrationType.FullRefresh;
321
- this.rehydrationManager.scheduleRehydration(subscription, import_types2.RehydrationReason.Uncertain);
322
- break;
323
- case import_types2.PlacementType.Within:
324
- break;
325
- }
326
- }
327
- if (!subscription.docIds.includes(temporaryName)) {
328
- this.subscriptionManager.insertDocumentIntoSubscription(subscription, optimisticDoc);
329
- globalDocIds.add(temporaryName);
330
- }
331
- }
332
- }
333
- async handleServerCreate(mutation) {
334
- const created = mutation.execute ? await mutation.execute() : await this.db.createDoc({
335
- ...mutation.doc,
336
- client_mutation_id: mutation.mutationId
337
- });
338
- const realName = created?.name;
339
- const temporaryName = mutation.temporaryName ?? mutation.doc.name;
340
- if (realName) {
341
- this.normalizedCache.upsert({
342
- ...created,
343
- doctype: created.doctype || mutation.doc.doctype
344
- });
345
- }
346
- if (realName && temporaryName && realName !== temporaryName) {
347
- this.handleTemporaryToRealMapping(mutation.doc.doctype, temporaryName, realName);
348
- this.rehydrationManager.registerTempIdMapping(temporaryName, realName);
349
- } else if (temporaryName) {
350
- const globalDocs = this.globalOptimisticDocIds.get(mutation.doc.doctype);
351
- if (globalDocs) {
352
- globalDocs.delete(temporaryName);
353
- }
354
- }
355
- }
356
- async handleServerUpdate(mutation, _version) {
357
- if (mutation.execute) {
358
- const updated = await mutation.execute();
359
- if (updated?.name) {
360
- this.normalizedCache.upsert({
361
- ...updated,
362
- doctype: updated.doctype || mutation.doc.doctype
363
- });
364
- }
365
- return;
366
- }
367
- await this.db.updateDoc(mutation.doc);
368
- }
369
- /**
370
- * Applies the local side of a delete: cache eviction, subscription
371
- * membership removal, and gap-filling rehydration. Runs before the server
372
- * call (mutate() body) so the row disappears immediately; the journal
373
- * snapshot restores it if the server rejects.
374
- */
375
- applyOptimisticDelete(doctype, name) {
376
- const affected = [...this.subscriptionManager.getAllSubscriptions().values()].filter(subscription => subscription.query.doctype === doctype && subscription.docIds.includes(name));
377
- this.normalizedCache.remove({
378
- doctype,
379
- name
380
- });
381
- this.subscriptionManager.removeFromAllSubscriptions(doctype, name);
382
- for (const subscription of affected) {
383
- this.rehydrationManager.scheduleRehydration(subscription, import_types2.RehydrationReason.Delete);
384
- }
385
- }
386
- async handleServerDelete(mutation, _version) {
387
- if (mutation.execute) {
388
- await mutation.execute();
389
- return;
390
- }
391
- await this.db.deleteDoc(mutation.doc);
392
- }
393
- handleTemporaryToRealMapping(doctype, temporaryName, realName) {
394
- this.temporaryIdToRealNameMap.set(temporaryName, realName);
395
- const globalDocs = this.globalOptimisticDocIds.get(doctype);
396
- if (globalDocs) {
397
- globalDocs.delete(temporaryName);
398
- }
399
- for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
400
- if (subscription.query.doctype !== doctype) continue;
401
- if (!subscription.docIds.includes(temporaryName)) continue;
402
- subscription.docIds = subscription.docIds.includes(realName) ? subscription.docIds.filter(id => id !== temporaryName) : subscription.docIds.map(id => id === temporaryName ? realName : id);
403
- }
404
- this.normalizedCache.remove({
405
- doctype,
406
- name: temporaryName
407
- });
408
- }
409
- async refetchAffectedDocs(mutation) {
410
- const targets = [];
411
- const docname = mutation.doc.name;
412
- const doctype = mutation.doc.doctype;
413
- const realName = docname && this.temporaryIdToRealNameMap.get(docname) || docname;
414
- if (realName && mutation.operation === import_types2.Operation.Update) {
415
- targets.push({
416
- doctype,
417
- name: realName
418
- });
419
- }
420
- if (mutation.affected?.length) targets.push(...mutation.affected);
421
- for (const target of targets) {
422
- const fresh = await this.db.getDoc(target.doctype, target.name);
423
- this.normalizedCache.upsert(fresh);
424
- }
425
- }
426
- async handleMutationError(mutation, err) {
427
- if (this.options.onMutationError) this.options.onMutationError({
428
- mutation,
429
- err
430
- });
431
- this.mutationJournal.fail(mutation.mutationId, toJournalError(err));
432
- const entry = this.mutationJournal.get(mutation.mutationId);
433
- const isOffline = typeof navigator !== "undefined" && navigator.onLine === false;
434
- if (!isOffline) {
435
- await this.rollbackOptimisticState(mutation, entry);
436
- }
437
- const errorWithStatus = err;
438
- const docname = mutation.doc.name;
439
- if (errorWithStatus && (errorWithStatus.status === 409 || errorWithStatus.status === 412) && docname) {
440
- await this.handleConflict(mutation, entry);
441
- }
442
- }
443
- /**
444
- * Rolls back optimistic state when a mutation fails.
445
- * Handles all operation types: create, update, and delete.
446
- */
447
- async rollbackOptimisticState(mutation, entry) {
448
- const doctype = mutation.doc.doctype;
449
- const docname = mutation.doc.name;
450
- switch (mutation.operation) {
451
- case import_types2.Operation.Create:
452
- await this.handleFailedCreate(mutation);
453
- break;
454
- case import_types2.Operation.Update:
455
- if (entry?.snapshot && docname) {
456
- this.normalizedCache.upsert(entry.snapshot, {
457
- replace: true
458
- });
459
- this.subscriptionManager.updateSubscriptionMembership(entry.snapshot);
460
- }
461
- break;
462
- case import_types2.Operation.Delete:
463
- if (entry?.snapshot && docname) {
464
- this.normalizedCache.upsert(entry.snapshot, {
465
- replace: true
466
- });
467
- const restoredDoc = entry.snapshot;
468
- for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
469
- if (subscription.query.doctype !== doctype) continue;
470
- const matches = (0, import_filters.matchesFilters)(restoredDoc, subscription.query.filters);
471
- if (matches && !subscription.docIds.includes(docname)) {
472
- this.subscriptionManager.insertDocumentIntoSubscription(subscription, restoredDoc);
473
- }
474
- }
475
- }
476
- break;
477
- }
478
- }
479
- async handleFailedCreate(mutation) {
480
- const temporaryName = mutation.operation === import_types2.Operation.Create ? mutation.temporaryName ?? mutation.doc.name : mutation.doc.name;
481
- const doctype = mutation.doc.doctype;
482
- if (temporaryName) {
483
- const globalDocs = this.globalOptimisticDocIds.get(doctype);
484
- if (globalDocs) {
485
- globalDocs.delete(temporaryName);
486
- }
487
- for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
488
- if (subscription.query.doctype !== doctype) continue;
489
- subscription.docIds = subscription.docIds.filter(id => id !== temporaryName);
490
- }
491
- this.normalizedCache.remove({
492
- doctype,
493
- name: temporaryName
494
- });
495
- }
496
- }
497
- async handleConflict(mutation, entry) {
498
- const doctype = mutation.doc.doctype;
499
- const docname = mutation.doc.name;
500
- if (!docname) return;
501
- try {
502
- const latest = await this.db.getDoc(doctype, docname);
503
- const base = entry?.snapshot;
504
- const clientPartial = (mutation.operation === import_types2.Operation.Delete ? void 0 : mutation.doc) ?? {};
505
- const fullClient = base ? {
506
- ...base,
507
- ...clientPartial,
508
- doctype,
509
- name: docname
510
- } : {
511
- ...clientPartial,
512
- doctype,
513
- name: docname
514
- };
515
- const mergeConfig = this.buildMergeConfig();
516
- const nonOverlap = (0, import_merge.merge)(base, fullClient, latest, mergeConfig, doctype);
517
- if (!nonOverlap.hasConflicts) {
518
- const versionField = this.options.versionFields?.[doctype] || this.options.versionField || "modified";
519
- if (nonOverlap.merged) {
520
- const newId = cryptoRandomId();
521
- await this.db.updateDoc({
522
- ...nonOverlap.merged,
523
- client_mutation_id: newId,
524
- base_modified: latest[versionField] || void 0
525
- });
526
- }
527
- const refreshed = await this.db.getDoc(doctype, docname);
528
- this.normalizedCache.upsert(refreshed);
529
- this.mutationJournal.confirm(mutation.mutationId);
530
- return;
531
- }
532
- this.normalizedCache.upsert(latest);
533
- } catch {}
534
- if (this.options.onConflict) this.options.onConflict({
535
- doctype,
536
- name: docname
537
- });
538
- }
539
- /**
540
- * Determines optimal placement for an optimistic item based on sort fields.
541
- * Supports multi-column sorting with proper tie-breaking.
542
- *
543
- * @param subscription - The subscription to check placement against
544
- * @param candidate - The document to place
545
- * @returns Placement relative to current page:
546
- * - 'before': Item belongs on a previous page
547
- * - 'within': Item belongs on the current page
548
- * - 'after': Item belongs on a later page
549
- * - 'unknown': Cannot determine placement (needs full refresh)
550
- *
551
- * @remarks
552
- * Uses page boundaries when available for O(1) placement checks.
553
- * Falls back to comparing against first/last items in current page.
554
- * Supports multi-field sorting with tie-breaking.
555
- */
556
- determineOptimisticPlacement(subscription, candidate) {
557
- const docIds = subscription.docIds;
558
- if (!docIds.length) return import_types2.PlacementType.Unknown;
559
- if (subscription.boundaries?.firstItem && subscription.boundaries?.lastItem) {
560
- return this.determinePlacementWithBoundaries(subscription.boundaries, candidate, subscription.query.orderBy);
561
- }
562
- const order = subscription.query.orderBy;
563
- if (!order) return import_types2.PlacementType.Unknown;
564
- const doctype = subscription.query.doctype;
565
- const first = this.normalizedCache.get({
566
- doctype,
567
- name: docIds[0]
568
- });
569
- const last = this.normalizedCache.get({
570
- doctype,
571
- name: docIds[docIds.length - 1]
572
- });
573
- if (!first || !last) return import_types2.PlacementType.Unknown;
574
- const sortFields = this.parseSortFields(order);
575
- for (const {
576
- field,
577
- isAsc
578
- } of sortFields) {
579
- const candidateValue = candidate[field];
580
- const firstValue = first[field];
581
- const lastValue = last[field];
582
- if (candidateValue == null || firstValue == null || lastValue == null) {
583
- continue;
584
- }
585
- if (isAsc) {
586
- if (candidateValue < firstValue) return import_types2.PlacementType.Before;
587
- if (candidateValue > lastValue) return import_types2.PlacementType.After;
588
- } else {
589
- if (candidateValue > firstValue) return import_types2.PlacementType.Before;
590
- if (candidateValue < lastValue) return import_types2.PlacementType.After;
591
- }
592
- if (candidateValue !== firstValue && candidateValue !== lastValue) {
593
- return import_types2.PlacementType.Within;
594
- }
595
- }
596
- return import_types2.PlacementType.Within;
597
- }
598
- determinePlacementWithBoundaries(boundaries, candidate, orderBy) {
599
- if (!boundaries.firstItem || !boundaries.lastItem) return import_types2.PlacementType.Unknown;
600
- const sortFields = this.parseSortFields(orderBy);
601
- for (const {
602
- field,
603
- isAsc
604
- } of sortFields) {
605
- const candidateValue = candidate[field];
606
- const firstValue = boundaries.firstItem[field];
607
- const lastValue = boundaries.lastItem[field];
608
- if (candidateValue == null || firstValue == null || lastValue == null) {
609
- continue;
610
- }
611
- if (isAsc) {
612
- if (candidateValue < firstValue) return import_types2.PlacementType.Before;
613
- if (candidateValue > lastValue) return import_types2.PlacementType.After;
614
- } else {
615
- if (candidateValue > firstValue) return import_types2.PlacementType.Before;
616
- if (candidateValue < lastValue) return import_types2.PlacementType.After;
617
- }
618
- if (candidateValue !== firstValue && candidateValue !== lastValue) {
619
- return import_types2.PlacementType.Within;
620
- }
621
- }
622
- return import_types2.PlacementType.Within;
623
- }
624
- parseSortFields(orderBy) {
625
- if (!orderBy) return [{
626
- field: "name",
627
- isAsc: true
628
- }];
629
- const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
630
- const sortFields = orderByArray.map(ob => ({
631
- field: ob.field,
632
- isAsc: ob.order !== import_types.Order.Desc
633
- }));
634
- const hasNameField = sortFields.some(sf => sf.field === "name");
635
- if (!hasNameField) {
636
- sortFields.push({
637
- field: "name",
638
- isAsc: true
639
- });
640
- }
641
- return sortFields;
642
- }
643
- /**
644
- * Replays pending mutations with simplified error handling and rate limiting.
645
- *
646
- * Since HTTP client now handles retries automatically for transient errors,
647
- * we only need to handle:
648
- * - Success → confirm and remove from journal
649
- * - Conflict (409/412) → attempt merge resolution, then retry
650
- * - Auth (401/403) → notify user, keep in journal for later retry
651
- * - Permanent (4xx validation) → fail and remove from journal
652
- * - Failed (exhausted retries) → keep in journal but notify
653
- *
654
- * The replay path uses plain CRUD without optimistic writes,
655
- * since optimistic state is already reflected in the cache.
656
- *
657
- * Rate limiting is applied to prevent hammering the server when replaying
658
- * large numbers of queued mutations after coming back online.
659
- */
660
- async replayPending() {
661
- let anyFailed = false;
662
- if (this.options.onReplayStart) this.options.onReplayStart();
663
- const pendingMutations = this.mutationJournal.listPending();
664
- if (pendingMutations.length === 0) {
665
- if (this.options.onReplayComplete) {
666
- this.options.onReplayComplete({
667
- anyFailed: false
668
- });
669
- }
670
- return;
671
- }
672
- const rateLimit = this.options.replayRateLimit ?? 10;
673
- const processMutation = async mutation => {
674
- const {
675
- id,
676
- entry
677
- } = mutation;
678
- if (this.options.onRetry) {
679
- this.options.onRetry({
680
- id,
681
- operation: entry.operation
682
- });
683
- }
684
- try {
685
- if (entry.operation === import_types2.Operation.Create) {
686
- const created = await this.db.createDoc({
687
- ...entry.values,
688
- client_mutation_id: id,
689
- doctype: entry.doctype,
690
- name: entry.docname || cryptoRandomId()
691
- });
692
- if (created?.name) {
693
- this.normalizedCache.upsert({
694
- ...created,
695
- doctype: created.doctype || entry.doctype
696
- });
697
- if (entry.docname && created.name !== entry.docname) {
698
- this.handleTemporaryToRealMapping(entry.doctype, entry.docname, created.name);
699
- this.rehydrationManager.registerTempIdMapping(entry.docname, created.name);
700
- }
701
- }
702
- } else if (entry.operation === import_types2.Operation.Update && entry.docname) {
703
- await this.db.updateDoc({
704
- ...entry.values,
705
- client_mutation_id: id,
706
- base_modified: entry.version,
707
- doctype: entry.doctype,
708
- name: entry.docname
709
- });
710
- } else if (entry.operation === import_types2.Operation.Delete && entry.docname) {
711
- await this.db.deleteDoc({
712
- doctype: entry.doctype,
713
- name: entry.docname,
714
- client_mutation_id: id
715
- });
716
- }
717
- this.mutationJournal.confirm(id);
718
- } catch (err) {
719
- const errorClass = this.classifyError(err);
720
- anyFailed = true;
721
- if (errorClass === "conflict") {
722
- if (this.options.onConflict) {
723
- this.options.onConflict({
724
- doctype: entry.doctype,
725
- name: entry.docname
726
- });
727
- }
728
- } else if (errorClass === "auth") {} else if (errorClass === "permanent") {
729
- this.mutationJournal.fail(id, toJournalError(err));
730
- this.notifyMutationError(id, entry, err);
731
- } else if (errorClass === "failed") {
732
- this.mutationJournal.fail(id, toJournalError(err));
733
- this.notifyMutationError(id, entry, err);
734
- }
735
- }
736
- };
737
- const delayMs = Math.ceil(1e3 / rateLimit);
738
- for (const mutation of pendingMutations) {
739
- await processMutation(mutation);
740
- if (pendingMutations.indexOf(mutation) < pendingMutations.length - 1) {
741
- await new Promise(resolve => setTimeout(resolve, delayMs));
742
- }
743
- }
744
- if (this.options.onReplayComplete) {
745
- this.options.onReplayComplete({
746
- anyFailed
747
- });
748
- }
749
- }
750
- /**
751
- * Classifies errors for journal management.
752
- */
753
- classifyError(err) {
754
- const errorWithStatus = err;
755
- const status = errorWithStatus?.status || errorWithStatus?.response?.status;
756
- if (status === 409 || status === 412) return "conflict";
757
- if (status === 401 || status === 403) return "auth";
758
- if (status && status >= 400 && status < 500) return "permanent";
759
- return "failed";
760
- }
761
- /**
762
- * Helper to notify about mutation errors with proper typing
763
- */
764
- notifyMutationError(id, entry, err) {
765
- if (!this.options.onMutationError) return;
766
- let mutation;
767
- if (entry.operation === import_types2.Operation.Create) {
768
- const doc = entry.values || {
769
- doctype: entry.doctype,
770
- name: entry.docname
771
- };
772
- mutation = {
773
- mutationId: id,
774
- operation: import_types2.Operation.Create,
775
- doc,
776
- version: entry.version,
777
- affected: []
778
- };
779
- } else if (entry.operation === import_types2.Operation.Update) {
780
- mutation = {
781
- mutationId: id,
782
- operation: import_types2.Operation.Update,
783
- doc: {
784
- ...entry.values,
785
- doctype: entry.doctype,
786
- name: entry.docname
787
- },
788
- version: entry.version,
789
- affected: []
790
- };
791
- } else {
792
- mutation = {
793
- mutationId: id,
794
- operation: import_types2.Operation.Delete,
795
- doc: {
796
- doctype: entry.doctype,
797
- name: entry.docname
798
- },
799
- version: entry.version,
800
- affected: []
801
- };
802
- }
803
- this.options.onMutationError({
804
- mutation,
805
- err
806
- });
807
- }
808
- /**
809
- * Converts SyncOptions.fieldMergeConfig into the MergeConfig format
810
- * expected by the merge() function.
811
- */
812
- buildMergeConfig() {
813
- const fmc = this.options.fieldMergeConfig;
814
- if (!fmc) return void 0;
815
- const doctypes = {};
816
- for (const [dt, fields] of Object.entries(fmc)) {
817
- doctypes[dt] = {
818
- fields
819
- };
820
- }
821
- return {
822
- defaultStrategy: import_merge.MergeStrategy.ServerWins,
823
- doctypes
824
- };
825
- }
826
- /** Gets temporary to real name mapping. */
827
- getTemporaryIdToRealNameMap() {
828
- return this.temporaryIdToRealNameMap;
829
- }
830
- /** Clears all temporary mappings. */
831
- clearTemporaryMappings() {
832
- this.temporaryIdToRealNameMap.clear();
833
- this.globalOptimisticDocIds.clear();
834
- }
835
- /**
836
- * Disposes of resources.
837
- */
838
- dispose() {
839
- this.batchDebouncer.cancel();
840
- this.pendingBatch = [];
841
- this.clearTemporaryMappings();
842
- }
30
+ if (err instanceof Error) return { message: err.message };
31
+ const message = err?.message;
32
+ return { message: message ?? String(err) };
843
33
  }
34
+ var MutationEngine = class {
35
+ temporaryIdToRealNameMap = /* @__PURE__ */ new Map();
36
+ globalOptimisticDocIds = /* @__PURE__ */ new Map();
37
+ /** Pending mutations waiting to be batched */
38
+ pendingBatch = [];
39
+ /** Debouncer for batch processing */
40
+ batchDebouncer;
41
+ db;
42
+ realtime;
43
+ normalizedCache;
44
+ mutationJournal;
45
+ subscriptionManager;
46
+ rehydrationManager;
47
+ options;
48
+ constructor(db, realtime, normalizedCache, mutationJournal, subscriptionManager, rehydrationManager, options = {}) {
49
+ this.db = db;
50
+ this.realtime = realtime;
51
+ this.normalizedCache = normalizedCache;
52
+ this.mutationJournal = mutationJournal;
53
+ this.subscriptionManager = subscriptionManager;
54
+ this.rehydrationManager = rehydrationManager;
55
+ this.options = options;
56
+ const batchDelay = options.batchDelay ?? 100;
57
+ this.batchDebouncer = new import_pacer.Debouncer(() => this.flushBatch(), { wait: batchDelay });
58
+ }
59
+ /**
60
+ * Queue a mutation for batch processing.
61
+ * Returns a promise that resolves when the batch is processed.
62
+ */
63
+ queueForBatch(mutation) {
64
+ return new Promise((resolve, reject) => {
65
+ this.pendingBatch.push({
66
+ mutation,
67
+ resolve,
68
+ reject
69
+ });
70
+ const maxSize = this.options.batchMaxSize ?? 50;
71
+ if (this.pendingBatch.length >= maxSize) {
72
+ this.flushBatch();
73
+ } else {
74
+ this.batchDebouncer.maybeExecute();
75
+ }
76
+ });
77
+ }
78
+ /**
79
+ * Flush pending mutations as a batch.
80
+ */
81
+ async flushBatch() {
82
+ if (this.pendingBatch.length === 0) return;
83
+ const batch = [...this.pendingBatch];
84
+ this.pendingBatch = [];
85
+ try {
86
+ const batchMutations = batch.map(({ mutation }) => {
87
+ const operationMap = {
88
+ [import_types2.Operation.Create]: "create",
89
+ [import_types2.Operation.Update]: "update",
90
+ [import_types2.Operation.Delete]: "delete"
91
+ };
92
+ return {
93
+ type: operationMap[mutation.operation],
94
+ doctype: mutation.doc.doctype,
95
+ name: mutation.doc.name,
96
+ data: mutation.operation === import_types2.Operation.Delete ? void 0 : mutation.doc
97
+ };
98
+ });
99
+ const results = await this.db.batchMutations({
100
+ mutations: batchMutations,
101
+ atomic: this.options.batchAtomic ?? false
102
+ });
103
+ for (let i = 0; i < batch.length; i++) {
104
+ const { mutation, resolve, reject } = batch[i];
105
+ const result = results[i];
106
+ if (result.success) {
107
+ this.mutationJournal.confirm(mutation.mutationId);
108
+ if (result.data) {
109
+ this.normalizedCache.upsert(result.data);
110
+ if (mutation.operation === import_types2.Operation.Create) {
111
+ const temporaryName = mutation.temporaryName ?? mutation.doc.name;
112
+ if (temporaryName && result.data.name && temporaryName !== result.data.name) {
113
+ this.handleTemporaryToRealMapping(mutation.doc.doctype, temporaryName, result.data.name);
114
+ this.rehydrationManager.registerTempIdMapping(temporaryName, result.data.name);
115
+ } else if (temporaryName) {
116
+ this.globalOptimisticDocIds.get(mutation.doc.doctype)?.delete(temporaryName);
117
+ }
118
+ }
119
+ }
120
+ if (this.options.onMutationSuccess) {
121
+ this.options.onMutationSuccess(mutation);
122
+ }
123
+ resolve(result.data);
124
+ } else {
125
+ const error = new Error(result.error || "Batch mutation failed");
126
+ this.mutationJournal.fail(mutation.mutationId, toJournalError(error));
127
+ reject(error);
128
+ }
129
+ }
130
+ } catch (err) {
131
+ for (const { mutation, reject } of batch) {
132
+ this.mutationJournal.fail(mutation.mutationId, toJournalError(err));
133
+ reject(err);
134
+ }
135
+ }
136
+ }
137
+ /**
138
+ * Force flush any pending batched mutations.
139
+ */
140
+ async forceBatchFlush() {
141
+ this.batchDebouncer.cancel();
142
+ await this.flushBatch();
143
+ }
144
+ async mutate(mutation) {
145
+ if (this.options.onMutationStart) this.options.onMutationStart(mutation);
146
+ const { doc } = mutation;
147
+ if ((mutation.operation === import_types2.Operation.Update || mutation.operation === import_types2.Operation.Delete) && !doc.name) {
148
+ throw new Error("docname is required for update/delete operations");
149
+ }
150
+ let version = mutation.version;
151
+ let cachedDoc = void 0;
152
+ if (doc.name) {
153
+ cachedDoc = this.normalizedCache.get({
154
+ doctype: doc.doctype,
155
+ name: doc.name
156
+ });
157
+ }
158
+ if (version === void 0 && doc.name) {
159
+ const versionField = this.options.versionFields?.[doc.doctype] || this.options.versionField || "modified";
160
+ const cachedVersion = cachedDoc ? cachedDoc[versionField] : void 0;
161
+ if (typeof cachedVersion === "string") version = cachedVersion;
162
+ }
163
+ if (mutation.operation === import_types2.Operation.Update && doc.name) {
164
+ await this.handleOptimisticUpdate(mutation, cachedDoc);
165
+ this.options.onStoreChange?.();
166
+ }
167
+ if (mutation.operation === import_types2.Operation.Create) {
168
+ await this.handleOptimisticCreate(mutation);
169
+ this.options.onStoreChange?.();
170
+ }
171
+ if (version === void 0 && doc.name && (mutation.operation === import_types2.Operation.Update || mutation.operation === import_types2.Operation.Delete) && !cachedDoc) {
172
+ try {
173
+ cachedDoc = await this.db.getDoc(doc.doctype, doc.name);
174
+ const versionField = this.options.versionFields?.[doc.doctype] || this.options.versionField || "modified";
175
+ const cachedVersion = cachedDoc ? cachedDoc[versionField] : void 0;
176
+ if (typeof cachedVersion === "string") version = cachedVersion;
177
+ this.normalizedCache.upsert(cachedDoc);
178
+ } catch (err) {
179
+ if (this.options.onTrace) {
180
+ this.options.onTrace({
181
+ event: "version-fetch-failed",
182
+ details: {
183
+ doctype: doc.doctype,
184
+ name: doc.name,
185
+ error: err
186
+ }
187
+ });
188
+ }
189
+ }
190
+ }
191
+ const values = mutation.operation === import_types2.Operation.Delete ? void 0 : mutation.operation === import_types2.Operation.Create ? mutation.doc : mutation.doc;
192
+ this.mutationJournal.add(mutation.mutationId, {
193
+ doctype: doc.doctype,
194
+ docname: mutation.operation === import_types2.Operation.Create ? mutation.temporaryName ?? doc.name : doc.name,
195
+ values,
196
+ operation: mutation.operation,
197
+ version,
198
+ status: import_types2.Status.Pending,
199
+ snapshot: doc.name ? cachedDoc : void 0
200
+ });
201
+ if (mutation.operation === import_types2.Operation.Delete && doc.name) {
202
+ this.applyOptimisticDelete(doc.doctype, doc.name);
203
+ this.options.onStoreChange?.();
204
+ }
205
+ if (this.options.enableBatching && !mutation.execute) {
206
+ try {
207
+ await this.queueForBatch(mutation);
208
+ if (mutation.operation === import_types2.Operation.Create) {
209
+ for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
210
+ if (subscription.query.doctype === mutation.doc.doctype) {
211
+ this.rehydrationManager.scheduleRehydration(subscription, import_types2.RehydrationReason.Create);
212
+ }
213
+ }
214
+ }
215
+ } catch (err) {
216
+ await this.handleMutationError(mutation, err);
217
+ throw err;
218
+ }
219
+ return;
220
+ }
221
+ try {
222
+ if (mutation.operation === import_types2.Operation.Create) {
223
+ await this.handleServerCreate(mutation);
224
+ } else if (mutation.operation === import_types2.Operation.Update && doc.name) {
225
+ await this.handleServerUpdate(mutation, version);
226
+ } else if (mutation.operation === import_types2.Operation.Delete && doc.name) {
227
+ await this.handleServerDelete(mutation, version);
228
+ }
229
+ this.mutationJournal.confirm(mutation.mutationId);
230
+ if (this.options.onMutationSuccess) {
231
+ this.options.onMutationSuccess(mutation);
232
+ }
233
+ if (mutation.operation === import_types2.Operation.Create) {
234
+ for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
235
+ if (subscription.query.doctype === mutation.doc.doctype) {
236
+ this.rehydrationManager.scheduleRehydration(subscription, import_types2.RehydrationReason.Create);
237
+ }
238
+ }
239
+ }
240
+ if (!this.realtime?.isHealthy()) {
241
+ await this.refetchAffectedDocs(mutation);
242
+ }
243
+ } catch (err) {
244
+ await this.handleMutationError(mutation, err);
245
+ throw err;
246
+ }
247
+ }
248
+ async handleOptimisticUpdate(mutation, cachedDoc) {
249
+ const doc = cachedDoc ? {
250
+ ...cachedDoc,
251
+ ...mutation.doc
252
+ } : mutation.doc;
253
+ this.normalizedCache.upsert(doc);
254
+ if (this.options.onOptimisticApply) {
255
+ this.options.onOptimisticApply({
256
+ doctype: mutation.doc.doctype,
257
+ name: mutation.doc.name,
258
+ operation: mutation.operation
259
+ });
260
+ }
261
+ this.subscriptionManager.updateSubscriptionMembership(doc);
262
+ }
263
+ async handleOptimisticCreate(mutation) {
264
+ const temporaryName = mutation.doc.name || `tmp_${cryptoRandomId()}`;
265
+ mutation.temporaryName = temporaryName;
266
+ const optimisticDoc = {
267
+ ...mutation.doc,
268
+ name: temporaryName
269
+ };
270
+ this.normalizedCache.upsert(optimisticDoc);
271
+ if (!this.globalOptimisticDocIds.has(mutation.doc.doctype)) {
272
+ this.globalOptimisticDocIds.set(mutation.doc.doctype, /* @__PURE__ */ new Set());
273
+ }
274
+ const globalDocIds = this.globalOptimisticDocIds.get(mutation.doc.doctype);
275
+ for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
276
+ if (subscription.query.doctype !== mutation.doc.doctype) continue;
277
+ const matches = (0, import_filters.matchesFilters)(optimisticDoc, subscription.query.filters);
278
+ if (!matches) continue;
279
+ if (globalDocIds.has(temporaryName)) {
280
+ continue;
281
+ }
282
+ if (subscription.query.orderBy && typeof subscription.query.limit === "number" && subscription.query.limit > 0 && subscription.docIds.length > 0) {
283
+ const placement = this.determineOptimisticPlacement(subscription, optimisticDoc);
284
+ switch (placement) {
285
+ case import_types2.PlacementType.Before:
286
+ if (subscription.metadata) {
287
+ subscription.metadata.itemsBeforePage = (subscription.metadata.itemsBeforePage || 0) + 1;
288
+ }
289
+ continue;
290
+ case import_types2.PlacementType.After:
291
+ if (subscription.metadata) {
292
+ subscription.metadata.itemsAfterPage = (subscription.metadata.itemsAfterPage || 0) + 1;
293
+ }
294
+ continue;
295
+ case import_types2.PlacementType.Unknown:
296
+ subscription.pendingRehydration = import_types2.PendingRehydrationType.FullRefresh;
297
+ this.rehydrationManager.scheduleRehydration(subscription, import_types2.RehydrationReason.Uncertain);
298
+ break;
299
+ case import_types2.PlacementType.Within: break;
300
+ }
301
+ }
302
+ if (!subscription.docIds.includes(temporaryName)) {
303
+ this.subscriptionManager.insertDocumentIntoSubscription(subscription, optimisticDoc);
304
+ globalDocIds.add(temporaryName);
305
+ }
306
+ }
307
+ }
308
+ async handleServerCreate(mutation) {
309
+ const created = mutation.execute ? await mutation.execute() : await this.db.createDoc({
310
+ ...mutation.doc,
311
+ client_mutation_id: mutation.mutationId
312
+ });
313
+ const realName = created?.name;
314
+ const temporaryName = mutation.temporaryName ?? mutation.doc.name;
315
+ if (realName) {
316
+ this.normalizedCache.upsert({
317
+ ...created,
318
+ doctype: created.doctype || mutation.doc.doctype
319
+ });
320
+ }
321
+ if (realName && temporaryName && realName !== temporaryName) {
322
+ this.handleTemporaryToRealMapping(mutation.doc.doctype, temporaryName, realName);
323
+ this.rehydrationManager.registerTempIdMapping(temporaryName, realName);
324
+ } else if (temporaryName) {
325
+ const globalDocs = this.globalOptimisticDocIds.get(mutation.doc.doctype);
326
+ if (globalDocs) {
327
+ globalDocs.delete(temporaryName);
328
+ }
329
+ }
330
+ }
331
+ async handleServerUpdate(mutation, _version) {
332
+ if (mutation.execute) {
333
+ const updated = await mutation.execute();
334
+ if (updated?.name) {
335
+ this.normalizedCache.upsert({
336
+ ...updated,
337
+ doctype: updated.doctype || mutation.doc.doctype
338
+ });
339
+ }
340
+ return;
341
+ }
342
+ await this.db.updateDoc(mutation.doc);
343
+ }
344
+ /**
345
+ * Applies the local side of a delete: cache eviction, subscription
346
+ * membership removal, and gap-filling rehydration. Runs before the server
347
+ * call (mutate() body) so the row disappears immediately; the journal
348
+ * snapshot restores it if the server rejects.
349
+ */
350
+ applyOptimisticDelete(doctype, name) {
351
+ const affected = [...this.subscriptionManager.getAllSubscriptions().values()].filter((subscription) => subscription.query.doctype === doctype && subscription.docIds.includes(name));
352
+ this.normalizedCache.remove({
353
+ doctype,
354
+ name
355
+ });
356
+ this.subscriptionManager.removeFromAllSubscriptions(doctype, name);
357
+ for (const subscription of affected) {
358
+ this.rehydrationManager.scheduleRehydration(subscription, import_types2.RehydrationReason.Delete);
359
+ }
360
+ }
361
+ async handleServerDelete(mutation, _version) {
362
+ if (mutation.execute) {
363
+ await mutation.execute();
364
+ return;
365
+ }
366
+ await this.db.deleteDoc(mutation.doc);
367
+ }
368
+ handleTemporaryToRealMapping(doctype, temporaryName, realName) {
369
+ this.temporaryIdToRealNameMap.set(temporaryName, realName);
370
+ const globalDocs = this.globalOptimisticDocIds.get(doctype);
371
+ if (globalDocs) {
372
+ globalDocs.delete(temporaryName);
373
+ }
374
+ for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
375
+ if (subscription.query.doctype !== doctype) continue;
376
+ if (!subscription.docIds.includes(temporaryName)) continue;
377
+ subscription.docIds = subscription.docIds.includes(realName) ? subscription.docIds.filter((id) => id !== temporaryName) : subscription.docIds.map((id) => id === temporaryName ? realName : id);
378
+ }
379
+ this.normalizedCache.remove({
380
+ doctype,
381
+ name: temporaryName
382
+ });
383
+ }
384
+ async refetchAffectedDocs(mutation) {
385
+ const targets = [];
386
+ const docname = mutation.doc.name;
387
+ const doctype = mutation.doc.doctype;
388
+ const realName = docname && this.temporaryIdToRealNameMap.get(docname) || docname;
389
+ if (realName && mutation.operation === import_types2.Operation.Update) {
390
+ targets.push({
391
+ doctype,
392
+ name: realName
393
+ });
394
+ }
395
+ if (mutation.affected?.length) targets.push(...mutation.affected);
396
+ for (const target of targets) {
397
+ const fresh = await this.db.getDoc(target.doctype, target.name);
398
+ this.normalizedCache.upsert(fresh);
399
+ }
400
+ }
401
+ async handleMutationError(mutation, err) {
402
+ if (this.options.onMutationError) this.options.onMutationError({
403
+ mutation,
404
+ err
405
+ });
406
+ this.mutationJournal.fail(mutation.mutationId, toJournalError(err));
407
+ const entry = this.mutationJournal.get(mutation.mutationId);
408
+ const isOffline = typeof navigator !== "undefined" && navigator.onLine === false;
409
+ if (!isOffline) {
410
+ await this.rollbackOptimisticState(mutation, entry);
411
+ }
412
+ const errorWithStatus = err;
413
+ const docname = mutation.doc.name;
414
+ if (errorWithStatus && (errorWithStatus.status === 409 || errorWithStatus.status === 412) && docname) {
415
+ await this.handleConflict(mutation, entry);
416
+ }
417
+ }
418
+ /**
419
+ * Rolls back optimistic state when a mutation fails.
420
+ * Handles all operation types: create, update, and delete.
421
+ */
422
+ async rollbackOptimisticState(mutation, entry) {
423
+ const doctype = mutation.doc.doctype;
424
+ const docname = mutation.doc.name;
425
+ switch (mutation.operation) {
426
+ case import_types2.Operation.Create:
427
+ await this.handleFailedCreate(mutation);
428
+ break;
429
+ case import_types2.Operation.Update:
430
+ if (entry?.snapshot && docname) {
431
+ this.normalizedCache.upsert(entry.snapshot, { replace: true });
432
+ this.subscriptionManager.updateSubscriptionMembership(entry.snapshot);
433
+ }
434
+ break;
435
+ case import_types2.Operation.Delete:
436
+ if (entry?.snapshot && docname) {
437
+ this.normalizedCache.upsert(entry.snapshot, { replace: true });
438
+ const restoredDoc = entry.snapshot;
439
+ for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
440
+ if (subscription.query.doctype !== doctype) continue;
441
+ const matches = (0, import_filters.matchesFilters)(restoredDoc, subscription.query.filters);
442
+ if (matches && !subscription.docIds.includes(docname)) {
443
+ this.subscriptionManager.insertDocumentIntoSubscription(subscription, restoredDoc);
444
+ }
445
+ }
446
+ }
447
+ break;
448
+ }
449
+ }
450
+ async handleFailedCreate(mutation) {
451
+ const temporaryName = mutation.operation === import_types2.Operation.Create ? mutation.temporaryName ?? mutation.doc.name : mutation.doc.name;
452
+ const doctype = mutation.doc.doctype;
453
+ if (temporaryName) {
454
+ const globalDocs = this.globalOptimisticDocIds.get(doctype);
455
+ if (globalDocs) {
456
+ globalDocs.delete(temporaryName);
457
+ }
458
+ for (const subscription of this.subscriptionManager.getAllSubscriptions().values()) {
459
+ if (subscription.query.doctype !== doctype) continue;
460
+ subscription.docIds = subscription.docIds.filter((id) => id !== temporaryName);
461
+ }
462
+ this.normalizedCache.remove({
463
+ doctype,
464
+ name: temporaryName
465
+ });
466
+ }
467
+ }
468
+ async handleConflict(mutation, entry) {
469
+ const doctype = mutation.doc.doctype;
470
+ const docname = mutation.doc.name;
471
+ if (!docname) return;
472
+ try {
473
+ const latest = await this.db.getDoc(doctype, docname);
474
+ const base = entry?.snapshot;
475
+ const clientPartial = (mutation.operation === import_types2.Operation.Delete ? void 0 : mutation.doc) ?? {};
476
+ const fullClient = base ? {
477
+ ...base,
478
+ ...clientPartial,
479
+ doctype,
480
+ name: docname
481
+ } : {
482
+ ...clientPartial,
483
+ doctype,
484
+ name: docname
485
+ };
486
+ const mergeConfig = this.buildMergeConfig();
487
+ const nonOverlap = (0, import_merge.merge)(base, fullClient, latest, mergeConfig, doctype);
488
+ if (!nonOverlap.hasConflicts) {
489
+ const versionField = this.options.versionFields?.[doctype] || this.options.versionField || "modified";
490
+ if (nonOverlap.merged) {
491
+ const newId = cryptoRandomId();
492
+ await this.db.updateDoc({
493
+ ...nonOverlap.merged,
494
+ client_mutation_id: newId,
495
+ base_modified: latest[versionField] || void 0
496
+ });
497
+ }
498
+ const refreshed = await this.db.getDoc(doctype, docname);
499
+ this.normalizedCache.upsert(refreshed);
500
+ this.mutationJournal.confirm(mutation.mutationId);
501
+ return;
502
+ }
503
+ this.normalizedCache.upsert(latest);
504
+ } catch {}
505
+ if (this.options.onConflict) this.options.onConflict({
506
+ doctype,
507
+ name: docname
508
+ });
509
+ }
510
+ /**
511
+ * Determines optimal placement for an optimistic item based on sort fields.
512
+ * Supports multi-column sorting with proper tie-breaking.
513
+ *
514
+ * @param subscription - The subscription to check placement against
515
+ * @param candidate - The document to place
516
+ * @returns Placement relative to current page:
517
+ * - 'before': Item belongs on a previous page
518
+ * - 'within': Item belongs on the current page
519
+ * - 'after': Item belongs on a later page
520
+ * - 'unknown': Cannot determine placement (needs full refresh)
521
+ *
522
+ * @remarks
523
+ * Uses page boundaries when available for O(1) placement checks.
524
+ * Falls back to comparing against first/last items in current page.
525
+ * Supports multi-field sorting with tie-breaking.
526
+ */
527
+ determineOptimisticPlacement(subscription, candidate) {
528
+ const docIds = subscription.docIds;
529
+ if (!docIds.length) return import_types2.PlacementType.Unknown;
530
+ if (subscription.boundaries?.firstItem && subscription.boundaries?.lastItem) {
531
+ return this.determinePlacementWithBoundaries(subscription.boundaries, candidate, subscription.query.orderBy);
532
+ }
533
+ const order = subscription.query.orderBy;
534
+ if (!order) return import_types2.PlacementType.Unknown;
535
+ const doctype = subscription.query.doctype;
536
+ const first = this.normalizedCache.get({
537
+ doctype,
538
+ name: docIds[0]
539
+ });
540
+ const last = this.normalizedCache.get({
541
+ doctype,
542
+ name: docIds[docIds.length - 1]
543
+ });
544
+ if (!first || !last) return import_types2.PlacementType.Unknown;
545
+ const sortFields = this.parseSortFields(order);
546
+ for (const { field, isAsc } of sortFields) {
547
+ const candidateValue = candidate[field];
548
+ const firstValue = first[field];
549
+ const lastValue = last[field];
550
+ if (candidateValue == null || firstValue == null || lastValue == null) {
551
+ continue;
552
+ }
553
+ if (isAsc) {
554
+ if (candidateValue < firstValue) return import_types2.PlacementType.Before;
555
+ if (candidateValue > lastValue) return import_types2.PlacementType.After;
556
+ } else {
557
+ if (candidateValue > firstValue) return import_types2.PlacementType.Before;
558
+ if (candidateValue < lastValue) return import_types2.PlacementType.After;
559
+ }
560
+ if (candidateValue !== firstValue && candidateValue !== lastValue) {
561
+ return import_types2.PlacementType.Within;
562
+ }
563
+ }
564
+ return import_types2.PlacementType.Within;
565
+ }
566
+ determinePlacementWithBoundaries(boundaries, candidate, orderBy) {
567
+ if (!boundaries.firstItem || !boundaries.lastItem) return import_types2.PlacementType.Unknown;
568
+ const sortFields = this.parseSortFields(orderBy);
569
+ for (const { field, isAsc } of sortFields) {
570
+ const candidateValue = candidate[field];
571
+ const firstValue = boundaries.firstItem[field];
572
+ const lastValue = boundaries.lastItem[field];
573
+ if (candidateValue == null || firstValue == null || lastValue == null) {
574
+ continue;
575
+ }
576
+ if (isAsc) {
577
+ if (candidateValue < firstValue) return import_types2.PlacementType.Before;
578
+ if (candidateValue > lastValue) return import_types2.PlacementType.After;
579
+ } else {
580
+ if (candidateValue > firstValue) return import_types2.PlacementType.Before;
581
+ if (candidateValue < lastValue) return import_types2.PlacementType.After;
582
+ }
583
+ if (candidateValue !== firstValue && candidateValue !== lastValue) {
584
+ return import_types2.PlacementType.Within;
585
+ }
586
+ }
587
+ return import_types2.PlacementType.Within;
588
+ }
589
+ parseSortFields(orderBy) {
590
+ if (!orderBy) return [{
591
+ field: "name",
592
+ isAsc: true
593
+ }];
594
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
595
+ const sortFields = orderByArray.map((ob) => ({
596
+ field: ob.field,
597
+ isAsc: ob.order !== import_types.Order.Desc
598
+ }));
599
+ const hasNameField = sortFields.some((sf) => sf.field === "name");
600
+ if (!hasNameField) {
601
+ sortFields.push({
602
+ field: "name",
603
+ isAsc: true
604
+ });
605
+ }
606
+ return sortFields;
607
+ }
608
+ /**
609
+ * Replays pending mutations with simplified error handling and rate limiting.
610
+ *
611
+ * Since HTTP client now handles retries automatically for transient errors,
612
+ * we only need to handle:
613
+ * - Success → confirm and remove from journal
614
+ * - Conflict (409/412) → attempt merge resolution, then retry
615
+ * - Auth (401/403) → notify user, keep in journal for later retry
616
+ * - Permanent (4xx validation) → fail and remove from journal
617
+ * - Failed (exhausted retries) → keep in journal but notify
618
+ *
619
+ * The replay path uses plain CRUD without optimistic writes,
620
+ * since optimistic state is already reflected in the cache.
621
+ *
622
+ * Rate limiting is applied to prevent hammering the server when replaying
623
+ * large numbers of queued mutations after coming back online.
624
+ */
625
+ async replayPending() {
626
+ let anyFailed = false;
627
+ if (this.options.onReplayStart) this.options.onReplayStart();
628
+ const pendingMutations = this.mutationJournal.listPending();
629
+ if (pendingMutations.length === 0) {
630
+ if (this.options.onReplayComplete) {
631
+ this.options.onReplayComplete({ anyFailed: false });
632
+ }
633
+ return;
634
+ }
635
+ const rateLimit = this.options.replayRateLimit ?? 10;
636
+ const processMutation = async (mutation) => {
637
+ const { id, entry } = mutation;
638
+ if (this.options.onRetry) {
639
+ this.options.onRetry({
640
+ id,
641
+ operation: entry.operation
642
+ });
643
+ }
644
+ try {
645
+ if (entry.operation === import_types2.Operation.Create) {
646
+ const created = await this.db.createDoc({
647
+ ...entry.values,
648
+ client_mutation_id: id,
649
+ doctype: entry.doctype,
650
+ name: entry.docname || cryptoRandomId()
651
+ });
652
+ if (created?.name) {
653
+ this.normalizedCache.upsert({
654
+ ...created,
655
+ doctype: created.doctype || entry.doctype
656
+ });
657
+ if (entry.docname && created.name !== entry.docname) {
658
+ this.handleTemporaryToRealMapping(entry.doctype, entry.docname, created.name);
659
+ this.rehydrationManager.registerTempIdMapping(entry.docname, created.name);
660
+ }
661
+ }
662
+ } else if (entry.operation === import_types2.Operation.Update && entry.docname) {
663
+ await this.db.updateDoc({
664
+ ...entry.values,
665
+ client_mutation_id: id,
666
+ base_modified: entry.version,
667
+ doctype: entry.doctype,
668
+ name: entry.docname
669
+ });
670
+ } else if (entry.operation === import_types2.Operation.Delete && entry.docname) {
671
+ await this.db.deleteDoc({
672
+ doctype: entry.doctype,
673
+ name: entry.docname,
674
+ client_mutation_id: id
675
+ });
676
+ }
677
+ this.mutationJournal.confirm(id);
678
+ } catch (err) {
679
+ const errorClass = this.classifyError(err);
680
+ anyFailed = true;
681
+ if (errorClass === "conflict") {
682
+ if (this.options.onConflict) {
683
+ this.options.onConflict({
684
+ doctype: entry.doctype,
685
+ name: entry.docname
686
+ });
687
+ }
688
+ } else if (errorClass === "auth") {} else if (errorClass === "permanent") {
689
+ this.mutationJournal.fail(id, toJournalError(err));
690
+ this.notifyMutationError(id, entry, err);
691
+ } else if (errorClass === "failed") {
692
+ this.mutationJournal.fail(id, toJournalError(err));
693
+ this.notifyMutationError(id, entry, err);
694
+ }
695
+ }
696
+ };
697
+ const delayMs = Math.ceil(1e3 / rateLimit);
698
+ for (const mutation of pendingMutations) {
699
+ await processMutation(mutation);
700
+ if (pendingMutations.indexOf(mutation) < pendingMutations.length - 1) {
701
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
702
+ }
703
+ }
704
+ if (this.options.onReplayComplete) {
705
+ this.options.onReplayComplete({ anyFailed });
706
+ }
707
+ }
708
+ /**
709
+ * Classifies errors for journal management.
710
+ */
711
+ classifyError(err) {
712
+ const errorWithStatus = err;
713
+ const status = errorWithStatus?.status || errorWithStatus?.response?.status;
714
+ if (status === 409 || status === 412) return "conflict";
715
+ if (status === 401 || status === 403) return "auth";
716
+ if (status && status >= 400 && status < 500) return "permanent";
717
+ return "failed";
718
+ }
719
+ /**
720
+ * Helper to notify about mutation errors with proper typing
721
+ */
722
+ notifyMutationError(id, entry, err) {
723
+ if (!this.options.onMutationError) return;
724
+ let mutation;
725
+ if (entry.operation === import_types2.Operation.Create) {
726
+ const doc = entry.values || {
727
+ doctype: entry.doctype,
728
+ name: entry.docname
729
+ };
730
+ mutation = {
731
+ mutationId: id,
732
+ operation: import_types2.Operation.Create,
733
+ doc,
734
+ version: entry.version,
735
+ affected: []
736
+ };
737
+ } else if (entry.operation === import_types2.Operation.Update) {
738
+ mutation = {
739
+ mutationId: id,
740
+ operation: import_types2.Operation.Update,
741
+ doc: {
742
+ ...entry.values,
743
+ doctype: entry.doctype,
744
+ name: entry.docname
745
+ },
746
+ version: entry.version,
747
+ affected: []
748
+ };
749
+ } else {
750
+ mutation = {
751
+ mutationId: id,
752
+ operation: import_types2.Operation.Delete,
753
+ doc: {
754
+ doctype: entry.doctype,
755
+ name: entry.docname
756
+ },
757
+ version: entry.version,
758
+ affected: []
759
+ };
760
+ }
761
+ this.options.onMutationError({
762
+ mutation,
763
+ err
764
+ });
765
+ }
766
+ /**
767
+ * Converts SyncOptions.fieldMergeConfig into the MergeConfig format
768
+ * expected by the merge() function.
769
+ */
770
+ buildMergeConfig() {
771
+ const fmc = this.options.fieldMergeConfig;
772
+ if (!fmc) return void 0;
773
+ const doctypes = {};
774
+ for (const [dt, fields] of Object.entries(fmc)) {
775
+ doctypes[dt] = { fields };
776
+ }
777
+ return {
778
+ defaultStrategy: import_merge.MergeStrategy.ServerWins,
779
+ doctypes
780
+ };
781
+ }
782
+ /** Gets temporary to real name mapping. */
783
+ getTemporaryIdToRealNameMap() {
784
+ return this.temporaryIdToRealNameMap;
785
+ }
786
+ /** Clears all temporary mappings. */
787
+ clearTemporaryMappings() {
788
+ this.temporaryIdToRealNameMap.clear();
789
+ this.globalOptimisticDocIds.clear();
790
+ }
791
+ /**
792
+ * Disposes of resources.
793
+ */
794
+ dispose() {
795
+ this.batchDebouncer.cancel();
796
+ this.pendingBatch = [];
797
+ this.clearTemporaryMappings();
798
+ }
799
+ };
844
800
  function cryptoRandomId() {
845
- if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
846
- return Math.random().toString(36).slice(2);
847
- }
801
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
802
+ return Math.random().toString(36).slice(2);
803
+ }