@wirecat/cli-core 0.719.0 → 0.720.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.
- package/CHANGELOG.md +33 -0
- package/dist/attachments/documents.d.ts +5 -0
- package/dist/attachments/documents.js +2 -2
- package/dist/documents/file-mirror-model.d.ts +14 -0
- package/dist/errors/reasons.js +2 -1
- package/dist/office/docx.d.ts +43 -0
- package/dist/office/docx.js +349 -0
- package/dist/office/index.d.ts +2 -0
- package/dist/office/index.js +2 -0
- package/dist/office/package.d.ts +39 -0
- package/dist/office/package.js +98 -0
- package/dist/office/xlsx.d.ts +55 -0
- package/dist/office/xlsx.js +550 -0
- package/dist/office/xml.d.ts +34 -0
- package/dist/office/xml.js +186 -0
- package/dist/office/zip.d.ts +10 -0
- package/dist/office/zip.js +116 -0
- package/dist/services/files/listing.d.ts +28 -0
- package/dist/services/files/listing.js +47 -0
- package/dist/services/files/mirror.d.ts +1 -1
- package/dist/services/files/mirror.js +16 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/index.d.ts +1 -0
- package/dist/store/people.d.ts +8 -0
- package/dist/store/people.js +2 -0
- package/dist/store/sqlite/account-purge.js +3 -0
- package/dist/store/sqlite/person-erase.d.ts +39 -0
- package/dist/store/sqlite/person-erase.js +152 -0
- package/package.json +5 -1
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export type CellValue = string | number | boolean | null;
|
|
2
|
+
export type CellType = "string" | "number" | "boolean" | "error" | "date" | "empty";
|
|
3
|
+
export interface XlsxCell {
|
|
4
|
+
/** A1 style, upper case. */
|
|
5
|
+
readonly address: string;
|
|
6
|
+
readonly row: number;
|
|
7
|
+
readonly column: number;
|
|
8
|
+
/** The stored value; for a formula cell, its last calculated result. */
|
|
9
|
+
readonly value: CellValue;
|
|
10
|
+
readonly type: CellType;
|
|
11
|
+
/** The formula without `=`, when the cell holds one. */
|
|
12
|
+
readonly formula?: string;
|
|
13
|
+
/** The index into the workbook's cell formats (`s`); 0 is the default. */
|
|
14
|
+
readonly style: number;
|
|
15
|
+
}
|
|
16
|
+
export interface XlsxSheet {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
readonly cells: XlsxCell[];
|
|
19
|
+
}
|
|
20
|
+
export interface ReadXlsxOptions {
|
|
21
|
+
/** One sheet by its name; all sheets when left out. */
|
|
22
|
+
readonly sheet?: string;
|
|
23
|
+
/** `B2` or `A1:C10`; every cell when left out. */
|
|
24
|
+
readonly range?: string;
|
|
25
|
+
}
|
|
26
|
+
export interface XlsxEdit {
|
|
27
|
+
readonly sheet: string;
|
|
28
|
+
readonly cell: string;
|
|
29
|
+
/** A string is stored as text (also one that starts with `=`), `null` empties the cell and keeps its format. */
|
|
30
|
+
readonly value: CellValue;
|
|
31
|
+
}
|
|
32
|
+
export interface EditXlsxOptions {
|
|
33
|
+
/** Replace a formula with the value; without it a formula cell is refused. */
|
|
34
|
+
readonly overwriteFormulas?: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface EditXlsxResult {
|
|
37
|
+
readonly bytes: Uint8Array;
|
|
38
|
+
readonly changed: {
|
|
39
|
+
sheet: string;
|
|
40
|
+
cell: string;
|
|
41
|
+
before: CellValue;
|
|
42
|
+
after: CellValue;
|
|
43
|
+
created: boolean;
|
|
44
|
+
}[];
|
|
45
|
+
/** True when a formula was replaced, so the workbook's calculation chain was dropped for Excel to rebuild. */
|
|
46
|
+
readonly calcChainDropped: boolean;
|
|
47
|
+
}
|
|
48
|
+
/** The workbook's sheets and their stored cells, with each cell's type, formula and format index. */
|
|
49
|
+
export declare const readXlsxCells: (bytes: Uint8Array, options?: ReadXlsxOptions) => Promise<XlsxSheet[]>;
|
|
50
|
+
/**
|
|
51
|
+
* Changes cells in place. Only the edited worksheets, the shared strings and the workbook part (marked to recalculate
|
|
52
|
+
* on open) are rewritten, each by splicing the changed elements into its original text; every other zip entry is
|
|
53
|
+
* copied byte for byte. A new cell or row goes in address order; an edited cell keeps its format (`s`).
|
|
54
|
+
*/
|
|
55
|
+
export declare const editXlsxCells: (bytes: Uint8Array, edits: readonly XlsxEdit[], options?: EditXlsxOptions) => Promise<EditXlsxResult>;
|
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { readSpreadsheet } from "../attachments/documents.js";
|
|
3
|
+
import { columnName } from "../attachments/sheets.js";
|
|
4
|
+
import { isSelfClosing, OfficePackage, openTag, qualified, REL, STRICT_REL, startTag, withAttribute, withoutAttribute, } from "./package.js";
|
|
5
|
+
import { attributeOf, childrenOf, contentText, descendants, escapeText } from "./xml.js";
|
|
6
|
+
const MAIN = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
|
|
7
|
+
const SHEET_NAMESPACES = [
|
|
8
|
+
"http://schemas.openxmlformats.org/spreadsheetml/2006/main",
|
|
9
|
+
"http://purl.oclc.org/ooxml/spreadsheetml/main",
|
|
10
|
+
];
|
|
11
|
+
const CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
|
|
12
|
+
const PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
13
|
+
/** CT_Workbook's children after calcPr; calcPr goes before the first of them. */
|
|
14
|
+
const AFTER_CALC = [
|
|
15
|
+
"oleSize",
|
|
16
|
+
"customWorkbookViews",
|
|
17
|
+
"pivotCaches",
|
|
18
|
+
"smartTagPr",
|
|
19
|
+
"smartTagTypes",
|
|
20
|
+
"webPublishing",
|
|
21
|
+
"fileRecoveryPr",
|
|
22
|
+
"webPublishObjects",
|
|
23
|
+
"extLst",
|
|
24
|
+
];
|
|
25
|
+
const MAX_ROW = 1_048_576;
|
|
26
|
+
const MAX_COLUMN = 16_384;
|
|
27
|
+
const refuse = (message, reason) => new CliError("validation_error", message, { reason });
|
|
28
|
+
const parseAddress = (address) => {
|
|
29
|
+
const match = /^([A-Z]{1,3})([1-9]\d{0,6})$/.exec(address.toUpperCase());
|
|
30
|
+
const column = match ? [...match[1]].reduce((sum, letter) => sum * 26 + letter.charCodeAt(0) - 64, 0) : 0;
|
|
31
|
+
const row = Number(match?.[2]);
|
|
32
|
+
if (!match || column > MAX_COLUMN || row > MAX_ROW)
|
|
33
|
+
throw refuse(`${address} is not a cell address like B7`, "office.invalid_cell");
|
|
34
|
+
return { row, column };
|
|
35
|
+
};
|
|
36
|
+
const parseRange = (range) => {
|
|
37
|
+
const [from, to = from] = range.split(":");
|
|
38
|
+
const start = parseAddress(from);
|
|
39
|
+
const end = parseAddress(to);
|
|
40
|
+
return {
|
|
41
|
+
top: Math.min(start.row, end.row),
|
|
42
|
+
bottom: Math.max(start.row, end.row),
|
|
43
|
+
left: Math.min(start.column, end.column),
|
|
44
|
+
right: Math.max(start.column, end.column),
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
class Workbook {
|
|
48
|
+
pack;
|
|
49
|
+
path;
|
|
50
|
+
ns;
|
|
51
|
+
workbook;
|
|
52
|
+
sheets;
|
|
53
|
+
strings;
|
|
54
|
+
/** Whether each shared string is one plain `t`, so a new cell may point at it without taking rich runs along. */
|
|
55
|
+
plainStrings;
|
|
56
|
+
sharedPath;
|
|
57
|
+
calcChain;
|
|
58
|
+
constructor(pack, path) {
|
|
59
|
+
this.pack = pack;
|
|
60
|
+
this.path = path;
|
|
61
|
+
this.workbook = pack.part(path);
|
|
62
|
+
this.ns = this.workbook.root.ns;
|
|
63
|
+
if (this.workbook.root.local !== "workbook" || !SHEET_NAMESPACES.includes(this.ns))
|
|
64
|
+
throw refuse("the file is not an Excel workbook", "office.wrong_format");
|
|
65
|
+
const rels = pack.relationships(path);
|
|
66
|
+
const sheetsElement = childrenOf(this.workbook.root, this.ns, "sheets")[0];
|
|
67
|
+
this.sheets = (sheetsElement ? childrenOf(sheetsElement, this.ns, "sheet") : []).map((sheet) => {
|
|
68
|
+
const id = attributeOf(sheet, REL, "id") ?? attributeOf(sheet, STRICT_REL, "id") ?? "";
|
|
69
|
+
const target = rels.get(id);
|
|
70
|
+
if (!target?.type.endsWith("/worksheet"))
|
|
71
|
+
throw refuse("a sheet of the workbook is not a worksheet (a chart sheet or a missing part)", "office.wrong_format");
|
|
72
|
+
return { name: attributeOf(sheet, "", "name") ?? "", path: target.path };
|
|
73
|
+
});
|
|
74
|
+
const shared = pack.related(path, "sharedStrings");
|
|
75
|
+
this.sharedPath = shared && pack.has(shared[1].path) ? shared[1].path : undefined;
|
|
76
|
+
const sharedPart = this.sharedPath ? pack.part(this.sharedPath) : undefined;
|
|
77
|
+
const entries = sharedPart ? childrenOf(sharedPart.root, this.ns, "si") : [];
|
|
78
|
+
this.strings = entries.map((entry) => sharedText(entry, this.ns, sharedPart?.text ?? ""));
|
|
79
|
+
this.plainStrings = entries.map((entry) => entry.children.length === 1 && entry.children[0]?.local === "t");
|
|
80
|
+
const chain = pack.related(path, "calcChain");
|
|
81
|
+
if (chain)
|
|
82
|
+
this.calcChain = { id: chain[0], path: chain[1].path };
|
|
83
|
+
}
|
|
84
|
+
static async open(bytes) {
|
|
85
|
+
const pack = await OfficePackage.open(bytes, "workbook");
|
|
86
|
+
return new Workbook(pack, pack.main(MAIN));
|
|
87
|
+
}
|
|
88
|
+
sheet(name) {
|
|
89
|
+
const found = this.sheets.find((sheet) => sheet.name === name);
|
|
90
|
+
if (!found)
|
|
91
|
+
throw refuse(`the workbook has no sheet "${name}"; it has ${this.sheets.map((sheet) => `"${sheet.name}"`).join(", ")}`, "office.no_sheet");
|
|
92
|
+
return found;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const sharedText = (entry, ns, text) => {
|
|
96
|
+
const parts = [];
|
|
97
|
+
const visit = (element) => {
|
|
98
|
+
for (const child of element.children) {
|
|
99
|
+
if (child.ns !== ns || child.local === "rPh")
|
|
100
|
+
continue;
|
|
101
|
+
if (child.local === "t")
|
|
102
|
+
parts.push(contentText(text.slice(child.openEnd, child.closeStart)));
|
|
103
|
+
else
|
|
104
|
+
visit(child);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
visit(entry);
|
|
108
|
+
return parts.join("");
|
|
109
|
+
};
|
|
110
|
+
const rowsOf = (sheetData, ns) => {
|
|
111
|
+
let previous = 0;
|
|
112
|
+
return childrenOf(sheetData, ns, "row").map((row) => {
|
|
113
|
+
const raw = attributeOf(row, "", "r");
|
|
114
|
+
const number = raw ? Number(raw) : previous + 1;
|
|
115
|
+
previous = number;
|
|
116
|
+
let column = 0;
|
|
117
|
+
const cells = childrenOf(row, ns, "c").map((cell) => {
|
|
118
|
+
const reference = attributeOf(cell, "", "r");
|
|
119
|
+
if (reference) {
|
|
120
|
+
const address = parseAddress(reference);
|
|
121
|
+
if (address.row !== number)
|
|
122
|
+
throw refuse(`cell ${reference} sits in row ${number}`, "office.wrong_format");
|
|
123
|
+
column = address.column;
|
|
124
|
+
}
|
|
125
|
+
else
|
|
126
|
+
column++;
|
|
127
|
+
return { element: cell, row: number, column };
|
|
128
|
+
});
|
|
129
|
+
return { element: row, row: number, explicit: raw !== undefined, cells };
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
const cellOf = (workbook, text, node) => {
|
|
133
|
+
const { ns } = workbook;
|
|
134
|
+
const element = node.element;
|
|
135
|
+
const type = attributeOf(element, "", "t") ?? "n";
|
|
136
|
+
const inner = (local) => {
|
|
137
|
+
const child = childrenOf(element, ns, local)[0];
|
|
138
|
+
return child ? contentText(text.slice(child.openEnd, child.closeStart)) : undefined;
|
|
139
|
+
};
|
|
140
|
+
const saved = inner("v");
|
|
141
|
+
const formulaElement = childrenOf(element, ns, "f")[0];
|
|
142
|
+
const formula = formulaElement
|
|
143
|
+
? contentText(text.slice(formulaElement.openEnd, formulaElement.closeStart))
|
|
144
|
+
: undefined;
|
|
145
|
+
let value = null;
|
|
146
|
+
let kind = "empty";
|
|
147
|
+
if (type === "inlineStr") {
|
|
148
|
+
const is = childrenOf(element, ns, "is")[0];
|
|
149
|
+
value = is
|
|
150
|
+
? descendants(is, ns, "t")
|
|
151
|
+
.filter((t) => t.parent?.local !== "rPh")
|
|
152
|
+
.map((t) => contentText(text.slice(t.openEnd, t.closeStart)))
|
|
153
|
+
.join("")
|
|
154
|
+
: "";
|
|
155
|
+
kind = "string";
|
|
156
|
+
}
|
|
157
|
+
else if (saved !== undefined) {
|
|
158
|
+
if (type === "s") {
|
|
159
|
+
const string = workbook.strings[Number(saved)];
|
|
160
|
+
if (!/^\d+$/.test(saved) || string === undefined)
|
|
161
|
+
throw refuse(`cell ${columnName(node.column)}${node.row} points at a missing shared string`, "office.wrong_format");
|
|
162
|
+
value = string;
|
|
163
|
+
kind = "string";
|
|
164
|
+
}
|
|
165
|
+
else if (type === "str") {
|
|
166
|
+
value = saved;
|
|
167
|
+
kind = "string";
|
|
168
|
+
}
|
|
169
|
+
else if (type === "b") {
|
|
170
|
+
value = saved === "1" || saved === "true";
|
|
171
|
+
kind = "boolean";
|
|
172
|
+
}
|
|
173
|
+
else if (type === "e") {
|
|
174
|
+
value = saved;
|
|
175
|
+
kind = "error";
|
|
176
|
+
}
|
|
177
|
+
else if (type === "d") {
|
|
178
|
+
value = saved;
|
|
179
|
+
kind = "date";
|
|
180
|
+
}
|
|
181
|
+
else if (saved !== "") {
|
|
182
|
+
value = Number(saved);
|
|
183
|
+
kind = "number";
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
address: `${columnName(node.column)}${node.row}`,
|
|
188
|
+
row: node.row,
|
|
189
|
+
column: node.column,
|
|
190
|
+
value,
|
|
191
|
+
type: kind,
|
|
192
|
+
...(formulaElement ? { formula: formula ?? "" } : {}),
|
|
193
|
+
style: Number(attributeOf(element, "", "s") ?? 0),
|
|
194
|
+
};
|
|
195
|
+
};
|
|
196
|
+
const sheetDataOf = (part, ns) => {
|
|
197
|
+
if (part.root.local !== "worksheet" || part.root.ns !== ns)
|
|
198
|
+
throw refuse(`${part.path} is not a worksheet`, "office.wrong_format");
|
|
199
|
+
const sheetData = childrenOf(part.root, ns, "sheetData")[0];
|
|
200
|
+
if (!sheetData)
|
|
201
|
+
throw refuse(`${part.path} has no cell data`, "office.wrong_format");
|
|
202
|
+
return sheetData;
|
|
203
|
+
};
|
|
204
|
+
/** The workbook's sheets and their stored cells, with each cell's type, formula and format index. */
|
|
205
|
+
export const readXlsxCells = async (bytes, options = {}) => {
|
|
206
|
+
const workbook = await Workbook.open(bytes);
|
|
207
|
+
const range = options.range ? parseRange(options.range) : undefined;
|
|
208
|
+
const wanted = options.sheet === undefined ? workbook.sheets : [workbook.sheet(options.sheet)];
|
|
209
|
+
return wanted.map((sheet) => {
|
|
210
|
+
const part = workbook.pack.part(sheet.path);
|
|
211
|
+
const cells = rowsOf(sheetDataOf(part, workbook.ns), workbook.ns)
|
|
212
|
+
.flatMap((row) => row.cells)
|
|
213
|
+
.filter((cell) => !range ||
|
|
214
|
+
(cell.row >= range.top &&
|
|
215
|
+
cell.row <= range.bottom &&
|
|
216
|
+
cell.column >= range.left &&
|
|
217
|
+
cell.column <= range.right))
|
|
218
|
+
.map((cell) => cellOf(workbook, part.text, cell));
|
|
219
|
+
return { name: sheet.name, cells };
|
|
220
|
+
});
|
|
221
|
+
};
|
|
222
|
+
class SharedStrings {
|
|
223
|
+
workbook;
|
|
224
|
+
added = [];
|
|
225
|
+
references = 0;
|
|
226
|
+
plain = new Map();
|
|
227
|
+
constructor(workbook) {
|
|
228
|
+
this.workbook = workbook;
|
|
229
|
+
workbook.strings.forEach((value, index) => {
|
|
230
|
+
if (workbook.plainStrings[index] && !this.plain.has(value))
|
|
231
|
+
this.plain.set(value, index);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
index(value) {
|
|
235
|
+
this.references++;
|
|
236
|
+
const known = this.plain.get(value);
|
|
237
|
+
if (known !== undefined)
|
|
238
|
+
return known;
|
|
239
|
+
const index = this.workbook.strings.length + this.added.length;
|
|
240
|
+
this.added.push(value);
|
|
241
|
+
this.plain.set(value, index);
|
|
242
|
+
return index;
|
|
243
|
+
}
|
|
244
|
+
release() {
|
|
245
|
+
this.references--;
|
|
246
|
+
}
|
|
247
|
+
write() {
|
|
248
|
+
const path = this.workbook.sharedPath;
|
|
249
|
+
if (!path || (!this.added.length && !this.references))
|
|
250
|
+
return;
|
|
251
|
+
const part = this.workbook.pack.part(path);
|
|
252
|
+
const root = part.root;
|
|
253
|
+
const si = qualified(root, "si");
|
|
254
|
+
const t = qualified(root, "t");
|
|
255
|
+
const entries = this.added
|
|
256
|
+
.map((value) => `<${si}><${t} xml:space="preserve">${escapeText(value)}</${t}></${si}>`)
|
|
257
|
+
.join("");
|
|
258
|
+
let tag = openTag(part.text, root);
|
|
259
|
+
const count = attributeOf(root, "", "count");
|
|
260
|
+
const unique = attributeOf(root, "", "uniqueCount");
|
|
261
|
+
if (count !== undefined)
|
|
262
|
+
tag = withAttribute(tag, "count", String(Math.max(0, Number(count) + this.references)));
|
|
263
|
+
if (unique !== undefined)
|
|
264
|
+
tag = withAttribute(tag, "uniqueCount", String(Number(unique) + this.added.length));
|
|
265
|
+
const splices = [{ start: root.start, end: root.openEnd, text: tag }];
|
|
266
|
+
if (isSelfClosing(part.text, root))
|
|
267
|
+
splices.push({ start: root.openEnd, end: root.openEnd, text: `${entries}</${root.name}>` });
|
|
268
|
+
else
|
|
269
|
+
splices.push({ start: root.closeStart, end: root.closeStart, text: entries });
|
|
270
|
+
this.workbook.pack.write(part, splices);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const valueXml = (cell, value, strings) => {
|
|
274
|
+
const v = qualified(cell, "v");
|
|
275
|
+
if (value === null)
|
|
276
|
+
return { type: undefined, content: "" };
|
|
277
|
+
if (typeof value === "boolean")
|
|
278
|
+
return { type: "b", content: `<${v}>${value ? 1 : 0}</${v}>` };
|
|
279
|
+
if (typeof value === "number") {
|
|
280
|
+
if (!Number.isFinite(value))
|
|
281
|
+
throw refuse("a cell number must be finite", "office.invalid_value");
|
|
282
|
+
return { type: undefined, content: `<${v}>${String(value)}</${v}>` };
|
|
283
|
+
}
|
|
284
|
+
if (strings)
|
|
285
|
+
return { type: "s", content: `<${v}>${strings.index(value)}</${v}>` };
|
|
286
|
+
const is = qualified(cell, "is");
|
|
287
|
+
const t = qualified(cell, "t");
|
|
288
|
+
return { type: "inlineStr", content: `<${is}><${t} xml:space="preserve">${escapeText(value)}</${t}></${is}>` };
|
|
289
|
+
};
|
|
290
|
+
/** A cell's start tag: its own attributes kept, `t` set for the new value, `cm` dropped with the formula. */
|
|
291
|
+
const cellTag = (text, cell, type) => {
|
|
292
|
+
let tag = withoutAttribute(withoutAttribute(startTag(text, cell), "t"), "cm");
|
|
293
|
+
if (type)
|
|
294
|
+
tag = withAttribute(tag, "t", type);
|
|
295
|
+
return tag.replace(/\s*\/\s*>$/, ">");
|
|
296
|
+
};
|
|
297
|
+
const arrayRanges = (rows, ns, text) => rows.flatMap((row) => row.cells.flatMap((cell) => {
|
|
298
|
+
const formula = childrenOf(cell.element, ns, "f")[0];
|
|
299
|
+
const ref = formula && attributeOf(formula, "", "ref");
|
|
300
|
+
return formula && ref && attributeOf(formula, "", "t") === "array"
|
|
301
|
+
? [{ master: cell, range: parseRange(ref), text: text.slice(formula.start, formula.end) }]
|
|
302
|
+
: [];
|
|
303
|
+
}));
|
|
304
|
+
/**
|
|
305
|
+
* Rows of an Excel table whose text the table part repeats (column names, totals labels). Excel reports a file as
|
|
306
|
+
* damaged when a header cell no longer matches its column's name.
|
|
307
|
+
*/
|
|
308
|
+
const tableLabels = (workbook, sheet) => {
|
|
309
|
+
const { pack } = workbook;
|
|
310
|
+
if (!pack.has(sheet.path.replace(/([^/]+)$/, "_rels/$1.rels")))
|
|
311
|
+
return [];
|
|
312
|
+
return [...pack.relationships(sheet.path).values()]
|
|
313
|
+
.filter((entry) => entry.type.endsWith("/table") && pack.has(entry.path))
|
|
314
|
+
.flatMap((entry) => {
|
|
315
|
+
const table = pack.part(entry.path).root;
|
|
316
|
+
const ref = attributeOf(table, "", "ref");
|
|
317
|
+
if (!ref)
|
|
318
|
+
return [];
|
|
319
|
+
const range = parseRange(ref);
|
|
320
|
+
const name = attributeOf(table, "", "displayName") ?? attributeOf(table, "", "name") ?? "";
|
|
321
|
+
const header = Number(attributeOf(table, "", "headerRowCount") ?? 1);
|
|
322
|
+
const totals = Number(attributeOf(table, "", "totalsRowCount") ?? 0);
|
|
323
|
+
return [
|
|
324
|
+
...(header > 0 ? [{ ...range, bottom: range.top + header - 1, kind: "header cell", table: name }] : []),
|
|
325
|
+
...(totals > 0 ? [{ ...range, top: range.bottom - totals + 1, kind: "totals cell", table: name }] : []),
|
|
326
|
+
];
|
|
327
|
+
});
|
|
328
|
+
};
|
|
329
|
+
const editSheet = (workbook, sheet, planned, options, strings) => {
|
|
330
|
+
const { ns, pack } = workbook;
|
|
331
|
+
const part = pack.part(sheet.path);
|
|
332
|
+
const { text } = part;
|
|
333
|
+
const sheetData = sheetDataOf(part, ns);
|
|
334
|
+
const rows = rowsOf(sheetData, ns);
|
|
335
|
+
const arrays = arrayRanges(rows, ns, text);
|
|
336
|
+
for (const label of tableLabels(workbook, sheet))
|
|
337
|
+
for (const item of planned)
|
|
338
|
+
if (item.row >= label.top && item.row <= label.bottom && item.column >= label.left && item.column <= label.right)
|
|
339
|
+
throw refuse(`${sheet.name}!${item.address} is a ${label.kind} of the table "${label.table}", whose part repeats the text; change it in Excel`, "office.table_header");
|
|
340
|
+
const splices = [];
|
|
341
|
+
const changed = [];
|
|
342
|
+
let formulaRemoved = false;
|
|
343
|
+
const byRow = new Map();
|
|
344
|
+
for (const item of planned)
|
|
345
|
+
byRow.set(item.row, [...(byRow.get(item.row) ?? []), item]);
|
|
346
|
+
const newCell = (item, style) => {
|
|
347
|
+
const { type, content } = valueXml(sheetData, item.edit.value, strings);
|
|
348
|
+
const c = qualified(sheetData, "c");
|
|
349
|
+
const attributes = `r="${item.address}"${style ? ` s="${style}"` : ""}${type ? ` t="${type}"` : ""}`;
|
|
350
|
+
return content ? `<${c} ${attributes}>${content}</${c}>` : `<${c} ${attributes}/>`;
|
|
351
|
+
};
|
|
352
|
+
for (const [rowNumber, items] of [...byRow].sort(([a], [b]) => a - b)) {
|
|
353
|
+
items.sort((a, b) => a.column - b.column);
|
|
354
|
+
const row = rows.find((candidate) => candidate.row === rowNumber);
|
|
355
|
+
if (!row) {
|
|
356
|
+
if (rows.some((candidate) => !candidate.explicit))
|
|
357
|
+
throw refuse(`${sheet.name} has rows without numbers, so row ${rowNumber} cannot be added`, "office.implicit_rows");
|
|
358
|
+
const next = rows.find((candidate) => candidate.row > rowNumber);
|
|
359
|
+
const r = qualified(sheetData, "row");
|
|
360
|
+
const xml = `<${r} r="${rowNumber}">${items.map((item) => newCell(item)).join("")}</${r}>`;
|
|
361
|
+
for (const item of items)
|
|
362
|
+
changed.push({ sheet: sheet.name, cell: item.address, before: null, after: item.edit.value, created: true });
|
|
363
|
+
if (next)
|
|
364
|
+
splices.push({ start: next.element.start, end: next.element.start, text: xml });
|
|
365
|
+
else if (isSelfClosing(text, sheetData))
|
|
366
|
+
splices.push({
|
|
367
|
+
start: sheetData.start,
|
|
368
|
+
end: sheetData.end,
|
|
369
|
+
text: `${openTag(text, sheetData)}${xml}</${sheetData.name}>`,
|
|
370
|
+
});
|
|
371
|
+
else
|
|
372
|
+
splices.push({ start: sheetData.closeStart, end: sheetData.closeStart, text: xml });
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
const inserts = [];
|
|
376
|
+
const rowStyle = attributeOf(row.element, "", "customFormat") === "1" ? attributeOf(row.element, "", "s") : undefined;
|
|
377
|
+
for (const item of items) {
|
|
378
|
+
const existing = row.cells.find((cell) => cell.column === item.column);
|
|
379
|
+
if (!existing) {
|
|
380
|
+
if (row.cells.some((cell) => attributeOf(cell.element, "", "r") === undefined))
|
|
381
|
+
throw refuse(`row ${rowNumber} of ${sheet.name} has cells without addresses, so ${item.address} cannot be added`, "office.implicit_cells");
|
|
382
|
+
const next = row.cells.find((cell) => cell.column > item.column);
|
|
383
|
+
inserts.push({ at: next ? next.element.start : -1, xml: newCell(item, rowStyle) });
|
|
384
|
+
changed.push({ sheet: sheet.name, cell: item.address, before: null, after: item.edit.value, created: true });
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
const before = cellOf(workbook, text, existing);
|
|
388
|
+
const element = existing.element;
|
|
389
|
+
if (attributeOf(element, "", "vm") !== undefined)
|
|
390
|
+
throw refuse(`${sheet.name}!${item.address} holds a picture or a linked data type, which this editor does not replace`, "office.rich_value");
|
|
391
|
+
const formula = childrenOf(element, ns, "f")[0];
|
|
392
|
+
const array = arrays.find((entry) => item.row >= entry.range.top &&
|
|
393
|
+
item.row <= entry.range.bottom &&
|
|
394
|
+
item.column >= entry.range.left &&
|
|
395
|
+
item.column <= entry.range.right &&
|
|
396
|
+
(entry.range.top !== entry.range.bottom || entry.range.left !== entry.range.right));
|
|
397
|
+
if (array)
|
|
398
|
+
throw refuse(`${sheet.name}!${item.address} is part of an array formula; change it in Excel`, "office.array_formula");
|
|
399
|
+
if (formula) {
|
|
400
|
+
if (!options.overwriteFormulas)
|
|
401
|
+
throw refuse(`${sheet.name}!${item.address} holds the formula =${before.formula}; pass overwriteFormulas to replace it with a value`, "office.formula_cell");
|
|
402
|
+
if (attributeOf(formula, "", "t") === "shared" && attributeOf(formula, "", "ref") !== undefined)
|
|
403
|
+
throw refuse(`${sheet.name}!${item.address} holds a formula that other cells share; replacing it would break theirs`, "office.shared_formula");
|
|
404
|
+
formulaRemoved = true;
|
|
405
|
+
}
|
|
406
|
+
if (attributeOf(element, "", "t") === "s" && strings)
|
|
407
|
+
strings.release();
|
|
408
|
+
const { type, content } = valueXml(element, item.edit.value, strings);
|
|
409
|
+
const extra = childrenOf(element, ns, "extLst")
|
|
410
|
+
.map((child) => text.slice(child.start, child.end))
|
|
411
|
+
.join("");
|
|
412
|
+
const tag = cellTag(text, element, type);
|
|
413
|
+
splices.push({ start: element.start, end: element.end, text: `${tag}${content}${extra}</${element.name}>` });
|
|
414
|
+
changed.push({
|
|
415
|
+
sheet: sheet.name,
|
|
416
|
+
cell: item.address,
|
|
417
|
+
before: before.value,
|
|
418
|
+
after: item.edit.value,
|
|
419
|
+
created: false,
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
if (inserts.length) {
|
|
423
|
+
const tail = inserts
|
|
424
|
+
.filter((insert) => insert.at < 0)
|
|
425
|
+
.map((insert) => insert.xml)
|
|
426
|
+
.join("");
|
|
427
|
+
for (const insert of inserts.filter((entry) => entry.at >= 0))
|
|
428
|
+
splices.push({ start: insert.at, end: insert.at, text: insert.xml });
|
|
429
|
+
if (tail) {
|
|
430
|
+
if (isSelfClosing(text, row.element))
|
|
431
|
+
splices.push({
|
|
432
|
+
start: row.element.start,
|
|
433
|
+
end: row.element.end,
|
|
434
|
+
text: `${openTag(text, row.element)}${tail}</${row.element.name}>`,
|
|
435
|
+
});
|
|
436
|
+
else
|
|
437
|
+
splices.push({ start: row.element.closeStart, end: row.element.closeStart, text: tail });
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const created = changed.filter((entry) => entry.created).map((entry) => parseAddress(entry.cell));
|
|
442
|
+
const dimension = childrenOf(part.root, ns, "dimension")[0];
|
|
443
|
+
const ref = dimension && attributeOf(dimension, "", "ref");
|
|
444
|
+
if (dimension && ref && created.length) {
|
|
445
|
+
const current = parseRange(ref);
|
|
446
|
+
const grown = created.reduce((box, cell) => ({
|
|
447
|
+
top: Math.min(box.top, cell.row),
|
|
448
|
+
bottom: Math.max(box.bottom, cell.row),
|
|
449
|
+
left: Math.min(box.left, cell.column),
|
|
450
|
+
right: Math.max(box.right, cell.column),
|
|
451
|
+
}), current);
|
|
452
|
+
if (grown.top !== current.top ||
|
|
453
|
+
grown.bottom !== current.bottom ||
|
|
454
|
+
grown.left !== current.left ||
|
|
455
|
+
grown.right !== current.right) {
|
|
456
|
+
const a1 = `${columnName(grown.left)}${grown.top}`;
|
|
457
|
+
const b2 = `${columnName(grown.right)}${grown.bottom}`;
|
|
458
|
+
splices.push({
|
|
459
|
+
start: dimension.start,
|
|
460
|
+
end: dimension.openEnd,
|
|
461
|
+
text: withAttribute(startTag(text, dimension), "ref", a1 === b2 ? a1 : `${a1}:${b2}`),
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
pack.write(part, splices);
|
|
466
|
+
return { changed, formulaRemoved };
|
|
467
|
+
};
|
|
468
|
+
const markRecalculation = (workbook) => {
|
|
469
|
+
const { workbook: part, ns } = workbook;
|
|
470
|
+
const { root, text } = part;
|
|
471
|
+
const calcPr = childrenOf(root, ns, "calcPr")[0];
|
|
472
|
+
if (calcPr) {
|
|
473
|
+
if (attributeOf(calcPr, "", "fullCalcOnLoad") === "1")
|
|
474
|
+
return;
|
|
475
|
+
workbook.pack.write(part, [
|
|
476
|
+
{ start: calcPr.start, end: calcPr.openEnd, text: withAttribute(startTag(text, calcPr), "fullCalcOnLoad", "1") },
|
|
477
|
+
]);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
const next = root.children.find((child) => child.ns === ns && AFTER_CALC.includes(child.local));
|
|
481
|
+
const xml = `<${qualified(root, "calcPr")} fullCalcOnLoad="1"/>`;
|
|
482
|
+
const at = next ? next.start : root.closeStart;
|
|
483
|
+
workbook.pack.write(part, [{ start: at, end: at, text: xml }]);
|
|
484
|
+
};
|
|
485
|
+
const dropCalcChain = (workbook) => {
|
|
486
|
+
const chain = workbook.calcChain;
|
|
487
|
+
if (!chain)
|
|
488
|
+
return false;
|
|
489
|
+
const { pack } = workbook;
|
|
490
|
+
const relsPath = workbook.path.replace(/([^/]+)$/, "_rels/$1.rels");
|
|
491
|
+
const rels = pack.part(relsPath);
|
|
492
|
+
const relation = childrenOf(rels.root, PACKAGE_REL, "Relationship").find((entry) => attributeOf(entry, "", "Id") === chain.id);
|
|
493
|
+
if (relation)
|
|
494
|
+
pack.write(rels, [{ start: relation.start, end: relation.end, text: "" }]);
|
|
495
|
+
const types = pack.part("[Content_Types].xml");
|
|
496
|
+
const override = childrenOf(types.root, CONTENT_TYPES, "Override").find((entry) => attributeOf(entry, "", "PartName") === `/${chain.path}`);
|
|
497
|
+
if (override)
|
|
498
|
+
pack.write(types, [{ start: override.start, end: override.end, text: "" }]);
|
|
499
|
+
if (pack.has(chain.path))
|
|
500
|
+
pack.remove(chain.path);
|
|
501
|
+
return true;
|
|
502
|
+
};
|
|
503
|
+
const same = (left, right) => left === right || (left === "" && right === null);
|
|
504
|
+
/**
|
|
505
|
+
* Changes cells in place. Only the edited worksheets, the shared strings and the workbook part (marked to recalculate
|
|
506
|
+
* on open) are rewritten, each by splicing the changed elements into its original text; every other zip entry is
|
|
507
|
+
* copied byte for byte. A new cell or row goes in address order; an edited cell keeps its format (`s`).
|
|
508
|
+
*/
|
|
509
|
+
export const editXlsxCells = async (bytes, edits, options = {}) => {
|
|
510
|
+
const workbook = await Workbook.open(bytes);
|
|
511
|
+
const bySheet = new Map();
|
|
512
|
+
const seen = new Set();
|
|
513
|
+
for (const edit of edits) {
|
|
514
|
+
const sheet = workbook.sheet(edit.sheet);
|
|
515
|
+
const { row, column } = parseAddress(edit.cell);
|
|
516
|
+
const address = `${columnName(column)}${row}`;
|
|
517
|
+
const key = `${sheet.name}!${address}`;
|
|
518
|
+
if (seen.has(key))
|
|
519
|
+
throw refuse(`${key} is edited twice in one call`, "office.duplicate_edit");
|
|
520
|
+
seen.add(key);
|
|
521
|
+
bySheet.set(sheet, [...(bySheet.get(sheet) ?? []), { edit, row, column, address }]);
|
|
522
|
+
}
|
|
523
|
+
if (!edits.length)
|
|
524
|
+
return { bytes: bytes.slice(), changed: [], calcChainDropped: false };
|
|
525
|
+
const strings = workbook.sharedPath ? new SharedStrings(workbook) : undefined;
|
|
526
|
+
let changed = [];
|
|
527
|
+
let formulaRemoved = false;
|
|
528
|
+
for (const [sheet, planned] of bySheet) {
|
|
529
|
+
const result = editSheet(workbook, sheet, planned, options, strings);
|
|
530
|
+
changed = changed.concat(result.changed);
|
|
531
|
+
formulaRemoved ||= result.formulaRemoved;
|
|
532
|
+
}
|
|
533
|
+
strings?.write();
|
|
534
|
+
markRecalculation(workbook);
|
|
535
|
+
const calcChainDropped = formulaRemoved && dropCalcChain(workbook);
|
|
536
|
+
const output = workbook.pack.build();
|
|
537
|
+
await verify(output, changed);
|
|
538
|
+
return { bytes: output, changed, calcChainDropped };
|
|
539
|
+
};
|
|
540
|
+
const verify = async (output, changed) => {
|
|
541
|
+
const sheets = await readXlsxCells(output);
|
|
542
|
+
for (const entry of changed) {
|
|
543
|
+
const cell = sheets
|
|
544
|
+
.find((sheet) => sheet.name === entry.sheet)
|
|
545
|
+
?.cells.find((candidate) => candidate.address === entry.cell);
|
|
546
|
+
if (!same(cell?.value ?? null, entry.after) || cell?.formula !== undefined)
|
|
547
|
+
throw new Error(`the edited workbook does not read back ${entry.sheet}!${entry.cell} as written`);
|
|
548
|
+
}
|
|
549
|
+
await readSpreadsheet(output, "xlsx");
|
|
550
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** An element with its offsets in the part's text, so an edit replaces a span and leaves every other byte alone. */
|
|
2
|
+
export interface XmlElement {
|
|
3
|
+
readonly name: string;
|
|
4
|
+
readonly prefix: string;
|
|
5
|
+
readonly local: string;
|
|
6
|
+
readonly ns: string;
|
|
7
|
+
readonly attributes: ReadonlyMap<string, string>;
|
|
8
|
+
readonly start: number;
|
|
9
|
+
readonly openEnd: number;
|
|
10
|
+
closeStart: number;
|
|
11
|
+
end: number;
|
|
12
|
+
readonly children: XmlElement[];
|
|
13
|
+
readonly parent: XmlElement | undefined;
|
|
14
|
+
readonly namespaces: ReadonlyMap<string, string>;
|
|
15
|
+
}
|
|
16
|
+
export declare const decodeEntities: (raw: string) => string;
|
|
17
|
+
/** Element content as text: entities decoded, CDATA unwrapped, comments and processing instructions dropped. */
|
|
18
|
+
export declare const contentText: (raw: string) => string;
|
|
19
|
+
export declare const escapeText: (value: string) => string;
|
|
20
|
+
export declare const parseXml: (text: string) => XmlElement;
|
|
21
|
+
/** An attribute by its namespace and local name, whatever prefix the file uses for it. */
|
|
22
|
+
export declare const attributeOf: (element: XmlElement, ns: string, local: string) => string | undefined;
|
|
23
|
+
export declare const childrenOf: (element: XmlElement, ns: string, local: string) => XmlElement[];
|
|
24
|
+
export declare const descendants: (element: XmlElement, ns: string, local: string) => XmlElement[];
|
|
25
|
+
export interface Splice {
|
|
26
|
+
readonly start: number;
|
|
27
|
+
readonly end: number;
|
|
28
|
+
readonly text: string;
|
|
29
|
+
}
|
|
30
|
+
/** Applies non-overlapping replacements; an insert goes before a replacement at its offset, inserts keep their order. */
|
|
31
|
+
export declare const applySplices: (text: string, splices: readonly Splice[]) => string;
|
|
32
|
+
/** A part's text; only UTF-8 parts are edited, since a rewrite in another encoding would contradict its declaration. */
|
|
33
|
+
export declare const partText: (bytes: Uint8Array, path: string) => string;
|
|
34
|
+
export declare const partBytes: (text: string) => NodeJS.NonSharedUint8Array;
|