@aionbuilders/nabu 0.1.0-beta.0 → 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.
- package/CHANGELOG.md +523 -0
- package/LICENSE +21 -0
- package/README.md +72 -341
- package/dist/behaviors/text/RichText.svelte +24 -4
- package/dist/behaviors/text/markdown-shortcuts.extension.d.ts +3 -0
- package/dist/behaviors/text/markdown-shortcuts.extension.js +35 -10
- package/dist/behaviors/text/markdown-syntax.d.ts +42 -0
- package/dist/behaviors/text/markdown-syntax.js +81 -0
- package/dist/behaviors/text/rich-text.extension.d.ts +3 -0
- package/dist/behaviors/text/rich-text.extension.js +95 -38
- package/dist/behaviors/text/text.behavior.svelte.d.ts +199 -48
- package/dist/behaviors/text/text.behavior.svelte.js +549 -83
- package/dist/behaviors/text/typography.extension.d.ts +2 -1
- package/dist/behaviors/text/typography.extension.js +3 -2
- package/dist/blocks/BlockList.svelte +48 -0
- package/dist/blocks/BlockList.svelte.d.ts +17 -0
- package/dist/blocks/Nabu.svelte +169 -25
- package/dist/blocks/Nabu.svelte.d.ts +13 -0
- package/dist/blocks/block.extension.d.ts +3 -0
- package/dist/blocks/block.extension.js +4 -7
- package/dist/blocks/block.svelte.d.ts +350 -86
- package/dist/blocks/block.svelte.js +370 -59
- package/dist/blocks/blockquote/Blockquote.svelte +1 -2
- package/dist/blocks/blockquote/blockquote.extension.d.ts +4 -1
- package/dist/blocks/blockquote/blockquote.extension.js +14 -5
- package/dist/blocks/blockquote/blockquote.svelte.d.ts +19 -11
- package/dist/blocks/blockquote/blockquote.svelte.js +58 -13
- package/dist/blocks/callout/Callout.svelte +6 -8
- package/dist/blocks/callout/callout.extension.d.ts +4 -1
- package/dist/blocks/callout/callout.extension.js +19 -3
- package/dist/blocks/callout/callout.svelte.d.ts +5 -3
- package/dist/blocks/callout/callout.svelte.js +11 -6
- package/dist/blocks/chunks.d.ts +49 -0
- package/dist/blocks/chunks.js +90 -0
- package/dist/blocks/code/Code.svelte +7 -8
- package/dist/blocks/code/code.extension.d.ts +4 -1
- package/dist/blocks/code/code.extension.js +22 -2
- package/dist/blocks/code/code.svelte.d.ts +9 -2
- package/dist/blocks/code/code.svelte.js +49 -25
- package/dist/blocks/container.utils.d.ts +85 -13
- package/dist/blocks/container.utils.js +338 -178
- package/dist/blocks/dialogue/Dialogue.svelte +8 -4
- package/dist/blocks/dialogue/dialogue.svelte.d.ts +33 -2
- package/dist/blocks/dialogue/dialogue.svelte.js +58 -4
- package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +2 -2
- package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +6 -4
- package/dist/blocks/dialogue/index.d.ts +12 -1
- package/dist/blocks/dialogue/index.js +51 -35
- package/dist/blocks/divider/divider.extension.d.ts +23 -1
- package/dist/blocks/divider/divider.extension.js +85 -19
- package/dist/blocks/divider/divider.svelte.d.ts +7 -2
- package/dist/blocks/divider/divider.svelte.js +9 -4
- package/dist/blocks/file/File.svelte +13 -6
- package/dist/blocks/file/file.extension.d.ts +4 -1
- package/dist/blocks/file/file.extension.js +9 -1
- package/dist/blocks/file/file.svelte.d.ts +3 -3
- package/dist/blocks/file/file.svelte.js +20 -14
- package/dist/blocks/heading/Heading.svelte +1 -2
- package/dist/blocks/heading/heading.svelte.d.ts +23 -11
- package/dist/blocks/heading/heading.svelte.js +68 -13
- package/dist/blocks/heading/hooks/onBeforeInput.hook.js +7 -5
- package/dist/blocks/heading/index.d.ts +2 -2
- package/dist/blocks/heading/index.js +33 -8
- package/dist/blocks/image/Image.svelte +5 -2
- package/dist/blocks/image/image.extension.d.ts +4 -1
- package/dist/blocks/image/image.extension.js +9 -1
- package/dist/blocks/image/image.svelte.d.ts +17 -6
- package/dist/blocks/image/image.svelte.js +33 -11
- package/dist/blocks/index.d.ts +1 -1
- package/dist/blocks/index.js +1 -1
- package/dist/blocks/list/List.svelte +1 -0
- package/dist/blocks/list/ListItem.svelte +1 -0
- package/dist/blocks/list/convert.d.ts +20 -0
- package/dist/blocks/list/convert.js +92 -0
- package/dist/blocks/list/hooks/onBeforeInput.hook.js +49 -28
- package/dist/blocks/list/html-flat.d.ts +78 -0
- package/dist/blocks/list/html-flat.js +244 -0
- package/dist/blocks/list/indent.d.ts +86 -0
- package/dist/blocks/list/indent.js +205 -0
- package/dist/blocks/list/index.d.ts +6 -3
- package/dist/blocks/list/index.js +42 -31
- package/dist/blocks/list/list-item.svelte.d.ts +31 -17
- package/dist/blocks/list/list-item.svelte.js +99 -100
- package/dist/blocks/list/list.behavior.svelte.d.ts +4 -1
- package/dist/blocks/list/list.behavior.svelte.js +6 -1
- package/dist/blocks/list/list.svelte.d.ts +89 -18
- package/dist/blocks/list/list.svelte.js +129 -125
- package/dist/blocks/list/markdown.d.ts +149 -0
- package/dist/blocks/list/markdown.js +442 -0
- package/dist/blocks/list/normalize.d.ts +11 -0
- package/dist/blocks/list/normalize.js +396 -0
- package/dist/blocks/list/paste.d.ts +45 -0
- package/dist/blocks/list/paste.js +242 -0
- package/dist/blocks/list/step-back.d.ts +24 -0
- package/dist/blocks/list/step-back.js +87 -0
- package/dist/blocks/list/to-list.d.ts +7 -0
- package/dist/blocks/list/to-list.js +44 -0
- package/dist/blocks/list/todos-toggle.d.ts +20 -0
- package/dist/blocks/list/todos-toggle.js +48 -0
- package/dist/blocks/media/markdown.d.ts +12 -0
- package/dist/blocks/media/markdown.js +26 -0
- package/dist/blocks/media/media-block.svelte.d.ts +77 -2
- package/dist/blocks/media/media-block.svelte.js +124 -12
- package/dist/blocks/media/media.helpers.d.ts +6 -1
- package/dist/blocks/media/media.helpers.js +43 -6
- package/dist/blocks/megablock.svelte.d.ts +50 -19
- package/dist/blocks/megablock.svelte.js +114 -74
- package/dist/blocks/move.d.ts +23 -0
- package/dist/blocks/move.js +92 -0
- package/dist/blocks/nabu.svelte.d.ts +764 -71
- package/dist/blocks/nabu.svelte.js +1746 -189
- package/dist/blocks/paragraph/Paragraph.svelte +1 -2
- package/dist/blocks/paragraph/index.d.ts +2 -2
- package/dist/blocks/paragraph/index.js +35 -13
- package/dist/blocks/paragraph/paragraph.svelte.d.ts +46 -14
- package/dist/blocks/paragraph/paragraph.svelte.js +77 -16
- package/dist/blocks/paragraph/table.html.d.ts +9 -0
- package/dist/blocks/paragraph/table.html.js +111 -0
- package/dist/blocks/paragraph/table.markdown.d.ts +32 -0
- package/dist/blocks/paragraph/table.markdown.js +90 -0
- package/dist/blocks/region/Region.svelte +264 -0
- package/dist/blocks/region/Region.svelte.d.ts +11 -0
- package/dist/blocks/region/actions.d.ts +135 -0
- package/dist/blocks/region/actions.js +402 -0
- package/dist/blocks/region/close.d.ts +35 -0
- package/dist/blocks/region/close.js +130 -0
- package/dist/blocks/region/commands.d.ts +6 -0
- package/dist/blocks/region/commands.js +277 -0
- package/dist/blocks/region/create.d.ts +72 -0
- package/dist/blocks/region/create.js +208 -0
- package/dist/blocks/region/end-marker.d.ts +35 -0
- package/dist/blocks/region/end-marker.js +51 -0
- package/dist/blocks/region/facts.d.ts +69 -0
- package/dist/blocks/region/facts.js +152 -0
- package/dist/blocks/region/format.d.ts +91 -0
- package/dist/blocks/region/format.js +260 -0
- package/dist/blocks/region/index.d.ts +14 -0
- package/dist/blocks/region/index.js +14 -0
- package/dist/blocks/region/insert.d.ts +59 -0
- package/dist/blocks/region/insert.js +102 -0
- package/dist/blocks/region/messages.d.ts +254 -0
- package/dist/blocks/region/messages.js +131 -0
- package/dist/blocks/region/normalize.d.ts +7 -0
- package/dist/blocks/region/normalize.js +170 -0
- package/dist/blocks/region/region.extension.d.ts +58 -0
- package/dist/blocks/region/region.extension.js +119 -0
- package/dist/blocks/region/region.svelte.d.ts +221 -0
- package/dist/blocks/region/region.svelte.js +582 -0
- package/dist/blocks/region/regions.svelte.d.ts +141 -0
- package/dist/blocks/region/regions.svelte.js +276 -0
- package/dist/blocks/region/serialize.d.ts +57 -0
- package/dist/blocks/region/serialize.js +112 -0
- package/dist/blocks/region/types.d.ts +255 -0
- package/dist/blocks/region/types.js +204 -0
- package/dist/blocks/selection.svelte.d.ts +106 -8
- package/dist/blocks/selection.svelte.js +622 -74
- package/dist/blocks/subthread.d.ts +80 -0
- package/dist/blocks/subthread.js +167 -0
- package/dist/blocks/text-block.svelte.d.ts +34 -13
- package/dist/blocks/text-block.svelte.js +42 -8
- package/dist/blocks/toggle/Toggle.svelte +4 -15
- package/dist/blocks/toggle/markdown.d.ts +20 -0
- package/dist/blocks/toggle/markdown.js +112 -0
- package/dist/blocks/toggle/toggle.extension.d.ts +4 -1
- package/dist/blocks/toggle/toggle.extension.js +6 -0
- package/dist/blocks/toggle/toggle.svelte.d.ts +54 -7
- package/dist/blocks/toggle/toggle.svelte.js +134 -34
- package/dist/blocks/undo-selection.d.ts +175 -0
- package/dist/blocks/undo-selection.js +360 -0
- package/dist/blocks/video/Video.svelte +5 -2
- package/dist/blocks/video/video.extension.d.ts +4 -1
- package/dist/blocks/video/video.extension.js +9 -1
- package/dist/blocks/video/video.svelte.d.ts +6 -5
- package/dist/blocks/video/video.svelte.js +18 -9
- package/dist/extend.d.ts +55 -0
- package/dist/extend.js +88 -0
- package/dist/files/assets.clipboard.d.ts +77 -0
- package/dist/files/assets.clipboard.js +152 -0
- package/dist/files/files.svelte.d.ts +321 -19
- package/dist/files/files.svelte.js +847 -43
- package/dist/files/index.d.ts +3 -1
- package/dist/files/index.js +3 -1
- package/dist/files/outbox.d.ts +69 -0
- package/dist/files/outbox.js +48 -0
- package/dist/files/status.d.ts +65 -0
- package/dist/files/status.js +87 -0
- package/dist/files/store.d.ts +97 -0
- package/dist/files/store.js +65 -0
- package/dist/files/uploads.svelte.d.ts +174 -0
- package/dist/files/uploads.svelte.js +504 -0
- package/dist/index.d.ts +68 -9
- package/dist/index.js +117 -10
- package/dist/nabu-theme.css +21 -1
- package/dist/paste/html.paste.d.ts +74 -3
- package/dist/paste/html.paste.js +550 -86
- package/dist/paste/markdown-inline.d.ts +86 -0
- package/dist/paste/markdown-inline.js +528 -0
- package/dist/paste/markdown.paste.d.ts +2 -8
- package/dist/paste/markdown.paste.js +78 -94
- package/dist/paste/nabu.paste.d.ts +3 -0
- package/dist/paste/nabu.paste.js +29 -3
- package/dist/paste/plain-text.paste.d.ts +2 -2
- package/dist/paste/plain-text.paste.js +3 -3
- package/dist/persistence/asset-store.d.ts +51 -0
- package/dist/persistence/asset-store.js +103 -0
- package/dist/persistence/autosave.d.ts +53 -0
- package/dist/persistence/autosave.js +62 -0
- package/dist/persistence/compact.d.ts +162 -0
- package/dist/persistence/compact.js +141 -0
- package/dist/persistence/history.d.ts +77 -0
- package/dist/persistence/history.js +176 -0
- package/dist/persistence/indexeddb.d.ts +190 -4
- package/dist/persistence/indexeddb.js +333 -29
- package/dist/persistence/merge.d.ts +38 -0
- package/dist/persistence/merge.js +36 -0
- package/dist/persistence/outbox.d.ts +25 -0
- package/dist/persistence/outbox.js +40 -0
- package/dist/persistence/persistence.d.ts +70 -9
- package/dist/persistence/persistence.js +507 -35
- package/dist/persistence/recovery.d.ts +79 -0
- package/dist/persistence/recovery.js +79 -0
- package/dist/persistence/release.d.ts +34 -0
- package/dist/persistence/release.js +64 -0
- package/dist/persistence/state.svelte.d.ts +53 -0
- package/dist/persistence/state.svelte.js +48 -0
- package/dist/persistence/sync.d.ts +39 -0
- package/dist/persistence/sync.js +138 -0
- package/dist/persistence/tail.d.ts +42 -0
- package/dist/persistence/tail.js +103 -0
- package/dist/presets.d.ts +29 -26
- package/dist/presets.js +35 -13
- package/dist/themes/atelier.css +318 -0
- package/dist/ui/CommandChooser.svelte +153 -0
- package/dist/ui/CommandChooser.svelte.d.ts +13 -0
- package/dist/ui/CommandInvite.svelte +99 -0
- package/dist/ui/CommandInvite.svelte.d.ts +12 -0
- package/dist/ui/DragHandle.svelte +97 -21
- package/dist/ui/FloatingToolbar.svelte +75 -27
- package/dist/ui/FloatingToolbar.svelte.d.ts +10 -0
- package/dist/ui/SlashMenu.svelte +147 -15
- package/dist/ui/SlashMenu.svelte.d.ts +20 -0
- package/dist/ui/anchor.d.ts +112 -0
- package/dist/ui/anchor.js +136 -0
- package/dist/ui/index.d.ts +7 -1
- package/dist/ui/index.js +12 -1
- package/dist/ui/slash-menu.svelte.d.ts +79 -7
- package/dist/ui/slash-menu.svelte.js +85 -51
- package/dist/utils/command-confirm.svelte.d.ts +349 -0
- package/dist/utils/command-confirm.svelte.js +673 -0
- package/dist/utils/commands.d.ts +328 -0
- package/dist/utils/commands.js +416 -0
- package/dist/utils/dom-scope.d.ts +14 -0
- package/dist/utils/dom-scope.js +20 -0
- package/dist/utils/drop.d.ts +160 -0
- package/dist/utils/drop.js +305 -0
- package/dist/utils/extensions.d.ts +439 -45
- package/dist/utils/extensions.js +271 -29
- package/dist/utils/html.d.ts +44 -0
- package/dist/utils/html.js +183 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +3 -0
- package/dist/utils/keys.d.ts +120 -0
- package/dist/utils/keys.js +248 -0
- package/dist/utils/links.d.ts +22 -0
- package/dist/utils/links.js +34 -0
- package/dist/utils/placeholders.d.ts +81 -3
- package/dist/utils/placeholders.js +73 -3
- package/dist/utils/selection.svelte.d.ts +47 -19
- package/dist/utils/selection.svelte.js +60 -10
- package/dist/utils/spellcheck.d.ts +9 -0
- package/dist/utils/spellcheck.js +17 -0
- package/dist/utils/tab.d.ts +31 -0
- package/dist/utils/tab.js +117 -0
- package/dist/utils/words.d.ts +7 -0
- package/dist/utils/words.js +62 -0
- package/dist/vite.d.ts +9 -3
- package/dist/vite.js +19 -8
- package/package.json +54 -20
- package/dist/blocks/variable.svelte.d.ts +0 -47
- package/dist/blocks/variable.svelte.js +0 -51
- package/dist/blocks/zone/TemplateEditor.svelte +0 -308
- package/dist/blocks/zone/TemplateEditor.svelte.d.ts +0 -11
- package/dist/blocks/zone/Zone.svelte +0 -272
- package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
- package/dist/blocks/zone/ZoneEditor.svelte +0 -289
- package/dist/blocks/zone/ZoneEditor.svelte.d.ts +0 -11
- package/dist/blocks/zone/ZoneTemplatesList.svelte +0 -188
- package/dist/blocks/zone/ZoneTemplatesList.svelte.d.ts +0 -11
- package/dist/blocks/zone/hooks/onBeforeInput.hook.d.ts +0 -3
- package/dist/blocks/zone/hooks/onBeforeInput.hook.js +0 -30
- package/dist/blocks/zone/index.d.ts +0 -2
- package/dist/blocks/zone/index.js +0 -2
- package/dist/blocks/zone/zone.extension.d.ts +0 -2
- package/dist/blocks/zone/zone.extension.js +0 -237
- package/dist/blocks/zone/zone.svelte.d.ts +0 -221
- package/dist/blocks/zone/zone.svelte.js +0 -608
- package/dist/overlays/context/Context.svelte +0 -182
- package/dist/overlays/context/Context.svelte.d.ts +0 -17
- package/dist/overlays/context/collect.d.ts +0 -17
- package/dist/overlays/context/collect.js +0 -33
- package/dist/overlays/context/context.extension.d.ts +0 -2
- package/dist/overlays/context/context.extension.js +0 -8
- package/dist/overlays/context/context.svelte.d.ts +0 -82
- package/dist/overlays/context/context.svelte.js +0 -159
- package/dist/overlays/context/index.d.ts +0 -3
- package/dist/overlays/context/index.js +0 -3
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {object} Recovery What happened when a stored document could not be read (ADR 010, theme 8). Exposed as
|
|
3
|
+
* `nabu.persistence.recovery` and given to the `onRecover` option, so the host can tell the user.
|
|
4
|
+
* @property {'backup' | 'empty'} kind `'backup'`: the document was restored from the PREVIOUS save (the last edits before the
|
|
5
|
+
* corrupted save are missing). `'empty'`: nothing readable was left, the editor started empty.
|
|
6
|
+
* @property {Error} error why the latest stored snapshot was refused
|
|
7
|
+
* @property {string | null} quarantinedKey key (in the `quarantine` object store of the `nabu` database) of the unreadable record,
|
|
8
|
+
* which is never deleted. `null` if there was nothing to move (a missing record)
|
|
9
|
+
* @property {string[]} quarantinedKeys every record moved aside (the backup too, when it was unreadable as well)
|
|
10
|
+
* @property {number} at epoch ms
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** @typedef {{ docId: string, snapshot: unknown, savedAt?: number }} StoredRecord */
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @template T
|
|
17
|
+
* @typedef {object} LoadDecision
|
|
18
|
+
* @property {'new' | 'ok' | 'backup' | 'empty'} outcome `new`: nothing stored. `ok`: the current snapshot loaded. `backup`: it did not, the
|
|
19
|
+
* backup did. `empty`: neither did.
|
|
20
|
+
* @property {T | null} value what `load` returned for the record that was used (`null` for `new` and `empty`)
|
|
21
|
+
* @property {StoredRecord | null} used the record that was loaded
|
|
22
|
+
* @property {{ source: 'snapshot' | 'backup', record: StoredRecord, error: Error }[]} failed the records that could not be read
|
|
23
|
+
* (to be quarantined, in the order they were tried)
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** @param {unknown} error @returns {Error} */
|
|
27
|
+
const asError = (error) => (error instanceof Error ? error : new Error(String(error)));
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Decide how to open a document from what is stored: try the current snapshot, then the backup, else start empty. Pure: `load`
|
|
31
|
+
* does the actual (throwing) import, so this is testable without IndexedDB.
|
|
32
|
+
* A current record that is MISSING while a backup exists counts as a failure (an odd state: a partial deletion).
|
|
33
|
+
*
|
|
34
|
+
* @template T
|
|
35
|
+
* @param {{ current: StoredRecord | null, backup: StoredRecord | null }} records
|
|
36
|
+
* @param {(snapshot: unknown) => T} load throws when the snapshot cannot be used
|
|
37
|
+
* @returns {LoadDecision<T>}
|
|
38
|
+
*/
|
|
39
|
+
export function resolveLoad(records, load) {
|
|
40
|
+
const { current, backup } = records;
|
|
41
|
+
/** @type {LoadDecision<T>['failed']} */
|
|
42
|
+
const failed = [];
|
|
43
|
+
if (!current && !backup) return { outcome: 'new', value: null, used: null, failed };
|
|
44
|
+
if (current) {
|
|
45
|
+
try {
|
|
46
|
+
return { outcome: 'ok', value: load(current.snapshot), used: current, failed };
|
|
47
|
+
} catch (error) {
|
|
48
|
+
failed.push({ source: 'snapshot', record: current, error: asError(error) });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (backup) {
|
|
52
|
+
try {
|
|
53
|
+
return { outcome: 'backup', value: load(backup.snapshot), used: backup, failed };
|
|
54
|
+
} catch (error) {
|
|
55
|
+
failed.push({ source: 'backup', record: backup, error: asError(error) });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return { outcome: 'empty', value: null, used: null, failed };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The {@link Recovery} to report for a decision, or `null` when nothing went wrong.
|
|
63
|
+
* @param {LoadDecision<unknown>} decision
|
|
64
|
+
* @param {string[]} quarantinedKeys keys of `decision.failed`, in the same order
|
|
65
|
+
* @param {number} at
|
|
66
|
+
* @returns {Recovery | null}
|
|
67
|
+
*/
|
|
68
|
+
export function describeRecovery(decision, quarantinedKeys, at) {
|
|
69
|
+
if (decision.outcome !== 'backup' && decision.outcome !== 'empty') return null;
|
|
70
|
+
const first = decision.failed[0];
|
|
71
|
+
const main = decision.failed.findIndex((f) => f.source === 'snapshot');
|
|
72
|
+
return {
|
|
73
|
+
kind: decision.outcome,
|
|
74
|
+
error: first?.error ?? new Error('the stored snapshot is missing'),
|
|
75
|
+
quarantinedKey: main >= 0 ? quarantinedKeys[main] ?? null : null,
|
|
76
|
+
quarantinedKeys: [...quarantinedKeys],
|
|
77
|
+
at,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** @import { Nabu } from '../blocks/nabu.svelte.js' */
|
|
2
|
+
/** @import { AssetStore } from '../files/store.js' */
|
|
3
|
+
/**
|
|
4
|
+
* Let go of files THIS document no longer keeps (ADR 014 §3.6 point 6), after the document that referenced them was
|
|
5
|
+
* compacted or deleted:
|
|
6
|
+
*
|
|
7
|
+
* - the document's `docRefs` must already be updated by the caller;
|
|
8
|
+
* - bytes: a file is deleted from the (shared) store only when NO document's `docRefs` lists it. A store without the `docRefs`
|
|
9
|
+
* API (a custom `files.store`) cannot tell, so nothing is deleted from it;
|
|
10
|
+
* - grace: a file whose store record is newer than `files.releaseGraceMs` (default {@link DEFAULT_RELEASE_GRACE_MS}), or has no
|
|
11
|
+
* `savedAt` (legacy / a store that cannot say), is SKIPPED, not deleted (multi-tab safety). `releaseGraceMs: 0` disables it;
|
|
12
|
+
* - host mode: Nabu never deletes anything at the host. `files.onAssetReleased(url)` is called, awaited, for each released file
|
|
13
|
+
* that has a host `url`; an error is swallowed and reported with `nabu.warn`.
|
|
14
|
+
*
|
|
15
|
+
* Never throws.
|
|
16
|
+
* @param {Nabu} nabu
|
|
17
|
+
* @param {AssetStore} store
|
|
18
|
+
* @param {Iterable<string>} hashes the released files
|
|
19
|
+
* @param {Map<string, string>} urls host location of the released files that have one (read from the index BEFORE its entries were removed)
|
|
20
|
+
* @returns {Promise<{ deleted: string[], skipped: string[] }>} the files whose bytes were deleted from the store, and the ones
|
|
21
|
+
* nobody references but that were kept for now (grace period): the caller keeps them in the document's `docRefs` to reconsider them later
|
|
22
|
+
*/
|
|
23
|
+
export function releaseFiles(nabu: Nabu, store: AssetStore, hashes: Iterable<string>, urls: Map<string, string>): Promise<{
|
|
24
|
+
deleted: string[];
|
|
25
|
+
skipped: string[];
|
|
26
|
+
}>;
|
|
27
|
+
/**
|
|
28
|
+
* Default `files.releaseGraceMs`: a file whose store record is newer than this is never deleted by a release, whoever released it
|
|
29
|
+
* (10 minutes). Another tab may have just added it (or just re-added a file that was already stored) without having saved its
|
|
30
|
+
* `docRefs` yet; the file is skipped this time and reconsidered by the next compaction / `clearPersistence()` of the document.
|
|
31
|
+
*/
|
|
32
|
+
export const DEFAULT_RELEASE_GRACE_MS: number;
|
|
33
|
+
import type { Nabu } from '../blocks/nabu.svelte.js';
|
|
34
|
+
import type { AssetStore } from '../files/store.js';
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default `files.releaseGraceMs`: a file whose store record is newer than this is never deleted by a release, whoever released it
|
|
3
|
+
* (10 minutes). Another tab may have just added it (or just re-added a file that was already stored) without having saved its
|
|
4
|
+
* `docRefs` yet; the file is skipped this time and reconsidered by the next compaction / `clearPersistence()` of the document.
|
|
5
|
+
*/
|
|
6
|
+
export const DEFAULT_RELEASE_GRACE_MS = 10 * 60 * 1000;
|
|
7
|
+
|
|
8
|
+
/** @import { Nabu } from '../blocks/nabu.svelte.js' */
|
|
9
|
+
/** @import { AssetStore } from '../files/store.js' */
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Let go of files THIS document no longer keeps (ADR 014 §3.6 point 6), after the document that referenced them was
|
|
13
|
+
* compacted or deleted:
|
|
14
|
+
*
|
|
15
|
+
* - the document's `docRefs` must already be updated by the caller;
|
|
16
|
+
* - bytes: a file is deleted from the (shared) store only when NO document's `docRefs` lists it. A store without the `docRefs`
|
|
17
|
+
* API (a custom `files.store`) cannot tell, so nothing is deleted from it;
|
|
18
|
+
* - grace: a file whose store record is newer than `files.releaseGraceMs` (default {@link DEFAULT_RELEASE_GRACE_MS}), or has no
|
|
19
|
+
* `savedAt` (legacy / a store that cannot say), is SKIPPED, not deleted (multi-tab safety). `releaseGraceMs: 0` disables it;
|
|
20
|
+
* - host mode: Nabu never deletes anything at the host. `files.onAssetReleased(url)` is called, awaited, for each released file
|
|
21
|
+
* that has a host `url`; an error is swallowed and reported with `nabu.warn`.
|
|
22
|
+
*
|
|
23
|
+
* Never throws.
|
|
24
|
+
* @param {Nabu} nabu
|
|
25
|
+
* @param {AssetStore} store
|
|
26
|
+
* @param {Iterable<string>} hashes the released files
|
|
27
|
+
* @param {Map<string, string>} urls host location of the released files that have one (read from the index BEFORE its entries were removed)
|
|
28
|
+
* @returns {Promise<{ deleted: string[], skipped: string[] }>} the files whose bytes were deleted from the store, and the ones
|
|
29
|
+
* nobody references but that were kept for now (grace period): the caller keeps them in the document's `docRefs` to reconsider them later
|
|
30
|
+
*/
|
|
31
|
+
export async function releaseFiles(nabu, store, hashes, urls) {
|
|
32
|
+
/** @type {string[]} */
|
|
33
|
+
const deleted = [];
|
|
34
|
+
/** @type {string[]} */
|
|
35
|
+
const skipped = [];
|
|
36
|
+
const configured = nabu.fileConfig?.releaseGraceMs;
|
|
37
|
+
const grace = typeof configured === 'number' && configured >= 0 ? configured : DEFAULT_RELEASE_GRACE_MS;
|
|
38
|
+
const released = [...hashes];
|
|
39
|
+
if (released.length && typeof store.referencedHashes === 'function') {
|
|
40
|
+
try {
|
|
41
|
+
const stillUsed = await store.referencedHashes();
|
|
42
|
+
for (const hash of released) {
|
|
43
|
+
if (stillUsed.has(hash)) continue;
|
|
44
|
+
if (grace > 0) {
|
|
45
|
+
const savedAt = typeof store.savedAt === 'function' ? await store.savedAt(hash) : null;
|
|
46
|
+
if (typeof savedAt !== 'number' || Date.now() - savedAt < grace) { if (await store.has(hash)) skipped.push(hash); continue; }
|
|
47
|
+
}
|
|
48
|
+
await store.delete(hash);
|
|
49
|
+
deleted.push(hash);
|
|
50
|
+
}
|
|
51
|
+
} catch (error) {
|
|
52
|
+
nabu.warn(`history: could not clean the file store: ${error}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const onReleased = nabu.fileConfig?.onAssetReleased;
|
|
56
|
+
if (typeof onReleased === 'function') {
|
|
57
|
+
for (const hash of released) {
|
|
58
|
+
const url = urls.get(hash);
|
|
59
|
+
if (!url) continue;
|
|
60
|
+
try { await onReleased(url); } catch (error) { nabu.warn(`files: onAssetReleased failed for ${url}: ${error}`); }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return { deleted, skipped };
|
|
64
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {'saved' | 'pending' | 'saving' | 'error' | 'unavailable'} SaveStatus
|
|
3
|
+
* - `saved`: everything is stored (also a document just opened, or fresh and untouched)
|
|
4
|
+
* - `pending`: there are changes that are not stored yet (the autosave is waiting)
|
|
5
|
+
* - `saving`: a save is running
|
|
6
|
+
* - `error`: the last save failed (quota…); the changes are still in memory and the next change retries
|
|
7
|
+
* - `unavailable`: IndexedDB cannot be used (or the stored document could not be moved aside safely): the editor works in memory only
|
|
8
|
+
*/
|
|
9
|
+
/** @import { Recovery } from './recovery.js' */
|
|
10
|
+
/**
|
|
11
|
+
* `nabu.persistence` — what a persisted editor tells the host. The fields are REACTIVE (Svelte 5 `$state`): read them in a
|
|
12
|
+
* template or an `$effect` to show a "saved / saving…" indicator. Outside Svelte they are plain properties.
|
|
13
|
+
*/
|
|
14
|
+
export class PersistenceState {
|
|
15
|
+
/** @param {string} docId */
|
|
16
|
+
constructor(docId: string);
|
|
17
|
+
/** Where the document is stored. */
|
|
18
|
+
docId: string;
|
|
19
|
+
/** `false` when IndexedDB could not be used at boot: the editor works in memory only (status `'unavailable'`). */
|
|
20
|
+
available: boolean;
|
|
21
|
+
/** @type {SaveStatus} */
|
|
22
|
+
status: SaveStatus;
|
|
23
|
+
/** Epoch ms of the last successful save of this session (`null`: none yet). @type {number | null} */
|
|
24
|
+
lastSavedAt: number | null;
|
|
25
|
+
/** The error of the last failed save, or why storage is unavailable (`null` after a successful save). @type {unknown} */
|
|
26
|
+
lastError: unknown;
|
|
27
|
+
/**
|
|
28
|
+
* Set at boot when the stored document could not be read and the editor started from the backup or empty (see
|
|
29
|
+
* {@link Recovery}); `null` otherwise. Not reactive in practice (it is set before the editor is returned). @type {Recovery | null}
|
|
30
|
+
*/
|
|
31
|
+
recovery: Recovery | null;
|
|
32
|
+
/**
|
|
33
|
+
* `true` while the live sync with the other tabs of the same document is running (`sync` option, a `BroadcastChannel` is available,
|
|
34
|
+
* IndexedDB is usable). Saving still merges what other tabs stored when it is `false`.
|
|
35
|
+
*/
|
|
36
|
+
sync: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Stop the persistence of this editor: cancel the pending autosave, remove the `visibilitychange` / `pagehide` listeners, close the
|
|
39
|
+
* live-sync channel, stop the automatic upload retries and close the IndexedDB connection. The editor keeps working in memory, nothing is saved any more. Call it when the editor is
|
|
40
|
+
* destroyed (e.g. in the cleanup of the component that created it). Idempotent. Replaced by `createPersistedEditor`.
|
|
41
|
+
* @returns {void}
|
|
42
|
+
*/
|
|
43
|
+
dispose(): void;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* - `saved`: everything is stored (also a document just opened, or fresh and untouched)
|
|
47
|
+
* - `pending`: there are changes that are not stored yet (the autosave is waiting)
|
|
48
|
+
* - `saving`: a save is running
|
|
49
|
+
* - `error`: the last save failed (quota…); the changes are still in memory and the next change retries
|
|
50
|
+
* - `unavailable`: IndexedDB cannot be used (or the stored document could not be moved aside safely): the editor works in memory only
|
|
51
|
+
*/
|
|
52
|
+
export type SaveStatus = "saved" | "pending" | "saving" | "error" | "unavailable";
|
|
53
|
+
import type { Recovery } from './recovery.js';
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {'saved' | 'pending' | 'saving' | 'error' | 'unavailable'} SaveStatus
|
|
3
|
+
* - `saved`: everything is stored (also a document just opened, or fresh and untouched)
|
|
4
|
+
* - `pending`: there are changes that are not stored yet (the autosave is waiting)
|
|
5
|
+
* - `saving`: a save is running
|
|
6
|
+
* - `error`: the last save failed (quota…); the changes are still in memory and the next change retries
|
|
7
|
+
* - `unavailable`: IndexedDB cannot be used (or the stored document could not be moved aside safely): the editor works in memory only
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** @import { Recovery } from './recovery.js' */
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* `nabu.persistence` — what a persisted editor tells the host. The fields are REACTIVE (Svelte 5 `$state`): read them in a
|
|
14
|
+
* template or an `$effect` to show a "saved / saving…" indicator. Outside Svelte they are plain properties.
|
|
15
|
+
*/
|
|
16
|
+
export class PersistenceState {
|
|
17
|
+
/** Where the document is stored. */
|
|
18
|
+
docId = '';
|
|
19
|
+
/** `false` when IndexedDB could not be used at boot: the editor works in memory only (status `'unavailable'`). */
|
|
20
|
+
available = $state(true);
|
|
21
|
+
/** @type {SaveStatus} */
|
|
22
|
+
status = $state('saved');
|
|
23
|
+
/** Epoch ms of the last successful save of this session (`null`: none yet). @type {number | null} */
|
|
24
|
+
lastSavedAt = $state(null);
|
|
25
|
+
/** The error of the last failed save, or why storage is unavailable (`null` after a successful save). @type {unknown} */
|
|
26
|
+
lastError = $state.raw(null);
|
|
27
|
+
/**
|
|
28
|
+
* Set at boot when the stored document could not be read and the editor started from the backup or empty (see
|
|
29
|
+
* {@link Recovery}); `null` otherwise. Not reactive in practice (it is set before the editor is returned). @type {Recovery | null}
|
|
30
|
+
*/
|
|
31
|
+
recovery = $state.raw(null);
|
|
32
|
+
/**
|
|
33
|
+
* `true` while the live sync with the other tabs of the same document is running (`sync` option, a `BroadcastChannel` is available,
|
|
34
|
+
* IndexedDB is usable). Saving still merges what other tabs stored when it is `false`.
|
|
35
|
+
*/
|
|
36
|
+
sync = $state(false);
|
|
37
|
+
|
|
38
|
+
/** @param {string} docId */
|
|
39
|
+
constructor(docId) { this.docId = docId; }
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Stop the persistence of this editor: cancel the pending autosave, remove the `visibilitychange` / `pagehide` listeners, close the
|
|
43
|
+
* live-sync channel, stop the automatic upload retries and close the IndexedDB connection. The editor keeps working in memory, nothing is saved any more. Call it when the editor is
|
|
44
|
+
* destroyed (e.g. in the cleanup of the component that created it). Idempotent. Replaced by `createPersistedEditor`.
|
|
45
|
+
* @returns {void}
|
|
46
|
+
*/
|
|
47
|
+
dispose() {}
|
|
48
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {object} SyncHandle
|
|
3
|
+
* @property {string} id this editor's id on the channel
|
|
4
|
+
* @property {() => void} hello ask the peers for what this editor lacks
|
|
5
|
+
* @property {() => void} close stop listening and close the channel (idempotent)
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Start the live sync of an editor. Returns `null` when no `BroadcastChannel` is available (nothing to do, no error).
|
|
9
|
+
* @param {object} options
|
|
10
|
+
* @param {import('../blocks/nabu.svelte.js').Nabu} options.nabu
|
|
11
|
+
* @param {string} options.docId
|
|
12
|
+
* @param {typeof BroadcastChannel} [options.BroadcastChannelImpl] default: the global one (injectable for tests)
|
|
13
|
+
* @param {(error: unknown) => void} [options.onError] a message that could not be imported (the sync goes on)
|
|
14
|
+
* @returns {SyncHandle | null}
|
|
15
|
+
*/
|
|
16
|
+
export function startSync({ nabu, docId, BroadcastChannelImpl, onError }: {
|
|
17
|
+
nabu: import("../blocks/nabu.svelte.js").Nabu;
|
|
18
|
+
docId: string;
|
|
19
|
+
BroadcastChannelImpl?: {
|
|
20
|
+
new (name: string): BroadcastChannel;
|
|
21
|
+
prototype: BroadcastChannel;
|
|
22
|
+
} | undefined;
|
|
23
|
+
onError?: ((error: unknown) => void) | undefined;
|
|
24
|
+
}): SyncHandle | null;
|
|
25
|
+
export function channelName(docId: string): string;
|
|
26
|
+
export type SyncHandle = {
|
|
27
|
+
/**
|
|
28
|
+
* this editor's id on the channel
|
|
29
|
+
*/
|
|
30
|
+
id: string;
|
|
31
|
+
/**
|
|
32
|
+
* ask the peers for what this editor lacks
|
|
33
|
+
*/
|
|
34
|
+
hello: () => void;
|
|
35
|
+
/**
|
|
36
|
+
* stop listening and close the channel (idempotent)
|
|
37
|
+
*/
|
|
38
|
+
close: () => void;
|
|
39
|
+
};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { VersionVector } from 'loro-crdt';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Live synchronisation of the tabs that edit the same persisted document (ADR 010, multi-tab, P-94): one `BroadcastChannel`
|
|
5
|
+
* (`nabu:<docId>`) per editor. Loro makes it small: updates are idempotent and commutative, so no leader, no lock, no ordering.
|
|
6
|
+
*
|
|
7
|
+
* Protocol (every message is a plain object; `from` is the sender's random id, `to` addresses one peer, absent = everybody):
|
|
8
|
+
* - `{ t: 'update', from, to?, bytes }` — a Loro update. Broadcast after each LOCAL commit (what changed since the last broadcast),
|
|
9
|
+
* or sent to one peer as the answer to a `hello`. The receiver imports it (`nabu.importRemote`: never an undo step, caret kept).
|
|
10
|
+
* - `{ t: 'hello', from, to?, vv, reply? }` — "this is my version (`vv`, an encoded version vector): send me what I lack". Sent when
|
|
11
|
+
* the editor opens, and again when an update arrives with a gap (its dependencies are missing). The receiver answers with an
|
|
12
|
+
* `update` of what the sender lacks and, unless this already is a `reply`, with its own `hello` (`reply: true`) when the sender has
|
|
13
|
+
* something the receiver lacks, so two tabs that diverged while one of them was frozen / offline converge in both directions.
|
|
14
|
+
*
|
|
15
|
+
* Echo safety: the changes imported from a peer are never rebroadcast (`sent` is moved to the document's version after each import,
|
|
16
|
+
* and the doc subscription ignores `by: 'import'`). An update that arrives while an IME composition is running is held until it ends.
|
|
17
|
+
* Best effort by nature (a closed or frozen tab misses messages): the merge on save (`mergeStored`) and the `hello` catch up.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** @param {string} docId */
|
|
21
|
+
export const channelName = (docId) => 'nabu:' + docId;
|
|
22
|
+
|
|
23
|
+
/** How long (ms) an update is held back while an IME composition is running before trying again. */
|
|
24
|
+
const COMPOSING_RETRY_MS = 120;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {object} SyncHandle
|
|
28
|
+
* @property {string} id this editor's id on the channel
|
|
29
|
+
* @property {() => void} hello ask the peers for what this editor lacks
|
|
30
|
+
* @property {() => void} close stop listening and close the channel (idempotent)
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Start the live sync of an editor. Returns `null` when no `BroadcastChannel` is available (nothing to do, no error).
|
|
35
|
+
* @param {object} options
|
|
36
|
+
* @param {import('../blocks/nabu.svelte.js').Nabu} options.nabu
|
|
37
|
+
* @param {string} options.docId
|
|
38
|
+
* @param {typeof BroadcastChannel} [options.BroadcastChannelImpl] default: the global one (injectable for tests)
|
|
39
|
+
* @param {(error: unknown) => void} [options.onError] a message that could not be imported (the sync goes on)
|
|
40
|
+
* @returns {SyncHandle | null}
|
|
41
|
+
*/
|
|
42
|
+
export function startSync({ nabu, docId, BroadcastChannelImpl = globalThis.BroadcastChannel, onError }) {
|
|
43
|
+
if (typeof BroadcastChannelImpl !== 'function') return null;
|
|
44
|
+
/** @type {BroadcastChannel} */
|
|
45
|
+
let channel;
|
|
46
|
+
try { channel = new BroadcastChannelImpl(channelName(docId)); } catch { return null; }
|
|
47
|
+
|
|
48
|
+
const doc = nabu.doc;
|
|
49
|
+
const id = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
50
|
+
let closed = false;
|
|
51
|
+
/** What has been broadcast (or came from a peer): the next update is exported from here. */
|
|
52
|
+
let sent = doc.version();
|
|
53
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
54
|
+
let held = null;
|
|
55
|
+
/** @type {Uint8Array[]} */
|
|
56
|
+
const heldUpdates = [];
|
|
57
|
+
|
|
58
|
+
/** @param {Record<string, unknown>} message */
|
|
59
|
+
const post = (message) => { if (!closed) try { channel.postMessage({ ...message, from: id }); } catch { /* a closed channel */ } };
|
|
60
|
+
|
|
61
|
+
/** Send the local changes made since the last broadcast. */
|
|
62
|
+
const broadcastLocal = () => {
|
|
63
|
+
if (closed) return;
|
|
64
|
+
try {
|
|
65
|
+
const now = doc.version();
|
|
66
|
+
if (now.compare(sent) === 0) return;
|
|
67
|
+
const bytes = doc.export({ mode: 'update', from: sent });
|
|
68
|
+
sent = doc.version(); // (the export committed any pending change: this is what `bytes` holds)
|
|
69
|
+
if (bytes.length) post({ t: 'update', bytes });
|
|
70
|
+
} catch (error) { onError?.(error); }
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const unsubscribe = doc.subscribe((event) => { if (event.by !== 'import') broadcastLocal(); });
|
|
74
|
+
|
|
75
|
+
/** Ask the peers for what we lack. */
|
|
76
|
+
const hello = () => post({ t: 'hello', vv: doc.version().encode() });
|
|
77
|
+
|
|
78
|
+
/** @param {Uint8Array} bytes */
|
|
79
|
+
const apply = (bytes) => {
|
|
80
|
+
try {
|
|
81
|
+
broadcastLocal(); // anything local goes out first: `sent` is about to jump over the imported changes
|
|
82
|
+
const status = nabu.importRemote(bytes);
|
|
83
|
+
sent = doc.version();
|
|
84
|
+
if (status?.pending && status.pending.size > 0) hello(); // a gap (we missed an update): ask for the missing part
|
|
85
|
+
} catch (error) { onError?.(error); }
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const flushHeld = () => {
|
|
89
|
+
held = null;
|
|
90
|
+
if (closed) return;
|
|
91
|
+
if (nabu.composing) { held = setTimeout(flushHeld, COMPOSING_RETRY_MS); return; }
|
|
92
|
+
for (const bytes of heldUpdates.splice(0)) apply(bytes);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/** @param {Uint8Array} bytes */
|
|
96
|
+
const receive = (bytes) => {
|
|
97
|
+
if (nabu.composing || held) {
|
|
98
|
+
heldUpdates.push(bytes);
|
|
99
|
+
held ??= setTimeout(flushHeld, COMPOSING_RETRY_MS);
|
|
100
|
+
} else apply(bytes);
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** @param {any} message */
|
|
104
|
+
const onMessage = (message) => {
|
|
105
|
+
if (closed || !message || typeof message !== 'object' || message.from === id) return;
|
|
106
|
+
if (message.to !== undefined && message.to !== id) return;
|
|
107
|
+
if (message.t === 'update' && message.bytes instanceof Uint8Array) {
|
|
108
|
+
receive(message.bytes);
|
|
109
|
+
} else if (message.t === 'hello' && message.vv instanceof Uint8Array) {
|
|
110
|
+
try {
|
|
111
|
+
broadcastLocal();
|
|
112
|
+
const theirs = VersionVector.decode(message.vv);
|
|
113
|
+
const ours = doc.version();
|
|
114
|
+
const cmp = ours.compare(theirs); // 1: ahead of them (they lack something), 0: same, -1 or undefined: they have something we lack
|
|
115
|
+
if (cmp === 1 || cmp === undefined) {
|
|
116
|
+
const bytes = doc.export({ mode: 'update', from: theirs });
|
|
117
|
+
if (bytes.length) post({ t: 'update', to: message.from, bytes });
|
|
118
|
+
}
|
|
119
|
+
if (!message.reply && (cmp === -1 || cmp === undefined)) post({ t: 'hello', to: message.from, reply: true, vv: ours.encode() });
|
|
120
|
+
} catch (error) { onError?.(error); }
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
channel.onmessage = (event) => onMessage(event.data);
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
id,
|
|
127
|
+
hello,
|
|
128
|
+
close() {
|
|
129
|
+
if (closed) return;
|
|
130
|
+
closed = true;
|
|
131
|
+
unsubscribe();
|
|
132
|
+
if (held) clearTimeout(held);
|
|
133
|
+
held = null;
|
|
134
|
+
heldUpdates.length = 0;
|
|
135
|
+
try { channel.onmessage = null; channel.close(); } catch { /* already closed */ }
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** @param {Uint8Array} bytes @returns {string} */
|
|
2
|
+
export function toBase64(bytes: Uint8Array): string;
|
|
3
|
+
/** @param {string} text @returns {Uint8Array} */
|
|
4
|
+
export function fromBase64(text: string): Uint8Array;
|
|
5
|
+
/**
|
|
6
|
+
* Store the tail of a document. Never throws.
|
|
7
|
+
* @param {string} docId
|
|
8
|
+
* @param {Uint8Array} update a Loro update (changes since the last save)
|
|
9
|
+
* @returns {boolean} whether it was written
|
|
10
|
+
*/
|
|
11
|
+
export function writeTail(docId: string, update: Uint8Array): boolean;
|
|
12
|
+
/** The stored tail of a document, or `null` (none, or unreadable). Never throws. @param {string} docId @returns {Uint8Array | null} */
|
|
13
|
+
export function readTail(docId: string): Uint8Array | null;
|
|
14
|
+
/** Forget the tail of a document. Never throws. @param {string} docId */
|
|
15
|
+
export function clearTail(docId: string): void;
|
|
16
|
+
/** Keep a tail that could not be merged under another key (and forget the live one). Never throws. @param {string} docId */
|
|
17
|
+
export function parkTail(docId: string): void;
|
|
18
|
+
/** Remember the token of the record that is stored now. Never throws. @param {string} docId @param {{ snapshot: Uint8Array, savedAt?: number } | null} record */
|
|
19
|
+
export function writeRev(docId: string, record: {
|
|
20
|
+
snapshot: Uint8Array;
|
|
21
|
+
savedAt?: number;
|
|
22
|
+
} | null): void;
|
|
23
|
+
/** The token left by the last save of any tab, or `null` (none, or no storage). Never throws. @param {string} docId @returns {string | null} */
|
|
24
|
+
export function readRev(docId: string): string | null;
|
|
25
|
+
/** Forget the token of a document. Never throws. @param {string} docId */
|
|
26
|
+
export function clearRev(docId: string): void;
|
|
27
|
+
/**
|
|
28
|
+
* The "tail" of a document (ADR 010, theme 8, P-91): the changes made since the last save, written SYNCHRONOUSLY to `localStorage` when
|
|
29
|
+
* the page is going away. An IndexedDB write started from `pagehide` is asynchronous and browsers drop it when the page is reloaded
|
|
30
|
+
* (observed in Chromium: the transaction is created and never completes); `localStorage.setItem` is synchronous and survives. The next
|
|
31
|
+
* boot merges the tail into the document (Loro imports are idempotent: if the IndexedDB write did make it, nothing changes) and the
|
|
32
|
+
* first successful save removes it. Best effort: no storage, a full quota, or a tail above {@link MAX_TAIL_BYTES} just means no tail.
|
|
33
|
+
*/
|
|
34
|
+
/** Largest tail written (bytes of the Loro update, before base64). A long offline session is saved by IndexedDB, not by this. */
|
|
35
|
+
export const MAX_TAIL_BYTES: number;
|
|
36
|
+
export function tailKey(docId: string): string;
|
|
37
|
+
export function unappliedTailKey(docId: string): string;
|
|
38
|
+
export function revKey(docId: string): string;
|
|
39
|
+
export function revToken(record: {
|
|
40
|
+
snapshot: Uint8Array;
|
|
41
|
+
savedAt?: number;
|
|
42
|
+
} | null): string | null;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The "tail" of a document (ADR 010, theme 8, P-91): the changes made since the last save, written SYNCHRONOUSLY to `localStorage` when
|
|
3
|
+
* the page is going away. An IndexedDB write started from `pagehide` is asynchronous and browsers drop it when the page is reloaded
|
|
4
|
+
* (observed in Chromium: the transaction is created and never completes); `localStorage.setItem` is synchronous and survives. The next
|
|
5
|
+
* boot merges the tail into the document (Loro imports are idempotent: if the IndexedDB write did make it, nothing changes) and the
|
|
6
|
+
* first successful save removes it. Best effort: no storage, a full quota, or a tail above {@link MAX_TAIL_BYTES} just means no tail.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Largest tail written (bytes of the Loro update, before base64). A long offline session is saved by IndexedDB, not by this. */
|
|
10
|
+
export const MAX_TAIL_BYTES = 256 * 1024;
|
|
11
|
+
|
|
12
|
+
/** @param {string} docId */
|
|
13
|
+
export const tailKey = (docId) => `nabu:tail:${docId}`;
|
|
14
|
+
/** Where a tail that could not be merged is kept (never deleted). @param {string} docId */
|
|
15
|
+
export const unappliedTailKey = (docId) => `nabu:tail:${docId}:unapplied`;
|
|
16
|
+
|
|
17
|
+
/** @returns {Storage | null} */
|
|
18
|
+
function storage() {
|
|
19
|
+
try { return typeof localStorage === 'undefined' ? null : localStorage; } catch { return null; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param {Uint8Array} bytes @returns {string} */
|
|
23
|
+
export function toBase64(bytes) {
|
|
24
|
+
let binary = '';
|
|
25
|
+
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
26
|
+
return btoa(binary);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {string} text @returns {Uint8Array} */
|
|
30
|
+
export function fromBase64(text) {
|
|
31
|
+
const binary = atob(text);
|
|
32
|
+
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Store the tail of a document. Never throws.
|
|
37
|
+
* @param {string} docId
|
|
38
|
+
* @param {Uint8Array} update a Loro update (changes since the last save)
|
|
39
|
+
* @returns {boolean} whether it was written
|
|
40
|
+
*/
|
|
41
|
+
export function writeTail(docId, update) {
|
|
42
|
+
const ls = storage();
|
|
43
|
+
if (!ls || update.length === 0 || update.length > MAX_TAIL_BYTES) return false;
|
|
44
|
+
try { ls.setItem(tailKey(docId), JSON.stringify({ v: 1, at: Date.now(), update: toBase64(update) })); return true; } catch { return false; }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The stored tail of a document, or `null` (none, or unreadable). Never throws. @param {string} docId @returns {Uint8Array | null} */
|
|
48
|
+
export function readTail(docId) {
|
|
49
|
+
const ls = storage();
|
|
50
|
+
if (!ls) return null;
|
|
51
|
+
try {
|
|
52
|
+
const raw = ls.getItem(tailKey(docId));
|
|
53
|
+
if (!raw) return null;
|
|
54
|
+
const record = JSON.parse(raw);
|
|
55
|
+
return record?.v === 1 && typeof record.update === 'string' ? fromBase64(record.update) : null;
|
|
56
|
+
} catch { return null; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Forget the tail of a document. Never throws. @param {string} docId */
|
|
60
|
+
export function clearTail(docId) {
|
|
61
|
+
try { storage()?.removeItem(tailKey(docId)); } catch { /* nothing to do */ }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Keep a tail that could not be merged under another key (and forget the live one). Never throws. @param {string} docId */
|
|
65
|
+
export function parkTail(docId) {
|
|
66
|
+
const ls = storage();
|
|
67
|
+
if (!ls) return;
|
|
68
|
+
try {
|
|
69
|
+
const raw = ls.getItem(tailKey(docId));
|
|
70
|
+
if (raw) ls.setItem(unappliedTailKey(docId), raw);
|
|
71
|
+
} catch { /* quota: the tail is dropped, it was already a best effort */ }
|
|
72
|
+
clearTail(docId);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ── The revision marker ──────────────────────────────────────────────────────────────────────────
|
|
76
|
+
// A page that is going away must write its snapshot BLIND (no read first: see `saveSnapshot`'s `previous`), which is only safe when no
|
|
77
|
+
// other tab wrote the record since this tab read or wrote it. `localStorage` is synchronous and shared by the tabs of the origin: every
|
|
78
|
+
// successful save leaves the token of the record it wrote (or found up to date) under `nabu:rev:<docId>`, and a tab compares it with
|
|
79
|
+
// the token of the record it knows before writing blind. A record written by an older version of Nabu left no token (`null`): unknown,
|
|
80
|
+
// treated as "nobody else" like before.
|
|
81
|
+
|
|
82
|
+
/** @param {string} docId */
|
|
83
|
+
export const revKey = (docId) => `nabu:rev:${docId}`;
|
|
84
|
+
|
|
85
|
+
/** The token of a stored record. @param {{ snapshot: Uint8Array, savedAt?: number } | null} record @returns {string | null} */
|
|
86
|
+
export const revToken = (record) => (record ? `${record.savedAt ?? 0}:${record.snapshot.length}` : null);
|
|
87
|
+
|
|
88
|
+
/** Remember the token of the record that is stored now. Never throws. @param {string} docId @param {{ snapshot: Uint8Array, savedAt?: number } | null} record */
|
|
89
|
+
export function writeRev(docId, record) {
|
|
90
|
+
const token = revToken(record);
|
|
91
|
+
if (token === null) return;
|
|
92
|
+
try { storage()?.setItem(revKey(docId), token); } catch { /* best effort */ }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The token left by the last save of any tab, or `null` (none, or no storage). Never throws. @param {string} docId @returns {string | null} */
|
|
96
|
+
export function readRev(docId) {
|
|
97
|
+
try { return storage()?.getItem(revKey(docId)) ?? null; } catch { return null; }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Forget the token of a document. Never throws. @param {string} docId */
|
|
101
|
+
export function clearRev(docId) {
|
|
102
|
+
try { storage()?.removeItem(revKey(docId)); } catch { /* nothing to do */ }
|
|
103
|
+
}
|