@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,104 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { ServerRequest } from '@svgrid/grid'
3
+ import { createRestDataSource } from './rest'
4
+
5
+ type Row = { id: string; name: string }
6
+
7
+ function jsonResponse(body: unknown, opts: { status?: number; headers?: Record<string, string> } = {}) {
8
+ const status = opts.status ?? 200
9
+ const headers = opts.headers ?? {}
10
+ return {
11
+ ok: status >= 200 && status < 300,
12
+ status,
13
+ statusText: 'OK',
14
+ headers: { get: (k: string) => headers[k.toLowerCase()] ?? null },
15
+ json: async () => body,
16
+ } as unknown as Response
17
+ }
18
+
19
+ function mockFetch(handler: (url: string, init?: RequestInit) => Response) {
20
+ const calls: Array<{ url: string; init?: RequestInit }> = []
21
+ const fetch = (async (url: string | URL, init?: RequestInit) => {
22
+ calls.push({ url: String(url), init })
23
+ return handler(String(url), init)
24
+ }) as unknown as typeof globalThis.fetch
25
+ return { fetch, calls }
26
+ }
27
+
28
+ const req = (p: Partial<ServerRequest>): ServerRequest => ({
29
+ startRow: 0, endRow: 10, pageIndex: 0, pageSize: 10, sortModel: [], filterModel: {}, ...p,
30
+ })
31
+
32
+ describe('createRestDataSource reads', () => {
33
+ it('builds the default query and parses an object response', async () => {
34
+ const { fetch, calls } = mockFetch(() => jsonResponse({ rows: [{ id: '1', name: 'Ada' }], rowCount: 5 }))
35
+ const src = createRestDataSource<Row>({ url: '/api/customers', fetch })
36
+ const out = await src.getRows(
37
+ req({
38
+ sortModel: [{ id: 'mrr', desc: true }, { id: 'name', desc: false }],
39
+ filterModel: { global: 'ada', columns: { name: { operator: 'contains', value: 'a' } } },
40
+ }),
41
+ )
42
+ const usp = new URLSearchParams(calls[0]!.url.split('?')[1])
43
+ expect(usp.get('offset')).toBe('0')
44
+ expect(usp.get('limit')).toBe('10')
45
+ expect(usp.get('sort')).toBe('-mrr,name')
46
+ expect(usp.get('search')).toBe('ada')
47
+ expect(usp.get('name')).toBe('contains:a')
48
+ expect(out).toEqual({ rows: [{ id: '1', name: 'Ada' }], rowCount: 5 })
49
+ })
50
+
51
+ it('merges static `query` params into every read (built paging wins on conflict)', async () => {
52
+ const { fetch, calls } = mockFetch(() => jsonResponse({ rows: [], rowCount: 0 }))
53
+ const src = createRestDataSource<Row>({ url: '/api/customers', fetch, query: { region: 'eu', limit: 'IGNORED' } })
54
+ await src.getRows(req({}))
55
+ const usp = new URLSearchParams(calls[0]!.url.split('?')[1])
56
+ expect(usp.get('region')).toBe('eu') // static param sent on every read
57
+ expect(usp.get('limit')).toBe('10') // the built paging limit wins over a static one
58
+ })
59
+
60
+ it('reads the total from Content-Range for an array body', async () => {
61
+ const { fetch } = mockFetch(() => jsonResponse([{ id: '1', name: 'Ada' }], { headers: { 'content-range': '0-0/240' } }))
62
+ const src = createRestDataSource<Row>({ url: '/api/customers', fetch })
63
+ const out = await src.getRows(req({}))
64
+ expect(out).toEqual({ rows: [{ id: '1', name: 'Ada' }], rowCount: 240 })
65
+ })
66
+
67
+ it('throws on a non-ok response', async () => {
68
+ const { fetch } = mockFetch(() => jsonResponse({}, { status: 500 }))
69
+ const src = createRestDataSource<Row>({ url: '/api/customers', fetch })
70
+ await expect(src.getRows(req({}))).rejects.toThrow(/500/)
71
+ })
72
+ })
73
+
74
+ describe('createRestDataSource writes', () => {
75
+ it('POSTs to the collection to create', async () => {
76
+ const { fetch, calls } = mockFetch(() => jsonResponse({ id: '9', name: 'New' }))
77
+ const src = createRestDataSource<Row>({ url: '/api/customers', fetch })
78
+ const row = await src.createRow({ name: 'New' })
79
+ expect(calls[0]!.url).toBe('/api/customers')
80
+ expect(calls[0]!.init?.method).toBe('POST')
81
+ expect(JSON.parse(String(calls[0]!.init?.body))).toEqual({ name: 'New' })
82
+ expect(row).toEqual({ id: '9', name: 'New' })
83
+ })
84
+
85
+ it('PATCHes /{id} to update and DELETEs /{id}', async () => {
86
+ const { fetch, calls } = mockFetch((_url, init) =>
87
+ init?.method === 'DELETE' ? jsonResponse(undefined, { status: 204 }) : jsonResponse({ id: '5', name: 'X' }),
88
+ )
89
+ const src = createRestDataSource<Row>({ url: '/api/customers', fetch })
90
+ await src.updateRow('5', { name: 'X' })
91
+ await src.deleteRow('7')
92
+ expect(calls[0]).toMatchObject({ url: '/api/customers/5' })
93
+ expect(calls[0]!.init?.method).toBe('PATCH')
94
+ expect(calls[1]!).toMatchObject({ url: '/api/customers/7' })
95
+ expect(calls[1]!.init?.method).toBe('DELETE')
96
+ })
97
+
98
+ it('applies custom headers', async () => {
99
+ const { fetch, calls } = mockFetch(() => jsonResponse({ rows: [], rowCount: 0 }))
100
+ const src = createRestDataSource<Row>({ url: '/api/x', fetch, headers: { authorization: 'Bearer t' } })
101
+ await src.getRows(req({}))
102
+ expect((calls[0]!.init?.headers as Record<string, string>).authorization).toBe('Bearer t')
103
+ })
104
+ })
@@ -0,0 +1,129 @@
1
+ /**
2
+ * createRestDataSource - a `ServerDataSource` over an HTTP/JSON API. Handles the
3
+ * request lifecycle and the four CRUD calls; you point it at a collection URL.
4
+ * The default request/response shaping suits a conventional REST endpoint, and
5
+ * every part is overridable (`buildQuery`, `parse`, `headers`, `fetch`) for
6
+ * bespoke or legacy APIs.
7
+ *
8
+ * const source = createRestDataSource({ url: '/api/customers', schema })
9
+ *
10
+ * Default wire format:
11
+ * read GET {url}?offset&limit&sort&search&<col>=<op>:<value>
12
+ * create POST {url} body: the new row
13
+ * update PATCH {url}/{id} body: the patch
14
+ * delete DELETE {url}/{id}
15
+ * where `sort` is a comma list with `-` for descending (e.g. `-createdAt,name`).
16
+ */
17
+ import type { RowData, ServerRequest, ServerResult } from '@svgrid/grid'
18
+ import { resolveIdField, type EntitySchema } from '../schema'
19
+ import { nudgeEnterprise } from '../license'
20
+ import type { WritableDataSource } from '../sveltekit/types'
21
+ import { normalizeFilters, type NormalizedPredicate } from './filters'
22
+
23
+ export type RestDataSourceConfig<TData extends RowData> = {
24
+ /** Collection endpoint, e.g. `/api/customers`. */
25
+ url: string
26
+ /** Used to resolve the id field for update/delete when `idField` is omitted. */
27
+ schema?: EntitySchema<TData>
28
+ /** Primary key property (default: from `schema`, else `'id'`). */
29
+ idField?: string
30
+ /** Custom fetch (SSR, auth). Defaults to the global `fetch`. */
31
+ fetch?: typeof fetch
32
+ /** Extra request headers, static or computed per call. */
33
+ headers?: Record<string, string> | (() => Record<string, string>)
34
+ /** Static query params merged into every read (e.g. an API key or filter). */
35
+ query?: Record<string, string>
36
+ /** Build read query params from the grid request. Override for bespoke APIs. */
37
+ buildQuery?: (request: ServerRequest) => Record<string, string>
38
+ /** Parse a read response body into rows + total. Override for bespoke shapes. */
39
+ parse?: (body: unknown, response: Response) => ServerResult<TData>
40
+ }
41
+
42
+ const encodePredicate = (p: NormalizedPredicate): string => {
43
+ if (p.op === 'in') return `in:${p.values.join(',')}`
44
+ if (p.op === 'isNull') return 'isNull'
45
+ if (p.op === 'between') return `between:${p.value},${p.valueTo}`
46
+ return `${p.op}:${p.value}`
47
+ }
48
+
49
+ function defaultBuildQuery(request: ServerRequest): Record<string, string> {
50
+ const params: Record<string, string> = {
51
+ offset: String(request.startRow),
52
+ limit: String(request.endRow - request.startRow),
53
+ }
54
+ if (request.sortModel.length) {
55
+ params.sort = request.sortModel.map((s) => (s.desc ? '-' : '') + s.id).join(',')
56
+ }
57
+ const { predicates, search } = normalizeFilters(request.filterModel)
58
+ if (search) params.search = search
59
+ for (const p of predicates) params[p.column] = encodePredicate(p)
60
+ return params
61
+ }
62
+
63
+ function defaultParse<TData>(body: unknown, response: Response): ServerResult<TData> {
64
+ if (Array.isArray(body)) {
65
+ // Total from a Content-Range header (`items 0-9/240`) when present.
66
+ const range = response.headers.get('content-range')
67
+ const total = range && /\/(\d+)\s*$/.exec(range)
68
+ return { rows: body as TData[], rowCount: total ? Number(total[1]) : body.length }
69
+ }
70
+ const b = (body ?? {}) as Record<string, unknown>
71
+ const rows = (b.rows ?? b.data ?? b.items ?? []) as TData[]
72
+ const rowCount = Number(b.rowCount ?? b.total ?? b.count ?? rows.length)
73
+ return { rows, rowCount }
74
+ }
75
+
76
+ export function createRestDataSource<TData extends RowData>(
77
+ config: RestDataSourceConfig<TData>,
78
+ ): WritableDataSource<TData> {
79
+ nudgeEnterprise('Studio') // soft-gate; never blocks
80
+ const doFetch = config.fetch ?? globalThis.fetch
81
+ const idField = config.idField ?? (config.schema ? resolveIdField(config.schema) : 'id')
82
+ const base = config.url.replace(/\/+$/, '')
83
+ const buildQuery = config.buildQuery ?? defaultBuildQuery
84
+ const parse = config.parse ?? defaultParse
85
+
86
+ const headers = (extra?: Record<string, string>): Record<string, string> => {
87
+ const h = typeof config.headers === 'function' ? config.headers() : (config.headers ?? {})
88
+ return { ...h, ...extra }
89
+ }
90
+
91
+ const send = async (url: string, init?: RequestInit): Promise<unknown> => {
92
+ const res = await doFetch(url, init)
93
+ if (!res.ok) throw new Error(`REST ${init?.method ?? 'GET'} ${url} -> ${res.status} ${res.statusText}`)
94
+ const parsed = res.status === 204 ? undefined : await res.json().catch(() => undefined)
95
+ return { body: parsed, res }
96
+ }
97
+
98
+ return {
99
+ async getRows(request: ServerRequest): Promise<ServerResult<TData>> {
100
+ // Static `query` params first; the built paging/sort/filter params win on conflict.
101
+ const qs = new URLSearchParams({ ...config.query, ...buildQuery(request) }).toString()
102
+ const url = qs ? `${base}?${qs}` : base
103
+ const { body, res } = (await send(url, { headers: headers() })) as { body: unknown; res: Response }
104
+ return parse(body, res)
105
+ },
106
+
107
+ async createRow(input: Partial<TData>): Promise<TData> {
108
+ const { body } = (await send(base, {
109
+ method: 'POST',
110
+ headers: headers({ 'content-type': 'application/json' }),
111
+ body: JSON.stringify(input),
112
+ })) as { body: unknown }
113
+ return (body ?? input) as TData
114
+ },
115
+
116
+ async updateRow(id: string, patch: Partial<TData>): Promise<TData> {
117
+ const { body } = (await send(`${base}/${encodeURIComponent(id)}`, {
118
+ method: 'PATCH',
119
+ headers: headers({ 'content-type': 'application/json' }),
120
+ body: JSON.stringify(patch),
121
+ })) as { body: unknown }
122
+ return (body ?? { ...patch, [idField]: id }) as TData
123
+ },
124
+
125
+ async deleteRow(id: string): Promise<void> {
126
+ await send(`${base}/${encodeURIComponent(id)}`, { method: 'DELETE', headers: headers() })
127
+ },
128
+ }
129
+ }
@@ -0,0 +1,106 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { EntitySchema } from '../schema'
3
+ import { buildEntitySchema, linkRelationLabels, pickLabelField } from './schema-from-columns'
4
+
5
+ describe('buildEntitySchema', () => {
6
+ it('uses an explicit primary key and marks it readonly', () => {
7
+ const s = buildEntitySchema('t', [
8
+ { name: 'name', type: 'text' },
9
+ { name: 'code', type: 'text', primaryKey: true },
10
+ ])
11
+ expect(s.idField).toBe('code')
12
+ expect(s.fields.find((f) => f.field === 'code')).toMatchObject({ primaryKey: true, readonly: true })
13
+ })
14
+
15
+ it('falls back to a column named id, then the first column', () => {
16
+ expect(buildEntitySchema('t', [{ name: 'a' }, { name: 'id' }]).idField).toBe('id')
17
+ expect(buildEntitySchema('t', [{ name: 'first' }, { name: 'second' }]).idField).toBe('first')
18
+ })
19
+
20
+ it('defaults type to text and carries required + enum options', () => {
21
+ const s = buildEntitySchema('t', [
22
+ { name: 'id', primaryKey: true },
23
+ { name: 'name', required: true },
24
+ { name: 'tier', enumValues: ['free', 'pro'] },
25
+ ])
26
+ expect(s.fields.find((f) => f.field === 'name')).toMatchObject({ type: 'text', required: true })
27
+ const tier = s.fields.find((f) => f.field === 'tier')
28
+ expect(tier?.type).toBe('enum')
29
+ expect(tier?.options).toEqual([{ value: 'free', label: 'free' }, { value: 'pro', label: 'pro' }])
30
+ })
31
+
32
+ it('does not mark the primary key as required', () => {
33
+ const s = buildEntitySchema('t', [{ name: 'id', primaryKey: true, required: true }])
34
+ expect(s.fields[0]!).toMatchObject({ primaryKey: true, readonly: true })
35
+ expect(s.fields[0]!.required).toBeUndefined()
36
+ })
37
+
38
+ it('throws with no columns', () => {
39
+ expect(() => buildEntitySchema('t', [])).toThrow(/no columns/)
40
+ })
41
+
42
+ it('turns a foreign-key column into a relation field', () => {
43
+ const s = buildEntitySchema('contacts', [
44
+ { name: 'id', primaryKey: true },
45
+ { name: 'name', required: true },
46
+ { name: 'company_id', required: true, references: { table: 'companies', column: 'id' } },
47
+ ])
48
+ const rel = s.fields.find((f) => f.field === 'company_id')
49
+ expect(rel).toMatchObject({
50
+ field: 'company_id',
51
+ type: 'relation',
52
+ required: true,
53
+ relation: { entity: 'companies', foreignKey: 'company_id', labelField: 'name' },
54
+ })
55
+ })
56
+
57
+ it('does not turn the primary key into a relation even if it references', () => {
58
+ const s = buildEntitySchema('t', [{ name: 'id', primaryKey: true, references: { table: 'other' } }])
59
+ expect(s.fields[0]!.type).not.toBe('relation')
60
+ expect(s.fields[0]).toMatchObject({ primaryKey: true })
61
+ })
62
+
63
+ it('honors an explicit labelField on the reference', () => {
64
+ const s = buildEntitySchema('t', [
65
+ { name: 'id', primaryKey: true },
66
+ { name: 'owner', references: { table: 'users', labelField: 'email' } },
67
+ ])
68
+ expect(s.fields.find((f) => f.field === 'owner')?.relation?.labelField).toBe('email')
69
+ })
70
+ })
71
+
72
+ describe('pickLabelField', () => {
73
+ const make = (fieldNames: [string, 'text' | 'number'][]): EntitySchema => ({
74
+ name: 't', idField: 'id',
75
+ fields: fieldNames.map(([field, type]) => ({ field, type, ...(field === 'id' ? { primaryKey: true } : {}) })),
76
+ })
77
+
78
+ it('prefers name / title / label', () => {
79
+ expect(pickLabelField(make([['id', 'number'], ['title', 'text'], ['body', 'text']]))).toBe('title')
80
+ })
81
+ it('falls back to the first non-id text field, then the id', () => {
82
+ expect(pickLabelField(make([['id', 'number'], ['slug', 'text']]))).toBe('slug')
83
+ expect(pickLabelField(make([['id', 'number'], ['count', 'number']]))).toBe('id')
84
+ })
85
+ })
86
+
87
+ describe('linkRelationLabels', () => {
88
+ it('resolves each relation labelField from the related schema', () => {
89
+ const companies: EntitySchema = {
90
+ name: 'companies', idField: 'id',
91
+ fields: [{ field: 'id', type: 'number', primaryKey: true }, { field: 'name', type: 'text' }],
92
+ }
93
+ const contacts: EntitySchema = {
94
+ name: 'contacts', idField: 'id',
95
+ fields: [
96
+ { field: 'id', type: 'number', primaryKey: true },
97
+ { field: 'company_id', type: 'relation', relation: { entity: 'companies', foreignKey: 'company_id', labelField: 'name' } },
98
+ { field: 'buddy_id', type: 'relation', relation: { entity: 'missing', foreignKey: 'buddy_id', labelField: 'name' } },
99
+ ],
100
+ }
101
+ const [, linkedContacts] = linkRelationLabels([companies, contacts])
102
+ expect(linkedContacts!.fields.find((f) => f.field === 'company_id')?.relation?.labelField).toBe('name')
103
+ // Unknown related entity is left untouched.
104
+ expect(linkedContacts!.fields.find((f) => f.field === 'buddy_id')?.relation?.labelField).toBe('name')
105
+ })
106
+ })
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The shared "columns -> EntitySchema" core. Every introspection path (SQL
3
+ * catalog, PostgREST/OpenAPI, a sample row, manual entry) discovers columns in
4
+ * its own way, then hands a normalized list here to assemble a consistent
5
+ * `EntitySchema` - primary key resolution, readonly on the key, enum options,
6
+ * and a sane default type. Keeping this in one place means the grid + form come
7
+ * out identical no matter which path found the columns.
8
+ */
9
+ import type { RowData } from '@svgrid/grid'
10
+ import type { EntityField, EntityFieldType, EntitySchema } from '../schema.js'
11
+ import { refineField } from './field-inference.js'
12
+
13
+ /** A discovered foreign key: this column references `table`.`column`. */
14
+ export type ColumnReference = {
15
+ /** Referenced table (becomes the relation's `entity`). */
16
+ table: string
17
+ /** Referenced column (usually the related PK). */
18
+ column?: string
19
+ /** Field on the related entity to show the user. Defaults to `'name'`. */
20
+ labelField?: string
21
+ }
22
+
23
+ /** One discovered column, backend-neutral. */
24
+ export type IntrospectedColumn = {
25
+ name: string
26
+ /** Actual DB column, when it differs from `name` (e.g. Drizzle `created_at` vs key `createdAt`). */
27
+ dbColumn?: string
28
+ /** High-level type. Defaults to `'text'` when a path can't determine it. */
29
+ type?: EntityFieldType
30
+ primaryKey?: boolean
31
+ /** NOT NULL (becomes a required, non-key field). */
32
+ required?: boolean
33
+ /** Allowed values, for enum columns. */
34
+ enumValues?: string[]
35
+ /** Foreign key: makes this a `relation` field with a searchable lookup. */
36
+ references?: ColumnReference
37
+ }
38
+
39
+ /** Assemble an EntitySchema from discovered columns. */
40
+ export function buildEntitySchema<TData extends RowData = RowData>(
41
+ table: string,
42
+ columns: IntrospectedColumn[],
43
+ ): EntitySchema<TData> {
44
+ if (!columns.length) throw new Error(`buildEntitySchema: "${table}" has no columns`)
45
+
46
+ // Primary key: first flagged pk, else a column literally named "id", else the
47
+ // first column (so update/delete always have a key to target).
48
+ const explicitPk = columns.find((c) => c.primaryKey)?.name
49
+ const idField = explicitPk ?? columns.find((c) => /^id$/i.test(c.name))?.name ?? columns[0]!.name
50
+
51
+ const fields: EntityField<TData>[] = columns.map((c) => {
52
+ const isPk = c.name === idField
53
+ // A foreign-key column (that isn't the PK) becomes a relation field, so the
54
+ // form renders a lookup and master-detail can be inferred.
55
+ if (c.references && !isPk) {
56
+ const rel = { field: c.name, type: 'relation' as const } as EntityField<TData>
57
+ rel.relation = {
58
+ entity: c.references.table,
59
+ foreignKey: c.name,
60
+ labelField: c.references.labelField ?? 'name',
61
+ }
62
+ if (c.dbColumn) rel.dbColumn = c.dbColumn
63
+ if (c.required) rel.required = true
64
+ return rel
65
+ }
66
+
67
+ const type: EntityFieldType = c.enumValues?.length ? 'enum' : (c.type ?? 'text')
68
+ const f = { field: c.name, type } as EntityField<TData>
69
+ if (c.dbColumn) f.dbColumn = c.dbColumn
70
+ if (isPk) {
71
+ f.primaryKey = true
72
+ f.readonly = true
73
+ } else if (c.required) {
74
+ f.required = true
75
+ }
76
+ if (type === 'enum' && c.enumValues?.length) {
77
+ f.options = c.enumValues.map((v) => ({ value: v, label: v }))
78
+ }
79
+ // Infer a rich editor from the column name/type (phone / email / rating / ...).
80
+ return refineField(f)
81
+ })
82
+
83
+ return { name: table, label: table, idField, fields }
84
+ }
85
+
86
+ // Schema-level relation helpers live in ../schema (studio consumes them under
87
+ // node16 resolution); re-exported here so introspection consumers get one entry.
88
+ export { pickLabelField, linkRelationLabels } from '../schema.js'
@@ -0,0 +1,110 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { ServerRequest } from '@svgrid/grid'
3
+ import type { EntitySchema } from '../schema'
4
+ import { createSupabaseDataSource } from './supabase'
5
+
6
+ type Customer = { id: number; name: string; email: string; tier: string; mrr: number }
7
+
8
+ const schema: EntitySchema<Customer> = {
9
+ name: 'customers',
10
+ idField: 'id',
11
+ fields: [
12
+ { field: 'id', type: 'number', primaryKey: true },
13
+ { field: 'name', type: 'text' },
14
+ { field: 'email', type: 'text' },
15
+ { field: 'tier', type: 'enum', options: [{ value: 'pro', label: 'Pro' }] },
16
+ { field: 'mrr', type: 'number' },
17
+ ],
18
+ }
19
+
20
+ /** A supabase-js-like builder: chainable AND awaitable (thenable). */
21
+ function makeClient(result: unknown) {
22
+ const calls: Array<[string, unknown[]]> = []
23
+ const builder: any = new Proxy(
24
+ {},
25
+ {
26
+ get(_t, prop: string) {
27
+ if (prop === 'then') return (res: (v: unknown) => void) => Promise.resolve(result).then(res)
28
+ return (...args: unknown[]) => {
29
+ calls.push([prop, args])
30
+ return builder
31
+ }
32
+ },
33
+ },
34
+ )
35
+ const client = { from: (table: string) => { calls.push(['from', [table]]); return builder } }
36
+ return { client, calls }
37
+ }
38
+
39
+ const req = (p: Partial<ServerRequest>): ServerRequest => ({
40
+ startRow: 0, endRow: 10, pageIndex: 0, pageSize: 10, sortModel: [], filterModel: {}, ...p,
41
+ })
42
+
43
+ const has = (calls: Array<[string, unknown[]]>, name: string) => calls.filter((c) => c[0] === name)
44
+
45
+ describe('createSupabaseDataSource reads', () => {
46
+ it('selects with an exact count and returns rows + rowCount', async () => {
47
+ const { client, calls } = makeClient({ data: [{ id: 1, name: 'Ada' }], count: 42, error: null })
48
+ const src = createSupabaseDataSource({ client, table: 'customers', schema })
49
+ const out = await src.getRows(req({}))
50
+ expect(has(calls, 'select')[0]![1]).toEqual(['*', { count: 'exact' }])
51
+ expect(has(calls, 'range')[0]![1]).toEqual([0, 9])
52
+ expect(out).toEqual({ rows: [{ id: 1, name: 'Ada' }], rowCount: 42 })
53
+ })
54
+
55
+ it('maps filters, sort, and global search onto the query builder', async () => {
56
+ const { client, calls } = makeClient({ data: [], count: 0, error: null })
57
+ const src = createSupabaseDataSource({ client, table: 'customers', schema })
58
+ await src.getRows(
59
+ req({
60
+ sortModel: [{ id: 'mrr', desc: true }],
61
+ filterModel: {
62
+ global: 'ada',
63
+ columns: {
64
+ name: { operator: 'contains', value: 'a' },
65
+ mrr: { operator: 'greaterThan', value: '100' },
66
+ tier: { operator: 'equals', value: '', selectedValues: ['pro', 'free'] },
67
+ },
68
+ },
69
+ }),
70
+ )
71
+ expect(has(calls, 'ilike')).toContainEqual(['ilike', ['name', '%a%']])
72
+ expect(has(calls, 'gt')).toContainEqual(['gt', ['mrr', '100']])
73
+ expect(has(calls, 'in')).toContainEqual(['in', ['tier', ['pro', 'free']]])
74
+ expect(has(calls, 'order')).toContainEqual(['order', ['mrr', { ascending: false }]])
75
+ // global search: OR of ILIKEs across text + enum columns (name, email, tier)
76
+ expect(has(calls, 'or')[0]![1][0]).toBe('name.ilike.%ada%,email.ilike.%ada%,tier.ilike.%ada%')
77
+ })
78
+
79
+ it('throws on a query error', async () => {
80
+ const { client } = makeClient({ data: null, count: null, error: { message: 'boom' } })
81
+ const src = createSupabaseDataSource({ client, table: 'customers', schema })
82
+ await expect(src.getRows(req({}))).rejects.toThrow('boom')
83
+ })
84
+ })
85
+
86
+ describe('createSupabaseDataSource writes', () => {
87
+ it('strips the primary key on insert', async () => {
88
+ const { client, calls } = makeClient({ data: { id: 9, name: 'New' }, error: null })
89
+ const src = createSupabaseDataSource({ client, table: 'customers', schema })
90
+ const row = await src.createRow({ id: 123, name: 'New' } as Partial<Customer>)
91
+ expect(has(calls, 'insert')[0]![1]).toEqual([{ name: 'New' }])
92
+ expect(row).toEqual({ id: 9, name: 'New' })
93
+ })
94
+
95
+ it('updates by the schema id field', async () => {
96
+ const { client, calls } = makeClient({ data: { id: 5, name: 'X' }, error: null })
97
+ const src = createSupabaseDataSource({ client, table: 'customers', schema })
98
+ await src.updateRow('5', { name: 'X' })
99
+ expect(has(calls, 'update')[0]![1]).toEqual([{ name: 'X' }])
100
+ expect(has(calls, 'eq')[0]![1]).toEqual(['id', '5'])
101
+ })
102
+
103
+ it('deletes by the schema id field', async () => {
104
+ const { client, calls } = makeClient({ error: null })
105
+ const src = createSupabaseDataSource({ client, table: 'customers', schema })
106
+ await src.deleteRow('7')
107
+ expect(has(calls, 'delete').length).toBe(1)
108
+ expect(has(calls, 'eq')[0]![1]).toEqual(['id', '7'])
109
+ })
110
+ })
@@ -0,0 +1,99 @@
1
+ /**
2
+ * createSupabaseDataSource - a browser-ready `ServerDataSource` over a Supabase
3
+ * table, using the `supabase-js` client (PostgREST). You bring the client (so
4
+ * there's no dependency here and Row-Level Security + auth apply per request);
5
+ * this maps the grid's sort / filter / page / CRUD onto the query builder.
6
+ *
7
+ * import { createClient } from '@supabase/supabase-js'
8
+ * const client = createClient(url, anonKey)
9
+ * const source = createSupabaseDataSource({ client, table: 'customers', schema })
10
+ *
11
+ * Global search covers the schema's text + enum columns by default; override
12
+ * with `searchColumns`. The primary key comes from the schema (`idField`) and is
13
+ * stripped from inserts (it's database-generated).
14
+ */
15
+ import type { RowData, ServerRequest, ServerResult } from '@svgrid/grid'
16
+ import { resolveIdField, type EntitySchema } from '../schema'
17
+ import { nudgeEnterprise } from '../license'
18
+ import type { WritableDataSource } from '../sveltekit/types'
19
+ import { normalizeFilters } from './filters'
20
+
21
+ /** The slice of a `supabase-js` client this adapter needs. */
22
+ export type SupabaseClientLike = {
23
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
+ from(table: string): any
25
+ }
26
+
27
+ export type SupabaseDataSourceConfig<TData extends RowData> = {
28
+ client: SupabaseClientLike
29
+ /** Table (or view) name. */
30
+ table: string
31
+ schema: EntitySchema<TData>
32
+ /**
33
+ * Columns the global search box matches (OR of ILIKEs). Defaults to the
34
+ * schema's text + enum fields.
35
+ */
36
+ searchColumns?: string[]
37
+ }
38
+
39
+ const sanitize = (term: string) => term.replace(/[%,()]/g, '')
40
+
41
+ export function createSupabaseDataSource<TData extends RowData>(
42
+ config: SupabaseDataSourceConfig<TData>,
43
+ ): WritableDataSource<TData> {
44
+ nudgeEnterprise('Studio') // soft-gate; never blocks
45
+ const { client, table, schema } = config
46
+ const idField = resolveIdField(schema)
47
+ const searchColumns =
48
+ config.searchColumns ??
49
+ schema.fields.filter((f) => f.type === 'text' || f.type === 'enum').map((f) => String(f.field))
50
+
51
+ return {
52
+ async getRows(request: ServerRequest): Promise<ServerResult<TData>> {
53
+ let q = client.from(table).select('*', { count: 'exact' })
54
+
55
+ const { predicates, search } = normalizeFilters(request.filterModel)
56
+ for (const p of predicates) {
57
+ switch (p.op) {
58
+ case 'in': q = q.in(p.column, p.values); break
59
+ case 'contains': q = q.ilike(p.column, `%${p.value}%`); break
60
+ case 'startsWith': q = q.ilike(p.column, `${p.value}%`); break
61
+ case 'eq': q = q.eq(p.column, p.value); break
62
+ case 'gt': q = q.gt(p.column, p.value); break
63
+ case 'lt': q = q.lt(p.column, p.value); break
64
+ case 'between': q = q.gte(p.column, p.value).lte(p.column, p.valueTo); break
65
+ case 'isNull': q = q.is(p.column, null); break
66
+ }
67
+ }
68
+ if (search && searchColumns.length) {
69
+ const term = sanitize(search)
70
+ q = q.or(searchColumns.map((c) => `${c}.ilike.%${term}%`).join(','))
71
+ }
72
+
73
+ for (const s of request.sortModel) q = q.order(s.id, { ascending: !s.desc })
74
+
75
+ const { data, count, error } = await q.range(request.startRow, request.endRow - 1)
76
+ if (error) throw new Error(error.message)
77
+ return { rows: (data ?? []) as ReadonlyArray<TData>, rowCount: count ?? 0 }
78
+ },
79
+
80
+ async createRow(input: Partial<TData>): Promise<TData> {
81
+ const rest = { ...input } as RowData
82
+ delete rest[idField] // primary key is database-generated
83
+ const { data, error } = await client.from(table).insert(rest).select().single()
84
+ if (error) throw new Error(error.message)
85
+ return (data ?? input) as TData
86
+ },
87
+
88
+ async updateRow(id: string, patch: Partial<TData>): Promise<TData> {
89
+ const { data, error } = await client.from(table).update(patch).eq(idField, id).select().single()
90
+ if (error) throw new Error(error.message)
91
+ return (data ?? { ...patch, [idField]: id }) as TData
92
+ },
93
+
94
+ async deleteRow(id: string): Promise<void> {
95
+ const { error } = await client.from(table).delete().eq(idField, id)
96
+ if (error) throw new Error(error.message)
97
+ },
98
+ }
99
+ }