@noy-db/as-xlsx 0.2.0-pre.20 → 0.2.0-pre.23
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/index.cjs +448 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +147 -3
- package/dist/index.d.ts +147 -3
- package/dist/index.js +443 -5
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -2,7 +2,19 @@
|
|
|
2
2
|
import { writeZip } from "@noy-db/as-zip";
|
|
3
3
|
var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
|
|
4
4
|
var ENCODER = new TextEncoder();
|
|
5
|
-
|
|
5
|
+
function formula(f, cachedValue) {
|
|
6
|
+
return cachedValue === void 0 ? { __xlsxFormula: f } : { __xlsxFormula: f, v: cachedValue };
|
|
7
|
+
}
|
|
8
|
+
function isFormulaCell(v) {
|
|
9
|
+
return typeof v === "object" && v !== null && typeof v.__xlsxFormula === "string";
|
|
10
|
+
}
|
|
11
|
+
function styled(value, numberFormat) {
|
|
12
|
+
return { __xlsxStyle: numberFormat, v: value };
|
|
13
|
+
}
|
|
14
|
+
function isStyledCell(v) {
|
|
15
|
+
return typeof v === "object" && v !== null && typeof v.__xlsxStyle === "string";
|
|
16
|
+
}
|
|
17
|
+
async function writeXlsx(sheets, options = {}) {
|
|
6
18
|
if (sheets.length === 0) {
|
|
7
19
|
throw new Error("writeXlsx: at least one sheet is required");
|
|
8
20
|
}
|
|
@@ -27,6 +39,16 @@ async function writeXlsx(sheets) {
|
|
|
27
39
|
stringIndex.set(s, idx);
|
|
28
40
|
return idx;
|
|
29
41
|
};
|
|
42
|
+
const numFmtCodes = [];
|
|
43
|
+
const styleIndexByCode = /* @__PURE__ */ new Map();
|
|
44
|
+
const internStyle = (code) => {
|
|
45
|
+
const existing = styleIndexByCode.get(code);
|
|
46
|
+
if (existing !== void 0) return existing;
|
|
47
|
+
const idx = numFmtCodes.length + 1;
|
|
48
|
+
numFmtCodes.push(code);
|
|
49
|
+
styleIndexByCode.set(code, idx);
|
|
50
|
+
return idx;
|
|
51
|
+
};
|
|
30
52
|
const sheetXmls = safeSheets.map((sheet) => {
|
|
31
53
|
const lines = [
|
|
32
54
|
XML_HEADER,
|
|
@@ -56,12 +78,42 @@ async function writeXlsx(sheets) {
|
|
|
56
78
|
}
|
|
57
79
|
for (const row of sheet.rows) {
|
|
58
80
|
rowNum++;
|
|
59
|
-
const cells = row.map((value, i) => cellXml(value, i + 1, rowNum, internString)).join("");
|
|
81
|
+
const cells = row.map((value, i) => cellXml(value, i + 1, rowNum, internString, internStyle)).join("");
|
|
60
82
|
lines.push(`<row r="${rowNum}">${cells}</row>`);
|
|
61
83
|
}
|
|
62
|
-
lines.push("</sheetData>"
|
|
84
|
+
lines.push("</sheetData>");
|
|
85
|
+
if (sheet.validations && sheet.validations.length > 0) {
|
|
86
|
+
lines.push(`<dataValidations count="${sheet.validations.length}">`);
|
|
87
|
+
for (const dv of sheet.validations) {
|
|
88
|
+
const f1 = dv.formula1 ?? `"${(dv.values ?? []).join(",")}"`;
|
|
89
|
+
lines.push(
|
|
90
|
+
`<dataValidation type="list" allowBlank="1" showInputMessage="1" showErrorMessage="1" sqref="${escapeXmlAttr(dv.sqref)}"><formula1>${escapeXmlText(f1)}</formula1></dataValidation>`
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
lines.push("</dataValidations>");
|
|
94
|
+
}
|
|
95
|
+
lines.push("</worksheet>");
|
|
63
96
|
return lines.join("");
|
|
64
97
|
});
|
|
98
|
+
const hasStyles = numFmtCodes.length > 0;
|
|
99
|
+
const stylesXml = hasStyles ? [
|
|
100
|
+
XML_HEADER,
|
|
101
|
+
'<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">',
|
|
102
|
+
`<numFmts count="${numFmtCodes.length}">`,
|
|
103
|
+
...numFmtCodes.map((code, i) => `<numFmt numFmtId="${164 + i}" formatCode="${escapeXmlAttr(code)}"/>`),
|
|
104
|
+
"</numFmts>",
|
|
105
|
+
'<fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts>',
|
|
106
|
+
'<fills count="1"><fill><patternFill patternType="none"/></fill></fills>',
|
|
107
|
+
'<borders count="1"><border/></borders>',
|
|
108
|
+
'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>',
|
|
109
|
+
`<cellXfs count="${numFmtCodes.length + 1}">`,
|
|
110
|
+
'<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>',
|
|
111
|
+
...numFmtCodes.map(
|
|
112
|
+
(_, i) => `<xf numFmtId="${164 + i}" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/>`
|
|
113
|
+
),
|
|
114
|
+
"</cellXfs>",
|
|
115
|
+
"</styleSheet>"
|
|
116
|
+
].join("") : "";
|
|
65
117
|
const sheetEntries = safeSheets.map((s, i) => ({
|
|
66
118
|
index: i + 1,
|
|
67
119
|
id: `rId${i + 1}`,
|
|
@@ -78,6 +130,7 @@ async function writeXlsx(sheets) {
|
|
|
78
130
|
(s) => `<Override PartName="/${s.path}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`
|
|
79
131
|
),
|
|
80
132
|
'<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>',
|
|
133
|
+
...hasStyles ? ['<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'] : [],
|
|
81
134
|
"</Types>"
|
|
82
135
|
].join("");
|
|
83
136
|
const rootRels = XML_HEADER + '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>';
|
|
@@ -89,6 +142,13 @@ async function writeXlsx(sheets) {
|
|
|
89
142
|
(s) => `<sheet name="${escapeXmlAttr(s.name)}" sheetId="${s.index}" r:id="${s.id}"/>`
|
|
90
143
|
),
|
|
91
144
|
"</sheets>",
|
|
145
|
+
...options.definedNames && options.definedNames.length > 0 ? [
|
|
146
|
+
"<definedNames>",
|
|
147
|
+
...options.definedNames.map(
|
|
148
|
+
(d) => `<definedName name="${escapeXmlAttr(d.name)}">${escapeXmlText(d.ref)}</definedName>`
|
|
149
|
+
),
|
|
150
|
+
"</definedNames>"
|
|
151
|
+
] : [],
|
|
92
152
|
"</workbook>"
|
|
93
153
|
].join("");
|
|
94
154
|
const workbookRels = [
|
|
@@ -98,6 +158,7 @@ async function writeXlsx(sheets) {
|
|
|
98
158
|
(s) => `<Relationship Id="${s.id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${s.index}.xml"/>`
|
|
99
159
|
),
|
|
100
160
|
`<Relationship Id="rIdSharedStrings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>`,
|
|
161
|
+
...hasStyles ? [`<Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>`] : [],
|
|
101
162
|
"</Relationships>"
|
|
102
163
|
].join("");
|
|
103
164
|
const sharedStringsXml = [
|
|
@@ -112,12 +173,28 @@ async function writeXlsx(sheets) {
|
|
|
112
173
|
{ path: "xl/workbook.xml", bytes: ENCODER.encode(workbookXml) },
|
|
113
174
|
{ path: "xl/_rels/workbook.xml.rels", bytes: ENCODER.encode(workbookRels) },
|
|
114
175
|
{ path: "xl/sharedStrings.xml", bytes: ENCODER.encode(sharedStringsXml) },
|
|
176
|
+
...hasStyles ? [{ path: "xl/styles.xml", bytes: ENCODER.encode(stylesXml) }] : [],
|
|
115
177
|
...sheetEntries.map((s, i) => ({ path: s.path, bytes: ENCODER.encode(sheetXmls[i] ?? "") }))
|
|
116
178
|
];
|
|
117
179
|
return await writeZip(entries);
|
|
118
180
|
}
|
|
119
|
-
function cellXml(value, colIdx, rowNum, intern) {
|
|
181
|
+
function cellXml(value, colIdx, rowNum, intern, internStyle) {
|
|
120
182
|
const ref = `${colLetter(colIdx)}${rowNum}`;
|
|
183
|
+
if (isStyledCell(value)) {
|
|
184
|
+
const s2 = internStyle(value.__xlsxStyle);
|
|
185
|
+
const v = value.v;
|
|
186
|
+
if (v === null || v === void 0 || v === "") return `<c r="${ref}" s="${s2}"/>`;
|
|
187
|
+
if (typeof v === "number" && Number.isFinite(v)) return `<c r="${ref}" s="${s2}"><v>${v}</v></c>`;
|
|
188
|
+
if (typeof v === "boolean") return `<c r="${ref}" s="${s2}" t="b"><v>${v ? 1 : 0}</v></c>`;
|
|
189
|
+
return `<c r="${ref}" s="${s2}" t="s"><v>${intern(typeof v === "string" ? v : String(v))}</v></c>`;
|
|
190
|
+
}
|
|
191
|
+
if (isFormulaCell(value)) {
|
|
192
|
+
const f = escapeXmlText(value.__xlsxFormula);
|
|
193
|
+
if (value.v === void 0) return `<c r="${ref}"><f>${f}</f></c>`;
|
|
194
|
+
if (typeof value.v === "number" && Number.isFinite(value.v)) return `<c r="${ref}"><f>${f}</f><v>${value.v}</v></c>`;
|
|
195
|
+
if (typeof value.v === "boolean") return `<c r="${ref}" t="b"><f>${f}</f><v>${value.v ? 1 : 0}</v></c>`;
|
|
196
|
+
return `<c r="${ref}" t="str"><f>${f}</f><v>${escapeXmlText(String(value.v))}</v></c>`;
|
|
197
|
+
}
|
|
121
198
|
if (value === null || value === void 0 || value === "") return `<c r="${ref}"/>`;
|
|
122
199
|
if (typeof value === "number" && Number.isFinite(value)) {
|
|
123
200
|
return `<c r="${ref}"><v>${value}</v></c>`;
|
|
@@ -342,6 +419,92 @@ function stringAttr(raw) {
|
|
|
342
419
|
return "";
|
|
343
420
|
}
|
|
344
421
|
|
|
422
|
+
// src/infer.ts
|
|
423
|
+
var ISO_DATE = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/;
|
|
424
|
+
function inferType(vals) {
|
|
425
|
+
if (vals.length === 0) return "string";
|
|
426
|
+
if (vals.every((v) => typeof v === "boolean")) return "boolean";
|
|
427
|
+
if (vals.every((v) => typeof v === "number")) return "number";
|
|
428
|
+
if (vals.every((v) => typeof v === "string" && ISO_DATE.test(v))) return "date";
|
|
429
|
+
return "string";
|
|
430
|
+
}
|
|
431
|
+
async function inferSchema(bytes, options = {}) {
|
|
432
|
+
const skip = new Set(options.skipSheets ?? []);
|
|
433
|
+
const decoded = await readXlsx(bytes);
|
|
434
|
+
const sheets = [];
|
|
435
|
+
for (const sh of decoded.sheets) {
|
|
436
|
+
if (sh.name.startsWith("_") || skip.has(sh.name)) continue;
|
|
437
|
+
const headerRow = sh.rows[0] ?? {};
|
|
438
|
+
const colToField = /* @__PURE__ */ new Map();
|
|
439
|
+
const fields = [];
|
|
440
|
+
for (const [letter, val] of Object.entries(headerRow)) {
|
|
441
|
+
const name = typeof val === "string" ? val.trim() : typeof val === "number" || typeof val === "boolean" ? String(val) : "";
|
|
442
|
+
if (!name) continue;
|
|
443
|
+
colToField.set(letter, name);
|
|
444
|
+
fields.push(name);
|
|
445
|
+
}
|
|
446
|
+
const records = sh.rows.slice(1).map((row) => {
|
|
447
|
+
const rec = {};
|
|
448
|
+
for (const [letter, val] of Object.entries(row)) {
|
|
449
|
+
const f = colToField.get(letter);
|
|
450
|
+
if (f !== void 0) rec[f] = val;
|
|
451
|
+
}
|
|
452
|
+
return rec;
|
|
453
|
+
});
|
|
454
|
+
sheets.push({ name: sh.name, fields, records });
|
|
455
|
+
}
|
|
456
|
+
const valuesOf = (s, f) => s.records.map((r) => r[f]).filter((v) => v != null && v !== "");
|
|
457
|
+
const idFieldOf = (s) => {
|
|
458
|
+
if (s.fields.includes("id")) return "id";
|
|
459
|
+
for (const f of s.fields) {
|
|
460
|
+
const vals = valuesOf(s, f);
|
|
461
|
+
if (vals.length > 0 && new Set(vals.map((v) => String(v))).size === vals.length) return f;
|
|
462
|
+
}
|
|
463
|
+
return s.fields[0] ?? "id";
|
|
464
|
+
};
|
|
465
|
+
const meta = sheets.map((s) => ({ s, idField: idFieldOf(s) }));
|
|
466
|
+
const idValuesByName = /* @__PURE__ */ new Map();
|
|
467
|
+
for (const { s, idField } of meta) {
|
|
468
|
+
idValuesByName.set(s.name, new Set(valuesOf(s, idField).map((v) => String(v))));
|
|
469
|
+
}
|
|
470
|
+
const collections = {};
|
|
471
|
+
for (const { s, idField } of meta) {
|
|
472
|
+
const fields = {};
|
|
473
|
+
for (const f of s.fields) {
|
|
474
|
+
const vals = valuesOf(s, f);
|
|
475
|
+
const type = inferType(vals);
|
|
476
|
+
let references;
|
|
477
|
+
if (f !== idField && type === "string" && vals.length > 0) {
|
|
478
|
+
const distinct = new Set(vals.map((v) => String(v)));
|
|
479
|
+
for (const { s: other } of meta) {
|
|
480
|
+
if (other.name === s.name) continue;
|
|
481
|
+
const ids = idValuesByName.get(other.name);
|
|
482
|
+
if (ids && ids.size > 0 && [...distinct].every((v) => ids.has(v))) {
|
|
483
|
+
references = other.name;
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
fields[f] = references ? { type, references } : { type };
|
|
489
|
+
}
|
|
490
|
+
collections[s.name] = { idField, fields };
|
|
491
|
+
}
|
|
492
|
+
return { collections };
|
|
493
|
+
}
|
|
494
|
+
function zodSourceFor(schema) {
|
|
495
|
+
const zType = (t) => t === "number" ? "z.number()" : t === "boolean" ? "z.boolean()" : t === "date" ? "z.string().datetime()" : "z.string()";
|
|
496
|
+
const blocks = [`import { z } from 'zod'`];
|
|
497
|
+
for (const [name, c] of Object.entries(schema.collections)) {
|
|
498
|
+
const lines = Object.entries(c.fields).map(
|
|
499
|
+
([f, d]) => ` ${f}: ${zType(d.type)},${d.references ? ` // \u2192 ${d.references}` : ""}`
|
|
500
|
+
);
|
|
501
|
+
blocks.push(`export const ${name}Schema = z.object({
|
|
502
|
+
${lines.join("\n")}
|
|
503
|
+
})`);
|
|
504
|
+
}
|
|
505
|
+
return blocks.join("\n\n");
|
|
506
|
+
}
|
|
507
|
+
|
|
345
508
|
// src/index.ts
|
|
346
509
|
import { diffVault } from "@noy-db/hub";
|
|
347
510
|
async function toBytesFromCollection(vault, collectionName) {
|
|
@@ -354,6 +517,10 @@ async function toBytes(vault, options) {
|
|
|
354
517
|
if (options.sheets.length === 0) {
|
|
355
518
|
throw new Error("as-xlsx: at least one sheet is required");
|
|
356
519
|
}
|
|
520
|
+
if (options.smart) {
|
|
521
|
+
const { sheets, definedNames } = await buildSmartSheets(vault, options);
|
|
522
|
+
return writeXlsx(sheets, { definedNames });
|
|
523
|
+
}
|
|
357
524
|
const materialisedSheets = [];
|
|
358
525
|
for (const sheetOpt of options.sheets) {
|
|
359
526
|
const collection = vault.collection(sheetOpt.collection);
|
|
@@ -397,6 +564,250 @@ async function write(vault, path, options) {
|
|
|
397
564
|
const { writeFile } = await import("fs/promises");
|
|
398
565
|
await writeFile(path, bytes);
|
|
399
566
|
}
|
|
567
|
+
function safeStringify(v) {
|
|
568
|
+
if (typeof v === "string") return v;
|
|
569
|
+
if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint") return String(v);
|
|
570
|
+
if (v == null) return "";
|
|
571
|
+
try {
|
|
572
|
+
return JSON.stringify(v) ?? "";
|
|
573
|
+
} catch {
|
|
574
|
+
return "";
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
function asCached(v) {
|
|
578
|
+
if (typeof v === "number" || typeof v === "boolean" || typeof v === "string") return v;
|
|
579
|
+
return safeStringify(v);
|
|
580
|
+
}
|
|
581
|
+
async function buildSmartSheets(vault, options) {
|
|
582
|
+
const snapshot = await vault.dumpSchema();
|
|
583
|
+
const sheetNameByCollection = /* @__PURE__ */ new Map();
|
|
584
|
+
for (const s of options.sheets) sheetNameByCollection.set(s.collection, s.name);
|
|
585
|
+
const mats = [];
|
|
586
|
+
const localeSet = /* @__PURE__ */ new Set();
|
|
587
|
+
for (const sheetOpt of options.sheets) {
|
|
588
|
+
const collection = vault.collection(sheetOpt.collection);
|
|
589
|
+
const list = await collection.list();
|
|
590
|
+
const records = [];
|
|
591
|
+
for (const item of list) {
|
|
592
|
+
const r = item;
|
|
593
|
+
if (sheetOpt.filter && !sheetOpt.filter(r)) continue;
|
|
594
|
+
records.push(r);
|
|
595
|
+
}
|
|
596
|
+
const base = sheetOpt.columns ?? inferColumns(records);
|
|
597
|
+
const cols = ["id", ...base.filter((c) => c !== "id")];
|
|
598
|
+
const labelCol = cols.find((c) => c !== "id");
|
|
599
|
+
const labelMap = /* @__PURE__ */ new Map();
|
|
600
|
+
if (labelCol) {
|
|
601
|
+
for (const r of records) if (r.id != null) labelMap.set(safeStringify(r.id), r[labelCol]);
|
|
602
|
+
}
|
|
603
|
+
const i18nFields = (sheetOpt.i18nFields ?? []).filter((f) => cols.includes(f));
|
|
604
|
+
for (const f of i18nFields) {
|
|
605
|
+
for (const r of records) {
|
|
606
|
+
const v = r[f];
|
|
607
|
+
if (v && typeof v === "object") for (const loc of Object.keys(v)) localeSet.add(loc);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
mats.push({ opt: sheetOpt, records, cols, labelMap, i18nFields });
|
|
611
|
+
}
|
|
612
|
+
const matByCollection = new Map(mats.map((m) => [m.opt.collection, m]));
|
|
613
|
+
const dictEntries = /* @__PURE__ */ new Map();
|
|
614
|
+
for (const m of mats) {
|
|
615
|
+
for (const [field, dictName] of Object.entries(m.opt.dictFields ?? {})) {
|
|
616
|
+
if (!m.cols.includes(field) || dictEntries.has(dictName)) continue;
|
|
617
|
+
dictEntries.set(dictName, await vault.dictionary(dictName).list());
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
for (const entries of dictEntries.values()) {
|
|
621
|
+
for (const e of entries) for (const loc of Object.keys(e.labels)) localeSet.add(loc);
|
|
622
|
+
}
|
|
623
|
+
const locales = [...localeSet].sort();
|
|
624
|
+
const hasLang = locales.length > 0;
|
|
625
|
+
const defaultLocale = locales.includes("en") ? "en" : locales[0] ?? "en";
|
|
626
|
+
const ifChain = (refOf) => {
|
|
627
|
+
if (locales.length === 0) return '""';
|
|
628
|
+
let expr = refOf(locales[0]);
|
|
629
|
+
for (let k = locales.length - 1; k >= 0; k--) {
|
|
630
|
+
expr = `IF(LANG="${locales[k]}",${refOf(locales[k])},${expr})`;
|
|
631
|
+
}
|
|
632
|
+
return expr;
|
|
633
|
+
};
|
|
634
|
+
const sheetMeta = /* @__PURE__ */ new Map();
|
|
635
|
+
const dataSheets = mats.map((m) => {
|
|
636
|
+
const refs = snapshot.collections[m.opt.collection]?.refs ?? {};
|
|
637
|
+
const fields = snapshot.collections[m.opt.collection]?.fields ?? {};
|
|
638
|
+
const i18nSet = new Set(m.i18nFields);
|
|
639
|
+
const refFields = Object.keys(refs).filter((f) => m.cols.includes(f) && matByCollection.has(refs[f].target));
|
|
640
|
+
const baseCols = m.cols.filter((c) => !i18nSet.has(c));
|
|
641
|
+
const i18nFlat = m.i18nFields.flatMap((f) => [f, ...locales.map((l) => `${f}__${l}`)]);
|
|
642
|
+
const dictPairs = Object.entries(m.opt.dictFields ?? {}).filter(([f]) => m.cols.includes(f));
|
|
643
|
+
const header = [
|
|
644
|
+
...baseCols,
|
|
645
|
+
...i18nFlat,
|
|
646
|
+
...dictPairs.map(([f]) => `${f}__label`),
|
|
647
|
+
...refFields.map((f) => `${f}__label`)
|
|
648
|
+
];
|
|
649
|
+
const colIndex = /* @__PURE__ */ new Map();
|
|
650
|
+
header.forEach((h, i) => colIndex.set(h, i + 1));
|
|
651
|
+
sheetMeta.set(m.opt.collection, { name: m.opt.name, colIndex });
|
|
652
|
+
const lastRow = Math.max(m.records.length + 1, 2);
|
|
653
|
+
const validations = [];
|
|
654
|
+
for (const field of baseCols) {
|
|
655
|
+
const colL = colLetter(colIndex.get(field));
|
|
656
|
+
const sqref = `${colL}2:${colL}${lastRow}`;
|
|
657
|
+
const explicit = m.opt.dropdowns?.[field];
|
|
658
|
+
if (explicit && explicit.length > 0) {
|
|
659
|
+
validations.push({ sqref, values: explicit });
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
const rf = refs[field];
|
|
663
|
+
if (rf && matByCollection.has(rf.target)) {
|
|
664
|
+
const targetSheet = sheetNameByCollection.get(rf.target);
|
|
665
|
+
const targetRows = Math.max(matByCollection.get(rf.target).records.length + 1, 2);
|
|
666
|
+
validations.push({ sqref, formula1: `'${targetSheet}'!$A$2:$A$${targetRows}` });
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
const enumVals = fields[field]?.constraints?.["values"];
|
|
670
|
+
if (Array.isArray(enumVals) && enumVals.length > 0) validations.push({ sqref, values: enumVals.map((v) => safeStringify(v)) });
|
|
671
|
+
}
|
|
672
|
+
const rows = m.records.map((r, i) => {
|
|
673
|
+
const rowNum = i + 2;
|
|
674
|
+
const baseCells = baseCols.map((c) => {
|
|
675
|
+
const raw = c === "id" ? r.id ?? null : r[c] ?? null;
|
|
676
|
+
const fmt = m.opt.numberFormats?.[c];
|
|
677
|
+
if (fmt === void 0) return raw;
|
|
678
|
+
const num = typeof raw === "string" && raw.trim() !== "" && Number.isFinite(Number(raw)) ? Number(raw) : raw;
|
|
679
|
+
return styled(num, fmt);
|
|
680
|
+
});
|
|
681
|
+
const i18nCells = m.i18nFields.flatMap((f) => {
|
|
682
|
+
const rawMap = r[f] && typeof r[f] === "object" ? r[f] : {};
|
|
683
|
+
const display = formula(
|
|
684
|
+
ifChain((l) => `${colLetter(colIndex.get(`${f}__${l}`))}${rowNum}`),
|
|
685
|
+
asCached(rawMap[defaultLocale] ?? "")
|
|
686
|
+
);
|
|
687
|
+
return [display, ...locales.map((l) => rawMap[l] ?? null)];
|
|
688
|
+
});
|
|
689
|
+
const dictCells = dictPairs.map(([f, dn]) => {
|
|
690
|
+
const codeRef = `${colLetter(colIndex.get(f))}${rowNum}`;
|
|
691
|
+
const lk = `_Lookups_${dn}`;
|
|
692
|
+
const f1 = `IFERROR(VLOOKUP(${codeRef},'${lk}'!$A:$ZZ,MATCH(LANG,'${lk}'!$1:$1,0),FALSE),${codeRef})`;
|
|
693
|
+
const code = r[f];
|
|
694
|
+
const entry = code == null ? void 0 : dictEntries.get(dn)?.find((e) => e.key === safeStringify(code));
|
|
695
|
+
return formula(f1, asCached(entry?.labels[defaultLocale] ?? (code ?? "")));
|
|
696
|
+
});
|
|
697
|
+
const refCells = refFields.map((f) => {
|
|
698
|
+
const target = refs[f].target;
|
|
699
|
+
const targetSheet = sheetNameByCollection.get(target);
|
|
700
|
+
const targetMat = matByCollection.get(target);
|
|
701
|
+
const codeRef = `${colLetter(colIndex.get(f))}${rowNum}`;
|
|
702
|
+
const f1 = `IFERROR(VLOOKUP(${codeRef},'${targetSheet}'!$A:$ZZ,2,FALSE),"")`;
|
|
703
|
+
const code = r[f];
|
|
704
|
+
const cached = code == null ? "" : asCached(targetMat.labelMap.get(safeStringify(code)));
|
|
705
|
+
return formula(f1, cached);
|
|
706
|
+
});
|
|
707
|
+
return [...baseCells, ...i18nCells, ...dictCells, ...refCells];
|
|
708
|
+
});
|
|
709
|
+
return {
|
|
710
|
+
name: m.opt.name,
|
|
711
|
+
header,
|
|
712
|
+
rows,
|
|
713
|
+
...validations.length > 0 ? { validations } : {},
|
|
714
|
+
...m.opt.widths !== void 0 ? { widths: m.opt.widths } : {}
|
|
715
|
+
};
|
|
716
|
+
});
|
|
717
|
+
const manifest = {
|
|
718
|
+
name: "_manifest",
|
|
719
|
+
header: ["Collection", "Records", "Refs"],
|
|
720
|
+
rows: mats.map((m) => {
|
|
721
|
+
const refs = snapshot.collections[m.opt.collection]?.refs ?? {};
|
|
722
|
+
return [m.opt.name, m.records.length, Object.entries(refs).map(([f, r]) => `${f}\u2192${r.target}`).join(", ")];
|
|
723
|
+
})
|
|
724
|
+
};
|
|
725
|
+
const dialect = options.dialect ?? "excel";
|
|
726
|
+
const summarySheets = [];
|
|
727
|
+
for (const spec of options.summaries ?? []) {
|
|
728
|
+
const src = sheetMeta.get(spec.from);
|
|
729
|
+
const srcMat = matByCollection.get(spec.from);
|
|
730
|
+
const gCol = src?.colIndex.get(spec.groupBy);
|
|
731
|
+
if (!src || !srcMat || gCol === void 0) continue;
|
|
732
|
+
const gLetter = colLetter(gCol);
|
|
733
|
+
if (dialect === "sheets") {
|
|
734
|
+
const selects = [];
|
|
735
|
+
const labels = [];
|
|
736
|
+
for (const a of spec.aggregates) {
|
|
737
|
+
if (a.op === "count") {
|
|
738
|
+
selects.push(`COUNT(${gLetter})`);
|
|
739
|
+
labels.push(`COUNT(${gLetter}) '${a.label}'`);
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
742
|
+
const vIdx = a.field ? src.colIndex.get(a.field) : void 0;
|
|
743
|
+
if (vIdx === void 0) continue;
|
|
744
|
+
const vL = colLetter(vIdx);
|
|
745
|
+
const fn = a.op === "sum" ? "SUM" : "AVG";
|
|
746
|
+
selects.push(`${fn}(${vL})`);
|
|
747
|
+
labels.push(`${fn}(${vL}) '${a.label}'`);
|
|
748
|
+
}
|
|
749
|
+
const q = `QUERY('${src.name}'!A:ZZ, "SELECT ${gLetter}, ${selects.join(", ")} GROUP BY ${gLetter} LABEL ${labels.join(", ")}", 1)`;
|
|
750
|
+
summarySheets.push({ name: spec.name, rows: [[formula(q)]] });
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
const seen = /* @__PURE__ */ new Set();
|
|
754
|
+
const groups = [];
|
|
755
|
+
for (const r of srcMat.records) {
|
|
756
|
+
const k = safeStringify(r[spec.groupBy]);
|
|
757
|
+
if (!seen.has(k)) {
|
|
758
|
+
seen.add(k);
|
|
759
|
+
groups.push(r[spec.groupBy]);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
const header = [spec.groupBy, ...spec.aggregates.map((a) => a.label)];
|
|
763
|
+
const rows = groups.map((g, i) => {
|
|
764
|
+
const rowNum = i + 2;
|
|
765
|
+
const groupRecs = srcMat.records.filter((r) => safeStringify(r[spec.groupBy]) === safeStringify(g));
|
|
766
|
+
const cells = [g];
|
|
767
|
+
for (const a of spec.aggregates) {
|
|
768
|
+
if (a.op === "count") {
|
|
769
|
+
cells.push(formula(`COUNTIFS('${src.name}'!$${gLetter}:$${gLetter},$A${rowNum})`, groupRecs.length));
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
const vIdx = a.field ? src.colIndex.get(a.field) : void 0;
|
|
773
|
+
if (vIdx === void 0) {
|
|
774
|
+
cells.push(null);
|
|
775
|
+
continue;
|
|
776
|
+
}
|
|
777
|
+
const vLetter = colLetter(vIdx);
|
|
778
|
+
const nums = groupRecs.map((r) => Number(r[a.field])).filter((n) => Number.isFinite(n));
|
|
779
|
+
const sum = nums.reduce((s, n) => s + n, 0);
|
|
780
|
+
const cached = a.op === "sum" ? sum : nums.length ? sum / nums.length : 0;
|
|
781
|
+
const fn = a.op === "sum" ? "SUMIFS" : "AVERAGEIFS";
|
|
782
|
+
cells.push(
|
|
783
|
+
formula(`${fn}('${src.name}'!$${vLetter}:$${vLetter},'${src.name}'!$${gLetter}:$${gLetter},$A${rowNum})`, cached)
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
return cells;
|
|
787
|
+
});
|
|
788
|
+
summarySheets.push({ name: spec.name, header, rows });
|
|
789
|
+
}
|
|
790
|
+
const lookupSheets = [...dictEntries.entries()].map(([dn, entries]) => ({
|
|
791
|
+
name: `_Lookups_${dn}`,
|
|
792
|
+
header: ["Code", ...locales],
|
|
793
|
+
rows: entries.map((e) => [e.key, ...locales.map((l) => e.labels[l] ?? "")])
|
|
794
|
+
}));
|
|
795
|
+
const settingsSheets = [];
|
|
796
|
+
const definedNames = [];
|
|
797
|
+
if (hasLang) {
|
|
798
|
+
settingsSheets.push({
|
|
799
|
+
name: "_settings",
|
|
800
|
+
header: ["Setting", "Value"],
|
|
801
|
+
rows: [["Language", defaultLocale]],
|
|
802
|
+
validations: [{ sqref: "B2:B2", values: locales }]
|
|
803
|
+
});
|
|
804
|
+
definedNames.push({ name: "LANG", ref: `'_settings'!$B$2` });
|
|
805
|
+
}
|
|
806
|
+
return {
|
|
807
|
+
sheets: [...settingsSheets, ...lookupSheets, manifest, ...summarySheets, ...dataSheets],
|
|
808
|
+
definedNames
|
|
809
|
+
};
|
|
810
|
+
}
|
|
400
811
|
function inferColumns(records) {
|
|
401
812
|
const seen = /* @__PURE__ */ new Set();
|
|
402
813
|
const out = [];
|
|
@@ -468,6 +879,13 @@ async function fromBytes(vault, bytes, options) {
|
|
|
468
879
|
} catch {
|
|
469
880
|
}
|
|
470
881
|
}
|
|
882
|
+
const i18nBases = /* @__PURE__ */ new Set();
|
|
883
|
+
if (options.smart) {
|
|
884
|
+
for (const field of colToField.values()) {
|
|
885
|
+
const m = /^(.+)__(.+)$/.exec(field);
|
|
886
|
+
if (m && m[2] !== "label") i18nBases.add(m[1]);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
471
889
|
const records = [];
|
|
472
890
|
for (let i = headerRowIdx + 1; i < allRows.length; i++) {
|
|
473
891
|
const row = allRows[i];
|
|
@@ -476,6 +894,22 @@ async function fromBytes(vault, bytes, options) {
|
|
|
476
894
|
for (const [col, value] of Object.entries(row)) {
|
|
477
895
|
const field = colToField.get(col);
|
|
478
896
|
if (field === void 0) continue;
|
|
897
|
+
if (options.smart) {
|
|
898
|
+
if (field.endsWith("__label")) continue;
|
|
899
|
+
const lm = /^(.+)__(.+)$/.exec(field);
|
|
900
|
+
if (lm && lm[2] !== "label" && i18nBases.has(lm[1])) {
|
|
901
|
+
const base = lm[1];
|
|
902
|
+
const coerced2 = coerceXlsxCell(value, types[base]);
|
|
903
|
+
if (coerced2 !== void 0 && coerced2 !== "") {
|
|
904
|
+
const map = record[base] ?? {};
|
|
905
|
+
map[lm[2]] = coerced2;
|
|
906
|
+
record[base] = map;
|
|
907
|
+
hasAny = true;
|
|
908
|
+
}
|
|
909
|
+
continue;
|
|
910
|
+
}
|
|
911
|
+
if (i18nBases.has(field)) continue;
|
|
912
|
+
}
|
|
479
913
|
const coerced = coerceXlsxCell(value, types[field]);
|
|
480
914
|
if (coerced !== void 0) {
|
|
481
915
|
const invMap = invertMaps.get(field);
|
|
@@ -582,11 +1016,15 @@ export {
|
|
|
582
1016
|
XlsxDictAmbiguityError,
|
|
583
1017
|
colLetter,
|
|
584
1018
|
download,
|
|
1019
|
+
formula,
|
|
585
1020
|
fromBytes,
|
|
1021
|
+
inferSchema,
|
|
586
1022
|
readXlsx,
|
|
1023
|
+
styled,
|
|
587
1024
|
toBytes,
|
|
588
1025
|
toBytesFromCollection,
|
|
589
1026
|
write,
|
|
590
|
-
writeXlsx
|
|
1027
|
+
writeXlsx,
|
|
1028
|
+
zodSourceFor
|
|
591
1029
|
};
|
|
592
1030
|
//# sourceMappingURL=index.js.map
|