javascript-excel 1.0.3 → 2.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +50 -2
  2. package/dist/auto-width-2oBzjeNG.d.cts +11 -0
  3. package/dist/auto-width-CT-BihTW.d.ts +10 -0
  4. package/dist/csv.cjs +623 -0
  5. package/dist/csv.d.cts +89 -0
  6. package/dist/csv.d.ts +89 -0
  7. package/dist/csv.js +618 -0
  8. package/dist/dom.cjs +464 -0
  9. package/dist/dom.d.cts +78 -0
  10. package/dist/dom.d.ts +78 -0
  11. package/dist/dom.js +461 -0
  12. package/dist/errors-CvGlfw0E.js +28 -0
  13. package/dist/errors-DOPrrGS4.cjs +69 -0
  14. package/dist/index.cjs +1424 -0
  15. package/dist/index.d.cts +140 -0
  16. package/dist/index.d.ts +140 -0
  17. package/dist/index.js +1397 -0
  18. package/dist/infer-BR-J9BZa.js +88 -0
  19. package/dist/infer-D9EC9vJ-.cjs +105 -0
  20. package/dist/iso-date-B22IvwL1.js +21 -0
  21. package/dist/iso-date-BSUsPSWO.cjs +26 -0
  22. package/dist/numfmt-B-TlCgr7.cjs +476 -0
  23. package/dist/numfmt-DEm0sYBJ.js +399 -0
  24. package/dist/read.cjs +2899 -0
  25. package/dist/read.d.cts +88 -0
  26. package/dist/read.d.ts +88 -0
  27. package/dist/read.js +2895 -0
  28. package/dist/sheet-names-CDsVK15c.js +831 -0
  29. package/dist/sheet-names-Cm-IhbBk.cjs +1004 -0
  30. package/dist/signal-Dz0ZYe6d.d.cts +13 -0
  31. package/dist/signal-Dz0ZYe6d.d.ts +13 -0
  32. package/dist/warnings-C_12PT4t.d.cts +410 -0
  33. package/dist/warnings-DXJKe1lx.d.ts +410 -0
  34. package/dist/worker.cjs +11 -0
  35. package/dist/worker.d.cts +8 -0
  36. package/dist/worker.d.ts +8 -0
  37. package/dist/worker.js +10 -0
  38. package/dist/write-C5JgeIar.d.cts +29 -0
  39. package/dist/write-CYpLGuzl.d.ts +29 -0
  40. package/package.json +67 -51
  41. package/.babelrc +0 -10
  42. package/.circleci/config.yml +0 -39
  43. package/lib/index.d.ts +0 -1
  44. package/lib/index.js +0 -22
  45. package/lib/javascript-excel.js +0 -17703
  46. package/src/index.tsx +0 -11
  47. package/test/unit/sample.spec.js +0 -5
  48. package/tsconfig.json +0 -54
  49. package/webpack.config.js +0 -19
  50. /package/{LICENSE.md → LICENSE} +0 -0
package/README.md CHANGED
@@ -1,2 +1,50 @@
1
- # JavaScript-Excel
2
- A lightweight library to build excel with power of JavaScript
1
+ # javascript-excel
2
+
3
+ > **2.0 is a from-scratch rewrite and is in progress.** The prerelease writes complete `.xlsx` files (cells, styles and sheet features), reads `.xlsx` files (`javascript-excel/read`), parses and serializes CSV (`javascript-excel/csv`), and turns HTML tables into sheets and downloads files (`javascript-excel/dom`). The Web Worker entry (`javascript-excel/worker`) is still to come: it is a placeholder in this prerelease. The API may change before 2.0.0.
4
+ >
5
+ > The last 1.x release is `javascript-excel@1.0.3`. Keep using it until 2.0 is released.
6
+
7
+ ```ts
8
+ import { toUint8Array } from "javascript-excel";
9
+
10
+ const bytes = await toUint8Array({
11
+ sheets: [
12
+ {
13
+ name: "Report",
14
+ rows: [
15
+ [{ value: "Item", style: { font: { bold: true }, fill: "DDEBF7" } }, "Qty", "Price"],
16
+ ["Pens", 10, { value: 1.5, style: { numFmt: "#,##0.00" } }],
17
+ ["Total", { formula: "SUM(B2:B2)", value: 10 }, new Date()],
18
+ ],
19
+ },
20
+ ],
21
+ });
22
+ ```
23
+
24
+ `toBlob()` returns the same file as a `Blob` for browser downloads.
25
+
26
+ **Written today:** strings (shared or inline), numbers, booleans, dates (1900 and 1904 systems), error values, rich text, formulas with cached values, array formulas, styled empty cells. The full style model: fonts, all fill patterns and gradients, all border styles with a colour per side, alignment (rotation, indent, reading order), protection flags, and built-in and custom number formats. Styles are deduplicated. Sheet order, names, visibility, the active sheet, the default font and document properties are written too.
27
+
28
+ **Sheet features:** column widths (characters, pixels or `'auto'`) and column styles, row heights and row styles, hidden rows and columns, outline levels, merges, autofilter, freeze panes, right-to-left sheets, zoom and selection, tab colours, default sizes, hyperlinks (external URLs limited to `http`, `https` and `mailto` unless you allow more with `hyperlinkSchemes`; internal locations), defined names, and print setup (orientation, paper size, fit to page, scale, margins, print area and titles, headers and footers).
29
+
30
+ Every writable field of the model is written; nothing is dropped silently. (`theme`, `indexedColors` and `dimension` are filled in by the reader and ignored on write.) Input that cannot be written faithfully throws a typed `ValidationError`.
31
+
32
+ **HTML tables** (`javascript-excel/dom`):
33
+
34
+ ```ts
35
+ import { toBlob } from "javascript-excel";
36
+ import { download, fromTable } from "javascript-excel/dom";
37
+
38
+ const sheet = fromTable(document.querySelector("table")!, { styles: "computed", freezeHeader: true, autoWidth: true });
39
+ download(await toBlob({ sheets: [sheet] }), "report.xlsx");
40
+ ```
41
+
42
+ `fromTable` reads `<thead>`, `<tbody>` and `<tfoot>`. It turns `colspan`/`rowspan` into merges, understands `data-type`, `data-value` and `data-numfmt` hints, skips hidden and `data-export-ignore` rows, keeps links, and with `styles: "computed"` maps bold, italic, underline, colour, background and alignment. `download` saves bytes, Blobs or strings through a temporary link without any dependency. Importing the module is safe during server-side rendering.
43
+
44
+ Runs on Node.js 22+ and in browsers with `CompressionStream('deflate-raw')`. Types are tested with TypeScript 5.0–7, with `moduleResolution` set to `node16`, `nodenext` or `bundler`.
45
+
46
+ Source, status and issues: https://github.com/securedeveloper/javascript-excel
47
+
48
+ ## License
49
+
50
+ MIT
@@ -0,0 +1,11 @@
1
+ import "./warnings-C_12PT4t.cjs";
2
+ /** Bounds for estimated column widths, in characters. */
3
+ interface AutoWidthOptions {
4
+ /** Default 8.43 (Excel's default width). */
5
+ min?: number | undefined;
6
+ /** Default 60 (a readability choice, not a measurement); at most 255. */
7
+ max?: number | undefined;
8
+ /** Rows measured from the top; default all. */
9
+ sampleRows?: number | undefined;
10
+ }
11
+ export { AutoWidthOptions as t };
@@ -0,0 +1,10 @@
1
+ /** Bounds for estimated column widths, in characters. */
2
+ interface AutoWidthOptions {
3
+ /** Default 8.43 (Excel's default width). */
4
+ min?: number | undefined;
5
+ /** Default 60 (a readability choice, not a measurement); at most 255. */
6
+ max?: number | undefined;
7
+ /** Rows measured from the top; default all. */
8
+ sampleRows?: number | undefined;
9
+ }
10
+ export { AutoWidthOptions as t };
package/dist/csv.cjs ADDED
@@ -0,0 +1,623 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_errors = require("./errors-DOPrrGS4.cjs");
3
+ const require_infer = require("./infer-D9EC9vJ-.cjs");
4
+ const require_iso_date = require("./iso-date-BSUsPSWO.cjs");
5
+ // src/internal/csv/decode.ts
6
+ /**
7
+ * Bytes -> text for readCsv (docs/api.md §5.3): a UTF-8, UTF-16LE or UTF-16BE
8
+ * BOM wins; otherwise the `encoding` label applies (default utf-8). Invalid
9
+ * bytes become U+FFFD and the caller adds a CSV_INVALID_ENCODING warning.
10
+ */
11
+ function decodeBytes(bytes, label) {
12
+ const Ctor = globalThis.TextDecoder;
13
+ if (typeof Ctor !== "function") throw new require_errors.EnvironmentError("ENVIRONMENT_UNSUPPORTED", "TextDecoder is not available in this runtime.", { details: { api: "TextDecoder" } });
14
+ let encoding = label;
15
+ let body = bytes;
16
+ let bom = false;
17
+ if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) {
18
+ encoding = "utf-8";
19
+ body = bytes.subarray(3);
20
+ bom = true;
21
+ } else if (bytes[0] === 255 && bytes[1] === 254) {
22
+ encoding = "utf-16le";
23
+ body = bytes.subarray(2);
24
+ bom = true;
25
+ } else if (bytes[0] === 254 && bytes[1] === 255) {
26
+ encoding = "utf-16be";
27
+ body = bytes.subarray(2);
28
+ bom = true;
29
+ }
30
+ let strict;
31
+ try {
32
+ strict = new Ctor(encoding, {
33
+ fatal: true,
34
+ ignoreBOM: true
35
+ });
36
+ } catch {
37
+ throw new TypeError(`encoding ${JSON.stringify(label)} is not supported by this runtime's TextDecoder`);
38
+ }
39
+ try {
40
+ return {
41
+ text: strict.decode(body),
42
+ bom,
43
+ encoding,
44
+ invalid: false
45
+ };
46
+ } catch {
47
+ return {
48
+ text: new Ctor(encoding, {
49
+ fatal: false,
50
+ ignoreBOM: true
51
+ }).decode(body),
52
+ bom,
53
+ encoding,
54
+ invalid: true
55
+ };
56
+ }
57
+ }
58
+ // src/internal/csv/ref.ts
59
+ /** A1 reference for a zero-based row and column, e.g. (2, 1) -> 'B3'. */
60
+ function cellRef(row, col) {
61
+ let name = "";
62
+ let n = col + 1;
63
+ while (n > 0) {
64
+ const r = (n - 1) % 26;
65
+ name = String.fromCharCode(65 + r) + name;
66
+ n = Math.floor((n - 1) / 26);
67
+ }
68
+ return `${name}${row + 1}`;
69
+ }
70
+ /** Warnings kept per parse; the rest are summarised by one WARNINGS_TRUNCATED. */
71
+ const MAX_WARNINGS = 1e3;
72
+ const CANDIDATES = [
73
+ ",",
74
+ ";",
75
+ " ",
76
+ "|"
77
+ ];
78
+ const SNIFF_RECORDS = 20;
79
+ const SNIFF_CHARS = 65536;
80
+ const LF = 10;
81
+ const CR = 13;
82
+ /** The resumable state of one parse. */
83
+ var CsvParser = class {
84
+ rows = [];
85
+ warnings = [];
86
+ delimiter;
87
+ bom;
88
+ newline;
89
+ done = false;
90
+ text;
91
+ cfg;
92
+ delimCode;
93
+ quoteCode;
94
+ pos;
95
+ line = 1;
96
+ expectedFields = -1;
97
+ dropped = 0;
98
+ constructor(text, cfg) {
99
+ validateConfig(cfg);
100
+ this.bom = text.charCodeAt(0) === 65279;
101
+ this.text = text;
102
+ this.pos = this.bom ? 1 : 0;
103
+ this.cfg = cfg;
104
+ this.delimiter = cfg.delimiter === "auto" ? detectDelimiter(text, this.pos, cfg.quote) : cfg.delimiter;
105
+ this.delimCode = this.delimiter.charCodeAt(0);
106
+ this.quoteCode = cfg.quote.charCodeAt(0);
107
+ }
108
+ /** Characters consumed so far (for chunking). */
109
+ get position() {
110
+ return this.pos;
111
+ }
112
+ /** Parses records until `pos` passes `untilPos` or the input ends. */
113
+ run(untilPos = Number.POSITIVE_INFINITY) {
114
+ const { text, cfg } = this;
115
+ while (!this.done && this.pos < untilPos) {
116
+ if (this.pos >= text.length) {
117
+ this.finish();
118
+ return;
119
+ }
120
+ const startLine = this.line;
121
+ const fields = this.record();
122
+ if (fields.length === 0 && cfg.skipEmptyLines) continue;
123
+ if (this.rows.length >= cfg.maxRows) {
124
+ this.warn("CSV_ROWS_TRUNCATED", `Stopped after maxRows (${cfg.maxRows}) rows; the rest of the input was not read.`, void 0, false);
125
+ this.finish();
126
+ return;
127
+ }
128
+ const rowIndex = this.rows.length;
129
+ if (fields.length > 0) {
130
+ if (this.expectedFields === -1) this.expectedFields = fields.length;
131
+ 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));
132
+ }
133
+ this.rows.push(cfg.inferTypes ? fields.map((f) => f.quoted ? f.text : require_infer.inferValue(f.text, cfg.dateZone)) : fields.map((f) => f.text));
134
+ }
135
+ }
136
+ finish() {
137
+ this.done = true;
138
+ if (this.dropped > 0) this.warnings.push({
139
+ code: "WARNINGS_TRUNCATED",
140
+ message: `${this.dropped} more warning(s) were not recorded (limit ${MAX_WARNINGS}).`
141
+ });
142
+ }
143
+ /** Reads one record starting at `pos`. A blank line gives zero fields. */
144
+ record() {
145
+ const { text } = this;
146
+ const len = text.length;
147
+ const fields = [];
148
+ const first = text.charCodeAt(this.pos);
149
+ if (first === LF || first === CR) {
150
+ this.newlineAt(this.pos);
151
+ return fields;
152
+ }
153
+ for (;;) {
154
+ const col = fields.length;
155
+ const row = this.rows.length;
156
+ let value;
157
+ let quoted = false;
158
+ if (text.charCodeAt(this.pos) === this.quoteCode) {
159
+ quoted = true;
160
+ value = this.quotedField(row, col);
161
+ } else value = this.plainField(row, col);
162
+ this.checkSize(value, row, col);
163
+ fields.push({
164
+ text: value,
165
+ quoted
166
+ });
167
+ if (this.pos >= len) return fields;
168
+ if (text.charCodeAt(this.pos) === this.delimCode) {
169
+ this.pos++;
170
+ if (this.pos >= len) {
171
+ fields.push({
172
+ text: "",
173
+ quoted: false
174
+ });
175
+ return fields;
176
+ }
177
+ continue;
178
+ }
179
+ this.newlineAt(this.pos);
180
+ return fields;
181
+ }
182
+ }
183
+ /** Consumes the newline at `i` and records the first style seen. */
184
+ newlineAt(i) {
185
+ const { text } = this;
186
+ let nl;
187
+ if (text.charCodeAt(i) === CR) {
188
+ if (text.charCodeAt(i + 1) === LF) {
189
+ nl = "\r\n";
190
+ this.pos = i + 2;
191
+ } else {
192
+ nl = "\r";
193
+ this.pos = i + 1;
194
+ }
195
+ } else {
196
+ nl = "\n";
197
+ this.pos = i + 1;
198
+ }
199
+ this.newline ??= nl;
200
+ this.line++;
201
+ }
202
+ plainField(row, col) {
203
+ const { text, delimCode, quoteCode } = this;
204
+ const len = text.length;
205
+ const start = this.pos;
206
+ let i = start;
207
+ let strayReported = false;
208
+ for (; i < len; i++) {
209
+ const c = text.charCodeAt(i);
210
+ if (c === delimCode || c === LF || c === CR) break;
211
+ if (c === quoteCode && !strayReported) {
212
+ strayReported = true;
213
+ this.warn("CSV_STRAY_QUOTE", `Quote character inside an unquoted field at row ${row + 1}, line ${this.line}; kept as text.`, cellRef(row, col));
214
+ }
215
+ }
216
+ this.pos = i;
217
+ return text.slice(start, i);
218
+ }
219
+ quotedField(row, col) {
220
+ const { text, delimCode, quoteCode } = this;
221
+ const len = text.length;
222
+ const startLine = this.line;
223
+ let i = this.pos + 1;
224
+ let out = "";
225
+ let chunk = i;
226
+ for (;;) {
227
+ if (i >= len) {
228
+ out += text.slice(chunk, i);
229
+ this.pos = i;
230
+ this.warn("CSV_UNTERMINATED_QUOTE", `Quoted field at row ${row + 1}, line ${startLine} is not closed; it runs to the end of the input.`, cellRef(row, col));
231
+ return out;
232
+ }
233
+ const c = text.charCodeAt(i);
234
+ if (c === quoteCode) {
235
+ if (text.charCodeAt(i + 1) === quoteCode) {
236
+ out += text.slice(chunk, i + 1);
237
+ i += 2;
238
+ chunk = i;
239
+ continue;
240
+ }
241
+ out += text.slice(chunk, i);
242
+ i++;
243
+ const next = i < len ? text.charCodeAt(i) : -1;
244
+ if (next === -1 || next === delimCode || next === LF || next === CR) {
245
+ this.pos = i;
246
+ return out;
247
+ }
248
+ this.warn("CSV_STRAY_QUOTE", `Text after the closing quote at row ${row + 1}, line ${this.line}; kept as part of the field.`, cellRef(row, col));
249
+ this.pos = i;
250
+ return out + this.plainFieldNoWarn();
251
+ }
252
+ if (c === LF) this.line++;
253
+ else if (c === CR && text.charCodeAt(i + 1) !== LF) this.line++;
254
+ i++;
255
+ }
256
+ }
257
+ plainFieldNoWarn() {
258
+ const { text, delimCode } = this;
259
+ const len = text.length;
260
+ const start = this.pos;
261
+ let i = start;
262
+ for (; i < len; i++) {
263
+ const c = text.charCodeAt(i);
264
+ if (c === delimCode || c === LF || c === CR) break;
265
+ }
266
+ this.pos = i;
267
+ return text.slice(start, i);
268
+ }
269
+ checkSize(value, row, col) {
270
+ const max = this.cfg.maxFieldBytes;
271
+ if (value.length * 3 <= max) return;
272
+ const bytes = utf8Length(value);
273
+ if (bytes > max) throw new require_errors.LimitError("LIMIT_EXCEEDED", `Field at row ${row + 1} is ${bytes} bytes; maxFieldBytes is ${max}.`, { details: {
274
+ limit: "maxFieldBytes",
275
+ value: bytes,
276
+ max,
277
+ ref: cellRef(row, col)
278
+ } });
279
+ }
280
+ warn(code, message, ref, malformed = true) {
281
+ if (this.cfg.strict && malformed) throw new require_errors.CsvError("CSV_MALFORMED", message, { details: {
282
+ warning: code,
283
+ ...ref === void 0 ? {} : { ref },
284
+ line: this.line
285
+ } });
286
+ if (this.warnings.length >= 1e3) {
287
+ this.dropped++;
288
+ return;
289
+ }
290
+ this.warnings.push(ref === void 0 ? {
291
+ code,
292
+ message
293
+ } : {
294
+ code,
295
+ message,
296
+ ref
297
+ });
298
+ }
299
+ };
300
+ /** UTF-8 length of a string without encoding it. */
301
+ function utf8Length(s) {
302
+ let n = 0;
303
+ for (let i = 0; i < s.length; i++) {
304
+ const c = s.charCodeAt(i);
305
+ if (c < 128) n += 1;
306
+ else if (c < 2048) n += 2;
307
+ else if (c >= 55296 && c <= 56319 && i + 1 < s.length && (s.charCodeAt(i + 1) & 64512) === 56320) {
308
+ n += 4;
309
+ i++;
310
+ } else n += 3;
311
+ }
312
+ return n;
313
+ }
314
+ function validateConfig(cfg) {
315
+ if (cfg.delimiter !== "auto") checkSeparator("delimiter", cfg.delimiter);
316
+ checkSeparator("quote", cfg.quote);
317
+ if (cfg.delimiter === cfg.quote) throw new TypeError("delimiter and quote must differ");
318
+ if (!(cfg.maxRows >= 0)) throw new TypeError("maxRows must be a non-negative number");
319
+ if (!(cfg.maxFieldBytes > 0)) throw new TypeError("maxFieldBytes must be a positive number");
320
+ }
321
+ /** A delimiter or quote: exactly one UTF-16 code unit, not CR or LF. */
322
+ function checkSeparator(name, value) {
323
+ if (typeof value !== "string" || value.length !== 1 || value === "\r" || value === "\n") throw new TypeError(`${name} must be a single character other than CR or LF, got ${JSON.stringify(value)}`);
324
+ }
325
+ /**
326
+ * Picks the delimiter from `, ; TAB |` by field-count consistency over the
327
+ * first records: the candidate whose most common field count (> 1) covers the
328
+ * most records wins; ties go to the earlier candidate. Falls back to ','.
329
+ */
330
+ function detectDelimiter(text, start, quote) {
331
+ const sample = text.slice(start, start + SNIFF_CHARS);
332
+ let best = ",";
333
+ let bestScore = 0;
334
+ for (const d of CANDIDATES) {
335
+ const counts = sniffCounts(sample, d, quote.charCodeAt(0));
336
+ const freq = /* @__PURE__ */ new Map();
337
+ for (const n of counts) if (n > 1) freq.set(n, (freq.get(n) ?? 0) + 1);
338
+ let score = 0;
339
+ for (const v of freq.values()) if (v > score) score = v;
340
+ if (score > bestScore) {
341
+ best = d;
342
+ bestScore = score;
343
+ }
344
+ }
345
+ return best;
346
+ }
347
+ /** Field counts of the first records, quote-aware. Blank lines are skipped. */
348
+ function sniffCounts(sample, delim, quoteCode) {
349
+ const delimCode = delim.charCodeAt(0);
350
+ const counts = [];
351
+ let fields = 1;
352
+ let inQuotes = false;
353
+ let empty = true;
354
+ for (let i = 0; i < sample.length && counts.length < SNIFF_RECORDS; i++) {
355
+ const c = sample.charCodeAt(i);
356
+ if (inQuotes) {
357
+ if (c === quoteCode) {
358
+ if (sample.charCodeAt(i + 1) === quoteCode) i++;
359
+ else inQuotes = false;
360
+ }
361
+ continue;
362
+ }
363
+ if (c === quoteCode) {
364
+ inQuotes = true;
365
+ empty = false;
366
+ } else if (c === delimCode) {
367
+ fields++;
368
+ empty = false;
369
+ } else if (c === LF || c === CR) {
370
+ if (!empty) counts.push(fields);
371
+ if (c === CR && sample.charCodeAt(i + 1) === LF) i++;
372
+ fields = 1;
373
+ empty = true;
374
+ } else empty = false;
375
+ }
376
+ if (!empty && counts.length < SNIFF_RECORDS) counts.push(fields);
377
+ return counts;
378
+ }
379
+ // src/internal/csv/write.ts
380
+ /**
381
+ * CSV serializer (docs/api.md §5.3).
382
+ *
383
+ * Values: numbers as `String(n)`, booleans as TRUE/FALSE, dates as ISO 8601,
384
+ * errors as their code, rich text as plain text, empty cells as empty fields.
385
+ * The formula-injection guard prefixes `'` to string fields starting with
386
+ * = + - @ TAB or CR; numbers, booleans and dates are never prefixed.
387
+ */
388
+ function validateWriteConfig(cfg) {
389
+ checkSeparator("delimiter", cfg.delimiter);
390
+ if (cfg.delimiter === "\"") throw new TypeError("delimiter must not be the quote character (\")");
391
+ if (cfg.newline !== "\r\n" && cfg.newline !== "\n") throw new TypeError(`newline must be "\\r\\n" or "\\n"`);
392
+ if (cfg.dates !== "iso" && typeof cfg.dates !== "function") throw new TypeError(`dates must be 'iso' or a function`);
393
+ if (cfg.dateZone !== "local" && cfg.dateZone !== "utc") throw new TypeError(`dateZone must be 'local' or 'utc'`);
394
+ if (cfg.formulas !== "value" && cfg.formulas !== "formula") throw new TypeError(`formulas must be 'value' or 'formula'`);
395
+ }
396
+ /** Rows to write: a Sheet from A1 to its last used cell (rectangular), or an array as given. */
397
+ function sourceRows(source) {
398
+ if (Array.isArray(source)) return {
399
+ rows: source,
400
+ width: 0
401
+ };
402
+ if (source === null || typeof source !== "object" || !Array.isArray(source.rows)) throw new TypeError("toCsv: source must be a Sheet or an array of rows");
403
+ let lastRow = -1;
404
+ let width = 0;
405
+ source.rows.forEach((row, r) => {
406
+ if (!row) return;
407
+ let last = -1;
408
+ row.forEach((cell, c) => {
409
+ if (isUsed(cell)) last = c;
410
+ });
411
+ if (last >= 0) {
412
+ lastRow = r;
413
+ if (last + 1 > width) width = last + 1;
414
+ }
415
+ });
416
+ return {
417
+ rows: source.rows.slice(0, lastRow + 1),
418
+ width
419
+ };
420
+ }
421
+ function isUsed(cell) {
422
+ if (cell === null || cell === void 0) return false;
423
+ if (isCell(cell)) return cell.value !== null && cell.value !== void 0 || cell.formula !== void 0 && cell.formula !== "";
424
+ return true;
425
+ }
426
+ /** Serializes rows to CSV text (no BOM). */
427
+ function serialize(source, cfg) {
428
+ validateWriteConfig(cfg);
429
+ const { rows, width } = sourceRows(source);
430
+ const out = [];
431
+ const n = rows.length;
432
+ for (let r = 0; r < n; r++) {
433
+ const row = rows[r];
434
+ const cols = Math.max(width, row ? row.length : 0);
435
+ const fields = new Array(cols);
436
+ for (let c = 0; c < cols; c++) fields[c] = quoteField(fieldText(row ? row[c] : void 0, r, c, cfg), cfg);
437
+ out.push(fields.join(cfg.delimiter));
438
+ }
439
+ if (out.length === 0) return "";
440
+ return out.join(cfg.newline) + cfg.newline;
441
+ }
442
+ function quoteField(s, cfg) {
443
+ if (cfg.quoteAll || needsQuotes(s, cfg.delimiter)) return `"${s.replaceAll("\"", "\"\"")}"`;
444
+ return s;
445
+ }
446
+ function needsQuotes(s, delimiter) {
447
+ const d = delimiter.charCodeAt(0);
448
+ for (let i = 0; i < s.length; i++) {
449
+ const c = s.charCodeAt(i);
450
+ if (c === d || c === 34 || c === 10 || c === 13) return true;
451
+ }
452
+ return false;
453
+ }
454
+ function fieldText(cell, r, c, cfg) {
455
+ if (cell === null || cell === void 0) return "";
456
+ if (isCell(cell)) {
457
+ if (cfg.formulas === "formula" && cell.formula !== void 0 && cell.formula !== "") return guard(cell.formula.startsWith("=") ? cell.formula : `=${cell.formula}`, cfg);
458
+ const v = cell.value;
459
+ return v === null || v === void 0 ? "" : valueText(v, r, c, cfg);
460
+ }
461
+ return valueText(cell, r, c, cfg);
462
+ }
463
+ function valueText(v, r, c, cfg) {
464
+ switch (typeof v) {
465
+ case "string": return guard(v, cfg);
466
+ case "number":
467
+ if (!Number.isFinite(v)) throw new require_errors.ValidationError("INVALID_NUMBER", `Cell ${cellRef(r, c)} holds ${String(v)}, which CSV cannot represent as a number.`, { details: {
468
+ ref: cellRef(r, c),
469
+ value: String(v)
470
+ } });
471
+ return String(v);
472
+ case "boolean": return v ? "TRUE" : "FALSE";
473
+ }
474
+ if (v instanceof Date || Object.prototype.toString.call(v) === "[object Date]") return dateText(v, r, c, cfg);
475
+ if (typeof v === "object" && v !== null) {
476
+ if ("error" in v && typeof v.error === "string") return v.error;
477
+ if ("richText" in v && Array.isArray(v.richText)) return guard(v.richText.map((run) => run.text).join(""), cfg);
478
+ }
479
+ throw new require_errors.ValidationError("INVALID_CELL", `Cell ${cellRef(r, c)} holds an unsupported value.`, { details: { ref: cellRef(r, c) } });
480
+ }
481
+ function guard(s, cfg) {
482
+ if (!cfg.escapeFormulas || s.length === 0) return s;
483
+ const c = s.charCodeAt(0);
484
+ if (c === 61 || c === 43 || c === 45 || c === 64 || c === 9 || c === 13) return `'${s}`;
485
+ return s;
486
+ }
487
+ function dateText(d, r, c, cfg) {
488
+ if (Number.isNaN(d.getTime())) throw new require_errors.ValidationError("INVALID_DATE", `Cell ${cellRef(r, c)} holds an invalid Date.`, { details: { ref: cellRef(r, c) } });
489
+ if (typeof cfg.dates === "function") return String(cfg.dates(d));
490
+ return require_iso_date.isoDate(d, cfg.dateZone);
491
+ }
492
+ function isCell(v) {
493
+ if (typeof v !== "object" || v === null || v instanceof Date) return false;
494
+ if ("error" in v || "richText" in v) return false;
495
+ return true;
496
+ }
497
+ // src/csv.ts
498
+ /** MIME type of `toCsvBlob` output. */
499
+ const CSV_MIME = "text/csv;charset=utf-8";
500
+ /** Records between yields in `readCsv` are bounded by this many characters. */
501
+ const CHUNK_CHARS = 1048576;
502
+ function parseConfig(options) {
503
+ const o = options ?? {};
504
+ return {
505
+ delimiter: o.delimiter ?? "auto",
506
+ quote: o.quote ?? "\"",
507
+ inferTypes: o.inferTypes ?? false,
508
+ skipEmptyLines: o.skipEmptyLines ?? false,
509
+ strict: (o.mode ?? "lenient") === "strict",
510
+ maxRows: o.maxRows ?? Number.POSITIVE_INFINITY,
511
+ maxFieldBytes: o.maxFieldBytes ?? 1048576,
512
+ dateZone: o.dateZone ?? "local"
513
+ };
514
+ }
515
+ function checkMode(options) {
516
+ const mode = options?.mode;
517
+ if (mode !== void 0 && mode !== "lenient" && mode !== "strict") throw new TypeError(`mode must be 'lenient' or 'strict'`);
518
+ const zone = options?.dateZone;
519
+ if (zone !== void 0 && zone !== "local" && zone !== "utc") throw new TypeError(`dateZone must be 'local' or 'utc'`);
520
+ }
521
+ function result(p, bom, extra) {
522
+ return {
523
+ rows: p.rows,
524
+ delimiter: p.delimiter,
525
+ newline: p.newline ?? "\r\n",
526
+ bom: bom || p.bom,
527
+ warnings: extra.length ? [...extra, ...p.warnings] : p.warnings
528
+ };
529
+ }
530
+ /** Parses CSV text synchronously. */
531
+ function parseCsv(text, options) {
532
+ if (typeof text !== "string") throw new TypeError("parseCsv: text must be a string; use readCsv for bytes");
533
+ checkMode(options);
534
+ const p = new CsvParser(text, parseConfig(options));
535
+ p.run();
536
+ return result(p, false, []);
537
+ }
538
+ /**
539
+ * Decodes (for bytes) and parses CSV without blocking: it yields to the event
540
+ * loop between chunks of records and honours `signal`.
541
+ */
542
+ async function readCsv(input, options) {
543
+ checkMode(options);
544
+ const signal = options?.signal;
545
+ throwIfAborted(signal);
546
+ let text;
547
+ let bom = false;
548
+ const extra = [];
549
+ if (typeof input === "string") text = input;
550
+ else {
551
+ const bytes = await require_infer.toBytes(input, "readCsv", "a string, ");
552
+ throwIfAborted(signal);
553
+ const decoded = decodeBytes(bytes, options?.encoding ?? "utf-8");
554
+ text = decoded.text;
555
+ bom = decoded.bom;
556
+ if (decoded.invalid) {
557
+ const message = `Input is not valid ${decoded.encoding}; invalid bytes were replaced with U+FFFD.`;
558
+ if (options?.mode === "strict") throw new require_errors.CsvError("CSV_MALFORMED", message, { details: {
559
+ warning: "CSV_INVALID_ENCODING",
560
+ encoding: decoded.encoding
561
+ } });
562
+ extra.push({
563
+ code: "CSV_INVALID_ENCODING",
564
+ message
565
+ });
566
+ }
567
+ }
568
+ const p = new CsvParser(text, parseConfig(options));
569
+ while (!p.done) {
570
+ p.run(p.position + CHUNK_CHARS);
571
+ if (!p.done) {
572
+ await yieldToEventLoop();
573
+ throwIfAborted(signal);
574
+ }
575
+ }
576
+ return result(p, bom, extra);
577
+ }
578
+ /** Serializes a sheet (A1 to its last used cell) or an array of rows to CSV text. */
579
+ function toCsv(source, options) {
580
+ const text = serialize(source, writeConfig(options));
581
+ return options?.bom === true ? `\uFEFF${text}` : text;
582
+ }
583
+ /** Like `toCsv`, as a `Blob` of type `text/csv;charset=utf-8`, with a BOM unless `bom: false`. */
584
+ function toCsvBlob(source, options) {
585
+ const Ctor = globalThis.Blob;
586
+ if (typeof Ctor !== "function") throw new require_errors.EnvironmentError("ENVIRONMENT_UNSUPPORTED", "Blob is not available in this runtime; use toCsv instead.", { details: { api: "Blob" } });
587
+ const text = serialize(source, writeConfig(options));
588
+ return new Ctor([options?.bom === false ? text : `\uFEFF${text}`], { type: CSV_MIME });
589
+ }
590
+ function writeConfig(options) {
591
+ const o = options ?? {};
592
+ const quote = o.quote ?? "auto";
593
+ if (quote !== "auto" && quote !== "all") throw new TypeError(`quote must be 'auto' or 'all'`);
594
+ return {
595
+ delimiter: o.delimiter ?? ",",
596
+ newline: o.newline ?? "\r\n",
597
+ quoteAll: quote === "all",
598
+ escapeFormulas: o.escapeFormulas ?? true,
599
+ dates: o.dates ?? "iso",
600
+ dateZone: o.dateZone ?? "local",
601
+ formulas: o.formulas ?? "value"
602
+ };
603
+ }
604
+ function throwIfAborted(signal) {
605
+ if (signal?.aborted) throw signal.reason ?? abortError();
606
+ }
607
+ function abortError() {
608
+ const err = /* @__PURE__ */ new Error("The operation was aborted.");
609
+ err.name = "AbortError";
610
+ return err;
611
+ }
612
+ function yieldToEventLoop() {
613
+ const st = globalThis.setTimeout;
614
+ return new Promise((resolve) => {
615
+ if (typeof st === "function") st(resolve, 0);
616
+ else Promise.resolve().then(resolve);
617
+ });
618
+ }
619
+ exports.CSV_MIME = CSV_MIME;
620
+ exports.parseCsv = parseCsv;
621
+ exports.readCsv = readCsv;
622
+ exports.toCsv = toCsv;
623
+ exports.toCsvBlob = toCsvBlob;