@aionbuilders/nabu 0.1.0-alpha.9 → 0.1.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 (319) hide show
  1. package/CHANGELOG.md +523 -0
  2. package/LICENSE +21 -0
  3. package/README.md +82 -144
  4. package/dist/behaviors/text/RichText.svelte +25 -2
  5. package/dist/behaviors/text/index.d.ts +2 -0
  6. package/dist/behaviors/text/index.js +2 -0
  7. package/dist/behaviors/text/markdown-shortcuts.extension.d.ts +5 -0
  8. package/dist/behaviors/text/markdown-shortcuts.extension.js +79 -0
  9. package/dist/behaviors/text/markdown-syntax.d.ts +42 -0
  10. package/dist/behaviors/text/markdown-syntax.js +81 -0
  11. package/dist/behaviors/text/rich-text.extension.d.ts +3 -0
  12. package/dist/behaviors/text/rich-text.extension.js +135 -53
  13. package/dist/behaviors/text/text.behavior.svelte.d.ts +217 -42
  14. package/dist/behaviors/text/text.behavior.svelte.js +657 -55
  15. package/dist/behaviors/text/typography.extension.d.ts +7 -0
  16. package/dist/behaviors/text/typography.extension.js +25 -0
  17. package/dist/blocks/Block.svelte +5 -2
  18. package/dist/blocks/BlockList.svelte +48 -0
  19. package/dist/blocks/BlockList.svelte.d.ts +17 -0
  20. package/dist/blocks/Nabu.svelte +180 -14
  21. package/dist/blocks/Nabu.svelte.d.ts +13 -0
  22. package/dist/blocks/block.extension.d.ts +3 -0
  23. package/dist/blocks/block.extension.js +8 -9
  24. package/dist/blocks/block.svelte.d.ts +356 -68
  25. package/dist/blocks/block.svelte.js +388 -42
  26. package/dist/blocks/blockquote/Blockquote.svelte +39 -0
  27. package/dist/blocks/blockquote/Blockquote.svelte.d.ts +11 -0
  28. package/dist/blocks/blockquote/blockquote.extension.d.ts +4 -0
  29. package/dist/blocks/blockquote/blockquote.extension.js +80 -0
  30. package/dist/blocks/blockquote/blockquote.svelte.d.ts +63 -0
  31. package/dist/blocks/blockquote/blockquote.svelte.js +136 -0
  32. package/dist/blocks/blockquote/index.d.ts +3 -0
  33. package/dist/blocks/blockquote/index.js +3 -0
  34. package/dist/blocks/callout/Callout.svelte +67 -0
  35. package/dist/blocks/callout/Callout.svelte.d.ts +11 -0
  36. package/dist/blocks/callout/callout.extension.d.ts +4 -0
  37. package/dist/blocks/callout/callout.extension.js +84 -0
  38. package/dist/blocks/callout/callout.svelte.d.ts +80 -0
  39. package/dist/blocks/callout/callout.svelte.js +189 -0
  40. package/dist/blocks/callout/index.d.ts +3 -0
  41. package/dist/blocks/callout/index.js +3 -0
  42. package/dist/blocks/chunks.d.ts +49 -0
  43. package/dist/blocks/chunks.js +90 -0
  44. package/dist/blocks/code/Code.svelte +84 -0
  45. package/dist/blocks/code/Code.svelte.d.ts +11 -0
  46. package/dist/blocks/code/code.extension.d.ts +4 -0
  47. package/dist/blocks/code/code.extension.js +88 -0
  48. package/dist/blocks/code/code.svelte.d.ts +68 -0
  49. package/dist/blocks/code/code.svelte.js +245 -0
  50. package/dist/blocks/code/index.d.ts +3 -0
  51. package/dist/blocks/code/index.js +3 -0
  52. package/dist/blocks/container.utils.d.ts +85 -13
  53. package/dist/blocks/container.utils.js +338 -178
  54. package/dist/blocks/dialogue/Dialogue.svelte +8 -2
  55. package/dist/blocks/dialogue/dialogue.svelte.d.ts +36 -23
  56. package/dist/blocks/dialogue/dialogue.svelte.js +51 -45
  57. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +2 -2
  58. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +6 -4
  59. package/dist/blocks/dialogue/index.d.ts +12 -1
  60. package/dist/blocks/dialogue/index.js +51 -35
  61. package/dist/blocks/divider/Divider.svelte +28 -0
  62. package/dist/blocks/divider/Divider.svelte.d.ts +11 -0
  63. package/dist/blocks/divider/divider.extension.d.ts +23 -0
  64. package/dist/blocks/divider/divider.extension.js +153 -0
  65. package/dist/blocks/divider/divider.svelte.d.ts +54 -0
  66. package/dist/blocks/divider/divider.svelte.js +89 -0
  67. package/dist/blocks/divider/index.d.ts +3 -0
  68. package/dist/blocks/divider/index.js +3 -0
  69. package/dist/blocks/file/File.svelte +56 -0
  70. package/dist/blocks/file/File.svelte.d.ts +11 -0
  71. package/dist/blocks/file/file.extension.d.ts +4 -0
  72. package/dist/blocks/file/file.extension.js +27 -0
  73. package/dist/blocks/file/file.svelte.d.ts +29 -0
  74. package/dist/blocks/file/file.svelte.js +77 -0
  75. package/dist/blocks/file/index.d.ts +3 -0
  76. package/dist/blocks/file/index.js +3 -0
  77. package/dist/blocks/heading/Heading.svelte +2 -1
  78. package/dist/blocks/heading/heading.svelte.d.ts +27 -34
  79. package/dist/blocks/heading/heading.svelte.js +72 -60
  80. package/dist/blocks/heading/hooks/onBeforeInput.hook.js +7 -5
  81. package/dist/blocks/heading/index.d.ts +2 -2
  82. package/dist/blocks/heading/index.js +33 -8
  83. package/dist/blocks/image/Image.svelte +41 -0
  84. package/dist/blocks/image/Image.svelte.d.ts +11 -0
  85. package/dist/blocks/image/image.extension.d.ts +5 -0
  86. package/dist/blocks/image/image.extension.js +34 -0
  87. package/dist/blocks/image/image.svelte.d.ts +61 -0
  88. package/dist/blocks/image/image.svelte.js +114 -0
  89. package/dist/blocks/image/index.d.ts +3 -0
  90. package/dist/blocks/image/index.js +3 -0
  91. package/dist/blocks/index.d.ts +11 -1
  92. package/dist/blocks/index.js +11 -1
  93. package/dist/blocks/list/List.svelte +9 -2
  94. package/dist/blocks/list/ListItem.svelte +44 -7
  95. package/dist/blocks/list/convert.d.ts +20 -0
  96. package/dist/blocks/list/convert.js +92 -0
  97. package/dist/blocks/list/hooks/onBeforeInput.hook.js +60 -26
  98. package/dist/blocks/list/html-flat.d.ts +78 -0
  99. package/dist/blocks/list/html-flat.js +244 -0
  100. package/dist/blocks/list/indent.d.ts +86 -0
  101. package/dist/blocks/list/indent.js +205 -0
  102. package/dist/blocks/list/index.d.ts +7 -3
  103. package/dist/blocks/list/index.js +43 -31
  104. package/dist/blocks/list/list-item.svelte.d.ts +43 -17
  105. package/dist/blocks/list/list-item.svelte.js +143 -93
  106. package/dist/blocks/list/list.behavior.svelte.d.ts +7 -4
  107. package/dist/blocks/list/list.behavior.svelte.js +10 -5
  108. package/dist/blocks/list/list.svelte.d.ts +101 -23
  109. package/dist/blocks/list/list.svelte.js +136 -114
  110. package/dist/blocks/list/markdown.d.ts +149 -0
  111. package/dist/blocks/list/markdown.js +442 -0
  112. package/dist/blocks/list/normalize.d.ts +11 -0
  113. package/dist/blocks/list/normalize.js +396 -0
  114. package/dist/blocks/list/paste.d.ts +45 -0
  115. package/dist/blocks/list/paste.js +242 -0
  116. package/dist/blocks/list/step-back.d.ts +24 -0
  117. package/dist/blocks/list/step-back.js +87 -0
  118. package/dist/blocks/list/to-list.d.ts +7 -0
  119. package/dist/blocks/list/to-list.js +44 -0
  120. package/dist/blocks/list/todos-toggle.d.ts +20 -0
  121. package/dist/blocks/list/todos-toggle.js +48 -0
  122. package/dist/blocks/list/todos.svelte.d.ts +35 -0
  123. package/dist/blocks/list/todos.svelte.js +76 -0
  124. package/dist/blocks/media/index.d.ts +2 -0
  125. package/dist/blocks/media/index.js +2 -0
  126. package/dist/blocks/media/markdown.d.ts +12 -0
  127. package/dist/blocks/media/markdown.js +26 -0
  128. package/dist/blocks/media/media-block.svelte.d.ts +107 -0
  129. package/dist/blocks/media/media-block.svelte.js +181 -0
  130. package/dist/blocks/media/media.helpers.d.ts +24 -0
  131. package/dist/blocks/media/media.helpers.js +88 -0
  132. package/dist/blocks/megablock.svelte.d.ts +50 -19
  133. package/dist/blocks/megablock.svelte.js +115 -74
  134. package/dist/blocks/move.d.ts +23 -0
  135. package/dist/blocks/move.js +92 -0
  136. package/dist/blocks/nabu.svelte.d.ts +846 -75
  137. package/dist/blocks/nabu.svelte.js +1990 -182
  138. package/dist/blocks/paragraph/Paragraph.svelte +1 -0
  139. package/dist/blocks/paragraph/index.d.ts +2 -2
  140. package/dist/blocks/paragraph/index.js +35 -16
  141. package/dist/blocks/paragraph/paragraph.svelte.d.ts +49 -35
  142. package/dist/blocks/paragraph/paragraph.svelte.js +81 -69
  143. package/dist/blocks/paragraph/table.html.d.ts +9 -0
  144. package/dist/blocks/paragraph/table.html.js +111 -0
  145. package/dist/blocks/paragraph/table.markdown.d.ts +32 -0
  146. package/dist/blocks/paragraph/table.markdown.js +90 -0
  147. package/dist/blocks/region/Region.svelte +264 -0
  148. package/dist/blocks/region/Region.svelte.d.ts +11 -0
  149. package/dist/blocks/region/actions.d.ts +135 -0
  150. package/dist/blocks/region/actions.js +402 -0
  151. package/dist/blocks/region/close.d.ts +35 -0
  152. package/dist/blocks/region/close.js +130 -0
  153. package/dist/blocks/region/commands.d.ts +6 -0
  154. package/dist/blocks/region/commands.js +277 -0
  155. package/dist/blocks/region/create.d.ts +72 -0
  156. package/dist/blocks/region/create.js +208 -0
  157. package/dist/blocks/region/end-marker.d.ts +35 -0
  158. package/dist/blocks/region/end-marker.js +51 -0
  159. package/dist/blocks/region/facts.d.ts +69 -0
  160. package/dist/blocks/region/facts.js +152 -0
  161. package/dist/blocks/region/format.d.ts +91 -0
  162. package/dist/blocks/region/format.js +260 -0
  163. package/dist/blocks/region/index.d.ts +14 -0
  164. package/dist/blocks/region/index.js +14 -0
  165. package/dist/blocks/region/insert.d.ts +59 -0
  166. package/dist/blocks/region/insert.js +102 -0
  167. package/dist/blocks/region/messages.d.ts +254 -0
  168. package/dist/blocks/region/messages.js +131 -0
  169. package/dist/blocks/region/normalize.d.ts +7 -0
  170. package/dist/blocks/region/normalize.js +170 -0
  171. package/dist/blocks/region/region.extension.d.ts +58 -0
  172. package/dist/blocks/region/region.extension.js +119 -0
  173. package/dist/blocks/region/region.svelte.d.ts +221 -0
  174. package/dist/blocks/region/region.svelte.js +582 -0
  175. package/dist/blocks/region/regions.svelte.d.ts +141 -0
  176. package/dist/blocks/region/regions.svelte.js +276 -0
  177. package/dist/blocks/region/serialize.d.ts +57 -0
  178. package/dist/blocks/region/serialize.js +112 -0
  179. package/dist/blocks/region/types.d.ts +255 -0
  180. package/dist/blocks/region/types.js +204 -0
  181. package/dist/blocks/selection.svelte.d.ts +106 -8
  182. package/dist/blocks/selection.svelte.js +632 -74
  183. package/dist/blocks/subthread.d.ts +80 -0
  184. package/dist/blocks/subthread.js +167 -0
  185. package/dist/blocks/text-block.svelte.d.ts +70 -0
  186. package/dist/blocks/text-block.svelte.js +108 -0
  187. package/dist/blocks/toggle/Toggle.svelte +73 -0
  188. package/dist/blocks/toggle/Toggle.svelte.d.ts +11 -0
  189. package/dist/blocks/toggle/index.d.ts +3 -0
  190. package/dist/blocks/toggle/index.js +3 -0
  191. package/dist/blocks/toggle/markdown.d.ts +20 -0
  192. package/dist/blocks/toggle/markdown.js +112 -0
  193. package/dist/blocks/toggle/toggle.extension.d.ts +4 -0
  194. package/dist/blocks/toggle/toggle.extension.js +18 -0
  195. package/dist/blocks/toggle/toggle.svelte.d.ts +135 -0
  196. package/dist/blocks/toggle/toggle.svelte.js +352 -0
  197. package/dist/blocks/undo-selection.d.ts +175 -0
  198. package/dist/blocks/undo-selection.js +360 -0
  199. package/dist/blocks/video/Video.svelte +42 -0
  200. package/dist/blocks/video/Video.svelte.d.ts +11 -0
  201. package/dist/blocks/video/index.d.ts +3 -0
  202. package/dist/blocks/video/index.js +3 -0
  203. package/dist/blocks/video/video.extension.d.ts +4 -0
  204. package/dist/blocks/video/video.extension.js +27 -0
  205. package/dist/blocks/video/video.svelte.d.ts +29 -0
  206. package/dist/blocks/video/video.svelte.js +80 -0
  207. package/dist/extend.d.ts +55 -0
  208. package/dist/extend.js +88 -0
  209. package/dist/files/assets.clipboard.d.ts +77 -0
  210. package/dist/files/assets.clipboard.js +152 -0
  211. package/dist/files/files.svelte.d.ts +363 -0
  212. package/dist/files/files.svelte.js +897 -0
  213. package/dist/files/index.d.ts +3 -0
  214. package/dist/files/index.js +3 -0
  215. package/dist/files/outbox.d.ts +69 -0
  216. package/dist/files/outbox.js +48 -0
  217. package/dist/files/status.d.ts +65 -0
  218. package/dist/files/status.js +87 -0
  219. package/dist/files/store.d.ts +97 -0
  220. package/dist/files/store.js +65 -0
  221. package/dist/files/uploads.svelte.d.ts +174 -0
  222. package/dist/files/uploads.svelte.js +504 -0
  223. package/dist/index.d.ts +68 -6
  224. package/dist/index.js +117 -7
  225. package/dist/nabu-theme.css +112 -0
  226. package/dist/paste/html.paste.d.ts +74 -3
  227. package/dist/paste/html.paste.js +555 -83
  228. package/dist/paste/markdown-inline.d.ts +86 -0
  229. package/dist/paste/markdown-inline.js +528 -0
  230. package/dist/paste/markdown.paste.d.ts +2 -8
  231. package/dist/paste/markdown.paste.js +78 -94
  232. package/dist/paste/nabu.paste.d.ts +3 -0
  233. package/dist/paste/nabu.paste.js +29 -3
  234. package/dist/paste/plain-text.paste.d.ts +2 -2
  235. package/dist/paste/plain-text.paste.js +3 -3
  236. package/dist/persistence/asset-store.d.ts +51 -0
  237. package/dist/persistence/asset-store.js +103 -0
  238. package/dist/persistence/autosave.d.ts +53 -0
  239. package/dist/persistence/autosave.js +62 -0
  240. package/dist/persistence/compact.d.ts +162 -0
  241. package/dist/persistence/compact.js +141 -0
  242. package/dist/persistence/history.d.ts +77 -0
  243. package/dist/persistence/history.js +176 -0
  244. package/dist/persistence/indexeddb.d.ts +190 -4
  245. package/dist/persistence/indexeddb.js +333 -29
  246. package/dist/persistence/merge.d.ts +38 -0
  247. package/dist/persistence/merge.js +36 -0
  248. package/dist/persistence/outbox.d.ts +25 -0
  249. package/dist/persistence/outbox.js +40 -0
  250. package/dist/persistence/persistence.d.ts +70 -9
  251. package/dist/persistence/persistence.js +507 -35
  252. package/dist/persistence/recovery.d.ts +79 -0
  253. package/dist/persistence/recovery.js +79 -0
  254. package/dist/persistence/release.d.ts +34 -0
  255. package/dist/persistence/release.js +64 -0
  256. package/dist/persistence/state.svelte.d.ts +53 -0
  257. package/dist/persistence/state.svelte.js +48 -0
  258. package/dist/persistence/sync.d.ts +39 -0
  259. package/dist/persistence/sync.js +138 -0
  260. package/dist/persistence/tail.d.ts +42 -0
  261. package/dist/persistence/tail.js +103 -0
  262. package/dist/presets.d.ts +29 -24
  263. package/dist/presets.js +51 -14
  264. package/dist/themes/atelier.css +318 -0
  265. package/dist/ui/CommandChooser.svelte +153 -0
  266. package/dist/ui/CommandChooser.svelte.d.ts +13 -0
  267. package/dist/ui/CommandInvite.svelte +99 -0
  268. package/dist/ui/CommandInvite.svelte.d.ts +12 -0
  269. package/dist/ui/DragHandle.svelte +217 -0
  270. package/dist/ui/DragHandle.svelte.d.ts +11 -0
  271. package/dist/ui/FloatingToolbar.svelte +165 -0
  272. package/dist/ui/FloatingToolbar.svelte.d.ts +27 -0
  273. package/dist/ui/SlashMenu.svelte +215 -0
  274. package/dist/ui/SlashMenu.svelte.d.ts +33 -0
  275. package/dist/ui/anchor.d.ts +112 -0
  276. package/dist/ui/anchor.js +136 -0
  277. package/dist/ui/index.d.ts +10 -0
  278. package/dist/ui/index.js +15 -0
  279. package/dist/ui/slash-menu.svelte.d.ts +112 -0
  280. package/dist/ui/slash-menu.svelte.js +150 -0
  281. package/dist/utils/command-confirm.svelte.d.ts +349 -0
  282. package/dist/utils/command-confirm.svelte.js +673 -0
  283. package/dist/utils/commands.d.ts +328 -0
  284. package/dist/utils/commands.js +416 -0
  285. package/dist/utils/dom-scope.d.ts +14 -0
  286. package/dist/utils/dom-scope.js +20 -0
  287. package/dist/utils/drop.d.ts +160 -0
  288. package/dist/utils/drop.js +305 -0
  289. package/dist/utils/extensions.d.ts +488 -40
  290. package/dist/utils/extensions.js +300 -19
  291. package/dist/utils/html.d.ts +44 -0
  292. package/dist/utils/html.js +183 -0
  293. package/dist/utils/index.d.ts +4 -0
  294. package/dist/utils/index.js +4 -0
  295. package/dist/utils/keys.d.ts +120 -0
  296. package/dist/utils/keys.js +248 -0
  297. package/dist/utils/links.d.ts +22 -0
  298. package/dist/utils/links.js +34 -0
  299. package/dist/utils/placeholders.d.ts +88 -0
  300. package/dist/utils/placeholders.js +91 -0
  301. package/dist/utils/selection.svelte.d.ts +47 -19
  302. package/dist/utils/selection.svelte.js +60 -10
  303. package/dist/utils/spellcheck.d.ts +9 -0
  304. package/dist/utils/spellcheck.js +17 -0
  305. package/dist/utils/tab.d.ts +31 -0
  306. package/dist/utils/tab.js +117 -0
  307. package/dist/utils/words.d.ts +7 -0
  308. package/dist/utils/words.js +62 -0
  309. package/dist/vite.d.ts +22 -0
  310. package/dist/vite.js +34 -0
  311. package/package.json +61 -22
  312. package/dist/blocks/zone/Zone.svelte +0 -258
  313. package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
  314. package/dist/blocks/zone/index.d.ts +0 -2
  315. package/dist/blocks/zone/index.js +0 -2
  316. package/dist/blocks/zone/zone.extension.d.ts +0 -2
  317. package/dist/blocks/zone/zone.extension.js +0 -221
  318. package/dist/blocks/zone/zone.svelte.d.ts +0 -112
  319. package/dist/blocks/zone/zone.svelte.js +0 -321
@@ -1,3 +1,24 @@
1
+ /**
2
+ * Open (and upgrade if needed) the `nabu` database. The connection closes itself when another context (a newer
3
+ * version of the code in another tab) asks to upgrade, so an upgrade is never blocked by an idle connection.
4
+ * @returns {Promise<IDBDatabase>}
5
+ */
6
+ export function openDB(): Promise<IDBDatabase>;
7
+ /**
8
+ * Run one request of an object store in its own transaction and close the connection afterwards.
9
+ * @template T
10
+ * @param {string} storeName
11
+ * @param {IDBTransactionMode} mode
12
+ * @param {(store: IDBObjectStore) => IDBRequest<T>} run
13
+ * @returns {Promise<T>}
14
+ */
15
+ export function withStore<T>(storeName: string, mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T>;
16
+ /**
17
+ * @typedef {object} SnapshotRecord
18
+ * @property {string} docId
19
+ * @property {unknown} snapshot normally a `Uint8Array`; whatever is stored when the record is corrupted
20
+ * @property {number} [savedAt]
21
+ */
1
22
  /**
2
23
  * Load a snapshot from IndexedDB.
3
24
  * @param {string} docId
@@ -5,15 +26,180 @@
5
26
  */
6
27
  export function loadSnapshot(docId: string): Promise<Uint8Array | null>;
7
28
  /**
8
- * Save a snapshot to IndexedDB.
29
+ * The raw stored records of a document: the current one and the backup (the snapshot the last save replaced). Not validated:
30
+ * a `snapshot` that is not bytes is returned as is, so the caller can quarantine it.
31
+ * @param {string} docId
32
+ * @param {IDBConnection} [conn]
33
+ * @returns {Promise<{ current: SnapshotRecord | null, backup: SnapshotRecord | null }>}
34
+ */
35
+ export function loadRecords(docId: string, conn?: IDBConnection): Promise<{
36
+ current: SnapshotRecord | null;
37
+ backup: SnapshotRecord | null;
38
+ }>;
39
+ /**
40
+ * Save a snapshot to IndexedDB, in ONE transaction: the snapshot it replaces becomes the document's backup.
41
+ *
42
+ * With `previous` (the bytes the caller wrote or loaded last) every request is issued SYNCHRONOUSLY, which a save started from
43
+ * `pagehide` needs: a request issued from a callback (after reading the old record) comes too late, the page is gone. Without it the
44
+ * stored record is read first, in the same transaction (an unreadable one never replaces a good backup).
9
45
  * @param {string} docId
10
46
  * @param {Uint8Array} snapshot
11
- * @returns {Promise<void>}
47
+ * @param {object} [options]
48
+ * @param {IDBConnection} [options.conn] a connection kept open (a save started from `pagehide` needs one)
49
+ * @param {{ snapshot: Uint8Array, savedAt?: number } | null} [options.previous] what is stored right now, to keep as the backup (`null`: nothing to keep)
50
+ * @param {boolean} [options.rotate] default `true`. `false`: do not keep the replaced record as the backup
51
+ * @param {boolean} [options.dropBackup] delete the backup (a compaction: the history it dropped must not survive in a backup)
52
+ * @returns {Promise<SnapshotRecord>} the record that was written
53
+ */
54
+ export function saveSnapshot(docId: string, snapshot: Uint8Array, { conn, previous, rotate, dropBackup }?: {
55
+ conn?: IDBConnection | undefined;
56
+ previous?: {
57
+ snapshot: Uint8Array;
58
+ savedAt?: number;
59
+ } | null | undefined;
60
+ rotate?: boolean | undefined;
61
+ dropBackup?: boolean | undefined;
62
+ }): Promise<SnapshotRecord>;
63
+ /**
64
+ * @typedef {object} MergePlan What {@link saveMerged}'s `prepare` decides, from the record stored RIGHT NOW.
65
+ * @property {Uint8Array | null} snapshot the bytes to write, or `null`: the stored record already holds everything (nothing is written)
66
+ * @property {unknown} [unmerged] the stored record could not be merged into the document (unreadable bytes, or a shallow snapshot
67
+ * that does not follow from this document): it is copied to the `quarantine` store before being replaced, never lost
68
+ */
69
+ /**
70
+ * Save a snapshot while MERGING what another tab stored (ADR 010, multi-tab, P-94), atomically: ONE read-write transaction reads the
71
+ * stored record, hands it to `prepare` (SYNCHRONOUS: it imports whatever the document lacks, then exports), and writes the result.
72
+ * IndexedDB serialises read-write transactions on a store across tabs, so two tabs saving at the same time cannot overwrite each
73
+ * other: the second one reads what the first wrote. The record it replaces becomes the backup, as in {@link saveSnapshot}.
74
+ *
75
+ * Not for a page that is going away (the write is issued from a request callback: see `previous` in {@link saveSnapshot}).
76
+ * @param {string} docId
77
+ * @param {(stored: SnapshotRecord | null) => MergePlan} prepare
78
+ * @param {object} [options]
79
+ * @param {IDBConnection} [options.conn]
80
+ * @returns {Promise<{ stored: SnapshotRecord | null, written: SnapshotRecord | null, quarantinedKey: string | null }>}
81
+ */
82
+ export function saveMerged(docId: string, prepare: (stored: SnapshotRecord | null) => MergePlan, { conn }?: {
83
+ conn?: IDBConnection | undefined;
84
+ }): Promise<{
85
+ stored: SnapshotRecord | null;
86
+ written: SnapshotRecord | null;
87
+ quarantinedKey: string | null;
88
+ }>;
89
+ /**
90
+ * @typedef {object} QuarantinedRecord
91
+ * @property {string} key `<docId>@<timestamp>[-backup]`
92
+ * @property {string} docId
93
+ * @property {'snapshot' | 'backup'} source which record it was
94
+ * @property {unknown} snapshot the unreadable value, untouched
95
+ * @property {number | undefined} savedAt when it had been saved
96
+ * @property {number} quarantinedAt
97
+ * @property {string} error why it was refused
12
98
  */
13
- export function saveSnapshot(docId: string, snapshot: Uint8Array): Promise<void>;
14
99
  /**
15
- * Delete a snapshot from IndexedDB.
100
+ * Move unreadable records aside and fix the live records, in ONE transaction (nothing is ever deleted without a copy being kept):
101
+ * each entry of `quarantine` is copied into the `quarantine` store; then the current snapshot is replaced by `restore` (the good
102
+ * backup) or removed (`restore: null`, the document restarts empty), and the backup is removed when it was itself unreadable.
103
+ * @param {string} docId
104
+ * @param {{ source: 'snapshot' | 'backup', record: SnapshotRecord, error: unknown }[]} quarantine
105
+ * @param {SnapshotRecord | null} restore the readable backup to put back as the current snapshot, or `null`
106
+ * @param {number} at
107
+ * @param {IDBConnection} [conn]
108
+ * @returns {Promise<string[]>} the keys of the quarantined copies, in the order of `quarantine`
109
+ */
110
+ export function quarantineRecords(docId: string, quarantine: {
111
+ source: "snapshot" | "backup";
112
+ record: SnapshotRecord;
113
+ error: unknown;
114
+ }[], restore: SnapshotRecord | null, at: number, conn?: IDBConnection): Promise<string[]>;
115
+ /**
116
+ * The records moved aside for a document (newest first).
117
+ * @param {string} docId
118
+ * @param {IDBConnection} [conn]
119
+ * @returns {Promise<QuarantinedRecord[]>}
120
+ */
121
+ export function listQuarantined(docId: string, conn?: IDBConnection): Promise<QuarantinedRecord[]>;
122
+ /**
123
+ * Delete a document from IndexedDB: its snapshot, its backup AND the records that were moved aside.
16
124
  * @param {string} docId
17
125
  * @returns {Promise<void>}
18
126
  */
19
127
  export function deleteSnapshot(docId: string): Promise<void>;
128
+ /** Object store of the file bytes, shared by every document of the origin (keyPath `hash`) — ADR 014 §3.3. */
129
+ export const ASSETS_STORE: "assets";
130
+ /** Object store of the files each document references (keyPath `docId`, `hashes: string[]`) — used by the cleanup (ADR 014 lot 3). */
131
+ export const DOC_REFS_STORE: "docRefs";
132
+ /**
133
+ * Object store of the upload outbox (keyPath `[docId, hash]`, index `docId`): the files of a document still to send to the
134
+ * host (`files.onBeforePersist`) — ADR 014 lot 2.
135
+ */
136
+ export const OUTBOX_STORE: "outbox";
137
+ /**
138
+ * Object store of the PREVIOUS good snapshot of each document (keyPath `docId`, same record shape as `snapshots`) — ADR 010
139
+ * (2026-10, theme 8): every successful save moves the snapshot it replaces here, so a corrupted latest snapshot can fall back on it.
140
+ */
141
+ export const BACKUPS_STORE: "backups";
142
+ /**
143
+ * Object store of the records that could not be read (keyPath `key`, index `docId`): moved aside, never deleted, when a document
144
+ * is recovered from its backup or restarted empty — ADR 010 (2026-10, theme 8).
145
+ */
146
+ export const QUARANTINE_STORE: "quarantine";
147
+ /**
148
+ * A connection kept open for the lifetime of a persisted editor. Opening a database is asynchronous; a save started from
149
+ * `pagehide` must create its transaction SYNCHRONOUSLY (the page may be gone by the time an `open` request answers), hence one
150
+ * connection opened at boot and reused. It reopens by itself when the browser or another tab closed it (`versionchange`, `close`).
151
+ */
152
+ export class IDBConnection {
153
+ /** The open database (opens it if needed). Rejects when IndexedDB is unavailable. @returns {Promise<IDBDatabase>} */
154
+ get(): Promise<IDBDatabase>;
155
+ /** Close the connection for good (the editor is released). */
156
+ close(): void;
157
+ #private;
158
+ }
159
+ export function isSnapshotBytes(value: unknown): value is Uint8Array;
160
+ export type SnapshotRecord = {
161
+ docId: string;
162
+ /**
163
+ * normally a `Uint8Array`; whatever is stored when the record is corrupted
164
+ */
165
+ snapshot: unknown;
166
+ savedAt?: number | undefined;
167
+ };
168
+ /**
169
+ * What {@link saveMerged}'s `prepare` decides, from the record stored RIGHT NOW.
170
+ */
171
+ export type MergePlan = {
172
+ /**
173
+ * the bytes to write, or `null`: the stored record already holds everything (nothing is written)
174
+ */
175
+ snapshot: Uint8Array | null;
176
+ /**
177
+ * the stored record could not be merged into the document (unreadable bytes, or a shallow snapshot
178
+ * that does not follow from this document): it is copied to the `quarantine` store before being replaced, never lost
179
+ */
180
+ unmerged?: unknown;
181
+ };
182
+ export type QuarantinedRecord = {
183
+ /**
184
+ * `<docId>@<timestamp>[-backup]`
185
+ */
186
+ key: string;
187
+ docId: string;
188
+ /**
189
+ * which record it was
190
+ */
191
+ source: "snapshot" | "backup";
192
+ /**
193
+ * the unreadable value, untouched
194
+ */
195
+ snapshot: unknown;
196
+ /**
197
+ * when it had been saved
198
+ */
199
+ savedAt: number | undefined;
200
+ quarantinedAt: number;
201
+ /**
202
+ * why it was refused
203
+ */
204
+ error: string;
205
+ };
@@ -1,11 +1,40 @@
1
1
  const DB_NAME = 'nabu';
2
+ /** Object store of the document snapshots (keyPath `docId`). */
2
3
  const STORE = 'snapshots';
3
- const DB_VERSION = 1;
4
+ /** Object store of the file bytes, shared by every document of the origin (keyPath `hash`) — ADR 014 §3.3. */
5
+ export const ASSETS_STORE = 'assets';
6
+ /** Object store of the files each document references (keyPath `docId`, `hashes: string[]`) — used by the cleanup (ADR 014 lot 3). */
7
+ export const DOC_REFS_STORE = 'docRefs';
8
+ /**
9
+ * Object store of the upload outbox (keyPath `[docId, hash]`, index `docId`): the files of a document still to send to the
10
+ * host (`files.onBeforePersist`) — ADR 014 lot 2.
11
+ */
12
+ export const OUTBOX_STORE = 'outbox';
13
+ /**
14
+ * Object store of the PREVIOUS good snapshot of each document (keyPath `docId`, same record shape as `snapshots`) — ADR 010
15
+ * (2026-10, theme 8): every successful save moves the snapshot it replaces here, so a corrupted latest snapshot can fall back on it.
16
+ */
17
+ export const BACKUPS_STORE = 'backups';
18
+ /**
19
+ * Object store of the records that could not be read (keyPath `key`, index `docId`): moved aside, never deleted, when a document
20
+ * is recovered from its backup or restarted empty — ADR 010 (2026-10, theme 8).
21
+ */
22
+ export const QUARANTINE_STORE = 'quarantine';
23
+ /**
24
+ * Schema version. 1: `snapshots`. 2 (ADR 014): + `assets` and `docRefs`. 3 (ADR 014 lot 2): + `outbox`. 4 (ADR 010, 2026-10): +
25
+ * `backups` and `quarantine`. An upgrade only ADDS the missing stores, so the data of an older database (snapshots, files, docRefs,
26
+ * outbox) is untouched and a document without a backup loads exactly as before.
27
+ */
28
+ const DB_VERSION = 4;
29
+ /** How long a `blocked` upgrade (another tab keeps an old connection open and does not close it) is waited for before giving up. */
30
+ const BLOCKED_TIMEOUT_MS = 3000;
4
31
 
5
32
  /**
33
+ * Open (and upgrade if needed) the `nabu` database. The connection closes itself when another context (a newer
34
+ * version of the code in another tab) asks to upgrade, so an upgrade is never blocked by an idle connection.
6
35
  * @returns {Promise<IDBDatabase>}
7
36
  */
8
- function openDB() {
37
+ export function openDB() {
9
38
  return new Promise((resolve, reject) => {
10
39
  const request = indexedDB.open(DB_NAME, DB_VERSION);
11
40
 
@@ -14,58 +43,333 @@ function openDB() {
14
43
  if (!db.objectStoreNames.contains(STORE)) {
15
44
  db.createObjectStore(STORE, { keyPath: 'docId' });
16
45
  }
46
+ if (!db.objectStoreNames.contains(ASSETS_STORE)) {
47
+ db.createObjectStore(ASSETS_STORE, { keyPath: 'hash' });
48
+ }
49
+ if (!db.objectStoreNames.contains(DOC_REFS_STORE)) {
50
+ db.createObjectStore(DOC_REFS_STORE, { keyPath: 'docId' });
51
+ }
52
+ if (!db.objectStoreNames.contains(OUTBOX_STORE)) {
53
+ db.createObjectStore(OUTBOX_STORE, { keyPath: ['docId', 'hash'] }).createIndex('docId', 'docId');
54
+ }
55
+ if (!db.objectStoreNames.contains(BACKUPS_STORE)) {
56
+ db.createObjectStore(BACKUPS_STORE, { keyPath: 'docId' });
57
+ }
58
+ if (!db.objectStoreNames.contains(QUARANTINE_STORE)) {
59
+ db.createObjectStore(QUARANTINE_STORE, { keyPath: 'key' }).createIndex('docId', 'docId');
60
+ }
61
+ };
62
+
63
+ let gaveUp = false;
64
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
65
+ let blockedTimer;
66
+ request.onblocked = () => {
67
+ // An upgrade waits for the other connections to close (they do on `versionchange`). If one never does, do not hang forever.
68
+ blockedTimer = setTimeout(() => { gaveUp = true; reject(new Error('IndexedDB: opening the database is blocked by another tab')); }, BLOCKED_TIMEOUT_MS);
69
+ };
70
+ request.onsuccess = (event) => {
71
+ clearTimeout(blockedTimer);
72
+ const db = /** @type {IDBOpenDBRequest} */ (event.target).result;
73
+ if (gaveUp) { db.close(); return; }
74
+ db.onversionchange = () => db.close();
75
+ resolve(db);
17
76
  };
77
+ request.onerror = (event) => { clearTimeout(blockedTimer); reject(/** @type {IDBOpenDBRequest} */ (event.target).error); };
78
+ });
79
+ }
80
+
81
+ /**
82
+ * A connection kept open for the lifetime of a persisted editor. Opening a database is asynchronous; a save started from
83
+ * `pagehide` must create its transaction SYNCHRONOUSLY (the page may be gone by the time an `open` request answers), hence one
84
+ * connection opened at boot and reused. It reopens by itself when the browser or another tab closed it (`versionchange`, `close`).
85
+ */
86
+ export class IDBConnection {
87
+ /** @type {IDBDatabase | null} */
88
+ #db = null;
89
+ /** @type {Promise<IDBDatabase> | null} */
90
+ #opening = null;
91
+ #closed = false;
92
+
93
+ /** The open database (opens it if needed). Rejects when IndexedDB is unavailable. @returns {Promise<IDBDatabase>} */
94
+ get() {
95
+ if (this.#db) return Promise.resolve(this.#db);
96
+ if (!this.#opening) {
97
+ this.#opening = openDB().then((db) => {
98
+ this.#opening = null;
99
+ if (this.#closed) { db.close(); throw new Error('IndexedDB connection closed'); }
100
+ this.#db = db;
101
+ const forget = () => { if (this.#db === db) this.#db = null; };
102
+ db.addEventListener('close', forget);
103
+ db.addEventListener('versionchange', forget);
104
+ return db;
105
+ }, (error) => { this.#opening = null; throw error; });
106
+ }
107
+ return this.#opening;
108
+ }
18
109
 
19
- request.onsuccess = (event) => resolve(/** @type {IDBOpenDBRequest} */ (event.target).result);
20
- request.onerror = (event) => reject(/** @type {IDBOpenDBRequest} */ (event.target).error);
110
+ /** Close the connection for good (the editor is released). */
111
+ close() {
112
+ this.#closed = true;
113
+ this.#db?.close();
114
+ this.#db = null;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Run `work` in ONE transaction over `storeNames`; resolves when the transaction completes, rejects when it aborts. An exception
120
+ * thrown by `work` (or reported with `fail`, from a request callback: an exception in an event handler would be reported as
121
+ * uncaught) aborts the transaction and rejects with it: nothing is half written.
122
+ * @param {IDBConnection | null | undefined} conn a shared connection (kept open), or none (a connection opened for this call only)
123
+ * @param {string[]} storeNames
124
+ * @param {IDBTransactionMode} mode
125
+ * @param {(stores: IDBObjectStore[], fail: (error: unknown) => void) => void | boolean} work returns `true` when it issued all its requests synchronously
126
+ * @returns {Promise<void>}
127
+ */
128
+ async function transact(conn, storeNames, mode, work) {
129
+ const db = conn ? await conn.get() : await openDB();
130
+ return new Promise((resolve, reject) => {
131
+ /** @type {unknown} */
132
+ let failure;
133
+ /** @type {IDBTransaction} */
134
+ let tx;
135
+ try {
136
+ tx = db.transaction(storeNames, mode);
137
+ } catch (error) {
138
+ if (!conn) db.close();
139
+ reject(error);
140
+ return;
141
+ }
142
+ /** @param {unknown} error */
143
+ const fail = (error) => { failure = error; try { tx.abort(); } catch { /* already finished */ } };
144
+ tx.oncomplete = () => { if (!conn) db.close(); resolve(); };
145
+ tx.onabort = tx.onerror = () => { if (!conn) db.close(); reject(failure ?? tx.error ?? new Error('IndexedDB transaction aborted')); };
146
+ try {
147
+ // `true`: every request was issued, commit now instead of at the end of the task (a page that is going away may not get that far)
148
+ if (work(storeNames.map((name) => tx.objectStore(name)), fail) === true) tx.commit?.();
149
+ } catch (error) {
150
+ fail(error);
151
+ }
21
152
  });
22
153
  }
23
154
 
155
+ /** Whether `value` is something Loro could import (non-empty bytes). @param {unknown} value @returns {value is Uint8Array} */
156
+ export const isSnapshotBytes = (value) => value instanceof Uint8Array && value.length > 0;
157
+
158
+ /**
159
+ * Run one request of an object store in its own transaction and close the connection afterwards.
160
+ * @template T
161
+ * @param {string} storeName
162
+ * @param {IDBTransactionMode} mode
163
+ * @param {(store: IDBObjectStore) => IDBRequest<T>} run
164
+ * @returns {Promise<T>}
165
+ */
166
+ export async function withStore(storeName, mode, run) {
167
+ const db = await openDB();
168
+ return new Promise((resolve, reject) => {
169
+ const tx = db.transaction(storeName, mode);
170
+ const request = run(tx.objectStore(storeName));
171
+ /** @type {any} */
172
+ let result;
173
+ request.onsuccess = () => { result = request.result; };
174
+ tx.oncomplete = () => { db.close(); resolve(result); };
175
+ tx.onabort = tx.onerror = () => { db.close(); reject(tx.error ?? request.error); };
176
+ });
177
+ }
178
+
179
+ /**
180
+ * @typedef {object} SnapshotRecord
181
+ * @property {string} docId
182
+ * @property {unknown} snapshot normally a `Uint8Array`; whatever is stored when the record is corrupted
183
+ * @property {number} [savedAt]
184
+ */
185
+
24
186
  /**
25
187
  * Load a snapshot from IndexedDB.
26
188
  * @param {string} docId
27
189
  * @returns {Promise<Uint8Array | null>}
28
190
  */
29
191
  export async function loadSnapshot(docId) {
30
- const db = await openDB();
31
- return new Promise((resolve, reject) => {
32
- const tx = db.transaction(STORE, 'readonly');
33
- const request = tx.objectStore(STORE).get(docId);
34
- request.onsuccess = (event) => {
35
- const record = /** @type {IDBRequest} */ (event.target).result;
36
- resolve(record ? record.snapshot : null);
37
- };
38
- request.onerror = (event) => reject(/** @type {IDBRequest} */ (event.target).error);
192
+ const record = await withStore(STORE, 'readonly', (s) => s.get(docId));
193
+ return record ? record.snapshot : null;
194
+ }
195
+
196
+ /**
197
+ * The raw stored records of a document: the current one and the backup (the snapshot the last save replaced). Not validated:
198
+ * a `snapshot` that is not bytes is returned as is, so the caller can quarantine it.
199
+ * @param {string} docId
200
+ * @param {IDBConnection} [conn]
201
+ * @returns {Promise<{ current: SnapshotRecord | null, backup: SnapshotRecord | null }>}
202
+ */
203
+ export async function loadRecords(docId, conn) {
204
+ let current = null;
205
+ let backup = null;
206
+ await transact(conn, [STORE, BACKUPS_STORE], 'readonly', ([snapshots, backups]) => {
207
+ const a = snapshots.get(docId);
208
+ const b = backups.get(docId);
209
+ a.onsuccess = () => { current = a.result ?? null; };
210
+ b.onsuccess = () => { backup = b.result ?? null; };
39
211
  });
212
+ return { current, backup };
40
213
  }
41
214
 
42
215
  /**
43
- * Save a snapshot to IndexedDB.
216
+ * Save a snapshot to IndexedDB, in ONE transaction: the snapshot it replaces becomes the document's backup.
217
+ *
218
+ * With `previous` (the bytes the caller wrote or loaded last) every request is issued SYNCHRONOUSLY, which a save started from
219
+ * `pagehide` needs: a request issued from a callback (after reading the old record) comes too late, the page is gone. Without it the
220
+ * stored record is read first, in the same transaction (an unreadable one never replaces a good backup).
44
221
  * @param {string} docId
45
222
  * @param {Uint8Array} snapshot
46
- * @returns {Promise<void>}
223
+ * @param {object} [options]
224
+ * @param {IDBConnection} [options.conn] a connection kept open (a save started from `pagehide` needs one)
225
+ * @param {{ snapshot: Uint8Array, savedAt?: number } | null} [options.previous] what is stored right now, to keep as the backup (`null`: nothing to keep)
226
+ * @param {boolean} [options.rotate] default `true`. `false`: do not keep the replaced record as the backup
227
+ * @param {boolean} [options.dropBackup] delete the backup (a compaction: the history it dropped must not survive in a backup)
228
+ * @returns {Promise<SnapshotRecord>} the record that was written
47
229
  */
48
- export async function saveSnapshot(docId, snapshot) {
49
- const db = await openDB();
50
- return new Promise((resolve, reject) => {
51
- const tx = db.transaction(STORE, 'readwrite');
52
- const request = tx.objectStore(STORE).put({ docId, snapshot, savedAt: Date.now() });
53
- request.onsuccess = () => resolve();
54
- request.onerror = (event) => reject(/** @type {IDBRequest} */ (event.target).error);
230
+ export async function saveSnapshot(docId, snapshot, { conn, previous, rotate = true, dropBackup = false } = {}) {
231
+ const record = { docId, snapshot, savedAt: Date.now() };
232
+ await transact(conn, [STORE, BACKUPS_STORE], 'readwrite', ([snapshots, backups], fail) => {
233
+ if (dropBackup) backups.delete(docId);
234
+ if (!rotate) { snapshots.put(record); return; }
235
+ if (previous !== undefined) {
236
+ if (previous && isSnapshotBytes(previous.snapshot)) backups.put({ docId, snapshot: previous.snapshot, savedAt: previous.savedAt });
237
+ snapshots.put(record);
238
+ return;
239
+ }
240
+ const get = snapshots.get(docId);
241
+ get.onsuccess = () => {
242
+ try {
243
+ const stored = get.result;
244
+ // An unreadable previous record never replaces a good backup
245
+ if (stored && isSnapshotBytes(stored.snapshot)) backups.put({ docId, snapshot: stored.snapshot, savedAt: stored.savedAt });
246
+ snapshots.put(record);
247
+ } catch (error) {
248
+ fail(error);
249
+ }
250
+ };
55
251
  });
252
+ return record;
56
253
  }
57
254
 
58
255
  /**
59
- * Delete a snapshot from IndexedDB.
256
+ * @typedef {object} MergePlan What {@link saveMerged}'s `prepare` decides, from the record stored RIGHT NOW.
257
+ * @property {Uint8Array | null} snapshot the bytes to write, or `null`: the stored record already holds everything (nothing is written)
258
+ * @property {unknown} [unmerged] the stored record could not be merged into the document (unreadable bytes, or a shallow snapshot
259
+ * that does not follow from this document): it is copied to the `quarantine` store before being replaced, never lost
260
+ */
261
+
262
+ /**
263
+ * Save a snapshot while MERGING what another tab stored (ADR 010, multi-tab, P-94), atomically: ONE read-write transaction reads the
264
+ * stored record, hands it to `prepare` (SYNCHRONOUS: it imports whatever the document lacks, then exports), and writes the result.
265
+ * IndexedDB serialises read-write transactions on a store across tabs, so two tabs saving at the same time cannot overwrite each
266
+ * other: the second one reads what the first wrote. The record it replaces becomes the backup, as in {@link saveSnapshot}.
267
+ *
268
+ * Not for a page that is going away (the write is issued from a request callback: see `previous` in {@link saveSnapshot}).
269
+ * @param {string} docId
270
+ * @param {(stored: SnapshotRecord | null) => MergePlan} prepare
271
+ * @param {object} [options]
272
+ * @param {IDBConnection} [options.conn]
273
+ * @returns {Promise<{ stored: SnapshotRecord | null, written: SnapshotRecord | null, quarantinedKey: string | null }>}
274
+ */
275
+ export async function saveMerged(docId, prepare, { conn } = {}) {
276
+ /** @type {SnapshotRecord | null} */
277
+ let stored = null;
278
+ /** @type {SnapshotRecord | null} */
279
+ let written = null;
280
+ /** @type {string | null} */
281
+ let quarantinedKey = null;
282
+ await transact(conn, [STORE, BACKUPS_STORE, QUARANTINE_STORE], 'readwrite', ([snapshots, backups, quarantined], fail) => {
283
+ const get = snapshots.get(docId);
284
+ get.onsuccess = () => {
285
+ try {
286
+ stored = get.result ?? null;
287
+ const plan = prepare(stored);
288
+ if (stored && plan.unmerged !== undefined) {
289
+ const at = Date.now();
290
+ quarantinedKey = `${docId}@${at}-unmerged`;
291
+ quarantined.put(/** @type {QuarantinedRecord} */ ({
292
+ key: quarantinedKey, docId, source: 'snapshot', snapshot: stored.snapshot, savedAt: stored.savedAt, quarantinedAt: at,
293
+ error: plan.unmerged instanceof Error ? `${plan.unmerged.name}: ${plan.unmerged.message}` : String(plan.unmerged),
294
+ }));
295
+ }
296
+ if (!plan.snapshot) return;
297
+ // An unreadable previous record never replaces a good backup
298
+ if (stored && isSnapshotBytes(stored.snapshot)) backups.put({ docId, snapshot: stored.snapshot, savedAt: stored.savedAt });
299
+ written = { docId, snapshot: plan.snapshot, savedAt: Date.now() };
300
+ snapshots.put(written);
301
+ } catch (error) {
302
+ fail(error);
303
+ }
304
+ };
305
+ });
306
+ return { stored, written, quarantinedKey };
307
+ }
308
+
309
+ /**
310
+ * @typedef {object} QuarantinedRecord
311
+ * @property {string} key `<docId>@<timestamp>[-backup]`
312
+ * @property {string} docId
313
+ * @property {'snapshot' | 'backup'} source which record it was
314
+ * @property {unknown} snapshot the unreadable value, untouched
315
+ * @property {number | undefined} savedAt when it had been saved
316
+ * @property {number} quarantinedAt
317
+ * @property {string} error why it was refused
318
+ */
319
+
320
+ /**
321
+ * Move unreadable records aside and fix the live records, in ONE transaction (nothing is ever deleted without a copy being kept):
322
+ * each entry of `quarantine` is copied into the `quarantine` store; then the current snapshot is replaced by `restore` (the good
323
+ * backup) or removed (`restore: null`, the document restarts empty), and the backup is removed when it was itself unreadable.
324
+ * @param {string} docId
325
+ * @param {{ source: 'snapshot' | 'backup', record: SnapshotRecord, error: unknown }[]} quarantine
326
+ * @param {SnapshotRecord | null} restore the readable backup to put back as the current snapshot, or `null`
327
+ * @param {number} at
328
+ * @param {IDBConnection} [conn]
329
+ * @returns {Promise<string[]>} the keys of the quarantined copies, in the order of `quarantine`
330
+ */
331
+ export async function quarantineRecords(docId, quarantine, restore, at, conn) {
332
+ const keys = quarantine.map(({ source }) => `${docId}@${at}${source === 'backup' ? '-backup' : ''}`);
333
+ await transact(conn, [STORE, BACKUPS_STORE, QUARANTINE_STORE], 'readwrite', ([snapshots, backups, quarantined]) => {
334
+ quarantine.forEach(({ source, record, error }, i) => {
335
+ quarantined.put(/** @type {QuarantinedRecord} */ ({
336
+ key: keys[i], docId, source, snapshot: record.snapshot, savedAt: record.savedAt, quarantinedAt: at,
337
+ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
338
+ }));
339
+ if (source === 'backup') backups.delete(docId);
340
+ });
341
+ if (restore) snapshots.put({ docId, snapshot: restore.snapshot, savedAt: restore.savedAt });
342
+ else if (quarantine.some(({ source }) => source === 'snapshot')) snapshots.delete(docId);
343
+ });
344
+ return keys;
345
+ }
346
+
347
+ /**
348
+ * The records moved aside for a document (newest first).
349
+ * @param {string} docId
350
+ * @param {IDBConnection} [conn]
351
+ * @returns {Promise<QuarantinedRecord[]>}
352
+ */
353
+ export async function listQuarantined(docId, conn) {
354
+ /** @type {QuarantinedRecord[]} */
355
+ let out = [];
356
+ await transact(conn, [QUARANTINE_STORE], 'readonly', ([store]) => {
357
+ const get = store.index('docId').getAll(docId);
358
+ get.onsuccess = () => { out = get.result; };
359
+ });
360
+ return out.sort((a, b) => b.quarantinedAt - a.quarantinedAt);
361
+ }
362
+
363
+ /**
364
+ * Delete a document from IndexedDB: its snapshot, its backup AND the records that were moved aside.
60
365
  * @param {string} docId
61
366
  * @returns {Promise<void>}
62
367
  */
63
368
  export async function deleteSnapshot(docId) {
64
- const db = await openDB();
65
- return new Promise((resolve, reject) => {
66
- const tx = db.transaction(STORE, 'readwrite');
67
- const request = tx.objectStore(STORE).delete(docId);
68
- request.onsuccess = () => resolve();
69
- request.onerror = (event) => reject(/** @type {IDBRequest} */ (event.target).error);
369
+ await transact(null, [STORE, BACKUPS_STORE, QUARANTINE_STORE], 'readwrite', ([snapshots, backups, quarantined]) => {
370
+ snapshots.delete(docId);
371
+ backups.delete(docId);
372
+ const keys = quarantined.index('docId').getAllKeys(docId);
373
+ keys.onsuccess = () => { for (const key of keys.result) quarantined.delete(key); };
70
374
  });
71
375
  }
@@ -0,0 +1,38 @@
1
+ /** @import { LoroDoc } from 'loro-crdt' */
2
+ /**
3
+ * @typedef {object} MergeResult
4
+ * @property {boolean} imported the stored record held changes the document did not have, and they were imported
5
+ * @property {boolean} covers the stored record now contains EVERYTHING the document has (writing the document again would add nothing)
6
+ * @property {boolean} merged `false`: the record holds something the document still lacks after the import (a shallow snapshot that
7
+ * does not follow from the document): it cannot be merged and must not be overwritten without a copy being kept
8
+ */
9
+ /**
10
+ * Merge a stored snapshot into the live document (ADR 010, multi-tab, P-94): whatever another tab saved that this document does not
11
+ * have is IMPORTED, so the save that follows (a full export of the document) cannot overwrite it. The version vector of the record
12
+ * is read from its header (no decoding of the whole record) and compared with the document's; the import only happens when the
13
+ * record is ahead of, or concurrent with, the document. Synchronous (it runs inside an IndexedDB request callback, see
14
+ * `saveMerged`). Throws when the bytes are unreadable.
15
+ *
16
+ * @param {LoroDoc} doc
17
+ * @param {Uint8Array} bytes the stored snapshot
18
+ * @param {(bytes: Uint8Array) => unknown} [importBytes] how to import (default `doc.import`; the editor passes `nabu.importRemote`, which
19
+ * keeps the caret and is never an undo step)
20
+ * @returns {MergeResult}
21
+ */
22
+ export function mergeStored(doc: LoroDoc, bytes: Uint8Array, importBytes?: (bytes: Uint8Array) => unknown): MergeResult;
23
+ export type MergeResult = {
24
+ /**
25
+ * the stored record held changes the document did not have, and they were imported
26
+ */
27
+ imported: boolean;
28
+ /**
29
+ * the stored record now contains EVERYTHING the document has (writing the document again would add nothing)
30
+ */
31
+ covers: boolean;
32
+ /**
33
+ * `false`: the record holds something the document still lacks after the import (a shallow snapshot that
34
+ * does not follow from the document): it cannot be merged and must not be overwritten without a copy being kept
35
+ */
36
+ merged: boolean;
37
+ };
38
+ import type { LoroDoc } from 'loro-crdt';