@noy-db/as-xlsx 0.2.0-pre.3 → 0.2.0-pre.31

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.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
- async function writeXlsx(sheets) {
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>", "</worksheet>");
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,339 @@ async function write(vault, path, options) {
397
564
  const { writeFile } = await import("fs/promises");
398
565
  await writeFile(path, bytes);
399
566
  }
567
+ async function toBytesMultiVault(entries, options = {}) {
568
+ const sep = options.sheetSeparator ?? "_";
569
+ for (const entry of entries) {
570
+ entry.vault.assertCanExport("plaintext", "xlsx");
571
+ }
572
+ const loaded = [];
573
+ const denormIndex = /* @__PURE__ */ new Map();
574
+ for (const entry of entries) {
575
+ const prefix = entry.label ?? entry.vault.name;
576
+ for (const s of entry.sheets) {
577
+ const all = await entry.vault.collection(s.collection).list();
578
+ const records = [];
579
+ for (const item of all) {
580
+ const r = item;
581
+ const allow = entry.closure?.get(s.collection);
582
+ if (allow && !allow.has(String(r.id))) continue;
583
+ if (s.filter && !s.filter(r)) continue;
584
+ records.push(r);
585
+ }
586
+ loaded.push({ entry, prefix, sheetOpt: s, records });
587
+ const indexKey = `${prefix}/${s.collection}`;
588
+ const collectionIndex = denormIndex.get(indexKey) ?? /* @__PURE__ */ new Map();
589
+ denormIndex.set(indexKey, collectionIndex);
590
+ for (const r of records) {
591
+ const idVal = r.id;
592
+ if (idVal != null) collectionIndex.set(safeStringify(idVal), r);
593
+ }
594
+ }
595
+ }
596
+ for (const ls of loaded) {
597
+ for (const d of ls.sheetOpt.denormalize ?? []) {
598
+ if (d.from.keyField === "id") continue;
599
+ const indexKey = `${d.from.label}/${d.from.collection}`;
600
+ const idx = denormIndex.get(indexKey);
601
+ if (!idx) continue;
602
+ const srcLoaded = loaded.find(
603
+ (l) => l.prefix === d.from.label && l.sheetOpt.collection === d.from.collection
604
+ );
605
+ if (!srcLoaded) continue;
606
+ for (const r of srcLoaded.records) {
607
+ const kv = r[d.from.keyField];
608
+ if (kv != null) idx.set(safeStringify(kv), r);
609
+ }
610
+ }
611
+ }
612
+ const allSheets = [];
613
+ const manifestRows = [];
614
+ for (const { prefix, sheetOpt: s, records } of loaded) {
615
+ const baseColumns = s.columns ?? inferColumns(records);
616
+ const denormDefs = s.denormalize ?? [];
617
+ if (denormDefs.length === 0) {
618
+ const sheetName2 = `${prefix}${sep}${s.name}`;
619
+ allSheets.push(buildFlatSheet(sheetName2, baseColumns, records));
620
+ manifestRows.push([prefix, s.collection, records.length]);
621
+ continue;
622
+ }
623
+ const allColumns = [...baseColumns, ...denormDefs.map((d) => d.column)];
624
+ const sheetName = `${prefix}${sep}${s.name}`;
625
+ const rows = records.map((r) => {
626
+ const baseCells = baseColumns.map((c) => r[c] ?? null);
627
+ const denormCells = denormDefs.map((d) => {
628
+ const idxKey = `${d.from.label}/${d.from.collection}`;
629
+ const idx = denormIndex.get(idxKey);
630
+ if (!idx) return "";
631
+ const fkVal = r[d.localField];
632
+ if (fkVal == null) return "";
633
+ const supporting = idx.get(safeStringify(fkVal));
634
+ if (!supporting) return "";
635
+ return supporting[d.from.pick] ?? "";
636
+ });
637
+ return [...baseCells, ...denormCells];
638
+ });
639
+ allSheets.push({ name: sheetName, header: allColumns, rows });
640
+ manifestRows.push([prefix, s.collection, records.length]);
641
+ }
642
+ allSheets.unshift({
643
+ name: "_manifest",
644
+ header: ["Vault", "Collection", "Records"],
645
+ rows: manifestRows
646
+ });
647
+ return writeXlsx(allSheets);
648
+ }
649
+ function buildFlatSheet(name, columns, records) {
650
+ return {
651
+ name,
652
+ header: [...columns],
653
+ rows: records.map((r) => columns.map((c) => r[c] ?? null))
654
+ };
655
+ }
656
+ function safeStringify(v) {
657
+ if (typeof v === "string") return v;
658
+ if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint") return String(v);
659
+ if (v == null) return "";
660
+ try {
661
+ return JSON.stringify(v) ?? "";
662
+ } catch {
663
+ return "";
664
+ }
665
+ }
666
+ function asCached(v) {
667
+ if (typeof v === "number" || typeof v === "boolean" || typeof v === "string") return v;
668
+ return safeStringify(v);
669
+ }
670
+ async function buildSmartSheets(vault, options) {
671
+ const snapshot = await vault.dumpSchema();
672
+ const sheetNameByCollection = /* @__PURE__ */ new Map();
673
+ for (const s of options.sheets) sheetNameByCollection.set(s.collection, s.name);
674
+ const mats = [];
675
+ const localeSet = /* @__PURE__ */ new Set();
676
+ for (const sheetOpt of options.sheets) {
677
+ const collection = vault.collection(sheetOpt.collection);
678
+ const list = await collection.list();
679
+ const records = [];
680
+ for (const item of list) {
681
+ const r = item;
682
+ if (sheetOpt.filter && !sheetOpt.filter(r)) continue;
683
+ records.push(r);
684
+ }
685
+ const base = sheetOpt.columns ?? inferColumns(records);
686
+ const cols = ["id", ...base.filter((c) => c !== "id")];
687
+ const labelCol = cols.find((c) => c !== "id");
688
+ const labelMap = /* @__PURE__ */ new Map();
689
+ if (labelCol) {
690
+ for (const r of records) if (r.id != null) labelMap.set(safeStringify(r.id), r[labelCol]);
691
+ }
692
+ const i18nFields = (sheetOpt.i18nFields ?? []).filter((f) => cols.includes(f));
693
+ for (const f of i18nFields) {
694
+ for (const r of records) {
695
+ const v = r[f];
696
+ if (v && typeof v === "object") for (const loc of Object.keys(v)) localeSet.add(loc);
697
+ }
698
+ }
699
+ mats.push({ opt: sheetOpt, records, cols, labelMap, i18nFields });
700
+ }
701
+ const matByCollection = new Map(mats.map((m) => [m.opt.collection, m]));
702
+ const dictEntries = /* @__PURE__ */ new Map();
703
+ for (const m of mats) {
704
+ for (const [field, dictName] of Object.entries(m.opt.dictFields ?? {})) {
705
+ if (!m.cols.includes(field) || dictEntries.has(dictName)) continue;
706
+ dictEntries.set(dictName, await vault.dictionary(dictName).list());
707
+ }
708
+ }
709
+ for (const entries of dictEntries.values()) {
710
+ for (const e of entries) for (const loc of Object.keys(e.labels)) localeSet.add(loc);
711
+ }
712
+ const locales = [...localeSet].sort();
713
+ const hasLang = locales.length > 0;
714
+ const defaultLocale = locales.includes("en") ? "en" : locales[0] ?? "en";
715
+ const ifChain = (refOf) => {
716
+ if (locales.length === 0) return '""';
717
+ let expr = refOf(locales[0]);
718
+ for (let k = locales.length - 1; k >= 0; k--) {
719
+ expr = `IF(LANG="${locales[k]}",${refOf(locales[k])},${expr})`;
720
+ }
721
+ return expr;
722
+ };
723
+ const sheetMeta = /* @__PURE__ */ new Map();
724
+ const dataSheets = mats.map((m) => {
725
+ const refs = snapshot.collections[m.opt.collection]?.refs ?? {};
726
+ const fields = snapshot.collections[m.opt.collection]?.fields ?? {};
727
+ const i18nSet = new Set(m.i18nFields);
728
+ const refFields = Object.keys(refs).filter((f) => m.cols.includes(f) && matByCollection.has(refs[f].target));
729
+ const baseCols = m.cols.filter((c) => !i18nSet.has(c));
730
+ const i18nFlat = m.i18nFields.flatMap((f) => [f, ...locales.map((l) => `${f}__${l}`)]);
731
+ const dictPairs = Object.entries(m.opt.dictFields ?? {}).filter(([f]) => m.cols.includes(f));
732
+ const header = [
733
+ ...baseCols,
734
+ ...i18nFlat,
735
+ ...dictPairs.map(([f]) => `${f}__label`),
736
+ ...refFields.map((f) => `${f}__label`)
737
+ ];
738
+ const colIndex = /* @__PURE__ */ new Map();
739
+ header.forEach((h, i) => colIndex.set(h, i + 1));
740
+ sheetMeta.set(m.opt.collection, { name: m.opt.name, colIndex });
741
+ const lastRow = Math.max(m.records.length + 1, 2);
742
+ const validations = [];
743
+ for (const field of baseCols) {
744
+ const colL = colLetter(colIndex.get(field));
745
+ const sqref = `${colL}2:${colL}${lastRow}`;
746
+ const explicit = m.opt.dropdowns?.[field];
747
+ if (explicit && explicit.length > 0) {
748
+ validations.push({ sqref, values: explicit });
749
+ continue;
750
+ }
751
+ const rf = refs[field];
752
+ if (rf && matByCollection.has(rf.target)) {
753
+ const targetSheet = sheetNameByCollection.get(rf.target);
754
+ const targetRows = Math.max(matByCollection.get(rf.target).records.length + 1, 2);
755
+ validations.push({ sqref, formula1: `'${targetSheet}'!$A$2:$A$${targetRows}` });
756
+ continue;
757
+ }
758
+ const enumVals = fields[field]?.constraints?.["values"];
759
+ if (Array.isArray(enumVals) && enumVals.length > 0) validations.push({ sqref, values: enumVals.map((v) => safeStringify(v)) });
760
+ }
761
+ const rows = m.records.map((r, i) => {
762
+ const rowNum = i + 2;
763
+ const baseCells = baseCols.map((c) => {
764
+ const raw = c === "id" ? r.id ?? null : r[c] ?? null;
765
+ const fmt = m.opt.numberFormats?.[c];
766
+ if (fmt === void 0) return raw;
767
+ const num = typeof raw === "string" && raw.trim() !== "" && Number.isFinite(Number(raw)) ? Number(raw) : raw;
768
+ return styled(num, fmt);
769
+ });
770
+ const i18nCells = m.i18nFields.flatMap((f) => {
771
+ const rawMap = r[f] && typeof r[f] === "object" ? r[f] : {};
772
+ const display = formula(
773
+ ifChain((l) => `${colLetter(colIndex.get(`${f}__${l}`))}${rowNum}`),
774
+ asCached(rawMap[defaultLocale] ?? "")
775
+ );
776
+ return [display, ...locales.map((l) => rawMap[l] ?? null)];
777
+ });
778
+ const dictCells = dictPairs.map(([f, dn]) => {
779
+ const codeRef = `${colLetter(colIndex.get(f))}${rowNum}`;
780
+ const lk = `_Lookups_${dn}`;
781
+ const f1 = `IFERROR(VLOOKUP(${codeRef},'${lk}'!$A:$ZZ,MATCH(LANG,'${lk}'!$1:$1,0),FALSE),${codeRef})`;
782
+ const code = r[f];
783
+ const entry = code == null ? void 0 : dictEntries.get(dn)?.find((e) => e.key === safeStringify(code));
784
+ return formula(f1, asCached(entry?.labels[defaultLocale] ?? (code ?? "")));
785
+ });
786
+ const refCells = refFields.map((f) => {
787
+ const target = refs[f].target;
788
+ const targetSheet = sheetNameByCollection.get(target);
789
+ const targetMat = matByCollection.get(target);
790
+ const codeRef = `${colLetter(colIndex.get(f))}${rowNum}`;
791
+ const f1 = `IFERROR(VLOOKUP(${codeRef},'${targetSheet}'!$A:$ZZ,2,FALSE),"")`;
792
+ const code = r[f];
793
+ const cached = code == null ? "" : asCached(targetMat.labelMap.get(safeStringify(code)));
794
+ return formula(f1, cached);
795
+ });
796
+ return [...baseCells, ...i18nCells, ...dictCells, ...refCells];
797
+ });
798
+ return {
799
+ name: m.opt.name,
800
+ header,
801
+ rows,
802
+ ...validations.length > 0 ? { validations } : {},
803
+ ...m.opt.widths !== void 0 ? { widths: m.opt.widths } : {}
804
+ };
805
+ });
806
+ const manifest = {
807
+ name: "_manifest",
808
+ header: ["Collection", "Records", "Refs"],
809
+ rows: mats.map((m) => {
810
+ const refs = snapshot.collections[m.opt.collection]?.refs ?? {};
811
+ return [m.opt.name, m.records.length, Object.entries(refs).map(([f, r]) => `${f}\u2192${r.target}`).join(", ")];
812
+ })
813
+ };
814
+ const dialect = options.dialect ?? "excel";
815
+ const summarySheets = [];
816
+ for (const spec of options.summaries ?? []) {
817
+ const src = sheetMeta.get(spec.from);
818
+ const srcMat = matByCollection.get(spec.from);
819
+ const gCol = src?.colIndex.get(spec.groupBy);
820
+ if (!src || !srcMat || gCol === void 0) continue;
821
+ const gLetter = colLetter(gCol);
822
+ if (dialect === "sheets") {
823
+ const selects = [];
824
+ const labels = [];
825
+ for (const a of spec.aggregates) {
826
+ if (a.op === "count") {
827
+ selects.push(`COUNT(${gLetter})`);
828
+ labels.push(`COUNT(${gLetter}) '${a.label}'`);
829
+ continue;
830
+ }
831
+ const vIdx = a.field ? src.colIndex.get(a.field) : void 0;
832
+ if (vIdx === void 0) continue;
833
+ const vL = colLetter(vIdx);
834
+ const fn = a.op === "sum" ? "SUM" : "AVG";
835
+ selects.push(`${fn}(${vL})`);
836
+ labels.push(`${fn}(${vL}) '${a.label}'`);
837
+ }
838
+ const q = `QUERY('${src.name}'!A:ZZ, "SELECT ${gLetter}, ${selects.join(", ")} GROUP BY ${gLetter} LABEL ${labels.join(", ")}", 1)`;
839
+ summarySheets.push({ name: spec.name, rows: [[formula(q)]] });
840
+ continue;
841
+ }
842
+ const seen = /* @__PURE__ */ new Set();
843
+ const groups = [];
844
+ for (const r of srcMat.records) {
845
+ const k = safeStringify(r[spec.groupBy]);
846
+ if (!seen.has(k)) {
847
+ seen.add(k);
848
+ groups.push(r[spec.groupBy]);
849
+ }
850
+ }
851
+ const header = [spec.groupBy, ...spec.aggregates.map((a) => a.label)];
852
+ const rows = groups.map((g, i) => {
853
+ const rowNum = i + 2;
854
+ const groupRecs = srcMat.records.filter((r) => safeStringify(r[spec.groupBy]) === safeStringify(g));
855
+ const cells = [g];
856
+ for (const a of spec.aggregates) {
857
+ if (a.op === "count") {
858
+ cells.push(formula(`COUNTIFS('${src.name}'!$${gLetter}:$${gLetter},$A${rowNum})`, groupRecs.length));
859
+ continue;
860
+ }
861
+ const vIdx = a.field ? src.colIndex.get(a.field) : void 0;
862
+ if (vIdx === void 0) {
863
+ cells.push(null);
864
+ continue;
865
+ }
866
+ const vLetter = colLetter(vIdx);
867
+ const nums = groupRecs.map((r) => Number(r[a.field])).filter((n) => Number.isFinite(n));
868
+ const sum = nums.reduce((s, n) => s + n, 0);
869
+ const cached = a.op === "sum" ? sum : nums.length ? sum / nums.length : 0;
870
+ const fn = a.op === "sum" ? "SUMIFS" : "AVERAGEIFS";
871
+ cells.push(
872
+ formula(`${fn}('${src.name}'!$${vLetter}:$${vLetter},'${src.name}'!$${gLetter}:$${gLetter},$A${rowNum})`, cached)
873
+ );
874
+ }
875
+ return cells;
876
+ });
877
+ summarySheets.push({ name: spec.name, header, rows });
878
+ }
879
+ const lookupSheets = [...dictEntries.entries()].map(([dn, entries]) => ({
880
+ name: `_Lookups_${dn}`,
881
+ header: ["Code", ...locales],
882
+ rows: entries.map((e) => [e.key, ...locales.map((l) => e.labels[l] ?? "")])
883
+ }));
884
+ const settingsSheets = [];
885
+ const definedNames = [];
886
+ if (hasLang) {
887
+ settingsSheets.push({
888
+ name: "_settings",
889
+ header: ["Setting", "Value"],
890
+ rows: [["Language", defaultLocale]],
891
+ validations: [{ sqref: "B2:B2", values: locales }]
892
+ });
893
+ definedNames.push({ name: "LANG", ref: `'_settings'!$B$2` });
894
+ }
895
+ return {
896
+ sheets: [...settingsSheets, ...lookupSheets, manifest, ...summarySheets, ...dataSheets],
897
+ definedNames
898
+ };
899
+ }
400
900
  function inferColumns(records) {
401
901
  const seen = /* @__PURE__ */ new Set();
402
902
  const out = [];
@@ -468,6 +968,13 @@ async function fromBytes(vault, bytes, options) {
468
968
  } catch {
469
969
  }
470
970
  }
971
+ const i18nBases = /* @__PURE__ */ new Set();
972
+ if (options.smart) {
973
+ for (const field of colToField.values()) {
974
+ const m = /^(.+)__(.+)$/.exec(field);
975
+ if (m && m[2] !== "label") i18nBases.add(m[1]);
976
+ }
977
+ }
471
978
  const records = [];
472
979
  for (let i = headerRowIdx + 1; i < allRows.length; i++) {
473
980
  const row = allRows[i];
@@ -476,6 +983,22 @@ async function fromBytes(vault, bytes, options) {
476
983
  for (const [col, value] of Object.entries(row)) {
477
984
  const field = colToField.get(col);
478
985
  if (field === void 0) continue;
986
+ if (options.smart) {
987
+ if (field.endsWith("__label")) continue;
988
+ const lm = /^(.+)__(.+)$/.exec(field);
989
+ if (lm && lm[2] !== "label" && i18nBases.has(lm[1])) {
990
+ const base = lm[1];
991
+ const coerced2 = coerceXlsxCell(value, types[base]);
992
+ if (coerced2 !== void 0 && coerced2 !== "") {
993
+ const map = record[base] ?? {};
994
+ map[lm[2]] = coerced2;
995
+ record[base] = map;
996
+ hasAny = true;
997
+ }
998
+ continue;
999
+ }
1000
+ if (i18nBases.has(field)) continue;
1001
+ }
479
1002
  const coerced = coerceXlsxCell(value, types[field]);
480
1003
  if (coerced !== void 0) {
481
1004
  const invMap = invertMaps.get(field);
@@ -582,11 +1105,16 @@ export {
582
1105
  XlsxDictAmbiguityError,
583
1106
  colLetter,
584
1107
  download,
1108
+ formula,
585
1109
  fromBytes,
1110
+ inferSchema,
586
1111
  readXlsx,
1112
+ styled,
587
1113
  toBytes,
588
1114
  toBytesFromCollection,
1115
+ toBytesMultiVault,
589
1116
  write,
590
- writeXlsx
1117
+ writeXlsx,
1118
+ zodSourceFor
591
1119
  };
592
1120
  //# sourceMappingURL=index.js.map