@rowsncolumns/y-spreadsheet 17.1.1 → 17.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.
@@ -120,6 +120,17 @@ var useYSpreadsheetV2 = function (_a) {
120
120
  var isV5Doc = (0, react_1.useCallback)(function () {
121
121
  return sheetDataVersion === "v5" || yDocMeta.getAttr("sheetDataVersion") === "v5";
122
122
  }, [sheetDataVersion, yDocMeta]);
123
+ // Final format (`docMeta.sheetDataVersion = "v6"`): the engine's. This hook
124
+ // would read it as an empty positional sheet, so its load and its writes
125
+ // refuse it (`FinalFormatError`) and its observers leave the state as it is.
126
+ // Read live: the stamp may arrive with a sync. A host checks
127
+ // `docIsFinalFormat` and opens such a doc through the engine instead.
128
+ // A doc stamped with a format this package does not know is refused the same
129
+ // way (`UnknownFormatError`): the engine alone decides what such a doc holds.
130
+ var isFinalDoc = (0, react_1.useCallback)(function () {
131
+ var format = (0, helpers_1.sheetDataFormatOf)(doc);
132
+ return format === "v6" || format === "unknown";
133
+ }, [doc]);
123
134
  // V5: the composed style plane, folded on a full read and on a remote style
124
135
  // change, updated in place by this hook's own writes
125
136
  var stylesV5Ref = (0, react_1.useRef)(null);
@@ -269,6 +280,8 @@ var useYSpreadsheetV2 = function (_a) {
269
280
  // Trigger cell recalcs
270
281
  var syncRecalcCells = (0, react_1.useCallback)(function (recalcCells, origin) {
271
282
  var e_2, _a;
283
+ if (isFinalDoc())
284
+ return;
272
285
  var readV5 = isV5Doc() ? (0, helpers_1.createCellReaderV5)(doc, stylesV5()) : null;
273
286
  try {
274
287
  for (var recalcCells_1 = tslib_1.__values(recalcCells), recalcCells_1_1 = recalcCells_1.next(); !recalcCells_1_1.done; recalcCells_1_1 = recalcCells_1.next()) {
@@ -350,6 +363,7 @@ var useYSpreadsheetV2 = function (_a) {
350
363
  useV3,
351
364
  reevaluateDerivationsForCells,
352
365
  isV5Doc,
366
+ isFinalDoc,
353
367
  doc,
354
368
  stylesV5,
355
369
  ]);
@@ -357,6 +371,8 @@ var useYSpreadsheetV2 = function (_a) {
357
371
  var setupInitialSync = (0, react_1.useCallback)(function () {
358
372
  var e_3, _a;
359
373
  var _b;
374
+ // Before the migrations below write anything.
375
+ (0, helpers_1.refuseEngineOwnedFormat)(doc);
360
376
  // Migration from sharedStrings (Array) to sharedStringsMap (Map) is disabled.
361
377
  // Both formats are now supported simultaneously via handleSharedStringsMapChange
362
378
  // and handleSharedStringsArrayChange callbacks.
@@ -493,6 +509,7 @@ var useYSpreadsheetV2 = function (_a) {
493
509
  onMigrationComplete,
494
510
  deleteV2AfterMigration,
495
511
  isV5Doc,
512
+ isFinalDoc,
496
513
  readSheetDataV5,
497
514
  yjs,
498
515
  ]);
@@ -504,6 +521,8 @@ var useYSpreadsheetV2 = function (_a) {
504
521
  * the backlog at all.
505
522
  */
506
523
  var drainBacklog = (0, react_1.useCallback)(function () {
524
+ if (isFinalDoc())
525
+ return;
507
526
  var backlog = getBacklog();
508
527
  if (!backlog.length)
509
528
  return;
@@ -513,7 +532,7 @@ var useYSpreadsheetV2 = function (_a) {
513
532
  (0, ynodes_1.listDelete)(yRecalcCells, 0, yRecalcCells.length);
514
533
  }, origin);
515
534
  }
516
- }, [getBacklog, syncRecalcCells, doc, yRecalcCells]);
535
+ }, [getBacklog, syncRecalcCells, doc, yRecalcCells, isFinalDoc]);
517
536
  // Synced
518
537
  var onSynced = (0, react_1.useCallback)(function () {
519
538
  if (!synced) {
@@ -589,7 +608,7 @@ var useYSpreadsheetV2 = function (_a) {
589
608
  * This is to prevent yjs from observing sheetdata
590
609
  * and updating it, which is not necessary
591
610
  */
592
- if (events.length) {
611
+ if (events.length && !isFinalDoc()) {
593
612
  var origin_1 = (_b = (_a = events === null || events === void 0 ? void 0 : events[0]) === null || _a === void 0 ? void 0 : _a.event.transaction) === null || _b === void 0 ? void 0 : _b.origin;
594
613
  if (origin_1 !== "local" || observesLocal()) {
595
614
  // Convert Y.js events to SheetDataEvent format and apply incremental updates
@@ -605,13 +624,16 @@ var useYSpreadsheetV2 = function (_a) {
605
624
  return function () {
606
625
  subscription.unsubscribe();
607
626
  };
608
- }, [onChangeSheetData, ySheetDataV2, useV3, yjs, observesLocal]);
627
+ }, [onChangeSheetData, ySheetDataV2, useV3, yjs, observesLocal, isFinalDoc]);
609
628
  // Only for sheet Data (V3 mode)
610
629
  (0, ui_1.useIsomorphicLayoutEffect)(function () {
611
630
  if (!useV3)
612
631
  return; // Skip V3 observer in V2 mode
613
632
  // Subscribe to V3 sheet data (flat Map)
614
633
  var callback = function (event) {
634
+ // The transaction that stamps a doc final empties `sheetDataV3`.
635
+ if (isFinalDoc())
636
+ return;
615
637
  if (event.transaction.origin !== "local" ||
616
638
  observesLocal()) {
617
639
  // Extract changes synchronously - they are read from the document as
@@ -619,6 +641,9 @@ var useYSpreadsheetV2 = function (_a) {
619
641
  var changedKeys_1 = (0, ynodes_1.changedKeys)(event);
620
642
  // Now we can safely use the extracted data in the async setState callback
621
643
  onChangeSheetData(function (prevSheetData) {
644
+ // The stamp may have arrived between the event and this update.
645
+ if (isFinalDoc())
646
+ return prevSheetData;
622
647
  var result = (0, helpers_1.processSheetDataEventsV3)(changedKeys_1, prevSheetData, ySheetDataV3);
623
648
  if (result) {
624
649
  return result;
@@ -634,7 +659,7 @@ var useYSpreadsheetV2 = function (_a) {
634
659
  return function () {
635
660
  ySheetDataV3.unobserve(callback);
636
661
  };
637
- }, [onChangeSheetData, ySheetDataV3, useV3, yjs, observesLocal]);
662
+ }, [onChangeSheetData, ySheetDataV3, useV3, yjs, observesLocal, isFinalDoc]);
638
663
  // Only for sheet Data (V5 docs): `rncCells`, `rncNotes`, the style planes,
639
664
  // the cold blocks and every sheet's id arrays. A change of an id array, a
640
665
  // style plane, a cold block (or of `docMeta`): full re-read; a cell or note change alone is applied
@@ -644,7 +669,8 @@ var useYSpreadsheetV2 = function (_a) {
644
669
  var callback = function (transaction) {
645
670
  var e_6, _a;
646
671
  if ((transaction.origin === "local" && !observesLocal()) ||
647
- !isV5Doc())
672
+ !isV5Doc() ||
673
+ isFinalDoc())
648
674
  return;
649
675
  var full = false;
650
676
  var cellKeys = [];
@@ -688,7 +714,7 @@ var useYSpreadsheetV2 = function (_a) {
688
714
  return function () {
689
715
  doc.off("afterTransaction", callback);
690
716
  };
691
- }, [doc, onChangeSheetData, isV5Doc, readSheetDataV5, stylesV5, observesLocal]);
717
+ }, [doc, onChangeSheetData, isV5Doc, isFinalDoc, readSheetDataV5, stylesV5, observesLocal]);
692
718
  // CellXfs
693
719
  (0, ui_1.useIsomorphicLayoutEffect)(function () {
694
720
  // Subscribe to sheet data
@@ -817,6 +843,7 @@ var useYSpreadsheetV2 = function (_a) {
817
843
  }, [syncRecalcCells, recalcCellsMaxEntries, synced, yRecalcCells, observesLocal]);
818
844
  // Broadcast patch
819
845
  var onBroadcastPatch = (0, react_1.useCallback)(function (patches) {
846
+ (0, helpers_1.refuseEngineOwnedFormat)(doc);
820
847
  // Ignore push flag
821
848
  var disableRecalc = Boolean(patches.find(function (_a) {
822
849
  var _b = tslib_1.__read(_a, 1), patch = _b[0];
@@ -1018,6 +1045,7 @@ var useYSpreadsheetV2 = function (_a) {
1018
1045
  recalcCellsMaxEntries,
1019
1046
  useV3,
1020
1047
  isV5Doc,
1048
+ isFinalDoc,
1021
1049
  stylesV5,
1022
1050
  ]);
1023
1051
  // Listen to active cell change
@@ -35,6 +35,8 @@ export type useYSpreadsheetProps<T extends CellData, S extends Sheet, C extends
35
35
  /**
36
36
  * Connects to a Y server and picks up the most recent change
37
37
  * Does not load initial data
38
+ * A doc stamped final (`docMeta.sheetDataVersion` "v6", `docIsFinalFormat`) is
39
+ * refused (`FinalFormatError`): open it through the engine.
38
40
  * @returns
39
41
  */
40
42
  export declare const useYSpreadsheet: <T extends CellData, S extends Sheet, C extends EmbeddedChart, O extends EmbeddedObject>({ onChangeSheetData, onChangeSheets, onChangeTables, onChangeCharts, onChangeEmbeds, onChangeConditionalFormats, onChangeDataValidations, onChangeNamedRanges, onChangeProtectedRanges, onError, enqueueCalculation, calculateNow, userId, title, sheetId, activeCell, doc, provider, yjs: yjsRuntime, }: useYSpreadsheetProps<T, S, C, O>) => {
@@ -1 +1 @@
1
- {"version":3,"file":"use-yspreadsheet.d.ts","sourceRoot":"","sources":["../../use-yspreadsheet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,qBAAqB,EACrB,wBAAwB,EACxB,aAAa,EACb,cAAc,EACd,UAAU,EACV,cAAc,EACd,KAAK,EACL,SAAS,EACV,MAAM,2BAA2B,CAAC;AAKnC,OAAO,KAAK,EACV,mBAAmB,EACnB,oBAAoB,EACpB,WAAW,EAEX,SAAS,EACT,gBAAgB,EACjB,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAKnC,OAAO,KAAK,EACV,kBAAkB,EAGlB,IAAI,EAEJ,UAAU,EAEX,MAAM,SAAS,CAAC;AAkBjB,MAAM,MAAM,oBAAoB,CAC9B,CAAC,SAAS,QAAQ,EAClB,CAAC,SAAS,KAAK,EACf,CAAC,SAAS,aAAa,EACvB,CAAC,SAAS,cAAc,IACtB;IACF,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,aAAa,CAAC;IAC3B,QAAQ,CAAC,EAAE,kBAAkB,GAAG,kBAAkB,GAAG,GAAG,CAAC;IACzD,wEAAwE;IACxE,GAAG,EAAE,IAAI,CAAC;IACV;;;;OAIG;IACH,GAAG,CAAC,EAAE,UAAU,CAAC;IACjB,YAAY,CAAC,OAAO,CAAC,EAAE,mBAAmB,GAAG,IAAI,CA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;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAC1B,CAAC,SAAS,QAAQ,EAClB,CAAC,SAAS,KAAK,EACf,CAAC,SAAS,aAAa,EACvB,CAAC,SAAS,cAAc,EACxB,0SAoBC,oBAAoB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;gCA0RpB,CACP,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC,EAC9B,IAAI,CAAC,EAAE,WAAW,GAAG,SAAS,CAC/B,EAAE;;;CAyDR,CAAC"}
@@ -6,6 +6,7 @@ var spreadsheet_1 = require("@rowsncolumns/spreadsheet");
6
6
  var immer_1 = require("immer");
7
7
  var uniqBy_1 = tslib_1.__importDefault(require("lodash/uniqBy"));
8
8
  var react_1 = require("react");
9
+ var helpers_v5_1 = require("./helpers-v5");
9
10
  var yjs_runtime_1 = require("./yjs-runtime");
10
11
  var ynodes_1 = require("./ynodes");
11
12
  var getStateVector = function (doc, yjs) {
@@ -20,6 +21,8 @@ var getUpdatesBetween = function (doc, stateVector1, stateVector2, yjs) {
20
21
  /**
21
22
  * Connects to a Y server and picks up the most recent change
22
23
  * Does not load initial data
24
+ * A doc stamped final (`docMeta.sheetDataVersion` "v6", `docIsFinalFormat`) is
25
+ * refused (`FinalFormatError`): open it through the engine.
23
26
  * @returns
24
27
  */
25
28
  var useYSpreadsheet = function (_a) {
@@ -29,6 +32,18 @@ var useYSpreadsheet = function (_a) {
29
32
  var _c = tslib_1.__read((0, react_1.useState)(false), 2), synced = _c[0], setSynced = _c[1];
30
33
  var previousStateVectorRef = (0, react_1.useRef)(undefined);
31
34
  var currentStateVectorRef = (0, react_1.useRef)(undefined);
35
+ // Final format (`docMeta.sheetDataVersion = "v6"`): the engine's. This hook
36
+ // keeps patch lists in roots such a doc uses otherwise (`sheets` is its sheet
37
+ // list), so its load and its writes refuse it (`FinalFormatError`) and its
38
+ // observers leave the state as it is. Read live: the stamp may arrive with a
39
+ // sync. A host checks `docIsFinalFormat` and opens such a doc through the
40
+ // engine instead.
41
+ // A doc stamped with a format this package does not know is refused the same
42
+ // way (`UnknownFormatError`): the engine alone decides what such a doc holds.
43
+ var isFinalDoc = (0, react_1.useCallback)(function () {
44
+ var format = (0, helpers_v5_1.sheetDataFormatOf)(doc);
45
+ return format === "v6" || format === "unknown";
46
+ }, [doc]);
32
47
  // Recalc cells
33
48
  var yRecalcCells = (0, react_1.useMemo)(function () { return doc.get("recalcCells"); }, [doc]);
34
49
  var yDisableRecalc = doc.get("disableRecalc");
@@ -76,6 +91,7 @@ var useYSpreadsheet = function (_a) {
76
91
  var onSynced = (0, react_1.useCallback)(function () {
77
92
  var e_1, _a;
78
93
  var _b;
94
+ (0, helpers_v5_1.refuseEngineOwnedFormat)(doc);
79
95
  var syncedDoc = doc;
80
96
  if (previousStateVectorRef.current) {
81
97
  // Capture the current state vector on subsequent syncs
@@ -152,7 +168,7 @@ var useYSpreadsheet = function (_a) {
152
168
  });
153
169
  // Set synced
154
170
  setSynced(true);
155
- }, [calculateNow, docMap, onError, doc, yjs]);
171
+ }, [calculateNow, docMap, onError, doc, yjs, isFinalDoc]);
156
172
  // Sync state
157
173
  if ((provider === null || provider === void 0 ? void 0 : provider.synced) && !synced) {
158
174
  onSynced();
@@ -271,6 +287,8 @@ var useYSpreadsheet = function (_a) {
271
287
  };
272
288
  // Trigger cell recalcs
273
289
  var onRecalcCellsChange = function (event) {
290
+ if (isFinalDoc())
291
+ return;
274
292
  var patches = getPatchDeltasFromEvent(event);
275
293
  if (event.transaction.origin !== "local") {
276
294
  syncRecalcCells(patches);
@@ -281,6 +299,8 @@ var useYSpreadsheet = function (_a) {
281
299
  var subs_1 = [];
282
300
  var _loop_2 = function (_4, doc_1, setStateFn) {
283
301
  var callback = function (event) {
302
+ if (isFinalDoc())
303
+ return;
284
304
  var patches = getPatchDeltasFromEvent(event);
285
305
  var disableRecalc = yDisableRecalc.getAttr("disableRecalc");
286
306
  if (event.transaction.origin !== "local" && disableRecalc !== true) {
@@ -324,9 +344,10 @@ var useYSpreadsheet = function (_a) {
324
344
  yRecalcCells.unobserve(onRecalcCellsChange);
325
345
  };
326
346
  }
327
- }, [userId, provider, synced, doc, yDisableRecalc]);
347
+ }, [userId, provider, synced, doc, yDisableRecalc, isFinalDoc]);
328
348
  // Broadcast patch
329
349
  var onBroadcastPatch = (0, react_1.useCallback)(function (patches) {
350
+ (0, helpers_v5_1.refuseEngineOwnedFormat)(doc);
330
351
  doc.transact(function () {
331
352
  var e_8, _a, e_9, _b;
332
353
  var _c, _d;
@@ -377,7 +398,7 @@ var useYSpreadsheet = function (_a) {
377
398
  finally { if (e_8) throw e_8.error; }
378
399
  }
379
400
  }, "local");
380
- }, [userId, docMap, doc, yRecalcCells, yDisableRecalc]);
401
+ }, [userId, docMap, doc, yRecalcCells, yDisableRecalc, isFinalDoc]);
381
402
  // Listen to active cell change
382
403
  (0, spreadsheet_1.useIsomorphicLayoutEffect)(function () {
383
404
  if (activeCell) {
@@ -10,6 +10,66 @@ export type ParsedCellKeyV5 = {
10
10
  };
11
11
  /** The composed style plane: cell key → format (`StyleOverlay`). */
12
12
  export type StyleOverlayV5 = Map<string, CellFormat>;
13
+ /**
14
+ * Whether the doc is a final room (`doc_is_final` in rnc-yrs-store-v3): it
15
+ * holds the final format's key, whatever its stamp and marker read now, or,
16
+ * holding no format key, is stamped `docMeta.sheetDataVersion = "v6"`. Only
17
+ * the engine reads and writes such a doc: a host checks this before it calls
18
+ * into this package, and opens the doc through the engine when it is true.
19
+ * Read from the doc each time (the key and the stamp can arrive with a sync);
20
+ * creates no root.
21
+ */
22
+ export declare const docIsFinalFormat: (doc: YDoc) => boolean;
23
+ /** What every reader and writer of this package throws on a final doc. */
24
+ export declare class FinalFormatError extends Error {
25
+ constructor();
26
+ }
27
+ /**
28
+ * What a doc's data plane is, judged as the engine judges it (`data_format`
29
+ * in rnc-yrs-store-v3 `stable_ids_guard`): by its format keys when one was
30
+ * ever written, else by its stamp, matched exactly.
31
+ *
32
+ * - the next format's key (`sheetDataV3["v7"]`) was ever written: `"unknown"`,
33
+ * with or without the final key beside it;
34
+ * - the final key (`sheetDataV3["v6"]`) was ever written: `"v6"`, whatever the
35
+ * stamp reads (an entry that never saw the room can outrank the stamp, a
36
+ * later write replace it, a removal take it away; the item under a map key
37
+ * cannot be unwritten);
38
+ * - neither: `"positional"` for no stamp, `"v2"`, `"v3"` or the retired
39
+ * `"v4"`; `"v5"`; `"v6"` (the final format); `"unknown"` for anything else
40
+ * (`"v7"`, `"v1"`, `"V6"`, `"v6 "`, `"6"`, `""`, `null`, a number).
41
+ *
42
+ * Creates no root.
43
+ */
44
+ export declare const sheetDataFormatOf: (doc: YDoc) => "positional" | "v5" | "v6" | "unknown";
45
+ /**
46
+ * What every reader and writer of this package throws on a doc of a data
47
+ * format it does not know (`sheetDataFormatOf(doc) === "unknown"`: by the key
48
+ * of a later format, or by its stamp): what such a doc holds is not this
49
+ * package's to read, and nothing may be written into it.
50
+ */
51
+ export declare class UnknownFormatError extends Error {
52
+ constructor();
53
+ }
54
+ /**
55
+ * What a positional writer of this package throws on a doc whose
56
+ * `sheet-format.cells` is past 2: a cell format newer than the envelopes and
57
+ * node cells it writes (the positional store refuses the same room,
58
+ * `unsupported-cell-format`).
59
+ */
60
+ export declare class NewerCellFormatError extends Error {
61
+ constructor();
62
+ }
63
+ /**
64
+ * Throws on a doc only the engine reads and writes: `FinalFormatError` for a
65
+ * final doc, `UnknownFormatError` for a format this package does not know.
66
+ */
67
+ export declare const refuseEngineOwnedFormat: (doc: YDoc) => void;
68
+ /**
69
+ * `refuseEngineOwnedFormat`, and `NewerCellFormatError` on a doc whose
70
+ * `sheet-format.cells` is past 2: for the writers of the positional plane.
71
+ */
72
+ export declare const refusePositionalWrite: (doc: YDoc) => void;
13
73
  /**
14
74
  * A sheet's line ids in grid order (position = index + 1), as decimal strings.
15
75
  * Later duplicates and non-id values are skipped, as the engine's index does.
@@ -1 +1 @@
1
- {"version":3,"file":"helpers-v5.d.ts","source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OAAc,EACtB,SAAS,cAAc,SA+CxB,CAAC;AAEF,8DAA8D;AAC9D,eAAO,MAAM,SAAS,GACpB,KAAK,IAAI,EACT,SAAS,MAAM,EACf,UAAU,MAAM,EAChB,aAAa,MAAM,EACnB,OAAO,QAAQ,KACd,IAGC,CAAC;AAEL,iEAAiE;AACjE,eAAO,MAAM,YAAY,GACvB,KAAK,IAAI,EACT,SAAS,MAAM,EACf,UAAU,MAAM,EAChB,aAAa,MAAM,KAClB,IAGC,CAAC;AAEL,kFAAkF;AAClF,eAAO,MAAM,aAAa,GAAI,KAAK,IAAI,EAAE,SAAS,MAAM,KAAG,IACM,CAAC"}
@@ -25,6 +25,13 @@
25
25
  // read, so a stored `ue.fv` may name cells the formula no longer reads. This
26
26
  // module reads `ue.fv` as stored: every reader and writer here refuses such a
27
27
  // doc (`V5FormulaTextOnReadError`); read it through the engine.
28
+ // A final doc (one that holds the final format's key, `sheetDataV3["v6"]`,
29
+ // whatever its stamp reads now; or, holding no format key, is stamped
30
+ // `docMeta.sheetDataVersion = "v6"`) holds node cells and may hold id runs in
31
+ // its line-id arrays, neither of which this module reads: every reader and
32
+ // writer here refuses it (`FinalFormatError`), and so do the positional entry
33
+ // points of this package, which would read it as an empty sheet. A host checks
34
+ // `docIsFinalFormat` first and opens it through the engine.
28
35
  import { getCellUserEnteredFormat } from "@rowsncolumns/utils";
29
36
  import { inflateSync } from "fflate";
30
37
  import * as decoding from "lib0/decoding";
@@ -45,6 +52,12 @@ const BLOCK_V2_MAGIC = 0x80000000; // BLOCK_V2_MAGIC
45
52
  const BLOCK_V2_DENSE = 0x40000000; // BLOCK_V2_DENSE
46
53
  const MAX_BLOCK_RAW_BYTES = 512 * 1024 * 1024; // MAX_BLOCK_RAW_BYTES
47
54
  const STYLE_LOG_V1 = 1; // STYLE_LOG_V1
55
+ const DOC_META = "docMeta"; // DOC_META
56
+ const SHEET_DATA_VERSION = "sheetDataVersion"; // SHEET_DATA_VERSION
57
+ const FINAL_STABLE_IDS_VERSION = "v6"; // rnc-yrs-store-v3 stable_ids_guard::FINAL_STABLE_IDS_VERSION
58
+ const POSITIONAL_CELLS_ROOT = "sheetDataV3"; // rnc-yrs-store-v3 stable_ids_guard::POSITIONAL_CELLS_ROOT
59
+ const FINAL_INERT_KEY = "v6"; // rnc-yrs-store-v3 stable_ids_guard::FINAL_INERT_KEY
60
+ const NEXT_FORMAT_KEY = "v7"; // rnc-yrs-store-v3 stable_ids_guard::NEXT_FORMAT_KEY
48
61
  const FORMAT_ROOT = "sheet-format"; // rnc-yrs-store-v3 node_cell::FORMAT_ROOT
49
62
  const NODE_CELL_FORMAT = 2; // rnc-yrs-store-v3 node_cell::NODE_CELL_FORMAT
50
63
  const STYLE_LOG_V2 = 2; // STYLE_LOG_V2
@@ -53,6 +66,121 @@ const BLOCK_KEY_V5 = /^(-?\d+):(-?\d+):(\d+)$/; // block_key
53
66
  const DIM_KEY_V5 = /^(-?\d+):([RC]):(-?\d+)$/; // dim_id_key
54
67
  const DIM_STRIPE_KEY_V5 = /^(-?\d+):([RC]):k(\d+)$/; // dim_c0_stripe_key
55
68
  const SEED_KEY = /^(-?\d+)!([A-Z]+)(\d+)$/; // `"{sheetId}!{A1}"`, parse_a1
69
+ // ── the final format ────────────────────────────────────────────────────────
70
+ /**
71
+ * Whether an entry was EVER written under `key` of the positional hot plane
72
+ * (`format_key_written` in rnc-yrs-store-v3 `stable_ids_guard`): live, written
73
+ * over, removed or collected. `hasAttr` answers for a live entry only. A
74
+ * `@y/y` node keeps the newest item of each key it ever held in `_map`, the
75
+ * deleted one for a removed key, also after a save that collects deleted
76
+ * content and a load of that save. Creates no root.
77
+ */
78
+ const formatKeyWritten = (doc, key) => {
79
+ if (!doc.share.has(POSITIONAL_CELLS_ROOT))
80
+ return false;
81
+ const items = doc.get(POSITIONAL_CELLS_ROOT)._map;
82
+ return items instanceof Map && items.has(key);
83
+ };
84
+ /**
85
+ * Whether the doc is a final room (`doc_is_final` in rnc-yrs-store-v3): it
86
+ * holds the final format's key, whatever its stamp and marker read now, or,
87
+ * holding no format key, is stamped `docMeta.sheetDataVersion = "v6"`. Only
88
+ * the engine reads and writes such a doc: a host checks this before it calls
89
+ * into this package, and opens the doc through the engine when it is true.
90
+ * Read from the doc each time (the key and the stamp can arrive with a sync);
91
+ * creates no root.
92
+ */
93
+ export const docIsFinalFormat = (doc) => sheetDataFormatOf(doc) === "v6";
94
+ /** What every reader and writer of this package throws on a final doc. */
95
+ export class FinalFormatError extends Error {
96
+ constructor() {
97
+ super('This sheet is in the final format (it holds the format key sheetDataV3["v6"], or is stamped docMeta.sheetDataVersion = "v6"): read and write it through the engine');
98
+ this.name = "FinalFormatError";
99
+ }
100
+ }
101
+ /**
102
+ * What a doc's data plane is, judged as the engine judges it (`data_format`
103
+ * in rnc-yrs-store-v3 `stable_ids_guard`): by its format keys when one was
104
+ * ever written, else by its stamp, matched exactly.
105
+ *
106
+ * - the next format's key (`sheetDataV3["v7"]`) was ever written: `"unknown"`,
107
+ * with or without the final key beside it;
108
+ * - the final key (`sheetDataV3["v6"]`) was ever written: `"v6"`, whatever the
109
+ * stamp reads (an entry that never saw the room can outrank the stamp, a
110
+ * later write replace it, a removal take it away; the item under a map key
111
+ * cannot be unwritten);
112
+ * - neither: `"positional"` for no stamp, `"v2"`, `"v3"` or the retired
113
+ * `"v4"`; `"v5"`; `"v6"` (the final format); `"unknown"` for anything else
114
+ * (`"v7"`, `"v1"`, `"V6"`, `"v6 "`, `"6"`, `""`, `null`, a number).
115
+ *
116
+ * Creates no root.
117
+ */
118
+ export const sheetDataFormatOf = (doc) => {
119
+ if (formatKeyWritten(doc, NEXT_FORMAT_KEY))
120
+ return "unknown";
121
+ if (formatKeyWritten(doc, FINAL_INERT_KEY))
122
+ return "v6";
123
+ if (!doc.share.has(DOC_META))
124
+ return "positional";
125
+ const stamp = doc.get(DOC_META).getAttr(SHEET_DATA_VERSION);
126
+ if (stamp === undefined)
127
+ return "positional";
128
+ if (stamp === "v2" || stamp === "v3" || stamp === "v4")
129
+ return "positional";
130
+ if (stamp === "v5")
131
+ return "v5";
132
+ if (stamp === FINAL_STABLE_IDS_VERSION)
133
+ return "v6";
134
+ return "unknown";
135
+ };
136
+ /**
137
+ * What every reader and writer of this package throws on a doc of a data
138
+ * format it does not know (`sheetDataFormatOf(doc) === "unknown"`: by the key
139
+ * of a later format, or by its stamp): what such a doc holds is not this
140
+ * package's to read, and nothing may be written into it.
141
+ */
142
+ export class UnknownFormatError extends Error {
143
+ constructor() {
144
+ super("This sheet is in a data format this package does not know (a later format's key in sheetDataV3, or its docMeta.sheetDataVersion): it is read-only here");
145
+ this.name = "UnknownFormatError";
146
+ }
147
+ }
148
+ /**
149
+ * What a positional writer of this package throws on a doc whose
150
+ * `sheet-format.cells` is past 2: a cell format newer than the envelopes and
151
+ * node cells it writes (the positional store refuses the same room,
152
+ * `unsupported-cell-format`).
153
+ */
154
+ export class NewerCellFormatError extends Error {
155
+ constructor() {
156
+ super("This sheet stores its cells in a newer format (sheet-format.cells > 2) than this package writes: it is read-only here");
157
+ this.name = "NewerCellFormatError";
158
+ }
159
+ }
160
+ /**
161
+ * Throws on a doc only the engine reads and writes: `FinalFormatError` for a
162
+ * final doc, `UnknownFormatError` for a format this package does not know.
163
+ */
164
+ export const refuseEngineOwnedFormat = (doc) => {
165
+ const format = sheetDataFormatOf(doc);
166
+ if (format === "v6")
167
+ throw new FinalFormatError();
168
+ if (format === "unknown")
169
+ throw new UnknownFormatError();
170
+ };
171
+ /**
172
+ * `refuseEngineOwnedFormat`, and `NewerCellFormatError` on a doc whose
173
+ * `sheet-format.cells` is past 2: for the writers of the positional plane.
174
+ */
175
+ export const refusePositionalWrite = (doc) => {
176
+ refuseEngineOwnedFormat(doc);
177
+ if (!doc.share.has(FORMAT_ROOT))
178
+ return;
179
+ const cells = doc.get(FORMAT_ROOT).getAttr("cells");
180
+ if (typeof cells === "number" && cells > 2)
181
+ throw new NewerCellFormatError();
182
+ };
183
+ const refuseFinalFormat = refuseEngineOwnedFormat;
56
184
  // ── ids (axis.rs: make_id, id_client, id_counter) ───────────────────────────
57
185
  const idCounter = (id) => Number((BigInt.asUintN(64, id) >> BigInt(32)) & BigInt(0xffffffff));
58
186
  const idClient = (id) => Number(BigInt.asUintN(32, id));
@@ -80,6 +208,8 @@ const lineIdText = (value) => {
80
208
  * Later duplicates and non-id values are skipped, as the engine's index does.
81
209
  */
82
210
  export const readLineIds = (doc, sheetId, axis) => {
211
+ // A final doc's array may hold id runs, which are not ids to skip.
212
+ refuseFinalFormat(doc);
83
213
  const name = lineIdsRootName(sheetId, axis);
84
214
  if (!doc.share.has(name))
85
215
  return [];
@@ -220,6 +350,7 @@ const foldStyleBuffer = (overlay, buf) => {
220
350
  * with every `rncCellStylesLog` buffer folded on in array order. Walks the log.
221
351
  */
222
352
  export const readStyleOverlayV5 = (doc) => {
353
+ refuseFinalFormat(doc);
223
354
  const overlay = new Map();
224
355
  if (doc.share.has(STYLES_SEED_V5)) {
225
356
  forEachEntry(doc.get(STYLES_SEED_V5), (value, key) => {
@@ -388,7 +519,9 @@ export class V5FormulaTextOnReadError extends Error {
388
519
  this.name = "V5FormulaTextOnReadError";
389
520
  }
390
521
  }
391
- const refuseRenderedText = (doc) => {
522
+ /** A doc only the engine reads: stamped final, or past the Stage 2 marker. */
523
+ const refuseEngineOnly = (doc) => {
524
+ refuseFinalFormat(doc);
392
525
  if (v5RendersFormulaTextOnRead(doc))
393
526
  throw new V5FormulaTextOnReadError();
394
527
  };
@@ -428,7 +561,7 @@ const composeCell = (doc, key, styles, cold) => {
428
561
  * skipped). Inflates every cold block once.
429
562
  */
430
563
  export const sheetDataV5ToV2 = (doc, styles = readStyleOverlayV5(doc)) => {
431
- refuseRenderedText(doc);
564
+ refuseEngineOnly(doc);
432
565
  const sheetData = {};
433
566
  const cache = new Map();
434
567
  const cold = new Map();
@@ -479,12 +612,12 @@ export const sheetDataV5ToV2 = (doc, styles = readStyleOverlayV5(doc)) => {
479
612
  * per sheet. Undefined when nothing is there or the line is unnamed.
480
613
  */
481
614
  export const createCellReaderV5 = (doc, styles = readStyleOverlayV5(doc)) => {
482
- refuseRenderedText(doc);
615
+ refuseEngineOnly(doc);
483
616
  const lines = new Map();
484
617
  const cold = new Map();
485
618
  return (sheetId, rowIndex, columnIndex) => {
486
- // The marker can arrive with a sync after the reader was made.
487
- refuseRenderedText(doc);
619
+ // The marker, or the final stamp, can arrive with a sync after the reader was made.
620
+ refuseEngineOnly(doc);
488
621
  let ids = lines.get(sheetId);
489
622
  if (!ids) {
490
623
  ids = [readLineIds(doc, sheetId, "row"), readLineIds(doc, sheetId, "column")];
@@ -506,7 +639,7 @@ export const getCellV5 = (doc, sheetId, rowIndex, columnIndex, styles) => create
506
639
  * cold block changed (those need `sheetDataV5ToV2`). Null when nothing changed.
507
640
  */
508
641
  export const processSheetDataChangesV5 = (changedKeys, currentSheetData, doc, styles = readStyleOverlayV5(doc)) => {
509
- refuseRenderedText(doc);
642
+ refuseEngineOnly(doc);
510
643
  const cache = new Map();
511
644
  const cold = new Map();
512
645
  const next = { ...currentSheetData };
@@ -645,6 +778,7 @@ export const decodeFacetAnchorV5 = (buf) => {
645
778
  * read facets through the engine.
646
779
  */
647
780
  export const resolveFacetAnchorV5 = (doc, sheetId, value, site) => {
781
+ refuseFinalFormat(doc);
648
782
  const positional = { status: "positional" };
649
783
  const buf = value.anchor;
650
784
  if (!(buf instanceof Uint8Array))
@@ -996,7 +1130,7 @@ const applyPatchV5 = (w, { op, path, value }) => {
996
1130
  export const addSheetDataPatchesV5 = (doc, patches, origin = null, styles) => {
997
1131
  if (!patches?.length)
998
1132
  return;
999
- refuseRenderedText(doc);
1133
+ refuseEngineOnly(doc);
1000
1134
  doc.transact(() => {
1001
1135
  const w = {
1002
1136
  doc,
@@ -22,6 +22,7 @@ export type SheetDataEvent = {
22
22
  * @param patches
23
23
  * @param source
24
24
  * @param sheetDataVersion - Version of sheet data format ("v2", "v3" or "v5"). Falls back to docMeta if undefined.
25
+ * @throws FinalFormatError on a doc stamped final (`docIsFinalFormat`), whatever `sheetDataVersion` says: nothing is written.
25
26
  */
26
27
  export declare const applyPatchesToYDoc: (doc: YDoc, userId: string | number, patches: [patch: SpreadsheetPatch<Patch>, type?: HistoryType | undefined | null][], source?: "agent" | "user" | "backend", sheetDataVersion?: "v2" | "v3" | "v5", yjsRuntime?: YjsRuntime) => void;
27
28
  /**
@@ -37,6 +38,21 @@ export declare const getSheetFromYSheetData: (ySheetData: YNode, sheetId: string
37
38
  export declare const deleteSheetFromYSheetData: (ySheetData: YNode, sheetId: string | number) => void;
38
39
  export declare const getRowDataFromSheet: (ysheet: YNode, rowIndex: number | string, yjsRuntime?: YjsRuntime) => YNode;
39
40
  export declare const setCellDataInRowData: (rowData: YNode, columnIndex: number | string, cellData?: CellData | null) => void;
41
+ /**
42
+ * Writes several cells of one row: each run of consecutive column indices is
43
+ * one range delete and one insert, instead of an insert and a delete per cell.
44
+ *
45
+ * A row's cells are usually one Y.js item (a paste writes them together).
46
+ * Replacing a cell inside an item splits it, and every split is a splice into
47
+ * the client's list of structs, which grows with the document. A column insert
48
+ * rewrites every cell right of the new column in every row, so per-cell
49
+ * replaces cost (rows × shifted cells) splices into a list proportional to the
50
+ * sheet: quadratic, 4.8 s for 8,000 rows × 10 columns in V8. A run splits the
51
+ * row's item once.
52
+ *
53
+ * The row ends with the same content as `setCellDataInRowData` for each cell.
54
+ */
55
+ export declare const setCellRunsInRowData: (rowData: YNode, cells: Map<number, CellData | null | undefined>) => void;
40
56
  export declare const removeRowData: (ysheet: YNode, rowIndex: number | string) => void;
41
57
  /**
42
58
  * Read a cell's data from the V2 Y.js structure without creating any
@@ -135,22 +151,27 @@ export declare const sheetDataV2ToV3: <T extends CellData>(v2Data: SheetData<T>)
135
151
  * Convert V3 flat Map format to V2 SheetData
136
152
  * V3: Map<cellKey, CellDataV3>
137
153
  * V2: { sheetId: [rows with values arrays] }
154
+ * Handed plain data, it cannot tell a doc stamped final: its caller checks `docIsFinalFormat` first.
138
155
  */
139
156
  export declare const sheetDataV3ToV2: <T extends CellData>(v3Data: Map<string, CellDataV3<T>>) => SheetData<T>;
140
157
  /**
141
158
  * Get a cell from V3 flat structure
159
+ * @throws FinalFormatError on a doc stamped final (`docIsFinalFormat`).
142
160
  */
143
161
  export declare const getCellV3: (ySheetDataV3: YSheetDataV3, sheetId: number, rowIndex: number, columnIndex: number) => CellDataV3 | undefined;
144
162
  /**
145
163
  * Set a cell in V3 flat structure
164
+ * @throws FinalFormatError on a doc stamped final (`docIsFinalFormat`): nothing is written.
146
165
  */
147
166
  export declare const setCellV3: (ySheetDataV3: YSheetDataV3, sheetId: number, rowIndex: number, columnIndex: number, value: CellData) => void;
148
167
  /**
149
168
  * Delete a cell from V3 flat structure
169
+ * @throws FinalFormatError on a doc stamped final (`docIsFinalFormat`): nothing is written.
150
170
  */
151
171
  export declare const deleteCellV3: (ySheetDataV3: YSheetDataV3, sheetId: number, rowIndex: number, columnIndex: number) => void;
152
172
  /**
153
173
  * Delete all cells for a sheet from V3 flat structure
174
+ * @throws FinalFormatError on a doc stamped final (`docIsFinalFormat`): nothing is written.
154
175
  */
155
176
  export declare const deleteSheetV3: (ySheetDataV3: YSheetDataV3, sheetId: number) => void;
156
177
  /**
@@ -164,6 +185,7 @@ export declare const getSheetDataV3: (doc: YDoc) => YSheetDataV3;
164
185
  * patches before applying to Y.js. This reduces overhead by:
165
186
  * 1. Deduplicating patches targeting the same cell (later patches win)
166
187
  * 2. Processing all cell updates in a single pass
188
+ * @throws FinalFormatError on a doc stamped final (`docIsFinalFormat`): nothing is written.
167
189
  */
168
190
  export declare const addSheetDataPatchesV3: (ySheetDataV3: YSheetDataV3, patches: Patch[]) => void;
169
191
  /**
@@ -171,6 +193,7 @@ export declare const addSheetDataPatchesV3: (ySheetDataV3: YSheetDataV3, patches
171
193
  * @param changedKeys - Pre-extracted changes from Yjs event
172
194
  * @param currentSheetData - Current sheet data state
173
195
  * @param ySheetDataV3 - The map node for V3 data
196
+ * @throws FinalFormatError on a doc stamped final (`docIsFinalFormat`).
174
197
  */
175
198
  export declare const processSheetDataEventsV3: <T extends CellData>(changedKeys: Map<string, {
176
199
  action: "add" | "update" | "delete";