@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,136 @@
1
+ /**
2
+ * Dashboard model - a declarative, schema-driven set of widgets (KPI tiles +
3
+ * charts) over an entity. This is a *data view*, not a page builder: the spec is
4
+ * plain data, `SvSchemaDashboard` renders it, and `dashboardFromSchema` proposes
5
+ * a sensible default from the schema's chart-able fields. KPI tiles reduce a
6
+ * measure to a single number; charts reuse `SvSchemaChart` (and its `aggregateRows`
7
+ * / `getAggregate` seam), so nothing here re-implements aggregation.
8
+ */
9
+ import type { RowData } from '@svgrid/grid'
10
+ import type { EntitySchema } from '../schema'
11
+ import { chartFieldsFromSchema, type AggregateReduce } from './aggregate'
12
+ import type { ChartType } from '@svgrid/grid'
13
+
14
+ /** A single-number tile: reduce `measure` over the rows (count ignores measure). */
15
+ export type KpiWidget = {
16
+ kind: 'kpi'
17
+ label: string
18
+ measure?: string
19
+ reduce: AggregateReduce
20
+ /** Format the number for display (e.g. currency). */
21
+ format?: (value: number) => string
22
+ }
23
+
24
+ /** A chart tile bound to a fixed dimension / measure / reduce / type. */
25
+ export type ChartWidget = {
26
+ kind: 'chart'
27
+ label?: string
28
+ dimension: string
29
+ measure?: string
30
+ reduce: AggregateReduce
31
+ type: ChartType
32
+ /** Columns spanned in the dashboard grid. Default 1. */
33
+ span?: 1 | 2 | 3
34
+ }
35
+
36
+ export type DashboardWidget = KpiWidget | ChartWidget
37
+
38
+ export type DashboardSpec = { widgets: DashboardWidget[] }
39
+
40
+ const num = (v: unknown): number => {
41
+ const n = Number(v)
42
+ return Number.isFinite(n) ? n : 0
43
+ }
44
+
45
+ /**
46
+ * Reduce a measure over rows into a single KPI number. `count` returns the row
47
+ * count; `sum`/`avg`/`min`/`max` fold the measure. An empty set is 0.
48
+ */
49
+ export function reduceValue<T extends RowData>(
50
+ rows: ReadonlyArray<T>,
51
+ request: { measure?: string; reduce: AggregateReduce },
52
+ ): number {
53
+ const { measure, reduce } = request
54
+ if (reduce === 'count' || !measure) return rows.length
55
+ if (rows.length === 0) return 0
56
+ const values = rows.map((r) => num(r[measure]))
57
+ if (reduce === 'sum') return values.reduce((a, b) => a + b, 0)
58
+ if (reduce === 'avg') return values.reduce((a, b) => a + b, 0) / values.length
59
+ if (reduce === 'min') return Math.min(...values)
60
+ return Math.max(...values) // 'max'
61
+ }
62
+
63
+ /**
64
+ * Group rows by `trendField` (sorted, so ISO dates / ordered categories line up)
65
+ * and reduce `measure` per bucket - the series behind a KPI card's sparkline.
66
+ */
67
+ export function kpiSeries<T extends RowData>(
68
+ rows: ReadonlyArray<T>,
69
+ opts: { trendField: string; measure?: string; reduce: AggregateReduce },
70
+ ): number[] {
71
+ const groups = new Map<string, T[]>()
72
+ for (const r of rows) {
73
+ const k = String(r[opts.trendField] ?? '')
74
+ if (k === '') continue
75
+ ;(groups.get(k) ?? groups.set(k, []).get(k)!).push(r)
76
+ }
77
+ return [...groups.keys()].sort().map((k) => reduceValue(groups.get(k)!, { measure: opts.measure, reduce: opts.reduce }))
78
+ }
79
+
80
+ /** SVG polyline points for a sparkline in a `w` x `h` box (y grows downward). */
81
+ export function sparklinePoints(values: number[], w = 120, h = 30, pad = 2): string {
82
+ if (values.length === 0) return ''
83
+ const min = Math.min(...values)
84
+ const range = Math.max(...values) - min || 1
85
+ const dx = values.length > 1 ? (w - pad * 2) / (values.length - 1) : 0
86
+ return values
87
+ .map((v, i) => `${(pad + i * dx).toFixed(1)},${(pad + (h - pad * 2) * (1 - (v - min) / range)).toFixed(1)}`)
88
+ .join(' ')
89
+ }
90
+
91
+ /** Percent change from the first non-zero point to the last (null when < 2 points). */
92
+ export function seriesDelta(values: number[]): number | null {
93
+ if (values.length < 2) return null
94
+ const first = values.find((v) => v !== 0)
95
+ const last = values[values.length - 1]!
96
+ if (first == null || first === 0) return null
97
+ return ((last - first) / Math.abs(first)) * 100
98
+ }
99
+
100
+ /** Format a KPI number: currency (`$`), percent (`%`), compact (`1.2k`), or grouped. */
101
+ export function formatKpiValue(value: number, format?: 'number' | 'currency' | 'percent' | 'compact'): string {
102
+ if (format === 'currency') return '$' + value.toLocaleString(undefined, { maximumFractionDigits: 0 })
103
+ if (format === 'percent') return value.toLocaleString(undefined, { maximumFractionDigits: 1 }) + '%'
104
+ if (format === 'compact') return new Intl.NumberFormat(undefined, { notation: 'compact', maximumFractionDigits: 1 }).format(value)
105
+ return value.toLocaleString(undefined, { maximumFractionDigits: 1 })
106
+ }
107
+
108
+ /**
109
+ * Propose a default dashboard from a schema: a total-count KPI, a sum/avg KPI on
110
+ * the first numeric measure (when there is one), and a bar chart on the default
111
+ * dimension / measure. Built from `chartFieldsFromSchema`.
112
+ */
113
+ export function dashboardFromSchema(schema: EntitySchema): DashboardSpec {
114
+ const { defaultDimension, defaultMeasure } = chartFieldsFromSchema(schema)
115
+ const label = schema.label ?? schema.name
116
+ const widgets: DashboardWidget[] = [{ kind: 'kpi', label: `Total ${label}`, reduce: 'count' }]
117
+
118
+ if (defaultMeasure) {
119
+ widgets.push({ kind: 'kpi', label: `Total ${defaultMeasure}`, measure: defaultMeasure, reduce: 'sum' })
120
+ widgets.push({ kind: 'kpi', label: `Avg ${defaultMeasure}`, measure: defaultMeasure, reduce: 'avg' })
121
+ }
122
+
123
+ if (defaultDimension) {
124
+ widgets.push({
125
+ kind: 'chart',
126
+ label: defaultMeasure ? `${defaultMeasure} by ${defaultDimension}` : `Count by ${defaultDimension}`,
127
+ dimension: defaultDimension,
128
+ measure: defaultMeasure ?? undefined,
129
+ reduce: defaultMeasure ? 'sum' : 'count',
130
+ type: 'bar',
131
+ span: 2,
132
+ })
133
+ }
134
+
135
+ return { widgets }
136
+ }
@@ -0,0 +1,60 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { refineField } from './field-inference'
3
+ import type { EntityField } from '../schema'
4
+
5
+ const f = (field: string, type: EntityField['type'] = 'text', extra: Partial<EntityField> = {}): EntityField =>
6
+ ({ field, type, ...extra })
7
+
8
+ describe('refineField', () => {
9
+ it('infers formats + editors from text column names', () => {
10
+ expect(refineField(f('email')).format).toBe('email')
11
+ expect(refineField(f('contact_email')).format).toBe('email')
12
+ expect(refineField(f('website')).format).toBe('url')
13
+ expect(refineField(f('phone')).input?.editorType).toBe('phone')
14
+ expect(refineField(f('mobile_number')).input?.editorType).toBe('phone')
15
+ expect(refineField(f('country')).input?.editorType).toBe('country')
16
+ expect(refineField(f('brand_color')).input?.editorType).toBe('color')
17
+ })
18
+
19
+ it('masks structured codes with the right pattern', () => {
20
+ expect(refineField(f('ssn')).input).toMatchObject({ editorType: 'mask', mask: '###-##-####' })
21
+ expect(refineField(f('vin')).input?.mask).toBe('*****************')
22
+ expect(refineField(f('license_plate')).input?.mask).toBe('AAA-####')
23
+ expect(refineField(f('isbn')).input?.mask).toBe('###-#-#####-###-#')
24
+ expect(refineField(f('zip')).input?.mask).toBe('#####')
25
+ expect(refineField(f('tax_id')).input?.mask).toBe('##-#######')
26
+ })
27
+
28
+ it('routes password fields to a hidden-from-grid password editor', () => {
29
+ const r = refineField(f('password'))
30
+ expect(r.input?.editorType).toBe('password')
31
+ expect(r.hidden).toEqual({ grid: true })
32
+ })
33
+
34
+ it('infers rating / slider from numeric column names', () => {
35
+ expect(refineField(f('rating', 'number')).input?.editorType).toBe('rating')
36
+ expect(refineField(f('csat', 'number')).input?.editorType).toBe('rating')
37
+ expect(refineField(f('progress', 'number')).input?.editorType).toBe('slider')
38
+ expect(refineField(f('fuel_level', 'number')).input?.editorType).toBe('slider')
39
+ })
40
+
41
+ it('does NOT add range validation (must not reject existing data)', () => {
42
+ const r = refineField(f('rating', 'number'))
43
+ expect(r.min).toBeUndefined()
44
+ expect(r.max).toBeUndefined()
45
+ })
46
+
47
+ it('leaves keys, relations, enums, and explicit editors untouched', () => {
48
+ expect(refineField(f('phone', 'text', { primaryKey: true })).input).toBeUndefined()
49
+ expect(refineField(f('email', 'text', { readonly: true })).format).toBeUndefined()
50
+ expect(refineField({ field: 'ownerId', type: 'relation', relation: { entity: 'users', labelField: 'name' } }).input).toBeUndefined()
51
+ expect(refineField(f('country', 'enum', { options: [{ value: 'us', label: 'US' }] })).input).toBeUndefined()
52
+ const explicit = f('phone', 'text', { input: { editorType: 'mask', mask: '###' } })
53
+ expect(refineField(explicit).input).toEqual({ editorType: 'mask', mask: '###' })
54
+ })
55
+
56
+ it('leaves an ordinary field alone', () => {
57
+ expect(refineField(f('description'))).toEqual(f('description'))
58
+ expect(refineField(f('quantity', 'number'))).toEqual(f('quantity', 'number'))
59
+ })
60
+ })
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Infer a richer form editor for an introspected field from its name + type, so
3
+ * a database connected through Studio produces the same rich forms as the curated
4
+ * sample apps (a `phone` column becomes a phone input, `rating` a star rating,
5
+ * `email` an email field, `ssn` a masked input) instead of a wall of text boxes.
6
+ *
7
+ * DELIBERATELY CONSERVATIVE: it only refines on a clear name match, never touches
8
+ * a primary key / relation / enum field, and never adds range validation that
9
+ * could reject rows already in the user's database. Pure + node-safe. Applied by
10
+ * the shared `buildEntitySchema` (Drizzle / Prisma / PostgREST / sample row) and
11
+ * by the SQL-catalog path (`introspectDatabase`).
12
+ */
13
+ import type { RowData } from '@svgrid/grid'
14
+ import type { EntityField } from '../schema.js'
15
+
16
+ /** Masked-code patterns keyed by a field-name test. `#`=digit, `A`=letter, `*`=alnum. */
17
+ const MASKS: Array<[RegExp, string]> = [
18
+ [/(^|_)ssn$|social.?security/, '###-##-####'],
19
+ [/(^|_)vin$/, '*****************'],
20
+ [/plate|registration/, 'AAA-####'],
21
+ [/isbn/, '###-#-#####-###-#'],
22
+ [/zip|postal/, '#####'],
23
+ [/(^|_)ein$|tax.?id|vat/, '##-#######'],
24
+ ]
25
+
26
+ /**
27
+ * Return a copy of `field` with an inferred `format` / `input.editorType` when the
28
+ * name (and type) clearly imply one; otherwise return it unchanged.
29
+ */
30
+ export function refineField<T extends RowData = RowData>(field: EntityField<T>): EntityField<T> {
31
+ // Never override an explicit editor, a key, a relation, or an enum.
32
+ if (field.primaryKey || field.readonly || field.type === 'relation' || field.options?.length || field.input?.editorType) {
33
+ return field
34
+ }
35
+ const name = String(field.field).toLowerCase()
36
+ const withEditor = (editorType: NonNullable<EntityField['input']>['editorType'], extra: Record<string, unknown> = {}): EntityField<T> =>
37
+ ({ ...field, input: { ...(field.input ?? {}), editorType, ...extra } })
38
+
39
+ if (field.type === 'text') {
40
+ if (field.format == null) {
41
+ if (/e-?mail/.test(name)) return { ...field, format: 'email' }
42
+ if (/url|website|link|homepage|domain/.test(name)) return { ...field, format: 'url' }
43
+ }
44
+ if (/phone|mobile|(^|_)fax$|(^|_)tel(ephone)?$/.test(name)) return withEditor('phone')
45
+ if (/(^|_)country$|nationality/.test(name)) return withEditor('country')
46
+ if (/password|passwd|(^|_)pwd$/.test(name)) return { ...withEditor('password'), hidden: { grid: true } }
47
+ if (/colou?r$/.test(name)) return withEditor('color')
48
+ for (const [re, mask] of MASKS) if (re.test(name)) return withEditor('mask', { mask })
49
+ }
50
+
51
+ if (field.type === 'number') {
52
+ // Star rating (panel defaults max 5) or a 0-100 slider (panel defaults max 100).
53
+ if (/(^|_)(rating|score|stars|satisfaction|csat)$/.test(name)) return withEditor('rating')
54
+ if (/percent|progress|probability|completion|utili[sz]ation|occupancy|fuel.?level/.test(name)) return withEditor('slider')
55
+ }
56
+
57
+ return field
58
+ }
59
+
60
+ /** Refine every field of a schema's field list (leaves keys/relations/enums alone). */
61
+ export function refineFields<T extends { fields: EntityField[] }>(schema: T): T {
62
+ return { ...schema, fields: schema.fields.map(refineField) }
63
+ }
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { ServerFilterModel } from '@svgrid/grid'
3
+ import { normalizeFilters } from './filters'
4
+
5
+ const model = (columns: ServerFilterModel['columns'], global?: string): ServerFilterModel => ({
6
+ columns,
7
+ ...(global !== undefined ? { global } : {}),
8
+ })
9
+
10
+ describe('normalizeFilters', () => {
11
+ it('maps each operator to a neutral predicate', () => {
12
+ const { predicates } = normalizeFilters(
13
+ model({
14
+ a: { operator: 'contains', value: 'x' },
15
+ b: { operator: 'startsWith', value: 'y' },
16
+ c: { operator: 'equals', value: 'z' },
17
+ d: { operator: 'greaterThan', value: '5' },
18
+ e: { operator: 'lessThan', value: '9' },
19
+ f: { operator: 'between', value: '1', valueTo: '4' },
20
+ g: { operator: 'isBlank', value: '' },
21
+ }),
22
+ )
23
+ expect(predicates).toEqual([
24
+ { column: 'a', op: 'contains', value: 'x' },
25
+ { column: 'b', op: 'startsWith', value: 'y' },
26
+ { column: 'c', op: 'eq', value: 'z' },
27
+ { column: 'd', op: 'gt', value: '5' },
28
+ { column: 'e', op: 'lt', value: '9' },
29
+ { column: 'f', op: 'between', value: '1', valueTo: '4' },
30
+ { column: 'g', op: 'isNull' },
31
+ ])
32
+ })
33
+
34
+ it('prefers selectedValues (set filter) as an in predicate', () => {
35
+ const { predicates } = normalizeFilters(
36
+ model({ tier: { operator: 'contains', value: 'ignored', selectedValues: ['pro', 'free'] } }),
37
+ )
38
+ expect(predicates).toEqual([{ column: 'tier', op: 'in', values: ['pro', 'free'] }])
39
+ })
40
+
41
+ it('drops empty column values but keeps isBlank', () => {
42
+ const { predicates } = normalizeFilters(
43
+ model({ a: { operator: 'contains', value: ' ' }, b: { operator: 'isBlank', value: '' } }),
44
+ )
45
+ expect(predicates).toEqual([{ column: 'b', op: 'isNull' }])
46
+ })
47
+
48
+ it('backfills a one-sided between with the given bound', () => {
49
+ const { predicates } = normalizeFilters(model({ a: { operator: 'between', value: '3', valueTo: '' } }))
50
+ expect(predicates).toEqual([{ column: 'a', op: 'between', value: '3', valueTo: '3' }])
51
+ })
52
+
53
+ it('trims the global search and omits it when blank', () => {
54
+ expect(normalizeFilters(model({}, ' hi ')).search).toBe('hi')
55
+ expect(normalizeFilters(model({}, ' ')).search).toBeUndefined()
56
+ expect(normalizeFilters(undefined)).toEqual({ predicates: [], search: undefined })
57
+ })
58
+ })
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Shared filter normalization for data-source adapters. The grid emits a
3
+ * `ServerFilterModel` (per-column `{ operator, value, valueTo, selectedValues }`
4
+ * plus a global search string); every backend then has to translate that into
5
+ * its own query language. This turns the grid's model into one small, uniform
6
+ * list of predicates so each adapter (Supabase, REST, ...) maps a handful of
7
+ * clear cases instead of re-parsing the raw model.
8
+ */
9
+ import type { ServerFilterModel } from '@svgrid/grid'
10
+
11
+ /** A backend-neutral predicate over a single column. */
12
+ export type NormalizedPredicate =
13
+ | { column: string; op: 'in'; values: string[] }
14
+ | { column: string; op: 'isNull' }
15
+ | { column: string; op: 'contains' | 'startsWith' | 'eq' | 'gt' | 'lt'; value: string }
16
+ | { column: string; op: 'between'; value: string; valueTo: string }
17
+
18
+ export type NormalizedFilter = {
19
+ /** Column predicates, empty ones dropped. */
20
+ predicates: NormalizedPredicate[]
21
+ /** Free-text global search term (trimmed), if any. */
22
+ search?: string
23
+ }
24
+
25
+ /** Map the grid's per-column filter model into neutral predicates. */
26
+ export function normalizeFilters(model: ServerFilterModel | undefined): NormalizedFilter {
27
+ const predicates: NormalizedPredicate[] = []
28
+ for (const [column, f] of Object.entries(model?.columns ?? {})) {
29
+ // Set / checklist filter takes precedence when present.
30
+ if (f.selectedValues?.length) {
31
+ predicates.push({ column, op: 'in', values: f.selectedValues })
32
+ continue
33
+ }
34
+ const value = (f.value ?? '').trim()
35
+ switch (f.operator) {
36
+ case 'isBlank':
37
+ predicates.push({ column, op: 'isNull' })
38
+ break
39
+ case 'between': {
40
+ const valueTo = (f.valueTo ?? '').trim()
41
+ if (value || valueTo) predicates.push({ column, op: 'between', value, valueTo: valueTo || value })
42
+ break
43
+ }
44
+ case 'startsWith':
45
+ if (value) predicates.push({ column, op: 'startsWith', value })
46
+ break
47
+ case 'equals':
48
+ if (value) predicates.push({ column, op: 'eq', value })
49
+ break
50
+ case 'greaterThan':
51
+ if (value) predicates.push({ column, op: 'gt', value })
52
+ break
53
+ case 'lessThan':
54
+ if (value) predicates.push({ column, op: 'lt', value })
55
+ break
56
+ case 'contains':
57
+ default:
58
+ if (value) predicates.push({ column, op: 'contains', value })
59
+ break
60
+ }
61
+ }
62
+ const search = model?.global?.trim()
63
+ return { predicates, search: search ? search : undefined }
64
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Data-source adapters + introspection. Each adapter implements the grid's
3
+ * `ServerDataSource` over a specific backend, so the grid, edit form, sorting,
4
+ * filtering, and paging work identically regardless of where the data lives.
5
+ */
6
+ export { normalizeFilters, type NormalizedFilter, type NormalizedPredicate } from './filters'
7
+ export {
8
+ buildEntitySchema,
9
+ pickLabelField,
10
+ linkRelationLabels,
11
+ type IntrospectedColumn,
12
+ type ColumnReference,
13
+ } from './schema-from-columns'
14
+ export { createSupabaseDataSource, type SupabaseDataSourceConfig, type SupabaseClientLike } from './supabase'
15
+ export { createRestDataSource, type RestDataSourceConfig } from './rest'
16
+ export {
17
+ offsetLimitAdapter,
18
+ dummyJsonAdapter,
19
+ jsonServerAdapter,
20
+ type RestAdapter,
21
+ type OffsetLimitOptions,
22
+ } from './rest-adapters'
23
+ export { introspectSupabaseTable, type IntrospectSupabaseOptions } from './introspect-supabase'
24
+ export {
25
+ createSupabaseRealtime,
26
+ type SupabaseRealtimeConfig,
27
+ type SupabaseRealtimeClientLike,
28
+ type SupabaseRealtimeHandle,
29
+ type RealtimeChannelLike,
30
+ type RealtimeChange,
31
+ } from './realtime-supabase'
32
+ export {
33
+ createRelationLookup,
34
+ type RelationLookup,
35
+ type RelationLookupConfig,
36
+ type RelationOption,
37
+ } from './relation-lookup'
38
+ export {
39
+ createSupabaseAuth,
40
+ type SupabaseAuthConfig,
41
+ type SupabaseAuthController,
42
+ type SupabaseAuthClientLike,
43
+ type AuthState,
44
+ type AuthUser,
45
+ } from './auth-supabase'
46
+ export {
47
+ aggregateRows,
48
+ chartFieldsFromSchema,
49
+ type AggregateReduce,
50
+ type AggregateRequest,
51
+ type AggregateBucket,
52
+ type AggregateSource,
53
+ } from './aggregate'
54
+ export { withEntityRules } from './with-entity-rules'
55
+ export { withRelationLabels, type RelationLabelConfig } from './with-relation-labels'
56
+ export {
57
+ reduceValue,
58
+ kpiSeries,
59
+ sparklinePoints,
60
+ seriesDelta,
61
+ formatKpiValue,
62
+ dashboardFromSchema,
63
+ type DashboardSpec,
64
+ type DashboardWidget,
65
+ type KpiWidget,
66
+ type ChartWidget,
67
+ } from './dashboard'
@@ -0,0 +1,100 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { introspectSupabaseTable } from './introspect-supabase'
3
+
4
+ type Parts = { openapi?: unknown; openapiStatus?: number; csv?: string; sample?: unknown }
5
+
6
+ function resp(opts: { status?: number; json?: unknown; text?: string; headers?: Record<string, string> }) {
7
+ const status = opts.status ?? 200
8
+ return {
9
+ ok: status >= 200 && status < 300,
10
+ status,
11
+ statusText: 'OK',
12
+ headers: { get: (k: string) => opts.headers?.[k.toLowerCase()] ?? null },
13
+ json: async () => opts.json,
14
+ text: async () => opts.text ?? '',
15
+ } as unknown as Response
16
+ }
17
+
18
+ function fetchFor(parts: Parts): typeof globalThis.fetch {
19
+ return (async (url: string | URL, init?: RequestInit) => {
20
+ const u = String(url)
21
+ const accept = (init?.headers as Record<string, string>)?.Accept
22
+ if (u.endsWith('/rest/v1/')) return resp({ status: parts.openapiStatus ?? 200, json: parts.openapi })
23
+ if (accept === 'text/csv') return resp({ text: parts.csv ?? '' })
24
+ return resp({ json: parts.sample ?? [] })
25
+ }) as unknown as typeof globalThis.fetch
26
+ }
27
+
28
+ const opts = (fetch: typeof globalThis.fetch) => ({ url: 'https://x.supabase.co', key: 'anon', table: 'customers', fetch })
29
+
30
+ describe('introspectSupabaseTable', () => {
31
+ it('reads columns, types, and the primary key from the OpenAPI doc', async () => {
32
+ const openapi = {
33
+ definitions: {
34
+ customers: {
35
+ required: ['name'],
36
+ properties: {
37
+ id: { type: 'integer', description: 'Note:\nThis is a Primary Key.<pk/>' },
38
+ name: { type: 'string' },
39
+ active: { type: 'boolean' },
40
+ tier: { type: 'string', enum: ['free', 'pro'] },
41
+ },
42
+ },
43
+ },
44
+ }
45
+ const schema = await introspectSupabaseTable(opts(fetchFor({ openapi })))
46
+ expect(schema?.idField).toBe('id')
47
+ expect(schema?.fields.map((f) => [f.field, f.type])).toEqual([
48
+ ['id', 'number'], ['name', 'text'], ['active', 'boolean'], ['tier', 'enum'],
49
+ ])
50
+ expect(schema?.fields.find((f) => f.field === 'id')).toMatchObject({ primaryKey: true, readonly: true })
51
+ expect(schema?.fields.find((f) => f.field === 'name')?.required).toBe(true)
52
+ })
53
+
54
+ it('detects a foreign key from the OpenAPI description', async () => {
55
+ const openapi = {
56
+ definitions: {
57
+ customers: {
58
+ properties: {
59
+ id: { type: 'integer', description: '<pk/>' },
60
+ name: { type: 'string' },
61
+ company_id: { type: 'integer', description: "Note:\nThis is a Foreign Key to `companies.id`.<fk table='companies' column='id'/>" },
62
+ },
63
+ },
64
+ },
65
+ }
66
+ const schema = await introspectSupabaseTable(opts(fetchFor({ openapi })))
67
+ const rel = schema?.fields.find((f) => f.field === 'company_id')
68
+ expect(rel?.type).toBe('relation')
69
+ expect(rel?.relation).toEqual({ entity: 'companies', foreignKey: 'company_id', labelField: 'name' })
70
+ })
71
+
72
+ it('supports the OpenAPI 3 components.schemas shape', async () => {
73
+ const openapi = { components: { schemas: { customers: { properties: { name: { type: 'string' } } } } } }
74
+ const schema = await introspectSupabaseTable(opts(fetchFor({ openapi })))
75
+ expect(schema?.fields.map((f) => f.field)).toEqual(['name'])
76
+ })
77
+
78
+ it('falls back to the CSV header for an empty table when OpenAPI is blocked', async () => {
79
+ // OpenAPI 404 (CORS/blocked), sample empty, CSV header present.
80
+ const schema = await introspectSupabaseTable(
81
+ opts(fetchFor({ openapiStatus: 404, sample: [], csv: 'id,Name\n' })),
82
+ )
83
+ expect(schema?.fields.map((f) => f.field)).toEqual(['id', 'Name'])
84
+ expect(schema?.idField).toBe('id')
85
+ })
86
+
87
+ it('falls back to a sample row when OpenAPI is blocked and the table has data', async () => {
88
+ const schema = await introspectSupabaseTable(
89
+ opts(fetchFor({ openapiStatus: 404, sample: [{ id: 1, name: 'Ada', active: true }] })),
90
+ )
91
+ expect(schema?.fields.map((f) => [f.field, f.type])).toEqual([
92
+ ['id', 'number'], ['name', 'text'], ['active', 'boolean'],
93
+ ])
94
+ })
95
+
96
+ it('returns null when nothing can determine the columns', async () => {
97
+ const schema = await introspectSupabaseTable(opts(fetchFor({ openapiStatus: 404, sample: [], csv: '' })))
98
+ expect(schema).toBeNull()
99
+ })
100
+ })
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Browser-side introspection for Supabase / PostgREST. Discovers a table's
3
+ * columns from the REST API alone (URL + anon key), so a screen can adapt to an
4
+ * arbitrary table with no server. Tries the most informative source first:
5
+ *
6
+ * 1. OpenAPI doc - names + types + primary key (best; sometimes CORS-blocked)
7
+ * 2. CSV header - names only, but works on an EMPTY table and is CORS-safe
8
+ * 3. sample row - names + types inferred from one row of data
9
+ *
10
+ * Returns null when none of them can determine the columns (e.g. an empty table
11
+ * whose OpenAPI is blocked) - the caller can then ask the user to list columns.
12
+ */
13
+ import type { RowData } from '@svgrid/grid'
14
+ import type { EntityFieldType, EntitySchema } from '../schema'
15
+ import { buildEntitySchema, type IntrospectedColumn } from './schema-from-columns'
16
+
17
+ export type IntrospectSupabaseOptions = {
18
+ /** Project URL, e.g. `https://xxxx.supabase.co`. */
19
+ url: string
20
+ /** anon public key. */
21
+ key: string
22
+ table: string
23
+ /** Custom fetch (SSR, tests). Defaults to the global `fetch`. */
24
+ fetch?: typeof fetch
25
+ }
26
+
27
+ const mapOpenApiType = (prop: { type?: string; enum?: unknown }): EntityFieldType => {
28
+ if (Array.isArray(prop.enum)) return 'enum'
29
+ if (prop.type === 'integer' || prop.type === 'number') return 'number'
30
+ if (prop.type === 'boolean') return 'boolean'
31
+ return 'text'
32
+ }
33
+
34
+ async function viaOpenApi(o: Required<IntrospectSupabaseOptions>, base: string): Promise<IntrospectedColumn[] | null> {
35
+ let res: Response
36
+ try {
37
+ res = await o.fetch(`${base}/rest/v1/`, {
38
+ headers: { apikey: o.key, Authorization: `Bearer ${o.key}`, Accept: 'application/json' },
39
+ })
40
+ } catch {
41
+ return null // network / CORS - let another path try
42
+ }
43
+ if (!res.ok) return null
44
+ let spec: any
45
+ try { spec = await res.json() } catch { return null }
46
+
47
+ const defs: Record<string, any> = spec?.definitions ?? spec?.components?.schemas ?? {}
48
+ let def = defs[o.table]
49
+ if (!def) {
50
+ const key = Object.keys(defs).find((k) => k.toLowerCase() === o.table.toLowerCase())
51
+ if (key) def = defs[key]
52
+ }
53
+ const props = def?.properties
54
+ if (!props || !Object.keys(props).length) return null
55
+
56
+ const required: string[] = Array.isArray(def.required) ? def.required : []
57
+ return Object.entries<any>(props).map(([name, prop]) => {
58
+ const desc: string = prop?.description ?? ''
59
+ // PostgREST annotates a foreign key in the column description:
60
+ // "...<fk table='companies' column='id'/>"
61
+ const fk = /<fk\s+table=['"]([^'"]+)['"]\s+column=['"]([^'"]+)['"]/i.exec(desc)
62
+ return {
63
+ name,
64
+ type: mapOpenApiType(prop),
65
+ primaryKey: /primary key|<pk\/>/i.test(desc),
66
+ required: required.includes(name),
67
+ enumValues: Array.isArray(prop?.enum) ? (prop.enum as string[]) : undefined,
68
+ references: fk ? { table: fk[1]!, column: fk[2]! } : undefined,
69
+ }
70
+ })
71
+ }
72
+
73
+ async function viaCsv(o: Required<IntrospectSupabaseOptions>, base: string): Promise<IntrospectedColumn[] | null> {
74
+ let res: Response
75
+ try {
76
+ res = await o.fetch(`${base}/rest/v1/${encodeURIComponent(o.table)}?select=*&limit=1`, {
77
+ headers: { apikey: o.key, Authorization: `Bearer ${o.key}`, Accept: 'text/csv' },
78
+ })
79
+ } catch {
80
+ return null
81
+ }
82
+ if (!res.ok) return null
83
+ const text = (await res.text()).trim()
84
+ const header = text.split(/\r?\n/)[0] ?? ''
85
+ const names = header.split(',').map((h) => h.trim().replace(/^"|"$/g, '')).filter(Boolean)
86
+ return names.length ? names.map((name) => ({ name })) : null
87
+ }
88
+
89
+ async function viaSample(o: Required<IntrospectSupabaseOptions>, base: string): Promise<IntrospectedColumn[] | null> {
90
+ let res: Response
91
+ try {
92
+ res = await o.fetch(`${base}/rest/v1/${encodeURIComponent(o.table)}?select=*&limit=1`, {
93
+ headers: { apikey: o.key, Authorization: `Bearer ${o.key}`, Accept: 'application/json' },
94
+ })
95
+ } catch {
96
+ return null
97
+ }
98
+ if (!res.ok) return null
99
+ let rows: any
100
+ try { rows = await res.json() } catch { return null }
101
+ const sample = Array.isArray(rows) ? rows[0] : undefined
102
+ if (!sample) return null
103
+ return Object.entries(sample).map(([name, v]) => ({
104
+ name,
105
+ type: (typeof v === 'number' ? 'number' : typeof v === 'boolean' ? 'boolean' : 'text') as EntityFieldType,
106
+ }))
107
+ }
108
+
109
+ /** Introspect a Supabase/PostgREST table into an EntitySchema, or null. */
110
+ export async function introspectSupabaseTable<TData extends RowData = RowData>(
111
+ options: IntrospectSupabaseOptions,
112
+ ): Promise<EntitySchema<TData> | null> {
113
+ const o: Required<IntrospectSupabaseOptions> = { fetch: globalThis.fetch, ...options }
114
+ const base = o.url.replace(/\/+$/, '')
115
+ const columns =
116
+ (await viaOpenApi(o, base)) ?? (await viaSample(o, base)) ?? (await viaCsv(o, base))
117
+ if (!columns || !columns.length) return null
118
+ return buildEntitySchema<TData>(o.table, columns)
119
+ }