react-smart-copy 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/table.js ADDED
@@ -0,0 +1,838 @@
1
+ //#region src/core/errors.ts
2
+ function createCopyError(type, message, cause) {
3
+ return cause === void 0 ? {
4
+ type,
5
+ message
6
+ } : {
7
+ type,
8
+ message,
9
+ cause
10
+ };
11
+ }
12
+ /**
13
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
14
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
15
+ */
16
+ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
17
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
18
+ var CopyFailure = class extends Error {
19
+ constructor(copyError) {
20
+ super(copyError.message);
21
+ this[COPY_FAILURE_BRAND] = true;
22
+ this.name = "CopyFailure";
23
+ this.copyError = copyError;
24
+ }
25
+ };
26
+ /** Shorthand for throwing a classified failure. */
27
+ function copyFailure(type, message, cause) {
28
+ return new CopyFailure(createCopyError(type, message, cause));
29
+ }
30
+ //#endregion
31
+ //#region src/table/serialize.ts
32
+ const DEFAULT_TABLE_MAX_CELLS = 1e6;
33
+ const FORMULA_START = /^[=+\-@\t\r\n=+-@]/;
34
+ const LINE_BREAKS = /\r\n?/g;
35
+ const EMPTY = {
36
+ text: "",
37
+ kind: "text"
38
+ };
39
+ const invalid$3 = (message) => copyFailure("invalid-payload", message);
40
+ /** Only called for values that are not null, undefined or a cell. */
41
+ function typeName(value) {
42
+ if (Array.isArray(value)) return "array";
43
+ return typeof value === "object" ? Object.prototype.toString.call(value).slice(8, -1) : typeof value;
44
+ }
45
+ function isRecord(value) {
46
+ return typeof value === "object" && value !== null;
47
+ }
48
+ function isList(value) {
49
+ return Array.isArray(value);
50
+ }
51
+ function isDate$1(value) {
52
+ return value instanceof Date || Object.prototype.toString.call(value) === "[object Date]";
53
+ }
54
+ function resolveLimit(value, fallback, name) {
55
+ if (value === void 0) return fallback;
56
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
57
+ throw invalid$3(`\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
58
+ }
59
+ function defaultText(value, where) {
60
+ if (value === null || value === void 0) return {
61
+ text: "",
62
+ kind: "text"
63
+ };
64
+ switch (typeof value) {
65
+ case "string": return {
66
+ text: value,
67
+ kind: "text"
68
+ };
69
+ case "number":
70
+ case "bigint":
71
+ case "boolean": return {
72
+ text: String(value),
73
+ kind: "value"
74
+ };
75
+ default:
76
+ if (isDate$1(value)) {
77
+ const time = value.getTime();
78
+ return {
79
+ text: Number.isNaN(time) ? "" : value.toISOString(),
80
+ kind: "value"
81
+ };
82
+ }
83
+ throw invalid$3(`${where} is ${typeName(value)}, which has no text form. Pass a string, number, bigint, boolean, Date, null or undefined, or convert it with \`formatCell\`.`);
84
+ }
85
+ }
86
+ function prepare(data, options) {
87
+ const input = data;
88
+ if (!isRecord(input) || !isList(input["rows"])) throw invalid$3("Table data must be an object with a `rows` array.");
89
+ const rawHeaders = input["headers"];
90
+ if (rawHeaders !== void 0 && rawHeaders !== null && !isList(rawHeaders)) throw invalid$3("`headers` must be an array of strings, null or undefined.");
91
+ const headers = options.headers === false ? null : rawHeaders ?? null;
92
+ const rows = input["rows"];
93
+ let width = headers?.length ?? 0;
94
+ const lines = [];
95
+ for (const [index, row] of rows.entries()) {
96
+ if (!isList(row)) throw invalid$3(`Row ${String(index + 1)} is not an array of cells.`);
97
+ width = Math.max(width, row.length);
98
+ lines.push(row);
99
+ }
100
+ if (width === 0) throw invalid$3("The table has no cells to copy.");
101
+ const maxCells = resolveLimit(options.maxCells, DEFAULT_TABLE_MAX_CELLS, "maxCells");
102
+ const cellCount = (rows.length + (headers ? 1 : 0)) * width;
103
+ if (cellCount > maxCells) throw copyFailure("too-large", `The table has ${String(cellCount)} cells, over the limit of ${String(maxCells)}. Raise \`maxCells\` or copy fewer rows.`);
104
+ const guard = options.formulaGuard ?? true;
105
+ const formatCell = options.formatCell;
106
+ const label = (column) => {
107
+ const value = headers?.[column];
108
+ return typeof value === "string" ? value : void 0;
109
+ };
110
+ const cell = (value, row, column) => {
111
+ const where = row < 0 ? `Header ${String(column + 1)}` : `Cell at row ${String(row + 1)}, column ${String(column + 1)}`;
112
+ const base = defaultText(value, where);
113
+ let text = base.text;
114
+ if (formatCell) {
115
+ const custom = formatCell(value, {
116
+ row,
117
+ column,
118
+ header: label(column)
119
+ });
120
+ if (custom !== void 0) {
121
+ if (typeof custom !== "string") throw invalid$3(`\`formatCell\` must return a string or undefined (${where}).`);
122
+ text = custom;
123
+ }
124
+ }
125
+ text = text.replace(LINE_BREAKS, "\n");
126
+ if (guard && base.kind === "text" && FORMULA_START.test(text)) text = `'${text}`;
127
+ return text === "" ? EMPTY : {
128
+ text,
129
+ kind: base.kind
130
+ };
131
+ };
132
+ return {
133
+ header: headers ? Array.from({ length: width }, (_, column) => {
134
+ const value = headers[column];
135
+ if (value !== void 0 && value !== null && typeof value !== "string") throw invalid$3(`Header ${String(column + 1)} must be a string (received ${typeName(value)}).`);
136
+ return cell(value ?? "", -1, column);
137
+ }) : null,
138
+ body: lines.map((row, rowIndex) => Array.from({ length: width }, (_, column) => cell(row[column], rowIndex, column)))
139
+ };
140
+ }
141
+ const NEEDS_QUOTES = /[\t\n\r"]/;
142
+ function tsvField(text) {
143
+ return NEEDS_QUOTES.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
144
+ }
145
+ function toTsv(table) {
146
+ const lines = table.header ? [table.header, ...table.body] : table.body;
147
+ const text = lines.map((row) => row.map((cell) => tsvField(cell.text)).join(" ")).join("\r\n");
148
+ const last = lines.at(-1);
149
+ return lines.length > 1 && last?.length === 1 && last[0]?.text === "" ? `${text}""` : text;
150
+ }
151
+ const HTML_ESCAPES = {
152
+ "&": "&amp;",
153
+ "<": "&lt;",
154
+ ">": "&gt;",
155
+ "\"": "&quot;"
156
+ };
157
+ function escapeHtml(text) {
158
+ return text.replace(/[&<>"]/g, (char) => HTML_ESCAPES[char]);
159
+ }
160
+ const SIGNIFICANT_SPACE = /^\s|\s$| {2}|\t/;
161
+ function htmlCell(tag, cell, preserveText) {
162
+ const styles = [];
163
+ if (preserveText && cell.kind === "text" && cell.text !== "") styles.push("mso-number-format:'\\@'");
164
+ if (SIGNIFICANT_SPACE.test(cell.text)) styles.push("white-space:pre-wrap");
165
+ return `<${tag}${styles.length > 0 ? ` style="${styles.join(";")}"` : ""}>${escapeHtml(cell.text).replace(/\n/g, "<br>")}</${tag}>`;
166
+ }
167
+ function toHtml(table, preserveText) {
168
+ const row = (cells, tag) => `<tr>${cells.map((cell) => htmlCell(tag, cell, preserveText)).join("")}</tr>`;
169
+ return `<table>${table.header ? `<thead>${row(table.header, "th")}</thead>` : ""}<tbody>${table.body.map((cells) => row(cells, "td")).join("")}</tbody></table>`;
170
+ }
171
+ /** `prepare` guarantees at least one line of at least one cell. */
172
+ function hasContent(table) {
173
+ const lines = table.header ? [table.header, ...table.body] : table.body;
174
+ const first = lines[0];
175
+ return lines.length > 1 || first.length > 1 || first[0].text !== "";
176
+ }
177
+ /**
178
+ * Tab-separated text, the format Excel, Google Sheets, Numbers and LibreOffice paste
179
+ * straight into cells. Cells containing tabs, line breaks or quotes are quoted the
180
+ * way Excel quotes them. Throws a `CopyFailure` (`invalid-payload` or `too-large`).
181
+ */
182
+ function tableToTsv(data, options = {}) {
183
+ return toTsv(prepare(data, options));
184
+ }
185
+ /** An HTML `<table>`: what rich editors (Docs, Word, Notion, mail) and spreadsheets read first. */
186
+ function tableToHtml(data, options = {}) {
187
+ return toHtml(prepare(data, options), options.preserveText ?? true);
188
+ }
189
+ function tablePayload(data, options = {}) {
190
+ const format = options.format ?? "html";
191
+ if (format !== "html" && format !== "text") throw invalid$3(`\`format\` must be "html" or "text" (received ${JSON.stringify(format)}).`);
192
+ const table = prepare(data, options);
193
+ if (!hasContent(table)) throw invalid$3("The table only contains one empty cell; there is nothing to copy.");
194
+ const text = toTsv(table);
195
+ return format === "text" ? {
196
+ kind: "text",
197
+ value: text
198
+ } : {
199
+ kind: "html",
200
+ html: toHtml(table, options.preserveText ?? true),
201
+ text
202
+ };
203
+ }
204
+ /**
205
+ * Turns your own row objects into {@link TableData}, choosing and ordering columns.
206
+ *
207
+ * ```ts
208
+ * fromRows(users, [
209
+ * { header: 'Name', value: 'name' },
210
+ * { header: 'Joined', value: (user) => user.joinedAt },
211
+ * ]);
212
+ * ```
213
+ */
214
+ function fromRows(rows, columns) {
215
+ const rowList = rows;
216
+ const columnList = columns;
217
+ if (!isList(rowList)) throw invalid$3("`fromRows` expects an array of rows.");
218
+ if (!isList(columnList) || columnList.length === 0) throw invalid$3("`fromRows` needs at least one column.");
219
+ const headers = [];
220
+ const readers = columnList.map((column, index) => {
221
+ if (!isRecord(column) || typeof column["header"] !== "string") throw invalid$3(`Column ${String(index + 1)} needs a string \`header\`.`);
222
+ const header = column["header"];
223
+ headers.push(header);
224
+ const value = column["value"];
225
+ if (typeof value === "function") return value;
226
+ if (typeof value === "string") return (row) => isRecord(row) ? row[value] : void 0;
227
+ throw invalid$3(`Column "${header}" needs a \`value\`: a property name or a function.`);
228
+ });
229
+ return {
230
+ headers,
231
+ rows: rows.map((row, index) => readers.map((read) => read(row, index)))
232
+ };
233
+ }
234
+ //#endregion
235
+ //#region src/table/parse.ts
236
+ const DEFAULT_PARSE_MAX_ROWS = 1e5;
237
+ const DEFAULT_PARSE_MAX_COLUMNS = 16384;
238
+ const DEFAULT_PARSE_MAX_CELLS = 1e6;
239
+ const DEFAULT_PARSE_MAX_LENGTH = 33554432;
240
+ const invalid$2 = (message) => copyFailure("invalid-payload", message);
241
+ function limit(value, fallback, name) {
242
+ if (value === void 0) return fallback;
243
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
244
+ throw invalid$2(`\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
245
+ }
246
+ function resolveLimits(options) {
247
+ return {
248
+ maxRows: limit(options.maxRows, DEFAULT_PARSE_MAX_ROWS, "maxRows"),
249
+ maxColumns: limit(options.maxColumns, DEFAULT_PARSE_MAX_COLUMNS, "maxColumns"),
250
+ maxCells: limit(options.maxCells, DEFAULT_PARSE_MAX_CELLS, "maxCells"),
251
+ maxLength: limit(options.maxLength, DEFAULT_PARSE_MAX_LENGTH, "maxLength")
252
+ };
253
+ }
254
+ function checkLength(input, limits) {
255
+ if (input.length > limits.maxLength) throw copyFailure("too-large", `The pasted content is ${String(input.length)} characters, over the limit of ${String(limits.maxLength)}.`);
256
+ }
257
+ /**
258
+ * Applies the row, column and cell limits, pads ragged rows, splits off the header
259
+ * and drops tables without a single non-empty cell.
260
+ */
261
+ function finish(grid, firstRowIsHeader, source, limits, alreadyTruncated) {
262
+ let truncated = alreadyTruncated;
263
+ let columnCount = 0;
264
+ for (const row of grid) columnCount = Math.max(columnCount, row.length);
265
+ let rowCount = Math.min(grid.length, limits.maxRows);
266
+ if (columnCount > 0) rowCount = Math.min(rowCount, Math.floor(limits.maxCells / columnCount));
267
+ if (rowCount < grid.length) truncated = true;
268
+ const shaped = [];
269
+ let anyContent = false;
270
+ for (let index = 0; index < rowCount; index++) {
271
+ const row = grid[index];
272
+ const cells = Array.from({ length: columnCount }, (_, column) => row[column] ?? "");
273
+ if (!anyContent && cells.some((cell) => cell !== "")) anyContent = true;
274
+ shaped.push(cells);
275
+ }
276
+ if (!anyContent) return null;
277
+ return {
278
+ headers: firstRowIsHeader ? shaped.shift() : null,
279
+ rows: shaped,
280
+ columnCount,
281
+ source,
282
+ truncated
283
+ };
284
+ }
285
+ /**
286
+ * Splits tab-separated text the way spreadsheets write it: a field that starts with
287
+ * `"` is quoted (`""` is a literal quote) and may contain tabs and line breaks; rows
288
+ * end in CRLF, LF or CR; the trailing line break spreadsheets add is ignored. A quote
289
+ * that never closes is read as an ordinary character, as Excel does.
290
+ */
291
+ function splitDelimited(text, delimiter, trim, limits) {
292
+ const grid = [];
293
+ const length = text.length;
294
+ let row = [];
295
+ let field = "";
296
+ let index = 0;
297
+ let fieldStart = true;
298
+ let quoting = true;
299
+ let cells = 0;
300
+ const state = {
301
+ full: false,
302
+ truncated: false
303
+ };
304
+ const pushField = () => {
305
+ if (row.length >= limits.maxColumns) state.truncated = true;
306
+ else if (cells >= limits.maxCells) state.full = true;
307
+ else {
308
+ row.push(trim ? field.trim() : field);
309
+ cells += 1;
310
+ }
311
+ field = "";
312
+ fieldStart = true;
313
+ };
314
+ const pushRow = () => {
315
+ pushField();
316
+ grid.push(row);
317
+ row = [];
318
+ if (grid.length >= limits.maxRows) state.full = true;
319
+ };
320
+ while (index < length && !state.full) {
321
+ const char = text[index];
322
+ if (fieldStart && quoting && char === "\"") {
323
+ let value = "";
324
+ let cursor = index + 1;
325
+ let closed = false;
326
+ while (cursor < length) {
327
+ const inner = text[cursor];
328
+ if (inner === "\"") {
329
+ if (text[cursor + 1] === "\"") {
330
+ value += "\"";
331
+ cursor += 2;
332
+ continue;
333
+ }
334
+ closed = true;
335
+ cursor += 1;
336
+ break;
337
+ }
338
+ value += inner;
339
+ cursor += 1;
340
+ }
341
+ if (!closed) {
342
+ quoting = false;
343
+ continue;
344
+ }
345
+ field = value;
346
+ fieldStart = false;
347
+ index = cursor;
348
+ continue;
349
+ }
350
+ if (char === delimiter) {
351
+ pushField();
352
+ index += 1;
353
+ } else if (char === "\r" || char === "\n") {
354
+ pushRow();
355
+ index += char === "\r" && text[index + 1] === "\n" ? 2 : 1;
356
+ } else {
357
+ field += char;
358
+ fieldStart = false;
359
+ index += 1;
360
+ }
361
+ }
362
+ if (state.full) {
363
+ if (index < length && !/^(\r\n|\r|\n)$/.test(text.slice(index))) state.truncated = true;
364
+ return {
365
+ grid,
366
+ truncated: state.truncated
367
+ };
368
+ }
369
+ const last = text[length - 1];
370
+ if (!(last === "\n" || last === "\r") || row.length > 0 || field !== "") pushRow();
371
+ return {
372
+ grid,
373
+ truncated: state.truncated
374
+ };
375
+ }
376
+ /**
377
+ * Reads tab-separated (or `delimiter`-separated) text into a table.
378
+ * Returns `null` when there is no non-empty cell.
379
+ */
380
+ function parseDelimited(text, options = {}) {
381
+ if (typeof text !== "string") throw invalid$2("`parseDelimited` expects a string.");
382
+ const limits = resolveLimits(options);
383
+ checkLength(text, limits);
384
+ const delimiter = options.delimiter ?? " ";
385
+ if (typeof delimiter !== "string" || delimiter.length !== 1 || delimiter === "\"" || delimiter === "\r" || delimiter === "\n") throw invalid$2("`delimiter` must be one character other than a quote or a line break.");
386
+ if (text === "") return null;
387
+ const { grid, truncated } = splitDelimited(text, delimiter, options.trim ?? false, limits);
388
+ return finish(grid, options.headers === true, "text", limits, truncated);
389
+ }
390
+ const SKIPPED = /* @__PURE__ */ new Set([
391
+ "SCRIPT",
392
+ "STYLE",
393
+ "TEMPLATE",
394
+ "NOSCRIPT",
395
+ "HEAD",
396
+ "TITLE",
397
+ "OBJECT",
398
+ "IFRAME",
399
+ "SVG",
400
+ "MATH"
401
+ ]);
402
+ const BLOCKS = /* @__PURE__ */ new Set([
403
+ "ADDRESS",
404
+ "ARTICLE",
405
+ "ASIDE",
406
+ "BLOCKQUOTE",
407
+ "DD",
408
+ "DIV",
409
+ "DL",
410
+ "DT",
411
+ "FIGCAPTION",
412
+ "FIGURE",
413
+ "FOOTER",
414
+ "FORM",
415
+ "H1",
416
+ "H2",
417
+ "H3",
418
+ "H4",
419
+ "H5",
420
+ "H6",
421
+ "HEADER",
422
+ "HR",
423
+ "LI",
424
+ "MAIN",
425
+ "NAV",
426
+ "OL",
427
+ "P",
428
+ "PRE",
429
+ "SECTION",
430
+ "TABLE",
431
+ "TR",
432
+ "UL"
433
+ ]);
434
+ const HARD_BREAK = "";
435
+ const SOFT_BREAK = "";
436
+ function isHidden(element) {
437
+ if (element.hasAttribute("hidden")) return true;
438
+ const style = element.getAttribute("style");
439
+ return style !== null && /(^|;)\s*display\s*:\s*none\s*(;|$)/i.test(style);
440
+ }
441
+ function collectText(node, out) {
442
+ for (const child of Array.from(node.childNodes)) if (child.nodeType === 3) out.push(child.data.replace(/[ \t\n\r\f]+/g, " "));
443
+ else if (child.nodeType === 1) {
444
+ const element = child;
445
+ const tag = element.tagName.toUpperCase();
446
+ if (SKIPPED.has(tag) || isHidden(element)) continue;
447
+ if (tag === "BR") {
448
+ out.push(HARD_BREAK);
449
+ continue;
450
+ }
451
+ const block = BLOCKS.has(tag);
452
+ const cellLike = tag === "TD" || tag === "TH";
453
+ if (block) out.push(SOFT_BREAK);
454
+ else if (cellLike) out.push(" ");
455
+ collectText(element, out);
456
+ if (block) out.push(SOFT_BREAK);
457
+ else if (cellLike) out.push(" ");
458
+ }
459
+ }
460
+ /** The text of one cell as it reads on screen: collapsed spaces, `<br>` and blocks as line breaks. */
461
+ function cellText(cell) {
462
+ const parts = [];
463
+ collectText(cell, parts);
464
+ return parts.join("").replace(/ {2,}/g, " ").replace(/ *\uE001[\uE001 ]*/g, SOFT_BREAK).replace(/^\uE001|\uE001$/g, "").replace(/[\uE000\uE001]/g, "\n").split("\n").map((line) => line.replace(/^ +| +$/g, "").replace(/\u00A0/g, " ")).join("\n").replace(/^\n+|\n+$/g, "");
465
+ }
466
+ function span(cell, name, max) {
467
+ const value = Number.parseInt(cell.getAttribute(name) ?? "", 10);
468
+ if (name === "rowspan" && value === 0) return max;
469
+ return Number.isFinite(value) && value >= 1 ? Math.min(value, max) : 1;
470
+ }
471
+ function isElement(value) {
472
+ return typeof value === "object" && value !== null && value.nodeType === 1;
473
+ }
474
+ function findTable(root) {
475
+ if (isElement(root) && root.tagName.toUpperCase() === "TABLE" && root.rows.length > 0) return root;
476
+ for (const table of Array.from(root.getElementsByTagName("table"))) if (table.rows.length > 0) return table;
477
+ return null;
478
+ }
479
+ function readGrid(table, repeat, limits) {
480
+ const rows = Array.from(table.rows).filter((row) => !isHidden(row));
481
+ const grid = [];
482
+ let truncated = rows.length > limits.maxRows;
483
+ const rowLimit = Math.min(rows.length, limits.maxRows);
484
+ let filled = 0;
485
+ let full = false;
486
+ for (let rowIndex = 0; rowIndex < rowLimit && !full; rowIndex++) {
487
+ var _rowIndex;
488
+ const row = rows[rowIndex];
489
+ const line = grid[_rowIndex = rowIndex] ?? (grid[_rowIndex] = []);
490
+ let column = 0;
491
+ for (const cell of Array.from(row.cells)) {
492
+ if (isHidden(cell)) continue;
493
+ while (line[column] !== void 0) column++;
494
+ if (column >= limits.maxColumns) {
495
+ truncated = true;
496
+ break;
497
+ }
498
+ const text = cellText(cell);
499
+ const colSpan = span(cell, "colspan", 1e3);
500
+ const rowSpan = span(cell, "rowspan", rowLimit - rowIndex);
501
+ for (let down = 0; down < rowSpan && !full; down++) {
502
+ var _ref;
503
+ const target = grid[_ref = rowIndex + down] ?? (grid[_ref] = []);
504
+ for (let across = 0; across < colSpan && column + across < limits.maxColumns; across++) {
505
+ if (filled >= limits.maxCells) {
506
+ full = true;
507
+ break;
508
+ }
509
+ target[column + across] = down === 0 && across === 0 ? text : repeat ? text : "";
510
+ filled += 1;
511
+ }
512
+ }
513
+ if (full) {
514
+ truncated = true;
515
+ break;
516
+ }
517
+ if (column + colSpan > limits.maxColumns) truncated = true;
518
+ column += colSpan;
519
+ }
520
+ }
521
+ const first = rows[0];
522
+ const headerRow = first !== void 0 && (first.parentElement?.tagName.toUpperCase() === "THEAD" || first.cells.length > 0 && Array.from(first.cells).every((cell) => cell.tagName.toUpperCase() === "TH"));
523
+ return {
524
+ grid: grid.map((line) => Array.from(line, (cell) => cell ?? "")),
525
+ headerRow,
526
+ truncated
527
+ };
528
+ }
529
+ function parseHtmlString(html) {
530
+ if (typeof DOMParser === "undefined") return null;
531
+ return new DOMParser().parseFromString(html, "text/html");
532
+ }
533
+ /**
534
+ * Reads the first non-empty `<table>` from an HTML string (such as Excel, Google Sheets,
535
+ * Word or a web page put on the clipboard) or from an element, which may be the table or
536
+ * contain it. Merged cells, `<br>` line breaks and hidden rows and cells are handled.
537
+ * Returns `null` without a table, without content, or on a server without `DOMParser`.
538
+ */
539
+ function parseHtmlTable(input, options = {}) {
540
+ const limits = resolveLimits(options);
541
+ let root;
542
+ if (typeof input === "string") {
543
+ checkLength(input, limits);
544
+ if (!/<table[\s>]/i.test(input)) return null;
545
+ root = parseHtmlString(input);
546
+ } else if (isElement(input)) root = input;
547
+ else throw invalid$2("`parseHtmlTable` expects an HTML string or an element.");
548
+ const table = root ? findTable(root) : null;
549
+ if (!table) return null;
550
+ const { grid, headerRow, truncated } = readGrid(table, options.spans === "repeat", limits);
551
+ const headers = options.headers ?? "auto";
552
+ return finish(grid, headers === "auto" ? headerRow : headers, "html", limits, truncated);
553
+ }
554
+ /**
555
+ * Reads a table from pasted content: a `PasteResult` (or any `{ html, text }`), or plain
556
+ * text. The HTML flavour is preferred when it holds a table; otherwise the text is split
557
+ * on tabs. Returns `null` when neither holds any cell content.
558
+ *
559
+ * ```ts
560
+ * usePaste({ accept: ['html', 'text'], onPaste: (result) => setRows(parseTable(result)?.rows ?? []) });
561
+ * ```
562
+ *
563
+ * Throws a `CopyFailure`: `too-large` past `maxLength`, `invalid-payload` for bad options.
564
+ */
565
+ function parseTable(source, options = {}) {
566
+ if (typeof source === "string") return parseDelimited(source, options);
567
+ const candidate = source;
568
+ if (typeof candidate !== "object" || candidate === null) throw invalid$2("`parseTable` expects a string or an object with `html` and/or `text`.");
569
+ const html = typeof source.html === "string" ? source.html : null;
570
+ const text = typeof source.text === "string" ? source.text : null;
571
+ const fromHtml = () => html === null ? null : parseHtmlTable(html, options);
572
+ const fromText = () => text === null ? null : parseDelimited(text, options);
573
+ return options.prefer === "text" ? fromText() ?? fromHtml() : fromHtml() ?? fromText();
574
+ }
575
+ /**
576
+ * Reads a rendered `<table>` (or the first table inside `element`) as {@link TableData},
577
+ * ready for `tablePayload`. Works with any library that renders real table markup.
578
+ * Throws `invalid-payload` when there is no table with content.
579
+ */
580
+ function fromTableElement(element, options = {}) {
581
+ const table = parseHtmlTable(element, options);
582
+ if (!table) throw invalid$2("No table with content was found in the element.");
583
+ return table;
584
+ }
585
+ //#endregion
586
+ //#region src/table/records.ts
587
+ const normalize = (label) => label.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase();
588
+ /**
589
+ * Maps a pasted table onto typed records, for importing rows from Excel or Google Sheets.
590
+ *
591
+ * ```ts
592
+ * const { records, missing, errors } = toRecords(parseTable(result)!, {
593
+ * email: { header: ['Email', 'E-mail'], required: true },
594
+ * seats: { header: 'Seats', parse: (text) => Number.parseInt(text, 10) },
595
+ * });
596
+ * // records: { email: string | undefined; seats: number | undefined }[]
597
+ * ```
598
+ */
599
+ function toRecords(table, schema, options = {}) {
600
+ const input = table;
601
+ if (typeof input !== "object" || input === null || !Array.isArray(input.rows)) throw copyFailure("invalid-payload", "`toRecords` expects a table with a `rows` array.");
602
+ const keys = Object.keys(schema);
603
+ if (keys.length === 0) throw copyFailure("invalid-payload", "`toRecords` needs at least one field.");
604
+ const headers = Array.isArray(table.headers) ? table.headers : null;
605
+ const match = options.match ?? "auto";
606
+ const byHeader = match === "header" || match === "auto" && headers !== null;
607
+ if (byHeader && headers === null) throw copyFailure("invalid-payload", "Matching by header needs a table with headers (`parseTable(…, { headers: true })`).");
608
+ const normalizedHeaders = headers?.map((label) => normalize(String(label))) ?? [];
609
+ let width = headers?.length ?? 0;
610
+ if (headers === null) for (const row of table.rows) width = Math.max(width, row.length);
611
+ const columnOf = /* @__PURE__ */ new Map();
612
+ const missing = [];
613
+ keys.forEach((key, position) => {
614
+ const field = schema[key];
615
+ let column = -1;
616
+ if (byHeader) {
617
+ const wanted = field.header === void 0 ? [key] : typeof field.header === "string" ? [field.header] : field.header;
618
+ for (const label of wanted) {
619
+ column = normalizedHeaders.indexOf(normalize(label));
620
+ if (column !== -1) break;
621
+ }
622
+ } else column = position;
623
+ if (column === -1 || column >= width) {
624
+ if (field.required === true) missing.push(key);
625
+ } else columnOf.set(key, column);
626
+ });
627
+ const skipEmpty = options.skipEmptyRows ?? true;
628
+ const records = [];
629
+ const errors = [];
630
+ table.rows.forEach((row, rowIndex) => {
631
+ if (skipEmpty && row.every((cell) => cell === "")) return;
632
+ const record = {};
633
+ for (const key of keys) {
634
+ const column = columnOf.get(key);
635
+ if (column === void 0) {
636
+ record[key] = void 0;
637
+ continue;
638
+ }
639
+ const text = row[column] ?? "";
640
+ const parse = schema[key].parse;
641
+ if (!parse) {
642
+ record[key] = text;
643
+ continue;
644
+ }
645
+ try {
646
+ record[key] = parse(text, {
647
+ row: rowIndex,
648
+ key
649
+ });
650
+ } catch (cause) {
651
+ record[key] = void 0;
652
+ errors.push({
653
+ row: rowIndex,
654
+ key,
655
+ text,
656
+ cause
657
+ });
658
+ }
659
+ }
660
+ records.push(record);
661
+ });
662
+ return {
663
+ records,
664
+ missing,
665
+ errors,
666
+ ok: missing.length === 0 && errors.length === 0
667
+ };
668
+ }
669
+ //#endregion
670
+ //#region src/table/cell-value.ts
671
+ function isDate(value) {
672
+ return value instanceof Date || Object.prototype.toString.call(value) === "[object Date]";
673
+ }
674
+ function json(value) {
675
+ try {
676
+ const encoded = JSON.stringify(value);
677
+ return typeof encoded === "string" ? encoded : "";
678
+ } catch {
679
+ return Object.prototype.toString.call(value);
680
+ }
681
+ }
682
+ /** One list item as text. Nested lists and objects become JSON: no recursion, so cycles are safe. */
683
+ function itemText(value) {
684
+ if (value === null || value === void 0) return "";
685
+ switch (typeof value) {
686
+ case "string": return value;
687
+ case "number":
688
+ case "bigint":
689
+ case "boolean": return String(value);
690
+ case "function":
691
+ case "symbol": return "";
692
+ }
693
+ if (isDate(value)) return Number.isNaN(value.getTime()) ? "" : value.toISOString();
694
+ return json(value);
695
+ }
696
+ /**
697
+ * Turns whatever a grid holds into a cell: primitives and dates as they are, arrays as
698
+ * a comma-separated list, other objects as JSON. Never throws, so one odd value can't
699
+ * break a copy of thousands of rows.
700
+ */
701
+ function toCellValue(value) {
702
+ switch (typeof value) {
703
+ case "string":
704
+ case "number":
705
+ case "bigint":
706
+ case "boolean":
707
+ case "undefined": return value;
708
+ case "function":
709
+ case "symbol": return "";
710
+ }
711
+ if (value === null) return null;
712
+ if (isDate(value)) return Number.isNaN(value.getTime()) ? "" : value;
713
+ if (Array.isArray(value)) return value.map(itemText).join(", ");
714
+ return json(value);
715
+ }
716
+ //#endregion
717
+ //#region src/table/ag-grid.ts
718
+ /** Ids of AG Grid's own utility columns, which hold no data. */
719
+ const UTILITY_COLUMNS = /* @__PURE__ */ new Set(["ag-Grid-SelectionColumn", "ag-Grid-RowNumbersColumn"]);
720
+ const invalid$1 = (message) => copyFailure("invalid-payload", message);
721
+ function collectRows(api, rows) {
722
+ if (typeof rows !== "string") {
723
+ const list = rows;
724
+ if (!Array.isArray(list)) throw invalid$1("`rows` must be \"displayed\", \"selected\", \"filtered\", \"all\" or an array of row nodes.");
725
+ return [...rows];
726
+ }
727
+ const nodes = [];
728
+ switch (rows) {
729
+ case "displayed": {
730
+ const count = api.getDisplayedRowCount();
731
+ for (let index = 0; index < count; index++) {
732
+ const node = api.getDisplayedRowAtIndex(index);
733
+ if (node) nodes.push(node);
734
+ }
735
+ return nodes;
736
+ }
737
+ case "selected": return api.getSelectedNodes().filter((node) => node.rowIndex !== null).sort((a, b) => a.rowIndex - b.rowIndex);
738
+ case "filtered":
739
+ api.forEachNodeAfterFilterAndSort((node) => nodes.push(node));
740
+ return nodes;
741
+ case "all":
742
+ api.forEachNode((node) => nodes.push(node));
743
+ return nodes;
744
+ default: throw invalid$1(`Unknown \`rows\` option: ${JSON.stringify(rows)}.`);
745
+ }
746
+ }
747
+ /**
748
+ * Reads rows from an AG Grid (v31+, Community or Enterprise) as table data.
749
+ *
750
+ * ```ts
751
+ * copy(() => tablePayload(fromAgGrid(gridRef.current!.api, { rows: 'selected' })));
752
+ * ```
753
+ *
754
+ * Gives Community grids Excel-ready copy, which AG Grid only ships in Enterprise.
755
+ */
756
+ function fromAgGrid(api, options = {}) {
757
+ const candidate = api;
758
+ if (typeof candidate !== "object" || candidate === null || typeof api.getAllDisplayedColumns !== "function") throw invalid$1("`fromAgGrid` expects an AG Grid API (v31 or later): `gridRef.current.api` or the API from `onGridReady`.");
759
+ const read = typeof api.getCellValue === "function" ? (node, column, useFormatter) => api.getCellValue?.({
760
+ rowNode: node,
761
+ colKey: column,
762
+ useFormatter
763
+ }) : typeof api.getValue === "function" ? (node, column) => api.getValue?.(column, node) : () => {
764
+ throw invalid$1("This grid API has neither `getCellValue` nor `getValue`; AG Grid v31 or later is required.");
765
+ };
766
+ const displayed = api.getAllDisplayedColumns();
767
+ let columns;
768
+ if (options.columns) {
769
+ const byId = new Map(displayed.map((column) => [column.getColId(), column]));
770
+ columns = options.columns.map((id) => {
771
+ const column = byId.get(id);
772
+ if (!column) throw invalid$1(`Column "${id}" is not displayed in the grid.`);
773
+ return column;
774
+ });
775
+ } else columns = displayed.filter((column) => !UTILITY_COLUMNS.has(column.getColId()));
776
+ const values = options.values ?? "auto";
777
+ const cell = (node, column) => {
778
+ if (values === "formatted") return toCellValue(read(node, column, true));
779
+ const raw = read(node, column, false);
780
+ if (values === "raw") return toCellValue(raw);
781
+ const type = typeof raw;
782
+ return type === "number" || type === "bigint" || type === "boolean" ? toCellValue(raw) : toCellValue(read(node, column, true));
783
+ };
784
+ const includeGroups = options.includeGroupRows ?? false;
785
+ const nodes = collectRows(api, options.rows ?? "displayed").filter((node) => includeGroups || node.group !== true);
786
+ return {
787
+ headers: columns.map((column) => options.header?.(column) ?? api.getDisplayNameForColumn(column, "csv")),
788
+ rows: nodes.map((node) => columns.map((column) => cell(node, column)))
789
+ };
790
+ }
791
+ //#endregion
792
+ //#region src/table/tanstack.ts
793
+ const invalid = (message) => copyFailure("invalid-payload", message);
794
+ /**
795
+ * Reads rows from a TanStack Table instance (v8 or v9) as table data.
796
+ *
797
+ * ```ts
798
+ * copy(() => tablePayload(fromTanStackTable(table, { rows: 'selected' })));
799
+ * ```
800
+ */
801
+ function fromTanStackTable(table, options = {}) {
802
+ const candidate = table;
803
+ if (typeof candidate !== "object" || candidate === null || typeof table.getRowModel !== "function") throw invalid("`fromTanStackTable` expects a TanStack Table instance (v8 or v9).");
804
+ const all = table.getAllLeafColumns();
805
+ let columns;
806
+ if (options.columns) {
807
+ const byId = new Map(all.map((column) => [column.id, column]));
808
+ columns = options.columns.map((id) => {
809
+ const column = byId.get(id);
810
+ if (!column) throw invalid(`Column "${id}" does not exist in the table.`);
811
+ return column;
812
+ });
813
+ } else columns = (typeof table.getVisibleLeafColumns === "function" ? table.getVisibleLeafColumns() : all).filter((column) => column.accessorFn !== void 0);
814
+ const selection = options.rows ?? "visible";
815
+ let rows;
816
+ if (selection === "visible" || selection === "selected") {
817
+ rows = table.getRowModel().rows;
818
+ if (selection === "selected") rows = rows.filter((row) => {
819
+ if (typeof row.getIsSelected !== "function") throw invalid("Row selection is not enabled on this table: register the row selection feature, or pass `rows`.");
820
+ return row.getIsSelected();
821
+ });
822
+ } else if (Array.isArray(selection)) rows = selection;
823
+ else throw invalid("`rows` must be \"visible\", \"selected\" or an array of rows.");
824
+ const header = (column) => {
825
+ if (options.header) return options.header(column);
826
+ const label = column.columnDef.header;
827
+ return typeof label === "string" ? label : column.id;
828
+ };
829
+ const value = options.value ?? ((row, column) => toCellValue(row.getValue(column.id)));
830
+ return {
831
+ headers: columns.map(header),
832
+ rows: rows.map((row) => columns.map((column) => value(row, column)))
833
+ };
834
+ }
835
+ //#endregion
836
+ export { DEFAULT_PARSE_MAX_CELLS, DEFAULT_PARSE_MAX_COLUMNS, DEFAULT_PARSE_MAX_LENGTH, DEFAULT_PARSE_MAX_ROWS, DEFAULT_TABLE_MAX_CELLS, fromAgGrid, fromRows, fromTableElement, fromTanStackTable, parseDelimited, parseHtmlTable, parseTable, tablePayload, tableToHtml, tableToTsv, toCellValue, toRecords };
837
+
838
+ //# sourceMappingURL=table.js.map