javascript-excel 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,8 +17,24 @@ const DEFAULT_LIMITS = Object.freeze({
17
17
  maxCells: 1e7,
18
18
  maxItems: 1e7,
19
19
  maxSharedStrings: 5e6,
20
+ maxCellTextLength: 1048576,
21
+ maxColumns: 16384,
20
22
  maxWarnings: 1e3
21
23
  });
24
+ function head(s) {
25
+ let end = 64;
26
+ const c = s.charCodeAt(end - 1);
27
+ if (c >= 55296 && c <= 56319) end--;
28
+ return s.slice(0, end);
29
+ }
30
+ /** `s` itself when short; else its start, `…` and its length: `abc… (16000000 characters)`. */
31
+ function excerpt(s) {
32
+ return s.length <= 128 ? s : `${head(s)}… (${s.length} characters)`;
33
+ }
34
+ /** `JSON.stringify(s)` when short; else the quoted start, `…` and its length: `"abc"… (16000000 characters)`. */
35
+ function quoted(s) {
36
+ return s.length <= 128 ? JSON.stringify(s) : `${JSON.stringify(head(s))}… (${s.length} characters)`;
37
+ }
22
38
  // src/internal/zip/read.ts
23
39
  /**
24
40
  * Zip container reader (docs/api.md §6, §8). Internal.
@@ -221,15 +237,15 @@ function openZip(bytes, options = {}) {
221
237
  }
222
238
  if (diskStart !== 0) throw invalid("Multi-disk zip archives are not supported.");
223
239
  const name = decodeName(rawName, flags, extra);
224
- if (flags & 65 || method === METHOD_AES) throw new require_errors.FormatError("ZIP_ENCRYPTED", `Entry ${name} is encrypted.`, { details: { entry: name } });
225
- if (method !== 0 && method !== 8) throw new require_errors.FormatError("ZIP_UNSUPPORTED_METHOD", `Entry ${name} uses compression method ${method}.`, { details: {
240
+ if (flags & 65 || method === METHOD_AES) throw new require_errors.FormatError("ZIP_ENCRYPTED", `Entry ${excerpt(name)} is encrypted.`, { details: { entry: name } });
241
+ if (method !== 0 && method !== 8) throw new require_errors.FormatError("ZIP_UNSUPPORTED_METHOD", `Entry ${excerpt(name)} uses compression method ${method}.`, { details: {
226
242
  entry: name,
227
243
  method
228
244
  } });
229
- if (method === 0 && compressedSize !== size) throw invalid(`Stored entry ${name} has mismatched sizes.`);
230
- if (byName.has(name)) throw invalid(`Duplicate entry name: ${name}`, { entry: name });
245
+ if (method === 0 && compressedSize !== size) throw invalid(`Stored entry ${excerpt(name)} has mismatched sizes.`);
246
+ if (byName.has(name)) throw invalid(`Duplicate entry name: ${excerpt(name)}`, { entry: name });
231
247
  const l = new Cursor(bytes, localOffset);
232
- if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${name}.`, { entry: name });
248
+ if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${excerpt(name)}.`, { entry: name });
233
249
  l.u16();
234
250
  const lFlags = l.u16();
235
251
  const lMethod = l.u16();
@@ -244,10 +260,10 @@ function openZip(bytes, options = {}) {
244
260
  l.take(lExtraLength);
245
261
  let agrees = lNameLength === nameLength && lName.every((b, k) => b === rawName[k]) && lMethod === method && (lFlags & FLAG_ENCRYPTED) === 0;
246
262
  if (agrees && !(lFlags & FLAG_DATA_DESCRIPTOR)) agrees = lCrc === crc && (lCompressed === compressedSize || lCompressed === 4294967295) && (lSize === size || lSize === 4294967295);
247
- if (!agrees) throw invalid(`Local header disagrees with the central directory for ${name}.`, { entry: name });
263
+ if (!agrees) throw invalid(`Local header disagrees with the central directory for ${excerpt(name)}.`, { entry: name });
248
264
  const dataOffset = l.pos;
249
265
  const dataEnd = dataOffset + compressedSize;
250
- if (dataEnd > cdOffset) throw invalid(`Data of ${name} runs into the central directory.`, { entry: name });
266
+ if (dataEnd > cdOffset) throw invalid(`Data of ${excerpt(name)} runs into the central directory.`, { entry: name });
251
267
  spans.push({
252
268
  start: localOffset,
253
269
  end: dataEnd,
@@ -267,7 +283,7 @@ function openZip(bytes, options = {}) {
267
283
  byName.set(name, info);
268
284
  }
269
285
  spans.sort((a, b) => a.start - b.start);
270
- for (let i = 1; i < spans.length; i++) if (spans[i].start < spans[i - 1].end) throw invalid(`Entries ${spans[i - 1].name} and ${spans[i].name} overlap.`);
286
+ for (let i = 1; i < spans.length; i++) if (spans[i].start < spans[i - 1].end) throw invalid(`Entries ${excerpt(spans[i - 1].name)} and ${excerpt(spans[i].name)} overlap.`);
271
287
  let totalBytesRead = 0;
272
288
  const resolve = (entry) => {
273
289
  const info = typeof entry === "string" ? byName.get(entry) : entry;
@@ -281,7 +297,7 @@ function openZip(bytes, options = {}) {
281
297
  async function* stream(entry, signal) {
282
298
  const info = resolve(entry);
283
299
  require_dos_time.throwIfAborted(signal);
284
- if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${info.name}`);
300
+ if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${excerpt(info.name)}`);
285
301
  const data = bytes.subarray(info.dataOffset, info.dataOffset + info.compressedSize);
286
302
  let crc = 0;
287
303
  let produced = 0;
@@ -302,12 +318,12 @@ function openZip(bytes, options = {}) {
302
318
  }, signal);
303
319
  for await (const chunk of chunks) {
304
320
  produced += chunk.length;
305
- if (produced > info.size) throw invalid(`Entry ${info.name} is larger than declared.`, { entry: info.name });
321
+ if (produced > info.size) throw invalid(`Entry ${excerpt(info.name)} is larger than declared.`, { entry: info.name });
306
322
  countTotal(chunk.length);
307
323
  crc = require_dos_time.crc32(chunk, crc);
308
324
  yield chunk;
309
325
  }
310
- if (produced !== info.size) throw invalid(`Entry ${info.name} is smaller than declared.`, { entry: info.name });
326
+ if (produced !== info.size) throw invalid(`Entry ${excerpt(info.name)} is smaller than declared.`, { entry: info.name });
311
327
  if (crc !== info.crc32) throw crcMismatch(info);
312
328
  }
313
329
  return {
@@ -325,7 +341,7 @@ function openZip(bytes, options = {}) {
325
341
  };
326
342
  }
327
343
  function crcMismatch(info) {
328
- return new require_errors.FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${info.name}.`, { details: { entry: info.name } });
344
+ return new require_errors.FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${excerpt(info.name)}.`, { details: { entry: info.name } });
329
345
  }
330
346
  // src/internal/read/xml-reader.ts
331
347
  /**
@@ -466,9 +482,9 @@ var XmlTokenizer = class {
466
482
  end() {
467
483
  if (this.wait !== Wait.None) this.unsuspend();
468
484
  this.pump(true);
469
- if (this.skipTag !== void 0) throw malformed(`Element <${this.skipTag.slice(2)}> is not closed.`);
485
+ if (this.skipTag !== void 0) throw malformed(`Element <${excerpt(this.skipTag.slice(2))}> is not closed.`);
470
486
  if (this.buf.trim() !== "") throw malformed("Unexpected end of XML data.");
471
- if (this.stack.length > 0) throw malformed(`Element <${this.stack.at(-1)}> is not closed.`);
487
+ if (this.stack.length > 0) throw malformed(`Element <${excerpt(this.stack.at(-1))}> is not closed.`);
472
488
  if (!this.rootSeen) throw malformed("XML part has no root element.");
473
489
  }
474
490
  /**
@@ -540,7 +556,7 @@ var XmlTokenizer = class {
540
556
  const tag = this.skipTag;
541
557
  const end = this.skipTo(buf, i);
542
558
  if (end === -1) {
543
- if (final) throw malformed(`Element <${tag.slice(2)}> is not closed.`);
559
+ if (final) throw malformed(`Element <${excerpt(tag.slice(2))}> is not closed.`);
544
560
  i = len;
545
561
  break;
546
562
  }
@@ -607,7 +623,7 @@ var XmlTokenizer = class {
607
623
  this.checkToken(e + 1 - i);
608
624
  const qname = buf.slice(i + 2, e).trim();
609
625
  const open = this.stack.pop();
610
- if (open === void 0 || open !== qname) throw malformed(open === void 0 ? `Unexpected end tag </${qname}>.` : `End tag </${qname}> does not match <${open}>.`);
626
+ if (open === void 0 || open !== qname) throw malformed(open === void 0 ? `Unexpected end tag </${excerpt(qname)}>.` : `End tag </${excerpt(qname)}> does not match <${excerpt(open)}>.`);
611
627
  if (this.stack.length === 0) this.rootClosed = true;
612
628
  this.handler.close(localName(qname));
613
629
  i = e + 1;
@@ -691,15 +707,15 @@ var XmlTokenizer = class {
691
707
  while (p < stop && buf.charCodeAt(p) !== 61 && !isSpace(buf.charCodeAt(p))) p++;
692
708
  const aname = buf.slice(nameStart, p);
693
709
  while (p < stop && isSpace(buf.charCodeAt(p))) p++;
694
- if (buf.charCodeAt(p) !== 61 || aname.length === 0) throw malformed(`Malformed attribute in <${qname}>.`);
710
+ if (buf.charCodeAt(p) !== 61 || aname.length === 0) throw malformed(`Malformed attribute in <${excerpt(qname)}>.`);
695
711
  p++;
696
712
  while (p < stop && isSpace(buf.charCodeAt(p))) p++;
697
713
  const q = buf.charCodeAt(p);
698
- if (q !== 34 && q !== 39) throw malformed(`Unquoted attribute value in <${qname}>.`);
714
+ if (q !== 34 && q !== 39) throw malformed(`Unquoted attribute value in <${excerpt(qname)}>.`);
699
715
  const close = buf.indexOf(q === 34 ? "\"" : "'", p + 1);
700
- if (close === -1 || close >= stop) throw malformed(`Unterminated attribute value in <${qname}>.`);
716
+ if (close === -1 || close >= stop) throw malformed(`Unterminated attribute value in <${excerpt(qname)}>.`);
701
717
  const raw = buf.slice(p + 1, close);
702
- if (raw.indexOf("<") !== -1) throw malformed(`'<' in an attribute value of <${qname}>.`);
718
+ if (raw.indexOf("<") !== -1) throw malformed(`'<' in an attribute value of <${excerpt(qname)}>.`);
703
719
  items.push(aname, normaliseAttr(raw));
704
720
  p = close + 1;
705
721
  }
@@ -944,7 +960,7 @@ var ReadContext = class {
944
960
  }
945
961
  };
946
962
  function withPart(err, part) {
947
- if (err instanceof require_errors.FormatError && (err.code === "XML_MALFORMED" || err.code === "XML_DTD_FORBIDDEN") && !err.details?.["part"]) return new require_errors.FormatError(err.code, `${part}: ${err.message}`, {
963
+ if (err instanceof require_errors.FormatError && (err.code === "XML_MALFORMED" || err.code === "XML_DTD_FORBIDDEN") && !err.details?.["part"]) return new require_errors.FormatError(err.code, `${excerpt(part)}: ${err.message}`, {
948
964
  details: {
949
965
  ...err.details,
950
966
  part
@@ -952,7 +968,7 @@ function withPart(err, part) {
952
968
  cause: err
953
969
  });
954
970
  const limit = err instanceof require_errors.LimitError ? err.details?.["limit"] : void 0;
955
- if (err instanceof require_errors.LimitError && (limit === "maxXmlDepth" || limit === "maxXmlTokenLength") && !err.details?.["part"]) return new require_errors.LimitError(err.code, `${part}: ${err.message}`, {
971
+ if (err instanceof require_errors.LimitError && (limit === "maxXmlDepth" || limit === "maxXmlTokenLength" || limit === "maxCellTextLength") && !err.details?.["part"]) return new require_errors.LimitError(err.code, `${excerpt(part)}: ${err.message}`, {
956
972
  details: {
957
973
  ...err.details,
958
974
  part
@@ -1081,7 +1097,7 @@ var Package = class {
1081
1097
  for (const e of ctx.zip.entries) {
1082
1098
  if (e.name.endsWith("/")) continue;
1083
1099
  const key = e.name.toLowerCase();
1084
- if (this.parts.has(key)) throw new require_errors.FormatError("ZIP_INVALID", `Part names ${this.parts.get(key).name} and ${e.name} differ only in case.`, { details: { entry: e.name } });
1100
+ if (this.parts.has(key)) throw new require_errors.FormatError("ZIP_INVALID", `Part names ${excerpt(this.parts.get(key).name)} and ${excerpt(e.name)} differ only in case.`, { details: { entry: e.name } });
1085
1101
  this.parts.set(key, e);
1086
1102
  }
1087
1103
  }
@@ -1182,13 +1198,17 @@ function resolveTarget(baseDir, target) {
1182
1198
  * references, external workbook indexes) are copied unchanged. Returns
1183
1199
  * undefined when a shifted reference would leave the sheet, so the caller
1184
1200
  * keeps the cached value only.
1201
+ *
1202
+ * A master formula is scanned once (`compileFormula`) into the text between its
1203
+ * references and the references themselves; each cell that shares it then costs
1204
+ * its number of references plus the length of its own text (`shiftCompiled`),
1205
+ * and whether its references stay on the sheet is known in constant time
1206
+ * (`canShift`). Before JSE-62 every cell rescanned the master character by
1207
+ * character and built its text with `+=`, so N cells sharing a long formula
1208
+ * cost N times the master's length in time and much more in memory.
1185
1209
  */
1186
1210
  const MAX_ROW = 1048576;
1187
1211
  const MAX_COL = 16384;
1188
- const CELL = /\$?([A-Za-z]{1,3})\$?(\d{1,7})/y;
1189
- const CELL_PARTS = /^(\$?)([A-Za-z]{1,3})(\$?)(\d{1,7})$/;
1190
- const COLS = /(\$?)([A-Za-z]{1,3}):(\$?)([A-Za-z]{1,3})/y;
1191
- const ROWS = /(\$?)(\d{1,7}):(\$?)(\d{1,7})/y;
1192
1212
  function colNumber(letters) {
1193
1213
  let n = 0;
1194
1214
  for (let i = 0; i < letters.length; i++) n = n * 26 + (letters.toUpperCase().charCodeAt(i) - 64);
@@ -1203,110 +1223,274 @@ function colLetters(n) {
1203
1223
  }
1204
1224
  return s;
1205
1225
  }
1206
- function isWordChar(c) {
1207
- return c !== void 0 && /[A-Za-z0-9_.\\]/.test(c);
1226
+ /** A letter or digit, by character code (JSE-62: a regex test per character made long masters slow). */
1227
+ function isAlnumCode(c) {
1228
+ return c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122;
1208
1229
  }
1209
- function shiftFormula(formula, dRow, dCol) {
1210
- if (dRow === 0 && dCol === 0) return formula;
1211
- let out = "";
1230
+ /** Part of a word: a letter, digit, `_`, `.` or `\\`. */
1231
+ function isWordCode(c) {
1232
+ return isAlnumCode(c) || c === 95 || c === 46 || c === 92;
1233
+ }
1234
+ /**
1235
+ * Excel's own limit on the length of a formula. A shared formula's master that
1236
+ * is longer is not expanded into the cells that share it (JSE-62): no
1237
+ * spreadsheet application writes one, and expanding it multiplied a few KB of
1238
+ * file into gigabytes.
1239
+ */
1240
+ const MAX_SHARED_FORMULA_LENGTH = 8192;
1241
+ /** Work done by the shifter, for the bounded-work tests (JSE-62). */
1242
+ const shiftWork = {
1243
+ compiles: 0,
1244
+ compiledChars: 0,
1245
+ shifts: 0,
1246
+ shiftedChars: 0
1247
+ };
1248
+ const COLS_REF = 0;
1249
+ const ROWS_REF = 1;
1250
+ const CELL_REF = 2;
1251
+ /**
1252
+ * Scans `formula` once, in time proportional to its length. With `boundsOnly`
1253
+ * only the relative bounds are kept (for `canShift`; no text can be built from
1254
+ * the result): what importDataset needs.
1255
+ */
1256
+ function compileFormula(formula, boundsOnly = false) {
1257
+ shiftWork.compiles++;
1258
+ shiftWork.compiledChars += formula.length;
1259
+ const segs = [];
1260
+ const refs = [];
1261
+ let rowMin = 1e400;
1262
+ let rowMax = -1e400;
1263
+ let colMin = 1e400;
1264
+ let colMax = -1e400;
1265
+ const relRow = (anchor, v) => {
1266
+ if (anchor === "$") return;
1267
+ if (v < rowMin) rowMin = v;
1268
+ if (v > rowMax) rowMax = v;
1269
+ };
1270
+ const relCol = (anchor, v) => {
1271
+ if (anchor === "$") return;
1272
+ if (v < colMin) colMin = v;
1273
+ if (v > colMax) colMax = v;
1274
+ };
1275
+ let segStart = 0;
1212
1276
  let i = 0;
1213
1277
  const n = formula.length;
1214
1278
  while (i < n) {
1215
- const ch = formula[i];
1216
- if (ch === "\"") {
1217
- let j = i + 1;
1218
- for (; j < n; j++) if (formula[j] === "\"") {
1219
- if (formula[j + 1] === "\"") j++;
1220
- else break;
1221
- }
1222
- out += formula.slice(i, j + 1);
1223
- i = j + 1;
1224
- continue;
1225
- }
1226
- if (ch === "'") {
1279
+ const code = formula.charCodeAt(i);
1280
+ if (code === 34 || code === 39) {
1227
1281
  let j = i + 1;
1228
- for (; j < n; j++) if (formula[j] === "'") {
1229
- if (formula[j + 1] === "'") j++;
1282
+ for (; j < n; j++) if (formula.charCodeAt(j) === code) {
1283
+ if (formula.charCodeAt(j + 1) === code) j++;
1230
1284
  else break;
1231
1285
  }
1232
- out += formula.slice(i, j + 1);
1233
1286
  i = j + 1;
1234
1287
  continue;
1235
1288
  }
1236
- if (ch === "[") {
1289
+ if (code === 91) {
1237
1290
  let depth = 0;
1238
1291
  let j = i;
1239
- for (; j < n; j++) if (formula[j] === "[") depth++;
1240
- else if (formula[j] === "]" && --depth === 0) break;
1241
- out += formula.slice(i, j + 1);
1292
+ for (; j < n; j++) {
1293
+ const c = formula.charCodeAt(j);
1294
+ if (c === 91) depth++;
1295
+ else if (c === 93 && --depth === 0) break;
1296
+ }
1242
1297
  i = j + 1;
1243
1298
  continue;
1244
1299
  }
1245
- const prev = i > 0 ? formula[i - 1] : void 0;
1246
- if ((ch === "$" || /[A-Za-z0-9]/.test(ch)) && !isWordChar(prev) && prev !== "$") {
1247
- const shifted = tryRef(formula, i, dRow, dCol);
1248
- if (shifted === null) return void 0;
1249
- if (shifted !== void 0) {
1250
- out += shifted.text;
1251
- i = shifted.end;
1300
+ const prev = i > 0 ? formula.charCodeAt(i - 1) : -1;
1301
+ if ((code === 36 || isAlnumCode(code)) && !isWordCode(prev) && prev !== 36) {
1302
+ const ref = parseRef$1(formula, i);
1303
+ if (ref) {
1304
+ const r = ref.ref;
1305
+ if (!boundsOnly) {
1306
+ segs.push(formula.slice(segStart, i));
1307
+ refs.push(r);
1308
+ }
1309
+ if (r.kind === COLS_REF) {
1310
+ relCol(r.aAnchor, r.a);
1311
+ relCol(r.bAnchor, r.b);
1312
+ } else if (r.kind === ROWS_REF) {
1313
+ relRow(r.aAnchor, r.a);
1314
+ relRow(r.bAnchor, r.b);
1315
+ } else {
1316
+ relCol(r.aAnchor, r.a);
1317
+ relRow(r.bAnchor, r.b);
1318
+ }
1319
+ i = segStart = ref.end;
1252
1320
  continue;
1253
1321
  }
1254
1322
  let j = i + 1;
1255
- while (j < n && isWordChar(formula[j])) j++;
1256
- out += formula.slice(i, j);
1323
+ while (j < n && isWordCode(formula.charCodeAt(j))) j++;
1257
1324
  i = j;
1258
1325
  continue;
1259
1326
  }
1260
- out += ch;
1261
1327
  i++;
1262
1328
  }
1263
- return out;
1264
- }
1265
- /** A reference at `i`: { text, end }, undefined if there is none, null if shifting fails. */
1266
- function tryRef(f, i, dRow, dCol) {
1267
- const after = (end) => f[end];
1268
- const isEnd = (end) => {
1269
- const c = after(end);
1270
- return c === void 0 || !(isWordChar(c) || c === "(" || c === "!" || c === "$");
1329
+ if (boundsOnly) return {
1330
+ source: formula,
1331
+ segs: [],
1332
+ slots: [],
1333
+ uniq: [],
1334
+ literalLength: 0,
1335
+ rowMin,
1336
+ rowMax,
1337
+ colMin,
1338
+ colMax
1271
1339
  };
1272
- COLS.lastIndex = i;
1273
- let m = COLS.exec(f);
1274
- if (m && isEnd(COLS.lastIndex)) {
1275
- const a = shiftPart(m[1], colNumber(m[2]), dCol, MAX_COL);
1276
- const b = shiftPart(m[3], colNumber(m[4]), dCol, MAX_COL);
1277
- if (colNumber(m[2]) > MAX_COL || colNumber(m[4]) > MAX_COL) return void 0;
1278
- if (a === void 0 || b === void 0) return null;
1279
- return {
1280
- text: `${m[1]}${colLetters(a)}:${m[3]}${colLetters(b)}`,
1281
- end: COLS.lastIndex
1282
- };
1340
+ segs.push(formula.slice(segStart));
1341
+ const outSegs = [segs[0]];
1342
+ const slots = [];
1343
+ const uniq = [];
1344
+ const index = /* @__PURE__ */ new Map();
1345
+ for (let k = 0; k < refs.length; k++) {
1346
+ const r = refs[k];
1347
+ const next = segs[k + 1];
1348
+ if (r.aAnchor === "$" && r.bAnchor === "$") {
1349
+ outSegs[outSegs.length - 1] += refText(r, 0, 0) + next;
1350
+ continue;
1351
+ }
1352
+ const key = `${r.kind}${r.aAnchor}${r.a},${r.bAnchor}${r.b}`;
1353
+ let u = index.get(key);
1354
+ if (u === void 0) {
1355
+ u = uniq.length;
1356
+ uniq.push(r);
1357
+ index.set(key, u);
1358
+ }
1359
+ slots.push(u);
1360
+ outSegs.push(next);
1283
1361
  }
1284
- ROWS.lastIndex = i;
1285
- m = ROWS.exec(f);
1286
- if (m && isEnd(ROWS.lastIndex)) {
1287
- const a = shiftPart(m[1], Number(m[2]), dRow, MAX_ROW);
1288
- const b = shiftPart(m[3], Number(m[4]), dRow, MAX_ROW);
1289
- if (a === void 0 || b === void 0) return null;
1290
- return {
1291
- text: `${m[1]}${a}:${m[3]}${b}`,
1292
- end: ROWS.lastIndex
1293
- };
1362
+ let literalLength = 0;
1363
+ for (const t of outSegs) literalLength += t.length;
1364
+ return {
1365
+ source: formula,
1366
+ segs: outSegs,
1367
+ slots,
1368
+ uniq,
1369
+ literalLength,
1370
+ rowMin,
1371
+ rowMax,
1372
+ colMin,
1373
+ colMax
1374
+ };
1375
+ }
1376
+ /** Column letters, cached: shifted references format the same columns over and over. */
1377
+ const LETTERS = [];
1378
+ function letters(n) {
1379
+ return LETTERS[n] ??= colLetters(n);
1380
+ }
1381
+ /** The text of `r` shifted by (dRow, dCol); every relative part must stay on the sheet (canShift). */
1382
+ function refText(r, dRow, dCol) {
1383
+ if (r.kind === COLS_REF) return `${r.aAnchor}${letters(shiftPart(r.aAnchor, r.a, dCol, MAX_COL))}:${r.bAnchor}${letters(shiftPart(r.bAnchor, r.b, dCol, MAX_COL))}`;
1384
+ if (r.kind === ROWS_REF) return `${r.aAnchor}${shiftPart(r.aAnchor, r.a, dRow, MAX_ROW)}:${r.bAnchor}${shiftPart(r.bAnchor, r.b, dRow, MAX_ROW)}`;
1385
+ return `${r.aAnchor}${letters(shiftPart(r.aAnchor, r.a, dCol, MAX_COL))}${r.bAnchor}${shiftPart(r.bAnchor, r.b, dRow, MAX_ROW)}`;
1386
+ }
1387
+ /** Whether every relative reference of `c` stays on the sheet when shifted by (dRow, dCol). Constant time. */
1388
+ function canShift(c, dRow, dCol) {
1389
+ if (dRow === 0 && dCol === 0) return true;
1390
+ if (c.rowMin !== 1e400 && (c.rowMin + dRow < 1 || c.rowMax + dRow > MAX_ROW)) return false;
1391
+ if (c.colMin !== 1e400 && (c.colMin + dCol < 1 || c.colMax + dCol > MAX_COL)) return false;
1392
+ return true;
1393
+ }
1394
+ /**
1395
+ * The text of `c` shifted by (dRow, dCol), built once as a flat string; or,
1396
+ * when that text would be longer than `maxLength`, its length (nothing is
1397
+ * built). The caller checks `canShift` first.
1398
+ */
1399
+ function shiftCompiled(c, dRow, dCol, maxLength = 1e400) {
1400
+ if (dRow === 0 && dCol === 0) return c.source.length > maxLength ? c.source.length : c.source;
1401
+ const { segs, slots, uniq } = c;
1402
+ const texts = [];
1403
+ for (let u = 0; u < uniq.length; u++) texts.push(refText(uniq[u], dRow, dCol));
1404
+ let length = c.literalLength;
1405
+ for (let k = 0; k < slots.length; k++) length += texts[slots[k]].length;
1406
+ if (length > maxLength) return length;
1407
+ const parts = [segs[0]];
1408
+ for (let k = 0; k < slots.length; k++) parts.push(texts[slots[k]], segs[k + 1]);
1409
+ const out = parts.join("");
1410
+ shiftWork.shifts++;
1411
+ shiftWork.shiftedChars += out.length;
1412
+ return out;
1413
+ }
1414
+ /** Whether a reference may end before `end`: no word character, `(`, `!` or `$` follows. */
1415
+ function isEnd(f, end) {
1416
+ if (end >= f.length) return true;
1417
+ const c = f.charCodeAt(end);
1418
+ return !(isWordCode(c) || c === 40 || c === 33 || c === 36);
1419
+ }
1420
+ /** A reference at `i`, or undefined if there is none. Does not depend on the offset. */
1421
+ function parseRef$1(f, i) {
1422
+ const n = f.length;
1423
+ const aAnchor = f.charCodeAt(i) === 36 ? "$" : "";
1424
+ const p = i + aAnchor.length;
1425
+ const la = run(f, p, isLetterCode, 3);
1426
+ const da = la === 0 ? run(f, p, isDigitCode, 7) : 0;
1427
+ const first = la || da;
1428
+ if (first > 0 && f.charCodeAt(p + first) === 58) {
1429
+ const q = p + first + 1;
1430
+ const bAnchor = q < n && f.charCodeAt(q) === 36 ? "$" : "";
1431
+ const r = q + bAnchor.length;
1432
+ const second = run(f, r, la ? isLetterCode : isDigitCode, la ? 3 : 7);
1433
+ if (second > 0 && isEnd(f, r + second)) {
1434
+ if (la) {
1435
+ const a = colNumber(f.slice(p, p + la));
1436
+ const b = colNumber(f.slice(r, r + second));
1437
+ if (a > MAX_COL || b > MAX_COL) return void 0;
1438
+ return {
1439
+ ref: {
1440
+ kind: COLS_REF,
1441
+ aAnchor,
1442
+ a,
1443
+ bAnchor,
1444
+ b
1445
+ },
1446
+ end: r + second
1447
+ };
1448
+ }
1449
+ return {
1450
+ ref: {
1451
+ kind: ROWS_REF,
1452
+ aAnchor,
1453
+ a: Number(f.slice(p, p + da)),
1454
+ bAnchor,
1455
+ b: Number(f.slice(r, r + second))
1456
+ },
1457
+ end: r + second
1458
+ };
1459
+ }
1294
1460
  }
1295
- CELL.lastIndex = i;
1296
- m = CELL.exec(f);
1297
- if (m && isEnd(CELL.lastIndex)) {
1298
- const parts = CELL_PARTS.exec(m[0]);
1299
- const col = colNumber(parts[2]);
1300
- if (col > MAX_COL) return void 0;
1301
- const c = shiftPart(parts[1], col, dCol, MAX_COL);
1302
- const r = shiftPart(parts[3], Number(parts[4]), dRow, MAX_ROW);
1303
- if (c === void 0 || r === void 0) return null;
1304
- return {
1305
- text: `${parts[1]}${colLetters(c)}${parts[3]}${r}`,
1306
- end: CELL.lastIndex
1307
- };
1461
+ if (la > 0) {
1462
+ const q = p + la;
1463
+ const bAnchor = f.charCodeAt(q) === 36 ? "$" : "";
1464
+ const r = q + bAnchor.length;
1465
+ const digits = run(f, r, isDigitCode, 7);
1466
+ if (digits > 0 && isEnd(f, r + digits)) {
1467
+ const col = colNumber(f.slice(p, p + la));
1468
+ if (col > MAX_COL) return void 0;
1469
+ return {
1470
+ ref: {
1471
+ kind: CELL_REF,
1472
+ aAnchor,
1473
+ a: col,
1474
+ bAnchor,
1475
+ b: Number(f.slice(r, r + digits))
1476
+ },
1477
+ end: r + digits
1478
+ };
1479
+ }
1308
1480
  }
1309
1481
  }
1482
+ function isLetterCode(c) {
1483
+ return c >= 65 && c <= 90 || c >= 97 && c <= 122;
1484
+ }
1485
+ function isDigitCode(c) {
1486
+ return c >= 48 && c <= 57;
1487
+ }
1488
+ /** Length of the run of `test` characters at `i`, at most `max` (a longer run then fails on the character after: no pattern accepts it there). */
1489
+ function run(f, i, test, max) {
1490
+ let k = 0;
1491
+ while (k < max && i + k < f.length && test(f.charCodeAt(i + k))) k++;
1492
+ return k;
1493
+ }
1310
1494
  function shiftPart(anchor, value, delta, max) {
1311
1495
  if (anchor === "$") return value;
1312
1496
  const v = value + delta;
@@ -1786,15 +1970,105 @@ function decodeXstring(s) {
1786
1970
  return s.replace(/_x([0-9A-Fa-f]{4})_/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
1787
1971
  }
1788
1972
  /**
1973
+ * The length a text will have once `decodeXstring` has run on it, counted
1974
+ * chunk by chunk as the text streams in (JSE-58), so a cell's text can be
1975
+ * refused before it is held whole. `committed` never exceeds the final
1976
+ * length: up to six trailing characters that may start an escape are held
1977
+ * back until the next chunk or `end()`. With `decode` false the text is
1978
+ * counted as it is (`<v>` of number, date, error and boolean cells).
1979
+ */
1980
+ var XstringLength = class {
1981
+ decode;
1982
+ /** Characters known so far. */
1983
+ committed = 0;
1984
+ tail = "";
1985
+ constructor(decode = true) {
1986
+ this.decode = decode;
1987
+ }
1988
+ add(chunk) {
1989
+ if (!this.decode) {
1990
+ this.committed += chunk.length;
1991
+ return;
1992
+ }
1993
+ const s = this.tail.length ? this.tail + chunk : chunk;
1994
+ const n = s.length;
1995
+ let i = 0;
1996
+ let escapes = 0;
1997
+ for (let j = s.indexOf("_x"); j !== -1 && j + 7 <= n; j = s.indexOf("_x", i)) if (isHex(s.charCodeAt(j + 2)) && isHex(s.charCodeAt(j + 3)) && isHex(s.charCodeAt(j + 4)) && isHex(s.charCodeAt(j + 5)) && s.charCodeAt(j + 6) === 95) {
1998
+ escapes++;
1999
+ i = j + 7;
2000
+ } else i = j + 1;
2001
+ const cut = Math.max(i, n - 6);
2002
+ this.committed += cut - 6 * escapes;
2003
+ this.tail = cut < n ? s.slice(cut) : "";
2004
+ }
2005
+ /** Settles the held-back characters and returns the final length. */
2006
+ end() {
2007
+ this.committed += this.tail.length;
2008
+ this.tail = "";
2009
+ return this.committed;
2010
+ }
2011
+ };
2012
+ function isHex(c) {
2013
+ return c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102;
2014
+ }
2015
+ /** The LimitError for a cell's text over maxCellTextLength; `value` is max + 1, "more than max" (JSE-58). */
2016
+ function cellTextTooLong(max, details = {}) {
2017
+ const where = typeof details["ref"] === "string" && details["ref"] !== "" ? `Cell ${details["ref"]}: its` : "A cell's";
2018
+ return new require_errors.LimitError("LIMIT_EXCEEDED", `${where} text is longer than maxCellTextLength (${max}) characters.`, { details: {
2019
+ limit: "maxCellTextLength",
2020
+ value: max + 1,
2021
+ max,
2022
+ ...details
2023
+ } });
2024
+ }
2025
+ /**
2026
+ * Counts text the reader keeps outside cells (header and footer text, a
2027
+ * defined name's formula, a document property's value) against
2028
+ * maxCellTextLength as it streams in, so it is refused before it is held
2029
+ * whole (JSE-58 review). This text is kept as written, so it is counted as
2030
+ * written. `what` names it in the error message.
2031
+ */
2032
+ var TextBudget = class {
2033
+ max;
2034
+ what;
2035
+ n = 0;
2036
+ constructor(max, what) {
2037
+ this.max = max;
2038
+ this.what = what;
2039
+ }
2040
+ add(s) {
2041
+ this.n += s.length;
2042
+ if (this.n > this.max) throw new require_errors.LimitError("LIMIT_EXCEEDED", `${this.what} is longer than maxCellTextLength (${this.max}) characters.`, { details: {
2043
+ limit: "maxCellTextLength",
2044
+ value: this.max + 1,
2045
+ max: this.max
2046
+ } });
2047
+ }
2048
+ };
2049
+ /**
1789
2050
  * Collects one string item (<si> or <is>). Feed it the events between the
1790
2051
  * item's open and close; `value()` gives the string or rich text.
1791
2052
  */
1792
2053
  var StringItem = class {
1793
2054
  charge;
1794
- /** @param charge Counts each run after the first against the read's maxItems budget (JSE-52). */
1795
- constructor(charge = () => {}) {
2055
+ max;
2056
+ details;
2057
+ /**
2058
+ * @param charge Counts each run after the first against the read's maxItems budget (JSE-52).
2059
+ * @param max maxCellTextLength: the item's text (all runs together, after decoding) may not be
2060
+ * longer; checked as the text arrives, so a longer item is refused before it is held whole (JSE-58).
2061
+ * @param details Extra `details` for the LimitError (a sheet cell's `ref`).
2062
+ */
2063
+ constructor(charge = () => {}, max = 1e400, details = {}) {
1796
2064
  this.charge = charge;
2065
+ this.max = max;
2066
+ this.details = details;
1797
2067
  }
2068
+ /** Decoded length of the plain text and of the current run; finished runs are in `runsLength`. */
2069
+ plainLength = new XstringLength();
2070
+ runLength = new XstringLength();
2071
+ runsLength = 0;
1798
2072
  runs = [];
1799
2073
  plain = "";
1800
2074
  hasRuns = false;
@@ -1817,6 +2091,7 @@ var StringItem = class {
1817
2091
  this.inRun = true;
1818
2092
  this.hasRuns = true;
1819
2093
  this.runText = "";
2094
+ this.runLength = new XstringLength();
1820
2095
  this.font = void 0;
1821
2096
  return;
1822
2097
  case "rPr":
@@ -1842,6 +2117,8 @@ var StringItem = class {
1842
2117
  this.inRPr = false;
1843
2118
  return;
1844
2119
  case "r": {
2120
+ this.runsLength += this.runLength.end();
2121
+ this.check(0);
1845
2122
  if (this.runs.length > 0) this.charge(1);
1846
2123
  const run = { text: decodeXstring(this.runText) };
1847
2124
  if (this.font && Object.keys(this.font.font).length) run.font = this.font.font;
@@ -1854,10 +2131,23 @@ var StringItem = class {
1854
2131
  }
1855
2132
  text(s) {
1856
2133
  if (!this.inT || this.inRPh > 0) return;
1857
- if (this.inRun) this.runText += s;
1858
- else this.plain += s;
2134
+ if (this.inRun) {
2135
+ this.runLength.add(s);
2136
+ this.check(this.runLength.committed);
2137
+ this.runText += s;
2138
+ } else {
2139
+ this.plainLength.add(s);
2140
+ this.check(0);
2141
+ this.plain += s;
2142
+ }
2143
+ }
2144
+ /** Throws once the text known so far (`current`: the open run's) is longer than max. */
2145
+ check(current) {
2146
+ if (this.plainLength.committed + this.runsLength + current > this.max) throw cellTextTooLong(this.max, this.details);
1859
2147
  }
1860
2148
  value(mode) {
2149
+ this.plainLength.end();
2150
+ this.check(0);
1861
2151
  if (!this.hasRuns) return decodeXstring(this.plain);
1862
2152
  if (mode === "plain") return this.runs.map((r) => r.text).join("");
1863
2153
  return { richText: this.runs };
@@ -1869,6 +2159,7 @@ var SharedStringsParser = class {
1869
2159
  max;
1870
2160
  stopAfter;
1871
2161
  charge;
2162
+ maxText;
1872
2163
  strings = [];
1873
2164
  item;
1874
2165
  depth = 0;
@@ -1877,11 +2168,12 @@ var SharedStringsParser = class {
1877
2168
  * `stopAfter`: decode only the first `stopAfter` items, then jump to the
1878
2169
  * end of the part without tokenizing the rest (previews, ReadOptions.maxRows).
1879
2170
  */
1880
- constructor(mode, max, stopAfter = 1e400, charge = () => {}) {
2171
+ constructor(mode, max, stopAfter = 1e400, charge = () => {}, maxText = 1e400) {
1881
2172
  this.mode = mode;
1882
2173
  this.max = max;
1883
2174
  this.stopAfter = stopAfter;
1884
2175
  this.charge = charge;
2176
+ this.maxText = maxText;
1885
2177
  }
1886
2178
  attach(control) {
1887
2179
  this.control = control;
@@ -1916,7 +2208,7 @@ var SharedStringsParser = class {
1916
2208
  this.strings.push("");
1917
2209
  this.pushed();
1918
2210
  } else {
1919
- this.item = new StringItem(this.charge);
2211
+ this.item = new StringItem(this.charge, this.maxText);
1920
2212
  this.depth = 0;
1921
2213
  }
1922
2214
  }
@@ -2077,6 +2369,7 @@ var SheetParser = class {
2077
2369
  colWork = 0;
2078
2370
  merges = [];
2079
2371
  hyperlinks = [];
2372
+ /** Shared formula masters by `si`; compiled when the first cell that shares one needs it. */
2080
2373
  shared = /* @__PURE__ */ new Map();
2081
2374
  view;
2082
2375
  print;
@@ -2141,7 +2434,7 @@ var SheetParser = class {
2141
2434
  return;
2142
2435
  case "is":
2143
2436
  if (this.cell && !empty) {
2144
- this.inline = new StringItem((n) => this.ctx.charge(n));
2437
+ this.inline = new StringItem((n) => this.ctx.charge(n), this.ctx.limits.maxCellTextLength, this.cell.ref ? { ref: this.cell.ref } : {});
2145
2438
  this.inlineDepth = 0;
2146
2439
  }
2147
2440
  return;
@@ -2247,10 +2540,12 @@ var SheetParser = class {
2247
2540
  this.path.pop();
2248
2541
  switch (name) {
2249
2542
  case "v":
2543
+ this.endText();
2250
2544
  if (this.cell && this.textTarget === "v") this.cell.v = this.buf;
2251
2545
  this.textTarget = void 0;
2252
2546
  return;
2253
2547
  case "f":
2548
+ this.endText();
2254
2549
  if (this.cell && this.textTarget === "f") this.cell.f = decodeXstring(this.buf);
2255
2550
  this.textTarget = void 0;
2256
2551
  return;
@@ -2276,11 +2571,38 @@ var SheetParser = class {
2276
2571
  this.inline.text(s);
2277
2572
  return;
2278
2573
  }
2279
- if (this.textTarget) this.buf += s;
2574
+ if (!this.textTarget) return;
2575
+ if (this.textTarget === "hf") this.hfBudget?.add(s);
2576
+ const len = this.textLength;
2577
+ if (len) {
2578
+ len.add(s);
2579
+ if (len.committed > this.ctx.limits.maxCellTextLength) this.textTooLong();
2580
+ }
2581
+ this.buf += s;
2582
+ }
2583
+ /**
2584
+ * Counts the text of a cell's `<v>` or `<f>` against maxCellTextLength as it
2585
+ * arrives (JSE-58), decoded as the cell's value will be: `_xHHHH_` escapes
2586
+ * count once in strings and formulas; other `<v>` text is kept as written.
2587
+ * Header and footer text is not cell text.
2588
+ */
2589
+ textLength;
2590
+ hfBudget;
2591
+ endText() {
2592
+ const len = this.textLength;
2593
+ this.textLength = void 0;
2594
+ if (len && len.end() > this.ctx.limits.maxCellTextLength) this.textTooLong();
2595
+ }
2596
+ textTooLong() {
2597
+ const ref = this.cell?.ref;
2598
+ throw cellTextTooLong(this.ctx.limits.maxCellTextLength, ref ? { ref } : {});
2280
2599
  }
2281
2600
  startText(target) {
2282
2601
  this.textTarget = target;
2283
2602
  this.buf = "";
2603
+ const t = this.cell?.t;
2604
+ this.textLength = target === "hf" ? void 0 : new XstringLength(target === "f" || t === "str" || t === "inlineStr");
2605
+ this.hfBudget = target === "hf" ? new TextBudget(this.ctx.limits.maxCellTextLength, "Header or footer text") : void 0;
2284
2606
  }
2285
2607
  openRow(a) {
2286
2608
  const r = int(a.get("r"));
@@ -2396,7 +2718,7 @@ var SheetParser = class {
2396
2718
  if (r !== void 0) {
2397
2719
  const pos = parseRef(r);
2398
2720
  if (!pos) {
2399
- this.ctx.warn("INVALID_CELL_REF", `Cell reference "${r}" is not valid; the cell was skipped.`, {
2721
+ this.ctx.warn("INVALID_CELL_REF", `Cell reference "${excerpt(r)}" is not valid; the cell was skipped.`, {
2400
2722
  part: this.part,
2401
2723
  sheet: this.sheet.name
2402
2724
  });
@@ -2413,7 +2735,7 @@ var SheetParser = class {
2413
2735
  return;
2414
2736
  }
2415
2737
  if (row >= 1048576 || col >= 16384) {
2416
- this.ctx.warn("CELL_OUT_OF_BOUNDS", `Cell ${r ?? `${colLetters(col + 1)}${row + 1}`} is beyond the format limits; it was skipped.`, {
2738
+ this.ctx.warn("CELL_OUT_OF_BOUNDS", `Cell ${excerpt(r ?? `${colLetters(col + 1)}${row + 1}`)} is beyond the format limits; it was skipped.`, {
2417
2739
  part: this.part,
2418
2740
  sheet: this.sheet.name
2419
2741
  });
@@ -2439,7 +2761,7 @@ var SheetParser = class {
2439
2761
  truncate() {
2440
2762
  if (this.truncated) return;
2441
2763
  this.truncated = true;
2442
- this.ctx.warn("ROWS_TRUNCATED", `Sheet "${this.sheet.name}" has rows beyond maxRows (${this.opts.maxRows}); they were not read.`, {
2764
+ this.ctx.warn("ROWS_TRUNCATED", `Sheet "${excerpt(this.sheet.name)}" has rows beyond maxRows (${this.opts.maxRows}); they were not read.`, {
2443
2765
  part: this.part,
2444
2766
  sheet: this.sheet.name
2445
2767
  });
@@ -2474,6 +2796,7 @@ var SheetParser = class {
2474
2796
  if (p.row < 0) return;
2475
2797
  const cell = this.convert(p);
2476
2798
  if (!cell) return;
2799
+ if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref);
2477
2800
  this.ctx.countCell();
2478
2801
  let row = this.rows[p.row];
2479
2802
  if (!row) row = this.rows[p.row] = [];
@@ -2500,6 +2823,20 @@ var SheetParser = class {
2500
2823
  if (p.col < this.minCol) this.minCol = p.col;
2501
2824
  if (p.col > this.maxCol) this.maxCol = p.col;
2502
2825
  }
2826
+ /**
2827
+ * A kept cell in a column past maxColumns (JSE-68). Counted on the cells the
2828
+ * sheet actually has, as each is kept, never on `<dimension>`.
2829
+ */
2830
+ tooWide(col, ref) {
2831
+ const max = this.ctx.limits.maxColumns;
2832
+ throw new require_errors.LimitError("LIMIT_EXCEEDED", `Sheet "${excerpt(this.sheet.name)}" has a cell in column ${colLetters(col + 1)} (${col + 1}); maxColumns is ${max}.`, { details: {
2833
+ limit: "maxColumns",
2834
+ value: col + 1,
2835
+ max,
2836
+ part: this.part,
2837
+ ref
2838
+ } });
2839
+ }
2503
2840
  convert(p) {
2504
2841
  const style = this.styles.style(p.s);
2505
2842
  let value;
@@ -2521,7 +2858,8 @@ var SheetParser = class {
2521
2858
  const sst = this.sharedStrings;
2522
2859
  const str = Number.isInteger(idx) && idx >= 0 ? sst[idx] : void 0;
2523
2860
  if (str === void 0) {
2524
- this.ctx.warn("INVALID_SHARED_STRING", `Cell ${p.ref} refers to shared string ${v}, which does not exist; the cell was left empty.`, {
2861
+ if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref);
2862
+ this.ctx.warn("INVALID_SHARED_STRING", `Cell ${p.ref} refers to shared string ${excerpt(v)}, which does not exist; the cell was left empty.`, {
2525
2863
  part: this.part,
2526
2864
  sheet: this.sheet.name,
2527
2865
  ref: p.ref
@@ -2624,21 +2962,33 @@ var SheetParser = class {
2624
2962
  this.shared.set(p.fSi, {
2625
2963
  formula: p.f,
2626
2964
  row: p.row,
2627
- col: p.col
2965
+ col: p.col,
2966
+ ref: p.ref,
2967
+ compiled: void 0
2628
2968
  });
2629
2969
  return { text: p.f };
2630
2970
  }
2631
2971
  const master = this.shared.get(p.fSi);
2632
- const shifted = master ? shiftFormula(master.formula, p.row - master.row, p.col - master.col) : void 0;
2633
- if (shifted === void 0) {
2634
- this.ctx.warn("SHARED_FORMULA_UNRESOLVED", `The shared formula of cell ${p.ref} could not be resolved; only its cached value was read.`, {
2635
- part: this.part,
2636
- sheet: this.sheet.name,
2637
- ref: p.ref
2638
- });
2972
+ const masterText = this.opts.sharedFormulaText === "master";
2973
+ if (master && !masterText && master.formula.length > 8192) {
2974
+ this.unresolved(p, `: its master formula in cell ${master.ref} has ${master.formula.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`);
2975
+ return;
2976
+ }
2977
+ const dRow = master ? p.row - master.row : 0;
2978
+ const dCol = master ? p.col - master.col : 0;
2979
+ const compiled = master && (dRow !== 0 || dCol !== 0) ? master.compiled ??= compileFormula(master.formula, masterText) : void 0;
2980
+ if (!master || compiled && !canShift(compiled, dRow, dCol)) {
2981
+ this.unresolved(p, "");
2982
+ return;
2983
+ }
2984
+ if (!compiled || masterText) return { text: master.formula };
2985
+ const max = this.ctx.limits.maxCellTextLength;
2986
+ const text = shiftCompiled(compiled, dRow, dCol, max);
2987
+ if (typeof text === "number") {
2988
+ this.unresolved(p, `: shifted, it would have ${text} characters, more than maxCellTextLength (${max})`);
2639
2989
  return;
2640
2990
  }
2641
- return { text: shifted };
2991
+ return { text };
2642
2992
  }
2643
2993
  if (p.fType === "dataTable") return void 0;
2644
2994
  if (p.f === "") return void 0;
@@ -2648,6 +2998,13 @@ var SheetParser = class {
2648
2998
  };
2649
2999
  return { text: p.f };
2650
3000
  }
3001
+ unresolved(p, why) {
3002
+ this.ctx.warn("SHARED_FORMULA_UNRESOLVED", `The shared formula of cell ${p.ref} could not be resolved${why}; only its cached value was read.`, {
3003
+ part: this.part,
3004
+ sheet: this.sheet.name,
3005
+ ref: p.ref
3006
+ });
3007
+ }
2651
3008
  /** Set before parsing; the shared strings table. */
2652
3009
  sharedStrings = [];
2653
3010
  /** When set, shared-string cells are collected here and filled in later (ReadOptions.maxRows). */
@@ -2777,7 +3134,7 @@ var SheetParser = class {
2777
3134
  const first = h.ref.split(":")[0];
2778
3135
  const pos = parseRef(first);
2779
3136
  if (!pos) return;
2780
- if (h.ref.includes(":") && h.ref.split(":")[1] !== first) this.ctx.warn("HYPERLINK_RANGE_REDUCED", `The hyperlink on ${h.ref} was attached to its top-left cell ${first}.`, {
3137
+ if (h.ref.includes(":") && h.ref.split(":")[1] !== first) this.ctx.warn("HYPERLINK_RANGE_REDUCED", `The hyperlink on ${excerpt(h.ref)} was attached to its top-left cell ${excerpt(first)}.`, {
2781
3138
  part: this.part,
2782
3139
  sheet: this.sheet.name,
2783
3140
  ref: h.ref
@@ -2799,6 +3156,7 @@ var SheetParser = class {
2799
3156
  if (!link) return;
2800
3157
  const [r, c] = pos;
2801
3158
  if (r >= 1048576 || c >= 16384) return;
3159
+ if (c >= this.ctx.limits.maxColumns) this.tooWide(c, `${colLetters(c + 1)}${r + 1}`);
2802
3160
  let row = this.rows[r];
2803
3161
  if (!row) row = this.rows[r] = [];
2804
3162
  const cell = row[c] ?? (row[c] = { type: "empty" });
@@ -2810,6 +3168,7 @@ var WorkbookParser = class {
2810
3168
  part;
2811
3169
  checkAbort;
2812
3170
  charge;
3171
+ maxText;
2813
3172
  sheets = [];
2814
3173
  definedNames = [];
2815
3174
  date1904 = false;
@@ -2825,12 +3184,14 @@ var WorkbookParser = class {
2825
3184
  * @param part The workbook part's name, for the error.
2826
3185
  * @param checkAbort Called every SHEET_ABORT_INTERVAL sheet entries, so a long sheet list cannot outrun the signal.
2827
3186
  */
2828
- constructor(maxSheets = 1e400, part = "", checkAbort, charge = () => {}) {
3187
+ constructor(maxSheets = 1e400, part = "", checkAbort, charge = () => {}, maxText = 1e400) {
2829
3188
  this.maxSheets = maxSheets;
2830
3189
  this.part = part;
2831
3190
  this.checkAbort = checkAbort;
2832
3191
  this.charge = charge;
3192
+ this.maxText = maxText;
2833
3193
  }
3194
+ nameBudget;
2834
3195
  open(name, a, empty) {
2835
3196
  switch (name) {
2836
3197
  case "workbook":
@@ -2889,13 +3250,16 @@ var WorkbookParser = class {
2889
3250
  }
2890
3251
  close(name) {
2891
3252
  if (name === "definedName" && this.name) {
3253
+ this.nameBudget = void 0;
2892
3254
  this.name.ref = this.nameText;
2893
3255
  this.definedNames.push(this.name);
2894
3256
  this.name = void 0;
2895
3257
  }
2896
3258
  }
2897
3259
  text(s) {
2898
- if (this.name) this.nameText += s;
3260
+ if (!this.name) return;
3261
+ (this.nameBudget ??= new TextBudget(this.maxText, `The formula of defined name "${excerpt(this.name.name)}"`)).add(s);
3262
+ this.nameText += s;
2899
3263
  }
2900
3264
  };
2901
3265
  const SCHEME_ORDER = [
@@ -2963,18 +3327,23 @@ const CORE_FIELDS = {
2963
3327
  /** docProps/core.xml and docProps/app.xml: simple elements with text. */
2964
3328
  var PropsParser = class {
2965
3329
  props;
3330
+ maxText;
2966
3331
  field;
2967
3332
  value = "";
2968
3333
  depth = 0;
2969
- constructor(props) {
3334
+ /** @param maxText maxCellTextLength, for each property's value (JSE-58 review). */
3335
+ constructor(props, maxText = 1e400) {
2970
3336
  this.props = props;
3337
+ this.maxText = maxText;
2971
3338
  }
3339
+ budget;
2972
3340
  open(name, _a, empty) {
2973
3341
  if (empty) return;
2974
3342
  this.depth++;
2975
3343
  if (this.depth === 2 && Object.prototype.hasOwnProperty.call(CORE_FIELDS, name)) {
2976
3344
  this.field = CORE_FIELDS[name];
2977
3345
  this.value = "";
3346
+ this.budget = new TextBudget(this.maxText, `Document property ${name}`);
2978
3347
  }
2979
3348
  }
2980
3349
  close() {
@@ -2990,17 +3359,23 @@ var PropsParser = class {
2990
3359
  this.depth--;
2991
3360
  }
2992
3361
  text(s) {
2993
- if (this.field) this.value += s;
3362
+ if (!this.field) return;
3363
+ this.budget?.add(s);
3364
+ this.value += s;
2994
3365
  }
2995
3366
  };
2996
3367
  /** docProps/custom.xml. */
2997
3368
  var CustomPropsParser = class {
2998
3369
  charge;
3370
+ maxText;
2999
3371
  items = [];
3000
3372
  /** @param charge Counts each property kept against the read's maxItems budget (JSE-52). */
3001
- constructor(charge = () => {}) {
3373
+ /** @param maxText maxCellTextLength, for each property's value (JSE-58 review). */
3374
+ constructor(charge = () => {}, maxText = 1e400) {
3002
3375
  this.charge = charge;
3376
+ this.maxText = maxText;
3003
3377
  }
3378
+ budget;
3004
3379
  name;
3005
3380
  kind;
3006
3381
  value = "";
@@ -3011,6 +3386,7 @@ var CustomPropsParser = class {
3011
3386
  } else if (this.name !== void 0 && this.kind === void 0) {
3012
3387
  this.kind = name;
3013
3388
  this.value = "";
3389
+ this.budget = new TextBudget(this.maxText, `Custom document property "${excerpt(this.name)}"`);
3014
3390
  }
3015
3391
  }
3016
3392
  close(name) {
@@ -3047,7 +3423,9 @@ var CustomPropsParser = class {
3047
3423
  this.kind = "";
3048
3424
  }
3049
3425
  text(s) {
3050
- if (this.kind) this.value += s;
3426
+ if (!this.kind) return;
3427
+ this.budget?.add(s);
3428
+ this.value += s;
3051
3429
  }
3052
3430
  };
3053
3431
  // src/internal/read/reader.ts
@@ -3127,7 +3505,7 @@ function openZipChecked(bytes, limits) {
3127
3505
  }
3128
3506
  async function parseWorkbook(pkg, part) {
3129
3507
  const ctx = pkg.ctx;
3130
- const wb = new WorkbookParser(ctx.limits.maxSheets, part, () => ctx.checkAbort(), (n) => ctx.charge(n));
3508
+ const wb = new WorkbookParser(ctx.limits.maxSheets, part, () => ctx.checkAbort(), (n) => ctx.charge(n), ctx.limits.maxCellTextLength);
3131
3509
  await ctx.parse(pkg.part(part), wb);
3132
3510
  return wb;
3133
3511
  }
@@ -3257,7 +3635,7 @@ async function readImpl(input, options, internal) {
3257
3635
  const stylesRel = relOf("styles");
3258
3636
  if (stylesRel) {
3259
3637
  const entry = pkg.part(stylesRel.target);
3260
- if (!entry) ctx.warn("MISSING_PART", `The styles part ${stylesRel.target} is missing; default styles were used.`, {
3638
+ if (!entry) ctx.warn("MISSING_PART", `The styles part ${excerpt(stylesRel.target)} is missing; default styles were used.`, {
3261
3639
  part: stylesRel.target,
3262
3640
  partKind: "styles"
3263
3641
  });
@@ -3275,7 +3653,7 @@ async function readImpl(input, options, internal) {
3275
3653
  const themeRel = relOf("theme");
3276
3654
  if (themeRel && o.styles !== false) {
3277
3655
  const entry = pkg.part(themeRel.target);
3278
- if (!entry) ctx.warn("MISSING_PART", `The theme part ${themeRel.target} is missing; the default theme applies.`, {
3656
+ if (!entry) ctx.warn("MISSING_PART", `The theme part ${excerpt(themeRel.target)} is missing; the default theme applies.`, {
3279
3657
  part: themeRel.target,
3280
3658
  partKind: "theme"
3281
3659
  });
@@ -3290,13 +3668,13 @@ async function readImpl(input, options, internal) {
3290
3668
  const sstRel = relOf("sharedStrings");
3291
3669
  if (sstRel) {
3292
3670
  const entry = pkg.part(sstRel.target);
3293
- if (!entry) ctx.warn("MISSING_PART", `The shared strings part ${sstRel.target} is missing; cells that use it are empty.`, {
3671
+ if (!entry) ctx.warn("MISSING_PART", `The shared strings part ${excerpt(sstRel.target)} is missing; cells that use it are empty.`, {
3294
3672
  part: sstRel.target,
3295
3673
  partKind: "sharedStrings"
3296
3674
  });
3297
3675
  else if (deferred) sstEntry = entry;
3298
3676
  else {
3299
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n));
3677
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n), limits.maxCellTextLength);
3300
3678
  await ctx.parse(entry, sp);
3301
3679
  sst = sp.strings;
3302
3680
  }
@@ -3318,6 +3696,7 @@ async function readImpl(input, options, internal) {
3318
3696
  const { entry, rel } = listed[i];
3319
3697
  const parser = new SheetParser(entry.name, entry.state, ctx, styles, {
3320
3698
  formulas: o.formulas !== false,
3699
+ sharedFormulaText: internal?.sharedFormulaText ?? "shifted",
3321
3700
  dates: o.dates ?? "date",
3322
3701
  dateZone: o.dateZone ?? "local",
3323
3702
  richText: o.richText ?? "runs",
@@ -3329,7 +3708,7 @@ async function readImpl(input, options, internal) {
3329
3708
  parser.deferred = deferred;
3330
3709
  const part = rel ? pkg.part(rel.target) : void 0;
3331
3710
  if (!part) {
3332
- ctx.warn("MISSING_PART", `The part for sheet "${entry.name}" is missing; the sheet is empty.`, {
3711
+ ctx.warn("MISSING_PART", `The part for sheet "${excerpt(entry.name)}" is missing; the sheet is empty.`, {
3333
3712
  sheet: entry.name,
3334
3713
  partKind: "worksheet"
3335
3714
  });
@@ -3363,7 +3742,7 @@ async function readImpl(input, options, internal) {
3363
3742
  if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name);
3364
3743
  if (deferred && deferred.cells.length > 0) {
3365
3744
  if (sstEntry) {
3366
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, deferred.maxIndex + 1, (n) => ctx.charge(n));
3745
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, deferred.maxIndex + 1, (n) => ctx.charge(n), limits.maxCellTextLength);
3367
3746
  await ctx.parse(sstEntry, sp);
3368
3747
  sst = sp.strings;
3369
3748
  }
@@ -3455,7 +3834,7 @@ async function optional(ctx, part, partKind, fn) {
3455
3834
  return true;
3456
3835
  } catch (err) {
3457
3836
  if (err instanceof require_errors.FormatError && err.code === "XML_MALFORMED") {
3458
- ctx.warn("BROKEN_OPTIONAL_PART", `${part} is not well-formed XML and was skipped.`, {
3837
+ ctx.warn("BROKEN_OPTIONAL_PART", `${excerpt(part)} is not well-formed XML and was skipped.`, {
3459
3838
  part,
3460
3839
  partKind
3461
3840
  });
@@ -3475,13 +3854,13 @@ async function readProperties(pkg, ctx) {
3475
3854
  const rel = rels.find((r) => (r.kind === kind || r.type.endsWith(`/${kind}`)) && !r.external);
3476
3855
  const entry = rel ? pkg.part(rel.target) : void 0;
3477
3856
  if (!entry) continue;
3478
- const handler = new PropsParser(props);
3857
+ const handler = new PropsParser(props, ctx.limits.maxCellTextLength);
3479
3858
  await optional(ctx, entry.name, partKind, () => ctx.parse(entry, handler));
3480
3859
  }
3481
3860
  const customRel = rels.find((r) => r.kind === "custom-properties" && !r.external);
3482
3861
  const custom = customRel ? pkg.part(customRel.target) : void 0;
3483
3862
  if (custom) {
3484
- const cp = new CustomPropsParser((n) => ctx.charge(n));
3863
+ const cp = new CustomPropsParser((n) => ctx.charge(n), ctx.limits.maxCellTextLength);
3485
3864
  if (await optional(ctx, custom.name, "customProperties", () => ctx.parse(custom, cp)) && cp.items.length) props.custom = cp.items;
3486
3865
  }
3487
3866
  return Object.keys(props).length ? props : void 0;
@@ -3505,6 +3884,12 @@ async function read(input, options) {
3505
3884
  warnings
3506
3885
  };
3507
3886
  }
3887
+ Object.defineProperty(exports, "DEFAULT_LIMITS", {
3888
+ enumerable: true,
3889
+ get: function() {
3890
+ return DEFAULT_LIMITS;
3891
+ }
3892
+ });
3508
3893
  Object.defineProperty(exports, "DEFAULT_READ_LIMITS", {
3509
3894
  enumerable: true,
3510
3895
  get: function() {
@@ -3517,12 +3902,30 @@ Object.defineProperty(exports, "detectFormat", {
3517
3902
  return detectFormat;
3518
3903
  }
3519
3904
  });
3905
+ Object.defineProperty(exports, "excerpt", {
3906
+ enumerable: true,
3907
+ get: function() {
3908
+ return excerpt;
3909
+ }
3910
+ });
3911
+ Object.defineProperty(exports, "quoted", {
3912
+ enumerable: true,
3913
+ get: function() {
3914
+ return quoted;
3915
+ }
3916
+ });
3520
3917
  Object.defineProperty(exports, "read", {
3521
3918
  enumerable: true,
3522
3919
  get: function() {
3523
3920
  return read;
3524
3921
  }
3525
3922
  });
3923
+ Object.defineProperty(exports, "readImpl", {
3924
+ enumerable: true,
3925
+ get: function() {
3926
+ return readImpl;
3927
+ }
3928
+ });
3526
3929
  Object.defineProperty(exports, "readSheetNames", {
3527
3930
  enumerable: true,
3528
3931
  get: function() {