javascript-excel 1.0.3 → 2.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +69 -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-DyVH9y7S.cjs +647 -0
  5. package/dist/csv-pXfaputs.js +618 -0
  6. package/dist/csv.cjs +7 -0
  7. package/dist/csv.d.cts +89 -0
  8. package/dist/csv.d.ts +89 -0
  9. package/dist/csv.js +1 -0
  10. package/dist/dom.cjs +440 -0
  11. package/dist/dom.d.cts +78 -0
  12. package/dist/dom.d.ts +78 -0
  13. package/dist/dom.js +437 -0
  14. package/dist/errors-CvGlfw0E.js +28 -0
  15. package/dist/errors-DOPrrGS4.cjs +69 -0
  16. package/dist/index.cjs +627 -0
  17. package/dist/index.d.cts +255 -0
  18. package/dist/index.d.ts +255 -0
  19. package/dist/index.js +597 -0
  20. package/dist/infer-BR-J9BZa.js +88 -0
  21. package/dist/infer-D9EC9vJ-.cjs +105 -0
  22. package/dist/iso-date-3TY1OlGd.cjs +57 -0
  23. package/dist/iso-date-CXnn-9mT.js +46 -0
  24. package/dist/numfmt-BBgB7iQA.js +429 -0
  25. package/dist/numfmt-Dv6AjopS.cjs +512 -0
  26. package/dist/read-C6L7Nyy3.d.cts +78 -0
  27. package/dist/read-DDN5ZsPe.js +2909 -0
  28. package/dist/read-Ddkks7qC.d.ts +78 -0
  29. package/dist/read-Ym1voUct.cjs +2932 -0
  30. package/dist/read.cjs +6 -0
  31. package/dist/read.d.cts +15 -0
  32. package/dist/read.d.ts +15 -0
  33. package/dist/read.js +1 -0
  34. package/dist/sheet-names-qpXsvMpM.cjs +1005 -0
  35. package/dist/sheet-names-uT2EH5Ui.js +832 -0
  36. package/dist/signal-Dz0ZYe6d.d.cts +13 -0
  37. package/dist/signal-Dz0ZYe6d.d.ts +13 -0
  38. package/dist/warnings-C_12PT4t.d.cts +410 -0
  39. package/dist/warnings-DXJKe1lx.d.ts +410 -0
  40. package/dist/worker.cjs +240 -0
  41. package/dist/worker.d.cts +65 -0
  42. package/dist/worker.d.ts +65 -0
  43. package/dist/worker.js +238 -0
  44. package/dist/write-BOh9jfu1.cjs +1487 -0
  45. package/dist/write-C5JgeIar.d.cts +29 -0
  46. package/dist/write-CYpLGuzl.d.ts +29 -0
  47. package/dist/write-DubvcG-x.js +1470 -0
  48. package/package.json +101 -51
  49. package/.babelrc +0 -10
  50. package/.circleci/config.yml +0 -39
  51. package/lib/index.d.ts +0 -1
  52. package/lib/index.js +0 -22
  53. package/lib/javascript-excel.js +0 -17703
  54. package/src/index.tsx +0 -11
  55. package/test/unit/sample.spec.js +0 -5
  56. package/tsconfig.json +0 -54
  57. package/webpack.config.js +0 -19
  58. /package/{LICENSE.md → LICENSE} +0 -0
package/dist/csv.d.cts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * javascript-excel/csv: CSV parse and serialize (docs/api.md §5.3).
3
+ *
4
+ * RFC 4180 with the usual real-world extensions: delimiter detection, CRLF,
5
+ * LF and CR newlines, a UTF-8 BOM, and lenient recovery from malformed
6
+ * quoting (warnings) unless `mode: 'strict'`. Pulls in nothing from the xlsx
7
+ * code.
8
+ */
9
+ import { A as RichTextRun, I as Workbook, M as Sheet, a as BlobType, b as ErrorCode, d as CellErrorValue, f as CellInput, i as BlobLike, k as RichText, m as CellValue, n as ExcelWarningCode, p as CellType, r as BinaryInput, t as ExcelWarning, u as Cell } from "./warnings-C_12PT4t.cjs";
10
+ import { t as AbortSignalLike } from "./signal-Dz0ZYe6d.cjs";
11
+ /** Options for `parseCsv` and `readCsv`. */
12
+ export interface CsvParseOptions {
13
+ /** A single character, or `'auto'` (default): picks from `, ; TAB |` by field-count consistency over the first records. */
14
+ delimiter?: string | undefined;
15
+ /** Default `'"'`. A quote inside a quoted field is doubled (RFC 4180). */
16
+ quote?: string | undefined;
17
+ /**
18
+ * Default false: every field is a string. true: unquoted fields that are numbers,
19
+ * `TRUE`/`FALSE` (or `true`/`false`) or ISO 8601 dates become numbers, booleans and
20
+ * `Date`s. No locale guessing. Quoted fields always stay strings.
21
+ */
22
+ inferTypes?: boolean | undefined;
23
+ /** Time zone for ISO dates without an offset when `inferTypes` is on. Default `'local'`. */
24
+ dateZone?: "local" | "utc" | undefined;
25
+ /** Default false. A blank line otherwise gives an empty row (`[]`). */
26
+ skipEmptyLines?: boolean | undefined;
27
+ /** `'lenient'` (default): malformed input gives warnings. `'strict'`: throws `CsvError` (`CSV_MALFORMED`). */
28
+ mode?: "lenient" | "strict" | undefined;
29
+ /** Stop after this many rows, with warning `CSV_ROWS_TRUNCATED`. Default unlimited. */
30
+ maxRows?: number | undefined;
31
+ /** Largest field, in UTF-8 bytes; a bigger one throws `LimitError` (`LIMIT_EXCEEDED`). Default 1,048,576 (1 MiB). */
32
+ maxFieldBytes?: number | undefined;
33
+ }
34
+ /** Options for `readCsv`. */
35
+ export interface CsvReadOptions extends CsvParseOptions {
36
+ /** Used when the bytes have no BOM. Any label `TextDecoder` accepts. Default `'utf-8'`. */
37
+ encoding?: string | undefined;
38
+ /** Rejects with `signal.reason` when aborted. */
39
+ signal?: AbortSignalLike | undefined;
40
+ }
41
+ /** Result of `parseCsv` and `readCsv`. */
42
+ export interface CsvParseResult {
43
+ /** `string[][]` unless `inferTypes`. */
44
+ rows: CellValue[][];
45
+ /** The delimiter used (detected or given). */
46
+ delimiter: string;
47
+ /** The first newline seen; `'\r\n'` when the input has none. */
48
+ newline: "\r\n" | "\n" | "\r";
49
+ /** The input started with a BOM (removed from the data). */
50
+ bom: boolean;
51
+ /** `CSV_UNTERMINATED_QUOTE`, `CSV_STRAY_QUOTE`, `CSV_FIELD_COUNT`, `CSV_INVALID_ENCODING`, `CSV_ROWS_TRUNCATED`. */
52
+ warnings: ExcelWarning[];
53
+ }
54
+ /** Options for `toCsv` and `toCsvBlob`. */
55
+ export interface CsvWriteOptions {
56
+ /** Default `','`. */
57
+ delimiter?: string | undefined;
58
+ /** Default `'\r\n'` (RFC 4180). */
59
+ newline?: "\r\n" | "\n" | undefined;
60
+ /** `'auto'` (default): quote fields containing the delimiter, a quote, CR or LF. `'all'`: quote every field. */
61
+ quote?: "auto" | "all" | undefined;
62
+ /** Prepend a UTF-8 BOM so Excel detects UTF-8. `toCsvBlob` default true, `toCsv` default false. */
63
+ bom?: boolean | undefined;
64
+ /**
65
+ * Formula-injection guard, default true: a string field starting with `=`, `+`, `-`, `@`,
66
+ * TAB or CR gets a leading `'`. Numbers, booleans and dates are never prefixed.
67
+ */
68
+ escapeFormulas?: boolean | undefined;
69
+ /** `'iso'` (default): `YYYY-MM-DD`, or `YYYY-MM-DDTHH:mm:ss` (`.sss` when there are milliseconds). Or a function. */
70
+ dates?: "iso" | ((d: Date) => string) | undefined;
71
+ /** Time zone for `'iso'` dates. Default `'local'`. */
72
+ dateZone?: "local" | "utc" | undefined;
73
+ /** Formula cells: the cached value (default) or the formula text (`'formula'`, which still passes the guard). */
74
+ formulas?: "value" | "formula" | undefined;
75
+ }
76
+ /** MIME type of `toCsvBlob` output. */
77
+ export declare const CSV_MIME = "text/csv;charset=utf-8";
78
+ /** Parses CSV text synchronously. */
79
+ export declare function parseCsv(text: string, options?: CsvParseOptions): CsvParseResult;
80
+ /**
81
+ * Decodes (for bytes) and parses CSV without blocking: it yields to the event
82
+ * loop between chunks of records and honours `signal`.
83
+ */
84
+ export declare function readCsv(input: string | BinaryInput, options?: CsvReadOptions): Promise<CsvParseResult>;
85
+ /** Serializes a sheet (A1 to its last used cell) or an array of rows to CSV text. */
86
+ export declare function toCsv(source: Sheet | CellInput[][], options?: CsvWriteOptions): string;
87
+ /** Like `toCsv`, as a `Blob` of type `text/csv;charset=utf-8`, with a BOM unless `bom: false`. */
88
+ export declare function toCsvBlob(source: Sheet | CellInput[][], options?: CsvWriteOptions): BlobType;
89
+ export type { AbortSignalLike, BinaryInput, BlobLike, BlobType, Cell, CellErrorValue, CellInput, CellType, CellValue, ErrorCode, ExcelWarning, ExcelWarningCode, RichText, RichTextRun, Sheet, Workbook };
package/dist/csv.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * javascript-excel/csv: CSV parse and serialize (docs/api.md §5.3).
3
+ *
4
+ * RFC 4180 with the usual real-world extensions: delimiter detection, CRLF,
5
+ * LF and CR newlines, a UTF-8 BOM, and lenient recovery from malformed
6
+ * quoting (warnings) unless `mode: 'strict'`. Pulls in nothing from the xlsx
7
+ * code.
8
+ */
9
+ import { D as RichTextRun, E as RichText, F as BlobLike, I as BlobType, N as Workbook, P as BinaryInput, _ as ErrorCode, c as CellErrorValue, d as CellValue, k as Sheet, l as CellInput, n as ExcelWarningCode, s as Cell, t as ExcelWarning, u as CellType } from "./warnings-DXJKe1lx.js";
10
+ import { t as AbortSignalLike } from "./signal-Dz0ZYe6d.js";
11
+ /** Options for `parseCsv` and `readCsv`. */
12
+ export interface CsvParseOptions {
13
+ /** A single character, or `'auto'` (default): picks from `, ; TAB |` by field-count consistency over the first records. */
14
+ delimiter?: string | undefined;
15
+ /** Default `'"'`. A quote inside a quoted field is doubled (RFC 4180). */
16
+ quote?: string | undefined;
17
+ /**
18
+ * Default false: every field is a string. true: unquoted fields that are numbers,
19
+ * `TRUE`/`FALSE` (or `true`/`false`) or ISO 8601 dates become numbers, booleans and
20
+ * `Date`s. No locale guessing. Quoted fields always stay strings.
21
+ */
22
+ inferTypes?: boolean | undefined;
23
+ /** Time zone for ISO dates without an offset when `inferTypes` is on. Default `'local'`. */
24
+ dateZone?: "local" | "utc" | undefined;
25
+ /** Default false. A blank line otherwise gives an empty row (`[]`). */
26
+ skipEmptyLines?: boolean | undefined;
27
+ /** `'lenient'` (default): malformed input gives warnings. `'strict'`: throws `CsvError` (`CSV_MALFORMED`). */
28
+ mode?: "lenient" | "strict" | undefined;
29
+ /** Stop after this many rows, with warning `CSV_ROWS_TRUNCATED`. Default unlimited. */
30
+ maxRows?: number | undefined;
31
+ /** Largest field, in UTF-8 bytes; a bigger one throws `LimitError` (`LIMIT_EXCEEDED`). Default 1,048,576 (1 MiB). */
32
+ maxFieldBytes?: number | undefined;
33
+ }
34
+ /** Options for `readCsv`. */
35
+ export interface CsvReadOptions extends CsvParseOptions {
36
+ /** Used when the bytes have no BOM. Any label `TextDecoder` accepts. Default `'utf-8'`. */
37
+ encoding?: string | undefined;
38
+ /** Rejects with `signal.reason` when aborted. */
39
+ signal?: AbortSignalLike | undefined;
40
+ }
41
+ /** Result of `parseCsv` and `readCsv`. */
42
+ export interface CsvParseResult {
43
+ /** `string[][]` unless `inferTypes`. */
44
+ rows: CellValue[][];
45
+ /** The delimiter used (detected or given). */
46
+ delimiter: string;
47
+ /** The first newline seen; `'\r\n'` when the input has none. */
48
+ newline: "\r\n" | "\n" | "\r";
49
+ /** The input started with a BOM (removed from the data). */
50
+ bom: boolean;
51
+ /** `CSV_UNTERMINATED_QUOTE`, `CSV_STRAY_QUOTE`, `CSV_FIELD_COUNT`, `CSV_INVALID_ENCODING`, `CSV_ROWS_TRUNCATED`. */
52
+ warnings: ExcelWarning[];
53
+ }
54
+ /** Options for `toCsv` and `toCsvBlob`. */
55
+ export interface CsvWriteOptions {
56
+ /** Default `','`. */
57
+ delimiter?: string | undefined;
58
+ /** Default `'\r\n'` (RFC 4180). */
59
+ newline?: "\r\n" | "\n" | undefined;
60
+ /** `'auto'` (default): quote fields containing the delimiter, a quote, CR or LF. `'all'`: quote every field. */
61
+ quote?: "auto" | "all" | undefined;
62
+ /** Prepend a UTF-8 BOM so Excel detects UTF-8. `toCsvBlob` default true, `toCsv` default false. */
63
+ bom?: boolean | undefined;
64
+ /**
65
+ * Formula-injection guard, default true: a string field starting with `=`, `+`, `-`, `@`,
66
+ * TAB or CR gets a leading `'`. Numbers, booleans and dates are never prefixed.
67
+ */
68
+ escapeFormulas?: boolean | undefined;
69
+ /** `'iso'` (default): `YYYY-MM-DD`, or `YYYY-MM-DDTHH:mm:ss` (`.sss` when there are milliseconds). Or a function. */
70
+ dates?: "iso" | ((d: Date) => string) | undefined;
71
+ /** Time zone for `'iso'` dates. Default `'local'`. */
72
+ dateZone?: "local" | "utc" | undefined;
73
+ /** Formula cells: the cached value (default) or the formula text (`'formula'`, which still passes the guard). */
74
+ formulas?: "value" | "formula" | undefined;
75
+ }
76
+ /** MIME type of `toCsvBlob` output. */
77
+ export declare const CSV_MIME = "text/csv;charset=utf-8";
78
+ /** Parses CSV text synchronously. */
79
+ export declare function parseCsv(text: string, options?: CsvParseOptions): CsvParseResult;
80
+ /**
81
+ * Decodes (for bytes) and parses CSV without blocking: it yields to the event
82
+ * loop between chunks of records and honours `signal`.
83
+ */
84
+ export declare function readCsv(input: string | BinaryInput, options?: CsvReadOptions): Promise<CsvParseResult>;
85
+ /** Serializes a sheet (A1 to its last used cell) or an array of rows to CSV text. */
86
+ export declare function toCsv(source: Sheet | CellInput[][], options?: CsvWriteOptions): string;
87
+ /** Like `toCsv`, as a `Blob` of type `text/csv;charset=utf-8`, with a BOM unless `bom: false`. */
88
+ export declare function toCsvBlob(source: Sheet | CellInput[][], options?: CsvWriteOptions): BlobType;
89
+ export type { AbortSignalLike, BinaryInput, BlobLike, BlobType, Cell, CellErrorValue, CellInput, CellType, CellValue, ErrorCode, ExcelWarning, ExcelWarningCode, RichText, RichTextRun, Sheet, Workbook };
package/dist/csv.js ADDED
@@ -0,0 +1 @@
1
+ export { t as CSV_MIME, n as parseCsv, r as readCsv, i as toCsv, a as toCsvBlob } from "./csv-pXfaputs.js";
package/dist/dom.cjs ADDED
@@ -0,0 +1,440 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sheet_names = require("./sheet-names-qpXsvMpM.cjs");
3
+ const require_errors = require("./errors-DOPrrGS4.cjs");
4
+ const require_iso_date = require("./iso-date-3TY1OlGd.cjs");
5
+ // src/auto-width.ts
6
+ /**
7
+ * Auto column widths for builders (docs/api.md §4.3, §5.4).
8
+ */
9
+ /** Estimated width in characters per column: widest `cellText` + 2 padding, clamped to [min, max]. */
10
+ function autoWidths(rows, options = {}) {
11
+ const min = options.min ?? require_sheet_names.AUTO_WIDTH.min;
12
+ const max = Math.min(255, options.max ?? require_sheet_names.AUTO_WIDTH.max);
13
+ const limit = Math.min(rows.length, options.sampleRows ?? rows.length);
14
+ const widest = [];
15
+ for (let r = 0; r < limit; r++) {
16
+ const row = rows[r];
17
+ if (!row) continue;
18
+ for (let c = 0; c < row.length; c++) {
19
+ const w = require_sheet_names.textWidth(require_sheet_names.cellText(row[c]));
20
+ if (w > (widest[c] ?? 0)) widest[c] = w;
21
+ }
22
+ }
23
+ return Array.from(widest, (w) => Math.min(max, Math.max(min, (w ?? 0) + require_sheet_names.AUTO_WIDTH.padding)));
24
+ }
25
+ // src/internal/css-color.ts
26
+ /** CSS colour values to RRGGBB, for computed-style mapping in javascript-excel/dom. */
27
+ const NAMED = {
28
+ black: "000000",
29
+ white: "FFFFFF",
30
+ red: "FF0000",
31
+ lime: "00FF00",
32
+ green: "008000",
33
+ blue: "0000FF",
34
+ yellow: "FFFF00",
35
+ cyan: "00FFFF",
36
+ aqua: "00FFFF",
37
+ magenta: "FF00FF",
38
+ fuchsia: "FF00FF",
39
+ silver: "C0C0C0",
40
+ gray: "808080",
41
+ grey: "808080",
42
+ maroon: "800000",
43
+ olive: "808000",
44
+ purple: "800080",
45
+ teal: "008080",
46
+ navy: "000080",
47
+ orange: "FFA500"
48
+ };
49
+ /** A CSS colour as RRGGBB, or undefined for transparent or unparseable values. */
50
+ function cssColor(value) {
51
+ const v = value.trim().toLowerCase();
52
+ if (!v || v === "transparent" || v === "currentcolor" || v === "inherit" || v === "initial") return void 0;
53
+ const hex = /^#([0-9a-f]{3,8})$/.exec(v)?.[1];
54
+ if (hex) {
55
+ if (hex.length === 3 || hex.length === 4) {
56
+ if (hex.length === 4 && hex[3] === "0") return void 0;
57
+ return hex.slice(0, 3).split("").map((c) => c + c).join("").toUpperCase();
58
+ }
59
+ if (hex.length === 6) return hex.toUpperCase();
60
+ if (hex.length === 8) return hex.slice(6) === "00" ? void 0 : hex.slice(0, 6).toUpperCase();
61
+ return;
62
+ }
63
+ const m = /^rgba?\(\s*([\d.]+%?)[\s,]+([\d.]+%?)[\s,]+([\d.]+%?)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(v);
64
+ if (m) {
65
+ const ch = (s) => Math.round(Math.min(255, Math.max(0, s.endsWith("%") ? parseFloat(s) * 255 / 100 : parseFloat(s))));
66
+ if (m[4] !== void 0) {
67
+ if (!((m[4].endsWith("%") ? parseFloat(m[4]) / 100 : parseFloat(m[4])) > 0)) return void 0;
68
+ }
69
+ return [
70
+ m[1],
71
+ m[2],
72
+ m[3]
73
+ ].map((s) => ch(s).toString(16).padStart(2, "0")).join("").toUpperCase();
74
+ }
75
+ return NAMED[v];
76
+ }
77
+ function isElement(n) {
78
+ return n.nodeType === 1;
79
+ }
80
+ // src/dom.ts
81
+ /**
82
+ * javascript-excel/dom: HTML table input and file download (docs/api.md §5.4).
83
+ *
84
+ * The only module that touches the DOM. Importing it never reads a global, so
85
+ * it is safe during server-side rendering; the DOM is used only inside the
86
+ * functions, and a table is read through its own window (iframes work).
87
+ */
88
+ const DEFAULT_IGNORE = "[data-export-ignore]";
89
+ const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
90
+ /** HTML's limits on colspan and rowspan. */
91
+ const MAX_COLSPAN = 1e3;
92
+ const MAX_ROWSPAN = 65534;
93
+ /**
94
+ * How long the object URL stays valid after the click. Browsers start the
95
+ * download asynchronously, and Safari needs the URL for a while; 40 s is the
96
+ * delay FileSaver.js uses. Not measured here.
97
+ */
98
+ const DOWNLOAD_REVOKE_DELAY_MS = 4e4;
99
+ function mimeFor(filename, data) {
100
+ const ext = /\.([A-Za-z0-9]+)$/.exec(filename)?.[1]?.toLowerCase();
101
+ if (ext === "xlsx") return XLSX_MIME;
102
+ if (ext === "csv") return "text/csv;charset=utf-8";
103
+ return typeof data === "string" ? "text/plain;charset=utf-8" : "application/octet-stream";
104
+ }
105
+ /**
106
+ * Saves data as a file in the browser: creates an object URL, clicks a
107
+ * temporary `<a download>` and revokes the URL after DOWNLOAD_REVOKE_DELAY_MS.
108
+ * A string is encoded as UTF-8. Throws ENVIRONMENT_UNSUPPORTED without a DOM.
109
+ */
110
+ function download(data, filename, options) {
111
+ const g = globalThis;
112
+ const doc = g.document;
113
+ if (!doc?.body || typeof g.URL?.createObjectURL !== "function" || typeof g.Blob !== "function") throw new require_errors.EnvironmentError("ENVIRONMENT_UNSUPPORTED", "download() needs a browser DOM (document, URL.createObjectURL, Blob).", { details: { api: "document" } });
114
+ if (typeof filename !== "string" || filename.length === 0) throw new TypeError("download(): filename must be a non-empty string");
115
+ const Blob = g.Blob;
116
+ const isBlob = typeof data === "object" && data !== null && !(data instanceof Uint8Array);
117
+ let blob;
118
+ if (isBlob) {
119
+ const b = data;
120
+ blob = options?.mimeType && b.type !== options.mimeType ? new Blob([b], { type: options.mimeType }) : b;
121
+ } else blob = new Blob([data], { type: options?.mimeType ?? mimeFor(filename, data) });
122
+ const url = g.URL.createObjectURL(blob);
123
+ const a = doc.createElement("a");
124
+ a.href = url;
125
+ a.download = filename;
126
+ a.rel = "noopener";
127
+ a.style.display = "none";
128
+ doc.body.appendChild(a);
129
+ try {
130
+ a.click();
131
+ } finally {
132
+ a.remove();
133
+ const revoke = () => g.URL.revokeObjectURL(url);
134
+ if (typeof g.setTimeout === "function") g.setTimeout(revoke, DOWNLOAD_REVOKE_DELAY_MS);
135
+ else revoke();
136
+ }
137
+ }
138
+ function css(ctx, el, prop) {
139
+ if (!ctx.view) return "";
140
+ try {
141
+ return ctx.view.getComputedStyle(el).getPropertyValue(prop).trim();
142
+ } catch {
143
+ return "";
144
+ }
145
+ }
146
+ function inlineDisplayNone(el) {
147
+ const style = el.getAttribute("style");
148
+ return style !== null && /(?:^|;)\s*display\s*:\s*none\s*(?:!important\s*)?(?:;|$)/i.test(style);
149
+ }
150
+ function skipped(ctx, el) {
151
+ if (el.matches(ctx.ignore)) return true;
152
+ if (!ctx.skipHidden) return false;
153
+ if (el.hasAttribute("hidden") || inlineDisplayNone(el)) return true;
154
+ return ctx.computed && css(ctx, el, "display") === "none";
155
+ }
156
+ const SKIP_TEXT = /* @__PURE__ */ new Set([
157
+ "SCRIPT",
158
+ "STYLE",
159
+ "TEMPLATE",
160
+ "NOSCRIPT"
161
+ ]);
162
+ /** Text of a cell: whitespace collapsed per line, <br> as a newline. */
163
+ function cellTextOf(el) {
164
+ const lines = [""];
165
+ let hasBreak = false;
166
+ const walk = (n) => {
167
+ if (n.nodeType === 3) {
168
+ lines[lines.length - 1] += n.textContent ?? "";
169
+ return;
170
+ }
171
+ if (!isElement(n)) return;
172
+ const tag = n.tagName.toUpperCase();
173
+ if (SKIP_TEXT.has(tag)) return;
174
+ if (tag === "BR") {
175
+ lines.push("");
176
+ hasBreak = true;
177
+ return;
178
+ }
179
+ for (let i = 0; i < n.childNodes.length; i++) walk(n.childNodes[i]);
180
+ };
181
+ for (let i = 0; i < el.childNodes.length; i++) walk(el.childNodes[i]);
182
+ return {
183
+ text: lines.map((l) => l.replace(/[ \t\n\r\f ]+/g, " ").trim()).join("\n").replace(/^\n+|\n+$/g, ""),
184
+ hasBreak
185
+ };
186
+ }
187
+ const PLAIN_NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
188
+ const GROUPED_NUMBER = /^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/;
189
+ function parseNumber(s) {
190
+ const t = s.trim();
191
+ if (PLAIN_NUMBER.test(t)) return Number(t);
192
+ if (GROUPED_NUMBER.test(t)) return Number(t.replace(/,/g, ""));
193
+ }
194
+ function parseBoolean(s) {
195
+ const t = s.trim().toLowerCase();
196
+ if (t === "true" || t === "yes" || t === "1") return true;
197
+ if (t === "false" || t === "no" || t === "0") return false;
198
+ }
199
+ function coerce(ctx, raw, type, ref) {
200
+ if (type === null || type === "" || type === "string") {
201
+ if (ctx.inferTypes) {
202
+ const n = PLAIN_NUMBER.test(raw.trim()) ? Number(raw.trim()) : void 0;
203
+ if (n !== void 0 && Number.isFinite(n)) return n;
204
+ const t = raw.trim().toLowerCase();
205
+ if (t === "true") return true;
206
+ if (t === "false") return false;
207
+ }
208
+ return raw;
209
+ }
210
+ const fail = () => {
211
+ ctx.warn({
212
+ code: "COERCION_FAILED",
213
+ message: `${ctx.sheet}!${ref}: ${JSON.stringify(raw)} is not a valid ${type}; kept as text.`,
214
+ sheet: ctx.sheet,
215
+ ref
216
+ });
217
+ return raw;
218
+ };
219
+ switch (type) {
220
+ case "number": {
221
+ const n = parseNumber(raw);
222
+ return n !== void 0 && Number.isFinite(n) ? n : fail();
223
+ }
224
+ case "boolean": return parseBoolean(raw) ?? fail();
225
+ case "date": return require_iso_date.parseIsoDate(raw) ?? fail();
226
+ default:
227
+ ctx.warn({
228
+ code: "COERCION_FAILED",
229
+ message: `${ctx.sheet}!${ref}: unknown data-type ${JSON.stringify(type)}; kept as text.`,
230
+ sheet: ctx.sheet,
231
+ ref
232
+ });
233
+ return raw;
234
+ }
235
+ }
236
+ /** The first non-transparent background of the cell, its row, section or table (what a reader sees). */
237
+ function backgroundOf(ctx, cell, table) {
238
+ for (let el = cell; el; el = el.parentElement) {
239
+ const c = cssColor(css(ctx, el, "background-color"));
240
+ if (c) return c;
241
+ if (el === table) break;
242
+ }
243
+ }
244
+ function computedStyle(ctx, el, table) {
245
+ const style = {};
246
+ const font = {};
247
+ const weight = css(ctx, el, "font-weight");
248
+ if (weight === "bold" || weight === "bolder" || Number(weight) >= 600) font.bold = true;
249
+ const fs = css(ctx, el, "font-style");
250
+ if (fs === "italic" || fs.startsWith("oblique")) font.italic = true;
251
+ const deco = `${css(ctx, el, "text-decoration-line")} ${css(ctx, el, "text-decoration")}`;
252
+ if (/\bunderline\b/.test(deco)) font.underline = true;
253
+ if (/\bline-through\b/.test(deco)) font.strike = true;
254
+ const color = cssColor(css(ctx, el, "color"));
255
+ if (color && color !== "000000") font.color = color;
256
+ if (Object.keys(font).length) style.font = font;
257
+ const bg = backgroundOf(ctx, el, table);
258
+ if (bg) style.fill = bg;
259
+ const alignment = {};
260
+ const ta = css(ctx, el, "text-align");
261
+ const h = /^(?:-webkit-|-internal-|-moz-)?center$/.test(ta) ? "center" : ta;
262
+ if (h === "left" || h === "right" || h === "center" || h === "justify") alignment.horizontal = h;
263
+ const va = css(ctx, el, "vertical-align");
264
+ if (va === "top" || va === "bottom") alignment.vertical = va;
265
+ const ws = css(ctx, el, "white-space");
266
+ if (ws === "pre-wrap" || ws === "pre-line" || ws === "break-spaces") alignment.wrapText = true;
267
+ if (Object.keys(alignment).length) style.alignment = alignment;
268
+ return Object.keys(style).length ? style : void 0;
269
+ }
270
+ function linkOf(ctx, cell, ref) {
271
+ const find = (n) => {
272
+ for (let i = 0; i < n.children.length; i++) {
273
+ const c = n.children[i];
274
+ if (c.tagName.toUpperCase() === "A" && c.hasAttribute("href")) return c;
275
+ const deeper = find(c);
276
+ if (deeper) return deeper;
277
+ }
278
+ };
279
+ const a = find(cell);
280
+ if (!a) return void 0;
281
+ const raw = a.getAttribute("href") ?? "";
282
+ if (raw.startsWith("#") || raw.trim() === "") return void 0;
283
+ const url = typeof a.href === "string" && a.href ? a.href : raw;
284
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(url)?.[1]?.toLowerCase();
285
+ if (!scheme || !ctx.schemes.has(scheme)) {
286
+ ctx.warn({
287
+ code: "HYPERLINK_DROPPED",
288
+ message: `${ctx.sheet}!${ref}: link ${JSON.stringify(url)} dropped (scheme not allowed).`,
289
+ sheet: ctx.sheet,
290
+ ref
291
+ });
292
+ return;
293
+ }
294
+ return url;
295
+ }
296
+ /** Rows in reading order: <thead> rows, then <tbody> and bare <tr> rows, then <tfoot> rows. */
297
+ function collectRows(table, includeFooter) {
298
+ const head = [];
299
+ const body = [];
300
+ const foot = [];
301
+ const bare = [];
302
+ const trs = (section) => Array.from(section.children).filter((c) => c.tagName.toUpperCase() === "TR");
303
+ for (const child of Array.from(table.children)) {
304
+ const tag = child.tagName.toUpperCase();
305
+ if (tag === "THEAD") head.push(trs(child));
306
+ else if (tag === "TBODY") {
307
+ if (bare.length) body.push(bare.splice(0));
308
+ body.push(trs(child));
309
+ } else if (tag === "TFOOT") {
310
+ if (includeFooter) foot.push(trs(child));
311
+ } else if (tag === "TR") bare.push(child);
312
+ }
313
+ if (bare.length) body.push(bare);
314
+ const groups = [
315
+ ...head,
316
+ ...body,
317
+ ...foot
318
+ ];
319
+ const rows = groups.flat();
320
+ const sections = [];
321
+ groups.forEach((g, i) => g.forEach(() => sections.push(i)));
322
+ return {
323
+ rows,
324
+ sections
325
+ };
326
+ }
327
+ function intAttr(el, name, fallback, min, max) {
328
+ const v = el.getAttribute(name);
329
+ if (v === null) return fallback;
330
+ const n = Number.parseInt(v, 10);
331
+ if (!Number.isFinite(n)) return fallback;
332
+ return Math.min(max, Math.max(min, n));
333
+ }
334
+ /** Reads an HTML table into a Sheet: values, merges from colspan/rowspan, hints, links and (optionally) styles. */
335
+ function fromTable(table, options = {}) {
336
+ const t = table;
337
+ if (typeof t !== "object" || t === null || typeof t.tagName !== "string" || typeof t.matches !== "function") throw new require_errors.EnvironmentError("ENVIRONMENT_UNSUPPORTED", "fromTable() needs a DOM <table> element.", { details: { api: "HTMLTableElement" } });
338
+ if (t.tagName.toUpperCase() !== "TABLE") throw new TypeError(`fromTable(): expected a <table> element, got <${t.tagName.toLowerCase()}>`);
339
+ const name = options.name ?? "Sheet1";
340
+ const problem = require_sheet_names.validateSheetName(name);
341
+ if (problem) throw new require_errors.ValidationError("INVALID_SHEET_NAME", `fromTable(): sheet name ${JSON.stringify(name)} is invalid (${problem}).`, { details: {
342
+ sheet: name,
343
+ problem
344
+ } });
345
+ const ctx = {
346
+ view: t.ownerDocument?.defaultView ?? null,
347
+ computed: options.styles === "computed",
348
+ skipHidden: options.skipHidden !== false,
349
+ ignore: options.ignore ?? DEFAULT_IGNORE,
350
+ inferTypes: options.inferTypes === true,
351
+ links: options.links !== false,
352
+ schemes: options.hyperlinkSchemes === void 0 ? new Set(require_sheet_names.DEFAULT_HYPERLINK_SCHEMES) : require_sheet_names.hyperlinkSchemes(options.hyperlinkSchemes),
353
+ sheet: name,
354
+ warn: options.onWarning ?? (() => {})
355
+ };
356
+ const rtl = t.closest("[dir]")?.getAttribute("dir")?.toLowerCase() === "rtl" || ctx.computed && css(ctx, t, "direction") === "rtl";
357
+ const { rows: allRows, sections: allSections } = collectRows(t, options.includeFooter !== false);
358
+ const header = options.header ?? "thead";
359
+ const headerStyle = options.headerStyle ?? { font: { bold: true } };
360
+ const out = [];
361
+ const merges = [];
362
+ const occupied = [];
363
+ const occupy = (r, c) => {
364
+ (occupied[r] ??= [])[c] = true;
365
+ };
366
+ const kept = allRows.map((tr, i) => ({
367
+ tr,
368
+ section: allSections[i]
369
+ })).filter(({ tr }) => !skipped(ctx, tr));
370
+ const headerCount = header === "thead" ? kept.filter(({ tr }) => tr.parentElement?.tagName.toUpperCase() === "THEAD").length : header === false ? 0 : Math.max(0, Math.trunc(header));
371
+ let maxCol = -1;
372
+ kept.forEach(({ tr, section }, r) => {
373
+ const row = out[r] ??= [];
374
+ let c = 0;
375
+ for (const cell of Array.from(tr.children)) {
376
+ const tag = cell.tagName.toUpperCase();
377
+ if (tag !== "TD" && tag !== "TH") continue;
378
+ if (skipped(ctx, cell)) continue;
379
+ while (occupied[r]?.[c]) c++;
380
+ const colspan = intAttr(cell, "colspan", 1, 1, MAX_COLSPAN);
381
+ let rowspan = intAttr(cell, "rowspan", 1, 0, MAX_ROWSPAN);
382
+ if (rowspan === 0) {
383
+ let end = r;
384
+ while (end + 1 < kept.length && kept[end + 1].section === section) end++;
385
+ rowspan = end - r + 1;
386
+ }
387
+ rowspan = Math.min(rowspan, kept.length - r);
388
+ for (let dr = 0; dr < rowspan; dr++) for (let dc = 0; dc < colspan; dc++) occupy(r + dr, c + dc);
389
+ const ref = `${colName(c)}${r + 1}`;
390
+ if (colspan > 1 || rowspan > 1) merges.push(`${ref}:${colName(c + colspan - 1)}${r + rowspan}`);
391
+ const isHeader = r < headerCount;
392
+ const hooked = options.cell?.(cell, {
393
+ row: r,
394
+ col: c,
395
+ header: isHeader
396
+ });
397
+ if (hooked !== void 0) row[c] = hooked;
398
+ else {
399
+ const dataValue = cell.getAttribute("data-value");
400
+ const { text, hasBreak } = cellTextOf(cell);
401
+ const value = coerce(ctx, dataValue ?? text, cell.getAttribute("data-type"), ref);
402
+ const layers = [];
403
+ if (isHeader) layers.push(headerStyle);
404
+ if (ctx.computed) layers.push(computedStyle(ctx, cell, t));
405
+ if (hasBreak) layers.push({ alignment: { wrapText: true } });
406
+ const numFmt = cell.getAttribute("data-numfmt");
407
+ if (numFmt) layers.push({ numFmt: /^\d+$/.test(numFmt) ? Number(numFmt) : numFmt });
408
+ const style = layers.some(Boolean) ? require_sheet_names.mergeStyles(...layers) : void 0;
409
+ const hyperlink = ctx.links ? linkOf(ctx, cell, ref) : void 0;
410
+ row[c] = style === void 0 && hyperlink === void 0 ? value : {
411
+ value,
412
+ ...style ? { style } : {},
413
+ ...hyperlink ? { hyperlink } : {}
414
+ };
415
+ }
416
+ maxCol = Math.max(maxCol, c + colspan - 1);
417
+ c += colspan;
418
+ }
419
+ });
420
+ const sheet = {
421
+ name,
422
+ rows: out
423
+ };
424
+ if (merges.length) sheet.merges = merges;
425
+ const view = {};
426
+ if (rtl) view.rightToLeft = true;
427
+ if (options.freezeHeader && headerCount > 0) view.freeze = { rows: headerCount };
428
+ if (Object.keys(view).length) sheet.view = view;
429
+ if (options.autoFilter && headerCount > 0 && maxCol >= 0) sheet.autoFilter = `A${headerCount}:${colName(maxCol)}${Math.max(headerCount, out.length)}`;
430
+ if (options.autoWidth) sheet.colProps = autoWidths(out, typeof options.autoWidth === "object" ? options.autoWidth : {}).map((width) => ({ width }));
431
+ return sheet;
432
+ }
433
+ function colName(c) {
434
+ let s = "";
435
+ for (let n = c + 1; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + (n - 1) % 26) + s;
436
+ return s;
437
+ }
438
+ exports.DOWNLOAD_REVOKE_DELAY_MS = DOWNLOAD_REVOKE_DELAY_MS;
439
+ exports.download = download;
440
+ exports.fromTable = fromTable;