@svgrid/enterprise 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/dist/cdn/svgrid-enterprise.svelte-external.js +26039 -805
  2. package/dist/designer/assets/index-Dp44bTid.js +939 -0
  3. package/dist/designer/assets/index-RJp6x8tw.css +1 -0
  4. package/dist/designer/assets/jszip.min-CjMo-QGg.js +2 -0
  5. package/dist/designer/index.html +13 -0
  6. package/dist/node/studio.js +22554 -0
  7. package/package.json +10 -3
  8. package/src/SvAuthGate.svelte +115 -0
  9. package/src/SvBoard.dom.test.ts +67 -0
  10. package/src/SvBoard.svelte +192 -0
  11. package/src/SvExportMenu.svelte +553 -0
  12. package/src/SvFileInput.svelte +113 -0
  13. package/src/SvGridEditPanel.dom.test.ts +146 -0
  14. package/src/SvGridEditPanel.svelte +793 -0
  15. package/src/SvGridMasterDetail.svelte +95 -0
  16. package/src/SvImportDialog.svelte +1020 -0
  17. package/src/SvLookupInput.svelte +180 -0
  18. package/src/SvRecordDetail.dom.test.ts +137 -0
  19. package/src/SvRecordDetail.svelte +288 -0
  20. package/src/SvSchedule.dom.test.ts +57 -0
  21. package/src/SvSchedule.svelte +156 -0
  22. package/src/SvSchemaChart.svelte +233 -0
  23. package/src/SvSchemaDashboard.svelte +130 -0
  24. package/src/ai-export-pdf.test.ts +74 -0
  25. package/src/ai-export-xlsx.test.ts +87 -0
  26. package/src/ai-export.test.ts +110 -0
  27. package/src/ai.ts +1188 -782
  28. package/src/edit-panel.test.ts +213 -0
  29. package/src/edit-panel.ts +228 -0
  30. package/src/export-conditional.test.ts +60 -0
  31. package/src/export-conditional.ts +94 -0
  32. package/src/export-ooxml.test.ts +152 -0
  33. package/src/export-ooxml.ts +485 -0
  34. package/src/export-pdf.test.ts +138 -0
  35. package/src/export-pdf.ts +245 -0
  36. package/src/export-print.test.ts +66 -0
  37. package/src/export-print.ts +132 -0
  38. package/src/export-serialize.test.ts +56 -0
  39. package/src/export-serialize.ts +24 -0
  40. package/src/export-xls.ts +196 -0
  41. package/src/export-xlsx-roundtrip.test.ts +120 -0
  42. package/src/export-xlsx.test.ts +150 -0
  43. package/src/export.test.ts +349 -0
  44. package/src/export.ts +1452 -549
  45. package/src/import-automap.test.ts +131 -0
  46. package/src/import-hardening.test.ts +158 -0
  47. package/src/import.ts +1042 -648
  48. package/src/index.ts +282 -0
  49. package/src/install.ts +134 -114
  50. package/src/license-core.test.ts +23 -0
  51. package/src/license-core.ts +35 -0
  52. package/src/license.ts +103 -90
  53. package/src/master-detail.test.ts +61 -0
  54. package/src/master-detail.ts +42 -0
  55. package/src/print.ts +107 -127
  56. package/src/schema-designer.test.ts +121 -0
  57. package/src/schema-designer.ts +142 -0
  58. package/src/schema.test.ts +268 -0
  59. package/src/schema.ts +499 -0
  60. package/src/smart-shim.ts +107 -105
  61. package/src/sources/aggregate.test.ts +79 -0
  62. package/src/sources/aggregate.ts +102 -0
  63. package/src/sources/auth-supabase.test.ts +80 -0
  64. package/src/sources/auth-supabase.ts +87 -0
  65. package/src/sources/dashboard.kpi.test.ts +50 -0
  66. package/src/sources/dashboard.test.ts +61 -0
  67. package/src/sources/dashboard.ts +136 -0
  68. package/src/sources/field-inference.test.ts +60 -0
  69. package/src/sources/field-inference.ts +63 -0
  70. package/src/sources/filters.test.ts +58 -0
  71. package/src/sources/filters.ts +64 -0
  72. package/src/sources/index.ts +67 -0
  73. package/src/sources/introspect-supabase.test.ts +100 -0
  74. package/src/sources/introspect-supabase.ts +119 -0
  75. package/src/sources/realtime-supabase.test.ts +93 -0
  76. package/src/sources/realtime-supabase.ts +99 -0
  77. package/src/sources/relation-lookup.test.ts +99 -0
  78. package/src/sources/relation-lookup.ts +128 -0
  79. package/src/sources/rest-adapters.test.ts +95 -0
  80. package/src/sources/rest-adapters.ts +120 -0
  81. package/src/sources/rest.test.ts +104 -0
  82. package/src/sources/rest.ts +129 -0
  83. package/src/sources/schema-from-columns.test.ts +106 -0
  84. package/src/sources/schema-from-columns.ts +88 -0
  85. package/src/sources/supabase.test.ts +110 -0
  86. package/src/sources/supabase.ts +99 -0
  87. package/src/sources/with-entity-rules.test.ts +104 -0
  88. package/src/sources/with-entity-rules.ts +78 -0
  89. package/src/sources/with-relation-labels.test.ts +75 -0
  90. package/src/sources/with-relation-labels.ts +73 -0
  91. package/src/studio/bug-report.test.ts +101 -0
  92. package/src/studio/bug-report.ts +165 -0
  93. package/src/studio/cli.test.ts +187 -0
  94. package/src/studio/cli.ts +112 -0
  95. package/src/studio/csv.test.ts +90 -0
  96. package/src/studio/csv.ts +165 -0
  97. package/src/studio/db-connect-string.test.ts +94 -0
  98. package/src/studio/db-connect-string.ts +128 -0
  99. package/src/studio/emit-project.test.ts +923 -0
  100. package/src/studio/emit-project.ts +1273 -0
  101. package/src/studio/emit-schema.test.ts +94 -0
  102. package/src/studio/emit-schema.ts +920 -0
  103. package/src/studio/index.ts +195 -0
  104. package/src/studio/introspect-db.test.ts +186 -0
  105. package/src/studio/introspect-db.ts +312 -0
  106. package/src/studio/introspect-prisma.test.ts +99 -0
  107. package/src/studio/introspect-prisma.ts +175 -0
  108. package/src/studio/introspect.test.ts +172 -0
  109. package/src/studio/introspect.ts +310 -0
  110. package/src/studio/pipeline.test.ts +42 -0
  111. package/src/studio/project-robust.test.ts +157 -0
  112. package/src/studio/project.test.ts +473 -0
  113. package/src/studio/project.ts +916 -0
  114. package/src/studio/sample-data.test.ts +58 -0
  115. package/src/studio/sample-data.ts +200 -0
  116. package/src/studio/samples/ats.ts +202 -0
  117. package/src/studio/samples/clinic.ts +177 -0
  118. package/src/studio/samples/crm.ts +250 -0
  119. package/src/studio/samples/ecommerce.ts +187 -0
  120. package/src/studio/samples/events.ts +199 -0
  121. package/src/studio/samples/fleet.ts +184 -0
  122. package/src/studio/samples/gym.ts +213 -0
  123. package/src/studio/samples/hr.ts +193 -0
  124. package/src/studio/samples/index.ts +55 -0
  125. package/src/studio/samples/insurance.ts +195 -0
  126. package/src/studio/samples/inventory.ts +182 -0
  127. package/src/studio/samples/invoicing.ts +162 -0
  128. package/src/studio/samples/library.ts +180 -0
  129. package/src/studio/samples/live-data.test.ts +98 -0
  130. package/src/studio/samples/live-data.ts +308 -0
  131. package/src/studio/samples/projects.ts +190 -0
  132. package/src/studio/samples/realestate.ts +196 -0
  133. package/src/studio/samples/restaurant.ts +187 -0
  134. package/src/studio/samples/samples.test.ts +208 -0
  135. package/src/studio/samples/school.ts +197 -0
  136. package/src/studio/samples/seed-floor.test.ts +25 -0
  137. package/src/studio/samples/shared.ts +305 -0
  138. package/src/studio/samples/subscriptions.ts +183 -0
  139. package/src/studio/samples/support.ts +182 -0
  140. package/src/studio/scaffold-app.test.ts +91 -0
  141. package/src/studio/scaffold-app.ts +161 -0
  142. package/src/studio/scaffold.test.ts +178 -0
  143. package/src/studio/scaffold.ts +374 -0
  144. package/src/studio/themes.ts +172 -0
  145. package/src/studio/verify.test.ts +47 -0
  146. package/src/studio/verify.ts +79 -0
  147. package/src/sveltekit/in-memory.test.ts +104 -0
  148. package/src/sveltekit/in-memory.ts +129 -0
  149. package/src/sveltekit/index.ts +23 -0
  150. package/src/sveltekit/query-plan.test.ts +109 -0
  151. package/src/sveltekit/query-plan.ts +125 -0
  152. package/src/sveltekit/sql-source.test.ts +185 -0
  153. package/src/sveltekit/sql-source.ts +166 -0
  154. package/src/sveltekit/sql.test.ts +80 -0
  155. package/src/sveltekit/sql.ts +131 -0
  156. package/src/sveltekit/transport.test.ts +175 -0
  157. package/src/sveltekit/transport.ts +254 -0
  158. package/src/sveltekit/types.ts +11 -0
  159. package/src/upgrade-prompt.ts +149 -148
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Legacy `.xls` export via the Excel 2003 XML Spreadsheet format
3
+ * (SpreadsheetML, `urn:schemas-microsoft-com:office:spreadsheet`). This is the
4
+ * "old compatibility" path: it opens natively in Excel 97-2003 and every
5
+ * newer Excel / LibreOffice / Numbers as a REAL spreadsheet - typed numeric
6
+ * and date cells (so sums/sort still work) with number formats - and needs no
7
+ * peer dependency (unlike xlsx, which needs jszip).
8
+ *
9
+ * We generate typed cells from the column `format`: number / currency /
10
+ * percent become `ss:Type="Number"` with a NumberFormat style, dates become
11
+ * `ss:Type="DateTime"`, everything else is a formatted `String`. An
12
+ * `exportValue` hook still wins and is emitted as a String.
13
+ */
14
+ import { formatValueForExport, toExcelNumFmt, valueForExcel } from '@svgrid/grid/format'
15
+ import type { ExportColumn } from './export'
16
+ import type { RowData } from '@svgrid/grid'
17
+ import type { SerializeOptions } from './export-serialize'
18
+
19
+ // Control chars illegal in XML 1.0 - strip so a stray \x00 can't corrupt the file.
20
+ const INVALID_XML = /[\x00-\x08\x0B\x0C\x0E-\x1F]/g
21
+ function xmlEscape(s: string): string {
22
+ return s
23
+ .replace(INVALID_XML, '')
24
+ .replace(/&/g, '&')
25
+ .replace(/</g, '&lt;')
26
+ .replace(/>/g, '&gt;')
27
+ .replace(/"/g, '&quot;')
28
+ }
29
+
30
+ /** A worksheet cell reduced to what SpreadsheetML needs. */
31
+ type XlsCell = { type: 'Number' | 'DateTime' | 'String'; value: string; styleId?: string; href?: string }
32
+
33
+ /** SpreadsheetML wants ISO-8601 with no timezone for a DateTime cell. */
34
+ function toSpreadsheetDate(d: Date): string {
35
+ // yyyy-mm-ddThh:mm:ss.000
36
+ const p = (n: number, w = 2) => String(n).padStart(w, '0')
37
+ return (
38
+ `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}` +
39
+ `T${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}.000`
40
+ )
41
+ }
42
+
43
+ /**
44
+ * Serialize rows to an Excel 2003 XML Spreadsheet (`.xls`) document string.
45
+ * Streams in chunks with `onProgress` + `AbortSignal`, matching the other
46
+ * native writers.
47
+ */
48
+ export async function serializeSpreadsheetML<TData extends RowData>(
49
+ sheetName: string,
50
+ cols: ReadonlyArray<ExportColumn<TData>>,
51
+ rows: ReadonlyArray<TData>,
52
+ opts: SerializeOptions & {
53
+ rawValues?: boolean
54
+ /** Freeze the header row. Default false. */
55
+ freezeHeader?: boolean
56
+ /** Freeze this many leading columns. Default 0. */
57
+ freezeColumns?: number
58
+ /** Per-column pixel widths (converted to points). */
59
+ widths?: ReadonlyArray<number>
60
+ /** Per-cell conditional-format visual (fill / color / bold / icon). */
61
+ cellVisual?: (rowIdx: number, colIdx: number) => { fill?: string; color?: string; bold?: boolean; icon?: string } | undefined
62
+ /** Write long integer IDs (>15 sig digits) as text so they survive. */
63
+ precisionSafe?: boolean
64
+ } = {},
65
+ ): Promise<string> {
66
+ const chunk = Math.max(1, opts.chunkRows ?? 5000)
67
+ const total = rows.length
68
+ const rawValues = opts.rawValues === true
69
+ const cellVisual = opts.cellVisual
70
+ const precisionSafe = opts.precisionSafe === true
71
+
72
+ // Build a style table. Each distinct combination of (numFmt, fill, color,
73
+ // bold, align) becomes one <Style>, referenced from cells via ss:StyleID.
74
+ type StyleDesc = {
75
+ numFmt?: string
76
+ fill?: string
77
+ color?: string
78
+ bold?: boolean
79
+ align?: 'left' | 'center' | 'right'
80
+ }
81
+ const styleCache = new Map<string, string>()
82
+ const styleDefs: string[] = [
83
+ '<Style ss:ID="sHeader"><Font ss:Bold="1"/><Interior ss:Color="#F2F2F2" ss:Pattern="Solid"/></Style>',
84
+ ]
85
+ const cap = (a: 'left' | 'center' | 'right') => (a === 'right' ? 'Right' : a === 'center' ? 'Center' : 'Left')
86
+ const styleIdFor = (d: StyleDesc): string | undefined => {
87
+ const hasAlign = d.align && d.align !== 'left'
88
+ if (!d.numFmt && !d.fill && !d.color && !d.bold && !hasAlign) return undefined
89
+ const key = `${d.numFmt ?? ''}|${d.fill ?? ''}|${d.color ?? ''}|${d.bold ? 'b' : ''}|${d.align ?? ''}`
90
+ const existing = styleCache.get(key)
91
+ if (existing) return existing
92
+ const id = `s${styleCache.size + 1}`
93
+ // SpreadsheetML element order: Alignment, Font, Interior, NumberFormat.
94
+ const parts: string[] = []
95
+ if (hasAlign) parts.push(`<Alignment ss:Horizontal="${cap(d.align!)}"/>`)
96
+ if (d.color || d.bold) parts.push(`<Font${d.color ? ` ss:Color="${d.color}"` : ''}${d.bold ? ' ss:Bold="1"' : ''}/>`)
97
+ if (d.fill) parts.push(`<Interior ss:Color="${d.fill}" ss:Pattern="Solid"/>`)
98
+ if (d.numFmt) parts.push(`<NumberFormat ss:Format="${xmlEscape(d.numFmt)}"/>`)
99
+ styleDefs.push(`<Style ss:ID="${id}">${parts.join('')}</Style>`)
100
+ styleCache.set(key, id)
101
+ return id
102
+ }
103
+
104
+ function cellFor(col: ExportColumn<TData>, row: TData, r: number, c: number): XlsCell {
105
+ const href = col.link?.(row) || undefined
106
+ const v = cellVisual?.(r, c)
107
+ const style = (numFmt?: string) =>
108
+ styleIdFor({ numFmt, fill: v?.fill, color: v?.color, bold: v?.bold, align: col.align })
109
+
110
+ if (col.exportValue) {
111
+ const ev = col.exportValue(row)
112
+ const text = ev == null ? '' : String(ev)
113
+ return { type: 'String', value: v?.icon ? `${v.icon} ${text}` : text, styleId: style(), href }
114
+ }
115
+ const raw = (row as unknown as Record<string, unknown>)[col.field]
116
+ // An icon-set glyph forces a string cell (icon + formatted value).
117
+ if (v?.icon) {
118
+ const disp = rawValues ? String(raw ?? '') : formatValueForExport(raw, col.format)
119
+ return { type: 'String', value: `${v.icon} ${disp}`, styleId: style(), href }
120
+ }
121
+ const unsafe = (n: number) => precisionSafe && Math.abs(n) >= 1e15
122
+ if (rawValues) {
123
+ const s = raw == null ? '' : String(raw)
124
+ const asNum = typeof raw === 'number' && Number.isFinite(raw) && !unsafe(raw)
125
+ return asNum
126
+ ? { type: 'Number', value: s, styleId: style(), href }
127
+ : { type: 'String', value: s, styleId: style(), href }
128
+ }
129
+ const typed = valueForExcel(raw, col.format)
130
+ if (typed.ok) {
131
+ const numFmt = toExcelNumFmt(col.format)
132
+ if (typed.value instanceof Date) {
133
+ return { type: 'DateTime', value: toSpreadsheetDate(typed.value), styleId: style(numFmt), href }
134
+ }
135
+ if (unsafe(typed.value)) return { type: 'String', value: String(typed.value), styleId: style(), href }
136
+ return { type: 'Number', value: String(typed.value), styleId: style(numFmt), href }
137
+ }
138
+ return { type: 'String', value: formatValueForExport(raw, col.format), styleId: style(), href }
139
+ }
140
+
141
+ const cellXml = (c: XlsCell): string => {
142
+ const style = c.styleId ? ` ss:StyleID="${c.styleId}"` : ''
143
+ const href = c.href ? ` ss:HRef="${xmlEscape(c.href)}"` : ''
144
+ return `<Cell${style}${href}><Data ss:Type="${c.type}">${xmlEscape(c.value)}</Data></Cell>`
145
+ }
146
+
147
+ // <Column> width elements (SpreadsheetML width is in points; ~0.75pt/px).
148
+ const columnXml = opts.widths
149
+ ? opts.widths.map((px) => `<Column ss:Width="${Math.round(px * 0.75)}"/>`).join('')
150
+ : ''
151
+
152
+ // Freeze panes: header row and/or leading columns.
153
+ const freezeCols = Math.max(0, Math.floor(opts.freezeColumns ?? 0))
154
+ const worksheetOptions =
155
+ opts.freezeHeader || freezeCols > 0
156
+ ? '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">' +
157
+ '<FreezePanes/><FrozenNoSplit/>' +
158
+ (opts.freezeHeader ? '<SplitHorizontal>1</SplitHorizontal><TopRowBottomPane>1</TopRowBottomPane>' : '') +
159
+ (freezeCols > 0 ? `<SplitVertical>${freezeCols}</SplitVertical><LeftColumnRightPane>${freezeCols}</LeftColumnRightPane>` : '') +
160
+ '<ActivePane>2</ActivePane></WorksheetOptions>'
161
+ : ''
162
+
163
+ // Header row (bold style).
164
+ const headerCells = cols
165
+ .map((c) => `<Cell ss:StyleID="sHeader"><Data ss:Type="String">${xmlEscape(c.header ?? c.field)}</Data></Cell>`)
166
+ .join('')
167
+ const bodyRows: string[] = [`<Row>${headerCells}</Row>`]
168
+
169
+ for (let i = 0; i < total; i++) {
170
+ if (opts.signal?.aborted) throw new DOMException('Export aborted', 'AbortError')
171
+ const row = rows[i]!
172
+ const cells = cols.map((c, ci) => cellXml(cellFor(c, row, i, ci))).join('')
173
+ bodyRows.push(`<Row>${cells}</Row>`)
174
+ if (i > 0 && i % chunk === 0) {
175
+ opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
176
+ await new Promise((resolve) => setTimeout(resolve, 0))
177
+ }
178
+ }
179
+ opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
180
+
181
+ return (
182
+ '<?xml version="1.0"?>\n' +
183
+ '<?mso-application progid="Excel.Sheet"?>\n' +
184
+ '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"' +
185
+ ' xmlns:o="urn:schemas-microsoft-com:office:office"' +
186
+ ' xmlns:x="urn:schemas-microsoft-com:office:excel"' +
187
+ ' xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"' +
188
+ ' xmlns:html="http://www.w3.org/TR/REC-html40">' +
189
+ `<Styles>${styleDefs.join('')}</Styles>` +
190
+ `<Worksheet ss:Name="${xmlEscape(sheetName.slice(0, 31) || 'Sheet1')}">` +
191
+ `<Table>${columnXml}${bodyRows.join('')}</Table>` +
192
+ worksheetOptions +
193
+ '</Worksheet>' +
194
+ '</Workbook>'
195
+ )
196
+ }
@@ -0,0 +1,120 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import JSZip from 'jszip'
3
+ import { buildXlsxParts, packageXlsx, type XlsxCell } from './export-ooxml'
4
+
5
+ // A real round-trip: build parts -> zip with the REAL jszip -> unzip -> assert
6
+ // every part survives byte-for-byte AND each XML part is well-formed. This is
7
+ // the safety net the string-matching tests can't give: if the hand-written
8
+ // OOXML is malformed or the package is broken, this fails before Excel does.
9
+
10
+ /** True when jsdom's DOMParser accepts `xml` as well-formed. */
11
+ function isWellFormed(xml: string): boolean {
12
+ const doc = new DOMParser().parseFromString(xml, 'application/xml')
13
+ // jsdom emits a <parsererror> element (in the docElement) for invalid XML.
14
+ return doc.getElementsByTagName('parsererror').length === 0
15
+ }
16
+
17
+ const model = {
18
+ sheetName: 'Report 2026',
19
+ header: ['Company', 'Price', 'When', 'Ratio', 'Note'],
20
+ rows: [
21
+ [
22
+ { t: 's', value: 'ACME & Co <"x">' },
23
+ { t: 'n', value: 19.95, numFmt: '"$"#,##0.00', align: 'right', fill: '#fee2e2', color: '#991b1b', bold: true },
24
+ { t: 'd', value: new Date('2026-03-04T00:00:00Z'), numFmt: 'yyyy-mm-dd' },
25
+ { t: 'n', value: 0.42, numFmt: '0.00%' },
26
+ { t: 's', value: 'ok', link: 'https://x.test/a?b=1&c=2' },
27
+ ],
28
+ [
29
+ { t: 's', value: 'Globex' },
30
+ { t: 'n', value: -1000 },
31
+ { t: 'd', value: new Date('2026-06-01T00:00:00Z'), numFmt: 'yyyy-mm-dd' },
32
+ { t: 'n', value: 0 },
33
+ { t: 's', value: '' },
34
+ ],
35
+ ] as XlsxCell[][],
36
+ widths: [160, 90, 110, 80, 120],
37
+ freezeHeader: true,
38
+ freezeColumns: 1,
39
+ condFormats: [
40
+ { kind: 'dataBar' as const, colIdx: 1, color: '#3b82f6' },
41
+ { kind: 'colorScale' as const, colIdx: 3, colors: ['#dcfce7', '#fef9c3', '#fee2e2'] },
42
+ ],
43
+ }
44
+
45
+ describe('xlsx round-trip (real jszip + XML validation)', () => {
46
+ it('packages, unzips, and every part survives + is well-formed XML', async () => {
47
+ const parts = buildXlsxParts(model)
48
+ const blob = await packageXlsx(parts, JSZip)
49
+ expect(blob).toBeInstanceOf(Blob)
50
+ expect(blob.size).toBeGreaterThan(0)
51
+
52
+ const zip = await JSZip.loadAsync(await blob.arrayBuffer())
53
+
54
+ for (const [path, expected] of Object.entries(parts)) {
55
+ const entry = zip.file(path)
56
+ expect(entry, `missing entry ${path}`).toBeTruthy()
57
+ const content = await entry!.async('string')
58
+ expect(content, `mismatch for ${path}`).toBe(expected) // byte-for-byte survive
59
+ if (path.endsWith('.xml') || path.endsWith('.rels')) {
60
+ expect(isWellFormed(content), `malformed XML in ${path}`).toBe(true)
61
+ }
62
+ }
63
+ })
64
+
65
+ it('the worksheet re-parses into the expected structure', async () => {
66
+ const parts = buildXlsxParts(model)
67
+ const zip = await JSZip.loadAsync(await (await packageXlsx(parts, JSZip)).arrayBuffer())
68
+ const sheetXml = await zip.file('xl/worksheets/sheet1.xml')!.async('string')
69
+ const doc = new DOMParser().parseFromString(sheetXml, 'application/xml')
70
+
71
+ // header + 2 data rows
72
+ expect(doc.getElementsByTagName('row')).toHaveLength(3)
73
+ // freeze pane present
74
+ expect(doc.getElementsByTagName('pane')).toHaveLength(1)
75
+ // two native conditional-formatting rules
76
+ expect(doc.getElementsByTagName('conditionalFormatting')).toHaveLength(2)
77
+ // the hyperlink survived with a rel id
78
+ expect(doc.getElementsByTagName('hyperlink')).toHaveLength(1)
79
+ // special chars were escaped, not corrupting the XML
80
+ expect(sheetXml).toContain('ACME &amp; Co &lt;&quot;x&quot;&gt;')
81
+ })
82
+
83
+ it('an Excel Table (with totals row) packages + re-parses as valid XML', async () => {
84
+ const parts = buildXlsxParts({
85
+ ...model,
86
+ table: { name: 'Table1', totalsRow: true, totalsFns: [undefined, 'sum', undefined, 'sum', undefined] },
87
+ })
88
+ const zip = await JSZip.loadAsync(await (await packageXlsx(parts, JSZip)).arrayBuffer())
89
+
90
+ const tableXml = await zip.file('xl/tables/table1.xml')!.async('string')
91
+ expect(isWellFormed(tableXml)).toBe(true)
92
+ const tdoc = new DOMParser().parseFromString(tableXml, 'application/xml')
93
+ expect(tdoc.getElementsByTagName('tableColumn')).toHaveLength(5)
94
+ expect(tableXml).toContain('totalsRowCount="1"')
95
+
96
+ const sheetXml = await zip.file('xl/worksheets/sheet1.xml')!.async('string')
97
+ expect(isWellFormed(sheetXml)).toBe(true)
98
+ // header + 2 data rows + totals row = 4 rows
99
+ expect(new DOMParser().parseFromString(sheetXml, 'application/xml').getElementsByTagName('row')).toHaveLength(4)
100
+ expect(sheetXml).toContain('SUBTOTAL(109,Table1[Price])')
101
+
102
+ // Content types + sheet rels reference the table part.
103
+ expect(await zip.file('[Content_Types].xml')!.async('string')).toContain('spreadsheetml.table+xml')
104
+ expect(isWellFormed(await zip.file('xl/worksheets/_rels/sheet1.xml.rels')!.async('string'))).toBe(true)
105
+ })
106
+
107
+ it('workbook + styles re-parse and reference the sheet', async () => {
108
+ const parts = buildXlsxParts(model)
109
+ const zip = await JSZip.loadAsync(await (await packageXlsx(parts, JSZip)).arrayBuffer())
110
+ const wb = new DOMParser().parseFromString(await zip.file('xl/workbook.xml')!.async('string'), 'application/xml')
111
+ expect(wb.getElementsByTagName('sheet')).toHaveLength(1)
112
+ expect(wb.getElementsByTagName('sheet')[0]!.getAttribute('name')).toBe('Report 2026')
113
+
114
+ const styles = await zip.file('xl/styles.xml')!.async('string')
115
+ expect(isWellFormed(styles)).toBe(true)
116
+ // fills index 0 (none) + 1 (gray125) are required to precede customs
117
+ expect(styles).toContain('patternType="none"')
118
+ expect(styles).toContain('patternType="gray125"')
119
+ })
120
+ })
@@ -0,0 +1,150 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
2
+
3
+ // Plain xlsx now goes through our native OOXML writer. Capture the parts a
4
+ // fake JSZip receives (instead of building a real .xlsx / touching the DOM).
5
+ const captured: { parts: Record<string, string> } = { parts: {} }
6
+ vi.mock('jszip', () => ({
7
+ default: class {
8
+ file(path: string, data: string) {
9
+ captured.parts[path] = data
10
+ }
11
+ async generateAsync() {
12
+ return new Blob([])
13
+ }
14
+ },
15
+ }))
16
+ vi.mock('./export-serialize', async (importOriginal) => {
17
+ const actual = (await importOriginal()) as Record<string, unknown>
18
+ return { ...actual, downloadBlobFile: () => {} }
19
+ })
20
+
21
+ import { exportGrid } from './export'
22
+ import { setLicenseKey } from './license'
23
+
24
+ type Row = { name: string; price: number; when: string; ratio: number }
25
+ const rows: Row[] = [
26
+ { name: 'ACME', price: 19.95, when: '2026-03-04', ratio: 42 },
27
+ { name: 'Globex', price: 1000, when: '2026-06-01', ratio: 8 },
28
+ ]
29
+
30
+ function makeApi() {
31
+ const columns = [
32
+ { id: 'name', field: 'name', header: 'Company', visible: true },
33
+ { id: 'price', field: 'price', header: 'Price', visible: true, format: { type: 'currency', currency: 'USD' } },
34
+ { id: 'when', field: 'when', header: 'Date', visible: true, format: { type: 'date', pattern: 'y-m-d' } },
35
+ { id: 'ratio', field: 'ratio', header: 'Ratio', visible: true, format: { type: 'percent', valueIsPercentPoints: true } },
36
+ ]
37
+ return {
38
+ getDisplayedRows: () => rows,
39
+ getSelectedRows: () => [],
40
+ getData: () => rows,
41
+ getColumns: () => columns,
42
+ getState: () => ({ grouping: [] }),
43
+ getColumnPinning: () => ({ left: [], right: [] }),
44
+ } as any
45
+ }
46
+
47
+ beforeEach(() => {
48
+ captured.parts = {}
49
+ setLicenseKey('SVENTERPRISE-DEV-TEST')
50
+ })
51
+
52
+ describe('native xlsx export', () => {
53
+ it('writes typed numbers/dates with number formats, freeze, and widths', async () => {
54
+ await exportGrid(makeApi(), { format: 'xlsx', filename: 'orders' })
55
+ const sheet = captured.parts['xl/worksheets/sheet1.xml']!
56
+ const styles = captured.parts['xl/styles.xml']!
57
+ expect(sheet).toContain('<v>19.95</v>') // real number, not "$19.95" text
58
+ expect(sheet).toMatch(/<v>0\.42<\/v>|<v>0.42<\/v>/) // percent points -> fraction
59
+ expect(styles).toContain('formatCode="&quot;$&quot;#,##0.00"') // currency numFmt
60
+ expect(styles).toContain('0.00%') // percent numFmt
61
+ expect(sheet).toContain('state="frozen"') // freeze header
62
+ expect(sheet).toContain('<cols>') // auto-fit widths
63
+ })
64
+
65
+ it('carries a predicate rule as a real per-cell fill', async () => {
66
+ await exportGrid(makeApi(), {
67
+ format: 'xlsx',
68
+ conditionalFormats: [
69
+ { type: 'rule', columns: ['price'], when: ({ value }) => Number(value) >= 1000, background: '#fee2e2' },
70
+ ],
71
+ })
72
+ // The CF fill lands in styles.xml (Smart could never do this).
73
+ expect(captured.parts['xl/styles.xml']).toContain('fgColor rgb="FFFEE2E2"')
74
+ })
75
+
76
+ it('turns data bars / color scales into native Excel conditional formatting', async () => {
77
+ await exportGrid(makeApi(), {
78
+ format: 'xlsx',
79
+ conditionalFormats: [
80
+ { type: 'dataBar', columns: ['price'], color: '#3b82f6' },
81
+ { type: 'colorScale', columns: ['ratio'], min: '#dcfce7', max: '#fee2e2' },
82
+ ],
83
+ })
84
+ const sheet = captured.parts['xl/worksheets/sheet1.xml']!
85
+ expect(sheet).toContain('type="dataBar"')
86
+ expect(sheet).toContain('type="colorScale"')
87
+ // Excel computes these, so there are NO per-cell CF fills baked into styles.
88
+ expect(captured.parts['xl/styles.xml']).not.toContain('patternType="solid"')
89
+ })
90
+
91
+ it('rawValues:true writes plain numbers without number formats', async () => {
92
+ await exportGrid(makeApi(), { format: 'xlsx', rawValues: true })
93
+ const sheet = captured.parts['xl/worksheets/sheet1.xml']!
94
+ expect(sheet).toContain('<v>42</v>') // raw ratio, not 0.42
95
+ expect(captured.parts['xl/styles.xml']).not.toContain('0.00%')
96
+ })
97
+
98
+ it('renders cell hyperlinks from a column link hook', async () => {
99
+ await exportGrid(makeApi(), {
100
+ format: 'xlsx',
101
+ columns: [{ field: 'name', header: 'Company', link: (r: Row) => `https://x.test/${r.name}` }],
102
+ })
103
+ expect(captured.parts['xl/worksheets/sheet1.xml']).toContain('<hyperlinks>')
104
+ expect(captured.parts['xl/worksheets/_rels/sheet1.xml.rels']).toContain('Target="https://x.test/ACME"')
105
+ })
106
+
107
+ it('auto-freezes from the grid pinned columns', async () => {
108
+ const api = makeApi()
109
+ api.getColumnPinning = () => ({ left: ['name'], right: [] })
110
+ await exportGrid(api, { format: 'xlsx' })
111
+ expect(captured.parts['xl/worksheets/sheet1.xml']).toContain('xSplit="1"')
112
+ })
113
+
114
+ it('precisionSafe writes long integer IDs as text (not a rounded number)', async () => {
115
+ const big = 1234567890123456 // 16 digits: > 1e15 but exactly representable
116
+ const api = {
117
+ getDisplayedRows: () => [{ id: big, name: 'A' }],
118
+ getSelectedRows: () => [],
119
+ getData: () => [{ id: big, name: 'A' }],
120
+ getColumns: () => [
121
+ { id: 'id', field: 'id', header: 'ID', visible: true, format: { type: 'number', options: { maximumFractionDigits: 0, useGrouping: false } } },
122
+ { id: 'name', field: 'name', header: 'Name', visible: true },
123
+ ],
124
+ getState: () => ({ grouping: [] }),
125
+ getColumnPinning: () => ({ left: [], right: [] }),
126
+ } as any
127
+ await exportGrid(api, { format: 'xlsx', precisionSafe: true })
128
+ const sheet = captured.parts['xl/worksheets/sheet1.xml']!
129
+ expect(sheet).toContain('t="inlineStr"><is><t xml:space="preserve">1234567890123456')
130
+ expect(sheet).not.toContain('<v>1234567890123456</v>')
131
+ // without precisionSafe it stays a real number
132
+ captured.parts = {}
133
+ await exportGrid(api, { format: 'xlsx' })
134
+ expect(captured.parts['xl/worksheets/sheet1.xml']).toContain('<v>1234567890123456</v>')
135
+ })
136
+
137
+ it('wraps the data in an Excel Table with a totals row + SUM formula', async () => {
138
+ await exportGrid(makeApi(), { format: 'xlsx', excelTable: { totalsRow: true } })
139
+ const table = captured.parts['xl/tables/table1.xml']!
140
+ expect(table).toContain('<table ')
141
+ expect(table).toContain('totalsRowCount="1"')
142
+ expect(table).toContain('<autoFilter')
143
+ expect(table).toContain('totalsRowFunction="sum"') // numeric columns
144
+ const sheet = captured.parts['xl/worksheets/sheet1.xml']!
145
+ expect(sheet).toContain('<tableParts')
146
+ expect(sheet).toContain('SUBTOTAL(109,Table1[Price])')
147
+ expect(captured.parts['xl/worksheets/_rels/sheet1.xml.rels']).toContain('/relationships/table')
148
+ expect(captured.parts['[Content_Types].xml']).toContain('spreadsheetml.table+xml')
149
+ })
150
+ })