javascript-excel 2.0.0-alpha.2 → 2.0.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -21
- package/dist/address-DUn7-5OS.js +75 -0
- package/dist/address-DZBHchLv.cjs +122 -0
- package/dist/{auto-width-2oBzjeNG.d.cts → auto-width-DRHsPKNk.d.cts} +1 -1
- package/dist/cells-CPXU722t.cjs +33 -0
- package/dist/cells-CrMF8h_t.js +28 -0
- package/dist/colors-B8Nf_xTx.js +114 -0
- package/dist/colors-oBpjx97l.cjs +119 -0
- package/dist/csv.d.cts +4 -1
- package/dist/csv.d.ts +4 -1
- package/dist/dataset-KeMzHCGl.js +664 -0
- package/dist/dataset-UUZCzsi3.cjs +687 -0
- package/dist/dates-BXcSWf9_.js +64 -0
- package/dist/dates-CA1dCizp.cjs +75 -0
- package/dist/dom.cjs +5 -2
- package/dist/dom.d.cts +5 -2
- package/dist/dom.d.ts +4 -1
- package/dist/dom.js +4 -1
- package/dist/{numfmt-Dv6AjopS.cjs → dos-time-FZ7-1tot.cjs} +0 -199
- package/dist/{numfmt-BBgB7iQA.js → dos-time-dD0z1YWU.js} +2 -177
- package/dist/format.cjs +1264 -0
- package/dist/format.d.cts +59 -0
- package/dist/format.d.ts +59 -0
- package/dist/format.js +1262 -0
- package/dist/import.cjs +10 -0
- package/dist/import.d.cts +10 -0
- package/dist/import.d.ts +10 -0
- package/dist/import.js +1 -0
- package/dist/index.cjs +24 -607
- package/dist/index.d.cts +32 -6
- package/dist/index.d.ts +31 -5
- package/dist/index.js +10 -594
- package/dist/{warnings-C_12PT4t.d.cts → model-0JikLfuM.d.cts} +1 -41
- package/dist/{warnings-DXJKe1lx.d.ts → model-0JikLfuM.d.ts} +1 -41
- package/dist/numfmt-BmEbm78Y.cjs +125 -0
- package/dist/numfmt-DCDrX9P1.js +114 -0
- package/dist/pipeline-BAJtzBdW.js +1085 -0
- package/dist/pipeline-Bnf7EU3X.cjs +1132 -0
- package/dist/pipeline-CctEa86r.d.cts +186 -0
- package/dist/pipeline-I8SLmV9S.d.ts +186 -0
- package/dist/{read-Ym1voUct.cjs → read-CZEWV4rK.cjs} +181 -17
- package/dist/{read-DDN5ZsPe.js → read-LWti17lz.js} +169 -5
- package/dist/read.cjs +1 -1
- package/dist/read.d.cts +78 -4
- package/dist/read.d.ts +78 -4
- package/dist/read.js +1 -1
- package/dist/render.cjs +751 -0
- package/dist/render.d.cts +215 -0
- package/dist/render.d.ts +215 -0
- package/dist/render.js +732 -0
- package/dist/{sheet-names-uT2EH5Ui.js → sheet-names-7p-joVsG.js} +2 -101
- package/dist/{sheet-names-qpXsvMpM.cjs → sheet-names-B8U5RAW0.cjs} +14 -167
- package/dist/warnings-B1v58nCZ.d.cts +41 -0
- package/dist/warnings-B1v58nCZ.d.ts +41 -0
- package/dist/worker.cjs +10 -2
- package/dist/worker.d.cts +10 -4
- package/dist/worker.d.ts +10 -4
- package/dist/worker.js +10 -2
- package/dist/{write-CYpLGuzl.d.ts → write-DM6ieuQY.d.ts} +2 -1
- package/dist/{write-DubvcG-x.js → write-DjgWy1PK.js} +5 -2
- package/dist/{write-C5JgeIar.d.cts → write-DtjfdIFm.d.cts} +2 -1
- package/dist/{write-BOh9jfu1.cjs → write-f9kcYf5K.cjs} +31 -28
- package/package.json +32 -1
- package/dist/read-C6L7Nyy3.d.cts +0 -78
- package/dist/read-Ddkks7qC.d.ts +0 -78
|
@@ -0,0 +1,1085 @@
|
|
|
1
|
+
import { r as readCsv } from "./csv-pXfaputs.js";
|
|
2
|
+
import { i as toDatasetDetailed } from "./dataset-KeMzHCGl.js";
|
|
3
|
+
import { a as LimitError, i as FormatError, o as ValidationError } from "./errors-CvGlfw0E.js";
|
|
4
|
+
import { i as readSheetNames, n as detectFormat, r as read } from "./read-LWti17lz.js";
|
|
5
|
+
import { n as parseIsoDate, r as toBytes } from "./infer-BR-J9BZa.js";
|
|
6
|
+
import { a as decodeRange } from "./address-DUn7-5OS.js";
|
|
7
|
+
import { t as isoDate } from "./iso-date-CXnn-9mT.js";
|
|
8
|
+
// src/internal/import/parse.ts
|
|
9
|
+
/**
|
|
10
|
+
* Locale-aware number and date parsing for javascript-excel/import
|
|
11
|
+
* (docs/api.md §5.6). Hand-written scanners: input is untrusted, so there is
|
|
12
|
+
* no regex backtracking and every loop is linear.
|
|
13
|
+
*/
|
|
14
|
+
const MAX_TEXT = 64;
|
|
15
|
+
function isDigit(c) {
|
|
16
|
+
return c >= 48 && c <= 57;
|
|
17
|
+
}
|
|
18
|
+
function isGroupChar(c, group) {
|
|
19
|
+
if (group === "") return false;
|
|
20
|
+
if (group === " ") return c === 32 || c === 160 || c === 8239;
|
|
21
|
+
return c === group.charCodeAt(0);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Parses `text` as a number written with `decimal` and `group` separators.
|
|
25
|
+
* Returns undefined for anything else (leading zeros, misplaced groups,
|
|
26
|
+
* percent or currency signs, integers beyond 2^53).
|
|
27
|
+
*/
|
|
28
|
+
function parseNumber(text, options = {}) {
|
|
29
|
+
const decimal = options.decimal ?? ".";
|
|
30
|
+
const group = options.group ?? "";
|
|
31
|
+
if (decimal !== "." && decimal !== ",") throw new TypeError(`decimal must be '.' or ',', got ${JSON.stringify(decimal)}`);
|
|
32
|
+
if (![
|
|
33
|
+
",",
|
|
34
|
+
".",
|
|
35
|
+
" ",
|
|
36
|
+
"'",
|
|
37
|
+
""
|
|
38
|
+
].includes(group)) throw new TypeError(`group must be one of , . space ' or '', got ${JSON.stringify(group)}`);
|
|
39
|
+
if (group === decimal) throw new TypeError("decimal and group must differ");
|
|
40
|
+
const s = text.trim();
|
|
41
|
+
const n = s.length;
|
|
42
|
+
if (n === 0 || n > MAX_TEXT) return void 0;
|
|
43
|
+
const dec = decimal.charCodeAt(0);
|
|
44
|
+
let i = 0;
|
|
45
|
+
let out = "";
|
|
46
|
+
const c0 = s.charCodeAt(0);
|
|
47
|
+
if (c0 === 43 || c0 === 45) {
|
|
48
|
+
if (c0 === 45) out = "-";
|
|
49
|
+
i = 1;
|
|
50
|
+
}
|
|
51
|
+
const intStart = i;
|
|
52
|
+
let digits = 0;
|
|
53
|
+
let groups = 0;
|
|
54
|
+
let sinceGroup = 0;
|
|
55
|
+
let firstGroupLen = 0;
|
|
56
|
+
while (i < n) {
|
|
57
|
+
const c = s.charCodeAt(i);
|
|
58
|
+
if (isDigit(c)) {
|
|
59
|
+
out += s[i];
|
|
60
|
+
digits++;
|
|
61
|
+
sinceGroup++;
|
|
62
|
+
i++;
|
|
63
|
+
} else if (isGroupChar(c, group) && digits > 0) {
|
|
64
|
+
if (groups === 0) firstGroupLen = sinceGroup;
|
|
65
|
+
else if (sinceGroup !== 3) return void 0;
|
|
66
|
+
if (firstGroupLen > 3) return void 0;
|
|
67
|
+
groups++;
|
|
68
|
+
sinceGroup = 0;
|
|
69
|
+
i++;
|
|
70
|
+
} else break;
|
|
71
|
+
}
|
|
72
|
+
if (groups > 0 && sinceGroup !== 3) return void 0;
|
|
73
|
+
const intDigits = s.slice(intStart, i);
|
|
74
|
+
let fraction = false;
|
|
75
|
+
if (i < n && s.charCodeAt(i) === dec) {
|
|
76
|
+
i++;
|
|
77
|
+
const fracStart = i;
|
|
78
|
+
while (i < n && isDigit(s.charCodeAt(i))) i++;
|
|
79
|
+
if (i === fracStart) return void 0;
|
|
80
|
+
out += "." + s.slice(fracStart, i);
|
|
81
|
+
fraction = true;
|
|
82
|
+
}
|
|
83
|
+
if (digits === 0 && !fraction) return void 0;
|
|
84
|
+
if (digits > 1 && intDigits.charCodeAt(0) === 48) return void 0;
|
|
85
|
+
let exponent = false;
|
|
86
|
+
if (i < n && (s.charCodeAt(i) === 101 || s.charCodeAt(i) === 69) && decimal === ".") {
|
|
87
|
+
let j = i + 1;
|
|
88
|
+
if (j < n && (s.charCodeAt(j) === 43 || s.charCodeAt(j) === 45)) j++;
|
|
89
|
+
const expStart = j;
|
|
90
|
+
while (j < n && isDigit(s.charCodeAt(j))) j++;
|
|
91
|
+
if (j === expStart) return void 0;
|
|
92
|
+
out += "e" + s.slice(i + 1, j);
|
|
93
|
+
i = j;
|
|
94
|
+
exponent = true;
|
|
95
|
+
}
|
|
96
|
+
if (i !== n) return void 0;
|
|
97
|
+
const value = Number(digits === 0 ? out.replace(/^(-?)\./, "$10.") : out);
|
|
98
|
+
if (!Number.isFinite(value)) return void 0;
|
|
99
|
+
if (!fraction && !exponent && !Number.isSafeInteger(value)) return void 0;
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
/** Splits "15/01/2024", "2024.01.15" or "1-2-2024 13:45:10" into numbers; one separator throughout. */
|
|
103
|
+
function dateParts(text) {
|
|
104
|
+
const s = text.trim();
|
|
105
|
+
const n = s.length;
|
|
106
|
+
if (n < 8 || n > 24) return void 0;
|
|
107
|
+
const nums = [];
|
|
108
|
+
const lens = [];
|
|
109
|
+
let i = 0;
|
|
110
|
+
let sep = -1;
|
|
111
|
+
for (let k = 0; k < 3; k++) {
|
|
112
|
+
const start = i;
|
|
113
|
+
while (i < n && isDigit(s.charCodeAt(i))) i++;
|
|
114
|
+
const len = i - start;
|
|
115
|
+
if (len === 0 || len > 4) return void 0;
|
|
116
|
+
nums.push(+s.slice(start, i));
|
|
117
|
+
lens.push(len);
|
|
118
|
+
if (k < 2) {
|
|
119
|
+
const c = s.charCodeAt(i);
|
|
120
|
+
if (c !== 47 && c !== 46 && c !== 45) return void 0;
|
|
121
|
+
if (sep === -1) sep = c;
|
|
122
|
+
else if (c !== sep) return void 0;
|
|
123
|
+
i++;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
let h = 0;
|
|
127
|
+
let mi = 0;
|
|
128
|
+
let sec = 0;
|
|
129
|
+
let hasTime = false;
|
|
130
|
+
if (i < n) {
|
|
131
|
+
if (s.charCodeAt(i) !== 32) return void 0;
|
|
132
|
+
const m = /^ (\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(s.slice(i));
|
|
133
|
+
if (!m) return void 0;
|
|
134
|
+
h = +m[1];
|
|
135
|
+
mi = +m[2];
|
|
136
|
+
sec = m[3] === void 0 ? 0 : +m[3];
|
|
137
|
+
if (h > 23 || mi > 59 || sec > 59) return void 0;
|
|
138
|
+
hasTime = true;
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
a: nums[0],
|
|
142
|
+
b: nums[1],
|
|
143
|
+
c: nums[2],
|
|
144
|
+
aLen: lens[0],
|
|
145
|
+
cLen: lens[2],
|
|
146
|
+
h,
|
|
147
|
+
mi,
|
|
148
|
+
s: sec,
|
|
149
|
+
hasTime
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function daysInMonth(y, m) {
|
|
153
|
+
if (m === 2) return y % 4 === 0 && y % 100 !== 0 || y % 400 === 0 ? 29 : 28;
|
|
154
|
+
return m === 4 || m === 6 || m === 9 || m === 11 ? 30 : 31;
|
|
155
|
+
}
|
|
156
|
+
/** Builds the date for parts in `order`; undefined if the parts don't fit it. Years must have four digits. */
|
|
157
|
+
function dateFromParts(p, order, zone) {
|
|
158
|
+
let y, mo, d;
|
|
159
|
+
if (order === "YMD") {
|
|
160
|
+
if (p.aLen !== 4) return void 0;
|
|
161
|
+
[y, mo, d] = [
|
|
162
|
+
p.a,
|
|
163
|
+
p.b,
|
|
164
|
+
p.c
|
|
165
|
+
];
|
|
166
|
+
} else {
|
|
167
|
+
if (p.cLen !== 4) return void 0;
|
|
168
|
+
[y, mo, d] = order === "DMY" ? [
|
|
169
|
+
p.c,
|
|
170
|
+
p.b,
|
|
171
|
+
p.a
|
|
172
|
+
] : [
|
|
173
|
+
p.c,
|
|
174
|
+
p.a,
|
|
175
|
+
p.b
|
|
176
|
+
];
|
|
177
|
+
}
|
|
178
|
+
if (mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo)) return void 0;
|
|
179
|
+
const t = zone === "utc" ? Date.UTC(y, mo - 1, d, p.h, p.mi, p.s) : new Date(y, mo - 1, d, p.h, p.mi, p.s).getTime();
|
|
180
|
+
const date = new Date(t);
|
|
181
|
+
return Number.isNaN(date.getTime()) ? void 0 : date;
|
|
182
|
+
}
|
|
183
|
+
/** ISO 8601 always; numeric dates (d/m/yyyy, …) only with `order`. Two-digit years are not accepted. */
|
|
184
|
+
function parseDate(text, options = {}) {
|
|
185
|
+
const zone = options.zone ?? "local";
|
|
186
|
+
if (zone !== "local" && zone !== "utc") throw new TypeError(`zone must be 'local' or 'utc', got ${JSON.stringify(zone)}`);
|
|
187
|
+
if (options.order !== void 0 && options.order !== "YMD" && options.order !== "DMY" && options.order !== "MDY") throw new TypeError(`order must be 'YMD', 'DMY' or 'MDY', got ${JSON.stringify(options.order)}`);
|
|
188
|
+
const s = text.trim();
|
|
189
|
+
if (s.length >= 10 && s.length <= 40 && s.charCodeAt(4) === 45) {
|
|
190
|
+
const iso = parseIsoDate(s, zone);
|
|
191
|
+
if (iso) return iso;
|
|
192
|
+
}
|
|
193
|
+
if (!options.order) return void 0;
|
|
194
|
+
const p = dateParts(s);
|
|
195
|
+
return p ? dateFromParts(p, options.order, zone) : void 0;
|
|
196
|
+
}
|
|
197
|
+
/** TRUE/FALSE in any case. */
|
|
198
|
+
function parseBoolean(text) {
|
|
199
|
+
const s = text.trim().toLowerCase();
|
|
200
|
+
return s === "true" ? true : s === "false" ? false : void 0;
|
|
201
|
+
}
|
|
202
|
+
/** Rows below a header candidate that are checked for non-text values. */
|
|
203
|
+
const LOOKAHEAD = 5;
|
|
204
|
+
function usedRange(sheet) {
|
|
205
|
+
let minR = 1e400, maxR = -1, minC = 1e400, maxC = -1;
|
|
206
|
+
sheet.rows.forEach((row, r) => row?.forEach((c, col) => {
|
|
207
|
+
if (c === void 0 || c === null) return;
|
|
208
|
+
if (r < minR) minR = r;
|
|
209
|
+
if (r > maxR) maxR = r;
|
|
210
|
+
if (col < minC) minC = col;
|
|
211
|
+
if (col > maxC) maxC = col;
|
|
212
|
+
}));
|
|
213
|
+
return maxR < 0 ? void 0 : {
|
|
214
|
+
start: {
|
|
215
|
+
row: minR,
|
|
216
|
+
col: minC
|
|
217
|
+
},
|
|
218
|
+
end: {
|
|
219
|
+
row: maxR,
|
|
220
|
+
col: maxC
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/** Text that reads as a number, boolean or date under the locale counts as "other". */
|
|
225
|
+
function textKind(text, locale) {
|
|
226
|
+
const s = text.trim();
|
|
227
|
+
if (s === "") return 0;
|
|
228
|
+
if (parseNumber(s, {
|
|
229
|
+
decimal: locale.decimal ?? ".",
|
|
230
|
+
group: locale.group ?? ""
|
|
231
|
+
}) !== void 0) return 2;
|
|
232
|
+
if (parseBoolean(s) !== void 0) return 2;
|
|
233
|
+
if (s.length >= 10 && s.charCodeAt(4) === 45 && parseIsoDate(s, "utc")) return 2;
|
|
234
|
+
if (dateParts(s)) return 2;
|
|
235
|
+
return 1;
|
|
236
|
+
}
|
|
237
|
+
function cellKind(c, locale) {
|
|
238
|
+
if (c === void 0 || c === null) return 0;
|
|
239
|
+
if (typeof c === "string") return textKind(c, locale);
|
|
240
|
+
if (typeof c === "number" || typeof c === "boolean" || c instanceof Date) return 2;
|
|
241
|
+
if (typeof c === "object") {
|
|
242
|
+
if ("error" in c) return 2;
|
|
243
|
+
if ("richText" in c) return textKind(c.richText.map((r) => r.text).join(""), locale);
|
|
244
|
+
const v = c.value;
|
|
245
|
+
if (v === void 0 || v === null) return c.formula ? 2 : 0;
|
|
246
|
+
return cellKind(v, locale);
|
|
247
|
+
}
|
|
248
|
+
return 1;
|
|
249
|
+
}
|
|
250
|
+
function detectHeader(sheet, options = {}) {
|
|
251
|
+
const maxScan = options.maxScan ?? 25;
|
|
252
|
+
if (!Number.isInteger(maxScan) || maxScan < 1) throw new TypeError(`maxScan must be a positive integer, got ${String(maxScan)}`);
|
|
253
|
+
const locale = options.locale ?? {};
|
|
254
|
+
const rng = options.range ? decodeRange(options.range) : sheet.dimension ? decodeRange(sheet.dimension) : usedRange(sheet);
|
|
255
|
+
if (!rng) return {
|
|
256
|
+
rows: [0],
|
|
257
|
+
confidence: "low"
|
|
258
|
+
};
|
|
259
|
+
const top = rng.start.row;
|
|
260
|
+
const last = Math.min(rng.end.row, top + maxScan - 1);
|
|
261
|
+
const width = rng.end.col - rng.start.col + 1;
|
|
262
|
+
const merges = (sheet.merges ?? []).map((m) => decodeRange(m)).filter((m) => m.start.row <= last && m.end.row >= top);
|
|
263
|
+
const rows = [];
|
|
264
|
+
for (let r = top; r <= last; r++) {
|
|
265
|
+
const row = sheet.rows[r];
|
|
266
|
+
const kinds = [];
|
|
267
|
+
let filled = 0;
|
|
268
|
+
let nonEmpty = 0;
|
|
269
|
+
let other = 0;
|
|
270
|
+
for (let c = rng.start.col; c <= rng.end.col; c++) {
|
|
271
|
+
const k = cellKind(row?.[c], locale);
|
|
272
|
+
kinds.push(k);
|
|
273
|
+
if (k !== 0) {
|
|
274
|
+
nonEmpty++;
|
|
275
|
+
filled++;
|
|
276
|
+
if (k === 2) other++;
|
|
277
|
+
} else if (merges.some((m) => r >= m.start.row && r <= m.end.row && c >= m.start.col && c <= m.end.col && (r !== m.start.row || c !== m.start.col))) filled++;
|
|
278
|
+
}
|
|
279
|
+
const fullWidthMerge = width > 1 && merges.some((m) => m.start.row === r && m.start.col <= rng.start.col && m.end.col >= rng.end.col);
|
|
280
|
+
rows.push({
|
|
281
|
+
r,
|
|
282
|
+
kinds,
|
|
283
|
+
filled,
|
|
284
|
+
nonEmpty,
|
|
285
|
+
allText: nonEmpty > 0 && other === 0,
|
|
286
|
+
fullWidthMerge
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
const counts = /* @__PURE__ */ new Map();
|
|
290
|
+
for (const x of rows) if (x.filled > 1) counts.set(x.filled, (counts.get(x.filled) ?? 0) + 1);
|
|
291
|
+
let tableWidth = 1;
|
|
292
|
+
let best = 0;
|
|
293
|
+
for (const [w, n] of counts) if (n > best || n === best && w > tableWidth) [tableWidth, best] = [w, n];
|
|
294
|
+
const isTitle = (x) => tableWidth > 1 && x.filled <= 1 || x.fullWidthMerge;
|
|
295
|
+
const candidates = rows.filter((x) => x.nonEmpty > 0 && !isTitle(x));
|
|
296
|
+
const hasOtherBelow = (idx) => {
|
|
297
|
+
const x = rows[idx];
|
|
298
|
+
let seen = 0;
|
|
299
|
+
for (let j = idx + 1; j < rows.length && seen < LOOKAHEAD; j++) {
|
|
300
|
+
const y = rows[j];
|
|
301
|
+
if (y.nonEmpty === 0) continue;
|
|
302
|
+
seen++;
|
|
303
|
+
for (let k = 0; k < width; k++) if (x.kinds[k] === 1 && y.kinds[k] === 2) return true;
|
|
304
|
+
}
|
|
305
|
+
return false;
|
|
306
|
+
};
|
|
307
|
+
let header;
|
|
308
|
+
let confidence = "low";
|
|
309
|
+
for (const x of candidates) if (x.allText && x.filled >= tableWidth && hasOtherBelow(rows.indexOf(x))) {
|
|
310
|
+
header = x;
|
|
311
|
+
confidence = "high";
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
if (!header) header = candidates.find((x) => x.allText && x.filled >= tableWidth);
|
|
315
|
+
if (!header) return {
|
|
316
|
+
rows: [top],
|
|
317
|
+
confidence: "low"
|
|
318
|
+
};
|
|
319
|
+
const joinsBelow = (x) => merges.some((m) => m.start.row === x.r && m.end.row > x.r) || merges.some((m) => m.start.row === x.r && m.end.row === x.r && m.end.col > m.start.col && !(m.start.col <= rng.start.col && m.end.col >= rng.end.col));
|
|
320
|
+
const result = [header.r];
|
|
321
|
+
let at = rows.indexOf(header);
|
|
322
|
+
while (at + 1 < rows.length && joinsBelow(rows[at]) && rows[at + 1].allText && rows[at + 1].r === rows[at].r + 1) {
|
|
323
|
+
at++;
|
|
324
|
+
result.push(rows[at].r);
|
|
325
|
+
}
|
|
326
|
+
for (let i = rows.indexOf(header) - 1; i >= 0; i--) {
|
|
327
|
+
const x = rows[i];
|
|
328
|
+
if (!x.allText || x.fullWidthMerge || !joinsBelow(x)) break;
|
|
329
|
+
result.unshift(x.r);
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
rows: result,
|
|
333
|
+
confidence
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
// src/internal/import/mapping.ts
|
|
337
|
+
/** NFKD, combining marks removed, lower case, whitespace _ - . removed. */
|
|
338
|
+
function normaliseTitle(s) {
|
|
339
|
+
return s.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase().replace(/[\s_.-]+/gu, "");
|
|
340
|
+
}
|
|
341
|
+
function fieldsOf(schema) {
|
|
342
|
+
if (!schema || typeof schema !== "object" || !schema.fields || typeof schema.fields !== "object") throw new TypeError("schema.fields must be an object");
|
|
343
|
+
return Object.keys(schema.fields).map((name) => {
|
|
344
|
+
const spec = schema.fields[name];
|
|
345
|
+
if (!spec || typeof spec !== "object") throw new TypeError(`schema.fields.${name} must be an object`);
|
|
346
|
+
if (spec.aliases !== void 0 && (!Array.isArray(spec.aliases) || spec.aliases.some((a) => typeof a !== "string"))) throw new TypeError(`schema.fields.${name}.aliases must be an array of strings`);
|
|
347
|
+
return [name, spec];
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
function mapColumns(columns, schema, mapping) {
|
|
351
|
+
const fields = fieldsOf(schema);
|
|
352
|
+
const keys = new Set(columns.map((c) => c.key));
|
|
353
|
+
const taken = /* @__PURE__ */ new Set();
|
|
354
|
+
const result = Object.create(null);
|
|
355
|
+
if (mapping !== void 0) {
|
|
356
|
+
if (!mapping || typeof mapping !== "object") throw new TypeError("mapping must be an object");
|
|
357
|
+
for (const [name] of fields) {
|
|
358
|
+
if (!Object.hasOwn(mapping, name)) continue;
|
|
359
|
+
const col = mapping[name];
|
|
360
|
+
if (col === null) {
|
|
361
|
+
result[name] = null;
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
if (typeof col !== "string" || !keys.has(col)) throw new TypeError(`mapping.${name}: no column with key ${JSON.stringify(col)}`);
|
|
365
|
+
if (taken.has(col)) throw new TypeError(`mapping: column ${JSON.stringify(col)} is mapped to more than one field`);
|
|
366
|
+
result[name] = col;
|
|
367
|
+
taken.add(col);
|
|
368
|
+
}
|
|
369
|
+
for (const name of Object.keys(mapping)) if (!fields.some(([f]) => f === name)) throw new TypeError(`mapping: ${JSON.stringify(name)} is not a schema field`);
|
|
370
|
+
}
|
|
371
|
+
const norm = columns.map((c) => ({
|
|
372
|
+
key: c.key,
|
|
373
|
+
n: [normaliseTitle(c.title), normaliseTitle(c.key)]
|
|
374
|
+
}));
|
|
375
|
+
for (const [name, spec] of fields) {
|
|
376
|
+
if (Object.hasOwn(result, name)) continue;
|
|
377
|
+
const wanted = new Set([name, ...spec.aliases ?? []].map(normaliseTitle).filter((x) => x !== ""));
|
|
378
|
+
const hit = norm.find((c) => !taken.has(c.key) && c.n.some((x) => wanted.has(x)));
|
|
379
|
+
result[name] = hit ? hit.key : null;
|
|
380
|
+
if (hit) taken.add(hit.key);
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
mapping: result,
|
|
384
|
+
missing: fields.filter(([name, spec]) => spec.required && result[name] === null).map(([name]) => name),
|
|
385
|
+
unmapped: columns.map((c) => c.key).filter((k) => !taken.has(k))
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
function applyMapping(dataset, mapping, schema) {
|
|
389
|
+
const fields = fieldsOf(schema);
|
|
390
|
+
const byKey = new Map(dataset.columns.map((c, i) => [c.key, {
|
|
391
|
+
...c,
|
|
392
|
+
index: i
|
|
393
|
+
}]));
|
|
394
|
+
for (const [name] of fields) {
|
|
395
|
+
const col = Object.hasOwn(mapping, name) ? mapping[name] : null;
|
|
396
|
+
if (col !== null && col !== void 0 && !byKey.has(col)) throw new TypeError(`mapping.${name}: no column with key ${JSON.stringify(col)}`);
|
|
397
|
+
}
|
|
398
|
+
const rowNumbers = dataset.data.map((_, i) => dataset.rowNumbers?.[i] ?? i + 2);
|
|
399
|
+
const issues = [];
|
|
400
|
+
const columns = [];
|
|
401
|
+
const plan = [];
|
|
402
|
+
const used = new Set(fields.map(([name]) => name));
|
|
403
|
+
for (const [name, spec] of fields) {
|
|
404
|
+
const from = Object.hasOwn(mapping, name) ? mapping[name] : null;
|
|
405
|
+
if (from === null || from === void 0) {
|
|
406
|
+
if (spec.required) issues.push({
|
|
407
|
+
row: 0,
|
|
408
|
+
field: name,
|
|
409
|
+
code: "MAPPING_MISSING",
|
|
410
|
+
message: `No column for the required field "${name}".`,
|
|
411
|
+
severity: "error"
|
|
412
|
+
});
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
const c = byKey.get(from);
|
|
416
|
+
columns.push({
|
|
417
|
+
key: name,
|
|
418
|
+
title: c.title,
|
|
419
|
+
letter: c.letter ?? "",
|
|
420
|
+
type: c.type ?? "mixed",
|
|
421
|
+
field: name
|
|
422
|
+
});
|
|
423
|
+
plan.push({
|
|
424
|
+
out: name,
|
|
425
|
+
from
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
if (schema.unmapped === "keep") {
|
|
429
|
+
const mapped = new Set(plan.map((p) => p.from));
|
|
430
|
+
for (const c of dataset.columns) {
|
|
431
|
+
if (mapped.has(c.key)) continue;
|
|
432
|
+
let key = c.key;
|
|
433
|
+
for (let n = 2; used.has(key); n++) key = `${c.key}_${n}`;
|
|
434
|
+
used.add(key);
|
|
435
|
+
columns.push({
|
|
436
|
+
key,
|
|
437
|
+
title: c.title,
|
|
438
|
+
letter: c.letter ?? "",
|
|
439
|
+
type: c.type ?? "mixed"
|
|
440
|
+
});
|
|
441
|
+
plan.push({
|
|
442
|
+
out: key,
|
|
443
|
+
from: c.key
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
const required = fields.filter(([name, spec]) => spec.required && plan.some((p) => p.out === name)).map(([name]) => name);
|
|
448
|
+
return {
|
|
449
|
+
columns,
|
|
450
|
+
data: dataset.data.map((row, i) => {
|
|
451
|
+
const out = Object.create(null);
|
|
452
|
+
for (const { out: k, from } of plan) out[k] = row[from] ?? null;
|
|
453
|
+
for (const name of required) {
|
|
454
|
+
const v = out[name];
|
|
455
|
+
if (v === null || v === void 0 || typeof v === "string" && v.trim() === "") {
|
|
456
|
+
const letter = byKey.get(plan.find((p) => p.out === name).from)?.letter;
|
|
457
|
+
issues.push({
|
|
458
|
+
row: rowNumbers[i],
|
|
459
|
+
field: name,
|
|
460
|
+
...letter ? { ref: `${letter}${rowNumbers[i]}` } : {},
|
|
461
|
+
code: "REQUIRED",
|
|
462
|
+
message: `Row ${rowNumbers[i]}: "${name}" is required.`,
|
|
463
|
+
severity: "error"
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return out;
|
|
468
|
+
}),
|
|
469
|
+
rowNumbers,
|
|
470
|
+
issues
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
// src/internal/import/types.ts
|
|
474
|
+
/**
|
|
475
|
+
* Column type inference and coercion for javascript-excel/import
|
|
476
|
+
* (docs/api.md §5.6, "Type rules"). All-or-nothing per column.
|
|
477
|
+
*/
|
|
478
|
+
function isEmpty(v) {
|
|
479
|
+
return v === null || v === void 0 || typeof v === "string" && v.trim() === "";
|
|
480
|
+
}
|
|
481
|
+
function hasTime(d, zone) {
|
|
482
|
+
return zone === "utc" ? d.getUTCHours() !== 0 || d.getUTCMinutes() !== 0 || d.getUTCSeconds() !== 0 || d.getUTCMilliseconds() !== 0 : d.getHours() !== 0 || d.getMinutes() !== 0 || d.getSeconds() !== 0 || d.getMilliseconds() !== 0;
|
|
483
|
+
}
|
|
484
|
+
function textOf(v) {
|
|
485
|
+
if (typeof v === "string") return v;
|
|
486
|
+
if (v && typeof v === "object" && "richText" in v) return v.richText.map((r) => r.text).join("");
|
|
487
|
+
}
|
|
488
|
+
function numberOptions(locale) {
|
|
489
|
+
return {
|
|
490
|
+
decimal: locale.decimal ?? ".",
|
|
491
|
+
group: locale.group ?? ""
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* The date order of a column of numeric date texts, decided from the data
|
|
496
|
+
* only: undefined when nothing proves an order, or the evidence conflicts.
|
|
497
|
+
*/
|
|
498
|
+
function dateOrderOf(texts, requested) {
|
|
499
|
+
if (requested && requested !== "auto") return {
|
|
500
|
+
order: requested,
|
|
501
|
+
ambiguous: false
|
|
502
|
+
};
|
|
503
|
+
let ymd = 0, dmy = 0, mdy = 0, any = 0;
|
|
504
|
+
for (const t of texts) {
|
|
505
|
+
const p = dateParts(t);
|
|
506
|
+
if (!p) continue;
|
|
507
|
+
any++;
|
|
508
|
+
if (p.aLen === 4) ymd++;
|
|
509
|
+
else if (p.a > 12) dmy++;
|
|
510
|
+
else if (p.b > 12) mdy++;
|
|
511
|
+
}
|
|
512
|
+
if (any === 0) return { ambiguous: false };
|
|
513
|
+
if (ymd === any) return {
|
|
514
|
+
order: "YMD",
|
|
515
|
+
ambiguous: false
|
|
516
|
+
};
|
|
517
|
+
if (ymd > 0) return { ambiguous: true };
|
|
518
|
+
if (dmy > 0 && mdy === 0) return {
|
|
519
|
+
order: "DMY",
|
|
520
|
+
ambiguous: false
|
|
521
|
+
};
|
|
522
|
+
if (mdy > 0 && dmy === 0) return {
|
|
523
|
+
order: "MDY",
|
|
524
|
+
ambiguous: false
|
|
525
|
+
};
|
|
526
|
+
return { ambiguous: true };
|
|
527
|
+
}
|
|
528
|
+
function textToDate(t, order, zone) {
|
|
529
|
+
const s = t.trim();
|
|
530
|
+
if (s.length >= 10 && s.charCodeAt(4) === 45) {
|
|
531
|
+
const iso = parseIsoDate(s, zone);
|
|
532
|
+
if (iso) return iso;
|
|
533
|
+
}
|
|
534
|
+
if (!order) return void 0;
|
|
535
|
+
const p = dateParts(s);
|
|
536
|
+
return p ? dateFromParts(p, order, zone) : void 0;
|
|
537
|
+
}
|
|
538
|
+
function inferOne(key, values, locale, zone, convertText) {
|
|
539
|
+
const present = values.filter((v) => !isEmpty(v) && !(v && typeof v === "object" && "error" in v));
|
|
540
|
+
if (present.length === 0) return {
|
|
541
|
+
key,
|
|
542
|
+
type: "empty",
|
|
543
|
+
ambiguousDates: false
|
|
544
|
+
};
|
|
545
|
+
const texts = [];
|
|
546
|
+
let nums = 0, bools = 0, dates = 0, others = 0, timed = false;
|
|
547
|
+
for (const v of present) {
|
|
548
|
+
const t = textOf(v);
|
|
549
|
+
if (t !== void 0) texts.push(t);
|
|
550
|
+
else if (typeof v === "number") nums++;
|
|
551
|
+
else if (typeof v === "boolean") bools++;
|
|
552
|
+
else if (v instanceof Date) {
|
|
553
|
+
dates++;
|
|
554
|
+
if (hasTime(v, zone)) timed = true;
|
|
555
|
+
} else others++;
|
|
556
|
+
}
|
|
557
|
+
if (others > 0) return {
|
|
558
|
+
key,
|
|
559
|
+
type: "mixed",
|
|
560
|
+
ambiguousDates: false
|
|
561
|
+
};
|
|
562
|
+
const typedKinds = (nums ? 1 : 0) + (bools ? 1 : 0) + (dates ? 1 : 0);
|
|
563
|
+
if (typedKinds > 1) return {
|
|
564
|
+
key,
|
|
565
|
+
type: "mixed",
|
|
566
|
+
ambiguousDates: false
|
|
567
|
+
};
|
|
568
|
+
const no = numberOptions(locale);
|
|
569
|
+
const textNumbers = texts.length > 0 && texts.every((t) => parseNumber(t, no) !== void 0);
|
|
570
|
+
const textBools = texts.length > 0 && texts.every((t) => parseBoolean(t) !== void 0);
|
|
571
|
+
const { order, ambiguous } = dateOrderOf(texts, locale.dateOrder);
|
|
572
|
+
let textDates = false;
|
|
573
|
+
let textTimed = false;
|
|
574
|
+
if (texts.length > 0 && !textNumbers) textDates = texts.every((t) => {
|
|
575
|
+
const d = textToDate(t, order, zone);
|
|
576
|
+
if (d && hasTime(d, zone)) textTimed = true;
|
|
577
|
+
return d !== void 0;
|
|
578
|
+
});
|
|
579
|
+
const dateType = () => timed || textTimed ? "datetime" : "date";
|
|
580
|
+
if (texts.length === 0) return {
|
|
581
|
+
key,
|
|
582
|
+
type: nums ? "number" : bools ? "boolean" : dateType(),
|
|
583
|
+
ambiguousDates: false
|
|
584
|
+
};
|
|
585
|
+
if (!convertText) return {
|
|
586
|
+
key,
|
|
587
|
+
type: typedKinds === 0 ? "string" : "mixed",
|
|
588
|
+
ambiguousDates: false
|
|
589
|
+
};
|
|
590
|
+
if ((nums || typedKinds === 0) && textNumbers && !bools && !dates) return {
|
|
591
|
+
key,
|
|
592
|
+
type: "number",
|
|
593
|
+
ambiguousDates: false
|
|
594
|
+
};
|
|
595
|
+
if ((bools || typedKinds === 0) && textBools && !nums && !dates) return {
|
|
596
|
+
key,
|
|
597
|
+
type: "boolean",
|
|
598
|
+
ambiguousDates: false
|
|
599
|
+
};
|
|
600
|
+
if ((dates || typedKinds === 0) && textDates && !nums && !bools) return {
|
|
601
|
+
key,
|
|
602
|
+
type: dateType(),
|
|
603
|
+
dateOrder: order,
|
|
604
|
+
ambiguousDates: false
|
|
605
|
+
};
|
|
606
|
+
if (typedKinds === 0) return {
|
|
607
|
+
key,
|
|
608
|
+
type: "string",
|
|
609
|
+
ambiguousDates: ambiguous && texts.every((t) => dateParts(t) !== void 0 || t.trim().length >= 10 && parseIsoDate(t.trim(), zone))
|
|
610
|
+
};
|
|
611
|
+
return {
|
|
612
|
+
key,
|
|
613
|
+
type: "mixed",
|
|
614
|
+
ambiguousDates: false
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
function inferColumnTypes(dataset, options = {}) {
|
|
618
|
+
return inferDetailed(dataset, options).map(({ key, type, dateOrder }) => dateOrder ? {
|
|
619
|
+
key,
|
|
620
|
+
type,
|
|
621
|
+
dateOrder
|
|
622
|
+
} : {
|
|
623
|
+
key,
|
|
624
|
+
type
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
/** @internal inferColumnTypes plus the ambiguity flag the pipeline reports. */
|
|
628
|
+
function inferDetailed(dataset, options = {}) {
|
|
629
|
+
const locale = options.locale ?? {};
|
|
630
|
+
const zone = options.dateZone ?? "local";
|
|
631
|
+
const convertText = options.convertText ?? true;
|
|
632
|
+
return dataset.columns.map(({ key }) => inferOne(key, dataset.data.map((row) => row[key]), locale, zone, convertText));
|
|
633
|
+
}
|
|
634
|
+
/** Converts one value to `type`; undefined when it can't be. */
|
|
635
|
+
function convert(v, col, locale, zone) {
|
|
636
|
+
if (isEmpty(v)) return {
|
|
637
|
+
ok: true,
|
|
638
|
+
value: null
|
|
639
|
+
};
|
|
640
|
+
if (col.type !== "string" && typeof v === "object" && v !== null && !(v instanceof Date) && "error" in v) return {
|
|
641
|
+
ok: true,
|
|
642
|
+
value: v
|
|
643
|
+
};
|
|
644
|
+
const t = textOf(v);
|
|
645
|
+
switch (col.type) {
|
|
646
|
+
case "string":
|
|
647
|
+
if (t !== void 0) return {
|
|
648
|
+
ok: true,
|
|
649
|
+
value: t
|
|
650
|
+
};
|
|
651
|
+
if (v instanceof Date) return {
|
|
652
|
+
ok: true,
|
|
653
|
+
value: isoDate(v, zone)
|
|
654
|
+
};
|
|
655
|
+
if (typeof v === "object" && v && "error" in v) return {
|
|
656
|
+
ok: true,
|
|
657
|
+
value: v.error
|
|
658
|
+
};
|
|
659
|
+
return {
|
|
660
|
+
ok: true,
|
|
661
|
+
value: String(v)
|
|
662
|
+
};
|
|
663
|
+
case "number": {
|
|
664
|
+
if (typeof v === "number") return {
|
|
665
|
+
ok: true,
|
|
666
|
+
value: v
|
|
667
|
+
};
|
|
668
|
+
const n = t === void 0 ? void 0 : parseNumber(t, numberOptions(locale));
|
|
669
|
+
return n === void 0 ? { ok: false } : {
|
|
670
|
+
ok: true,
|
|
671
|
+
value: n
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
case "boolean": {
|
|
675
|
+
if (typeof v === "boolean") return {
|
|
676
|
+
ok: true,
|
|
677
|
+
value: v
|
|
678
|
+
};
|
|
679
|
+
const b = t === void 0 ? void 0 : parseBoolean(t);
|
|
680
|
+
return b === void 0 ? { ok: false } : {
|
|
681
|
+
ok: true,
|
|
682
|
+
value: b
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
case "date":
|
|
686
|
+
case "datetime": {
|
|
687
|
+
if (v instanceof Date) return {
|
|
688
|
+
ok: true,
|
|
689
|
+
value: v
|
|
690
|
+
};
|
|
691
|
+
const order = col.dateOrder ?? (locale.dateOrder && locale.dateOrder !== "auto" ? locale.dateOrder : void 0);
|
|
692
|
+
const d = t === void 0 ? void 0 : order ? textToDate(t, order, zone) : parseDate(t, { zone });
|
|
693
|
+
return d === void 0 ? { ok: false } : {
|
|
694
|
+
ok: true,
|
|
695
|
+
value: d
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
default: return {
|
|
699
|
+
ok: true,
|
|
700
|
+
value: v
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
function coerceColumns(dataset, types, options = {}) {
|
|
705
|
+
const locale = options.locale ?? {};
|
|
706
|
+
const zone = options.dateZone ?? "local";
|
|
707
|
+
const issues = [];
|
|
708
|
+
const plan = dataset.columns.map((c) => {
|
|
709
|
+
const t = Object.hasOwn(types, c.key) ? types[c.key] : void 0;
|
|
710
|
+
if (t === void 0) return void 0;
|
|
711
|
+
return {
|
|
712
|
+
column: c,
|
|
713
|
+
spec: typeof t === "string" ? {
|
|
714
|
+
key: c.key,
|
|
715
|
+
type: t
|
|
716
|
+
} : t
|
|
717
|
+
};
|
|
718
|
+
}).filter((x) => x !== void 0);
|
|
719
|
+
return {
|
|
720
|
+
data: dataset.data.map((row, i) => {
|
|
721
|
+
const out = Object.create(null);
|
|
722
|
+
for (const k of Object.keys(row)) out[k] = row[k];
|
|
723
|
+
for (const { column, spec } of plan) {
|
|
724
|
+
const r = convert(row[column.key], spec, locale, zone);
|
|
725
|
+
if (r.ok) out[column.key] = r.value;
|
|
726
|
+
else {
|
|
727
|
+
const rowNumber = dataset.rowNumbers?.[i] ?? i + 2;
|
|
728
|
+
out[column.key] = null;
|
|
729
|
+
issues.push({
|
|
730
|
+
row: rowNumber,
|
|
731
|
+
field: column.key,
|
|
732
|
+
...column.letter ? { ref: `${column.letter}${rowNumber}` } : {},
|
|
733
|
+
code: "TYPE",
|
|
734
|
+
message: `${column.letter ? `${column.letter}${rowNumber}` : `Row ${rowNumber}`}: ${JSON.stringify(String(textOf(row[column.key]) ?? row[column.key]))} is not a ${spec.type}.`,
|
|
735
|
+
severity: "error"
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
return out;
|
|
740
|
+
}),
|
|
741
|
+
issues
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
// src/internal/import/pipeline.ts
|
|
745
|
+
const CSV_NAME = /\.(csv|tsv|txt)$/i;
|
|
746
|
+
const CSV_MIME = /* @__PURE__ */ new Set([
|
|
747
|
+
"text/csv",
|
|
748
|
+
"text/plain",
|
|
749
|
+
"text/tab-separated-values"
|
|
750
|
+
]);
|
|
751
|
+
function checkEnum(name, v, allowed) {
|
|
752
|
+
if (v !== void 0 && !allowed.includes(v)) throw new TypeError(`${name} must be one of ${allowed.map((a) => `'${a}'`).join(", ")}, got ${JSON.stringify(v)}`);
|
|
753
|
+
}
|
|
754
|
+
function checkCount(name, v, min) {
|
|
755
|
+
if (v !== void 0 && (!Number.isInteger(v) || v < min)) throw new TypeError(`${name} must be an integer of at least ${min}, got ${String(v)}`);
|
|
756
|
+
}
|
|
757
|
+
function throwIfAborted(signal) {
|
|
758
|
+
if (signal?.aborted) throw signal.reason ?? Object.assign(/* @__PURE__ */ new Error("The operation was aborted."), { name: "AbortError" });
|
|
759
|
+
}
|
|
760
|
+
function bomEncoding(bytes) {
|
|
761
|
+
if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) return "utf-8";
|
|
762
|
+
if (bytes[0] === 255 && bytes[1] === 254) return "utf-16le";
|
|
763
|
+
if (bytes[0] === 254 && bytes[1] === 255) return "utf-16be";
|
|
764
|
+
}
|
|
765
|
+
function isError(v) {
|
|
766
|
+
return typeof v === "object" && v !== null && !(v instanceof Date) && "error" in v;
|
|
767
|
+
}
|
|
768
|
+
/** Rows to read before stopping: the header area plus the rows asked for, plus one to see whether more exist. */
|
|
769
|
+
function readCap(options) {
|
|
770
|
+
const rows = options.preview ?? options.maxRows;
|
|
771
|
+
if (rows === void 0) return void 0;
|
|
772
|
+
const h = options.header ?? "auto";
|
|
773
|
+
return (h === false ? 0 : typeof h === "number" ? h + 1 : typeof h === "object" ? (h.row === void 0 ? 25 : h.row) + h.rows : 25) + rows + 1;
|
|
774
|
+
}
|
|
775
|
+
async function importDataset(input, options = {}) {
|
|
776
|
+
const o = options;
|
|
777
|
+
checkEnum("format", o.format, [
|
|
778
|
+
"auto",
|
|
779
|
+
"xlsx",
|
|
780
|
+
"csv"
|
|
781
|
+
]);
|
|
782
|
+
checkEnum("types", typeof o.types === "string" ? o.types : void 0, ["infer", "none"]);
|
|
783
|
+
checkEnum("errorCells", o.errorCells, ["null", "keep"]);
|
|
784
|
+
checkEnum("dates", o.dates, ["date", "serial"]);
|
|
785
|
+
checkEnum("dateZone", o.dateZone, ["local", "utc"]);
|
|
786
|
+
checkEnum("locale.dateOrder", o.locale?.dateOrder, [
|
|
787
|
+
"auto",
|
|
788
|
+
"YMD",
|
|
789
|
+
"DMY",
|
|
790
|
+
"MDY"
|
|
791
|
+
]);
|
|
792
|
+
checkCount("maxRows", o.maxRows, 0);
|
|
793
|
+
checkCount("preview", o.preview, 0);
|
|
794
|
+
if (typeof o.header === "object" && o.header !== null) {
|
|
795
|
+
checkCount("header.rows", o.header.rows, 1);
|
|
796
|
+
checkCount("header.row", o.header.row, 0);
|
|
797
|
+
} else if (o.header !== void 0 && o.header !== "auto" && o.header !== false) checkCount("header", o.header, 0);
|
|
798
|
+
if (o.sheet !== void 0 && typeof o.sheet !== "string" && !(Number.isInteger(o.sheet) && o.sheet >= 0)) throw new TypeError("sheet must be a name, a non-negative index or 'first-visible'");
|
|
799
|
+
if (o.mapping !== void 0 && !o.schema) throw new TypeError("mapping needs a schema");
|
|
800
|
+
const warnings = [];
|
|
801
|
+
const warn = (w) => {
|
|
802
|
+
warnings.push(w);
|
|
803
|
+
o.onWarning?.(w);
|
|
804
|
+
};
|
|
805
|
+
const progress = (phase, ratio) => o.onProgress?.({
|
|
806
|
+
phase,
|
|
807
|
+
ratio
|
|
808
|
+
});
|
|
809
|
+
const zone = o.dateZone ?? "local";
|
|
810
|
+
const locale = o.locale ?? {};
|
|
811
|
+
throwIfAborted(o.signal);
|
|
812
|
+
const named = typeof input === "object" && input !== null ? input : {};
|
|
813
|
+
const fileName = o.fileName ?? (typeof named.name === "string" ? named.name : void 0);
|
|
814
|
+
const mimeType = (o.mimeType ?? (typeof named.type === "string" ? named.type : "")).split(";")[0].trim().toLowerCase();
|
|
815
|
+
const csvHint = fileName !== void 0 && CSV_NAME.test(fileName) || CSV_MIME.has(mimeType);
|
|
816
|
+
let bytes;
|
|
817
|
+
let format;
|
|
818
|
+
if (typeof input === "string") format = "csv";
|
|
819
|
+
else {
|
|
820
|
+
bytes = await toBytes(input, "importDataset", "a string, ");
|
|
821
|
+
if (o.format === "csv") format = "csv";
|
|
822
|
+
else if (o.format === "xlsx") format = "xlsx";
|
|
823
|
+
else {
|
|
824
|
+
const detected = await detectFormat(bytes);
|
|
825
|
+
if (detected === "unknown") {
|
|
826
|
+
if (!csvHint) throw new FormatError("UNSUPPORTED_FORMAT", "The file is neither a zip-based workbook nor named or typed as CSV.", { details: { format: "unknown" } });
|
|
827
|
+
format = "csv";
|
|
828
|
+
} else format = detected === "xlsm" || detected === "xltx" || detected === "xltm" ? detected : "xlsx";
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
throwIfAborted(o.signal);
|
|
832
|
+
const cap = readCap(o);
|
|
833
|
+
let sheet;
|
|
834
|
+
let truncatedRead = false;
|
|
835
|
+
const meta = {
|
|
836
|
+
format,
|
|
837
|
+
...fileName !== void 0 ? { fileName } : {}
|
|
838
|
+
};
|
|
839
|
+
if (format === "csv") {
|
|
840
|
+
const r = await readCsv(typeof input === "string" ? input : bytes, {
|
|
841
|
+
delimiter: o.delimiter ?? "auto",
|
|
842
|
+
encoding: o.encoding,
|
|
843
|
+
maxRows: cap,
|
|
844
|
+
signal: o.signal,
|
|
845
|
+
inferTypes: false
|
|
846
|
+
});
|
|
847
|
+
for (const w of r.warnings) {
|
|
848
|
+
if (w.code === "CSV_ROWS_TRUNCATED") truncatedRead = true;
|
|
849
|
+
warn(w);
|
|
850
|
+
}
|
|
851
|
+
sheet = {
|
|
852
|
+
name: "CSV",
|
|
853
|
+
rows: r.rows
|
|
854
|
+
};
|
|
855
|
+
meta.delimiter = r.delimiter;
|
|
856
|
+
meta.bom = r.bom;
|
|
857
|
+
if (bytes) meta.encoding = bomEncoding(bytes) ?? (o.encoding ?? "utf-8").toLowerCase();
|
|
858
|
+
} else {
|
|
859
|
+
const sheets = await readSheetNames(bytes, {
|
|
860
|
+
limits: o.limits,
|
|
861
|
+
signal: o.signal
|
|
862
|
+
});
|
|
863
|
+
const want = o.sheet ?? "first-visible";
|
|
864
|
+
const info = want === "first-visible" ? sheets.find((s) => s.state === "visible") : typeof want === "number" ? sheets[want] : sheets.find((s) => s.name === want);
|
|
865
|
+
if (!info) throw new ValidationError("SHEET_NOT_FOUND", want === "first-visible" ? "The workbook has no visible sheet." : `No sheet ${JSON.stringify(want)} in the workbook.`, { details: {
|
|
866
|
+
sheet: want,
|
|
867
|
+
sheets: sheets.map((s) => s.name)
|
|
868
|
+
} });
|
|
869
|
+
const { workbook } = await read(bytes, {
|
|
870
|
+
sheets: [info.index],
|
|
871
|
+
styles: false,
|
|
872
|
+
richText: "plain",
|
|
873
|
+
formulas: true,
|
|
874
|
+
dates: o.dates ?? "date",
|
|
875
|
+
dateZone: zone,
|
|
876
|
+
limits: o.limits,
|
|
877
|
+
signal: o.signal,
|
|
878
|
+
maxRows: cap,
|
|
879
|
+
onProgress: (p) => progress(p.phase === "unzip" ? "unzip" : "parse", p.ratio * .9),
|
|
880
|
+
onWarning: (w) => {
|
|
881
|
+
if (w.code === "ROWS_TRUNCATED") truncatedRead = true;
|
|
882
|
+
warn(w);
|
|
883
|
+
}
|
|
884
|
+
});
|
|
885
|
+
sheet = workbook.sheets[info.index];
|
|
886
|
+
meta.sheet = {
|
|
887
|
+
name: info.name,
|
|
888
|
+
index: info.index
|
|
889
|
+
};
|
|
890
|
+
meta.sheets = sheets;
|
|
891
|
+
}
|
|
892
|
+
throwIfAborted(o.signal);
|
|
893
|
+
progress("dataset", .9);
|
|
894
|
+
const header = o.header ?? "auto";
|
|
895
|
+
let headerRows;
|
|
896
|
+
let detected = false;
|
|
897
|
+
let confidence;
|
|
898
|
+
let join;
|
|
899
|
+
if (header === "auto") {
|
|
900
|
+
const d = detectHeader(sheet, {
|
|
901
|
+
range: o.range,
|
|
902
|
+
locale
|
|
903
|
+
});
|
|
904
|
+
headerRows = d.rows;
|
|
905
|
+
detected = true;
|
|
906
|
+
confidence = d.confidence;
|
|
907
|
+
} else if (header === false) headerRows = [];
|
|
908
|
+
else if (typeof header === "number") headerRows = [header];
|
|
909
|
+
else {
|
|
910
|
+
let start = header.row;
|
|
911
|
+
if (start === void 0) {
|
|
912
|
+
const d = detectHeader(sheet, {
|
|
913
|
+
range: o.range,
|
|
914
|
+
locale
|
|
915
|
+
});
|
|
916
|
+
start = d.rows[0];
|
|
917
|
+
detected = true;
|
|
918
|
+
confidence = d.confidence;
|
|
919
|
+
}
|
|
920
|
+
headerRows = Array.from({ length: header.rows }, (_, i) => start + i);
|
|
921
|
+
join = header.join;
|
|
922
|
+
}
|
|
923
|
+
const ds = toDatasetDetailed(sheet, {
|
|
924
|
+
headerRow: headerRows.length ? headerRows[0] : false,
|
|
925
|
+
headerRows: Math.max(1, headerRows.length),
|
|
926
|
+
join,
|
|
927
|
+
range: o.range,
|
|
928
|
+
skipTotals: o.skipTotals ?? "auto"
|
|
929
|
+
});
|
|
930
|
+
const issues = [];
|
|
931
|
+
const base = {
|
|
932
|
+
header: {
|
|
933
|
+
rows: headerRows,
|
|
934
|
+
detected,
|
|
935
|
+
...confidence ? { confidence } : {}
|
|
936
|
+
},
|
|
937
|
+
range: ds.range ?? "",
|
|
938
|
+
totalsRowSkipped: ds.totalsSkipped
|
|
939
|
+
};
|
|
940
|
+
if (ds.range === void 0 || ds.columns.length === 0) {
|
|
941
|
+
issues.push({
|
|
942
|
+
row: 0,
|
|
943
|
+
code: "EMPTY",
|
|
944
|
+
message: "The file has no data.",
|
|
945
|
+
severity: "warning"
|
|
946
|
+
});
|
|
947
|
+
progress("dataset", 1);
|
|
948
|
+
return {
|
|
949
|
+
columns: [],
|
|
950
|
+
data: [],
|
|
951
|
+
rowNumbers: [],
|
|
952
|
+
issues,
|
|
953
|
+
warnings,
|
|
954
|
+
meta: {
|
|
955
|
+
...meta,
|
|
956
|
+
...base,
|
|
957
|
+
truncated: false
|
|
958
|
+
}
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
let data = ds.data;
|
|
962
|
+
let rowNumbers = ds.rowNumbers;
|
|
963
|
+
let truncated = false;
|
|
964
|
+
if (o.preview !== void 0) {
|
|
965
|
+
if (data.length > o.preview || truncatedRead) truncated = true;
|
|
966
|
+
data = data.slice(0, o.preview);
|
|
967
|
+
rowNumbers = rowNumbers.slice(0, o.preview);
|
|
968
|
+
} else if (o.maxRows !== void 0 && (data.length > o.maxRows || truncatedRead)) throw new LimitError("LIMIT_EXCEEDED", `The file has more than maxRows (${o.maxRows}) data rows.`, { details: {
|
|
969
|
+
limit: "maxRows",
|
|
970
|
+
value: data.length,
|
|
971
|
+
max: o.maxRows
|
|
972
|
+
} });
|
|
973
|
+
if (data.length === 0) issues.push({
|
|
974
|
+
row: 0,
|
|
975
|
+
code: "EMPTY",
|
|
976
|
+
message: "The file has a header but no data rows.",
|
|
977
|
+
severity: "warning"
|
|
978
|
+
});
|
|
979
|
+
if ((o.errorCells ?? "null") === "null") for (let i = 0; i < data.length; i++) {
|
|
980
|
+
const row = data[i];
|
|
981
|
+
for (const c of ds.columns) {
|
|
982
|
+
const v = row[c.key];
|
|
983
|
+
if (!isError(v)) continue;
|
|
984
|
+
row[c.key] = null;
|
|
985
|
+
const ref = `${c.letter}${rowNumbers[i]}`;
|
|
986
|
+
issues.push({
|
|
987
|
+
row: rowNumbers[i],
|
|
988
|
+
field: c.key,
|
|
989
|
+
ref,
|
|
990
|
+
code: "ERROR_CELL",
|
|
991
|
+
message: `${ref} holds the error ${v.error}; read as empty.`,
|
|
992
|
+
severity: "warning"
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
throwIfAborted(o.signal);
|
|
997
|
+
const keyOf = (name) => {
|
|
998
|
+
const byKey = ds.columns.find((c) => c.key === name);
|
|
999
|
+
if (byKey) return byKey.key;
|
|
1000
|
+
const byTitle = ds.columns.find((c) => c.title === name);
|
|
1001
|
+
if (byTitle) return byTitle.key;
|
|
1002
|
+
throw new TypeError(`types: no column with key or title ${JSON.stringify(name)}`);
|
|
1003
|
+
};
|
|
1004
|
+
const forced = /* @__PURE__ */ new Map();
|
|
1005
|
+
if (typeof o.types === "object" && o.types !== null) for (const name of Object.keys(o.types)) forced.set(keyOf(name), o.types[name]);
|
|
1006
|
+
const mapped = o.schema && o.preview === void 0 ? mapColumns(ds.columns, o.schema, o.mapping) : void 0;
|
|
1007
|
+
if (mapped) for (const [field, spec] of Object.entries(o.schema.fields)) {
|
|
1008
|
+
const col = mapped.mapping[field];
|
|
1009
|
+
if (spec.type && col) forced.set(col, spec.type);
|
|
1010
|
+
}
|
|
1011
|
+
const mode = typeof o.types === "string" ? o.types : "infer";
|
|
1012
|
+
const dsLike = {
|
|
1013
|
+
columns: ds.columns,
|
|
1014
|
+
data,
|
|
1015
|
+
rowNumbers
|
|
1016
|
+
};
|
|
1017
|
+
const inferred = inferDetailed(dsLike, {
|
|
1018
|
+
locale,
|
|
1019
|
+
dateZone: zone,
|
|
1020
|
+
convertText: mode === "infer"
|
|
1021
|
+
});
|
|
1022
|
+
const plan = Object.create(null);
|
|
1023
|
+
const typeOf = /* @__PURE__ */ new Map();
|
|
1024
|
+
for (const inf of inferred) {
|
|
1025
|
+
const f = forced.get(inf.key);
|
|
1026
|
+
if (f) {
|
|
1027
|
+
plan[inf.key] = inf.dateOrder ? {
|
|
1028
|
+
key: inf.key,
|
|
1029
|
+
type: f,
|
|
1030
|
+
dateOrder: inf.dateOrder
|
|
1031
|
+
} : f;
|
|
1032
|
+
typeOf.set(inf.key, f);
|
|
1033
|
+
} else {
|
|
1034
|
+
if (mode === "infer") plan[inf.key] = inf;
|
|
1035
|
+
typeOf.set(inf.key, inf.type);
|
|
1036
|
+
if (inf.ambiguousDates) issues.push({
|
|
1037
|
+
row: 0,
|
|
1038
|
+
field: inf.key,
|
|
1039
|
+
code: "DATE_ORDER_AMBIGUOUS",
|
|
1040
|
+
message: `Column "${inf.key}" looks like dates, but the day/month order can't be told from the data; set locale.dateOrder.`,
|
|
1041
|
+
severity: "warning"
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
const coerced = coerceColumns(dsLike, plan, {
|
|
1046
|
+
locale,
|
|
1047
|
+
dateZone: zone
|
|
1048
|
+
});
|
|
1049
|
+
issues.push(...coerced.issues);
|
|
1050
|
+
const typedColumns = ds.columns.map((c) => ({
|
|
1051
|
+
key: c.key,
|
|
1052
|
+
title: c.title,
|
|
1053
|
+
letter: c.letter,
|
|
1054
|
+
type: typeOf.get(c.key) ?? "mixed"
|
|
1055
|
+
}));
|
|
1056
|
+
progress("dataset", .97);
|
|
1057
|
+
let result;
|
|
1058
|
+
if (mapped) {
|
|
1059
|
+
const m = applyMapping({
|
|
1060
|
+
columns: typedColumns,
|
|
1061
|
+
data: coerced.data,
|
|
1062
|
+
rowNumbers
|
|
1063
|
+
}, mapped.mapping, o.schema);
|
|
1064
|
+
issues.push(...m.issues);
|
|
1065
|
+
result = m;
|
|
1066
|
+
meta.mapping = mapped.mapping;
|
|
1067
|
+
meta.unmappedColumns = mapped.unmapped;
|
|
1068
|
+
} else result = {
|
|
1069
|
+
columns: typedColumns,
|
|
1070
|
+
data: coerced.data,
|
|
1071
|
+
rowNumbers
|
|
1072
|
+
};
|
|
1073
|
+
progress("dataset", 1);
|
|
1074
|
+
return {
|
|
1075
|
+
...result,
|
|
1076
|
+
issues,
|
|
1077
|
+
warnings,
|
|
1078
|
+
meta: {
|
|
1079
|
+
...meta,
|
|
1080
|
+
...base,
|
|
1081
|
+
truncated
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
export { mapColumns as a, parseNumber as c, applyMapping as i, coerceColumns as n, detectHeader as o, inferColumnTypes as r, parseDate as s, importDataset as t };
|