@svgrid/enterprise 2.2.1 → 2.3.1
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.
- package/README.md +95 -81
- package/dist/cdn/svgrid-enterprise.svelte-external.js +26642 -11252
- package/dist/designer/assets/GridMenus-BtWVk9Ab.js +7 -0
- package/dist/designer/assets/SvGridChartPanel-DWlBO2SD.js +10 -0
- package/dist/designer/assets/SvGridChartView-8c8Mb4j8.js +1 -0
- package/dist/designer/assets/SvGridChartView-DX9HfkBR.css +1 -0
- package/dist/designer/assets/index-DsDgp9Xq.js +78758 -0
- package/dist/designer/assets/index-tTY_Dx4P.css +1 -0
- package/dist/designer/assets/jszip.min-fkJdmAmj.js +2 -0
- package/dist/designer/assets/pdfmake-DeCsnyl9.js +242 -0
- package/dist/designer/assets/smart.export-BZlSCE8T.js +35 -0
- package/dist/designer/assets/vfs_fonts-eX2NpmfX.js +1 -0
- package/dist/designer/index.html +13 -0
- package/dist/node/studio.js +15304 -2708
- package/package.json +35 -11
- package/src/SvAlertRuleEditor.svelte +294 -0
- package/src/SvAlertsManager.svelte +210 -0
- package/src/SvAlertsPanel.svelte +129 -0
- package/src/SvBoard.svelte +3 -1
- package/src/SvExpressionEditor.svelte +341 -0
- package/src/SvGridAlerts.dom.test.ts +113 -0
- package/src/SvGridAlerts.svelte +265 -0
- package/src/SvGridBoard.svelte +2358 -0
- package/src/SvGridEditPanel.svelte +849 -794
- package/src/SvGridScheduler.svelte +5358 -4410
- package/src/SvPivotDesigner.svelte +3 -3
- package/src/SvRecordDetail.svelte +6 -2
- package/src/SvSchedule.svelte +3 -1
- package/src/{ai-export-pdf.test.ts → ai-export-pdf.dom.test.ts} +77 -74
- package/src/{ai-export-xlsx.test.ts → ai-export-xlsx.dom.test.ts} +90 -87
- package/src/{ai-export.test.ts → ai-export.dom.test.ts} +114 -110
- package/src/alerts/alert-engine-attach.ts +165 -0
- package/src/alerts/alert-engine.test.ts +135 -0
- package/src/alerts/alert-engine.ts +260 -0
- package/src/alerts/alert-formats.test.ts +87 -0
- package/src/alerts/alert-formats.ts +77 -0
- package/src/alerts/alert-observer.test.ts +189 -0
- package/src/alerts/alert-observer.ts +208 -0
- package/src/alerts/alert-scheduler.ts +96 -0
- package/src/alerts/alert-storage.test.ts +54 -0
- package/src/alerts/alert-storage.ts +116 -0
- package/src/alerts/alert-store.svelte.ts +80 -0
- package/src/alerts/alert-types.ts +94 -0
- package/src/alerts.ts +28 -0
- package/src/board.dom.test.ts +941 -0
- package/src/board.ts +36 -0
- package/src/export-ooxml.ts +4 -0
- package/src/export-xls.ts +3 -0
- package/src/export.ts +6 -0
- package/src/expressions/evaluate.test.ts +111 -0
- package/src/expressions/evaluate.ts +237 -0
- package/src/expressions/expression-columns.ts +133 -0
- package/src/expressions/expression-types.ts +84 -0
- package/src/expressions/parse.test.ts +106 -0
- package/src/expressions/parse.ts +610 -0
- package/src/import.test.ts +1 -1
- package/src/import.ts +3 -1
- package/src/index.ts +192 -46
- package/src/install.ts +12 -2
- package/src/pivot-enable.ts +44 -0
- package/src/pivot.test.ts +0 -1
- package/src/scheduler-assignments.test.ts +97 -0
- package/src/scheduler-assignments.ts +134 -0
- package/src/scheduler-axis.test.ts +108 -0
- package/src/scheduler-axis.ts +238 -0
- package/src/scheduler-booking.test.ts +57 -0
- package/src/scheduler-booking.ts +63 -0
- package/src/scheduler-config.ts +179 -0
- package/src/scheduler-dependencies.test.ts +155 -0
- package/src/scheduler-dependencies.ts +223 -0
- package/src/scheduler-freebusy.test.ts +41 -0
- package/src/scheduler-freebusy.ts +36 -0
- package/src/scheduler-heatmap.test.ts +39 -0
- package/src/scheduler-heatmap.ts +55 -0
- package/src/scheduler-resource-tree.test.ts +84 -0
- package/src/scheduler-resource-tree.ts +107 -0
- package/src/scheduler-slots.test.ts +53 -0
- package/src/scheduler-slots.ts +94 -0
- package/src/scheduler-summary.test.ts +47 -0
- package/src/scheduler-summary.ts +81 -0
- package/src/schema-designer.ts +1 -1
- package/src/sources/index.ts +1 -1
- package/src/sources/introspect-supabase.test.ts +13 -1
- package/src/sources/introspect-supabase.ts +20 -0
- package/src/studio/copilot-core.test.ts +45 -0
- package/src/studio/copilot-core.ts +65 -0
- package/src/studio/deploy-cli.test.ts +56 -0
- package/src/studio/deploy-cli.ts +100 -0
- package/src/studio/emit-project.test.ts +800 -24
- package/src/studio/emit-project.ts +1307 -135
- package/src/studio/emit-schema.test.ts +17 -0
- package/src/studio/emit-schema.ts +182 -41
- package/src/studio/index.ts +59 -1
- package/src/studio/init-flow.test.ts +239 -0
- package/src/studio/init-flow.ts +358 -0
- package/src/studio/introspect-openapi.test.ts +84 -0
- package/src/studio/introspect-openapi.ts +252 -0
- package/src/studio/project.test.ts +57 -1
- package/src/studio/project.ts +302 -8
- package/src/studio/samples/crm.ts +282 -258
- package/src/studio/samples/datasets.test.ts +84 -0
- package/src/studio/samples/datasets.ts +340 -0
- package/src/studio/samples/fleet.ts +213 -186
- package/src/studio/samples/insurance.ts +223 -195
- package/src/studio/samples/inventory.ts +213 -182
- package/src/studio/samples/live-data.test.ts +99 -98
- package/src/studio/samples/live-data.ts +8 -10
- package/src/studio/samples/projects.ts +212 -190
- package/src/studio/samples/samples.test.ts +268 -216
- package/src/studio/samples/shared.ts +22 -145
- package/src/studio/samples/starter.ts +251 -0
- package/src/studio/samples/support.ts +209 -184
- package/src/studio/screen-suites.test.ts +226 -0
- package/src/studio/screen-suites.ts +445 -0
- package/src/studio/ui-components-surface.test.ts +185 -0
- package/src/studio/ui-components.generated.ts +7154 -0
- package/src/studio/ui-components.ts +273 -3
- package/src/sveltekit/index.ts +1 -0
- package/src/sveltekit/sql-source.test.ts +13 -0
- package/src/sveltekit/sql-source.ts +12 -7
- package/src/sveltekit/transport-scope.test.ts +125 -0
- package/src/sveltekit/transport.ts +76 -2
- package/src/upgrade-prompt.ts +2 -2
- package/src/watermark.ts +2 -2
- package/src/ai.test.ts +0 -522
- package/src/ai.ts +0 -1388
|
@@ -109,9 +109,29 @@ export type KitValidateContext<TData extends RowData> = {
|
|
|
109
109
|
event: { request: Request; locals?: Record<string, unknown> }
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
+
/** A row-scoping rule: every row this caller may touch has `field === value`. */
|
|
113
|
+
export type KitScope = { field: string; value: unknown }
|
|
114
|
+
|
|
112
115
|
export type KitHandlerOptions<TData extends RowData> = {
|
|
113
116
|
schema: EntitySchema<TData>
|
|
114
117
|
source: ServerDataSource<TData>
|
|
118
|
+
/**
|
|
119
|
+
* Restrict every operation to rows matching one column - the mechanism behind
|
|
120
|
+
* multi-tenancy (`field: 'tenantId'`), and usable for any "you only see your
|
|
121
|
+
* own rows" rule.
|
|
122
|
+
*
|
|
123
|
+
* Enforced on all four paths, because scoping reads alone is not isolation:
|
|
124
|
+
* - **read**: the predicate is merged into the query's filter model;
|
|
125
|
+
* - **create**: the value is stamped onto the row, overriding whatever the
|
|
126
|
+
* client sent;
|
|
127
|
+
* - **update / delete**: the target row is re-read under the scope first, and
|
|
128
|
+
* the write is rejected with `403` if it isn't the caller's - otherwise
|
|
129
|
+
* guessing an id would reach across tenants.
|
|
130
|
+
*
|
|
131
|
+
* Return `null` to apply no scope (e.g. a super-admin). Throwing rejects the
|
|
132
|
+
* request, which is the safer default when a tenant cannot be resolved.
|
|
133
|
+
*/
|
|
134
|
+
scope?: (ctx: { event: { request: Request; locals?: Record<string, unknown> } }) => KitScope | null | Promise<KitScope | null>
|
|
115
135
|
/**
|
|
116
136
|
* Optional server-side guard run BEFORE every op. Return `false` (or throw) to
|
|
117
137
|
* reject the request with `403`. Receives the SvelteKit event, so you can read
|
|
@@ -188,7 +208,7 @@ const actionOf = <TData extends RowData>(msg: KitMessage<TData>): KitAction =>
|
|
|
188
208
|
export function createKitHandlers<TData extends RowData>(
|
|
189
209
|
options: KitHandlerOptions<TData>,
|
|
190
210
|
): KitHandlers {
|
|
191
|
-
const { source, authorize, validate, audit, hooks } = options
|
|
211
|
+
const { source, authorize, validate, audit, hooks, scope } = options
|
|
192
212
|
const idField = options.schema.idField ?? options.schema.fields.find((f) => f.primaryKey)?.field ?? 'id'
|
|
193
213
|
const rowId = (row: unknown): string | null => {
|
|
194
214
|
const v = (row as Record<string, unknown> | null)?.[idField]
|
|
@@ -237,13 +257,62 @@ export function createKitHandlers<TData extends RowData>(
|
|
|
237
257
|
}
|
|
238
258
|
}
|
|
239
259
|
|
|
260
|
+
// Resolve the row scope once per request. A thrown resolver is a rejection,
|
|
261
|
+
// not a 500: "I can't tell which tenant you are" must not fall through to
|
|
262
|
+
// an unscoped query.
|
|
263
|
+
let activeScope: KitScope | null = null
|
|
264
|
+
if (scope) {
|
|
265
|
+
try {
|
|
266
|
+
activeScope = (await scope({ event: { request, locals: event?.locals } })) ?? null
|
|
267
|
+
} catch (err) {
|
|
268
|
+
return jsonResponse({ error: err instanceof Error ? err.message : 'forbidden' }, 403)
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/** True when `id` exists AND belongs to the caller's scope. */
|
|
272
|
+
const ownsRow = async (id: string): Promise<boolean> => {
|
|
273
|
+
if (!activeScope) return true
|
|
274
|
+
const idField = options.schema.idField ?? options.schema.fields.find((f) => f.primaryKey)?.field ?? 'id'
|
|
275
|
+
const { rows } = await source.getRows({
|
|
276
|
+
startRow: 0,
|
|
277
|
+
endRow: 1,
|
|
278
|
+
pageIndex: 0,
|
|
279
|
+
pageSize: 1,
|
|
280
|
+
sortModel: [],
|
|
281
|
+
filterModel: {
|
|
282
|
+
columns: {
|
|
283
|
+
[idField]: { operator: 'equals' as const, value: id },
|
|
284
|
+
[activeScope.field]: { operator: 'equals' as const, value: String(activeScope.value) },
|
|
285
|
+
},
|
|
286
|
+
},
|
|
287
|
+
})
|
|
288
|
+
return rows.length > 0
|
|
289
|
+
}
|
|
290
|
+
|
|
240
291
|
try {
|
|
241
292
|
if (msg.kind === 'query') {
|
|
242
|
-
|
|
293
|
+
// Merge the scope into the requested filter. Written last so a client
|
|
294
|
+
// that sends its own `tenantId` filter cannot widen the scope.
|
|
295
|
+
const request = activeScope
|
|
296
|
+
? {
|
|
297
|
+
...msg.request,
|
|
298
|
+
filterModel: {
|
|
299
|
+
...msg.request.filterModel,
|
|
300
|
+
columns: {
|
|
301
|
+
...(msg.request.filterModel?.columns ?? {}),
|
|
302
|
+
[activeScope.field]: { operator: 'equals' as const, value: String(activeScope.value) },
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
: msg.request
|
|
307
|
+
const result = await source.getRows(request)
|
|
243
308
|
return jsonResponse(result)
|
|
244
309
|
}
|
|
245
310
|
if (msg.kind === 'mutate') {
|
|
246
311
|
const evt = { request, locals: event?.locals }
|
|
312
|
+
// Cross-tenant writes: reject before the source sees the id.
|
|
313
|
+
if (activeScope && (msg.op === 'update' || msg.op === 'delete')) {
|
|
314
|
+
if (!(await ownsRow(msg.id))) return jsonResponse({ error: 'forbidden' }, 403)
|
|
315
|
+
}
|
|
247
316
|
// A `before*` hook throwing is a business-rule rejection -> 422 (not a 500).
|
|
248
317
|
const runBefore = async <R>(fn: () => Promise<R>): Promise<R | Response> => {
|
|
249
318
|
try { return await fn() } catch (err) { return jsonResponse({ error: err instanceof Error ? err.message : 'rejected' }, 422) }
|
|
@@ -256,6 +325,9 @@ export function createKitHandlers<TData extends RowData>(
|
|
|
256
325
|
if (r instanceof Response) return r
|
|
257
326
|
if (r) input = r as Partial<TData>
|
|
258
327
|
}
|
|
328
|
+
// Stamp the scope LAST - after the before-hook - so neither the client
|
|
329
|
+
// nor a business rule can write a row into another tenant.
|
|
330
|
+
if (activeScope) input = { ...input, [activeScope.field]: activeScope.value } as Partial<TData>
|
|
259
331
|
const row = await source.createRow(input)
|
|
260
332
|
if (hooks?.afterCreate) await hooks.afterCreate({ row, event: evt })
|
|
261
333
|
await fireAudit({ action: 'create', id: rowId(row), values: input, result: row, event: evt })
|
|
@@ -269,6 +341,8 @@ export function createKitHandlers<TData extends RowData>(
|
|
|
269
341
|
if (r instanceof Response) return r
|
|
270
342
|
if (r) patch = r as Partial<TData>
|
|
271
343
|
}
|
|
344
|
+
// A patch must not be able to hand the row to another tenant.
|
|
345
|
+
if (activeScope) patch = { ...patch, [activeScope.field]: activeScope.value } as Partial<TData>
|
|
272
346
|
const row = await source.updateRow(msg.id, patch)
|
|
273
347
|
if (hooks?.afterUpdate) await hooks.afterUpdate({ id: msg.id, row, event: evt })
|
|
274
348
|
await fireAudit({ action: 'update', id: msg.id, values: patch, result: row, event: evt })
|
package/src/upgrade-prompt.ts
CHANGED
|
@@ -18,10 +18,10 @@
|
|
|
18
18
|
// bundle, works in any host app regardless of its styling.
|
|
19
19
|
|
|
20
20
|
const CARD_ATTR = 'data-svgrid-enterprise-upgrade'
|
|
21
|
-
const PRICING_URL = 'https://
|
|
21
|
+
const PRICING_URL = 'https://svgrid.com/pricing'
|
|
22
22
|
// ?ref=in-app lets us measure how many trials start from this exact prompt
|
|
23
23
|
// vs. the pricing page itself - the whole point of a moment-of-intent CTA.
|
|
24
|
-
const TRIAL_URL = 'https://
|
|
24
|
+
const TRIAL_URL = 'https://svgrid.com/pricing?ref=in-app&utm_source=svgrid-enterprise&utm_medium=upgrade-prompt'
|
|
25
25
|
|
|
26
26
|
let shownThisSession = false
|
|
27
27
|
|
package/src/watermark.ts
CHANGED
|
@@ -9,8 +9,8 @@ const WATERMARK_ATTR = 'data-svgrid-enterprise-watermark'
|
|
|
9
9
|
// Marks a grid that has already shown (and faded) its watermark, so the
|
|
10
10
|
// MutationObserver doesn't re-add it once it fades out and is removed.
|
|
11
11
|
const NUDGED_ATTR = 'data-svgrid-enterprise-nudged'
|
|
12
|
-
const HOMEPAGE_URL = 'https://
|
|
13
|
-
const LICENSE_URL = 'https://
|
|
12
|
+
const HOMEPAGE_URL = 'https://svgrid.com'
|
|
13
|
+
const LICENSE_URL = 'https://svgrid.com/pricing/'
|
|
14
14
|
const WATERMARK_LABEL = 'www.svgrid.com'
|
|
15
15
|
|
|
16
16
|
// How long the watermark stays fully visible before it starts fading, and how
|
package/src/ai.test.ts
DELETED
|
@@ -1,522 +0,0 @@
|
|
|
1
|
-
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
-
import {
|
|
3
|
-
setAIProvider, getAIProvider, hasAIProvider,
|
|
4
|
-
mockAIProvider,
|
|
5
|
-
aiFilter, aiSmartFill, aiSummarize, aiClassify,
|
|
6
|
-
type AIProvider, type AIRequest,
|
|
7
|
-
} from './ai'
|
|
8
|
-
import { clearLicenseKey, setLicenseKey } from './license'
|
|
9
|
-
|
|
10
|
-
// ---------------------------------------------------------------------------
|
|
11
|
-
// Test helpers
|
|
12
|
-
// ---------------------------------------------------------------------------
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Minimal stub of the SvGridApi surface our AI helpers depend on. We don't
|
|
16
|
-
* mock the entire grid - the AI helpers only read `getData()` and (for
|
|
17
|
-
* the `apply` branch of aiFilter) call setFilter/setSort/clearAllFilters/
|
|
18
|
-
* clearSort. Everything else stays a no-op.
|
|
19
|
-
*/
|
|
20
|
-
function fakeApi<T extends Record<string, unknown>>(data: T[]) {
|
|
21
|
-
const calls: Array<{ method: string; args: unknown[] }> = []
|
|
22
|
-
const log = (method: string) => (...args: unknown[]) => {
|
|
23
|
-
calls.push({ method, args })
|
|
24
|
-
}
|
|
25
|
-
const api = {
|
|
26
|
-
getData: () => data,
|
|
27
|
-
getDisplayedRows: () => data,
|
|
28
|
-
setFilter: log('setFilter'),
|
|
29
|
-
clearAllFilters: log('clearAllFilters'),
|
|
30
|
-
setSort: log('setSort'),
|
|
31
|
-
clearSort: log('clearSort'),
|
|
32
|
-
setColumnVisible: log('setColumnVisible'),
|
|
33
|
-
isColumnVisible: () => true,
|
|
34
|
-
getCellValue: () => undefined,
|
|
35
|
-
setCellValue: log('setCellValue'),
|
|
36
|
-
addRow: log('addRow'),
|
|
37
|
-
addRows: log('addRows'),
|
|
38
|
-
removeRow: log('removeRow'),
|
|
39
|
-
removeRows: log('removeRows'),
|
|
40
|
-
addColumn: log('addColumn'),
|
|
41
|
-
addColumns: log('addColumns'),
|
|
42
|
-
removeColumn: log('removeColumn'),
|
|
43
|
-
setGroupBy: log('setGroupBy'),
|
|
44
|
-
clearFilter: log('clearFilter'),
|
|
45
|
-
getFilters: () => ({}),
|
|
46
|
-
clearRowSelection: log('clearRowSelection'),
|
|
47
|
-
}
|
|
48
|
-
return { api: api as any, calls }
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Build a provider that records every request it sees and replies with a
|
|
53
|
-
* caller-chosen response. Used for the deterministic-shape tests where we
|
|
54
|
-
* need to assert what the helper put into the prompt or what it does with
|
|
55
|
-
* the model's reply.
|
|
56
|
-
*/
|
|
57
|
-
function recordingProvider(reply: string | ((req: AIRequest) => string)) {
|
|
58
|
-
const seen: AIRequest[] = []
|
|
59
|
-
const fn: AIProvider = async (req) => {
|
|
60
|
-
seen.push(req)
|
|
61
|
-
return typeof reply === 'function' ? reply(req) : reply
|
|
62
|
-
}
|
|
63
|
-
return { provider: fn, seen }
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Make sure each test starts from a known state. The provider, license, and
|
|
67
|
-
// any persistent flags in the AI module are global, so we reset them.
|
|
68
|
-
beforeEach(() => {
|
|
69
|
-
setAIProvider(null)
|
|
70
|
-
// Default to a licensed state so the soft-gate doesn't dump noise on the
|
|
71
|
-
// console during expected-failure tests. Individual cases clear it when
|
|
72
|
-
// they want to assert soft-gate behaviour.
|
|
73
|
-
setLicenseKey('SVENTERPRISE-DEV-TEST')
|
|
74
|
-
})
|
|
75
|
-
afterEach(() => {
|
|
76
|
-
setAIProvider(null)
|
|
77
|
-
clearLicenseKey()
|
|
78
|
-
})
|
|
79
|
-
|
|
80
|
-
// ---------------------------------------------------------------------------
|
|
81
|
-
// Provider plumbing
|
|
82
|
-
// ---------------------------------------------------------------------------
|
|
83
|
-
|
|
84
|
-
describe('AI provider registration', () => {
|
|
85
|
-
it('setAIProvider stores the function and hasAIProvider reflects it', () => {
|
|
86
|
-
expect(hasAIProvider()).toBe(false)
|
|
87
|
-
expect(getAIProvider()).toBeNull()
|
|
88
|
-
|
|
89
|
-
const fn: AIProvider = async () => '{}'
|
|
90
|
-
setAIProvider(fn)
|
|
91
|
-
expect(hasAIProvider()).toBe(true)
|
|
92
|
-
expect(getAIProvider()).toBe(fn)
|
|
93
|
-
})
|
|
94
|
-
|
|
95
|
-
it('setAIProvider(null) clears the registration', () => {
|
|
96
|
-
setAIProvider(async () => '{}')
|
|
97
|
-
setAIProvider(null)
|
|
98
|
-
expect(hasAIProvider()).toBe(false)
|
|
99
|
-
})
|
|
100
|
-
|
|
101
|
-
it('throws a typed NoProviderError when no provider is registered', async () => {
|
|
102
|
-
const { api } = fakeApi([{ id: 1, value: 10 }])
|
|
103
|
-
await expect(aiFilter(api, 'anything')).rejects.toThrow(/no AI provider registered/i)
|
|
104
|
-
})
|
|
105
|
-
|
|
106
|
-
it('throws on non-JSON when a json-format helper gets back prose', async () => {
|
|
107
|
-
const { provider } = recordingProvider('this is not JSON at all')
|
|
108
|
-
setAIProvider(provider)
|
|
109
|
-
const { api } = fakeApi([{ id: 1, value: 10 }])
|
|
110
|
-
await expect(aiFilter(api, 'find rows')).rejects.toThrow(/non-JSON/i)
|
|
111
|
-
})
|
|
112
|
-
|
|
113
|
-
it('strips a markdown ```json fence before parsing', async () => {
|
|
114
|
-
const { provider } = recordingProvider(
|
|
115
|
-
'```json\n{"filters": [], "sort": [], "rationale": "ok"}\n```',
|
|
116
|
-
)
|
|
117
|
-
setAIProvider(provider)
|
|
118
|
-
const { api } = fakeApi([{ id: 1, value: 10 }])
|
|
119
|
-
const r = await aiFilter(api, 'anything')
|
|
120
|
-
expect(r.rationale).toBe('ok')
|
|
121
|
-
})
|
|
122
|
-
})
|
|
123
|
-
|
|
124
|
-
// ---------------------------------------------------------------------------
|
|
125
|
-
// aiFilter
|
|
126
|
-
// ---------------------------------------------------------------------------
|
|
127
|
-
|
|
128
|
-
describe('aiFilter', () => {
|
|
129
|
-
it('passes the column schema to the prompt and tags the task', async () => {
|
|
130
|
-
const { provider, seen } = recordingProvider(
|
|
131
|
-
JSON.stringify({ filters: [], sort: [], rationale: 'x' }),
|
|
132
|
-
)
|
|
133
|
-
setAIProvider(provider)
|
|
134
|
-
const { api } = fakeApi([
|
|
135
|
-
{ id: 'A1', amount: 100, region: 'EMEA' },
|
|
136
|
-
{ id: 'A2', amount: 250, region: 'NA' },
|
|
137
|
-
])
|
|
138
|
-
await aiFilter(api, 'show big EMEA deals')
|
|
139
|
-
|
|
140
|
-
expect(seen).toHaveLength(1)
|
|
141
|
-
const req = seen[0]!
|
|
142
|
-
expect(req.task).toBe('filter')
|
|
143
|
-
expect(req.responseFormat).toBe('json')
|
|
144
|
-
// The schema block must mention every column.
|
|
145
|
-
expect(req.prompt).toMatch(/id \(string\)/)
|
|
146
|
-
expect(req.prompt).toMatch(/amount \(number\)/)
|
|
147
|
-
expect(req.prompt).toMatch(/region \(string\)/)
|
|
148
|
-
// The user's query is forwarded verbatim.
|
|
149
|
-
expect(req.prompt).toMatch(/show big EMEA deals/)
|
|
150
|
-
})
|
|
151
|
-
|
|
152
|
-
it('drops filter / sort clauses that reference a column the grid does not have', async () => {
|
|
153
|
-
// The model hallucinates "made_up_field" - the helper must silently drop
|
|
154
|
-
// it rather than pass it through to setFilter, which would otherwise
|
|
155
|
-
// throw.
|
|
156
|
-
const reply = {
|
|
157
|
-
filters: [
|
|
158
|
-
{ field: 'amount', operator: 'greaterThan', value: '100' },
|
|
159
|
-
{ field: 'made_up_field', operator: 'contains', value: 'foo' },
|
|
160
|
-
],
|
|
161
|
-
sort: [
|
|
162
|
-
{ field: 'amount', desc: true },
|
|
163
|
-
{ field: 'imaginary', desc: false },
|
|
164
|
-
],
|
|
165
|
-
rationale: 'amount > 100',
|
|
166
|
-
}
|
|
167
|
-
setAIProvider(recordingProvider(JSON.stringify(reply)).provider)
|
|
168
|
-
const { api } = fakeApi([{ amount: 100, region: 'NA' }])
|
|
169
|
-
const r = await aiFilter(api, 'anything')
|
|
170
|
-
|
|
171
|
-
expect(r.filters).toHaveLength(1)
|
|
172
|
-
expect(r.filters[0]?.field).toBe('amount')
|
|
173
|
-
expect(r.sort).toHaveLength(1)
|
|
174
|
-
expect(r.sort[0]?.field).toBe('amount')
|
|
175
|
-
})
|
|
176
|
-
|
|
177
|
-
it('with apply=true applies filters and the last sort clause to the grid', async () => {
|
|
178
|
-
const reply = {
|
|
179
|
-
filters: [{ field: 'amount', operator: 'greaterThan', value: '100' }],
|
|
180
|
-
sort: [
|
|
181
|
-
{ field: 'amount', desc: false }, // earlier - should be overridden
|
|
182
|
-
{ field: 'amount', desc: true }, // last - this is the one applied
|
|
183
|
-
],
|
|
184
|
-
rationale: '',
|
|
185
|
-
}
|
|
186
|
-
setAIProvider(recordingProvider(JSON.stringify(reply)).provider)
|
|
187
|
-
const { api, calls } = fakeApi([{ amount: 100, region: 'NA' }])
|
|
188
|
-
await aiFilter(api, 'q', { apply: true })
|
|
189
|
-
|
|
190
|
-
const methods = calls.map((c) => c.method)
|
|
191
|
-
expect(methods).toContain('clearAllFilters')
|
|
192
|
-
expect(methods).toContain('clearSort')
|
|
193
|
-
const setFilter = calls.find((c) => c.method === 'setFilter')!
|
|
194
|
-
expect(setFilter.args[0]).toBe('amount')
|
|
195
|
-
expect((setFilter.args[1] as any).operator).toBe('greaterThan')
|
|
196
|
-
const setSort = calls.find((c) => c.method === 'setSort')!
|
|
197
|
-
expect(setSort.args[0]).toBe('amount')
|
|
198
|
-
expect(setSort.args[1]).toBe('desc')
|
|
199
|
-
})
|
|
200
|
-
|
|
201
|
-
it('does NOT apply when apply is omitted (preview-only mode)', async () => {
|
|
202
|
-
const reply = {
|
|
203
|
-
filters: [{ field: 'amount', operator: 'greaterThan', value: '100' }],
|
|
204
|
-
sort: [{ field: 'amount', desc: true }],
|
|
205
|
-
rationale: '',
|
|
206
|
-
}
|
|
207
|
-
setAIProvider(recordingProvider(JSON.stringify(reply)).provider)
|
|
208
|
-
const { api, calls } = fakeApi([{ amount: 100, region: 'NA' }])
|
|
209
|
-
const r = await aiFilter(api, 'q')
|
|
210
|
-
|
|
211
|
-
expect(calls.find((c) => c.method === 'setFilter')).toBeUndefined()
|
|
212
|
-
expect(calls.find((c) => c.method === 'setSort')).toBeUndefined()
|
|
213
|
-
// But the result still contains the plan so the caller can render a preview.
|
|
214
|
-
expect(r.filters).toHaveLength(1)
|
|
215
|
-
expect(r.sort).toHaveLength(1)
|
|
216
|
-
})
|
|
217
|
-
})
|
|
218
|
-
|
|
219
|
-
// ---------------------------------------------------------------------------
|
|
220
|
-
// aiSmartFill
|
|
221
|
-
// ---------------------------------------------------------------------------
|
|
222
|
-
|
|
223
|
-
describe('aiSmartFill', () => {
|
|
224
|
-
it('throws when no examples are provided', async () => {
|
|
225
|
-
setAIProvider(recordingProvider('{}').provider)
|
|
226
|
-
const { api } = fakeApi([{ id: 1, tier: '' }])
|
|
227
|
-
await expect(
|
|
228
|
-
aiSmartFill(api, { field: 'tier', examples: [] }),
|
|
229
|
-
).rejects.toThrow(/requires at least one example/i)
|
|
230
|
-
})
|
|
231
|
-
|
|
232
|
-
it('auto-selects empty rows when targetRowIndices is omitted', async () => {
|
|
233
|
-
const { provider, seen } = recordingProvider(
|
|
234
|
-
JSON.stringify({
|
|
235
|
-
predictions: [{ rowIndex: 1, value: 'auto', confidence: 0.9 }],
|
|
236
|
-
rationale: '',
|
|
237
|
-
}),
|
|
238
|
-
)
|
|
239
|
-
setAIProvider(provider)
|
|
240
|
-
const { api } = fakeApi([
|
|
241
|
-
{ id: 1, tier: 'enterprise' }, // already filled
|
|
242
|
-
{ id: 2, tier: '' }, // empty -> picked
|
|
243
|
-
{ id: 3, tier: null as unknown as string }, // null -> picked
|
|
244
|
-
{ id: 4, tier: 'starter' }, // already filled
|
|
245
|
-
])
|
|
246
|
-
await aiSmartFill(api, {
|
|
247
|
-
field: 'tier',
|
|
248
|
-
examples: [{ input: { id: 999 }, output: 'starter' }],
|
|
249
|
-
})
|
|
250
|
-
|
|
251
|
-
const prompt = seen[0]!.prompt
|
|
252
|
-
// Rows 1 and 2 (0-indexed) are the empty ones.
|
|
253
|
-
expect(prompt).toMatch(/Row 1: /)
|
|
254
|
-
expect(prompt).toMatch(/Row 2: /)
|
|
255
|
-
// Rows 0 and 3 are already filled - should NOT appear.
|
|
256
|
-
expect(prompt).not.toMatch(/Row 0: /)
|
|
257
|
-
expect(prompt).not.toMatch(/Row 3: /)
|
|
258
|
-
})
|
|
259
|
-
|
|
260
|
-
it('returns an empty prediction list when there are no empty cells', async () => {
|
|
261
|
-
setAIProvider(recordingProvider('{"predictions":[],"rationale":""}').provider)
|
|
262
|
-
const { api } = fakeApi([
|
|
263
|
-
{ id: 1, tier: 'enterprise' },
|
|
264
|
-
{ id: 2, tier: 'starter' },
|
|
265
|
-
])
|
|
266
|
-
const r = await aiSmartFill(api, {
|
|
267
|
-
field: 'tier',
|
|
268
|
-
examples: [{ input: { id: 1 }, output: 'enterprise' }],
|
|
269
|
-
})
|
|
270
|
-
expect(r.predictions).toHaveLength(0)
|
|
271
|
-
expect(r.rationale).toMatch(/no empty/i)
|
|
272
|
-
})
|
|
273
|
-
|
|
274
|
-
it('respects explicit targetRowIndices', async () => {
|
|
275
|
-
const { provider, seen } = recordingProvider(
|
|
276
|
-
JSON.stringify({
|
|
277
|
-
predictions: [{ rowIndex: 0, value: 'x', confidence: 0.5 }],
|
|
278
|
-
rationale: '',
|
|
279
|
-
}),
|
|
280
|
-
)
|
|
281
|
-
setAIProvider(provider)
|
|
282
|
-
const { api } = fakeApi([
|
|
283
|
-
{ id: 1, tier: 'enterprise' },
|
|
284
|
-
{ id: 2, tier: 'starter' },
|
|
285
|
-
])
|
|
286
|
-
await aiSmartFill(api, {
|
|
287
|
-
field: 'tier',
|
|
288
|
-
targetRowIndices: [0],
|
|
289
|
-
examples: [{ input: { id: 1 }, output: 'override' }],
|
|
290
|
-
})
|
|
291
|
-
expect(seen[0]!.prompt).toMatch(/Row 0: /)
|
|
292
|
-
expect(seen[0]!.prompt).not.toMatch(/Row 1: /)
|
|
293
|
-
})
|
|
294
|
-
})
|
|
295
|
-
|
|
296
|
-
// ---------------------------------------------------------------------------
|
|
297
|
-
// aiSummarize
|
|
298
|
-
// ---------------------------------------------------------------------------
|
|
299
|
-
|
|
300
|
-
describe('aiSummarize', () => {
|
|
301
|
-
it('returns a safe empty result when the slice is empty', async () => {
|
|
302
|
-
// Use a non-empty dataset but a row target that doesn't exist - the
|
|
303
|
-
// helper must short-circuit BEFORE calling the provider.
|
|
304
|
-
let calls = 0
|
|
305
|
-
setAIProvider(async () => { calls += 1; return '{}' })
|
|
306
|
-
const { api } = fakeApi([{ id: 1 }])
|
|
307
|
-
const r = await aiSummarize(api, { target: { kind: 'row', rowIndex: 99 } })
|
|
308
|
-
expect(r.text).toBe('No rows in scope.')
|
|
309
|
-
expect(r.bullets).toEqual([])
|
|
310
|
-
expect(calls).toBe(0)
|
|
311
|
-
})
|
|
312
|
-
|
|
313
|
-
it('groups by field value when target.kind = "group"', async () => {
|
|
314
|
-
const { provider, seen } = recordingProvider(
|
|
315
|
-
JSON.stringify({ text: 'ok', bullets: [], highlightedFields: [] }),
|
|
316
|
-
)
|
|
317
|
-
setAIProvider(provider)
|
|
318
|
-
const { api } = fakeApi([
|
|
319
|
-
{ id: 1, region: 'NA' },
|
|
320
|
-
{ id: 2, region: 'NA' },
|
|
321
|
-
{ id: 3, region: 'EMEA' },
|
|
322
|
-
])
|
|
323
|
-
const r = await aiSummarize(api, {
|
|
324
|
-
target: { kind: 'group', field: 'region', value: 'NA' },
|
|
325
|
-
})
|
|
326
|
-
expect(r.text).toBe('ok')
|
|
327
|
-
// Only the two NA rows should appear in the prompt.
|
|
328
|
-
const prompt = seen[0]!.prompt
|
|
329
|
-
expect(prompt).toMatch(/"id":1/)
|
|
330
|
-
expect(prompt).toMatch(/"id":2/)
|
|
331
|
-
expect(prompt).not.toMatch(/"id":3/)
|
|
332
|
-
})
|
|
333
|
-
|
|
334
|
-
it('samples large slices uniformly so the prompt stays under budget', async () => {
|
|
335
|
-
const { provider, seen } = recordingProvider(
|
|
336
|
-
JSON.stringify({ text: 'ok', bullets: [], highlightedFields: [] }),
|
|
337
|
-
)
|
|
338
|
-
setAIProvider(provider)
|
|
339
|
-
const rows = Array.from({ length: 200 }, (_, i) => ({ id: i }))
|
|
340
|
-
const { api } = fakeApi(rows)
|
|
341
|
-
await aiSummarize(api, { target: { kind: 'all' } })
|
|
342
|
-
|
|
343
|
-
// Default sample cap is 25. We can't easily inspect the exact sample
|
|
344
|
-
// count without parsing, but the prompt should advertise the FULL
|
|
345
|
-
// slice size while only sampling a subset (so the rendered JSON line
|
|
346
|
-
// count is ~25 rather than ~200).
|
|
347
|
-
const prompt = seen[0]!.prompt
|
|
348
|
-
expect(prompt).toMatch(/Slice size: 200 row/)
|
|
349
|
-
const jsonLines = (prompt.match(/\{"id":/g) ?? []).length
|
|
350
|
-
expect(jsonLines).toBeLessThanOrEqual(30)
|
|
351
|
-
})
|
|
352
|
-
|
|
353
|
-
it('includes the user question in the prompt when provided', async () => {
|
|
354
|
-
const { provider, seen } = recordingProvider(
|
|
355
|
-
JSON.stringify({ text: 'ok', bullets: [], highlightedFields: [] }),
|
|
356
|
-
)
|
|
357
|
-
setAIProvider(provider)
|
|
358
|
-
const { api } = fakeApi([{ id: 1 }])
|
|
359
|
-
await aiSummarize(api, {
|
|
360
|
-
target: { kind: 'all' },
|
|
361
|
-
question: 'Which accounts are at risk?',
|
|
362
|
-
})
|
|
363
|
-
expect(seen[0]!.prompt).toMatch(/Which accounts are at risk\?/)
|
|
364
|
-
})
|
|
365
|
-
})
|
|
366
|
-
|
|
367
|
-
// ---------------------------------------------------------------------------
|
|
368
|
-
// aiClassify
|
|
369
|
-
// ---------------------------------------------------------------------------
|
|
370
|
-
|
|
371
|
-
describe('aiClassify', () => {
|
|
372
|
-
it('drops predictions whose value is not in the allowed class set', async () => {
|
|
373
|
-
setAIProvider(
|
|
374
|
-
recordingProvider(JSON.stringify({
|
|
375
|
-
predictions: [
|
|
376
|
-
{ rowIndex: 0, value: 'at-risk', confidence: 0.9 },
|
|
377
|
-
{ rowIndex: 1, value: 'expanding', confidence: 0.8 },
|
|
378
|
-
// Hallucinated label - must be dropped.
|
|
379
|
-
{ rowIndex: 2, value: 'something-else', confidence: 0.95 },
|
|
380
|
-
],
|
|
381
|
-
})).provider,
|
|
382
|
-
)
|
|
383
|
-
const { api } = fakeApi([
|
|
384
|
-
{ notes: 'losing momentum' },
|
|
385
|
-
{ notes: 'expanding fast' },
|
|
386
|
-
{ notes: 'unclear' },
|
|
387
|
-
])
|
|
388
|
-
const r = await aiClassify(api, {
|
|
389
|
-
inputField: 'notes',
|
|
390
|
-
outputField: 'sentiment',
|
|
391
|
-
classes: ['at-risk', 'expanding', 'steady'],
|
|
392
|
-
})
|
|
393
|
-
expect(r.predictions).toHaveLength(2)
|
|
394
|
-
expect(r.predictions.find((p) => p.value === 'something-else')).toBeUndefined()
|
|
395
|
-
})
|
|
396
|
-
|
|
397
|
-
it('includes the rubric in the prompt when classDescriptions is provided', async () => {
|
|
398
|
-
const { provider, seen } = recordingProvider('{"predictions":[]}')
|
|
399
|
-
setAIProvider(provider)
|
|
400
|
-
const { api } = fakeApi([{ notes: 'x' }])
|
|
401
|
-
await aiClassify(api, {
|
|
402
|
-
inputField: 'notes',
|
|
403
|
-
outputField: 'sentiment',
|
|
404
|
-
classes: ['at-risk', 'steady'],
|
|
405
|
-
classDescriptions: {
|
|
406
|
-
'at-risk': 'churn signals',
|
|
407
|
-
steady: 'no signals',
|
|
408
|
-
},
|
|
409
|
-
})
|
|
410
|
-
expect(seen[0]!.prompt).toMatch(/- at-risk: churn signals/)
|
|
411
|
-
expect(seen[0]!.prompt).toMatch(/- steady: no signals/)
|
|
412
|
-
})
|
|
413
|
-
})
|
|
414
|
-
|
|
415
|
-
// ---------------------------------------------------------------------------
|
|
416
|
-
// mockAIProvider end-to-end
|
|
417
|
-
// ---------------------------------------------------------------------------
|
|
418
|
-
|
|
419
|
-
describe('mockAIProvider', () => {
|
|
420
|
-
it('round-trips through aiFilter with at least one sensible clause', async () => {
|
|
421
|
-
setAIProvider(mockAIProvider)
|
|
422
|
-
const { api } = fakeApi([
|
|
423
|
-
{ id: 'A1', arr: 100_000, region: 'EMEA', owner: 'Sasha' },
|
|
424
|
-
{ id: 'A2', arr: 250_000, region: 'NA', owner: 'Jamie' },
|
|
425
|
-
{ id: 'A3', arr: 50_000, region: 'APAC', owner: 'Casey' },
|
|
426
|
-
])
|
|
427
|
-
const r = await aiFilter(api, 'show accounts over $80k in EMEA, highest first')
|
|
428
|
-
// Should have inferred something about "over $80k", "EMEA", and a sort.
|
|
429
|
-
const fields = r.filters.map((f) => f.field)
|
|
430
|
-
expect(fields).toContain('arr')
|
|
431
|
-
expect(fields).toContain('region')
|
|
432
|
-
expect(r.sort.length).toBeGreaterThan(0)
|
|
433
|
-
expect(r.rationale).toMatch(/Interpreted/i)
|
|
434
|
-
})
|
|
435
|
-
|
|
436
|
-
it('round-trips through aiClassify and returns labels from the allowed set', async () => {
|
|
437
|
-
setAIProvider(mockAIProvider)
|
|
438
|
-
const { api } = fakeApi([
|
|
439
|
-
{ id: 1, notes: 'champion left, ARR at risk' },
|
|
440
|
-
{ id: 2, notes: 'expanding into two new regions' },
|
|
441
|
-
{ id: 3, notes: 'steady usage no surprises' },
|
|
442
|
-
])
|
|
443
|
-
const r = await aiClassify(api, {
|
|
444
|
-
inputField: 'notes',
|
|
445
|
-
outputField: 'sentiment',
|
|
446
|
-
classes: ['at-risk', 'expanding', 'steady'],
|
|
447
|
-
})
|
|
448
|
-
expect(r.predictions.length).toBeGreaterThan(0)
|
|
449
|
-
for (const p of r.predictions) {
|
|
450
|
-
expect(['at-risk', 'expanding', 'steady']).toContain(p.value)
|
|
451
|
-
expect(p.confidence).toBeGreaterThan(0)
|
|
452
|
-
expect(p.confidence).toBeLessThanOrEqual(1)
|
|
453
|
-
}
|
|
454
|
-
})
|
|
455
|
-
|
|
456
|
-
it('summarises the whole view via the mock', async () => {
|
|
457
|
-
setAIProvider(mockAIProvider)
|
|
458
|
-
const { api } = fakeApi(Array.from({ length: 12 }, (_, i) => ({ id: i, value: i * 100 })))
|
|
459
|
-
const r = await aiSummarize(api, { target: { kind: 'all' } })
|
|
460
|
-
expect(r.text).toMatch(/12 rows in scope/i)
|
|
461
|
-
expect(r.bullets.length).toBeGreaterThan(0)
|
|
462
|
-
})
|
|
463
|
-
})
|
|
464
|
-
|
|
465
|
-
// ---------------------------------------------------------------------------
|
|
466
|
-
// License soft-gate
|
|
467
|
-
// ---------------------------------------------------------------------------
|
|
468
|
-
|
|
469
|
-
describe('license interaction', () => {
|
|
470
|
-
it('AI calls still succeed without a license key (soft-gate)', async () => {
|
|
471
|
-
clearLicenseKey()
|
|
472
|
-
setAIProvider(mockAIProvider)
|
|
473
|
-
const { api } = fakeApi([{ id: 1 }])
|
|
474
|
-
// Should NOT throw - the soft-gate emits a console nudge then proceeds.
|
|
475
|
-
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
|
476
|
-
try {
|
|
477
|
-
const r = await aiFilter(api, 'anything')
|
|
478
|
-
expect(r).toBeDefined()
|
|
479
|
-
} finally {
|
|
480
|
-
consoleSpy.mockRestore()
|
|
481
|
-
}
|
|
482
|
-
})
|
|
483
|
-
|
|
484
|
-
it('AI calls throw on a malformed license prefix', async () => {
|
|
485
|
-
setLicenseKey('NOT-A-VALID-PREFIX-AT-ALL')
|
|
486
|
-
setAIProvider(mockAIProvider)
|
|
487
|
-
const { api } = fakeApi([{ id: 1 }])
|
|
488
|
-
await expect(aiFilter(api, 'q')).rejects.toThrow(/invalid license/i)
|
|
489
|
-
})
|
|
490
|
-
})
|
|
491
|
-
|
|
492
|
-
// ---------------------------------------------------------------------------
|
|
493
|
-
// Abort + cancellation
|
|
494
|
-
// ---------------------------------------------------------------------------
|
|
495
|
-
|
|
496
|
-
describe('cancellation', () => {
|
|
497
|
-
it('forwards the AbortSignal to the provider for aiFilter', async () => {
|
|
498
|
-
let receivedSignal: AbortSignal | undefined
|
|
499
|
-
const provider: AIProvider = async (req) => {
|
|
500
|
-
receivedSignal = req.signal
|
|
501
|
-
return JSON.stringify({ filters: [], sort: [], rationale: '' })
|
|
502
|
-
}
|
|
503
|
-
setAIProvider(provider)
|
|
504
|
-
const controller = new AbortController()
|
|
505
|
-
const { api } = fakeApi([{ id: 1 }])
|
|
506
|
-
await aiFilter(api, 'q', { signal: controller.signal })
|
|
507
|
-
expect(receivedSignal).toBe(controller.signal)
|
|
508
|
-
})
|
|
509
|
-
|
|
510
|
-
it('forwards the AbortSignal for aiSummarize', async () => {
|
|
511
|
-
let receivedSignal: AbortSignal | undefined
|
|
512
|
-
const provider: AIProvider = async (req) => {
|
|
513
|
-
receivedSignal = req.signal
|
|
514
|
-
return JSON.stringify({ text: '', bullets: [], highlightedFields: [] })
|
|
515
|
-
}
|
|
516
|
-
setAIProvider(provider)
|
|
517
|
-
const controller = new AbortController()
|
|
518
|
-
const { api } = fakeApi([{ id: 1 }])
|
|
519
|
-
await aiSummarize(api, { target: { kind: 'all' }, signal: controller.signal })
|
|
520
|
-
expect(receivedSignal).toBe(controller.signal)
|
|
521
|
-
})
|
|
522
|
-
})
|