diff --git a/src/core/xlsx/drawings.ts b/src/core/xlsx/drawings.ts index 7a11e22..0397d3c 100644 --- a/src/core/xlsx/drawings.ts +++ b/src/core/xlsx/drawings.ts @@ -7,7 +7,8 @@ * frame does not hold. */ import { isWebImage, type OpcPackage } from '../opc' -import { desc, descAll, kid, num, textOf, type XEl } from '../xml' +import { desc, descAll, kid, textOf, type XEl } from '../xml' +import { MAX_COL, MAX_ROWS, MAX_SHEET_WIDTH_PX, MAX_SHEET_HEIGHT_PX, ooxmlInt } from './limits' /** A cell corner: 0-based column and row, and the offset into that cell in CSS pixels */ export interface DrawingCorner { @@ -49,15 +50,39 @@ const attr = (el: XEl | undefined, local: string) => { return undefined } -const corner = (el: XEl | undefined): DrawingCorner | undefined => - el - ? { - c: num(textOf(kid(el, 'col')), 0)!, - r: num(textOf(kid(el, 'row')), 0)!, - dx: num(textOf(kid(el, 'colOff')), 0)! / EMU_PER_PX, - dy: num(textOf(kid(el, 'rowOff')), 0)! / EMU_PER_PX, - } - : undefined +function emu(value: string | undefined, maxPx: number, signed = false): number | undefined { + const n = ooxmlInt(value, signed ? -maxPx * EMU_PER_PX : 0, maxPx * EMU_PER_PX) + return n === undefined ? undefined : n / EMU_PER_PX +} + +function corner(el: XEl | undefined): DrawingCorner | undefined { + if (!el) return undefined + const c = ooxmlInt(textOf(kid(el, 'col')), 0, MAX_COL - 1) + const r = ooxmlInt(textOf(kid(el, 'row')), 0, MAX_ROWS - 1) + const dx = emu(textOf(kid(el, 'colOff')), MAX_SHEET_WIDTH_PX, true) + const dy = emu(textOf(kid(el, 'rowOff')), MAX_SHEET_HEIGHT_PX, true) + if (c === undefined || r === undefined || dx === undefined || dy === undefined) return undefined + return { c, r, dx, dy } +} + +/** Reject an invalid anchor as a whole; do not move corrupt drawings to the sheet's last cell. */ +function placement(anchor: XEl): Pick | undefined { + const from = corner(kid(anchor, 'from')) + if (anchor.n === 'twoCellAnchor') { + const to = corner(kid(anchor, 'to')) + return from && to ? { from, to } : undefined + } + const ext = kid(anchor, 'ext') + const w = emu(ext?.a.cx, MAX_SHEET_WIDTH_PX) + const h = emu(ext?.a.cy, MAX_SHEET_HEIGHT_PX) + if (w === undefined || h === undefined) return undefined + const size = { w, h } + if (anchor.n === 'oneCellAnchor') return from ? { from, size } : undefined + const pos = kid(anchor, 'pos') + const x = emu(pos?.a.x, MAX_SHEET_WIDTH_PX, true) + const y = emu(pos?.a.y, MAX_SHEET_HEIGHT_PX, true) + return x !== undefined && y !== undefined ? { at: { x, y }, size } : undefined +} /** a chart's kind and title, from its chart part */ async function chartOf(pkg: OpcPackage, part: string): Promise<{ chart: string; title: string }> { @@ -81,14 +106,8 @@ export async function readSheetDrawings(pkg: OpcPackage, sheetPath: string): Pro const rels = await pkg.rels(rel.target) for (const anchor of root?.c ?? []) { if (anchor.n !== 'twoCellAnchor' && anchor.n !== 'oneCellAnchor' && anchor.n !== 'absoluteAnchor') continue - const ext = kid(anchor, 'ext') - const pos = kid(anchor, 'pos') - const place = { - from: corner(kid(anchor, 'from')), - to: corner(kid(anchor, 'to')), - at: pos ? { x: num(pos.a.x, 0)! / EMU_PER_PX, y: num(pos.a.y, 0)! / EMU_PER_PX } : undefined, - size: ext ? { w: num(ext.a.cx, 0)! / EMU_PER_PX, h: num(ext.a.cy, 0)! / EMU_PER_PX } : undefined, - } + const place = placement(anchor) + if (!place) continue const chartRef = desc(anchor, 'chart') const blip = desc(anchor, 'blip') if (chartRef) { diff --git a/src/core/xlsx/limits.ts b/src/core/xlsx/limits.ts new file mode 100644 index 0000000..67e474c --- /dev/null +++ b/src/core/xlsx/limits.ts @@ -0,0 +1,20 @@ +/** OOXML worksheet limits. Imported CSV row counts and the generic view axes may exceed these. */ +export const MAX_COL = 16_384 +export const MAX_ROWS = 1_048_576 +export const MAX_ROW_HEIGHT_PT = 409.5 +export const MAX_COL_WIDTH = 255 + +/** Conservative drawing geometry budget: a whole worksheet at its largest cell sizes, in CSS px. */ +export const MAX_SHEET_WIDTH_PX = MAX_COL * (MAX_COL_WIDTH * 7 + 8) +export const MAX_SHEET_HEIGHT_PX = MAX_ROWS * MAX_ROW_HEIGHT_PT * (4 / 3) + +export function ooxmlNumber(value: string | undefined, min: number, max: number): number | undefined { + if (value === undefined || !value.trim()) return undefined + const n = Number(value) + return Number.isFinite(n) && n >= min && n <= max ? n : undefined +} + +export function ooxmlInt(value: string | undefined, min: number, max: number): number | undefined { + const n = ooxmlNumber(value, min, max) + return Number.isSafeInteger(n) ? n : undefined +} diff --git a/src/core/xlsx/workbook.ts b/src/core/xlsx/workbook.ts index ecf7592..4fc90a6 100644 --- a/src/core/xlsx/workbook.ts +++ b/src/core/xlsx/workbook.ts @@ -4,9 +4,10 @@ import type { LoadReport, RowPages, SheetLoader } from './import' import { toCsv } from '../convert' import { parseTheme, type Theme } from '../theme' import { Calc } from './calc' -import { kid, kids, num, parseXmlStream, type Attrs, type SaxHandler } from '../xml' +import { kid, kids, parseXmlStream, type Attrs, type SaxHandler } from '../xml' import { formatValue, formatText } from './numfmt' import { parseSheetStyles, type SheetStyles } from './styles' +import { MAX_COL, MAX_ROWS, MAX_COL_WIDTH, MAX_ROW_HEIGHT_PT, ooxmlInt, ooxmlNumber } from './limits' import type { BlockOut, CellDetail, CellOut, ColInfo, FindMatch, FindOptions, Merge, RowOut, SheetInfo, SheetProgress, WorkbookMeta } from './types' export const T_NUM = 0 @@ -17,9 +18,7 @@ export const T_ERR = 4 export const T_DATE = 5 export const T_EMPTY = 6 -export const MAX_COL = 16384 -/** rows a worksheet holds (Excel's limit): a sheet with more cannot be saved as a workbook */ -export const MAX_ROWS = 1_048_576 +export { MAX_COL, MAX_ROWS } from './limits' const decodeX = (s: string) => (s.indexOf('_x') >= 0 ? s.replace(/_x([0-9A-Fa-f]{4})_/g, (_, h: string) => String.fromCharCode(parseInt(h, 16))) : s) @@ -58,6 +57,13 @@ export function parseRange(ref: string): Merge | undefined { return { r0, c0, r1, c1 } } +/** Validate file coordinates here, without restricting parseRef/parseRange used by CSV and editing. */ +function worksheetRef(ref: string): [number, number] | undefined { + if (!/^\$?[A-Z]{1,3}\$?[1-9][0-9]{0,6}$/.test(ref)) return undefined + const [r, c] = parseRef(ref.replace(/\$/g, '')) + return r < MAX_ROWS && c < MAX_COL ? [r, c] : undefined +} + export class SheetData { /** shared formula groups: si → master cell key + formula text */ shared = new Map() @@ -121,8 +127,11 @@ class SheetHandler implements SaxHandler { open(name: string, a: Attrs): boolean | void { switch (name) { case 'c': { + if (!this.rowCells) return true const r = a.r - this.col = r ? parseRef(r)[1] : this.col + 1 + const ref = r === undefined ? [this.row, this.col + 1] : worksheetRef(r) + if (!ref || ref[0] !== this.row || ref[1] >= MAX_COL) return true + this.col = ref[1] this.cType = a.t ?? '' this.cStyle = a.s ? Number(a.s) : 0 this.val = '' @@ -149,40 +158,49 @@ class SheetHandler implements SaxHandler { return true case 'row': { this.headerReady = true - this.row = a.r ? Number(a.r) - 1 : this.row + 1 + const row = a.r === undefined ? this.row + 1 : (ooxmlInt(a.r, 1, MAX_ROWS) ?? 0) - 1 + // Discard the whole record before sparse array lengths or progress counts can grow. + if (row < 0 || row >= MAX_ROWS) return true + this.row = row this.col = -1 this.rowCells = [] const hidden = a.hidden === '1' || a.hidden === 'true' - if (hidden || a.ht) this.d.rowAttrs.set(this.row, { ht: a.ht ? Number(a.ht) : undefined, hidden: hidden || undefined }) - this.rowHasHt = hidden || !!a.ht + const ht = ooxmlNumber(a.ht, 0, MAX_ROW_HEIGHT_PT) + if (hidden || ht !== undefined) this.d.rowAttrs.set(this.row, { ht, hidden: hidden || undefined }) + this.rowHasHt = hidden || ht !== undefined this.rowMaxPt = 0 if (hidden) this.newSizes.push([this.row, 0]) - else if (a.ht) { - const px = Math.round((Number(a.ht) * 4) / 3) + else if (ht !== undefined) { + const px = Math.round((ht * 4) / 3) if (px !== this.d.defaultRowH) this.newSizes.push([this.row, px]) } return } case 'sheetFormatPr': { - const h = num(a.defaultRowHeight) - if (h) this.d.defaultRowH = Math.round((h * 4) / 3) - const w = num(a.defaultColWidth) - const base = num(a.baseColWidth) - if (w) this.d.defaultColW = Math.round(w * 7) + const h = ooxmlNumber(a.defaultRowHeight, 0, MAX_ROW_HEIGHT_PT) + if (h) this.d.defaultRowH = Math.max(1, Math.round((h * 4) / 3)) + const w = ooxmlNumber(a.defaultColWidth, 0, MAX_COL_WIDTH) + const base = ooxmlInt(a.baseColWidth, 0, MAX_COL_WIDTH) + if (w) this.d.defaultColW = Math.max(1, Math.round(w * 7)) else if (base !== undefined) this.d.defaultColW = Math.round(base * 7 + 8) return } case 'col': { - const min = Number(a.min) - 1 - const max = Math.min(Number(a.max) - 1, MAX_COL - 1) + const first = ooxmlInt(a.min, 1, MAX_COL) + const last = ooxmlInt(a.max, 1, MAX_COL) + if (first === undefined || last === undefined || first > last) return + const min = first - 1 + const max = last - 1 const hidden = a.hidden === '1' || a.hidden === 'true' - const w = hidden ? 0 : a.width ? Math.round(Number(a.width) * 7) : this.d.defaultColW + const width = ooxmlNumber(a.width, 0, MAX_COL_WIDTH) + if (a.width !== undefined && width === undefined) return + const w = hidden ? 0 : width !== undefined ? Math.round(width * 7) : this.d.defaultColW this.d.colInfo.push({ min, max, w }) return } case 'pane': if (a.state === 'frozen' || a.state === 'frozenSplit') { - this.d.frozen = { rows: Math.round(num(a.ySplit, 0)!), cols: Math.round(num(a.xSplit, 0)!) } + this.d.frozen = { rows: ooxmlInt(a.ySplit, 0, MAX_ROWS - 1) ?? 0, cols: ooxmlInt(a.xSplit, 0, MAX_COL - 1) ?? 0 } } return case 'sheetView': @@ -192,8 +210,12 @@ class SheetHandler implements SaxHandler { this.headerReady = true return case 'mergeCell': { - const m = a.ref ? parseRange(a.ref) : undefined - if (m) this.d.merges.push(m) + const parts = a.ref?.split(':') ?? [] + const start = worksheetRef(parts[0] ?? '') + const end = parts.length === 1 ? start : worksheetRef(parts[1] ?? '') + if (parts.length <= 2 && start && end && start[0] <= end[0] && start[1] <= end[1]) { + this.d.merges.push({ r0: start[0], c0: start[1], r1: end[0], c1: end[1] }) + } return } case 'extLst': @@ -274,7 +296,7 @@ class SheetHandler implements SaxHandler { } case 'row': if (!this.rowHasHt && this.rowMaxPt > this.basePt * 1.15) { - const px = Math.round(this.rowMaxPt * (4 / 3) * 1.3 + 3) + const px = Math.min(MAX_ROW_HEIGHT_PT * (4 / 3), Math.round(this.rowMaxPt * (4 / 3) * 1.3 + 3)) if (px > this.d.defaultRowH) { this.newSizes.push([this.row, px]) this.d.autoRowH.set(this.row, px) diff --git a/src/react/xlsx/axis.ts b/src/react/xlsx/axis.ts index 8874823..3828d4e 100644 --- a/src/react/xlsx/axis.ts +++ b/src/react/xlsx/axis.ts @@ -38,7 +38,7 @@ export class Axis { let hi = this.keys.length - 1 let k = -1 while (lo <= hi) { - const mid = (lo + hi) >> 1 + const mid = lo + Math.floor((hi - lo) / 2) if (this.keys[mid] < i) { k = mid lo = mid + 1 @@ -53,11 +53,12 @@ export class Axis { /** Index containing offset px (clamped to [0, count-1]). */ index(px: number): number { - if (px <= 0) return 0 + if (px <= 0 || Number.isNaN(px) || !Number.isSafeInteger(this.count)) return 0 let lo = 0 let hi = Math.max(0, this.count - 1) while (lo < hi) { - const mid = (lo + hi + 1) >> 1 + // Bitwise midpoints overflow at 2^31; large CSV axes intentionally exceed Excel's limits. + const mid = lo + Math.ceil((hi - lo) / 2) if (this.pos(mid) <= px) lo = mid else hi = mid - 1 } diff --git a/src/react/xlsx/drawings.tsx b/src/react/xlsx/drawings.tsx index b8c2c3e..2a2b248 100644 --- a/src/react/xlsx/drawings.tsx +++ b/src/react/xlsx/drawings.tsx @@ -1,6 +1,7 @@ import { useEffect, useState, type CSSProperties, type ReactNode } from 'react' import type { DocumentClient } from '../../core/worker/client' import type { SheetDrawing } from '../../core/xlsx/drawings' +import { MAX_COL, MAX_ROWS } from '../../core/xlsx/limits' import { Icon } from '../edit/Toolbar' import type { Axis } from './axis' @@ -54,9 +55,11 @@ export function drawingExtent(list: SheetDrawing[], cols: Axis, rows: Axis): { r const end = d.to ?? (d.from && d.size ? { c: d.from.c + Math.ceil(d.size.w / cols.def), r: d.from.r + Math.ceil(d.size.h / rows.def) } : undefined) const fromAt = !end && d.at && d.size ? { c: Math.ceil((d.at.x + d.size.w) / cols.def), r: Math.ceil((d.at.y + d.size.h) / rows.def) } : undefined const e = end ?? fromAt - if (e) { - r = Math.max(r, e.r + 1) - c = Math.max(c, e.c + 1) + if (e && Number.isFinite(e.r) && Number.isFinite(e.c)) { + // Sizes/absolute positions are in pixels and can span many default-sized cells. Only this + // OOXML drawing contribution is bounded; the sheet's CSV row count and Axis stay unrestricted. + r = Math.max(r, Math.min(MAX_ROWS, e.r + 1)) + c = Math.max(c, Math.min(MAX_COL, e.c + 1)) } } return { rows: r, cols: c } diff --git a/test/axis.test.ts b/test/axis.test.ts new file mode 100644 index 0000000..46d6508 --- /dev/null +++ b/test/axis.test.ts @@ -0,0 +1,53 @@ +import { expect, test } from 'bun:test' +import { Axis } from '../src/react/xlsx/axis' + +/** Bound the old non-converging search as well, so a regression fails without hanging the test runner. */ +class BoundedAxis extends Axis { + lookups = 0 + override pos(i: number): number { + if (++this.lookups > 64) throw new Error('Axis.index did not converge within 64 lookups') + return super.pos(i) + } + lookup(px: number): number { + this.lookups = 0 + return this.index(px) + } +} + +test('axis lookup preserves large CSV counts without signed 32-bit overflow', () => { + const axis = new BoundedAxis(20) + for (const count of [500_000_000, 2 ** 31, 4_000_000_000, 2 ** 32 + 1, Number.MAX_SAFE_INTEGER]) { + axis.count = count + expect(axis.lookup(0)).toBe(0) + expect(axis.lookup(20)).toBe(1) + expect(axis.lookup((count - 2) * 20)).toBe(count - 2) + expect(axis.lookup(Infinity)).toBe(count - 1) + expect(axis.count).toBe(count) + } +}) + +test('large sparse axes find custom-sized and hidden rows at their exact boundaries', () => { + const axis = new BoundedAxis(20) + axis.count = 4_000_000_000 + axis.set(0, 0) + axis.set(3_000_000_000, 40) + axis.set(3_000_000_001, 0) + expect(axis.lookup(1)).toBe(1) + const start = axis.pos(3_000_000_000) + expect(start).toBe(3_000_000_000 * 20 - 20) + expect(axis.lookup(start)).toBe(3_000_000_000) + expect(axis.lookup(start + 39)).toBe(3_000_000_000) + expect(axis.lookup(start + 40)).toBe(3_000_000_002) + expect(axis.total()).toBe(axis.count * 20 - 20) +}) + +test('empty axes and nonfinite inputs terminate', () => { + const axis = new BoundedAxis(20) + for (const count of [0, -1, NaN, Infinity, 1.5]) { + axis.count = count + expect(axis.lookup(20)).toBe(0) + } + axis.count = 4_000_000_000 + expect(axis.lookup(NaN)).toBe(0) + expect(axis.lookup(-Infinity)).toBe(0) +}) diff --git a/test/xlsx-bounds.test.ts b/test/xlsx-bounds.test.ts new file mode 100644 index 0000000..41b0f11 --- /dev/null +++ b/test/xlsx-bounds.test.ts @@ -0,0 +1,138 @@ +import { expect, test } from 'bun:test' +import { rowsToXlsx } from '../src/core/convert' +import { OpcPackage } from '../src/core/opc' +import { BlobSource } from '../src/core/source' +import { ZipArchive } from '../src/core/zip' +import { MAX_COL, MAX_ROWS, rowSizesOf, XlsxWorkbook } from '../src/core/xlsx/workbook' +import type { SheetProgress } from '../src/core/xlsx/types' + +async function workbook(xml: string) { + const zip = await ZipArchive.open(new BlobSource(await rowsToXlsx([['base']]))) + const pkg = new OpcPackage(zip) + pkg.setPart('xl/worksheets/sheet1.xml', `${xml}`) + return XlsxWorkbook.open(pkg, 'xl/workbook.xml') +} + +async function parsed(xml: string) { + const wb = await workbook(xml) + const progress: SheetProgress[] = [] + await wb.loadSheet(0, (p) => progress.push(p)) + const d = wb.sheetsData.get(0)! + expect(d.error).toBeUndefined() + return { wb, d, progress } +} + +test('worksheet coordinates reject malformed records and retain valid explicit and implicit cells', async () => { + const invalidRows = ['0', '-1', '1.5', 'NaN', 'Infinity', '1048577', ''] + .map((r) => `9`).join('') + const invalidCells = ['A0', 'A-1', 'A1.5', 'XFE1', 'ZZZ1', 'A1048577', 'A2', '', '1', 'A1:B2'] + .map((r) => `9`).join('') + const { wb, d, progress } = await parsed( + '' + invalidRows + + `${invalidCells}12` + + '3', + ) + expect(d.maxRow).toBe(1) + expect(d.maxCol).toBe(1) + expect(d.rows.length).toBe(2) + expect(d.rowAttrs.size).toBe(0) + expect(progress.at(-1)).toMatchObject({ rows: 2, cols: 2, done: true }) + expect((await wb.block(0, 0, 2)).rows.map((r) => r.cells.map((c) => c[1]))).toEqual([['1', '2'], ['3']]) +}) + +test('worksheet boundaries preserve XFD1048576 and skip implicit overflow', async () => { + const { wb, d } = await parsed( + '78' + + '9', + ) + expect(d.maxRow).toBe(MAX_ROWS - 1) + expect(d.maxCol).toBe(MAX_COL - 1) + expect(d.rows.length).toBe(MAX_ROWS) + expect((await wb.block(0, MAX_ROWS - 1, MAX_ROWS)).rows[0].cells).toEqual([[MAX_COL - 1, '7', 0, 1]]) +}) + +test('worksheet dimensions, column records, merges, and sizes cannot bypass coordinate validation', async () => { + const invalidCols = [ + ['-Infinity', '4', '10'], ['0', '4', '10'], ['1.5', '4', '10'], ['1', '16385', '10'], + ['4', '3', '10'], ['NaN', '4', '10'], ['1', '4', 'Infinity'], ['1', '4', '-1'], ['1', '4', '256'], + ].map(([min, max, width]) => ``).join('') + const invalidMerges = ['A1:A4000000000', 'A1:XFE2', 'A0:B2', 'A1.5:B2', 'B2:A1', 'A1:B2:C3', 'NaN', 'A1:'] + .map((ref) => ``).join('') + const { d, progress } = await parsed( + '' + + '' + + '' + + `${invalidCols}` + + '1' + + '' + + `${invalidMerges}`, + ) + expect(d.colInfo).toEqual([{ min: MAX_COL - 1, max: MAX_COL - 1, w: 1785 }, { min: 1, max: 2, w: 0 }]) + expect(d.merges).toEqual([{ r0: 0, c0: 0, r1: 1, c1: 1 }, { r0: MAX_ROWS - 2, c0: MAX_COL - 2, r1: MAX_ROWS - 1, c1: MAX_COL - 1 }]) + expect(d.defaultRowH).toBe(20) + expect(d.defaultColW).toBe(64) + expect(d.frozen).toEqual({ rows: 0, cols: 0 }) + expect(rowSizesOf(d)).toEqual([[2, 546], [3, 0], [4, 0]]) + expect(progress.at(-1)).toMatchObject({ rows: 5, cols: 1 }) +}) + +test('valid worksheet sizes and panes are preserved', async () => { + const { d, progress } = await parsed( + '' + + '' + + '', + ) + expect(progress[0]).toMatchObject({ defaultRowH: 30, defaultColW: 84, frozen: { rows: 3, cols: 2 } }) + expect(d.colInfo).toEqual([{ min: 0, max: 1, w: 67 }]) + expect(rowSizesOf(d)).toEqual([[0, 25]]) +}) + +test('tiny defaults stay positive and font-grown OOXML row heights stay bounded', async () => { + const wb = await workbook('' + + '1') + wb.styles.xfs.push({ ...wb.styles.xfs[0], fontPt: 1e300 }) + await wb.loadSheet(0, () => {}) + const d = wb.sheetsData.get(0)! + expect(d.defaultRowH).toBe(1) + expect(d.defaultColW).toBe(1) + expect(rowSizesOf(d)).toEqual([[0, 546]]) +}) + +test('non-OOXML loaders retain 500 million rows and larger counts', async () => { + const wb = await workbook('') + for (const count of [500_000_000, 4_000_000_000]) { + wb.sheetsData.clear() + wb.loaders.set(wb.sheets[0].path, async (d) => { d.maxRow = count - 1 }) + let last: SheetProgress | undefined + await wb.loadSheet(0, (p) => { last = p }) + expect(last).toMatchObject({ rows: count, done: true }) + } +}) + +test('corrupt multi-billion row records remain bounded in an isolated process', async () => { + // A separate, forcibly time-limited process contains sparse-array/CPU regressions in this repro. + const proc = Bun.spawn([process.execPath, '--eval', ` + import assert from 'node:assert/strict' + import { rowsToXlsx } from './src/core/convert.ts' + import { OpcPackage } from './src/core/opc.ts' + import { BlobSource } from './src/core/source.ts' + import { ZipArchive } from './src/core/zip.ts' + import { XlsxWorkbook } from './src/core/xlsx/workbook.ts' + const pkg = new OpcPackage(await ZipArchive.open(new BlobSource(await rowsToXlsx([['base']])))) + pkg.setPart('xl/worksheets/sheet1.xml', '' + + ['4000000000', '9007199254740992', '1e300', 'Infinity'].map(r => + '9').join('') + + '79') + const wb = await XlsxWorkbook.open(pkg, 'xl/workbook.xml') + await wb.loadSheet(0, p => { assert.ok(p.rows <= 1); assert.ok(p.cols <= 1) }) + const d = wb.sheetsData.get(0) + assert.equal(d.error, undefined) + assert.equal(d.rows.length, 1) + assert.equal(d.maxRow, 0) + assert.equal(d.maxCol, 0) + assert.equal((await wb.block(0, 0, 1)).rows[0].cells[0][1], '7') + `], { cwd: `${import.meta.dir}/..`, stdout: 'pipe', stderr: 'pipe', timeout: 5000, killSignal: 'SIGKILL' }) + const [exit, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]) + expect(stderr).toBe('') + expect(exit).toBe(0) +}, 10_000) diff --git a/test/xlsx-drawings.test.ts b/test/xlsx-drawings.test.ts index 691bcca..78ca40f 100644 --- a/test/xlsx-drawings.test.ts +++ b/test/xlsx-drawings.test.ts @@ -7,6 +7,7 @@ import { rebuildZip } from '../src/core/zipwrite' import type { SheetDrawing } from '../src/core/xlsx/drawings' import { drawingBox, drawingExtent } from '../src/react/xlsx/drawings' import { Axis } from '../src/react/xlsx/axis' +import { MAX_COL, MAX_ROWS, MAX_SHEET_HEIGHT_PX, MAX_SHEET_WIDTH_PX } from '../src/core/xlsx/limits' const RELS = 'http://schemas.openxmlformats.org/package/2006/relationships' const R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' @@ -20,7 +21,7 @@ const pic = (rid: string, descr: string) => `` /** a workbook whose sheet has a picture between two cells, a column chart by one cell and a size, an EMF picture at a position, and a text box */ -async function withDrawings(): Promise { +async function withDrawings(anchors?: string): Promise { const base = await rowsToXlsx([['a', 'b'], ['c', 'd']], 'Data') const zip = await ZipArchive.open(new BlobSource(base)) const files = new Map() @@ -32,10 +33,10 @@ async function withDrawings(): Promise { files.set( 'xl/drawings/drawing1.xml', `${HEAD}` + - `${corner('from', 1, 2, 10, 5)}${corner('to', 4, 8)}${pic('rId1', 'Logo')}` + + (anchors ?? (`${corner('from', 1, 2, 10, 5)}${corner('to', 4, 8)}${pic('rId1', 'Logo')}` + `${corner('from', 6, 1)}` + `${pic('rId3', '')}` + - `${corner('from', 0, 0)}${corner('to', 1, 1)}` + + `${corner('from', 0, 0)}${corner('to', 1, 1)}`)) + ``, ) files.set( @@ -80,3 +81,45 @@ test('a drawing is placed by its cells, so it moves and grows with them', () => // the sheet reaches past its last drawing expect(drawingExtent([d, { kind: 'chart', title: '', at: { x: 0, y: 600 }, size: { w: 80, h: 40 } }], new Axis(64), new Axis(20))).toEqual({ rows: 33, cols: 5 }) }) + +test('invalid drawing coordinates discard the anchor without stretching the sheet', async () => { + const two = (from: string, to = corner('to', 2, 3)) => `${from}${to}${pic('rId1', 'bad')}` + const invalid: string[] = [] + for (const r of [-1, 0.5, MAX_ROWS, 3_999_999_998, NaN, Infinity]) invalid.push(two(corner('from', 0, r))) + for (const c of [-1, 0.5, MAX_COL, 4_000_000_000, NaN, Infinity]) invalid.push(two(corner('from', c, 0))) + invalid.push(two(corner('from', 0, 0), corner('to', 0, 4_000_000_000))) + for (const offset of [NaN, Infinity, Number.MAX_SAFE_INTEGER, MAX_SHEET_HEIGHT_PX + 1]) { + invalid.push(two(corner('from', 0, 0, 0, offset))) + } + invalid.push(two(corner('from', 0, 0).replace('0', ''))) + invalid.push(two(corner('from', 0, 0).replace('0', '0.5'))) + invalid.push(two(corner('from', 0, 0), '')) + for (const [cx, cy] of [['NaN', '9525'], ['9525', 'Infinity'], ['-1', '9525'], ['0.5', '9525'], ['9007199254740992', '9525'], [String((MAX_SHEET_WIDTH_PX + 1) * EMU), '9525']]) { + invalid.push(`${corner('from', 0, 0)}${pic('rId1', 'bad')}`) + } + for (const x of ['NaN', 'Infinity', '0.5', '9007199254740992', String((MAX_SHEET_WIDTH_PX + 1) * EMU)]) { + invalid.push(`${pic('rId1', 'bad')}`) + } + const valid = two(corner('from', MAX_COL - 2, MAX_ROWS - 2, -1, 1 / EMU), corner('to', MAX_COL - 1, MAX_ROWS - 1)) + const engine = new Engine(() => {}) + await engine.open(await withDrawings(invalid.join('') + valid), {}) + const list = await engine.call('xlsx.drawings', [0]) as SheetDrawing[] + expect(list).toHaveLength(1) + expect(list[0].from).toEqual({ c: MAX_COL - 2, r: MAX_ROWS - 2, dx: -1, dy: 1 / EMU }) + expect(drawingExtent(list, new Axis(64), new Axis(20))).toEqual({ rows: MAX_ROWS, cols: MAX_COL }) +}) + +test('valid large pixel anchors contribute at most an OOXML worksheet to view extents', async () => { + const size = `` + const engine = new Engine(() => {}) + await engine.open(await withDrawings( + `${corner('from', MAX_COL - 1, MAX_ROWS - 1)}${size}${pic('rId1', 'large cell anchor')}` + + `${size}${pic('rId1', 'large absolute anchor')}`, + ), {}) + const list = await engine.call('xlsx.drawings', [0]) as SheetDrawing[] + expect(list).toHaveLength(2) + for (const d of list) { + expect(d.size).toEqual({ w: MAX_SHEET_WIDTH_PX, h: MAX_SHEET_HEIGHT_PX }) + expect(drawingExtent([d], new Axis(64), new Axis(20))).toEqual({ rows: MAX_ROWS, cols: MAX_COL }) + } +})