@aionbuilders/nabu 0.1.2 → 0.1.3

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 CHANGED
@@ -4,6 +4,20 @@
4
4
 
5
5
  Nothing yet.
6
6
 
7
+ ## 0.1.3 (2026-11-04)
8
+
9
+ Fixes found by testing the published package in a real SvelteKit app: the first thing a consumer's build, a Firefox user and a page that mounts editors on demand would hit. The API only gains two methods.
10
+
11
+ ### Added
12
+ - **`engine.destroy()`** releases an engine for good, memory included: it unsubscribes the engine and its blocks from the document, stops the subsystems, closes the persistence and the upload retries, and the engine can then be garbage collected. Idempotent. The document stays readable (`serialize()`), the engine no longer follows changes, and it must not be mounted again. Changes that are not saved yet are dropped: await `saveNow()` first when they matter.
13
+ - **`engine.track(unsubscribe)`** hands a Loro subscription or any cleanup over to `destroy()`. A custom block should pass its own, `nabu.track(node.data.subscribe(...))`: Loro keeps the callback until it is unsubscribed, so an untracked one keeps the engine in memory.
14
+
15
+ ### Fixed
16
+ - **`vite build` failed on a server-rendered page that imports Nabu**, with `Cannot find module './snippets/loro-wasm-…/inline0.js'`. The `nabu()` helper now keeps `loro-crdt` out of the SSR bundle (`ssr.external`). With pnpm, whose strict `node_modules` hides it from your app, also run `pnpm add loro-crdt`.
17
+ - **Firefox lost everything typed after Tab or `element.focus()`.** Firefox leaves the caret on the editor root, and the correction looked for text before the start of the document, found none and gave up. Such a caret now lands on the nearest text in either direction. Covered by `tests/e2e/dead-root-caret.spec.ts`, and checked on real Firefox, WebKit and Chromium through a packed build.
18
+ - **Every unmounted editor left 5 listeners on `document`.** They now exist only while an editor is mounted: unmounting is enough to release the page, and the same engine can be mounted again. Covered by `tests/e2e/lifecycle.spec.ts`, which counts the listeners and checks through the garbage collector that a destroyed engine is really gone.
19
+ - **A flaky documentation test.** The walkthrough of `docs/recipes/autosave-to-your-server.md` raced its own 10 ms timer under load.
20
+
7
21
  ## 0.1.2 (2026-10-29)
8
22
 
9
23
  Fixes from the first days of the beta: rich text that stayed split after removing a mark, mark edges, Ctrl+B at the edge of a word, and code block editing. No API change.
package/README.md CHANGED
@@ -26,7 +26,7 @@ bun add @aionbuilders/nabu
26
26
  ### Requirements
27
27
 
28
28
  - **Svelte 5.20 or newer**.
29
- - A Vite setup (SvelteKit, or Svelte + Vite) that can load WebAssembly. Loro ships as a WebAssembly module loaded with top-level `await`, so the build needs `vite-plugin-wasm` and `build.target: 'esnext'`. The bundled helper does both:
29
+ - A Vite setup (SvelteKit, or Svelte + Vite) that can load WebAssembly. Loro ships as a WebAssembly module loaded with top-level `await`, so the build needs `vite-plugin-wasm` and `build.target: 'esnext'` (and, for server rendering, `loro-crdt` kept out of the SSR bundle). The bundled helper does all three:
30
30
 
31
31
  ```js
32
32
  // vite.config.js
@@ -201,11 +201,11 @@ export class TextBehavior {
201
201
  this.text = $state(this.container.toString());
202
202
  /** @public */
203
203
  this.delta = $state(readDelta(this.container));
204
- this.container.subscribe(() => {
204
+ this.nabu.track(this.container.subscribe(() => {
205
205
  this.text = this.container.toString();
206
206
  this.delta = readDelta(this.container);
207
207
  this.nabu.noteTextChange?.(this.block); // a selection end in this block must follow the edit (P-109)
208
- });
208
+ }));
209
209
  }
210
210
 
211
211
  /** @public */
@@ -40,9 +40,9 @@ export class CalloutBlock extends TextBlock {
40
40
  );
41
41
 
42
42
  // Sync variant from Loro data changes (mirrors Heading's level sync)
43
- this.node.data.subscribe(() => {
43
+ this.nabu.track(this.node.data.subscribe(() => {
44
44
  this.variant = this.node.data.get('variant') || 'note';
45
- });
45
+ }));
46
46
  }
47
47
 
48
48
  // ── Capability flags ─────────────────────────────────────────────────────
@@ -93,9 +93,9 @@ export class CodeBlock extends TextBlock {
93
93
  );
94
94
 
95
95
  // Sync language from Loro data changes (mirrors Heading's level sync)
96
- this.node.data.subscribe(() => {
96
+ this.nabu.track(this.node.data.subscribe(() => {
97
97
  this.language = this.node.data.get('language') || null;
98
- });
98
+ }));
99
99
  }
100
100
 
101
101
  // ── Capability flags ─────────────────────────────────────────────────────
@@ -49,9 +49,9 @@ export class Heading extends TextBlock {
49
49
  this.serializers.set('application/x-nabu+json', (ctx) => this.behavior.toClipboardBlock({ ...ctx, props: { level: this.level } }));
50
50
 
51
51
  // Synchronisation du niveau
52
- this.node.data.subscribe(() => {
52
+ this.nabu.track(this.node.data.subscribe(() => {
53
53
  this.level = this.node.data.get("level") || 1;
54
- });
54
+ }));
55
55
  }
56
56
 
57
57
  /** @type {number} */
@@ -60,9 +60,9 @@ export class ListItem extends MegaBlock {
60
60
  // Initialize checked from Loro metadata
61
61
  this.checked = !!node.data.get('checked');
62
62
  // Subscribe to data changes to keep checked in sync
63
- this.node.data.subscribe(() => {
63
+ this.nabu.track(this.node.data.subscribe(() => {
64
64
  this.checked = !!this.node.data.get('checked');
65
- });
65
+ }));
66
66
 
67
67
  // One item (and its sublists), indented under the items that hold it. A whole list is rendered by the List.
68
68
  this.serializers.set('markdown', () => {
@@ -17,10 +17,10 @@ export class ListBehavior {
17
17
  this.node = /** @type {ListNode} */ (block.node);
18
18
  this.listType = /** @type {"bullet" | "ordered" | "todo"} */ (this.node.data.get("listType") || "bullet");
19
19
  this.start = /** @type {any} */ (this.node.data.get("start")) ?? null;
20
- this.node.data.subscribe(() => {
20
+ this.nabu.track(this.node.data.subscribe(() => {
21
21
  this.listType = /** @type {"bullet" | "ordered" | "todo"} */ (this.node.data.get("listType") || "bullet");
22
22
  this.start = /** @type {any} */ (this.node.data.get("start")) ?? null;
23
- });
23
+ }));
24
24
  }
25
25
 
26
26
  /** Raw `start` number from the node (null = unset); List.start normalizes it. @type {number | null} */
@@ -29,7 +29,7 @@ export class MediaBlock extends Block {
29
29
  this.status = data.get('status') || 'ready';
30
30
  this.#reason = normalizeReason(data.get('reason'));
31
31
  this.name = data.get('name') || '';
32
- data.subscribe(() => {
32
+ this.nabu.track(data.subscribe(() => {
33
33
  this.ref = data.get('ref') || '';
34
34
  this.alt = data.get('alt') || '';
35
35
  this.status = data.get('status') || 'ready';
@@ -41,7 +41,7 @@ export class MediaBlock extends Block {
41
41
  if (this.previewUrl.startsWith('blob:')) URL.revokeObjectURL(this.previewUrl);
42
42
  this.previewUrl = null;
43
43
  }
44
- });
44
+ }));
45
45
  }
46
46
 
47
47
  /** @type {string} */ ref = $state('');
@@ -66,6 +66,26 @@ export class Nabu {
66
66
  * @public
67
67
  */
68
68
  public static CONTINUE: symbol;
69
+ /**
70
+ * The `onPush` / `onPop` of the undo manager. Built HERE, out of the constructor, so that they close over `holder` and nothing
71
+ * else: a closure made in the constructor would keep the constructor's scope, and `this` with it, alive.
72
+ * @param {{ owner: Nabu | null }} holder
73
+ */
74
+ static #undoCallbacks(holder: {
75
+ owner: Nabu | null;
76
+ }): {
77
+ /** @param {boolean} isUndo @param {{ end?: any } | undefined} range */
78
+ onPush: (isUndo: boolean, range: {
79
+ end?: any;
80
+ } | undefined) => {
81
+ value: any;
82
+ cursors: never[];
83
+ };
84
+ /** @param {boolean} isUndo @param {any} storedValue @param {{ end?: any } | undefined} range */
85
+ onPop: (isUndo: boolean, storedValue: any, range: {
86
+ end?: any;
87
+ } | undefined) => void;
88
+ };
69
89
  /** @param {NabuInit} init */
70
90
  constructor(init?: NabuInit);
71
91
  /**
@@ -691,6 +711,32 @@ export class Nabu {
691
711
  * @unstable
692
712
  */
693
713
  public get internals(): NabuInternals;
714
+ /**
715
+ * Hand over a Loro subscription (or any cleanup) that lives as long as the engine: `destroy()` calls it, once. A block or an
716
+ * extension passes its own, `nabu.track(node.data.subscribe(...))`: Loro keeps the callback (and what it closes over, the engine
717
+ * with it) until it is unsubscribed, so one that is not tracked keeps the engine in memory after `destroy()`.
718
+ * @template {() => void} T
719
+ * @param {T} unsubscribe
720
+ * @returns {T} what it was given
721
+ * @public
722
+ */
723
+ public track<T extends () => void>(unsubscribe: T): T;
724
+ /**
725
+ * Release the engine for good, for a host that is done with it: the memory, not only the page. Unmounting `<NabuEditor>`
726
+ * releases the page listeners but not the memory (the engine can be mounted again); `destroy()` releases the memory: it
727
+ * unsubscribes the engine and its blocks from the document (see {@link Nabu#track}), stops the subsystems, closes `persistence`
728
+ * if the engine is persisted, releases the files (upload retries) and stops the selection tracking, so that the engine can be
729
+ * garbage collected. Idempotent. Call it after `unmount()` or instead of it (e.g. `onDestroy(() => engine.destroy())`).
730
+ *
731
+ * Changes that are not saved yet are DROPPED, not written: `persistence.dispose()` cancels the pending autosave and removes the
732
+ * `pagehide` flush. Await `saveNow()` first when they matter.
733
+ *
734
+ * The document stays in memory and readable as it was (`serialize()`, `doc`), but the engine no longer follows changes: no more
735
+ * edits. A destroyed engine must not be mounted again.
736
+ * @returns {void}
737
+ * @public
738
+ */
739
+ public destroy(): void;
694
740
  /**
695
741
  * Log a diagnostic to the console when `debugging` is on. Silent otherwise.
696
742
  * @param {...any} args
@@ -251,30 +251,16 @@ export class Nabu {
251
251
  this.tree = /** @type {LoroTree<NabuNodeData>} */ (this.doc.getTree("blocks"));
252
252
  this.content = this.doc.getMap("content");
253
253
 
254
- // Initialize Undo/Redo Manager
254
+ // Initialize Undo/Redo Manager. Loro keeps the two callbacks for as long as the manager lives and has no way to drop
255
+ // them: they reach the engine through `holder`, which `destroy()` clears (else the engine could never be collected).
256
+ const holder = { owner: /** @type {Nabu | null} */ (this) };
257
+ this.track(() => { holder.owner = null; });
255
258
  this.undoManager = new UndoManager(this.doc, {
256
259
  maxUndoSteps: 100,
257
260
  // Background completions (e.g. a pasted file finishing its upload) are not undo steps of their own.
258
261
  excludeOriginPrefixes: ['nabu:silent'],
259
262
  mergeInterval: this.#mergeInterval,
260
- onPush: (isUndo, range) => {
261
- if (this.#isolatedSteps > 0) this.#isolatedSteps--;
262
- // The selection to give back when this step is popped. An undo step: the selection right BEFORE the change
263
- // (it is pushed after the commit, but the captured selection predates the change). The redo step pushed by
264
- // an undo: where the undone action ENDED. A caret decided by the caller (block shortcut) wins.
265
- const explicit = this.#undoCursor;
266
- this.#undoCursor = null;
267
- const ended = !isUndo && this.#undoneEnd !== null ? this.#actionEnds.get(this.#undoneEnd) : undefined;
268
- const stored = (explicit ? explicitSelection(explicit.block, explicit.offset) : ended ?? this.#undoSel) ?? legacySelection(this);
269
- this.#endKey = isUndo ? range?.end ?? null : null;
270
- return { value: /** @type {any} */ (stored), cursors: [] };
271
- },
272
- onPop: (isUndo, storedValue, range) => {
273
- this.#undoneEnd = isUndo ? range?.end ?? null : null;
274
- this.#endKey = null;
275
- const value = /** @type {any} */ (storedValue?.value);
276
- if (value && typeof value === 'object' && 'anchor' in value) restoreSelection(this, value);
277
- }
263
+ ...Nabu.#undoCallbacks(holder),
278
264
  });
279
265
 
280
266
  /**
@@ -394,7 +380,7 @@ export class Nabu {
394
380
  // One event batch = one refresh. The affected containers are COLLECTED while the batch is read, then each is refreshed
395
381
  // once (the root list at most once, every parent at most once): refreshing per action made an import / a mass undo / a
396
382
  // big paste quadratic (P-104). The doc already holds the final state of the batch, so the order of the actions is moot.
397
- this.tree.subscribe((event) => {
383
+ this.track(this.tree.subscribe((event) => {
398
384
  let rootsDirty = false;
399
385
  /** @type {Set<string>} */
400
386
  const parents = new Set();
@@ -440,7 +426,7 @@ export class Nabu {
440
426
  // A block retyped into a leaf (no children) in the same transaction has no updateChildren().
441
427
  /** @type {{ updateChildren?: (retyped?: Set<string>) => void } | undefined} */ (this.blocks.get(parentId))?.updateChildren?.(retyped);
442
428
  }
443
- });
429
+ }));
444
430
 
445
431
  this.init();
446
432
  }
@@ -2580,6 +2566,81 @@ export class Nabu {
2580
2566
  });
2581
2567
  }
2582
2568
 
2569
+ /**
2570
+ * The `onPush` / `onPop` of the undo manager. Built HERE, out of the constructor, so that they close over `holder` and nothing
2571
+ * else: a closure made in the constructor would keep the constructor's scope, and `this` with it, alive.
2572
+ * @param {{ owner: Nabu | null }} holder
2573
+ */
2574
+ static #undoCallbacks(holder) {
2575
+ return {
2576
+ /** @param {boolean} isUndo @param {{ end?: any } | undefined} range */
2577
+ onPush: (isUndo, range) => {
2578
+ const self = holder.owner;
2579
+ if (!self) return { value: null, cursors: [] };
2580
+ if (self.#isolatedSteps > 0) self.#isolatedSteps--;
2581
+ // The selection to give back when this step is popped. An undo step: the selection right BEFORE the change
2582
+ // (it is pushed after the commit, but the captured selection predates the change). The redo step pushed by
2583
+ // an undo: where the undone action ENDED. A caret decided by the caller (block shortcut) wins.
2584
+ const explicit = self.#undoCursor;
2585
+ self.#undoCursor = null;
2586
+ const ended = !isUndo && self.#undoneEnd !== null ? self.#actionEnds.get(self.#undoneEnd) : undefined;
2587
+ const stored = (explicit ? explicitSelection(explicit.block, explicit.offset) : ended ?? self.#undoSel) ?? legacySelection(self);
2588
+ self.#endKey = isUndo ? range?.end ?? null : null;
2589
+ return { value: /** @type {any} */ (stored), cursors: [] };
2590
+ },
2591
+ /** @param {boolean} isUndo @param {any} storedValue @param {{ end?: any } | undefined} range */
2592
+ onPop: (isUndo, storedValue, range) => {
2593
+ const self = holder.owner;
2594
+ if (!self) return;
2595
+ self.#undoneEnd = isUndo ? range?.end ?? null : null;
2596
+ self.#endKey = null;
2597
+ const value = /** @type {any} */ (storedValue?.value);
2598
+ if (value && typeof value === 'object' && 'anchor' in value) restoreSelection(self, value);
2599
+ },
2600
+ };
2601
+ }
2602
+
2603
+ /** What `destroy()` calls: the unsubscribe functions given to {@link Nabu#track}. @type {Set<() => void>} */
2604
+ #tracked = new Set();
2605
+
2606
+ /**
2607
+ * Hand over a Loro subscription (or any cleanup) that lives as long as the engine: `destroy()` calls it, once. A block or an
2608
+ * extension passes its own, `nabu.track(node.data.subscribe(...))`: Loro keeps the callback (and what it closes over, the engine
2609
+ * with it) until it is unsubscribed, so one that is not tracked keeps the engine in memory after `destroy()`.
2610
+ * @template {() => void} T
2611
+ * @param {T} unsubscribe
2612
+ * @returns {T} what it was given
2613
+ * @public
2614
+ */
2615
+ track(unsubscribe) {
2616
+ this.#tracked.add(unsubscribe);
2617
+ return unsubscribe;
2618
+ }
2619
+
2620
+ /**
2621
+ * Release the engine for good, for a host that is done with it: the memory, not only the page. Unmounting `<NabuEditor>`
2622
+ * releases the page listeners but not the memory (the engine can be mounted again); `destroy()` releases the memory: it
2623
+ * unsubscribes the engine and its blocks from the document (see {@link Nabu#track}), stops the subsystems, closes `persistence`
2624
+ * if the engine is persisted, releases the files (upload retries) and stops the selection tracking, so that the engine can be
2625
+ * garbage collected. Idempotent. Call it after `unmount()` or instead of it (e.g. `onDestroy(() => engine.destroy())`).
2626
+ *
2627
+ * Changes that are not saved yet are DROPPED, not written: `persistence.dispose()` cancels the pending autosave and removes the
2628
+ * `pagehide` flush. Await `saveNow()` first when they matter.
2629
+ *
2630
+ * The document stays in memory and readable as it was (`serialize()`, `doc`), but the engine no longer follows changes: no more
2631
+ * edits. A destroyed engine must not be mounted again.
2632
+ * @returns {void}
2633
+ * @public
2634
+ */
2635
+ destroy() {
2636
+ for (const stop of this.#tracked) stop();
2637
+ this.#tracked.clear();
2638
+ for (const system of this.systems.values()) system.stop?.();
2639
+ /** @type {any} */ (this).persistence?.dispose?.();
2640
+ /** @type {any} */ (this.systems.get('files'))?.dispose?.();
2641
+ this.selection.destroy();
2642
+ }
2643
+
2583
2644
  /**
2584
2645
  * Log a diagnostic to the console when `debugging` is on. Silent otherwise.
2585
2646
  * @param {...any} args
@@ -109,7 +109,7 @@ export class RegionBlock extends MegaBlock {
109
109
 
110
110
  this.#read();
111
111
  // Local commits, imports and remote peers all end up here (the `fields` map is a child container of `data`).
112
- node.data.subscribe(() => this.#read());
112
+ nabu.track(node.data.subscribe(() => this.#read()));
113
113
 
114
114
  // Document export: exact round trip (`importJSON` reads `props` and `content` back, see RegionBlock.create).
115
115
  this.serializers.set('json', () => ({
@@ -16,7 +16,8 @@ export class NabuSelection extends SvelteSelection {
16
16
  root: HTMLElement | null;
17
17
  /**
18
18
  * Declare the element that renders this engine (the `[data-nabu-root]` div). Returns the function that detaches it (only
19
- * clears the reference when it is still this element: a remount may already have set the next one).
19
+ * clears the reference when it is still this element: a remount may already have set the next one). The page listeners
20
+ * (`connected`) exist only while a root is attached: an engine with no editor mounted holds nothing on the document.
20
21
  * @param {HTMLElement} el
21
22
  * @returns {() => void}
22
23
  */
@@ -36,13 +36,15 @@ export class NabuSelection extends SvelteSelection {
36
36
 
37
37
  /**
38
38
  * Declare the element that renders this engine (the `[data-nabu-root]` div). Returns the function that detaches it (only
39
- * clears the reference when it is still this element: a remount may already have set the next one).
39
+ * clears the reference when it is still this element: a remount may already have set the next one). The page listeners
40
+ * (`connected`) exist only while a root is attached: an engine with no editor mounted holds nothing on the document.
40
41
  * @param {HTMLElement} el
41
42
  * @returns {() => void}
42
43
  */
43
44
  attachRoot(el) {
44
45
  this.root = el;
45
- return () => { if (this.root === el) this.root = null; };
46
+ this.connected = true;
47
+ return () => { if (this.root === el) { this.root = null; this.connected = false; } };
46
48
  }
47
49
 
48
50
  /**
@@ -102,6 +104,7 @@ export class NabuSelection extends SvelteSelection {
102
104
  constructor(nabu) {
103
105
  super();
104
106
  this.nabu = nabu;
107
+ this.connected = false; // no root yet: `attachRoot` turns the page listeners on
105
108
 
106
109
  // Every caret the editor itself places (after an action, an undo…) is remembered for undo / redo (ADR 015): it is
107
110
  // where that action ended. `setBaseAndExtent` is an own-property arrow function of the base class: wrap it.
@@ -114,7 +117,7 @@ export class NabuSelection extends SvelteSelection {
114
117
  return done;
115
118
  };
116
119
 
117
- $effect.root(() => {
120
+ this.#stop = $effect.root(() => {
118
121
  $effect(() => {
119
122
  if (this.blocks) {
120
123
  this.previous.forEach(block => block.clearSelection());
@@ -134,6 +137,7 @@ export class NabuSelection extends SvelteSelection {
134
137
  // This is the only reliable source of direction — DOM position comparisons
135
138
  // break when anchorNode is an ancestor of the previous position.
136
139
  $effect(() => {
140
+ if (!this.connected) return;
137
141
  /** @param {KeyboardEvent} e */
138
142
  const onKeydown = (e) => {
139
143
  // Capture phase on document = runs before every other keydown handler
@@ -233,8 +237,22 @@ export class NabuSelection extends SvelteSelection {
233
237
  });
234
238
  });
235
239
  });
240
+
241
+ // Stop for good (`Nabu#destroy`): both effect roots (this one and the base class's), and the pending repair.
242
+ const stopBase = this.destroy;
243
+ this.destroy = () => {
244
+ this.#stop?.();
245
+ this.#stop = null;
246
+ if (this.#repairTimer !== null) clearTimeout(this.#repairTimer);
247
+ this.#repairTimer = null;
248
+ this.root = null;
249
+ stopBase();
250
+ };
236
251
  }
237
252
 
253
+ /** Stops this class's effect root (see `destroy`). @type {(() => void) | null} */
254
+ #stop = null;
255
+
238
256
  /**
239
257
  * Move a caret / focus that sits on a NON-TEXT position to the nearest valid text position, in the
240
258
  * direction of travel (arrow keys; a heuristic otherwise): inert blocks (dividers, images…), element
@@ -327,8 +345,14 @@ export class NabuSelection extends SvelteSelection {
327
345
  }
328
346
 
329
347
  if (anchorInvalid) {
330
- const dir = explicit ?? offsetHeuristic(anchor, anchorOffset);
331
- const target = findNearestTextNode(anchor, anchorOffset, dir, filter, this.root);
348
+ let dir = explicit ?? offsetHeuristic(anchor, anchorOffset);
349
+ let target = findNearestTextNode(anchor, anchorOffset, dir, filter, this.root);
350
+ // No arrow key, a collapsed caret, and nothing in the guessed direction: Firefox puts the caret on (root, 0) after a Tab
351
+ // or `root.focus()`, a caret past the last child is the mirror case. Typing there is lost, so land on the other side.
352
+ if (!target && !explicit && live.isCollapsed) {
353
+ dir = dir === 'forward' ? 'backward' : 'forward';
354
+ target = findNearestTextNode(anchor, anchorOffset, dir, filter, this.root);
355
+ }
332
356
  if (!target) {
333
357
  // Leaving the document by keyboard with nothing to land on: the document must offer a caret there.
334
358
  if (explicit === 'forward') this.nabu.openTrailingCaret();
@@ -29,10 +29,10 @@ export class ToggleBlock extends MegaBlock {
29
29
  // Initialize collapsed from Loro metadata
30
30
  this.collapsed = !!data.get('collapsed');
31
31
  // Subscribe to data changes to keep collapsed in sync (a change of the document wins over the read-only view state)
32
- this.node.data.subscribe(() => {
32
+ this.nabu.track(this.node.data.subscribe(() => {
33
33
  this.#viewState = null;
34
34
  this.collapsed = !!this.node.data.get('collapsed');
35
- });
35
+ }));
36
36
 
37
37
  this.serializers.set('markdown', () => toggleMarkdown(this.#stored, this.behavior.toMarkdown(), /** @type {any} */ (this.children.map(c => c.serialize('markdown')))));
38
38
  this.serializers.set('json', () => ({
@@ -130,7 +130,7 @@ export class Files {
130
130
  forgetMissing: () => { for (const [key, value] of this.#urls) if (value === null) this.#urls.delete(key); },
131
131
  track: (promise) => this.#track(promise),
132
132
  });
133
- nabu.doc.subscribe((event) => this.#uploads.onDocEvent(event));
133
+ nabu.track(nabu.doc.subscribe((event) => this.#uploads.onDocEvent(event)));
134
134
  if (this.assets.size > 0) this.#track(this.#migrate());
135
135
  this.#preload();
136
136
  }
@@ -23,6 +23,11 @@
23
23
  * // Utiliser selection.text, selection.isCollapsed, etc. dans vos composants
24
24
  */
25
25
  export class SvelteSelection {
26
+ /**
27
+ * Whether the wrapper listens to the page (`selectionchange` on the document). On by default; a subclass tied to a part of the
28
+ * page turns it off while it has none, so that an unmounted owner leaves nothing behind. Reactive.
29
+ */
30
+ connected: boolean;
26
31
  /** @type {Selection?} */
27
32
  raw: Selection | null;
28
33
  /** @public */
@@ -33,13 +33,19 @@ export class SvelteSelection {
33
33
  if (typeof window === 'undefined' || !window.getSelection) {
34
34
  return;
35
35
  }
36
-
36
+
37
+ // Disconnected: no listener on the page, and nothing mirrored (the wrapper would keep removed DOM nodes alive).
38
+ if (!this.connected) {
39
+ this.#sel = null;
40
+ this.#ranges = [];
41
+ return;
42
+ }
43
+
37
44
  document.addEventListener('selectionchange', this.#updateSelection);
38
45
  this.#updateSelection();
39
46
 
40
47
  return () => {
41
48
  document.removeEventListener('selectionchange', this.#updateSelection);
42
- this.#cleanup?.();
43
49
  };
44
50
  });
45
51
  });
@@ -47,6 +53,12 @@ export class SvelteSelection {
47
53
 
48
54
  /** @type {Function?} */
49
55
  #cleanup = null;
56
+
57
+ /**
58
+ * Whether the wrapper listens to the page (`selectionchange` on the document). On by default; a subclass tied to a part of the
59
+ * page turns it off while it has none, so that an unmounted owner leaves nothing behind. Reactive.
60
+ */
61
+ connected = $state(true);
50
62
 
51
63
  /** @type {Selection?} */
52
64
  raw = null;
@@ -649,6 +661,7 @@ export class SvelteSelection {
649
661
  destroy = () => {
650
662
  this.unobserveAll();
651
663
  this.#cleanup?.();
664
+ this.#cleanup = null;
652
665
  this.raw = null;
653
666
  this.#sel = null;
654
667
  this.#ranges = [];
package/dist/vite.d.ts CHANGED
@@ -16,6 +16,14 @@
16
16
  * natively, so no `vite-plugin-top-level-await` transform is needed (that
17
17
  * plugin is incompatible with Vite 8 / Rolldown).
18
18
  *
19
+ * It also adds `loro-crdt` to `ssr.external`, so that a server-rendered page
20
+ * (SvelteKit) loads loro-crdt's Node build from `node_modules` at run time.
21
+ * Bundled into the SSR output, that build fails with
22
+ * `Cannot find module './snippets/loro-wasm-…/inline0.js'`. It is left alone
23
+ * when `ssr.external` is `true` (everything is already external). `noExternal`
24
+ * is no reason to skip it: SvelteKit sets `ssr.noExternal: true` on every build,
25
+ * and an entry of `ssr.external` still wins over it.
26
+ *
19
27
  * @returns {Promise<import('vite').Plugin[]>}
20
28
  */
21
29
  export function nabu(): Promise<import("vite").Plugin[]>;
package/dist/vite.js CHANGED
@@ -16,6 +16,14 @@
16
16
  * natively, so no `vite-plugin-top-level-await` transform is needed (that
17
17
  * plugin is incompatible with Vite 8 / Rolldown).
18
18
  *
19
+ * It also adds `loro-crdt` to `ssr.external`, so that a server-rendered page
20
+ * (SvelteKit) loads loro-crdt's Node build from `node_modules` at run time.
21
+ * Bundled into the SSR output, that build fails with
22
+ * `Cannot find module './snippets/loro-wasm-…/inline0.js'`. It is left alone
23
+ * when `ssr.external` is `true` (everything is already external). `noExternal`
24
+ * is no reason to skip it: SvelteKit sets `ssr.noExternal: true` on every build,
25
+ * and an entry of `ssr.external` still wins over it.
26
+ *
19
27
  * @returns {Promise<import('vite').Plugin[]>}
20
28
  */
21
29
  export async function nabu() {
@@ -23,9 +31,14 @@ export async function nabu() {
23
31
  return [
24
32
  wasm(),
25
33
  {
26
- name: 'nabu:esnext-target',
34
+ name: 'nabu:config',
27
35
  config(config) {
28
- if (config.build?.target === undefined) return { build: { target: 'esnext' } };
36
+ /** @type {import('vite').UserConfig} */
37
+ const patch = {};
38
+ if (config.build?.target === undefined) patch.build = { target: 'esnext' };
39
+ // Arrays merge in Vite's `mergeConfig`, so the consumer's own `ssr.external` entries are kept.
40
+ if (config.ssr?.external !== true) patch.ssr = { external: ['loro-crdt'] };
41
+ return Object.keys(patch).length ? patch : undefined;
29
42
  },
30
43
  },
31
44
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aionbuilders/nabu",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "scripts": {
5
5
  "dev": "vite dev",
6
6
  "predev": "npm run api:model:ensure",