javascript-excel 2.3.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- 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-Bck8eW_D.js → csv-5jVhfM5l.js} +204 -33
- package/dist/{csv-f4P3fGs-.cjs → csv-BkVmMYQq.cjs} +204 -33
- package/dist/csv.cjs +1 -1
- package/dist/csv.d.cts +50 -3
- package/dist/csv.d.ts +50 -3
- package/dist/csv.js +1 -1
- package/dist/{dataset-DzoMeOG1.cjs → dataset-B4-SEdCn.cjs} +49 -5
- package/dist/{dataset-BLo9CwB-.js → dataset-Dh598YSG.js} +49 -5
- 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-2dgQM9E9.js → pipeline-1AVJbbqT.js} +39 -12
- package/dist/{pipeline-LCTU0Eg_.cjs → pipeline-C9zhwGAV.cjs} +39 -12
- package/dist/{pipeline-D1eAhqJu.d.cts → pipeline-CJWE3NWg.d.cts} +12 -5
- package/dist/{pipeline-Bh7FUyzW.d.ts → pipeline-DVgO1aGC.d.ts} +12 -5
- package/dist/{read-BnXzPjGc.js → read-B6tY0ooT.js} +2479 -869
- package/dist/{read-BYI7EVMo.cjs → read-Dgw9kMzh.cjs} +2489 -861
- package/dist/read.cjs +2 -1
- package/dist/read.d.cts +73 -3
- package/dist/read.d.ts +73 -3
- 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-DEsTp6rd.d.cts} +13 -2
- package/dist/{warnings-DhonqJ7A.d.cts → warnings-DEsTp6rd.d.ts} +13 -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-DKXhuvKR.cjs → write-Bgl_QfA8.cjs} +5 -5
- package/dist/{write-BaMv1Z7W.d.ts → write-BylKqAmD.d.ts} +1 -1
- package/dist/{write-BVXB2_2C.js → write-DFz-h8gz.js} +5 -5
- package/dist/{write-Izl2NG0Y.d.cts → write-JvXRv63d.d.cts} +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -91,7 +91,9 @@ const cell = exact.workbook.sheets[0]?.rows[0]?.[0];
|
|
|
91
91
|
console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30"
|
|
92
92
|
```
|
|
93
93
|
|
|
94
|
-
Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file.
|
|
94
|
+
Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part, including ActiveX controls, embedded files, customUI, web add-ins and parts no relationship reaches, wherever they sit in the package) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file.
|
|
95
|
+
|
|
96
|
+
To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens, searches the bytes of every one of them for `<!DOCTYPE` (ASCII-compatible, UTF-16 and UTF-32 forms, whatever the part's name; a declaration inside an XML comment or in an embedded file is refused too), and refuses XML parts whose byte order mark, first bytes or complete declaration show an encoding other than UTF-8 or UTF-16, or whose declaration is malformed or not at the very start. Set `limits.maxItems` (for example 100,000): it bounds the styles and defined names `inspect` still holds, and the shared-formula masters and reference records it keeps. See [docs/api.md §5.2.1](https://github.com/securedeveloper/javascript-excel/blob/main/docs/api.md#521-inspect-inspect-added-in-25).
|
|
95
97
|
|
|
96
98
|
## CSV
|
|
97
99
|
|
|
@@ -181,9 +183,9 @@ const bytes = await excel.write(workbook, { signal: controller.signal, onProgres
|
|
|
181
183
|
- **Reader:** `.xlsx`, `.xlsm`, `.xltx` and `.xltm`, including ISO 29500 Strict files.
|
|
182
184
|
- Reads values, shared, inline and rich strings, and formula text with cached values (shared formulas expanded).
|
|
183
185
|
- Styles come back as shared frozen objects. Merges, column widths and row heights, views and panes, print setup, hyperlinks, defined names and document properties are read too.
|
|
184
|
-
- **Untrusted files:** bounded by limits on size, zip entries, compression ratio, XML depth and token length, sheets, cells, shared strings and the length of one cell's text. A `DOCTYPE` is rejected, nothing is ever fetched or executed, and file content never becomes an object key.
|
|
186
|
+
- **Untrusted files:** bounded by limits on size, zip entries, compression ratio, XML depth and token length, sheets, cells, sheet width (`maxColumns`; set it low, for example 256, for untrusted files), shared strings and the length of one cell's text; a shared formula is expanded only from a master within Excel's 8,192-character formula limit. A `DOCTYPE` is rejected, nothing is ever fetched or executed, and file content never becomes an object key.
|
|
185
187
|
- **Rejected formats:** `.xls`, `.xlsb`, `.ods` and encrypted files throw `UNSUPPORTED_FORMAT`.
|
|
186
|
-
- **CSV:** RFC 4180 parsing with delimiter detection, BOM and CRLF/LF/CR handling, lenient or strict modes, and optional type inference. `readCsv` decodes bytes in any `TextDecoder` encoding. Serializing gives you quoting, a BOM for Excel, ISO dates and a formula-injection guard, which is on by default.
|
|
188
|
+
- **CSV:** RFC 4180 parsing with delimiter detection, BOM and CRLF/LF/CR handling, lenient or strict modes, and optional type inference. `readCsv` decodes bytes in any `TextDecoder` encoding, or with `encoding: 'auto'` as UTF-8 and then Windows-1252, and for uploads can refuse binary input (`rejectBinary`), cap the input size (`maxInputBytes`) and check a file without keeping its rows (`keepRows: false`). Serializing gives you quoting, a BOM for Excel, ISO dates and a formula-injection guard, which is on by default.
|
|
187
189
|
- **Datasets:** `fromDataset` and `fromDatasets` support `key`, `path` and function accessors, grouped headers, number formats, widths and a totals row. `toDataset` reads a sheet back into `{ columns, data }`.
|
|
188
190
|
- **DOM:** `fromTable` handles `colspan`/`rowspan` merges, `data-*` type hints and computed styles. `download()` needs no dependency, and the module is safe to import during SSR.
|
|
189
191
|
- **Worker:** progress, warnings and `AbortSignal` work across the boundary, and results are transferred, not copied.
|
|
@@ -1,31 +1,43 @@
|
|
|
1
|
-
import { a as LimitError, n as EnvironmentError, o as ValidationError, t as CsvError } from "./errors-
|
|
2
|
-
import { a as
|
|
1
|
+
import { a as LimitError, i as FormatError, n as EnvironmentError, o as ValidationError, t as CsvError } from "./errors-BQE62PFo.js";
|
|
2
|
+
import { a as checkBlobSize, i as checkMaxWarnings, o as inputTooLarge, r as WarningCap, s as toBytes, t as inferValue } from "./infer-DuSahY5i.js";
|
|
3
3
|
import { t as isoDate } from "./iso-date-CXnn-9mT.js";
|
|
4
4
|
// src/internal/csv/decode.ts
|
|
5
5
|
/**
|
|
6
6
|
* Bytes -> text for readCsv (docs/api.md §5.3): a UTF-8, UTF-16LE or UTF-16BE
|
|
7
7
|
* BOM wins; otherwise the `encoding` label applies (default utf-8). Invalid
|
|
8
8
|
* bytes become U+FFFD and the caller adds a CSV_INVALID_ENCODING warning.
|
|
9
|
+
*
|
|
10
|
+
* `encoding: 'auto'` (JSE-73): a BOM still wins; otherwise strict UTF-8, then
|
|
11
|
+
* strict Windows-1252 (the five bytes it leaves undefined are not text). Bytes
|
|
12
|
+
* that are neither throw FormatError CSV_INVALID_ENCODING.
|
|
13
|
+
*
|
|
14
|
+
* The binary check (`findBinary`) looks at the decoded text.
|
|
9
15
|
*/
|
|
10
|
-
function
|
|
16
|
+
function decoderCtor() {
|
|
11
17
|
const Ctor = globalThis.TextDecoder;
|
|
12
18
|
if (typeof Ctor !== "function") throw new EnvironmentError("ENVIRONMENT_UNSUPPORTED", "TextDecoder is not available in this runtime.", { details: { api: "TextDecoder" } });
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) {
|
|
17
|
-
encoding
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
encoding
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
encoding
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
19
|
+
return Ctor;
|
|
20
|
+
}
|
|
21
|
+
function sniffBom(bytes) {
|
|
22
|
+
if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) return {
|
|
23
|
+
encoding: "utf-8",
|
|
24
|
+
length: 3
|
|
25
|
+
};
|
|
26
|
+
if (bytes[0] === 255 && bytes[1] === 254) return {
|
|
27
|
+
encoding: "utf-16le",
|
|
28
|
+
length: 2
|
|
29
|
+
};
|
|
30
|
+
if (bytes[0] === 254 && bytes[1] === 255) return {
|
|
31
|
+
encoding: "utf-16be",
|
|
32
|
+
length: 2
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function decodeBytes(bytes, label) {
|
|
36
|
+
const Ctor = decoderCtor();
|
|
37
|
+
const sniffed = sniffBom(bytes);
|
|
38
|
+
const encoding = sniffed ? sniffed.encoding : label;
|
|
39
|
+
const bomBytes = sniffed ? sniffed.length : 0;
|
|
40
|
+
const body = sniffed ? bytes.subarray(bomBytes) : bytes;
|
|
29
41
|
let strict;
|
|
30
42
|
try {
|
|
31
43
|
strict = new Ctor(encoding, {
|
|
@@ -35,12 +47,15 @@ function decodeBytes(bytes, label) {
|
|
|
35
47
|
} catch {
|
|
36
48
|
throw new TypeError(`encoding ${JSON.stringify(label)} is not supported by this runtime's TextDecoder`);
|
|
37
49
|
}
|
|
50
|
+
const canonical = strict.encoding;
|
|
38
51
|
try {
|
|
39
52
|
return {
|
|
40
53
|
text: strict.decode(body),
|
|
41
|
-
bom,
|
|
54
|
+
bom: sniffed !== void 0,
|
|
42
55
|
encoding,
|
|
43
|
-
|
|
56
|
+
canonical,
|
|
57
|
+
invalid: false,
|
|
58
|
+
bomBytes
|
|
44
59
|
};
|
|
45
60
|
} catch {
|
|
46
61
|
return {
|
|
@@ -48,12 +63,108 @@ function decodeBytes(bytes, label) {
|
|
|
48
63
|
fatal: false,
|
|
49
64
|
ignoreBOM: true
|
|
50
65
|
}).decode(body),
|
|
51
|
-
bom,
|
|
66
|
+
bom: sniffed !== void 0,
|
|
52
67
|
encoding,
|
|
53
|
-
|
|
68
|
+
canonical,
|
|
69
|
+
invalid: true,
|
|
70
|
+
bomBytes
|
|
54
71
|
};
|
|
55
72
|
}
|
|
56
73
|
}
|
|
74
|
+
/** The bytes Windows-1252 leaves undefined (WHATWG's decoder maps them to C1 controls). */
|
|
75
|
+
function isUndefined1252(b) {
|
|
76
|
+
return b === 129 || b === 141 || b === 143 || b === 144 || b === 157;
|
|
77
|
+
}
|
|
78
|
+
/** `encoding: 'auto'`: BOM, else strict UTF-8, else strict Windows-1252, else CSV_INVALID_ENCODING. */
|
|
79
|
+
function decodeAuto(bytes) {
|
|
80
|
+
const Ctor = decoderCtor();
|
|
81
|
+
const sniffed = sniffBom(bytes);
|
|
82
|
+
if (sniffed) try {
|
|
83
|
+
return {
|
|
84
|
+
text: new Ctor(sniffed.encoding, {
|
|
85
|
+
fatal: true,
|
|
86
|
+
ignoreBOM: true
|
|
87
|
+
}).decode(bytes.subarray(sniffed.length)),
|
|
88
|
+
bom: true,
|
|
89
|
+
encoding: sniffed.encoding,
|
|
90
|
+
canonical: sniffed.encoding,
|
|
91
|
+
invalid: false,
|
|
92
|
+
bomBytes: sniffed.length
|
|
93
|
+
};
|
|
94
|
+
} catch {
|
|
95
|
+
throw new FormatError("CSV_INVALID_ENCODING", `The input starts with a ${sniffed.encoding} byte order mark but is not valid ${sniffed.encoding}.`, { details: { encodings: [sniffed.encoding] } });
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
return {
|
|
99
|
+
text: new Ctor("utf-8", {
|
|
100
|
+
fatal: true,
|
|
101
|
+
ignoreBOM: true
|
|
102
|
+
}).decode(bytes),
|
|
103
|
+
bom: false,
|
|
104
|
+
encoding: "utf-8",
|
|
105
|
+
canonical: "utf-8",
|
|
106
|
+
invalid: false,
|
|
107
|
+
bomBytes: 0
|
|
108
|
+
};
|
|
109
|
+
} catch {}
|
|
110
|
+
for (let i = 0; i < bytes.length; i++) if (isUndefined1252(bytes[i])) throw new FormatError("CSV_INVALID_ENCODING", `The input is neither valid UTF-8 nor valid Windows-1252 (byte ${i} is undefined in Windows-1252).`, { details: {
|
|
111
|
+
encodings: ["utf-8", "windows-1252"],
|
|
112
|
+
byteOffset: i
|
|
113
|
+
} });
|
|
114
|
+
return {
|
|
115
|
+
text: new Ctor("windows-1252", { ignoreBOM: true }).decode(bytes),
|
|
116
|
+
bom: false,
|
|
117
|
+
encoding: "windows-1252",
|
|
118
|
+
canonical: "windows-1252",
|
|
119
|
+
invalid: false,
|
|
120
|
+
bomBytes: 0
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* True for a character rejectBinary refuses: C0 controls other than TAB, LF, VT, FF,
|
|
125
|
+
* CR and ESC, and DEL; with `c1`, also U+0080..U+009F (Windows-1252 text, where only
|
|
126
|
+
* the undefined bytes decode to them).
|
|
127
|
+
*/
|
|
128
|
+
function isBinaryChar(c, c1) {
|
|
129
|
+
if (c < 32) return c < 9 || c > 13 && c !== 27;
|
|
130
|
+
if (c === 127) return true;
|
|
131
|
+
return c1 && c >= 128 && c <= 159;
|
|
132
|
+
}
|
|
133
|
+
/** Index of the first refused character in text[from, to), or -1. Linear; stops at the first hit. */
|
|
134
|
+
function findBinary(text, from, to, c1) {
|
|
135
|
+
const end = Math.min(to, text.length);
|
|
136
|
+
for (let i = from; i < end; i++) {
|
|
137
|
+
const c = text.charCodeAt(i);
|
|
138
|
+
if ((c < 32 || c >= 127) && isBinaryChar(c, c1)) return i;
|
|
139
|
+
}
|
|
140
|
+
return -1;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Byte offset in the input of character `index` of text decoded without
|
|
144
|
+
* replacements, for the encodings where that is exact; undefined otherwise.
|
|
145
|
+
*/
|
|
146
|
+
function byteOffsetOf(d, index) {
|
|
147
|
+
if (d.invalid) return void 0;
|
|
148
|
+
switch (d.canonical) {
|
|
149
|
+
case "utf-8": {
|
|
150
|
+
let n = d.bomBytes;
|
|
151
|
+
for (let i = 0; i < index; i++) {
|
|
152
|
+
const c = d.text.charCodeAt(i);
|
|
153
|
+
if (c < 128) n += 1;
|
|
154
|
+
else if (c < 2048) n += 2;
|
|
155
|
+
else if (c >= 55296 && c <= 56319) {
|
|
156
|
+
n += 4;
|
|
157
|
+
i++;
|
|
158
|
+
} else n += 3;
|
|
159
|
+
}
|
|
160
|
+
return n;
|
|
161
|
+
}
|
|
162
|
+
case "utf-16le":
|
|
163
|
+
case "utf-16be": return d.bomBytes + 2 * index;
|
|
164
|
+
case "windows-1252": return d.bomBytes + index;
|
|
165
|
+
default: return;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
57
168
|
// src/internal/csv/ref.ts
|
|
58
169
|
/** A1 reference for a zero-based row and column, e.g. (2, 1) -> 'B3'. */
|
|
59
170
|
function cellRef(row, col) {
|
|
@@ -78,6 +189,12 @@ function cellRef(row, col) {
|
|
|
78
189
|
const DEFAULT_MAX_FIELD_BYTES = 1048576;
|
|
79
190
|
/** Default `maxCellTextLength`: 1 Mi UTF-16 code units per field, as `DEFAULT_READ_LIMITS` for xlsx (JSE-58). */
|
|
80
191
|
const DEFAULT_MAX_CELL_TEXT_LENGTH = 1048576;
|
|
192
|
+
/**
|
|
193
|
+
* Default `maxColumns`: fields in one record (JSE-68). 1 Mi, 64 times Excel's 16,384 columns and
|
|
194
|
+
* beyond any spreadsheet's width, so it refuses no CSV file that 2.3 read; a record that wide is
|
|
195
|
+
* at least 1 MiB of text, so the rows parseCsv returns stay linear in the input.
|
|
196
|
+
*/
|
|
197
|
+
const DEFAULT_MAX_COLUMNS = 1048576;
|
|
81
198
|
/** Default `maxWarnings`: warnings kept per parse before the cap (internal/warning-cap.ts) applies. */
|
|
82
199
|
const MAX_WARNINGS = 1e3;
|
|
83
200
|
const CANDIDATES = [
|
|
@@ -93,6 +210,8 @@ const CR = 13;
|
|
|
93
210
|
/** The resumable state of one parse. */
|
|
94
211
|
var CsvParser = class {
|
|
95
212
|
rows = [];
|
|
213
|
+
/** Records read so far, kept or not. */
|
|
214
|
+
rowCount = 0;
|
|
96
215
|
warnings;
|
|
97
216
|
delimiter;
|
|
98
217
|
bom;
|
|
@@ -133,17 +252,17 @@ var CsvParser = class {
|
|
|
133
252
|
const startLine = this.line;
|
|
134
253
|
const fields = this.record();
|
|
135
254
|
if (fields.length === 0 && cfg.skipEmptyLines) continue;
|
|
136
|
-
if (this.
|
|
255
|
+
if (this.rowCount >= cfg.maxRows) {
|
|
137
256
|
this.warn("CSV_ROWS_TRUNCATED", `Stopped after maxRows (${cfg.maxRows}) rows; the rest of the input was not read.`, void 0, false);
|
|
138
257
|
this.finish();
|
|
139
258
|
return;
|
|
140
259
|
}
|
|
141
|
-
const rowIndex = this.
|
|
260
|
+
const rowIndex = this.rowCount++;
|
|
142
261
|
if (fields.length > 0) {
|
|
143
262
|
if (this.expectedFields === -1) this.expectedFields = fields.length;
|
|
144
263
|
else if (fields.length !== this.expectedFields) this.warn("CSV_FIELD_COUNT", `Row ${rowIndex + 1} (line ${startLine}) has ${fields.length} fields; the first row has ${this.expectedFields}.`, cellRef(rowIndex, 0));
|
|
145
264
|
}
|
|
146
|
-
this.rows.push(cfg.inferTypes ? fields.map((f) => f.quoted ? f.text : inferValue(f.text, cfg.dateZone)) : fields.map((f) => f.text));
|
|
265
|
+
if (cfg.keepRows) this.rows.push(cfg.inferTypes ? fields.map((f) => f.quoted ? f.text : inferValue(f.text, cfg.dateZone)) : fields.map((f) => f.text));
|
|
147
266
|
}
|
|
148
267
|
}
|
|
149
268
|
finish() {
|
|
@@ -167,7 +286,7 @@ var CsvParser = class {
|
|
|
167
286
|
}
|
|
168
287
|
for (;;) {
|
|
169
288
|
const col = fields.length;
|
|
170
|
-
const row = this.
|
|
289
|
+
const row = this.rowCount;
|
|
171
290
|
let value;
|
|
172
291
|
let quoted = false;
|
|
173
292
|
if (text.charCodeAt(this.pos) === this.quoteCode) {
|
|
@@ -175,6 +294,7 @@ var CsvParser = class {
|
|
|
175
294
|
value = this.quotedField(row, col);
|
|
176
295
|
} else value = this.plainField(row, col);
|
|
177
296
|
this.checkSize(value, row, col);
|
|
297
|
+
this.checkWidth(col, row);
|
|
178
298
|
fields.push({
|
|
179
299
|
text: value,
|
|
180
300
|
quoted
|
|
@@ -183,6 +303,7 @@ var CsvParser = class {
|
|
|
183
303
|
if (text.charCodeAt(this.pos) === this.delimCode) {
|
|
184
304
|
this.pos++;
|
|
185
305
|
if (this.pos >= len) {
|
|
306
|
+
this.checkWidth(fields.length, row);
|
|
186
307
|
fields.push({
|
|
187
308
|
text: "",
|
|
188
309
|
quoted: false
|
|
@@ -300,6 +421,20 @@ var CsvParser = class {
|
|
|
300
421
|
ref: cellRef(row, col)
|
|
301
422
|
} });
|
|
302
423
|
}
|
|
424
|
+
/**
|
|
425
|
+
* Field `col` (zero-based) of a record, before it is kept: refused past maxColumns (JSE-68). The
|
|
426
|
+
* record read only to find that maxRows was reached is dropped, so it is not checked.
|
|
427
|
+
*/
|
|
428
|
+
checkWidth(col, row) {
|
|
429
|
+
const max = this.cfg.maxColumns;
|
|
430
|
+
if (col < max || row >= this.cfg.maxRows) return;
|
|
431
|
+
throw new LimitError("LIMIT_EXCEEDED", `Row ${row + 1} has more than maxColumns (${max}) fields.`, { details: {
|
|
432
|
+
limit: "maxColumns",
|
|
433
|
+
value: col + 1,
|
|
434
|
+
max,
|
|
435
|
+
ref: cellRef(row, col)
|
|
436
|
+
} });
|
|
437
|
+
}
|
|
303
438
|
warn(code, message, ref, malformed = true) {
|
|
304
439
|
if (this.cfg.strict && malformed) throw new CsvError("CSV_MALFORMED", message, { details: {
|
|
305
440
|
warning: code,
|
|
@@ -338,7 +473,9 @@ function validateConfig(cfg) {
|
|
|
338
473
|
if (!(cfg.maxRows >= 0)) throw new TypeError("maxRows must be a non-negative number");
|
|
339
474
|
if (!(cfg.maxFieldBytes > 0)) throw new TypeError("maxFieldBytes must be a positive number");
|
|
340
475
|
if (!(cfg.maxCellTextLength > 0)) throw new TypeError("maxCellTextLength must be a positive number");
|
|
476
|
+
if (!(cfg.maxColumns > 0)) throw new TypeError("maxColumns must be a positive number");
|
|
341
477
|
checkMaxWarnings("maxWarnings", cfg.maxWarnings);
|
|
478
|
+
if (typeof cfg.keepRows !== "boolean") throw new TypeError("keepRows must be a boolean");
|
|
342
479
|
}
|
|
343
480
|
/** A delimiter or quote: exactly one UTF-16 code unit, not CR or LF. */
|
|
344
481
|
function checkSeparator(name, value) {
|
|
@@ -573,8 +710,10 @@ function parseConfig(options) {
|
|
|
573
710
|
maxRows: o.maxRows ?? Number.POSITIVE_INFINITY,
|
|
574
711
|
maxFieldBytes: o.maxFieldBytes ?? 1048576,
|
|
575
712
|
maxCellTextLength: o.maxCellTextLength === void 0 ? DEFAULT_MAX_CELL_TEXT_LENGTH : o.maxCellTextLength,
|
|
713
|
+
maxColumns: o.maxColumns === void 0 ? DEFAULT_MAX_COLUMNS : o.maxColumns,
|
|
576
714
|
dateZone: o.dateZone ?? "local",
|
|
577
|
-
maxWarnings: o.maxWarnings === void 0 ? MAX_WARNINGS : o.maxWarnings
|
|
715
|
+
maxWarnings: o.maxWarnings === void 0 ? MAX_WARNINGS : o.maxWarnings,
|
|
716
|
+
keepRows: o.keepRows ?? true
|
|
578
717
|
};
|
|
579
718
|
}
|
|
580
719
|
function checkMode(options) {
|
|
@@ -583,13 +722,14 @@ function checkMode(options) {
|
|
|
583
722
|
const zone = options?.dateZone;
|
|
584
723
|
if (zone !== void 0 && zone !== "local" && zone !== "utc") throw new TypeError(`dateZone must be 'local' or 'utc'`);
|
|
585
724
|
}
|
|
586
|
-
function result(p, bom, extra) {
|
|
725
|
+
function result(p, bom, extra, encoding) {
|
|
587
726
|
return {
|
|
588
727
|
rows: p.rows,
|
|
589
728
|
delimiter: p.delimiter,
|
|
590
729
|
newline: p.newline ?? "\r\n",
|
|
591
730
|
bom: bom || p.bom,
|
|
592
|
-
warnings: extra.length ? [...extra, ...p.warnings] : p.warnings
|
|
731
|
+
warnings: extra.length ? [...extra, ...p.warnings] : p.warnings,
|
|
732
|
+
...encoding === void 0 ? {} : { encoding }
|
|
593
733
|
};
|
|
594
734
|
}
|
|
595
735
|
/** Parses CSV text synchronously. */
|
|
@@ -606,16 +746,25 @@ function parseCsv(text, options) {
|
|
|
606
746
|
*/
|
|
607
747
|
async function readCsv(input, options) {
|
|
608
748
|
checkMode(options);
|
|
749
|
+
const rejectBinary = options?.rejectBinary ?? false;
|
|
750
|
+
if (typeof rejectBinary !== "boolean") throw new TypeError("rejectBinary must be a boolean");
|
|
751
|
+
const maxInputBytes = options?.maxInputBytes === void 0 ? Number.POSITIVE_INFINITY : options.maxInputBytes;
|
|
752
|
+
if (typeof maxInputBytes !== "number" || !(maxInputBytes > 0)) throw new TypeError("maxInputBytes must be a positive number");
|
|
753
|
+
const config = parseConfig(options);
|
|
609
754
|
const signal = options?.signal;
|
|
610
755
|
throwIfAborted(signal);
|
|
611
756
|
let text;
|
|
612
757
|
let bom = false;
|
|
758
|
+
let decoded;
|
|
613
759
|
const extra = [];
|
|
614
760
|
if (typeof input === "string") text = input;
|
|
615
761
|
else {
|
|
762
|
+
checkBlobSize(input, maxInputBytes);
|
|
616
763
|
const bytes = await toBytes(input, "readCsv", "a string, ");
|
|
764
|
+
if (bytes.length > maxInputBytes) throw inputTooLarge(bytes.length, maxInputBytes);
|
|
617
765
|
throwIfAborted(signal);
|
|
618
|
-
const
|
|
766
|
+
const label = options?.encoding ?? "utf-8";
|
|
767
|
+
decoded = label === "auto" ? decodeAuto(bytes) : decodeBytes(bytes, label);
|
|
619
768
|
text = decoded.text;
|
|
620
769
|
bom = decoded.bom;
|
|
621
770
|
if (decoded.invalid) {
|
|
@@ -630,7 +779,18 @@ async function readCsv(input, options) {
|
|
|
630
779
|
});
|
|
631
780
|
}
|
|
632
781
|
}
|
|
633
|
-
|
|
782
|
+
if (rejectBinary) {
|
|
783
|
+
const c1 = decoded?.canonical === "windows-1252";
|
|
784
|
+
for (let from = 0; from < text.length; from += CHUNK_CHARS) {
|
|
785
|
+
const at = findBinary(text, from, from + CHUNK_CHARS, c1);
|
|
786
|
+
if (at >= 0) throw binaryInput(text, at, decoded);
|
|
787
|
+
if (from + CHUNK_CHARS < text.length) {
|
|
788
|
+
await yieldToEventLoop();
|
|
789
|
+
throwIfAborted(signal);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
const p = new CsvParser(text, config);
|
|
634
794
|
while (!p.done) {
|
|
635
795
|
p.run(p.position + CHUNK_CHARS);
|
|
636
796
|
if (!p.done) {
|
|
@@ -638,7 +798,18 @@ async function readCsv(input, options) {
|
|
|
638
798
|
throwIfAborted(signal);
|
|
639
799
|
}
|
|
640
800
|
}
|
|
641
|
-
return result(p, bom, extra);
|
|
801
|
+
return result(p, bom, extra, decoded?.canonical);
|
|
802
|
+
}
|
|
803
|
+
function binaryInput(text, offset, decoded) {
|
|
804
|
+
const codePoint = text.charCodeAt(offset);
|
|
805
|
+
const byteOffset = decoded === void 0 ? void 0 : byteOffsetOf(decoded, offset);
|
|
806
|
+
const hex = codePoint.toString(16).toUpperCase().padStart(4, "0");
|
|
807
|
+
return new FormatError("CSV_BINARY_INPUT", `The input is not text: control character U+${hex} at character ${offset}${byteOffset === void 0 ? "" : ` (byte ${byteOffset})`}.`, { details: {
|
|
808
|
+
offset,
|
|
809
|
+
...byteOffset === void 0 ? {} : { byteOffset },
|
|
810
|
+
codePoint,
|
|
811
|
+
...decoded === void 0 ? {} : { encoding: decoded.canonical }
|
|
812
|
+
} });
|
|
642
813
|
}
|
|
643
814
|
/** Serializes a sheet (A1 to its last used cell) or an array of rows to CSV text. */
|
|
644
815
|
function toCsv(source, options) {
|