@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,152 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { buildXlsxParts, colName, type XlsxCell } from './export-ooxml'
3
+
4
+ const model = {
5
+ sheetName: 'Orders',
6
+ header: ['Company', 'Price', 'When'],
7
+ rows: [
8
+ [
9
+ { t: 's', value: 'ACME' },
10
+ { t: 'n', value: 19.95, numFmt: '"$"#,##0.00', align: 'right', fill: '#fee2e2', color: '#991b1b', bold: true },
11
+ { t: 'd', value: new Date('2026-03-04T00:00:00Z'), numFmt: 'yyyy-mm-dd' },
12
+ ],
13
+ [
14
+ { t: 's', value: 'Globex', link: 'https://x.test/globex' },
15
+ { t: 'n', value: 1000 },
16
+ { t: 'd', value: new Date('2026-06-01T00:00:00Z') },
17
+ ],
18
+ ] as XlsxCell[][],
19
+ widths: [140, 90, 110],
20
+ freezeHeader: true,
21
+ }
22
+
23
+ const parts = buildXlsxParts(model)
24
+
25
+ describe('buildXlsxParts', () => {
26
+ it('emits all required package parts', () => {
27
+ for (const p of [
28
+ '[Content_Types].xml',
29
+ '_rels/.rels',
30
+ 'xl/workbook.xml',
31
+ 'xl/_rels/workbook.xml.rels',
32
+ 'xl/styles.xml',
33
+ 'xl/worksheets/sheet1.xml',
34
+ ]) {
35
+ expect(parts[p]).toBeTruthy()
36
+ }
37
+ expect(parts['xl/workbook.xml']).toContain('name="Orders"')
38
+ })
39
+
40
+ it('writes typed number, date-serial, and string cells', () => {
41
+ const s = parts['xl/worksheets/sheet1.xml']!
42
+ expect(s).toContain('<v>19.95</v>')
43
+ expect(s).toContain('<v>1000</v>')
44
+ expect(s).toMatch(/<v>46\d{3}<\/v>/) // 2026 date serial (~46085)
45
+ expect(s).toContain('t="inlineStr"') // header + string cells
46
+ })
47
+
48
+ it('registers numFmt + fill + bold-colored font in styles.xml', () => {
49
+ const st = parts['xl/styles.xml']!
50
+ expect(st).toContain('formatCode="&quot;$&quot;#,##0.00"')
51
+ expect(st).toContain('fgColor rgb="FFFEE2E2"') // CF fill
52
+ expect(st).toContain('<color rgb="FF991B1B"/>') // CF font color
53
+ expect(st).toContain('<b/>') // header + CF bold
54
+ })
55
+
56
+ it('freezes the header row and sets column widths', () => {
57
+ const s = parts['xl/worksheets/sheet1.xml']!
58
+ expect(s).toContain('state="frozen"')
59
+ expect(s).toContain('ySplit="1"')
60
+ expect(s).toContain('<cols>')
61
+ expect(s).toContain('customWidth="1"')
62
+ })
63
+
64
+ it('emits hyperlinks + a sheet rels part', () => {
65
+ const s = parts['xl/worksheets/sheet1.xml']!
66
+ expect(s).toContain('<hyperlinks>')
67
+ expect(s).toContain('<hyperlink ref="A3"') // Globex is row 3
68
+ expect(parts['xl/worksheets/_rels/sheet1.xml.rels']).toContain('Target="https://x.test/globex"')
69
+ })
70
+
71
+ it('produces no <hyperlinks> / rels when no cell has a link', () => {
72
+ const p = buildXlsxParts({ sheetName: 'S', header: ['A'], rows: [[{ t: 's', value: 'x' }]] })
73
+ expect(p['xl/worksheets/sheet1.xml']).not.toContain('<hyperlinks>')
74
+ expect(p['xl/worksheets/_rels/sheet1.xml.rels']).toBeUndefined()
75
+ })
76
+ })
77
+
78
+ describe('buildXlsxParts - edge cases', () => {
79
+ it('preserves 0 and negative numbers; blanks null / empty', () => {
80
+ const p = buildXlsxParts({
81
+ sheetName: 'S',
82
+ header: ['A', 'B', 'C', 'D'],
83
+ rows: [[{ t: 'n', value: 0 }, { t: 'n', value: -12.5 }, { t: 's', value: '' }, { t: 'n', value: null }]],
84
+ })
85
+ const s = p['xl/worksheets/sheet1.xml']!
86
+ expect(s).toContain('<v>0</v>')
87
+ expect(s).toContain('<v>-12.5</v>')
88
+ // empty string + null render as truly empty cells (no <v>/<is>)
89
+ expect(s).toMatch(/<c r="C2"[^>]*\/>/)
90
+ expect(s).toMatch(/<c r="D2"[^>]*\/>/)
91
+ })
92
+
93
+ it('strips illegal XML control characters', () => {
94
+ const p = buildXlsxParts({
95
+ sheetName: 'S',
96
+ header: ['A'],
97
+ rows: [[{ t: 's', value: `a${String.fromCharCode(0)}b${String.fromCharCode(7)}c` }]],
98
+ })
99
+ expect(p['xl/worksheets/sheet1.xml']).toContain('<t xml:space="preserve">abc</t>')
100
+ })
101
+
102
+ it('sanitizes an invalid sheet name', () => {
103
+ const p = buildXlsxParts({ sheetName: 'a/b:c*[d]', header: ['A'], rows: [[{ t: 's', value: 'x' }]] })
104
+ expect(p['xl/workbook.xml']).toContain('name="a b c d"') // invalid chars -> spaces, trimmed
105
+ expect(p['xl/workbook.xml']).not.toMatch(/name="[^"]*[/:*[\]][^"]*"/)
106
+ })
107
+ })
108
+
109
+ describe('buildXlsxParts - native conditional formatting', () => {
110
+ it('emits data bar + 3-stop color scale rules over the column range', () => {
111
+ const p = buildXlsxParts({
112
+ sheetName: 'S',
113
+ header: ['A', 'B'],
114
+ rows: [
115
+ [{ t: 'n', value: 1 }, { t: 'n', value: 2 }],
116
+ [{ t: 'n', value: 4 }, { t: 'n', value: 5 }],
117
+ ],
118
+ condFormats: [
119
+ { kind: 'dataBar', colIdx: 0, color: '#3b82f6' },
120
+ { kind: 'colorScale', colIdx: 1, colors: ['#dcfce7', '#fef9c3', '#fee2e2'] },
121
+ ],
122
+ })
123
+ const s = p['xl/worksheets/sheet1.xml']!
124
+ expect(s).toContain('<conditionalFormatting sqref="A2:A3">')
125
+ expect(s).toContain('type="dataBar"')
126
+ expect(s).toContain('<color rgb="FF3B82F6"/>')
127
+ expect(s).toContain('<conditionalFormatting sqref="B2:B3">')
128
+ expect(s).toContain('type="colorScale"')
129
+ expect(s).toContain('type="percentile" val="50"') // the mid stop
130
+ // conditionalFormatting must precede any hyperlinks in the worksheet
131
+ expect(s.indexOf('conditionalFormatting')).toBeGreaterThan(s.indexOf('</sheetData>'))
132
+ })
133
+
134
+ it('omits conditional formatting when there are no data rows', () => {
135
+ const p = buildXlsxParts({
136
+ sheetName: 'S',
137
+ header: ['A'],
138
+ rows: [],
139
+ condFormats: [{ kind: 'dataBar', colIdx: 0, color: '#3b82f6' }],
140
+ })
141
+ expect(p['xl/worksheets/sheet1.xml']).not.toContain('conditionalFormatting')
142
+ })
143
+ })
144
+
145
+ describe('colName', () => {
146
+ it('maps 0-based indices to Excel letters', () => {
147
+ expect(colName(0)).toBe('A')
148
+ expect(colName(25)).toBe('Z')
149
+ expect(colName(26)).toBe('AA')
150
+ expect(colName(27)).toBe('AB')
151
+ })
152
+ })
@@ -0,0 +1,485 @@
1
+ /**
2
+ * Native OOXML (.xlsx) writer. The vendored Smart exporter only applies uniform
3
+ * header/row styles - it ignores per-cell styles, and can't do color scales /
4
+ * data bars - so conditional-formatting colors never reached Excel. This writer
5
+ * builds a real xlsx workbook from scratch (styles.xml + sheet.xml, zipped with
6
+ * jszip) so we get, together, in one file:
7
+ * - typed number / date cells with a number format (Excel sums + sorts them),
8
+ * - true PER-CELL fills / font color / bold (conditional formatting),
9
+ * - a frozen header (and optional frozen columns),
10
+ * - auto-fit / explicit column widths,
11
+ * - real cell hyperlinks.
12
+ *
13
+ * It's split into a pure `buildXlsxParts` (returns the XML parts - fully unit
14
+ * testable) and `packageXlsx` (zips them into a Blob via a provided JSZip).
15
+ */
16
+
17
+ /** One worksheet cell, already resolved by the caller. */
18
+ export type XlsxCell = {
19
+ /** 'n' number, 'd' date, 's' string, 'b' boolean. */
20
+ t: 'n' | 'd' | 's' | 'b'
21
+ value: number | string | boolean | Date | null | undefined
22
+ /** Excel number-format code (for 'n' / 'd'). */
23
+ numFmt?: string
24
+ align?: 'left' | 'center' | 'right'
25
+ /** Background fill hex (e.g. '#fee2e2'). */
26
+ fill?: string
27
+ /** Font color hex. */
28
+ color?: string
29
+ bold?: boolean
30
+ /** Hyperlink URL. */
31
+ link?: string
32
+ }
33
+
34
+ /**
35
+ * A native Excel Table (ListObject) over the data: filter dropdowns, banded
36
+ * rows, structured references, and (optionally) a totals row with SUBTOTAL
37
+ * formulas per numeric column.
38
+ */
39
+ export type XlsxTableSpec = {
40
+ /** Table name (no spaces; must start with a letter). E.g. 'Table1'. */
41
+ name: string
42
+ /** Add a totals row. */
43
+ totalsRow: boolean
44
+ /** Table style id (default 'TableStyleMedium2'). */
45
+ style?: string
46
+ /** Per-column totals function, aligned with `header`. */
47
+ totalsFns: ReadonlyArray<'sum' | 'average' | 'count' | undefined>
48
+ }
49
+
50
+ /**
51
+ * Native Excel conditional formatting over a whole column's data range - a
52
+ * data bar or a 2/3-stop color scale. Unlike per-cell fills, Excel computes
53
+ * these itself (and recomputes when the user edits), so they're interactive
54
+ * and higher fidelity.
55
+ */
56
+ export type XlsxCondFormat =
57
+ | { kind: 'dataBar'; colIdx: number; color: string }
58
+ | { kind: 'colorScale'; colIdx: number; colors: ReadonlyArray<string> }
59
+
60
+ export type XlsxModel = {
61
+ sheetName: string
62
+ /** Header labels (row 1). */
63
+ header: ReadonlyArray<string>
64
+ /** Data rows (each an array of cells, column-aligned with `header`). */
65
+ rows: ReadonlyArray<ReadonlyArray<XlsxCell>>
66
+ /** Per-column widths in pixels (optional). */
67
+ widths?: ReadonlyArray<number>
68
+ /** Freeze the header row. */
69
+ freezeHeader?: boolean
70
+ /** Freeze this many leading columns. */
71
+ freezeColumns?: number
72
+ /** Native column conditional formatting (data bars / color scales). */
73
+ condFormats?: ReadonlyArray<XlsxCondFormat>
74
+ /** Wrap the data in a native Excel Table. */
75
+ table?: XlsxTableSpec
76
+ }
77
+
78
+ const XML_ESCAPE: Record<string, string> = {
79
+ '&': '&amp;',
80
+ '<': '&lt;',
81
+ '>': '&gt;',
82
+ '"': '&quot;',
83
+ "'": '&apos;',
84
+ }
85
+ // Control chars that are illegal in XML 1.0 (would make Excel reject the file).
86
+ const INVALID_XML = /[\x00-\x08\x0B\x0C\x0E-\x1F]/g
87
+ function esc(s: string): string {
88
+ return s.replace(INVALID_XML, '').replace(/[&<>"']/g, (c) => XML_ESCAPE[c]!)
89
+ }
90
+
91
+ /** 0-based column index -> Excel letter (0 -> A, 26 -> AA). */
92
+ export function colName(index: number): string {
93
+ let n = index
94
+ let s = ''
95
+ do {
96
+ s = String.fromCharCode(65 + (n % 26)) + s
97
+ n = Math.floor(n / 26) - 1
98
+ } while (n >= 0)
99
+ return s
100
+ }
101
+
102
+ /** '#rrggbb' -> 'FFRRGGBB' (ARGB) for OOXML; null when unparseable. */
103
+ function argb(hex: string | undefined): string | null {
104
+ if (!hex) return null
105
+ const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim())
106
+ return m ? 'FF' + m[1]!.toUpperCase() : null
107
+ }
108
+
109
+ /** Excel serial date (days since 1899-12-30), UTC-based. */
110
+ function toSerialDate(d: Date): number {
111
+ const epoch = Date.UTC(1899, 11, 30)
112
+ return (d.getTime() - epoch) / 86_400_000
113
+ }
114
+
115
+ // Static package parts that never change.
116
+ const CONTENT_TYPES =
117
+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
118
+ `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
119
+ `<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
120
+ `<Default Extension="xml" ContentType="application/xml"/>` +
121
+ `<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>` +
122
+ `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>` +
123
+ `<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>` +
124
+ `</Types>`
125
+
126
+ const ROOT_RELS =
127
+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
128
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
129
+ `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>` +
130
+ `</Relationships>`
131
+
132
+ /** Excel forbids \ / ? * [ ] : in a sheet name and caps it at 31 chars. */
133
+ function safeSheetName(name: string): string {
134
+ return name.replace(/[\\/?*[\]:]/g, ' ').trim().slice(0, 31) || 'Sheet1'
135
+ }
136
+
137
+ function workbookXml(sheetName: string): string {
138
+ return (
139
+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
140
+ `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ` +
141
+ `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">` +
142
+ `<sheets><sheet name="${esc(safeSheetName(sheetName))}" sheetId="1" r:id="rId1"/></sheets>` +
143
+ `</workbook>`
144
+ )
145
+ }
146
+
147
+ const WORKBOOK_RELS =
148
+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
149
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
150
+ `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>` +
151
+ `<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
152
+ `</Relationships>`
153
+
154
+ /**
155
+ * Build a style registry from the cell styles used, and return `styles.xml`
156
+ * plus a `styleIndexOf(cell)` that maps each cell to its `s=` index.
157
+ */
158
+ function buildStyles(header: ReadonlyArray<string>, rows: ReadonlyArray<ReadonlyArray<XlsxCell>>) {
159
+ // numFmts (custom codes start at 164), fonts, fills, and cellXfs are deduped.
160
+ const numFmts = new Map<string, number>() // code -> id
161
+ let nextNumFmtId = 164
162
+ const numFmtIdOf = (code: string | undefined): number => {
163
+ if (!code) return 0
164
+ const existing = numFmts.get(code)
165
+ if (existing != null) return existing
166
+ const id = nextNumFmtId++
167
+ numFmts.set(code, id)
168
+ return id
169
+ }
170
+
171
+ // Font 0 = default. Header font (bold) is font 1.
172
+ const fonts: string[] = ['<font><sz val="11"/><name val="Calibri"/></font>', '<font><b/><sz val="11"/><name val="Calibri"/></font>']
173
+ const fontKey = new Map<string, number>()
174
+ const fontIdOf = (bold: boolean, color: string | undefined): number => {
175
+ const c = argb(color)
176
+ if (!bold && !c) return 0
177
+ const key = `${bold ? 'b' : ''}|${c ?? ''}`
178
+ const existing = fontKey.get(key)
179
+ if (existing != null) return existing
180
+ const id = fonts.length
181
+ fonts.push(`<font>${bold ? '<b/>' : ''}<sz val="11"/><name val="Calibri"/>${c ? `<color rgb="${c}"/>` : ''}</font>`)
182
+ fontKey.set(key, id)
183
+ return id
184
+ }
185
+
186
+ // Fill 0 = none, fill 1 = gray125 (Excel requires both first).
187
+ const fills: string[] = ['<fill><patternFill patternType="none"/></fill>', '<fill><patternFill patternType="gray125"/></fill>']
188
+ const fillKey = new Map<string, number>()
189
+ const fillIdOf = (bg: string | undefined): number => {
190
+ const c = argb(bg)
191
+ if (!c) return 0
192
+ const existing = fillKey.get(c)
193
+ if (existing != null) return existing
194
+ const id = fills.length
195
+ fills.push(`<fill><patternFill patternType="solid"><fgColor rgb="${c}"/><bgColor indexed="64"/></patternFill></fill>`)
196
+ fillKey.set(c, id)
197
+ return id
198
+ }
199
+
200
+ // cellXfs: xf 0 = default. Header xf (bold) is 1.
201
+ const xfs: string[] = ['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>', '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>']
202
+ const xfKey = new Map<string, number>()
203
+ const xfIdOf = (numFmtId: number, fontId: number, fillId: number, align: XlsxCell['align']): number => {
204
+ const key = `${numFmtId}|${fontId}|${fillId}|${align ?? ''}`
205
+ const existing = xfKey.get(key)
206
+ if (existing != null) return existing
207
+ const id = xfs.length
208
+ const alignXml = align && align !== 'left' ? `<alignment horizontal="${align}"/>` : ''
209
+ xfs.push(
210
+ `<xf numFmtId="${numFmtId}" fontId="${fontId}" fillId="${fillId}" borderId="0" xfId="0"` +
211
+ `${numFmtId ? ' applyNumberFormat="1"' : ''}${fontId ? ' applyFont="1"' : ''}` +
212
+ `${fillId ? ' applyFill="1"' : ''}${alignXml ? ' applyAlignment="1"' : ''}>${alignXml}</xf>`,
213
+ )
214
+ xfKey.set(key, id)
215
+ return id
216
+ }
217
+
218
+ const styleIndexOf = (cell: XlsxCell): number => {
219
+ const numFmtId = numFmtIdOf(cell.numFmt)
220
+ const fontId = fontIdOf(cell.bold === true, cell.color)
221
+ const fillId = fillIdOf(cell.fill)
222
+ if (numFmtId === 0 && fontId === 0 && fillId === 0 && (!cell.align || cell.align === 'left')) return 0
223
+ return xfIdOf(numFmtId, fontId, fillId, cell.align)
224
+ }
225
+
226
+ // Pre-register every cell's style so the registry is complete before we emit.
227
+ for (const row of rows) for (const cell of row) styleIndexOf(cell)
228
+
229
+ const build = () => {
230
+ const numFmtXml =
231
+ numFmts.size > 0
232
+ ? `<numFmts count="${numFmts.size}">${[...numFmts.entries()]
233
+ .map(([code, id]) => `<numFmt numFmtId="${id}" formatCode="${esc(code)}"/>`)
234
+ .join('')}</numFmts>`
235
+ : ''
236
+ return (
237
+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
238
+ `<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">` +
239
+ numFmtXml +
240
+ `<fonts count="${fonts.length}">${fonts.join('')}</fonts>` +
241
+ `<fills count="${fills.length}">${fills.join('')}</fills>` +
242
+ `<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>` +
243
+ `<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>` +
244
+ `<cellXfs count="${xfs.length}">${xfs.join('')}</cellXfs>` +
245
+ `<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>` +
246
+ `</styleSheet>`
247
+ )
248
+ }
249
+
250
+ return { styleIndexOf, build }
251
+ }
252
+
253
+ /**
254
+ * Build the OOXML package parts for a single-sheet workbook. Returns a map of
255
+ * `path -> xml string` ready to be zipped by {@link packageXlsx}.
256
+ */
257
+ export function buildXlsxParts(model: XlsxModel): Record<string, string> {
258
+ const { header, rows } = model
259
+ const styles = buildStyles(header, rows)
260
+
261
+ // Collect hyperlinks (ref -> url) for the sheet rels + <hyperlinks> block.
262
+ const links: Array<{ ref: string; url: string; id: string }> = []
263
+
264
+ // Header row (row 1), style index 1 (bold).
265
+ const headerCells = header
266
+ .map((h, c) => `<c r="${colName(c)}1" s="1" t="inlineStr"><is><t xml:space="preserve">${esc(h)}</t></is></c>`)
267
+ .join('')
268
+ const sheetRows: string[] = [`<row r="1">${headerCells}</row>`]
269
+
270
+ for (let r = 0; r < rows.length; r++) {
271
+ const rowNum = r + 2
272
+ const cells = rows[r]!
273
+ const cellXml: string[] = []
274
+ for (let c = 0; c < cells.length; c++) {
275
+ const cell = cells[c]!
276
+ const ref = `${colName(c)}${rowNum}`
277
+ const s = styles.styleIndexOf(cell)
278
+ const sAttr = s ? ` s="${s}"` : ''
279
+ if (cell.link) links.push({ ref, url: cell.link, id: `rId${links.length + 1}` })
280
+
281
+ if (cell.value == null || cell.value === '') {
282
+ cellXml.push(`<c r="${ref}"${sAttr}/>`)
283
+ } else if (cell.t === 'n') {
284
+ cellXml.push(`<c r="${ref}"${sAttr}><v>${Number(cell.value)}</v></c>`)
285
+ } else if (cell.t === 'd') {
286
+ const d = cell.value instanceof Date ? cell.value : new Date(String(cell.value))
287
+ cellXml.push(`<c r="${ref}"${sAttr}><v>${toSerialDate(d)}</v></c>`)
288
+ } else if (cell.t === 'b') {
289
+ cellXml.push(`<c r="${ref}"${sAttr} t="b"><v>${cell.value ? 1 : 0}</v></c>`)
290
+ } else {
291
+ cellXml.push(`<c r="${ref}"${sAttr} t="inlineStr"><is><t xml:space="preserve">${esc(String(cell.value))}</t></is></c>`)
292
+ }
293
+ }
294
+ sheetRows.push(`<row r="${rowNum}">${cellXml.join('')}</row>`)
295
+ }
296
+
297
+ // <cols> widths (px -> Excel char width ~ px/7).
298
+ const colsXml = model.widths
299
+ ? `<cols>${model.widths
300
+ .map((px, i) => `<col min="${i + 1}" max="${i + 1}" width="${Math.max(4, Math.round((px / 7) * 100) / 100)}" customWidth="1"/>`)
301
+ .join('')}</cols>`
302
+ : ''
303
+
304
+ // Freeze panes.
305
+ const fCols = Math.max(0, Math.floor(model.freezeColumns ?? 0))
306
+ const fRow = model.freezeHeader ? 1 : 0
307
+ let sheetView = '<sheetView workbookViewId="0"/>'
308
+ if (fRow > 0 || fCols > 0) {
309
+ const topLeft = `${colName(fCols)}${fRow + 1}`
310
+ const activePane = fCols > 0 && fRow > 0 ? 'bottomRight' : fCols > 0 ? 'topRight' : 'bottomLeft'
311
+ sheetView =
312
+ `<sheetView workbookViewId="0">` +
313
+ `<pane${fCols > 0 ? ` xSplit="${fCols}"` : ''}${fRow > 0 ? ` ySplit="${fRow}"` : ''} topLeftCell="${topLeft}" activePane="${activePane}" state="frozen"/>` +
314
+ `<selection pane="${activePane}" activeCell="${topLeft}" sqref="${topLeft}"/>` +
315
+ `</sheetView>`
316
+ }
317
+
318
+ // Native conditional formatting (data bars / color scales) over each targeted
319
+ // column's data range. Only when there are data rows to cover.
320
+ const cfXml =
321
+ rows.length > 0
322
+ ? (model.condFormats ?? [])
323
+ .map((cf, i) => {
324
+ const col = colName(cf.colIdx)
325
+ const sqref = `${col}2:${col}${rows.length + 1}`
326
+ if (cf.kind === 'dataBar') {
327
+ const c = argb(cf.color) ?? 'FF638EC6'
328
+ return (
329
+ `<conditionalFormatting sqref="${sqref}"><cfRule type="dataBar" priority="${i + 1}">` +
330
+ `<dataBar><cfvo type="min"/><cfvo type="max"/><color rgb="${c}"/></dataBar>` +
331
+ `</cfRule></conditionalFormatting>`
332
+ )
333
+ }
334
+ const stops = cf.colors.map((c) => argb(c) ?? 'FFFFFFFF')
335
+ const cfvo =
336
+ stops.length >= 3
337
+ ? '<cfvo type="min"/><cfvo type="percentile" val="50"/><cfvo type="max"/>'
338
+ : '<cfvo type="min"/><cfvo type="max"/>'
339
+ const colors = stops.map((c) => `<color rgb="${c}"/>`).join('')
340
+ return (
341
+ `<conditionalFormatting sqref="${sqref}"><cfRule type="colorScale" priority="${i + 1}">` +
342
+ `<colorScale>${cfvo}${colors}</colorScale></cfRule></conditionalFormatting>`
343
+ )
344
+ })
345
+ .join('')
346
+ : ''
347
+
348
+ const hyperlinksXml = links.length
349
+ ? `<hyperlinks>${links.map((l) => `<hyperlink ref="${l.ref}" r:id="${l.id}"/>`).join('')}</hyperlinks>`
350
+ : ''
351
+
352
+ // Excel Table (ListObject), optionally with a totals row of SUBTOTAL formulas.
353
+ let tablePartXml = ''
354
+ let tablePartsXml = ''
355
+ let tableRelId = ''
356
+ if (model.table && header.length > 0) {
357
+ const t = model.table
358
+ // Unique, non-empty column names (Excel requires distinct table columns).
359
+ const seen = new Set<string>()
360
+ const colNames = header.map((h, i) => {
361
+ const bn = (h ?? '').trim() || `Column${i + 1}`
362
+ let n = bn
363
+ let k = 1
364
+ while (seen.has(n.toLowerCase())) n = `${bn}${++k}`
365
+ seen.add(n.toLowerCase())
366
+ return n
367
+ })
368
+ const lastCol = colName(header.length - 1)
369
+ const dataLastRow = rows.length + 1 // header (row 1) + data
370
+ const totalRowNum = dataLastRow + 1
371
+ const hasTotals = t.totalsRow && rows.length > 0
372
+ const labelIdx = t.totalsFns.findIndex((fn) => !fn)
373
+
374
+ if (hasTotals) {
375
+ const totalCells = header.map((_, c) => {
376
+ const ref = `${colName(c)}${totalRowNum}`
377
+ const fn = t.totalsFns[c]
378
+ if (fn) {
379
+ let sum = 0
380
+ for (const row of rows) {
381
+ const cell = row[c]
382
+ if (cell?.t === 'n' && typeof cell.value === 'number') sum += cell.value
383
+ }
384
+ const numFmt = rows.find((r) => r[c]?.t === 'n')?.[c]?.numFmt
385
+ const s = styles.styleIndexOf({ t: 'n', value: sum, numFmt, bold: true })
386
+ const fnNum = fn === 'average' ? 101 : fn === 'count' ? 103 : 109
387
+ const value = fn === 'count' ? rows.length : sum
388
+ return `<c r="${ref}"${s ? ` s="${s}"` : ''}><f>SUBTOTAL(${fnNum},${t.name}[${esc(colNames[c]!)}])</f><v>${value}</v></c>`
389
+ }
390
+ if (c === labelIdx) {
391
+ const s = styles.styleIndexOf({ t: 's', value: 'Total', bold: true })
392
+ return `<c r="${ref}"${s ? ` s="${s}"` : ''} t="inlineStr"><is><t>Total</t></is></c>`
393
+ }
394
+ return `<c r="${ref}"/>`
395
+ })
396
+ sheetRows.push(`<row r="${totalRowNum}">${totalCells.join('')}</row>`)
397
+ }
398
+
399
+ const tableColsXml = colNames
400
+ .map((n, i) => {
401
+ const fn = hasTotals ? t.totalsFns[i] : undefined
402
+ const totalsAttr = hasTotals
403
+ ? fn
404
+ ? ` totalsRowFunction="${fn}"`
405
+ : i === labelIdx
406
+ ? ` totalsRowLabel="Total"`
407
+ : ''
408
+ : ''
409
+ return `<tableColumn id="${i + 1}" name="${esc(n)}"${totalsAttr}/>`
410
+ })
411
+ .join('')
412
+ tablePartXml =
413
+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
414
+ `<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" ` +
415
+ `name="${esc(t.name)}" displayName="${esc(t.name)}" ref="A1:${lastCol}${hasTotals ? totalRowNum : dataLastRow}"` +
416
+ `${hasTotals ? ' totalsRowCount="1"' : ' totalsRowShown="0"'}>` +
417
+ `<autoFilter ref="A1:${lastCol}${dataLastRow}"/>` +
418
+ `<tableColumns count="${header.length}">${tableColsXml}</tableColumns>` +
419
+ `<tableStyleInfo name="${esc(t.style ?? 'TableStyleMedium2')}" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/>` +
420
+ `</table>`
421
+ tableRelId = `rId${links.length + 1}`
422
+ tablePartsXml = `<tableParts count="1"><tablePart r:id="${tableRelId}"/></tableParts>`
423
+ }
424
+
425
+ const sheetXml =
426
+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
427
+ `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ` +
428
+ `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">` +
429
+ `<sheetViews>${sheetView}</sheetViews>` +
430
+ `<sheetFormatPr defaultRowHeight="15"/>` +
431
+ colsXml +
432
+ `<sheetData>${sheetRows.join('')}</sheetData>` +
433
+ cfXml +
434
+ hyperlinksXml +
435
+ tablePartsXml +
436
+ `</worksheet>`
437
+
438
+ const parts: Record<string, string> = {
439
+ '[Content_Types].xml': tablePartXml
440
+ ? CONTENT_TYPES.replace(
441
+ '</Types>',
442
+ '<Override PartName="/xl/tables/table1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/></Types>',
443
+ )
444
+ : CONTENT_TYPES,
445
+ '_rels/.rels': ROOT_RELS,
446
+ 'xl/workbook.xml': workbookXml(model.sheetName),
447
+ 'xl/_rels/workbook.xml.rels': WORKBOOK_RELS,
448
+ 'xl/styles.xml': styles.build(),
449
+ 'xl/worksheets/sheet1.xml': sheetXml,
450
+ }
451
+ if (tablePartXml) parts['xl/tables/table1.xml'] = tablePartXml
452
+ if (links.length || tableRelId) {
453
+ const rels: string[] = links.map(
454
+ (l) =>
455
+ `<Relationship Id="${l.id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="${esc(l.url)}" TargetMode="External"/>`,
456
+ )
457
+ if (tableRelId) {
458
+ rels.push(
459
+ `<Relationship Id="${tableRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table" Target="../tables/table1.xml"/>`,
460
+ )
461
+ }
462
+ parts['xl/worksheets/_rels/sheet1.xml.rels'] =
463
+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
464
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
465
+ rels.join('') +
466
+ `</Relationships>`
467
+ }
468
+ return parts
469
+ }
470
+
471
+ /** Zip the parts into an xlsx Blob using a provided JSZip constructor. */
472
+ export async function packageXlsx(
473
+ parts: Record<string, string>,
474
+ JSZip: new () => {
475
+ file(path: string, data: string): void
476
+ generateAsync(opts: { type: 'blob'; mimeType?: string }): Promise<Blob>
477
+ },
478
+ ): Promise<Blob> {
479
+ const zip = new JSZip()
480
+ for (const [path, content] of Object.entries(parts)) zip.file(path, content)
481
+ return zip.generateAsync({
482
+ type: 'blob',
483
+ mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
484
+ })
485
+ }