@w100n/documents 0.18.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  'use client';
2
2
  import {
3
3
  useLive
4
- } from "./chunk-TSB2QS56.js";
4
+ } from "./chunk-ZQYSBWLK.js";
5
5
  import {
6
6
  SheetRefusal,
7
7
  build,
@@ -25,7 +25,7 @@ import {
25
25
  strip,
26
26
  worksheets,
27
27
  writeSheet
28
- } from "./chunk-2G34AIPU.js";
28
+ } from "./chunk-JSJEB2CO.js";
29
29
  import "./chunk-GSIPTCQH.js";
30
30
  import {
31
31
  rove,
@@ -970,4 +970,4 @@ export {
970
970
  readSheet,
971
971
  writeSheet
972
972
  };
973
- //# sourceMappingURL=SheetView-F4CBWEOS.js.map
973
+ //# sourceMappingURL=SheetView-PUSRW7W2.js.map
@@ -9,8 +9,8 @@ import {
9
9
  } from "./chunk-QDH7EZAF.js";
10
10
  import {
11
11
  useLive
12
- } from "./chunk-TSB2QS56.js";
13
- import "./chunk-2G34AIPU.js";
12
+ } from "./chunk-ZQYSBWLK.js";
13
+ import "./chunk-JSJEB2CO.js";
14
14
  import {
15
15
  fromMarkdown,
16
16
  toMarkdown,
@@ -1786,4 +1786,4 @@ img { max-width: 100%; } img[data-wrap='left'] { float: left; margin: 0 12pt 6pt
1786
1786
  export {
1787
1787
  TextEditor as default
1788
1788
  };
1789
- //# sourceMappingURL=TextEditor-ZY4B7YIF.js.map
1789
+ //# sourceMappingURL=TextEditor-Z4KSBLBV.js.map
@@ -40,10 +40,10 @@ import {
40
40
  import { getSchema } from "@tiptap/core";
41
41
  import { Transform } from "@tiptap/pm/transform";
42
42
  import { prosemirrorJSONToYXmlFragment, updateYFragment, yXmlFragmentToProseMirrorRootNode } from "@tiptap/y-tiptap";
43
- import * as Y2 from "yjs";
43
+ import * as Y3 from "yjs";
44
44
 
45
45
  // package.json
46
- var version = "0.18.1";
46
+ var version = "0.19.0";
47
47
 
48
48
  // src/sheets/model.ts
49
49
  var SheetRefusal = class extends Error {
@@ -56,8 +56,8 @@ var SheetRefusal = class extends Error {
56
56
  var counter = 0;
57
57
  var fresh = (prefix) => `${prefix}${Date.now().toString(36)}${(counter++).toString(36)}${Math.random().toString(36).slice(2, 6)}`;
58
58
  var numbered = (prefix, count) => Array.from({ length: count }, (_, i) => `${prefix}${i}`);
59
- function insert(list, at, count, prefix) {
60
- list.splice(at, 0, ...Array.from({ length: count }, () => fresh(prefix)));
59
+ function insert(list, at2, count, prefix) {
60
+ list.splice(at2, 0, ...Array.from({ length: count }, () => fresh(prefix)));
61
61
  }
62
62
  function move(list, from, count, to) {
63
63
  const taken = list.splice(from, count);
@@ -107,12 +107,12 @@ function encode(text, encoding, bom) {
107
107
  if (encoding === "utf-16le" || encoding === "utf-16be") {
108
108
  const out2 = new Uint8Array(text.length * 2 + (bom ? 2 : 0));
109
109
  const view = new DataView(out2.buffer);
110
- let at = 0;
110
+ let at2 = 0;
111
111
  if (bom) {
112
112
  view.setUint16(0, 65279, encoding === "utf-16le");
113
- at = 2;
113
+ at2 = 2;
114
114
  }
115
- for (let i = 0; i < text.length; i++) view.setUint16(at + i * 2, text.charCodeAt(i), encoding === "utf-16le");
115
+ for (let i = 0; i < text.length; i++) view.setUint16(at2 + i * 2, text.charCodeAt(i), encoding === "utf-16le");
116
116
  return out2;
117
117
  }
118
118
  const table = /* @__PURE__ */ new Map();
@@ -248,8 +248,8 @@ function writeCsv(original, model) {
248
248
  const r0 = rowFrom.get(lines2.rows[r]) ?? -1;
249
249
  const was = r0 >= 0 ? old[r0] : void 0;
250
250
  const line = cells[r] ?? {};
251
- const filled2 = Object.keys(line).map(Number).filter((c) => show(value(line[c])) !== "");
252
- let count = filled2.length ? Math.max(...filled2) + 1 : 0;
251
+ const filled3 = Object.keys(line).map(Number).filter((c) => show(value(line[c])) !== "");
252
+ let count = filled3.length ? Math.max(...filled3) + 1 : 0;
253
253
  if (was) for (let c0 = 0; c0 < was.length; c0++) count = Math.max(count, lines2.cols.indexOf(origin.cols[c0]) + 1);
254
254
  const fields = [];
255
255
  for (let c = 0; c < count; c++) {
@@ -685,8 +685,8 @@ var Styles = class {
685
685
  return index;
686
686
  }
687
687
  add(list, xml) {
688
- const at = this[list].indexOf(xml);
689
- if (at >= 0) return at;
688
+ const at2 = this[list].indexOf(xml);
689
+ if (at2 >= 0) return at2;
690
690
  this[list].push(xml);
691
691
  this.added = true;
692
692
  return this[list].length - 1;
@@ -765,8 +765,8 @@ var Styles = class {
765
765
  edits2.push([el.start, el.end, `${open} count="${lists[name].length}">${lists[name].join("")}</${el.name}>`]);
766
766
  } else {
767
767
  const after = root.kids.find((k) => order2.indexOf(this.bare(k.name)) > order2.indexOf(name));
768
- const at = after ? after.start : root.close;
769
- edits2.push([at, at, `<${p}${name} count="${lists[name].length}">${lists[name].join("")}</${p}${name}>`]);
768
+ const at2 = after ? after.start : root.close;
769
+ edits2.push([at2, at2, `<${p}${name} count="${lists[name].length}">${lists[name].join("")}</${p}${name}>`]);
770
770
  }
771
771
  }
772
772
  edits2.sort((x, y) => y[0] - x[0]);
@@ -868,7 +868,7 @@ function load(bytes) {
868
868
  if (state === "hidden") sheet.hidden = 1;
869
869
  if (state === "veryHidden") sheet.hidden = 2;
870
870
  const open = element(sxml, `${p}sheetData`);
871
- const bounds = open ? [open.start, open.open, open.close, open.end] : [sxml.length, sxml.length, sxml.length, sxml.length];
871
+ const bounds2 = open ? [open.start, open.open, open.close, open.end] : [sxml.length, sxml.length, sxml.length, sxml.length];
872
872
  const head = open ? sxml.slice(0, open.start) : sxml;
873
873
  const tail = open ? sxml.slice(open.end) : "";
874
874
  const format = /<(?:\w+:)?sheetFormatPr\b[^>]*>/.exec(head)?.[0];
@@ -908,13 +908,13 @@ function load(bytes) {
908
908
  let maxRow = -1, maxCol = -1;
909
909
  if (open && open.close > open.open) {
910
910
  const end = open.close;
911
- let at = open.open, row = -1, col = -1;
912
- while (at < end) {
913
- const lt = sxml.indexOf("<", at);
911
+ let at2 = open.open, row = -1, col = -1;
912
+ while (at2 < end) {
913
+ const lt = sxml.indexOf("<", at2);
914
914
  if (lt < 0 || lt >= end) break;
915
915
  const gt = sxml.indexOf(">", lt);
916
916
  if (sxml.charCodeAt(lt + 1) === 47) {
917
- at = gt + 1;
917
+ at2 = gt + 1;
918
918
  continue;
919
919
  }
920
920
  let j = lt + 1;
@@ -942,11 +942,11 @@ function load(bytes) {
942
942
  }
943
943
  if (Object.keys(rd).length) rowData[row] = rd;
944
944
  if (rd.h !== void 0 || rd.hd || rd.s) maxRow = Math.max(maxRow, row);
945
- at = gt + 1;
945
+ at2 = gt + 1;
946
946
  continue;
947
947
  }
948
948
  if (name !== "c") {
949
- at = gt + 1;
949
+ at2 = gt + 1;
950
950
  continue;
951
951
  }
952
952
  const ref = attr2(tag, "r");
@@ -1010,7 +1010,7 @@ function load(bytes) {
1010
1010
  }
1011
1011
  }
1012
1012
  cells.set(key(row, col), { start: lt, end: stop, shared });
1013
- at = stop;
1013
+ at2 = stop;
1014
1014
  }
1015
1015
  }
1016
1016
  for (const [r, c, si] of children) {
@@ -1091,7 +1091,7 @@ function load(bytes) {
1091
1091
  xml: sxml,
1092
1092
  p,
1093
1093
  rels: srels,
1094
- bounds,
1094
+ bounds: bounds2,
1095
1095
  rows,
1096
1096
  cells,
1097
1097
  cols,
@@ -1118,8 +1118,8 @@ function load(bytes) {
1118
1118
  if (Object.keys(notes).length) resources.push({ name: "SHEET_NOTE_PLUGIN", data: JSON.stringify(notes) });
1119
1119
  if (Object.keys(validations).length) resources.push({ name: "SHEET_DATA_VALIDATION_PLUGIN", data: JSON.stringify(validations) });
1120
1120
  if (Object.keys(filters).length) resources.push({ name: "SHEET_FILTER_PLUGIN", data: JSON.stringify(filters) });
1121
- const shown = entries[active];
1122
- if (shown?.sheet && book.sheetOrder.includes(`s${shown.sheetId}`)) model.active = `s${shown.sheetId}`;
1121
+ const shown2 = entries[active];
1122
+ if (shown2?.sheet && book.sheetOrder.includes(`s${shown2.sheetId}`)) model.active = `s${shown2.sheetId}`;
1123
1123
  return { model, book: { pack, part, xml, rels, styles, stylesPart: stylesPart ?? null, sheets, entries } };
1124
1124
  }
1125
1125
  var kinds = { whole: "whole", decimal: "decimal", list: "list", textLength: "textLength", custom: "custom" };
@@ -1287,14 +1287,14 @@ function place(xml, name, value2) {
1287
1287
  if (found) return xml.slice(0, found.start) + (value2 ?? "") + xml.slice(found.end);
1288
1288
  if (value2 === null) return xml;
1289
1289
  const rank = order.indexOf(name);
1290
- let at = -1;
1290
+ let at2 = -1;
1291
1291
  for (const later of order.slice(rank + 1)) {
1292
1292
  const f = find(xml, later);
1293
- if (f && (at < 0 || f.start < at)) at = f.start;
1293
+ if (f && (at2 < 0 || f.start < at2)) at2 = f.start;
1294
1294
  }
1295
- if (at < 0) at = xml.search(/<\/(?:\w+:)?worksheet>\s*$/);
1296
- if (at < 0) at = xml.length;
1297
- return xml.slice(0, at) + value2 + xml.slice(at);
1295
+ if (at2 < 0) at2 = xml.search(/<\/(?:\w+:)?worksheet>\s*$/);
1296
+ if (at2 < 0) at2 = xml.length;
1297
+ return xml.slice(0, at2) + value2 + xml.slice(at2);
1298
1298
  }
1299
1299
  function remapZone(xml, mine, rows, cols) {
1300
1300
  const ranges = (sqref) => boxes(sqref).map((b) => squeeze(b, rows.map, cols.map)).filter((b) => b !== null).map(span).join(" ");
@@ -1528,8 +1528,8 @@ function writeXlsx(original, model) {
1528
1528
  if (curRules && !same(rules.map(canonRule), oldRules.map(canonRule))) {
1529
1529
  changed = true;
1530
1530
  const known = new Map((rec?.validations ?? []).map((v, i) => [`dv${i}`, v]));
1531
- const shown = new Set(rules.map((r) => r.uid));
1532
- const hiddenRules = [...known].filter(([uid, v]) => !shown.has(uid) && !(rec && baseRules[rec.sid]?.some((r) => r.uid === uid)) && v).map(([, v]) => rows.moved || cols.moved ? remapZone(v, mine, rows, cols) : v);
1531
+ const shown2 = new Set(rules.map((r) => r.uid));
1532
+ const hiddenRules = [...known].filter(([uid, v]) => !shown2.has(uid) && !(rec && baseRules[rec.sid]?.some((r) => r.uid === uid)) && v).map(([, v]) => rows.moved || cols.moved ? remapZone(v, mine, rows, cols) : v);
1533
1533
  const list = [...hiddenRules, ...rules.map((r) => validationXml(p, r, known.get(r.uid)))].filter(Boolean);
1534
1534
  tail = place(tail, "dataValidations", list.length ? `<${p}dataValidations count="${list.length}">${list.join("")}</${p}dataValidations>` : null);
1535
1535
  }
@@ -1640,9 +1640,9 @@ function writeXlsx(original, model) {
1640
1640
  listed.push({ xml: tag, sheetId: s.sheetId, oldIndex: s.rec ? indexOf.get(s.sheetId) : -1 });
1641
1641
  }
1642
1642
  for (const { e, i } of nonSheets) {
1643
- let at = listed.findIndex((x) => x.oldIndex > i);
1644
- if (at < 0) at = listed.length;
1645
- listed.splice(at, 0, { xml: e.xml, sheetId: e.sheetId, oldIndex: i });
1643
+ let at2 = listed.findIndex((x) => x.oldIndex > i);
1644
+ if (at2 < 0) at2 = listed.length;
1645
+ listed.splice(at2, 0, { xml: e.xml, sheetId: e.sheetId, oldIndex: i });
1646
1646
  }
1647
1647
  wb = wb.replace(/(<(?:\w+:)?sheets\b[^>]*>)[\s\S]*?(<\/(?:\w+:)?sheets>)/, (_, a, b) => a + listed.map((x) => x.xml).join("") + b);
1648
1648
  const newIndex = new Map(listed.map((x, i) => [x.oldIndex, i]));
@@ -1668,9 +1668,9 @@ function writeXlsx(original, model) {
1668
1668
  for (const [from, to] of names) f = renamed(f, from, to);
1669
1669
  return `${tag}${escape(f)}</${p}definedName>`;
1670
1670
  });
1671
- for (const [sheetId, f] of filterNames) {
1671
+ for (const [sheetId2, f] of filterNames) {
1672
1672
  if (!f) continue;
1673
- const def = `<${wp}definedName name="_xlnm._FilterDatabase" localSheetId="${sheetIndex.get(sheetId)}" hidden="1">${escape(f)}</${wp}definedName>`;
1673
+ const def = `<${wp}definedName name="_xlnm._FilterDatabase" localSheetId="${sheetIndex.get(sheetId2)}" hidden="1">${escape(f)}</${wp}definedName>`;
1674
1674
  wb = /<(?:\w+:)?definedNames\b/.test(wb) ? wb.replace(/<\/(?:\w+:)?definedNames>/, (end) => def + end) : wb.replace(/<\/(?:\w+:)?sheets>/, (end) => `${end}<${wp}definedNames>${def}</${wp}definedNames>`);
1675
1675
  }
1676
1676
  wb = wb.replace(/<((?:\w+:)?)definedNames>\s*<\/\1definedNames>/, "");
@@ -1987,18 +1987,18 @@ function fill(doc, model) {
1987
1987
  const { cells, rowData, colData, merges, notes: kept } = pieces(sheets.get(sid));
1988
1988
  for (const [r, line] of Object.entries(sheet.cellData ?? {})) for (const [c, x] of Object.entries(line ?? {})) {
1989
1989
  if (!x) continue;
1990
- const at = spot(l.rows[+r], l.cols[+c]);
1990
+ const at2 = spot(l.rows[+r], l.cols[+c]);
1991
1991
  const out = {};
1992
1992
  if (x.f) {
1993
1993
  out.f = x.f;
1994
- values.set(`${sid}:${at}`, { v: x.v ?? null, t: x.t ?? null });
1994
+ values.set(`${sid}:${at2}`, { v: x.v ?? null, t: x.t ?? null });
1995
1995
  } else {
1996
1996
  if (x.v !== void 0 && x.v !== null) out.v = x.v;
1997
1997
  if (x.t) out.t = x.t;
1998
1998
  }
1999
1999
  if (x.p) out.p = x.p;
2000
2000
  if (typeof x.s === "string") out.s = x.s;
2001
- cells.set(at, out);
2001
+ cells.set(at2, out);
2002
2002
  }
2003
2003
  for (const [r, rd] of Object.entries(sheet.rowData ?? {})) if (rd) rowData.set(l.rows[+r], strip({ h: rd.h, hd: rd.hd, ia: rd.ia, s: typeof rd.s === "string" ? rd.s : void 0 }));
2004
2004
  for (const [c, cd] of Object.entries(sheet.columnData ?? {})) if (cd) colData.set(l.cols[+c], strip({ w: cd.w, hd: cd.hd, s: typeof cd.s === "string" ? cd.s : void 0 }));
@@ -2013,11 +2013,11 @@ function sheetOf(doc, sid, l) {
2013
2013
  const { cells, rowData, colData, merges } = pieces(m);
2014
2014
  const rows = new Map(l.rows.map((id, i) => [id, i])), cols = new Map(l.cols.map((id, i) => [id, i]));
2015
2015
  const cellData = {};
2016
- for (const [at, x] of cells) {
2017
- const [row, col] = at.split(":");
2016
+ for (const [at2, x] of cells) {
2017
+ const [row, col] = at2.split(":");
2018
2018
  const r = rows.get(row), c = cols.get(col);
2019
2019
  if (r === void 0 || c === void 0) continue;
2020
- const kept = x.f ? values.get(`${sid}:${at}`) : void 0;
2020
+ const kept = x.f ? values.get(`${sid}:${at2}`) : void 0;
2021
2021
  (cellData[r] ?? (cellData[r] = {}))[c] = kept ? { ...x, v: kept.v, t: kept.t } : { ...x };
2022
2022
  }
2023
2023
  const rowsOut = {}, colsOut = {};
@@ -2030,7 +2030,7 @@ function sheetOf(doc, sid, l) {
2030
2030
  }
2031
2031
  var notesOf = (m, l) => {
2032
2032
  const rows = new Map(l.rows.map((id, i) => [id, i])), cols = new Map(l.cols.map((id, i) => [id, i]));
2033
- return [...pieces(m).notes].map(([at, n]) => ({ ...n, row: rows.get(at.split(":")[0]), col: cols.get(at.split(":")[1]) })).filter((n) => n.row !== void 0 && n.col !== void 0);
2033
+ return [...pieces(m).notes].map(([at2, n]) => ({ ...n, row: rows.get(at2.split(":")[0]), col: cols.get(at2.split(":")[1]) })).filter((n) => n.row !== void 0 && n.col !== void 0);
2034
2034
  };
2035
2035
  function build(doc) {
2036
2036
  const { book, order: order2, sheets, styles, origin } = parts(doc);
@@ -2114,17 +2114,19 @@ function applyCells(doc, list, origin) {
2114
2114
  const [r, c] = cell(x.ref);
2115
2115
  if (!sid || r < 0) continue;
2116
2116
  const { rows, cols, cells } = pieces(sheets.get(sid));
2117
- if (r >= rows.length || c >= cols.length) continue;
2118
- const at = spot(rows.get(r), cols.get(c));
2117
+ if (r >= rows.length + 1e4 || c >= cols.length + 1e3) continue;
2118
+ if (r >= rows.length) rows.push(Array.from({ length: r + 1 - rows.length }, () => fresh("n")));
2119
+ if (c >= cols.length) cols.push(Array.from({ length: c + 1 - cols.length }, () => fresh("n")));
2120
+ const at2 = spot(rows.get(r), cols.get(c));
2119
2121
  const next = {};
2120
2122
  if (x.formula !== void 0) next.f = x.formula.startsWith("=") ? x.formula : `=${x.formula}`;
2121
2123
  else if (typeof x.value === "boolean") Object.assign(next, { v: x.value ? 1 : 0, t: 3 });
2122
2124
  else if (x.value !== void 0 && x.value !== null && x.value !== "") Object.assign(next, { v: x.value, t: typeof x.value === "number" ? 2 : 1 });
2123
- const s = cells.get(at)?.s;
2125
+ const s = cells.get(at2)?.s;
2124
2126
  if (s) next.s = s;
2125
- values.delete(`${sid}:${at}`);
2126
- if (Object.keys(next).length) cells.set(at, next);
2127
- else cells.delete(at);
2127
+ values.delete(`${sid}:${at2}`);
2128
+ if (Object.keys(next).length) cells.set(at2, next);
2129
+ else cells.delete(at2);
2128
2130
  done++;
2129
2131
  }
2130
2132
  }, origin);
@@ -2353,25 +2355,107 @@ var uk = {
2353
2355
  };
2354
2356
  var sheetTexts = { en, pl, uk };
2355
2357
 
2358
+ // src/sheets/agent.ts
2359
+ import * as Y2 from "yjs";
2360
+ var sheetId = (doc, name) => {
2361
+ const { order: order2, sheets } = parts(doc);
2362
+ return order2.toArray().find((id) => sheets.get(id)?.get("name") === name);
2363
+ };
2364
+ function at(doc, x) {
2365
+ const sid = sheetId(doc, x.sheet);
2366
+ const [r, c] = cell(x.ref);
2367
+ if (!sid || r < 0) return void 0;
2368
+ const { rows, cols, cells } = pieces(parts(doc).sheets.get(sid));
2369
+ return r < rows.length && c < cols.length ? cells.get(spot(rows.get(r), cols.get(c))) : void 0;
2370
+ }
2371
+ var filled = (x) => !!x?.f || x?.v !== void 0 && x.v !== null && x.v !== "";
2372
+ var bare = (x) => x?.f ? `=${x.f}` : filled(x) ? canon([x.v, x.t ?? null]) : "";
2373
+ var shown = (x) => x?.f ?? (filled(x) ? String(x.v) : "");
2374
+ function clashes(doc, kind, seen, list) {
2375
+ const old = new Y2.Doc();
2376
+ fill(old, readSheet(seen, kind));
2377
+ const out = list.filter((x) => sheetId(old, x.sheet) && bare(at(old, x)) !== bare(at(doc, x))).map((x) => ({ sheet: x.sheet, ref: x.ref, now: shown(at(doc, x)) }));
2378
+ old.destroy();
2379
+ return out;
2380
+ }
2381
+ function appendRows(doc, sheet, lines2, origin) {
2382
+ const sid = sheetId(doc, sheet);
2383
+ if (!sid || !lines2.length) return null;
2384
+ const { rows, cells } = pieces(parts(doc).sheets.get(sid));
2385
+ const index = new Map(rows.toArray().map((id, i) => [id, i]));
2386
+ let last = -1;
2387
+ for (const [key2, x] of cells) if (filled(x)) last = Math.max(last, index.get(key2.split(":")[0]) ?? -1);
2388
+ const writes = lines2.flatMap((line, i) => line.map((x, c) => ({ sheet, ref: a1(last + 1 + i, c), ...typeof x === "string" && x.startsWith("=") ? { formula: x } : { value: x } })));
2389
+ applyCells(doc, writes.filter((w) => "formula" in w || w.value !== null && w.value !== ""), origin);
2390
+ return `${a1(last + 1, 0)}:${a1(last + lines2.length, Math.max(1, ...lines2.map((l) => l.length)) - 1)}`;
2391
+ }
2392
+ async function compute(doc, origin) {
2393
+ const { sheets, values } = parts(doc);
2394
+ const model = build(doc);
2395
+ const formulas2 = [];
2396
+ for (const sid of model.book.sheetOrder) {
2397
+ const l = model.lines[sid];
2398
+ const rows = new Map(l.rows.map((id, i) => [id, i])), cols = new Map(l.cols.map((id, i) => [id, i]));
2399
+ for (const [key2, x] of pieces(sheets.get(sid)).cells) {
2400
+ const [r, c] = key2.split(":");
2401
+ if (x.f && rows.has(r) && cols.has(c)) formulas2.push([sid, key2, rows.get(r), cols.get(c)]);
2402
+ }
2403
+ }
2404
+ if (!formulas2.length) return 0;
2405
+ const [{ LocaleType, LogLevel, Univer }, { FUniver }, { UniverFormulaEnginePlugin }, { UniverSheetsPlugin }, { UniverSheetsFormulaPlugin }] = await Promise.all([
2406
+ import("@univerjs/core"),
2407
+ import("@univerjs/core/facade"),
2408
+ import("@univerjs/engine-formula"),
2409
+ import("@univerjs/sheets"),
2410
+ import("@univerjs/sheets-formula"),
2411
+ import("@univerjs/engine-formula/facade"),
2412
+ import("@univerjs/sheets/facade")
2413
+ ]);
2414
+ const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: {} }, logLevel: LogLevel.ERROR });
2415
+ univer.registerPlugin(UniverFormulaEnginePlugin);
2416
+ univer.registerPlugin(UniverSheetsPlugin);
2417
+ univer.registerPlugin(UniverSheetsFormulaPlugin);
2418
+ try {
2419
+ const api = FUniver.newAPI(univer);
2420
+ const wb = api.createWorkbook(structuredClone(model.book));
2421
+ const applied = api.getFormula().onCalculationResultApplied(1e4);
2422
+ api.getFormula().executeCalculation();
2423
+ await applied;
2424
+ let changed = 0;
2425
+ doc.transact(() => {
2426
+ for (const [sid, key2, r, c] of formulas2) {
2427
+ const got = wb.getSheetBySheetId(sid)?.getRange(r, c).getCellData();
2428
+ const next = { v: got?.v ?? null, t: got?.t ?? null };
2429
+ if (canon(values.get(`${sid}:${key2}`)) === canon(next)) continue;
2430
+ values.set(`${sid}:${key2}`, next);
2431
+ changed++;
2432
+ }
2433
+ }, origin);
2434
+ return changed;
2435
+ } finally {
2436
+ univer.dispose();
2437
+ }
2438
+ }
2439
+
2356
2440
  // src/collab.ts
2357
2441
  var ours = "w100n-collab";
2358
2442
  var schemas = /* @__PURE__ */ new Map();
2359
2443
  var schemaOf = (kind) => schemas.get(kind) ?? schemas.set(kind, getSchema(kit(kind, texts.en))).get(kind);
2360
2444
  var parse2 = async (kind, bytes) => kind === "docx" ? (await readDocx(bytes)).doc : fromMarkdown(new TextDecoder().decode(bytes)).doc;
2361
2445
  var edits = (tr) => tr.changedParentTypes.has(tr.doc.get("default")) || tr.changedParentTypes.has(tr.doc.get("book")) || tr.changedParentTypes.has(tr.doc.get("setup"));
2362
- var filled = (doc) => doc.getXmlFragment("default").length > 0 || doc.getMap("book").size > 0;
2446
+ var filled2 = (doc) => doc.getXmlFragment("default").length > 0 || doc.getMap("book").size > 0;
2363
2447
  function seed(doc, kind, bytes, json) {
2364
- if (filled(doc)) return false;
2365
- const fixed = new Y2.Doc();
2448
+ if (filled2(doc)) return false;
2449
+ const fixed = new Y3.Doc();
2366
2450
  fixed.clientID = fnv(new Uint8Array(bytes), fnv(new TextEncoder().encode(`${version}:${kind}`)));
2367
2451
  if (kind === "xlsx" || kind === "csv") fill(fixed, readSheet(bytes, kind));
2368
2452
  else prosemirrorJSONToYXmlFragment(schemaOf(kind), json, fixed.getXmlFragment("default"));
2369
- Y2.applyUpdate(doc, Y2.encodeStateAsUpdate(fixed), ours);
2453
+ Y3.applyUpdate(doc, Y3.encodeStateAsUpdate(fixed), ours);
2370
2454
  return true;
2371
2455
  }
2372
2456
  function follow(doc, author) {
2373
2457
  const editors = doc.getMap("editors");
2374
- const before = (tr) => tr.meta.set("fresh", !filled(doc));
2458
+ const before = (tr) => tr.meta.set("fresh", !filled2(doc));
2375
2459
  const after = (tr) => {
2376
2460
  const who = !tr.meta.get("fresh") && edits(tr) ? author(tr.origin) : null;
2377
2461
  if (who && !editors.has(who.id)) doc.transact(() => editors.set(who.id, who), ours);
@@ -2399,13 +2483,57 @@ function applyText(doc, kind, changes, origin) {
2399
2483
  return false;
2400
2484
  });
2401
2485
  if (hits.length !== 1) throw new Refusal(`${hits.length ? "more than once" : "not"} in the document: ${c.find.slice(0, 80)}`);
2402
- const [at] = hits;
2403
- if (c.replace) step.replaceWith(at, at + c.find.length, schema.text(c.replace, step.doc.resolve(at + 1).marks()));
2404
- else step.delete(at, at + c.find.length);
2486
+ const [at2] = hits;
2487
+ if (c.replace) step.replaceWith(at2, at2 + c.find.length, schema.text(c.replace, step.doc.resolve(at2 + 1).marks()));
2488
+ else step.delete(at2, at2 + c.find.length);
2405
2489
  }
2406
2490
  updateYFragment({ transact: (run) => doc.transact(run, origin) }, fragment, step.doc, { mapping: /* @__PURE__ */ new Map(), isOMark: /* @__PURE__ */ new Map() });
2407
2491
  return changes.length;
2408
2492
  }
2493
+ var bounds = (doc, heading) => {
2494
+ const want = heading.trim().replace(/^#+\s*/, "").toLowerCase();
2495
+ let at2 = -1, level = 0, end = doc.content.size, pos = 0;
2496
+ doc.forEach((node, offset) => {
2497
+ if (end !== doc.content.size) return;
2498
+ if (at2 < 0 && node.type.name === "heading" && node.textContent.trim().toLowerCase() === want) [at2, level, pos] = [offset, node.attrs.level, offset + node.nodeSize];
2499
+ else if (at2 >= 0 && node.type.name === "heading" && node.attrs.level <= level) end = offset;
2500
+ });
2501
+ if (at2 < 0) throw new Refusal(`no heading ${heading.slice(0, 80)} in the document`);
2502
+ return { from: pos, to: end };
2503
+ };
2504
+ function applySteps(doc, kind, steps, seen, origin) {
2505
+ const schema = schemaOf(kind);
2506
+ const fragment = doc.getXmlFragment("default");
2507
+ const step = new Transform(yXmlFragmentToProseMirrorRootNode(fragment, schema));
2508
+ const old = seen && schema.nodeFromJSON(seen);
2509
+ const clashes2 = [];
2510
+ let done = 0, span2 = null;
2511
+ for (const s of steps) {
2512
+ const blocks2 = schema.nodeFromJSON(fromMarkdown(s.text).doc).content;
2513
+ const range = s.op === "append" ? { from: step.doc.content.size, to: step.doc.content.size } : s.op === "all" ? { from: 0, to: step.doc.content.size } : bounds(step.doc, s.heading ?? "");
2514
+ const was = !old || s.op === "append" ? null : s.op === "all" ? { from: 0, to: old.content.size } : (() => {
2515
+ try {
2516
+ return bounds(old, s.heading ?? "");
2517
+ } catch {
2518
+ return null;
2519
+ }
2520
+ })();
2521
+ if (old && was) {
2522
+ const now = step.doc.textBetween(range.from, range.to, "\n\n");
2523
+ if (old.textBetween(was.from, was.to, "\n\n") !== now) {
2524
+ clashes2.push({ section: s.op === "all" ? "" : s.heading ?? "", now });
2525
+ continue;
2526
+ }
2527
+ }
2528
+ const from = s.op === "after" ? range.to : range.from;
2529
+ if (s.op === "after") step.insert(range.to, blocks2);
2530
+ else step.replaceWith(range.from, range.to, blocks2);
2531
+ span2 = [step.doc.resolve(from).index(0), step.doc.resolve(Math.min(from + blocks2.size, step.doc.content.size)).index(0)];
2532
+ done++;
2533
+ }
2534
+ if (done) updateYFragment({ transact: (run) => doc.transact(run, origin) }, fragment, step.doc, { mapping: /* @__PURE__ */ new Map(), isOMark: /* @__PURE__ */ new Map() });
2535
+ return { done, clashes: clashes2, span: span2 };
2536
+ }
2409
2537
  async function write(kind, base, node, load2, setup) {
2410
2538
  if (kind === "docx") return writeDocx(base, node.toJSON(), load2, setup);
2411
2539
  const parsed = fromMarkdown(new TextDecoder().decode(base));
@@ -2414,7 +2542,7 @@ async function write(kind, base, node, load2, setup) {
2414
2542
  var blocks = (fragment, schema) => {
2415
2543
  const out = [];
2416
2544
  const walk = (parent) => parent.toArray().forEach((child) => {
2417
- if (!(child instanceof Y2.XmlElement) || !schema.nodes[child.nodeName]?.isBlock) return;
2545
+ if (!(child instanceof Y3.XmlElement) || !schema.nodes[child.nodeName]?.isBlock) return;
2418
2546
  out.push(child);
2419
2547
  walk(child);
2420
2548
  });
@@ -2513,15 +2641,19 @@ export {
2513
2641
  extras,
2514
2642
  applyCells,
2515
2643
  sheetTexts,
2644
+ clashes,
2645
+ appendRows,
2646
+ compute,
2516
2647
  ours,
2517
2648
  parse2 as parse,
2518
2649
  edits,
2519
- filled,
2650
+ filled2 as filled,
2520
2651
  seed,
2521
2652
  follow,
2522
2653
  pending,
2523
2654
  Refusal,
2524
2655
  applyText,
2656
+ applySteps,
2525
2657
  save
2526
2658
  };
2527
- //# sourceMappingURL=chunk-2G34AIPU.js.map
2659
+ //# sourceMappingURL=chunk-JSJEB2CO.js.map