@aionbuilders/nabu 0.1.0-beta.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/CHANGELOG.md +531 -0
  2. package/LICENSE +21 -0
  3. package/README.md +72 -341
  4. package/dist/behaviors/text/RichText.svelte +24 -4
  5. package/dist/behaviors/text/markdown-shortcuts.extension.d.ts +3 -0
  6. package/dist/behaviors/text/markdown-shortcuts.extension.js +35 -10
  7. package/dist/behaviors/text/markdown-syntax.d.ts +42 -0
  8. package/dist/behaviors/text/markdown-syntax.js +81 -0
  9. package/dist/behaviors/text/rich-text.extension.d.ts +3 -0
  10. package/dist/behaviors/text/rich-text.extension.js +95 -38
  11. package/dist/behaviors/text/text.behavior.svelte.d.ts +195 -55
  12. package/dist/behaviors/text/text.behavior.svelte.js +531 -103
  13. package/dist/behaviors/text/typography.extension.d.ts +2 -1
  14. package/dist/behaviors/text/typography.extension.js +3 -2
  15. package/dist/blocks/BlockList.svelte +48 -0
  16. package/dist/blocks/BlockList.svelte.d.ts +17 -0
  17. package/dist/blocks/Nabu.svelte +169 -25
  18. package/dist/blocks/Nabu.svelte.d.ts +13 -0
  19. package/dist/blocks/block.extension.d.ts +3 -0
  20. package/dist/blocks/block.extension.js +4 -7
  21. package/dist/blocks/block.svelte.d.ts +350 -86
  22. package/dist/blocks/block.svelte.js +370 -59
  23. package/dist/blocks/blockquote/Blockquote.svelte +1 -2
  24. package/dist/blocks/blockquote/blockquote.extension.d.ts +4 -1
  25. package/dist/blocks/blockquote/blockquote.extension.js +14 -5
  26. package/dist/blocks/blockquote/blockquote.svelte.d.ts +19 -11
  27. package/dist/blocks/blockquote/blockquote.svelte.js +58 -13
  28. package/dist/blocks/callout/Callout.svelte +6 -8
  29. package/dist/blocks/callout/callout.extension.d.ts +4 -1
  30. package/dist/blocks/callout/callout.extension.js +19 -3
  31. package/dist/blocks/callout/callout.svelte.d.ts +5 -3
  32. package/dist/blocks/callout/callout.svelte.js +11 -6
  33. package/dist/blocks/chunks.d.ts +49 -0
  34. package/dist/blocks/chunks.js +90 -0
  35. package/dist/blocks/code/Code.svelte +7 -8
  36. package/dist/blocks/code/code.extension.d.ts +4 -1
  37. package/dist/blocks/code/code.extension.js +22 -2
  38. package/dist/blocks/code/code.svelte.d.ts +9 -2
  39. package/dist/blocks/code/code.svelte.js +49 -25
  40. package/dist/blocks/container.utils.d.ts +85 -13
  41. package/dist/blocks/container.utils.js +338 -178
  42. package/dist/blocks/dialogue/Dialogue.svelte +8 -4
  43. package/dist/blocks/dialogue/dialogue.svelte.d.ts +33 -2
  44. package/dist/blocks/dialogue/dialogue.svelte.js +58 -4
  45. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +2 -2
  46. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +6 -4
  47. package/dist/blocks/dialogue/index.d.ts +12 -1
  48. package/dist/blocks/dialogue/index.js +51 -35
  49. package/dist/blocks/divider/divider.extension.d.ts +23 -1
  50. package/dist/blocks/divider/divider.extension.js +85 -19
  51. package/dist/blocks/divider/divider.svelte.d.ts +7 -2
  52. package/dist/blocks/divider/divider.svelte.js +9 -4
  53. package/dist/blocks/file/File.svelte +13 -6
  54. package/dist/blocks/file/file.extension.d.ts +4 -1
  55. package/dist/blocks/file/file.extension.js +9 -1
  56. package/dist/blocks/file/file.svelte.d.ts +3 -3
  57. package/dist/blocks/file/file.svelte.js +20 -14
  58. package/dist/blocks/heading/Heading.svelte +1 -2
  59. package/dist/blocks/heading/heading.svelte.d.ts +23 -11
  60. package/dist/blocks/heading/heading.svelte.js +68 -13
  61. package/dist/blocks/heading/hooks/onBeforeInput.hook.js +7 -5
  62. package/dist/blocks/heading/index.d.ts +2 -2
  63. package/dist/blocks/heading/index.js +33 -8
  64. package/dist/blocks/image/Image.svelte +5 -2
  65. package/dist/blocks/image/image.extension.d.ts +4 -1
  66. package/dist/blocks/image/image.extension.js +9 -1
  67. package/dist/blocks/image/image.svelte.d.ts +17 -6
  68. package/dist/blocks/image/image.svelte.js +33 -11
  69. package/dist/blocks/index.d.ts +1 -1
  70. package/dist/blocks/index.js +1 -1
  71. package/dist/blocks/list/List.svelte +1 -0
  72. package/dist/blocks/list/ListItem.svelte +1 -0
  73. package/dist/blocks/list/convert.d.ts +20 -0
  74. package/dist/blocks/list/convert.js +92 -0
  75. package/dist/blocks/list/hooks/onBeforeInput.hook.js +49 -28
  76. package/dist/blocks/list/html-flat.d.ts +78 -0
  77. package/dist/blocks/list/html-flat.js +244 -0
  78. package/dist/blocks/list/indent.d.ts +86 -0
  79. package/dist/blocks/list/indent.js +205 -0
  80. package/dist/blocks/list/index.d.ts +6 -3
  81. package/dist/blocks/list/index.js +42 -31
  82. package/dist/blocks/list/list-item.svelte.d.ts +32 -18
  83. package/dist/blocks/list/list-item.svelte.js +99 -100
  84. package/dist/blocks/list/list.behavior.svelte.d.ts +4 -1
  85. package/dist/blocks/list/list.behavior.svelte.js +6 -1
  86. package/dist/blocks/list/list.svelte.d.ts +89 -18
  87. package/dist/blocks/list/list.svelte.js +129 -125
  88. package/dist/blocks/list/markdown.d.ts +149 -0
  89. package/dist/blocks/list/markdown.js +442 -0
  90. package/dist/blocks/list/normalize.d.ts +11 -0
  91. package/dist/blocks/list/normalize.js +396 -0
  92. package/dist/blocks/list/paste.d.ts +45 -0
  93. package/dist/blocks/list/paste.js +242 -0
  94. package/dist/blocks/list/step-back.d.ts +24 -0
  95. package/dist/blocks/list/step-back.js +87 -0
  96. package/dist/blocks/list/to-list.d.ts +7 -0
  97. package/dist/blocks/list/to-list.js +44 -0
  98. package/dist/blocks/list/todos-toggle.d.ts +20 -0
  99. package/dist/blocks/list/todos-toggle.js +48 -0
  100. package/dist/blocks/media/markdown.d.ts +12 -0
  101. package/dist/blocks/media/markdown.js +26 -0
  102. package/dist/blocks/media/media-block.svelte.d.ts +77 -2
  103. package/dist/blocks/media/media-block.svelte.js +124 -12
  104. package/dist/blocks/media/media.helpers.d.ts +6 -1
  105. package/dist/blocks/media/media.helpers.js +43 -6
  106. package/dist/blocks/megablock.svelte.d.ts +50 -19
  107. package/dist/blocks/megablock.svelte.js +114 -74
  108. package/dist/blocks/move.d.ts +23 -0
  109. package/dist/blocks/move.js +92 -0
  110. package/dist/blocks/nabu.svelte.d.ts +764 -71
  111. package/dist/blocks/nabu.svelte.js +1753 -189
  112. package/dist/blocks/paragraph/Paragraph.svelte +1 -2
  113. package/dist/blocks/paragraph/index.d.ts +2 -2
  114. package/dist/blocks/paragraph/index.js +35 -13
  115. package/dist/blocks/paragraph/paragraph.svelte.d.ts +46 -14
  116. package/dist/blocks/paragraph/paragraph.svelte.js +77 -16
  117. package/dist/blocks/paragraph/table.html.d.ts +9 -0
  118. package/dist/blocks/paragraph/table.html.js +111 -0
  119. package/dist/blocks/paragraph/table.markdown.d.ts +32 -0
  120. package/dist/blocks/paragraph/table.markdown.js +90 -0
  121. package/dist/blocks/region/Region.svelte +264 -0
  122. package/dist/blocks/region/Region.svelte.d.ts +11 -0
  123. package/dist/blocks/region/actions.d.ts +135 -0
  124. package/dist/blocks/region/actions.js +402 -0
  125. package/dist/blocks/region/close.d.ts +35 -0
  126. package/dist/blocks/region/close.js +130 -0
  127. package/dist/blocks/region/commands.d.ts +6 -0
  128. package/dist/blocks/region/commands.js +277 -0
  129. package/dist/blocks/region/create.d.ts +72 -0
  130. package/dist/blocks/region/create.js +208 -0
  131. package/dist/blocks/region/end-marker.d.ts +35 -0
  132. package/dist/blocks/region/end-marker.js +51 -0
  133. package/dist/blocks/region/facts.d.ts +69 -0
  134. package/dist/blocks/region/facts.js +152 -0
  135. package/dist/blocks/region/format.d.ts +91 -0
  136. package/dist/blocks/region/format.js +260 -0
  137. package/dist/blocks/region/index.d.ts +14 -0
  138. package/dist/blocks/region/index.js +14 -0
  139. package/dist/blocks/region/insert.d.ts +59 -0
  140. package/dist/blocks/region/insert.js +102 -0
  141. package/dist/blocks/region/messages.d.ts +254 -0
  142. package/dist/blocks/region/messages.js +131 -0
  143. package/dist/blocks/region/normalize.d.ts +7 -0
  144. package/dist/blocks/region/normalize.js +170 -0
  145. package/dist/blocks/region/region.extension.d.ts +58 -0
  146. package/dist/blocks/region/region.extension.js +119 -0
  147. package/dist/blocks/region/region.svelte.d.ts +221 -0
  148. package/dist/blocks/region/region.svelte.js +582 -0
  149. package/dist/blocks/region/regions.svelte.d.ts +141 -0
  150. package/dist/blocks/region/regions.svelte.js +276 -0
  151. package/dist/blocks/region/serialize.d.ts +57 -0
  152. package/dist/blocks/region/serialize.js +112 -0
  153. package/dist/blocks/region/types.d.ts +255 -0
  154. package/dist/blocks/region/types.js +204 -0
  155. package/dist/blocks/selection.svelte.d.ts +106 -8
  156. package/dist/blocks/selection.svelte.js +622 -74
  157. package/dist/blocks/subthread.d.ts +80 -0
  158. package/dist/blocks/subthread.js +167 -0
  159. package/dist/blocks/text-block.svelte.d.ts +35 -14
  160. package/dist/blocks/text-block.svelte.js +42 -8
  161. package/dist/blocks/toggle/Toggle.svelte +4 -15
  162. package/dist/blocks/toggle/markdown.d.ts +20 -0
  163. package/dist/blocks/toggle/markdown.js +112 -0
  164. package/dist/blocks/toggle/toggle.extension.d.ts +4 -1
  165. package/dist/blocks/toggle/toggle.extension.js +6 -0
  166. package/dist/blocks/toggle/toggle.svelte.d.ts +55 -8
  167. package/dist/blocks/toggle/toggle.svelte.js +134 -34
  168. package/dist/blocks/undo-selection.d.ts +175 -0
  169. package/dist/blocks/undo-selection.js +360 -0
  170. package/dist/blocks/video/Video.svelte +5 -2
  171. package/dist/blocks/video/video.extension.d.ts +4 -1
  172. package/dist/blocks/video/video.extension.js +9 -1
  173. package/dist/blocks/video/video.svelte.d.ts +6 -5
  174. package/dist/blocks/video/video.svelte.js +18 -9
  175. package/dist/extend.d.ts +55 -0
  176. package/dist/extend.js +88 -0
  177. package/dist/files/assets.clipboard.d.ts +77 -0
  178. package/dist/files/assets.clipboard.js +152 -0
  179. package/dist/files/files.svelte.d.ts +321 -19
  180. package/dist/files/files.svelte.js +847 -43
  181. package/dist/files/index.d.ts +3 -1
  182. package/dist/files/index.js +3 -1
  183. package/dist/files/outbox.d.ts +69 -0
  184. package/dist/files/outbox.js +48 -0
  185. package/dist/files/status.d.ts +65 -0
  186. package/dist/files/status.js +87 -0
  187. package/dist/files/store.d.ts +97 -0
  188. package/dist/files/store.js +65 -0
  189. package/dist/files/uploads.svelte.d.ts +174 -0
  190. package/dist/files/uploads.svelte.js +504 -0
  191. package/dist/index.d.ts +68 -9
  192. package/dist/index.js +117 -10
  193. package/dist/nabu-theme.css +21 -1
  194. package/dist/paste/html.paste.d.ts +74 -3
  195. package/dist/paste/html.paste.js +550 -86
  196. package/dist/paste/markdown-inline.d.ts +86 -0
  197. package/dist/paste/markdown-inline.js +528 -0
  198. package/dist/paste/markdown.paste.d.ts +2 -8
  199. package/dist/paste/markdown.paste.js +78 -94
  200. package/dist/paste/nabu.paste.d.ts +3 -0
  201. package/dist/paste/nabu.paste.js +29 -3
  202. package/dist/paste/plain-text.paste.d.ts +2 -2
  203. package/dist/paste/plain-text.paste.js +3 -3
  204. package/dist/persistence/asset-store.d.ts +51 -0
  205. package/dist/persistence/asset-store.js +103 -0
  206. package/dist/persistence/autosave.d.ts +53 -0
  207. package/dist/persistence/autosave.js +62 -0
  208. package/dist/persistence/compact.d.ts +162 -0
  209. package/dist/persistence/compact.js +141 -0
  210. package/dist/persistence/history.d.ts +77 -0
  211. package/dist/persistence/history.js +176 -0
  212. package/dist/persistence/indexeddb.d.ts +190 -4
  213. package/dist/persistence/indexeddb.js +333 -29
  214. package/dist/persistence/merge.d.ts +38 -0
  215. package/dist/persistence/merge.js +36 -0
  216. package/dist/persistence/outbox.d.ts +25 -0
  217. package/dist/persistence/outbox.js +40 -0
  218. package/dist/persistence/persistence.d.ts +70 -9
  219. package/dist/persistence/persistence.js +507 -35
  220. package/dist/persistence/recovery.d.ts +79 -0
  221. package/dist/persistence/recovery.js +79 -0
  222. package/dist/persistence/release.d.ts +34 -0
  223. package/dist/persistence/release.js +64 -0
  224. package/dist/persistence/state.svelte.d.ts +53 -0
  225. package/dist/persistence/state.svelte.js +48 -0
  226. package/dist/persistence/sync.d.ts +39 -0
  227. package/dist/persistence/sync.js +138 -0
  228. package/dist/persistence/tail.d.ts +42 -0
  229. package/dist/persistence/tail.js +103 -0
  230. package/dist/presets.d.ts +29 -26
  231. package/dist/presets.js +35 -13
  232. package/dist/themes/atelier.css +318 -0
  233. package/dist/ui/CommandChooser.svelte +153 -0
  234. package/dist/ui/CommandChooser.svelte.d.ts +13 -0
  235. package/dist/ui/CommandInvite.svelte +99 -0
  236. package/dist/ui/CommandInvite.svelte.d.ts +12 -0
  237. package/dist/ui/DragHandle.svelte +97 -21
  238. package/dist/ui/FloatingToolbar.svelte +75 -27
  239. package/dist/ui/FloatingToolbar.svelte.d.ts +10 -0
  240. package/dist/ui/SlashMenu.svelte +147 -15
  241. package/dist/ui/SlashMenu.svelte.d.ts +20 -0
  242. package/dist/ui/anchor.d.ts +112 -0
  243. package/dist/ui/anchor.js +136 -0
  244. package/dist/ui/index.d.ts +7 -1
  245. package/dist/ui/index.js +12 -1
  246. package/dist/ui/slash-menu.svelte.d.ts +79 -7
  247. package/dist/ui/slash-menu.svelte.js +85 -51
  248. package/dist/utils/command-confirm.svelte.d.ts +349 -0
  249. package/dist/utils/command-confirm.svelte.js +673 -0
  250. package/dist/utils/commands.d.ts +328 -0
  251. package/dist/utils/commands.js +416 -0
  252. package/dist/utils/composition.d.ts +28 -0
  253. package/dist/utils/composition.js +51 -0
  254. package/dist/utils/dom-scope.d.ts +14 -0
  255. package/dist/utils/dom-scope.js +20 -0
  256. package/dist/utils/drop.d.ts +160 -0
  257. package/dist/utils/drop.js +305 -0
  258. package/dist/utils/extensions.d.ts +439 -45
  259. package/dist/utils/extensions.js +271 -29
  260. package/dist/utils/html.d.ts +44 -0
  261. package/dist/utils/html.js +183 -0
  262. package/dist/utils/index.d.ts +3 -0
  263. package/dist/utils/index.js +3 -0
  264. package/dist/utils/keys.d.ts +120 -0
  265. package/dist/utils/keys.js +248 -0
  266. package/dist/utils/links.d.ts +22 -0
  267. package/dist/utils/links.js +34 -0
  268. package/dist/utils/placeholders.d.ts +81 -3
  269. package/dist/utils/placeholders.js +73 -3
  270. package/dist/utils/selection.svelte.d.ts +48 -20
  271. package/dist/utils/selection.svelte.js +60 -10
  272. package/dist/utils/spellcheck.d.ts +9 -0
  273. package/dist/utils/spellcheck.js +17 -0
  274. package/dist/utils/tab.d.ts +31 -0
  275. package/dist/utils/tab.js +117 -0
  276. package/dist/utils/words.d.ts +42 -0
  277. package/dist/utils/words.js +147 -0
  278. package/dist/vite.d.ts +9 -3
  279. package/dist/vite.js +19 -8
  280. package/package.json +56 -20
  281. package/dist/blocks/variable.svelte.d.ts +0 -47
  282. package/dist/blocks/variable.svelte.js +0 -51
  283. package/dist/blocks/zone/TemplateEditor.svelte +0 -308
  284. package/dist/blocks/zone/TemplateEditor.svelte.d.ts +0 -11
  285. package/dist/blocks/zone/Zone.svelte +0 -272
  286. package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
  287. package/dist/blocks/zone/ZoneEditor.svelte +0 -289
  288. package/dist/blocks/zone/ZoneEditor.svelte.d.ts +0 -11
  289. package/dist/blocks/zone/ZoneTemplatesList.svelte +0 -188
  290. package/dist/blocks/zone/ZoneTemplatesList.svelte.d.ts +0 -11
  291. package/dist/blocks/zone/hooks/onBeforeInput.hook.d.ts +0 -3
  292. package/dist/blocks/zone/hooks/onBeforeInput.hook.js +0 -30
  293. package/dist/blocks/zone/index.d.ts +0 -2
  294. package/dist/blocks/zone/index.js +0 -2
  295. package/dist/blocks/zone/zone.extension.d.ts +0 -2
  296. package/dist/blocks/zone/zone.extension.js +0 -237
  297. package/dist/blocks/zone/zone.svelte.d.ts +0 -221
  298. package/dist/blocks/zone/zone.svelte.js +0 -608
  299. package/dist/overlays/context/Context.svelte +0 -182
  300. package/dist/overlays/context/Context.svelte.d.ts +0 -17
  301. package/dist/overlays/context/collect.d.ts +0 -17
  302. package/dist/overlays/context/collect.js +0 -33
  303. package/dist/overlays/context/context.extension.d.ts +0 -2
  304. package/dist/overlays/context/context.extension.js +0 -8
  305. package/dist/overlays/context/context.svelte.d.ts +0 -82
  306. package/dist/overlays/context/context.svelte.js +0 -159
  307. package/dist/overlays/context/index.d.ts +0 -3
  308. package/dist/overlays/context/index.js +0 -3
@@ -1,13 +1,32 @@
1
1
  import { Nabu } from '../blocks/nabu.svelte.js';
2
- import { FullPreset } from '../presets.js';
3
- import { loadSnapshot, saveSnapshot, deleteSnapshot } from './indexeddb.js';
2
+ import { FullPreset, tabDefaultFor } from '../presets.js';
3
+ import { Files } from '../files/files.svelte.js';
4
+ import { MemoryAssetStore } from '../files/store.js';
5
+ import { loadSnapshot, saveSnapshot, saveMerged, deleteSnapshot, loadRecords, quarantineRecords, listQuarantined, IDBConnection, isSnapshotBytes } from './indexeddb.js';
6
+ import { createAutosave, resolveMaxWait } from './autosave.js';
7
+ import { resolveLoad, describeRecovery } from './recovery.js';
8
+ import { PersistenceState } from './state.svelte.js';
9
+ import { readTail, writeTail, clearTail, parkTail, writeRev, readRev, clearRev, revToken } from './tail.js';
10
+ import { mergeStored } from './merge.js';
11
+ import { startSync } from './sync.js';
12
+ import { IndexedDBAssetStore } from './asset-store.js';
13
+ import { IndexedDBOutbox } from './outbox.js';
14
+ import { parseHistory } from './history.js';
15
+ import { runCompaction } from './compact.js';
16
+ import { releaseFiles } from './release.js';
4
17
 
5
- export { loadSnapshot, saveSnapshot, deleteSnapshot };
18
+ export { loadSnapshot, saveSnapshot, deleteSnapshot, loadRecords, listQuarantined, IndexedDBAssetStore, IndexedDBOutbox, PersistenceState };
6
19
 
7
20
  /**
8
21
  * @import { Extension } from '../utils/extensions.js';
22
+ * @import { CompactOptions } from './history.js';
23
+ * @import { CompactResult } from './compact.js';
24
+ * @import { Recovery } from './recovery.js';
9
25
  */
10
26
 
27
+ /** Persistence problems are shown even when `nabu.debugging` is off (`nabu.warn` is silent then): the host's user may be losing work. @param {string} message */
28
+ const warn = (message) => console.warn('[Nabu]', message);
29
+
11
30
  /**
12
31
  * Create a Nabu editor instance with automatic IndexedDB persistence.
13
32
  *
@@ -17,16 +36,58 @@ export { loadSnapshot, saveSnapshot, deleteSnapshot };
17
36
  * On first call, the document is empty (only the default paragraph from ParagraphExtension).
18
37
  * On subsequent calls, the document state is restored from the last saved snapshot.
19
38
  *
20
- * The instance gains three extra methods:
21
- * - `nabu.saveNow()` — force an immediate save (returns a Promise)
22
- * - `nabu.clearPersistence()` — delete the stored snapshot (returns a Promise)
23
- * - `nabu.isNew` — `true` if no previous snapshot was found (fresh document)
39
+ * The bytes of the files (images, videos…) are NOT saved in the snapshot (ADR 014): they go to an `IndexedDBAssetStore`
40
+ * (base `nabu`, object store `assets`, shared by every document of the origin), unless `files.store` provides another one.
41
+ * The document only keeps references and a small metadata index; the store also records which files each document references.
42
+ * With a host (`files.onBeforePersist`) the uploads still to do are listed in an `IndexedDBOutbox` (object store `outbox`, unless
43
+ * `files.outbox` provides another one): an upload interrupted by a closed tab RESUMES when the document is opened again.
44
+ *
45
+ * History (ADR 014 §3.6): the default `history: 'full'` NEVER compacts or trims anything (the whole evolution of the document
46
+ * is kept and saved, whatever the number of sessions). `history: { mode: 'compact', retain, onBeforeCompact }` opts in to a
47
+ * compaction when the document is OPENED (after loading, migration and upload reconciliation; never mid-session): history older
48
+ * than `retain` is dropped and the files only that history referenced are released. See {@link CompactOptions} and `nabu.compact()`.
49
+ *
50
+ * Timestamps of the changes are recorded (`doc.setRecordTimestamp(true)`) so a retention window can be honoured.
51
+ *
52
+ * Robustness (ADR 010, theme 8): the autosave also happens at most every `maxWait` ms during a continuous burst, and immediately when
53
+ * the page is hidden (`visibilitychange` → `hidden`, `pagehide`). Every save keeps the snapshot it replaces as a BACKUP. A stored
54
+ * snapshot that cannot be read is moved aside (never deleted: the `quarantine` object store), the backup is tried, else the editor
55
+ * starts empty — it always boots, and `nabu.persistence.recovery` / `onRecover` tell the host what happened. When IndexedDB is not
56
+ * usable the editor boots IN MEMORY (`nabu.persistence.available === false`, status `'unavailable'`): `createPersistedEditor` does not reject.
57
+ *
58
+ * Several tabs (ADR 010, P-94): two tabs on the same `docId` never overwrite each other. EVERY save first merges what is stored (read and
59
+ * written in one IndexedDB transaction: the changes another tab saved are imported into the live document, not as undo steps, the caret
60
+ * stays on its character), and, with `sync` (default), the tabs also exchange their changes LIVE through a `BroadcastChannel`
61
+ * (`nabu:<docId>`): an edit made in one tab appears in the others at once.
62
+ *
63
+ * The instance gains extra members:
64
+ * - `nabu.persistence` — reactive state: `status` (`'saved' | 'pending' | 'saving' | 'error' | 'unavailable'`), `lastSavedAt`,
65
+ * `lastError`, `available`, `recovery`, `sync`, and `dispose()` (stop autosave, remove the page listeners, close the sync channel and
66
+ * the connection)
67
+ * - `nabu.saveNow()` — force an immediate save (returns a Promise; rejects if the save fails)
68
+ * - `nabu.compact({ retain, onBeforeCompact })` — explicit compaction (returns a `CompactResult`, never throws for a refusal)
69
+ * - `nabu.clearPersistence()` — delete the stored snapshot and release the document's files (returns a Promise)
70
+ * - `nabu.isNew` — `true` if no previous snapshot was found (fresh document, or nothing readable was left: `persistence.recovery.kind === 'empty'`)
24
71
  *
25
72
  * @param {object} options
26
73
  * @param {string} options.docId - Unique identifier for this document in IndexedDB
27
74
  * @param {Extension[]} [options.preset] - Extension preset (default: FullPreset)
28
75
  * @param {Extension[]} [options.extensions] - Additional extensions to append
29
76
  * @param {number} [options.debounce] - Auto-save debounce delay in ms (default: 2000)
77
+ * @param {number} [options.maxWait] - Longest time (ms) a continuous burst of edits goes without a save (default: 3000, never shorter than
78
+ * `debounce`; `0` / `Infinity`: no maximum, the autosave only happens after a pause)
79
+ * @param {(error: unknown) => void} [options.onSaveError] - Called when an AUTOMATIC save fails (quota…); `nabu.persistence.status` is `'error'` and the
80
+ * next change retries. `saveNow()` rejects for its awaiter instead (the hook is not called for it)
81
+ * @param {(recovery: Recovery) => void} [options.onRecover] - Called at boot when the stored document could not be read (see `nabu.persistence.recovery`)
82
+ * @param {boolean} [options.sync] - Live sync between the tabs that edit the same `docId` through a `BroadcastChannel` (default `true`; `false`
83
+ * disables it; a browser without `BroadcastChannel` skips it silently). The merge on save does not depend on it. `nabu.persistence.sync` tells whether it runs.
84
+ * @param {import('../files/files.svelte.js').FilesConfig} [options.files] - File handling; `files.store` replaces the default IndexedDB asset store
85
+ * @param {'full' | { mode: 'full' } | { mode: 'compact', retain: number | string, onBeforeCompact?: CompactOptions['onBeforeCompact'] }} [options.history] - `'full'` (default): nothing is ever compacted.
86
+ * `{ mode: 'compact', retain, onBeforeCompact }`: compact at open (`retain`: ms, `'30d'`, `'12h'`, or `0` = keep no past history).
87
+ * @param {import('../utils/placeholders.js').PlaceholdersOption} [options.placeholders] - Forwarded to Nabu
88
+ * (any other Nabu init option, e.g. `files`, is forwarded too; `files.store` replaces the default IndexedDB asset store)
89
+ * @param {boolean} [options.spellcheck] - Forwarded to Nabu (default `true`)
90
+ * @param {string} [options.lang] - Forwarded to Nabu (BCP 47 tag of the content)
30
91
  * @returns {Promise<Nabu>}
31
92
  *
32
93
  * @example
@@ -45,36 +106,447 @@ export async function createPersistedEditor({
45
106
  docId,
46
107
  preset = FullPreset,
47
108
  extensions = [],
48
- debounce = 2000
49
- } = {}) {
50
- const snapshot = await loadSnapshot(docId);
51
-
52
- const nabu = new Nabu({
53
- extensions: [...preset, ...extensions],
54
- ...(snapshot ? { snapshot } : {})
55
- });
56
-
57
- // Auto-save: Loro fires doc.subscribe() after every committed change
58
- let saveTimer;
59
- nabu.doc.subscribe(() => {
60
- clearTimeout(saveTimer);
61
- saveTimer = setTimeout(async () => {
62
- const snap = nabu.doc.export({ mode: 'snapshot' });
63
- await saveSnapshot(docId, snap);
64
- }, debounce);
65
- });
66
-
67
- /** Whether this instance was created from a fresh document (no prior snapshot). */
68
- nabu.isNew = !snapshot;
69
-
70
- /** Force an immediate save of the current document state. @returns {Promise<void>} */
71
- nabu.saveNow = async () => {
72
- const snap = nabu.doc.export({ mode: 'snapshot' });
73
- await saveSnapshot(docId, snap);
109
+ debounce = 2000,
110
+ maxWait,
111
+ sync = true,
112
+ onSaveError,
113
+ onRecover,
114
+ history,
115
+ ...init
116
+ } = /** @type {any} */ ({})) {
117
+ const historyConfig = parseHistory(history); // a typo in `history` must fail loudly, before anything is read
118
+ const maxWaitMs = resolveMaxWait(maxWait, debounce);
119
+ const conn = new IDBConnection();
120
+
121
+ // ── 1. read what is stored. IndexedDB missing / refusing / blocked: boot in memory, never reject ──
122
+ /** @type {{ current: any, backup: any } | null} */
123
+ let records = null;
124
+ /** @type {unknown} */
125
+ let unavailableError = null;
126
+ try {
127
+ records = await loadRecords(docId, conn);
128
+ } catch (error) {
129
+ unavailableError = error ?? new Error('IndexedDB is not available');
130
+ }
131
+ let available = !unavailableError;
132
+ const store = init.files?.store ?? (available ? new IndexedDBAssetStore() : new MemoryAssetStore());
133
+ const outbox = init.files?.outbox ?? (available ? new IndexedDBOutbox(docId) : undefined);
134
+
135
+ /** @param {Uint8Array | null} snapshot */
136
+ const build = (snapshot) => {
137
+ const nabu = new Nabu({
138
+ tabDefault: tabDefaultFor(preset),
139
+ ...init,
140
+ files: { ...init.files, store, ...(outbox ? { outbox } : {}) },
141
+ extensions: [...preset, ...extensions],
142
+ ...(snapshot ? { snapshot } : {})
143
+ });
144
+ // Timestamps make a retention window (`retain: '30d'`) possible. Off by default in Loro; harmless to enable (a few bytes per change).
145
+ nabu.doc.setRecordTimestamp(true);
146
+ return nabu;
147
+ };
148
+
149
+ // ── 2. open the document: the current snapshot, else the backup, else empty. A record that cannot be read is moved aside, never deleted ──
150
+ const decision = available
151
+ ? resolveLoad(/** @type {NonNullable<typeof records>} */ (records), (snapshot) => {
152
+ if (!isSnapshotBytes(snapshot)) throw new TypeError('the stored snapshot is not a non-empty byte array');
153
+ return build(snapshot);
154
+ })
155
+ : /** @type {any} */ ({ outcome: 'new', value: null, used: null, failed: [] });
156
+ /** @type {Recovery | null} */
157
+ let recovery = null;
158
+ /** @type {unknown} */
159
+ let quarantineError = null;
160
+ if (decision.outcome === 'backup' || decision.outcome === 'empty') {
161
+ const at = Date.now();
162
+ try {
163
+ const keys = await quarantineRecords(docId, decision.failed, decision.outcome === 'backup' ? decision.used : null, at, conn);
164
+ recovery = describeRecovery(decision, keys, at);
165
+ } catch (error) {
166
+ // The unreadable record could not be copied aside: touching the stored data is not safe, so nothing will be written (memory only).
167
+ quarantineError = error;
168
+ recovery = describeRecovery(decision, [], at);
169
+ available = false;
170
+ }
171
+ }
172
+ const initialSnapshot = decision.used ? /** @type {Uint8Array} */ (decision.used.snapshot) : null;
173
+
174
+ /** The reactive state exposed as `nabu.persistence`. */
175
+ const state = new PersistenceState(docId);
176
+ state.available = available;
177
+ state.recovery = recovery;
178
+ if (!available) { state.status = 'unavailable'; state.lastError = quarantineError ?? unavailableError; }
179
+
180
+ /** The version of a document, to tell whether something changed since the last save. @param {import('loro-crdt').LoroDoc} doc */
181
+ const versionKey = (doc) => JSON.stringify(doc.oplogFrontiers());
182
+
183
+ /**
184
+ * Wire autosave and the extra methods onto `nabu`. Returns `dispose()` (stops this wiring: used for the instance that is
185
+ * replaced after a compaction at open, which nobody has seen).
186
+ * @param {Nabu} nabu @param {{ snapshot: Uint8Array, savedAt: number } | null} stored the record `nabu` was loaded from and that is
187
+ * stored now (`null`: a document with nothing stored)
188
+ * @param {import('loro-crdt').VersionVector | undefined} storedVersion what that record contains (`undefined`: nothing, or unknown)
189
+ * @param {boolean} [unsaved] `nabu` holds changes that are not in the stored record (a tail was merged): a save is due
190
+ */
191
+ const attach = (nabu, stored, storedVersion, unsaved = false) => {
192
+ const loaded = stored !== null && !unsaved;
193
+ /** What the stored record contains, to export the tail from. @type {import('loro-crdt').VersionVector | undefined} */
194
+ let savedVersion = storedVersion;
195
+ /** Version known to be saved (`null`: never saved). */
196
+ let savedKey = loaded ? versionKey(nabu.doc) : null;
197
+ /**
198
+ * What this editor last wrote or loaded (the record stored now, unless another tab wrote since), kept to become the backup
199
+ * of the next save WITHOUT reading it back first (a save from `pagehide` must issue its requests synchronously).
200
+ * @type {{ snapshot: Uint8Array, savedAt: number } | null}
201
+ */
202
+ let lastStored = stored;
203
+ /** Version of the last save that was STARTED (a second flush must not repeat a save that is already running). @type {string | null} */
204
+ let requestedKey = savedKey;
205
+ /**
206
+ * Where the last compaction of THIS session cut the history. The live document still holds the older history (Loro cannot
207
+ * trim it in place), so from then on every save is a shallow snapshot at that version: the saved document stays compacted.
208
+ * @type {{ peer: `${number}`, counter: number }[] | undefined}
209
+ */
210
+ let compactedAt;
211
+ /** Saves and the critical part of a compaction never overlap. */
212
+ let chain = Promise.resolve();
213
+ /** @template T @param {() => Promise<T>} fn @returns {Promise<T>} */
214
+ const lock = (fn) => { const run = chain.then(fn, fn); chain = run.then(() => {}, () => {}); return run; };
215
+
216
+ /**
217
+ * Files a release kept because they were too recent to delete (`files.releaseGraceMs`). They stay in this document's `docRefs`
218
+ * (so they are tracked, and nobody deletes them meanwhile) and are reconsidered by the next compaction / `clearPersistence()`.
219
+ * Loaded from the stored `docRefs` the first time (what the index does not list is what an earlier session held back).
220
+ * @type {Set<string>}
221
+ */
222
+ const held = new Set();
223
+ let heldLoaded = false;
224
+ const loadHeld = async () => {
225
+ if (heldLoaded) return;
226
+ heldLoaded = true;
227
+ const reader = /** @type {any} */ (store);
228
+ if (typeof reader.getDocRefs !== 'function') return;
229
+ const indexed = new Set(Files.get(nabu).indexedHashes());
230
+ for (const hash of await reader.getDocRefs(docId)) if (!indexed.has(hash)) held.add(hash);
231
+ };
232
+
233
+ /** Record which files the document references (the store's `docRefs`, used by the cleanup): its index, plus the files held back. */
234
+ const saveRefs = async () => {
235
+ const refs = /** @type {any} */ (store).setDocRefs;
236
+ if (typeof refs !== 'function') return;
237
+ await loadHeld();
238
+ await refs.call(store, docId, new Set([...Files.get(nabu).indexedHashes(), ...held]));
239
+ };
240
+
241
+ let disposed = false;
242
+ /** True while a save imports the stored record into the document (see the `doc.subscribe` below). */
243
+ let mergingStored = false;
244
+
245
+ /** Whether there is anything not stored yet (a save scheduled, a change since the last save, a failed save to retry). */
246
+ const isUnsaved = () => autosave.pending()
247
+ || state.status === 'error'
248
+ || nabu.doc.getPendingTxnLength() > 0
249
+ || (requestedKey !== null && versionKey(nabu.doc) !== requestedKey);
250
+
251
+ /** Never throws away the status of a change that came while a save was running. */
252
+ const settle = () => { state.status = isUnsaved() ? 'pending' : 'saved'; };
253
+
254
+ /** Whether a record is the one this editor wrote or loaded last (so nobody else wrote since: nothing to merge). @param {{ snapshot: Uint8Array, savedAt?: number }} record */
255
+ const isMine = (record) => lastStored !== null && record.savedAt === lastStored.savedAt && record.snapshot.length === lastStored.snapshot.length;
256
+
257
+ /**
258
+ * Save the document. By default the save MERGES what is stored first (P-94): in one read-write transaction the stored record is read,
259
+ * whatever it holds that this document lacks is imported, and the result is exported and written (nothing at all when the stored
260
+ * record already holds everything). `blind` (a page that is going away, nobody else wrote since) skips the read, so that every request
261
+ * is issued synchronously.
262
+ * @param {{ blind?: boolean }} [options]
263
+ */
264
+ const save = ({ blind = false } = {}) => lock(async () => {
265
+ if (!available) throw new Error('persistence is unavailable: IndexedDB cannot be used, the document is only in memory');
266
+ if (disposed) throw new Error('persistence was disposed');
267
+ requestedKey = versionKey(nabu.doc);
268
+ state.status = 'saving';
269
+ try {
270
+ /** @type {{ snapshot: Uint8Array, savedAt: number }} */
271
+ let record;
272
+ /** The version / key of the document at the moment it was exported (a merge may have moved them). */
273
+ let version = nabu.doc.version();
274
+ let key = versionKey(nabu.doc);
275
+ const exportDoc = () => (compactedAt
276
+ ? nabu.doc.export({ mode: 'shallow-snapshot', frontiers: compactedAt })
277
+ : nabu.doc.export({ mode: 'snapshot' }));
278
+ if (blind) {
279
+ const snap = exportDoc();
280
+ version = nabu.doc.version(); // (the export above committed any pending change: this is what `snap` contains)
281
+ key = versionKey(nabu.doc);
282
+ record = /** @type {{ snapshot: Uint8Array, savedAt: number }} */ (await saveSnapshot(docId, snap, { conn, previous: lastStored }));
283
+ } else {
284
+ const { stored, written, quarantinedKey } = await saveMerged(docId, (found) => {
285
+ /** @type {unknown} */
286
+ let unmerged;
287
+ let covers = false;
288
+ if (found && !isSnapshotBytes(found.snapshot)) {
289
+ unmerged = new TypeError('the stored snapshot is not a non-empty byte array');
290
+ } else if (found && !isMine(/** @type {any} */ (found))) {
291
+ mergingStored = true; // (Loro may deliver the events of the import before this callback returns)
292
+ try {
293
+ const merge = mergeStored(nabu.doc, /** @type {Uint8Array} */ (found.snapshot), (bytes) => nabu.importRemote(bytes));
294
+ covers = merge.covers;
295
+ if (!merge.merged) unmerged = new Error('the stored document holds changes this one cannot merge (a compacted copy saved by another tab)');
296
+ } catch (error) {
297
+ unmerged = error ?? new Error('the stored document could not be merged');
298
+ } finally {
299
+ mergingStored = false;
300
+ }
301
+ }
302
+ const snapshot = covers && !compactedAt && unmerged === undefined ? null : exportDoc();
303
+ version = nabu.doc.version();
304
+ key = requestedKey = versionKey(nabu.doc);
305
+ return unmerged === undefined ? { snapshot } : { snapshot, unmerged };
306
+ }, { conn });
307
+ if (quarantinedKey) warn(`persistence: the stored copy of "${docId}" could not be merged with this tab and is kept in the "quarantine" store (${quarantinedKey}); it was replaced by this tab's document`);
308
+ const kept = written ?? stored;
309
+ if (!kept || !isSnapshotBytes(kept.snapshot)) throw new Error('nothing was saved');
310
+ record = { snapshot: kept.snapshot, savedAt: kept.savedAt ?? Date.now() };
311
+ }
312
+ lastStored = { snapshot: record.snapshot, savedAt: record.savedAt };
313
+ savedVersion = version;
314
+ writeRev(docId, lastStored);
315
+ clearTail(docId); // the stored snapshot holds everything the tail had
316
+ await saveRefs();
317
+ savedKey = key;
318
+ requestedKey = key;
319
+ state.lastSavedAt = Date.now();
320
+ state.lastError = null;
321
+ settle();
322
+ } catch (error) {
323
+ requestedKey = savedKey; // the failed version is unsaved again
324
+ state.lastError = error;
325
+ state.status = 'error';
326
+ throw error;
327
+ }
328
+ });
329
+
330
+ /** An automatic save (timer, page hide): nobody awaits it, so a failure is reported, not thrown. */
331
+ const autosaveRun = async (/** @type {{ blind?: boolean }} */ options = {}) => {
332
+ try {
333
+ await save(options);
334
+ } catch (error) {
335
+ warn(`persistence: could not save "${docId}" (the changes stay in memory; the next change retries): ${error}`);
336
+ try { onSaveError?.(error); } catch (hookError) { warn(`persistence: onSaveError threw: ${hookError}`); }
337
+ }
338
+ };
339
+
340
+ const autosave = createAutosave({ debounce, maxWait: maxWaitMs, run: () => { void autosaveRun(); } });
341
+
342
+ // Auto-save: Loro fires doc.subscribe() after every committed change
343
+ const unsubscribe = available
344
+ ? nabu.doc.subscribe((event) => {
345
+ // What a save just imported from the stored record is in that record: it makes nothing unsaved (the event comes after the save)
346
+ if (event.by === 'import' && (mergingStored || versionKey(nabu.doc) === savedKey || versionKey(nabu.doc) === requestedKey)) return;
347
+ if (state.status !== 'saving') state.status = 'pending'; // a change that comes while saving is picked up by `settle()`
348
+ autosave.touch();
349
+ })
350
+ : () => {};
351
+
352
+ /** Write the changes since the last save to `localStorage`, synchronously (see tail.js). Never throws. */
353
+ const writeTailNow = () => {
354
+ try { writeTail(docId, nabu.doc.export(savedVersion ? { mode: 'update', from: savedVersion } : { mode: 'update' })); } catch { /* best effort */ }
355
+ };
356
+
357
+ /**
358
+ * Save RIGHT NOW (no debounce) if something is not stored: the page is going away (tab hidden, closed, navigated, reloaded).
359
+ * CAVEAT: IndexedDB is asynchronous, and a browser may finish unloading before the write commits (Chromium drops the transaction
360
+ * of a RELOAD, and often of a close). So the IndexedDB save is started at once from the connection kept open since boot (its
361
+ * requests are issued synchronously and committed explicitly, which is what lets it complete on a navigation or a tab switch), AND
362
+ * the changes since the last save are written synchronously to `localStorage` (the "tail", see tail.js), merged at the next boot.
363
+ * Still best effort: a crash, a killed process, or a mobile browser that never sends these events loses the last seconds.
364
+ */
365
+ const flushOnHide = () => {
366
+ if (disposed || !available || !isUnsaved()) return;
367
+ writeTailNow();
368
+ autosave.cancel();
369
+ // BLIND (every request issued at once, which a page that is leaving needs) only while no other tab wrote the record since this one
370
+ // read or wrote it; otherwise the save merges first (it completes when the tab merely goes to the background; for a page that
371
+ // is really leaving, the tail above is what keeps the changes).
372
+ const rev = readRev(docId);
373
+ void autosaveRun({ blind: rev === null || rev === revToken(lastStored) });
374
+ };
375
+ const onVisibility = () => { if (document.visibilityState === 'hidden') flushOnHide(); };
376
+ const listening = available && typeof document !== 'undefined' && typeof window !== 'undefined';
377
+ if (listening) {
378
+ document.addEventListener('visibilitychange', onVisibility);
379
+ window.addEventListener('pagehide', flushOnHide);
380
+ }
381
+
382
+ // Live sync with the other tabs of this document (P-94): the channel is closed with the editor
383
+ const syncHandle = available && sync ? startSync({
384
+ nabu, docId,
385
+ onError: (error) => warn(`persistence: could not apply a change from another tab of "${docId}": ${error}`),
386
+ }) : null;
387
+ state.sync = syncHandle !== null;
388
+
389
+ const stop = () => {
390
+ autosave.cancel();
391
+ unsubscribe();
392
+ syncHandle?.close();
393
+ if (syncHandle) state.sync = false;
394
+ Files.get(nabu).dispose();
395
+ if (listening) {
396
+ document.removeEventListener('visibilitychange', onVisibility);
397
+ window.removeEventListener('pagehide', flushOnHide);
398
+ }
399
+ };
400
+
401
+ /** @type {import('./compact.js').CompactContext} */
402
+ const ctx = {
403
+ nabu,
404
+ store,
405
+ compacting: false,
406
+ base: () => compactedAt,
407
+ isDirty: () => savedKey === null || versionKey(nabu.doc) !== savedKey,
408
+ flush: async () => { autosave.cancel(); await save(); },
409
+ lock,
410
+ versionKey,
411
+ candidates: async () => { await loadHeld(); return new Set([...Files.get(nabu).indexedHashes(), ...held]); },
412
+ held: () => new Set(held),
413
+ setHeld: (hashes) => { heldLoaded = true; held.clear(); for (const hash of hashes) held.add(hash); },
414
+ saveRefs,
415
+ commit: async (snapshot, frontiers, key) => {
416
+ // the compacted snapshot replaces the history: the backup (the complete history) must not outlive it
417
+ await saveSnapshot(docId, snapshot, { conn, rotate: false, dropBackup: true });
418
+ lastStored = { snapshot, savedAt: Date.now() };
419
+ savedVersion = undefined; // (unknown which changes came in meanwhile: the next tail is exported in full, or not at all)
420
+ compactedAt = frontiers;
421
+ savedKey = key;
422
+ requestedKey = key;
423
+ await saveRefs();
424
+ },
425
+ };
426
+
427
+ /** Force an immediate save of the current document state. @returns {Promise<void>} */
428
+ /** @type {any} */ (nabu).saveNow = async () => {
429
+ autosave.cancel();
430
+ await Files.get(nabu).whenIdle(); // files of a paste / import / migration in progress belong to this save
431
+ await save();
432
+ };
433
+
434
+ /**
435
+ * Explicit compaction (ADR 014 §3.6): drop the history older than `retain`, keep everything newer, release the files no
436
+ * kept version references. Never automatic. Save first (`await nabu.saveNow()`): unsaved changes make it refuse. Resolves with a
437
+ * {@link CompactResult} and never throws for a refusal (pending upload, unsaved changes, `onBeforeCompact` failing…): then
438
+ * NOTHING was dropped. See `runCompaction` for the safeguards, the undo stack is cleared on success, and the in-memory document
439
+ * keeps its history until the editor is opened again (the SAVED document is compacted at once).
440
+ * @param {CompactOptions} options
441
+ * @returns {Promise<CompactResult>}
442
+ */
443
+ /** @type {any} */ (nabu).compact = /** @param {CompactOptions} options */ (options) => {
444
+ if (available) return runCompaction(ctx, options);
445
+ parseHistory({ mode: 'compact', retain: options?.retain }); // an invalid configuration still throws
446
+ return Promise.resolve({ compacted: false, reason: /** @type {const} */ ('failed'), error: new Error('persistence is unavailable') });
447
+ };
448
+
449
+ /**
450
+ * Delete the persisted snapshot for this document (and its backup, and the records that were moved aside) and release its files:
451
+ * a file is deleted from the shared store only when no other document references it; with a host, `files.onAssetReleased(url)`
452
+ * is called for each hosted file (Nabu deletes nothing at the host).
453
+ * @returns {Promise<void>}
454
+ */
455
+ /** @type {any} */ (nabu).clearPersistence = async () => {
456
+ autosave.cancel();
457
+ if (!available) return; // nothing was ever read or written
458
+ const files = Files.get(nabu);
459
+ const reader = /** @type {any} */ (store);
460
+ const mine = new Set(files.indexedHashes());
461
+ if (typeof reader.getDocRefs === 'function') for (const hash of await reader.getDocRefs(docId)) mine.add(hash);
462
+ const urls = files.hostUrls(mine);
463
+ await deleteSnapshot(docId);
464
+ if (typeof reader.clearDocRefs === 'function') await reader.clearDocRefs(docId);
465
+ await outbox?.clear?.();
466
+ const { skipped } = await releaseFiles(nabu, store, mine, urls);
467
+ // too recent to delete (grace period): kept in this docId's `docRefs`, reconsidered when a document with this id is next compacted / cleared
468
+ held.clear();
469
+ for (const hash of skipped) held.add(hash);
470
+ heldLoaded = true;
471
+ if (skipped.length && typeof reader.setDocRefs === 'function') await reader.setDocRefs(docId, skipped);
472
+ lastStored = null; // the backup was deleted with the rest
473
+ savedVersion = undefined;
474
+ clearTail(docId);
475
+ clearRev(docId);
476
+ requestedKey = versionKey(nabu.doc); // what is in memory now is deliberately NOT stored: a page hide must not bring it back
477
+ if (state.status === 'pending') state.status = 'saved'; // the pending autosave was cancelled above: nothing is waiting
478
+ };
479
+
480
+ state.dispose = () => {
481
+ if (disposed) return;
482
+ disposed = true;
483
+ stop();
484
+ conn.close();
485
+ };
486
+
487
+ syncHandle?.hello(); // the peers send what this tab lacks (their unsaved changes)
488
+
489
+ return { ctx, dispose: stop, touch: () => { state.status = 'pending'; autosave.touch(); } };
74
490
  };
75
491
 
76
- /** Delete the persisted snapshot for this document. @returns {Promise<void>} */
77
- nabu.clearPersistence = () => deleteSnapshot(docId);
492
+ let nabu = decision.value ?? build(null);
493
+
494
+ // ── 3. the tail left by a page that went away before IndexedDB could be written (see tail.js) ──
495
+ /** What the stored record contains, to export the next tail from. @type {import('loro-crdt').VersionVector | undefined} */
496
+ let storedVersion = initialSnapshot ? nabu.doc.version() : undefined;
497
+ let restoredFromTail = false;
498
+ let tailApplied = false;
499
+ const tail = available ? readTail(docId) : null;
500
+ if (tail) {
501
+ if (decision.outcome === 'new') {
502
+ // nothing stored (the first session never reached IndexedDB): the tail IS the document, history included
503
+ try { nabu = build(tail); restoredFromTail = tailApplied = true; } catch { parkTail(docId); }
504
+ } else {
505
+ try {
506
+ const before = versionKey(nabu.doc);
507
+ const status = nabu.doc.import(tail);
508
+ if (status.pending && status.pending.size > 0) parkTail(docId); // it does not follow from what is stored: keep it aside
509
+ else tailApplied = versionKey(nabu.doc) !== before;
510
+ if (!tailApplied && !(status.pending && status.pending.size > 0)) clearTail(docId); // already in the snapshot
511
+ } catch { parkTail(docId); }
512
+ }
513
+ }
514
+
515
+ let wiring = attach(nabu, available && initialSnapshot ? { snapshot: initialSnapshot, savedAt: decision.used?.savedAt ?? Date.now() } : null, storedVersion, tailApplied);
516
+ /** @type {any} */ (nabu).persistence = state;
517
+
518
+ if (tailApplied && available) wiring.touch(); // the merged tail is not in IndexedDB yet
519
+
520
+ if (!available) {
521
+ warn(unavailableError
522
+ ? `persistence: IndexedDB is not available (${unavailableError}); "${docId}" works in memory only and will not be saved`
523
+ : `persistence: "${docId}" could not be moved aside safely (${quarantineError}); it works in memory only and will not be saved`);
524
+ }
525
+ if (recovery) {
526
+ warn(recovery.kind === 'backup'
527
+ ? `persistence: the saved document "${docId}" could not be read (${recovery.error.message}); restored from the previous save, the unreadable record is kept in the "quarantine" store (${recovery.quarantinedKey})`
528
+ : `persistence: the saved document "${docId}" could not be read (${recovery.error.message}) and no backup was usable; starting empty, the unreadable record is kept in the "quarantine" store (${recovery.quarantinedKey})`);
529
+ try { onRecover?.(recovery); } catch (error) { warn(`persistence: onRecover threw: ${error}`); }
530
+ }
531
+
532
+ // `history: { mode: 'compact' }`: compact when the document is opened (never mid-session), once it is loaded, migrated and its
533
+ // uploads reconciled. A refusal (pending upload, failing archive…) leaves the document exactly as it was.
534
+ if (historyConfig.mode === 'compact' && initialSnapshot && available) {
535
+ const { retain, onBeforeCompact } = historyConfig;
536
+ const result = await runCompaction(wiring.ctx, { retain, onBeforeCompact }, { flush: true });
537
+ if (result.compacted && result.snapshot) {
538
+ // Replace the instance nobody has seen yet by one built from the compacted snapshot: the history is gone from memory too.
539
+ wiring.dispose();
540
+ nabu = build(result.snapshot);
541
+ wiring = attach(nabu, { snapshot: result.snapshot, savedAt: Date.now() }, nabu.doc.version());
542
+ /** @type {any} */ (nabu).persistence = state;
543
+ } else if (result.reason !== 'nothing-to-compact') {
544
+ nabu.warn(`history: compaction at open skipped (${result.reason}), the document is unchanged`);
545
+ }
546
+ }
547
+
548
+ /** Whether this instance was created from a fresh document (no readable snapshot, no tail). */
549
+ /** @type {any} */ (nabu).isNew = !initialSnapshot && !restoredFromTail;
78
550
 
79
551
  return nabu;
80
552
  }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Decide how to open a document from what is stored: try the current snapshot, then the backup, else start empty. Pure: `load`
3
+ * does the actual (throwing) import, so this is testable without IndexedDB.
4
+ * A current record that is MISSING while a backup exists counts as a failure (an odd state: a partial deletion).
5
+ *
6
+ * @template T
7
+ * @param {{ current: StoredRecord | null, backup: StoredRecord | null }} records
8
+ * @param {(snapshot: unknown) => T} load throws when the snapshot cannot be used
9
+ * @returns {LoadDecision<T>}
10
+ */
11
+ export function resolveLoad<T>(records: {
12
+ current: StoredRecord | null;
13
+ backup: StoredRecord | null;
14
+ }, load: (snapshot: unknown) => T): LoadDecision<T>;
15
+ /**
16
+ * The {@link Recovery} to report for a decision, or `null` when nothing went wrong.
17
+ * @param {LoadDecision<unknown>} decision
18
+ * @param {string[]} quarantinedKeys keys of `decision.failed`, in the same order
19
+ * @param {number} at
20
+ * @returns {Recovery | null}
21
+ */
22
+ export function describeRecovery(decision: LoadDecision<unknown>, quarantinedKeys: string[], at: number): Recovery | null;
23
+ /**
24
+ * What happened when a stored document could not be read (ADR 010, theme 8). Exposed as
25
+ * `nabu.persistence.recovery` and given to the `onRecover` option, so the host can tell the user.
26
+ */
27
+ export type Recovery = {
28
+ /**
29
+ * `'backup'`: the document was restored from the PREVIOUS save (the last edits before the
30
+ * corrupted save are missing). `'empty'`: nothing readable was left, the editor started empty.
31
+ */
32
+ kind: "backup" | "empty";
33
+ /**
34
+ * why the latest stored snapshot was refused
35
+ */
36
+ error: Error;
37
+ /**
38
+ * key (in the `quarantine` object store of the `nabu` database) of the unreadable record,
39
+ * which is never deleted. `null` if there was nothing to move (a missing record)
40
+ */
41
+ quarantinedKey: string | null;
42
+ /**
43
+ * every record moved aside (the backup too, when it was unreadable as well)
44
+ */
45
+ quarantinedKeys: string[];
46
+ /**
47
+ * epoch ms
48
+ */
49
+ at: number;
50
+ };
51
+ export type StoredRecord = {
52
+ docId: string;
53
+ snapshot: unknown;
54
+ savedAt?: number;
55
+ };
56
+ export type LoadDecision<T> = {
57
+ /**
58
+ * `new`: nothing stored. `ok`: the current snapshot loaded. `backup`: it did not, the
59
+ * backup did. `empty`: neither did.
60
+ */
61
+ outcome: "new" | "ok" | "backup" | "empty";
62
+ /**
63
+ * what `load` returned for the record that was used (`null` for `new` and `empty`)
64
+ */
65
+ value: T | null;
66
+ /**
67
+ * the record that was loaded
68
+ */
69
+ used: StoredRecord | null;
70
+ /**
71
+ * the records that could not be read
72
+ * (to be quarantined, in the order they were tried)
73
+ */
74
+ failed: {
75
+ source: "snapshot" | "backup";
76
+ record: StoredRecord;
77
+ error: Error;
78
+ }[];
79
+ };