@arbidocs/blocks 0.5.133 → 0.5.135

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 (70) hide show
  1. package/dist/{ConnectedNativeDocxComparison-H72RQJKH.cjs → ConnectedNativeDocxComparison-W4KIGO54.cjs} +8 -8
  2. package/dist/{ConnectedNativeDocxComparison-H72RQJKH.cjs.map → ConnectedNativeDocxComparison-W4KIGO54.cjs.map} +1 -1
  3. package/dist/{ConnectedStreamedWordArtifact-T7PZIRBY.cjs → ConnectedStreamedWordArtifact-764NSXPQ.cjs} +8 -8
  4. package/dist/{ConnectedStreamedWordArtifact-T7PZIRBY.cjs.map → ConnectedStreamedWordArtifact-764NSXPQ.cjs.map} +1 -1
  5. package/dist/{FilesViewerDialog-OA3HDLOI.cjs → FilesViewerDialog-IFF2JR2A.cjs} +7 -7
  6. package/dist/{FilesViewerDialog-OA3HDLOI.cjs.map → FilesViewerDialog-IFF2JR2A.cjs.map} +1 -1
  7. package/dist/{NativeDocxEditor-XZAEU5QU.cjs → NativeDocxEditor-KM6U4ZLA.cjs} +6 -6
  8. package/dist/{NativeDocxEditor-XZAEU5QU.cjs.map → NativeDocxEditor-KM6U4ZLA.cjs.map} +1 -1
  9. package/dist/{chunk-T2DUNNYY.cjs → chunk-C6DF6WB2.cjs} +745 -21
  10. package/dist/chunk-C6DF6WB2.cjs.map +1 -0
  11. package/dist/{chunk-64247UHS.cjs → chunk-DBGBAD4J.cjs} +4 -4
  12. package/dist/{chunk-64247UHS.cjs.map → chunk-DBGBAD4J.cjs.map} +1 -1
  13. package/dist/{chunk-UOZ237OW.cjs → chunk-FABKMTAI.cjs} +42 -5
  14. package/dist/chunk-FABKMTAI.cjs.map +1 -0
  15. package/dist/{chunk-L4Y6UMRC.cjs → chunk-FDRZJFNV.cjs} +5 -5
  16. package/dist/{chunk-L4Y6UMRC.cjs.map → chunk-FDRZJFNV.cjs.map} +1 -1
  17. package/dist/{chunk-5JK3232B.cjs → chunk-IEAZX7L6.cjs} +4 -4
  18. package/dist/{chunk-5JK3232B.cjs.map → chunk-IEAZX7L6.cjs.map} +1 -1
  19. package/dist/{chunk-2SWS7ESM.cjs → chunk-L62EU3TQ.cjs} +3 -3
  20. package/dist/{chunk-2SWS7ESM.cjs.map → chunk-L62EU3TQ.cjs.map} +1 -1
  21. package/dist/{chunk-IN3KXI3K.cjs → chunk-LG36LSVZ.cjs} +6 -6
  22. package/dist/{chunk-IN3KXI3K.cjs.map → chunk-LG36LSVZ.cjs.map} +1 -1
  23. package/dist/{chunk-VCEX7COE.cjs → chunk-LIDXIX36.cjs} +10 -5
  24. package/dist/chunk-LIDXIX36.cjs.map +1 -0
  25. package/dist/{chunk-RZSBHRQL.cjs → chunk-MMKMQZ2B.cjs} +5 -5
  26. package/dist/{chunk-RZSBHRQL.cjs.map → chunk-MMKMQZ2B.cjs.map} +1 -1
  27. package/dist/chunk-MMMGOZYH.cjs +18 -0
  28. package/dist/{chunk-KWD5Q4XH.cjs.map → chunk-MMMGOZYH.cjs.map} +1 -1
  29. package/dist/{chunk-V6SFJ44C.cjs → chunk-ZN2JXV65.cjs} +50 -13
  30. package/dist/chunk-ZN2JXV65.cjs.map +1 -0
  31. package/dist/connect/docx.cjs +12 -12
  32. package/dist/connect/index.cjs +108 -94
  33. package/dist/connect/index.cjs.map +1 -1
  34. package/dist/connect/viewer.cjs +5 -5
  35. package/dist/connection/auth/ConnectedSsoCallback.js +21 -5
  36. package/dist/connection/auth/ConnectedSsoCallback.js.map +2 -2
  37. package/dist/connection/docx/ConnectedNativeDocxEditor.js +39 -2
  38. package/dist/connection/docx/ConnectedNativeDocxEditor.js.map +2 -2
  39. package/dist/connection/runtime/ConnectedAppRuntime.js.map +1 -1
  40. package/dist/connection/runtime/useWelcomeDialog.d.ts +0 -2
  41. package/dist/connection/runtime/useWelcomeDialog.js +11 -20
  42. package/dist/connection/runtime/useWelcomeDialog.js.map +2 -2
  43. package/dist/connection/viewer/ConnectedDocumentViewer.js +43 -6
  44. package/dist/connection/viewer/ConnectedDocumentViewer.js.map +2 -2
  45. package/dist/docx/NativeDocxEditor.d.ts +12 -1
  46. package/dist/docx/NativeDocxEditor.js +513 -20
  47. package/dist/docx/NativeDocxEditor.js.map +3 -3
  48. package/dist/docx/index.cjs +38 -38
  49. package/dist/docx/recoveryStore.d.ts +8 -0
  50. package/dist/docx/recoveryStore.js +208 -0
  51. package/dist/docx/recoveryStore.js.map +7 -0
  52. package/dist/docx/temporaryRecovery.d.ts +8 -0
  53. package/dist/docx/temporaryRecovery.js +37 -0
  54. package/dist/docx/temporaryRecovery.js.map +7 -0
  55. package/dist/index.cjs +64 -64
  56. package/dist/shell/AccountBanners.d.ts +2 -7
  57. package/dist/shell/AccountBanners.js +9 -3
  58. package/dist/shell/AccountBanners.js.map +2 -2
  59. package/dist/shell/index.cjs +14 -14
  60. package/dist/styles.css +1 -1
  61. package/dist/workflow-canvas/index.cjs +9 -9
  62. package/node_modules/@arbidocs/coedit/package.json +1 -1
  63. package/package.json +5 -5
  64. package/src/connection/billing/project-purchase.css +2 -0
  65. package/src/docx/styles.css +37 -7
  66. package/dist/chunk-KWD5Q4XH.cjs +0 -18
  67. package/dist/chunk-T2DUNNYY.cjs.map +0 -1
  68. package/dist/chunk-UOZ237OW.cjs.map +0 -1
  69. package/dist/chunk-V6SFJ44C.cjs.map +0 -1
  70. package/dist/chunk-VCEX7COE.cjs.map +0 -1
@@ -18,6 +18,8 @@ var react = require('@docx-editor.dev/react');
18
18
  var shell = require('@arbidocs/react/shell');
19
19
  var lucideReact = require('lucide-react');
20
20
  var Y = require('yjs');
21
+ var encoding = require('@arbidocs/coedit/encoding');
22
+ var client = require('@arbidocs/client');
21
23
  var coedit = require('@arbidocs/coedit');
22
24
  var hocuspocus = require('@arbidocs/coedit/hocuspocus');
23
25
  var commands = require('@arbidocs/coedit/commands');
@@ -1429,6 +1431,242 @@ function DocxMentions({
1429
1431
  }
1430
1432
  ) });
1431
1433
  }
1434
+ var MAX_BYTES = 32 * 1024 * 1024;
1435
+ var MAX_COPIES = 10;
1436
+ var STORE = "checkpoints";
1437
+ function createRecoveryStore(identity, dbName = "arbi-docx-recovery") {
1438
+ const secret = identity.secretKey.slice(), publicKey = identity.publicKey.slice();
1439
+ let closed = false;
1440
+ let dbPromise;
1441
+ let pending = Promise.resolve();
1442
+ let pendingBytes = 0;
1443
+ const activeTransactions = /* @__PURE__ */ new Set();
1444
+ const sealer = client.createOfflineSealer("arbi-docx-recovery-v1", {
1445
+ locked: () => new Error("The recovery identity is locked."),
1446
+ keypair: async () => closed ? null : { publicKey: publicKey.slice(), secretKey: secret.slice() }
1447
+ });
1448
+ const ensureOpen = () => {
1449
+ if (closed) throw new Error("The recovery identity is closed.");
1450
+ };
1451
+ const open = () => {
1452
+ ensureOpen();
1453
+ if (!dbPromise)
1454
+ dbPromise = new Promise((resolve, reject) => {
1455
+ const request = indexedDB.open(dbName, 1);
1456
+ let settled = false;
1457
+ request.onupgradeneeded = () => {
1458
+ if (!request.result.objectStoreNames.contains(STORE))
1459
+ request.result.createObjectStore(STORE, { keyPath: "key" }).createIndex("scope", "scope");
1460
+ };
1461
+ request.onerror = () => {
1462
+ if (!settled) {
1463
+ settled = true;
1464
+ reject(request.error ?? new Error("Could not open recovery storage."));
1465
+ }
1466
+ };
1467
+ request.onblocked = () => {
1468
+ if (!settled) {
1469
+ settled = true;
1470
+ reject(new Error("Recovery storage is blocked by another tab."));
1471
+ }
1472
+ };
1473
+ request.onsuccess = () => {
1474
+ if (settled) {
1475
+ request.result.close();
1476
+ return;
1477
+ }
1478
+ settled = true;
1479
+ if (closed) {
1480
+ request.result.close();
1481
+ reject(new Error("The recovery identity is closed."));
1482
+ return;
1483
+ }
1484
+ request.result.onversionchange = () => {
1485
+ request.result.close();
1486
+ dbPromise = void 0;
1487
+ };
1488
+ resolve(request.result);
1489
+ };
1490
+ }).catch((error) => {
1491
+ dbPromise = void 0;
1492
+ throw error;
1493
+ });
1494
+ return dbPromise;
1495
+ };
1496
+ const scopeKey = async (workspace, document2) => {
1497
+ if (!workspace || !document2 || workspace.includes("\0") || document2.includes("\0"))
1498
+ throw new Error("Invalid recovery scope.");
1499
+ return sealer.blind(workspace, document2);
1500
+ };
1501
+ const validId = (id) => {
1502
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id))
1503
+ throw new Error("Invalid recovery copy id.");
1504
+ };
1505
+ const serial = (run2) => {
1506
+ const result = pending.catch(() => {
1507
+ }).then(run2);
1508
+ pending = result;
1509
+ return result;
1510
+ };
1511
+ const run = async (mode, action) => {
1512
+ const db = await open();
1513
+ ensureOpen();
1514
+ return new Promise((resolve, reject) => {
1515
+ const tx = db.transaction(STORE, mode), request = action(tx.objectStore(STORE));
1516
+ activeTransactions.add(tx);
1517
+ let value;
1518
+ request.onsuccess = () => {
1519
+ value = request.result;
1520
+ };
1521
+ request.onerror = () => reject(request.error ?? new Error("Recovery storage failed."));
1522
+ tx.oncomplete = () => {
1523
+ activeTransactions.delete(tx);
1524
+ resolve(value);
1525
+ };
1526
+ tx.onerror = () => {
1527
+ activeTransactions.delete(tx);
1528
+ reject(tx.error ?? new Error("Recovery storage failed."));
1529
+ };
1530
+ tx.onabort = () => {
1531
+ activeTransactions.delete(tx);
1532
+ reject(tx.error ?? new Error("Recovery storage was aborted."));
1533
+ };
1534
+ });
1535
+ };
1536
+ return {
1537
+ checkpoint(workspace, document2, bytes) {
1538
+ if (!bytes.length || bytes.length > MAX_BYTES)
1539
+ return Promise.reject(new Error("The recovery copy has an unsupported size."));
1540
+ if (closed) return Promise.reject(new Error("The recovery identity is closed."));
1541
+ if (pendingBytes + bytes.length > MAX_BYTES)
1542
+ return Promise.reject(
1543
+ new Error("Recovery storage is busy; keep the editor open and retry.")
1544
+ );
1545
+ pendingBytes += bytes.length;
1546
+ const copy = bytes.slice();
1547
+ return serial(async () => {
1548
+ ensureOpen();
1549
+ const scope = await scopeKey(workspace, document2), id = crypto.randomUUID();
1550
+ const key = await sealer.blind(workspace, document2, id), data = await sealer.sealBytes(copy);
1551
+ const db = await open();
1552
+ ensureOpen();
1553
+ await new Promise((resolve, reject) => {
1554
+ const tx = db.transaction(STORE, "readwrite"), store = tx.objectStore(STORE), count = store.index("scope").count(scope);
1555
+ activeTransactions.add(tx);
1556
+ let full = false;
1557
+ count.onsuccess = () => {
1558
+ if (count.result >= MAX_COPIES) {
1559
+ full = true;
1560
+ tx.abort();
1561
+ } else store.add({ key, scope, id, data });
1562
+ };
1563
+ tx.oncomplete = () => {
1564
+ activeTransactions.delete(tx);
1565
+ resolve();
1566
+ };
1567
+ tx.onerror = () => {
1568
+ activeTransactions.delete(tx);
1569
+ reject(tx.error ?? new Error("Recovery storage failed."));
1570
+ };
1571
+ tx.onabort = () => {
1572
+ activeTransactions.delete(tx);
1573
+ reject(
1574
+ full ? new Error("Recovery storage is full; export an existing copy before removing it.") : tx.error ?? new Error("Recovery storage was aborted.")
1575
+ );
1576
+ };
1577
+ });
1578
+ return id;
1579
+ }).finally(() => {
1580
+ pendingBytes -= copy.length;
1581
+ copy.fill(0);
1582
+ });
1583
+ },
1584
+ list(workspace, document2) {
1585
+ return serial(async () => {
1586
+ ensureOpen();
1587
+ const scope = await scopeKey(workspace, document2);
1588
+ const records = await run(
1589
+ "readonly",
1590
+ (store) => store.index("scope").getAll(scope)
1591
+ );
1592
+ for (const record of records) validId(record.id);
1593
+ return records.map((record) => record.id);
1594
+ });
1595
+ },
1596
+ load(workspace, document2, id) {
1597
+ return serial(async () => {
1598
+ ensureOpen();
1599
+ validId(id);
1600
+ await scopeKey(workspace, document2);
1601
+ const key = await sealer.blind(workspace, document2, id);
1602
+ const record = await run("readonly", (store) => store.get(key));
1603
+ if (!record) return void 0;
1604
+ const bytes = await sealer.openBytes(record.data);
1605
+ ensureOpen();
1606
+ return bytes;
1607
+ });
1608
+ },
1609
+ remove(workspace, document2, id) {
1610
+ return serial(async () => {
1611
+ ensureOpen();
1612
+ validId(id);
1613
+ await scopeKey(workspace, document2);
1614
+ const key = await sealer.blind(workspace, document2, id);
1615
+ await run("readwrite", (store) => store.delete(key));
1616
+ });
1617
+ },
1618
+ async close() {
1619
+ closed = true;
1620
+ for (const tx of activeTransactions) {
1621
+ try {
1622
+ tx.abort();
1623
+ } catch {
1624
+ }
1625
+ }
1626
+ await pending.catch(() => {
1627
+ });
1628
+ sealer.forget();
1629
+ secret.fill(0);
1630
+ const db = await dbPromise?.catch(() => void 0);
1631
+ db?.close();
1632
+ dbPromise = void 0;
1633
+ }
1634
+ };
1635
+ }
1636
+
1637
+ // src/docx/temporaryRecovery.ts
1638
+ function createTemporaryRecoveryStore(limit) {
1639
+ const copies = /* @__PURE__ */ new Map();
1640
+ let size = 0;
1641
+ return {
1642
+ get size() {
1643
+ return size;
1644
+ },
1645
+ add(scope, bytes) {
1646
+ if (size + bytes.length > limit) return false;
1647
+ const items = copies.get(scope) ?? [];
1648
+ items.push({ id: crypto.randomUUID(), bytes });
1649
+ copies.set(scope, items);
1650
+ size += bytes.length;
1651
+ return true;
1652
+ },
1653
+ list(scope) {
1654
+ return (copies.get(scope) ?? []).map((copy) => copy.id);
1655
+ },
1656
+ get(scope, id) {
1657
+ return copies.get(scope)?.find((copy) => copy.id === id)?.bytes;
1658
+ },
1659
+ remove(scope, id) {
1660
+ const items = copies.get(scope), index = items?.findIndex((copy) => copy.id === id) ?? -1;
1661
+ if (!items || index < 0) return false;
1662
+ const [removed] = items.splice(index, 1);
1663
+ size -= removed.bytes.length;
1664
+ removed.bytes.fill(0);
1665
+ if (!items.length) copies.delete(scope);
1666
+ return true;
1667
+ }
1668
+ };
1669
+ }
1432
1670
  var RELOADED_AT = "arbi-coedit-update-reload";
1433
1671
  var RELOAD_GAP_MS = 6e4;
1434
1672
  var RETRY_MS = 3e4;
@@ -4762,6 +5000,20 @@ function TableTabKeys({ scope }) {
4762
5000
  return null;
4763
5001
  }
4764
5002
  var drafts = /* @__PURE__ */ new Map();
5003
+ var pendingRecoveryWrites = /* @__PURE__ */ new Map();
5004
+ var failedRecoveryWrites = /* @__PURE__ */ new Set();
5005
+ var unretainedRecoveryFailures = /* @__PURE__ */ new Set();
5006
+ var MEMORY_RECOVERY_LIMIT = 32 * 1024 * 1024;
5007
+ var memoryRecovery = createTemporaryRecoveryStore(MEMORY_RECOVERY_LIMIT);
5008
+ var warnMemoryRecovery = (event) => event.preventDefault();
5009
+ var recoveryKey = (workspace, doc, key) => `${workspace}\0${doc}\0${Array.from(key, (b) => b.toString(16).padStart(2, "0")).join("")}`;
5010
+ var memoryKey = (scope, workspace, doc, key) => scope ? `scope\0${scope}\0${doc}` : recoveryKey(workspace, doc, key);
5011
+ function retainMemoryRecovery(key, bytes) {
5012
+ const empty = memoryRecovery.size === 0;
5013
+ if (!memoryRecovery.add(key, bytes)) return false;
5014
+ if (empty) window.addEventListener("beforeunload", warnMemoryRecovery);
5015
+ return true;
5016
+ }
4765
5017
  var stateBytes = (room) => Y__namespace.encodeStateAsUpdate(room.ydoc);
4766
5018
  var encodeState = (room) => {
4767
5019
  let binary = "";
@@ -4957,7 +5209,8 @@ function NativeDocxEditor({
4957
5209
  adapter,
4958
5210
  compact = false,
4959
5211
  stateRef,
4960
- saveRef
5212
+ saveRef,
5213
+ leaveRef
4961
5214
  }) {
4962
5215
  const [ready, setReady] = React4.useState(), [error, setError] = React4.useState(""), [retry, setRetry] = React4.useState(0);
4963
5216
  const [status, setStatus] = React4.useState("Connecting\u2026"), [dirty, setDirty] = React4.useState(false), [saving, setSaving] = React4.useState(false), [offline, setOffline] = React4.useState(false);
@@ -4968,6 +5221,30 @@ function NativeDocxEditor({
4968
5221
  const fitting = React4.useRef(true), fitted = React4.useRef(void 0);
4969
5222
  const [fitWidth, setFitWidth] = React4.useState(true), [zoomPercent, setZoomPercent] = React4.useState(100);
4970
5223
  const ref = React4.useRef(null), dirtyRef = React4.useRef(false), draftTimer = React4.useRef(void 0);
5224
+ const acknowledgedStateRef = React4.useRef(void 0);
5225
+ const [recoveryCopies, setRecoveryCopies] = React4.useState([]);
5226
+ const [memoryCopies, setMemoryCopies] = React4.useState([]);
5227
+ const [recoveryWarning, setRecoveryWarning] = React4.useState("");
5228
+ const recoveryRef = React4.useRef(null);
5229
+ const unmountRecoveryRef = React4.useRef(void 0);
5230
+ const checkpointedStateRef = React4.useRef(void 0);
5231
+ const proactiveTimerRef = React4.useRef(void 0);
5232
+ const proactiveCopyRef = React4.useRef(void 0);
5233
+ const proactiveGenerationRef = React4.useRef(0);
5234
+ const currentRecovery = async () => {
5235
+ if (adapter.recoveryIsCurrent && !adapter.recoveryIsCurrent())
5236
+ throw new Error("The signed-in recovery identity changed.");
5237
+ const saved = recoveryRef.current, identity = await adapter.recoveryIdentity?.();
5238
+ if (!identity) throw new Error("Recovery identity is unavailable.");
5239
+ if (!saved) {
5240
+ identity.keypair.secretKey.fill(0);
5241
+ throw new Error("Recovery identity is unavailable.");
5242
+ }
5243
+ const same = identity.workspaceId === saved.workspaceId && identity.keypair.publicKey.length === saved.publicKey.length && identity.keypair.publicKey.every((byte, index) => byte === saved.publicKey[index]);
5244
+ identity.keypair.secretKey.fill(0);
5245
+ if (!same) throw new Error("The signed-in recovery identity changed.");
5246
+ return saved;
5247
+ };
4971
5248
  const isDraft = draftContent !== void 0;
4972
5249
  const streamRef = React4.useRef(stream);
4973
5250
  streamRef.current = stream;
@@ -5006,6 +5283,7 @@ function NativeDocxEditor({
5006
5283
  React4.useEffect(() => () => clearTimeout(streamTimer.current), []);
5007
5284
  React4.useEffect(() => {
5008
5285
  let cancelled = false;
5286
+ let recoveryInvalidated = false;
5009
5287
  let room;
5010
5288
  const cleanups = [];
5011
5289
  setReady(void 0);
@@ -5013,6 +5291,92 @@ function NativeDocxEditor({
5013
5291
  setStatus("Connecting\u2026");
5014
5292
  setDirty(false);
5015
5293
  dirtyRef.current = false;
5294
+ setRecoveryCopies([]);
5295
+ setMemoryCopies([]);
5296
+ setRecoveryWarning("");
5297
+ acknowledgedStateRef.current = void 0;
5298
+ checkpointedStateRef.current = void 0;
5299
+ proactiveCopyRef.current = void 0;
5300
+ proactiveGenerationRef.current += 1;
5301
+ if (adapter.onRecoveryInvalidated)
5302
+ cleanups.push(
5303
+ adapter.onRecoveryInvalidated(() => {
5304
+ if (recoveryInvalidated) return;
5305
+ recoveryInvalidated = true;
5306
+ const recovery = recoveryRef.current;
5307
+ if (recovery) {
5308
+ try {
5309
+ if (!room || !flushInputRef.current) throw new Error("Editor input is unavailable");
5310
+ flushInputRef.current();
5311
+ runBeforeSave(ref.current);
5312
+ room.session.flushPendingJournals();
5313
+ const bytes = stateBytes(room), confirmed = acknowledgedStateRef.current, checkpointed = checkpointedStateRef.current;
5314
+ const same = (other) => !!other && other.length === bytes.length && other.every((byte, index) => byte === bytes[index]);
5315
+ if (!same(confirmed) && !same(checkpointed)) {
5316
+ const key = memoryKey(
5317
+ adapter.recoveryScope,
5318
+ recovery.workspaceId,
5319
+ documentId,
5320
+ recovery.publicKey
5321
+ );
5322
+ failedRecoveryWrites.add(
5323
+ recoveryKey(recovery.workspaceId, documentId, recovery.publicKey)
5324
+ );
5325
+ if (retainMemoryRecovery(key, bytes)) {
5326
+ checkpointedStateRef.current = bytes;
5327
+ adapter.notify?.(
5328
+ "A recovery copy is held only in this tab for the previous account or workspace.",
5329
+ "error"
5330
+ );
5331
+ } else {
5332
+ unretainedRecoveryFailures.add(
5333
+ recoveryKey(recovery.workspaceId, documentId, recovery.publicKey)
5334
+ );
5335
+ adapter.notify?.(
5336
+ "The temporary recovery buffer is full. Local changes could not be retained.",
5337
+ "error"
5338
+ );
5339
+ }
5340
+ }
5341
+ } catch {
5342
+ adapter.notify?.(
5343
+ "Local changes could not be prepared for account or workspace switching.",
5344
+ "error"
5345
+ );
5346
+ }
5347
+ recoveryRef.current = null;
5348
+ void recovery.store.close();
5349
+ } else if (room && flushInputRef.current && adapter.recoveryScope) {
5350
+ try {
5351
+ flushInputRef.current();
5352
+ runBeforeSave(ref.current);
5353
+ room.session.flushPendingJournals();
5354
+ const bytes = stateBytes(room), confirmed = acknowledgedStateRef.current;
5355
+ if (!confirmed || confirmed.length !== bytes.length || confirmed.some((byte, index) => byte !== bytes[index])) {
5356
+ const key = memoryKey(adapter.recoveryScope, "", documentId, new Uint8Array());
5357
+ if (retainMemoryRecovery(key, bytes)) {
5358
+ checkpointedStateRef.current = bytes;
5359
+ adapter.notify?.(
5360
+ "A recovery copy is held only in this tab for the previous account or workspace.",
5361
+ "error"
5362
+ );
5363
+ } else
5364
+ adapter.notify?.(
5365
+ "The temporary recovery buffer is full. Local changes could not be retained.",
5366
+ "error"
5367
+ );
5368
+ }
5369
+ } catch {
5370
+ adapter.notify?.(
5371
+ "Local changes could not be prepared for account or workspace switching.",
5372
+ "error"
5373
+ );
5374
+ }
5375
+ }
5376
+ setRecoveryCopies([]);
5377
+ setMemoryCopies([]);
5378
+ })
5379
+ );
5016
5380
  const updating = (reason) => {
5017
5381
  const cancel = awaitMatchingEditor(reason, () => setRetry((x) => x + 1));
5018
5382
  if (!cancel) return false;
@@ -5072,11 +5436,58 @@ function NativeDocxEditor({
5072
5436
  return;
5073
5437
  }
5074
5438
  const current = room;
5439
+ if (adapter.recoveryIdentity) {
5440
+ void adapter.recoveryIdentity().then(async (identity) => {
5441
+ if (!identity) return;
5442
+ const publicKey = identity.keypair.publicKey.slice(), store = createRecoveryStore(identity.keypair);
5443
+ identity.keypair.secretKey.fill(0);
5444
+ if (cancelled || recoveryInvalidated || adapter.recoveryIsCurrent && !adapter.recoveryIsCurrent()) {
5445
+ await store.close();
5446
+ return;
5447
+ }
5448
+ recoveryRef.current = { store, workspaceId: identity.workspaceId, publicKey };
5449
+ try {
5450
+ const key = recoveryKey(identity.workspaceId, documentId, publicKey);
5451
+ while (pendingRecoveryWrites.get(key)?.size)
5452
+ await Promise.all([...pendingRecoveryWrites.get(key)]);
5453
+ if (!cancelled)
5454
+ setMemoryCopies(
5455
+ memoryRecovery.list(
5456
+ memoryKey(adapter.recoveryScope, identity.workspaceId, documentId, publicKey)
5457
+ )
5458
+ );
5459
+ if (!cancelled && failedRecoveryWrites.has(key))
5460
+ setError(
5461
+ "A local recovery copy could not be saved. The prior editor was closed before storage succeeded."
5462
+ );
5463
+ const copies = await store.list(identity.workspaceId, documentId);
5464
+ if (!cancelled) setRecoveryCopies(copies);
5465
+ } catch {
5466
+ if (!cancelled)
5467
+ setRecoveryWarning(
5468
+ "Local recovery storage is unavailable. Download your DOCX before leaving if it has unsaved changes."
5469
+ );
5470
+ }
5471
+ }).catch(() => {
5472
+ if (!cancelled)
5473
+ setRecoveryWarning(
5474
+ "Local recovery storage is unavailable. Download your DOCX before leaving if it has unsaved changes."
5475
+ );
5476
+ });
5477
+ }
5478
+ acknowledgedStateRef.current = stateBytes(current);
5075
5479
  cleanups.push(
5076
5480
  current.session.subscribeStatus((s, _reason, detail) => {
5077
- const disconnected = s === "disconnected";
5481
+ const disconnected = s === "disconnected" || s === "error";
5078
5482
  setOffline(disconnected);
5079
5483
  if (s === "error") {
5484
+ if (coedit.formatRefusal(detail)) {
5485
+ setError(
5486
+ "The editor and collaboration server need matching versions. Download your DOCX before reloading to preserve any local edits."
5487
+ );
5488
+ setStatus("Update required");
5489
+ return;
5490
+ }
5080
5491
  if (updating(detail)) return;
5081
5492
  setError(
5082
5493
  detail || "The collaboration session failed. Export your local document before reconnecting."
@@ -5094,6 +5505,7 @@ function NativeDocxEditor({
5094
5505
  const message = JSON.parse(payload);
5095
5506
  if (message.type === "persisted") {
5096
5507
  if (!cancelled && message.vector && message.receipt && covered(current, message.vector, message.receipt)) {
5508
+ acknowledgedStateRef.current = stateBytes(current);
5097
5509
  dirtyRef.current = false;
5098
5510
  setDirty(false);
5099
5511
  setStatus("All changes saved");
@@ -5138,10 +5550,115 @@ function NativeDocxEditor({
5138
5550
  cancelled = true;
5139
5551
  cleanups.forEach((f) => f());
5140
5552
  clearTimeout(draftTimer.current);
5553
+ clearTimeout(proactiveTimerRef.current);
5141
5554
  fitCleanup.current?.();
5555
+ const recovery = recoveryRef.current;
5556
+ recoveryRef.current = null;
5557
+ if (recovery) {
5558
+ const pending = unmountRecoveryRef.current;
5559
+ unmountRecoveryRef.current = void 0;
5560
+ if (pending)
5561
+ void pending.then(
5562
+ () => recovery.store.close(),
5563
+ () => recovery.store.close()
5564
+ );
5565
+ else void recovery.store.close();
5566
+ }
5142
5567
  room?.destroy();
5143
5568
  };
5144
- }, [documentId, isDraft, snapshot, retry]);
5569
+ }, [documentId, isDraft, snapshot, retry, adapter.recoveryScope]);
5570
+ React4.useLayoutEffect(() => {
5571
+ const room = ready?.room;
5572
+ return () => {
5573
+ const recovery = recoveryRef.current;
5574
+ if (!room) return;
5575
+ try {
5576
+ if (!flushInputRef.current) throw new Error("Editor input is unavailable");
5577
+ flushInputRef.current();
5578
+ runBeforeSave(ref.current);
5579
+ room.session.flushPendingJournals();
5580
+ const bytes = stateBytes(room), confirmed = acknowledgedStateRef.current;
5581
+ if (confirmed && confirmed.length === bytes.length && confirmed.every((byte, index) => byte === bytes[index]))
5582
+ return;
5583
+ const checkpointed = checkpointedStateRef.current;
5584
+ if (checkpointed && checkpointed.length === bytes.length && checkpointed.every((byte, index) => byte === bytes[index]))
5585
+ return;
5586
+ if (!recovery) {
5587
+ if (!adapter.recoveryScope) throw new Error("Recovery identity is unavailable");
5588
+ const retained = retainMemoryRecovery(
5589
+ memoryKey(adapter.recoveryScope, "", documentId, new Uint8Array()),
5590
+ bytes
5591
+ );
5592
+ adapter.notify?.(
5593
+ retained ? "A recovery copy is held only in this tab. Reopen the document and download it." : "The temporary recovery buffer is full. Local changes could not be retained.",
5594
+ "error"
5595
+ );
5596
+ return;
5597
+ }
5598
+ const key = recoveryKey(recovery.workspaceId, documentId, recovery.publicKey);
5599
+ if (adapter.recoveryIsCurrent && !adapter.recoveryIsCurrent()) {
5600
+ failedRecoveryWrites.add(key);
5601
+ adapter.notify?.(
5602
+ retainMemoryRecovery(
5603
+ memoryKey(
5604
+ adapter.recoveryScope,
5605
+ recovery.workspaceId,
5606
+ documentId,
5607
+ recovery.publicKey
5608
+ ),
5609
+ bytes
5610
+ ) ? "A recovery copy is held only in this tab. Reopen the document and download it." : "The temporary recovery buffer is full. Local changes could not be retained.",
5611
+ "error"
5612
+ );
5613
+ return;
5614
+ }
5615
+ const writes = pendingRecoveryWrites.get(key) ?? /* @__PURE__ */ new Set();
5616
+ const pending = recovery.store.checkpoint(recovery.workspaceId, documentId, bytes).then(
5617
+ () => {
5618
+ },
5619
+ () => {
5620
+ failedRecoveryWrites.add(key);
5621
+ if (retainMemoryRecovery(
5622
+ memoryKey(
5623
+ adapter.recoveryScope,
5624
+ recovery.workspaceId,
5625
+ documentId,
5626
+ recovery.publicKey
5627
+ ),
5628
+ bytes
5629
+ )) {
5630
+ adapter.notify?.(
5631
+ "A recovery copy is held only in this tab. Reopen the document and download it.",
5632
+ "error"
5633
+ );
5634
+ } else {
5635
+ unretainedRecoveryFailures.add(key);
5636
+ adapter.notify?.(
5637
+ "Recovery storage and the temporary recovery buffer are full. Local changes could not be retained.",
5638
+ "error"
5639
+ );
5640
+ }
5641
+ }
5642
+ ).finally(() => {
5643
+ writes.delete(pending);
5644
+ if (!writes.size) pendingRecoveryWrites.delete(key);
5645
+ });
5646
+ writes.add(pending);
5647
+ pendingRecoveryWrites.set(key, writes);
5648
+ unmountRecoveryRef.current = pending;
5649
+ } catch {
5650
+ if (recovery) {
5651
+ const key = recoveryKey(recovery.workspaceId, documentId, recovery.publicKey);
5652
+ failedRecoveryWrites.add(key);
5653
+ unretainedRecoveryFailures.add(key);
5654
+ }
5655
+ adapter.notify?.(
5656
+ "A local recovery copy could not be prepared before the editor closed.",
5657
+ "error"
5658
+ );
5659
+ }
5660
+ };
5661
+ }, [ready?.room, documentId, adapter.recoveryScope]);
5145
5662
  React4.useEffect(() => {
5146
5663
  if (!stateRef) return;
5147
5664
  const room = ready?.room;
@@ -5150,6 +5667,43 @@ function NativeDocxEditor({
5150
5667
  stateRef.current = null;
5151
5668
  };
5152
5669
  }, [stateRef, ready?.room]);
5670
+ React4.useEffect(() => {
5671
+ if (!leaveRef) return;
5672
+ leaveRef.current = async () => {
5673
+ const room = ready?.room;
5674
+ if (!room) return "unchanged";
5675
+ try {
5676
+ if (!flushInputRef.current) throw new Error("Editor input is not ready.");
5677
+ flushInputRef.current();
5678
+ runBeforeSave(ref.current);
5679
+ room.session.flushPendingJournals();
5680
+ const bytes = stateBytes(room), confirmed = acknowledgedStateRef.current;
5681
+ if (confirmed && confirmed.length === bytes.length && confirmed.every((byte, index) => byte === bytes[index]))
5682
+ return "unchanged";
5683
+ const checkpointed = checkpointedStateRef.current;
5684
+ if (checkpointed && checkpointed.length === bytes.length && checkpointed.every((byte, index) => byte === bytes[index]))
5685
+ return "unchanged";
5686
+ const recovery = await currentRecovery();
5687
+ await recovery.store.checkpoint(recovery.workspaceId, documentId, bytes);
5688
+ await currentRecovery();
5689
+ flushInputRef.current();
5690
+ room.session.flushPendingJournals();
5691
+ const after = stateBytes(room);
5692
+ if (bytes.length !== after.length || bytes.some((byte, index) => byte !== after[index]))
5693
+ throw new Error("The document changed while preserving it; try again.");
5694
+ checkpointedStateRef.current = bytes;
5695
+ return "saved";
5696
+ } catch (error2) {
5697
+ setError(
5698
+ error2 instanceof Error ? `${error2.message} Keep this editor open or download your DOCX.` : "Recovery failed. Keep this editor open or download your DOCX."
5699
+ );
5700
+ return false;
5701
+ }
5702
+ };
5703
+ return () => {
5704
+ leaveRef.current = null;
5705
+ };
5706
+ }, [leaveRef, ready?.room, documentId, adapter]);
5153
5707
  React4.useEffect(() => {
5154
5708
  adapter.onDirtyChange?.(dirty);
5155
5709
  const beforeUnload = (e) => {
@@ -5176,6 +5730,89 @@ function NativeDocxEditor({
5176
5730
  a.click();
5177
5731
  setTimeout(() => URL.revokeObjectURL(url), 5e3);
5178
5732
  }
5733
+ async function downloadRecovery(id) {
5734
+ try {
5735
+ const recovery = await currentRecovery();
5736
+ const state = await recovery.store.load(recovery.workspaceId, documentId, id);
5737
+ if (!state) throw new Error("The recovery copy is unavailable.");
5738
+ await currentRecovery();
5739
+ const doc = new Y__namespace.Doc();
5740
+ try {
5741
+ Y__namespace.applyUpdate(doc, state);
5742
+ const url = URL.createObjectURL(
5743
+ new Blob([encoding.materializeBytes(doc)], {
5744
+ type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
5745
+ })
5746
+ );
5747
+ const a = document.createElement("a");
5748
+ a.href = url;
5749
+ a.download = title.replace(/\.[^.]+$/, "") + "-recovery.docx";
5750
+ a.click();
5751
+ setTimeout(() => URL.revokeObjectURL(url), 5e3);
5752
+ } finally {
5753
+ doc.destroy();
5754
+ }
5755
+ } catch (error2) {
5756
+ setError(error2 instanceof Error ? error2.message : "Could not open the recovery copy.");
5757
+ }
5758
+ }
5759
+ async function downloadMemoryRecovery(id) {
5760
+ try {
5761
+ const recovery = await currentRecovery(), key = memoryKey(adapter.recoveryScope, recovery.workspaceId, documentId, recovery.publicKey);
5762
+ const state = memoryRecovery.get(key, id);
5763
+ if (!state) throw new Error("The temporary recovery copy is unavailable.");
5764
+ const doc = new Y__namespace.Doc();
5765
+ try {
5766
+ Y__namespace.applyUpdate(doc, state);
5767
+ await currentRecovery();
5768
+ const url = URL.createObjectURL(
5769
+ new Blob([encoding.materializeBytes(doc)], {
5770
+ type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
5771
+ })
5772
+ );
5773
+ const a = document.createElement("a");
5774
+ a.href = url;
5775
+ a.download = title.replace(/\.[^.]+$/, "") + "-recovery.docx";
5776
+ a.click();
5777
+ setTimeout(() => URL.revokeObjectURL(url), 5e3);
5778
+ } finally {
5779
+ doc.destroy();
5780
+ }
5781
+ } catch (error2) {
5782
+ setError(
5783
+ error2 instanceof Error ? error2.message : "Could not open the temporary recovery copy."
5784
+ );
5785
+ }
5786
+ }
5787
+ async function removeMemoryRecovery(id) {
5788
+ if (!window.confirm("Delete this temporary recovery copy?")) return;
5789
+ try {
5790
+ const recovery = await currentRecovery(), key = memoryKey(adapter.recoveryScope, recovery.workspaceId, documentId, recovery.publicKey);
5791
+ if (!memoryRecovery.remove(key, id))
5792
+ throw new Error("The temporary recovery copy is unavailable.");
5793
+ const copies = memoryRecovery.list(key);
5794
+ const failureKey = recoveryKey(recovery.workspaceId, documentId, recovery.publicKey);
5795
+ if (!copies.length && !unretainedRecoveryFailures.has(failureKey))
5796
+ failedRecoveryWrites.delete(failureKey);
5797
+ if (memoryRecovery.size === 0) window.removeEventListener("beforeunload", warnMemoryRecovery);
5798
+ setMemoryCopies(copies);
5799
+ } catch (error2) {
5800
+ setError(
5801
+ error2 instanceof Error ? error2.message : "Could not remove the temporary recovery copy."
5802
+ );
5803
+ }
5804
+ }
5805
+ async function removeRecovery(id) {
5806
+ if (!window.confirm("Delete this local recovery copy?")) return;
5807
+ try {
5808
+ const recovery = await currentRecovery();
5809
+ await recovery.store.remove(recovery.workspaceId, documentId, id);
5810
+ await currentRecovery();
5811
+ setRecoveryCopies((copies) => copies.filter((copy) => copy !== id));
5812
+ } catch (error2) {
5813
+ setError(error2 instanceof Error ? error2.message : "Could not remove the recovery copy.");
5814
+ }
5815
+ }
5179
5816
  React4.useLayoutEffect(() => {
5180
5817
  const editor = ref.current;
5181
5818
  return () => {
@@ -5334,6 +5971,32 @@ function NativeDocxEditor({
5334
5971
  setStatus(
5335
5972
  isDraft ? "Unsaved note" : offline ? "Offline \xB7 edits buffered locally" : "Saving changes\u2026"
5336
5973
  );
5974
+ if (offline && ready?.room && adapter.recoveryIdentity) {
5975
+ clearTimeout(proactiveTimerRef.current);
5976
+ const room = ready.room;
5977
+ const generation = ++proactiveGenerationRef.current;
5978
+ proactiveTimerRef.current = setTimeout(() => {
5979
+ void (async () => {
5980
+ try {
5981
+ if (!flushInputRef.current) throw new Error("Editor input is unavailable.");
5982
+ flushInputRef.current();
5983
+ room.session.flushPendingJournals();
5984
+ const bytes = stateBytes(room), recovery = await currentRecovery();
5985
+ const id = await recovery.store.checkpoint(recovery.workspaceId, documentId, bytes);
5986
+ await currentRecovery();
5987
+ if (generation !== proactiveGenerationRef.current) return;
5988
+ const previous = proactiveCopyRef.current;
5989
+ proactiveCopyRef.current = id;
5990
+ checkpointedStateRef.current = bytes;
5991
+ if (previous) await recovery.store.remove(recovery.workspaceId, documentId, previous);
5992
+ } catch {
5993
+ setError(
5994
+ "A local recovery copy could not be saved. Keep this editor open or download your DOCX."
5995
+ );
5996
+ }
5997
+ })();
5998
+ }, 750);
5999
+ }
5337
6000
  if (isDraft) {
5338
6001
  clearTimeout(draftTimer.current);
5339
6002
  draftTimer.current = setTimeout(() => {
@@ -5351,22 +6014,83 @@ function NativeDocxEditor({
5351
6014
  "aria-busy": !!stream?.busy,
5352
6015
  "data-generation-state": stream ? stream.busy ? "generating" : stream.error ? "stopped" : "generated" : "ready",
5353
6016
  children: [
5354
- offline && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "native-docx-notice", children: "Changes are buffered in this browser. Keep this tab open until the connection returns, or download your DOCX." }),
5355
- error && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "native-docx-notice", "data-error": "true", role: "alert", children: [
5356
- error,
5357
- " ",
5358
- /* @__PURE__ */ jsxRuntime.jsxs(
5359
- "button",
5360
- {
5361
- disabled: !stream && dirty,
5362
- title: dirty ? "Download your unsaved DOCX before reopening the editor" : void 0,
5363
- onClick: () => stream ? (setError(""), setStreamAttempt((x) => x + 1)) : setRetry((x) => x + 1),
5364
- children: [
5365
- /* @__PURE__ */ jsxRuntime.jsx(lucideReact.RefreshCw, { size: 12 }),
5366
- "Retry"
5367
- ]
5368
- }
5369
- )
6017
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "native-docx-notice-stack", children: [
6018
+ recoveryWarning && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "native-docx-notice", role: "status", children: recoveryWarning }),
6019
+ recoveryCopies.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "native-docx-notice", role: "status", children: [
6020
+ "Local recovery ",
6021
+ recoveryCopies.length === 1 ? "copy" : "copies",
6022
+ " available.",
6023
+ " ",
6024
+ recoveryCopies.map((id, index) => /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
6025
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { onClick: () => void downloadRecovery(id), children: [
6026
+ "Download recovery copy ",
6027
+ index + 1
6028
+ ] }),
6029
+ " ",
6030
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { onClick: () => void removeRecovery(id), children: [
6031
+ "Delete recovery copy ",
6032
+ index + 1
6033
+ ] }),
6034
+ " "
6035
+ ] }, id))
6036
+ ] }),
6037
+ memoryCopies.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "native-docx-notice", role: "status", children: [
6038
+ "Recovery copies held only in this tab will be lost when it closes.",
6039
+ " ",
6040
+ memoryCopies.map((id, index) => /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
6041
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { onClick: () => void downloadMemoryRecovery(id), children: [
6042
+ "Download temporary recovery copy ",
6043
+ index + 1
6044
+ ] }),
6045
+ " ",
6046
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { onClick: () => void removeMemoryRecovery(id), children: [
6047
+ "Delete temporary recovery copy ",
6048
+ index + 1
6049
+ ] }),
6050
+ " "
6051
+ ] }, id))
6052
+ ] }),
6053
+ offline && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "native-docx-notice", children: "Changes are buffered in this browser. Keep this tab open until the connection returns, or download your DOCX." }),
6054
+ error && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "native-docx-notice", "data-error": "true", role: "alert", children: [
6055
+ error,
6056
+ " ",
6057
+ compact && ready && /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: () => void exportDocument(), children: "Download DOCX" }),
6058
+ " ",
6059
+ /* @__PURE__ */ jsxRuntime.jsxs(
6060
+ "button",
6061
+ {
6062
+ disabled: !stream && dirty,
6063
+ title: dirty ? "Download this document before reopening the editor" : void 0,
6064
+ onClick: () => {
6065
+ if (stream) {
6066
+ setError("");
6067
+ setStreamAttempt((x) => x + 1);
6068
+ return;
6069
+ }
6070
+ if (ready?.room) {
6071
+ try {
6072
+ if (!flushInputRef.current) throw new Error("Editor input is not available");
6073
+ flushInputRef.current();
6074
+ ready.room.session.flushPendingJournals();
6075
+ const previous = acknowledgedStateRef.current, current = stateBytes(ready.room);
6076
+ if (!previous || previous.length !== current.length || previous.some((byte, index) => byte !== current[index]))
6077
+ throw new Error("Room has unconfirmed changes");
6078
+ } catch {
6079
+ setError(
6080
+ "This document has changes that are not confirmed saved. Download your DOCX before reloading."
6081
+ );
6082
+ return;
6083
+ }
6084
+ }
6085
+ setRetry((x) => x + 1);
6086
+ },
6087
+ children: [
6088
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.RefreshCw, { size: 12 }),
6089
+ "Retry"
6090
+ ]
6091
+ }
6092
+ )
6093
+ ] })
5370
6094
  ] }),
5371
6095
  !ready && !error && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "native-docx-error", role: "status", children: "Opening Word document\u2026" }),
5372
6096
  ready && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "native-docx-body docx-editor", children: /* @__PURE__ */ jsxRuntime.jsx(EditorBoundary, { children: /* @__PURE__ */ jsxRuntime.jsx(
@@ -5611,5 +6335,5 @@ exports.useDefinedTerms = useDefinedTerms;
5611
6335
  exports.useReview = useReview;
5612
6336
  exports.useReviewItem = useReviewItem;
5613
6337
  exports.withDirectEditing = withDirectEditing;
5614
- //# sourceMappingURL=chunk-T2DUNNYY.cjs.map
5615
- //# sourceMappingURL=chunk-T2DUNNYY.cjs.map
6338
+ //# sourceMappingURL=chunk-C6DF6WB2.cjs.map
6339
+ //# sourceMappingURL=chunk-C6DF6WB2.cjs.map