@file-viewer/renderer-spreadsheet 3.3.3 → 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 (41) 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/comments.d.ts +40 -0
  7. package/dist/spreadsheet/comments.js +388 -0
  8. package/dist/spreadsheet/drawingAutoHeight.d.ts +7 -0
  9. package/dist/spreadsheet/drawingAutoHeight.js +51 -0
  10. package/dist/spreadsheet/sourceRegion.d.ts +37 -0
  11. package/dist/spreadsheet/sourceRegion.js +54 -0
  12. package/dist/spreadsheet/state.d.ts +7 -1
  13. package/dist/spreadsheet/state.js +6 -0
  14. package/dist/spreadsheet/view.d.ts +9 -4
  15. package/dist/spreadsheet/view.js +98 -27
  16. package/dist/spreadsheet/worker/sheetjs/SheetJsModel.d.ts +61 -2
  17. package/dist/spreadsheet/worker/sheetjs/SheetJsModel.js +134 -28
  18. package/dist/spreadsheet/worker/sheetjs/chartParser.d.ts +3 -2
  19. package/dist/spreadsheet/worker/sheetjs/chartParser.js +13 -5
  20. package/dist/spreadsheet/worker/sheetjs/commentParser.d.ts +7 -0
  21. package/dist/spreadsheet/worker/sheetjs/commentParser.js +232 -0
  22. package/dist/spreadsheet/worker/sheetjs/drawingRowAnchor.d.ts +4 -0
  23. package/dist/spreadsheet/worker/sheetjs/drawingRowAnchor.js +90 -0
  24. package/dist/spreadsheet/worker/sheetjs/parser.d.ts +40 -3
  25. package/dist/spreadsheet/worker/sheetjs/parser.js +452 -54
  26. package/dist/spreadsheet/worker/sheetjs/richDataParser.js +5 -2
  27. package/dist/spreadsheet/worker/sheetjs/rowSizing.d.ts +10 -0
  28. package/dist/spreadsheet/worker/sheetjs/rowSizing.js +156 -0
  29. package/dist/spreadsheet/worker/sheetjs/sheetLayout.d.ts +2 -0
  30. package/dist/spreadsheet/worker/sheetjs/sourceAnchor.d.ts +10 -0
  31. package/dist/spreadsheet/worker/sheetjs/sourceAnchor.js +286 -0
  32. package/dist/spreadsheet/worker/sheetjs/textEncoding.d.ts +1 -1
  33. package/dist/spreadsheet/worker/sheetjs/textEncoding.js +1 -1
  34. package/dist/spreadsheet/worker/sheetjs/workbookFont.d.ts +4 -0
  35. package/dist/spreadsheet/worker/sheetjs/workbookFont.js +15 -0
  36. package/dist/spreadsheet/worker/sheetjs/xmlBudget.d.ts +11 -0
  37. package/dist/spreadsheet/worker/sheetjs/xmlBudget.js +39 -0
  38. package/dist/spreadsheet/worker/type.d.ts +145 -0
  39. package/dist/spreadsheet.js +150 -39
  40. package/dist/worker/sheet.worker.js +49 -65
  41. package/package.json +22 -2
@@ -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,
@@ -99,6 +103,8 @@ export const createSpreadsheetParserContext = () => ({
99
103
  sheets: [],
100
104
  charts: {},
101
105
  cellImages: {},
106
+ comments: {},
107
+ commentsError: false,
102
108
  });
103
109
  const toErrorResponse = (error, payload = {}) => ({
104
110
  type: 'parseError',
@@ -107,42 +113,34 @@ const toErrorResponse = (error, payload = {}) => ({
107
113
  message: error instanceof Error ? error.message : String(error),
108
114
  },
109
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;
110
119
  const getDrawingBounds = (worksheet) => {
111
- var _a;
112
- const images = ((_a = worksheet === null || worksheet === void 0 ? void 0 : worksheet['!drawings']) === null || _a === void 0 ? void 0 : _a.images) || [];
113
- return images.reduce((bounds, image) => {
114
- var _a, _b, _c, _d, _e, _f;
115
- const anchor = image.anchor;
116
- 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);
117
- 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);
118
- return {
119
- rowCount: Number.isFinite(row) ? Math.max(bounds.rowCount, row + 1) : bounds.rowCount,
120
- colCount: Number.isFinite(col) ? Math.max(bounds.colCount, col + 1) : bounds.colCount,
121
- };
122
- }, {
123
- rowCount: 0,
124
- colCount: 0,
125
- });
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;
126
130
  };
127
131
  const getChartBounds = (charts) => {
128
- return (charts || []).reduce((bounds, chart) => {
129
- var _a, _b, _c, _d, _e, _f;
130
- const estimatedRows = ((_a = chart.ext) === null || _a === void 0 ? void 0 : _a.height)
131
- ? Math.ceil(chart.ext.height / 9525 / 20)
132
- : 0;
133
- const estimatedCols = ((_b = chart.ext) === null || _b === void 0 ? void 0 : _b.width)
134
- ? Math.ceil(chart.ext.width / 9525 / 64)
135
- : 0;
136
- const row = (_d = (_c = chart.to) === null || _c === void 0 ? void 0 : _c.row) !== null && _d !== void 0 ? _d : chart.from.row + estimatedRows;
137
- const col = (_f = (_e = chart.to) === null || _e === void 0 ? void 0 : _e.col) !== null && _f !== void 0 ? _f : chart.from.col + estimatedCols;
138
- return {
139
- rowCount: Math.max(bounds.rowCount, row + 1),
140
- colCount: Math.max(bounds.colCount, col + 1),
141
- };
142
- }, {
143
- rowCount: 0,
144
- colCount: 0,
145
- });
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;
146
144
  };
147
145
  const EMPTY_RANGE_ROW_LIMIT = 1000;
148
146
  const EMPTY_RANGE_COLUMN_LIMIT = 256;
@@ -172,7 +170,61 @@ const compactSparseExtent = (indices, slack, gapMultiplier, contentExtent) => {
172
170
  }
173
171
  return end + 1;
174
172
  };
175
- 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) => {
176
228
  const bounds = { rowCount: 0, colCount: 0 };
177
229
  if (!worksheet)
178
230
  return bounds;
@@ -181,12 +233,13 @@ const getCellBounds = (worksheet) => {
181
233
  let contentRows = 0;
182
234
  let contentCols = 0;
183
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;
184
241
  rowIndices.push(row);
185
242
  colIndices.push(col);
186
- const cell = value;
187
- const meaningful = typeof value !== 'object' || cell.v != null || cell.f != null
188
- || cell.F != null || !!cell.w || !!cell.r || !!cell.h || !!cell.l
189
- || (Array.isArray(cell.c) && cell.c.length > 0);
190
243
  if (meaningful) {
191
244
  contentRows = Math.max(contentRows, row + 1);
192
245
  contentCols = Math.max(contentCols, col + 1);
@@ -245,7 +298,7 @@ const reconcileDeclaredRange = (declaredCount, observedCount, slack, emptyLimit)
245
298
  ? Math.max(declaredCount, observedCount)
246
299
  : observedCount;
247
300
  };
248
- export const getWorksheetDisplayBounds = (worksheet, charts) => {
301
+ export const getWorksheetDisplayBounds = (worksheet, charts, _comments = [], options = {}) => {
249
302
  let declaredRowCount = 0;
250
303
  let declaredColCount = 0;
251
304
  const ref = worksheet === null || worksheet === void 0 ? void 0 : worksheet['!ref'];
@@ -258,7 +311,7 @@ export const getWorksheetDisplayBounds = (worksheet, charts) => {
258
311
  catch {
259
312
  }
260
313
  }
261
- const cellBounds = getCellBounds(worksheet);
314
+ const cellBounds = getCellBounds(worksheet, options.defaultFont);
262
315
  const mergeBounds = getMergeBounds(worksheet);
263
316
  const drawingBounds = getDrawingBounds(worksheet);
264
317
  const chartBounds = getChartBounds(charts);
@@ -290,33 +343,64 @@ const parseSheets = (context, includeEmptySheets = false) => {
290
343
  }
291
344
  const workbookSheets = ((_a = workbook.Workbook) === null || _a === void 0 ? void 0 : _a.Sheets) || [];
292
345
  context.sheets = workbook.SheetNames.reduce((result, name, sourceIndex) => {
293
- var _a;
346
+ var _a, _b, _c, _d;
294
347
  const worksheet = workbook.Sheets[name];
295
- const bounds = getWorksheetDisplayBounds(worksheet, context.charts[name]);
296
- const empty = !(worksheet === null || worksheet === void 0 ? void 0 : worksheet['!ref']) && !bounds.observedRowCount && !bounds.observedColCount;
297
- 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)) {
298
354
  return result;
299
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;
300
367
  if (bounds.trimmed) {
301
368
  console.warn(`[file-viewer] Ignored pathological worksheet dimensions for ${name}: `
302
- + `${bounds.declaredRowCount}x${bounds.declaredColCount} -> ${bounds.rowCount}x${bounds.colCount}.`);
369
+ + `${bounds.declaredRowCount}x${bounds.declaredColCount} -> ${dataExtent.rows}x${dataExtent.cols}.`);
303
370
  }
304
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) } : {}),
305
381
  id: result.length,
306
382
  name,
307
- 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] || [],
308
385
  rowCount: empty ? 0 : bounds.rowCount,
309
386
  colCount: empty ? 0 : bounds.colCount,
310
387
  });
311
388
  return result;
312
389
  }, []);
313
- return [{ type: 'sheets', payload: { sheets: context.sheets } }];
390
+ return [{ type: 'sheets', payload: { sheets: context.sheets, commentsError: context.commentsError } }];
314
391
  };
315
392
  export const parseSpreadsheetWorkbook = async (context, data, source = {}) => {
316
393
  try {
317
394
  const input = prepareSpreadsheetReadInput(data, source);
318
395
  context.workbook = readWorkbookWithMergeRecovery(input);
319
- 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;
320
404
  const signature = data.byteLength >= 2 ? new DataView(data).getUint16(0, false) : 0;
321
405
  if (signature === 0x504b) {
322
406
  const [charts, cellImages] = await Promise.all([
@@ -346,6 +430,11 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
346
430
  var _a;
347
431
  const { sheet, startRow = 0, pageSize = 500, sessionId = 0, } = payload;
348
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
+ }
349
438
  const workbook = context.workbook;
350
439
  const sheetName = (_a = context.sheets.find(item => item.id === sheet)) === null || _a === void 0 ? void 0 : _a.name;
351
440
  if (!(workbook === null || workbook === void 0 ? void 0 : workbook.Sheets) || !sheetName) {
@@ -356,6 +445,34 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
356
445
  return [];
357
446
  }
358
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
+ }
359
476
  const sheetModel = SheetJsModel.create(worksheet, {
360
477
  startRow,
361
478
  pageSize,
@@ -363,14 +480,16 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
363
480
  totalCols: sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.colCount,
364
481
  charts: context.charts[sheetName],
365
482
  cellImages: context.cellImages[sheetName],
483
+ defaultFont: readWorkbookDefaultFont(context.workbook),
366
484
  });
367
- const windowData = sheetModel.toObject({ includeLayout: startRow === 0 });
368
- const structure = startRow === 0 ? sheetModel.structure : undefined;
485
+ const windowData = sheetModel.toObject({ includeLayout });
486
+ const structure = includeLayout ? sheetModel.structure : undefined;
369
487
  return [{
370
488
  type: 'parseSheet',
371
489
  payload: {
372
490
  sessionId,
373
491
  sheet,
492
+ materialization,
374
493
  sheetData: structure ? {
375
494
  ...windowData,
376
495
  structure,
@@ -379,7 +498,44 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
379
498
  }];
380
499
  }
381
500
  catch (error) {
382
- 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 })];
383
539
  }
384
540
  };
385
541
  const escapeSearchRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -395,13 +551,17 @@ const visitWorksheetCells = (worksheet, visit) => {
395
551
  ? worksheet
396
552
  : candidate['!data'];
397
553
  if (rows) {
398
- for (const rowKey of Object.keys(rows)) {
554
+ for (const rowKey in rows) {
555
+ if (!Object.prototype.hasOwnProperty.call(rows, rowKey))
556
+ continue;
399
557
  const row = rows[Number(rowKey)];
400
558
  const rowIndex = Number(rowKey);
401
559
  if (!Number.isInteger(rowIndex) || rowIndex < 0 || !Array.isArray(row)) {
402
560
  continue;
403
561
  }
404
- for (const colKey of Object.keys(row)) {
562
+ for (const colKey in row) {
563
+ if (!Object.prototype.hasOwnProperty.call(row, colKey))
564
+ continue;
405
565
  const colIndex = Number(colKey);
406
566
  const cell = row[colIndex];
407
567
  if (!Number.isInteger(colIndex) || colIndex < 0 || !cell) {
@@ -414,7 +574,9 @@ const visitWorksheetCells = (worksheet, visit) => {
414
574
  }
415
575
  return true;
416
576
  }
417
- for (const key of Object.keys(worksheet)) {
577
+ for (const key in worksheet) {
578
+ if (!Object.prototype.hasOwnProperty.call(worksheet, key))
579
+ continue;
418
580
  if (key.startsWith('!') || !/^[A-Z]+[1-9][0-9]*$/i.test(key)) {
419
581
  continue;
420
582
  }
@@ -435,6 +597,240 @@ const visitWorksheetCells = (worksheet, visit) => {
435
597
  }
436
598
  return true;
437
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
+ };
438
834
  export const searchSpreadsheetWorkbook = (context, query, options = {}) => {
439
835
  var _a;
440
836
  const normalizedQuery = query.replace(/\s+/g, ' ').trim();
@@ -490,6 +886,8 @@ export const handleSpreadsheetWorkerRequest = (context, request) => {
490
886
  });
491
887
  case 'parseSheet':
492
888
  return parseSpreadsheetSheet(context, request.payload);
889
+ case 'parseRegion':
890
+ return parseSpreadsheetRegion(context, request.payload);
493
891
  case 'searchWorkbook':
494
892
  return [{
495
893
  type: 'searchWorkbook',