@file-viewer/renderer-spreadsheet 3.3.1 → 3.3.4

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 (52) hide show
  1. package/README.en.md +14 -0
  2. package/README.md +14 -0
  3. package/README.zh-CN.md +14 -0
  4. package/dist/spreadsheet/autoRowHeight.d.ts +16 -0
  5. package/dist/spreadsheet/autoRowHeight.js +208 -0
  6. package/dist/spreadsheet/chartRenderer.js +0 -5
  7. package/dist/spreadsheet/chartSampling.d.ts +0 -4
  8. package/dist/spreadsheet/chartSampling.js +0 -6
  9. package/dist/spreadsheet/comments.d.ts +40 -0
  10. package/dist/spreadsheet/comments.js +388 -0
  11. package/dist/spreadsheet/drawingAutoHeight.d.ts +7 -0
  12. package/dist/spreadsheet/drawingAutoHeight.js +51 -0
  13. package/dist/spreadsheet/rangeNavigation.d.ts +0 -2
  14. package/dist/spreadsheet/rangeNavigation.js +0 -4
  15. package/dist/spreadsheet/sourceRegion.d.ts +37 -0
  16. package/dist/spreadsheet/sourceRegion.js +54 -0
  17. package/dist/spreadsheet/state.d.ts +7 -2
  18. package/dist/spreadsheet/state.js +6 -2
  19. package/dist/spreadsheet/view.d.ts +9 -4
  20. package/dist/spreadsheet/view.js +98 -39
  21. package/dist/spreadsheet/viewport.d.ts +0 -1
  22. package/dist/spreadsheet/viewport.js +0 -2
  23. package/dist/spreadsheet/worker/sheetjs/SheetJsModel.d.ts +61 -2
  24. package/dist/spreadsheet/worker/sheetjs/SheetJsModel.js +134 -43
  25. package/dist/spreadsheet/worker/sheetjs/chartParser.d.ts +3 -2
  26. package/dist/spreadsheet/worker/sheetjs/chartParser.js +13 -24
  27. package/dist/spreadsheet/worker/sheetjs/color.js +8 -10
  28. package/dist/spreadsheet/worker/sheetjs/commentParser.d.ts +7 -0
  29. package/dist/spreadsheet/worker/sheetjs/commentParser.js +232 -0
  30. package/dist/spreadsheet/worker/sheetjs/drawingRowAnchor.d.ts +4 -0
  31. package/dist/spreadsheet/worker/sheetjs/drawingRowAnchor.js +90 -0
  32. package/dist/spreadsheet/worker/sheetjs/formulaValues.js +0 -9
  33. package/dist/spreadsheet/worker/sheetjs/parser.d.ts +40 -4
  34. package/dist/spreadsheet/worker/sheetjs/parser.js +453 -78
  35. package/dist/spreadsheet/worker/sheetjs/richDataParser.js +5 -4
  36. package/dist/spreadsheet/worker/sheetjs/richText.js +0 -1
  37. package/dist/spreadsheet/worker/sheetjs/rowSizing.d.ts +10 -0
  38. package/dist/spreadsheet/worker/sheetjs/rowSizing.js +156 -0
  39. package/dist/spreadsheet/worker/sheetjs/sheetLayout.d.ts +2 -4
  40. package/dist/spreadsheet/worker/sheetjs/sheetLayout.js +0 -8
  41. package/dist/spreadsheet/worker/sheetjs/sourceAnchor.d.ts +10 -0
  42. package/dist/spreadsheet/worker/sheetjs/sourceAnchor.js +286 -0
  43. package/dist/spreadsheet/worker/sheetjs/textEncoding.d.ts +1 -1
  44. package/dist/spreadsheet/worker/sheetjs/textEncoding.js +1 -8
  45. package/dist/spreadsheet/worker/sheetjs/workbookFont.d.ts +4 -0
  46. package/dist/spreadsheet/worker/sheetjs/workbookFont.js +15 -0
  47. package/dist/spreadsheet/worker/sheetjs/xmlBudget.d.ts +11 -0
  48. package/dist/spreadsheet/worker/sheetjs/xmlBudget.js +39 -0
  49. package/dist/spreadsheet/worker/type.d.ts +145 -3
  50. package/dist/spreadsheet.js +150 -63
  51. package/dist/worker/sheet.worker.js +49 -65
  52. package/package.json +23 -3
@@ -1,9 +1,13 @@
1
+ import { assertSheetRegion, createSheetRegion, sourceToRegion, getSheetMaterialization, EXCEL_SOURCE_EXTENT, REGION_LIMIT, ORDINARY_GRID_BUDGET, OCCUPIED_INDEX_BUDGET } from '../../sourceRegion.js';
2
+ import { readImageSourceProvenance, unknownSourceAnchor } from './sourceAnchor.js';
3
+ import { parseSpreadsheetComments, readWorkbookNotes } from './commentParser.js';
1
4
  import { read, utils } from 'styled-exceljs';
2
5
  import SheetJsModel, { formatCellValue } from './SheetJsModel.js';
3
6
  import { parseSpreadsheetCharts } from './chartParser.js';
4
7
  import { prepareSpreadsheetReadInput, } from './textEncoding.js';
5
8
  import { parseSpreadsheetCellImages } from './richDataParser.js';
6
9
  import { recoverUncachedFormulaValues } from './formulaValues.js';
10
+ import { readWorkbookDefaultFont } from './workbookFont.js';
7
11
  const readOptions = {
8
12
  type: 'array',
9
13
  dense: true,
@@ -12,7 +16,6 @@ const readOptions = {
12
16
  browserPixels: true,
13
17
  drawings: true,
14
18
  };
15
- // HTML/XML 文件必须传入 type: 'string' 保持原有的 HTML 单元格解析结果
16
19
  const prefersSheetJsTextSniff = (text) => /^[\s\uFEFF]*</.test(text);
17
20
  const isMergeValidationError = (error) => (error instanceof Error
18
21
  && typeof error.code === 'string'
@@ -79,14 +82,7 @@ const sanitizeToleratedMerges = (workbook) => {
79
82
  });
80
83
  }
81
84
  };
82
- const readPreparedWorkbook = (input, validateMerges) => (
83
- /***
84
- * 对于二进制格式,直接透传 ArrayBuffer
85
- * 对于文本格式用 prefersSheetJsTextSniff 选 type:
86
- * - 普通文本 -> 'binary',绕过 SheetJS 内部 utf8write 的大数组崩溃
87
- * - HTML/XML -> 'string',保持原有的 HTML 单元格解析结果
88
- */
89
- input.kind === 'text'
85
+ const readPreparedWorkbook = (input, validateMerges) => (input.kind === 'text'
90
86
  ? read(input.data, { ...readOptions, type: prefersSheetJsTextSniff(input.data) ? 'string' : 'binary', validateMerges })
91
87
  : read(input.data, { ...readOptions, validateMerges }));
92
88
  const readWorkbookWithMergeRecovery = (input) => {
@@ -107,6 +103,8 @@ export const createSpreadsheetParserContext = () => ({
107
103
  sheets: [],
108
104
  charts: {},
109
105
  cellImages: {},
106
+ comments: {},
107
+ commentsError: false,
110
108
  });
111
109
  const toErrorResponse = (error, payload = {}) => ({
112
110
  type: 'parseError',
@@ -115,66 +113,49 @@ const toErrorResponse = (error, payload = {}) => ({
115
113
  message: error instanceof Error ? error.message : String(error),
116
114
  },
117
115
  });
116
+ const legalSourcePoint = (point) => Number.isSafeInteger(point === null || point === void 0 ? void 0 : point.row)
117
+ && Number.isSafeInteger(point === null || point === void 0 ? void 0 : point.col) && point.row >= 0 && point.col >= 0
118
+ && point.row < EXCEL_SOURCE_EXTENT.rows && point.col < EXCEL_SOURCE_EXTENT.cols;
118
119
  const getDrawingBounds = (worksheet) => {
119
- var _a;
120
- const images = ((_a = worksheet === null || worksheet === void 0 ? void 0 : worksheet['!drawings']) === null || _a === void 0 ? void 0 : _a.images) || [];
121
- return images.reduce((bounds, image) => {
122
- var _a, _b, _c, _d, _e, _f;
123
- const anchor = image.anchor;
124
- const row = Number((_b = (_a = anchor === null || anchor === void 0 ? void 0 : anchor.to) === null || _a === void 0 ? void 0 : _a.row) !== null && _b !== void 0 ? _b : (_c = anchor === null || anchor === void 0 ? void 0 : anchor.from) === null || _c === void 0 ? void 0 : _c.row);
125
- const col = Number((_e = (_d = anchor === null || anchor === void 0 ? void 0 : anchor.to) === null || _d === void 0 ? void 0 : _d.col) !== null && _e !== void 0 ? _e : (_f = anchor === null || anchor === void 0 ? void 0 : anchor.from) === null || _f === void 0 ? void 0 : _f.col);
126
- return {
127
- rowCount: Number.isFinite(row) ? Math.max(bounds.rowCount, row + 1) : bounds.rowCount,
128
- colCount: Number.isFinite(col) ? Math.max(bounds.colCount, col + 1) : bounds.colCount,
129
- };
130
- }, {
131
- rowCount: 0,
132
- colCount: 0,
133
- });
120
+ var _a, _b, _c;
121
+ const bounds = { rowCount: 0, colCount: 0 };
122
+ for (const image of ((_a = worksheet === null || worksheet === void 0 ? void 0 : worksheet['!drawings']) === null || _a === void 0 ? void 0 : _a.images) || []) {
123
+ for (const point of [(_b = image.anchor) === null || _b === void 0 ? void 0 : _b.from, (_c = image.anchor) === null || _c === void 0 ? void 0 : _c.to])
124
+ if (legalSourcePoint(point)) {
125
+ bounds.rowCount = Math.max(bounds.rowCount, point.row + 1);
126
+ bounds.colCount = Math.max(bounds.colCount, point.col + 1);
127
+ }
128
+ }
129
+ return bounds;
134
130
  };
135
131
  const getChartBounds = (charts) => {
136
- return (charts || []).reduce((bounds, chart) => {
137
- var _a, _b, _c, _d, _e, _f;
138
- const estimatedRows = ((_a = chart.ext) === null || _a === void 0 ? void 0 : _a.height)
139
- ? Math.ceil(chart.ext.height / 9525 / 20)
140
- : 0;
141
- const estimatedCols = ((_b = chart.ext) === null || _b === void 0 ? void 0 : _b.width)
142
- ? Math.ceil(chart.ext.width / 9525 / 64)
143
- : 0;
144
- const row = (_d = (_c = chart.to) === null || _c === void 0 ? void 0 : _c.row) !== null && _d !== void 0 ? _d : chart.from.row + estimatedRows;
145
- const col = (_f = (_e = chart.to) === null || _e === void 0 ? void 0 : _e.col) !== null && _f !== void 0 ? _f : chart.from.col + estimatedCols;
146
- return {
147
- rowCount: Math.max(bounds.rowCount, row + 1),
148
- colCount: Math.max(bounds.colCount, col + 1),
149
- };
150
- }, {
151
- rowCount: 0,
152
- colCount: 0,
153
- });
132
+ var _a, _b, _c;
133
+ const bounds = { rowCount: 0, colCount: 0 };
134
+ for (const chart of charts || []) {
135
+ const estimated = { row: chart.from.row + Math.ceil((((_a = chart.ext) === null || _a === void 0 ? void 0 : _a.height) || 0) / 9525 / 20),
136
+ col: chart.from.col + Math.ceil((((_b = chart.ext) === null || _b === void 0 ? void 0 : _b.width) || 0) / 9525 / 64) };
137
+ for (const point of [chart.from, (_c = chart.to) !== null && _c !== void 0 ? _c : estimated])
138
+ if (legalSourcePoint(point)) {
139
+ bounds.rowCount = Math.max(bounds.rowCount, point.row + 1);
140
+ bounds.colCount = Math.max(bounds.colCount, point.col + 1);
141
+ }
142
+ }
143
+ return bounds;
154
144
  };
155
145
  const EMPTY_RANGE_ROW_LIMIT = 1000;
156
146
  const EMPTY_RANGE_COLUMN_LIMIT = 256;
157
147
  const RANGE_ROW_SLACK = 256;
158
148
  const RANGE_COLUMN_SLACK = 64;
159
149
  const RANGE_GROWTH_FACTOR = 4;
160
- /** Drop sparse far outliers once the gap dwarfs the dense cluster near A1. */
161
150
  const CONTENT_GAP_ROW_MULTIPLIER = 4;
162
151
  const CONTENT_GAP_COL_MULTIPLIER = 4;
163
- /**
164
- * Keep the dense cell cluster that starts nearest A1.
165
- * Nearby style-only stubs still count (needed for formatted empty tables, see #175),
166
- * but a huge gap before far ghost cells near Excel max is treated as an outlier (#405).
167
- */
168
152
  const compactSparseExtent = (indices, slack, gapMultiplier, contentExtent) => {
169
153
  if (indices.length === 0)
170
154
  return 0;
171
155
  const sorted = [...new Set(indices)].sort((a, b) => a - b);
172
156
  const originThreshold = Math.max(slack * gapMultiplier, RANGE_GROWTH_FACTOR);
173
- // A workbook whose only sheet entries sit absurdly far from A1 has no usable near cluster.
174
157
  if (!contentExtent && sorted[0] > originThreshold)
175
158
  return 0;
176
- // All meaningful cells are mandatory, even across gaps or far from A1.
177
- // Only blank formatting beyond the last content cell may be compacted.
178
159
  let end = Math.max(sorted[0], contentExtent - 1);
179
160
  for (let i = 1; i < sorted.length; i += 1) {
180
161
  const current = sorted[i];
@@ -189,7 +170,61 @@ const compactSparseExtent = (indices, slack, gapMultiplier, contentExtent) => {
189
170
  }
190
171
  return end + 1;
191
172
  };
192
- const getCellBounds = (worksheet) => {
173
+ export const classifySpreadsheetCell = (value, defaultFont) => {
174
+ if (value == null)
175
+ return { value: false, style: 'default', visual: false };
176
+ if (typeof value !== 'object')
177
+ return { value: true, style: 'default', visual: true };
178
+ const cell = value;
179
+ const content = cell.v != null || cell.f != null || cell.F != null || !!cell.w || !!cell.r || !!cell.h || !!cell.l;
180
+ const raw = cell.s;
181
+ const sameFont = (left, right, depth = 0) => {
182
+ if (left === right)
183
+ return true;
184
+ if (depth > 4 || !left || !right || typeof left !== 'object' || typeof right !== 'object'
185
+ || Array.isArray(left) || Array.isArray(right))
186
+ return false;
187
+ const keys = Object.keys(left), other = Object.keys(right);
188
+ return keys.length <= 32 && keys.length === other.length
189
+ && keys.every(key => Object.prototype.hasOwnProperty.call(right, key) && sameFont(left[key], right[key], depth + 1));
190
+ };
191
+ const provenNoteDefaultFont = !content && Array.isArray(cell.c) && cell.c.length > 0
192
+ && (raw === null || raw === void 0 ? void 0 : raw.id) === 0 && defaultFont !== undefined && sameFont(raw.font, defaultFont);
193
+ let style = 'default';
194
+ if (raw != null) {
195
+ if (typeof raw !== 'object' || Array.isArray(raw))
196
+ style = 'unknown';
197
+ else {
198
+ const isEmpty = (item) => item != null && typeof item === 'object' && Object.keys(item).length === 0;
199
+ for (const [key, item] of Object.entries(raw)) {
200
+ if (item == null || (key === 'font' && provenNoteDefaultFont) || (key === 'patternType' && item === 'none')
201
+ || (key === 'numFmtId' && item === 0)
202
+ || (key === 'id' && item === 0 && Object.keys(raw).some(k => ['font', 'fill', 'border', 'alignment', 'patternType', 'numFmt'].includes(k)))
203
+ || (key === 'numFmt' && item === 'General')
204
+ || (['font', 'border', 'alignment', 'fill', 'protection', 'xf'].includes(key) && isEmpty(item))
205
+ || (key === 'fill' && typeof item === 'object' && item !== null
206
+ && Object.keys(item).every(k => k === 'patternType') && item.patternType === 'none'))
207
+ continue;
208
+ if (['font', 'border', 'alignment', 'fill', 'numFmt', 'numFmtId', 'patternType', 'fgColor', 'bgColor', 'protection'].includes(key)) {
209
+ if (style !== 'unknown')
210
+ style = 'authored';
211
+ }
212
+ else if (key === 'id' && typeof item === 'number' && item > 0) {
213
+ if (style !== 'unknown')
214
+ style = 'authored';
215
+ }
216
+ else if (key === 'xf') {
217
+ if (!['font', 'fill', 'border', 'alignment', 'numFmt'].some(k => raw[k] && !isEmpty(raw[k])))
218
+ style = 'unknown';
219
+ }
220
+ else
221
+ style = 'unknown';
222
+ }
223
+ }
224
+ }
225
+ return { value: content, style, visual: content || style !== 'default' };
226
+ };
227
+ const getCellBounds = (worksheet, defaultFont) => {
193
228
  const bounds = { rowCount: 0, colCount: 0 };
194
229
  if (!worksheet)
195
230
  return bounds;
@@ -198,14 +233,13 @@ const getCellBounds = (worksheet) => {
198
233
  let contentRows = 0;
199
234
  let contentCols = 0;
200
235
  const observe = (row, col, value) => {
236
+ const cell = value;
237
+ const classification = classifySpreadsheetCell(value, defaultFont);
238
+ const meaningful = classification.value;
239
+ if (!meaningful && Array.isArray(cell.c) && cell.c.length && classification.style === 'default')
240
+ return;
201
241
  rowIndices.push(row);
202
242
  colIndices.push(col);
203
- const cell = value;
204
- // Do not test truthiness: zero, false and an explicitly stored empty string
205
- // are content too. Uncached formulas have no v but must remain reachable.
206
- const meaningful = typeof value !== 'object' || cell.v != null || cell.f != null
207
- || cell.F != null || !!cell.w || !!cell.r || !!cell.h || !!cell.l
208
- || (Array.isArray(cell.c) && cell.c.length > 0);
209
243
  if (meaningful) {
210
244
  contentRows = Math.max(contentRows, row + 1);
211
245
  contentCols = Math.max(contentCols, col + 1);
@@ -237,7 +271,6 @@ const getCellBounds = (worksheet) => {
237
271
  observe(cell.r, cell.c, worksheet[key]);
238
272
  }
239
273
  catch {
240
- // Ignore non-cell extension keys exposed by third-party workbook producers.
241
274
  }
242
275
  }
243
276
  }
@@ -265,7 +298,7 @@ const reconcileDeclaredRange = (declaredCount, observedCount, slack, emptyLimit)
265
298
  ? Math.max(declaredCount, observedCount)
266
299
  : observedCount;
267
300
  };
268
- export const getWorksheetDisplayBounds = (worksheet, charts) => {
301
+ export const getWorksheetDisplayBounds = (worksheet, charts, _comments = [], options = {}) => {
269
302
  let declaredRowCount = 0;
270
303
  let declaredColCount = 0;
271
304
  const ref = worksheet === null || worksheet === void 0 ? void 0 : worksheet['!ref'];
@@ -276,10 +309,9 @@ export const getWorksheetDisplayBounds = (worksheet, charts) => {
276
309
  declaredColCount = range.e.c + 1;
277
310
  }
278
311
  catch {
279
- // Invalid producer dimensions must not block content-based recovery.
280
312
  }
281
313
  }
282
- const cellBounds = getCellBounds(worksheet);
314
+ const cellBounds = getCellBounds(worksheet, options.defaultFont);
283
315
  const mergeBounds = getMergeBounds(worksheet);
284
316
  const drawingBounds = getDrawingBounds(worksheet);
285
317
  const chartBounds = getChartBounds(charts);
@@ -311,33 +343,64 @@ const parseSheets = (context, includeEmptySheets = false) => {
311
343
  }
312
344
  const workbookSheets = ((_a = workbook.Workbook) === null || _a === void 0 ? void 0 : _a.Sheets) || [];
313
345
  context.sheets = workbook.SheetNames.reduce((result, name, sourceIndex) => {
314
- var _a;
346
+ var _a, _b, _c, _d;
315
347
  const worksheet = workbook.Sheets[name];
316
- const bounds = getWorksheetDisplayBounds(worksheet, context.charts[name]);
317
- const empty = !(worksheet === null || worksheet === void 0 ? void 0 : worksheet['!ref']) && !bounds.observedRowCount && !bounds.observedColCount;
318
- if (!worksheet || (empty && !includeEmptySheets)) {
348
+ const bounds = getWorksheetDisplayBounds(worksheet, context.charts[name], context.comments[name], { defaultFont: readWorkbookDefaultFont(workbook) });
349
+ const comments = context.comments[name] || [];
350
+ const discovered = worksheet ? discoverSpreadsheetSource(workbook.Sheets[name], { charts: context.charts[name], cellImages: context.cellImages[name], defaultFont: readWorkbookDefaultFont(workbook) }) : undefined;
351
+ const hasVisualSource = !!discovered && (discovered.extent.rows > 0 || discovered.sourceDiscovery.objects.length > 0 || discovered.sourceDiscovery.status === 'partial');
352
+ const empty = (!(worksheet === null || worksheet === void 0 ? void 0 : worksheet['!ref']) || comments.length > 0) && !bounds.observedRowCount && !bounds.observedColCount;
353
+ if (!worksheet || (empty && !includeEmptySheets && !comments.length && !hasVisualSource)) {
319
354
  return result;
320
355
  }
356
+ const dataExtent = { rows: empty ? 0 : bounds.rowCount, cols: empty ? 0 : bounds.colCount };
357
+ const visualExtent = { rows: Math.max(dataExtent.rows, (discovered === null || discovered === void 0 ? void 0 : discovered.extent.rows) || 0), cols: Math.max(dataExtent.cols, (discovered === null || discovered === void 0 ? void 0 : discovered.extent.cols) || 0) };
358
+ const logicalExtent = comments.reduce((extent, comment) => ({
359
+ rows: Math.max(extent.rows, comment.row + 1), cols: Math.max(extent.cols, comment.col + 1),
360
+ }), { ...visualExtent });
361
+ const materialization = getSheetMaterialization(dataExtent);
362
+ const occupied = materialization.kind === 'region-required' ? indexOccupiedRegions(workbook.Sheets[name]) : undefined;
363
+ const occupiedRegions = occupied === null || occupied === void 0 ? void 0 : occupied.regions;
364
+ const needsSourceRegion = materialization.kind === 'region-required' || visualExtent.rows > dataExtent.rows || visualExtent.cols > dataExtent.cols || empty;
365
+ const firstTarget = needsSourceRegion ? (((_a = occupiedRegions === null || occupiedRegions === void 0 ? void 0 : occupiedRegions[0]) === null || _a === void 0 ? void 0 : _a.firstCell) || ((_b = discovered === null || discovered === void 0 ? void 0 : discovered.sourceDiscovery.cellRegions[0]) === null || _b === void 0 ? void 0 : _b.firstCell)
366
+ || ((_c = discovered === null || discovered === void 0 ? void 0 : discovered.sourceDiscovery.objects.find(object => object.from)) === null || _c === void 0 ? void 0 : _c.from) || (empty ? comments[0] : undefined)) : undefined;
321
367
  if (bounds.trimmed) {
322
368
  console.warn(`[file-viewer] Ignored pathological worksheet dimensions for ${name}: `
323
- + `${bounds.declaredRowCount}x${bounds.declaredColCount} -> ${bounds.rowCount}x${bounds.colCount}.`);
369
+ + `${bounds.declaredRowCount}x${bounds.declaredColCount} -> ${dataExtent.rows}x${dataExtent.cols}.`);
324
370
  }
325
371
  result.push({
372
+ dataExtent,
373
+ visualExtent,
374
+ visualMaterialization: getSheetMaterialization(visualExtent),
375
+ sourceDiscovery: discovered === null || discovered === void 0 ? void 0 : discovered.sourceDiscovery,
376
+ logicalExtent,
377
+ materialization,
378
+ ...(occupied ? { occupiedRegions, occupiedIndex: occupied.index } : {}),
379
+ ...(firstTarget ? { initialRegion: createSheetRegion(firstTarget, 0, logicalExtent.rows <= EXCEL_SOURCE_EXTENT.rows && logicalExtent.cols <= EXCEL_SOURCE_EXTENT.cols
380
+ ? logicalExtent : EXCEL_SOURCE_EXTENT) } : {}),
326
381
  id: result.length,
327
382
  name,
328
- hidden: !!((_a = workbookSheets[sourceIndex]) === null || _a === void 0 ? void 0 : _a.Hidden),
383
+ hidden: !!((_d = workbookSheets[sourceIndex]) === null || _d === void 0 ? void 0 : _d.Hidden),
384
+ comments: context.comments[name] || [],
329
385
  rowCount: empty ? 0 : bounds.rowCount,
330
386
  colCount: empty ? 0 : bounds.colCount,
331
387
  });
332
388
  return result;
333
389
  }, []);
334
- return [{ type: 'sheets', payload: { sheets: context.sheets } }];
390
+ return [{ type: 'sheets', payload: { sheets: context.sheets, commentsError: context.commentsError } }];
335
391
  };
336
392
  export const parseSpreadsheetWorkbook = async (context, data, source = {}) => {
337
393
  try {
338
394
  const input = prepareSpreadsheetReadInput(data, source);
339
395
  context.workbook = readWorkbookWithMergeRecovery(input);
340
- recoverUncachedFormulaValues(context.workbook);
396
+ const workbook = context.workbook;
397
+ recoverUncachedFormulaValues(workbook);
398
+ const commentResult = await parseSpreadsheetComments(data, workbook).catch(error => {
399
+ console.warn('[file-viewer] Spreadsheet comment parsing failed; continuing with notes.', error);
400
+ return { comments: readWorkbookNotes(workbook), hasError: true };
401
+ });
402
+ context.comments = commentResult.comments;
403
+ context.commentsError = commentResult.hasError;
341
404
  const signature = data.byteLength >= 2 ? new DataView(data).getUint16(0, false) : 0;
342
405
  if (signature === 0x504b) {
343
406
  const [charts, cellImages] = await Promise.all([
@@ -367,6 +430,11 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
367
430
  var _a;
368
431
  const { sheet, startRow = 0, pageSize = 500, sessionId = 0, } = payload;
369
432
  try {
433
+ if (!Number.isSafeInteger(startRow) || startRow < 0 || !Number.isSafeInteger(pageSize) || pageSize < 1) {
434
+ return [toErrorResponse(new RangeError('A spreadsheet window requires a nonnegative integer start and a positive integer size.'), {
435
+ code: 'INVALID_WINDOW', operation: 'parseSheet', sheet, sessionId, startRow,
436
+ })];
437
+ }
370
438
  const workbook = context.workbook;
371
439
  const sheetName = (_a = context.sheets.find(item => item.id === sheet)) === null || _a === void 0 ? void 0 : _a.name;
372
440
  if (!(workbook === null || workbook === void 0 ? void 0 : workbook.Sheets) || !sheetName) {
@@ -377,6 +445,34 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
377
445
  return [];
378
446
  }
379
447
  const sheetMeta = context.sheets.find(item => item.id === sheet);
448
+ const includeLayout = startRow === 0 && payload.includeLayout !== false;
449
+ const materialization = (sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.materialization) || getSheetMaterialization({
450
+ rows: (sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.rowCount) || 0, cols: (sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.colCount) || 0,
451
+ });
452
+ if (payload.requireOrdinaryGrid === true && (materialization.kind === 'region-required' || (sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.initialRegion) && !sheetMeta.rowCount)) {
453
+ return [toErrorResponse(new Error('This worksheet requires bounded source-region navigation.'), {
454
+ code: 'REGION_REQUIRED', operation: 'parseSheet', sheet, sessionId, startRow,
455
+ materialization, initialRegion: sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.initialRegion,
456
+ migration: {
457
+ operation: 'parseRegion', regionLimits: { ...REGION_LIMIT },
458
+ requiredIdentity: ['sheet', 'sessionId', 'requestId', 'region.id'],
459
+ dataWindow: { operation: 'parseSheet', payload: { sheet, sessionId, startRow,
460
+ pageSize: Math.min(pageSize, Math.max(1, Math.floor(ORDINARY_GRID_BUDGET.windowCells / Math.max(1, (sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.colCount) || 1)))),
461
+ includeLayout: false } },
462
+ },
463
+ })];
464
+ }
465
+ const rowCount = (sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.rowCount) || 0, colCount = (sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.colCount) || 0;
466
+ const effectiveStart = Math.min(startRow, Math.max(rowCount - 1, 0));
467
+ const effectiveRows = Math.min(pageSize, Math.max(0, rowCount - effectiveStart));
468
+ const requestedCells = effectiveRows * colCount;
469
+ if (requestedCells > ORDINARY_GRID_BUDGET.windowCells) {
470
+ return [toErrorResponse(new RangeError('This requested window exceeds the ordinary cell budget.'), {
471
+ code: 'WINDOW_BUDGET_EXCEEDED', operation: 'parseSheet', sheet, sessionId, startRow,
472
+ requestedRows: effectiveRows, requestedCells, maxWindowCells: ORDINARY_GRID_BUDGET.windowCells,
473
+ suggestedPageSize: Math.max(1, Math.floor(ORDINARY_GRID_BUDGET.windowCells / Math.max(1, colCount))),
474
+ })];
475
+ }
380
476
  const sheetModel = SheetJsModel.create(worksheet, {
381
477
  startRow,
382
478
  pageSize,
@@ -384,16 +480,16 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
384
480
  totalCols: sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.colCount,
385
481
  charts: context.charts[sheetName],
386
482
  cellImages: context.cellImages[sheetName],
483
+ defaultFont: readWorkbookDefaultFont(context.workbook),
387
484
  });
388
- // Keep the first response backward-compatible; later virtual windows only need rows and cells.
389
- // Avoid recalculating auto-fit column widths for every 500-row request.
390
- const windowData = sheetModel.toObject({ includeLayout: startRow === 0 });
391
- const structure = startRow === 0 ? sheetModel.structure : undefined;
485
+ const windowData = sheetModel.toObject({ includeLayout });
486
+ const structure = includeLayout ? sheetModel.structure : undefined;
392
487
  return [{
393
488
  type: 'parseSheet',
394
489
  payload: {
395
490
  sessionId,
396
491
  sheet,
492
+ materialization,
397
493
  sheetData: structure ? {
398
494
  ...windowData,
399
495
  structure,
@@ -402,7 +498,44 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
402
498
  }];
403
499
  }
404
500
  catch (error) {
405
- return [toErrorResponse(error, { sessionId, startRow })];
501
+ const layoutError = (error === null || error === void 0 ? void 0 : error.code) === 'LAYOUT_BUDGET_EXCEEDED';
502
+ return [toErrorResponse(error, { sheet, sessionId, startRow,
503
+ ...(layoutError ? { code: 'LAYOUT_BUDGET_EXCEEDED', operation: 'parseSheet',
504
+ maxLayoutEntries: error.limit,
505
+ migration: { operation: 'parseSheet', payload: { sheet, sessionId, startRow, pageSize, includeLayout: false } }, } : {}),
506
+ })];
507
+ }
508
+ };
509
+ export const parseSpreadsheetRegion = (context, payload = {}) => {
510
+ var _a, _b, _c;
511
+ const { sheet, sessionId, requestId } = payload;
512
+ try {
513
+ for (const value of [sheet, sessionId, requestId]) {
514
+ if (!Number.isSafeInteger(value) || value < 0)
515
+ throw new RangeError('Invalid region request identity');
516
+ }
517
+ const input = payload.region;
518
+ const region = { id: input === null || input === void 0 ? void 0 : input.id, startRow: input === null || input === void 0 ? void 0 : input.startRow, startCol: input === null || input === void 0 ? void 0 : input.startCol,
519
+ rowCount: input === null || input === void 0 ? void 0 : input.rowCount, colCount: input === null || input === void 0 ? void 0 : input.colCount };
520
+ assertSheetRegion(region);
521
+ const definition = context.sheets.find(item => item.id === sheet);
522
+ const worksheet = definition && ((_b = (_a = context.workbook) === null || _a === void 0 ? void 0 : _a.Sheets) === null || _b === void 0 ? void 0 : _b[definition.name]);
523
+ if (!definition || !worksheet)
524
+ throw new RangeError('Unknown source worksheet');
525
+ const model = SheetJsModel.create(worksheet, {
526
+ charts: context.charts[definition.name], cellImages: context.cellImages[definition.name],
527
+ defaultFont: readWorkbookDefaultFont(context.workbook),
528
+ });
529
+ return [{ type: 'parseRegion', payload: {
530
+ sheet, sessionId, requestId, region,
531
+ logicalExtent: definition.logicalExtent || definition.dataExtent,
532
+ regionData: model.toRegionObject(region),
533
+ comments: (context.comments[definition.name] || []).filter(comment => sourceToRegion(region, comment) !== null),
534
+ } }];
535
+ }
536
+ catch (error) {
537
+ return [toErrorResponse(error, { operation: 'parseRegion', sheet, sessionId, requestId,
538
+ regionId: Number.isSafeInteger((_c = payload.region) === null || _c === void 0 ? void 0 : _c.id) ? payload.region.id : undefined })];
406
539
  }
407
540
  };
408
541
  const escapeSearchRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -418,13 +551,17 @@ const visitWorksheetCells = (worksheet, visit) => {
418
551
  ? worksheet
419
552
  : candidate['!data'];
420
553
  if (rows) {
421
- for (const rowKey of Object.keys(rows)) {
554
+ for (const rowKey in rows) {
555
+ if (!Object.prototype.hasOwnProperty.call(rows, rowKey))
556
+ continue;
422
557
  const row = rows[Number(rowKey)];
423
558
  const rowIndex = Number(rowKey);
424
559
  if (!Number.isInteger(rowIndex) || rowIndex < 0 || !Array.isArray(row)) {
425
560
  continue;
426
561
  }
427
- for (const colKey of Object.keys(row)) {
562
+ for (const colKey in row) {
563
+ if (!Object.prototype.hasOwnProperty.call(row, colKey))
564
+ continue;
428
565
  const colIndex = Number(colKey);
429
566
  const cell = row[colIndex];
430
567
  if (!Number.isInteger(colIndex) || colIndex < 0 || !cell) {
@@ -437,7 +574,9 @@ const visitWorksheetCells = (worksheet, visit) => {
437
574
  }
438
575
  return true;
439
576
  }
440
- for (const key of Object.keys(worksheet)) {
577
+ for (const key in worksheet) {
578
+ if (!Object.prototype.hasOwnProperty.call(worksheet, key))
579
+ continue;
441
580
  if (key.startsWith('!') || !/^[A-Z]+[1-9][0-9]*$/i.test(key)) {
442
581
  continue;
443
582
  }
@@ -458,6 +597,240 @@ const visitWorksheetCells = (worksheet, visit) => {
458
597
  }
459
598
  return true;
460
599
  };
600
+ export const indexOccupiedRegions = (worksheet, budget = OCCUPIED_INDEX_BUDGET) => {
601
+ for (const value of [budget.tiles, budget.visitedCells]) {
602
+ if (!Number.isSafeInteger(value) || value < 1)
603
+ throw new RangeError('Invalid occupied index budget');
604
+ }
605
+ const limits = { tiles: Math.min(budget.tiles, OCCUPIED_INDEX_BUDGET.tiles),
606
+ visitedCells: Math.min(budget.visitedCells, OCCUPIED_INDEX_BUDGET.visitedCells) };
607
+ const tiles = new Map();
608
+ let visitedCells = 0, exceeded = false;
609
+ visitWorksheetCells(worksheet, (cell, row, col) => {
610
+ if (visitedCells >= limits.visitedCells) {
611
+ exceeded = true;
612
+ return false;
613
+ }
614
+ visitedCells++;
615
+ const meaningful = classifySpreadsheetCell(cell).value;
616
+ if (!meaningful || row < 0 || col < 0 || row >= EXCEL_SOURCE_EXTENT.rows || col >= EXCEL_SOURCE_EXTENT.cols)
617
+ return true;
618
+ const startRow = Math.floor(row / REGION_LIMIT.rows) * REGION_LIMIT.rows;
619
+ const startCol = Math.floor(col / REGION_LIMIT.cols) * REGION_LIMIT.cols;
620
+ const key = `${startRow}:${startCol}`, prior = tiles.get(key);
621
+ if (prior)
622
+ prior.cellCount++;
623
+ else {
624
+ if (tiles.size >= limits.tiles) {
625
+ exceeded = true;
626
+ return false;
627
+ }
628
+ tiles.set(key, { firstCell: { row, col }, cellCount: 1, region: {
629
+ id: 0, startRow, startCol,
630
+ rowCount: Math.min(REGION_LIMIT.rows, EXCEL_SOURCE_EXTENT.rows - startRow),
631
+ colCount: Math.min(REGION_LIMIT.cols, EXCEL_SOURCE_EXTENT.cols - startCol),
632
+ } });
633
+ }
634
+ return true;
635
+ });
636
+ return {
637
+ regions: [...tiles.values()].sort((a, b) => a.region.startRow - b.region.startRow || a.region.startCol - b.region.startCol),
638
+ index: { coverage: 'value-formula-link-rich-text-cells-only', status: exceeded ? 'budget-exceeded' : 'complete',
639
+ visitedCells, indexedTiles: tiles.size, limits },
640
+ };
641
+ };
642
+ export const discoverSpreadsheetSource = (worksheet, sources = {}, budget = {}) => {
643
+ var _a, _b, _c;
644
+ const defaults = { ...OCCUPIED_INDEX_BUDGET, objects: 4096, metadata: 8192, diagnostics: 32 };
645
+ const limits = { ...defaults };
646
+ for (const key of Object.keys(defaults)) {
647
+ const value = (_a = budget[key]) !== null && _a !== void 0 ? _a : defaults[key];
648
+ if (!Number.isSafeInteger(value) || value < 1)
649
+ throw new RangeError('Invalid source discovery budget');
650
+ limits[key] = Math.min(value, defaults[key]);
651
+ }
652
+ const sourceDiscovery = {
653
+ scope: 'parsed-cells-and-source-object-anchors', status: 'complete',
654
+ extentSemantics: 'source-cells-and-anchor-endpoints',
655
+ coverage: { values: 'complete', styles: 'complete', merges: 'complete', images: 'complete',
656
+ charts: 'complete', cellImages: 'complete', axisStyles: 'complete', tableStyles: 'complete', conditionalFormats: 'complete', otherDrawings: 'complete' },
657
+ cellRegions: [], objects: [], visitedCells: 0, visitedMetadata: 0, limits,
658
+ diagnostics: [], diagnosticsTruncated: false,
659
+ };
660
+ const extent = { rows: 0, cols: 0 };
661
+ const tiles = new Map();
662
+ const diagnostic = (code, kind, point, unsupported = false) => {
663
+ sourceDiscovery.status = 'partial';
664
+ sourceDiscovery.coverage[kind] = unsupported ? 'unsupported' : 'partial';
665
+ if (sourceDiscovery.diagnostics.length < limits.diagnostics)
666
+ sourceDiscovery.diagnostics.push({ code, kind, ...point });
667
+ else
668
+ sourceDiscovery.diagnosticsTruncated = true;
669
+ };
670
+ const point = (value) => {
671
+ var _a, _b;
672
+ const row = (_a = value === null || value === void 0 ? void 0 : value.row) !== null && _a !== void 0 ? _a : value === null || value === void 0 ? void 0 : value.r, col = (_b = value === null || value === void 0 ? void 0 : value.col) !== null && _b !== void 0 ? _b : value === null || value === void 0 ? void 0 : value.c;
673
+ return Number.isSafeInteger(row) && Number.isSafeInteger(col) && row >= 0 && col >= 0
674
+ && row < EXCEL_SOURCE_EXTENT.rows && col < EXCEL_SOURCE_EXTENT.cols ? { row, col } : undefined;
675
+ };
676
+ const observe = (value) => {
677
+ extent.rows = Math.max(extent.rows, value.row + 1);
678
+ extent.cols = Math.max(extent.cols, value.col + 1);
679
+ };
680
+ visitWorksheetCells(worksheet, (cell, row, col) => {
681
+ if (sourceDiscovery.visitedCells >= limits.visitedCells) {
682
+ diagnostic('CELL_VISIT_BUDGET', 'values');
683
+ diagnostic('CELL_VISIT_BUDGET', 'styles');
684
+ return false;
685
+ }
686
+ sourceDiscovery.visitedCells++;
687
+ const content = classifySpreadsheetCell(cell, sources.defaultFont);
688
+ if (!content.visual)
689
+ return true;
690
+ const location = point({ row, col });
691
+ if (!location) {
692
+ diagnostic('INVALID_CELL_ADDRESS', content.value ? 'values' : 'styles');
693
+ return true;
694
+ }
695
+ observe(location);
696
+ if (content.style === 'unknown')
697
+ diagnostic('UNKNOWN_STYLE_PRESERVED', 'styles', location);
698
+ const startRow = Math.floor(row / REGION_LIMIT.rows) * REGION_LIMIT.rows;
699
+ const startCol = Math.floor(col / REGION_LIMIT.cols) * REGION_LIMIT.cols;
700
+ const key = `${startRow}:${startCol}`, prior = tiles.get(key);
701
+ if (prior)
702
+ prior.cellCount++;
703
+ else {
704
+ if (tiles.size >= limits.tiles) {
705
+ diagnostic('CELL_TILE_BUDGET', 'values');
706
+ diagnostic('CELL_TILE_BUDGET', 'styles');
707
+ return false;
708
+ }
709
+ tiles.set(key, { firstCell: location, cellCount: 1, region: { id: 0, startRow, startCol,
710
+ rowCount: Math.min(REGION_LIMIT.rows, EXCEL_SOURCE_EXTENT.rows - startRow),
711
+ colCount: Math.min(REGION_LIMIT.cols, EXCEL_SOURCE_EXTENT.cols - startCol) } });
712
+ }
713
+ return true;
714
+ });
715
+ sourceDiscovery.cellRegions = [...tiles.values()].sort((a, b) => a.region.startRow - b.region.startRow || a.region.startCol - b.region.startCol);
716
+ const visitMetadata = (collection, kind, visit) => {
717
+ if (collection == null)
718
+ return;
719
+ if (typeof collection !== 'object') {
720
+ diagnostic('UNRECOGNIZED_METADATA', kind);
721
+ return;
722
+ }
723
+ for (const key in collection) {
724
+ if (!Object.prototype.hasOwnProperty.call(collection, key))
725
+ continue;
726
+ if (sourceDiscovery.visitedMetadata >= limits.metadata) {
727
+ diagnostic('METADATA_VISIT_BUDGET', kind);
728
+ break;
729
+ }
730
+ sourceDiscovery.visitedMetadata++;
731
+ const index = Number(key);
732
+ if (!Number.isSafeInteger(index) || index < 0) {
733
+ diagnostic('UNRECOGNIZED_METADATA_KEY', kind);
734
+ continue;
735
+ }
736
+ visit(collection[key], index);
737
+ }
738
+ };
739
+ const appendObject = (entry, kind) => {
740
+ if (entry.from)
741
+ observe(entry.from);
742
+ if (entry.to)
743
+ observe(entry.to);
744
+ if (sourceDiscovery.objects.length >= limits.objects) {
745
+ diagnostic('SOURCE_OBJECT_BUDGET', kind);
746
+ return;
747
+ }
748
+ sourceDiscovery.objects.push(entry);
749
+ if (entry.coordinateSpace !== 'cell')
750
+ diagnostic(entry.coordinateSpace === 'absolute' ? 'ABSOLUTE_OBJECT_NEEDS_PIXEL_NAVIGATION' : 'UNKNOWN_OBJECT_ANCHOR', kind);
751
+ };
752
+ const raw = worksheet;
753
+ visitMetadata(raw['!merges'], 'merges', (merge, index) => {
754
+ const from = point(merge === null || merge === void 0 ? void 0 : merge.s), to = point(merge === null || merge === void 0 ? void 0 : merge.e);
755
+ if (!from || !to || to.row < from.row || to.col < from.col)
756
+ diagnostic('INVALID_MERGE_RANGE', 'merges');
757
+ appendObject({ kind: 'merge', sourceIndex: index, coordinateSpace: from && to ? 'cell' : 'unknown', from, to }, 'merges');
758
+ });
759
+ const drawingMetadata = raw['!drawings'];
760
+ if ((drawingMetadata === null || drawingMetadata === void 0 ? void 0 : drawingMetadata.shapes) && (!Array.isArray(drawingMetadata.shapes) || drawingMetadata.shapes.length > 0)) {
761
+ diagnostic('DRAWING_SHAPES_NOT_INDEXED', 'otherDrawings', undefined, true);
762
+ }
763
+ if ((drawingMetadata === null || drawingMetadata === void 0 ? void 0 : drawingMetadata.charts) != null && (!Array.isArray(drawingMetadata.charts) || drawingMetadata.charts.length > (((_b = sources.charts) === null || _b === void 0 ? void 0 : _b.length) || 0))) {
764
+ diagnostic('UNRESOLVED_CHART_SOURCE', 'charts');
765
+ }
766
+ for (const key in drawingMetadata) {
767
+ if (!Object.prototype.hasOwnProperty.call(drawingMetadata, key))
768
+ continue;
769
+ if (!['images', 'charts', 'shapes', 'raw', 'chart'].includes(key)) {
770
+ diagnostic('UNKNOWN_DRAWING_CLASS', 'otherDrawings', undefined, true);
771
+ break;
772
+ }
773
+ }
774
+ const imageAudit = readImageSourceProvenance(drawingMetadata === null || drawingMetadata === void 0 ? void 0 : drawingMetadata.raw, Array.isArray(drawingMetadata === null || drawingMetadata === void 0 ? void 0 : drawingMetadata.images) ? drawingMetadata.images : [], drawingMetadata != null || raw['!drawel'] != null);
775
+ const imageSources = imageAudit.anchors;
776
+ sourceDiscovery.imageSource = imageAudit.summary;
777
+ if (imageAudit.summary.status === 'partial') {
778
+ for (const reason of imageAudit.summary.reasons)
779
+ diagnostic('RAW_IMAGE_SOURCE:' + reason, 'images');
780
+ if (imageAudit.summary.reasonsTruncated)
781
+ sourceDiscovery.diagnosticsTruncated = true;
782
+ }
783
+ visitMetadata((_c = raw['!drawings']) === null || _c === void 0 ? void 0 : _c.images, 'images', (image, index) => {
784
+ const anchor = imageSources.get(image) || unknownSourceAnchor('unavailable-source-provenance'), anchorType = typeof (anchor === null || anchor === void 0 ? void 0 : anchor.type) === 'string' ? anchor.type : undefined;
785
+ const absolute = anchorType === 'absoluteAnchor' || (anchor === null || anchor === void 0 ? void 0 : anchor.editAs) === 'absolute';
786
+ const from = point(anchor === null || anchor === void 0 ? void 0 : anchor.from), to = point(anchor === null || anchor === void 0 ? void 0 : anchor.to);
787
+ const knownMode = ['oneCellAnchor', 'twoCellAnchor', 'absoluteAnchor'].includes(anchorType || '');
788
+ const validEdit = (anchor === null || anchor === void 0 ? void 0 : anchor.editAs) == null || ['absolute', 'oneCell', 'twoCell'].includes(anchor.editAs);
789
+ const ordered = !!from && !!to && to.row >= from.row && to.col >= from.col;
790
+ const valid = anchor.status === 'valid' && knownMode && validEdit && !!from
791
+ && (anchorType !== 'twoCellAnchor' || ordered) && ((anchor === null || anchor === void 0 ? void 0 : anchor.to) == null || ordered);
792
+ if (anchor.status !== 'valid')
793
+ diagnostic('UNVERIFIED_SOURCE_ANCHOR:' + (anchor.reason || 'unknown'), 'images');
794
+ if (!knownMode || !validEdit)
795
+ diagnostic('UNKNOWN_ANCHOR_MODE', 'images');
796
+ else if (!absolute && !valid)
797
+ diagnostic('INVALID_ANCHOR_ENDPOINTS', 'images');
798
+ appendObject({ kind: 'image', sourceIndex: index, id: typeof (image === null || image === void 0 ? void 0 : image.id) === 'string' ? image.id : undefined,
799
+ coordinateSpace: absolute ? 'absolute' : valid ? 'cell' : 'unknown', sourceAnchor: anchor, from, to, anchorType,
800
+ editAs: typeof (anchor === null || anchor === void 0 ? void 0 : anchor.editAs) === 'string' ? anchor.editAs : undefined }, 'images');
801
+ });
802
+ visitMetadata(sources.charts, 'charts', (chart, index) => {
803
+ const anchor = (chart === null || chart === void 0 ? void 0 : chart.sourceAnchor) || unknownSourceAnchor('missing-chart-source-provenance');
804
+ const from = point(anchor.from), to = point(anchor.to);
805
+ const absolute = anchor.type === 'absoluteAnchor' || anchor.editAs === 'absolute';
806
+ const valid = anchor.status === 'valid';
807
+ if (!valid)
808
+ diagnostic('UNVERIFIED_SOURCE_ANCHOR:' + (anchor.reason || 'unknown'), 'charts');
809
+ appendObject({ kind: 'chart', sourceIndex: index, id: typeof (chart === null || chart === void 0 ? void 0 : chart.id) === 'string' ? chart.id : undefined,
810
+ coordinateSpace: absolute ? 'absolute' : valid ? 'cell' : 'unknown', sourceAnchor: anchor, from, to,
811
+ anchorType: anchor.type, editAs: anchor.editAs }, 'charts');
812
+ });
813
+ visitMetadata(sources.cellImages, 'cellImages', (image, index) => {
814
+ const from = point(image);
815
+ appendObject({ kind: 'cellImage', sourceIndex: index, id: typeof (image === null || image === void 0 ? void 0 : image.id) === 'string' ? image.id : undefined,
816
+ coordinateSpace: from ? 'cell' : 'unknown', from }, 'cellImages');
817
+ });
818
+ for (const axis of ['!rows', '!cols'])
819
+ visitMetadata(raw[axis], 'axisStyles', (entry, index) => {
820
+ var _a;
821
+ if ((entry === null || entry === void 0 ? void 0 : entry.s) != null || (entry === null || entry === void 0 ? void 0 : entry.style) != null) {
822
+ const classification = classifySpreadsheetCell({ s: (_a = entry.s) !== null && _a !== void 0 ? _a : entry.style });
823
+ if (classification.style !== 'default')
824
+ diagnostic('AXIS_STYLE_NOT_INDEXED', 'axisStyles', undefined, true);
825
+ }
826
+ });
827
+ for (const [key, kind] of [['!tables', 'tableStyles'], ['!conditionalFormatting', 'conditionalFormats'], ['!conditionalFormats', 'conditionalFormats']]) {
828
+ const value = raw[key];
829
+ if (value != null && (Array.isArray(value) ? value.length > 0 : true))
830
+ diagnostic('VISUAL_CLASS_NOT_INDEXED', kind, undefined, true);
831
+ }
832
+ return { extent, sourceDiscovery };
833
+ };
461
834
  export const searchSpreadsheetWorkbook = (context, query, options = {}) => {
462
835
  var _a;
463
836
  const normalizedQuery = query.replace(/\s+/g, ' ').trim();
@@ -513,6 +886,8 @@ export const handleSpreadsheetWorkerRequest = (context, request) => {
513
886
  });
514
887
  case 'parseSheet':
515
888
  return parseSpreadsheetSheet(context, request.payload);
889
+ case 'parseRegion':
890
+ return parseSpreadsheetRegion(context, request.payload);
516
891
  case 'searchWorkbook':
517
892
  return [{
518
893
  type: 'searchWorkbook',