dsh-artifact-studio 0.7.3 → 0.9.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.
@@ -0,0 +1,628 @@
1
+ /**
2
+ * The sheet artifact model: a small, engine-neutral workbook JSON that both
3
+ * the host and the panel parse, validate, and render. It has no dependency on
4
+ * a spreadsheet library, so the stored content stays readable by the agent and
5
+ * survives a future editor swap.
6
+ *
7
+ * Shape:
8
+ * {
9
+ * "schemaVersion": 1,
10
+ * "sheets": [
11
+ * {
12
+ * "name": "Budget",
13
+ * "cells": {
14
+ * "A1": "Item",
15
+ * "B2": 1200,
16
+ * "C2": "=B2*1.2",
17
+ * "A1:H1": { "style": { "bold": true } }
18
+ * },
19
+ * "columnWidths": { "A": 160 }
20
+ * }
21
+ * ]
22
+ * }
23
+ *
24
+ * A cell value is written as a plain JSON scalar for readability. A leading
25
+ * "=" in a string means a formula; use { "value": "=literal" } for text that
26
+ * starts with "=". A styled or formula cell uses the object form.
27
+ */
28
+ /** The one supported schema version. */
29
+ export const SHEET_SCHEMA_VERSION = 1;
30
+ /** Bounds that keep one sheet artifact fast enough for the panel and the host. */
31
+ export const SHEET_LIMITS = {
32
+ maxSheets: 20,
33
+ maxRows: 5000,
34
+ maxColumns: 100,
35
+ maxCells: 20000,
36
+ maxFormulaCells: 5000,
37
+ maxCellText: 10000,
38
+ maxFormula: 2000,
39
+ maxName: 31,
40
+ minColumnWidth: 24,
41
+ maxColumnWidth: 800,
42
+ defaultColumnWidth: 96,
43
+ defaultRowHeight: 28,
44
+ maxOperations: 200,
45
+ maxOperationCells: 4000,
46
+ maxEvaluationCells: 200000,
47
+ maxSelectionQuote: 1500,
48
+ };
49
+ /** A failure the caller can show or wrap: invalid JSON, an invalid cell, a bad operation. */
50
+ export class SheetError extends Error {
51
+ code;
52
+ constructor(message, code = 'sheet/invalid') {
53
+ super(message);
54
+ this.name = 'SheetError';
55
+ this.code = code;
56
+ }
57
+ }
58
+ const REF = /^\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})$/;
59
+ const COLUMN = /^[A-Za-z]{1,3}$/;
60
+ const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
61
+ const BAD_SHEET_NAME = /[\\/?*[\]:]/;
62
+ const NUMBER_FORMATS = ['general', 'number', 'integer', 'currency', 'percent', 'date'];
63
+ const ALIGNS = ['left', 'center', 'right'];
64
+ const STYLE_KEYS = ['bold', 'italic', 'underline', 'strike', 'align', 'color', 'background', 'numberFormat'];
65
+ const CELL_KEYS = ['value', 'formula', 'style'];
66
+ const SHEET_KEYS = ['name', 'cells', 'columnWidths'];
67
+ const WORKBOOK_KEYS = ['schemaVersion', 'sheets'];
68
+ function isFields(value) {
69
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
70
+ }
71
+ /**
72
+ * Refuse an unknown key so a typo cannot be silently dropped from a saved sheet.
73
+ * @param value the object.
74
+ * @param allowed the keys it may have.
75
+ * @param at the field path for the message.
76
+ */
77
+ function onlyKeys(value, allowed, at) {
78
+ for (const key of Object.keys(value)) {
79
+ if (!allowed.includes(key)) {
80
+ throw new SheetError(at + ' has an unknown field "' + key + '". Use ' + allowed.join(', ') + '.');
81
+ }
82
+ }
83
+ }
84
+ /**
85
+ * A column index as spreadsheet letters.
86
+ * @param column the zero-based column.
87
+ * @returns the letters.
88
+ */
89
+ export function columnName(column) {
90
+ if (!Number.isInteger(column) || column < 0)
91
+ throw new SheetError('A column index must be a non-negative integer.');
92
+ let value = column + 1;
93
+ let name = '';
94
+ while (value > 0) {
95
+ const remainder = (value - 1) % 26;
96
+ name = String.fromCharCode(65 + remainder) + name;
97
+ value = Math.floor((value - 1) / 26);
98
+ }
99
+ return name;
100
+ }
101
+ /**
102
+ * The zero-based column index of letters.
103
+ * @param name the column letters.
104
+ * @returns the index, or undefined when the name is not a column.
105
+ */
106
+ export function columnIndex(name) {
107
+ if (!COLUMN.test(name))
108
+ return undefined;
109
+ let value = 0;
110
+ for (const letter of name.toUpperCase())
111
+ value = value * 26 + (letter.charCodeAt(0) - 64);
112
+ const index = value - 1;
113
+ return index < SHEET_LIMITS.maxColumns ? index : undefined;
114
+ }
115
+ /**
116
+ * Read a cell reference.
117
+ * @param ref a reference such as A1 or $B$12.
118
+ * @returns the position, or undefined when out of bounds.
119
+ */
120
+ export function parseCellRef(ref) {
121
+ const match = REF.exec(ref.trim());
122
+ if (match === null)
123
+ return undefined;
124
+ const column = columnIndex(match[1] ?? '');
125
+ const row = Number(match[2]);
126
+ if (column === undefined || !Number.isInteger(row) || row < 1 || row > SHEET_LIMITS.maxRows)
127
+ return undefined;
128
+ return { row, column };
129
+ }
130
+ /**
131
+ * Format a zero-based cell position as a reference.
132
+ * @param row the one-based row.
133
+ * @param column the zero-based column.
134
+ * @returns the reference.
135
+ */
136
+ export function formatCellRef(row, column) {
137
+ return columnName(column) + String(row);
138
+ }
139
+ /**
140
+ * Read an inclusive range such as A1:C4.
141
+ * @param range the range text.
142
+ * @returns the normalised range, or undefined when malformed.
143
+ */
144
+ export function parseRangeRef(range) {
145
+ const parts = range.trim().split(':');
146
+ if (parts.length !== 2)
147
+ return undefined;
148
+ const start = parseCellRef(parts[0] ?? '');
149
+ const end = parseCellRef(parts[1] ?? '');
150
+ if (start === undefined || end === undefined)
151
+ return undefined;
152
+ return {
153
+ row1: Math.min(start.row, end.row),
154
+ column1: Math.min(start.column, end.column),
155
+ row2: Math.max(start.row, end.row),
156
+ column2: Math.max(start.column, end.column),
157
+ };
158
+ }
159
+ /**
160
+ * Format a range.
161
+ * @param range the range.
162
+ * @returns the text form.
163
+ */
164
+ export function formatRangeRef(range) {
165
+ return formatCellRef(range.row1, range.column1) + ':' + formatCellRef(range.row2, range.column2);
166
+ }
167
+ /** How many cells a range covers. */
168
+ export function rangeSize(range) {
169
+ return (range.row2 - range.row1 + 1) * (range.column2 - range.column1 + 1);
170
+ }
171
+ /**
172
+ * Iterate every cell of a range, row by row.
173
+ * @param range the range.
174
+ * @returns the positions.
175
+ */
176
+ export function rangeCells(range) {
177
+ const cells = [];
178
+ for (let row = range.row1; row <= range.row2; row += 1) {
179
+ for (let column = range.column1; column <= range.column2; column += 1)
180
+ cells.push({ row, column });
181
+ }
182
+ return cells;
183
+ }
184
+ export function checkSheetName(raw, at = 'The sheet name') {
185
+ if (typeof raw !== 'string')
186
+ throw new SheetError(at + ' must be a string.');
187
+ const name = raw.trim();
188
+ if (name === '' || name.length > SHEET_LIMITS.maxName) {
189
+ throw new SheetError(at + ' must be 1 to ' + String(SHEET_LIMITS.maxName) + ' characters.');
190
+ }
191
+ if (BAD_SHEET_NAME.test(name))
192
+ throw new SheetError(at + ' cannot contain \\ / ? * [ ] or : characters.');
193
+ if (name.startsWith("'") || name.endsWith("'"))
194
+ throw new SheetError(at + " cannot start or end with an apostrophe.");
195
+ return name;
196
+ }
197
+ function checkColor(raw, at) {
198
+ if (typeof raw !== 'string' || !HEX.test(raw.trim())) {
199
+ throw new SheetError(at + ' must be a hex color such as #1f2933.');
200
+ }
201
+ const color = raw.trim().toLowerCase();
202
+ if (color.length === 4)
203
+ return '#' + color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
204
+ return color;
205
+ }
206
+ function checkStyle(raw, at) {
207
+ if (!isFields(raw))
208
+ throw new SheetError(at + ' must be an object.');
209
+ onlyKeys(raw, STYLE_KEYS, at);
210
+ const style = {};
211
+ for (const key of ['bold', 'italic', 'underline', 'strike']) {
212
+ const value = raw[key];
213
+ if (value === undefined)
214
+ continue;
215
+ if (typeof value !== 'boolean')
216
+ throw new SheetError(at + '.' + key + ' must be true or false.');
217
+ style[key] = value;
218
+ }
219
+ if (raw.align !== undefined) {
220
+ if (typeof raw.align !== 'string' || !ALIGNS.includes(raw.align)) {
221
+ throw new SheetError(at + '.align must be left, center, or right.');
222
+ }
223
+ style.align = raw.align;
224
+ }
225
+ if (raw.numberFormat !== undefined) {
226
+ if (typeof raw.numberFormat !== 'string' || !NUMBER_FORMATS.includes(raw.numberFormat)) {
227
+ throw new SheetError(at + '.numberFormat must be ' + NUMBER_FORMATS.join(', ') + '.');
228
+ }
229
+ style.numberFormat = raw.numberFormat;
230
+ }
231
+ if (raw.color !== undefined)
232
+ style.color = checkColor(raw.color, at + '.color');
233
+ if (raw.background !== undefined)
234
+ style.background = checkColor(raw.background, at + '.background');
235
+ return style;
236
+ }
237
+ function styleIsEmpty(style) {
238
+ return Object.keys(style).length === 0;
239
+ }
240
+ /**
241
+ * Copy a style so a caller cannot mutate stored model state through it.
242
+ * @param style the style.
243
+ * @returns a copy.
244
+ */
245
+ export function copyStyle(style) {
246
+ if (style === undefined)
247
+ return undefined;
248
+ return { ...style };
249
+ }
250
+ /**
251
+ * Merge a partial style onto a cell style. A null value removes one property;
252
+ * false removes a boolean style, and a null alignment or number format resets.
253
+ * @param base the current style.
254
+ * @param patch the keys to set, with null removing.
255
+ * @returns the merged style, or undefined when it becomes empty.
256
+ */
257
+ export function mergeStyle(base, patch) {
258
+ const next = { ...(base ?? {}) };
259
+ const booleans = ['bold', 'italic', 'underline', 'strike'];
260
+ for (const key of booleans) {
261
+ const value = patch[key];
262
+ if (value === undefined)
263
+ continue;
264
+ if (value === null || value === false)
265
+ delete next[key];
266
+ else
267
+ next[key] = true;
268
+ }
269
+ if (patch.align !== undefined) {
270
+ if (patch.align === null)
271
+ delete next.align;
272
+ else
273
+ next.align = patch.align;
274
+ }
275
+ if (patch.numberFormat !== undefined) {
276
+ if (patch.numberFormat === null || patch.numberFormat === 'general')
277
+ delete next.numberFormat;
278
+ else
279
+ next.numberFormat = patch.numberFormat;
280
+ }
281
+ if (patch.color !== undefined) {
282
+ if (patch.color === null)
283
+ delete next.color;
284
+ else
285
+ next.color = patch.color;
286
+ }
287
+ if (patch.background !== undefined) {
288
+ if (patch.background === null)
289
+ delete next.background;
290
+ else
291
+ next.background = patch.background;
292
+ }
293
+ return styleIsEmpty(next) ? undefined : next;
294
+ }
295
+ function checkScalar(raw, at) {
296
+ if (raw === null || raw === undefined)
297
+ return undefined;
298
+ if (typeof raw === 'boolean')
299
+ return raw;
300
+ if (typeof raw === 'number') {
301
+ if (!Number.isFinite(raw))
302
+ throw new SheetError(at + ' must be a finite number.');
303
+ return raw;
304
+ }
305
+ if (typeof raw === 'string') {
306
+ if (raw.length > SHEET_LIMITS.maxCellText)
307
+ throw new SheetError(at + ' is longer than ' + String(SHEET_LIMITS.maxCellText) + ' characters.');
308
+ return raw;
309
+ }
310
+ throw new SheetError(at + ' must be a string, number, boolean, or null.');
311
+ }
312
+ function normalizeCell(raw, at) {
313
+ if (raw === null)
314
+ return undefined;
315
+ if (typeof raw === 'string' || typeof raw === 'number' || typeof raw === 'boolean') {
316
+ const value = checkScalar(raw, at);
317
+ if (value === undefined)
318
+ return undefined;
319
+ if (typeof value === 'string' && value.startsWith('='))
320
+ return normalizeCell({ formula: value }, at);
321
+ return { value };
322
+ }
323
+ if (!isFields(raw))
324
+ throw new SheetError(at + ' must be a JSON scalar or an object with value, formula, or style.');
325
+ onlyKeys(raw, CELL_KEYS, at);
326
+ const style = raw.style === undefined ? undefined : checkStyle(raw.style, at + '.style');
327
+ const formula = raw.formula === undefined ? undefined : normalizeFormula(raw.formula, at + '.formula');
328
+ if (formula !== undefined && raw.value !== undefined) {
329
+ throw new SheetError(at + ' cannot have both value and formula; the value of a formula is computed.');
330
+ }
331
+ const value = checkScalar(raw.value, at + '.value');
332
+ const cell = {};
333
+ if (formula !== undefined)
334
+ cell.formula = formula;
335
+ if (value !== undefined)
336
+ cell.value = value;
337
+ if (style !== undefined && !styleIsEmpty(style))
338
+ cell.style = style;
339
+ if (cell.formula === undefined && cell.value === undefined && cell.style === undefined)
340
+ return undefined;
341
+ return cell;
342
+ }
343
+ function normalizeFormula(raw, at) {
344
+ if (typeof raw !== 'string')
345
+ throw new SheetError(at + ' must be a string formula.');
346
+ let formula = raw.trim();
347
+ if (formula === '' || formula === '=')
348
+ throw new SheetError(at + ' is empty.');
349
+ if (!formula.startsWith('='))
350
+ formula = '=' + formula;
351
+ if (formula.length > SHEET_LIMITS.maxFormula)
352
+ throw new SheetError(at + ' is longer than ' + String(SHEET_LIMITS.maxFormula) + ' characters.');
353
+ return formula;
354
+ }
355
+ function normalizeWidths(raw, at) {
356
+ if (raw === undefined)
357
+ return undefined;
358
+ if (!isFields(raw))
359
+ throw new SheetError(at + ' must be an object of column letters to pixel widths.');
360
+ const widths = {};
361
+ for (const [key, value] of Object.entries(raw)) {
362
+ const column = columnIndex(key);
363
+ if (column === undefined)
364
+ throw new SheetError(at + ' has an invalid column "' + key + '".');
365
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value)) {
366
+ throw new SheetError(at + '.' + key + ' must be a whole number of pixels.');
367
+ }
368
+ if (value < SHEET_LIMITS.minColumnWidth || value > SHEET_LIMITS.maxColumnWidth) {
369
+ throw new SheetError(at + '.' + key + ' must be between ' + String(SHEET_LIMITS.minColumnWidth) + ' and ' + String(SHEET_LIMITS.maxColumnWidth) + ' pixels.');
370
+ }
371
+ const name = columnName(column);
372
+ if (widths[name] !== undefined)
373
+ throw new SheetError(at + ' names column ' + name + ' twice.');
374
+ widths[name] = value;
375
+ }
376
+ return Object.keys(widths).length === 0 ? undefined : widths;
377
+ }
378
+ /**
379
+ * Validate an unknown value as a workbook and return a normalised copy.
380
+ * @param value the parsed JSON or a constructed value.
381
+ * @returns the workbook.
382
+ */
383
+ export function normalizeSheetWorkbook(value) {
384
+ if (!isFields(value))
385
+ throw new SheetError('A sheet workbook must be a JSON object.');
386
+ onlyKeys(value, WORKBOOK_KEYS, 'The workbook');
387
+ if (value.schemaVersion !== undefined && value.schemaVersion !== SHEET_SCHEMA_VERSION) {
388
+ throw new SheetError('Unsupported sheet schemaVersion ' + String(value.schemaVersion) + '; this build reads version ' + String(SHEET_SCHEMA_VERSION) + '.');
389
+ }
390
+ const rawSheets = value.sheets;
391
+ if (!Array.isArray(rawSheets) || rawSheets.length === 0)
392
+ throw new SheetError('A sheet workbook needs a "sheets" array with at least one sheet.');
393
+ if (rawSheets.length > SHEET_LIMITS.maxSheets)
394
+ throw new SheetError('A workbook holds at most ' + String(SHEET_LIMITS.maxSheets) + ' sheets.');
395
+ const names = new Set();
396
+ let totalCells = 0;
397
+ let totalFormulas = 0;
398
+ const sheets = rawSheets.map((rawSheet, sheetIndex) => {
399
+ const at = 'sheets[' + String(sheetIndex) + ']';
400
+ if (!isFields(rawSheet))
401
+ throw new SheetError(at + ' must be an object.');
402
+ onlyKeys(rawSheet, SHEET_KEYS, at);
403
+ const name = checkSheetName(rawSheet.name, at + '.name');
404
+ if (names.has(name.toLowerCase()))
405
+ throw new SheetError('Two sheets are named "' + name + '"; names must be unique.');
406
+ names.add(name.toLowerCase());
407
+ const rawCells = rawSheet.cells ?? {};
408
+ if (!isFields(rawCells))
409
+ throw new SheetError(at + '.cells must be an object of cell references to values.');
410
+ const cells = {};
411
+ for (const [ref, rawCell] of Object.entries(rawCells)) {
412
+ const index = parseCellRef(ref);
413
+ if (index === undefined)
414
+ throw new SheetError(at + '.cells has an invalid cell reference "' + ref + '".');
415
+ const cell = normalizeCell(rawCell, at + '.cells.' + formatCellRef(index.row, index.column));
416
+ if (cell === undefined)
417
+ continue;
418
+ totalCells += 1;
419
+ if (cell.formula !== undefined)
420
+ totalFormulas += 1;
421
+ cells[formatCellRef(index.row, index.column)] = cell;
422
+ }
423
+ if (totalCells > SHEET_LIMITS.maxCells)
424
+ throw new SheetError('A sheet artifact holds at most ' + String(SHEET_LIMITS.maxCells) + ' cells.');
425
+ if (totalFormulas > SHEET_LIMITS.maxFormulaCells)
426
+ throw new SheetError('A sheet artifact holds at most ' + String(SHEET_LIMITS.maxFormulaCells) + ' formulas.');
427
+ const ordered = {};
428
+ const refs = Object.keys(cells).sort((left, right) => {
429
+ const a = parseCellRef(left);
430
+ const b = parseCellRef(right);
431
+ if (a === undefined || b === undefined)
432
+ return left < right ? -1 : 1;
433
+ return a.row === b.row ? a.column - b.column : a.row - b.row;
434
+ });
435
+ for (const ref of refs) {
436
+ const cell = cells[ref];
437
+ if (cell !== undefined)
438
+ ordered[ref] = cell;
439
+ }
440
+ const columnWidths = normalizeWidths(rawSheet.columnWidths, at + '.columnWidths');
441
+ return { name, cells: ordered, ...(columnWidths === undefined ? {} : { columnWidths }) };
442
+ });
443
+ return { schemaVersion: SHEET_SCHEMA_VERSION, sheets };
444
+ }
445
+ /**
446
+ * Parse the stored content into a workbook.
447
+ * @param text the JSON source.
448
+ * @returns the normalised workbook.
449
+ */
450
+ export function parseSheetWorkbook(text) {
451
+ let value;
452
+ try {
453
+ value = JSON.parse(text);
454
+ }
455
+ catch {
456
+ throw new SheetError('The sheet content is not valid JSON. Send one JSON object with schemaVersion and sheets.');
457
+ }
458
+ return normalizeSheetWorkbook(value);
459
+ }
460
+ function cellToJson(cell) {
461
+ const hasStyle = cell.style !== undefined && !styleIsEmpty(cell.style);
462
+ if (!hasStyle) {
463
+ if (cell.formula !== undefined)
464
+ return { formula: cell.formula };
465
+ // A literal string that starts with "=" must keep the object form, or the
466
+ // reader would parse it back as a formula.
467
+ if (typeof cell.value === 'string' && cell.value.startsWith('='))
468
+ return { value: cell.value };
469
+ if (cell.value !== undefined)
470
+ return cell.value;
471
+ return null;
472
+ }
473
+ const out = {};
474
+ if (cell.formula !== undefined)
475
+ out.formula = cell.formula;
476
+ else if (cell.value !== undefined)
477
+ out.value = cell.value;
478
+ out.style = styleToJson(cell.style);
479
+ return out;
480
+ }
481
+ function styleToJson(style) {
482
+ const out = {};
483
+ if (style === undefined)
484
+ return out;
485
+ for (const key of STYLE_KEYS) {
486
+ const value = style[key];
487
+ if (value !== undefined)
488
+ out[key] = value;
489
+ }
490
+ return out;
491
+ }
492
+ /**
493
+ * Serialise a workbook in canonical order. Stable ordering keeps a content hash
494
+ * meaningful and makes an artifact diff easy to read.
495
+ * @param workbook the workbook.
496
+ * @returns the JSON text ending in a newline.
497
+ */
498
+ export function serializeSheetWorkbook(workbook) {
499
+ const sheets = workbook.sheets.map((sheet) => {
500
+ const refs = Object.keys(sheet.cells).sort((left, right) => {
501
+ const a = parseCellRef(left);
502
+ const b = parseCellRef(right);
503
+ if (a === undefined || b === undefined)
504
+ return left < right ? -1 : 1;
505
+ return a.row === b.row ? a.column - b.column : a.row - b.row;
506
+ });
507
+ const cells = {};
508
+ for (const ref of refs) {
509
+ const cell = sheet.cells[ref];
510
+ if (cell === undefined)
511
+ continue;
512
+ const encoded = cellToJson(cell);
513
+ if (encoded === null)
514
+ continue;
515
+ cells[ref] = encoded;
516
+ }
517
+ const data = { name: sheet.name, cells };
518
+ if (sheet.columnWidths !== undefined && Object.keys(sheet.columnWidths).length > 0) {
519
+ const widths = {};
520
+ const names = Object.keys(sheet.columnWidths).sort((left, right) => (columnIndex(left) ?? 0) - (columnIndex(right) ?? 0));
521
+ for (const name of names) {
522
+ const width = sheet.columnWidths[name];
523
+ if (width !== undefined)
524
+ widths[name] = width;
525
+ }
526
+ data.columnWidths = widths;
527
+ }
528
+ return data;
529
+ });
530
+ return JSON.stringify({ schemaVersion: SHEET_SCHEMA_VERSION, sheets }, null, 2) + '\n';
531
+ }
532
+ /**
533
+ * The sheet with a name, or the first sheet when no name is given.
534
+ * @param workbook the workbook.
535
+ * @param name the sheet name, when the caller names one.
536
+ * @returns the sheet.
537
+ */
538
+ export function sheetOf(workbook, name) {
539
+ if (name === undefined) {
540
+ const first = workbook.sheets[0];
541
+ if (first === undefined)
542
+ throw new SheetError('The workbook has no sheets.');
543
+ return first;
544
+ }
545
+ const found = workbook.sheets.find((sheet) => sheet.name.toLowerCase() === name.trim().toLowerCase());
546
+ if (found === undefined)
547
+ throw new SheetError('No sheet is named "' + name + '".');
548
+ return found;
549
+ }
550
+ /**
551
+ * The greatest used row and column of one sheet, or undefined for an empty sheet.
552
+ * @param sheet the sheet.
553
+ * @returns the bounds, one-based row, zero-based column.
554
+ */
555
+ export function usedBounds(sheet) {
556
+ let rows = 0;
557
+ let columns = 0;
558
+ for (const ref of Object.keys(sheet.cells)) {
559
+ const index = parseCellRef(ref);
560
+ if (index === undefined)
561
+ continue;
562
+ if (index.row > rows)
563
+ rows = index.row;
564
+ if (index.column + 1 > columns)
565
+ columns = index.column + 1;
566
+ }
567
+ return { rows, columns };
568
+ }
569
+ /**
570
+ * A short, content-free summary for tool results and the panel header.
571
+ * @param workbook the workbook.
572
+ * @returns sheet names and counts.
573
+ */
574
+ export function sheetSummary(workbook) {
575
+ let cells = 0;
576
+ let formulas = 0;
577
+ const sheets = workbook.sheets.map((sheet) => {
578
+ let sheetCells = 0;
579
+ let sheetFormulas = 0;
580
+ for (const cell of Object.values(sheet.cells)) {
581
+ sheetCells += 1;
582
+ if (cell.formula !== undefined)
583
+ sheetFormulas += 1;
584
+ }
585
+ cells += sheetCells;
586
+ formulas += sheetFormulas;
587
+ return { name: sheet.name, cells: sheetCells, formulas: sheetFormulas };
588
+ });
589
+ return { sheets, cells, formulas };
590
+ }
591
+ /**
592
+ * Resolve a cell in a sheet, when it exists.
593
+ * @param workbook the workbook.
594
+ * @param sheetName the sheet.
595
+ * @param ref the cell.
596
+ * @returns the cell, or undefined.
597
+ */
598
+ export function cellOf(workbook, sheetName, ref) {
599
+ return sheetOf(workbook, sheetName).cells[ref];
600
+ }
601
+ /**
602
+ * A copy of the workbook safe to mutate. Sheet and cell objects are copied
603
+ * shallowly; callers replace a cell rather than editing one in place.
604
+ * @param workbook the workbook.
605
+ * @returns the copy.
606
+ */
607
+ export function cloneWorkbook(workbook) {
608
+ return {
609
+ schemaVersion: SHEET_SCHEMA_VERSION,
610
+ sheets: workbook.sheets.map((sheet) => ({
611
+ name: sheet.name,
612
+ cells: Object.fromEntries(Object.entries(sheet.cells).map(([ref, cell]) => [ref, cloneCell(cell)])),
613
+ ...(sheet.columnWidths === undefined ? {} : { columnWidths: { ...sheet.columnWidths } }),
614
+ })),
615
+ };
616
+ }
617
+ /**
618
+ * Copy one cell.
619
+ * @param cell the cell.
620
+ * @returns a copy.
621
+ */
622
+ export function cloneCell(cell) {
623
+ return {
624
+ ...(cell.value === undefined ? {} : { value: cell.value }),
625
+ ...(cell.formula === undefined ? {} : { formula: cell.formula }),
626
+ ...(cell.style === undefined ? {} : { style: { ...cell.style } }),
627
+ };
628
+ }