@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,79 @@
1
+ /**
2
+ * verifyScaffold - the generator's self-check. Compiles each generated
3
+ * `.svelte` file with Svelte's own compiler and reports any errors, so
4
+ * malformed output is caught BEFORE it's written to a project. This is the
5
+ * cheap first gate of the verify loop; the deep gate (type resolution across
6
+ * real imports) is the host running the project's own `svelte-check`.
7
+ *
8
+ * The Svelte compiler is imported dynamically and best-effort: if it can't be
9
+ * resolved (e.g. a bare `npx @svgrid/mcp` with no svelte on disk), those files
10
+ * are counted as `skipped` rather than failing - the function never throws and
11
+ * carries no hard dependency, so it's safe in Node and in the browser.
12
+ *
13
+ * `.ts` files aren't compiled here (that needs the project's tsc + imports);
14
+ * they're reported as skipped.
15
+ */
16
+ import type { GeneratedFile } from './scaffold.js'
17
+
18
+ export type VerifySeverity = 'error' | 'warning'
19
+ export type VerifyIssue = { path: string; severity: VerifySeverity; message: string }
20
+ export type VerifyResult = {
21
+ /** True when no error-level issues were found (warnings are allowed). */
22
+ ok: boolean
23
+ issues: VerifyIssue[]
24
+ /** How many files were actually compiled. */
25
+ checked: number
26
+ /** How many files were skipped (non-svelte, or compiler unavailable). */
27
+ skipped: number
28
+ }
29
+
30
+ export async function verifyScaffold(
31
+ files: ReadonlyArray<GeneratedFile>,
32
+ ): Promise<VerifyResult> {
33
+ const issues: VerifyIssue[] = []
34
+ let checked = 0
35
+ let skipped = 0
36
+
37
+ let compile: ((source: string, options: Record<string, unknown>) => { warnings: Array<{ message?: string }> }) | undefined
38
+ try {
39
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
+ const mod: any = await import('svelte/compiler')
41
+ compile = mod.compile
42
+ } catch {
43
+ compile = undefined
44
+ }
45
+
46
+ for (const file of files) {
47
+ if (!file.path.endsWith('.svelte') || !compile) {
48
+ skipped++
49
+ continue
50
+ }
51
+ try {
52
+ const { warnings } = compile(file.contents, { filename: file.path, generate: 'client' })
53
+ checked++
54
+ for (const w of warnings) {
55
+ issues.push({ path: file.path, severity: 'warning', message: w.message ?? 'warning' })
56
+ }
57
+ } catch (err) {
58
+ checked++
59
+ issues.push({
60
+ path: file.path,
61
+ severity: 'error',
62
+ message: err instanceof Error ? err.message : String(err),
63
+ })
64
+ }
65
+ }
66
+
67
+ return { ok: !issues.some((i) => i.severity === 'error'), issues, checked, skipped }
68
+ }
69
+
70
+ /** One-line human summary of a verify result, for tool output / logs. */
71
+ export function summarizeVerify(result: VerifyResult): string {
72
+ if (result.checked === 0) {
73
+ return 'verification skipped (Svelte compiler unavailable) - run svelte-check in your project.'
74
+ }
75
+ const errors = result.issues.filter((i) => i.severity === 'error')
76
+ if (errors.length === 0) return `verified: ${result.checked} file(s) compile.`
77
+ return `VERIFICATION FAILED (${errors.length} error(s)):\n` +
78
+ errors.map((e) => ` ${e.path}: ${e.message}`).join('\n')
79
+ }
@@ -0,0 +1,104 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { ServerRequest } from '@svgrid/grid'
3
+ import type { EntitySchema } from '../schema'
4
+ import { createInMemoryDataSource } from './in-memory'
5
+
6
+ type Customer = { id: string; name: string; age: number; tier: string }
7
+
8
+ const schema: EntitySchema<Customer> = {
9
+ name: 'customers',
10
+ fields: [
11
+ { field: 'id', type: 'text', primaryKey: true },
12
+ { field: 'name', type: 'text' },
13
+ { field: 'age', type: 'number' },
14
+ { field: 'tier', type: 'enum' },
15
+ ],
16
+ }
17
+
18
+ const seed: Customer[] = [
19
+ { id: '1', name: 'Ann', age: 30, tier: 'pro' },
20
+ { id: '2', name: 'Bob', age: 41, tier: 'free' },
21
+ { id: '3', name: 'Cara', age: 25, tier: 'pro' },
22
+ { id: '4', name: 'Dan', age: 55, tier: 'free' },
23
+ { id: '5', name: 'Eve', age: 38, tier: 'pro' },
24
+ ]
25
+
26
+ function req(partial: Partial<ServerRequest>): ServerRequest {
27
+ return { startRow: 0, endRow: 50, pageIndex: 0, pageSize: 50, sortModel: [], filterModel: {}, ...partial }
28
+ }
29
+
30
+ describe('createInMemoryDataSource reads', () => {
31
+ it('filters with a numeric operator and reports the filtered count', async () => {
32
+ const src = createInMemoryDataSource(seed, schema)
33
+ const { rows, rowCount } = await src.getRows(
34
+ req({ filterModel: { columns: { age: { operator: 'greaterThan', value: '35' } } } }),
35
+ )
36
+ expect(rows.map((r) => r.name).sort()).toEqual(['Bob', 'Dan', 'Eve'])
37
+ expect(rowCount).toBe(3)
38
+ })
39
+
40
+ it('runs a case-insensitive global search over textual fields', async () => {
41
+ const src = createInMemoryDataSource(seed, schema)
42
+ const { rows } = await src.getRows(req({ filterModel: { global: 'PRO' } }))
43
+ expect(rows.map((r) => r.id).sort()).toEqual(['1', '3', '5'])
44
+ })
45
+
46
+ it('sorts descending and pages', async () => {
47
+ const src = createInMemoryDataSource(seed, schema)
48
+ const { rows, rowCount } = await src.getRows(
49
+ req({ sortModel: [{ id: 'age', desc: true }], startRow: 0, pageSize: 2 }),
50
+ )
51
+ expect(rows.map((r) => r.age)).toEqual([55, 41])
52
+ expect(rowCount).toBe(5)
53
+ })
54
+
55
+ it('an `in` (facet) filter selects the listed values', async () => {
56
+ const src = createInMemoryDataSource(seed, schema)
57
+ const { rows } = await src.getRows(
58
+ req({ filterModel: { columns: { tier: { operator: 'equals', value: '', selectedValues: ['free'] } } } }),
59
+ )
60
+ expect(rows.map((r) => r.name).sort()).toEqual(['Bob', 'Dan'])
61
+ })
62
+ })
63
+
64
+ describe('createInMemoryDataSource writes', () => {
65
+ it('creates, updates, and deletes, reflected in subsequent reads', async () => {
66
+ const src = createInMemoryDataSource(seed, schema)
67
+
68
+ const created = await src.createRow({ id: '6', name: 'Fay', age: 22, tier: 'free' })
69
+ expect(created.name).toBe('Fay')
70
+ expect((await src.getRows(req({}))).rowCount).toBe(6)
71
+
72
+ const updated = await src.updateRow('6', { age: 23 })
73
+ expect(updated.age).toBe(23)
74
+
75
+ await src.deleteRow('1')
76
+ const after = await src.getRows(req({}))
77
+ expect(after.rowCount).toBe(5)
78
+ expect(after.rows.some((r) => r.id === '1')).toBe(false)
79
+ })
80
+
81
+ it('throws when updating a missing row', async () => {
82
+ const src = createInMemoryDataSource(seed, schema)
83
+ await expect(src.updateRow('999', { age: 1 })).rejects.toThrow(/no row with id="999"/)
84
+ })
85
+
86
+ it('getAggregate groups + reduces, honoring a filter', async () => {
87
+ const src = createInMemoryDataSource(seed, schema)
88
+ expect(await src.getAggregate({ dimension: 'tier', reduce: 'count' })).toEqual([
89
+ { category: 'pro', value: 3 },
90
+ { category: 'free', value: 2 },
91
+ ])
92
+ // filtered: only age > 35 -> Bob(free), Dan(free), Eve(pro)
93
+ const filtered = await src.getAggregate({
94
+ dimension: 'tier', reduce: 'count',
95
+ filterModel: { columns: { age: { operator: 'greaterThan', value: '35' } } },
96
+ })
97
+ expect(filtered).toEqual([{ category: 'free', value: 2 }, { category: 'pro', value: 1 }])
98
+ })
99
+
100
+ it('getAggregate with no dimension is a single grand total (a KPI)', async () => {
101
+ const src = createInMemoryDataSource(seed, schema)
102
+ expect(await src.getAggregate({ reduce: 'count' })).toEqual([{ category: '', value: 5 }])
103
+ })
104
+ })
@@ -0,0 +1,129 @@
1
+ /**
2
+ * In-memory reference `ServerDataSource`. Applies a `QueryPlan` to a plain
3
+ * array - filter, global search, sort, page - and supports the full CRUD
4
+ * contract. It is the executable specification of what a backend adapter must
5
+ * do, and is genuinely useful on its own for small datasets, tests, demos,
6
+ * and prototyping a schema before a database exists behind it.
7
+ */
8
+ import type { RowData, ServerRequest, ServerResult } from '@svgrid/grid'
9
+ import { resolveIdField, type EntitySchema } from '../schema'
10
+ import { planQuery, type PlanPredicate, type QueryPlan } from './query-plan'
11
+ import type { WritableDataSource } from './types'
12
+ import { aggregateRows, type AggregateBucket, type AggregateRequest, type AggregateSource } from '../sources/aggregate'
13
+
14
+ function asString(v: unknown): string {
15
+ return v == null ? '' : String(v)
16
+ }
17
+
18
+ function num(v: unknown): number {
19
+ return typeof v === 'number' ? v : Number(v)
20
+ }
21
+
22
+ function matchesPredicate(row: RowData, p: PlanPredicate): boolean {
23
+ const cell = row[p.field]
24
+ switch (p.op) {
25
+ case 'eq':
26
+ return asString(cell) === asString(p.value)
27
+ case 'contains':
28
+ return asString(cell).toLowerCase().includes(asString(p.value).toLowerCase())
29
+ case 'startsWith':
30
+ return asString(cell).toLowerCase().startsWith(asString(p.value).toLowerCase())
31
+ case 'gt':
32
+ return typeof p.value === 'number' ? num(cell) > p.value : asString(cell) > asString(p.value)
33
+ case 'lt':
34
+ return typeof p.value === 'number' ? num(cell) < p.value : asString(cell) < asString(p.value)
35
+ case 'between': {
36
+ if (typeof p.value === 'number' && typeof p.valueTo === 'number') {
37
+ return num(cell) >= p.value && num(cell) <= p.valueTo
38
+ }
39
+ return asString(cell) >= asString(p.value) && asString(cell) <= asString(p.valueTo)
40
+ }
41
+ case 'isBlank':
42
+ return cell == null || cell === ''
43
+ case 'in':
44
+ return (p.values ?? []).some((v) => asString(v) === asString(cell))
45
+ default:
46
+ return true
47
+ }
48
+ }
49
+
50
+ function matches(row: RowData, plan: QueryPlan): boolean {
51
+ if (plan.search) {
52
+ const term = plan.search.term.toLowerCase()
53
+ const hit = plan.search.fields.some((f) => asString(row[f]).toLowerCase().includes(term))
54
+ if (!hit) return false
55
+ }
56
+ return plan.where.every((p) => matchesPredicate(row, p))
57
+ }
58
+
59
+ function sortRows<T extends RowData>(rows: T[], orderBy: QueryPlan['orderBy']): T[] {
60
+ if (orderBy.length === 0) return rows
61
+ // Stable multi-key sort: decorate with index, compare keys in order, fall back to index.
62
+ return rows
63
+ .map((row, index) => ({ row, index }))
64
+ .sort((a, b) => {
65
+ for (const { field, desc } of orderBy) {
66
+ const av = a.row[field]
67
+ const bv = b.row[field]
68
+ let cmp: number
69
+ if (typeof av === 'number' && typeof bv === 'number') cmp = av - bv
70
+ else cmp = asString(av).localeCompare(asString(bv))
71
+ if (cmp !== 0) return desc ? -cmp : cmp
72
+ }
73
+ return a.index - b.index
74
+ })
75
+ .map((d) => d.row)
76
+ }
77
+
78
+ export function createInMemoryDataSource<TData extends RowData>(
79
+ initial: ReadonlyArray<TData>,
80
+ schema: EntitySchema<TData>,
81
+ ): WritableDataSource<TData> & AggregateSource & { rows(): ReadonlyArray<TData> } {
82
+ let store: TData[] = [...initial]
83
+ const idField = resolveIdField(schema)
84
+
85
+ return {
86
+ async getRows(request: ServerRequest): Promise<ServerResult<TData>> {
87
+ const plan = planQuery(schema, request)
88
+ const filtered = sortRows(
89
+ store.filter((r) => matches(r, plan)),
90
+ plan.orderBy,
91
+ )
92
+ return {
93
+ rows: filtered.slice(plan.offset, plan.offset + plan.limit),
94
+ rowCount: filtered.length,
95
+ }
96
+ },
97
+ async createRow(input: Partial<TData>): Promise<TData> {
98
+ const row = { ...input } as TData
99
+ store = [...store, row]
100
+ return row
101
+ },
102
+ async updateRow(id: string, patch: Partial<TData>): Promise<TData> {
103
+ let updated: TData | undefined
104
+ store = store.map((r) => {
105
+ if (asString(r[idField]) === id) {
106
+ updated = { ...r, ...patch }
107
+ return updated
108
+ }
109
+ return r
110
+ })
111
+ if (!updated) throw new Error(`createInMemoryDataSource: no row with ${idField}="${id}"`)
112
+ return updated
113
+ },
114
+ async deleteRow(id: string): Promise<void> {
115
+ store = store.filter((r) => asString(r[idField]) !== id)
116
+ },
117
+ async getAggregate(request: AggregateRequest): Promise<AggregateBucket[]> {
118
+ // Apply the (optional) filter using the same plan machinery as getRows,
119
+ // over the whole store (no paging), then reduce in memory.
120
+ const plan = planQuery(schema, {
121
+ startRow: 0, endRow: store.length, pageIndex: 0, pageSize: store.length,
122
+ sortModel: [], filterModel: request.filterModel ?? {},
123
+ })
124
+ const filtered = store.filter((r) => matches(r, plan))
125
+ return aggregateRows(filtered, request)
126
+ },
127
+ rows: () => store,
128
+ }
129
+ }
@@ -0,0 +1,23 @@
1
+ export {
2
+ planQuery,
3
+ coerce,
4
+ type QueryPlan,
5
+ type PlanPredicate,
6
+ type PlanOp,
7
+ } from './query-plan'
8
+ export { createInMemoryDataSource } from './in-memory'
9
+ export {
10
+ createKitDataSource,
11
+ createKitHandlers,
12
+ type KitDataSourceOptions,
13
+ type KitHandlerOptions,
14
+ type KitHandlers,
15
+ type KitMessage,
16
+ } from './transport'
17
+ export { planToSql, type SqlDialect, type SqlPlan } from './sql'
18
+ export {
19
+ createSqlDataSource,
20
+ type SqlExecutor,
21
+ type SqlDataSourceConfig,
22
+ } from './sql-source'
23
+ export type { WritableDataSource } from './types'
@@ -0,0 +1,109 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { ServerRequest } from '@svgrid/grid'
3
+ import type { EntitySchema } from '../schema'
4
+ import { planQuery } from './query-plan'
5
+
6
+ type Customer = { id: string; name: string; age: number; tier: string; active: boolean }
7
+
8
+ const schema: EntitySchema<Customer> = {
9
+ name: 'customers',
10
+ fields: [
11
+ { field: 'id', type: 'text', primaryKey: true },
12
+ { field: 'name', type: 'text' },
13
+ { field: 'age', type: 'number' },
14
+ { field: 'tier', type: 'enum', options: [{ value: 'free', label: 'Free' }, { value: 'pro', label: 'Pro' }] },
15
+ { field: 'active', type: 'boolean' },
16
+ ],
17
+ }
18
+
19
+ function req(partial: Partial<ServerRequest>): ServerRequest {
20
+ return {
21
+ startRow: 0,
22
+ endRow: 50,
23
+ pageIndex: 0,
24
+ pageSize: 50,
25
+ sortModel: [],
26
+ filterModel: {},
27
+ ...partial,
28
+ }
29
+ }
30
+
31
+ describe('planQuery', () => {
32
+ it('maps grid operators to plan predicates', () => {
33
+ const plan = planQuery(
34
+ schema,
35
+ req({ filterModel: { columns: { name: { operator: 'contains', value: 'ann' } } } }),
36
+ )
37
+ expect(plan.where).toEqual([{ field: 'name', op: 'contains', value: 'ann' }])
38
+ })
39
+
40
+ it('coerces numeric operands to numbers', () => {
41
+ const plan = planQuery(
42
+ schema,
43
+ req({ filterModel: { columns: { age: { operator: 'greaterThan', value: '30' } } } }),
44
+ )
45
+ expect(plan.where[0]).toEqual({ field: 'age', op: 'gt', value: 30 })
46
+ })
47
+
48
+ it('turns selectedValues into an `in` predicate', () => {
49
+ const plan = planQuery(
50
+ schema,
51
+ req({ filterModel: { columns: { tier: { operator: 'equals', value: '', selectedValues: ['free', 'pro'] } } } }),
52
+ )
53
+ expect(plan.where[0]).toEqual({ field: 'tier', op: 'in', values: ['free', 'pro'] })
54
+ })
55
+
56
+ it('coerces both bounds of a between', () => {
57
+ const plan = planQuery(
58
+ schema,
59
+ req({ filterModel: { columns: { age: { operator: 'between', value: '20', valueTo: '40' } } } }),
60
+ )
61
+ expect(plan.where[0]).toEqual({ field: 'age', op: 'between', value: 20, valueTo: 40 })
62
+ })
63
+
64
+ it('whitelists fields: unknown columns are dropped', () => {
65
+ const plan = planQuery(
66
+ schema,
67
+ req({ filterModel: { columns: { evil: { operator: 'contains', value: 'x' } } } }),
68
+ )
69
+ expect(plan.where).toHaveLength(0)
70
+ })
71
+
72
+ it('drops empty operator values but keeps isBlank', () => {
73
+ const plan = planQuery(
74
+ schema,
75
+ req({
76
+ filterModel: {
77
+ columns: {
78
+ name: { operator: 'contains', value: '' },
79
+ id: { operator: 'isBlank', value: '' },
80
+ },
81
+ },
82
+ }),
83
+ )
84
+ expect(plan.where).toEqual([{ field: 'id', op: 'isBlank' }])
85
+ })
86
+
87
+ it('builds a search over textual fields only', () => {
88
+ const plan = planQuery(schema, req({ filterModel: { global: ' acme ' } }))
89
+ expect(plan.search).toEqual({ term: 'acme', fields: ['name', 'tier'] })
90
+ })
91
+
92
+ it('is null-search when no global term', () => {
93
+ expect(planQuery(schema, req({})).search).toBeNull()
94
+ })
95
+
96
+ it('maps sort, dropping unknown sort fields', () => {
97
+ const plan = planQuery(
98
+ schema,
99
+ req({ sortModel: [{ id: 'age', desc: true }, { id: 'ghost', desc: false }] }),
100
+ )
101
+ expect(plan.orderBy).toEqual([{ field: 'age', desc: true }])
102
+ })
103
+
104
+ it('carries paging through as limit/offset', () => {
105
+ const plan = planQuery(schema, req({ startRow: 100, pageSize: 25 }))
106
+ expect(plan.limit).toBe(25)
107
+ expect(plan.offset).toBe(100)
108
+ })
109
+ })
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The query-plan seam. `planQuery` turns the grid's `ServerRequest` (sort +
3
+ * filter + paging) into a neutral, backend-agnostic `QueryPlan`. Every backend
4
+ * adapter - the in-memory reference source, `planToSql` for any SQL database,
5
+ * a Drizzle/Supabase mapping - consumes this one plan, so the request-shaping
6
+ * logic (operator mapping, type coercion, field whitelisting) lives and is
7
+ * tested in exactly one place.
8
+ *
9
+ * Security note: only fields declared on the `EntitySchema` reach the plan.
10
+ * Unknown column names in the request are dropped, so a client cannot smuggle
11
+ * arbitrary identifiers through to SQL.
12
+ */
13
+ import type { RowData, ServerRequest } from '@svgrid/grid'
14
+ import type { EntityFieldType, EntitySchema } from '../schema'
15
+
16
+ /** Normalized predicate operators (a stable superset of the grid's filter operators). */
17
+ export type PlanOp = 'eq' | 'contains' | 'startsWith' | 'gt' | 'lt' | 'between' | 'isBlank' | 'in'
18
+
19
+ export type PlanPredicate = {
20
+ field: string
21
+ op: PlanOp
22
+ /** Single operand (eq / contains / startsWith / gt / lt, and the low bound of between). */
23
+ value?: unknown
24
+ /** Upper bound for `between`. */
25
+ valueTo?: unknown
26
+ /** Operands for `in` (set / facet filter). */
27
+ values?: unknown[]
28
+ }
29
+
30
+ export type QueryPlan = {
31
+ /** AND-combined column predicates. */
32
+ where: PlanPredicate[]
33
+ /** Global free-text search: OR `contains` across these textual fields. Null when no search term. */
34
+ search: { term: string; fields: string[] } | null
35
+ orderBy: Array<{ field: string; desc: boolean }>
36
+ limit: number
37
+ offset: number
38
+ }
39
+
40
+ /** Grid filter operator -> normalized plan operator. Unmapped operators are ignored. */
41
+ const OP_MAP: Record<string, PlanOp> = {
42
+ equals: 'eq',
43
+ contains: 'contains',
44
+ startsWith: 'startsWith',
45
+ greaterThan: 'gt',
46
+ lessThan: 'lt',
47
+ between: 'between',
48
+ isBlank: 'isBlank',
49
+ }
50
+
51
+ /** Field types that global text search scans. */
52
+ const TEXTUAL: ReadonlySet<EntityFieldType> = new Set<EntityFieldType>(['text', 'enum'])
53
+
54
+ /** Coerce a raw string request value to the field's runtime type for correct comparisons. */
55
+ export function coerce(type: EntityFieldType, raw: unknown): unknown {
56
+ if (raw == null) return raw
57
+ switch (type) {
58
+ case 'number': {
59
+ const n = Number(raw)
60
+ return Number.isFinite(n) ? n : undefined
61
+ }
62
+ case 'boolean':
63
+ return raw === true || raw === 'true'
64
+ default:
65
+ // text / date / dateString / datetime / enum / relation / json: compared as strings
66
+ return typeof raw === 'string' ? raw : String(raw)
67
+ }
68
+ }
69
+
70
+ export function planQuery<TData extends RowData>(
71
+ schema: EntitySchema<TData>,
72
+ request: ServerRequest,
73
+ ): QueryPlan {
74
+ const fields = new Map(schema.fields.map((f) => [f.field, f]))
75
+ const where: PlanPredicate[] = []
76
+ const fm = request.filterModel ?? {}
77
+
78
+ for (const [field, spec] of Object.entries(fm.columns ?? {})) {
79
+ const def = fields.get(field)
80
+ if (!def) continue // whitelist: ignore columns not on the schema
81
+
82
+ // A facet / set selection wins over the operator filter.
83
+ if (spec.selectedValues && spec.selectedValues.length > 0) {
84
+ where.push({ field, op: 'in', values: spec.selectedValues.map((v) => coerce(def.type, v)) })
85
+ continue
86
+ }
87
+
88
+ const op = OP_MAP[spec.operator]
89
+ if (!op) continue
90
+
91
+ if (op === 'isBlank') {
92
+ where.push({ field, op })
93
+ continue
94
+ }
95
+ if (op === 'between') {
96
+ where.push({
97
+ field,
98
+ op,
99
+ value: coerce(def.type, spec.value),
100
+ valueTo: coerce(def.type, spec.valueTo),
101
+ })
102
+ continue
103
+ }
104
+ if (spec.value === '' || spec.value == null) continue
105
+ where.push({ field, op, value: coerce(def.type, spec.value) })
106
+ }
107
+
108
+ const term = (fm.global ?? '').trim()
109
+ const search =
110
+ term.length > 0
111
+ ? {
112
+ term,
113
+ // Textual, non-key fields: searching a primary key by substring is noise.
114
+ fields: schema.fields
115
+ .filter((f) => TEXTUAL.has(f.type) && !f.primaryKey && f.field !== schema.idField)
116
+ .map((f) => f.field),
117
+ }
118
+ : null
119
+
120
+ const orderBy = (request.sortModel ?? [])
121
+ .filter((s) => fields.has(s.id))
122
+ .map((s) => ({ field: s.id, desc: !!s.desc }))
123
+
124
+ return { where, search, orderBy, limit: request.pageSize, offset: request.startRow }
125
+ }