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/dom.d.cts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * javascript-excel/dom: HTML table input and file download (docs/api.md §5.4).
3
+ *
4
+ * The only module that touches the DOM. Importing it never reads a global, so
5
+ * it is safe during server-side rendering; the DOM is used only inside the
6
+ * functions, and a table is read through its own window (iframes work).
7
+ */
8
+ import { t as AutoWidthOptions } from "./auto-width-2oBzjeNG.cjs";
9
+ import { M as Sheet, P as Style, a as BlobType, f as CellInput, n as ExcelWarningCode, t as ExcelWarning } from "./warnings-C_12PT4t.cjs";
10
+ /** `HTMLTableElement` when the consumer has DOM types, else `object`. */
11
+ export type TableElement = typeof globalThis extends {
12
+ HTMLTableElement: {
13
+ prototype: infer T;
14
+ };
15
+ } ? T : object;
16
+ /** `HTMLTableCellElement` when the consumer has DOM types, else `object`. */
17
+ export type TableCellElement = typeof globalThis extends {
18
+ HTMLTableCellElement: {
19
+ prototype: infer T;
20
+ };
21
+ } ? T : object;
22
+ /** Options for `fromTable`. */
23
+ export interface FromTableOptions {
24
+ /** Sheet name, default 'Sheet1'. An invalid name throws INVALID_SHEET_NAME (§12 Q19). */
25
+ name?: string | undefined;
26
+ /** Header rows: 'thead' (default: the rows of <thead>), a fixed number of rows, or false. */
27
+ header?: "thead" | number | false | undefined;
28
+ /** Base style of header rows; default { font: { bold: true } }. */
29
+ headerStyle?: Style | undefined;
30
+ /** Include <tfoot> rows (last). Default true. */
31
+ includeFooter?: boolean | undefined;
32
+ /** Skip rows and cells with the `hidden` attribute or inline display:none (with styles: 'computed', also computed display:none). Default true. */
33
+ skipHidden?: boolean | undefined;
34
+ /** Rows and cells matching this selector are skipped. Default '[data-export-ignore]'. */
35
+ ignore?: string | undefined;
36
+ /** 'none' (default) or 'computed': map computed styles to cell styles. */
37
+ styles?: "none" | "computed" | undefined;
38
+ /** Turn plain numbers and TRUE/FALSE text into numbers and booleans. Default false. */
39
+ inferTypes?: boolean | undefined;
40
+ /** The first <a href> in a cell becomes its hyperlink. Default true. */
41
+ links?: boolean | undefined;
42
+ /** Link schemes kept; others are dropped with a HYPERLINK_DROPPED warning. Default ['http', 'https', 'mailto']. */
43
+ hyperlinkSchemes?: string[] | undefined;
44
+ /** Freeze the header rows. */
45
+ freezeHeader?: boolean | undefined;
46
+ /** Autofilter over the last header row and the body. Needs at least one header row. */
47
+ autoFilter?: boolean | undefined;
48
+ /** Estimate column widths from the text. */
49
+ autoWidth?: boolean | AutoWidthOptions | undefined;
50
+ /** Per-cell hook: return a CellInput to use instead of the default mapping, or undefined to keep it. */
51
+ cell?: ((el: TableCellElement, ctx: {
52
+ row: number;
53
+ col: number;
54
+ header: boolean;
55
+ }) => CellInput | undefined) | undefined;
56
+ /** Called for data problems that do not stop the conversion (COERCION_FAILED, HYPERLINK_DROPPED). */
57
+ onWarning?: ((w: ExcelWarning) => void) | undefined;
58
+ }
59
+ /** Options for `download`. */
60
+ export interface DownloadOptions {
61
+ /** Content type. Default from the data: a Blob keeps its own; otherwise from the file extension (.xlsx, .csv), else text/plain for strings and application/octet-stream for bytes. */
62
+ mimeType?: string | undefined;
63
+ }
64
+ /**
65
+ * How long the object URL stays valid after the click. Browsers start the
66
+ * download asynchronously, and Safari needs the URL for a while; 40 s is the
67
+ * delay FileSaver.js uses. Not measured here.
68
+ */
69
+ export declare const DOWNLOAD_REVOKE_DELAY_MS = 4e4;
70
+ /**
71
+ * Saves data as a file in the browser: creates an object URL, clicks a
72
+ * temporary `<a download>` and revokes the URL after DOWNLOAD_REVOKE_DELAY_MS.
73
+ * A string is encoded as UTF-8. Throws ENVIRONMENT_UNSUPPORTED without a DOM.
74
+ */
75
+ export declare function download(data: Uint8Array | BlobType | string, filename: string, options?: DownloadOptions): void;
76
+ /** Reads an HTML table into a Sheet: values, merges from colspan/rowspan, hints, links and (optionally) styles. */
77
+ export declare function fromTable(table: TableElement, options?: FromTableOptions): Sheet;
78
+ export type { AutoWidthOptions, BlobType, CellInput, ExcelWarning, ExcelWarningCode, Sheet, Style };
package/dist/dom.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * javascript-excel/dom: HTML table input and file download (docs/api.md §5.4).
3
+ *
4
+ * The only module that touches the DOM. Importing it never reads a global, so
5
+ * it is safe during server-side rendering; the DOM is used only inside the
6
+ * functions, and a table is read through its own window (iframes work).
7
+ */
8
+ import { t as AutoWidthOptions } from "./auto-width-CT-BihTW.js";
9
+ import { I as BlobType, j as Style, k as Sheet, l as CellInput, n as ExcelWarningCode, t as ExcelWarning } from "./warnings-DXJKe1lx.js";
10
+ /** `HTMLTableElement` when the consumer has DOM types, else `object`. */
11
+ export type TableElement = typeof globalThis extends {
12
+ HTMLTableElement: {
13
+ prototype: infer T;
14
+ };
15
+ } ? T : object;
16
+ /** `HTMLTableCellElement` when the consumer has DOM types, else `object`. */
17
+ export type TableCellElement = typeof globalThis extends {
18
+ HTMLTableCellElement: {
19
+ prototype: infer T;
20
+ };
21
+ } ? T : object;
22
+ /** Options for `fromTable`. */
23
+ export interface FromTableOptions {
24
+ /** Sheet name, default 'Sheet1'. An invalid name throws INVALID_SHEET_NAME (§12 Q19). */
25
+ name?: string | undefined;
26
+ /** Header rows: 'thead' (default: the rows of <thead>), a fixed number of rows, or false. */
27
+ header?: "thead" | number | false | undefined;
28
+ /** Base style of header rows; default { font: { bold: true } }. */
29
+ headerStyle?: Style | undefined;
30
+ /** Include <tfoot> rows (last). Default true. */
31
+ includeFooter?: boolean | undefined;
32
+ /** Skip rows and cells with the `hidden` attribute or inline display:none (with styles: 'computed', also computed display:none). Default true. */
33
+ skipHidden?: boolean | undefined;
34
+ /** Rows and cells matching this selector are skipped. Default '[data-export-ignore]'. */
35
+ ignore?: string | undefined;
36
+ /** 'none' (default) or 'computed': map computed styles to cell styles. */
37
+ styles?: "none" | "computed" | undefined;
38
+ /** Turn plain numbers and TRUE/FALSE text into numbers and booleans. Default false. */
39
+ inferTypes?: boolean | undefined;
40
+ /** The first <a href> in a cell becomes its hyperlink. Default true. */
41
+ links?: boolean | undefined;
42
+ /** Link schemes kept; others are dropped with a HYPERLINK_DROPPED warning. Default ['http', 'https', 'mailto']. */
43
+ hyperlinkSchemes?: string[] | undefined;
44
+ /** Freeze the header rows. */
45
+ freezeHeader?: boolean | undefined;
46
+ /** Autofilter over the last header row and the body. Needs at least one header row. */
47
+ autoFilter?: boolean | undefined;
48
+ /** Estimate column widths from the text. */
49
+ autoWidth?: boolean | AutoWidthOptions | undefined;
50
+ /** Per-cell hook: return a CellInput to use instead of the default mapping, or undefined to keep it. */
51
+ cell?: ((el: TableCellElement, ctx: {
52
+ row: number;
53
+ col: number;
54
+ header: boolean;
55
+ }) => CellInput | undefined) | undefined;
56
+ /** Called for data problems that do not stop the conversion (COERCION_FAILED, HYPERLINK_DROPPED). */
57
+ onWarning?: ((w: ExcelWarning) => void) | undefined;
58
+ }
59
+ /** Options for `download`. */
60
+ export interface DownloadOptions {
61
+ /** Content type. Default from the data: a Blob keeps its own; otherwise from the file extension (.xlsx, .csv), else text/plain for strings and application/octet-stream for bytes. */
62
+ mimeType?: string | undefined;
63
+ }
64
+ /**
65
+ * How long the object URL stays valid after the click. Browsers start the
66
+ * download asynchronously, and Safari needs the URL for a while; 40 s is the
67
+ * delay FileSaver.js uses. Not measured here.
68
+ */
69
+ export declare const DOWNLOAD_REVOKE_DELAY_MS = 4e4;
70
+ /**
71
+ * Saves data as a file in the browser: creates an object URL, clicks a
72
+ * temporary `<a download>` and revokes the URL after DOWNLOAD_REVOKE_DELAY_MS.
73
+ * A string is encoded as UTF-8. Throws ENVIRONMENT_UNSUPPORTED without a DOM.
74
+ */
75
+ export declare function download(data: Uint8Array | BlobType | string, filename: string, options?: DownloadOptions): void;
76
+ /** Reads an HTML table into a Sheet: values, merges from colspan/rowspan, hints, links and (optionally) styles. */
77
+ export declare function fromTable(table: TableElement, options?: FromTableOptions): Sheet;
78
+ export type { AutoWidthOptions, BlobType, CellInput, ExcelWarning, ExcelWarningCode, Sheet, Style };
package/dist/dom.js ADDED
@@ -0,0 +1,437 @@
1
+ import { c as hyperlinkSchemes, h as mergeStyles, i as DEFAULT_HYPERLINK_SCHEMES, l as textWidth, m as cellText, n as validateSheetName, r as AUTO_WIDTH } from "./sheet-names-uT2EH5Ui.js";
2
+ import { n as EnvironmentError, o as ValidationError } from "./errors-CvGlfw0E.js";
3
+ import { n as parseIsoDate } from "./iso-date-CXnn-9mT.js";
4
+ // src/auto-width.ts
5
+ /**
6
+ * Auto column widths for builders (docs/api.md §4.3, §5.4).
7
+ */
8
+ /** Estimated width in characters per column: widest `cellText` + 2 padding, clamped to [min, max]. */
9
+ function autoWidths(rows, options = {}) {
10
+ const min = options.min ?? AUTO_WIDTH.min;
11
+ const max = Math.min(255, options.max ?? AUTO_WIDTH.max);
12
+ const limit = Math.min(rows.length, options.sampleRows ?? rows.length);
13
+ const widest = [];
14
+ for (let r = 0; r < limit; r++) {
15
+ const row = rows[r];
16
+ if (!row) continue;
17
+ for (let c = 0; c < row.length; c++) {
18
+ const w = textWidth(cellText(row[c]));
19
+ if (w > (widest[c] ?? 0)) widest[c] = w;
20
+ }
21
+ }
22
+ return Array.from(widest, (w) => Math.min(max, Math.max(min, (w ?? 0) + AUTO_WIDTH.padding)));
23
+ }
24
+ // src/internal/css-color.ts
25
+ /** CSS colour values to RRGGBB, for computed-style mapping in javascript-excel/dom. */
26
+ const NAMED = {
27
+ black: "000000",
28
+ white: "FFFFFF",
29
+ red: "FF0000",
30
+ lime: "00FF00",
31
+ green: "008000",
32
+ blue: "0000FF",
33
+ yellow: "FFFF00",
34
+ cyan: "00FFFF",
35
+ aqua: "00FFFF",
36
+ magenta: "FF00FF",
37
+ fuchsia: "FF00FF",
38
+ silver: "C0C0C0",
39
+ gray: "808080",
40
+ grey: "808080",
41
+ maroon: "800000",
42
+ olive: "808000",
43
+ purple: "800080",
44
+ teal: "008080",
45
+ navy: "000080",
46
+ orange: "FFA500"
47
+ };
48
+ /** A CSS colour as RRGGBB, or undefined for transparent or unparseable values. */
49
+ function cssColor(value) {
50
+ const v = value.trim().toLowerCase();
51
+ if (!v || v === "transparent" || v === "currentcolor" || v === "inherit" || v === "initial") return void 0;
52
+ const hex = /^#([0-9a-f]{3,8})$/.exec(v)?.[1];
53
+ if (hex) {
54
+ if (hex.length === 3 || hex.length === 4) {
55
+ if (hex.length === 4 && hex[3] === "0") return void 0;
56
+ return hex.slice(0, 3).split("").map((c) => c + c).join("").toUpperCase();
57
+ }
58
+ if (hex.length === 6) return hex.toUpperCase();
59
+ if (hex.length === 8) return hex.slice(6) === "00" ? void 0 : hex.slice(0, 6).toUpperCase();
60
+ return;
61
+ }
62
+ const m = /^rgba?\(\s*([\d.]+%?)[\s,]+([\d.]+%?)[\s,]+([\d.]+%?)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(v);
63
+ if (m) {
64
+ const ch = (s) => Math.round(Math.min(255, Math.max(0, s.endsWith("%") ? parseFloat(s) * 255 / 100 : parseFloat(s))));
65
+ if (m[4] !== void 0) {
66
+ if (!((m[4].endsWith("%") ? parseFloat(m[4]) / 100 : parseFloat(m[4])) > 0)) return void 0;
67
+ }
68
+ return [
69
+ m[1],
70
+ m[2],
71
+ m[3]
72
+ ].map((s) => ch(s).toString(16).padStart(2, "0")).join("").toUpperCase();
73
+ }
74
+ return NAMED[v];
75
+ }
76
+ function isElement(n) {
77
+ return n.nodeType === 1;
78
+ }
79
+ // src/dom.ts
80
+ /**
81
+ * javascript-excel/dom: HTML table input and file download (docs/api.md §5.4).
82
+ *
83
+ * The only module that touches the DOM. Importing it never reads a global, so
84
+ * it is safe during server-side rendering; the DOM is used only inside the
85
+ * functions, and a table is read through its own window (iframes work).
86
+ */
87
+ const DEFAULT_IGNORE = "[data-export-ignore]";
88
+ const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
89
+ /** HTML's limits on colspan and rowspan. */
90
+ const MAX_COLSPAN = 1e3;
91
+ const MAX_ROWSPAN = 65534;
92
+ /**
93
+ * How long the object URL stays valid after the click. Browsers start the
94
+ * download asynchronously, and Safari needs the URL for a while; 40 s is the
95
+ * delay FileSaver.js uses. Not measured here.
96
+ */
97
+ const DOWNLOAD_REVOKE_DELAY_MS = 4e4;
98
+ function mimeFor(filename, data) {
99
+ const ext = /\.([A-Za-z0-9]+)$/.exec(filename)?.[1]?.toLowerCase();
100
+ if (ext === "xlsx") return XLSX_MIME;
101
+ if (ext === "csv") return "text/csv;charset=utf-8";
102
+ return typeof data === "string" ? "text/plain;charset=utf-8" : "application/octet-stream";
103
+ }
104
+ /**
105
+ * Saves data as a file in the browser: creates an object URL, clicks a
106
+ * temporary `<a download>` and revokes the URL after DOWNLOAD_REVOKE_DELAY_MS.
107
+ * A string is encoded as UTF-8. Throws ENVIRONMENT_UNSUPPORTED without a DOM.
108
+ */
109
+ function download(data, filename, options) {
110
+ const g = globalThis;
111
+ const doc = g.document;
112
+ if (!doc?.body || typeof g.URL?.createObjectURL !== "function" || typeof g.Blob !== "function") throw new EnvironmentError("ENVIRONMENT_UNSUPPORTED", "download() needs a browser DOM (document, URL.createObjectURL, Blob).", { details: { api: "document" } });
113
+ if (typeof filename !== "string" || filename.length === 0) throw new TypeError("download(): filename must be a non-empty string");
114
+ const Blob = g.Blob;
115
+ const isBlob = typeof data === "object" && data !== null && !(data instanceof Uint8Array);
116
+ let blob;
117
+ if (isBlob) {
118
+ const b = data;
119
+ blob = options?.mimeType && b.type !== options.mimeType ? new Blob([b], { type: options.mimeType }) : b;
120
+ } else blob = new Blob([data], { type: options?.mimeType ?? mimeFor(filename, data) });
121
+ const url = g.URL.createObjectURL(blob);
122
+ const a = doc.createElement("a");
123
+ a.href = url;
124
+ a.download = filename;
125
+ a.rel = "noopener";
126
+ a.style.display = "none";
127
+ doc.body.appendChild(a);
128
+ try {
129
+ a.click();
130
+ } finally {
131
+ a.remove();
132
+ const revoke = () => g.URL.revokeObjectURL(url);
133
+ if (typeof g.setTimeout === "function") g.setTimeout(revoke, DOWNLOAD_REVOKE_DELAY_MS);
134
+ else revoke();
135
+ }
136
+ }
137
+ function css(ctx, el, prop) {
138
+ if (!ctx.view) return "";
139
+ try {
140
+ return ctx.view.getComputedStyle(el).getPropertyValue(prop).trim();
141
+ } catch {
142
+ return "";
143
+ }
144
+ }
145
+ function inlineDisplayNone(el) {
146
+ const style = el.getAttribute("style");
147
+ return style !== null && /(?:^|;)\s*display\s*:\s*none\s*(?:!important\s*)?(?:;|$)/i.test(style);
148
+ }
149
+ function skipped(ctx, el) {
150
+ if (el.matches(ctx.ignore)) return true;
151
+ if (!ctx.skipHidden) return false;
152
+ if (el.hasAttribute("hidden") || inlineDisplayNone(el)) return true;
153
+ return ctx.computed && css(ctx, el, "display") === "none";
154
+ }
155
+ const SKIP_TEXT = /* @__PURE__ */ new Set([
156
+ "SCRIPT",
157
+ "STYLE",
158
+ "TEMPLATE",
159
+ "NOSCRIPT"
160
+ ]);
161
+ /** Text of a cell: whitespace collapsed per line, <br> as a newline. */
162
+ function cellTextOf(el) {
163
+ const lines = [""];
164
+ let hasBreak = false;
165
+ const walk = (n) => {
166
+ if (n.nodeType === 3) {
167
+ lines[lines.length - 1] += n.textContent ?? "";
168
+ return;
169
+ }
170
+ if (!isElement(n)) return;
171
+ const tag = n.tagName.toUpperCase();
172
+ if (SKIP_TEXT.has(tag)) return;
173
+ if (tag === "BR") {
174
+ lines.push("");
175
+ hasBreak = true;
176
+ return;
177
+ }
178
+ for (let i = 0; i < n.childNodes.length; i++) walk(n.childNodes[i]);
179
+ };
180
+ for (let i = 0; i < el.childNodes.length; i++) walk(el.childNodes[i]);
181
+ return {
182
+ text: lines.map((l) => l.replace(/[ \t\n\r\f ]+/g, " ").trim()).join("\n").replace(/^\n+|\n+$/g, ""),
183
+ hasBreak
184
+ };
185
+ }
186
+ const PLAIN_NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
187
+ const GROUPED_NUMBER = /^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/;
188
+ function parseNumber(s) {
189
+ const t = s.trim();
190
+ if (PLAIN_NUMBER.test(t)) return Number(t);
191
+ if (GROUPED_NUMBER.test(t)) return Number(t.replace(/,/g, ""));
192
+ }
193
+ function parseBoolean(s) {
194
+ const t = s.trim().toLowerCase();
195
+ if (t === "true" || t === "yes" || t === "1") return true;
196
+ if (t === "false" || t === "no" || t === "0") return false;
197
+ }
198
+ function coerce(ctx, raw, type, ref) {
199
+ if (type === null || type === "" || type === "string") {
200
+ if (ctx.inferTypes) {
201
+ const n = PLAIN_NUMBER.test(raw.trim()) ? Number(raw.trim()) : void 0;
202
+ if (n !== void 0 && Number.isFinite(n)) return n;
203
+ const t = raw.trim().toLowerCase();
204
+ if (t === "true") return true;
205
+ if (t === "false") return false;
206
+ }
207
+ return raw;
208
+ }
209
+ const fail = () => {
210
+ ctx.warn({
211
+ code: "COERCION_FAILED",
212
+ message: `${ctx.sheet}!${ref}: ${JSON.stringify(raw)} is not a valid ${type}; kept as text.`,
213
+ sheet: ctx.sheet,
214
+ ref
215
+ });
216
+ return raw;
217
+ };
218
+ switch (type) {
219
+ case "number": {
220
+ const n = parseNumber(raw);
221
+ return n !== void 0 && Number.isFinite(n) ? n : fail();
222
+ }
223
+ case "boolean": return parseBoolean(raw) ?? fail();
224
+ case "date": return parseIsoDate(raw) ?? fail();
225
+ default:
226
+ ctx.warn({
227
+ code: "COERCION_FAILED",
228
+ message: `${ctx.sheet}!${ref}: unknown data-type ${JSON.stringify(type)}; kept as text.`,
229
+ sheet: ctx.sheet,
230
+ ref
231
+ });
232
+ return raw;
233
+ }
234
+ }
235
+ /** The first non-transparent background of the cell, its row, section or table (what a reader sees). */
236
+ function backgroundOf(ctx, cell, table) {
237
+ for (let el = cell; el; el = el.parentElement) {
238
+ const c = cssColor(css(ctx, el, "background-color"));
239
+ if (c) return c;
240
+ if (el === table) break;
241
+ }
242
+ }
243
+ function computedStyle(ctx, el, table) {
244
+ const style = {};
245
+ const font = {};
246
+ const weight = css(ctx, el, "font-weight");
247
+ if (weight === "bold" || weight === "bolder" || Number(weight) >= 600) font.bold = true;
248
+ const fs = css(ctx, el, "font-style");
249
+ if (fs === "italic" || fs.startsWith("oblique")) font.italic = true;
250
+ const deco = `${css(ctx, el, "text-decoration-line")} ${css(ctx, el, "text-decoration")}`;
251
+ if (/\bunderline\b/.test(deco)) font.underline = true;
252
+ if (/\bline-through\b/.test(deco)) font.strike = true;
253
+ const color = cssColor(css(ctx, el, "color"));
254
+ if (color && color !== "000000") font.color = color;
255
+ if (Object.keys(font).length) style.font = font;
256
+ const bg = backgroundOf(ctx, el, table);
257
+ if (bg) style.fill = bg;
258
+ const alignment = {};
259
+ const ta = css(ctx, el, "text-align");
260
+ const h = /^(?:-webkit-|-internal-|-moz-)?center$/.test(ta) ? "center" : ta;
261
+ if (h === "left" || h === "right" || h === "center" || h === "justify") alignment.horizontal = h;
262
+ const va = css(ctx, el, "vertical-align");
263
+ if (va === "top" || va === "bottom") alignment.vertical = va;
264
+ const ws = css(ctx, el, "white-space");
265
+ if (ws === "pre-wrap" || ws === "pre-line" || ws === "break-spaces") alignment.wrapText = true;
266
+ if (Object.keys(alignment).length) style.alignment = alignment;
267
+ return Object.keys(style).length ? style : void 0;
268
+ }
269
+ function linkOf(ctx, cell, ref) {
270
+ const find = (n) => {
271
+ for (let i = 0; i < n.children.length; i++) {
272
+ const c = n.children[i];
273
+ if (c.tagName.toUpperCase() === "A" && c.hasAttribute("href")) return c;
274
+ const deeper = find(c);
275
+ if (deeper) return deeper;
276
+ }
277
+ };
278
+ const a = find(cell);
279
+ if (!a) return void 0;
280
+ const raw = a.getAttribute("href") ?? "";
281
+ if (raw.startsWith("#") || raw.trim() === "") return void 0;
282
+ const url = typeof a.href === "string" && a.href ? a.href : raw;
283
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(url)?.[1]?.toLowerCase();
284
+ if (!scheme || !ctx.schemes.has(scheme)) {
285
+ ctx.warn({
286
+ code: "HYPERLINK_DROPPED",
287
+ message: `${ctx.sheet}!${ref}: link ${JSON.stringify(url)} dropped (scheme not allowed).`,
288
+ sheet: ctx.sheet,
289
+ ref
290
+ });
291
+ return;
292
+ }
293
+ return url;
294
+ }
295
+ /** Rows in reading order: <thead> rows, then <tbody> and bare <tr> rows, then <tfoot> rows. */
296
+ function collectRows(table, includeFooter) {
297
+ const head = [];
298
+ const body = [];
299
+ const foot = [];
300
+ const bare = [];
301
+ const trs = (section) => Array.from(section.children).filter((c) => c.tagName.toUpperCase() === "TR");
302
+ for (const child of Array.from(table.children)) {
303
+ const tag = child.tagName.toUpperCase();
304
+ if (tag === "THEAD") head.push(trs(child));
305
+ else if (tag === "TBODY") {
306
+ if (bare.length) body.push(bare.splice(0));
307
+ body.push(trs(child));
308
+ } else if (tag === "TFOOT") {
309
+ if (includeFooter) foot.push(trs(child));
310
+ } else if (tag === "TR") bare.push(child);
311
+ }
312
+ if (bare.length) body.push(bare);
313
+ const groups = [
314
+ ...head,
315
+ ...body,
316
+ ...foot
317
+ ];
318
+ const rows = groups.flat();
319
+ const sections = [];
320
+ groups.forEach((g, i) => g.forEach(() => sections.push(i)));
321
+ return {
322
+ rows,
323
+ sections
324
+ };
325
+ }
326
+ function intAttr(el, name, fallback, min, max) {
327
+ const v = el.getAttribute(name);
328
+ if (v === null) return fallback;
329
+ const n = Number.parseInt(v, 10);
330
+ if (!Number.isFinite(n)) return fallback;
331
+ return Math.min(max, Math.max(min, n));
332
+ }
333
+ /** Reads an HTML table into a Sheet: values, merges from colspan/rowspan, hints, links and (optionally) styles. */
334
+ function fromTable(table, options = {}) {
335
+ const t = table;
336
+ if (typeof t !== "object" || t === null || typeof t.tagName !== "string" || typeof t.matches !== "function") throw new EnvironmentError("ENVIRONMENT_UNSUPPORTED", "fromTable() needs a DOM <table> element.", { details: { api: "HTMLTableElement" } });
337
+ if (t.tagName.toUpperCase() !== "TABLE") throw new TypeError(`fromTable(): expected a <table> element, got <${t.tagName.toLowerCase()}>`);
338
+ const name = options.name ?? "Sheet1";
339
+ const problem = validateSheetName(name);
340
+ if (problem) throw new ValidationError("INVALID_SHEET_NAME", `fromTable(): sheet name ${JSON.stringify(name)} is invalid (${problem}).`, { details: {
341
+ sheet: name,
342
+ problem
343
+ } });
344
+ const ctx = {
345
+ view: t.ownerDocument?.defaultView ?? null,
346
+ computed: options.styles === "computed",
347
+ skipHidden: options.skipHidden !== false,
348
+ ignore: options.ignore ?? DEFAULT_IGNORE,
349
+ inferTypes: options.inferTypes === true,
350
+ links: options.links !== false,
351
+ schemes: options.hyperlinkSchemes === void 0 ? new Set(DEFAULT_HYPERLINK_SCHEMES) : hyperlinkSchemes(options.hyperlinkSchemes),
352
+ sheet: name,
353
+ warn: options.onWarning ?? (() => {})
354
+ };
355
+ const rtl = t.closest("[dir]")?.getAttribute("dir")?.toLowerCase() === "rtl" || ctx.computed && css(ctx, t, "direction") === "rtl";
356
+ const { rows: allRows, sections: allSections } = collectRows(t, options.includeFooter !== false);
357
+ const header = options.header ?? "thead";
358
+ const headerStyle = options.headerStyle ?? { font: { bold: true } };
359
+ const out = [];
360
+ const merges = [];
361
+ const occupied = [];
362
+ const occupy = (r, c) => {
363
+ (occupied[r] ??= [])[c] = true;
364
+ };
365
+ const kept = allRows.map((tr, i) => ({
366
+ tr,
367
+ section: allSections[i]
368
+ })).filter(({ tr }) => !skipped(ctx, tr));
369
+ const headerCount = header === "thead" ? kept.filter(({ tr }) => tr.parentElement?.tagName.toUpperCase() === "THEAD").length : header === false ? 0 : Math.max(0, Math.trunc(header));
370
+ let maxCol = -1;
371
+ kept.forEach(({ tr, section }, r) => {
372
+ const row = out[r] ??= [];
373
+ let c = 0;
374
+ for (const cell of Array.from(tr.children)) {
375
+ const tag = cell.tagName.toUpperCase();
376
+ if (tag !== "TD" && tag !== "TH") continue;
377
+ if (skipped(ctx, cell)) continue;
378
+ while (occupied[r]?.[c]) c++;
379
+ const colspan = intAttr(cell, "colspan", 1, 1, MAX_COLSPAN);
380
+ let rowspan = intAttr(cell, "rowspan", 1, 0, MAX_ROWSPAN);
381
+ if (rowspan === 0) {
382
+ let end = r;
383
+ while (end + 1 < kept.length && kept[end + 1].section === section) end++;
384
+ rowspan = end - r + 1;
385
+ }
386
+ rowspan = Math.min(rowspan, kept.length - r);
387
+ for (let dr = 0; dr < rowspan; dr++) for (let dc = 0; dc < colspan; dc++) occupy(r + dr, c + dc);
388
+ const ref = `${colName(c)}${r + 1}`;
389
+ if (colspan > 1 || rowspan > 1) merges.push(`${ref}:${colName(c + colspan - 1)}${r + rowspan}`);
390
+ const isHeader = r < headerCount;
391
+ const hooked = options.cell?.(cell, {
392
+ row: r,
393
+ col: c,
394
+ header: isHeader
395
+ });
396
+ if (hooked !== void 0) row[c] = hooked;
397
+ else {
398
+ const dataValue = cell.getAttribute("data-value");
399
+ const { text, hasBreak } = cellTextOf(cell);
400
+ const value = coerce(ctx, dataValue ?? text, cell.getAttribute("data-type"), ref);
401
+ const layers = [];
402
+ if (isHeader) layers.push(headerStyle);
403
+ if (ctx.computed) layers.push(computedStyle(ctx, cell, t));
404
+ if (hasBreak) layers.push({ alignment: { wrapText: true } });
405
+ const numFmt = cell.getAttribute("data-numfmt");
406
+ if (numFmt) layers.push({ numFmt: /^\d+$/.test(numFmt) ? Number(numFmt) : numFmt });
407
+ const style = layers.some(Boolean) ? mergeStyles(...layers) : void 0;
408
+ const hyperlink = ctx.links ? linkOf(ctx, cell, ref) : void 0;
409
+ row[c] = style === void 0 && hyperlink === void 0 ? value : {
410
+ value,
411
+ ...style ? { style } : {},
412
+ ...hyperlink ? { hyperlink } : {}
413
+ };
414
+ }
415
+ maxCol = Math.max(maxCol, c + colspan - 1);
416
+ c += colspan;
417
+ }
418
+ });
419
+ const sheet = {
420
+ name,
421
+ rows: out
422
+ };
423
+ if (merges.length) sheet.merges = merges;
424
+ const view = {};
425
+ if (rtl) view.rightToLeft = true;
426
+ if (options.freezeHeader && headerCount > 0) view.freeze = { rows: headerCount };
427
+ if (Object.keys(view).length) sheet.view = view;
428
+ if (options.autoFilter && headerCount > 0 && maxCol >= 0) sheet.autoFilter = `A${headerCount}:${colName(maxCol)}${Math.max(headerCount, out.length)}`;
429
+ if (options.autoWidth) sheet.colProps = autoWidths(out, typeof options.autoWidth === "object" ? options.autoWidth : {}).map((width) => ({ width }));
430
+ return sheet;
431
+ }
432
+ function colName(c) {
433
+ let s = "";
434
+ for (let n = c + 1; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + (n - 1) % 26) + s;
435
+ return s;
436
+ }
437
+ export { DOWNLOAD_REVOKE_DELAY_MS, download, fromTable };
@@ -0,0 +1,28 @@
1
+ // src/errors.ts
2
+ const BRAND = Symbol.for("javascript-excel.error");
3
+ /** Base class of every error the library throws. */
4
+ var ExcelError = class extends Error {
5
+ code;
6
+ constructor(code, message, options) {
7
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
8
+ this.name = new.target.name;
9
+ this.code = code;
10
+ if (options?.details !== void 0) this.details = options.details;
11
+ Object.defineProperty(this, BRAND, { value: true });
12
+ }
13
+ };
14
+ /** The model or options cannot be written. */
15
+ var ValidationError = class extends ExcelError {};
16
+ /** The input is not a readable xlsx or zip file. */
17
+ var FormatError = class extends ExcelError {};
18
+ /** A read limit was exceeded; `details.limit` names it. */
19
+ var LimitError = class extends ExcelError {};
20
+ /** Malformed CSV in strict mode. */
21
+ var CsvError = class extends ExcelError {};
22
+ /** A required platform API is missing. */
23
+ var EnvironmentError = class extends ExcelError {};
24
+ /** True for any error thrown by this library, across ESM/CJS copies and realms. */
25
+ function isExcelError(e) {
26
+ return typeof e === "object" && e !== null && e[BRAND] === true;
27
+ }
28
+ export { LimitError as a, FormatError as i, EnvironmentError as n, ValidationError as o, ExcelError as r, isExcelError as s, CsvError as t };