javascript-excel 2.4.0 → 2.6.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.
- package/README.md +4 -2
- package/dist/{address-DUn7-5OS.js → address-BGH42dEg.js} +1 -1
- package/dist/{address-DZBHchLv.cjs → address-DKd_3EGf.cjs} +1 -1
- package/dist/{csv-Dn4MIESx.js → csv-5jVhfM5l.js} +180 -33
- package/dist/{csv-DZ241Y5F.cjs → csv-BkVmMYQq.cjs} +180 -33
- package/dist/csv.cjs +1 -1
- package/dist/csv.d.cts +42 -3
- package/dist/csv.d.ts +42 -3
- package/dist/csv.js +1 -1
- package/dist/{dataset-CbZnEWXu.cjs → dataset-B4-SEdCn.cjs} +4 -4
- package/dist/{dataset-CyEHVht4.js → dataset-Dh598YSG.js} +4 -4
- package/dist/{dates-BXcSWf9_.js → dates-CIL1z9EY.js} +1 -1
- package/dist/{dates-CA1dCizp.cjs → dates-DcdgnJto.cjs} +1 -1
- package/dist/dom.cjs +2 -2
- package/dist/dom.d.cts +1 -1
- package/dist/dom.d.ts +1 -1
- package/dist/dom.js +2 -2
- package/dist/{dos-time-BsH7f0ef.js → dos-time-BEAyK3U8.js} +1 -1
- package/dist/{dos-time-CxEs--rI.cjs → dos-time-BUWyklco.cjs} +1 -1
- package/dist/{errors-CvGlfw0E.js → errors-BQE62PFo.js} +1 -1
- package/dist/{errors-DOPrrGS4.cjs → errors-CKYdpCoB.cjs} +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.js +1 -1
- package/dist/import.cjs +1 -1
- package/dist/import.d.cts +2 -2
- package/dist/import.d.ts +2 -2
- package/dist/import.js +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +7 -7
- package/dist/{infer-BniOucP6.cjs → infer-B950M3-F.cjs} +27 -0
- package/dist/{infer-DcUyZ1T-.js → infer-DuSahY5i.js} +16 -1
- package/dist/{pipeline-C8F9lecW.js → pipeline-BRzRd5v3.js} +12 -7
- package/dist/{pipeline-BegSPu8X.d.ts → pipeline-BY-SiQWW.d.ts} +7 -3
- package/dist/{pipeline-BwkRpV5Z.cjs → pipeline-C13EIWHJ.cjs} +12 -7
- package/dist/{pipeline-4U7Xnuc1.d.cts → pipeline-C7R86kQg.d.cts} +7 -3
- package/dist/{read-cvxu6O-H.js → read-CrI550TK.js} +2269 -784
- package/dist/{read-DmUPztqh.cjs → read-X1KxggZ7.cjs} +2284 -793
- package/dist/read.cjs +2 -1
- package/dist/read.d.cts +49 -2
- package/dist/read.d.ts +49 -2
- package/dist/read.js +2 -2
- package/dist/render.cjs +2 -2
- package/dist/render.js +2 -2
- package/dist/{sheet-names-DDY64-dt.cjs → sheet-names-D8sYcjSd.cjs} +2 -2
- package/dist/{sheet-names-BLrwcn33.js → sheet-names-RoFkpk_R.js} +2 -2
- package/dist/{warnings-DhonqJ7A.d.ts → warnings-Bphby2c7.d.cts} +28 -2
- package/dist/{warnings-DhonqJ7A.d.cts → warnings-Bphby2c7.d.ts} +28 -2
- package/dist/worker.cjs +5 -5
- package/dist/worker.d.cts +4 -4
- package/dist/worker.d.ts +4 -4
- package/dist/worker.js +5 -5
- package/dist/{write-Izl2NG0Y.d.cts → write-BbV7BlbS.d.cts} +1 -1
- package/dist/{write-DKXhuvKR.cjs → write-Bgl_QfA8.cjs} +5 -5
- package/dist/{write-BVXB2_2C.js → write-DFz-h8gz.js} +5 -5
- package/dist/{write-BaMv1Z7W.d.ts → write-DryxCc2Q.d.ts} +1 -1
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as LimitError, i as FormatError } from "./errors-
|
|
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-
|
|
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-
|
|
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/
|
|
38
|
+
// src/internal/read/xml-reader.ts
|
|
39
39
|
/**
|
|
40
|
-
*
|
|
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
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
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
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
95
|
-
|
|
157
|
+
depth() {
|
|
158
|
+
return this.stack.length;
|
|
96
159
|
}
|
|
97
|
-
|
|
98
|
-
this.
|
|
99
|
-
|
|
100
|
-
this.
|
|
101
|
-
|
|
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
|
-
|
|
104
|
-
this.
|
|
105
|
-
|
|
106
|
-
this.
|
|
107
|
-
|
|
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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
if (
|
|
113
|
-
|
|
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
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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,9 @@ 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
|
+
if (where?.relationshipTypes !== void 0) w.relationshipTypes = where.relationshipTypes;
|
|
564
|
+
this.tap?.(w);
|
|
857
565
|
if (this.cap.add(w, (dropped) => {
|
|
858
566
|
const t = {
|
|
859
567
|
code: "WARNINGS_TRUNCATED",
|
|
@@ -922,10 +630,12 @@ var ReadContext = class {
|
|
|
922
630
|
*/
|
|
923
631
|
async parse(entry, handler, onChunk) {
|
|
924
632
|
this.consumed.add(entry.name);
|
|
925
|
-
const
|
|
633
|
+
const sniffer = this.sniff?.(entry.name);
|
|
634
|
+
const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength, sniffer && ((pi) => sniffer.pi(pi)));
|
|
926
635
|
let decoder;
|
|
927
636
|
try {
|
|
928
637
|
for await (const chunk of this.zip.stream(entry, this.signal)) {
|
|
638
|
+
sniffer?.feed(chunk);
|
|
929
639
|
let bytes = chunk;
|
|
930
640
|
if (!decoder) {
|
|
931
641
|
decoder = newDecoder(chunk);
|
|
@@ -954,239 +664,818 @@ var ReadContext = class {
|
|
|
954
664
|
}
|
|
955
665
|
if (decoder) tok.feed(decoder.decode());
|
|
956
666
|
tok.end();
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
}
|
|
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;
|
|
979
|
-
}
|
|
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");
|
|
985
|
-
}
|
|
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;
|
|
990
|
-
}
|
|
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
|
-
]
|
|
1024
|
-
}
|
|
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)"
|
|
1059
|
-
}
|
|
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" }
|
|
667
|
+
sniffer?.end();
|
|
668
|
+
} catch (err) {
|
|
669
|
+
throw withPart(err, entry.name);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
1066
672
|
};
|
|
1067
|
-
function
|
|
1068
|
-
|
|
1069
|
-
|
|
673
|
+
function withPart(err, part) {
|
|
674
|
+
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}`, {
|
|
675
|
+
details: {
|
|
676
|
+
...err.details,
|
|
677
|
+
part
|
|
678
|
+
},
|
|
679
|
+
cause: err
|
|
680
|
+
});
|
|
681
|
+
const limit = err instanceof LimitError ? err.details?.["limit"] : void 0;
|
|
682
|
+
if (err instanceof LimitError && (limit === "maxXmlDepth" || limit === "maxXmlTokenLength" || limit === "maxCellTextLength") && !err.details?.["part"]) return new LimitError(err.code, `${excerpt(part)}: ${err.message}`, {
|
|
683
|
+
details: {
|
|
684
|
+
...err.details,
|
|
685
|
+
part
|
|
686
|
+
},
|
|
687
|
+
cause: err
|
|
688
|
+
});
|
|
689
|
+
return err;
|
|
690
|
+
}
|
|
691
|
+
function newDecoder(first) {
|
|
692
|
+
const Ctor = globalThis.TextDecoder;
|
|
693
|
+
if (first[0] === 255 && first[1] === 254) return new Ctor("utf-16le");
|
|
694
|
+
if (first[0] === 254 && first[1] === 255) return new Ctor("utf-16be");
|
|
695
|
+
return new Ctor("utf-8");
|
|
696
|
+
}
|
|
697
|
+
function stripBom(b) {
|
|
698
|
+
if (b[0] === 239 && b[1] === 187 && b[2] === 191) return b.subarray(3);
|
|
699
|
+
if (b[0] === 255 && b[1] === 254 || b[0] === 254 && b[1] === 255) return b.subarray(2);
|
|
700
|
+
return b;
|
|
1070
701
|
}
|
|
702
|
+
// src/internal/read/opc.ts
|
|
1071
703
|
/**
|
|
1072
|
-
*
|
|
1073
|
-
*
|
|
1074
|
-
*
|
|
704
|
+
* Open Packaging Conventions for the reader: part lookup by part-name
|
|
705
|
+
* equivalence (percent-decoded once, case-insensitive, as OPC requires),
|
|
706
|
+
* [Content_Types].xml and relationship parts. Internal.
|
|
1075
707
|
*/
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
return WORKBOOK_FORMATS[0];
|
|
708
|
+
/** A URI scheme (RFC 3986) at the start, after spaces; a network-path reference (`//`); or a backslash anywhere. */
|
|
709
|
+
function pointsOutside(target) {
|
|
710
|
+
if (target.includes("\\")) return true;
|
|
711
|
+
const t = target.trimStart();
|
|
712
|
+
return t.startsWith("//") || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(t);
|
|
1082
713
|
}
|
|
1083
|
-
// src/internal/read/opc.ts
|
|
1084
714
|
/**
|
|
1085
|
-
*
|
|
1086
|
-
*
|
|
715
|
+
* Whether the attributes of a `<Relationship>` read as internal may name a
|
|
716
|
+
* target outside the package (Relationship.outside). One pass over the
|
|
717
|
+
* attributes as written (duplicates included), linear in the tag.
|
|
1087
718
|
*/
|
|
719
|
+
function outsideByAttributes(a) {
|
|
720
|
+
let modes = 0;
|
|
721
|
+
for (const [q, v] of a.entries()) {
|
|
722
|
+
const colon = q.indexOf(":");
|
|
723
|
+
if (q === "xmlns" || colon > 0 && q.slice(0, colon) === "xmlns") continue;
|
|
724
|
+
const len = q.length - colon - 1;
|
|
725
|
+
if (len !== 10 && len !== 6) continue;
|
|
726
|
+
const local = (colon === -1 ? q : q.slice(colon + 1)).toLowerCase();
|
|
727
|
+
if (local === "targetmode") {
|
|
728
|
+
if (q !== "TargetMode" || ++modes > 1) return true;
|
|
729
|
+
const mode = v.toLowerCase();
|
|
730
|
+
if (mode !== "internal" && mode !== "external") return true;
|
|
731
|
+
} else if (local === "target" && pointsOutside(v)) return true;
|
|
732
|
+
}
|
|
733
|
+
return false;
|
|
734
|
+
}
|
|
1088
735
|
var Package = class {
|
|
1089
736
|
ctx;
|
|
737
|
+
/** partKey(name) -> entry. */
|
|
1090
738
|
parts = /* @__PURE__ */ new Map();
|
|
1091
|
-
/**
|
|
739
|
+
/** entry -> partKey(entry.name), computed once. */
|
|
740
|
+
keys = /* @__PURE__ */ new Map();
|
|
741
|
+
/**
|
|
742
|
+
* Names OPC forbids, in the order found: zip entries (see `forbiddenName`),
|
|
743
|
+
* then `[Content_Types].xml` when one of its PartNames is forbidden.
|
|
744
|
+
*/
|
|
745
|
+
forbiddenNames = [];
|
|
746
|
+
/**
|
|
747
|
+
* Relationships that are not well-formed, by relationships part (entry
|
|
748
|
+
* name): an element without `Id` (or with an empty one) or without
|
|
749
|
+
* `Target`. They are left out of `rels()`, so the model ignores them as
|
|
750
|
+
* 2.4.0 did, but the package scan classifies them. One without `Type` is
|
|
751
|
+
* listed with type '' (nothing to classify).
|
|
752
|
+
*/
|
|
753
|
+
malformedRels = /* @__PURE__ */ new Map();
|
|
754
|
+
/** 2.4.0's override table (raw lower-case PartName, last wins), for format detection only. */
|
|
755
|
+
legacyOverrides = /* @__PURE__ */ new Map();
|
|
756
|
+
/** partKey(part name) -> content types, in the order [Content_Types].xml lists them. */
|
|
1092
757
|
overrides = /* @__PURE__ */ new Map();
|
|
1093
|
-
/** Extension (lower case) -> content
|
|
758
|
+
/** Extension (lower case) -> content types. */
|
|
1094
759
|
defaults = /* @__PURE__ */ new Map();
|
|
760
|
+
/**
|
|
761
|
+
* Indexes the zip entries by part name. Two entries whose names are
|
|
762
|
+
* equivalent (equal in canonical form, case-insensitively) make the package
|
|
763
|
+
* invalid: ZIP_INVALID, as OPC requires. Consults the signal for every
|
|
764
|
+
* entry (each costs work linear in its name, up to 64 KB).
|
|
765
|
+
*/
|
|
1095
766
|
constructor(ctx) {
|
|
1096
767
|
this.ctx = ctx;
|
|
1097
|
-
|
|
768
|
+
const entries = ctx.zip.entries;
|
|
769
|
+
for (let i = 0; i < entries.length; i++) {
|
|
770
|
+
ctx.checkAbort();
|
|
771
|
+
const e = entries[i];
|
|
1098
772
|
if (e.name.endsWith("/")) continue;
|
|
1099
|
-
const key = e.name
|
|
1100
|
-
|
|
773
|
+
const key = partKey(e.name);
|
|
774
|
+
const earlier = this.parts.get(key);
|
|
775
|
+
if (earlier) {
|
|
776
|
+
const how = earlier.name.toLowerCase() === e.name.toLowerCase() ? "differ only in case" : "are equivalent (they differ only in case or percent-encoding)";
|
|
777
|
+
throw new FormatError("ZIP_INVALID", `Part names ${excerpt(earlier.name)} and ${excerpt(e.name)} ${how}.`, { details: { entry: e.name } });
|
|
778
|
+
}
|
|
1101
779
|
this.parts.set(key, e);
|
|
780
|
+
this.keys.set(e, key);
|
|
781
|
+
if (forbiddenName(e.name, false)) this.forbiddenNames.push(e.name);
|
|
782
|
+
}
|
|
783
|
+
ctx.checkAbort();
|
|
784
|
+
}
|
|
785
|
+
/** The lookup key of a zip entry of this package (partKey of its name, computed once). */
|
|
786
|
+
keyOf(entry) {
|
|
787
|
+
return this.keys.get(entry) ?? partKey(entry.name);
|
|
788
|
+
}
|
|
789
|
+
part(name) {
|
|
790
|
+
if (name.length > 196605) return void 0;
|
|
791
|
+
return this.parts.get(partKey(name));
|
|
792
|
+
}
|
|
793
|
+
get partNames() {
|
|
794
|
+
return [...this.parts.values()].map((e) => e.name);
|
|
795
|
+
}
|
|
796
|
+
async loadContentTypes() {
|
|
797
|
+
const entry = this.part("[Content_Types].xml");
|
|
798
|
+
if (!entry) return;
|
|
799
|
+
let badPartName = false;
|
|
800
|
+
await this.ctx.parse(entry, {
|
|
801
|
+
open: (name, a) => {
|
|
802
|
+
if (name === "Default") {
|
|
803
|
+
const ext = a.get("Extension");
|
|
804
|
+
const type = a.get("ContentType");
|
|
805
|
+
if (ext && type) push(this.defaults, ext.toLowerCase(), type);
|
|
806
|
+
} else if (name === "Override") {
|
|
807
|
+
const part = a.get("PartName");
|
|
808
|
+
const type = a.get("ContentType");
|
|
809
|
+
if (!part || !type) return;
|
|
810
|
+
this.legacyOverrides.set(stripSlash(part).toLowerCase(), type);
|
|
811
|
+
if (part.length > 196605) {
|
|
812
|
+
badPartName = true;
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
if (forbiddenName(part, false)) badPartName = true;
|
|
816
|
+
const key = partKey(part);
|
|
817
|
+
push(this.overrides, key, type);
|
|
818
|
+
const decoded = partKey(resolveTarget("", part));
|
|
819
|
+
if (decoded !== key) push(this.overrides, decoded, type);
|
|
820
|
+
}
|
|
821
|
+
},
|
|
822
|
+
close: () => {},
|
|
823
|
+
text: () => {}
|
|
824
|
+
});
|
|
825
|
+
if (badPartName) this.forbiddenNames.push(entry.name);
|
|
826
|
+
}
|
|
827
|
+
/** 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. */
|
|
828
|
+
contentType(name) {
|
|
829
|
+
const key = stripSlash(name).toLowerCase();
|
|
830
|
+
const o = this.legacyOverrides.get(key);
|
|
831
|
+
if (o) return o;
|
|
832
|
+
const dot = key.lastIndexOf(".");
|
|
833
|
+
return dot === -1 ? void 0 : this.defaults.get(key.slice(dot + 1))?.at(-1);
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Every content type [Content_Types].xml gives the part: all Overrides with
|
|
837
|
+
* an equivalent part name, else all Defaults for its extension. The package
|
|
838
|
+
* scan checks each, so a later passive entry cannot hide an active one.
|
|
839
|
+
*/
|
|
840
|
+
contentTypes(name) {
|
|
841
|
+
if (name.length > 196605) return [];
|
|
842
|
+
const key = partKey(name);
|
|
843
|
+
const o = this.overrides.get(key);
|
|
844
|
+
if (o) return o;
|
|
845
|
+
const dot = key.lastIndexOf(".");
|
|
846
|
+
return (dot > key.lastIndexOf("/") ? this.defaults.get(key.slice(dot + 1)) : void 0) ?? [];
|
|
847
|
+
}
|
|
848
|
+
/** Content types of the overrides for format detection: one per raw PartName, the last given, exactly as 2.4.0. */
|
|
849
|
+
get overrideTypes() {
|
|
850
|
+
return [...this.legacyOverrides.values()];
|
|
851
|
+
}
|
|
852
|
+
/** The relationships part of `source` ('' for the package), whether or not it exists. */
|
|
853
|
+
relsPartOf(source) {
|
|
854
|
+
const src = stripSlash(source);
|
|
855
|
+
const slash = src.lastIndexOf("/");
|
|
856
|
+
return `${slash === -1 ? "" : src.slice(0, slash + 1)}_rels/${slash === -1 ? src : src.slice(slash + 1)}.rels`;
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Relationships of `source` ('' for the package). Missing rels part: [].
|
|
860
|
+
* Each relationships part is parsed once per read and the result shared, so
|
|
861
|
+
* callers must not change the array. With `peek`, a part not read before is
|
|
862
|
+
* not marked as consumed (InternalReadOptions.retainParts still keeps it).
|
|
863
|
+
*/
|
|
864
|
+
async rels(source, options) {
|
|
865
|
+
const entry = this.part(this.relsPartOf(source));
|
|
866
|
+
if (!entry) return [];
|
|
867
|
+
const consumed = this.ctx.consumed;
|
|
868
|
+
const cached = this.relsCache.get(entry.name);
|
|
869
|
+
if (cached) {
|
|
870
|
+
if (!options?.peek) consumed.add(entry.name);
|
|
871
|
+
return cached;
|
|
872
|
+
}
|
|
873
|
+
const wasConsumed = consumed.has(entry.name);
|
|
874
|
+
try {
|
|
875
|
+
const out = await this.parseRels(entry, source);
|
|
876
|
+
this.relsCache.set(entry.name, out);
|
|
877
|
+
return out;
|
|
878
|
+
} finally {
|
|
879
|
+
if (options?.peek && !wasConsumed) consumed.delete(entry.name);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
relsCache = /* @__PURE__ */ new Map();
|
|
883
|
+
async parseRels(entry, source) {
|
|
884
|
+
const src = stripSlash(source);
|
|
885
|
+
const slash = src.lastIndexOf("/");
|
|
886
|
+
const dir = slash === -1 ? "" : src.slice(0, slash + 1);
|
|
887
|
+
const out = [];
|
|
888
|
+
const malformed = [];
|
|
889
|
+
await this.ctx.parse(entry, {
|
|
890
|
+
open: (name, a) => {
|
|
891
|
+
if (name !== "Relationship") return;
|
|
892
|
+
const id = a.get("Id");
|
|
893
|
+
const type = a.get("Type") ?? "";
|
|
894
|
+
const target = a.get("Target");
|
|
895
|
+
const external = (a.get("TargetMode") ?? "").toLowerCase() === "external";
|
|
896
|
+
const rel = {
|
|
897
|
+
id: id ?? "",
|
|
898
|
+
type,
|
|
899
|
+
kind: type.slice(type.lastIndexOf("/") + 1),
|
|
900
|
+
target: "",
|
|
901
|
+
external
|
|
902
|
+
};
|
|
903
|
+
if (!external && outsideByAttributes(a)) rel.outside = true;
|
|
904
|
+
if (target === void 0) {
|
|
905
|
+
malformed.push(rel);
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
if (external) rel.target = target;
|
|
909
|
+
else if (target.trim().length > 196605) {
|
|
910
|
+
rel.tooLong = true;
|
|
911
|
+
rel.forbidden = true;
|
|
912
|
+
} else {
|
|
913
|
+
const readings = resolveReadings(dir, target);
|
|
914
|
+
rel.target = readings.target;
|
|
915
|
+
const key = partKey(rel.target);
|
|
916
|
+
if (forbiddenName(stripFragment(target), true) || isPackageMetadata(key)) rel.forbidden = true;
|
|
917
|
+
if (readings.alt !== void 0) {
|
|
918
|
+
const altKey = partKey(readings.alt);
|
|
919
|
+
if (altKey !== key) {
|
|
920
|
+
rel.altTarget = readings.alt;
|
|
921
|
+
if (isPackageMetadata(altKey)) rel.forbidden = true;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
if (!id || !type) malformed.push(rel);
|
|
926
|
+
else out.push(rel);
|
|
927
|
+
},
|
|
928
|
+
close: () => {},
|
|
929
|
+
text: () => {}
|
|
930
|
+
});
|
|
931
|
+
if (malformed.length) this.malformedRels.set(entry.name, malformed);
|
|
932
|
+
this.ctx.relsParsed?.(entry.name, out);
|
|
933
|
+
return out;
|
|
934
|
+
}
|
|
935
|
+
};
|
|
936
|
+
/**
|
|
937
|
+
* A relationships part (`…/_rels/<name>.rels`) or `[Content_Types].xml`, by
|
|
938
|
+
* part key: package metadata that OPC forbids as a relationship target.
|
|
939
|
+
*/
|
|
940
|
+
function isPackageMetadata(key) {
|
|
941
|
+
if (key === "[content_types].xml") return true;
|
|
942
|
+
if (!key.endsWith(".rels")) return false;
|
|
943
|
+
const slash = key.lastIndexOf("/");
|
|
944
|
+
const parent = key.slice(0, slash === -1 ? 0 : slash);
|
|
945
|
+
return parent === "_rels" || parent.endsWith("/_rels");
|
|
946
|
+
}
|
|
947
|
+
/** The owner of a relationships part (`a/_rels/b.xml.rels` -> `a/b.xml`, `_rels/.rels` -> ''), or undefined if `name` is not one. */
|
|
948
|
+
function relsOwner(name) {
|
|
949
|
+
const slash = name.lastIndexOf("/");
|
|
950
|
+
const file = name.slice(slash + 1);
|
|
951
|
+
if (slash === -1 || !/\.rels$/i.test(file)) return void 0;
|
|
952
|
+
const parent = name.slice(0, slash);
|
|
953
|
+
const parentSlash = parent.lastIndexOf("/");
|
|
954
|
+
if (parent.slice(parentSlash + 1).toLowerCase() !== "_rels") return void 0;
|
|
955
|
+
return parent.slice(0, parentSlash + 1) + file.slice(0, -5);
|
|
956
|
+
}
|
|
957
|
+
function stripSlash(name) {
|
|
958
|
+
return name.startsWith("/") ? name.slice(1) : name;
|
|
959
|
+
}
|
|
960
|
+
function push(map, key, value) {
|
|
961
|
+
const list = map.get(key);
|
|
962
|
+
if (list) list.push(value);
|
|
963
|
+
else map.set(key, [value]);
|
|
964
|
+
}
|
|
965
|
+
function stripFragment(target) {
|
|
966
|
+
const hash = target.indexOf("#");
|
|
967
|
+
return hash === -1 ? target : target.slice(0, hash);
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* True when a part name or relationship target uses a segment OPC forbids
|
|
971
|
+
* (ECMA-376 Part 2 §6.2.2): one containing `%2F` or `%5C`, a percent-encoded
|
|
972
|
+
* dot segment (`%2E`, `%2E%2E`, `.%2E`, `%2E.`), or one ending in a dot. For
|
|
973
|
+
* a relationship target (`isTarget`), the literal `.` and `..` segments of a
|
|
974
|
+
* relative reference are allowed; in a zip entry name they are forbidden too.
|
|
975
|
+
* Segments are split on `/` and, in a target, on `\`. Linear in the length.
|
|
976
|
+
*/
|
|
977
|
+
function forbiddenName(name, isTarget) {
|
|
978
|
+
const n = name.length;
|
|
979
|
+
let segStart = 0;
|
|
980
|
+
for (let i = 0; i <= n; i++) {
|
|
981
|
+
const c = i < n ? name.charCodeAt(i) : 47;
|
|
982
|
+
if (c !== 47 && !(isTarget && c === 92)) continue;
|
|
983
|
+
if (i > segStart && forbiddenSegment(name, segStart, i, isTarget)) return true;
|
|
984
|
+
segStart = i + 1;
|
|
985
|
+
}
|
|
986
|
+
return false;
|
|
987
|
+
}
|
|
988
|
+
function forbiddenSegment(s, from, to, isTarget) {
|
|
989
|
+
let lastIsDot = false;
|
|
990
|
+
let literalDotSegment = true;
|
|
991
|
+
for (let i = from; i < to; i++) {
|
|
992
|
+
const c = s.charCodeAt(i);
|
|
993
|
+
if (c === 37 && i + 2 < to) {
|
|
994
|
+
const h = s.charCodeAt(i + 1) << 8 | (s.charCodeAt(i + 2) | 32);
|
|
995
|
+
if (h === 12902 || h === 13667) return true;
|
|
996
|
+
if (h === 12901) {
|
|
997
|
+
lastIsDot = true;
|
|
998
|
+
literalDotSegment = false;
|
|
999
|
+
i += 2;
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
lastIsDot = c === 46;
|
|
1004
|
+
if (!lastIsDot) literalDotSegment = false;
|
|
1005
|
+
}
|
|
1006
|
+
if (!lastIsDot) return false;
|
|
1007
|
+
if (isTarget && literalDotSegment && to - from <= 2) return false;
|
|
1008
|
+
return true;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Part-name equivalence (OPC, ECMA-376 Part 2 §6.2.2.3 and the zip mapping of
|
|
1012
|
+
* §7.3.4): `name` with its percent-escapes decoded once, as UTF-8. Kept
|
|
1013
|
+
* encoded (upper-case hex), so that nothing decoded can act as structure or
|
|
1014
|
+
* as a new escape: `%2F`, `%5C`, `%25`, a `%` that does not start an escape
|
|
1015
|
+
* (written `%25`), and each byte that is not part of a valid UTF-8 sequence.
|
|
1016
|
+
* Not lower-cased. Idempotent: canonicalPartName(canonicalPartName(s)) ===
|
|
1017
|
+
* canonicalPartName(s). One linear pass, no decoder calls.
|
|
1018
|
+
*/
|
|
1019
|
+
function canonicalPartName(name) {
|
|
1020
|
+
let i = name.indexOf("%");
|
|
1021
|
+
if (i === -1) return name;
|
|
1022
|
+
const n = name.length;
|
|
1023
|
+
let out = "";
|
|
1024
|
+
/** Start of the input not yet copied: text that canonicalises to itself is copied in one slice. */
|
|
1025
|
+
let from = 0;
|
|
1026
|
+
const emit = (end, text, next) => {
|
|
1027
|
+
out += name.slice(from, end) + text;
|
|
1028
|
+
from = next;
|
|
1029
|
+
};
|
|
1030
|
+
while (i < n) {
|
|
1031
|
+
if (name.charCodeAt(i) !== 37) {
|
|
1032
|
+
i = name.indexOf("%", i);
|
|
1033
|
+
if (i === -1) break;
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
const b = hexByte(name, i);
|
|
1037
|
+
if (b < 0) {
|
|
1038
|
+
emit(i, "%25", i + 1);
|
|
1039
|
+
i++;
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
if (b === 37 || b === 47 || b === 92 || b >= 128) {
|
|
1043
|
+
const len = b >= 128 ? utf8Length(name, i, b) : 0;
|
|
1044
|
+
if (len) {
|
|
1045
|
+
let cp = len === 2 ? b & 31 : len === 3 ? b & 15 : b & 7;
|
|
1046
|
+
for (let k = 1; k < len; k++) cp = cp << 6 | hexByte(name, i + 3 * k) & 63;
|
|
1047
|
+
emit(i, String.fromCodePoint(cp), i + 3 * len);
|
|
1048
|
+
i += 3 * len;
|
|
1049
|
+
} else {
|
|
1050
|
+
if (name.charCodeAt(i + 1) > 96 || name.charCodeAt(i + 2) > 96) emit(i, HEX[b], i + 3);
|
|
1051
|
+
i += 3;
|
|
1052
|
+
}
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
emit(i, String.fromCharCode(b), i + 3);
|
|
1056
|
+
i += 3;
|
|
1057
|
+
}
|
|
1058
|
+
return from === 0 ? name : out + name.slice(from);
|
|
1059
|
+
}
|
|
1060
|
+
const HEX = Array.from({ length: 256 }, (_, b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`);
|
|
1061
|
+
/**
|
|
1062
|
+
* The length in bytes of the valid UTF-8 sequence whose lead byte `b` is the
|
|
1063
|
+
* escape at `i` (its continuation bytes are the escapes that follow), or 0.
|
|
1064
|
+
* Rejects overlong forms, surrogates and code points above U+10FFFF.
|
|
1065
|
+
*/
|
|
1066
|
+
function utf8Length(name, i, b) {
|
|
1067
|
+
const len = b >= 194 && b <= 223 ? 2 : b >= 224 && b <= 239 ? 3 : b >= 240 && b <= 244 ? 4 : 0;
|
|
1068
|
+
for (let k = 1; k < len; k++) {
|
|
1069
|
+
const cb = hexByte(name, i + 3 * k);
|
|
1070
|
+
if (cb < 0 || (cb & 192) !== 128) return 0;
|
|
1071
|
+
if (k === 1 && (b === 224 && cb < 160 || b === 237 && cb > 159 || b === 240 && cb < 144 || b === 244 && cb > 143)) return 0;
|
|
1072
|
+
}
|
|
1073
|
+
return len;
|
|
1074
|
+
}
|
|
1075
|
+
/** The byte of the escape `%XX` at `i`, or -1. */
|
|
1076
|
+
function hexByte(s, i) {
|
|
1077
|
+
if (s.charCodeAt(i) !== 37 || i + 2 >= s.length) return -1;
|
|
1078
|
+
const h = hexDigit(s.charCodeAt(i + 1));
|
|
1079
|
+
const l = hexDigit(s.charCodeAt(i + 2));
|
|
1080
|
+
return h < 0 || l < 0 ? -1 : h << 4 | l;
|
|
1081
|
+
}
|
|
1082
|
+
function hexDigit(c) {
|
|
1083
|
+
if (c >= 48 && c <= 57) return c - 48;
|
|
1084
|
+
const l = c | 32;
|
|
1085
|
+
return l >= 97 && l <= 102 ? l - 97 + 10 : -1;
|
|
1086
|
+
}
|
|
1087
|
+
/** The lookup key of a part name: canonical, no leading '/', lower case (part names compare case-insensitively). */
|
|
1088
|
+
function partKey(name) {
|
|
1089
|
+
return canonicalPartName(stripSlash(name)).toLowerCase();
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Resolves a relationship target against the source part's folder, as a
|
|
1093
|
+
* decoder reads it (and as 2.4.0 did): `/`, `\`, `%2F` and `%5C` separate
|
|
1094
|
+
* segments, and a segment that is `.` or `..` once `%2E` is decoded is a dot
|
|
1095
|
+
* segment. Each other segment is put in canonical form once. For a target
|
|
1096
|
+
* OPC allows this is the only reading; for others, see resolveTargetLiteral.
|
|
1097
|
+
*/
|
|
1098
|
+
function resolveTarget(baseDir, target) {
|
|
1099
|
+
return resolveReadings(baseDir, target).target;
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Both readings of a relationship target. `target` is the one `read` uses,
|
|
1103
|
+
* as 2.4.0 resolved it: decoded (resolveTargetDecoded), or, when the target
|
|
1104
|
+
* has an escape that is not valid UTF-8 or a `%` that starts no escape (2.4.0's
|
|
1105
|
+
* decodeURIComponent threw and the target was kept raw), literal
|
|
1106
|
+
* (resolveTargetLiteral). `alt` is the other reading, when the target has
|
|
1107
|
+
* an escape that can change its structure (`%2F`, `%5C`, `%2E`).
|
|
1108
|
+
*/
|
|
1109
|
+
function resolveReadings(baseDir, target) {
|
|
1110
|
+
const t = stripFragment(target);
|
|
1111
|
+
const structural = /%(2f|5c|2e)/i.test(t);
|
|
1112
|
+
if (malformedEscapes(t)) {
|
|
1113
|
+
const literal = resolveTargetLiteral(baseDir, t);
|
|
1114
|
+
return structural ? {
|
|
1115
|
+
target: literal,
|
|
1116
|
+
alt: resolveTargetDecoded(baseDir, t)
|
|
1117
|
+
} : { target: literal };
|
|
1118
|
+
}
|
|
1119
|
+
const decoded = resolveTargetDecoded(baseDir, t);
|
|
1120
|
+
return structural ? {
|
|
1121
|
+
target: decoded,
|
|
1122
|
+
alt: resolveTargetLiteral(baseDir, t)
|
|
1123
|
+
} : { target: decoded };
|
|
1124
|
+
}
|
|
1125
|
+
/** True when decodeURIComponent would throw: a `%` that starts no escape, or escapes that are not valid UTF-8. Linear. */
|
|
1126
|
+
function malformedEscapes(name) {
|
|
1127
|
+
let i = name.indexOf("%");
|
|
1128
|
+
while (i !== -1) {
|
|
1129
|
+
const b = hexByte(name, i);
|
|
1130
|
+
if (b < 0) return true;
|
|
1131
|
+
if (b < 128) i += 3;
|
|
1132
|
+
else {
|
|
1133
|
+
const len = utf8Length(name, i, b);
|
|
1134
|
+
if (!len) return true;
|
|
1135
|
+
i += 3 * len;
|
|
1102
1136
|
}
|
|
1137
|
+
i = name.indexOf("%", i);
|
|
1138
|
+
}
|
|
1139
|
+
return false;
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* The decoder's reading: `/`, `\`, `%2F` and `%5C` separate segments, and a
|
|
1143
|
+
* segment that is `.` or `..` once `%2E` is decoded is a dot segment. Each
|
|
1144
|
+
* other segment is put in canonical form once.
|
|
1145
|
+
*/
|
|
1146
|
+
function resolveTargetDecoded(baseDir, target) {
|
|
1147
|
+
const t = stripFragment(target).replace(/%2f|%5c|\\/gi, "/");
|
|
1148
|
+
const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== "");
|
|
1149
|
+
for (const seg of t.split("/")) {
|
|
1150
|
+
const dots = seg.length <= 6 ? seg.replace(/%2e/gi, ".") : seg;
|
|
1151
|
+
if (dots === "" || dots === ".") continue;
|
|
1152
|
+
if (dots === "..") segments.pop();
|
|
1153
|
+
else segments.push(canonicalPartName(seg));
|
|
1154
|
+
}
|
|
1155
|
+
return segments.join("/");
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Resolves a relationship target taking every escape literally: only `/` and
|
|
1159
|
+
* `\` separate segments and only literal `.` and `..` are dot segments, so
|
|
1160
|
+
* `%2E%2E`, `%2F` and `%5C` stay part of a name.
|
|
1161
|
+
*/
|
|
1162
|
+
function resolveTargetLiteral(baseDir, target) {
|
|
1163
|
+
const t = stripFragment(target).replace(/\\/g, "/");
|
|
1164
|
+
const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== "");
|
|
1165
|
+
for (const seg of t.split("/")) {
|
|
1166
|
+
if (seg === "" || seg === ".") continue;
|
|
1167
|
+
if (seg === "..") segments.pop();
|
|
1168
|
+
else segments.push(canonicalPartName(seg));
|
|
1169
|
+
}
|
|
1170
|
+
return segments.join("/");
|
|
1171
|
+
}
|
|
1172
|
+
// src/internal/zip/read.ts
|
|
1173
|
+
/**
|
|
1174
|
+
* Zip container reader (docs/api.md §6, §8). Internal.
|
|
1175
|
+
*
|
|
1176
|
+
* `openZip` parses the central directory synchronously and validates the whole
|
|
1177
|
+
* layout before any data is inflated:
|
|
1178
|
+
* - end-of-central-directory record, with zip64 records when present;
|
|
1179
|
+
* - single-disk archives only;
|
|
1180
|
+
* - every entry's local header must agree with its central record;
|
|
1181
|
+
* - entry data must not overlap other entries or the central directory;
|
|
1182
|
+
* - duplicate names, encryption and methods other than 0 and 8 are rejected.
|
|
1183
|
+
*
|
|
1184
|
+
* Reading an entry counts the actual decompressed bytes against the limits
|
|
1185
|
+
* (never trusting declared sizes), stops when an entry produces more than it
|
|
1186
|
+
* declared, and verifies its CRC-32.
|
|
1187
|
+
*/
|
|
1188
|
+
/** The zip-related defaults of docs/api.md §5.2, the same values as DEFAULT_READ_LIMITS (measured in JSE-6). */
|
|
1189
|
+
const DEFAULT_ZIP_LIMITS = Object.freeze({
|
|
1190
|
+
maxInputBytes: 268435456,
|
|
1191
|
+
maxEntries: 1e4,
|
|
1192
|
+
maxEntryBytes: 536870912,
|
|
1193
|
+
maxTotalBytes: 1073741824,
|
|
1194
|
+
maxRatio: 1e3
|
|
1195
|
+
});
|
|
1196
|
+
const SIG_LOCAL = 67324752;
|
|
1197
|
+
const SIG_CENTRAL = 33639248;
|
|
1198
|
+
const SIG_EOCD = 101010256;
|
|
1199
|
+
const SIG_ZIP64_EOCD = 101075792;
|
|
1200
|
+
const SIG_ZIP64_LOCATOR = 117853008;
|
|
1201
|
+
const FLAG_ENCRYPTED = 1;
|
|
1202
|
+
const FLAG_DATA_DESCRIPTOR = 8;
|
|
1203
|
+
const FLAG_UTF8 = 2048;
|
|
1204
|
+
const EXTRA_ZIP64 = 1;
|
|
1205
|
+
const EXTRA_UNICODE_PATH = 28789;
|
|
1206
|
+
const METHOD_AES = 99;
|
|
1207
|
+
/** Code page 437, bytes 0x80..0xFF: the spec's default encoding for names without bit 11. */
|
|
1208
|
+
const CP437_HIGH = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
|
|
1209
|
+
function invalid(message, details) {
|
|
1210
|
+
return new FormatError("ZIP_INVALID", message, details ? { details } : void 0);
|
|
1211
|
+
}
|
|
1212
|
+
function limitError(limit, value, max, what) {
|
|
1213
|
+
return new LimitError("LIMIT_EXCEEDED", `${what} exceeds the ${limit} limit (${max}).`, { details: {
|
|
1214
|
+
limit,
|
|
1215
|
+
value,
|
|
1216
|
+
max
|
|
1217
|
+
} });
|
|
1218
|
+
}
|
|
1219
|
+
var Cursor = class {
|
|
1220
|
+
bytes;
|
|
1221
|
+
pos;
|
|
1222
|
+
view;
|
|
1223
|
+
constructor(bytes, pos) {
|
|
1224
|
+
this.bytes = bytes;
|
|
1225
|
+
this.pos = pos;
|
|
1226
|
+
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1227
|
+
}
|
|
1228
|
+
need(n) {
|
|
1229
|
+
if (this.pos < 0 || this.pos + n > this.bytes.length) throw invalid("Unexpected end of zip data.");
|
|
1230
|
+
}
|
|
1231
|
+
u16() {
|
|
1232
|
+
this.need(2);
|
|
1233
|
+
const v = this.view.getUint16(this.pos, true);
|
|
1234
|
+
this.pos += 2;
|
|
1235
|
+
return v;
|
|
1103
1236
|
}
|
|
1104
|
-
|
|
1105
|
-
|
|
1237
|
+
u32() {
|
|
1238
|
+
this.need(4);
|
|
1239
|
+
const v = this.view.getUint32(this.pos, true);
|
|
1240
|
+
this.pos += 4;
|
|
1241
|
+
return v;
|
|
1106
1242
|
}
|
|
1107
|
-
|
|
1108
|
-
|
|
1243
|
+
u64() {
|
|
1244
|
+
const lo = this.u32();
|
|
1245
|
+
const v = this.u32() * 4294967296 + lo;
|
|
1246
|
+
if (!Number.isSafeInteger(v)) throw invalid("Zip64 value out of range.");
|
|
1247
|
+
return v;
|
|
1109
1248
|
}
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
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
|
-
});
|
|
1249
|
+
take(n) {
|
|
1250
|
+
this.need(n);
|
|
1251
|
+
const out = this.bytes.subarray(this.pos, this.pos + n);
|
|
1252
|
+
this.pos += n;
|
|
1253
|
+
return out;
|
|
1128
1254
|
}
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1255
|
+
};
|
|
1256
|
+
function decodeName(raw, flags, extra) {
|
|
1257
|
+
if (flags & FLAG_UTF8) try {
|
|
1258
|
+
return decodeUtf8Strict(raw);
|
|
1259
|
+
} catch {
|
|
1260
|
+
throw invalid("Entry name is not valid UTF-8.");
|
|
1135
1261
|
}
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1262
|
+
const unicode = findExtra(extra, EXTRA_UNICODE_PATH);
|
|
1263
|
+
if (unicode && unicode.length >= 5 && unicode[0] === 1) {
|
|
1264
|
+
if (new Cursor(unicode, 1).u32() === crc32(raw)) try {
|
|
1265
|
+
return decodeUtf8Strict(unicode.subarray(5));
|
|
1266
|
+
} catch {}
|
|
1139
1267
|
}
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
const
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1268
|
+
let s = "";
|
|
1269
|
+
for (const b of raw) s += b < 128 ? String.fromCharCode(b) : CP437_HIGH[b - 128];
|
|
1270
|
+
return s;
|
|
1271
|
+
}
|
|
1272
|
+
function findExtra(extra, id) {
|
|
1273
|
+
const c = new Cursor(extra, 0);
|
|
1274
|
+
while (c.pos + 4 <= extra.length) {
|
|
1275
|
+
const tag = c.u16();
|
|
1276
|
+
const len = c.u16();
|
|
1277
|
+
if (c.pos + len > extra.length) return void 0;
|
|
1278
|
+
const body = c.take(len);
|
|
1279
|
+
if (tag === id) return body;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
function findEocd(bytes) {
|
|
1283
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1284
|
+
const last = bytes.length - 22;
|
|
1285
|
+
const first = Math.max(0, last - 65535);
|
|
1286
|
+
for (let p = last; p >= first; p--) if (view.getUint32(p, true) === SIG_EOCD) {
|
|
1287
|
+
const commentLength = view.getUint16(p + 20, true);
|
|
1288
|
+
if (p + 22 + commentLength <= bytes.length) return p;
|
|
1289
|
+
}
|
|
1290
|
+
throw invalid("Not a zip file: no end-of-central-directory record.");
|
|
1291
|
+
}
|
|
1292
|
+
/** Bytes of a stored entry checksummed between two abort checks. */
|
|
1293
|
+
const STORED_CRC_STEP = 1048576;
|
|
1294
|
+
/** Parses and validates the archive layout. Does not inflate anything. */
|
|
1295
|
+
function openZip(bytes, options = {}) {
|
|
1296
|
+
const limits = {
|
|
1297
|
+
...DEFAULT_ZIP_LIMITS,
|
|
1298
|
+
...options.limits
|
|
1299
|
+
};
|
|
1300
|
+
const codec = options.codec ?? nativeCodec;
|
|
1301
|
+
if (bytes.length > limits.maxInputBytes) throw limitError("maxInputBytes", bytes.length, limits.maxInputBytes, "Input size");
|
|
1302
|
+
if (bytes.length < 22) throw invalid("Not a zip file: too short.");
|
|
1303
|
+
const eocdPos = findEocd(bytes);
|
|
1304
|
+
const e = new Cursor(bytes, eocdPos + 4);
|
|
1305
|
+
const disk = e.u16();
|
|
1306
|
+
const cdDisk = e.u16();
|
|
1307
|
+
const entriesOnDisk = e.u16();
|
|
1308
|
+
let entryCount = e.u16();
|
|
1309
|
+
let cdSize = e.u32();
|
|
1310
|
+
let cdOffset = e.u32();
|
|
1311
|
+
let cdLimit = eocdPos;
|
|
1312
|
+
if (eocdPos >= 20 && new Cursor(bytes, eocdPos - 20).u32() === SIG_ZIP64_LOCATOR) {
|
|
1313
|
+
const l = new Cursor(bytes, eocdPos - 16);
|
|
1314
|
+
const z64Disk = l.u32();
|
|
1315
|
+
const z64Pos = l.u64();
|
|
1316
|
+
const totalDisks = l.u32();
|
|
1317
|
+
if (z64Disk !== 0 || totalDisks > 1) throw invalid("Multi-disk zip archives are not supported.");
|
|
1318
|
+
if (z64Pos + 56 > eocdPos - 20) throw invalid("Zip64 end-of-central-directory record out of range.");
|
|
1319
|
+
const z = new Cursor(bytes, z64Pos);
|
|
1320
|
+
if (z.u32() !== SIG_ZIP64_EOCD) throw invalid("Bad zip64 end-of-central-directory signature.");
|
|
1321
|
+
z.u64();
|
|
1322
|
+
z.u16();
|
|
1323
|
+
z.u16();
|
|
1324
|
+
const z64ThisDisk = z.u32();
|
|
1325
|
+
const z64CdDisk = z.u32();
|
|
1326
|
+
z.u64();
|
|
1327
|
+
entryCount = z.u64();
|
|
1328
|
+
cdSize = z.u64();
|
|
1329
|
+
cdOffset = z.u64();
|
|
1330
|
+
if (z64ThisDisk !== 0 || z64CdDisk !== 0) throw invalid("Multi-disk zip archives are not supported.");
|
|
1331
|
+
cdLimit = z64Pos;
|
|
1332
|
+
} else {
|
|
1333
|
+
if (disk !== 0 || cdDisk !== 0 || entriesOnDisk !== entryCount) throw invalid("Multi-disk zip archives are not supported.");
|
|
1334
|
+
if (entryCount === 65535 || cdSize === 4294967295 || cdOffset === 4294967295) throw invalid("Zip64 values without a zip64 end-of-central-directory locator.");
|
|
1335
|
+
}
|
|
1336
|
+
if (entryCount > limits.maxEntries) throw limitError("maxEntries", entryCount, limits.maxEntries, "Entry count");
|
|
1337
|
+
if (cdOffset + cdSize > cdLimit) throw invalid("Central directory out of range.");
|
|
1338
|
+
if (entryCount * 46 > cdSize) throw invalid("Central directory too small for its entry count.");
|
|
1339
|
+
const entries = [];
|
|
1340
|
+
const byName = /* @__PURE__ */ new Map();
|
|
1341
|
+
const spans = [];
|
|
1342
|
+
const c = new Cursor(bytes.subarray(0, cdOffset + cdSize), cdOffset);
|
|
1343
|
+
for (let i = 0; i < entryCount; i++) {
|
|
1344
|
+
if (c.u32() !== SIG_CENTRAL) throw invalid("Bad central directory signature.", { index: i });
|
|
1345
|
+
c.u16();
|
|
1346
|
+
c.u16();
|
|
1347
|
+
const flags = c.u16();
|
|
1348
|
+
const method = c.u16();
|
|
1349
|
+
const time = c.u16();
|
|
1350
|
+
const date = c.u16();
|
|
1351
|
+
const crc = c.u32();
|
|
1352
|
+
let compressedSize = c.u32();
|
|
1353
|
+
let size = c.u32();
|
|
1354
|
+
const nameLength = c.u16();
|
|
1355
|
+
const extraLength = c.u16();
|
|
1356
|
+
const commentLength = c.u16();
|
|
1357
|
+
let diskStart = c.u16();
|
|
1358
|
+
c.u16();
|
|
1359
|
+
c.u32();
|
|
1360
|
+
let localOffset = c.u32();
|
|
1361
|
+
const rawName = c.take(nameLength);
|
|
1362
|
+
const extra = c.take(extraLength);
|
|
1363
|
+
c.take(commentLength);
|
|
1364
|
+
const z64 = findExtra(extra, EXTRA_ZIP64);
|
|
1365
|
+
if (z64) {
|
|
1366
|
+
const x = new Cursor(z64, 0);
|
|
1367
|
+
if (size === 4294967295) size = x.u64();
|
|
1368
|
+
if (compressedSize === 4294967295) compressedSize = x.u64();
|
|
1369
|
+
if (localOffset === 4294967295) localOffset = x.u64();
|
|
1370
|
+
if (diskStart === 65535) diskStart = x.u32();
|
|
1371
|
+
}
|
|
1372
|
+
if (diskStart !== 0) throw invalid("Multi-disk zip archives are not supported.");
|
|
1373
|
+
const name = decodeName(rawName, flags, extra);
|
|
1374
|
+
if (flags & 65 || method === METHOD_AES) throw new FormatError("ZIP_ENCRYPTED", `Entry ${excerpt(name)} is encrypted.`, { details: { entry: name } });
|
|
1375
|
+
if (method !== 0 && method !== 8) throw new FormatError("ZIP_UNSUPPORTED_METHOD", `Entry ${excerpt(name)} uses compression method ${method}.`, { details: {
|
|
1376
|
+
entry: name,
|
|
1377
|
+
method
|
|
1378
|
+
} });
|
|
1379
|
+
if (method === 0 && compressedSize !== size) throw invalid(`Stored entry ${excerpt(name)} has mismatched sizes.`);
|
|
1380
|
+
if (byName.has(name)) throw invalid(`Duplicate entry name: ${excerpt(name)}`, { entry: name });
|
|
1381
|
+
const l = new Cursor(bytes, localOffset);
|
|
1382
|
+
if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${excerpt(name)}.`, { entry: name });
|
|
1383
|
+
l.u16();
|
|
1384
|
+
const lFlags = l.u16();
|
|
1385
|
+
const lMethod = l.u16();
|
|
1386
|
+
l.u16();
|
|
1387
|
+
l.u16();
|
|
1388
|
+
const lCrc = l.u32();
|
|
1389
|
+
const lCompressed = l.u32();
|
|
1390
|
+
const lSize = l.u32();
|
|
1391
|
+
const lNameLength = l.u16();
|
|
1392
|
+
const lExtraLength = l.u16();
|
|
1393
|
+
const lName = l.take(lNameLength);
|
|
1394
|
+
l.take(lExtraLength);
|
|
1395
|
+
let agrees = lNameLength === nameLength && lName.every((b, k) => b === rawName[k]) && lMethod === method && (lFlags & FLAG_ENCRYPTED) === 0;
|
|
1396
|
+
if (agrees && !(lFlags & FLAG_DATA_DESCRIPTOR)) agrees = lCrc === crc && (lCompressed === compressedSize || lCompressed === 4294967295) && (lSize === size || lSize === 4294967295);
|
|
1397
|
+
if (!agrees) throw invalid(`Local header disagrees with the central directory for ${excerpt(name)}.`, { entry: name });
|
|
1398
|
+
const dataOffset = l.pos;
|
|
1399
|
+
const dataEnd = dataOffset + compressedSize;
|
|
1400
|
+
if (dataEnd > cdOffset) throw invalid(`Data of ${excerpt(name)} runs into the central directory.`, { entry: name });
|
|
1401
|
+
spans.push({
|
|
1402
|
+
start: localOffset,
|
|
1403
|
+
end: dataEnd,
|
|
1404
|
+
name
|
|
1167
1405
|
});
|
|
1168
|
-
|
|
1406
|
+
const info = Object.freeze({
|
|
1407
|
+
name,
|
|
1408
|
+
method,
|
|
1409
|
+
flags,
|
|
1410
|
+
crc32: crc,
|
|
1411
|
+
compressedSize,
|
|
1412
|
+
size,
|
|
1413
|
+
modified: fromDosDateTime(date, time),
|
|
1414
|
+
dataOffset
|
|
1415
|
+
});
|
|
1416
|
+
entries.push(info);
|
|
1417
|
+
byName.set(name, info);
|
|
1418
|
+
}
|
|
1419
|
+
spans.sort((a, b) => a.start - b.start);
|
|
1420
|
+
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.`);
|
|
1421
|
+
let totalBytesRead = 0;
|
|
1422
|
+
const resolve = (entry) => {
|
|
1423
|
+
const info = typeof entry === "string" ? byName.get(entry) : entry;
|
|
1424
|
+
if (!info || byName.get(info.name) !== info) throw new Error(`No such zip entry: ${typeof entry === "string" ? entry : entry.name}`);
|
|
1425
|
+
return info;
|
|
1426
|
+
};
|
|
1427
|
+
const countTotal = (n) => {
|
|
1428
|
+
totalBytesRead += n;
|
|
1429
|
+
if (totalBytesRead > limits.maxTotalBytes) throw limitError("maxTotalBytes", totalBytesRead, limits.maxTotalBytes, "Total decompressed size");
|
|
1430
|
+
};
|
|
1431
|
+
async function* stream(entry, signal) {
|
|
1432
|
+
const info = resolve(entry);
|
|
1433
|
+
throwIfAborted$1(signal);
|
|
1434
|
+
if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${excerpt(info.name)}`);
|
|
1435
|
+
const data = bytes.subarray(info.dataOffset, info.dataOffset + info.compressedSize);
|
|
1436
|
+
let crc = 0;
|
|
1437
|
+
let produced = 0;
|
|
1438
|
+
if (info.method === 0) {
|
|
1439
|
+
countTotal(data.length);
|
|
1440
|
+
for (let at = 0; at < data.length; at += STORED_CRC_STEP) {
|
|
1441
|
+
if (at > 0) throwIfAborted$1(signal);
|
|
1442
|
+
crc = crc32(data.subarray(at, at + STORED_CRC_STEP), crc);
|
|
1443
|
+
}
|
|
1444
|
+
produced = data.length;
|
|
1445
|
+
if (crc !== info.crc32) throw crcMismatch(info);
|
|
1446
|
+
yield data;
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1449
|
+
const chunks = codec.inflateRaw(data, {
|
|
1450
|
+
maxOutputBytes: limits.maxEntryBytes,
|
|
1451
|
+
maxRatio: limits.maxRatio
|
|
1452
|
+
}, signal);
|
|
1453
|
+
for await (const chunk of chunks) {
|
|
1454
|
+
produced += chunk.length;
|
|
1455
|
+
if (produced > info.size) throw invalid(`Entry ${excerpt(info.name)} is larger than declared.`, { entry: info.name });
|
|
1456
|
+
countTotal(chunk.length);
|
|
1457
|
+
crc = crc32(chunk, crc);
|
|
1458
|
+
yield chunk;
|
|
1459
|
+
}
|
|
1460
|
+
if (produced !== info.size) throw invalid(`Entry ${excerpt(info.name)} is smaller than declared.`, { entry: info.name });
|
|
1461
|
+
if (crc !== info.crc32) throw crcMismatch(info);
|
|
1169
1462
|
}
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1463
|
+
return {
|
|
1464
|
+
entries,
|
|
1465
|
+
get: (name) => byName.get(name),
|
|
1466
|
+
stream,
|
|
1467
|
+
async read(entry, signal) {
|
|
1468
|
+
const parts = [];
|
|
1469
|
+
for await (const chunk of stream(entry, signal)) parts.push(chunk);
|
|
1470
|
+
return concatBytes(parts);
|
|
1471
|
+
},
|
|
1472
|
+
get totalBytesRead() {
|
|
1473
|
+
return totalBytesRead;
|
|
1474
|
+
}
|
|
1475
|
+
};
|
|
1173
1476
|
}
|
|
1174
|
-
|
|
1175
|
-
|
|
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("/");
|
|
1477
|
+
function crcMismatch(info) {
|
|
1478
|
+
return new FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${excerpt(info.name)}.`, { details: { entry: info.name } });
|
|
1190
1479
|
}
|
|
1191
1480
|
// src/internal/read/formula.ts
|
|
1192
1481
|
/**
|
|
@@ -1411,7 +1700,215 @@ function shiftCompiled(c, dRow, dCol, maxLength = 1e400) {
|
|
|
1411
1700
|
shiftWork.shiftedChars += out.length;
|
|
1412
1701
|
return out;
|
|
1413
1702
|
}
|
|
1703
|
+
/** The length of a copy shifted by (dRow, dCol), from formulaShape's `fixed` and partsOf's records; the offset must pass `canShift`. */
|
|
1704
|
+
function shiftedLength(fixed, parts, dRow, dCol) {
|
|
1705
|
+
let n = fixed;
|
|
1706
|
+
for (let i = 0; i < parts.length; i += 3) {
|
|
1707
|
+
const v = parts[i + 1] + (parts[i] ? dRow : dCol);
|
|
1708
|
+
n += parts[i + 2] * (parts[i] ? digitCount(v) : v <= 26 ? 1 : v <= 702 ? 2 : 3);
|
|
1709
|
+
}
|
|
1710
|
+
return n;
|
|
1711
|
+
}
|
|
1712
|
+
function digitCount(v) {
|
|
1713
|
+
let d = 1;
|
|
1714
|
+
while (v >= 10) {
|
|
1715
|
+
v = Math.floor(v / 10);
|
|
1716
|
+
d++;
|
|
1717
|
+
}
|
|
1718
|
+
return d;
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* One pass over a master's text (JSE-71), allocating nothing per reference:
|
|
1722
|
+
* the relative bounds as compileFormula gives them, the range of a copy's
|
|
1723
|
+
* length and the characters that never change (the tests compute both from
|
|
1724
|
+
* the compiled formula too); with `collectParts`, the relative parts. It walks the text as
|
|
1725
|
+
* compileFormula does and recognises references as parseRef does (the tests
|
|
1726
|
+
* compare the two on seeded formulas), so a copy's text is the original's
|
|
1727
|
+
* with each reference re-printed as refText prints it.
|
|
1728
|
+
*/
|
|
1729
|
+
function formulaShape(formula, collectParts) {
|
|
1730
|
+
let rowMin = 1e400;
|
|
1731
|
+
let rowMax = -1e400;
|
|
1732
|
+
let colMin = 1e400;
|
|
1733
|
+
let colMax = -1e400;
|
|
1734
|
+
let fixed = formula.length;
|
|
1735
|
+
let relCols = 0;
|
|
1736
|
+
let relRows = 0;
|
|
1737
|
+
const keys = [];
|
|
1738
|
+
const col = (anchored, v) => {
|
|
1739
|
+
if (anchored) fixed += 1 + (v <= 26 ? 1 : v <= 702 ? 2 : 3);
|
|
1740
|
+
else {
|
|
1741
|
+
relCols++;
|
|
1742
|
+
if (v < colMin) colMin = v;
|
|
1743
|
+
if (v > colMax) colMax = v;
|
|
1744
|
+
if (collectParts) keys.push(v * 2);
|
|
1745
|
+
}
|
|
1746
|
+
};
|
|
1747
|
+
const row = (anchored, v) => {
|
|
1748
|
+
if (anchored) fixed += 1 + digitCount(v);
|
|
1749
|
+
else {
|
|
1750
|
+
relRows++;
|
|
1751
|
+
if (v < rowMin) rowMin = v;
|
|
1752
|
+
if (v > rowMax) rowMax = v;
|
|
1753
|
+
if (collectParts) keys.push(v * 2 + 1);
|
|
1754
|
+
}
|
|
1755
|
+
};
|
|
1756
|
+
const n = formula.length;
|
|
1757
|
+
let i = 0;
|
|
1758
|
+
while (i < n) {
|
|
1759
|
+
const code = formula.charCodeAt(i);
|
|
1760
|
+
if (code === 34 || code === 39) {
|
|
1761
|
+
let j = i + 1;
|
|
1762
|
+
for (; j < n; j++) if (formula.charCodeAt(j) === code) {
|
|
1763
|
+
if (formula.charCodeAt(j + 1) === code) j++;
|
|
1764
|
+
else break;
|
|
1765
|
+
}
|
|
1766
|
+
i = j + 1;
|
|
1767
|
+
continue;
|
|
1768
|
+
}
|
|
1769
|
+
if (code === 91) {
|
|
1770
|
+
let depth = 0;
|
|
1771
|
+
let j = i;
|
|
1772
|
+
for (; j < n; j++) {
|
|
1773
|
+
const c = formula.charCodeAt(j);
|
|
1774
|
+
if (c === 91) depth++;
|
|
1775
|
+
else if (c === 93 && --depth === 0) break;
|
|
1776
|
+
}
|
|
1777
|
+
i = j + 1;
|
|
1778
|
+
continue;
|
|
1779
|
+
}
|
|
1780
|
+
const prev = i > 0 ? formula.charCodeAt(i - 1) : -1;
|
|
1781
|
+
if ((code === 36 || isAlnumCode(code)) && !isWordCode(prev) && prev !== 36) {
|
|
1782
|
+
const end = refAt(formula, i);
|
|
1783
|
+
if (end >= 0) {
|
|
1784
|
+
fixed -= end - i;
|
|
1785
|
+
const r = REF;
|
|
1786
|
+
if (r.kind === COLS_REF) {
|
|
1787
|
+
col(r.aAnchored, r.a);
|
|
1788
|
+
col(r.bAnchored, r.b);
|
|
1789
|
+
fixed += 1;
|
|
1790
|
+
} else if (r.kind === ROWS_REF) {
|
|
1791
|
+
row(r.aAnchored, r.a);
|
|
1792
|
+
row(r.bAnchored, r.b);
|
|
1793
|
+
fixed += 1;
|
|
1794
|
+
} else {
|
|
1795
|
+
col(r.aAnchored, r.a);
|
|
1796
|
+
row(r.bAnchored, r.b);
|
|
1797
|
+
}
|
|
1798
|
+
i = end;
|
|
1799
|
+
continue;
|
|
1800
|
+
}
|
|
1801
|
+
let j = i + 1;
|
|
1802
|
+
while (j < n && isWordCode(formula.charCodeAt(j))) j++;
|
|
1803
|
+
i = j;
|
|
1804
|
+
continue;
|
|
1805
|
+
}
|
|
1806
|
+
i++;
|
|
1807
|
+
}
|
|
1808
|
+
return {
|
|
1809
|
+
rowMin,
|
|
1810
|
+
rowMax,
|
|
1811
|
+
colMin,
|
|
1812
|
+
colMax,
|
|
1813
|
+
min: fixed + relCols + relRows,
|
|
1814
|
+
max: fixed + 3 * relCols + 7 * relRows,
|
|
1815
|
+
fixed,
|
|
1816
|
+
keys
|
|
1817
|
+
};
|
|
1818
|
+
}
|
|
1819
|
+
/** refAt's result, reused (formulaShape reads it before the next call). */
|
|
1820
|
+
const REF = {
|
|
1821
|
+
kind: CELL_REF,
|
|
1822
|
+
aAnchored: false,
|
|
1823
|
+
a: 0,
|
|
1824
|
+
bAnchored: false,
|
|
1825
|
+
b: 0
|
|
1826
|
+
};
|
|
1827
|
+
/** parseRef without allocating: the reference at `i` into REF and the index after it, or -1. */
|
|
1828
|
+
function refAt(f, i) {
|
|
1829
|
+
const n = f.length;
|
|
1830
|
+
const aAnchored = f.charCodeAt(i) === 36;
|
|
1831
|
+
const p = i + (aAnchored ? 1 : 0);
|
|
1832
|
+
let la = 0;
|
|
1833
|
+
while (la < 3 && p + la < n && isLetterCode(f.charCodeAt(p + la))) la++;
|
|
1834
|
+
let da = 0;
|
|
1835
|
+
if (la === 0) while (da < 7 && p + da < n && isDigitCode(f.charCodeAt(p + da))) da++;
|
|
1836
|
+
const first = la || da;
|
|
1837
|
+
if (first > 0 && f.charCodeAt(p + first) === 58) {
|
|
1838
|
+
const q = p + first + 1;
|
|
1839
|
+
const bAnchored = q < n && f.charCodeAt(q) === 36;
|
|
1840
|
+
const r = q + (bAnchored ? 1 : 0);
|
|
1841
|
+
let second = 0;
|
|
1842
|
+
if (la) while (second < 3 && r + second < n && isLetterCode(f.charCodeAt(r + second))) second++;
|
|
1843
|
+
else while (second < 7 && r + second < n && isDigitCode(f.charCodeAt(r + second))) second++;
|
|
1844
|
+
if (second > 0 && isEnd(f, r + second)) {
|
|
1845
|
+
if (la) {
|
|
1846
|
+
const a = colAt(f, p, la);
|
|
1847
|
+
const b = colAt(f, r, second);
|
|
1848
|
+
if (a > MAX_COL || b > MAX_COL) return -1;
|
|
1849
|
+
return setRef(COLS_REF, aAnchored, a, bAnchored, b, r + second);
|
|
1850
|
+
}
|
|
1851
|
+
return setRef(ROWS_REF, aAnchored, digitsAt(f, p, da), bAnchored, digitsAt(f, r, second), r + second);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
if (la > 0) {
|
|
1855
|
+
const q = p + la;
|
|
1856
|
+
const bAnchored = f.charCodeAt(q) === 36;
|
|
1857
|
+
const r = q + (bAnchored ? 1 : 0);
|
|
1858
|
+
let digits = 0;
|
|
1859
|
+
while (digits < 7 && r + digits < n && isDigitCode(f.charCodeAt(r + digits))) digits++;
|
|
1860
|
+
if (digits > 0 && isEnd(f, r + digits)) {
|
|
1861
|
+
const c = colAt(f, p, la);
|
|
1862
|
+
if (c > MAX_COL) return -1;
|
|
1863
|
+
return setRef(CELL_REF, aAnchored, c, bAnchored, digitsAt(f, r, digits), r + digits);
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
return -1;
|
|
1867
|
+
}
|
|
1868
|
+
function setRef(kind, aAnchored, a, bAnchored, b, end) {
|
|
1869
|
+
REF.kind = kind;
|
|
1870
|
+
REF.aAnchored = aAnchored;
|
|
1871
|
+
REF.a = a;
|
|
1872
|
+
REF.bAnchored = bAnchored;
|
|
1873
|
+
REF.b = b;
|
|
1874
|
+
return end;
|
|
1875
|
+
}
|
|
1876
|
+
/** formulaShape's keys as records: triples (isRow, value, count), one per distinct relative part. */
|
|
1877
|
+
/** partsOf's sort buffer, reused so that sorting allocates nothing. */
|
|
1878
|
+
let sortScratch = /* @__PURE__ */ new Int32Array(256);
|
|
1879
|
+
function partsOf(list) {
|
|
1880
|
+
if (sortScratch.length < list.length) sortScratch = new Int32Array(Math.max(list.length, 2 * sortScratch.length));
|
|
1881
|
+
const keys = sortScratch.subarray(0, list.length);
|
|
1882
|
+
keys.set(list);
|
|
1883
|
+
keys.sort();
|
|
1884
|
+
let distinct = 0;
|
|
1885
|
+
for (let i = 0; i < keys.length; i++) if (i === 0 || keys[i] !== keys[i - 1]) distinct++;
|
|
1886
|
+
const out = new Array(distinct * 3).fill(0);
|
|
1887
|
+
let o = -3;
|
|
1888
|
+
for (let i = 0; i < keys.length; i++) {
|
|
1889
|
+
const k = keys[i];
|
|
1890
|
+
if (i === 0 || k !== keys[i - 1]) {
|
|
1891
|
+
o += 3;
|
|
1892
|
+
out[o] = k & 1;
|
|
1893
|
+
out[o + 1] = Math.floor(k / 2);
|
|
1894
|
+
}
|
|
1895
|
+
out[o + 2] = out[o + 2] + 1;
|
|
1896
|
+
}
|
|
1897
|
+
return out;
|
|
1898
|
+
}
|
|
1414
1899
|
/** Whether a reference may end before `end`: no word character, `(`, `!` or `$` follows. */
|
|
1900
|
+
/** colNumber(f.slice(at, at + n)) without the slice; `n` ASCII letters. */
|
|
1901
|
+
function colAt(f, at, n) {
|
|
1902
|
+
let v = 0;
|
|
1903
|
+
for (let k = 0; k < n; k++) v = v * 26 + ((f.charCodeAt(at + k) & -33) - 64);
|
|
1904
|
+
return v;
|
|
1905
|
+
}
|
|
1906
|
+
/** Number(f.slice(at, at + n)) without the slice; `n` (at most 7) ASCII digits. */
|
|
1907
|
+
function digitsAt(f, at, n) {
|
|
1908
|
+
let v = 0;
|
|
1909
|
+
for (let k = 0; k < n; k++) v = v * 10 + (f.charCodeAt(at + k) - 48);
|
|
1910
|
+
return v;
|
|
1911
|
+
}
|
|
1415
1912
|
function isEnd(f, end) {
|
|
1416
1913
|
if (end >= f.length) return true;
|
|
1417
1914
|
const c = f.charCodeAt(end);
|
|
@@ -2160,7 +2657,10 @@ var SharedStringsParser = class {
|
|
|
2160
2657
|
stopAfter;
|
|
2161
2658
|
charge;
|
|
2162
2659
|
maxText;
|
|
2660
|
+
keep;
|
|
2163
2661
|
strings = [];
|
|
2662
|
+
/** Items decoded so far; with `keep` false, the only record of them (inspect, JSE-71). */
|
|
2663
|
+
count = 0;
|
|
2164
2664
|
item;
|
|
2165
2665
|
depth = 0;
|
|
2166
2666
|
control;
|
|
@@ -2168,12 +2668,13 @@ var SharedStringsParser = class {
|
|
|
2168
2668
|
* `stopAfter`: decode only the first `stopAfter` items, then jump to the
|
|
2169
2669
|
* end of the part without tokenizing the rest (previews, ReadOptions.maxRows).
|
|
2170
2670
|
*/
|
|
2171
|
-
constructor(mode, max, stopAfter = 1e400, charge = () => {}, maxText = 1e400) {
|
|
2671
|
+
constructor(mode, max, stopAfter = 1e400, charge = () => {}, maxText = 1e400, keep = true) {
|
|
2172
2672
|
this.mode = mode;
|
|
2173
2673
|
this.max = max;
|
|
2174
2674
|
this.stopAfter = stopAfter;
|
|
2175
2675
|
this.charge = charge;
|
|
2176
2676
|
this.maxText = maxText;
|
|
2677
|
+
this.keep = keep;
|
|
2177
2678
|
}
|
|
2178
2679
|
attach(control) {
|
|
2179
2680
|
this.control = control;
|
|
@@ -2181,8 +2682,10 @@ var SharedStringsParser = class {
|
|
|
2181
2682
|
}
|
|
2182
2683
|
/** True once stopAfter items were decoded and the rest of the part is skipped. */
|
|
2183
2684
|
stopped = false;
|
|
2184
|
-
|
|
2185
|
-
if (this.
|
|
2685
|
+
push(item) {
|
|
2686
|
+
if (this.keep) this.strings.push(item);
|
|
2687
|
+
this.count++;
|
|
2688
|
+
if (this.count >= this.stopAfter && !this.stopped && this.control) {
|
|
2186
2689
|
this.stopped = true;
|
|
2187
2690
|
this.control.skipToEndOf(1);
|
|
2188
2691
|
}
|
|
@@ -2199,15 +2702,13 @@ var SharedStringsParser = class {
|
|
|
2199
2702
|
return;
|
|
2200
2703
|
}
|
|
2201
2704
|
if (name === "si") {
|
|
2202
|
-
if (this.
|
|
2705
|
+
if (this.count >= this.max) throw new LimitError("LIMIT_EXCEEDED", `More than maxSharedStrings (${this.max}) shared strings.`, { details: {
|
|
2203
2706
|
limit: "maxSharedStrings",
|
|
2204
|
-
value: this.
|
|
2707
|
+
value: this.count + 1,
|
|
2205
2708
|
max: this.max
|
|
2206
2709
|
} });
|
|
2207
|
-
if (empty)
|
|
2208
|
-
|
|
2209
|
-
this.pushed();
|
|
2210
|
-
} else {
|
|
2710
|
+
if (empty) this.push("");
|
|
2711
|
+
else {
|
|
2211
2712
|
this.item = new StringItem(this.charge, this.maxText);
|
|
2212
2713
|
this.depth = 0;
|
|
2213
2714
|
}
|
|
@@ -2216,9 +2717,9 @@ var SharedStringsParser = class {
|
|
|
2216
2717
|
close(name) {
|
|
2217
2718
|
if (!this.item) return;
|
|
2218
2719
|
if (this.depth === 0 && name === "si") {
|
|
2219
|
-
this.
|
|
2720
|
+
const value = this.item.value(this.mode);
|
|
2220
2721
|
this.item = void 0;
|
|
2221
|
-
this.
|
|
2722
|
+
this.push(value);
|
|
2222
2723
|
return;
|
|
2223
2724
|
}
|
|
2224
2725
|
this.depth--;
|
|
@@ -2286,6 +2787,34 @@ var DeferredStrings = class {
|
|
|
2286
2787
|
}
|
|
2287
2788
|
}
|
|
2288
2789
|
};
|
|
2790
|
+
/** Bytes (UTF-8) of shared-formula masters a sheet keeps, at most, until a copy needs them (inspect, JSE-71). */
|
|
2791
|
+
const PENDING_TEXT = 8388608;
|
|
2792
|
+
/**
|
|
2793
|
+
* A shared formula's master as inspect keeps it (keepCells false, JSE-71):
|
|
2794
|
+
* numbers only, in one small object; the bounds are canShift's.
|
|
2795
|
+
*/
|
|
2796
|
+
const UTF8 = new globalThis.TextEncoder();
|
|
2797
|
+
const UTF8_TEXT = new globalThis.TextDecoder();
|
|
2798
|
+
var LeanMaster = class {
|
|
2799
|
+
row;
|
|
2800
|
+
col;
|
|
2801
|
+
length;
|
|
2802
|
+
rowMin = 1e400;
|
|
2803
|
+
rowMax = -1e400;
|
|
2804
|
+
colMin = 1e400;
|
|
2805
|
+
colMax = -1e400;
|
|
2806
|
+
/** Whether every copy fits maxCellTextLength; `parts`, when set, decides per copy instead. */
|
|
2807
|
+
fits = false;
|
|
2808
|
+
fixed = 0;
|
|
2809
|
+
parts = void 0;
|
|
2810
|
+
/** The master's text, as UTF-8, until it is shaped (setLean); then undefined. */
|
|
2811
|
+
text = void 0;
|
|
2812
|
+
constructor(row, col, length) {
|
|
2813
|
+
this.row = row;
|
|
2814
|
+
this.col = col;
|
|
2815
|
+
this.length = length;
|
|
2816
|
+
}
|
|
2817
|
+
};
|
|
2289
2818
|
/** Maximum digit width of Calibri 11 in pixels; the writer uses the same value (internal/write/sheet-features.ts). */
|
|
2290
2819
|
const MAX_DIGIT_WIDTH = 7;
|
|
2291
2820
|
/**
|
|
@@ -2393,6 +2922,20 @@ var SheetParser = class {
|
|
|
2393
2922
|
maxCol = -1;
|
|
2394
2923
|
truncated = false;
|
|
2395
2924
|
control;
|
|
2925
|
+
/** opts.keepCells (default true). */
|
|
2926
|
+
keep;
|
|
2927
|
+
/** Cells kept (or, without keepCells, that would have been), as maxCells counts them. */
|
|
2928
|
+
cellCount = 0;
|
|
2929
|
+
/** Without keepCells: the shared-formula masters by si, their reference records, and the masters whose text is pending (setLean). */
|
|
2930
|
+
lean = /* @__PURE__ */ new Map();
|
|
2931
|
+
leanRecords = 0;
|
|
2932
|
+
pending = [];
|
|
2933
|
+
pendingHead = 0;
|
|
2934
|
+
/** Masters in `pending` that still wait (have text); the others are dropped by compactPending. */
|
|
2935
|
+
pendingLive = 0;
|
|
2936
|
+
pendingText = 0;
|
|
2937
|
+
/** Without keepCells: the rows that had properties, one bit per row (for counting each once, as `rowProps` does). */
|
|
2938
|
+
rowPropSeen;
|
|
2396
2939
|
constructor(name, state, ctx, styles, opts, part) {
|
|
2397
2940
|
this.ctx = ctx;
|
|
2398
2941
|
this.styles = styles;
|
|
@@ -2403,6 +2946,7 @@ var SheetParser = class {
|
|
|
2403
2946
|
rows: this.rows
|
|
2404
2947
|
};
|
|
2405
2948
|
if (state && state !== "visible") this.sheet.state = state;
|
|
2949
|
+
this.keep = opts.keepCells !== false;
|
|
2406
2950
|
}
|
|
2407
2951
|
attach(control) {
|
|
2408
2952
|
this.control = control;
|
|
@@ -2448,7 +2992,7 @@ var SheetParser = class {
|
|
|
2448
2992
|
const ref = a.get("ref");
|
|
2449
2993
|
if (ref) {
|
|
2450
2994
|
this.ctx.charge(1);
|
|
2451
|
-
this.merges.push(cleanRange(ref));
|
|
2995
|
+
if (this.keep) this.merges.push(cleanRange(ref));
|
|
2452
2996
|
}
|
|
2453
2997
|
return;
|
|
2454
2998
|
}
|
|
@@ -2456,7 +3000,7 @@ var SheetParser = class {
|
|
|
2456
3000
|
if (parent === "hyperlinks") {
|
|
2457
3001
|
const ref = a.get("ref");
|
|
2458
3002
|
if (ref) this.ctx.charge(1);
|
|
2459
|
-
if (ref) this.hyperlinks.push({
|
|
3003
|
+
if (ref && (this.keep || this.mayBeTooWide(ref))) this.hyperlinks.push({
|
|
2460
3004
|
ref: cleanRange(ref),
|
|
2461
3005
|
relId: a.getPrefixed("id"),
|
|
2462
3006
|
location: a.get("location"),
|
|
@@ -2473,7 +3017,7 @@ var SheetParser = class {
|
|
|
2473
3017
|
case "selection":
|
|
2474
3018
|
if (parent === "sheetView" && this.viewCount === 1) {
|
|
2475
3019
|
this.ctx.charge(1);
|
|
2476
|
-
this.selections.push({
|
|
3020
|
+
if (this.keep) this.selections.push({
|
|
2477
3021
|
pane: a.get("pane"),
|
|
2478
3022
|
activeCell: a.get("activeCell"),
|
|
2479
3023
|
sqref: a.get("sqref")
|
|
@@ -2634,6 +3178,13 @@ var SheetParser = class {
|
|
|
2634
3178
|
if (st) p.style = st;
|
|
2635
3179
|
}
|
|
2636
3180
|
if (Object.keys(p).length) {
|
|
3181
|
+
if (!this.keep) {
|
|
3182
|
+
const seen = this.rowPropSeen ??= /* @__PURE__ */ new Uint8Array(131072);
|
|
3183
|
+
const bit = 1 << (this.curRow & 7);
|
|
3184
|
+
if (!(seen[this.curRow >> 3] & bit)) this.ctx.charge(1);
|
|
3185
|
+
seen[this.curRow >> 3] |= bit;
|
|
3186
|
+
return;
|
|
3187
|
+
}
|
|
2637
3188
|
if (this.rowProps[this.curRow] === void 0) this.ctx.charge(1);
|
|
2638
3189
|
this.rowProps[this.curRow] = p;
|
|
2639
3190
|
}
|
|
@@ -2798,6 +3349,12 @@ var SheetParser = class {
|
|
|
2798
3349
|
if (!cell) return;
|
|
2799
3350
|
if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref);
|
|
2800
3351
|
this.ctx.countCell();
|
|
3352
|
+
this.cellCount++;
|
|
3353
|
+
if (!this.keep) {
|
|
3354
|
+
this.pendingIndex = -1;
|
|
3355
|
+
this.extend(p.row, p.col);
|
|
3356
|
+
return;
|
|
3357
|
+
}
|
|
2801
3358
|
let row = this.rows[p.row];
|
|
2802
3359
|
if (!row) row = this.rows[p.row] = [];
|
|
2803
3360
|
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 +3375,19 @@ var SheetParser = class {
|
|
|
2818
3375
|
if (this.pendingIndex > d.maxIndex) d.maxIndex = this.pendingIndex;
|
|
2819
3376
|
this.pendingIndex = -1;
|
|
2820
3377
|
}
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
3378
|
+
this.extend(p.row, p.col);
|
|
3379
|
+
}
|
|
3380
|
+
/** Widens the sheet's dimension to a kept cell. */
|
|
3381
|
+
extend(row, col) {
|
|
3382
|
+
if (row < this.minRow) this.minRow = row;
|
|
3383
|
+
if (row > this.maxRow) this.maxRow = row;
|
|
3384
|
+
if (col < this.minCol) this.minCol = col;
|
|
3385
|
+
if (col > this.maxCol) this.maxCol = col;
|
|
3386
|
+
}
|
|
3387
|
+
/** Without keepCells: whether a hyperlink on `ref` could fail maxColumns when the sheet is finished (attachHyperlink). */
|
|
3388
|
+
mayBeTooWide(ref) {
|
|
3389
|
+
const pos = parseRef(cleanRange(ref).split(":")[0]);
|
|
3390
|
+
return pos !== void 0 && pos[1] >= this.ctx.limits.maxColumns;
|
|
2825
3391
|
}
|
|
2826
3392
|
/**
|
|
2827
3393
|
* A kept cell in a column past maxColumns (JSE-68). Counted on the cells the
|
|
@@ -2856,7 +3422,8 @@ var SheetParser = class {
|
|
|
2856
3422
|
break;
|
|
2857
3423
|
}
|
|
2858
3424
|
const sst = this.sharedStrings;
|
|
2859
|
-
const
|
|
3425
|
+
const count = this.sharedStringCount;
|
|
3426
|
+
const str = Number.isInteger(idx) && idx >= 0 ? count === void 0 ? sst[idx] : idx < count ? "" : void 0 : void 0;
|
|
2860
3427
|
if (str === void 0) {
|
|
2861
3428
|
if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref);
|
|
2862
3429
|
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 +3525,7 @@ var SheetParser = class {
|
|
|
2958
3525
|
formula(p) {
|
|
2959
3526
|
if (p.f === void 0 || !this.opts.formulas) return void 0;
|
|
2960
3527
|
if (p.fType === "shared" && p.fSi !== void 0) {
|
|
3528
|
+
if (!this.keep) return this.leanFormula(p);
|
|
2961
3529
|
if (p.f !== "") {
|
|
2962
3530
|
this.shared.set(p.fSi, {
|
|
2963
3531
|
formula: p.f,
|
|
@@ -2998,6 +3566,131 @@ var SheetParser = class {
|
|
|
2998
3566
|
};
|
|
2999
3567
|
return { text: p.f };
|
|
3000
3568
|
}
|
|
3569
|
+
/**
|
|
3570
|
+
* keepCells false (JSE-71): a shared formula decided as formula() decides
|
|
3571
|
+
* it, in the same order, from a LeanMaster instead of the master's text.
|
|
3572
|
+
* Only whether the cell has a formula matters here, so a resolved one
|
|
3573
|
+
* returns an empty text.
|
|
3574
|
+
*/
|
|
3575
|
+
leanFormula(p) {
|
|
3576
|
+
const si = p.fSi;
|
|
3577
|
+
if (p.f !== "") {
|
|
3578
|
+
this.setLean(si, p);
|
|
3579
|
+
return { text: "" };
|
|
3580
|
+
}
|
|
3581
|
+
const m = this.lean.get(si);
|
|
3582
|
+
if (m && m.length > 8192) {
|
|
3583
|
+
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}`);
|
|
3584
|
+
return;
|
|
3585
|
+
}
|
|
3586
|
+
if (!m) {
|
|
3587
|
+
this.unresolved(p, "");
|
|
3588
|
+
return;
|
|
3589
|
+
}
|
|
3590
|
+
const dRow = p.row - m.row;
|
|
3591
|
+
const dCol = p.col - m.col;
|
|
3592
|
+
if (dRow === 0 && dCol === 0) return { text: "" };
|
|
3593
|
+
if (m.text !== void 0) this.shape(m, p);
|
|
3594
|
+
if (!canShift(m, dRow, dCol)) {
|
|
3595
|
+
this.unresolved(p, "");
|
|
3596
|
+
return;
|
|
3597
|
+
}
|
|
3598
|
+
const max = this.ctx.limits.maxCellTextLength;
|
|
3599
|
+
if (m.parts ? shiftedLength(m.fixed, m.parts, dRow, dCol) <= max : m.fits) return { text: "" };
|
|
3600
|
+
this.unresolved(p, `: shifted, it would have more than maxCellTextLength (${max}) characters`);
|
|
3601
|
+
}
|
|
3602
|
+
/**
|
|
3603
|
+
* Keeps a master as a LeanMaster. Its text is kept only until a copy needs
|
|
3604
|
+
* it (as read compiles a master only then), and only while the text pending
|
|
3605
|
+
* on this sheet is at most PENDING_TEXT characters; past that, the oldest
|
|
3606
|
+
* pending masters are shaped and their text dropped. Shaping (formula.ts
|
|
3607
|
+
* formulaShape) keeps numbers only: the bounds, and whether copies fit
|
|
3608
|
+
* maxCellTextLength from the range of lengths a copy can have, or, when the
|
|
3609
|
+
* limit falls inside that range, records of the relative parts (partsOf).
|
|
3610
|
+
* Every live master (one per si: a redefinition replaces it, its pending
|
|
3611
|
+
* text and its records) and every record counts against maxItems (budget()).
|
|
3612
|
+
*/
|
|
3613
|
+
setLean(si, p) {
|
|
3614
|
+
const f = p.f;
|
|
3615
|
+
const old = this.lean.get(si);
|
|
3616
|
+
if (old) this.release(old);
|
|
3617
|
+
const m = new LeanMaster(p.row, p.col, f.length);
|
|
3618
|
+
this.lean.set(si, m);
|
|
3619
|
+
if (f.length <= 8192) {
|
|
3620
|
+
m.text = f.length > 12 ? UTF8.encode(f) : (" " + f).slice(1);
|
|
3621
|
+
this.pendingText += m.text.length;
|
|
3622
|
+
this.pending.push(m);
|
|
3623
|
+
this.pendingLive++;
|
|
3624
|
+
while (this.pendingText > PENDING_TEXT) {
|
|
3625
|
+
const next = this.pending[this.pendingHead++];
|
|
3626
|
+
if (next.text !== void 0) this.shape(next, p);
|
|
3627
|
+
}
|
|
3628
|
+
this.compactPending();
|
|
3629
|
+
}
|
|
3630
|
+
this.budget(p);
|
|
3631
|
+
}
|
|
3632
|
+
/** A master's numbers from its text, which is then dropped (setLean). */
|
|
3633
|
+
shape(m, p) {
|
|
3634
|
+
const bytes = m.text;
|
|
3635
|
+
m.text = void 0;
|
|
3636
|
+
this.pendingText -= bytes.length;
|
|
3637
|
+
this.pendingLive--;
|
|
3638
|
+
const f = typeof bytes === "string" ? bytes : UTF8_TEXT.decode(bytes);
|
|
3639
|
+
const limit = this.ctx.limits.maxCellTextLength;
|
|
3640
|
+
const shape = formulaShape(f, 7 * f.length > limit);
|
|
3641
|
+
if (shape.min <= limit && shape.max > limit) {
|
|
3642
|
+
m.parts = partsOf(shape.keys);
|
|
3643
|
+
this.leanRecords += m.parts.length / 3;
|
|
3644
|
+
}
|
|
3645
|
+
m.rowMin = shape.rowMin;
|
|
3646
|
+
m.rowMax = shape.rowMax;
|
|
3647
|
+
m.colMin = shape.colMin;
|
|
3648
|
+
m.colMax = shape.colMax;
|
|
3649
|
+
m.fixed = shape.fixed;
|
|
3650
|
+
m.fits = shape.max <= limit;
|
|
3651
|
+
if (m.parts) this.budget(p);
|
|
3652
|
+
}
|
|
3653
|
+
/** A replaced master: its pending text and its records no longer count. */
|
|
3654
|
+
release(m) {
|
|
3655
|
+
if (m.text !== void 0) {
|
|
3656
|
+
this.pendingText -= m.text.length;
|
|
3657
|
+
this.pendingLive--;
|
|
3658
|
+
m.text = void 0;
|
|
3659
|
+
}
|
|
3660
|
+
if (m.parts) this.leanRecords -= m.parts.length / 3;
|
|
3661
|
+
m.parts = void 0;
|
|
3662
|
+
}
|
|
3663
|
+
/**
|
|
3664
|
+
* Drops the masters that no longer wait (shaped, or replaced by a
|
|
3665
|
+
* redefinition) from `pending` once they outnumber the waiting ones, so a
|
|
3666
|
+
* replaced master is unreachable and nothing is kept per redefinition.
|
|
3667
|
+
* Amortised constant time per master.
|
|
3668
|
+
*/
|
|
3669
|
+
compactPending() {
|
|
3670
|
+
if (this.pending.length - this.pendingHead <= 2 * this.pendingLive + 64) return;
|
|
3671
|
+
const live = [];
|
|
3672
|
+
for (let i = this.pendingHead; i < this.pending.length; i++) if (this.pending[i].text !== void 0) live.push(this.pending[i]);
|
|
3673
|
+
this.pending = live;
|
|
3674
|
+
this.pendingHead = 0;
|
|
3675
|
+
}
|
|
3676
|
+
/**
|
|
3677
|
+
* inspect's own budget, the one documented exception to "the same error as
|
|
3678
|
+
* read" (docs/api.md §5.2.1): live masters and reference records, with the
|
|
3679
|
+
* items the read built besides cells, may not pass maxItems.
|
|
3680
|
+
*/
|
|
3681
|
+
budget(p) {
|
|
3682
|
+
const most = this.ctx.limits.maxItems;
|
|
3683
|
+
if (this.ctx.items + this.lean.size + this.leanRecords <= most) return;
|
|
3684
|
+
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: {
|
|
3685
|
+
limit: "maxItems",
|
|
3686
|
+
value: most + 1,
|
|
3687
|
+
max: most,
|
|
3688
|
+
part: this.part,
|
|
3689
|
+
ref: p.ref,
|
|
3690
|
+
sharedFormulaMasters: this.lean.size,
|
|
3691
|
+
sharedFormulaReferences: this.leanRecords
|
|
3692
|
+
} });
|
|
3693
|
+
}
|
|
3001
3694
|
unresolved(p, why) {
|
|
3002
3695
|
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
3696
|
part: this.part,
|
|
@@ -3007,6 +3700,8 @@ var SheetParser = class {
|
|
|
3007
3700
|
}
|
|
3008
3701
|
/** Set before parsing; the shared strings table. */
|
|
3009
3702
|
sharedStrings = [];
|
|
3703
|
+
/** Set instead of `sharedStrings` when they were counted, not kept (inspect, JSE-71). */
|
|
3704
|
+
sharedStringCount;
|
|
3010
3705
|
/** When set, shared-string cells are collected here and filled in later (ReadOptions.maxRows). */
|
|
3011
3706
|
deferred;
|
|
3012
3707
|
openView(a) {
|
|
@@ -3123,46 +3818,428 @@ var SheetParser = class {
|
|
|
3123
3818
|
this.attachHyperlink(this.hyperlinks[i], byId);
|
|
3124
3819
|
}
|
|
3125
3820
|
}
|
|
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
|
|
3821
|
+
if (this.maxRow >= 0) {
|
|
3822
|
+
const tl = `${colLetters(this.minCol + 1)}${this.minRow + 1}`;
|
|
3823
|
+
const br = `${colLetters(this.maxCol + 1)}${this.maxRow + 1}`;
|
|
3824
|
+
sheet.dimension = tl === br ? tl : `${tl}:${br}`;
|
|
3825
|
+
}
|
|
3826
|
+
return sheet;
|
|
3827
|
+
}
|
|
3828
|
+
attachHyperlink(h, rels) {
|
|
3829
|
+
const first = h.ref.split(":")[0];
|
|
3830
|
+
const pos = parseRef(first);
|
|
3831
|
+
if (!pos) return;
|
|
3832
|
+
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)}.`, {
|
|
3833
|
+
part: this.part,
|
|
3834
|
+
sheet: this.sheet.name,
|
|
3835
|
+
ref: h.ref
|
|
3836
|
+
});
|
|
3837
|
+
let link;
|
|
3838
|
+
if (h.relId) {
|
|
3839
|
+
const rel = rels.get(h.relId);
|
|
3840
|
+
if (rel) {
|
|
3841
|
+
const target = h.location ? `${rel.target}#${h.location}` : rel.target;
|
|
3842
|
+
link = h.tooltip !== void 0 ? {
|
|
3843
|
+
target,
|
|
3844
|
+
tooltip: h.tooltip
|
|
3845
|
+
} : { target };
|
|
3846
|
+
}
|
|
3847
|
+
} else if (h.location !== void 0) link = h.tooltip !== void 0 ? {
|
|
3848
|
+
location: h.location,
|
|
3849
|
+
tooltip: h.tooltip
|
|
3850
|
+
} : { location: h.location };
|
|
3851
|
+
if (!link) return;
|
|
3852
|
+
const [r, c] = pos;
|
|
3853
|
+
if (r >= 1048576 || c >= 16384) return;
|
|
3854
|
+
if (c >= this.ctx.limits.maxColumns) this.tooWide(c, `${colLetters(c + 1)}${r + 1}`);
|
|
3855
|
+
if (!this.keep) return;
|
|
3856
|
+
let row = this.rows[r];
|
|
3857
|
+
if (!row) row = this.rows[r] = [];
|
|
3858
|
+
const cell = row[c] ?? (row[c] = { type: "empty" });
|
|
3859
|
+
cell.hyperlink = link;
|
|
3860
|
+
}
|
|
3861
|
+
};
|
|
3862
|
+
// src/internal/read/scan.ts
|
|
3863
|
+
/**
|
|
3864
|
+
* The package scan (JSE-72): walks the whole relationship graph from the
|
|
3865
|
+
* package root and classifies every part the model does not represent, and
|
|
3866
|
+
* lists the parts no relationship reaches. `read` uses it; it is kept in one
|
|
3867
|
+
* function so that other entry points can reuse it. Internal.
|
|
3868
|
+
*/
|
|
3869
|
+
/**
|
|
3870
|
+
* Relationship kinds (the type URI's last segment) of parts the model does not
|
|
3871
|
+
* represent, with the words the UNSUPPORTED_PART message uses for them.
|
|
3872
|
+
*/
|
|
3873
|
+
const UNSUPPORTED_RELATIONSHIPS = /* @__PURE__ */ new Map([
|
|
3874
|
+
["drawing", "drawings (charts, images, shapes)"],
|
|
3875
|
+
["vmlDrawing", "legacy drawings (VML)"],
|
|
3876
|
+
["comments", "comments"],
|
|
3877
|
+
["threadedComment", "threaded comments"],
|
|
3878
|
+
["pivotTable", "pivot tables"],
|
|
3879
|
+
["pivotCacheDefinition", "pivot caches"],
|
|
3880
|
+
["table", "tables (ListObjects)"],
|
|
3881
|
+
["oleObject", "embedded OLE objects"],
|
|
3882
|
+
["ctrlProp", "form controls"],
|
|
3883
|
+
["image", "images"],
|
|
3884
|
+
["vbaProject", "VBA macros"],
|
|
3885
|
+
["externalLink", "external links"],
|
|
3886
|
+
["connections", "data connections"],
|
|
3887
|
+
["queryTable", "query tables"],
|
|
3888
|
+
["slicer", "slicers"],
|
|
3889
|
+
["slicerCache", "slicer caches"],
|
|
3890
|
+
["timeline", "timelines"],
|
|
3891
|
+
["chartsheet", "chart sheets"],
|
|
3892
|
+
["dialogsheet", "dialog sheets"],
|
|
3893
|
+
["macrosheet", "macro sheets"]
|
|
3894
|
+
]);
|
|
3895
|
+
/** Words for the kinds the scan adds (since 2.5). `unreferencedPart` has its own message. */
|
|
3896
|
+
const SCANNED_KINDS = /* @__PURE__ */ new Map([
|
|
3897
|
+
["activeX", "ActiveX controls"],
|
|
3898
|
+
["embeddedPackage", "embedded packages (files such as documents embedded in the workbook)"],
|
|
3899
|
+
["customUI", "custom ribbon UI (customUI)"],
|
|
3900
|
+
["webExtension", "Office web add-ins"]
|
|
3901
|
+
]);
|
|
3902
|
+
/**
|
|
3903
|
+
* Relationship kinds, lower case (relationship types compare
|
|
3904
|
+
* case-insensitively), that name a kind other than their own last segment.
|
|
3905
|
+
*/
|
|
3906
|
+
const RELATIONSHIP_ALIASES = /* @__PURE__ */ new Map([
|
|
3907
|
+
["control", "activeX"],
|
|
3908
|
+
["activexcontrolbinary", "activeX"],
|
|
3909
|
+
["package", "embeddedPackage"],
|
|
3910
|
+
["xlmacrosheet", "macrosheet"],
|
|
3911
|
+
["xlintlmacrosheet", "macrosheet"],
|
|
3912
|
+
["webextensiontaskpanes", "webExtension"],
|
|
3913
|
+
["webextension", "webExtension"],
|
|
3914
|
+
["attachedtoolbars", "vbaProject"],
|
|
3915
|
+
["vbaprojectsignature", "vbaProject"],
|
|
3916
|
+
["vbaprojectsignatureagile", "vbaProject"],
|
|
3917
|
+
["vbaprojectsignaturev3", "vbaProject"],
|
|
3918
|
+
["wordvbadata", "vbaProject"]
|
|
3919
|
+
]);
|
|
3920
|
+
/** UNSUPPORTED_RELATIONSHIPS keyed by lower-case kind. */
|
|
3921
|
+
const RELATIONSHIP_KINDS = new Map([...UNSUPPORTED_RELATIONSHIPS.keys()].map((k) => [k.toLowerCase(), k]));
|
|
3922
|
+
/**
|
|
3923
|
+
* Content types (lower case) of active or embedded content: a part with one
|
|
3924
|
+
* of these is reported as its kind whatever relationship reaches it.
|
|
3925
|
+
*/
|
|
3926
|
+
const CONTENT_TYPES = /* @__PURE__ */ new Map([
|
|
3927
|
+
["application/vnd.ms-office.activex+xml", "activeX"],
|
|
3928
|
+
["application/vnd.ms-office.activex", "activeX"],
|
|
3929
|
+
["application/vnd.openxmlformats-officedocument.oleobject", "oleObject"],
|
|
3930
|
+
["application/vnd.ms-office.oleobject", "oleObject"],
|
|
3931
|
+
["application/vnd.ms-office.vbaproject", "vbaProject"],
|
|
3932
|
+
["application/vnd.ms-office.vbaprojectsignature", "vbaProject"],
|
|
3933
|
+
["application/vnd.ms-excel.attachedtoolbars", "vbaProject"],
|
|
3934
|
+
["application/vnd.ms-excel.macrosheet+xml", "macrosheet"],
|
|
3935
|
+
["application/vnd.ms-excel.intlmacrosheet+xml", "macrosheet"],
|
|
3936
|
+
["application/vnd.ms-office.webextension+xml", "webExtension"],
|
|
3937
|
+
["application/vnd.ms-office.webextensiontaskpanes+xml", "webExtension"],
|
|
3938
|
+
["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "embeddedPackage"],
|
|
3939
|
+
["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "embeddedPackage"],
|
|
3940
|
+
["application/vnd.openxmlformats-officedocument.presentationml.presentation", "embeddedPackage"],
|
|
3941
|
+
["application/vnd.openxmlformats-officedocument.presentationml.slideshow", "embeddedPackage"],
|
|
3942
|
+
["application/vnd.ms-word.document.macroenabled.12", "embeddedPackage"],
|
|
3943
|
+
["application/vnd.ms-excel.sheet.macroenabled.12", "embeddedPackage"],
|
|
3944
|
+
["application/vnd.ms-excel.sheet.binary.macroenabled.12", "embeddedPackage"],
|
|
3945
|
+
["application/vnd.ms-powerpoint.presentation.macroenabled.12", "embeddedPackage"],
|
|
3946
|
+
["application/vnd.ms-powerpoint.slideshow.macroenabled.12", "embeddedPackage"],
|
|
3947
|
+
["application/vnd.openxmlformats-officedocument.spreadsheetml.template", "embeddedPackage"],
|
|
3948
|
+
["application/vnd.openxmlformats-officedocument.wordprocessingml.template", "embeddedPackage"],
|
|
3949
|
+
["application/vnd.openxmlformats-officedocument.presentationml.template", "embeddedPackage"],
|
|
3950
|
+
["application/vnd.openxmlformats-officedocument.presentationml.slide", "embeddedPackage"],
|
|
3951
|
+
["application/vnd.ms-excel.template.macroenabled.12", "embeddedPackage"],
|
|
3952
|
+
["application/vnd.ms-excel.addin.macroenabled.12", "embeddedPackage"],
|
|
3953
|
+
["application/vnd.ms-word.template.macroenabled.12", "embeddedPackage"],
|
|
3954
|
+
["application/vnd.ms-powerpoint.template.macroenabled.12", "embeddedPackage"],
|
|
3955
|
+
["application/vnd.ms-powerpoint.slide.macroenabled.12", "embeddedPackage"],
|
|
3956
|
+
["application/vnd.ms-powerpoint.addin.macroenabled.12", "embeddedPackage"]
|
|
3957
|
+
]);
|
|
3958
|
+
/**
|
|
3959
|
+
* Kinds `read` reports wherever the scan finds them: on any sheet (also one
|
|
3960
|
+
* left out by `sheets`) and under any part (a drawing, a table, ...). These are
|
|
3961
|
+
* active or embedded content and links out of the file. The other kinds
|
|
3962
|
+
* (drawings, images, comments, tables, pivots, ...) are reported, as before
|
|
3963
|
+
* 2.5, from the workbook's and the read sheets' own relationships only.
|
|
3964
|
+
*/
|
|
3965
|
+
const REPORTED_ANYWHERE = /* @__PURE__ */ new Set([
|
|
3966
|
+
"activeX",
|
|
3967
|
+
"embeddedPackage",
|
|
3968
|
+
"customUI",
|
|
3969
|
+
"oleObject",
|
|
3970
|
+
"vbaProject",
|
|
3971
|
+
"externalLink",
|
|
3972
|
+
"connections",
|
|
3973
|
+
"queryTable",
|
|
3974
|
+
"macrosheet",
|
|
3975
|
+
"webExtension"
|
|
3976
|
+
]);
|
|
3977
|
+
/**
|
|
3978
|
+
* Hyperlink relationship types (lower case), transitional and strict: their
|
|
3979
|
+
* external targets open only when a user follows the link, so they are not
|
|
3980
|
+
* reported as `externalTarget` (JSE-85). Compared as whole URIs, not by last
|
|
3981
|
+
* segment, so a made-up type ending in `/hyperlink` is reported.
|
|
3982
|
+
*/
|
|
3983
|
+
const HYPERLINK_TYPES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/officedocument/2006/relationships/hyperlink", "http://purl.oclc.org/ooxml/officedocument/relationships/hyperlink"]);
|
|
3984
|
+
const HYPERLINK_TYPE_LENGTH = Math.max(...[...HYPERLINK_TYPES].map((t) => t.length));
|
|
3985
|
+
/**
|
|
3986
|
+
* The kind a relationship names, by its type alone: the last segment of the
|
|
3987
|
+
* type URI, compared without regard to case, or an alias (RELATIONSHIP_ALIASES).
|
|
3988
|
+
* customUI is matched on the whole type (`.../ui/extensibility`).
|
|
3989
|
+
*/
|
|
3990
|
+
function relationshipKindOf(rel) {
|
|
3991
|
+
const kind = rel.kind.toLowerCase();
|
|
3992
|
+
if (kind === "extensibility" && /\/ui\/extensibility$/i.test(rel.type)) return "customUI";
|
|
3993
|
+
return RELATIONSHIP_ALIASES.get(kind) ?? RELATIONSHIP_KINDS.get(kind);
|
|
3994
|
+
}
|
|
3995
|
+
/**
|
|
3996
|
+
* What a relationship and its target's content type make of a part; undefined
|
|
3997
|
+
* for parts the model reads or that need no report. A kind in REPORTED_ANYWHERE
|
|
3998
|
+
* wins: an active content type behind a passive or unknown relationship (an
|
|
3999
|
+
* `image` relationship to an OLE object) is reported by its content type.
|
|
4000
|
+
*/
|
|
4001
|
+
function partKindOf(rel, contentTypes) {
|
|
4002
|
+
const byRel = relationshipKindOf(rel);
|
|
4003
|
+
if (byRel !== void 0 && REPORTED_ANYWHERE.has(byRel)) return byRel;
|
|
4004
|
+
for (const t of contentTypes) {
|
|
4005
|
+
const byType = CONTENT_TYPES.get(t.toLowerCase().split(";")[0].trim());
|
|
4006
|
+
if (byType) return byType;
|
|
4007
|
+
}
|
|
4008
|
+
return byRel;
|
|
4009
|
+
}
|
|
4010
|
+
/**
|
|
4011
|
+
* Walks the relationship graph of `pkg` from the package root, breadth first.
|
|
4012
|
+
* Reads only relationships parts (each at most once per read, through the
|
|
4013
|
+
* zip and XML limits of `pkg.ctx`, without marking them consumed) and the
|
|
4014
|
+
* content types already loaded; never inflates the parts it classifies.
|
|
4015
|
+
* A target OPC forbids is followed both as a decoder reads it and literally,
|
|
4016
|
+
* so content behind it is found either way. Consults the signal per part and
|
|
4017
|
+
* every 4,096 relationships or zip entries. A relationships part that is not
|
|
4018
|
+
* well-formed XML is treated as unreferenced instead of failing the read;
|
|
4019
|
+
* limit and DTD errors are thrown as anywhere else.
|
|
4020
|
+
*/
|
|
4021
|
+
async function scanPackageParts(pkg) {
|
|
4022
|
+
const ctx = pkg.ctx;
|
|
4023
|
+
const found = [];
|
|
4024
|
+
const foundKeys = /* @__PURE__ */ new Set();
|
|
4025
|
+
const forbidden = new Set(pkg.forbiddenNames);
|
|
4026
|
+
/** partKey of the parts accounted for (reached from the package root). */
|
|
4027
|
+
const reached = /* @__PURE__ */ new Set([partKey("[Content_Types].xml")]);
|
|
4028
|
+
/** 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). */
|
|
4029
|
+
const queued = /* @__PURE__ */ new Set([""]);
|
|
4030
|
+
/** Relationships parts parsed, by partKey. */
|
|
4031
|
+
const parsed = /* @__PURE__ */ new Set();
|
|
4032
|
+
const queue = [{
|
|
4033
|
+
source: "",
|
|
4034
|
+
counts: true
|
|
4035
|
+
}];
|
|
4036
|
+
const external = {
|
|
4037
|
+
count: 0,
|
|
4038
|
+
parts: [],
|
|
4039
|
+
types: []
|
|
4040
|
+
};
|
|
4041
|
+
const externalTypes = /* @__PURE__ */ new Set();
|
|
4042
|
+
const visit = (target, counts) => {
|
|
4043
|
+
const entry = pkg.part(target);
|
|
4044
|
+
if (!entry) return;
|
|
4045
|
+
const key = pkg.keyOf(entry);
|
|
4046
|
+
if (counts) reached.add(key);
|
|
4047
|
+
if (queued.has(key)) return;
|
|
4048
|
+
queued.add(key);
|
|
4049
|
+
queue.push({
|
|
4050
|
+
source: entry.name,
|
|
4051
|
+
counts
|
|
4052
|
+
});
|
|
4053
|
+
};
|
|
4054
|
+
const classify = (rel, source, relsPart) => {
|
|
4055
|
+
const targets = rel.external || rel.tooLong || rel.target === "" ? [] : rel.altTarget === void 0 ? [rel.target] : [rel.target, rel.altTarget];
|
|
4056
|
+
for (const target of targets.length ? targets : [void 0]) {
|
|
4057
|
+
const kind = partKindOf(rel, target === void 0 ? [] : pkg.contentTypes(target));
|
|
4058
|
+
if (!kind) continue;
|
|
4059
|
+
const part = target ?? (rel.external ? source || relsPart : relsPart);
|
|
4060
|
+
const key = `${kind}\u0000${partKey(part)}`;
|
|
4061
|
+
if (foundKeys.has(key)) continue;
|
|
4062
|
+
foundKeys.add(key);
|
|
4063
|
+
found.push({
|
|
4064
|
+
kind,
|
|
4065
|
+
part,
|
|
4066
|
+
source,
|
|
4067
|
+
external: rel.external
|
|
4068
|
+
});
|
|
4069
|
+
}
|
|
4070
|
+
};
|
|
4071
|
+
const drain = async () => {
|
|
4072
|
+
for (let q = 0; q < queue.length; q++) {
|
|
4073
|
+
const pause = ctx.step();
|
|
4074
|
+
if (pause) await pause;
|
|
4075
|
+
const { source, counts } = queue[q];
|
|
4076
|
+
const relsEntry = pkg.part(pkg.relsPartOf(source));
|
|
4077
|
+
if (!relsEntry) continue;
|
|
4078
|
+
const relsKey = pkg.keyOf(relsEntry);
|
|
4079
|
+
if (parsed.has(relsKey)) continue;
|
|
4080
|
+
parsed.add(relsKey);
|
|
4081
|
+
let rels;
|
|
4082
|
+
try {
|
|
4083
|
+
rels = await pkg.rels(source, { peek: true });
|
|
4084
|
+
} catch (err) {
|
|
4085
|
+
if (err instanceof FormatError && err.code === "XML_MALFORMED") continue;
|
|
4086
|
+
throw err;
|
|
4087
|
+
}
|
|
4088
|
+
if (counts) reached.add(relsKey);
|
|
4089
|
+
const malformed = pkg.malformedRels.get(relsEntry.name) ?? [];
|
|
4090
|
+
if (malformed.length) forbidden.add(relsEntry.name);
|
|
4091
|
+
const all = malformed.length ? [...rels, ...malformed] : rels;
|
|
4092
|
+
let externalHere = false;
|
|
4093
|
+
for (let i = 0; i < all.length; i++) {
|
|
4094
|
+
if ((i & 4095) === 4095) ctx.checkAbort();
|
|
4095
|
+
const rel = all[i];
|
|
4096
|
+
if (rel.forbidden) forbidden.add(relsEntry.name);
|
|
4097
|
+
classify(rel, source, relsEntry.name);
|
|
4098
|
+
if ((rel.external || rel.outside) && !isHyperlink(rel)) {
|
|
4099
|
+
external.count++;
|
|
4100
|
+
if (!externalHere) {
|
|
4101
|
+
externalHere = true;
|
|
4102
|
+
external.parts.push(relsEntry.name);
|
|
4103
|
+
}
|
|
4104
|
+
if (external.types.length < 16) {
|
|
4105
|
+
const t = rel.type.toLowerCase();
|
|
4106
|
+
if (!externalTypes.has(t)) {
|
|
4107
|
+
externalTypes.add(t);
|
|
4108
|
+
external.types.push(excerpt(rel.type));
|
|
4109
|
+
}
|
|
4110
|
+
}
|
|
4111
|
+
}
|
|
4112
|
+
if (rel.external || rel.tooLong) continue;
|
|
4113
|
+
visit(rel.target, counts);
|
|
4114
|
+
if (rel.altTarget !== void 0) visit(rel.altTarget, counts);
|
|
4115
|
+
}
|
|
4116
|
+
}
|
|
4117
|
+
queue.length = 0;
|
|
4118
|
+
};
|
|
4119
|
+
await drain();
|
|
4120
|
+
const entries = ctx.zip.entries;
|
|
4121
|
+
for (let i = 0; i < entries.length; i++) {
|
|
4122
|
+
if ((i & 4095) === 4095) ctx.checkAbort();
|
|
4123
|
+
const e = entries[i];
|
|
4124
|
+
if (e.name.endsWith("/") || parsed.has(pkg.keyOf(e))) continue;
|
|
4125
|
+
const owner = relsOwner(pkg.keyOf(e));
|
|
4126
|
+
if (owner === void 0) continue;
|
|
4127
|
+
queue.push({
|
|
4128
|
+
source: owner,
|
|
4129
|
+
counts: false
|
|
3141
4130
|
});
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
4131
|
+
await drain();
|
|
4132
|
+
}
|
|
4133
|
+
const unreferenced = [];
|
|
4134
|
+
for (let i = 0; i < entries.length; i++) {
|
|
4135
|
+
if ((i & 4095) === 4095) ctx.checkAbort();
|
|
4136
|
+
const e = entries[i];
|
|
4137
|
+
if (e.name.endsWith("/")) continue;
|
|
4138
|
+
if (!reached.has(pkg.keyOf(e))) unreferenced.push(e.name);
|
|
4139
|
+
}
|
|
4140
|
+
return {
|
|
4141
|
+
found,
|
|
4142
|
+
unreferenced,
|
|
4143
|
+
forbidden: [...forbidden],
|
|
4144
|
+
external
|
|
4145
|
+
};
|
|
4146
|
+
}
|
|
4147
|
+
/** A hyperlink relationship (HYPERLINK_TYPES): never reported as `externalTarget`. */
|
|
4148
|
+
function isHyperlink(rel) {
|
|
4149
|
+
return rel.type.length <= HYPERLINK_TYPE_LENGTH && HYPERLINK_TYPES.has(rel.type.toLowerCase());
|
|
4150
|
+
}
|
|
4151
|
+
// src/internal/read/formats.ts
|
|
4152
|
+
/** Container signatures, checked in order. */
|
|
4153
|
+
const CONTAINERS = [
|
|
4154
|
+
{
|
|
4155
|
+
kind: "cfb",
|
|
4156
|
+
magic: [
|
|
4157
|
+
208,
|
|
4158
|
+
207,
|
|
4159
|
+
17,
|
|
4160
|
+
224,
|
|
4161
|
+
161,
|
|
4162
|
+
177,
|
|
4163
|
+
26,
|
|
4164
|
+
225
|
|
4165
|
+
]
|
|
4166
|
+
},
|
|
4167
|
+
{
|
|
4168
|
+
kind: "zip",
|
|
4169
|
+
magic: [
|
|
4170
|
+
80,
|
|
4171
|
+
75,
|
|
4172
|
+
3,
|
|
4173
|
+
4
|
|
4174
|
+
]
|
|
4175
|
+
},
|
|
4176
|
+
{
|
|
4177
|
+
kind: "zip",
|
|
4178
|
+
magic: [
|
|
4179
|
+
80,
|
|
4180
|
+
75,
|
|
4181
|
+
5,
|
|
4182
|
+
6
|
|
4183
|
+
]
|
|
4184
|
+
}
|
|
4185
|
+
];
|
|
4186
|
+
/** OPC workbook formats by the content type of their workbook part. */
|
|
4187
|
+
const WORKBOOK_FORMATS = [
|
|
4188
|
+
{
|
|
4189
|
+
format: "xlsx",
|
|
4190
|
+
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
|
|
4191
|
+
decoder: "spreadsheetml",
|
|
4192
|
+
label: "Excel workbook (.xlsx)"
|
|
4193
|
+
},
|
|
4194
|
+
{
|
|
4195
|
+
format: "xltx",
|
|
4196
|
+
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml",
|
|
4197
|
+
decoder: "spreadsheetml",
|
|
4198
|
+
label: "Excel template (.xltx)"
|
|
4199
|
+
},
|
|
4200
|
+
{
|
|
4201
|
+
format: "xlsm",
|
|
4202
|
+
contentType: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
|
|
4203
|
+
decoder: "spreadsheetml",
|
|
4204
|
+
macros: true,
|
|
4205
|
+
label: "macro-enabled workbook (.xlsm)"
|
|
4206
|
+
},
|
|
4207
|
+
{
|
|
4208
|
+
format: "xltm",
|
|
4209
|
+
contentType: "application/vnd.ms-excel.template.macroEnabled.main+xml",
|
|
4210
|
+
decoder: "spreadsheetml",
|
|
4211
|
+
macros: true,
|
|
4212
|
+
label: "macro-enabled template (.xltm)"
|
|
4213
|
+
},
|
|
4214
|
+
{
|
|
4215
|
+
format: "xlsb",
|
|
4216
|
+
contentType: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
|
|
4217
|
+
macros: true,
|
|
4218
|
+
label: "binary workbook (.xlsb)"
|
|
3164
4219
|
}
|
|
4220
|
+
];
|
|
4221
|
+
/** Formats recognised by something other than a workbook content type. */
|
|
4222
|
+
const OTHER_FORMATS = {
|
|
4223
|
+
ods: { label: "OpenDocument spreadsheet (.ods)" },
|
|
4224
|
+
cfb: { label: "legacy .xls file or a password-protected (encrypted) workbook" },
|
|
4225
|
+
unknown: { label: "file that is not a spreadsheet package" }
|
|
3165
4226
|
};
|
|
4227
|
+
function sniffContainer(b) {
|
|
4228
|
+
for (const c of CONTAINERS) if (c.magic.every((x, i) => b[i] === x)) return c.kind;
|
|
4229
|
+
return "unknown";
|
|
4230
|
+
}
|
|
4231
|
+
/**
|
|
4232
|
+
* The workbook format for a workbook part, from its content type; when the
|
|
4233
|
+
* content type is missing or unknown, from the part's extension (.bin is
|
|
4234
|
+
* binary, anything else is read as SpreadsheetML).
|
|
4235
|
+
*/
|
|
4236
|
+
function workbookFormat(contentType, partName) {
|
|
4237
|
+
const ct = (contentType ?? "").toLowerCase();
|
|
4238
|
+
const known = WORKBOOK_FORMATS.find((f) => f.contentType.toLowerCase() === ct);
|
|
4239
|
+
if (known) return known;
|
|
4240
|
+
if (partName.toLowerCase().endsWith(".bin")) return WORKBOOK_FORMATS.find((f) => f.format === "xlsb");
|
|
4241
|
+
return WORKBOOK_FORMATS[0];
|
|
4242
|
+
}
|
|
3166
4243
|
var WorkbookParser = class {
|
|
3167
4244
|
maxSheets;
|
|
3168
4245
|
part;
|
|
@@ -3429,29 +4506,6 @@ var CustomPropsParser = class {
|
|
|
3429
4506
|
}
|
|
3430
4507
|
};
|
|
3431
4508
|
// 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
4509
|
function unsupported(format, message) {
|
|
3456
4510
|
return new FormatError("UNSUPPORTED_FORMAT", message, { details: { format } });
|
|
3457
4511
|
}
|
|
@@ -3586,10 +4640,10 @@ function warnUnsupportedParts(ctx, rels, part, seen) {
|
|
|
3586
4640
|
for (let i = 0; i < rels.length; i++) {
|
|
3587
4641
|
if ((i & 4095) === 4095) ctx.checkAbort();
|
|
3588
4642
|
const r = rels[i];
|
|
3589
|
-
const kind = r
|
|
3590
|
-
const what =
|
|
3591
|
-
if (what && !seen.has(
|
|
3592
|
-
seen.add(
|
|
4643
|
+
const kind = relationshipKindOf(r);
|
|
4644
|
+
const what = kind === void 0 ? void 0 : UNSUPPORTED_RELATIONSHIPS.get(kind);
|
|
4645
|
+
if (kind && what && !seen.has(kind)) {
|
|
4646
|
+
seen.add(kind);
|
|
3593
4647
|
ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
|
|
3594
4648
|
part: r.external ? part : r.target,
|
|
3595
4649
|
partKind: kind
|
|
@@ -3597,6 +4651,59 @@ function warnUnsupportedParts(ctx, rels, part, seen) {
|
|
|
3597
4651
|
}
|
|
3598
4652
|
}
|
|
3599
4653
|
}
|
|
4654
|
+
/**
|
|
4655
|
+
* After the sheets (JSE-72): the kinds in REPORTED_ANYWHERE that the
|
|
4656
|
+
* workbook's and the read sheets' relationships did not already report,
|
|
4657
|
+
* wherever the package scan found them, then one `externalTarget` warning
|
|
4658
|
+
* for all non-hyperlink relationships that point, or may point, outside the
|
|
4659
|
+
* package, whatever their kind (JSE-85), one `invalidPartName` warning
|
|
4660
|
+
* for all names OPC forbids and one `unreferencedPart` warning for all parts
|
|
4661
|
+
* no relationship reaches, each listing every name in `parts`.
|
|
4662
|
+
*/
|
|
4663
|
+
async function warnScannedParts(pkg, seen) {
|
|
4664
|
+
const ctx = pkg.ctx;
|
|
4665
|
+
const scan = await scanPackageParts(pkg);
|
|
4666
|
+
for (const f of scan.found) {
|
|
4667
|
+
if (!REPORTED_ANYWHERE.has(f.kind) || seen.has(f.kind)) continue;
|
|
4668
|
+
seen.add(f.kind);
|
|
4669
|
+
const what = SCANNED_KINDS.get(f.kind) ?? UNSUPPORTED_RELATIONSHIPS.get(f.kind);
|
|
4670
|
+
ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
|
|
4671
|
+
part: f.part,
|
|
4672
|
+
partKind: f.kind
|
|
4673
|
+
});
|
|
4674
|
+
}
|
|
4675
|
+
const ext = scan.external;
|
|
4676
|
+
if (ext.count > 0) {
|
|
4677
|
+
const first = ext.parts[0];
|
|
4678
|
+
const message = ext.count === 1 ? `The package has 1 relationship to a target outside the file (in "${excerpt(first)}"); it is not read or fetched, but Excel may fetch it when the file is opened.` : `The package has ${ext.count} relationships to targets outside the file (in ${ext.parts.length} relationships part${ext.parts.length === 1 ? "" : "s"}; first in "${excerpt(first)}"); they are not read or fetched, but Excel may fetch them when the file is opened.`;
|
|
4679
|
+
ctx.warn("UNSUPPORTED_PART", message, {
|
|
4680
|
+
part: first,
|
|
4681
|
+
partKind: "externalTarget",
|
|
4682
|
+
parts: ext.parts,
|
|
4683
|
+
relationshipTypes: ext.types
|
|
4684
|
+
});
|
|
4685
|
+
}
|
|
4686
|
+
const bad = scan.forbidden;
|
|
4687
|
+
if (bad.length > 0) {
|
|
4688
|
+
const first = bad[0];
|
|
4689
|
+
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.`;
|
|
4690
|
+
ctx.warn("UNSUPPORTED_PART", message, {
|
|
4691
|
+
part: first,
|
|
4692
|
+
partKind: "invalidPartName",
|
|
4693
|
+
parts: bad
|
|
4694
|
+
});
|
|
4695
|
+
}
|
|
4696
|
+
const n = scan.unreferenced.length;
|
|
4697
|
+
if (n > 0) {
|
|
4698
|
+
const first = scan.unreferenced[0];
|
|
4699
|
+
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.`;
|
|
4700
|
+
ctx.warn("UNSUPPORTED_PART", message, {
|
|
4701
|
+
part: first,
|
|
4702
|
+
partKind: "unreferencedPart",
|
|
4703
|
+
parts: scan.unreferenced
|
|
4704
|
+
});
|
|
4705
|
+
}
|
|
4706
|
+
}
|
|
3600
4707
|
/** Reads an .xlsx-family file into the model. */
|
|
3601
4708
|
async function readImpl(input, options, internal) {
|
|
3602
4709
|
const o = options ?? {};
|
|
@@ -3612,12 +4719,26 @@ async function readImpl(input, options, internal) {
|
|
|
3612
4719
|
let ctx;
|
|
3613
4720
|
const { pkg, workbookPart, format } = await openPackage(bytes, limits, (zip) => {
|
|
3614
4721
|
ctx = new ReadContext(zip, limits, o.signal, o.onWarning, o.onProgress);
|
|
4722
|
+
if (internal?.inspect) {
|
|
4723
|
+
ctx.sniff = internal.inspect.sniff;
|
|
4724
|
+
ctx.relsParsed = internal.inspect.relsParsed;
|
|
4725
|
+
}
|
|
3615
4726
|
return ctx;
|
|
3616
4727
|
});
|
|
3617
4728
|
ctx.progress({
|
|
3618
4729
|
phase: "unzip",
|
|
3619
4730
|
ratio: .02
|
|
3620
4731
|
});
|
|
4732
|
+
const inspect = internal?.inspect;
|
|
4733
|
+
if (inspect) {
|
|
4734
|
+
inspect.ctx = ctx;
|
|
4735
|
+
inspect.pkg = pkg;
|
|
4736
|
+
inspect.format = format;
|
|
4737
|
+
ctx.tap = (w) => {
|
|
4738
|
+
if (w.code === "UNSUPPORTED_PART") inspect.unsupported.push(w);
|
|
4739
|
+
else if (w.code === "BROKEN_OPTIONAL_PART" && w.part !== void 0) inspect.broken.add(w.part);
|
|
4740
|
+
};
|
|
4741
|
+
}
|
|
3621
4742
|
const wbp = await parseWorkbook(pkg, workbookPart);
|
|
3622
4743
|
const wbRels = await pkg.rels(workbookPart);
|
|
3623
4744
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -3674,9 +4795,10 @@ async function readImpl(input, options, internal) {
|
|
|
3674
4795
|
});
|
|
3675
4796
|
else if (deferred) sstEntry = entry;
|
|
3676
4797
|
else {
|
|
3677
|
-
const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n), limits.maxCellTextLength);
|
|
4798
|
+
const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n), limits.maxCellTextLength, !inspect);
|
|
3678
4799
|
await ctx.parse(entry, sp);
|
|
3679
4800
|
sst = sp.strings;
|
|
4801
|
+
if (inspect) inspect.sharedStrings = sp.count;
|
|
3680
4802
|
}
|
|
3681
4803
|
}
|
|
3682
4804
|
const properties = await readProperties(pkg, ctx);
|
|
@@ -3690,6 +4812,13 @@ async function readImpl(input, options, internal) {
|
|
|
3690
4812
|
totalBytes ||= 1;
|
|
3691
4813
|
let doneBytes = 0;
|
|
3692
4814
|
const sheets = [];
|
|
4815
|
+
const done = (parser, part, sheet) => {
|
|
4816
|
+
sheets.push(sheet);
|
|
4817
|
+
inspect?.sheets.push({
|
|
4818
|
+
part: part?.name,
|
|
4819
|
+
cells: parser.cellCount
|
|
4820
|
+
});
|
|
4821
|
+
};
|
|
3693
4822
|
for (let i = 0; i < listed.length; i++) {
|
|
3694
4823
|
const pause = ctx.step();
|
|
3695
4824
|
if (pause) await pause;
|
|
@@ -3702,9 +4831,11 @@ async function readImpl(input, options, internal) {
|
|
|
3702
4831
|
richText: o.richText ?? "runs",
|
|
3703
4832
|
rawText: o.rawText === true,
|
|
3704
4833
|
date1904: wbp.date1904,
|
|
3705
|
-
maxRows: o.maxRows ?? 1048576
|
|
4834
|
+
maxRows: o.maxRows ?? 1048576,
|
|
4835
|
+
keepCells: !inspect
|
|
3706
4836
|
}, rel?.target ?? workbookPart);
|
|
3707
4837
|
parser.sharedStrings = sst;
|
|
4838
|
+
if (inspect) parser.sharedStringCount = inspect.sharedStrings;
|
|
3708
4839
|
parser.deferred = deferred;
|
|
3709
4840
|
const part = rel ? pkg.part(rel.target) : void 0;
|
|
3710
4841
|
if (!part) {
|
|
@@ -3712,11 +4843,11 @@ async function readImpl(input, options, internal) {
|
|
|
3712
4843
|
sheet: entry.name,
|
|
3713
4844
|
partKind: "worksheet"
|
|
3714
4845
|
});
|
|
3715
|
-
|
|
4846
|
+
done(parser, part, parser.finish([]));
|
|
3716
4847
|
continue;
|
|
3717
4848
|
}
|
|
3718
4849
|
if (!wanted(entry.name, i)) {
|
|
3719
|
-
|
|
4850
|
+
done(parser, part, parser.finish([]));
|
|
3720
4851
|
continue;
|
|
3721
4852
|
}
|
|
3722
4853
|
const sheetRels = await pkg.rels(part.name);
|
|
@@ -3737,8 +4868,9 @@ async function readImpl(input, options, internal) {
|
|
|
3737
4868
|
});
|
|
3738
4869
|
});
|
|
3739
4870
|
doneBytes += part.size;
|
|
3740
|
-
|
|
4871
|
+
done(parser, part, parser.finish(sheetRels));
|
|
3741
4872
|
}
|
|
4873
|
+
await warnScannedParts(pkg, seen);
|
|
3742
4874
|
if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name);
|
|
3743
4875
|
if (deferred && deferred.cells.length > 0) {
|
|
3744
4876
|
if (sstEntry) {
|
|
@@ -3865,6 +4997,349 @@ async function readProperties(pkg, ctx) {
|
|
|
3865
4997
|
}
|
|
3866
4998
|
return Object.keys(props).length ? props : void 0;
|
|
3867
4999
|
}
|
|
5000
|
+
// src/internal/read/inspect.ts
|
|
5001
|
+
/**
|
|
5002
|
+
* inspect (docs/api.md §5.2.1, JSE-71): checks a workbook part by part with
|
|
5003
|
+
* read's zip and XML safety, without building cells. Internal.
|
|
5004
|
+
*
|
|
5005
|
+
* The workbook is read by readImpl itself, with every check read makes, in
|
|
5006
|
+
* the same order, but with no cells and no shared strings kept (the sheet
|
|
5007
|
+
* and shared-strings parsers count instead). So inspect refuses what read
|
|
5008
|
+
* refuses, with the same error, and reports the part kinds read reports;
|
|
5009
|
+
* whatever readImpl learns to check or report, inspect does too. Only once
|
|
5010
|
+
* that read has succeeded come the checks read does not make:
|
|
5011
|
+
* - every XML part (by content type, by name, or as the target of a
|
|
5012
|
+
* relationship of a kind that is not binary, from the relationships read's
|
|
5013
|
+
* package scan parsed), including the parts read parses, must be in UTF-8
|
|
5014
|
+
* or UTF-16, as OPC requires;
|
|
5015
|
+
* - every zip entry the read did not parse, or parsed only up to an error it
|
|
5016
|
+
* forgave (a broken optional part), is inflated (zip limits, CRC) and its
|
|
5017
|
+
* bytes searched for `<!DOCTYPE`, whatever its name or content type.
|
|
5018
|
+
*/
|
|
5019
|
+
/**
|
|
5020
|
+
* `<!DOCTYPE` in the bytes of a part, read one byte per character: ASCII and
|
|
5021
|
+
* UTF-8 text, UTF-16 (one NUL between the characters) and UTF-32 (three), in
|
|
5022
|
+
* either byte order; and UTF-7, where `<` and `!` are base64 runs. In any
|
|
5023
|
+
* case, as the tokenizer refuses it.
|
|
5024
|
+
*/
|
|
5025
|
+
const DOCTYPE = /<(\u0000{0,3})!\1d\1o\1c\1t\1y\1p\1e|\+ADw(?:-!|AIQ-|-\+ACE-)doctype/i;
|
|
5026
|
+
/** A processing instruction whose target is `xml` in any case, in the same byte forms as DOCTYPE. */
|
|
5027
|
+
const XML_PI = /<(\u0000{0,3})\?\1x\1m\1l\1[ \t\r\n?]/gi;
|
|
5028
|
+
/** Reads bytes as characters one to one (windows-1252: ASCII and NUL map to themselves). */
|
|
5029
|
+
const BYTES = new TextDecoder("latin1");
|
|
5030
|
+
/** Relationship kinds (lower case) whose target is not XML. Every other internal target is treated as an XML part. */
|
|
5031
|
+
const BINARY_KINDS = /* @__PURE__ */ new Set([
|
|
5032
|
+
"image",
|
|
5033
|
+
"oleobject",
|
|
5034
|
+
"package",
|
|
5035
|
+
"vbaproject",
|
|
5036
|
+
"vbaprojectsignature",
|
|
5037
|
+
"vbaprojectsignatureagile",
|
|
5038
|
+
"vbaprojectsignaturev3",
|
|
5039
|
+
"attachedtoolbars",
|
|
5040
|
+
"printersettings",
|
|
5041
|
+
"activexcontrolbinary",
|
|
5042
|
+
"thumbnail",
|
|
5043
|
+
"font",
|
|
5044
|
+
"media",
|
|
5045
|
+
"audio",
|
|
5046
|
+
"video",
|
|
5047
|
+
"hyperlink",
|
|
5048
|
+
"attachedtemplate",
|
|
5049
|
+
"externallinkpath",
|
|
5050
|
+
"xlbinaryindex"
|
|
5051
|
+
]);
|
|
5052
|
+
/** Parts whose content type or name says XML. */
|
|
5053
|
+
function isXmlByName(pkg, name) {
|
|
5054
|
+
const type = (pkg.contentType(name) ?? "").toLowerCase();
|
|
5055
|
+
return /[+/]xml\s*(;|$)/.test(type) || type.endsWith("vmldrawing") || /\.(xml|rels|vml|svg)$/i.test(name);
|
|
5056
|
+
}
|
|
5057
|
+
/**
|
|
5058
|
+
* The encoding a part's first four bytes show when OPC does not allow it
|
|
5059
|
+
* (ECMA-376 Part 2: UTF-8 or UTF-16), else undefined: a UTF-32 or UCS-4 byte
|
|
5060
|
+
* order mark or `<`, the EBCDIC bytes of `<?xml`, the UTF-7 signature
|
|
5061
|
+
* (`+/v`) or a UTF-7 `<` (`+ADw`).
|
|
5062
|
+
*/
|
|
5063
|
+
function signatureEncoding(b) {
|
|
5064
|
+
const [b0, b1, b2, b3] = [
|
|
5065
|
+
b[0],
|
|
5066
|
+
b[1],
|
|
5067
|
+
b[2],
|
|
5068
|
+
b[3]
|
|
5069
|
+
];
|
|
5070
|
+
if (b0 === 0 && b1 === 0 && b2 === 254 && b3 === 255) return "UTF-32BE";
|
|
5071
|
+
if (b0 === 255 && b1 === 254 && b2 === 0 && b3 === 0) return "UTF-32LE";
|
|
5072
|
+
if (b0 === 0 && b1 === 0 && b2 === 0 && b3 === 60) return "UTF-32BE";
|
|
5073
|
+
if (b0 === 60 && b1 === 0 && b2 === 0 && b3 === 0) return "UTF-32LE";
|
|
5074
|
+
if (b0 === 0 && b1 === 0 && b2 === 60 && b3 === 0 || b0 === 0 && b1 === 60 && b2 === 0 && b3 === 0) return "UCS-4";
|
|
5075
|
+
if (b0 === 76 && b1 === 111 && b2 === 167 && b3 === 148) return "EBCDIC";
|
|
5076
|
+
if (b0 === 43 && b1 === 47 && b2 === 118) return "UTF-7";
|
|
5077
|
+
if (b0 === 43 && b1 === 65 && b2 === 68 && (b3 === 119 || b3 === 120)) return "UTF-7";
|
|
5078
|
+
}
|
|
5079
|
+
/**
|
|
5080
|
+
* The XMLDecl production (XML 1.0 §2.8), strictly: `<?xml`, then version,
|
|
5081
|
+
* encoding and standalone in that order, each once, quoted, only the first
|
|
5082
|
+
* required, with spaces as XML counts them.
|
|
5083
|
+
*/
|
|
5084
|
+
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]*\?>$/;
|
|
5085
|
+
/** A whole declaration at the start of a part: undefined when it is well-formed and names UTF-8, UTF-16 or nothing. */
|
|
5086
|
+
function checkDeclaration(part, declaration) {
|
|
5087
|
+
const m = XML_DECLARATION.exec(declaration);
|
|
5088
|
+
if (!m) return new FormatError("XML_MALFORMED", `${excerpt(part)}: the XML declaration is not well-formed (XML 1.0 XMLDecl).`, { details: {
|
|
5089
|
+
part,
|
|
5090
|
+
declaration: printable(declaration)
|
|
5091
|
+
} });
|
|
5092
|
+
const name = m[1] ?? m[2];
|
|
5093
|
+
return name === void 0 || /^utf-?(8|16(le|be)?)$/i.test(name) ? void 0 : encodingError(part, printable(name));
|
|
5094
|
+
}
|
|
5095
|
+
function misplacedDeclaration(part) {
|
|
5096
|
+
return new FormatError("XML_MALFORMED", `${excerpt(part)}: an XML declaration (<?xml …?>) appears other than at the very start of the part.`, { details: { part } });
|
|
5097
|
+
}
|
|
5098
|
+
/** File text for `details`: printable ASCII only, at most 40 characters. */
|
|
5099
|
+
function printable(s) {
|
|
5100
|
+
const clean = s.replace(/[^\x20-\x7e]/g, "?");
|
|
5101
|
+
return clean.length > 40 ? `${clean.slice(0, 37)}...` : clean;
|
|
5102
|
+
}
|
|
5103
|
+
function encodingError(part, encoding) {
|
|
5104
|
+
return new FormatError("XML_MALFORMED", `${excerpt(part)}: the part is encoded in ${encoding}; XML parts must be UTF-8 or UTF-16.`, { details: {
|
|
5105
|
+
part,
|
|
5106
|
+
encoding
|
|
5107
|
+
} });
|
|
5108
|
+
}
|
|
5109
|
+
function doctype() {
|
|
5110
|
+
return new FormatError("XML_DTD_FORBIDDEN", "XML parts must not contain a document type declaration (<!DOCTYPE).");
|
|
5111
|
+
}
|
|
5112
|
+
async function inspectImpl(bytes, options) {
|
|
5113
|
+
let deferred;
|
|
5114
|
+
const maxToken = options?.limits?.maxXmlTokenLength ?? DEFAULT_LIMITS.maxXmlTokenLength;
|
|
5115
|
+
const xmlTargets = /* @__PURE__ */ new Set();
|
|
5116
|
+
const relsDone = /* @__PURE__ */ new Set();
|
|
5117
|
+
const sink = {
|
|
5118
|
+
unsupported: [],
|
|
5119
|
+
broken: /* @__PURE__ */ new Set(),
|
|
5120
|
+
sharedStrings: 0,
|
|
5121
|
+
sheets: [],
|
|
5122
|
+
sniff: (part) => new PartCheck(part, maxToken, (err) => deferred ??= err),
|
|
5123
|
+
relsParsed: (part, rels) => {
|
|
5124
|
+
relsDone.add(part);
|
|
5125
|
+
for (const r of rels) {
|
|
5126
|
+
if (r.external || r.tooLong || r.target === "" || BINARY_KINDS.has(r.kind.toLowerCase())) continue;
|
|
5127
|
+
xmlTargets.add(partKey(r.target));
|
|
5128
|
+
if (r.altTarget !== void 0) xmlTargets.add(partKey(r.altTarget));
|
|
5129
|
+
}
|
|
5130
|
+
}
|
|
5131
|
+
};
|
|
5132
|
+
const { workbook } = await readImpl(bytes, {
|
|
5133
|
+
limits: options?.limits,
|
|
5134
|
+
signal: options?.signal
|
|
5135
|
+
}, { inspect: sink });
|
|
5136
|
+
const ctx = sink.ctx;
|
|
5137
|
+
const pkg = sink.pkg;
|
|
5138
|
+
if (deferred !== void 0) throw deferred;
|
|
5139
|
+
for (const entry of ctx.zip.entries) {
|
|
5140
|
+
if ((ctx.consumed.has(entry.name) || relsDone.has(entry.name)) && !sink.broken.has(entry.name)) continue;
|
|
5141
|
+
const pause = ctx.step();
|
|
5142
|
+
if (pause) await pause;
|
|
5143
|
+
await scanPart(ctx, entry, isXmlByName(pkg, entry.name) || xmlTargets.has(pkg.keyOf(entry)));
|
|
5144
|
+
}
|
|
5145
|
+
const kinds = /* @__PURE__ */ new Set();
|
|
5146
|
+
for (const w of sink.unsupported) if (w.partKind !== void 0) kinds.add(w.partKind);
|
|
5147
|
+
const sheets = workbook.sheets.map((s, index) => {
|
|
5148
|
+
const out = {
|
|
5149
|
+
name: s.name,
|
|
5150
|
+
index,
|
|
5151
|
+
state: s.state ?? "visible",
|
|
5152
|
+
cells: sink.sheets[index].cells
|
|
5153
|
+
};
|
|
5154
|
+
const part = sink.sheets[index].part;
|
|
5155
|
+
if (part !== void 0) out.part = part;
|
|
5156
|
+
if (s.dimension !== void 0) out.dimension = s.dimension;
|
|
5157
|
+
return out;
|
|
5158
|
+
});
|
|
5159
|
+
return {
|
|
5160
|
+
format: sink.format.format,
|
|
5161
|
+
sheets,
|
|
5162
|
+
partKinds: [...kinds],
|
|
5163
|
+
warnings: sink.unsupported,
|
|
5164
|
+
parts: pkg.partNames.length,
|
|
5165
|
+
inflatedBytes: ctx.zip.totalBytesRead,
|
|
5166
|
+
cells: ctx.cells,
|
|
5167
|
+
sharedStrings: sink.sharedStrings
|
|
5168
|
+
};
|
|
5169
|
+
}
|
|
5170
|
+
/**
|
|
5171
|
+
* Inflates one entry to its end, so the zip limits and its CRC are checked;
|
|
5172
|
+
* searches its bytes for `<!DOCTYPE`; and, for an XML part, checks the
|
|
5173
|
+
* encoding of its first bytes. The bytes are searched in PARSE_SLICE pieces
|
|
5174
|
+
* with the signal consulted and the event loop given a turn between them, as
|
|
5175
|
+
* ctx.parse does, so a large stored entry is not one long step.
|
|
5176
|
+
*/
|
|
5177
|
+
async function scanPart(ctx, entry, xml) {
|
|
5178
|
+
let tail = "";
|
|
5179
|
+
let offset = 0;
|
|
5180
|
+
let lastPi = -1;
|
|
5181
|
+
let failure;
|
|
5182
|
+
const check = xml ? new PartCheck(entry.name, ctx.limits.maxXmlTokenLength, (err) => failure ??= err) : void 0;
|
|
5183
|
+
try {
|
|
5184
|
+
for await (const chunk of ctx.zip.stream(entry, ctx.signal)) {
|
|
5185
|
+
check?.feed(chunk);
|
|
5186
|
+
if (failure !== void 0) throw failure;
|
|
5187
|
+
for (let at = 0; at < chunk.length;) {
|
|
5188
|
+
const piece = chunk.subarray(at, at + PARSE_SLICE);
|
|
5189
|
+
const s = tail + BYTES.decode(piece);
|
|
5190
|
+
if (DOCTYPE.test(s)) throw doctype();
|
|
5191
|
+
if (check) {
|
|
5192
|
+
const base = offset + at - tail.length;
|
|
5193
|
+
XML_PI.lastIndex = 0;
|
|
5194
|
+
for (let m = XML_PI.exec(s); m; m = XML_PI.exec(s)) if (base + m.index > lastPi) {
|
|
5195
|
+
lastPi = base + m.index;
|
|
5196
|
+
check.pi();
|
|
5197
|
+
}
|
|
5198
|
+
}
|
|
5199
|
+
at += piece.length;
|
|
5200
|
+
tail = s.slice(-32);
|
|
5201
|
+
if (at < chunk.length) {
|
|
5202
|
+
const pause = ctx.step();
|
|
5203
|
+
if (pause) await pause;
|
|
5204
|
+
}
|
|
5205
|
+
}
|
|
5206
|
+
offset += chunk.length;
|
|
5207
|
+
const pause = ctx.step();
|
|
5208
|
+
if (pause) await pause;
|
|
5209
|
+
}
|
|
5210
|
+
check?.end();
|
|
5211
|
+
if (failure !== void 0) throw failure;
|
|
5212
|
+
} catch (err) {
|
|
5213
|
+
throw withPart(err, entry.name);
|
|
5214
|
+
}
|
|
5215
|
+
}
|
|
5216
|
+
/**
|
|
5217
|
+
* The checks of one XML part, parsed by read (through ctx.sniff) or not
|
|
5218
|
+
* (scanPart): its first bytes and its declaration (DeclarationReader), and
|
|
5219
|
+
* that no `<?xml` processing instruction stands anywhere but at the very start.
|
|
5220
|
+
* What it finds is reported once, through `fail`.
|
|
5221
|
+
*/
|
|
5222
|
+
var PartCheck = class {
|
|
5223
|
+
part;
|
|
5224
|
+
fail;
|
|
5225
|
+
reader;
|
|
5226
|
+
instructions = 0;
|
|
5227
|
+
failed = false;
|
|
5228
|
+
constructor(part, maxToken, fail) {
|
|
5229
|
+
this.part = part;
|
|
5230
|
+
this.fail = fail;
|
|
5231
|
+
this.reader = new DeclarationReader(part, maxToken);
|
|
5232
|
+
}
|
|
5233
|
+
feed(chunk) {
|
|
5234
|
+
if (!this.failed) this.report(() => this.reader.feed(chunk));
|
|
5235
|
+
}
|
|
5236
|
+
pi() {
|
|
5237
|
+
this.instructions++;
|
|
5238
|
+
}
|
|
5239
|
+
end() {
|
|
5240
|
+
if (!this.failed) this.report(() => this.reader.end());
|
|
5241
|
+
if (!this.failed && this.instructions > (this.reader.hasDeclaration ? 1 : 0)) this.report(() => misplacedDeclaration(this.part));
|
|
5242
|
+
}
|
|
5243
|
+
report(step) {
|
|
5244
|
+
let err;
|
|
5245
|
+
try {
|
|
5246
|
+
err = step();
|
|
5247
|
+
} catch (thrown) {
|
|
5248
|
+
err = withPart(thrown, this.part);
|
|
5249
|
+
}
|
|
5250
|
+
if (err !== void 0) {
|
|
5251
|
+
this.failed = true;
|
|
5252
|
+
this.fail(err);
|
|
5253
|
+
}
|
|
5254
|
+
}
|
|
5255
|
+
};
|
|
5256
|
+
/**
|
|
5257
|
+
* Reads the start of an XML part, however it is chunked: its first four bytes
|
|
5258
|
+
* (signatureEncoding), then, decoded as UTF-8 or UTF-16 by its byte order mark
|
|
5259
|
+
* or, without one, by `<?` in UTF-16, its XML declaration up to `?>`, bounded
|
|
5260
|
+
* like any token by maxXmlTokenLength, which must stand at the very start
|
|
5261
|
+
* (checkDeclaration). Linear: each chunk is decoded and searched once.
|
|
5262
|
+
*/
|
|
5263
|
+
var DeclarationReader = class {
|
|
5264
|
+
part;
|
|
5265
|
+
maxToken;
|
|
5266
|
+
hasDeclaration = false;
|
|
5267
|
+
pending = [];
|
|
5268
|
+
pendingLength = 0;
|
|
5269
|
+
decoder;
|
|
5270
|
+
text = "";
|
|
5271
|
+
searched = 0;
|
|
5272
|
+
done = false;
|
|
5273
|
+
constructor(part, maxToken) {
|
|
5274
|
+
this.part = part;
|
|
5275
|
+
this.maxToken = maxToken;
|
|
5276
|
+
}
|
|
5277
|
+
feed(chunk) {
|
|
5278
|
+
if (this.done) return void 0;
|
|
5279
|
+
if (!this.decoder) {
|
|
5280
|
+
this.pending.push(chunk);
|
|
5281
|
+
this.pendingLength += chunk.length;
|
|
5282
|
+
if (this.pendingLength < 4) return void 0;
|
|
5283
|
+
return this.start();
|
|
5284
|
+
}
|
|
5285
|
+
return this.more(this.decoder.decode(chunk, { stream: true }));
|
|
5286
|
+
}
|
|
5287
|
+
end() {
|
|
5288
|
+
if (this.done) return void 0;
|
|
5289
|
+
if (!this.decoder) {
|
|
5290
|
+
const found = this.start();
|
|
5291
|
+
if (found !== void 0 || this.done) return found;
|
|
5292
|
+
}
|
|
5293
|
+
return this.more(this.decoder.decode(), true);
|
|
5294
|
+
}
|
|
5295
|
+
start() {
|
|
5296
|
+
const head = new Uint8Array(this.pendingLength);
|
|
5297
|
+
let at = 0;
|
|
5298
|
+
for (const p of this.pending) {
|
|
5299
|
+
head.set(p, at);
|
|
5300
|
+
at += p.length;
|
|
5301
|
+
}
|
|
5302
|
+
this.pending = [];
|
|
5303
|
+
const sig = signatureEncoding(head);
|
|
5304
|
+
if (sig !== void 0) {
|
|
5305
|
+
this.done = true;
|
|
5306
|
+
return encodingError(this.part, sig);
|
|
5307
|
+
}
|
|
5308
|
+
const Ctor = globalThis.TextDecoder;
|
|
5309
|
+
if (head[0] === 60 && head[1] === 0 && head[2] === 63 && head[3] === 0) this.decoder = new Ctor("utf-16le");
|
|
5310
|
+
else if (head[0] === 0 && head[1] === 60 && head[2] === 0 && head[3] === 63) this.decoder = new Ctor("utf-16be");
|
|
5311
|
+
else this.decoder = newDecoder(head);
|
|
5312
|
+
return this.more(this.decoder.decode(head, { stream: true }));
|
|
5313
|
+
}
|
|
5314
|
+
more(text, final = false) {
|
|
5315
|
+
this.text += text;
|
|
5316
|
+
const t = this.text;
|
|
5317
|
+
if (t.length < 6 && !final && "<?xml".startsWith(t.slice(0, 5).toLowerCase())) return this.bound();
|
|
5318
|
+
if (!/^<\?xml[ \t\r\n?]/i.test(t)) {
|
|
5319
|
+
this.done = true;
|
|
5320
|
+
return;
|
|
5321
|
+
}
|
|
5322
|
+
this.hasDeclaration = true;
|
|
5323
|
+
const close = t.indexOf("?>", Math.max(0, this.searched - 1));
|
|
5324
|
+
if (close === -1) {
|
|
5325
|
+
this.searched = t.length;
|
|
5326
|
+
if (!final) return this.bound();
|
|
5327
|
+
this.done = true;
|
|
5328
|
+
return checkDeclaration(this.part, t);
|
|
5329
|
+
}
|
|
5330
|
+
this.done = true;
|
|
5331
|
+
if (close + 2 > this.maxToken) this.bound(true);
|
|
5332
|
+
return checkDeclaration(this.part, t.slice(0, close + 2));
|
|
5333
|
+
}
|
|
5334
|
+
/** A declaration longer than maxXmlTokenLength is refused, as the tokenizer refuses a token. */
|
|
5335
|
+
bound(over = false) {
|
|
5336
|
+
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: {
|
|
5337
|
+
limit: "maxXmlTokenLength",
|
|
5338
|
+
value: this.maxToken + 1,
|
|
5339
|
+
max: this.maxToken
|
|
5340
|
+
} });
|
|
5341
|
+
}
|
|
5342
|
+
};
|
|
3868
5343
|
// src/read.ts
|
|
3869
5344
|
/** Default limits (docs/api.md §5.2; the measurements behind each value are listed there). */
|
|
3870
5345
|
const DEFAULT_READ_LIMITS = DEFAULT_LIMITS;
|
|
@@ -3884,4 +5359,14 @@ async function read(input, options) {
|
|
|
3884
5359
|
warnings
|
|
3885
5360
|
};
|
|
3886
5361
|
}
|
|
3887
|
-
|
|
5362
|
+
/**
|
|
5363
|
+
* Checks an .xlsx, .xlsm, .xltx or .xltm file part by part without building
|
|
5364
|
+
* its cells: every part `read` parses is parsed with the same checks and
|
|
5365
|
+
* limits (every sheet to its end), every other part is inflated and its
|
|
5366
|
+
* bytes searched for a DOCTYPE, and XML parts must be UTF-8 or UTF-16. Throws what `read` throws for any file
|
|
5367
|
+
* `read` refuses under the same limits (docs/api.md §5.2.1).
|
|
5368
|
+
*/
|
|
5369
|
+
async function inspect(input, options) {
|
|
5370
|
+
return inspectImpl(await toBytes(input, "inspect"), options);
|
|
5371
|
+
}
|
|
5372
|
+
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 };
|