@ai-matrx/office 0.3.1 → 0.5.2

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 (74) hide show
  1. package/CHANGELOG.md +47 -2
  2. package/dist/chunk-2UBGQUXW.cjs +37 -0
  3. package/dist/chunk-2UBGQUXW.cjs.map +1 -0
  4. package/dist/chunk-5T2M6LSI.js +529 -0
  5. package/dist/chunk-5T2M6LSI.js.map +1 -0
  6. package/dist/chunk-BWMAYLW4.cjs +272 -0
  7. package/dist/chunk-BWMAYLW4.cjs.map +1 -0
  8. package/dist/chunk-IDEA5UXK.js +272 -0
  9. package/dist/chunk-IDEA5UXK.js.map +1 -0
  10. package/dist/chunk-MPKXXZZV.js +37 -0
  11. package/dist/chunk-MPKXXZZV.js.map +1 -0
  12. package/dist/chunk-O6FTSXHE.cjs +463 -0
  13. package/dist/chunk-O6FTSXHE.cjs.map +1 -0
  14. package/dist/chunk-PI473GES.js +463 -0
  15. package/dist/chunk-PI473GES.js.map +1 -0
  16. package/dist/chunk-QZE7HBZB.cjs +529 -0
  17. package/dist/chunk-QZE7HBZB.cjs.map +1 -0
  18. package/dist/chunk-WKBWRG7N.js +209 -0
  19. package/dist/chunk-WKBWRG7N.js.map +1 -0
  20. package/dist/chunk-ZDZCCOUB.cjs +209 -0
  21. package/dist/chunk-ZDZCCOUB.cjs.map +1 -0
  22. package/dist/core.d.cts +5 -1
  23. package/dist/core.d.ts +5 -1
  24. package/dist/docs-io.cjs +496 -0
  25. package/dist/docs-io.cjs.map +1 -0
  26. package/dist/docs-io.d.cts +147 -0
  27. package/dist/docs-io.d.ts +147 -0
  28. package/dist/docs-io.js +496 -0
  29. package/dist/docs-io.js.map +1 -0
  30. package/dist/docs-tools.cjs +217 -0
  31. package/dist/docs-tools.cjs.map +1 -0
  32. package/dist/docs-tools.d.cts +150 -0
  33. package/dist/docs-tools.d.ts +150 -0
  34. package/dist/docs-tools.js +217 -0
  35. package/dist/docs-tools.js.map +1 -0
  36. package/dist/docs.cjs +657 -0
  37. package/dist/docs.cjs.map +1 -0
  38. package/dist/docs.d.cts +582 -0
  39. package/dist/docs.d.ts +582 -0
  40. package/dist/docs.js +657 -0
  41. package/dist/docs.js.map +1 -0
  42. package/dist/matrxImagePorts-JDFYE4QI.cjs +59 -0
  43. package/dist/matrxImagePorts-JDFYE4QI.cjs.map +1 -0
  44. package/dist/matrxImagePorts-VPBBUADM.js +59 -0
  45. package/dist/matrxImagePorts-VPBBUADM.js.map +1 -0
  46. package/dist/sheets-xlsx.cjs +525 -0
  47. package/dist/sheets-xlsx.cjs.map +1 -0
  48. package/dist/sheets-xlsx.d.cts +153 -0
  49. package/dist/sheets-xlsx.d.ts +153 -0
  50. package/dist/sheets-xlsx.js +525 -0
  51. package/dist/sheets-xlsx.js.map +1 -0
  52. package/dist/sheets.cjs +921 -0
  53. package/dist/sheets.cjs.map +1 -0
  54. package/dist/sheets.d.cts +605 -0
  55. package/dist/sheets.d.ts +605 -0
  56. package/dist/sheets.js +921 -0
  57. package/dist/sheets.js.map +1 -0
  58. package/dist/univer-collab.cjs +4 -77
  59. package/dist/univer-collab.cjs.map +1 -1
  60. package/dist/univer-collab.d.cts +8 -15
  61. package/dist/univer-collab.d.ts +8 -15
  62. package/dist/univer-collab.js +4 -77
  63. package/dist/univer-collab.js.map +1 -1
  64. package/dist/univer-realtime.cjs +102 -0
  65. package/dist/univer-realtime.cjs.map +1 -0
  66. package/dist/univer-realtime.d.cts +15 -0
  67. package/dist/univer-realtime.d.ts +15 -0
  68. package/dist/univer-realtime.js +80 -0
  69. package/dist/univer-realtime.js.map +1 -0
  70. package/dist/xlsx-to-univer-AQAXU3TC.cjs +7 -0
  71. package/dist/xlsx-to-univer-AQAXU3TC.cjs.map +1 -0
  72. package/dist/xlsx-to-univer-OPMMBWEW.js +7 -0
  73. package/dist/xlsx-to-univer-OPMMBWEW.js.map +1 -0
  74. package/package.json +75 -4
@@ -0,0 +1,525 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+ var _chunkZDZCCOUBcjs = require('./chunk-ZDZCCOUB.cjs');
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+ var _chunkQZE7HBZBcjs = require('./chunk-QZE7HBZB.cjs');
28
+
29
+ // src/sheets/univer-to-xlsx.ts
30
+ var _operate = require('@ai-matrx/alchemy/operate');
31
+ var _download = require('@ai-matrx/kit/download');
32
+ var _xlsxstyled = require('@ai-matrx/print/xlsx-styled');
33
+ function univerSnapshotToWorkbookJson(snapshot) {
34
+ const sheetOrder = _nullishCoalesce(snapshot.sheetOrder, () => ( Object.keys(_nullishCoalesce(snapshot.sheets, () => ( {})))));
35
+ const sheets = [];
36
+ for (const sheetId of sheetOrder) {
37
+ const sheet = _optionalChain([snapshot, 'access', _ => _.sheets, 'optionalAccess', _2 => _2[sheetId]]);
38
+ if (!sheet) continue;
39
+ sheets.push(sheetToJson(sheet, (_nullishCoalesce(sheet.name, () => ( sheetId))).slice(0, 31) || "Sheet1"));
40
+ }
41
+ return { sheets };
42
+ }
43
+ async function univerSnapshotToXlsxBytes(snapshot, options = {}) {
44
+ return (await buildXlsxFromUniver(snapshot, options)).bytes;
45
+ }
46
+ async function downloadUniverAsXlsx(snapshot, options = {}) {
47
+ if (typeof document === "undefined") return { dropped: [] };
48
+ const filename = `${(_nullishCoalesce(options.filename, () => ( "workbook"))).replace(/\.xlsx$/i, "")}.xlsx`;
49
+ const { bytes, report } = await buildXlsxFromUniver(snapshot, options);
50
+ const blob = new Blob([bytes], {
51
+ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
52
+ });
53
+ _download.downloadFile.call(void 0, filename, blob, blob.type);
54
+ return report;
55
+ }
56
+ async function buildXlsxFromUniver(snapshot, options = {}) {
57
+ const ExcelJS = await _xlsxstyled.loadExcelJs.call(void 0, );
58
+ const wb = new ExcelJS.Workbook();
59
+ const dropped = /* @__PURE__ */ new Set();
60
+ const resources = _nullishCoalesce(snapshot.resources, () => ( []));
61
+ const styles = _nullishCoalesce(snapshot.styles, () => ( {}));
62
+ const validation = _nullishCoalesce(_chunkQZE7HBZBcjs.readResource.call(void 0, resources, _chunkQZE7HBZBcjs.RESOURCE.validation), () => ( {}));
63
+ const conditional = _nullishCoalesce(_chunkQZE7HBZBcjs.readResource.call(void 0, resources, _chunkQZE7HBZBcjs.RESOURCE.conditional), () => ( {}));
64
+ const filters = _nullishCoalesce(_chunkQZE7HBZBcjs.readResource.call(void 0, resources, _chunkQZE7HBZBcjs.RESOURCE.filter), () => ( {}));
65
+ const notes = _nullishCoalesce(_chunkQZE7HBZBcjs.readResource.call(void 0, resources, _chunkQZE7HBZBcjs.RESOURCE.note), () => ( {}));
66
+ const comments = _nullishCoalesce(_chunkQZE7HBZBcjs.readResource.call(void 0, resources, _chunkQZE7HBZBcjs.RESOURCE.comments), () => ( {}));
67
+ const drawings = _nullishCoalesce(_chunkQZE7HBZBcjs.readResource.call(void 0, resources, _chunkQZE7HBZBcjs.RESOURCE.drawing), () => ( {}));
68
+ const tables = _nullishCoalesce(_chunkQZE7HBZBcjs.readResource.call(void 0, resources, _chunkQZE7HBZBcjs.RESOURCE.table), () => ( {}));
69
+ const order = _nullishCoalesce(snapshot.sheetOrder, () => ( Object.keys(_nullishCoalesce(snapshot.sheets, () => ( {})))));
70
+ for (const sheetId of order) {
71
+ const sheet = _optionalChain([snapshot, 'access', _3 => _3.sheets, 'optionalAccess', _4 => _4[sheetId]]);
72
+ if (!sheet) continue;
73
+ const ws = wb.addWorksheet(uniqueName(wb, (_nullishCoalesce(sheet.name, () => ( sheetId))).slice(0, 31) || "Sheet1"));
74
+ writeCells(ws, sheet, styles);
75
+ writeLayout(ws, sheet);
76
+ const tab = _chunkQZE7HBZBcjs.colorToArgb.call(void 0, typeof sheet.tabColor === "string" ? sheet.tabColor : void 0);
77
+ if (tab) ws.properties.tabColor = { argb: tab };
78
+ writeValidation(ws, validation[sheetId], dropped);
79
+ writeConditional(ws, conditional[sheetId], dropped);
80
+ writeFilter(ws, filters[sheetId], dropped);
81
+ writeNotes(ws, notes[sheetId], comments[sheetId], dropped);
82
+ await writeImages(wb, ws, drawings[sheetId], options.resolveImage, dropped);
83
+ if (tables[sheetId] && Object.keys(tables[sheetId]).length) {
84
+ dropped.add("Tables are exported as plain ranges (their data and styling are kept)");
85
+ }
86
+ }
87
+ const buffer = await wb.xlsx.writeBuffer();
88
+ return { bytes: new Uint8Array(buffer), report: { dropped: [...dropped] } };
89
+ }
90
+ function uniqueName(wb, name) {
91
+ let candidate = name;
92
+ let n = 2;
93
+ while (wb.getWorksheet(candidate)) candidate = `${name.slice(0, 28)} ${n++}`;
94
+ return candidate;
95
+ }
96
+ function styleOf(cell, styles) {
97
+ const s = cell.s;
98
+ if (!s) return void 0;
99
+ return typeof s === "string" ? styles[s] : s;
100
+ }
101
+ function applyStyle(target, st) {
102
+ if (!st) return;
103
+ const font = {};
104
+ if (st.ff) font.name = String(st.ff);
105
+ if (typeof st.fs === "number") font.size = st.fs;
106
+ if (st.bl === 1) font.bold = true;
107
+ if (st.it === 1) font.italic = true;
108
+ if (_optionalChain([st, 'access', _5 => _5.ul, 'optionalAccess', _6 => _6.s]) === 1) font.underline = true;
109
+ if (_optionalChain([st, 'access', _7 => _7.st, 'optionalAccess', _8 => _8.s]) === 1) font.strike = true;
110
+ const fg = _chunkQZE7HBZBcjs.colorToArgb.call(void 0, _optionalChain([st, 'access', _9 => _9.cl, 'optionalAccess', _10 => _10.rgb]));
111
+ if (fg) font.color = { argb: fg };
112
+ if (Object.keys(font).length) target.font = font;
113
+ const bg = _chunkQZE7HBZBcjs.colorToArgb.call(void 0, _optionalChain([st, 'access', _11 => _11.bg, 'optionalAccess', _12 => _12.rgb]));
114
+ if (bg) target.fill = { type: "pattern", pattern: "solid", fgColor: { argb: bg } };
115
+ const alignment = {};
116
+ if (typeof st.ht === "number" && _chunkQZE7HBZBcjs.H_ALIGN_OUT[st.ht]) alignment.horizontal = _chunkQZE7HBZBcjs.H_ALIGN_OUT[st.ht];
117
+ if (typeof st.vt === "number" && _chunkQZE7HBZBcjs.V_ALIGN_OUT[st.vt]) alignment.vertical = _chunkQZE7HBZBcjs.V_ALIGN_OUT[st.vt];
118
+ if (st.tb === 3) alignment.wrapText = true;
119
+ if (Object.keys(alignment).length) target.alignment = alignment;
120
+ const bd = st.bd;
121
+ if (bd) {
122
+ const border = {};
123
+ for (const [key, side] of [["t", "top"], ["b", "bottom"], ["l", "left"], ["r", "right"]]) {
124
+ const b = bd[key];
125
+ const style = _chunkQZE7HBZBcjs.borderToExcel.call(void 0, _optionalChain([b, 'optionalAccess', _13 => _13.s]));
126
+ if (style) {
127
+ border[side] = { style, color: { argb: _nullishCoalesce(_chunkQZE7HBZBcjs.colorToArgb.call(void 0, _optionalChain([b, 'optionalAccess', _14 => _14.cl, 'optionalAccess', _15 => _15.rgb])), () => ( "FF000000")) } };
128
+ }
129
+ }
130
+ if (Object.keys(border).length) target.border = border;
131
+ }
132
+ const pattern = _optionalChain([st, 'access', _16 => _16.n, 'optionalAccess', _17 => _17.pattern]);
133
+ if (typeof pattern === "string" && pattern && pattern !== "General") target.numFmt = pattern;
134
+ }
135
+ function plainText(p) {
136
+ return String(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _18 => _18.body, 'optionalAccess', _19 => _19.dataStream]), () => ( ""))).replace(/\r\n$/, "").replace(/\r\n/g, "\n");
137
+ }
138
+ function linkOf(p) {
139
+ const ranges = _optionalChain([p, 'optionalAccess', _20 => _20.body, 'optionalAccess', _21 => _21.customRanges]);
140
+ return _optionalChain([ranges, 'optionalAccess', _22 => _22.find, 'call', _23 => _23((r) => r.rangeType === 0 && _optionalChain([r, 'access', _24 => _24.properties, 'optionalAccess', _25 => _25.url])), 'optionalAccess', _26 => _26.properties, 'optionalAccess', _27 => _27.url]);
141
+ }
142
+ function writeCells(ws, sheet, styles) {
143
+ const cellData = _nullishCoalesce(sheet.cellData, () => ( {}));
144
+ for (const rKey of Object.keys(cellData)) {
145
+ const r = Number(rKey);
146
+ const row = cellData[r];
147
+ if (!row || !Number.isFinite(r)) continue;
148
+ for (const cKey of Object.keys(row)) {
149
+ const c = Number(cKey);
150
+ const cell = row[c];
151
+ if (!cell || !Number.isFinite(c)) continue;
152
+ const target = ws.getCell(r + 1, c + 1);
153
+ const formula = typeof cell.f === "string" ? cell.f.replace(/^=/, "") : void 0;
154
+ const rich = cell.p;
155
+ let value = null;
156
+ if (cell.v !== void 0 && cell.v !== null && cell.v !== "") {
157
+ if (cell.t === 3) value = Boolean(cell.v);
158
+ else if (cell.t === 2 || typeof cell.v === "number") value = Number(cell.v);
159
+ else value = String(cell.v);
160
+ } else if (rich) {
161
+ value = plainText(rich);
162
+ }
163
+ const url = linkOf(rich);
164
+ if (url) value = { text: String(_nullishCoalesce(value, () => ( url))), hyperlink: url };
165
+ if (formula) value = { formula, result: _nullishCoalesce(value, () => ( void 0)) };
166
+ if (value !== null && value !== "") target.value = value;
167
+ applyStyle(target, styleOf(cell, styles));
168
+ }
169
+ }
170
+ }
171
+ function writeLayout(ws, sheet) {
172
+ const defaultCol = sheet.defaultColumnWidth;
173
+ const columns = _nullishCoalesce(sheet.columnData, () => ( {}));
174
+ for (const key of Object.keys(columns)) {
175
+ const c = Number(key);
176
+ const col = columns[c];
177
+ if (!col) continue;
178
+ const target = ws.getColumn(c + 1);
179
+ if (typeof col.w === "number") target.width = _chunkQZE7HBZBcjs.colPxToChars.call(void 0, col.w);
180
+ else if (defaultCol) target.width = _chunkQZE7HBZBcjs.colPxToChars.call(void 0, defaultCol);
181
+ if (col.hd === 1) target.hidden = true;
182
+ }
183
+ const rows = _nullishCoalesce(sheet.rowData, () => ( {}));
184
+ for (const key of Object.keys(rows)) {
185
+ const r = Number(key);
186
+ const row = rows[r];
187
+ if (!row) continue;
188
+ const target = ws.getRow(r + 1);
189
+ if (typeof row.h === "number") target.height = _chunkQZE7HBZBcjs.rowPxToPt.call(void 0, row.h);
190
+ if (row.hd === 1) target.hidden = true;
191
+ }
192
+ for (const m of _nullishCoalesce(sheet.mergeData, () => ( []))) {
193
+ try {
194
+ ws.mergeCells(m.startRow + 1, m.startColumn + 1, m.endRow + 1, m.endColumn + 1);
195
+ } catch (e2) {
196
+ }
197
+ }
198
+ const freeze = sheet.freeze;
199
+ if (freeze && (freeze.xSplit > 0 || freeze.ySplit > 0)) {
200
+ ws.views = [{ state: "frozen", xSplit: freeze.xSplit, ySplit: freeze.ySplit }];
201
+ }
202
+ }
203
+ var eachCell = (ranges, fn, cap = 1e5) => {
204
+ let n = 0;
205
+ for (const r of ranges) {
206
+ for (let row = r.startRow; row <= r.endRow; row++) {
207
+ for (let col = r.startColumn; col <= r.endColumn; col++) {
208
+ if (++n > cap) return false;
209
+ fn(row, col);
210
+ }
211
+ }
212
+ }
213
+ return true;
214
+ };
215
+ function writeValidation(ws, rules, dropped) {
216
+ for (const rule of _nullishCoalesce(rules, () => ( []))) {
217
+ const type = String(rule.type);
218
+ const base = {
219
+ allowBlank: rule.allowBlank !== false,
220
+ showErrorMessage: rule.showErrorMessage !== false,
221
+ errorTitle: rule.errorTitle,
222
+ error: rule.error,
223
+ showInputMessage: Boolean(rule.showInputMessage),
224
+ promptTitle: rule.promptTitle,
225
+ prompt: rule.prompt
226
+ };
227
+ let dv = null;
228
+ if (type === "list" || type === "listMultiple") {
229
+ const f1 = String(_nullishCoalesce(rule.formula1, () => ( "")));
230
+ const isRange = /^=?'?[^,"]*!?\$?[A-Z]+\$?\d+(:\$?[A-Z]+\$?\d+)?$/i.test(f1) && !f1.includes(",");
231
+ dv = { ...base, type: "list", formulae: [isRange ? f1.replace(/^=/, "") : `"${f1.replace(/"/g, "")}"`] };
232
+ if (type === "listMultiple") dropped.add("Multi-select dropdowns become single-select");
233
+ } else if (type === "checkbox") {
234
+ dv = { ...base, type: "list", formulae: ['"TRUE,FALSE"'] };
235
+ dropped.add("Checkboxes become TRUE/FALSE dropdowns");
236
+ } else if (["whole", "decimal", "date", "time", "textLength"].includes(type)) {
237
+ dv = {
238
+ ...base,
239
+ type,
240
+ operator: _nullishCoalesce(rule.operator, () => ( "between")),
241
+ formulae: [rule.formula1, rule.formula2].filter((f) => f !== void 0 && f !== "")
242
+ };
243
+ } else if (type === "custom") {
244
+ dv = { ...base, type: "custom", formulae: [String(_nullishCoalesce(rule.formula1, () => ( ""))).replace(/^=/, "")] };
245
+ }
246
+ if (!dv) continue;
247
+ if (!dv.errorTitle) delete dv.errorTitle;
248
+ const complete = eachCell(_nullishCoalesce(rule.ranges, () => ( [])), (r, c) => {
249
+ ws.getCell(r + 1, c + 1).dataValidation = dv;
250
+ });
251
+ if (!complete) dropped.add("Data validation on very large ranges was cut off");
252
+ }
253
+ }
254
+ var NUMBER_OPS = /* @__PURE__ */ new Set(["greaterThan", "greaterThanOrEqual", "lessThan", "lessThanOrEqual", "equal", "notEqual", "between", "notBetween"]);
255
+ function cfStyle(style) {
256
+ const out = {};
257
+ const font = {};
258
+ const fg = _chunkQZE7HBZBcjs.colorToArgb.call(void 0, _optionalChain([style, 'optionalAccess', _28 => _28.cl, 'optionalAccess', _29 => _29.rgb]));
259
+ if (fg) font.color = { argb: fg };
260
+ if (_optionalChain([style, 'optionalAccess', _30 => _30.bl]) === 1) font.bold = true;
261
+ if (_optionalChain([style, 'optionalAccess', _31 => _31.it]) === 1) font.italic = true;
262
+ if (Object.keys(font).length) out.font = font;
263
+ const bg = _chunkQZE7HBZBcjs.colorToArgb.call(void 0, _optionalChain([style, 'optionalAccess', _32 => _32.bg, 'optionalAccess', _33 => _33.rgb]));
264
+ if (bg) out.fill = { type: "pattern", pattern: "solid", bgColor: { argb: bg } };
265
+ return out;
266
+ }
267
+ function writeConditional(ws, rules, dropped) {
268
+ for (const entry of _nullishCoalesce(rules, () => ( []))) {
269
+ const ranges = _nullishCoalesce(entry.ranges, () => ( []));
270
+ if (!ranges.length) continue;
271
+ const ref = ranges.map(_chunkQZE7HBZBcjs.rangeToA1).join(" ");
272
+ const first = ranges[0];
273
+ const topLeft = _chunkQZE7HBZBcjs.rangeToA1.call(void 0, { ...first, endRow: first.startRow, endColumn: first.startColumn });
274
+ const rule = entry.rule;
275
+ let out = null;
276
+ if (_optionalChain([rule, 'optionalAccess', _34 => _34.type]) === "highlightCell") {
277
+ const style = cfStyle(rule.style);
278
+ switch (rule.subType) {
279
+ case "number":
280
+ if (NUMBER_OPS.has(rule.operator)) {
281
+ out = { type: "cellIs", operator: rule.operator, formulae: Array.isArray(rule.value) ? rule.value : [rule.value], style };
282
+ }
283
+ break;
284
+ case "text":
285
+ if (rule.operator === "containsText") out = { type: "containsText", operator: "containsText", text: String(_nullishCoalesce(rule.value, () => ( ""))), style };
286
+ break;
287
+ case "duplicateValues":
288
+ out = { type: "expression", formulae: [`COUNTIF(${ref.split(" ")[0]},${topLeft})>1`], style };
289
+ break;
290
+ case "uniqueValues":
291
+ out = { type: "expression", formulae: [`COUNTIF(${ref.split(" ")[0]},${topLeft})=1`], style };
292
+ break;
293
+ case "formula":
294
+ out = { type: "expression", formulae: [String(_nullishCoalesce(rule.value, () => ( ""))).replace(/^=/, "")], style };
295
+ break;
296
+ }
297
+ } else if (_optionalChain([rule, 'optionalAccess', _35 => _35.type]) === "colorScale" && Array.isArray(rule.config)) {
298
+ const cfg = [...rule.config].sort((a, b) => a.index - b.index);
299
+ out = {
300
+ type: "colorScale",
301
+ cfvo: cfg.map((c) => ({ type: _nullishCoalesce(_optionalChain([c, 'access', _36 => _36.value, 'optionalAccess', _37 => _37.type]), () => ( "min")), ..._optionalChain([c, 'access', _38 => _38.value, 'optionalAccess', _39 => _39.value]) !== void 0 ? { value: c.value.value } : {} })),
302
+ color: cfg.map((c) => ({ argb: _nullishCoalesce(_chunkQZE7HBZBcjs.colorToArgb.call(void 0, c.color), () => ( "FFFFFFFF")) }))
303
+ };
304
+ } else if (_optionalChain([rule, 'optionalAccess', _40 => _40.type]) === "dataBar") {
305
+ out = {
306
+ type: "dataBar",
307
+ gradient: _optionalChain([rule, 'access', _41 => _41.config, 'optionalAccess', _42 => _42.isGradient]) !== false,
308
+ cfvo: [{ type: _nullishCoalesce(_optionalChain([rule, 'access', _43 => _43.config, 'optionalAccess', _44 => _44.min, 'optionalAccess', _45 => _45.type]), () => ( "min")) }, { type: _nullishCoalesce(_optionalChain([rule, 'access', _46 => _46.config, 'optionalAccess', _47 => _47.max, 'optionalAccess', _48 => _48.type]), () => ( "max")) }],
309
+ color: { argb: _nullishCoalesce(_chunkQZE7HBZBcjs.colorToArgb.call(void 0, _optionalChain([rule, 'access', _49 => _49.config, 'optionalAccess', _50 => _50.positiveColor])), () => ( "FF638EC6")) }
310
+ };
311
+ }
312
+ if (!out) {
313
+ dropped.add("Some conditional formats (icon sets, top/bottom, average, date rules) are not written");
314
+ continue;
315
+ }
316
+ ws.addConditionalFormatting({ ref, rules: [{ ...out, priority: 1 }] });
317
+ }
318
+ }
319
+ function writeFilter(ws, filter, dropped) {
320
+ const ref = _optionalChain([filter, 'optionalAccess', _51 => _51.ref]);
321
+ if (!ref) return;
322
+ ws.autoFilter = {
323
+ from: { row: ref.startRow + 1, column: ref.startColumn + 1 },
324
+ to: { row: ref.endRow + 1, column: ref.endColumn + 1 }
325
+ };
326
+ if (_optionalChain([filter, 'optionalAccess', _52 => _52.filterColumns, 'optionalAccess', _53 => _53.length])) {
327
+ dropped.add("Which filter choices were applied is not saved (the filter arrows are)");
328
+ }
329
+ }
330
+ function threadText(c) {
331
+ return String(_nullishCoalesce(_optionalChain([c, 'optionalAccess', _54 => _54.text, 'optionalAccess', _55 => _55.dataStream]), () => ( ""))).replace(/\r\n?$/, "").replace(/\r\n?/g, "\n");
332
+ }
333
+ function writeNotes(ws, sheetNotes, sheetComments, dropped) {
334
+ for (const [row, cols] of Object.entries(_nullishCoalesce(sheetNotes, () => ( {})))) {
335
+ for (const [col, note] of Object.entries(cols)) {
336
+ const text = String(_nullishCoalesce(note.note, () => ( "")));
337
+ if (text) ws.getCell(Number(row) + 1, Number(col) + 1).note = text;
338
+ }
339
+ }
340
+ const list = Array.isArray(sheetComments) ? sheetComments : sheetComments ? Object.values(sheetComments).flat() : [];
341
+ const threads = /* @__PURE__ */ new Map();
342
+ for (const c of list) {
343
+ if (!_optionalChain([c, 'optionalAccess', _56 => _56.ref])) continue;
344
+ const lines = _nullishCoalesce(threads.get(c.ref), () => ( []));
345
+ const who = _nullishCoalesce(_nullishCoalesce(c.authorName, () => ( c.personId)), () => ( ""));
346
+ lines.push(`${who ? who + ": " : ""}${threadText(c)}`);
347
+ for (const child of _nullishCoalesce(c.children, () => ( []))) {
348
+ lines.push(`${_nullishCoalesce(_nullishCoalesce(child.authorName, () => ( child.personId)), () => ( ""))}: ${threadText(child)}`);
349
+ }
350
+ threads.set(c.ref, lines);
351
+ }
352
+ for (const [ref, lines] of threads) {
353
+ const cell = ws.getCell(ref);
354
+ const existing = typeof cell.note === "string" ? cell.note : "";
355
+ cell.note = [existing, ...lines].filter(Boolean).join("\n");
356
+ }
357
+ if (threads.size) dropped.add("Comment threads are written as cell notes (replies and resolved state are flattened)");
358
+ }
359
+ async function writeImages(wb, ws, sheetDrawings, resolve, dropped) {
360
+ const data = _nullishCoalesce(_optionalChain([sheetDrawings, 'optionalAccess', _57 => _57.data]), () => ( {}));
361
+ for (const d of Object.values(data)) {
362
+ if (d.drawingType !== 0 || !d.source) continue;
363
+ const from = _optionalChain([d, 'access', _58 => _58.sheetTransform, 'optionalAccess', _59 => _59.from]);
364
+ if (!from) continue;
365
+ let bytes = null;
366
+ let extension = "png";
367
+ const dataUrl = /^data:image\/(png|jpeg|jpg|gif);base64,(.+)$/i.exec(String(d.source));
368
+ if (dataUrl) {
369
+ extension = dataUrl[1].toLowerCase() === "gif" ? "gif" : dataUrl[1].toLowerCase() === "png" ? "png" : "jpeg";
370
+ bytes = Uint8Array.from(atob(dataUrl[2]), (ch) => ch.charCodeAt(0));
371
+ } else if (resolve) {
372
+ try {
373
+ const got = await resolve(String(d.source));
374
+ if (got) ({ bytes, extension } = got);
375
+ } catch (e3) {
376
+ bytes = null;
377
+ }
378
+ }
379
+ if (!bytes) {
380
+ dropped.add("Some pictures could not be read and were left out");
381
+ continue;
382
+ }
383
+ const id = wb.addImage({ buffer: bytes, extension });
384
+ ws.addImage(id, {
385
+ tl: { col: from.column + (_nullishCoalesce(from.columnOffset, () => ( 0))) / 64, row: from.row + (_nullishCoalesce(from.rowOffset, () => ( 0))) / 20 },
386
+ ext: { width: _nullishCoalesce(_optionalChain([d, 'access', _60 => _60.transform, 'optionalAccess', _61 => _61.width]), () => ( 200)), height: _nullishCoalesce(_optionalChain([d, 'access', _62 => _62.transform, 'optionalAccess', _63 => _63.height]), () => ( 150)) }
387
+ });
388
+ }
389
+ }
390
+ function sheetToJson(sheet, name) {
391
+ const cellData = _nullishCoalesce(sheet.cellData, () => ( {}));
392
+ const rows = [];
393
+ for (const rKey of Object.keys(cellData)) {
394
+ const r = Number(rKey);
395
+ if (!Number.isFinite(r)) continue;
396
+ const row = cellData[r];
397
+ if (!row) continue;
398
+ for (const cKey of Object.keys(row)) {
399
+ const c = Number(cKey);
400
+ if (!Number.isFinite(c)) continue;
401
+ const cell = row[c];
402
+ if (!cell) continue;
403
+ const out = toWorkbookCell(cell);
404
+ if (!out) continue;
405
+ while (rows.length <= r) rows.push([]);
406
+ const line = rows[r];
407
+ while (line.length < c) line.push(null);
408
+ line[c] = out;
409
+ }
410
+ }
411
+ const merges = (_nullishCoalesce(sheet.mergeData, () => ( []))).map((m) => ({
412
+ s: { r: m.startRow, c: m.startColumn },
413
+ e: { r: m.endRow, c: m.endColumn }
414
+ }));
415
+ return { name, rows, ...merges.length ? { merges } : {} };
416
+ }
417
+ function toWorkbookCell(cell) {
418
+ const formula = typeof cell.f === "string" ? cell.f.replace(/^=/, "") : void 0;
419
+ let out;
420
+ switch (cell.t) {
421
+ case 2:
422
+ out = { t: "n", v: typeof cell.v === "number" ? cell.v : Number(_nullishCoalesce(cell.v, () => ( 0))) };
423
+ break;
424
+ case 3:
425
+ out = { t: "b", v: Boolean(cell.v) };
426
+ break;
427
+ default:
428
+ out = {
429
+ t: "s",
430
+ v: cell.v === null || cell.v === void 0 ? "" : typeof cell.v === "object" ? JSON.stringify(cell.v) : String(cell.v)
431
+ };
432
+ }
433
+ if ((out.v === "" || out.v === null || out.v === void 0) && !formula) return null;
434
+ return formula ? { ...out, f: formula } : out;
435
+ }
436
+ async function univerSnapshotToRegisteredXlsxBytes(snapshot) {
437
+ const built = await _operate.buildFile.call(void 0,
438
+ { kind: "registered", format: "workbook", value: univerSnapshotToWorkbookJson(snapshot) },
439
+ "xlsx-workbook"
440
+ );
441
+ return built.bytes;
442
+ }
443
+
444
+ // src/sheets/import-workbook-file.ts
445
+ var _core = require('@ai-matrx/records/core');
446
+ function unsupportedFileReason(file) {
447
+ const name = file.name.toLowerCase();
448
+ if (name.endsWith(".xlsx") || name.endsWith(".xls") || name.endsWith(".csv")) {
449
+ return null;
450
+ }
451
+ if (name.endsWith(".tsv") || name.endsWith(".txt")) return null;
452
+ if (name.endsWith(".gsheet")) {
453
+ return "A Google Sheets shortcut can't be uploaded. Use Import from Google Sheets.";
454
+ }
455
+ return `"${file.name}" isn't a spreadsheet file. Supported: .xlsx, .xls, .csv. For a Google Sheet, use Import from Google Sheets.`;
456
+ }
457
+ async function importWorkbookFile(file, organizationId) {
458
+ const capturedOrganizationId = await _chunkZDZCCOUBcjs.getSheetsHost.call(void 0, ).ensureOrgId(organizationId);
459
+ const { xlsxToUniverWorkbook: xlsxToUniverWorkbook2 } = await Promise.resolve().then(() => _interopRequireWildcard(require("./xlsx-to-univer-AQAXU3TC.cjs")));
460
+ const droppedOnImport = [];
461
+ const { uploadImportedImage } = await Promise.resolve().then(() => _interopRequireWildcard(require("./matrxImagePorts-JDFYE4QI.cjs")));
462
+ const snapshot = await xlsxToUniverWorkbook2(file, {
463
+ uploadImage: uploadImportedImage,
464
+ onDropped: (what) => droppedOnImport.push(what)
465
+ });
466
+ let originalFileId;
467
+ try {
468
+ const uploaded = await _chunkZDZCCOUBcjs.getSheetsHost.call(void 0, ).uploadOriginalFile(file, { folderPath: "Workbooks/Imports" });
469
+ originalFileId = uploaded.fileId;
470
+ } catch (uploadErr) {
471
+ console.warn(
472
+ "Workbook import: stashing original failed; continuing without link.",
473
+ uploadErr
474
+ );
475
+ }
476
+ const cleanName = file.name.replace(/\.[^.]+$/, "") || "Imported workbook";
477
+ const created = await _chunkZDZCCOUBcjs.createWorkbook.call(void 0, {
478
+ name: cleanName,
479
+ description: `Imported from ${file.name}`,
480
+ source: file.name.toLowerCase().endsWith(".csv") ? "imported_csv" : "imported_xlsx",
481
+ organizationId: capturedOrganizationId,
482
+ ...originalFileId ? { originalFileId } : {}
483
+ });
484
+ if (_core.isServiceFailure.call(void 0, created)) throw new Error(created.error);
485
+ const saved = await _chunkZDZCCOUBcjs.saveSnapshot.call(void 0, {
486
+ workbookId: created.data.id,
487
+ snapshot,
488
+ origin: "imported",
489
+ label: file.name
490
+ });
491
+ if (_core.isServiceFailure.call(void 0, saved)) {
492
+ await _chunkZDZCCOUBcjs.discardFailedWorkbook.call(void 0, created.data.id);
493
+ throw new Error(saved.error);
494
+ }
495
+ return { id: created.data.id, name: cleanName, notCarried: droppedOnImport };
496
+ }
497
+
498
+
499
+
500
+
501
+
502
+
503
+
504
+
505
+
506
+
507
+
508
+
509
+
510
+
511
+
512
+
513
+
514
+
515
+
516
+
517
+
518
+
519
+
520
+
521
+
522
+
523
+
524
+ exports.H_ALIGN_IN = _chunkQZE7HBZBcjs.H_ALIGN_IN; exports.H_ALIGN_OUT = _chunkQZE7HBZBcjs.H_ALIGN_OUT; exports.RESOURCE = _chunkQZE7HBZBcjs.RESOURCE; exports.V_ALIGN_IN = _chunkQZE7HBZBcjs.V_ALIGN_IN; exports.V_ALIGN_OUT = _chunkQZE7HBZBcjs.V_ALIGN_OUT; exports.a1 = _chunkQZE7HBZBcjs.a1; exports.argbToColor = _chunkQZE7HBZBcjs.argbToColor; exports.borderFromExcel = _chunkQZE7HBZBcjs.borderFromExcel; exports.borderToExcel = _chunkQZE7HBZBcjs.borderToExcel; exports.buildXlsxFromUniver = buildXlsxFromUniver; exports.colCharsToPx = _chunkQZE7HBZBcjs.colCharsToPx; exports.colPxToChars = _chunkQZE7HBZBcjs.colPxToChars; exports.colorToArgb = _chunkQZE7HBZBcjs.colorToArgb; exports.downloadUniverAsXlsx = downloadUniverAsXlsx; exports.importWorkbookFile = importWorkbookFile; exports.parseA1Range = _chunkQZE7HBZBcjs.parseA1Range; exports.rangeToA1 = _chunkQZE7HBZBcjs.rangeToA1; exports.readResource = _chunkQZE7HBZBcjs.readResource; exports.rowPtToPx = _chunkQZE7HBZBcjs.rowPtToPx; exports.rowPxToPt = _chunkQZE7HBZBcjs.rowPxToPt; exports.univerSnapshotToRegisteredXlsxBytes = univerSnapshotToRegisteredXlsxBytes; exports.univerSnapshotToWorkbookJson = univerSnapshotToWorkbookJson; exports.univerSnapshotToXlsxBytes = univerSnapshotToXlsxBytes; exports.unsupportedFileReason = unsupportedFileReason; exports.writeResource = _chunkQZE7HBZBcjs.writeResource; exports.xlsxToUniverWorkbook = _chunkQZE7HBZBcjs.xlsxToUniverWorkbook;
525
+ //# sourceMappingURL=sheets-xlsx.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/aidream/aidream/apps/shared/office/dist/sheets-xlsx.cjs","../src/sheets/univer-to-xlsx.ts","../src/sheets/import-workbook-file.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACVA,oDAA0B;AAG1B,kDAA6B;AAC7B,yDAA+C;AAoCxC,SAAS,4BAAA,CAA6B,QAAA,EAAkC;AAC7E,EAAA,MAAM,WAAA,mBAAa,QAAA,CAAS,UAAA,UAAc,MAAA,CAAO,IAAA,kBAAK,QAAA,CAAS,MAAA,UAAU,CAAC,GAAC,GAAA;AAC3E,EAAA,MAAM,OAAA,EAAiC,CAAC,CAAA;AACxC,EAAA,IAAA,CAAA,MAAW,QAAA,GAAW,UAAA,EAAY;AAChC,IAAA,MAAM,MAAA,kBAAQ,QAAA,mBAAS,MAAA,4BAAA,CAAS,OAAO,GAAA;AACvC,IAAA,GAAA,CAAI,CAAC,KAAA,EAAO,QAAA;AACZ,IAAA,MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,KAAA,EAAA,kBAAQ,KAAA,CAAM,IAAA,UAAQ,SAAA,CAAA,CAAS,KAAA,CAAM,CAAA,EAAG,EAAE,EAAA,GAAK,QAAQ,CAAC,CAAA;AAAA,EAClF;AACA,EAAA,OAAO,EAAE,OAAO,CAAA;AAClB;AAGA,MAAA,SAAsB,yBAAA,CACpB,QAAA,EACA,QAAA,EAAmD,CAAC,CAAA,EAC/B;AACrB,EAAA,OAAA,CAAQ,MAAM,mBAAA,CAAoB,QAAA,EAAU,OAAO,CAAA,CAAA,CAAG,KAAA;AACxD;AAGA,MAAA,SAAsB,oBAAA,CACpB,QAAA,EACA,QAAA,EAA6B,CAAC,CAAA,EACH;AAC3B,EAAA,GAAA,CAAI,OAAO,SAAA,IAAa,WAAA,EAAa,OAAO,EAAE,OAAA,EAAS,CAAC,EAAE,CAAA;AAC1D,EAAA,MAAM,SAAA,EAAW,CAAA,EAAA;AACF,EAAA;AACE,EAAA;AACT,IAAA;AACP,EAAA;AACY,EAAA;AACN,EAAA;AACT;AAIsB;AAIJ,EAAA;AACD,EAAA;AACC,EAAA;AACG,EAAA;AACH,EAAA;AAEV,EAAA;AACA,EAAA;AACU,EAAA;AACF,EAAA;AACG,EAAA;AACA,EAAA;AACF,EAAA;AAED,EAAA;AACH,EAAA;AACK,IAAA;AACF,IAAA;AACE,IAAA;AACC,IAAA;AACC,IAAA;AACJ,IAAA;AACA,IAAA;AACI,IAAA;AAChB,IAAA;AACgB,IAAA;AACD,IAAA;AACT,IAAA;AACK,IAAA;AACG,MAAA;AACd,IAAA;AACF,EAAA;AAEe,EAAA;AACC,EAAA;AAClB;AAEoB;AACF,EAAA;AACR,EAAA;AACE,EAAA;AACH,EAAA;AACT;AAEiB;AACA,EAAA;AACA,EAAA;AACD,EAAA;AAChB;AAEoB;AACT,EAAA;AACiC,EAAA;AAC1B,EAAA;AACF,EAAA;AACG,EAAA;AACA,EAAA;AACsB,EAAA;AACA,EAAA;AAC5B,EAAA;AACE,EAAA;AACG,EAAA;AACL,EAAA;AACI,EAAA;AACoC,EAAA;AACrC,EAAA;AACA,EAAA;AACG,EAAA;AACD,EAAA;AACF,EAAA;AACN,EAAA;AACyC,IAAA;AACnC,IAAA;AACG,MAAA;AACC,MAAA;AACH,MAAA;AACY,QAAA;AACvB,MAAA;AACF,IAAA;AACgB,IAAA;AAClB,EAAA;AACiB,EAAA;AACN,EAAA;AACb;AAEmB;AACA,EAAA;AACnB;AAEyD;AACrC,EAAA;AACH,EAAA;AACjB;AAEoB;AACD,EAAA;AACN,EAAA;AACC,IAAA;AACE,IAAA;AACC,IAAA;AACF,IAAA;AACC,MAAA;AACG,MAAA;AACC,MAAA;AACR,MAAA;AACA,MAAA;AACO,MAAA;AACuB,MAAA;AAC3B,MAAA;AACE,QAAA;AACA,QAAA;AACJ,QAAA;AACI,MAAA;AACD,QAAA;AACV,MAAA;AACY,MAAA;AACH,MAAA;AACI,MAAA;AACC,MAAA;AACH,MAAA;AACb,IAAA;AACF,EAAA;AACF;AAES;AACD,EAAA;AACU,EAAA;AACE,EAAA;AACN,IAAA;AACE,IAAA;AACF,IAAA;AACK,IAAA;AACA,IAAA;AACN,IAAA;AACM,IAAA;AACjB,EAAA;AACa,EAAA;AACK,EAAA;AACN,IAAA;AACE,IAAA;AACF,IAAA;AACK,IAAA;AACA,IAAA;AACA,IAAA;AACjB,EAAA;AACgB,EAAA;AACV,IAAA;AACY,MAAA;AACR,IAAA;AAER,IAAA;AACF,EAAA;AACe,EAAA;AACA,EAAA;AACC,IAAA;AAChB,EAAA;AACF;AAEkB;AACR,EAAA;AACQ,EAAA;AACC,IAAA;AACJ,MAAA;AACG,QAAA;AACC,QAAA;AACb,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAES;AACI,EAAA;AACI,IAAA;AACM,IAAA;AACL,MAAA;AACZ,MAAA;AACY,MAAA;AACA,MAAA;AACZ,MAAA;AACa,MAAA;AACA,MAAA;AACf,IAAA;AACsB,IAAA;AACT,IAAA;AACA,MAAA;AACL,MAAA;AACI,MAAA;AACG,MAAA;AACJ,IAAA;AACC,MAAA;AACE,MAAA;AACF,IAAA;AACL,MAAA;AACA,QAAA;AACH,QAAA;AACU,QAAA;AACC,QAAA;AACb,MAAA;AACS,IAAA;AACC,MAAA;AACZ,IAAA;AACS,IAAA;AACD,IAAA;AACF,IAAA;AACO,MAAA;AACZ,IAAA;AACc,IAAA;AACjB,EAAA;AACF;AAEmB;AAEF;AACI,EAAA;AACC,EAAA;AACT,EAAA;AACE,EAAA;AACK,EAAA;AACA,EAAA;AACF,EAAA;AACL,EAAA;AACC,EAAA;AACL,EAAA;AACT;AAES;AACI,EAAA;AACO,IAAA;AACJ,IAAA;AACA,IAAA;AACE,IAAA;AACE,IAAA;AACH,IAAA;AACU,IAAA;AACb,IAAA;AACM,MAAA;AACD,MAAA;AACN,QAAA;AACC,UAAA;AACM,YAAA;AACV,UAAA;AACA,UAAA;AACG,QAAA;AACM,UAAA;AACT,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACJ,MAAA;AACS,IAAA;AACI,MAAA;AACP,MAAA;AACE,QAAA;AACI,QAAA;AACC,QAAA;AACb,MAAA;AACS,IAAA;AACH,MAAA;AACE,QAAA;AACI,QAAA;AACD,QAAA;AACA,QAAA;AACX,MAAA;AACF,IAAA;AACU,IAAA;AACI,MAAA;AACZ,MAAA;AACF,IAAA;AACG,IAAA;AACL,EAAA;AACF;AAES;AACK,EAAA;AACF,EAAA;AACM,EAAA;AACD,IAAA;AACE,IAAA;AACjB,EAAA;AACa,EAAA;AACC,IAAA;AACd,EAAA;AACF;AAEoB;AACD,EAAA;AACnB;AAEoB;AACD,EAAA;AACH,IAAA;AACG,MAAA;AACA,MAAA;AACf,IAAA;AACF,EAAA;AACqB,EAAA;AACL,EAAA;AACA,EAAA;AACD,IAAA;AACC,IAAA;AACA,IAAA;AACA,IAAA;AACH,IAAA;AACK,MAAA;AAChB,IAAA;AACc,IAAA;AAChB,EAAA;AACiB,EAAA;AACC,IAAA;AACV,IAAA;AACO,IAAA;AACf,EAAA;AACkB,EAAA;AACpB;AAEe;AAOC,EAAA;AACE,EAAA;AACR,IAAA;AACS,IAAA;AACJ,IAAA;AACoB,IAAA;AACS,IAAA;AACxB,IAAA;AACH,IAAA;AACC,MAAA;AACJ,MAAA;AACC,IAAA;AACL,MAAA;AACU,QAAA;AACA,QAAA;AACN,MAAA;AACE,QAAA;AACV,MAAA;AACF,IAAA;AACY,IAAA;AACE,MAAA;AACZ,MAAA;AACF,IAAA;AACc,IAAA;AACE,IAAA;AACH,MAAA;AACG,MAAA;AACf,IAAA;AACH,EAAA;AACF;AAIS;AACU,EAAA;AAC4B,EAAA;AAClC,EAAA;AACC,IAAA;AACE,IAAA;AACA,IAAA;AACF,IAAA;AACC,IAAA;AACC,MAAA;AACE,MAAA;AACC,MAAA;AACF,MAAA;AACC,MAAA;AACF,MAAA;AACE,MAAA;AACC,MAAA;AACD,MAAA;AACF,MAAA;AACZ,IAAA;AACF,EAAA;AACgB,EAAA;AACJ,IAAA;AACA,IAAA;AACV,EAAA;AACa,EAAA;AACjB;AAES;AACS,EAAA;AACZ,EAAA;AACY,EAAA;AACT,IAAA;AACQ,MAAA;AACX,MAAA;AACG,IAAA;AACQ,MAAA;AACX,MAAA;AACF,IAAA;AACQ,MAAA;AACD,QAAA;AAEI,QAAA;AAKT,MAAA;AACJ,EAAA;AACe,EAAA;AACE,EAAA;AACnB;AAGsB;AACN,EAAA;AACJ,IAAA;AACR,IAAA;AACF,EAAA;AACa,EAAA;AACf;AD9EoB;AACA;AEpbX;AAgBO;AACI,EAAA;AAGF,EAAA;AAIP,IAAA;AACT,EAAA;AACkB,EAAA;AAIA,EAAA;AACT,IAAA;AACT,EAAA;AAEgB,EAAA;AAClB;AAEsB;AAId,EAAA;AAGE,EAAA;AAEF,EAAA;AACE,EAAA;AACS,EAAA;AACF,IAAA;AACD,IAAA;AACb,EAAA;AAOG,EAAA;AACA,EAAA;AACI,IAAA;AACN,IAAA;AACO,EAAA;AACC,IAAA;AACN,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AAEkB,EAAA;AACF,EAAA;AACR,IAAA;AACO,IAAA;AACA,IAAA;AAGG,IAAA;AACZ,IAAA;AACL,EAAA;AACG,EAAA;AAEU,EAAA;AACA,IAAA;AACZ,IAAA;AACQ,IAAA;AACI,IAAA;AACb,EAAA;AACG,EAAA;AAKI,IAAA;AACU,IAAA;AAClB,EAAA;AAEa,EAAA;AACf;AFwYoB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/aidream/aidream/apps/shared/office/dist/sheets-xlsx.cjs","sourcesContent":[null,"/**\n * univerToXlsx — convert a Univer IWorkbookData snapshot to an .xlsx file.\n *\n * Symmetric counterpart to `xlsx-to-univer.ts`. Carries everything the xlsx\n * format can hold from what Univer holds: values, formulas, merged ranges,\n * cell styles and number formats, column widths, row heights, frozen panes,\n * data validation, conditional formatting, the header-row filter range,\n * notes, comment threads (as notes), cell links, and pictures.\n *\n * What it cannot carry is NAMED in the returned report and shown to the person\n * at export time — never dropped silently.\n *\n * Engine: ExcelJS (the xlsx reader/writer that holds styles, validation,\n * conditional formatting, notes, links and images; the registered\n * `xlsx-workbook` format writes values only). It is loaded on demand, so\n * the editor bundle does not pay for it until someone exports or imports.\n */\n\nimport { buildFile } from \"@ai-matrx/alchemy/operate\";\nimport type { WorkbookCellJson, WorkbookJson } from \"@ai-matrx/alchemy/operate/read\";\nimport type { ICellData, IWorkbookData, IWorksheetData } from \"@univerjs/core\";\nimport { downloadFile } from \"@ai-matrx/kit/download\";\nimport { loadExcelJs, type ExcelJSTypes } from \"@ai-matrx/print/xlsx-styled\";\nimport {\n H_ALIGN_OUT,\n RESOURCE,\n V_ALIGN_OUT,\n borderToExcel,\n colPxToChars,\n colorToArgb,\n readResource,\n rangeToA1,\n rowPxToPt,\n type RangeLike,\n type UniverResource,\n} from \"./xlsx-shared\";\n\nexport type ExportXlsxOptions = {\n /** File name without extension. Defaults to \"workbook\". */\n filename?: string;\n /** Reads a picture's bytes (a `matrx-file:` reference or a URL). Pictures it cannot read are reported. */\n resolveImage?: ExportImagePort;\n};\n\nexport type ExportImagePort = (\n source: string,\n) => Promise<{ bytes: Uint8Array; extension: \"png\" | \"jpeg\" | \"gif\" } | null>;\n\n/** What an export could not carry, in words for the person. Empty when nothing was lost. */\nexport type XlsxExportReport = { dropped: string[] };\n\ntype Snapshot = Partial<IWorkbookData>;\ntype Style = Record<string, unknown>;\ntype Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any -- Univer resource payloads are untyped JSON\n\n// ─── the thin WorkbookJson path (values + merges), kept for other callers ───\n\n/** A Univer snapshot as the `xlsx-workbook` format's value (sheets of typed cells + merges). */\nexport function univerSnapshotToWorkbookJson(snapshot: Snapshot): WorkbookJson {\n const sheetOrder = snapshot.sheetOrder ?? Object.keys(snapshot.sheets ?? {});\n const sheets: WorkbookJson[\"sheets\"] = [];\n for (const sheetId of sheetOrder) {\n const sheet = snapshot.sheets?.[sheetId];\n if (!sheet) continue;\n sheets.push(sheetToJson(sheet, (sheet.name ?? sheetId).slice(0, 31) || \"Sheet1\"));\n }\n return { sheets };\n}\n\n/** Full-fidelity bytes. Does NOT trigger a download. */\nexport async function univerSnapshotToXlsxBytes(\n snapshot: Snapshot,\n options: Pick<ExportXlsxOptions, \"resolveImage\"> = {},\n): Promise<Uint8Array> {\n return (await buildXlsxFromUniver(snapshot, options)).bytes;\n}\n\n/** Convert + trigger a browser download; returns what could not be carried. */\nexport async function downloadUniverAsXlsx(\n snapshot: Snapshot,\n options: ExportXlsxOptions = {},\n): Promise<XlsxExportReport> {\n if (typeof document === \"undefined\") return { dropped: [] };\n const filename = `${(options.filename ?? \"workbook\").replace(/\\.xlsx$/i, \"\")}.xlsx`;\n const { bytes, report } = await buildXlsxFromUniver(snapshot, options);\n const blob = new Blob([bytes as BlobPart], {\n type: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n });\n downloadFile(filename, blob, blob.type);\n return report;\n}\n\n// ─── the full-fidelity writer ──────────────────────────────────────────────\n\nexport async function buildXlsxFromUniver(\n snapshot: Snapshot,\n options: Pick<ExportXlsxOptions, \"resolveImage\"> = {},\n): Promise<{ bytes: Uint8Array; report: XlsxExportReport }> {\n const ExcelJS = await loadExcelJs();\n const wb = new ExcelJS.Workbook();\n const dropped = new Set<string>();\n const resources = (snapshot.resources ?? []) as UniverResource[];\n const styles = (snapshot.styles ?? {}) as Record<string, Style>;\n\n const validation = readResource<Json>(resources, RESOURCE.validation) ?? {};\n const conditional = readResource<Json>(resources, RESOURCE.conditional) ?? {};\n const filters = readResource<Json>(resources, RESOURCE.filter) ?? {};\n const notes = readResource<Json>(resources, RESOURCE.note) ?? {};\n const comments = readResource<Json>(resources, RESOURCE.comments) ?? {};\n const drawings = readResource<Json>(resources, RESOURCE.drawing) ?? {};\n const tables = readResource<Json>(resources, RESOURCE.table) ?? {};\n\n const order = snapshot.sheetOrder ?? Object.keys(snapshot.sheets ?? {});\n for (const sheetId of order) {\n const sheet = snapshot.sheets?.[sheetId] as Partial<IWorksheetData> | undefined;\n if (!sheet) continue;\n const ws = wb.addWorksheet(uniqueName(wb, (sheet.name ?? sheetId).slice(0, 31) || \"Sheet1\"));\n writeCells(ws, sheet, styles);\n writeLayout(ws, sheet);\n const tab = colorToArgb(typeof sheet.tabColor === \"string\" ? sheet.tabColor : undefined);\n if (tab) ws.properties.tabColor = { argb: tab };\n writeValidation(ws, validation[sheetId], dropped);\n writeConditional(ws, conditional[sheetId], dropped);\n writeFilter(ws, filters[sheetId], dropped);\n writeNotes(ws, notes[sheetId], comments[sheetId], dropped);\n await writeImages(wb, ws, drawings[sheetId], options.resolveImage, dropped);\n if (tables[sheetId] && Object.keys(tables[sheetId]).length) {\n dropped.add(\"Tables are exported as plain ranges (their data and styling are kept)\");\n }\n }\n\n const buffer = await wb.xlsx.writeBuffer();\n return { bytes: new Uint8Array(buffer as ArrayBuffer), report: { dropped: [...dropped] } };\n}\n\nfunction uniqueName(wb: ExcelJSTypes.Workbook, name: string): string {\n let candidate = name;\n let n = 2;\n while (wb.getWorksheet(candidate)) candidate = `${name.slice(0, 28)} ${n++}`;\n return candidate;\n}\n\nfunction styleOf(cell: ICellData, styles: Record<string, Style>): Style | undefined {\n const s = cell.s;\n if (!s) return undefined;\n return typeof s === \"string\" ? styles[s] : (s as Style);\n}\n\nfunction applyStyle(target: ExcelJSTypes.Cell, st: Style | undefined): void {\n if (!st) return;\n const font: Partial<ExcelJSTypes.Font> = {};\n if (st.ff) font.name = String(st.ff);\n if (typeof st.fs === \"number\") font.size = st.fs;\n if (st.bl === 1) font.bold = true;\n if (st.it === 1) font.italic = true;\n if ((st.ul as Json | undefined)?.s === 1) font.underline = true;\n if ((st.st as Json | undefined)?.s === 1) font.strike = true;\n const fg = colorToArgb((st.cl as Json | undefined)?.rgb);\n if (fg) font.color = { argb: fg };\n if (Object.keys(font).length) target.font = font;\n const bg = colorToArgb((st.bg as Json | undefined)?.rgb);\n if (bg) target.fill = { type: \"pattern\", pattern: \"solid\", fgColor: { argb: bg } };\n const alignment: Partial<ExcelJSTypes.Alignment> = {};\n if (typeof st.ht === \"number\" && H_ALIGN_OUT[st.ht]) alignment.horizontal = H_ALIGN_OUT[st.ht] as ExcelJSTypes.Alignment[\"horizontal\"];\n if (typeof st.vt === \"number\" && V_ALIGN_OUT[st.vt]) alignment.vertical = V_ALIGN_OUT[st.vt] as ExcelJSTypes.Alignment[\"vertical\"];\n if (st.tb === 3) alignment.wrapText = true;\n if (Object.keys(alignment).length) target.alignment = alignment;\n const bd = st.bd as Json | undefined;\n if (bd) {\n const border: Partial<ExcelJSTypes.Borders> = {};\n for (const [key, side] of [[\"t\", \"top\"], [\"b\", \"bottom\"], [\"l\", \"left\"], [\"r\", \"right\"]] as const) {\n const b = bd[key] as Json | undefined;\n const style = borderToExcel(b?.s);\n if (style) {\n (border as Json)[side] = { style, color: { argb: colorToArgb(b?.cl?.rgb) ?? \"FF000000\" } };\n }\n }\n if (Object.keys(border).length) target.border = border;\n }\n const pattern = (st.n as Json | undefined)?.pattern;\n if (typeof pattern === \"string\" && pattern && pattern !== \"General\") target.numFmt = pattern;\n}\n\nfunction plainText(p: Json | undefined): string {\n return String(p?.body?.dataStream ?? \"\").replace(/\\r\\n$/, \"\").replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction linkOf(p: Json | undefined): string | undefined {\n const ranges = p?.body?.customRanges as Json[] | undefined;\n return ranges?.find((r) => r.rangeType === 0 && r.properties?.url)?.properties?.url;\n}\n\nfunction writeCells(ws: ExcelJSTypes.Worksheet, sheet: Partial<IWorksheetData>, styles: Record<string, Style>): void {\n const cellData = sheet.cellData ?? {};\n for (const rKey of Object.keys(cellData)) {\n const r = Number(rKey);\n const row = cellData[r];\n if (!row || !Number.isFinite(r)) continue;\n for (const cKey of Object.keys(row)) {\n const c = Number(cKey);\n const cell = row[c] as ICellData | undefined;\n if (!cell || !Number.isFinite(c)) continue;\n const target = ws.getCell(r + 1, c + 1);\n const formula = typeof cell.f === \"string\" ? cell.f.replace(/^=/, \"\") : undefined;\n const rich = cell.p as Json | undefined;\n let value: ExcelJSTypes.CellValue = null;\n if (cell.v !== undefined && cell.v !== null && cell.v !== \"\") {\n if (cell.t === 3) value = Boolean(cell.v);\n else if (cell.t === 2 || typeof cell.v === \"number\") value = Number(cell.v);\n else value = String(cell.v);\n } else if (rich) {\n value = plainText(rich);\n }\n const url = linkOf(rich);\n if (url) value = { text: String(value ?? url), hyperlink: url };\n if (formula) value = { formula, result: (value as number | string | boolean | undefined) ?? undefined } as ExcelJSTypes.CellFormulaValue;\n if (value !== null && value !== \"\") target.value = value;\n applyStyle(target, styleOf(cell, styles));\n }\n }\n}\n\nfunction writeLayout(ws: ExcelJSTypes.Worksheet, sheet: Partial<IWorksheetData>): void {\n const defaultCol = sheet.defaultColumnWidth;\n const columns = sheet.columnData ?? {};\n for (const key of Object.keys(columns)) {\n const c = Number(key);\n const col = columns[c];\n if (!col) continue;\n const target = ws.getColumn(c + 1);\n if (typeof col.w === \"number\") target.width = colPxToChars(col.w);\n else if (defaultCol) target.width = colPxToChars(defaultCol);\n if (col.hd === 1) target.hidden = true;\n }\n const rows = sheet.rowData ?? {};\n for (const key of Object.keys(rows)) {\n const r = Number(key);\n const row = rows[r];\n if (!row) continue;\n const target = ws.getRow(r + 1);\n if (typeof row.h === \"number\") target.height = rowPxToPt(row.h);\n if (row.hd === 1) target.hidden = true;\n }\n for (const m of sheet.mergeData ?? []) {\n try {\n ws.mergeCells(m.startRow + 1, m.startColumn + 1, m.endRow + 1, m.endColumn + 1);\n } catch {\n /* an overlapping merge in a damaged snapshot: keep the first */\n }\n }\n const freeze = sheet.freeze;\n if (freeze && (freeze.xSplit > 0 || freeze.ySplit > 0)) {\n ws.views = [{ state: \"frozen\", xSplit: freeze.xSplit, ySplit: freeze.ySplit }];\n }\n}\n\nconst eachCell = (ranges: RangeLike[], fn: (row: number, col: number) => void, cap = 100_000): boolean => {\n let n = 0;\n for (const r of ranges) {\n for (let row = r.startRow; row <= r.endRow; row++) {\n for (let col = r.startColumn; col <= r.endColumn; col++) {\n if (++n > cap) return false;\n fn(row, col);\n }\n }\n }\n return true;\n};\n\nfunction writeValidation(ws: ExcelJSTypes.Worksheet, rules: Json[] | undefined, dropped: Set<string>): void {\n for (const rule of rules ?? []) {\n const type = String(rule.type);\n const base: Json = {\n allowBlank: rule.allowBlank !== false,\n showErrorMessage: rule.showErrorMessage !== false,\n errorTitle: rule.errorTitle,\n error: rule.error,\n showInputMessage: Boolean(rule.showInputMessage),\n promptTitle: rule.promptTitle,\n prompt: rule.prompt,\n };\n let dv: Json | null = null;\n if (type === \"list\" || type === \"listMultiple\") {\n const f1 = String(rule.formula1 ?? \"\");\n const isRange = /^=?'?[^,\"]*!?\\$?[A-Z]+\\$?\\d+(:\\$?[A-Z]+\\$?\\d+)?$/i.test(f1) && !f1.includes(\",\");\n dv = { ...base, type: \"list\", formulae: [isRange ? f1.replace(/^=/, \"\") : `\"${f1.replace(/\"/g, \"\")}\"`] };\n if (type === \"listMultiple\") dropped.add(\"Multi-select dropdowns become single-select\");\n } else if (type === \"checkbox\") {\n dv = { ...base, type: \"list\", formulae: ['\"TRUE,FALSE\"'] };\n dropped.add(\"Checkboxes become TRUE/FALSE dropdowns\");\n } else if ([\"whole\", \"decimal\", \"date\", \"time\", \"textLength\"].includes(type)) {\n dv = {\n ...base,\n type,\n operator: rule.operator ?? \"between\",\n formulae: [rule.formula1, rule.formula2].filter((f) => f !== undefined && f !== \"\"),\n };\n } else if (type === \"custom\") {\n dv = { ...base, type: \"custom\", formulae: [String(rule.formula1 ?? \"\").replace(/^=/, \"\")] };\n }\n if (!dv) continue;\n if (!dv.errorTitle) delete dv.errorTitle;\n const complete = eachCell((rule.ranges ?? []) as RangeLike[], (r, c) => {\n ws.getCell(r + 1, c + 1).dataValidation = dv as ExcelJSTypes.DataValidation;\n });\n if (!complete) dropped.add(\"Data validation on very large ranges was cut off\");\n }\n}\n\nconst NUMBER_OPS = new Set([\"greaterThan\", \"greaterThanOrEqual\", \"lessThan\", \"lessThanOrEqual\", \"equal\", \"notEqual\", \"between\", \"notBetween\"]);\n\nfunction cfStyle(style: Json | undefined): Json {\n const out: Json = {};\n const font: Json = {};\n const fg = colorToArgb(style?.cl?.rgb);\n if (fg) font.color = { argb: fg };\n if (style?.bl === 1) font.bold = true;\n if (style?.it === 1) font.italic = true;\n if (Object.keys(font).length) out.font = font;\n const bg = colorToArgb(style?.bg?.rgb);\n if (bg) out.fill = { type: \"pattern\", pattern: \"solid\", bgColor: { argb: bg } };\n return out;\n}\n\nfunction writeConditional(ws: ExcelJSTypes.Worksheet, rules: Json[] | undefined, dropped: Set<string>): void {\n for (const entry of rules ?? []) {\n const ranges = (entry.ranges ?? []) as RangeLike[];\n if (!ranges.length) continue;\n const ref = ranges.map(rangeToA1).join(\" \");\n const first = ranges[0]!;\n const topLeft = rangeToA1({ ...first, endRow: first.startRow, endColumn: first.startColumn });\n const rule = entry.rule as Json;\n let out: Json | null = null;\n if (rule?.type === \"highlightCell\") {\n const style = cfStyle(rule.style);\n switch (rule.subType) {\n case \"number\":\n if (NUMBER_OPS.has(rule.operator)) {\n out = { type: \"cellIs\", operator: rule.operator, formulae: Array.isArray(rule.value) ? rule.value : [rule.value], style };\n }\n break;\n case \"text\":\n if (rule.operator === \"containsText\") out = { type: \"containsText\", operator: \"containsText\", text: String(rule.value ?? \"\"), style };\n break;\n case \"duplicateValues\":\n out = { type: \"expression\", formulae: [`COUNTIF(${ref.split(\" \")[0]},${topLeft})>1`], style };\n break;\n case \"uniqueValues\":\n out = { type: \"expression\", formulae: [`COUNTIF(${ref.split(\" \")[0]},${topLeft})=1`], style };\n break;\n case \"formula\":\n out = { type: \"expression\", formulae: [String(rule.value ?? \"\").replace(/^=/, \"\")], style };\n break;\n }\n } else if (rule?.type === \"colorScale\" && Array.isArray(rule.config)) {\n const cfg = [...rule.config].sort((a: Json, b: Json) => a.index - b.index);\n out = {\n type: \"colorScale\",\n cfvo: cfg.map((c: Json) => ({ type: c.value?.type ?? \"min\", ...(c.value?.value !== undefined ? { value: c.value.value } : {}) })),\n color: cfg.map((c: Json) => ({ argb: colorToArgb(c.color) ?? \"FFFFFFFF\" })),\n };\n } else if (rule?.type === \"dataBar\") {\n out = {\n type: \"dataBar\",\n gradient: rule.config?.isGradient !== false,\n cfvo: [{ type: rule.config?.min?.type ?? \"min\" }, { type: rule.config?.max?.type ?? \"max\" }],\n color: { argb: colorToArgb(rule.config?.positiveColor) ?? \"FF638EC6\" },\n };\n }\n if (!out) {\n dropped.add(\"Some conditional formats (icon sets, top/bottom, average, date rules) are not written\");\n continue;\n }\n ws.addConditionalFormatting({ ref, rules: [{ ...out, priority: 1 }] } as ExcelJSTypes.ConditionalFormattingOptions);\n }\n}\n\nfunction writeFilter(ws: ExcelJSTypes.Worksheet, filter: Json | undefined, dropped: Set<string>): void {\n const ref = filter?.ref as RangeLike | undefined;\n if (!ref) return;\n ws.autoFilter = {\n from: { row: ref.startRow + 1, column: ref.startColumn + 1 },\n to: { row: ref.endRow + 1, column: ref.endColumn + 1 },\n };\n if ((filter?.filterColumns as unknown[] | undefined)?.length) {\n dropped.add(\"Which filter choices were applied is not saved (the filter arrows are)\");\n }\n}\n\nfunction threadText(c: Json): string {\n return String(c?.text?.dataStream ?? \"\").replace(/\\r\\n?$/, \"\").replace(/\\r\\n?/g, \"\\n\");\n}\n\nfunction writeNotes(ws: ExcelJSTypes.Worksheet, sheetNotes: Json | undefined, sheetComments: Json | Json[] | undefined, dropped: Set<string>): void {\n for (const [row, cols] of Object.entries(sheetNotes ?? {})) {\n for (const [col, note] of Object.entries(cols as Json)) {\n const text = String((note as Json).note ?? \"\");\n if (text) ws.getCell(Number(row) + 1, Number(col) + 1).note = text;\n }\n }\n const list: Json[] = Array.isArray(sheetComments) ? sheetComments : sheetComments ? Object.values(sheetComments).flat() : [];\n const threads = new Map<string, string[]>();\n for (const c of list) {\n if (!c?.ref) continue;\n const lines = threads.get(c.ref) ?? [];\n const who = c.authorName ?? c.personId ?? \"\";\n lines.push(`${who ? who + \": \" : \"\"}${threadText(c)}`);\n for (const child of (c.children ?? []) as Json[]) {\n lines.push(`${child.authorName ?? child.personId ?? \"\"}: ${threadText(child)}`);\n }\n threads.set(c.ref, lines);\n }\n for (const [ref, lines] of threads) {\n const cell = ws.getCell(ref);\n const existing = typeof cell.note === \"string\" ? cell.note : \"\";\n cell.note = [existing, ...lines].filter(Boolean).join(\"\\n\");\n }\n if (threads.size) dropped.add(\"Comment threads are written as cell notes (replies and resolved state are flattened)\");\n}\n\nasync function writeImages(\n wb: ExcelJSTypes.Workbook,\n ws: ExcelJSTypes.Worksheet,\n sheetDrawings: Json | undefined,\n resolve: ExportImagePort | undefined,\n dropped: Set<string>,\n): Promise<void> {\n const data = (sheetDrawings?.data ?? {}) as Record<string, Json>;\n for (const d of Object.values(data)) {\n if (d.drawingType !== 0 || !d.source) continue;\n const from = d.sheetTransform?.from;\n if (!from) continue;\n let bytes: Uint8Array | null = null;\n let extension: \"png\" | \"jpeg\" | \"gif\" = \"png\";\n const dataUrl = /^data:image\\/(png|jpeg|jpg|gif);base64,(.+)$/i.exec(String(d.source));\n if (dataUrl) {\n extension = dataUrl[1]!.toLowerCase() === \"gif\" ? \"gif\" : dataUrl[1]!.toLowerCase() === \"png\" ? \"png\" : \"jpeg\";\n bytes = Uint8Array.from(atob(dataUrl[2]!), (ch) => ch.charCodeAt(0));\n } else if (resolve) {\n try {\n const got = await resolve(String(d.source));\n if (got) ({ bytes, extension } = got);\n } catch {\n bytes = null;\n }\n }\n if (!bytes) {\n dropped.add(\"Some pictures could not be read and were left out\");\n continue;\n }\n const id = wb.addImage({ buffer: bytes as unknown as NonNullable<Parameters<typeof wb.addImage>[0][\"buffer\"]>, extension });\n ws.addImage(id, {\n tl: { col: from.column + (from.columnOffset ?? 0) / 64, row: from.row + (from.rowOffset ?? 0) / 20 },\n ext: { width: d.transform?.width ?? 200, height: d.transform?.height ?? 150 },\n });\n }\n}\n\n// ─── internals of the thin path ────────────────────────────────────────────\n\nfunction sheetToJson(sheet: Partial<IWorksheetData>, name: string): WorkbookJson[\"sheets\"][number] {\n const cellData = sheet.cellData ?? {};\n const rows: (WorkbookCellJson | null)[][] = [];\n for (const rKey of Object.keys(cellData)) {\n const r = Number(rKey);\n if (!Number.isFinite(r)) continue;\n const row = cellData[r];\n if (!row) continue;\n for (const cKey of Object.keys(row)) {\n const c = Number(cKey);\n if (!Number.isFinite(c)) continue;\n const cell = row[c];\n if (!cell) continue;\n const out = toWorkbookCell(cell);\n if (!out) continue;\n while (rows.length <= r) rows.push([]);\n const line = rows[r]!;\n while (line.length < c) line.push(null);\n line[c] = out;\n }\n }\n const merges = (sheet.mergeData ?? []).map((m) => ({\n s: { r: m.startRow, c: m.startColumn },\n e: { r: m.endRow, c: m.endColumn },\n }));\n return { name, rows, ...(merges.length ? { merges } : {}) };\n}\n\nfunction toWorkbookCell(cell: ICellData): WorkbookCellJson | null {\n const formula = typeof cell.f === \"string\" ? cell.f.replace(/^=/, \"\") : undefined;\n let out: WorkbookCellJson;\n switch (cell.t) {\n case 2:\n out = { t: \"n\", v: typeof cell.v === \"number\" ? cell.v : Number(cell.v ?? 0) };\n break;\n case 3:\n out = { t: \"b\", v: Boolean(cell.v) };\n break;\n default:\n out = {\n t: \"s\",\n v:\n cell.v === null || cell.v === undefined\n ? \"\"\n : typeof cell.v === \"object\"\n ? JSON.stringify(cell.v)\n : String(cell.v),\n };\n }\n if ((out.v === \"\" || out.v === null || out.v === undefined) && !formula) return null;\n return formula ? { ...out, f: formula } : out;\n}\n\n// Kept so existing callers of the registered-format path keep compiling.\nexport async function univerSnapshotToRegisteredXlsxBytes(snapshot: Snapshot): Promise<Uint8Array> {\n const built = await buildFile(\n { kind: \"registered\", format: \"workbook\", value: univerSnapshotToWorkbookJson(snapshot) },\n \"xlsx-workbook\",\n );\n return built.bytes;\n}\n","/**\n * Spreadsheet file → a NEW workbook, the ONE import path: the Workbooks home and the editor's\n * File → Import both run it. The file is parsed before anything is created (a malformed file leaves\n * no empty workbook behind), the lossless original is stashed (non-fatal), and a failed save rolls\n * the new row back.\n */\n\nimport { isServiceFailure } from \"@ai-matrx/records/core\";\n\nimport { getSheetsHost } from \"./ports\";\nimport {\n createWorkbook,\n discardFailedWorkbook,\n saveSnapshot,\n} from \"./workbook-service\";\n\n/**\n * Pre-flight import file check. We deliberately do NOT use the `accept`\n * attribute on the picker (it greys out everything in Drive / Google\n * Sheets pickers on iOS and many Android pickers), so we validate after\n * pick. Returns null when the file is accepted, or a short user-facing\n * reason string when it isn't.\n */\nexport function unsupportedFileReason(file: File): string | null {\n const name = file.name.toLowerCase();\n // Native, parseable formats.\n if (\n name.endsWith(\".xlsx\") ||\n name.endsWith(\".xls\") ||\n name.endsWith(\".csv\")\n ) {\n return null;\n }\n if (name.endsWith(\".tsv\") || name.endsWith(\".txt\")) return null; // SheetJS parses these too\n\n // Drive's \"Google Sheets\" shortcut is a tiny JSON pointer file that browsers cannot resolve into\n // the sheet; the Google Sheets import reads the real file through Google's own picker.\n if (name.endsWith(\".gsheet\")) {\n return \"A Google Sheets shortcut can't be uploaded. Use Import from Google Sheets.\";\n }\n // Anything else.\n return `\"${file.name}\" isn't a spreadsheet file. Supported: .xlsx, .xls, .csv. For a Google Sheet, use Import from Google Sheets.`;\n}\n\nexport async function importWorkbookFile(\n file: File,\n organizationId: string | null,\n): Promise<{ id: string; name: string; notCarried: string[] }> {\n const capturedOrganizationId = await getSheetsHost().ensureOrgId(organizationId);\n // Parse first — if the file is malformed, we surface the error\n // BEFORE creating an empty workbook the user would have to delete.\n const { xlsxToUniverWorkbook } =\n await import(\"./xlsx-to-univer\");\n const droppedOnImport: string[] = [];\n const { uploadImportedImage } = await import(\"../univer/matrxImagePorts\");\n const snapshot = await xlsxToUniverWorkbook(file, {\n uploadImage: uploadImportedImage,\n onDropped: (what) => droppedOnImport.push(what),\n });\n\n // Stash the lossless original in cld_files so users can download or\n // re-import the source later. Failure here is non-fatal — the workbook\n // import path is the primary deliverable, the original-file link is\n // a recoverability nicety (FK is ON DELETE SET NULL, so we'd nil out\n // the link if the file went away anyway). Log + continue on failure.\n let originalFileId: string | undefined;\n try {\n const uploaded = await getSheetsHost().uploadOriginalFile(file, { folderPath: \"Workbooks/Imports\" });\n originalFileId = uploaded.fileId;\n } catch (uploadErr) {\n console.warn(\n \"Workbook import: stashing original failed; continuing without link.\",\n uploadErr,\n );\n }\n\n const cleanName = file.name.replace(/\\.[^.]+$/, \"\") || \"Imported workbook\";\n const created = await createWorkbook({\n name: cleanName,\n description: `Imported from ${file.name}`,\n source: file.name.toLowerCase().endsWith(\".csv\")\n ? \"imported_csv\"\n : \"imported_xlsx\",\n organizationId: capturedOrganizationId,\n ...(originalFileId ? { originalFileId } : {}),\n });\n if (isServiceFailure(created)) throw new Error(created.error);\n\n const saved = await saveSnapshot({\n workbookId: created.data.id,\n snapshot,\n origin: \"imported\",\n label: file.name,\n });\n if (isServiceFailure(saved)) {\n // Roll back the workbook so we don't leave an empty husk on import\n // failure. Best-effort, and a HARD delete on purpose: this row was\n // created seconds ago by this same flow and never reached the user, so\n // tombstoning it would leave invisible litter instead of cleaning up.\n await discardFailedWorkbook(created.data.id);\n throw new Error(saved.error);\n }\n\n return { id: created.data.id, name: cleanName, notCarried: droppedOnImport };\n}\n"]}