javascript-excel 2.4.0 → 2.5.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.
Files changed (58) hide show
  1. package/README.md +4 -2
  2. package/dist/{address-DUn7-5OS.js → address-BGH42dEg.js} +1 -1
  3. package/dist/{address-DZBHchLv.cjs → address-DKd_3EGf.cjs} +1 -1
  4. package/dist/{csv-Dn4MIESx.js → csv-5jVhfM5l.js} +180 -33
  5. package/dist/{csv-DZ241Y5F.cjs → csv-BkVmMYQq.cjs} +180 -33
  6. package/dist/csv.cjs +1 -1
  7. package/dist/csv.d.cts +42 -3
  8. package/dist/csv.d.ts +42 -3
  9. package/dist/csv.js +1 -1
  10. package/dist/{dataset-CbZnEWXu.cjs → dataset-B4-SEdCn.cjs} +4 -4
  11. package/dist/{dataset-CyEHVht4.js → dataset-Dh598YSG.js} +4 -4
  12. package/dist/{dates-BXcSWf9_.js → dates-CIL1z9EY.js} +1 -1
  13. package/dist/{dates-CA1dCizp.cjs → dates-DcdgnJto.cjs} +1 -1
  14. package/dist/dom.cjs +2 -2
  15. package/dist/dom.d.cts +1 -1
  16. package/dist/dom.d.ts +1 -1
  17. package/dist/dom.js +2 -2
  18. package/dist/{dos-time-BsH7f0ef.js → dos-time-BEAyK3U8.js} +1 -1
  19. package/dist/{dos-time-CxEs--rI.cjs → dos-time-BUWyklco.cjs} +1 -1
  20. package/dist/{errors-CvGlfw0E.js → errors-BQE62PFo.js} +1 -1
  21. package/dist/{errors-DOPrrGS4.cjs → errors-CKYdpCoB.cjs} +1 -1
  22. package/dist/format.cjs +1 -1
  23. package/dist/format.js +1 -1
  24. package/dist/import.cjs +1 -1
  25. package/dist/import.d.cts +2 -2
  26. package/dist/import.d.ts +2 -2
  27. package/dist/import.js +1 -1
  28. package/dist/index.cjs +7 -7
  29. package/dist/index.d.cts +5 -5
  30. package/dist/index.d.ts +5 -5
  31. package/dist/index.js +7 -7
  32. package/dist/{infer-BniOucP6.cjs → infer-B950M3-F.cjs} +27 -0
  33. package/dist/{infer-DcUyZ1T-.js → infer-DuSahY5i.js} +16 -1
  34. package/dist/{pipeline-C8F9lecW.js → pipeline-1AVJbbqT.js} +12 -7
  35. package/dist/{pipeline-BwkRpV5Z.cjs → pipeline-C9zhwGAV.cjs} +12 -7
  36. package/dist/{pipeline-4U7Xnuc1.d.cts → pipeline-CJWE3NWg.d.cts} +7 -3
  37. package/dist/{pipeline-BegSPu8X.d.ts → pipeline-DVgO1aGC.d.ts} +7 -3
  38. package/dist/{read-cvxu6O-H.js → read-B6tY0ooT.js} +2202 -799
  39. package/dist/{read-DmUPztqh.cjs → read-Dgw9kMzh.cjs} +2203 -794
  40. package/dist/read.cjs +2 -1
  41. package/dist/read.d.cts +49 -2
  42. package/dist/read.d.ts +49 -2
  43. package/dist/read.js +2 -2
  44. package/dist/render.cjs +2 -2
  45. package/dist/render.js +2 -2
  46. package/dist/{sheet-names-DDY64-dt.cjs → sheet-names-D8sYcjSd.cjs} +2 -2
  47. package/dist/{sheet-names-BLrwcn33.js → sheet-names-RoFkpk_R.js} +2 -2
  48. package/dist/{warnings-DhonqJ7A.d.ts → warnings-DEsTp6rd.d.cts} +13 -2
  49. package/dist/{warnings-DhonqJ7A.d.cts → warnings-DEsTp6rd.d.ts} +13 -2
  50. package/dist/worker.cjs +5 -5
  51. package/dist/worker.d.cts +4 -4
  52. package/dist/worker.d.ts +4 -4
  53. package/dist/worker.js +5 -5
  54. package/dist/{write-DKXhuvKR.cjs → write-Bgl_QfA8.cjs} +5 -5
  55. package/dist/{write-BaMv1Z7W.d.ts → write-BylKqAmD.d.ts} +1 -1
  56. package/dist/{write-BVXB2_2C.js → write-DFz-h8gz.js} +5 -5
  57. package/dist/{write-Izl2NG0Y.d.cts → write-JvXRv63d.d.cts} +1 -1
  58. package/package.json +1 -1
@@ -1,8 +1,8 @@
1
- import { a as toBytes, n as parseIsoDate, r as WarningCap } from "./infer-DcUyZ1T-.js";
2
- import { a as LimitError, i as FormatError } from "./errors-CvGlfw0E.js";
3
- import { a as decodeUtf8Strict, c as throttleProgress, d as throwIfAborted$1, i as nativeCodec, r as crc32, s as createYielder, t as fromDosDateTime, u as concatBytes } from "./dos-time-BsH7f0ef.js";
1
+ import { n as parseIsoDate, r as WarningCap, s as toBytes } from "./infer-DuSahY5i.js";
2
+ import { a as LimitError, i as FormatError } from "./errors-BQE62PFo.js";
3
+ import { a as decodeUtf8Strict, c as throttleProgress, d as throwIfAborted$1, i as nativeCodec, r as crc32, s as createYielder, t as fromDosDateTime, u as concatBytes } from "./dos-time-BEAyK3U8.js";
4
4
  import { n as isDateFormat } from "./numfmt-Ci_oW11p.js";
5
- import { n as serialToDate } from "./dates-BXcSWf9_.js";
5
+ import { n as serialToDate } from "./dates-CIL1z9EY.js";
6
6
  // src/internal/read/limits.ts
7
7
  /** Default limits (docs/api.md §5.2; the measurements behind each value are listed there). */
8
8
  const DEFAULT_LIMITS = Object.freeze({
@@ -35,503 +35,197 @@ function excerpt(s) {
35
35
  function quoted(s) {
36
36
  return s.length <= 128 ? JSON.stringify(s) : `${JSON.stringify(head(s))}… (${s.length} characters)`;
37
37
  }
38
- // src/internal/zip/read.ts
38
+ // src/internal/read/xml-reader.ts
39
39
  /**
40
- * Zip container reader (docs/api.md §6, §8). Internal.
41
- *
42
- * `openZip` parses the central directory synchronously and validates the whole
43
- * layout before any data is inflated:
44
- * - end-of-central-directory record, with zip64 records when present;
45
- * - single-disk archives only;
46
- * - every entry's local header must agree with its central record;
47
- * - entry data must not overlap other entries or the central directory;
48
- * - duplicate names, encryption and methods other than 0 and 8 are rejected.
40
+ * Streaming XML pull tokenizer for the reader (docs/api.md §5.2, §8). Internal.
49
41
  *
50
- * Reading an entry counts the actual decompressed bytes against the limits
51
- * (never trusting declared sizes), stops when an entry produces more than it
52
- * declared, and verifies its CRC-32.
42
+ * - Push-fed: `feed()` text chunks as they are inflated, then `end()`. Only
43
+ * the unfinished tail of a chunk is kept, so a part is never held whole.
44
+ * - Linear in the input, however the chunks fall (JSE-43). An unfinished
45
+ * token (tag, comment, CDATA section, PI) is collected as a list of chunks;
46
+ * each new chunk alone is searched for the token's end, with the scan state
47
+ * (the open quote of a start tag, or the last characters that may begin a
48
+ * `-->`) carried over. The chunks are joined once, when the end is found.
49
+ * One token is limited to `maxXmlTokenLength` characters while it is read.
50
+ * Text is never collected: it is passed on chunk by chunk.
51
+ * - Iterative, never recursive. Element depth is limited (`maxXmlDepth`).
52
+ * - Any `<!DOCTYPE` is rejected (XML_DTD_FORBIDDEN), so there is no entity
53
+ * expansion and nothing external is ever fetched. Only the five predefined
54
+ * entities and numeric character references are decoded.
55
+ * - Well-formedness is checked as far as the reader needs: tags must nest and
56
+ * match, attributes must be quoted, references must be valid.
57
+ * - Names are reported without their namespace prefix (`x:row` -> `row`), so
58
+ * prefixed SpreadsheetML and ISO 29500 Strict parts read like transitional
59
+ * ones. Attributes keep their qualified names; see `XmlAttrs`.
53
60
  */
54
- /** The zip-related defaults of docs/api.md §5.2, the same values as DEFAULT_READ_LIMITS (measured in JSE-6). */
55
- const DEFAULT_ZIP_LIMITS = Object.freeze({
56
- maxInputBytes: 268435456,
57
- maxEntries: 1e4,
58
- maxEntryBytes: 536870912,
59
- maxTotalBytes: 1073741824,
60
- maxRatio: 1e3
61
- });
62
- const SIG_LOCAL = 67324752;
63
- const SIG_CENTRAL = 33639248;
64
- const SIG_EOCD = 101010256;
65
- const SIG_ZIP64_EOCD = 101075792;
66
- const SIG_ZIP64_LOCATOR = 117853008;
67
- const FLAG_ENCRYPTED = 1;
68
- const FLAG_DATA_DESCRIPTOR = 8;
69
- const FLAG_UTF8 = 2048;
70
- const EXTRA_ZIP64 = 1;
71
- const EXTRA_UNICODE_PATH = 28789;
72
- const METHOD_AES = 99;
73
- /** Code page 437, bytes 0x80..0xFF: the spec's default encoding for names without bit 11. */
74
- const CP437_HIGH = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
75
- function invalid(message, details) {
76
- return new FormatError("ZIP_INVALID", message, details ? { details } : void 0);
61
+ /** Attributes of one start tag. Names are never used as object keys. */
62
+ var XmlAttrs = class {
63
+ items;
64
+ /** Flat [qname, value, qname, value, ...]. */
65
+ constructor(items) {
66
+ this.items = items;
67
+ }
68
+ /** Value of the unprefixed attribute `local`. */
69
+ get(local) {
70
+ const items = this.items;
71
+ for (let i = 0; i < items.length; i += 2) if (items[i] === local) return items[i + 1];
72
+ }
73
+ /**
74
+ * Value of a prefixed attribute with local name `local` (e.g. `r:id` for
75
+ * "id"), whatever the prefix; `xml:` and `xmlns:` are skipped.
76
+ */
77
+ getPrefixed(local) {
78
+ const items = this.items;
79
+ for (let i = 0; i < items.length; i += 2) {
80
+ const q = items[i];
81
+ const colon = q.indexOf(":");
82
+ if (colon <= 0 || q.slice(colon + 1) !== local) continue;
83
+ const prefix = q.slice(0, colon);
84
+ if (prefix === "xml" || prefix === "xmlns") continue;
85
+ return items[i + 1];
86
+ }
87
+ }
88
+ /** Value of the attribute with exactly this qualified name (e.g. `xml:space`, `xmlns`). */
89
+ getQualified(qname) {
90
+ return this.get(qname);
91
+ }
92
+ /** Every [qualified name, value] pair, in document order. */
93
+ *entries() {
94
+ for (let i = 0; i < this.items.length; i += 2) yield [this.items[i], this.items[i + 1]];
95
+ }
96
+ };
97
+ function malformed(message) {
98
+ return new FormatError("XML_MALFORMED", message);
77
99
  }
78
- function limitError(limit, value, max, what) {
79
- return new LimitError("LIMIT_EXCEEDED", `${what} exceeds the ${limit} limit (${max}).`, { details: {
80
- limit,
81
- value,
100
+ const EMPTY_ATTRS = new XmlAttrs([]);
101
+ const Wait = {
102
+ None: 0,
103
+ /** A plain terminator: `delim`. */
104
+ Delim: 1,
105
+ /** The '>' that ends a start tag (or a '<', which is an error), outside quoted values. */
106
+ Tag: 2
107
+ };
108
+ /** The longest reference pump() may keep unfinished: `&` plus 11 characters (a `;` after that makes it invalid anyway). */
109
+ const MAX_REF_TAIL = 12;
110
+ /**
111
+ * `details.value` is `max + 1`, meaning "more than max": the limit trips
112
+ * before the token's end is read, so its real length is not known, and how
113
+ * much of it was buffered depends on how the chunks fell.
114
+ */
115
+ function tokenLimit(max) {
116
+ return new LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${max}).`, { details: {
117
+ limit: "maxXmlTokenLength",
118
+ value: max + 1,
82
119
  max
83
120
  } });
84
121
  }
85
- var Cursor = class {
86
- bytes;
87
- pos;
88
- view;
89
- constructor(bytes, pos) {
90
- this.bytes = bytes;
91
- this.pos = pos;
92
- this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
122
+ /** Unfinished-token chunks shorter than this are appended to the previous one, so 1-character chunks do not make a huge parts list. */
123
+ const MIN_PART = 4096;
124
+ var XmlTokenizer = class {
125
+ handler;
126
+ maxDepth;
127
+ maxToken;
128
+ onDeclaration;
129
+ buf = "";
130
+ stack = [];
131
+ /** While skipping: the end tag being searched for ("</qname"), and the depth to keep. */
132
+ skipTag;
133
+ skipDepth = 0;
134
+ /** While skipping: how many characters of `skipTag` the input seen so far ends with. */
135
+ skipMatched = 0;
136
+ rootSeen = false;
137
+ rootClosed = false;
138
+ pendingCR = false;
139
+ /** An unfinished token, from its '<': the chunks fed so far (`buf` is empty meanwhile). */
140
+ wait = Wait.None;
141
+ parts = [];
142
+ partsLength = 0;
143
+ /** Wait.Delim: the terminator, and the end of the searched text that may begin it. */
144
+ delim = "";
145
+ carry = "";
146
+ /** Wait.Tag: the open quote (34 or 39), or 0. */
147
+ quote = 0;
148
+ /** Characters examined or copied so far. A test hook for proving the scan is linear. */
149
+ work = 0;
150
+ constructor(handler, maxDepth, maxToken = DEFAULT_LIMITS.maxXmlTokenLength, onDeclaration) {
151
+ this.handler = handler;
152
+ this.maxDepth = maxDepth;
153
+ this.maxToken = maxToken;
154
+ this.onDeclaration = onDeclaration;
155
+ handler.attach?.(this);
93
156
  }
94
- need(n) {
95
- if (this.pos < 0 || this.pos + n > this.bytes.length) throw invalid("Unexpected end of zip data.");
157
+ depth() {
158
+ return this.stack.length;
96
159
  }
97
- u16() {
98
- this.need(2);
99
- const v = this.view.getUint16(this.pos, true);
100
- this.pos += 2;
101
- return v;
160
+ skipToEndOf(depth) {
161
+ if (depth < 1 || depth > this.stack.length) throw new RangeError(`skipToEndOf: no open element at depth ${depth}`);
162
+ this.skipTag = `</${this.stack[depth - 1]}`;
163
+ this.skipDepth = depth;
164
+ this.skipMatched = 0;
102
165
  }
103
- u32() {
104
- this.need(4);
105
- const v = this.view.getUint32(this.pos, true);
106
- this.pos += 4;
107
- return v;
166
+ feed(chunk) {
167
+ if (this.wait !== Wait.None) {
168
+ if (!this.resume(chunk)) return;
169
+ } else if (this.buf.length === 0) this.buf = chunk;
170
+ else {
171
+ this.work += this.buf.length + chunk.length;
172
+ this.buf += chunk;
173
+ }
174
+ this.pump(false);
108
175
  }
109
- u64() {
110
- const lo = this.u32();
111
- const v = this.u32() * 4294967296 + lo;
112
- if (!Number.isSafeInteger(v)) throw invalid("Zip64 value out of range.");
113
- return v;
176
+ end() {
177
+ if (this.wait !== Wait.None) this.unsuspend();
178
+ this.pump(true);
179
+ if (this.skipTag !== void 0) throw malformed(`Element <${excerpt(this.skipTag.slice(2))}> is not closed.`);
180
+ if (this.buf.trim() !== "") throw malformed("Unexpected end of XML data.");
181
+ if (this.stack.length > 0) throw malformed(`Element <${excerpt(this.stack.at(-1))}> is not closed.`);
182
+ if (!this.rootSeen) throw malformed("XML part has no root element.");
114
183
  }
115
- take(n) {
116
- this.need(n);
117
- const out = this.bytes.subarray(this.pos, this.pos + n);
118
- this.pos += n;
119
- return out;
184
+ /**
185
+ * Feeds one chunk to the unfinished token: only `chunk` is searched. Returns
186
+ * true when the token's end is in it; the chunks are then joined into `buf`
187
+ * and pump() reads the token from its start, exactly as if it had arrived
188
+ * whole. Throws when the token grows past maxXmlTokenLength.
189
+ */
190
+ resume(chunk) {
191
+ this.work += chunk.length;
192
+ const last = this.parts.length - 1;
193
+ if (this.parts[last].length < MIN_PART) this.parts[last] += chunk;
194
+ else this.parts.push(chunk);
195
+ this.partsLength += chunk.length;
196
+ let found;
197
+ if (this.wait === Wait.Tag) {
198
+ const e = scanTag(chunk, 0, chunk.length, this.quote);
199
+ found = e >= 0;
200
+ if (!found) this.quote = -1 - e;
201
+ } else {
202
+ const s = this.carry + chunk;
203
+ found = s.indexOf(this.delim) !== -1;
204
+ if (!found) this.carry = s.slice(Math.max(0, s.length - (this.delim.length - 1)));
205
+ }
206
+ if (!found) {
207
+ if (this.partsLength > this.maxToken) throw tokenLimit(this.maxToken);
208
+ return false;
209
+ }
210
+ this.unsuspend();
211
+ return true;
120
212
  }
121
- };
122
- function decodeName(raw, flags, extra) {
123
- if (flags & FLAG_UTF8) try {
124
- return decodeUtf8Strict(raw);
125
- } catch {
126
- throw invalid("Entry name is not valid UTF-8.");
213
+ /** Parks the unfinished token that starts at `buf[i]`. */
214
+ suspend(buf, i, wait, delim = "", searchFrom = 0) {
215
+ this.wait = wait;
216
+ this.parts = [buf.slice(i)];
217
+ this.partsLength = buf.length - i;
218
+ this.delim = delim;
219
+ this.carry = wait === Wait.Delim ? buf.slice(Math.max(searchFrom, buf.length - (delim.length - 1))) : "";
220
+ this.buf = "";
127
221
  }
128
- const unicode = findExtra(extra, EXTRA_UNICODE_PATH);
129
- if (unicode && unicode.length >= 5 && unicode[0] === 1) {
130
- if (new Cursor(unicode, 1).u32() === crc32(raw)) try {
131
- return decodeUtf8Strict(unicode.subarray(5));
132
- } catch {}
133
- }
134
- let s = "";
135
- for (const b of raw) s += b < 128 ? String.fromCharCode(b) : CP437_HIGH[b - 128];
136
- return s;
137
- }
138
- function findExtra(extra, id) {
139
- const c = new Cursor(extra, 0);
140
- while (c.pos + 4 <= extra.length) {
141
- const tag = c.u16();
142
- const len = c.u16();
143
- if (c.pos + len > extra.length) return void 0;
144
- const body = c.take(len);
145
- if (tag === id) return body;
146
- }
147
- }
148
- function findEocd(bytes) {
149
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
150
- const last = bytes.length - 22;
151
- const first = Math.max(0, last - 65535);
152
- for (let p = last; p >= first; p--) if (view.getUint32(p, true) === SIG_EOCD) {
153
- const commentLength = view.getUint16(p + 20, true);
154
- if (p + 22 + commentLength <= bytes.length) return p;
155
- }
156
- throw invalid("Not a zip file: no end-of-central-directory record.");
157
- }
158
- /** Bytes of a stored entry checksummed between two abort checks. */
159
- const STORED_CRC_STEP = 1048576;
160
- /** Parses and validates the archive layout. Does not inflate anything. */
161
- function openZip(bytes, options = {}) {
162
- const limits = {
163
- ...DEFAULT_ZIP_LIMITS,
164
- ...options.limits
165
- };
166
- const codec = options.codec ?? nativeCodec;
167
- if (bytes.length > limits.maxInputBytes) throw limitError("maxInputBytes", bytes.length, limits.maxInputBytes, "Input size");
168
- if (bytes.length < 22) throw invalid("Not a zip file: too short.");
169
- const eocdPos = findEocd(bytes);
170
- const e = new Cursor(bytes, eocdPos + 4);
171
- const disk = e.u16();
172
- const cdDisk = e.u16();
173
- const entriesOnDisk = e.u16();
174
- let entryCount = e.u16();
175
- let cdSize = e.u32();
176
- let cdOffset = e.u32();
177
- let cdLimit = eocdPos;
178
- if (eocdPos >= 20 && new Cursor(bytes, eocdPos - 20).u32() === SIG_ZIP64_LOCATOR) {
179
- const l = new Cursor(bytes, eocdPos - 16);
180
- const z64Disk = l.u32();
181
- const z64Pos = l.u64();
182
- const totalDisks = l.u32();
183
- if (z64Disk !== 0 || totalDisks > 1) throw invalid("Multi-disk zip archives are not supported.");
184
- if (z64Pos + 56 > eocdPos - 20) throw invalid("Zip64 end-of-central-directory record out of range.");
185
- const z = new Cursor(bytes, z64Pos);
186
- if (z.u32() !== SIG_ZIP64_EOCD) throw invalid("Bad zip64 end-of-central-directory signature.");
187
- z.u64();
188
- z.u16();
189
- z.u16();
190
- const z64ThisDisk = z.u32();
191
- const z64CdDisk = z.u32();
192
- z.u64();
193
- entryCount = z.u64();
194
- cdSize = z.u64();
195
- cdOffset = z.u64();
196
- if (z64ThisDisk !== 0 || z64CdDisk !== 0) throw invalid("Multi-disk zip archives are not supported.");
197
- cdLimit = z64Pos;
198
- } else {
199
- if (disk !== 0 || cdDisk !== 0 || entriesOnDisk !== entryCount) throw invalid("Multi-disk zip archives are not supported.");
200
- if (entryCount === 65535 || cdSize === 4294967295 || cdOffset === 4294967295) throw invalid("Zip64 values without a zip64 end-of-central-directory locator.");
201
- }
202
- if (entryCount > limits.maxEntries) throw limitError("maxEntries", entryCount, limits.maxEntries, "Entry count");
203
- if (cdOffset + cdSize > cdLimit) throw invalid("Central directory out of range.");
204
- if (entryCount * 46 > cdSize) throw invalid("Central directory too small for its entry count.");
205
- const entries = [];
206
- const byName = /* @__PURE__ */ new Map();
207
- const spans = [];
208
- const c = new Cursor(bytes.subarray(0, cdOffset + cdSize), cdOffset);
209
- for (let i = 0; i < entryCount; i++) {
210
- if (c.u32() !== SIG_CENTRAL) throw invalid("Bad central directory signature.", { index: i });
211
- c.u16();
212
- c.u16();
213
- const flags = c.u16();
214
- const method = c.u16();
215
- const time = c.u16();
216
- const date = c.u16();
217
- const crc = c.u32();
218
- let compressedSize = c.u32();
219
- let size = c.u32();
220
- const nameLength = c.u16();
221
- const extraLength = c.u16();
222
- const commentLength = c.u16();
223
- let diskStart = c.u16();
224
- c.u16();
225
- c.u32();
226
- let localOffset = c.u32();
227
- const rawName = c.take(nameLength);
228
- const extra = c.take(extraLength);
229
- c.take(commentLength);
230
- const z64 = findExtra(extra, EXTRA_ZIP64);
231
- if (z64) {
232
- const x = new Cursor(z64, 0);
233
- if (size === 4294967295) size = x.u64();
234
- if (compressedSize === 4294967295) compressedSize = x.u64();
235
- if (localOffset === 4294967295) localOffset = x.u64();
236
- if (diskStart === 65535) diskStart = x.u32();
237
- }
238
- if (diskStart !== 0) throw invalid("Multi-disk zip archives are not supported.");
239
- const name = decodeName(rawName, flags, extra);
240
- if (flags & 65 || method === METHOD_AES) throw new FormatError("ZIP_ENCRYPTED", `Entry ${excerpt(name)} is encrypted.`, { details: { entry: name } });
241
- if (method !== 0 && method !== 8) throw new FormatError("ZIP_UNSUPPORTED_METHOD", `Entry ${excerpt(name)} uses compression method ${method}.`, { details: {
242
- entry: name,
243
- method
244
- } });
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 });
247
- const l = new Cursor(bytes, localOffset);
248
- if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${excerpt(name)}.`, { entry: name });
249
- l.u16();
250
- const lFlags = l.u16();
251
- const lMethod = l.u16();
252
- l.u16();
253
- l.u16();
254
- const lCrc = l.u32();
255
- const lCompressed = l.u32();
256
- const lSize = l.u32();
257
- const lNameLength = l.u16();
258
- const lExtraLength = l.u16();
259
- const lName = l.take(lNameLength);
260
- l.take(lExtraLength);
261
- let agrees = lNameLength === nameLength && lName.every((b, k) => b === rawName[k]) && lMethod === method && (lFlags & FLAG_ENCRYPTED) === 0;
262
- if (agrees && !(lFlags & FLAG_DATA_DESCRIPTOR)) agrees = lCrc === crc && (lCompressed === compressedSize || lCompressed === 4294967295) && (lSize === size || lSize === 4294967295);
263
- if (!agrees) throw invalid(`Local header disagrees with the central directory for ${excerpt(name)}.`, { entry: name });
264
- const dataOffset = l.pos;
265
- const dataEnd = dataOffset + compressedSize;
266
- if (dataEnd > cdOffset) throw invalid(`Data of ${excerpt(name)} runs into the central directory.`, { entry: name });
267
- spans.push({
268
- start: localOffset,
269
- end: dataEnd,
270
- name
271
- });
272
- const info = Object.freeze({
273
- name,
274
- method,
275
- flags,
276
- crc32: crc,
277
- compressedSize,
278
- size,
279
- modified: fromDosDateTime(date, time),
280
- dataOffset
281
- });
282
- entries.push(info);
283
- byName.set(name, info);
284
- }
285
- spans.sort((a, b) => a.start - b.start);
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.`);
287
- let totalBytesRead = 0;
288
- const resolve = (entry) => {
289
- const info = typeof entry === "string" ? byName.get(entry) : entry;
290
- if (!info || byName.get(info.name) !== info) throw new Error(`No such zip entry: ${typeof entry === "string" ? entry : entry.name}`);
291
- return info;
292
- };
293
- const countTotal = (n) => {
294
- totalBytesRead += n;
295
- if (totalBytesRead > limits.maxTotalBytes) throw limitError("maxTotalBytes", totalBytesRead, limits.maxTotalBytes, "Total decompressed size");
296
- };
297
- async function* stream(entry, signal) {
298
- const info = resolve(entry);
299
- throwIfAborted$1(signal);
300
- if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${excerpt(info.name)}`);
301
- const data = bytes.subarray(info.dataOffset, info.dataOffset + info.compressedSize);
302
- let crc = 0;
303
- let produced = 0;
304
- if (info.method === 0) {
305
- countTotal(data.length);
306
- for (let at = 0; at < data.length; at += STORED_CRC_STEP) {
307
- if (at > 0) throwIfAborted$1(signal);
308
- crc = crc32(data.subarray(at, at + STORED_CRC_STEP), crc);
309
- }
310
- produced = data.length;
311
- if (crc !== info.crc32) throw crcMismatch(info);
312
- yield data;
313
- return;
314
- }
315
- const chunks = codec.inflateRaw(data, {
316
- maxOutputBytes: limits.maxEntryBytes,
317
- maxRatio: limits.maxRatio
318
- }, signal);
319
- for await (const chunk of chunks) {
320
- produced += chunk.length;
321
- if (produced > info.size) throw invalid(`Entry ${excerpt(info.name)} is larger than declared.`, { entry: info.name });
322
- countTotal(chunk.length);
323
- crc = crc32(chunk, crc);
324
- yield chunk;
325
- }
326
- if (produced !== info.size) throw invalid(`Entry ${excerpt(info.name)} is smaller than declared.`, { entry: info.name });
327
- if (crc !== info.crc32) throw crcMismatch(info);
328
- }
329
- return {
330
- entries,
331
- get: (name) => byName.get(name),
332
- stream,
333
- async read(entry, signal) {
334
- const parts = [];
335
- for await (const chunk of stream(entry, signal)) parts.push(chunk);
336
- return concatBytes(parts);
337
- },
338
- get totalBytesRead() {
339
- return totalBytesRead;
340
- }
341
- };
342
- }
343
- function crcMismatch(info) {
344
- return new FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${excerpt(info.name)}.`, { details: { entry: info.name } });
345
- }
346
- // src/internal/read/xml-reader.ts
347
- /**
348
- * Streaming XML pull tokenizer for the reader (docs/api.md §5.2, §8). Internal.
349
- *
350
- * - Push-fed: `feed()` text chunks as they are inflated, then `end()`. Only
351
- * the unfinished tail of a chunk is kept, so a part is never held whole.
352
- * - Linear in the input, however the chunks fall (JSE-43). An unfinished
353
- * token (tag, comment, CDATA section, PI) is collected as a list of chunks;
354
- * each new chunk alone is searched for the token's end, with the scan state
355
- * (the open quote of a start tag, or the last characters that may begin a
356
- * `-->`) carried over. The chunks are joined once, when the end is found.
357
- * One token is limited to `maxXmlTokenLength` characters while it is read.
358
- * Text is never collected: it is passed on chunk by chunk.
359
- * - Iterative, never recursive. Element depth is limited (`maxXmlDepth`).
360
- * - Any `<!DOCTYPE` is rejected (XML_DTD_FORBIDDEN), so there is no entity
361
- * expansion and nothing external is ever fetched. Only the five predefined
362
- * entities and numeric character references are decoded.
363
- * - Well-formedness is checked as far as the reader needs: tags must nest and
364
- * match, attributes must be quoted, references must be valid.
365
- * - Names are reported without their namespace prefix (`x:row` -> `row`), so
366
- * prefixed SpreadsheetML and ISO 29500 Strict parts read like transitional
367
- * ones. Attributes keep their qualified names; see `XmlAttrs`.
368
- */
369
- /** Attributes of one start tag. Names are never used as object keys. */
370
- var XmlAttrs = class {
371
- items;
372
- /** Flat [qname, value, qname, value, ...]. */
373
- constructor(items) {
374
- this.items = items;
375
- }
376
- /** Value of the unprefixed attribute `local`. */
377
- get(local) {
378
- const items = this.items;
379
- for (let i = 0; i < items.length; i += 2) if (items[i] === local) return items[i + 1];
380
- }
381
- /**
382
- * Value of a prefixed attribute with local name `local` (e.g. `r:id` for
383
- * "id"), whatever the prefix; `xml:` and `xmlns:` are skipped.
384
- */
385
- getPrefixed(local) {
386
- const items = this.items;
387
- for (let i = 0; i < items.length; i += 2) {
388
- const q = items[i];
389
- const colon = q.indexOf(":");
390
- if (colon <= 0 || q.slice(colon + 1) !== local) continue;
391
- const prefix = q.slice(0, colon);
392
- if (prefix === "xml" || prefix === "xmlns") continue;
393
- return items[i + 1];
394
- }
395
- }
396
- /** Value of the attribute with exactly this qualified name (e.g. `xml:space`, `xmlns`). */
397
- getQualified(qname) {
398
- return this.get(qname);
399
- }
400
- /** Every [qualified name, value] pair, in document order. */
401
- *entries() {
402
- for (let i = 0; i < this.items.length; i += 2) yield [this.items[i], this.items[i + 1]];
403
- }
404
- };
405
- function malformed(message) {
406
- return new FormatError("XML_MALFORMED", message);
407
- }
408
- const EMPTY_ATTRS = new XmlAttrs([]);
409
- const Wait = {
410
- None: 0,
411
- /** A plain terminator: `delim`. */
412
- Delim: 1,
413
- /** The '>' that ends a start tag (or a '<', which is an error), outside quoted values. */
414
- Tag: 2
415
- };
416
- /** The longest reference pump() may keep unfinished: `&` plus 11 characters (a `;` after that makes it invalid anyway). */
417
- const MAX_REF_TAIL = 12;
418
- /**
419
- * `details.value` is `max + 1`, meaning "more than max": the limit trips
420
- * before the token's end is read, so its real length is not known, and how
421
- * much of it was buffered depends on how the chunks fell.
422
- */
423
- function tokenLimit(max) {
424
- return new LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${max}).`, { details: {
425
- limit: "maxXmlTokenLength",
426
- value: max + 1,
427
- max
428
- } });
429
- }
430
- /** Unfinished-token chunks shorter than this are appended to the previous one, so 1-character chunks do not make a huge parts list. */
431
- const MIN_PART = 4096;
432
- var XmlTokenizer = class {
433
- handler;
434
- maxDepth;
435
- maxToken;
436
- buf = "";
437
- stack = [];
438
- /** While skipping: the end tag being searched for ("</qname"), and the depth to keep. */
439
- skipTag;
440
- skipDepth = 0;
441
- /** While skipping: how many characters of `skipTag` the input seen so far ends with. */
442
- skipMatched = 0;
443
- rootSeen = false;
444
- rootClosed = false;
445
- pendingCR = false;
446
- /** An unfinished token, from its '<': the chunks fed so far (`buf` is empty meanwhile). */
447
- wait = Wait.None;
448
- parts = [];
449
- partsLength = 0;
450
- /** Wait.Delim: the terminator, and the end of the searched text that may begin it. */
451
- delim = "";
452
- carry = "";
453
- /** Wait.Tag: the open quote (34 or 39), or 0. */
454
- quote = 0;
455
- /** Characters examined or copied so far. A test hook for proving the scan is linear. */
456
- work = 0;
457
- constructor(handler, maxDepth, maxToken = DEFAULT_LIMITS.maxXmlTokenLength) {
458
- this.handler = handler;
459
- this.maxDepth = maxDepth;
460
- this.maxToken = maxToken;
461
- handler.attach?.(this);
462
- }
463
- depth() {
464
- return this.stack.length;
465
- }
466
- skipToEndOf(depth) {
467
- if (depth < 1 || depth > this.stack.length) throw new RangeError(`skipToEndOf: no open element at depth ${depth}`);
468
- this.skipTag = `</${this.stack[depth - 1]}`;
469
- this.skipDepth = depth;
470
- this.skipMatched = 0;
471
- }
472
- feed(chunk) {
473
- if (this.wait !== Wait.None) {
474
- if (!this.resume(chunk)) return;
475
- } else if (this.buf.length === 0) this.buf = chunk;
476
- else {
477
- this.work += this.buf.length + chunk.length;
478
- this.buf += chunk;
479
- }
480
- this.pump(false);
481
- }
482
- end() {
483
- if (this.wait !== Wait.None) this.unsuspend();
484
- this.pump(true);
485
- if (this.skipTag !== void 0) throw malformed(`Element <${excerpt(this.skipTag.slice(2))}> is not closed.`);
486
- if (this.buf.trim() !== "") throw malformed("Unexpected end of XML data.");
487
- if (this.stack.length > 0) throw malformed(`Element <${excerpt(this.stack.at(-1))}> is not closed.`);
488
- if (!this.rootSeen) throw malformed("XML part has no root element.");
489
- }
490
- /**
491
- * Feeds one chunk to the unfinished token: only `chunk` is searched. Returns
492
- * true when the token's end is in it; the chunks are then joined into `buf`
493
- * and pump() reads the token from its start, exactly as if it had arrived
494
- * whole. Throws when the token grows past maxXmlTokenLength.
495
- */
496
- resume(chunk) {
497
- this.work += chunk.length;
498
- const last = this.parts.length - 1;
499
- if (this.parts[last].length < MIN_PART) this.parts[last] += chunk;
500
- else this.parts.push(chunk);
501
- this.partsLength += chunk.length;
502
- let found;
503
- if (this.wait === Wait.Tag) {
504
- const e = scanTag(chunk, 0, chunk.length, this.quote);
505
- found = e >= 0;
506
- if (!found) this.quote = -1 - e;
507
- } else {
508
- const s = this.carry + chunk;
509
- found = s.indexOf(this.delim) !== -1;
510
- if (!found) this.carry = s.slice(Math.max(0, s.length - (this.delim.length - 1)));
511
- }
512
- if (!found) {
513
- if (this.partsLength > this.maxToken) throw tokenLimit(this.maxToken);
514
- return false;
515
- }
516
- this.unsuspend();
517
- return true;
518
- }
519
- /** Parks the unfinished token that starts at `buf[i]`. */
520
- suspend(buf, i, wait, delim = "", searchFrom = 0) {
521
- this.wait = wait;
522
- this.parts = [buf.slice(i)];
523
- this.partsLength = buf.length - i;
524
- this.delim = delim;
525
- this.carry = wait === Wait.Delim ? buf.slice(Math.max(searchFrom, buf.length - (delim.length - 1))) : "";
526
- this.buf = "";
527
- }
528
- unsuspend() {
529
- this.buf = this.parts.length === 1 ? this.parts[0] : this.parts.join("");
530
- this.work += this.buf.length;
531
- this.wait = Wait.None;
532
- this.parts = [];
533
- this.partsLength = 0;
534
- this.carry = "";
222
+ unsuspend() {
223
+ this.buf = this.parts.length === 1 ? this.parts[0] : this.parts.join("");
224
+ this.work += this.buf.length;
225
+ this.wait = Wait.None;
226
+ this.parts = [];
227
+ this.partsLength = 0;
228
+ this.carry = "";
535
229
  }
536
230
  /** A token of `length` characters (from '<' to the end of its terminator) is complete. */
537
231
  checkToken(length) {
@@ -594,6 +288,7 @@ var XmlTokenizer = class {
594
288
  const e = buf.indexOf("?>", i + 2);
595
289
  if (e === -1) return this.unfinished(buf, i, final, "Unterminated processing instruction.", Wait.Delim, "?>", i + 2);
596
290
  this.checkToken(e + 2 - i);
291
+ if (this.onDeclaration && /^<\?xml(?:[ \t\r\n?]|$)/i.test(buf.slice(i, i + 6))) this.onDeclaration(buf.slice(i, e + 2));
597
292
  i = e + 2;
598
293
  continue;
599
294
  }
@@ -838,6 +533,16 @@ var ReadContext = class {
838
533
  this.warnings = this.cap.warnings;
839
534
  }
840
535
  onProgress;
536
+ /** Sees every warning before the cap applies (inspect collects UNSUPPORTED_PART with it, JSE-71). */
537
+ tap;
538
+ /**
539
+ * inspect (JSE-71): for every part parsed as XML, a sniffer that sees its
540
+ * inflated bytes (however the inflater splits them) and, from the tokenizer,
541
+ * every processing instruction whose target is `xml` in any case.
542
+ */
543
+ sniff;
544
+ /** inspect (JSE-71): sees every relationship part the package parses, with its relationships. */
545
+ relsParsed;
841
546
  /** Returns to the event loop about every 16 ms between chunks, so a big read does not freeze the page (JSE-24). */
842
547
  pause = createYielder();
843
548
  /**
@@ -854,6 +559,8 @@ var ReadContext = class {
854
559
  if (where?.sheet !== void 0) w.sheet = where.sheet;
855
560
  if (where?.ref !== void 0) w.ref = where.ref;
856
561
  if (where?.partKind !== void 0) w.partKind = where.partKind;
562
+ if (where?.parts !== void 0) w.parts = where.parts;
563
+ this.tap?.(w);
857
564
  if (this.cap.add(w, (dropped) => {
858
565
  const t = {
859
566
  code: "WARNINGS_TRUNCATED",
@@ -922,10 +629,12 @@ var ReadContext = class {
922
629
  */
923
630
  async parse(entry, handler, onChunk) {
924
631
  this.consumed.add(entry.name);
925
- const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength);
632
+ const sniffer = this.sniff?.(entry.name);
633
+ const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength, sniffer && ((pi) => sniffer.pi(pi)));
926
634
  let decoder;
927
635
  try {
928
636
  for await (const chunk of this.zip.stream(entry, this.signal)) {
637
+ sniffer?.feed(chunk);
929
638
  let bytes = chunk;
930
639
  if (!decoder) {
931
640
  decoder = newDecoder(chunk);
@@ -944,249 +653,794 @@ var ReadContext = class {
944
653
  this.checkAbort();
945
654
  }
946
655
  }
947
- onChunk?.(chunk.length);
948
- this.checkAbort();
949
- const pause = this.pause();
950
- if (pause) {
951
- await pause;
952
- this.checkAbort();
656
+ onChunk?.(chunk.length);
657
+ this.checkAbort();
658
+ const pause = this.pause();
659
+ if (pause) {
660
+ await pause;
661
+ this.checkAbort();
662
+ }
663
+ }
664
+ if (decoder) tok.feed(decoder.decode());
665
+ tok.end();
666
+ sniffer?.end();
667
+ } catch (err) {
668
+ throw withPart(err, entry.name);
669
+ }
670
+ }
671
+ };
672
+ function withPart(err, part) {
673
+ if (err instanceof FormatError && (err.code === "XML_MALFORMED" || err.code === "XML_DTD_FORBIDDEN") && !err.details?.["part"]) return new FormatError(err.code, `${excerpt(part)}: ${err.message}`, {
674
+ details: {
675
+ ...err.details,
676
+ part
677
+ },
678
+ cause: err
679
+ });
680
+ const limit = err instanceof LimitError ? err.details?.["limit"] : void 0;
681
+ if (err instanceof LimitError && (limit === "maxXmlDepth" || limit === "maxXmlTokenLength" || limit === "maxCellTextLength") && !err.details?.["part"]) return new LimitError(err.code, `${excerpt(part)}: ${err.message}`, {
682
+ details: {
683
+ ...err.details,
684
+ part
685
+ },
686
+ cause: err
687
+ });
688
+ return err;
689
+ }
690
+ function newDecoder(first) {
691
+ const Ctor = globalThis.TextDecoder;
692
+ if (first[0] === 255 && first[1] === 254) return new Ctor("utf-16le");
693
+ if (first[0] === 254 && first[1] === 255) return new Ctor("utf-16be");
694
+ return new Ctor("utf-8");
695
+ }
696
+ function stripBom(b) {
697
+ if (b[0] === 239 && b[1] === 187 && b[2] === 191) return b.subarray(3);
698
+ if (b[0] === 255 && b[1] === 254 || b[0] === 254 && b[1] === 255) return b.subarray(2);
699
+ return b;
700
+ }
701
+ var Package = class {
702
+ ctx;
703
+ /** partKey(name) -> entry. */
704
+ parts = /* @__PURE__ */ new Map();
705
+ /** entry -> partKey(entry.name), computed once. */
706
+ keys = /* @__PURE__ */ new Map();
707
+ /**
708
+ * Names OPC forbids, in the order found: zip entries (see `forbiddenName`),
709
+ * then `[Content_Types].xml` when one of its PartNames is forbidden.
710
+ */
711
+ forbiddenNames = [];
712
+ /**
713
+ * Relationships that are not well-formed, by relationships part (entry
714
+ * name): an element without `Id` (or with an empty one) or without
715
+ * `Target`. They are left out of `rels()`, so the model ignores them as
716
+ * 2.4.0 did, but the package scan classifies them. One without `Type` is
717
+ * listed with type '' (nothing to classify).
718
+ */
719
+ malformedRels = /* @__PURE__ */ new Map();
720
+ /** 2.4.0's override table (raw lower-case PartName, last wins), for format detection only. */
721
+ legacyOverrides = /* @__PURE__ */ new Map();
722
+ /** partKey(part name) -> content types, in the order [Content_Types].xml lists them. */
723
+ overrides = /* @__PURE__ */ new Map();
724
+ /** Extension (lower case) -> content types. */
725
+ defaults = /* @__PURE__ */ new Map();
726
+ /**
727
+ * Indexes the zip entries by part name. Two entries whose names are
728
+ * equivalent (equal in canonical form, case-insensitively) make the package
729
+ * invalid: ZIP_INVALID, as OPC requires. Consults the signal for every
730
+ * entry (each costs work linear in its name, up to 64 KB).
731
+ */
732
+ constructor(ctx) {
733
+ this.ctx = ctx;
734
+ const entries = ctx.zip.entries;
735
+ for (let i = 0; i < entries.length; i++) {
736
+ ctx.checkAbort();
737
+ const e = entries[i];
738
+ if (e.name.endsWith("/")) continue;
739
+ const key = partKey(e.name);
740
+ const earlier = this.parts.get(key);
741
+ if (earlier) {
742
+ const how = earlier.name.toLowerCase() === e.name.toLowerCase() ? "differ only in case" : "are equivalent (they differ only in case or percent-encoding)";
743
+ throw new FormatError("ZIP_INVALID", `Part names ${excerpt(earlier.name)} and ${excerpt(e.name)} ${how}.`, { details: { entry: e.name } });
744
+ }
745
+ this.parts.set(key, e);
746
+ this.keys.set(e, key);
747
+ if (forbiddenName(e.name, false)) this.forbiddenNames.push(e.name);
748
+ }
749
+ ctx.checkAbort();
750
+ }
751
+ /** The lookup key of a zip entry of this package (partKey of its name, computed once). */
752
+ keyOf(entry) {
753
+ return this.keys.get(entry) ?? partKey(entry.name);
754
+ }
755
+ part(name) {
756
+ if (name.length > 196605) return void 0;
757
+ return this.parts.get(partKey(name));
758
+ }
759
+ get partNames() {
760
+ return [...this.parts.values()].map((e) => e.name);
761
+ }
762
+ async loadContentTypes() {
763
+ const entry = this.part("[Content_Types].xml");
764
+ if (!entry) return;
765
+ let badPartName = false;
766
+ await this.ctx.parse(entry, {
767
+ open: (name, a) => {
768
+ if (name === "Default") {
769
+ const ext = a.get("Extension");
770
+ const type = a.get("ContentType");
771
+ if (ext && type) push(this.defaults, ext.toLowerCase(), type);
772
+ } else if (name === "Override") {
773
+ const part = a.get("PartName");
774
+ const type = a.get("ContentType");
775
+ if (!part || !type) return;
776
+ this.legacyOverrides.set(stripSlash(part).toLowerCase(), type);
777
+ if (part.length > 196605) {
778
+ badPartName = true;
779
+ return;
780
+ }
781
+ if (forbiddenName(part, false)) badPartName = true;
782
+ const key = partKey(part);
783
+ push(this.overrides, key, type);
784
+ const decoded = partKey(resolveTarget("", part));
785
+ if (decoded !== key) push(this.overrides, decoded, type);
786
+ }
787
+ },
788
+ close: () => {},
789
+ text: () => {}
790
+ });
791
+ if (badPartName) this.forbiddenNames.push(entry.name);
792
+ }
793
+ /** The content type of a part for format decisions, exactly as 2.4.0: the last Override with the same raw PartName (case-insensitive), else the last Default for its extension. */
794
+ contentType(name) {
795
+ const key = stripSlash(name).toLowerCase();
796
+ const o = this.legacyOverrides.get(key);
797
+ if (o) return o;
798
+ const dot = key.lastIndexOf(".");
799
+ return dot === -1 ? void 0 : this.defaults.get(key.slice(dot + 1))?.at(-1);
800
+ }
801
+ /**
802
+ * Every content type [Content_Types].xml gives the part: all Overrides with
803
+ * an equivalent part name, else all Defaults for its extension. The package
804
+ * scan checks each, so a later passive entry cannot hide an active one.
805
+ */
806
+ contentTypes(name) {
807
+ if (name.length > 196605) return [];
808
+ const key = partKey(name);
809
+ const o = this.overrides.get(key);
810
+ if (o) return o;
811
+ const dot = key.lastIndexOf(".");
812
+ return (dot > key.lastIndexOf("/") ? this.defaults.get(key.slice(dot + 1)) : void 0) ?? [];
813
+ }
814
+ /** Content types of the overrides for format detection: one per raw PartName, the last given, exactly as 2.4.0. */
815
+ get overrideTypes() {
816
+ return [...this.legacyOverrides.values()];
817
+ }
818
+ /** The relationships part of `source` ('' for the package), whether or not it exists. */
819
+ relsPartOf(source) {
820
+ const src = stripSlash(source);
821
+ const slash = src.lastIndexOf("/");
822
+ return `${slash === -1 ? "" : src.slice(0, slash + 1)}_rels/${slash === -1 ? src : src.slice(slash + 1)}.rels`;
823
+ }
824
+ /**
825
+ * Relationships of `source` ('' for the package). Missing rels part: [].
826
+ * Each relationships part is parsed once per read and the result shared, so
827
+ * callers must not change the array. With `peek`, a part not read before is
828
+ * not marked as consumed (InternalReadOptions.retainParts still keeps it).
829
+ */
830
+ async rels(source, options) {
831
+ const entry = this.part(this.relsPartOf(source));
832
+ if (!entry) return [];
833
+ const consumed = this.ctx.consumed;
834
+ const cached = this.relsCache.get(entry.name);
835
+ if (cached) {
836
+ if (!options?.peek) consumed.add(entry.name);
837
+ return cached;
838
+ }
839
+ const wasConsumed = consumed.has(entry.name);
840
+ try {
841
+ const out = await this.parseRels(entry, source);
842
+ this.relsCache.set(entry.name, out);
843
+ return out;
844
+ } finally {
845
+ if (options?.peek && !wasConsumed) consumed.delete(entry.name);
846
+ }
847
+ }
848
+ relsCache = /* @__PURE__ */ new Map();
849
+ async parseRels(entry, source) {
850
+ const src = stripSlash(source);
851
+ const slash = src.lastIndexOf("/");
852
+ const dir = slash === -1 ? "" : src.slice(0, slash + 1);
853
+ const out = [];
854
+ const malformed = [];
855
+ await this.ctx.parse(entry, {
856
+ open: (name, a) => {
857
+ if (name !== "Relationship") return;
858
+ const id = a.get("Id");
859
+ const type = a.get("Type") ?? "";
860
+ const target = a.get("Target");
861
+ const external = (a.get("TargetMode") ?? "").toLowerCase() === "external";
862
+ const rel = {
863
+ id: id ?? "",
864
+ type,
865
+ kind: type.slice(type.lastIndexOf("/") + 1),
866
+ target: "",
867
+ external
868
+ };
869
+ if (target === void 0) {
870
+ malformed.push(rel);
871
+ return;
872
+ }
873
+ if (external) rel.target = target;
874
+ else if (target.trim().length > 196605) {
875
+ rel.tooLong = true;
876
+ rel.forbidden = true;
877
+ } else {
878
+ const readings = resolveReadings(dir, target);
879
+ rel.target = readings.target;
880
+ const key = partKey(rel.target);
881
+ if (forbiddenName(stripFragment(target), true) || isPackageMetadata(key)) rel.forbidden = true;
882
+ if (readings.alt !== void 0) {
883
+ const altKey = partKey(readings.alt);
884
+ if (altKey !== key) {
885
+ rel.altTarget = readings.alt;
886
+ if (isPackageMetadata(altKey)) rel.forbidden = true;
887
+ }
888
+ }
953
889
  }
954
- }
955
- if (decoder) tok.feed(decoder.decode());
956
- tok.end();
957
- } catch (err) {
958
- throw withPart(err, entry.name);
959
- }
890
+ if (!id || !type) malformed.push(rel);
891
+ else out.push(rel);
892
+ },
893
+ close: () => {},
894
+ text: () => {}
895
+ });
896
+ if (malformed.length) this.malformedRels.set(entry.name, malformed);
897
+ this.ctx.relsParsed?.(entry.name, out);
898
+ return out;
960
899
  }
961
900
  };
962
- function withPart(err, part) {
963
- if (err instanceof FormatError && (err.code === "XML_MALFORMED" || err.code === "XML_DTD_FORBIDDEN") && !err.details?.["part"]) return new FormatError(err.code, `${excerpt(part)}: ${err.message}`, {
964
- details: {
965
- ...err.details,
966
- part
967
- },
968
- cause: err
969
- });
970
- const limit = err instanceof LimitError ? err.details?.["limit"] : void 0;
971
- if (err instanceof LimitError && (limit === "maxXmlDepth" || limit === "maxXmlTokenLength" || limit === "maxCellTextLength") && !err.details?.["part"]) return new LimitError(err.code, `${excerpt(part)}: ${err.message}`, {
972
- details: {
973
- ...err.details,
974
- part
975
- },
976
- cause: err
977
- });
978
- return err;
901
+ /**
902
+ * A relationships part (`…/_rels/<name>.rels`) or `[Content_Types].xml`, by
903
+ * part key: package metadata that OPC forbids as a relationship target.
904
+ */
905
+ function isPackageMetadata(key) {
906
+ if (key === "[content_types].xml") return true;
907
+ if (!key.endsWith(".rels")) return false;
908
+ const slash = key.lastIndexOf("/");
909
+ const parent = key.slice(0, slash === -1 ? 0 : slash);
910
+ return parent === "_rels" || parent.endsWith("/_rels");
979
911
  }
980
- function newDecoder(first) {
981
- const Ctor = globalThis.TextDecoder;
982
- if (first[0] === 255 && first[1] === 254) return new Ctor("utf-16le");
983
- if (first[0] === 254 && first[1] === 255) return new Ctor("utf-16be");
984
- return new Ctor("utf-8");
912
+ /** The owner of a relationships part (`a/_rels/b.xml.rels` -> `a/b.xml`, `_rels/.rels` -> ''), or undefined if `name` is not one. */
913
+ function relsOwner(name) {
914
+ const slash = name.lastIndexOf("/");
915
+ const file = name.slice(slash + 1);
916
+ if (slash === -1 || !/\.rels$/i.test(file)) return void 0;
917
+ const parent = name.slice(0, slash);
918
+ const parentSlash = parent.lastIndexOf("/");
919
+ if (parent.slice(parentSlash + 1).toLowerCase() !== "_rels") return void 0;
920
+ return parent.slice(0, parentSlash + 1) + file.slice(0, -5);
985
921
  }
986
- function stripBom(b) {
987
- if (b[0] === 239 && b[1] === 187 && b[2] === 191) return b.subarray(3);
988
- if (b[0] === 255 && b[1] === 254 || b[0] === 254 && b[1] === 255) return b.subarray(2);
989
- return b;
922
+ function stripSlash(name) {
923
+ return name.startsWith("/") ? name.slice(1) : name;
990
924
  }
991
- // src/internal/read/formats.ts
992
- /** Container signatures, checked in order. */
993
- const CONTAINERS = [
994
- {
995
- kind: "cfb",
996
- magic: [
997
- 208,
998
- 207,
999
- 17,
1000
- 224,
1001
- 161,
1002
- 177,
1003
- 26,
1004
- 225
1005
- ]
1006
- },
1007
- {
1008
- kind: "zip",
1009
- magic: [
1010
- 80,
1011
- 75,
1012
- 3,
1013
- 4
1014
- ]
1015
- },
1016
- {
1017
- kind: "zip",
1018
- magic: [
1019
- 80,
1020
- 75,
1021
- 5,
1022
- 6
1023
- ]
925
+ function push(map, key, value) {
926
+ const list = map.get(key);
927
+ if (list) list.push(value);
928
+ else map.set(key, [value]);
929
+ }
930
+ function stripFragment(target) {
931
+ const hash = target.indexOf("#");
932
+ return hash === -1 ? target : target.slice(0, hash);
933
+ }
934
+ /**
935
+ * True when a part name or relationship target uses a segment OPC forbids
936
+ * (ECMA-376 Part 2 §6.2.2): one containing `%2F` or `%5C`, a percent-encoded
937
+ * dot segment (`%2E`, `%2E%2E`, `.%2E`, `%2E.`), or one ending in a dot. For
938
+ * a relationship target (`isTarget`), the literal `.` and `..` segments of a
939
+ * relative reference are allowed; in a zip entry name they are forbidden too.
940
+ * Segments are split on `/` and, in a target, on `\`. Linear in the length.
941
+ */
942
+ function forbiddenName(name, isTarget) {
943
+ const n = name.length;
944
+ let segStart = 0;
945
+ for (let i = 0; i <= n; i++) {
946
+ const c = i < n ? name.charCodeAt(i) : 47;
947
+ if (c !== 47 && !(isTarget && c === 92)) continue;
948
+ if (i > segStart && forbiddenSegment(name, segStart, i, isTarget)) return true;
949
+ segStart = i + 1;
1024
950
  }
1025
- ];
1026
- /** OPC workbook formats by the content type of their workbook part. */
1027
- const WORKBOOK_FORMATS = [
1028
- {
1029
- format: "xlsx",
1030
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
1031
- decoder: "spreadsheetml",
1032
- label: "Excel workbook (.xlsx)"
1033
- },
1034
- {
1035
- format: "xltx",
1036
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml",
1037
- decoder: "spreadsheetml",
1038
- label: "Excel template (.xltx)"
1039
- },
1040
- {
1041
- format: "xlsm",
1042
- contentType: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
1043
- decoder: "spreadsheetml",
1044
- macros: true,
1045
- label: "macro-enabled workbook (.xlsm)"
1046
- },
1047
- {
1048
- format: "xltm",
1049
- contentType: "application/vnd.ms-excel.template.macroEnabled.main+xml",
1050
- decoder: "spreadsheetml",
1051
- macros: true,
1052
- label: "macro-enabled template (.xltm)"
1053
- },
1054
- {
1055
- format: "xlsb",
1056
- contentType: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
1057
- macros: true,
1058
- label: "binary workbook (.xlsb)"
951
+ return false;
952
+ }
953
+ function forbiddenSegment(s, from, to, isTarget) {
954
+ let lastIsDot = false;
955
+ let literalDotSegment = true;
956
+ for (let i = from; i < to; i++) {
957
+ const c = s.charCodeAt(i);
958
+ if (c === 37 && i + 2 < to) {
959
+ const h = s.charCodeAt(i + 1) << 8 | (s.charCodeAt(i + 2) | 32);
960
+ if (h === 12902 || h === 13667) return true;
961
+ if (h === 12901) {
962
+ lastIsDot = true;
963
+ literalDotSegment = false;
964
+ i += 2;
965
+ continue;
966
+ }
967
+ }
968
+ lastIsDot = c === 46;
969
+ if (!lastIsDot) literalDotSegment = false;
1059
970
  }
1060
- ];
1061
- /** Formats recognised by something other than a workbook content type. */
1062
- const OTHER_FORMATS = {
1063
- ods: { label: "OpenDocument spreadsheet (.ods)" },
1064
- cfb: { label: "legacy .xls file or a password-protected (encrypted) workbook" },
1065
- unknown: { label: "file that is not a spreadsheet package" }
1066
- };
1067
- function sniffContainer(b) {
1068
- for (const c of CONTAINERS) if (c.magic.every((x, i) => b[i] === x)) return c.kind;
1069
- return "unknown";
971
+ if (!lastIsDot) return false;
972
+ if (isTarget && literalDotSegment && to - from <= 2) return false;
973
+ return true;
1070
974
  }
1071
975
  /**
1072
- * The workbook format for a workbook part, from its content type; when the
1073
- * content type is missing or unknown, from the part's extension (.bin is
1074
- * binary, anything else is read as SpreadsheetML).
976
+ * Part-name equivalence (OPC, ECMA-376 Part 2 §6.2.2.3 and the zip mapping of
977
+ * §7.3.4): `name` with its percent-escapes decoded once, as UTF-8. Kept
978
+ * encoded (upper-case hex), so that nothing decoded can act as structure or
979
+ * as a new escape: `%2F`, `%5C`, `%25`, a `%` that does not start an escape
980
+ * (written `%25`), and each byte that is not part of a valid UTF-8 sequence.
981
+ * Not lower-cased. Idempotent: canonicalPartName(canonicalPartName(s)) ===
982
+ * canonicalPartName(s). One linear pass, no decoder calls.
1075
983
  */
1076
- function workbookFormat(contentType, partName) {
1077
- const ct = (contentType ?? "").toLowerCase();
1078
- const known = WORKBOOK_FORMATS.find((f) => f.contentType.toLowerCase() === ct);
1079
- if (known) return known;
1080
- if (partName.toLowerCase().endsWith(".bin")) return WORKBOOK_FORMATS.find((f) => f.format === "xlsb");
1081
- return WORKBOOK_FORMATS[0];
984
+ function canonicalPartName(name) {
985
+ let i = name.indexOf("%");
986
+ if (i === -1) return name;
987
+ const n = name.length;
988
+ let out = "";
989
+ /** Start of the input not yet copied: text that canonicalises to itself is copied in one slice. */
990
+ let from = 0;
991
+ const emit = (end, text, next) => {
992
+ out += name.slice(from, end) + text;
993
+ from = next;
994
+ };
995
+ while (i < n) {
996
+ if (name.charCodeAt(i) !== 37) {
997
+ i = name.indexOf("%", i);
998
+ if (i === -1) break;
999
+ continue;
1000
+ }
1001
+ const b = hexByte(name, i);
1002
+ if (b < 0) {
1003
+ emit(i, "%25", i + 1);
1004
+ i++;
1005
+ continue;
1006
+ }
1007
+ if (b === 37 || b === 47 || b === 92 || b >= 128) {
1008
+ const len = b >= 128 ? utf8Length(name, i, b) : 0;
1009
+ if (len) {
1010
+ let cp = len === 2 ? b & 31 : len === 3 ? b & 15 : b & 7;
1011
+ for (let k = 1; k < len; k++) cp = cp << 6 | hexByte(name, i + 3 * k) & 63;
1012
+ emit(i, String.fromCodePoint(cp), i + 3 * len);
1013
+ i += 3 * len;
1014
+ } else {
1015
+ if (name.charCodeAt(i + 1) > 96 || name.charCodeAt(i + 2) > 96) emit(i, HEX[b], i + 3);
1016
+ i += 3;
1017
+ }
1018
+ continue;
1019
+ }
1020
+ emit(i, String.fromCharCode(b), i + 3);
1021
+ i += 3;
1022
+ }
1023
+ return from === 0 ? name : out + name.slice(from);
1082
1024
  }
1083
- // src/internal/read/opc.ts
1025
+ const HEX = Array.from({ length: 256 }, (_, b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`);
1084
1026
  /**
1085
- * Open Packaging Conventions for the reader: part lookup (case-insensitive,
1086
- * as OPC requires), [Content_Types].xml and relationship parts. Internal.
1027
+ * The length in bytes of the valid UTF-8 sequence whose lead byte `b` is the
1028
+ * escape at `i` (its continuation bytes are the escapes that follow), or 0.
1029
+ * Rejects overlong forms, surrogates and code points above U+10FFFF.
1087
1030
  */
1088
- var Package = class {
1089
- ctx;
1090
- parts = /* @__PURE__ */ new Map();
1091
- /** Part name (lower case, no leading '/') -> content type. */
1092
- overrides = /* @__PURE__ */ new Map();
1093
- /** Extension (lower case) -> content type. */
1094
- defaults = /* @__PURE__ */ new Map();
1095
- constructor(ctx) {
1096
- this.ctx = ctx;
1097
- for (const e of ctx.zip.entries) {
1098
- if (e.name.endsWith("/")) continue;
1099
- const key = e.name.toLowerCase();
1100
- if (this.parts.has(key)) throw new FormatError("ZIP_INVALID", `Part names ${excerpt(this.parts.get(key).name)} and ${excerpt(e.name)} differ only in case.`, { details: { entry: e.name } });
1101
- this.parts.set(key, e);
1031
+ function utf8Length(name, i, b) {
1032
+ const len = b >= 194 && b <= 223 ? 2 : b >= 224 && b <= 239 ? 3 : b >= 240 && b <= 244 ? 4 : 0;
1033
+ for (let k = 1; k < len; k++) {
1034
+ const cb = hexByte(name, i + 3 * k);
1035
+ if (cb < 0 || (cb & 192) !== 128) return 0;
1036
+ if (k === 1 && (b === 224 && cb < 160 || b === 237 && cb > 159 || b === 240 && cb < 144 || b === 244 && cb > 143)) return 0;
1037
+ }
1038
+ return len;
1039
+ }
1040
+ /** The byte of the escape `%XX` at `i`, or -1. */
1041
+ function hexByte(s, i) {
1042
+ if (s.charCodeAt(i) !== 37 || i + 2 >= s.length) return -1;
1043
+ const h = hexDigit(s.charCodeAt(i + 1));
1044
+ const l = hexDigit(s.charCodeAt(i + 2));
1045
+ return h < 0 || l < 0 ? -1 : h << 4 | l;
1046
+ }
1047
+ function hexDigit(c) {
1048
+ if (c >= 48 && c <= 57) return c - 48;
1049
+ const l = c | 32;
1050
+ return l >= 97 && l <= 102 ? l - 97 + 10 : -1;
1051
+ }
1052
+ /** The lookup key of a part name: canonical, no leading '/', lower case (part names compare case-insensitively). */
1053
+ function partKey(name) {
1054
+ return canonicalPartName(stripSlash(name)).toLowerCase();
1055
+ }
1056
+ /**
1057
+ * Resolves a relationship target against the source part's folder, as a
1058
+ * decoder reads it (and as 2.4.0 did): `/`, `\`, `%2F` and `%5C` separate
1059
+ * segments, and a segment that is `.` or `..` once `%2E` is decoded is a dot
1060
+ * segment. Each other segment is put in canonical form once. For a target
1061
+ * OPC allows this is the only reading; for others, see resolveTargetLiteral.
1062
+ */
1063
+ function resolveTarget(baseDir, target) {
1064
+ return resolveReadings(baseDir, target).target;
1065
+ }
1066
+ /**
1067
+ * Both readings of a relationship target. `target` is the one `read` uses,
1068
+ * as 2.4.0 resolved it: decoded (resolveTargetDecoded), or, when the target
1069
+ * has an escape that is not valid UTF-8 or a `%` that starts no escape (2.4.0's
1070
+ * decodeURIComponent threw and the target was kept raw), literal
1071
+ * (resolveTargetLiteral). `alt` is the other reading, when the target has
1072
+ * an escape that can change its structure (`%2F`, `%5C`, `%2E`).
1073
+ */
1074
+ function resolveReadings(baseDir, target) {
1075
+ const t = stripFragment(target);
1076
+ const structural = /%(2f|5c|2e)/i.test(t);
1077
+ if (malformedEscapes(t)) {
1078
+ const literal = resolveTargetLiteral(baseDir, t);
1079
+ return structural ? {
1080
+ target: literal,
1081
+ alt: resolveTargetDecoded(baseDir, t)
1082
+ } : { target: literal };
1083
+ }
1084
+ const decoded = resolveTargetDecoded(baseDir, t);
1085
+ return structural ? {
1086
+ target: decoded,
1087
+ alt: resolveTargetLiteral(baseDir, t)
1088
+ } : { target: decoded };
1089
+ }
1090
+ /** True when decodeURIComponent would throw: a `%` that starts no escape, or escapes that are not valid UTF-8. Linear. */
1091
+ function malformedEscapes(name) {
1092
+ let i = name.indexOf("%");
1093
+ while (i !== -1) {
1094
+ const b = hexByte(name, i);
1095
+ if (b < 0) return true;
1096
+ if (b < 128) i += 3;
1097
+ else {
1098
+ const len = utf8Length(name, i, b);
1099
+ if (!len) return true;
1100
+ i += 3 * len;
1102
1101
  }
1102
+ i = name.indexOf("%", i);
1103
+ }
1104
+ return false;
1105
+ }
1106
+ /**
1107
+ * The decoder's reading: `/`, `\`, `%2F` and `%5C` separate segments, and a
1108
+ * segment that is `.` or `..` once `%2E` is decoded is a dot segment. Each
1109
+ * other segment is put in canonical form once.
1110
+ */
1111
+ function resolveTargetDecoded(baseDir, target) {
1112
+ const t = stripFragment(target).replace(/%2f|%5c|\\/gi, "/");
1113
+ const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== "");
1114
+ for (const seg of t.split("/")) {
1115
+ const dots = seg.length <= 6 ? seg.replace(/%2e/gi, ".") : seg;
1116
+ if (dots === "" || dots === ".") continue;
1117
+ if (dots === "..") segments.pop();
1118
+ else segments.push(canonicalPartName(seg));
1119
+ }
1120
+ return segments.join("/");
1121
+ }
1122
+ /**
1123
+ * Resolves a relationship target taking every escape literally: only `/` and
1124
+ * `\` separate segments and only literal `.` and `..` are dot segments, so
1125
+ * `%2E%2E`, `%2F` and `%5C` stay part of a name.
1126
+ */
1127
+ function resolveTargetLiteral(baseDir, target) {
1128
+ const t = stripFragment(target).replace(/\\/g, "/");
1129
+ const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== "");
1130
+ for (const seg of t.split("/")) {
1131
+ if (seg === "" || seg === ".") continue;
1132
+ if (seg === "..") segments.pop();
1133
+ else segments.push(canonicalPartName(seg));
1134
+ }
1135
+ return segments.join("/");
1136
+ }
1137
+ // src/internal/zip/read.ts
1138
+ /**
1139
+ * Zip container reader (docs/api.md §6, §8). Internal.
1140
+ *
1141
+ * `openZip` parses the central directory synchronously and validates the whole
1142
+ * layout before any data is inflated:
1143
+ * - end-of-central-directory record, with zip64 records when present;
1144
+ * - single-disk archives only;
1145
+ * - every entry's local header must agree with its central record;
1146
+ * - entry data must not overlap other entries or the central directory;
1147
+ * - duplicate names, encryption and methods other than 0 and 8 are rejected.
1148
+ *
1149
+ * Reading an entry counts the actual decompressed bytes against the limits
1150
+ * (never trusting declared sizes), stops when an entry produces more than it
1151
+ * declared, and verifies its CRC-32.
1152
+ */
1153
+ /** The zip-related defaults of docs/api.md §5.2, the same values as DEFAULT_READ_LIMITS (measured in JSE-6). */
1154
+ const DEFAULT_ZIP_LIMITS = Object.freeze({
1155
+ maxInputBytes: 268435456,
1156
+ maxEntries: 1e4,
1157
+ maxEntryBytes: 536870912,
1158
+ maxTotalBytes: 1073741824,
1159
+ maxRatio: 1e3
1160
+ });
1161
+ const SIG_LOCAL = 67324752;
1162
+ const SIG_CENTRAL = 33639248;
1163
+ const SIG_EOCD = 101010256;
1164
+ const SIG_ZIP64_EOCD = 101075792;
1165
+ const SIG_ZIP64_LOCATOR = 117853008;
1166
+ const FLAG_ENCRYPTED = 1;
1167
+ const FLAG_DATA_DESCRIPTOR = 8;
1168
+ const FLAG_UTF8 = 2048;
1169
+ const EXTRA_ZIP64 = 1;
1170
+ const EXTRA_UNICODE_PATH = 28789;
1171
+ const METHOD_AES = 99;
1172
+ /** Code page 437, bytes 0x80..0xFF: the spec's default encoding for names without bit 11. */
1173
+ const CP437_HIGH = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
1174
+ function invalid(message, details) {
1175
+ return new FormatError("ZIP_INVALID", message, details ? { details } : void 0);
1176
+ }
1177
+ function limitError(limit, value, max, what) {
1178
+ return new LimitError("LIMIT_EXCEEDED", `${what} exceeds the ${limit} limit (${max}).`, { details: {
1179
+ limit,
1180
+ value,
1181
+ max
1182
+ } });
1183
+ }
1184
+ var Cursor = class {
1185
+ bytes;
1186
+ pos;
1187
+ view;
1188
+ constructor(bytes, pos) {
1189
+ this.bytes = bytes;
1190
+ this.pos = pos;
1191
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1192
+ }
1193
+ need(n) {
1194
+ if (this.pos < 0 || this.pos + n > this.bytes.length) throw invalid("Unexpected end of zip data.");
1103
1195
  }
1104
- part(name) {
1105
- return this.parts.get(stripSlash(name).toLowerCase());
1196
+ u16() {
1197
+ this.need(2);
1198
+ const v = this.view.getUint16(this.pos, true);
1199
+ this.pos += 2;
1200
+ return v;
1106
1201
  }
1107
- get partNames() {
1108
- return [...this.parts.values()].map((e) => e.name);
1202
+ u32() {
1203
+ this.need(4);
1204
+ const v = this.view.getUint32(this.pos, true);
1205
+ this.pos += 4;
1206
+ return v;
1109
1207
  }
1110
- async loadContentTypes() {
1111
- const entry = this.part("[Content_Types].xml");
1112
- if (!entry) return;
1113
- await this.ctx.parse(entry, {
1114
- open: (name, a) => {
1115
- if (name === "Default") {
1116
- const ext = a.get("Extension");
1117
- const type = a.get("ContentType");
1118
- if (ext && type) this.defaults.set(ext.toLowerCase(), type);
1119
- } else if (name === "Override") {
1120
- const part = a.get("PartName");
1121
- const type = a.get("ContentType");
1122
- if (part && type) this.overrides.set(stripSlash(part).toLowerCase(), type);
1123
- }
1124
- },
1125
- close: () => {},
1126
- text: () => {}
1127
- });
1208
+ u64() {
1209
+ const lo = this.u32();
1210
+ const v = this.u32() * 4294967296 + lo;
1211
+ if (!Number.isSafeInteger(v)) throw invalid("Zip64 value out of range.");
1212
+ return v;
1128
1213
  }
1129
- contentType(name) {
1130
- const key = stripSlash(name).toLowerCase();
1131
- const o = this.overrides.get(key);
1132
- if (o) return o;
1133
- const dot = key.lastIndexOf(".");
1134
- return dot === -1 ? void 0 : this.defaults.get(key.slice(dot + 1));
1214
+ take(n) {
1215
+ this.need(n);
1216
+ const out = this.bytes.subarray(this.pos, this.pos + n);
1217
+ this.pos += n;
1218
+ return out;
1135
1219
  }
1136
- /** Content types of all overrides (for format detection). */
1137
- get overrideTypes() {
1138
- return [...this.overrides.values()];
1220
+ };
1221
+ function decodeName(raw, flags, extra) {
1222
+ if (flags & FLAG_UTF8) try {
1223
+ return decodeUtf8Strict(raw);
1224
+ } catch {
1225
+ throw invalid("Entry name is not valid UTF-8.");
1139
1226
  }
1140
- /** Relationships of `source` ('' for the package). Missing rels part: []. */
1141
- async rels(source) {
1142
- const src = stripSlash(source);
1143
- const slash = src.lastIndexOf("/");
1144
- const dir = slash === -1 ? "" : src.slice(0, slash + 1);
1145
- const relsName = `${dir}_rels/${slash === -1 ? src : src.slice(slash + 1)}.rels`;
1146
- const entry = this.part(relsName);
1147
- if (!entry) return [];
1148
- const out = [];
1149
- await this.ctx.parse(entry, {
1150
- open: (name, a) => {
1151
- if (name !== "Relationship") return;
1152
- const id = a.get("Id");
1153
- const type = a.get("Type");
1154
- const target = a.get("Target");
1155
- if (!id || !type || target === void 0) return;
1156
- const external = (a.get("TargetMode") ?? "").toLowerCase() === "external";
1157
- out.push({
1158
- id,
1159
- type,
1160
- kind: type.slice(type.lastIndexOf("/") + 1),
1161
- target: external ? target : resolveTarget(dir, target),
1162
- external
1163
- });
1164
- },
1165
- close: () => {},
1166
- text: () => {}
1227
+ const unicode = findExtra(extra, EXTRA_UNICODE_PATH);
1228
+ if (unicode && unicode.length >= 5 && unicode[0] === 1) {
1229
+ if (new Cursor(unicode, 1).u32() === crc32(raw)) try {
1230
+ return decodeUtf8Strict(unicode.subarray(5));
1231
+ } catch {}
1232
+ }
1233
+ let s = "";
1234
+ for (const b of raw) s += b < 128 ? String.fromCharCode(b) : CP437_HIGH[b - 128];
1235
+ return s;
1236
+ }
1237
+ function findExtra(extra, id) {
1238
+ const c = new Cursor(extra, 0);
1239
+ while (c.pos + 4 <= extra.length) {
1240
+ const tag = c.u16();
1241
+ const len = c.u16();
1242
+ if (c.pos + len > extra.length) return void 0;
1243
+ const body = c.take(len);
1244
+ if (tag === id) return body;
1245
+ }
1246
+ }
1247
+ function findEocd(bytes) {
1248
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1249
+ const last = bytes.length - 22;
1250
+ const first = Math.max(0, last - 65535);
1251
+ for (let p = last; p >= first; p--) if (view.getUint32(p, true) === SIG_EOCD) {
1252
+ const commentLength = view.getUint16(p + 20, true);
1253
+ if (p + 22 + commentLength <= bytes.length) return p;
1254
+ }
1255
+ throw invalid("Not a zip file: no end-of-central-directory record.");
1256
+ }
1257
+ /** Bytes of a stored entry checksummed between two abort checks. */
1258
+ const STORED_CRC_STEP = 1048576;
1259
+ /** Parses and validates the archive layout. Does not inflate anything. */
1260
+ function openZip(bytes, options = {}) {
1261
+ const limits = {
1262
+ ...DEFAULT_ZIP_LIMITS,
1263
+ ...options.limits
1264
+ };
1265
+ const codec = options.codec ?? nativeCodec;
1266
+ if (bytes.length > limits.maxInputBytes) throw limitError("maxInputBytes", bytes.length, limits.maxInputBytes, "Input size");
1267
+ if (bytes.length < 22) throw invalid("Not a zip file: too short.");
1268
+ const eocdPos = findEocd(bytes);
1269
+ const e = new Cursor(bytes, eocdPos + 4);
1270
+ const disk = e.u16();
1271
+ const cdDisk = e.u16();
1272
+ const entriesOnDisk = e.u16();
1273
+ let entryCount = e.u16();
1274
+ let cdSize = e.u32();
1275
+ let cdOffset = e.u32();
1276
+ let cdLimit = eocdPos;
1277
+ if (eocdPos >= 20 && new Cursor(bytes, eocdPos - 20).u32() === SIG_ZIP64_LOCATOR) {
1278
+ const l = new Cursor(bytes, eocdPos - 16);
1279
+ const z64Disk = l.u32();
1280
+ const z64Pos = l.u64();
1281
+ const totalDisks = l.u32();
1282
+ if (z64Disk !== 0 || totalDisks > 1) throw invalid("Multi-disk zip archives are not supported.");
1283
+ if (z64Pos + 56 > eocdPos - 20) throw invalid("Zip64 end-of-central-directory record out of range.");
1284
+ const z = new Cursor(bytes, z64Pos);
1285
+ if (z.u32() !== SIG_ZIP64_EOCD) throw invalid("Bad zip64 end-of-central-directory signature.");
1286
+ z.u64();
1287
+ z.u16();
1288
+ z.u16();
1289
+ const z64ThisDisk = z.u32();
1290
+ const z64CdDisk = z.u32();
1291
+ z.u64();
1292
+ entryCount = z.u64();
1293
+ cdSize = z.u64();
1294
+ cdOffset = z.u64();
1295
+ if (z64ThisDisk !== 0 || z64CdDisk !== 0) throw invalid("Multi-disk zip archives are not supported.");
1296
+ cdLimit = z64Pos;
1297
+ } else {
1298
+ if (disk !== 0 || cdDisk !== 0 || entriesOnDisk !== entryCount) throw invalid("Multi-disk zip archives are not supported.");
1299
+ if (entryCount === 65535 || cdSize === 4294967295 || cdOffset === 4294967295) throw invalid("Zip64 values without a zip64 end-of-central-directory locator.");
1300
+ }
1301
+ if (entryCount > limits.maxEntries) throw limitError("maxEntries", entryCount, limits.maxEntries, "Entry count");
1302
+ if (cdOffset + cdSize > cdLimit) throw invalid("Central directory out of range.");
1303
+ if (entryCount * 46 > cdSize) throw invalid("Central directory too small for its entry count.");
1304
+ const entries = [];
1305
+ const byName = /* @__PURE__ */ new Map();
1306
+ const spans = [];
1307
+ const c = new Cursor(bytes.subarray(0, cdOffset + cdSize), cdOffset);
1308
+ for (let i = 0; i < entryCount; i++) {
1309
+ if (c.u32() !== SIG_CENTRAL) throw invalid("Bad central directory signature.", { index: i });
1310
+ c.u16();
1311
+ c.u16();
1312
+ const flags = c.u16();
1313
+ const method = c.u16();
1314
+ const time = c.u16();
1315
+ const date = c.u16();
1316
+ const crc = c.u32();
1317
+ let compressedSize = c.u32();
1318
+ let size = c.u32();
1319
+ const nameLength = c.u16();
1320
+ const extraLength = c.u16();
1321
+ const commentLength = c.u16();
1322
+ let diskStart = c.u16();
1323
+ c.u16();
1324
+ c.u32();
1325
+ let localOffset = c.u32();
1326
+ const rawName = c.take(nameLength);
1327
+ const extra = c.take(extraLength);
1328
+ c.take(commentLength);
1329
+ const z64 = findExtra(extra, EXTRA_ZIP64);
1330
+ if (z64) {
1331
+ const x = new Cursor(z64, 0);
1332
+ if (size === 4294967295) size = x.u64();
1333
+ if (compressedSize === 4294967295) compressedSize = x.u64();
1334
+ if (localOffset === 4294967295) localOffset = x.u64();
1335
+ if (diskStart === 65535) diskStart = x.u32();
1336
+ }
1337
+ if (diskStart !== 0) throw invalid("Multi-disk zip archives are not supported.");
1338
+ const name = decodeName(rawName, flags, extra);
1339
+ if (flags & 65 || method === METHOD_AES) throw new FormatError("ZIP_ENCRYPTED", `Entry ${excerpt(name)} is encrypted.`, { details: { entry: name } });
1340
+ if (method !== 0 && method !== 8) throw new FormatError("ZIP_UNSUPPORTED_METHOD", `Entry ${excerpt(name)} uses compression method ${method}.`, { details: {
1341
+ entry: name,
1342
+ method
1343
+ } });
1344
+ if (method === 0 && compressedSize !== size) throw invalid(`Stored entry ${excerpt(name)} has mismatched sizes.`);
1345
+ if (byName.has(name)) throw invalid(`Duplicate entry name: ${excerpt(name)}`, { entry: name });
1346
+ const l = new Cursor(bytes, localOffset);
1347
+ if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${excerpt(name)}.`, { entry: name });
1348
+ l.u16();
1349
+ const lFlags = l.u16();
1350
+ const lMethod = l.u16();
1351
+ l.u16();
1352
+ l.u16();
1353
+ const lCrc = l.u32();
1354
+ const lCompressed = l.u32();
1355
+ const lSize = l.u32();
1356
+ const lNameLength = l.u16();
1357
+ const lExtraLength = l.u16();
1358
+ const lName = l.take(lNameLength);
1359
+ l.take(lExtraLength);
1360
+ let agrees = lNameLength === nameLength && lName.every((b, k) => b === rawName[k]) && lMethod === method && (lFlags & FLAG_ENCRYPTED) === 0;
1361
+ if (agrees && !(lFlags & FLAG_DATA_DESCRIPTOR)) agrees = lCrc === crc && (lCompressed === compressedSize || lCompressed === 4294967295) && (lSize === size || lSize === 4294967295);
1362
+ if (!agrees) throw invalid(`Local header disagrees with the central directory for ${excerpt(name)}.`, { entry: name });
1363
+ const dataOffset = l.pos;
1364
+ const dataEnd = dataOffset + compressedSize;
1365
+ if (dataEnd > cdOffset) throw invalid(`Data of ${excerpt(name)} runs into the central directory.`, { entry: name });
1366
+ spans.push({
1367
+ start: localOffset,
1368
+ end: dataEnd,
1369
+ name
1167
1370
  });
1168
- return out;
1371
+ const info = Object.freeze({
1372
+ name,
1373
+ method,
1374
+ flags,
1375
+ crc32: crc,
1376
+ compressedSize,
1377
+ size,
1378
+ modified: fromDosDateTime(date, time),
1379
+ dataOffset
1380
+ });
1381
+ entries.push(info);
1382
+ byName.set(name, info);
1383
+ }
1384
+ spans.sort((a, b) => a.start - b.start);
1385
+ 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.`);
1386
+ let totalBytesRead = 0;
1387
+ const resolve = (entry) => {
1388
+ const info = typeof entry === "string" ? byName.get(entry) : entry;
1389
+ if (!info || byName.get(info.name) !== info) throw new Error(`No such zip entry: ${typeof entry === "string" ? entry : entry.name}`);
1390
+ return info;
1391
+ };
1392
+ const countTotal = (n) => {
1393
+ totalBytesRead += n;
1394
+ if (totalBytesRead > limits.maxTotalBytes) throw limitError("maxTotalBytes", totalBytesRead, limits.maxTotalBytes, "Total decompressed size");
1395
+ };
1396
+ async function* stream(entry, signal) {
1397
+ const info = resolve(entry);
1398
+ throwIfAborted$1(signal);
1399
+ if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${excerpt(info.name)}`);
1400
+ const data = bytes.subarray(info.dataOffset, info.dataOffset + info.compressedSize);
1401
+ let crc = 0;
1402
+ let produced = 0;
1403
+ if (info.method === 0) {
1404
+ countTotal(data.length);
1405
+ for (let at = 0; at < data.length; at += STORED_CRC_STEP) {
1406
+ if (at > 0) throwIfAborted$1(signal);
1407
+ crc = crc32(data.subarray(at, at + STORED_CRC_STEP), crc);
1408
+ }
1409
+ produced = data.length;
1410
+ if (crc !== info.crc32) throw crcMismatch(info);
1411
+ yield data;
1412
+ return;
1413
+ }
1414
+ const chunks = codec.inflateRaw(data, {
1415
+ maxOutputBytes: limits.maxEntryBytes,
1416
+ maxRatio: limits.maxRatio
1417
+ }, signal);
1418
+ for await (const chunk of chunks) {
1419
+ produced += chunk.length;
1420
+ if (produced > info.size) throw invalid(`Entry ${excerpt(info.name)} is larger than declared.`, { entry: info.name });
1421
+ countTotal(chunk.length);
1422
+ crc = crc32(chunk, crc);
1423
+ yield chunk;
1424
+ }
1425
+ if (produced !== info.size) throw invalid(`Entry ${excerpt(info.name)} is smaller than declared.`, { entry: info.name });
1426
+ if (crc !== info.crc32) throw crcMismatch(info);
1169
1427
  }
1170
- };
1171
- function stripSlash(name) {
1172
- return name.startsWith("/") ? name.slice(1) : name;
1428
+ return {
1429
+ entries,
1430
+ get: (name) => byName.get(name),
1431
+ stream,
1432
+ async read(entry, signal) {
1433
+ const parts = [];
1434
+ for await (const chunk of stream(entry, signal)) parts.push(chunk);
1435
+ return concatBytes(parts);
1436
+ },
1437
+ get totalBytesRead() {
1438
+ return totalBytesRead;
1439
+ }
1440
+ };
1173
1441
  }
1174
- /** Resolves a relationship target against the source part's folder (RFC 3986 dot segments, '%xx' decoded). */
1175
- function resolveTarget(baseDir, target) {
1176
- let t = target;
1177
- const hash = t.indexOf("#");
1178
- if (hash !== -1) t = t.slice(0, hash);
1179
- try {
1180
- t = decodeURIComponent(t);
1181
- } catch {}
1182
- t = t.replace(/\\/g, "/");
1183
- const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== "");
1184
- for (const seg of t.split("/")) {
1185
- if (seg === "" || seg === ".") continue;
1186
- if (seg === "..") segments.pop();
1187
- else segments.push(seg);
1188
- }
1189
- return segments.join("/");
1442
+ function crcMismatch(info) {
1443
+ return new FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${excerpt(info.name)}.`, { details: { entry: info.name } });
1190
1444
  }
1191
1445
  // src/internal/read/formula.ts
1192
1446
  /**
@@ -1411,7 +1665,215 @@ function shiftCompiled(c, dRow, dCol, maxLength = 1e400) {
1411
1665
  shiftWork.shiftedChars += out.length;
1412
1666
  return out;
1413
1667
  }
1668
+ /** The length of a copy shifted by (dRow, dCol), from formulaShape's `fixed` and partsOf's records; the offset must pass `canShift`. */
1669
+ function shiftedLength(fixed, parts, dRow, dCol) {
1670
+ let n = fixed;
1671
+ for (let i = 0; i < parts.length; i += 3) {
1672
+ const v = parts[i + 1] + (parts[i] ? dRow : dCol);
1673
+ n += parts[i + 2] * (parts[i] ? digitCount(v) : v <= 26 ? 1 : v <= 702 ? 2 : 3);
1674
+ }
1675
+ return n;
1676
+ }
1677
+ function digitCount(v) {
1678
+ let d = 1;
1679
+ while (v >= 10) {
1680
+ v = Math.floor(v / 10);
1681
+ d++;
1682
+ }
1683
+ return d;
1684
+ }
1685
+ /**
1686
+ * One pass over a master's text (JSE-71), allocating nothing per reference:
1687
+ * the relative bounds as compileFormula gives them, the range of a copy's
1688
+ * length and the characters that never change (the tests compute both from
1689
+ * the compiled formula too); with `collectParts`, the relative parts. It walks the text as
1690
+ * compileFormula does and recognises references as parseRef does (the tests
1691
+ * compare the two on seeded formulas), so a copy's text is the original's
1692
+ * with each reference re-printed as refText prints it.
1693
+ */
1694
+ function formulaShape(formula, collectParts) {
1695
+ let rowMin = 1e400;
1696
+ let rowMax = -1e400;
1697
+ let colMin = 1e400;
1698
+ let colMax = -1e400;
1699
+ let fixed = formula.length;
1700
+ let relCols = 0;
1701
+ let relRows = 0;
1702
+ const keys = [];
1703
+ const col = (anchored, v) => {
1704
+ if (anchored) fixed += 1 + (v <= 26 ? 1 : v <= 702 ? 2 : 3);
1705
+ else {
1706
+ relCols++;
1707
+ if (v < colMin) colMin = v;
1708
+ if (v > colMax) colMax = v;
1709
+ if (collectParts) keys.push(v * 2);
1710
+ }
1711
+ };
1712
+ const row = (anchored, v) => {
1713
+ if (anchored) fixed += 1 + digitCount(v);
1714
+ else {
1715
+ relRows++;
1716
+ if (v < rowMin) rowMin = v;
1717
+ if (v > rowMax) rowMax = v;
1718
+ if (collectParts) keys.push(v * 2 + 1);
1719
+ }
1720
+ };
1721
+ const n = formula.length;
1722
+ let i = 0;
1723
+ while (i < n) {
1724
+ const code = formula.charCodeAt(i);
1725
+ if (code === 34 || code === 39) {
1726
+ let j = i + 1;
1727
+ for (; j < n; j++) if (formula.charCodeAt(j) === code) {
1728
+ if (formula.charCodeAt(j + 1) === code) j++;
1729
+ else break;
1730
+ }
1731
+ i = j + 1;
1732
+ continue;
1733
+ }
1734
+ if (code === 91) {
1735
+ let depth = 0;
1736
+ let j = i;
1737
+ for (; j < n; j++) {
1738
+ const c = formula.charCodeAt(j);
1739
+ if (c === 91) depth++;
1740
+ else if (c === 93 && --depth === 0) break;
1741
+ }
1742
+ i = j + 1;
1743
+ continue;
1744
+ }
1745
+ const prev = i > 0 ? formula.charCodeAt(i - 1) : -1;
1746
+ if ((code === 36 || isAlnumCode(code)) && !isWordCode(prev) && prev !== 36) {
1747
+ const end = refAt(formula, i);
1748
+ if (end >= 0) {
1749
+ fixed -= end - i;
1750
+ const r = REF;
1751
+ if (r.kind === COLS_REF) {
1752
+ col(r.aAnchored, r.a);
1753
+ col(r.bAnchored, r.b);
1754
+ fixed += 1;
1755
+ } else if (r.kind === ROWS_REF) {
1756
+ row(r.aAnchored, r.a);
1757
+ row(r.bAnchored, r.b);
1758
+ fixed += 1;
1759
+ } else {
1760
+ col(r.aAnchored, r.a);
1761
+ row(r.bAnchored, r.b);
1762
+ }
1763
+ i = end;
1764
+ continue;
1765
+ }
1766
+ let j = i + 1;
1767
+ while (j < n && isWordCode(formula.charCodeAt(j))) j++;
1768
+ i = j;
1769
+ continue;
1770
+ }
1771
+ i++;
1772
+ }
1773
+ return {
1774
+ rowMin,
1775
+ rowMax,
1776
+ colMin,
1777
+ colMax,
1778
+ min: fixed + relCols + relRows,
1779
+ max: fixed + 3 * relCols + 7 * relRows,
1780
+ fixed,
1781
+ keys
1782
+ };
1783
+ }
1784
+ /** refAt's result, reused (formulaShape reads it before the next call). */
1785
+ const REF = {
1786
+ kind: CELL_REF,
1787
+ aAnchored: false,
1788
+ a: 0,
1789
+ bAnchored: false,
1790
+ b: 0
1791
+ };
1792
+ /** parseRef without allocating: the reference at `i` into REF and the index after it, or -1. */
1793
+ function refAt(f, i) {
1794
+ const n = f.length;
1795
+ const aAnchored = f.charCodeAt(i) === 36;
1796
+ const p = i + (aAnchored ? 1 : 0);
1797
+ let la = 0;
1798
+ while (la < 3 && p + la < n && isLetterCode(f.charCodeAt(p + la))) la++;
1799
+ let da = 0;
1800
+ if (la === 0) while (da < 7 && p + da < n && isDigitCode(f.charCodeAt(p + da))) da++;
1801
+ const first = la || da;
1802
+ if (first > 0 && f.charCodeAt(p + first) === 58) {
1803
+ const q = p + first + 1;
1804
+ const bAnchored = q < n && f.charCodeAt(q) === 36;
1805
+ const r = q + (bAnchored ? 1 : 0);
1806
+ let second = 0;
1807
+ if (la) while (second < 3 && r + second < n && isLetterCode(f.charCodeAt(r + second))) second++;
1808
+ else while (second < 7 && r + second < n && isDigitCode(f.charCodeAt(r + second))) second++;
1809
+ if (second > 0 && isEnd(f, r + second)) {
1810
+ if (la) {
1811
+ const a = colAt(f, p, la);
1812
+ const b = colAt(f, r, second);
1813
+ if (a > MAX_COL || b > MAX_COL) return -1;
1814
+ return setRef(COLS_REF, aAnchored, a, bAnchored, b, r + second);
1815
+ }
1816
+ return setRef(ROWS_REF, aAnchored, digitsAt(f, p, da), bAnchored, digitsAt(f, r, second), r + second);
1817
+ }
1818
+ }
1819
+ if (la > 0) {
1820
+ const q = p + la;
1821
+ const bAnchored = f.charCodeAt(q) === 36;
1822
+ const r = q + (bAnchored ? 1 : 0);
1823
+ let digits = 0;
1824
+ while (digits < 7 && r + digits < n && isDigitCode(f.charCodeAt(r + digits))) digits++;
1825
+ if (digits > 0 && isEnd(f, r + digits)) {
1826
+ const c = colAt(f, p, la);
1827
+ if (c > MAX_COL) return -1;
1828
+ return setRef(CELL_REF, aAnchored, c, bAnchored, digitsAt(f, r, digits), r + digits);
1829
+ }
1830
+ }
1831
+ return -1;
1832
+ }
1833
+ function setRef(kind, aAnchored, a, bAnchored, b, end) {
1834
+ REF.kind = kind;
1835
+ REF.aAnchored = aAnchored;
1836
+ REF.a = a;
1837
+ REF.bAnchored = bAnchored;
1838
+ REF.b = b;
1839
+ return end;
1840
+ }
1841
+ /** formulaShape's keys as records: triples (isRow, value, count), one per distinct relative part. */
1842
+ /** partsOf's sort buffer, reused so that sorting allocates nothing. */
1843
+ let sortScratch = /* @__PURE__ */ new Int32Array(256);
1844
+ function partsOf(list) {
1845
+ if (sortScratch.length < list.length) sortScratch = new Int32Array(Math.max(list.length, 2 * sortScratch.length));
1846
+ const keys = sortScratch.subarray(0, list.length);
1847
+ keys.set(list);
1848
+ keys.sort();
1849
+ let distinct = 0;
1850
+ for (let i = 0; i < keys.length; i++) if (i === 0 || keys[i] !== keys[i - 1]) distinct++;
1851
+ const out = new Array(distinct * 3).fill(0);
1852
+ let o = -3;
1853
+ for (let i = 0; i < keys.length; i++) {
1854
+ const k = keys[i];
1855
+ if (i === 0 || k !== keys[i - 1]) {
1856
+ o += 3;
1857
+ out[o] = k & 1;
1858
+ out[o + 1] = Math.floor(k / 2);
1859
+ }
1860
+ out[o + 2] = out[o + 2] + 1;
1861
+ }
1862
+ return out;
1863
+ }
1414
1864
  /** Whether a reference may end before `end`: no word character, `(`, `!` or `$` follows. */
1865
+ /** colNumber(f.slice(at, at + n)) without the slice; `n` ASCII letters. */
1866
+ function colAt(f, at, n) {
1867
+ let v = 0;
1868
+ for (let k = 0; k < n; k++) v = v * 26 + ((f.charCodeAt(at + k) & -33) - 64);
1869
+ return v;
1870
+ }
1871
+ /** Number(f.slice(at, at + n)) without the slice; `n` (at most 7) ASCII digits. */
1872
+ function digitsAt(f, at, n) {
1873
+ let v = 0;
1874
+ for (let k = 0; k < n; k++) v = v * 10 + (f.charCodeAt(at + k) - 48);
1875
+ return v;
1876
+ }
1415
1877
  function isEnd(f, end) {
1416
1878
  if (end >= f.length) return true;
1417
1879
  const c = f.charCodeAt(end);
@@ -2160,7 +2622,10 @@ var SharedStringsParser = class {
2160
2622
  stopAfter;
2161
2623
  charge;
2162
2624
  maxText;
2625
+ keep;
2163
2626
  strings = [];
2627
+ /** Items decoded so far; with `keep` false, the only record of them (inspect, JSE-71). */
2628
+ count = 0;
2164
2629
  item;
2165
2630
  depth = 0;
2166
2631
  control;
@@ -2168,12 +2633,13 @@ var SharedStringsParser = class {
2168
2633
  * `stopAfter`: decode only the first `stopAfter` items, then jump to the
2169
2634
  * end of the part without tokenizing the rest (previews, ReadOptions.maxRows).
2170
2635
  */
2171
- constructor(mode, max, stopAfter = 1e400, charge = () => {}, maxText = 1e400) {
2636
+ constructor(mode, max, stopAfter = 1e400, charge = () => {}, maxText = 1e400, keep = true) {
2172
2637
  this.mode = mode;
2173
2638
  this.max = max;
2174
2639
  this.stopAfter = stopAfter;
2175
2640
  this.charge = charge;
2176
2641
  this.maxText = maxText;
2642
+ this.keep = keep;
2177
2643
  }
2178
2644
  attach(control) {
2179
2645
  this.control = control;
@@ -2181,8 +2647,10 @@ var SharedStringsParser = class {
2181
2647
  }
2182
2648
  /** True once stopAfter items were decoded and the rest of the part is skipped. */
2183
2649
  stopped = false;
2184
- pushed() {
2185
- if (this.strings.length >= this.stopAfter && !this.stopped && this.control) {
2650
+ push(item) {
2651
+ if (this.keep) this.strings.push(item);
2652
+ this.count++;
2653
+ if (this.count >= this.stopAfter && !this.stopped && this.control) {
2186
2654
  this.stopped = true;
2187
2655
  this.control.skipToEndOf(1);
2188
2656
  }
@@ -2199,15 +2667,13 @@ var SharedStringsParser = class {
2199
2667
  return;
2200
2668
  }
2201
2669
  if (name === "si") {
2202
- if (this.strings.length >= this.max) throw new LimitError("LIMIT_EXCEEDED", `More than maxSharedStrings (${this.max}) shared strings.`, { details: {
2670
+ if (this.count >= this.max) throw new LimitError("LIMIT_EXCEEDED", `More than maxSharedStrings (${this.max}) shared strings.`, { details: {
2203
2671
  limit: "maxSharedStrings",
2204
- value: this.strings.length + 1,
2672
+ value: this.count + 1,
2205
2673
  max: this.max
2206
2674
  } });
2207
- if (empty) {
2208
- this.strings.push("");
2209
- this.pushed();
2210
- } else {
2675
+ if (empty) this.push("");
2676
+ else {
2211
2677
  this.item = new StringItem(this.charge, this.maxText);
2212
2678
  this.depth = 0;
2213
2679
  }
@@ -2216,9 +2682,9 @@ var SharedStringsParser = class {
2216
2682
  close(name) {
2217
2683
  if (!this.item) return;
2218
2684
  if (this.depth === 0 && name === "si") {
2219
- this.strings.push(this.item.value(this.mode));
2685
+ const value = this.item.value(this.mode);
2220
2686
  this.item = void 0;
2221
- this.pushed();
2687
+ this.push(value);
2222
2688
  return;
2223
2689
  }
2224
2690
  this.depth--;
@@ -2286,6 +2752,34 @@ var DeferredStrings = class {
2286
2752
  }
2287
2753
  }
2288
2754
  };
2755
+ /** Bytes (UTF-8) of shared-formula masters a sheet keeps, at most, until a copy needs them (inspect, JSE-71). */
2756
+ const PENDING_TEXT = 8388608;
2757
+ /**
2758
+ * A shared formula's master as inspect keeps it (keepCells false, JSE-71):
2759
+ * numbers only, in one small object; the bounds are canShift's.
2760
+ */
2761
+ const UTF8 = new globalThis.TextEncoder();
2762
+ const UTF8_TEXT = new globalThis.TextDecoder();
2763
+ var LeanMaster = class {
2764
+ row;
2765
+ col;
2766
+ length;
2767
+ rowMin = 1e400;
2768
+ rowMax = -1e400;
2769
+ colMin = 1e400;
2770
+ colMax = -1e400;
2771
+ /** Whether every copy fits maxCellTextLength; `parts`, when set, decides per copy instead. */
2772
+ fits = false;
2773
+ fixed = 0;
2774
+ parts = void 0;
2775
+ /** The master's text, as UTF-8, until it is shaped (setLean); then undefined. */
2776
+ text = void 0;
2777
+ constructor(row, col, length) {
2778
+ this.row = row;
2779
+ this.col = col;
2780
+ this.length = length;
2781
+ }
2782
+ };
2289
2783
  /** Maximum digit width of Calibri 11 in pixels; the writer uses the same value (internal/write/sheet-features.ts). */
2290
2784
  const MAX_DIGIT_WIDTH = 7;
2291
2785
  /**
@@ -2393,6 +2887,20 @@ var SheetParser = class {
2393
2887
  maxCol = -1;
2394
2888
  truncated = false;
2395
2889
  control;
2890
+ /** opts.keepCells (default true). */
2891
+ keep;
2892
+ /** Cells kept (or, without keepCells, that would have been), as maxCells counts them. */
2893
+ cellCount = 0;
2894
+ /** Without keepCells: the shared-formula masters by si, their reference records, and the masters whose text is pending (setLean). */
2895
+ lean = /* @__PURE__ */ new Map();
2896
+ leanRecords = 0;
2897
+ pending = [];
2898
+ pendingHead = 0;
2899
+ /** Masters in `pending` that still wait (have text); the others are dropped by compactPending. */
2900
+ pendingLive = 0;
2901
+ pendingText = 0;
2902
+ /** Without keepCells: the rows that had properties, one bit per row (for counting each once, as `rowProps` does). */
2903
+ rowPropSeen;
2396
2904
  constructor(name, state, ctx, styles, opts, part) {
2397
2905
  this.ctx = ctx;
2398
2906
  this.styles = styles;
@@ -2403,6 +2911,7 @@ var SheetParser = class {
2403
2911
  rows: this.rows
2404
2912
  };
2405
2913
  if (state && state !== "visible") this.sheet.state = state;
2914
+ this.keep = opts.keepCells !== false;
2406
2915
  }
2407
2916
  attach(control) {
2408
2917
  this.control = control;
@@ -2448,7 +2957,7 @@ var SheetParser = class {
2448
2957
  const ref = a.get("ref");
2449
2958
  if (ref) {
2450
2959
  this.ctx.charge(1);
2451
- this.merges.push(cleanRange(ref));
2960
+ if (this.keep) this.merges.push(cleanRange(ref));
2452
2961
  }
2453
2962
  return;
2454
2963
  }
@@ -2456,7 +2965,7 @@ var SheetParser = class {
2456
2965
  if (parent === "hyperlinks") {
2457
2966
  const ref = a.get("ref");
2458
2967
  if (ref) this.ctx.charge(1);
2459
- if (ref) this.hyperlinks.push({
2968
+ if (ref && (this.keep || this.mayBeTooWide(ref))) this.hyperlinks.push({
2460
2969
  ref: cleanRange(ref),
2461
2970
  relId: a.getPrefixed("id"),
2462
2971
  location: a.get("location"),
@@ -2473,7 +2982,7 @@ var SheetParser = class {
2473
2982
  case "selection":
2474
2983
  if (parent === "sheetView" && this.viewCount === 1) {
2475
2984
  this.ctx.charge(1);
2476
- this.selections.push({
2985
+ if (this.keep) this.selections.push({
2477
2986
  pane: a.get("pane"),
2478
2987
  activeCell: a.get("activeCell"),
2479
2988
  sqref: a.get("sqref")
@@ -2634,6 +3143,13 @@ var SheetParser = class {
2634
3143
  if (st) p.style = st;
2635
3144
  }
2636
3145
  if (Object.keys(p).length) {
3146
+ if (!this.keep) {
3147
+ const seen = this.rowPropSeen ??= /* @__PURE__ */ new Uint8Array(131072);
3148
+ const bit = 1 << (this.curRow & 7);
3149
+ if (!(seen[this.curRow >> 3] & bit)) this.ctx.charge(1);
3150
+ seen[this.curRow >> 3] |= bit;
3151
+ return;
3152
+ }
2637
3153
  if (this.rowProps[this.curRow] === void 0) this.ctx.charge(1);
2638
3154
  this.rowProps[this.curRow] = p;
2639
3155
  }
@@ -2798,6 +3314,12 @@ var SheetParser = class {
2798
3314
  if (!cell) return;
2799
3315
  if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref);
2800
3316
  this.ctx.countCell();
3317
+ this.cellCount++;
3318
+ if (!this.keep) {
3319
+ this.pendingIndex = -1;
3320
+ this.extend(p.row, p.col);
3321
+ return;
3322
+ }
2801
3323
  let row = this.rows[p.row];
2802
3324
  if (!row) row = this.rows[p.row] = [];
2803
3325
  if (row[p.col] !== void 0) this.ctx.warn("DUPLICATE_CELL", `Cell ${p.ref} appears more than once; the last one was kept.`, {
@@ -2818,10 +3340,19 @@ var SheetParser = class {
2818
3340
  if (this.pendingIndex > d.maxIndex) d.maxIndex = this.pendingIndex;
2819
3341
  this.pendingIndex = -1;
2820
3342
  }
2821
- if (p.row < this.minRow) this.minRow = p.row;
2822
- if (p.row > this.maxRow) this.maxRow = p.row;
2823
- if (p.col < this.minCol) this.minCol = p.col;
2824
- if (p.col > this.maxCol) this.maxCol = p.col;
3343
+ this.extend(p.row, p.col);
3344
+ }
3345
+ /** Widens the sheet's dimension to a kept cell. */
3346
+ extend(row, col) {
3347
+ if (row < this.minRow) this.minRow = row;
3348
+ if (row > this.maxRow) this.maxRow = row;
3349
+ if (col < this.minCol) this.minCol = col;
3350
+ if (col > this.maxCol) this.maxCol = col;
3351
+ }
3352
+ /** Without keepCells: whether a hyperlink on `ref` could fail maxColumns when the sheet is finished (attachHyperlink). */
3353
+ mayBeTooWide(ref) {
3354
+ const pos = parseRef(cleanRange(ref).split(":")[0]);
3355
+ return pos !== void 0 && pos[1] >= this.ctx.limits.maxColumns;
2825
3356
  }
2826
3357
  /**
2827
3358
  * A kept cell in a column past maxColumns (JSE-68). Counted on the cells the
@@ -2856,7 +3387,8 @@ var SheetParser = class {
2856
3387
  break;
2857
3388
  }
2858
3389
  const sst = this.sharedStrings;
2859
- const str = Number.isInteger(idx) && idx >= 0 ? sst[idx] : void 0;
3390
+ const count = this.sharedStringCount;
3391
+ const str = Number.isInteger(idx) && idx >= 0 ? count === void 0 ? sst[idx] : idx < count ? "" : void 0 : void 0;
2860
3392
  if (str === void 0) {
2861
3393
  if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref);
2862
3394
  this.ctx.warn("INVALID_SHARED_STRING", `Cell ${p.ref} refers to shared string ${excerpt(v)}, which does not exist; the cell was left empty.`, {
@@ -2958,6 +3490,7 @@ var SheetParser = class {
2958
3490
  formula(p) {
2959
3491
  if (p.f === void 0 || !this.opts.formulas) return void 0;
2960
3492
  if (p.fType === "shared" && p.fSi !== void 0) {
3493
+ if (!this.keep) return this.leanFormula(p);
2961
3494
  if (p.f !== "") {
2962
3495
  this.shared.set(p.fSi, {
2963
3496
  formula: p.f,
@@ -2998,6 +3531,131 @@ var SheetParser = class {
2998
3531
  };
2999
3532
  return { text: p.f };
3000
3533
  }
3534
+ /**
3535
+ * keepCells false (JSE-71): a shared formula decided as formula() decides
3536
+ * it, in the same order, from a LeanMaster instead of the master's text.
3537
+ * Only whether the cell has a formula matters here, so a resolved one
3538
+ * returns an empty text.
3539
+ */
3540
+ leanFormula(p) {
3541
+ const si = p.fSi;
3542
+ if (p.f !== "") {
3543
+ this.setLean(si, p);
3544
+ return { text: "" };
3545
+ }
3546
+ const m = this.lean.get(si);
3547
+ if (m && m.length > 8192) {
3548
+ this.unresolved(p, `: its master formula in cell ${colLetters(m.col + 1)}${m.row + 1} has ${m.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`);
3549
+ return;
3550
+ }
3551
+ if (!m) {
3552
+ this.unresolved(p, "");
3553
+ return;
3554
+ }
3555
+ const dRow = p.row - m.row;
3556
+ const dCol = p.col - m.col;
3557
+ if (dRow === 0 && dCol === 0) return { text: "" };
3558
+ if (m.text !== void 0) this.shape(m, p);
3559
+ if (!canShift(m, dRow, dCol)) {
3560
+ this.unresolved(p, "");
3561
+ return;
3562
+ }
3563
+ const max = this.ctx.limits.maxCellTextLength;
3564
+ if (m.parts ? shiftedLength(m.fixed, m.parts, dRow, dCol) <= max : m.fits) return { text: "" };
3565
+ this.unresolved(p, `: shifted, it would have more than maxCellTextLength (${max}) characters`);
3566
+ }
3567
+ /**
3568
+ * Keeps a master as a LeanMaster. Its text is kept only until a copy needs
3569
+ * it (as read compiles a master only then), and only while the text pending
3570
+ * on this sheet is at most PENDING_TEXT characters; past that, the oldest
3571
+ * pending masters are shaped and their text dropped. Shaping (formula.ts
3572
+ * formulaShape) keeps numbers only: the bounds, and whether copies fit
3573
+ * maxCellTextLength from the range of lengths a copy can have, or, when the
3574
+ * limit falls inside that range, records of the relative parts (partsOf).
3575
+ * Every live master (one per si: a redefinition replaces it, its pending
3576
+ * text and its records) and every record counts against maxItems (budget()).
3577
+ */
3578
+ setLean(si, p) {
3579
+ const f = p.f;
3580
+ const old = this.lean.get(si);
3581
+ if (old) this.release(old);
3582
+ const m = new LeanMaster(p.row, p.col, f.length);
3583
+ this.lean.set(si, m);
3584
+ if (f.length <= 8192) {
3585
+ m.text = f.length > 12 ? UTF8.encode(f) : (" " + f).slice(1);
3586
+ this.pendingText += m.text.length;
3587
+ this.pending.push(m);
3588
+ this.pendingLive++;
3589
+ while (this.pendingText > PENDING_TEXT) {
3590
+ const next = this.pending[this.pendingHead++];
3591
+ if (next.text !== void 0) this.shape(next, p);
3592
+ }
3593
+ this.compactPending();
3594
+ }
3595
+ this.budget(p);
3596
+ }
3597
+ /** A master's numbers from its text, which is then dropped (setLean). */
3598
+ shape(m, p) {
3599
+ const bytes = m.text;
3600
+ m.text = void 0;
3601
+ this.pendingText -= bytes.length;
3602
+ this.pendingLive--;
3603
+ const f = typeof bytes === "string" ? bytes : UTF8_TEXT.decode(bytes);
3604
+ const limit = this.ctx.limits.maxCellTextLength;
3605
+ const shape = formulaShape(f, 7 * f.length > limit);
3606
+ if (shape.min <= limit && shape.max > limit) {
3607
+ m.parts = partsOf(shape.keys);
3608
+ this.leanRecords += m.parts.length / 3;
3609
+ }
3610
+ m.rowMin = shape.rowMin;
3611
+ m.rowMax = shape.rowMax;
3612
+ m.colMin = shape.colMin;
3613
+ m.colMax = shape.colMax;
3614
+ m.fixed = shape.fixed;
3615
+ m.fits = shape.max <= limit;
3616
+ if (m.parts) this.budget(p);
3617
+ }
3618
+ /** A replaced master: its pending text and its records no longer count. */
3619
+ release(m) {
3620
+ if (m.text !== void 0) {
3621
+ this.pendingText -= m.text.length;
3622
+ this.pendingLive--;
3623
+ m.text = void 0;
3624
+ }
3625
+ if (m.parts) this.leanRecords -= m.parts.length / 3;
3626
+ m.parts = void 0;
3627
+ }
3628
+ /**
3629
+ * Drops the masters that no longer wait (shaped, or replaced by a
3630
+ * redefinition) from `pending` once they outnumber the waiting ones, so a
3631
+ * replaced master is unreachable and nothing is kept per redefinition.
3632
+ * Amortised constant time per master.
3633
+ */
3634
+ compactPending() {
3635
+ if (this.pending.length - this.pendingHead <= 2 * this.pendingLive + 64) return;
3636
+ const live = [];
3637
+ for (let i = this.pendingHead; i < this.pending.length; i++) if (this.pending[i].text !== void 0) live.push(this.pending[i]);
3638
+ this.pending = live;
3639
+ this.pendingHead = 0;
3640
+ }
3641
+ /**
3642
+ * inspect's own budget, the one documented exception to "the same error as
3643
+ * read" (docs/api.md §5.2.1): live masters and reference records, with the
3644
+ * items the read built besides cells, may not pass maxItems.
3645
+ */
3646
+ budget(p) {
3647
+ const most = this.ctx.limits.maxItems;
3648
+ if (this.ctx.items + this.lean.size + this.leanRecords <= most) return;
3649
+ throw new LimitError("LIMIT_EXCEEDED", `Sheet "${excerpt(this.sheet.name)}": its shared formulas need more than maxItems (${most}) masters and reference records, with the items the read built besides cells, to be checked without their text.`, { details: {
3650
+ limit: "maxItems",
3651
+ value: most + 1,
3652
+ max: most,
3653
+ part: this.part,
3654
+ ref: p.ref,
3655
+ sharedFormulaMasters: this.lean.size,
3656
+ sharedFormulaReferences: this.leanRecords
3657
+ } });
3658
+ }
3001
3659
  unresolved(p, why) {
3002
3660
  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
3661
  part: this.part,
@@ -3007,6 +3665,8 @@ var SheetParser = class {
3007
3665
  }
3008
3666
  /** Set before parsing; the shared strings table. */
3009
3667
  sharedStrings = [];
3668
+ /** Set instead of `sharedStrings` when they were counted, not kept (inspect, JSE-71). */
3669
+ sharedStringCount;
3010
3670
  /** When set, shared-string cells are collected here and filled in later (ReadOptions.maxRows). */
3011
3671
  deferred;
3012
3672
  openView(a) {
@@ -3118,51 +3778,399 @@ var SheetParser = class {
3118
3778
  const r = rels[i];
3119
3779
  if (!byId.has(r.id)) byId.set(r.id, r);
3120
3780
  }
3121
- for (let i = 0; i < this.hyperlinks.length; i++) {
3122
- if ((i & 4095) === 4095) this.ctx.checkAbort();
3123
- this.attachHyperlink(this.hyperlinks[i], byId);
3781
+ for (let i = 0; i < this.hyperlinks.length; i++) {
3782
+ if ((i & 4095) === 4095) this.ctx.checkAbort();
3783
+ this.attachHyperlink(this.hyperlinks[i], byId);
3784
+ }
3785
+ }
3786
+ if (this.maxRow >= 0) {
3787
+ const tl = `${colLetters(this.minCol + 1)}${this.minRow + 1}`;
3788
+ const br = `${colLetters(this.maxCol + 1)}${this.maxRow + 1}`;
3789
+ sheet.dimension = tl === br ? tl : `${tl}:${br}`;
3790
+ }
3791
+ return sheet;
3792
+ }
3793
+ attachHyperlink(h, rels) {
3794
+ const first = h.ref.split(":")[0];
3795
+ const pos = parseRef(first);
3796
+ if (!pos) return;
3797
+ 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)}.`, {
3798
+ part: this.part,
3799
+ sheet: this.sheet.name,
3800
+ ref: h.ref
3801
+ });
3802
+ let link;
3803
+ if (h.relId) {
3804
+ const rel = rels.get(h.relId);
3805
+ if (rel) {
3806
+ const target = h.location ? `${rel.target}#${h.location}` : rel.target;
3807
+ link = h.tooltip !== void 0 ? {
3808
+ target,
3809
+ tooltip: h.tooltip
3810
+ } : { target };
3811
+ }
3812
+ } else if (h.location !== void 0) link = h.tooltip !== void 0 ? {
3813
+ location: h.location,
3814
+ tooltip: h.tooltip
3815
+ } : { location: h.location };
3816
+ if (!link) return;
3817
+ const [r, c] = pos;
3818
+ if (r >= 1048576 || c >= 16384) return;
3819
+ if (c >= this.ctx.limits.maxColumns) this.tooWide(c, `${colLetters(c + 1)}${r + 1}`);
3820
+ if (!this.keep) return;
3821
+ let row = this.rows[r];
3822
+ if (!row) row = this.rows[r] = [];
3823
+ const cell = row[c] ?? (row[c] = { type: "empty" });
3824
+ cell.hyperlink = link;
3825
+ }
3826
+ };
3827
+ // src/internal/read/scan.ts
3828
+ /**
3829
+ * The package scan (JSE-72): walks the whole relationship graph from the
3830
+ * package root and classifies every part the model does not represent, and
3831
+ * lists the parts no relationship reaches. `read` uses it; it is kept in one
3832
+ * function so that other entry points can reuse it. Internal.
3833
+ */
3834
+ /**
3835
+ * Relationship kinds (the type URI's last segment) of parts the model does not
3836
+ * represent, with the words the UNSUPPORTED_PART message uses for them.
3837
+ */
3838
+ const UNSUPPORTED_RELATIONSHIPS = /* @__PURE__ */ new Map([
3839
+ ["drawing", "drawings (charts, images, shapes)"],
3840
+ ["vmlDrawing", "legacy drawings (VML)"],
3841
+ ["comments", "comments"],
3842
+ ["threadedComment", "threaded comments"],
3843
+ ["pivotTable", "pivot tables"],
3844
+ ["pivotCacheDefinition", "pivot caches"],
3845
+ ["table", "tables (ListObjects)"],
3846
+ ["oleObject", "embedded OLE objects"],
3847
+ ["ctrlProp", "form controls"],
3848
+ ["image", "images"],
3849
+ ["vbaProject", "VBA macros"],
3850
+ ["externalLink", "external links"],
3851
+ ["connections", "data connections"],
3852
+ ["queryTable", "query tables"],
3853
+ ["slicer", "slicers"],
3854
+ ["slicerCache", "slicer caches"],
3855
+ ["timeline", "timelines"],
3856
+ ["chartsheet", "chart sheets"],
3857
+ ["dialogsheet", "dialog sheets"],
3858
+ ["macrosheet", "macro sheets"]
3859
+ ]);
3860
+ /** Words for the kinds the scan adds (since 2.5). `unreferencedPart` has its own message. */
3861
+ const SCANNED_KINDS = /* @__PURE__ */ new Map([
3862
+ ["activeX", "ActiveX controls"],
3863
+ ["embeddedPackage", "embedded packages (files such as documents embedded in the workbook)"],
3864
+ ["customUI", "custom ribbon UI (customUI)"],
3865
+ ["webExtension", "Office web add-ins"]
3866
+ ]);
3867
+ /**
3868
+ * Relationship kinds, lower case (relationship types compare
3869
+ * case-insensitively), that name a kind other than their own last segment.
3870
+ */
3871
+ const RELATIONSHIP_ALIASES = /* @__PURE__ */ new Map([
3872
+ ["control", "activeX"],
3873
+ ["activexcontrolbinary", "activeX"],
3874
+ ["package", "embeddedPackage"],
3875
+ ["xlmacrosheet", "macrosheet"],
3876
+ ["xlintlmacrosheet", "macrosheet"],
3877
+ ["webextensiontaskpanes", "webExtension"],
3878
+ ["webextension", "webExtension"],
3879
+ ["attachedtoolbars", "vbaProject"],
3880
+ ["vbaprojectsignature", "vbaProject"],
3881
+ ["vbaprojectsignatureagile", "vbaProject"],
3882
+ ["vbaprojectsignaturev3", "vbaProject"],
3883
+ ["wordvbadata", "vbaProject"]
3884
+ ]);
3885
+ /** UNSUPPORTED_RELATIONSHIPS keyed by lower-case kind. */
3886
+ const RELATIONSHIP_KINDS = new Map([...UNSUPPORTED_RELATIONSHIPS.keys()].map((k) => [k.toLowerCase(), k]));
3887
+ /**
3888
+ * Content types (lower case) of active or embedded content: a part with one
3889
+ * of these is reported as its kind whatever relationship reaches it.
3890
+ */
3891
+ const CONTENT_TYPES = /* @__PURE__ */ new Map([
3892
+ ["application/vnd.ms-office.activex+xml", "activeX"],
3893
+ ["application/vnd.ms-office.activex", "activeX"],
3894
+ ["application/vnd.openxmlformats-officedocument.oleobject", "oleObject"],
3895
+ ["application/vnd.ms-office.oleobject", "oleObject"],
3896
+ ["application/vnd.ms-office.vbaproject", "vbaProject"],
3897
+ ["application/vnd.ms-office.vbaprojectsignature", "vbaProject"],
3898
+ ["application/vnd.ms-excel.attachedtoolbars", "vbaProject"],
3899
+ ["application/vnd.ms-excel.macrosheet+xml", "macrosheet"],
3900
+ ["application/vnd.ms-excel.intlmacrosheet+xml", "macrosheet"],
3901
+ ["application/vnd.ms-office.webextension+xml", "webExtension"],
3902
+ ["application/vnd.ms-office.webextensiontaskpanes+xml", "webExtension"],
3903
+ ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "embeddedPackage"],
3904
+ ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "embeddedPackage"],
3905
+ ["application/vnd.openxmlformats-officedocument.presentationml.presentation", "embeddedPackage"],
3906
+ ["application/vnd.openxmlformats-officedocument.presentationml.slideshow", "embeddedPackage"],
3907
+ ["application/vnd.ms-word.document.macroenabled.12", "embeddedPackage"],
3908
+ ["application/vnd.ms-excel.sheet.macroenabled.12", "embeddedPackage"],
3909
+ ["application/vnd.ms-excel.sheet.binary.macroenabled.12", "embeddedPackage"],
3910
+ ["application/vnd.ms-powerpoint.presentation.macroenabled.12", "embeddedPackage"],
3911
+ ["application/vnd.ms-powerpoint.slideshow.macroenabled.12", "embeddedPackage"],
3912
+ ["application/vnd.openxmlformats-officedocument.spreadsheetml.template", "embeddedPackage"],
3913
+ ["application/vnd.openxmlformats-officedocument.wordprocessingml.template", "embeddedPackage"],
3914
+ ["application/vnd.openxmlformats-officedocument.presentationml.template", "embeddedPackage"],
3915
+ ["application/vnd.openxmlformats-officedocument.presentationml.slide", "embeddedPackage"],
3916
+ ["application/vnd.ms-excel.template.macroenabled.12", "embeddedPackage"],
3917
+ ["application/vnd.ms-excel.addin.macroenabled.12", "embeddedPackage"],
3918
+ ["application/vnd.ms-word.template.macroenabled.12", "embeddedPackage"],
3919
+ ["application/vnd.ms-powerpoint.template.macroenabled.12", "embeddedPackage"],
3920
+ ["application/vnd.ms-powerpoint.slide.macroenabled.12", "embeddedPackage"],
3921
+ ["application/vnd.ms-powerpoint.addin.macroenabled.12", "embeddedPackage"]
3922
+ ]);
3923
+ /**
3924
+ * Kinds `read` reports wherever the scan finds them: on any sheet (also one
3925
+ * left out by `sheets`) and under any part (a drawing, a table, ...). These are
3926
+ * active or embedded content and links out of the file. The other kinds
3927
+ * (drawings, images, comments, tables, pivots, ...) are reported, as before
3928
+ * 2.5, from the workbook's and the read sheets' own relationships only.
3929
+ */
3930
+ const REPORTED_ANYWHERE = /* @__PURE__ */ new Set([
3931
+ "activeX",
3932
+ "embeddedPackage",
3933
+ "customUI",
3934
+ "oleObject",
3935
+ "vbaProject",
3936
+ "externalLink",
3937
+ "connections",
3938
+ "queryTable",
3939
+ "macrosheet",
3940
+ "webExtension"
3941
+ ]);
3942
+ /**
3943
+ * The kind a relationship names, by its type alone: the last segment of the
3944
+ * type URI, compared without regard to case, or an alias (RELATIONSHIP_ALIASES).
3945
+ * customUI is matched on the whole type (`.../ui/extensibility`).
3946
+ */
3947
+ function relationshipKindOf(rel) {
3948
+ const kind = rel.kind.toLowerCase();
3949
+ if (kind === "extensibility" && /\/ui\/extensibility$/i.test(rel.type)) return "customUI";
3950
+ return RELATIONSHIP_ALIASES.get(kind) ?? RELATIONSHIP_KINDS.get(kind);
3951
+ }
3952
+ /**
3953
+ * What a relationship and its target's content type make of a part; undefined
3954
+ * for parts the model reads or that need no report. A kind in REPORTED_ANYWHERE
3955
+ * wins: an active content type behind a passive or unknown relationship (an
3956
+ * `image` relationship to an OLE object) is reported by its content type.
3957
+ */
3958
+ function partKindOf(rel, contentTypes) {
3959
+ const byRel = relationshipKindOf(rel);
3960
+ if (byRel !== void 0 && REPORTED_ANYWHERE.has(byRel)) return byRel;
3961
+ for (const t of contentTypes) {
3962
+ const byType = CONTENT_TYPES.get(t.toLowerCase().split(";")[0].trim());
3963
+ if (byType) return byType;
3964
+ }
3965
+ return byRel;
3966
+ }
3967
+ /**
3968
+ * Walks the relationship graph of `pkg` from the package root, breadth first.
3969
+ * Reads only relationships parts (each at most once per read, through the
3970
+ * zip and XML limits of `pkg.ctx`, without marking them consumed) and the
3971
+ * content types already loaded; never inflates the parts it classifies.
3972
+ * A target OPC forbids is followed both as a decoder reads it and literally,
3973
+ * so content behind it is found either way. Consults the signal per part and
3974
+ * every 4,096 relationships or zip entries. A relationships part that is not
3975
+ * well-formed XML is treated as unreferenced instead of failing the read;
3976
+ * limit and DTD errors are thrown as anywhere else.
3977
+ */
3978
+ async function scanPackageParts(pkg) {
3979
+ const ctx = pkg.ctx;
3980
+ const found = [];
3981
+ const foundKeys = /* @__PURE__ */ new Set();
3982
+ const forbidden = new Set(pkg.forbiddenNames);
3983
+ /** partKey of the parts accounted for (reached from the package root). */
3984
+ const reached = /* @__PURE__ */ new Set([partKey("[Content_Types].xml")]);
3985
+ /** partKey of the parts whose relationships are queued: a part reached as a target is queued even if it was accounted for otherwise (a relationships part, [Content_Types].xml). */
3986
+ const queued = /* @__PURE__ */ new Set([""]);
3987
+ /** Relationships parts parsed, by partKey. */
3988
+ const parsed = /* @__PURE__ */ new Set();
3989
+ const queue = [{
3990
+ source: "",
3991
+ counts: true
3992
+ }];
3993
+ const visit = (target, counts) => {
3994
+ const entry = pkg.part(target);
3995
+ if (!entry) return;
3996
+ const key = pkg.keyOf(entry);
3997
+ if (counts) reached.add(key);
3998
+ if (queued.has(key)) return;
3999
+ queued.add(key);
4000
+ queue.push({
4001
+ source: entry.name,
4002
+ counts
4003
+ });
4004
+ };
4005
+ const classify = (rel, source, relsPart) => {
4006
+ const targets = rel.external || rel.tooLong || rel.target === "" ? [] : rel.altTarget === void 0 ? [rel.target] : [rel.target, rel.altTarget];
4007
+ for (const target of targets.length ? targets : [void 0]) {
4008
+ const kind = partKindOf(rel, target === void 0 ? [] : pkg.contentTypes(target));
4009
+ if (!kind) continue;
4010
+ const part = target ?? (rel.external ? source || relsPart : relsPart);
4011
+ const key = `${kind}\u0000${partKey(part)}`;
4012
+ if (foundKeys.has(key)) continue;
4013
+ foundKeys.add(key);
4014
+ found.push({
4015
+ kind,
4016
+ part,
4017
+ source,
4018
+ external: rel.external
4019
+ });
4020
+ }
4021
+ };
4022
+ const drain = async () => {
4023
+ for (let q = 0; q < queue.length; q++) {
4024
+ const pause = ctx.step();
4025
+ if (pause) await pause;
4026
+ const { source, counts } = queue[q];
4027
+ const relsEntry = pkg.part(pkg.relsPartOf(source));
4028
+ if (!relsEntry) continue;
4029
+ const relsKey = pkg.keyOf(relsEntry);
4030
+ if (parsed.has(relsKey)) continue;
4031
+ parsed.add(relsKey);
4032
+ let rels;
4033
+ try {
4034
+ rels = await pkg.rels(source, { peek: true });
4035
+ } catch (err) {
4036
+ if (err instanceof FormatError && err.code === "XML_MALFORMED") continue;
4037
+ throw err;
4038
+ }
4039
+ if (counts) reached.add(relsKey);
4040
+ const malformed = pkg.malformedRels.get(relsEntry.name) ?? [];
4041
+ if (malformed.length) forbidden.add(relsEntry.name);
4042
+ const all = malformed.length ? [...rels, ...malformed] : rels;
4043
+ for (let i = 0; i < all.length; i++) {
4044
+ if ((i & 4095) === 4095) ctx.checkAbort();
4045
+ const rel = all[i];
4046
+ if (rel.forbidden) forbidden.add(relsEntry.name);
4047
+ classify(rel, source, relsEntry.name);
4048
+ if (rel.external || rel.tooLong) continue;
4049
+ visit(rel.target, counts);
4050
+ if (rel.altTarget !== void 0) visit(rel.altTarget, counts);
3124
4051
  }
3125
4052
  }
3126
- if (this.maxRow >= 0) {
3127
- const tl = `${colLetters(this.minCol + 1)}${this.minRow + 1}`;
3128
- const br = `${colLetters(this.maxCol + 1)}${this.maxRow + 1}`;
3129
- sheet.dimension = tl === br ? tl : `${tl}:${br}`;
3130
- }
3131
- return sheet;
3132
- }
3133
- attachHyperlink(h, rels) {
3134
- const first = h.ref.split(":")[0];
3135
- const pos = parseRef(first);
3136
- if (!pos) return;
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)}.`, {
3138
- part: this.part,
3139
- sheet: this.sheet.name,
3140
- ref: h.ref
4053
+ queue.length = 0;
4054
+ };
4055
+ await drain();
4056
+ const entries = ctx.zip.entries;
4057
+ for (let i = 0; i < entries.length; i++) {
4058
+ if ((i & 4095) === 4095) ctx.checkAbort();
4059
+ const e = entries[i];
4060
+ if (e.name.endsWith("/") || parsed.has(pkg.keyOf(e))) continue;
4061
+ const owner = relsOwner(pkg.keyOf(e));
4062
+ if (owner === void 0) continue;
4063
+ queue.push({
4064
+ source: owner,
4065
+ counts: false
3141
4066
  });
3142
- let link;
3143
- if (h.relId) {
3144
- const rel = rels.get(h.relId);
3145
- if (rel) {
3146
- const target = h.location ? `${rel.target}#${h.location}` : rel.target;
3147
- link = h.tooltip !== void 0 ? {
3148
- target,
3149
- tooltip: h.tooltip
3150
- } : { target };
3151
- }
3152
- } else if (h.location !== void 0) link = h.tooltip !== void 0 ? {
3153
- location: h.location,
3154
- tooltip: h.tooltip
3155
- } : { location: h.location };
3156
- if (!link) return;
3157
- const [r, c] = pos;
3158
- if (r >= 1048576 || c >= 16384) return;
3159
- if (c >= this.ctx.limits.maxColumns) this.tooWide(c, `${colLetters(c + 1)}${r + 1}`);
3160
- let row = this.rows[r];
3161
- if (!row) row = this.rows[r] = [];
3162
- const cell = row[c] ?? (row[c] = { type: "empty" });
3163
- cell.hyperlink = link;
4067
+ await drain();
4068
+ }
4069
+ const unreferenced = [];
4070
+ for (let i = 0; i < entries.length; i++) {
4071
+ if ((i & 4095) === 4095) ctx.checkAbort();
4072
+ const e = entries[i];
4073
+ if (e.name.endsWith("/")) continue;
4074
+ if (!reached.has(pkg.keyOf(e))) unreferenced.push(e.name);
4075
+ }
4076
+ return {
4077
+ found,
4078
+ unreferenced,
4079
+ forbidden: [...forbidden]
4080
+ };
4081
+ }
4082
+ // src/internal/read/formats.ts
4083
+ /** Container signatures, checked in order. */
4084
+ const CONTAINERS = [
4085
+ {
4086
+ kind: "cfb",
4087
+ magic: [
4088
+ 208,
4089
+ 207,
4090
+ 17,
4091
+ 224,
4092
+ 161,
4093
+ 177,
4094
+ 26,
4095
+ 225
4096
+ ]
4097
+ },
4098
+ {
4099
+ kind: "zip",
4100
+ magic: [
4101
+ 80,
4102
+ 75,
4103
+ 3,
4104
+ 4
4105
+ ]
4106
+ },
4107
+ {
4108
+ kind: "zip",
4109
+ magic: [
4110
+ 80,
4111
+ 75,
4112
+ 5,
4113
+ 6
4114
+ ]
4115
+ }
4116
+ ];
4117
+ /** OPC workbook formats by the content type of their workbook part. */
4118
+ const WORKBOOK_FORMATS = [
4119
+ {
4120
+ format: "xlsx",
4121
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
4122
+ decoder: "spreadsheetml",
4123
+ label: "Excel workbook (.xlsx)"
4124
+ },
4125
+ {
4126
+ format: "xltx",
4127
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml",
4128
+ decoder: "spreadsheetml",
4129
+ label: "Excel template (.xltx)"
4130
+ },
4131
+ {
4132
+ format: "xlsm",
4133
+ contentType: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
4134
+ decoder: "spreadsheetml",
4135
+ macros: true,
4136
+ label: "macro-enabled workbook (.xlsm)"
4137
+ },
4138
+ {
4139
+ format: "xltm",
4140
+ contentType: "application/vnd.ms-excel.template.macroEnabled.main+xml",
4141
+ decoder: "spreadsheetml",
4142
+ macros: true,
4143
+ label: "macro-enabled template (.xltm)"
4144
+ },
4145
+ {
4146
+ format: "xlsb",
4147
+ contentType: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
4148
+ macros: true,
4149
+ label: "binary workbook (.xlsb)"
3164
4150
  }
4151
+ ];
4152
+ /** Formats recognised by something other than a workbook content type. */
4153
+ const OTHER_FORMATS = {
4154
+ ods: { label: "OpenDocument spreadsheet (.ods)" },
4155
+ cfb: { label: "legacy .xls file or a password-protected (encrypted) workbook" },
4156
+ unknown: { label: "file that is not a spreadsheet package" }
3165
4157
  };
4158
+ function sniffContainer(b) {
4159
+ for (const c of CONTAINERS) if (c.magic.every((x, i) => b[i] === x)) return c.kind;
4160
+ return "unknown";
4161
+ }
4162
+ /**
4163
+ * The workbook format for a workbook part, from its content type; when the
4164
+ * content type is missing or unknown, from the part's extension (.bin is
4165
+ * binary, anything else is read as SpreadsheetML).
4166
+ */
4167
+ function workbookFormat(contentType, partName) {
4168
+ const ct = (contentType ?? "").toLowerCase();
4169
+ const known = WORKBOOK_FORMATS.find((f) => f.contentType.toLowerCase() === ct);
4170
+ if (known) return known;
4171
+ if (partName.toLowerCase().endsWith(".bin")) return WORKBOOK_FORMATS.find((f) => f.format === "xlsb");
4172
+ return WORKBOOK_FORMATS[0];
4173
+ }
3166
4174
  var WorkbookParser = class {
3167
4175
  maxSheets;
3168
4176
  part;
@@ -3429,29 +4437,6 @@ var CustomPropsParser = class {
3429
4437
  }
3430
4438
  };
3431
4439
  // src/internal/read/reader.ts
3432
- /** Friendly names for parts the model does not represent, keyed by relationship kind. */
3433
- const UNSUPPORTED = /* @__PURE__ */ new Map([
3434
- ["drawing", "drawings (charts, images, shapes)"],
3435
- ["vmlDrawing", "legacy drawings (VML)"],
3436
- ["comments", "comments"],
3437
- ["threadedComment", "threaded comments"],
3438
- ["pivotTable", "pivot tables"],
3439
- ["pivotCacheDefinition", "pivot caches"],
3440
- ["table", "tables (ListObjects)"],
3441
- ["oleObject", "embedded OLE objects"],
3442
- ["ctrlProp", "form controls"],
3443
- ["image", "images"],
3444
- ["vbaProject", "VBA macros"],
3445
- ["externalLink", "external links"],
3446
- ["connections", "data connections"],
3447
- ["queryTable", "query tables"],
3448
- ["slicer", "slicers"],
3449
- ["slicerCache", "slicer caches"],
3450
- ["timeline", "timelines"],
3451
- ["chartsheet", "chart sheets"],
3452
- ["dialogsheet", "dialog sheets"],
3453
- ["macrosheet", "macro sheets"]
3454
- ]);
3455
4440
  function unsupported(format, message) {
3456
4441
  return new FormatError("UNSUPPORTED_FORMAT", message, { details: { format } });
3457
4442
  }
@@ -3586,10 +4571,10 @@ function warnUnsupportedParts(ctx, rels, part, seen) {
3586
4571
  for (let i = 0; i < rels.length; i++) {
3587
4572
  if ((i & 4095) === 4095) ctx.checkAbort();
3588
4573
  const r = rels[i];
3589
- const kind = r.kind;
3590
- const what = UNSUPPORTED.get(kind);
3591
- if (what && !seen.has(r.kind)) {
3592
- seen.add(r.kind);
4574
+ const kind = relationshipKindOf(r);
4575
+ const what = kind === void 0 ? void 0 : UNSUPPORTED_RELATIONSHIPS.get(kind);
4576
+ if (kind && what && !seen.has(kind)) {
4577
+ seen.add(kind);
3593
4578
  ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
3594
4579
  part: r.external ? part : r.target,
3595
4580
  partKind: kind
@@ -3597,6 +4582,46 @@ function warnUnsupportedParts(ctx, rels, part, seen) {
3597
4582
  }
3598
4583
  }
3599
4584
  }
4585
+ /**
4586
+ * After the sheets (JSE-72): the kinds in REPORTED_ANYWHERE that the
4587
+ * workbook's and the read sheets' relationships did not already report,
4588
+ * wherever the package scan found them, then one `invalidPartName` warning
4589
+ * for all names OPC forbids and one `unreferencedPart` warning for all parts
4590
+ * no relationship reaches, each listing every name in `parts`.
4591
+ */
4592
+ async function warnScannedParts(pkg, seen) {
4593
+ const ctx = pkg.ctx;
4594
+ const scan = await scanPackageParts(pkg);
4595
+ for (const f of scan.found) {
4596
+ if (!REPORTED_ANYWHERE.has(f.kind) || seen.has(f.kind)) continue;
4597
+ seen.add(f.kind);
4598
+ const what = SCANNED_KINDS.get(f.kind) ?? UNSUPPORTED_RELATIONSHIPS.get(f.kind);
4599
+ ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
4600
+ part: f.part,
4601
+ partKind: f.kind
4602
+ });
4603
+ }
4604
+ const bad = scan.forbidden;
4605
+ if (bad.length > 0) {
4606
+ const first = bad[0];
4607
+ const message = bad.length === 1 ? `The package uses a part name or relationship target that OPC forbids (in "${excerpt(first)}"); it is not read.` : `The package uses ${bad.length} part names or relationship targets that OPC forbids (first in "${excerpt(first)}"); they are not read.`;
4608
+ ctx.warn("UNSUPPORTED_PART", message, {
4609
+ part: first,
4610
+ partKind: "invalidPartName",
4611
+ parts: bad
4612
+ });
4613
+ }
4614
+ const n = scan.unreferenced.length;
4615
+ if (n > 0) {
4616
+ const first = scan.unreferenced[0];
4617
+ const message = n === 1 ? `The package contains 1 part that no relationship refers to ("${excerpt(first)}"), which is not read.` : `The package contains ${n} parts that no relationship refers to (first: "${excerpt(first)}"), which are not read.`;
4618
+ ctx.warn("UNSUPPORTED_PART", message, {
4619
+ part: first,
4620
+ partKind: "unreferencedPart",
4621
+ parts: scan.unreferenced
4622
+ });
4623
+ }
4624
+ }
3600
4625
  /** Reads an .xlsx-family file into the model. */
3601
4626
  async function readImpl(input, options, internal) {
3602
4627
  const o = options ?? {};
@@ -3612,12 +4637,26 @@ async function readImpl(input, options, internal) {
3612
4637
  let ctx;
3613
4638
  const { pkg, workbookPart, format } = await openPackage(bytes, limits, (zip) => {
3614
4639
  ctx = new ReadContext(zip, limits, o.signal, o.onWarning, o.onProgress);
4640
+ if (internal?.inspect) {
4641
+ ctx.sniff = internal.inspect.sniff;
4642
+ ctx.relsParsed = internal.inspect.relsParsed;
4643
+ }
3615
4644
  return ctx;
3616
4645
  });
3617
4646
  ctx.progress({
3618
4647
  phase: "unzip",
3619
4648
  ratio: .02
3620
4649
  });
4650
+ const inspect = internal?.inspect;
4651
+ if (inspect) {
4652
+ inspect.ctx = ctx;
4653
+ inspect.pkg = pkg;
4654
+ inspect.format = format;
4655
+ ctx.tap = (w) => {
4656
+ if (w.code === "UNSUPPORTED_PART") inspect.unsupported.push(w);
4657
+ else if (w.code === "BROKEN_OPTIONAL_PART" && w.part !== void 0) inspect.broken.add(w.part);
4658
+ };
4659
+ }
3621
4660
  const wbp = await parseWorkbook(pkg, workbookPart);
3622
4661
  const wbRels = await pkg.rels(workbookPart);
3623
4662
  const seen = /* @__PURE__ */ new Set();
@@ -3674,9 +4713,10 @@ async function readImpl(input, options, internal) {
3674
4713
  });
3675
4714
  else if (deferred) sstEntry = entry;
3676
4715
  else {
3677
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n), limits.maxCellTextLength);
4716
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n), limits.maxCellTextLength, !inspect);
3678
4717
  await ctx.parse(entry, sp);
3679
4718
  sst = sp.strings;
4719
+ if (inspect) inspect.sharedStrings = sp.count;
3680
4720
  }
3681
4721
  }
3682
4722
  const properties = await readProperties(pkg, ctx);
@@ -3690,6 +4730,13 @@ async function readImpl(input, options, internal) {
3690
4730
  totalBytes ||= 1;
3691
4731
  let doneBytes = 0;
3692
4732
  const sheets = [];
4733
+ const done = (parser, part, sheet) => {
4734
+ sheets.push(sheet);
4735
+ inspect?.sheets.push({
4736
+ part: part?.name,
4737
+ cells: parser.cellCount
4738
+ });
4739
+ };
3693
4740
  for (let i = 0; i < listed.length; i++) {
3694
4741
  const pause = ctx.step();
3695
4742
  if (pause) await pause;
@@ -3702,9 +4749,11 @@ async function readImpl(input, options, internal) {
3702
4749
  richText: o.richText ?? "runs",
3703
4750
  rawText: o.rawText === true,
3704
4751
  date1904: wbp.date1904,
3705
- maxRows: o.maxRows ?? 1048576
4752
+ maxRows: o.maxRows ?? 1048576,
4753
+ keepCells: !inspect
3706
4754
  }, rel?.target ?? workbookPart);
3707
4755
  parser.sharedStrings = sst;
4756
+ if (inspect) parser.sharedStringCount = inspect.sharedStrings;
3708
4757
  parser.deferred = deferred;
3709
4758
  const part = rel ? pkg.part(rel.target) : void 0;
3710
4759
  if (!part) {
@@ -3712,11 +4761,11 @@ async function readImpl(input, options, internal) {
3712
4761
  sheet: entry.name,
3713
4762
  partKind: "worksheet"
3714
4763
  });
3715
- sheets.push(parser.finish([]));
4764
+ done(parser, part, parser.finish([]));
3716
4765
  continue;
3717
4766
  }
3718
4767
  if (!wanted(entry.name, i)) {
3719
- sheets.push(parser.finish([]));
4768
+ done(parser, part, parser.finish([]));
3720
4769
  continue;
3721
4770
  }
3722
4771
  const sheetRels = await pkg.rels(part.name);
@@ -3737,8 +4786,9 @@ async function readImpl(input, options, internal) {
3737
4786
  });
3738
4787
  });
3739
4788
  doneBytes += part.size;
3740
- sheets.push(parser.finish(sheetRels));
4789
+ done(parser, part, parser.finish(sheetRels));
3741
4790
  }
4791
+ await warnScannedParts(pkg, seen);
3742
4792
  if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name);
3743
4793
  if (deferred && deferred.cells.length > 0) {
3744
4794
  if (sstEntry) {
@@ -3865,6 +4915,349 @@ async function readProperties(pkg, ctx) {
3865
4915
  }
3866
4916
  return Object.keys(props).length ? props : void 0;
3867
4917
  }
4918
+ // src/internal/read/inspect.ts
4919
+ /**
4920
+ * inspect (docs/api.md §5.2.1, JSE-71): checks a workbook part by part with
4921
+ * read's zip and XML safety, without building cells. Internal.
4922
+ *
4923
+ * The workbook is read by readImpl itself, with every check read makes, in
4924
+ * the same order, but with no cells and no shared strings kept (the sheet
4925
+ * and shared-strings parsers count instead). So inspect refuses what read
4926
+ * refuses, with the same error, and reports the part kinds read reports;
4927
+ * whatever readImpl learns to check or report, inspect does too. Only once
4928
+ * that read has succeeded come the checks read does not make:
4929
+ * - every XML part (by content type, by name, or as the target of a
4930
+ * relationship of a kind that is not binary, from the relationships read's
4931
+ * package scan parsed), including the parts read parses, must be in UTF-8
4932
+ * or UTF-16, as OPC requires;
4933
+ * - every zip entry the read did not parse, or parsed only up to an error it
4934
+ * forgave (a broken optional part), is inflated (zip limits, CRC) and its
4935
+ * bytes searched for `<!DOCTYPE`, whatever its name or content type.
4936
+ */
4937
+ /**
4938
+ * `<!DOCTYPE` in the bytes of a part, read one byte per character: ASCII and
4939
+ * UTF-8 text, UTF-16 (one NUL between the characters) and UTF-32 (three), in
4940
+ * either byte order; and UTF-7, where `<` and `!` are base64 runs. In any
4941
+ * case, as the tokenizer refuses it.
4942
+ */
4943
+ const DOCTYPE = /<(\u0000{0,3})!\1d\1o\1c\1t\1y\1p\1e|\+ADw(?:-!|AIQ-|-\+ACE-)doctype/i;
4944
+ /** A processing instruction whose target is `xml` in any case, in the same byte forms as DOCTYPE. */
4945
+ const XML_PI = /<(\u0000{0,3})\?\1x\1m\1l\1[ \t\r\n?]/gi;
4946
+ /** Reads bytes as characters one to one (windows-1252: ASCII and NUL map to themselves). */
4947
+ const BYTES = new TextDecoder("latin1");
4948
+ /** Relationship kinds (lower case) whose target is not XML. Every other internal target is treated as an XML part. */
4949
+ const BINARY_KINDS = /* @__PURE__ */ new Set([
4950
+ "image",
4951
+ "oleobject",
4952
+ "package",
4953
+ "vbaproject",
4954
+ "vbaprojectsignature",
4955
+ "vbaprojectsignatureagile",
4956
+ "vbaprojectsignaturev3",
4957
+ "attachedtoolbars",
4958
+ "printersettings",
4959
+ "activexcontrolbinary",
4960
+ "thumbnail",
4961
+ "font",
4962
+ "media",
4963
+ "audio",
4964
+ "video",
4965
+ "hyperlink",
4966
+ "attachedtemplate",
4967
+ "externallinkpath",
4968
+ "xlbinaryindex"
4969
+ ]);
4970
+ /** Parts whose content type or name says XML. */
4971
+ function isXmlByName(pkg, name) {
4972
+ const type = (pkg.contentType(name) ?? "").toLowerCase();
4973
+ return /[+/]xml\s*(;|$)/.test(type) || type.endsWith("vmldrawing") || /\.(xml|rels|vml|svg)$/i.test(name);
4974
+ }
4975
+ /**
4976
+ * The encoding a part's first four bytes show when OPC does not allow it
4977
+ * (ECMA-376 Part 2: UTF-8 or UTF-16), else undefined: a UTF-32 or UCS-4 byte
4978
+ * order mark or `<`, the EBCDIC bytes of `<?xml`, the UTF-7 signature
4979
+ * (`+/v`) or a UTF-7 `<` (`+ADw`).
4980
+ */
4981
+ function signatureEncoding(b) {
4982
+ const [b0, b1, b2, b3] = [
4983
+ b[0],
4984
+ b[1],
4985
+ b[2],
4986
+ b[3]
4987
+ ];
4988
+ if (b0 === 0 && b1 === 0 && b2 === 254 && b3 === 255) return "UTF-32BE";
4989
+ if (b0 === 255 && b1 === 254 && b2 === 0 && b3 === 0) return "UTF-32LE";
4990
+ if (b0 === 0 && b1 === 0 && b2 === 0 && b3 === 60) return "UTF-32BE";
4991
+ if (b0 === 60 && b1 === 0 && b2 === 0 && b3 === 0) return "UTF-32LE";
4992
+ if (b0 === 0 && b1 === 0 && b2 === 60 && b3 === 0 || b0 === 0 && b1 === 60 && b2 === 0 && b3 === 0) return "UCS-4";
4993
+ if (b0 === 76 && b1 === 111 && b2 === 167 && b3 === 148) return "EBCDIC";
4994
+ if (b0 === 43 && b1 === 47 && b2 === 118) return "UTF-7";
4995
+ if (b0 === 43 && b1 === 65 && b2 === 68 && (b3 === 119 || b3 === 120)) return "UTF-7";
4996
+ }
4997
+ /**
4998
+ * The XMLDecl production (XML 1.0 §2.8), strictly: `<?xml`, then version,
4999
+ * encoding and standalone in that order, each once, quoted, only the first
5000
+ * required, with spaces as XML counts them.
5001
+ */
5002
+ const XML_DECLARATION = /^<\?xml[ \t\r\n]+version[ \t\r\n]*=[ \t\r\n]*(?:"1\.[0-9]+"|'1\.[0-9]+')(?:[ \t\r\n]+encoding[ \t\r\n]*=[ \t\r\n]*(?:"([A-Za-z][A-Za-z0-9._-]*)"|'([A-Za-z][A-Za-z0-9._-]*)'))?(?:[ \t\r\n]+standalone[ \t\r\n]*=[ \t\r\n]*(?:"(?:yes|no)"|'(?:yes|no)'))?[ \t\r\n]*\?>$/;
5003
+ /** A whole declaration at the start of a part: undefined when it is well-formed and names UTF-8, UTF-16 or nothing. */
5004
+ function checkDeclaration(part, declaration) {
5005
+ const m = XML_DECLARATION.exec(declaration);
5006
+ if (!m) return new FormatError("XML_MALFORMED", `${excerpt(part)}: the XML declaration is not well-formed (XML 1.0 XMLDecl).`, { details: {
5007
+ part,
5008
+ declaration: printable(declaration)
5009
+ } });
5010
+ const name = m[1] ?? m[2];
5011
+ return name === void 0 || /^utf-?(8|16(le|be)?)$/i.test(name) ? void 0 : encodingError(part, printable(name));
5012
+ }
5013
+ function misplacedDeclaration(part) {
5014
+ return new FormatError("XML_MALFORMED", `${excerpt(part)}: an XML declaration (<?xml …?>) appears other than at the very start of the part.`, { details: { part } });
5015
+ }
5016
+ /** File text for `details`: printable ASCII only, at most 40 characters. */
5017
+ function printable(s) {
5018
+ const clean = s.replace(/[^\x20-\x7e]/g, "?");
5019
+ return clean.length > 40 ? `${clean.slice(0, 37)}...` : clean;
5020
+ }
5021
+ function encodingError(part, encoding) {
5022
+ return new FormatError("XML_MALFORMED", `${excerpt(part)}: the part is encoded in ${encoding}; XML parts must be UTF-8 or UTF-16.`, { details: {
5023
+ part,
5024
+ encoding
5025
+ } });
5026
+ }
5027
+ function doctype() {
5028
+ return new FormatError("XML_DTD_FORBIDDEN", "XML parts must not contain a document type declaration (<!DOCTYPE).");
5029
+ }
5030
+ async function inspectImpl(bytes, options) {
5031
+ let deferred;
5032
+ const maxToken = options?.limits?.maxXmlTokenLength ?? DEFAULT_LIMITS.maxXmlTokenLength;
5033
+ const xmlTargets = /* @__PURE__ */ new Set();
5034
+ const relsDone = /* @__PURE__ */ new Set();
5035
+ const sink = {
5036
+ unsupported: [],
5037
+ broken: /* @__PURE__ */ new Set(),
5038
+ sharedStrings: 0,
5039
+ sheets: [],
5040
+ sniff: (part) => new PartCheck(part, maxToken, (err) => deferred ??= err),
5041
+ relsParsed: (part, rels) => {
5042
+ relsDone.add(part);
5043
+ for (const r of rels) {
5044
+ if (r.external || r.tooLong || r.target === "" || BINARY_KINDS.has(r.kind.toLowerCase())) continue;
5045
+ xmlTargets.add(partKey(r.target));
5046
+ if (r.altTarget !== void 0) xmlTargets.add(partKey(r.altTarget));
5047
+ }
5048
+ }
5049
+ };
5050
+ const { workbook } = await readImpl(bytes, {
5051
+ limits: options?.limits,
5052
+ signal: options?.signal
5053
+ }, { inspect: sink });
5054
+ const ctx = sink.ctx;
5055
+ const pkg = sink.pkg;
5056
+ if (deferred !== void 0) throw deferred;
5057
+ for (const entry of ctx.zip.entries) {
5058
+ if ((ctx.consumed.has(entry.name) || relsDone.has(entry.name)) && !sink.broken.has(entry.name)) continue;
5059
+ const pause = ctx.step();
5060
+ if (pause) await pause;
5061
+ await scanPart(ctx, entry, isXmlByName(pkg, entry.name) || xmlTargets.has(pkg.keyOf(entry)));
5062
+ }
5063
+ const kinds = /* @__PURE__ */ new Set();
5064
+ for (const w of sink.unsupported) if (w.partKind !== void 0) kinds.add(w.partKind);
5065
+ const sheets = workbook.sheets.map((s, index) => {
5066
+ const out = {
5067
+ name: s.name,
5068
+ index,
5069
+ state: s.state ?? "visible",
5070
+ cells: sink.sheets[index].cells
5071
+ };
5072
+ const part = sink.sheets[index].part;
5073
+ if (part !== void 0) out.part = part;
5074
+ if (s.dimension !== void 0) out.dimension = s.dimension;
5075
+ return out;
5076
+ });
5077
+ return {
5078
+ format: sink.format.format,
5079
+ sheets,
5080
+ partKinds: [...kinds],
5081
+ warnings: sink.unsupported,
5082
+ parts: pkg.partNames.length,
5083
+ inflatedBytes: ctx.zip.totalBytesRead,
5084
+ cells: ctx.cells,
5085
+ sharedStrings: sink.sharedStrings
5086
+ };
5087
+ }
5088
+ /**
5089
+ * Inflates one entry to its end, so the zip limits and its CRC are checked;
5090
+ * searches its bytes for `<!DOCTYPE`; and, for an XML part, checks the
5091
+ * encoding of its first bytes. The bytes are searched in PARSE_SLICE pieces
5092
+ * with the signal consulted and the event loop given a turn between them, as
5093
+ * ctx.parse does, so a large stored entry is not one long step.
5094
+ */
5095
+ async function scanPart(ctx, entry, xml) {
5096
+ let tail = "";
5097
+ let offset = 0;
5098
+ let lastPi = -1;
5099
+ let failure;
5100
+ const check = xml ? new PartCheck(entry.name, ctx.limits.maxXmlTokenLength, (err) => failure ??= err) : void 0;
5101
+ try {
5102
+ for await (const chunk of ctx.zip.stream(entry, ctx.signal)) {
5103
+ check?.feed(chunk);
5104
+ if (failure !== void 0) throw failure;
5105
+ for (let at = 0; at < chunk.length;) {
5106
+ const piece = chunk.subarray(at, at + PARSE_SLICE);
5107
+ const s = tail + BYTES.decode(piece);
5108
+ if (DOCTYPE.test(s)) throw doctype();
5109
+ if (check) {
5110
+ const base = offset + at - tail.length;
5111
+ XML_PI.lastIndex = 0;
5112
+ for (let m = XML_PI.exec(s); m; m = XML_PI.exec(s)) if (base + m.index > lastPi) {
5113
+ lastPi = base + m.index;
5114
+ check.pi();
5115
+ }
5116
+ }
5117
+ at += piece.length;
5118
+ tail = s.slice(-32);
5119
+ if (at < chunk.length) {
5120
+ const pause = ctx.step();
5121
+ if (pause) await pause;
5122
+ }
5123
+ }
5124
+ offset += chunk.length;
5125
+ const pause = ctx.step();
5126
+ if (pause) await pause;
5127
+ }
5128
+ check?.end();
5129
+ if (failure !== void 0) throw failure;
5130
+ } catch (err) {
5131
+ throw withPart(err, entry.name);
5132
+ }
5133
+ }
5134
+ /**
5135
+ * The checks of one XML part, parsed by read (through ctx.sniff) or not
5136
+ * (scanPart): its first bytes and its declaration (DeclarationReader), and
5137
+ * that no `<?xml` processing instruction stands anywhere but at the very start.
5138
+ * What it finds is reported once, through `fail`.
5139
+ */
5140
+ var PartCheck = class {
5141
+ part;
5142
+ fail;
5143
+ reader;
5144
+ instructions = 0;
5145
+ failed = false;
5146
+ constructor(part, maxToken, fail) {
5147
+ this.part = part;
5148
+ this.fail = fail;
5149
+ this.reader = new DeclarationReader(part, maxToken);
5150
+ }
5151
+ feed(chunk) {
5152
+ if (!this.failed) this.report(() => this.reader.feed(chunk));
5153
+ }
5154
+ pi() {
5155
+ this.instructions++;
5156
+ }
5157
+ end() {
5158
+ if (!this.failed) this.report(() => this.reader.end());
5159
+ if (!this.failed && this.instructions > (this.reader.hasDeclaration ? 1 : 0)) this.report(() => misplacedDeclaration(this.part));
5160
+ }
5161
+ report(step) {
5162
+ let err;
5163
+ try {
5164
+ err = step();
5165
+ } catch (thrown) {
5166
+ err = withPart(thrown, this.part);
5167
+ }
5168
+ if (err !== void 0) {
5169
+ this.failed = true;
5170
+ this.fail(err);
5171
+ }
5172
+ }
5173
+ };
5174
+ /**
5175
+ * Reads the start of an XML part, however it is chunked: its first four bytes
5176
+ * (signatureEncoding), then, decoded as UTF-8 or UTF-16 by its byte order mark
5177
+ * or, without one, by `<?` in UTF-16, its XML declaration up to `?>`, bounded
5178
+ * like any token by maxXmlTokenLength, which must stand at the very start
5179
+ * (checkDeclaration). Linear: each chunk is decoded and searched once.
5180
+ */
5181
+ var DeclarationReader = class {
5182
+ part;
5183
+ maxToken;
5184
+ hasDeclaration = false;
5185
+ pending = [];
5186
+ pendingLength = 0;
5187
+ decoder;
5188
+ text = "";
5189
+ searched = 0;
5190
+ done = false;
5191
+ constructor(part, maxToken) {
5192
+ this.part = part;
5193
+ this.maxToken = maxToken;
5194
+ }
5195
+ feed(chunk) {
5196
+ if (this.done) return void 0;
5197
+ if (!this.decoder) {
5198
+ this.pending.push(chunk);
5199
+ this.pendingLength += chunk.length;
5200
+ if (this.pendingLength < 4) return void 0;
5201
+ return this.start();
5202
+ }
5203
+ return this.more(this.decoder.decode(chunk, { stream: true }));
5204
+ }
5205
+ end() {
5206
+ if (this.done) return void 0;
5207
+ if (!this.decoder) {
5208
+ const found = this.start();
5209
+ if (found !== void 0 || this.done) return found;
5210
+ }
5211
+ return this.more(this.decoder.decode(), true);
5212
+ }
5213
+ start() {
5214
+ const head = new Uint8Array(this.pendingLength);
5215
+ let at = 0;
5216
+ for (const p of this.pending) {
5217
+ head.set(p, at);
5218
+ at += p.length;
5219
+ }
5220
+ this.pending = [];
5221
+ const sig = signatureEncoding(head);
5222
+ if (sig !== void 0) {
5223
+ this.done = true;
5224
+ return encodingError(this.part, sig);
5225
+ }
5226
+ const Ctor = globalThis.TextDecoder;
5227
+ if (head[0] === 60 && head[1] === 0 && head[2] === 63 && head[3] === 0) this.decoder = new Ctor("utf-16le");
5228
+ else if (head[0] === 0 && head[1] === 60 && head[2] === 0 && head[3] === 63) this.decoder = new Ctor("utf-16be");
5229
+ else this.decoder = newDecoder(head);
5230
+ return this.more(this.decoder.decode(head, { stream: true }));
5231
+ }
5232
+ more(text, final = false) {
5233
+ this.text += text;
5234
+ const t = this.text;
5235
+ if (t.length < 6 && !final && "<?xml".startsWith(t.slice(0, 5).toLowerCase())) return this.bound();
5236
+ if (!/^<\?xml[ \t\r\n?]/i.test(t)) {
5237
+ this.done = true;
5238
+ return;
5239
+ }
5240
+ this.hasDeclaration = true;
5241
+ const close = t.indexOf("?>", Math.max(0, this.searched - 1));
5242
+ if (close === -1) {
5243
+ this.searched = t.length;
5244
+ if (!final) return this.bound();
5245
+ this.done = true;
5246
+ return checkDeclaration(this.part, t);
5247
+ }
5248
+ this.done = true;
5249
+ if (close + 2 > this.maxToken) this.bound(true);
5250
+ return checkDeclaration(this.part, t.slice(0, close + 2));
5251
+ }
5252
+ /** A declaration longer than maxXmlTokenLength is refused, as the tokenizer refuses a token. */
5253
+ bound(over = false) {
5254
+ if (over || this.text.length > this.maxToken) throw new LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${this.maxToken}).`, { details: {
5255
+ limit: "maxXmlTokenLength",
5256
+ value: this.maxToken + 1,
5257
+ max: this.maxToken
5258
+ } });
5259
+ }
5260
+ };
3868
5261
  // src/read.ts
3869
5262
  /** Default limits (docs/api.md §5.2; the measurements behind each value are listed there). */
3870
5263
  const DEFAULT_READ_LIMITS = DEFAULT_LIMITS;
@@ -3884,4 +5277,14 @@ async function read(input, options) {
3884
5277
  warnings
3885
5278
  };
3886
5279
  }
3887
- export { readImpl as a, DEFAULT_LIMITS as c, readSheetNames as i, detectFormat as n, excerpt as o, read as r, quoted as s, DEFAULT_READ_LIMITS as t };
5280
+ /**
5281
+ * Checks an .xlsx, .xlsm, .xltx or .xltm file part by part without building
5282
+ * its cells: every part `read` parses is parsed with the same checks and
5283
+ * limits (every sheet to its end), every other part is inflated and its
5284
+ * bytes searched for a DOCTYPE, and XML parts must be UTF-8 or UTF-16. Throws what `read` throws for any file
5285
+ * `read` refuses under the same limits (docs/api.md §5.2.1).
5286
+ */
5287
+ async function inspect(input, options) {
5288
+ return inspectImpl(await toBytes(input, "inspect"), options);
5289
+ }
5290
+ export { readSheetNames as a, quoted as c, read as i, DEFAULT_LIMITS as l, detectFormat as n, readImpl as o, inspect as r, excerpt as s, DEFAULT_READ_LIMITS as t };