@svgrid/grid 2.6.21 → 2.7.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 (358) hide show
  1. package/CHANGELOG.md +150 -88
  2. package/README.md +221 -199
  3. package/dist/FlexRender.svelte +96 -96
  4. package/dist/GridFooter.svelte +181 -181
  5. package/dist/GridMenus.svelte +201 -18
  6. package/dist/SvAutoComplete.svelte +169 -165
  7. package/dist/SvAvatar.svelte +75 -75
  8. package/dist/SvCalendar.svelte +503 -503
  9. package/dist/SvCarousel.svelte +141 -141
  10. package/dist/SvCheckBox.svelte +102 -102
  11. package/dist/SvCircularProgress.svelte +109 -109
  12. package/dist/SvColorInput.svelte +181 -181
  13. package/dist/SvComboBox.svelte +279 -275
  14. package/dist/SvContextMenu.svelte +116 -116
  15. package/dist/SvCountryInput.svelte +163 -163
  16. package/dist/SvDateRangeInput.svelte +25 -3
  17. package/dist/SvDrawer.svelte +254 -254
  18. package/dist/SvDropDownList.svelte +378 -374
  19. package/dist/SvDurationInput.svelte +126 -126
  20. package/dist/SvField.svelte +293 -293
  21. package/dist/SvForm.svelte +437 -437
  22. package/dist/SvGrid.controller.svelte.d.ts +61 -9
  23. package/dist/SvGrid.controller.svelte.js +363 -123
  24. package/dist/SvGrid.css +222 -1
  25. package/dist/SvGrid.helpers.d.ts +55 -0
  26. package/dist/SvGrid.helpers.js +83 -0
  27. package/dist/SvGrid.svelte +255 -56
  28. package/dist/SvGrid.types.d.ts +146 -1
  29. package/dist/SvGridCellEditor.svelte +744 -662
  30. package/dist/SvGridChart.svelte +1716 -1716
  31. package/dist/SvGridChartPanel.svelte +485 -485
  32. package/dist/SvGridChartView.svelte +70 -70
  33. package/dist/SvGridDropdown.svelte +728 -728
  34. package/dist/SvGridSelect.svelte +270 -266
  35. package/dist/SvGridSelect.svelte.d.ts +1 -1
  36. package/dist/SvGroupCell.svelte +116 -116
  37. package/dist/SvListBox.svelte +334 -326
  38. package/dist/SvMaskedInput.svelte +122 -122
  39. package/dist/SvMenu.svelte +124 -124
  40. package/dist/SvMenuList.svelte +146 -146
  41. package/dist/SvMultiSelect.svelte +293 -289
  42. package/dist/SvMultiSelect.svelte.d.ts +1 -1
  43. package/dist/SvNumberInput.svelte +172 -168
  44. package/dist/SvOtpInput.svelte +158 -158
  45. package/dist/SvPasswordInput.svelte +151 -151
  46. package/dist/SvPhoneInput.svelte +133 -133
  47. package/dist/SvPopover.svelte +197 -197
  48. package/dist/SvProgress.svelte +116 -116
  49. package/dist/SvRadioGroup.svelte +107 -107
  50. package/dist/SvRating.svelte +112 -112
  51. package/dist/SvResult.svelte +73 -73
  52. package/dist/SvRichCell.svelte +125 -0
  53. package/dist/SvRichCell.svelte.d.ts +15 -0
  54. package/dist/SvRichText.svelte +211 -211
  55. package/dist/SvRowGroupPanel.svelte +170 -170
  56. package/dist/SvScrollArea.svelte +61 -61
  57. package/dist/SvSlider.svelte +203 -203
  58. package/dist/SvSwitchButton.svelte +108 -108
  59. package/dist/SvTagsInput.svelte +115 -115
  60. package/dist/SvTextArea.svelte +5 -1
  61. package/dist/SvTextInput.svelte +147 -147
  62. package/dist/SvTimePicker.svelte +245 -245
  63. package/dist/SvToaster.svelte +159 -159
  64. package/dist/SvToggleButton.svelte +85 -85
  65. package/dist/SvTooltip.svelte +161 -161
  66. package/dist/SvTour.svelte +208 -208
  67. package/dist/SvTree.svelte +444 -444
  68. package/dist/SvTreeSelect.svelte +239 -235
  69. package/dist/SvTreeSelect.svelte.d.ts +1 -1
  70. package/dist/builtin-editors.d.ts +2 -2
  71. package/dist/builtin-editors.js +19 -3
  72. package/dist/cdn/GridMenus-C4oLsJyj.js +600 -0
  73. package/dist/cdn/GridMenus-yEivjNwl.js +601 -0
  74. package/dist/cdn/SvDateRangeInput-Bh0A0JkF.js +199 -0
  75. package/dist/cdn/SvDateRangeInput-DflbiP7N.js +198 -0
  76. package/dist/cdn/SvDateTimePicker-BWwpfB_o.js +812 -0
  77. package/dist/cdn/SvDateTimePicker-Bivn8dAP.js +816 -0
  78. package/dist/cdn/SvGridCellEditor-AXL8cHGO.js +550 -0
  79. package/dist/cdn/SvGridCellEditor-Ba7rY3eu.js +549 -0
  80. package/dist/cdn/{SvGridChart-BwVos976.js → SvGridChart-Bs2GIR2Q.js} +1 -1
  81. package/dist/cdn/{SvGridChart-BEJmNNx9.js → SvGridChart-CwhFz7GV.js} +1 -1
  82. package/dist/cdn/{SvGridChartPanel-BOknOkrP.js → SvGridChartPanel-1WXuStzM.js} +1 -1
  83. package/dist/cdn/{SvGridChartPanel-D2PjII4O.js → SvGridChartPanel-e5_nqNP9.js} +1 -1
  84. package/dist/cdn/{SvGridChartView-00LPUHL1.js → SvGridChartView-SmPW10dI.js} +1 -1
  85. package/dist/cdn/{SvGridChartView-BhUEJ5ki.js → SvGridChartView-eSPuJE6g.js} +1 -1
  86. package/dist/cdn/{SvGridDropdown-D0VdjeR8.js → SvGridDropdown-B1ZcLpgs.js} +1 -1
  87. package/dist/cdn/{SvGridDropdown-D13MtJ2j.js → SvGridDropdown-CtdbHcIS.js} +1 -1
  88. package/dist/cdn/column-resize-DsfNXMom.js +102 -0
  89. package/dist/cdn/date-format-CcP1tafP.js +1395 -0
  90. package/dist/cdn/date-format-DZT7T1wf.js +1393 -0
  91. package/dist/cdn/{editor-registry-CiI0xlKg.js → editor-registry-BhgE3S84.js} +51 -25
  92. package/dist/cdn/row-resize-BRcimkUT.js +95 -0
  93. package/dist/cdn/{src-BYq-qyrp.js → src-COC0vnpg.js} +7846 -7317
  94. package/dist/cdn/{src-DBel9wRZ.js → src-pYGV2rMR.js} +10033 -9504
  95. package/dist/cdn/svgrid.js +15 -11
  96. package/dist/cdn/svgrid.svelte-external.js +15 -11
  97. package/dist/cell-values.d.ts +16 -0
  98. package/dist/cell-values.js +28 -0
  99. package/dist/chart-export.js +8 -8
  100. package/dist/clipboard.d.ts +22 -0
  101. package/dist/clipboard.js +405 -27
  102. package/dist/column-groups.js +1 -1
  103. package/dist/column-resize.d.ts +46 -0
  104. package/dist/column-resize.js +205 -0
  105. package/dist/columns.d.ts +0 -3
  106. package/dist/columns.js +0 -57
  107. package/dist/core.d.ts +19 -4
  108. package/dist/core.js +460 -119
  109. package/dist/editing.js +12 -7
  110. package/dist/editors/cell-editors.d.ts +11 -0
  111. package/dist/editors/cell-editors.js +18 -1
  112. package/dist/filtering/excel-filters.js +28 -0
  113. package/dist/grid-messages.d.ts +15 -0
  114. package/dist/grid-messages.js +15 -0
  115. package/dist/group-display.d.ts +1 -1
  116. package/dist/index.d.ts +6 -1
  117. package/dist/index.js +10 -0
  118. package/dist/list-option.d.ts +6 -0
  119. package/dist/menus.js +41 -8
  120. package/dist/row-resize.d.ts +11 -0
  121. package/dist/row-resize.js +7 -1
  122. package/dist/sanitize-html.d.ts +37 -0
  123. package/dist/sanitize-html.js +234 -0
  124. package/dist/selection-bar-view.svelte.d.ts +25 -0
  125. package/dist/selection-bar-view.svelte.js +13 -0
  126. package/dist/selection.d.ts +2 -1
  127. package/dist/selection.js +133 -8
  128. package/dist/spreadsheet.d.ts +1 -1
  129. package/dist/spreadsheet.js +1 -1
  130. package/package.json +11 -11
  131. package/src/FlexRender.svelte +96 -96
  132. package/src/GridFooter.svelte +181 -181
  133. package/src/GridMenus.svelte +201 -18
  134. package/src/SvAutoComplete.svelte +169 -165
  135. package/src/SvAvatar.svelte +75 -75
  136. package/src/SvCalendar.svelte +503 -503
  137. package/src/SvCalendar.test.ts +226 -226
  138. package/src/SvCarousel.svelte +141 -141
  139. package/src/SvCheckBox.svelte +102 -102
  140. package/src/SvCircularProgress.svelte +109 -109
  141. package/src/SvColorInput.svelte +181 -181
  142. package/src/SvComboBox.svelte +279 -275
  143. package/src/SvContextMenu.svelte +116 -116
  144. package/src/SvCountryInput.svelte +163 -163
  145. package/src/SvDateRangeInput.svelte +25 -3
  146. package/src/SvDrawer.svelte +254 -254
  147. package/src/SvDropDownList.svelte +378 -374
  148. package/src/SvDurationInput.svelte +126 -126
  149. package/src/SvField.svelte +293 -293
  150. package/src/SvForm.svelte +437 -437
  151. package/src/SvForm.test.ts +411 -411
  152. package/src/SvGrid.controller.svelte.ts +404 -133
  153. package/src/SvGrid.css +222 -1
  154. package/src/SvGrid.helpers.ts +87 -0
  155. package/src/SvGrid.svelte +255 -56
  156. package/src/SvGrid.types.ts +2092 -1940
  157. package/src/SvGridCellEditor.svelte +744 -662
  158. package/src/SvGridChart.svelte +1716 -1716
  159. package/src/SvGridChartPanel.svelte +485 -485
  160. package/src/SvGridChartView.svelte +70 -70
  161. package/src/SvGridDropdown.svelte +728 -728
  162. package/src/SvGridSelect.svelte +270 -266
  163. package/src/SvGroupCell.svelte +116 -116
  164. package/src/SvListBox.svelte +334 -326
  165. package/src/SvMaskedInput.svelte +122 -122
  166. package/src/SvMenu.svelte +124 -124
  167. package/src/SvMenu.test.ts +97 -97
  168. package/src/SvMenuList.svelte +146 -146
  169. package/src/SvMultiSelect.svelte +293 -289
  170. package/src/SvNumberInput.svelte +172 -168
  171. package/src/SvOtpInput.svelte +158 -158
  172. package/src/SvPasswordInput.svelte +151 -151
  173. package/src/SvPhoneInput.svelte +133 -133
  174. package/src/SvPopover.svelte +197 -197
  175. package/src/SvProgress.svelte +116 -116
  176. package/src/SvRadioGroup.svelte +107 -107
  177. package/src/SvRating.svelte +112 -112
  178. package/src/SvResult.svelte +73 -73
  179. package/src/SvRichCell.svelte +125 -0
  180. package/src/SvRichText.svelte +211 -211
  181. package/src/SvRowGroupPanel.svelte +170 -170
  182. package/src/SvScrollArea.svelte +61 -61
  183. package/src/SvSlider.svelte +203 -203
  184. package/src/SvSwitchButton.svelte +108 -108
  185. package/src/SvTagsInput.svelte +115 -115
  186. package/src/SvTextArea.svelte +5 -1
  187. package/src/SvTextInput.svelte +147 -147
  188. package/src/SvTimePicker.svelte +245 -245
  189. package/src/SvToaster.svelte +159 -159
  190. package/src/SvToaster.test.ts +95 -95
  191. package/src/SvToggleButton.svelte +85 -85
  192. package/src/SvTooltip.svelte +161 -161
  193. package/src/SvTour.svelte +208 -208
  194. package/src/SvTree.svelte +444 -444
  195. package/src/SvTreeSelect.svelte +239 -235
  196. package/src/a11y/dismissable.test.ts +119 -119
  197. package/src/a11y/dismissable.ts +114 -114
  198. package/src/a11y.contract.test.ts +49 -49
  199. package/src/a11y.test.ts +59 -59
  200. package/src/a11y.ts +61 -61
  201. package/src/ai.test.ts +502 -502
  202. package/src/ai.ts +1419 -1419
  203. package/src/build-api.coverage.test.ts +633 -633
  204. package/src/build-api.ts +846 -846
  205. package/src/builtin-editors.grid.test.ts +83 -83
  206. package/src/builtin-editors.test.ts +18 -1
  207. package/src/builtin-editors.ts +19 -3
  208. package/src/cell-formatting.ts +171 -171
  209. package/src/cell-render.test.ts +513 -513
  210. package/src/cell-render.ts +496 -496
  211. package/src/cell-values.ts +148 -118
  212. package/src/chart-export.ts +202 -202
  213. package/src/chart-view.svelte.ts +36 -36
  214. package/src/chart.ts +2321 -2321
  215. package/src/clipboard.test.ts +93 -20
  216. package/src/clipboard.ts +433 -33
  217. package/src/collaboration.test.ts +104 -104
  218. package/src/collaboration.ts +167 -167
  219. package/src/column-groups.ts +78 -78
  220. package/src/column-resize.test.ts +381 -0
  221. package/src/column-resize.ts +227 -0
  222. package/src/columns.test.ts +0 -103
  223. package/src/columns.ts +0 -58
  224. package/src/core.aggregate.test.ts +134 -0
  225. package/src/core.filter.test.ts +156 -0
  226. package/src/core.grouping.test.ts +146 -0
  227. package/src/core.performance.test.ts +30 -30
  228. package/src/core.row-shape.test.ts +119 -0
  229. package/src/core.rowmodel-cache.test.ts +121 -0
  230. package/src/core.sort.test.ts +293 -0
  231. package/src/core.ts +1865 -1468
  232. package/src/createAutocomplete.svelte.ts +132 -132
  233. package/src/createCombobox.svelte.ts +191 -191
  234. package/src/createCountryInput.svelte.ts +157 -157
  235. package/src/createDropdownList.svelte.ts +168 -168
  236. package/src/createForm.svelte.ts +386 -386
  237. package/src/createGrid.svelte.ts +42 -42
  238. package/src/createGrid.test.ts +10 -10
  239. package/src/createGridState.svelte.ts +17 -17
  240. package/src/createListbox.svelte.ts +250 -250
  241. package/src/createMenu.svelte.ts +224 -224
  242. package/src/createPopoverSelect.svelte.ts +213 -213
  243. package/src/createSlider.svelte.ts +191 -191
  244. package/src/createTooltip.svelte.ts +144 -144
  245. package/src/createTree.svelte.ts +322 -322
  246. package/src/date-string-column.test.ts +87 -0
  247. package/src/datetime/date-core.ts +206 -206
  248. package/src/datetime/date-restrict.ts +61 -61
  249. package/src/datetime/timezone.ts +135 -135
  250. package/src/dock-manager-model.ts +596 -596
  251. package/src/dock-model.ts +374 -374
  252. package/src/editing.test.ts +974 -949
  253. package/src/editing.ts +609 -606
  254. package/src/editor-block-prop.test.ts +132 -0
  255. package/src/editor-contract.ts +171 -171
  256. package/src/editor-registry.grid.test.ts +144 -144
  257. package/src/editor-registry.ts +122 -122
  258. package/src/editors/cell-editors.ts +27 -1
  259. package/src/export-data-api.test.ts +126 -126
  260. package/src/export-format.test.ts +107 -107
  261. package/src/export-format.ts +601 -601
  262. package/src/filter-operators.ts +160 -160
  263. package/src/filtering/excel-filters.ts +325 -295
  264. package/src/filtering/normalize-fast-path.test.ts +104 -0
  265. package/src/flex-render.ts +3 -3
  266. package/src/form-field.ts +127 -127
  267. package/src/grid-messages.ts +34 -0
  268. package/src/group-display.test.ts +167 -167
  269. package/src/group-display.ts +200 -200
  270. package/src/headless.ts +87 -87
  271. package/src/index.ts +25 -1
  272. package/src/js-scroller.svelte.ts +173 -173
  273. package/src/keyboard-handlers.ts +270 -270
  274. package/src/keyboard.test.ts +59 -59
  275. package/src/keyboard.ts +97 -97
  276. package/src/list-nav.test.ts +49 -49
  277. package/src/list-nav.ts +29 -29
  278. package/src/list-option.test.ts +56 -56
  279. package/src/list-option.ts +179 -173
  280. package/src/menus.test.ts +43 -0
  281. package/src/menus.ts +597 -567
  282. package/src/merge-objects.ts +48 -48
  283. package/src/move-cells.test.ts +850 -0
  284. package/src/number-editor-literal.test.ts +84 -0
  285. package/src/number-editor.grid.test.ts +160 -0
  286. package/src/overlays.test.ts +90 -90
  287. package/src/positioning.ts +268 -268
  288. package/src/render-component.ts +28 -28
  289. package/src/resize-props.test.ts +361 -0
  290. package/src/row-drag-touch.ts +211 -211
  291. package/src/row-drag.test.ts +353 -353
  292. package/src/row-drag.ts +415 -415
  293. package/src/row-resize.test.ts +524 -493
  294. package/src/row-resize.ts +228 -210
  295. package/src/sanitize-html.test.ts +182 -0
  296. package/src/sanitize-html.ts +235 -0
  297. package/src/scheduler-ical.ts +181 -181
  298. package/src/scheduler-model.test.ts +562 -562
  299. package/src/scheduler-model.ts +873 -873
  300. package/src/selection-bar-view.svelte.ts +36 -0
  301. package/src/selection.test.ts +900 -743
  302. package/src/selection.ts +135 -8
  303. package/src/server-data-source.test.ts +383 -383
  304. package/src/server-data-source.ts +469 -469
  305. package/src/sparkline.test.ts +68 -68
  306. package/src/sparkline.ts +169 -169
  307. package/src/spreadsheet.test.ts +488 -488
  308. package/src/spreadsheet.ts +312 -312
  309. package/src/static-functions.ts +11 -11
  310. package/src/subscribe.ts +38 -38
  311. package/src/summaries.ts +113 -113
  312. package/src/svgrid-wrapper.types.ts +563 -563
  313. package/src/svgrid.async-editor-options.test.ts +273 -273
  314. package/src/svgrid.auto-row-height.test.ts +204 -204
  315. package/src/svgrid.behavior.test.ts +910 -910
  316. package/src/svgrid.charting.test.ts +534 -534
  317. package/src/svgrid.comments-autocomplete.test.ts +127 -127
  318. package/src/svgrid.context-menu.test.ts +147 -147
  319. package/src/svgrid.features.test.ts +157 -157
  320. package/src/svgrid.filter-depth.test.ts +163 -163
  321. package/src/svgrid.filter-menu-listbox.svelte.test.ts +377 -331
  322. package/src/svgrid.filter-menu-scroll.test.ts +112 -112
  323. package/src/svgrid.grand-total.test.ts +188 -188
  324. package/src/svgrid.group-display-mode.test.ts +171 -171
  325. package/src/svgrid.group-footers.test.ts +121 -121
  326. package/src/svgrid.group-pagination.test.ts +153 -153
  327. package/src/svgrid.in-suggest-snapshot.svelte.test.ts +91 -0
  328. package/src/svgrid.menu-scroll-close.test.ts +204 -0
  329. package/src/svgrid.new-features.wrapper.test.ts +251 -251
  330. package/src/svgrid.selection-bar-seam.test.ts +185 -0
  331. package/src/svgrid.tree-data.test.ts +186 -186
  332. package/src/svgrid.upsell-license.test.ts +117 -0
  333. package/src/svgrid.wrapper.test.ts +63 -63
  334. package/src/svgriddropdown.async-panel.svelte.test.ts +195 -195
  335. package/src/test-setup.ts +62 -62
  336. package/src/themes/index.ts +288 -288
  337. package/src/toast-store.svelte.ts +250 -250
  338. package/src/toast-store.test.ts +147 -147
  339. package/src/tree-row-model.test.ts +168 -168
  340. package/src/ui-buttons.test.ts +144 -144
  341. package/src/ui-inputs.test.ts +118 -118
  342. package/src/ui-localization.test.ts +113 -113
  343. package/src/ui-range.test.ts +70 -70
  344. package/src/ui-selection.test.ts +155 -155
  345. package/src/ui-tier1.test.ts +142 -142
  346. package/src/virtual.test.ts +88 -88
  347. package/src/virtualization/column-virtualizer.test.ts +27 -27
  348. package/src/virtualization/column-virtualizer.ts +30 -30
  349. package/src/virtualization/svelte-virtualizer.svelte.ts +26 -26
  350. package/src/virtualization/types.ts +30 -30
  351. package/src/virtualization/virtualizer.test.ts +47 -47
  352. package/src/virtualization/virtualizer.ts +322 -322
  353. package/dist/cdn/GridMenus-BfTAKn84.js +0 -488
  354. package/dist/cdn/GridMenus-C3bJd7w8.js +0 -489
  355. package/dist/cdn/SvDateTimePicker-CHnUkWcH.js +0 -2206
  356. package/dist/cdn/SvDateTimePicker-CRQH_U7E.js +0 -2201
  357. package/dist/cdn/SvGridCellEditor-BGUCzuPB.js +0 -523
  358. package/dist/cdn/SvGridCellEditor-G8IMWIws.js +0 -522
package/src/ai.ts CHANGED
@@ -1,1419 +1,1419 @@
1
- /**
2
- * Pro AI feature pack
3
- * -------------------
4
- *
5
- * Three jobs every analyst wishes a data grid could do:
6
- *
7
- * 1. Natural-language filter / sort (`aiFilter`)
8
- * "show me deals closing this quarter over $50k owned by Sasha"
9
- * -> { filters: [...], sort: [...] }
10
- *
11
- * 2. Smart fill (`aiSmartFill`)
12
- * User edits two cells in a column with example values; the
13
- * Grid proposes the rest. Excel "Flash Fill" pattern.
14
- *
15
- * 3. Summarise rows (`aiSummarize`)
16
- * Single row, the current selection, a group key, or the whole
17
- * filtered view -> a one-paragraph summary.
18
- *
19
- * The grid stays headless / model-agnostic. The consumer supplies an
20
- * `AIProvider` that knows how to call OpenAI / Anthropic / a local
21
- * model / a server-side proxy. We never bundle a model client.
22
- *
23
- * Built-in + free: the AI helpers live in `@svgrid/grid`. They ship no model
24
- * client and do nothing until you register a provider with `setAIProvider(...)`,
25
- * so they add nothing to the base bundle unless you actually use them.
26
- */
27
-
28
- import type { RowData, SvGridApi, TableFeatures } from './index'
29
- import { getExportProvider } from './export-provider'
30
-
31
- // Export formats an AI export can plan. WRITING the enterprise formats (xlsx /
32
- // pdf / html / xml / md) needs the export engine from `@svgrid/enterprise`
33
- // (registered via the export-provider seam); csv / tsv / json are also handled
34
- // by that engine when present. The union is declared locally so the free grid
35
- // carries no dependency on the enterprise export module.
36
- type ExportFormat = 'xlsx' | 'xls' | 'pdf' | 'csv' | 'tsv' | 'html' | 'json' | 'xml' | 'md'
37
-
38
- // ---------------------------------------------------------------------------
39
- // Provider contract
40
- // ---------------------------------------------------------------------------
41
-
42
- /**
43
- * Shape every consumer-provided model adapter must implement. Keeping this
44
- * tiny (one async call, two response formats) lets the same adapter drive
45
- * OpenAI's `chat.completions`, Anthropic's `messages`, a self-hosted
46
- * llama.cpp endpoint, or a server-side proxy. The grid only cares that the
47
- * provider eventually returns a string we can parse.
48
- */
49
- export type AIProvider = (request: AIRequest) => Promise<string>
50
-
51
- /** One call out to the model, as the grid builds it. Providers receive this. */
52
- export type AIRequest = {
53
- /** Full prompt the grid built for the model. Already includes column
54
- * schema and any sampled rows where applicable. */
55
- prompt: string
56
- /** When 'json', the provider should ask the model to return strict
57
- * JSON only - no prose. We parse the response with JSON.parse and
58
- * throw a typed error on failure. */
59
- responseFormat?: 'text' | 'json'
60
- /** Honored if the underlying transport supports cancellation. */
61
- signal?: AbortSignal
62
- /** Free-form tag for telemetry / logging. One of: 'filter',
63
- * 'smart-fill', 'summarize', 'classify'. */
64
- task: AITask
65
- /** Soft hint to the provider about how many tokens we expect back.
66
- * Useful for routing small jobs to a cheaper model. */
67
- maxOutputTokens?: number
68
- }
69
-
70
- /** Which helper produced a request - carried on {@link AIRequest} for routing and telemetry. */
71
- export type AITask = 'filter' | 'smart-fill' | 'summarize' | 'classify' | 'export' | 'anomaly' | 'chart'
72
-
73
- let provider: AIProvider | null = null
74
-
75
- /**
76
- * Register the model adapter every AI call will route through. Call once
77
- * at app boot. Passing `null` clears the provider and AI calls revert to
78
- * throwing "no provider" errors.
79
- */
80
- export function setAIProvider(p: AIProvider | null): void {
81
- provider = p
82
- }
83
-
84
- /** The provider registered with `setAIProvider`, or null when none is. */
85
- export function getAIProvider(): AIProvider | null {
86
- return provider
87
- }
88
-
89
- /** Whether an AI provider is registered. Gate AI affordances on this so the UI stays honest. */
90
- export function hasAIProvider(): boolean {
91
- return provider != null
92
- }
93
-
94
- class NoProviderError extends Error {
95
- constructor() {
96
- super(
97
- '@svgrid/grid ai: no AI provider registered. Call setAIProvider(fn) ' +
98
- 'with an adapter that talks to OpenAI / Anthropic / your proxy.',
99
- )
100
- this.name = 'NoProviderError'
101
- }
102
- }
103
-
104
- class BadJsonError extends Error {
105
- constructor(raw: string) {
106
- super(
107
- '@svgrid/grid ai: provider returned non-JSON for a json-format request. ' +
108
- `First 200 chars: ${raw.slice(0, 200)}`,
109
- )
110
- this.name = 'BadJsonError'
111
- }
112
- }
113
-
114
- async function callProvider(req: AIRequest): Promise<string> {
115
- if (!provider) throw new NoProviderError()
116
- return provider(req)
117
- }
118
-
119
- async function callJSON<T>(req: AIRequest): Promise<T> {
120
- const raw = await callProvider({ ...req, responseFormat: 'json' })
121
- // Models occasionally wrap JSON in markdown code fences even when asked
122
- // for raw JSON. Strip a single fenced block if present, then parse.
123
- const stripped = raw.trim().replace(/^```(?:json)?\s*|\s*```$/g, '')
124
- try {
125
- return JSON.parse(stripped) as T
126
- } catch {
127
- throw new BadJsonError(raw)
128
- }
129
- }
130
-
131
- // ---------------------------------------------------------------------------
132
- // Helpers - build column schema + row sample from the grid API
133
- // ---------------------------------------------------------------------------
134
-
135
- type ColumnSchemaEntry = {
136
- field: string
137
- type: 'string' | 'number' | 'boolean' | 'date' | 'unknown'
138
- sampleValues: unknown[]
139
- }
140
-
141
- /**
142
- * Inspect the first N rows the grid is holding to infer a typed schema +
143
- * a handful of sample values per column. This is the context every AI
144
- * task needs and the most expensive thing to build, so the helpers cache
145
- * the result inside one task call rather than calling api.getData()
146
- * repeatedly.
147
- */
148
- function buildColumnSchema<
149
- TFeatures extends TableFeatures,
150
- TData extends RowData,
151
- >(api: SvGridApi<TFeatures, TData>, sampleSize = 50): ColumnSchemaEntry[] {
152
- const data = api.getData()
153
- if (data.length === 0) return []
154
- const slice = data.slice(0, Math.min(data.length, sampleSize))
155
- const fields = new Set<string>()
156
- for (const row of slice) {
157
- for (const k of Object.keys(row as object)) fields.add(k)
158
- }
159
- const out: ColumnSchemaEntry[] = []
160
- for (const field of fields) {
161
- const values: unknown[] = []
162
- for (const row of slice) {
163
- const v = (row as Record<string, unknown>)[field]
164
- if (v != null) values.push(v)
165
- if (values.length >= 5) break
166
- }
167
- out.push({
168
- field,
169
- type: inferType(values),
170
- sampleValues: values,
171
- })
172
- }
173
- return out
174
- }
175
-
176
- function inferType(samples: unknown[]): ColumnSchemaEntry['type'] {
177
- if (samples.length === 0) return 'unknown'
178
- const v = samples[0]
179
- if (typeof v === 'number') return 'number'
180
- if (typeof v === 'boolean') return 'boolean'
181
- if (typeof v === 'string') {
182
- // Cheap ISO-date sniff so we route date-style filters correctly.
183
- if (/^\d{4}-\d{2}-\d{2}/.test(v)) return 'date'
184
- return 'string'
185
- }
186
- return 'unknown'
187
- }
188
-
189
- function schemaToPromptBlock(schema: ColumnSchemaEntry[]): string {
190
- return schema
191
- .map(
192
- (c) =>
193
- `- ${c.field} (${c.type}): e.g. ${c.sampleValues
194
- .slice(0, 3)
195
- .map((v) => JSON.stringify(v))
196
- .join(', ')}`,
197
- )
198
- .join('\n')
199
- }
200
-
201
- // ---------------------------------------------------------------------------
202
- // 1. Natural-language filter / sort
203
- // ---------------------------------------------------------------------------
204
-
205
- /** One condition in a filter plan: a column, a comparison, and the value to match. */
206
- export type AIFilterClause = {
207
- field: string
208
- operator: 'contains' | 'equals' | 'startsWith' | 'greaterThan' | 'lessThan' | 'isBlank'
209
- value?: string
210
- }
211
- /** One ordering clause in a filter plan. */
212
- export type AISortClause = { field: string; desc: boolean }
213
-
214
- /** A natural-language query turned into filters and sorting, plus the model's reasoning. */
215
- export type AIFilterResult = {
216
- filters: AIFilterClause[]
217
- sort: AISortClause[]
218
- /** Plain-English explanation of how the model interpreted the query.
219
- * Surface this in the UI so the user can confirm or undo. */
220
- rationale: string
221
- }
222
-
223
- /** Options for `aiFilter` - preview the plan, or apply it straight to the grid. */
224
- export type AIFilterOptions = {
225
- /**
226
- * When true, the helper not only RETURNS the plan but also applies it
227
- * to the grid via `api.setFilter` / `api.setSort`. Defaults to false
228
- * so callers can show a preview before committing.
229
- */
230
- apply?: boolean
231
- signal?: AbortSignal
232
- }
233
-
234
- /**
235
- * Translate a natural-language query into a filter+sort plan against
236
- * the current grid's columns. The grid passes the column schema (names,
237
- * types, sample values) to the model so it can pick the right field
238
- * names without hallucinating.
239
- */
240
- export async function aiFilter<
241
- TFeatures extends TableFeatures,
242
- TData extends RowData,
243
- >(
244
- api: SvGridApi<TFeatures, TData>,
245
- query: string,
246
- opts: AIFilterOptions = {},
247
- ): Promise<AIFilterResult> {
248
- const schema = buildColumnSchema(api)
249
- const prompt =
250
- `You are a data-grid filter planner. Translate the user's natural-language ` +
251
- `query into a strict-JSON plan that the grid can apply.\n\n` +
252
- `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
253
- `Output JSON schema:\n` +
254
- `{ "filters": [{"field": "<one of the columns above>", ` +
255
- `"operator": "contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank", ` +
256
- `"value": "<string>"}], ` +
257
- `"sort": [{"field": "<column>", "desc": true|false}], ` +
258
- `"rationale": "<one-sentence explanation>" }\n\n` +
259
- `User query: ${query}\n\n` +
260
- `Return JSON only, no prose.`
261
-
262
- const result = await callJSON<AIFilterResult>({
263
- prompt,
264
- task: 'filter',
265
- signal: opts.signal,
266
- maxOutputTokens: 400,
267
- })
268
-
269
- // Defensive: drop anything that doesn't match a real column. Models love
270
- // to invent plausible-sounding field names; we'd rather skip a clause
271
- // than throw at runtime.
272
- const valid = new Set(schema.map((c) => c.field))
273
- result.filters = (result.filters ?? []).filter((f) => valid.has(f.field))
274
- result.sort = (result.sort ?? []).filter((s) => valid.has(s.field))
275
-
276
- if (opts.apply) {
277
- api.clearAllFilters()
278
- api.clearSort()
279
- for (const f of result.filters) {
280
- api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' })
281
- }
282
- // Multiple sort clauses get applied last-wins because the public
283
- // `setSort` is single-key. Multi-sort is on the roadmap.
284
- const last = result.sort[result.sort.length - 1]
285
- if (last) api.setSort(last.field, last.desc ? 'desc' : 'asc')
286
- }
287
-
288
- return result
289
- }
290
-
291
- // ---------------------------------------------------------------------------
292
- // 2. Smart fill
293
- // ---------------------------------------------------------------------------
294
-
295
- /** One worked example teaching smart-fill what to produce for a row. */
296
- export type AISmartFillExample = { input: Record<string, unknown>; output: unknown }
297
-
298
- /** Proposed values for the blank cells of one column, each with a confidence score. */
299
- export type AISmartFillResult<TValue = unknown> = {
300
- field: string
301
- predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>
302
- rationale: string
303
- }
304
-
305
- /** Options for `aiSmartFill` - which column to fill, which rows, and the examples to learn from. */
306
- export type AISmartFillOptions = {
307
- /** Target column - the one whose values we want filled. */
308
- field: string
309
- /** Index of rows the model should propose values for. If omitted, every
310
- * row whose current `field` value is `null`, `undefined` or `''` is
311
- * selected automatically. */
312
- targetRowIndices?: number[]
313
- /**
314
- * Worked examples the user has already filled in. Required - the
315
- * model needs at least one to know the pattern, two or more to lock
316
- * the schema. We don't pull these from the grid automatically because
317
- * "edited" vs "untouched" isn't a state SvGrid exposes today.
318
- */
319
- examples: AISmartFillExample[]
320
- signal?: AbortSignal
321
- }
322
-
323
- /**
324
- * Given a column and a few user-provided examples, propose values for the
325
- * untouched rows. Returns predictions only - the caller chooses whether to
326
- * commit them via `api.setCellValue`. This is the right shape for an
327
- * accept-per-cell UX with confidence-coloured highlights.
328
- */
329
- export async function aiSmartFill<
330
- TFeatures extends TableFeatures,
331
- TData extends RowData,
332
- TValue = unknown,
333
- >(
334
- api: SvGridApi<TFeatures, TData>,
335
- opts: AISmartFillOptions,
336
- ): Promise<AISmartFillResult<TValue>> {
337
- if (opts.examples.length === 0) {
338
- throw new Error('@svgrid/grid ai: aiSmartFill requires at least one example.')
339
- }
340
- const data = api.getData()
341
- const targets =
342
- opts.targetRowIndices ??
343
- data
344
- .map((row, i) => {
345
- const v = (row as Record<string, unknown>)[opts.field]
346
- return v == null || v === '' ? i : -1
347
- })
348
- .filter((i) => i >= 0)
349
-
350
- if (targets.length === 0) {
351
- return { field: opts.field, predictions: [], rationale: 'No empty cells to fill.' }
352
- }
353
-
354
- const examplesBlock = opts.examples
355
- .map((ex, i) => `Example ${i + 1}: input=${JSON.stringify(ex.input)} -> output=${JSON.stringify(ex.output)}`)
356
- .join('\n')
357
-
358
- const targetRowsBlock = targets
359
- .map((i) => `Row ${i}: ${JSON.stringify(data[i])}`)
360
- .join('\n')
361
-
362
- const prompt =
363
- `You are filling in a single column of a data grid based on user-provided ` +
364
- `examples. Match the pattern in the examples exactly.\n\n` +
365
- `Target column: ${opts.field}\n\n` +
366
- `Examples:\n${examplesBlock}\n\n` +
367
- `Rows to fill:\n${targetRowsBlock}\n\n` +
368
- `Return strict JSON only:\n` +
369
- `{ "predictions": [{"rowIndex": <number>, "value": <inferred value>, ` +
370
- `"confidence": <0..1>}], "rationale": "<one-sentence pattern description>" }`
371
-
372
- const result = await callJSON<{
373
- predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>
374
- rationale: string
375
- }>({
376
- prompt,
377
- task: 'smart-fill',
378
- signal: opts.signal,
379
- maxOutputTokens: 600,
380
- })
381
-
382
- return {
383
- field: opts.field,
384
- predictions: result.predictions ?? [],
385
- rationale: result.rationale ?? '',
386
- }
387
- }
388
-
389
- // ---------------------------------------------------------------------------
390
- // 3. Summarise
391
- // ---------------------------------------------------------------------------
392
-
393
- /** What to summarise: one row, the selection, a group, or the whole set. */
394
- export type AISummarizeTarget =
395
- | { kind: 'row'; rowIndex: number }
396
- | { kind: 'all' }
397
- | { kind: 'selection'; rowIndices: number[] }
398
- | { kind: 'group'; field: string; value: unknown }
399
-
400
- /** A generated summary: prose, bullets, and the columns the model leaned on. */
401
- export type AISummary = {
402
- text: string
403
- bullets: string[]
404
- /** Field names the model thinks are the most load-bearing for the
405
- * story it just told. UI can highlight those columns. */
406
- highlightedFields: string[]
407
- }
408
-
409
- /** Options for `aiSummarize` - the target, and optionally the question to answer. */
410
- export type AISummarizeOptions = {
411
- target: AISummarizeTarget
412
- /** Optional question the user is trying to answer. Helps the model
413
- * bias the summary toward the relevant columns. */
414
- question?: string
415
- signal?: AbortSignal
416
- }
417
-
418
- /**
419
- * Ask the model to summarise a slice of the grid. Caps the row sample at
420
- * a model-friendly size; for huge selections it samples uniformly so the
421
- * summary stays representative without blowing the context window.
422
- */
423
- export async function aiSummarize<
424
- TFeatures extends TableFeatures,
425
- TData extends RowData,
426
- >(
427
- api: SvGridApi<TFeatures, TData>,
428
- opts: AISummarizeOptions,
429
- ): Promise<AISummary> {
430
- const all = api.getData()
431
- const rows: TData[] = (() => {
432
- const t = opts.target
433
- if (t.kind === 'row') {
434
- const r = all[t.rowIndex]
435
- return r ? [r] : []
436
- }
437
- if (t.kind === 'selection') {
438
- return t.rowIndices.map((i) => all[i]).filter((r): r is TData => r != null)
439
- }
440
- if (t.kind === 'group') {
441
- return all.filter((r) => (r as Record<string, unknown>)[t.field] === t.value)
442
- }
443
- return all.slice()
444
- })()
445
-
446
- if (rows.length === 0) {
447
- return { text: 'No rows in scope.', bullets: [], highlightedFields: [] }
448
- }
449
-
450
- // Uniform sample to stay inside a sensible context budget.
451
- const MAX_SAMPLE = 25
452
- const sample = rows.length <= MAX_SAMPLE
453
- ? rows
454
- : Array.from({ length: MAX_SAMPLE }, (_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]!)
455
-
456
- const schema = buildColumnSchema(api, 30)
457
- const prompt =
458
- `You are summarising a slice of a business data grid for a busy analyst.\n\n` +
459
- `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
460
- `Slice size: ${rows.length} row(s). Sampled rows shown below.\n` +
461
- `${sample.map((r) => JSON.stringify(r)).join('\n')}\n\n` +
462
- (opts.question ? `User's question: ${opts.question}\n\n` : '') +
463
- `Return strict JSON only:\n` +
464
- `{ "text": "<one short paragraph>", ` +
465
- `"bullets": ["<3-5 punchy bullets>"], ` +
466
- `"highlightedFields": ["<column names the summary leans on>"] }`
467
-
468
- const result = await callJSON<AISummary>({
469
- prompt,
470
- task: 'summarize',
471
- signal: opts.signal,
472
- maxOutputTokens: 600,
473
- })
474
- return {
475
- text: result.text ?? '',
476
- bullets: result.bullets ?? [],
477
- highlightedFields: result.highlightedFields ?? [],
478
- }
479
- }
480
-
481
- // ---------------------------------------------------------------------------
482
- // 4. Classify (free-text -> bucketed value)
483
- // ---------------------------------------------------------------------------
484
-
485
- /** Options for `aiClassify` - the column to label and the categories to choose from. */
486
- export type AIClassifyOptions = {
487
- /** Column whose free-text we're classifying. */
488
- inputField: string
489
- /** Target column the model should write to. */
490
- outputField: string
491
- /** Allowed values. The model is constrained to pick one. */
492
- classes: string[]
493
- /** Optional one-line description of each class (acts as a labeling rubric). */
494
- classDescriptions?: Record<string, string>
495
- /** Rows to classify. Defaults to all. */
496
- targetRowIndices?: number[]
497
- signal?: AbortSignal
498
- }
499
-
500
- /** Proposed category labels per row, with the model's reasoning. */
501
- export type AIClassifyResult = {
502
- inputField: string
503
- outputField: string
504
- predictions: Array<{ rowIndex: number; value: string; confidence: number }>
505
- }
506
-
507
- /**
508
- * Bucket free-text cells into one of a known set of classes. The model
509
- * is constrained to pick from `opts.classes`; predictions outside the set
510
- * are dropped so the caller can rely on the output being clean enum
511
- * values it can write straight back into the grid.
512
- */
513
- export async function aiClassify<
514
- TFeatures extends TableFeatures,
515
- TData extends RowData,
516
- >(
517
- api: SvGridApi<TFeatures, TData>,
518
- opts: AIClassifyOptions,
519
- ): Promise<AIClassifyResult> {
520
- const data = api.getData()
521
- const targets = opts.targetRowIndices ?? data.map((_, i) => i)
522
- const rubric = opts.classDescriptions
523
- ? Object.entries(opts.classDescriptions)
524
- .map(([k, v]) => `- ${k}: ${v}`)
525
- .join('\n')
526
- : opts.classes.map((c) => `- ${c}`).join('\n')
527
-
528
- const rowsBlock = targets
529
- .map((i) => `Row ${i}: ${JSON.stringify((data[i] as Record<string, unknown>)?.[opts.inputField] ?? '')}`)
530
- .join('\n')
531
-
532
- const prompt =
533
- `You are a strict text classifier. For each row, pick exactly one ` +
534
- `label from the list. If unsure, pick the closest match and lower the ` +
535
- `confidence.\n\n` +
536
- `Allowed labels (with optional rubric):\n${rubric}\n\n` +
537
- `Rows to classify (text from column "${opts.inputField}"):\n${rowsBlock}\n\n` +
538
- `Return strict JSON only:\n` +
539
- `{ "predictions": [{"rowIndex": <number>, "value": "<label>", "confidence": <0..1>}] }`
540
-
541
- const result = await callJSON<{
542
- predictions: Array<{ rowIndex: number; value: string; confidence: number }>
543
- }>({
544
- prompt,
545
- task: 'classify',
546
- signal: opts.signal,
547
- maxOutputTokens: Math.min(2000, 30 + targets.length * 30),
548
- })
549
-
550
- const allowed = new Set(opts.classes)
551
- return {
552
- inputField: opts.inputField,
553
- outputField: opts.outputField,
554
- predictions: (result.predictions ?? []).filter((p) => allowed.has(p.value)),
555
- }
556
- }
557
-
558
- // ---------------------------------------------------------------------------
559
- // 5. Natural-language export
560
- // ---------------------------------------------------------------------------
561
-
562
- const EXPORT_FORMATS: ExportFormat[] = ['xlsx', 'xls', 'pdf', 'csv', 'tsv', 'html', 'json', 'xml', 'md']
563
-
564
- /** An export the model derived from a request: format, columns, and scope. */
565
- export type AIExportPlan = {
566
- format: ExportFormat
567
- filters: AIFilterClause[]
568
- sort: AISortClause[]
569
- groupBy: string[]
570
- /** Plain-English explanation of how the model read the request. */
571
- rationale: string
572
- }
573
-
574
- /** Options for `aiExport` - preview the plan, or run the export it describes. */
575
- export type AIExportOptions = {
576
- /**
577
- * Also apply the filter / sort / grouping to the grid (mutating the view) so
578
- * it mirrors the export. Default FALSE - the export is self-contained (it
579
- * computes its own rows), so the grid is left untouched unless you opt in.
580
- */
581
- apply?: boolean
582
- /** Actually download the file. Default true; set false to preview the plan. */
583
- run?: boolean
584
- /** Base filename (no extension). Default 'export'. */
585
- filename?: string
586
- signal?: AbortSignal
587
- }
588
-
589
- /**
590
- * Turn a natural-language request ("export EU orders from Q2 as a grouped PDF")
591
- * into an export: the model returns a `{ format, filters, sort, groupBy }` plan
592
- * against the grid's columns; we apply the filter/sort to the grid and hand the
593
- * result to the registered export engine (@svgrid/enterprise). Returns the plan
594
- * so the UI can show what it did (or preview it first with `run: false`).
595
- */
596
- export async function aiExport<
597
- TFeatures extends TableFeatures,
598
- TData extends RowData,
599
- >(
600
- api: SvGridApi<TFeatures, TData>,
601
- query: string,
602
- opts: AIExportOptions = {},
603
- ): Promise<AIExportPlan> {
604
- const schema = buildColumnSchema(api)
605
- const prompt =
606
- `You are an export assistant for a data grid. Translate the user's request ` +
607
- `into a strict-JSON export plan.\n\n` +
608
- `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
609
- `Output JSON schema:\n` +
610
- `{ "format": "xlsx"|"xls"|"pdf"|"csv"|"tsv"|"html"|"json"|"xml"|"md", ` +
611
- `"filters": [{"field":"<column>","operator":"contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank","value":"<string>"}], ` +
612
- `"sort": [{"field":"<column>","desc":true|false}], ` +
613
- `"groupBy": ["<column>"], ` +
614
- `"rationale": "<one sentence>" }\n\n` +
615
- `Rules: use the format the user names (default "xlsx"); only use column ` +
616
- `names from the list above; "grouped" / "group by X" -> groupBy. ` +
617
- `Return JSON only, no prose.\n\n` +
618
- `User request: ${query}`
619
-
620
- const plan = await callJSON<AIExportPlan>({
621
- prompt,
622
- task: 'export',
623
- signal: opts.signal,
624
- maxOutputTokens: 500,
625
- })
626
-
627
- // Defensive validation - drop invented fields, clamp the format.
628
- const valid = new Set(schema.map((c) => c.field))
629
- plan.format = EXPORT_FORMATS.includes(plan.format) ? plan.format : 'xlsx'
630
- plan.filters = (plan.filters ?? []).filter((f) => valid.has(f.field))
631
- plan.sort = (plan.sort ?? []).filter((s) => valid.has(s.field))
632
- plan.groupBy = (plan.groupBy ?? []).filter((g) => valid.has(g))
633
- plan.rationale = plan.rationale ?? ''
634
-
635
- // Optionally mirror the plan onto the grid (opt-in). Off by default so the
636
- // export never disturbs the user's current view.
637
- if (opts.apply === true) {
638
- api.clearAllFilters()
639
- api.clearSort()
640
- for (const f of plan.filters) {
641
- api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' })
642
- }
643
- const last = plan.sort[plan.sort.length - 1]
644
- if (last) api.setSort(last.field, last.desc ? 'desc' : 'asc')
645
- if (plan.groupBy.length > 0) {
646
- try {
647
- api.setGroupBy(plan.groupBy)
648
- } catch {
649
- // grouping feature not enabled - the export still groups on its own
650
- }
651
- }
652
- }
653
-
654
- // Planning is always free; WRITING the file uses the export engine registered
655
- // by @svgrid/enterprise (export-provider seam). Without it, we return the plan
656
- // so the UI can still show what the AI decided - the download just no-ops.
657
- const runExport = getExportProvider()
658
- if (opts.run !== false && runExport) {
659
- // Compute the export rows from the plan directly (filter + sort + make
660
- // contiguous by group) rather than reading the grid's reactive displayed
661
- // rows - so the download always has exactly the intended data.
662
- const exportRows = applyPlanToRows(api.getData(), plan)
663
- await runExport(api, {
664
- format: plan.format,
665
- filename: opts.filename ?? 'export',
666
- rows: exportRows,
667
- ...(plan.groupBy.length > 0 ? { groupBy: plan.groupBy } : {}),
668
- })
669
- }
670
- return plan
671
- }
672
-
673
- /** Evaluate one AI filter clause against a raw row value. */
674
- function matchesClause(row: Record<string, unknown>, clause: AIFilterClause): boolean {
675
- const v = row[clause.field]
676
- const val = clause.value ?? ''
677
- switch (clause.operator) {
678
- case 'contains':
679
- return String(v ?? '').toLowerCase().includes(val.toLowerCase())
680
- case 'equals':
681
- return String(v ?? '').toLowerCase() === val.toLowerCase()
682
- case 'startsWith':
683
- return String(v ?? '').toLowerCase().startsWith(val.toLowerCase())
684
- case 'greaterThan':
685
- return Number(v) > Number(val)
686
- case 'lessThan':
687
- return Number(v) < Number(val)
688
- case 'isBlank':
689
- return v == null || v === ''
690
- default:
691
- return true
692
- }
693
- }
694
-
695
- /** Filter + sort + (stable) group the raw rows per an export plan. */
696
- function applyPlanToRows<TData extends RowData>(
697
- data: ReadonlyArray<TData>,
698
- plan: AIExportPlan,
699
- ): TData[] {
700
- let rows: TData[] = data.slice()
701
- if (plan.filters.length > 0) {
702
- rows = rows.filter((r) =>
703
- plan.filters.every((f) => matchesClause(r as Record<string, unknown>, f)),
704
- )
705
- }
706
- const last = plan.sort[plan.sort.length - 1]
707
- if (last) {
708
- rows = [...rows].sort((a, b) => {
709
- const av = (a as Record<string, unknown>)[last.field]
710
- const bv = (b as Record<string, unknown>)[last.field]
711
- const na = Number(av)
712
- const nb = Number(bv)
713
- let cmp: number
714
- if (Number.isFinite(na) && Number.isFinite(nb)) cmp = na - nb
715
- else cmp = String(av ?? '').localeCompare(String(bv ?? ''))
716
- return last.desc ? -cmp : cmp
717
- })
718
- }
719
- // Contiguous grouping (first-seen order) so PDF group rows + Excel outline
720
- // line up.
721
- if (plan.groupBy.length > 0) {
722
- const buckets = new Map<string, TData[]>()
723
- for (const r of rows) {
724
- const key = plan.groupBy
725
- .map((k) => String((r as Record<string, unknown>)[k] ?? ''))
726
- .join('')
727
- const bucket = buckets.get(key)
728
- if (bucket) bucket.push(r)
729
- else buckets.set(key, [r])
730
- }
731
- rows = [...buckets.values()].flat()
732
- }
733
- return rows
734
- }
735
-
736
- // ---------------------------------------------------------------------------
737
- // 6. Find anomalies
738
- // ---------------------------------------------------------------------------
739
-
740
- /** One flagged value, with why it stands out and how strongly. */
741
- export type AIAnomaly = {
742
- /** Index into the SCANNED rows (target order), when the model pins one row. */
743
- rowIndex?: number
744
- field?: string
745
- value?: unknown
746
- reason: string
747
- severity: 'low' | 'medium' | 'high'
748
- }
749
-
750
- /** Everything an anomaly scan flagged across the rows it looked at. */
751
- export type AIAnomalyResult = {
752
- anomalies: AIAnomaly[]
753
- summary: string
754
- }
755
-
756
- /** Options for `aiFindAnomalies` - which rows and columns to scan. */
757
- export type AIAnomalyOptions = {
758
- /** Which rows to scan. Defaults to the whole dataset. */
759
- target?: AISummarizeTarget
760
- /** Optional focus, e.g. "look at pricing and margins". */
761
- question?: string
762
- signal?: AbortSignal
763
- }
764
-
765
- function sliceForTarget<TFeatures extends TableFeatures, TData extends RowData>(
766
- api: SvGridApi<TFeatures, TData>,
767
- target: AISummarizeTarget,
768
- ): TData[] {
769
- const all = api.getData()
770
- if (target.kind === 'row') {
771
- const r = all[target.rowIndex]
772
- return r ? [r] : []
773
- }
774
- if (target.kind === 'selection') {
775
- return target.rowIndices.map((i) => all[i]).filter((r): r is TData => r != null)
776
- }
777
- if (target.kind === 'group') {
778
- return all.filter((r) => (r as Record<string, unknown>)[target.field] === target.value)
779
- }
780
- return all.slice()
781
- }
782
-
783
- /**
784
- * Scan a slice of the grid (all / selection / group) for anomalies - outliers,
785
- * suspicious values, inconsistencies - and return a structured list plus a
786
- * one-line summary. Pairs naturally with an export: "find the odd ones, then
787
- * export just those".
788
- */
789
- export async function aiFindAnomalies<
790
- TFeatures extends TableFeatures,
791
- TData extends RowData,
792
- >(
793
- api: SvGridApi<TFeatures, TData>,
794
- opts: AIAnomalyOptions = {},
795
- ): Promise<AIAnomalyResult> {
796
- const rows = sliceForTarget(api, opts.target ?? { kind: 'all' })
797
- if (rows.length === 0) return { anomalies: [], summary: 'No rows in scope.' }
798
-
799
- const MAX_SAMPLE = 40
800
- const sample =
801
- rows.length <= MAX_SAMPLE
802
- ? rows
803
- : Array.from(
804
- { length: MAX_SAMPLE },
805
- (_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]!,
806
- )
807
-
808
- const schema = buildColumnSchema(api, 30)
809
- const prompt =
810
- `You are a data-quality analyst. Scan the rows below for anomalies: ` +
811
- `numeric outliers, impossible / inconsistent values, unexpected blanks, ` +
812
- `and values that break the pattern of the column.\n\n` +
813
- `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
814
- `Rows (index is 0-based into this list):\n` +
815
- `${sample.map((r, i) => `${i}: ${JSON.stringify(r)}`).join('\n')}\n\n` +
816
- (opts.question ? `Focus: ${opts.question}\n\n` : '') +
817
- `Return strict JSON only:\n` +
818
- `{ "anomalies": [{"rowIndex": <number|null>, "field": "<column|null>", ` +
819
- `"reason": "<why it's odd>", "severity": "low"|"medium"|"high"}], ` +
820
- `"summary": "<one sentence>" }`
821
-
822
- const result = await callJSON<AIAnomalyResult>({
823
- prompt,
824
- task: 'anomaly',
825
- signal: opts.signal,
826
- maxOutputTokens: 800,
827
- })
828
- return {
829
- anomalies: result.anomalies ?? [],
830
- summary: result.summary ?? '',
831
- }
832
- }
833
-
834
- // ---------------------------------------------------------------------------
835
- // 7. Natural-language chart ("chart this")
836
- // ---------------------------------------------------------------------------
837
-
838
- /** Chart shapes the model may choose from when planning a visualisation. */
839
- export type AIChartType = 'bar' | 'line' | 'area' | 'pie'
840
-
841
- /** A chart the model proposed: its type, and the fields to plot. */
842
- export type AIChartPlan = {
843
- type: AIChartType
844
- /** Group-by (category-axis) column field, or null. */
845
- dimension: string | null
846
- /** Split-by column field: one series per distinct value, or null. */
847
- series: string | null
848
- /** Measure (value-axis) column field, or null. */
849
- measure: string | null
850
- reduce: 'sum' | 'avg' | 'count'
851
- stacked: boolean
852
- logScale: boolean
853
- timeAxis: boolean
854
- valueFormat: 'number' | 'currency' | 'percent'
855
- rationale: string
856
- }
857
-
858
- /** Options for `aiChart` - preview the plan, or render it into the grid. */
859
- export type AIChartOptions = {
860
- /** Apply the plan to the grid's chart panel (open + configure). Default false. */
861
- apply?: boolean
862
- signal?: AbortSignal
863
- }
864
-
865
- /**
866
- * Translate a natural-language request into a chart plan for the grid's built-in
867
- * `charting` panel. Validates every field against the real schema, then (with
868
- * `apply: true`) pushes it into the panel through `api.configureChart`.
869
- */
870
- export async function aiChart<
871
- TFeatures extends TableFeatures,
872
- TData extends RowData,
873
- >(
874
- api: SvGridApi<TFeatures, TData>,
875
- query: string,
876
- opts: AIChartOptions = {},
877
- ): Promise<AIChartPlan> {
878
- const schema = buildColumnSchema(api)
879
- const prompt =
880
- `You are a charting assistant for a data grid. Translate the user's request ` +
881
- `into a strict-JSON chart plan the grid can render.\n\n` +
882
- `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
883
- `Output JSON schema:\n` +
884
- `{ "type": "bar"|"line"|"area"|"pie", ` +
885
- `"dimension": "<a categorical column to group by>", ` +
886
- `"series": "<a second categorical column to split into series, or null>", ` +
887
- `"measure": "<a numeric column to aggregate>", ` +
888
- `"reduce": "sum"|"avg"|"count", ` +
889
- `"stacked": true|false, ` +
890
- `"logScale": true|false, ` +
891
- `"timeAxis": true|false, ` +
892
- `"valueFormat": "number"|"currency"|"percent", ` +
893
- `"rationale": "<one-sentence explanation>" }\n\n` +
894
- `Rules: pick "dimension" and "series" from text/date columns and "measure" ` +
895
- `from a numeric column; use only column names from the list above; ` +
896
- `"stacked"/"stack" -> stacked:true; "log"/"logarithmic" -> logScale:true; ` +
897
- `"over time"/"by date"/a date dimension -> timeAxis:true; ` +
898
- `money/revenue/price/$ -> valueFormat:"currency"; rate/%/share -> valueFormat:"percent"; ` +
899
- `else valueFormat:"number". default reduce is "sum". ` +
900
- `Return JSON only, no prose.\n\n` +
901
- `User request: ${query}`
902
-
903
- const plan = await callJSON<AIChartPlan>({
904
- prompt,
905
- task: 'chart',
906
- signal: opts.signal,
907
- maxOutputTokens: 300,
908
- })
909
-
910
- const valid = new Set(schema.map((c) => c.field))
911
- const numericFields = new Set(schema.filter((c) => c.type === 'number').map((c) => c.field))
912
- const CHART_TYPES: AIChartType[] = ['bar', 'line', 'area', 'pie']
913
- plan.type = CHART_TYPES.includes(plan.type) ? plan.type : 'bar'
914
- plan.dimension = plan.dimension && valid.has(plan.dimension) ? plan.dimension : null
915
- plan.series = plan.series && valid.has(plan.series) && plan.series !== plan.dimension ? plan.series : null
916
- plan.measure =
917
- plan.measure && numericFields.has(plan.measure)
918
- ? plan.measure
919
- : (schema.find((c) => c.type === 'number')?.field ?? null)
920
- plan.reduce = ['sum', 'avg', 'count'].includes(plan.reduce) ? plan.reduce : 'sum'
921
- plan.stacked = plan.stacked === true
922
- plan.logScale = plan.logScale === true
923
- plan.timeAxis = plan.timeAxis === true
924
- plan.valueFormat = ['number', 'currency', 'percent'].includes(plan.valueFormat) ? plan.valueFormat : 'number'
925
- plan.rationale = plan.rationale ?? ''
926
-
927
- if (opts.apply === true) {
928
- const cfg = api as unknown as { configureChart?: (c: Record<string, unknown>) => void }
929
- cfg.configureChart?.({
930
- open: true,
931
- type: plan.type,
932
- dimension: plan.dimension,
933
- series: plan.series,
934
- measure: plan.measure,
935
- reduce: plan.reduce,
936
- stacked: plan.stacked,
937
- logScale: plan.logScale,
938
- timeAxis: plan.timeAxis,
939
- valueFormat: plan.valueFormat,
940
- })
941
- }
942
-
943
- return plan
944
- }
945
-
946
- /**
947
- * Wire the grid's chart-panel AI button to the model: registers a handler (via
948
- * `api.setChartAiHandler`) that runs `aiChart` and returns the plan for the
949
- * panel to apply + explain. Call once after `onApiReady`. `installEnterprise`
950
- * calls this for you.
951
- */
952
- export function enableAiCharting<
953
- TFeatures extends TableFeatures,
954
- TData extends RowData,
955
- >(api: SvGridApi<TFeatures, TData>): void {
956
- const hook = api as unknown as {
957
- setChartAiHandler?: (
958
- fn: ((prompt: string) => Promise<Record<string, unknown> | null>) | null,
959
- ) => void
960
- }
961
- hook.setChartAiHandler?.(async (prompt: string) => {
962
- const plan = await aiChart(api, prompt)
963
- return {
964
- type: plan.type,
965
- dimension: plan.dimension,
966
- series: plan.series,
967
- measure: plan.measure,
968
- reduce: plan.reduce,
969
- stacked: plan.stacked,
970
- logScale: plan.logScale,
971
- timeAxis: plan.timeAxis,
972
- valueFormat: plan.valueFormat,
973
- rationale: plan.rationale,
974
- }
975
- })
976
- }
977
-
978
- /**
979
- * Remove the natural-language chart handler, hiding the AI button in the chart
980
- * panel. The inverse of `enableAiCharting`; safe to call when none was set.
981
- */
982
- export function disableAiCharting<
983
- TFeatures extends TableFeatures,
984
- TData extends RowData,
985
- >(api: SvGridApi<TFeatures, TData>): void {
986
- const hook = api as unknown as { setChartAiHandler?: (fn: null) => void }
987
- hook.setChartAiHandler?.(null)
988
- }
989
-
990
- // ---------------------------------------------------------------------------
991
- // 8. Mock provider for examples + tests
992
- // ---------------------------------------------------------------------------
993
-
994
- /**
995
- * A deterministic provider that returns canned, schema-shaped responses
996
- * for each task. Wire it in via `setAIProvider(mockAIProvider)` to make
997
- * the AI demo work end-to-end without a real model key. Not for production.
998
- */
999
- export const mockAIProvider: AIProvider = async (req) => {
1000
- // Tiny artificial delay so the UI's "thinking" state is visible.
1001
- await new Promise((r) => setTimeout(r, 350 + Math.random() * 400))
1002
-
1003
- if (req.task === 'filter') {
1004
- const q = extractUserQuery(req.prompt)
1005
- return JSON.stringify(buildMockFilter(req.prompt, q))
1006
- }
1007
- if (req.task === 'smart-fill') {
1008
- return JSON.stringify(buildMockSmartFill(req.prompt))
1009
- }
1010
- if (req.task === 'summarize') {
1011
- return JSON.stringify(buildMockSummary(req.prompt))
1012
- }
1013
- if (req.task === 'classify') {
1014
- return JSON.stringify(buildMockClassify(req.prompt))
1015
- }
1016
- if (req.task === 'export') {
1017
- return JSON.stringify(buildMockExport(req.prompt))
1018
- }
1019
- if (req.task === 'anomaly') {
1020
- return JSON.stringify(buildMockAnomaly(req.prompt))
1021
- }
1022
- if (req.task === 'chart') {
1023
- return JSON.stringify(buildMockChart(req.prompt))
1024
- }
1025
- return '{}'
1026
- }
1027
-
1028
- function buildMockChart(prompt: string): AIChartPlan {
1029
- const q = extractUserRequest(prompt)
1030
- const typed = extractFieldTypes(prompt)
1031
- const textFields = typed.filter((f) => f.type === 'string' || f.type === 'date').map((f) => f.name)
1032
- const numberFields = typed.filter((f) => f.type === 'number').map((f) => f.name)
1033
-
1034
- const type: AIChartType =
1035
- /\bline\b|\btrend\b|over time/.test(q) ? 'line'
1036
- : /\barea\b/.test(q) ? 'area'
1037
- : /\bpie\b|share|proportion|breakdown/.test(q) ? 'pie'
1038
- : 'bar'
1039
-
1040
- const byMatch = q.match(/\bby\s+([a-z0-9_ ]+?)(?:\s+(?:split|stacked|grouped|by|as|,|$))/)
1041
- const pickText = (hint?: string): string | null => {
1042
- if (hint) {
1043
- const f = textFields.find((t) => t.toLowerCase() === hint.trim() || (hint.trim().length >= 4 && t.toLowerCase().includes(hint.trim())))
1044
- if (f) return f
1045
- }
1046
- return null
1047
- }
1048
- const dimension = pickText(byMatch?.[1]) ?? textFields[0] ?? null
1049
- const series =
1050
- /\b(split|stack(?:ed)?|by product|by category|per)\b/.test(q)
1051
- ? (textFields.find((t) => t !== dimension) ?? null)
1052
- : null
1053
- const measure = numberFields.find((n) => q.includes(n.toLowerCase())) ?? numberFields[0] ?? null
1054
- const reduce: 'sum' | 'avg' | 'count' =
1055
- /\b(average|avg|mean)\b/.test(q) ? 'avg' : /\b(count|number of|how many)\b/.test(q) ? 'count' : 'sum'
1056
- const stacked = /\bstack(ed)?\b/.test(q)
1057
- const logScale = /\b(log|logarithmic)\b/.test(q)
1058
- const timeAxis = /\b(over time|by date|by day|by month|by week|time series|timeline|trend)\b/.test(q)
1059
- const valueFormat: 'number' | 'currency' | 'percent' =
1060
- /\b(currency|money|revenue|sales|price|cost|\$|dollar)\b/.test(q) || /(price|revenue|amount|cost|sales)/i.test(measure ?? '')
1061
- ? 'currency'
1062
- : /\b(percent|percentage|%|rate|share)\b/.test(q)
1063
- ? 'percent'
1064
- : 'number'
1065
-
1066
- return {
1067
- type, dimension, series, measure, reduce, stacked, logScale, timeAxis, valueFormat,
1068
- rationale:
1069
- `${type} chart of ${reduce}(${measure ?? 'value'}) by ${dimension ?? 'category'}` +
1070
- `${series ? `, split by ${series}` : ''}${stacked ? ', stacked' : ''}` +
1071
- `${logScale ? ', log scale' : ''}${timeAxis ? ', date axis' : ''} (mock - wire a real model for genuine parsing).`,
1072
- }
1073
- }
1074
-
1075
- function extractUserRequest(prompt: string): string {
1076
- const m = prompt.match(/User request:\s*([\s\S]+)$/)
1077
- return (m?.[1] ?? '').trim().toLowerCase()
1078
- }
1079
-
1080
- function buildMockExport(prompt: string): AIExportPlan {
1081
- const q = extractUserRequest(prompt)
1082
- const fields = extractFields(prompt)
1083
- // Reuse the filter mock (it reads "User query:"; feed it a compatible line).
1084
- const filterPlan = buildMockFilter(prompt + `\nUser query: ${q}\n`, q)
1085
-
1086
- // Format keyword routing.
1087
- const format: ExportFormat =
1088
- /\bpdf\b/.test(q) ? 'pdf'
1089
- : /\bxls\b(?!x)/.test(q) || /97-2003|legacy excel/.test(q) ? 'xls'
1090
- : /\b(xlsx|excel|spreadsheet|workbook)\b/.test(q) ? 'xlsx'
1091
- : /\b(markdown|md)\b/.test(q) ? 'md'
1092
- : /\bjson\b/.test(q) ? 'json'
1093
- : /\bxml\b/.test(q) ? 'xml'
1094
- : /\btsv\b/.test(q) ? 'tsv'
1095
- : /\bhtml\b/.test(q) ? 'html'
1096
- : /\bcsv\b/.test(q) ? 'csv'
1097
- : 'xlsx'
1098
-
1099
- // Grouping: "group by X" / "grouped by X", else "grouped" -> a categorical field.
1100
- const groupBy: string[] = []
1101
- const byMatch = q.match(/group(?:ed)?\s+by\s+([a-z0-9_ ,]+)/)
1102
- if (byMatch) {
1103
- for (const token of byMatch[1]!.split(/[, ]+/).filter(Boolean)) {
1104
- // Exact field match, or a substring match only for tokens long enough to
1105
- // be meaningful (so "a"/"as" don't match "amount").
1106
- const f = fields.find(
1107
- (ff) => ff.toLowerCase() === token || (token.length >= 4 && ff.toLowerCase().includes(token)),
1108
- )
1109
- if (f && !groupBy.includes(f)) groupBy.push(f)
1110
- }
1111
- } else if (/\bgroup(ed)?\b/.test(q)) {
1112
- const cat = fields.find((f) => /region|country|category|status|stage|type|group|dept|team/i.test(f))
1113
- if (cat) groupBy.push(cat)
1114
- }
1115
-
1116
- return {
1117
- format,
1118
- filters: filterPlan.filters,
1119
- sort: filterPlan.sort,
1120
- groupBy,
1121
- rationale: `Export as ${format}${groupBy.length ? `, grouped by ${groupBy.join(' / ')}` : ''}${filterPlan.filters.length ? `; ${filterPlan.rationale}` : ''}`,
1122
- }
1123
- }
1124
-
1125
- function buildMockAnomaly(prompt: string): AIAnomalyResult {
1126
- // Parse the sampled rows, flag the numeric outliers per numeric field.
1127
- const rowsBlock = prompt.match(/Rows \(index is 0-based into this list\):\n([\s\S]*?)\n\n/)?.[1] ?? ''
1128
- const parsed = rowsBlock
1129
- .split('\n')
1130
- .map((line) => {
1131
- const m = line.match(/^(\d+):\s*(\{[\s\S]*\})$/)
1132
- if (!m) return null
1133
- const row = safeParse(m[2]!) as Record<string, unknown> | null
1134
- return row ? { idx: parseInt(m[1]!, 10), row } : null
1135
- })
1136
- .filter((r): r is { idx: number; row: Record<string, unknown> } => !!r)
1137
-
1138
- if (parsed.length === 0) {
1139
- return { anomalies: [], summary: 'No rows to scan (mock).' }
1140
- }
1141
-
1142
- // Genuinely numeric fields only: every value is null or a real number (so
1143
- // booleans like `inStock` and id-ish strings are excluded). Also skip
1144
- // identifier / row-index columns - a max "id" isn't an anomaly.
1145
- const isIdLike = (f: string) => /(^id$|_id$|index|idx|^#|guid|uuid|serial|rownum)/i.test(f)
1146
- const numericFields = Object.keys(parsed[0]!.row).filter(
1147
- (f) =>
1148
- !isIdLike(f) &&
1149
- parsed.some((p) => typeof p.row[f] === 'number') &&
1150
- parsed.every((p) => p.row[f] == null || typeof p.row[f] === 'number'),
1151
- )
1152
-
1153
- const anomalies: AIAnomaly[] = []
1154
- for (const f of numericFields.slice(0, 2)) {
1155
- let maxIdx = -1
1156
- let maxVal = -Infinity
1157
- for (const p of parsed) {
1158
- const n = Number(p.row[f])
1159
- if (Number.isFinite(n) && n > maxVal) {
1160
- maxVal = n
1161
- maxIdx = p.idx
1162
- }
1163
- }
1164
- if (maxIdx >= 0) {
1165
- anomalies.push({
1166
- rowIndex: maxIdx,
1167
- field: f,
1168
- value: maxVal,
1169
- reason: `${f} = ${maxVal} is the highest in the sample and may be an outlier`,
1170
- severity: 'medium',
1171
- })
1172
- }
1173
- }
1174
-
1175
- return {
1176
- anomalies,
1177
- summary:
1178
- anomalies.length > 0
1179
- ? `Flagged ${anomalies.length} potential outlier${anomalies.length === 1 ? '' : 's'} (mock heuristic - wire a real model for genuine analysis).`
1180
- : 'No obvious anomalies in the sample (mock).',
1181
- }
1182
- }
1183
-
1184
- function extractUserQuery(prompt: string): string {
1185
- const m = prompt.match(/User query:\s*(.+?)\n/)
1186
- return (m?.[1] ?? '').toLowerCase()
1187
- }
1188
-
1189
- function extractFields(prompt: string): string[] {
1190
- const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
1191
- if (!m) return []
1192
- return (m[1] ?? '')
1193
- .split('\n')
1194
- .map((l) => l.match(/^- (\w+)/)?.[1])
1195
- .filter((s): s is string => !!s)
1196
- }
1197
-
1198
- /** Parse the "- name (type): ..." schema block into {name, type} pairs. */
1199
- function extractFieldTypes(prompt: string): Array<{ name: string; type: string }> {
1200
- const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
1201
- if (!m) return []
1202
- return (m[1] ?? '')
1203
- .split('\n')
1204
- .map((l) => {
1205
- const mm = l.match(/^- (\w+)\s*\((\w+)\)/)
1206
- return mm ? { name: mm[1]!, type: mm[2]! } : null
1207
- })
1208
- .filter((x): x is { name: string; type: string } => !!x)
1209
- }
1210
-
1211
- function buildMockFilter(prompt: string, q: string): AIFilterResult {
1212
- const fields = extractFields(prompt)
1213
- const filters: AIFilterClause[] = []
1214
- const sort: AISortClause[] = []
1215
- const rationale: string[] = []
1216
-
1217
- // Greedy keyword routing. Real model would be smarter; this only needs
1218
- // to convince the demo viewer the pipeline works.
1219
- const numberWord = q.match(/(?:over|above|>|greater than)\s+\$?([\d.,]+)([kmb])?/)
1220
- const lessWord = q.match(/(?:under|below|<|less than)\s+\$?([\d.,]+)([kmb])?/)
1221
- // Pick a NUMBER-typed field (never a boolean like `inStock`), money-named
1222
- // ones first so "$300" targets price/amount rather than a count/index.
1223
- const numberTyped = extractFieldTypes(prompt).filter((f) => f.type === 'number').map((f) => f.name)
1224
- const moneyRe = /(price|amount|cost|revenue|total|value|salary|arr|fee|spend|budget|sales)/i
1225
- const numberPool = numberTyped.length > 0 ? numberTyped : fields
1226
- const numberFields = [
1227
- ...numberPool.filter((f) => moneyRe.test(f)),
1228
- ...numberPool.filter((f) => !moneyRe.test(f)),
1229
- ]
1230
-
1231
- if (numberWord && numberFields[0]) {
1232
- const raw = parseFloat(numberWord[1]!.replace(/,/g, ''))
1233
- const mul = numberWord[2] === 'k' ? 1_000 : numberWord[2] === 'm' ? 1_000_000 : numberWord[2] === 'b' ? 1_000_000_000 : 1
1234
- filters.push({ field: numberFields[0], operator: 'greaterThan', value: String(raw * mul) })
1235
- rationale.push(`amount > ${raw}${numberWord[2] ?? ''}`)
1236
- } else if (lessWord && numberFields[0]) {
1237
- const raw = parseFloat(lessWord[1]!.replace(/,/g, ''))
1238
- const mul = lessWord[2] === 'k' ? 1_000 : lessWord[2] === 'm' ? 1_000_000 : 1
1239
- filters.push({ field: numberFields[0], operator: 'lessThan', value: String(raw * mul) })
1240
- rationale.push(`amount < ${raw}${lessWord[2] ?? ''}`)
1241
- }
1242
-
1243
- // Quoted phrases -> contains on a likely text field.
1244
- const quote = q.match(/"([^"]+)"|'([^']+)'/)
1245
- const textFields = fields.filter((f) => /(name|company|customer|title|owner|status|region|category|industry)/i.test(f))
1246
- if (quote) {
1247
- const term = quote[1] ?? quote[2] ?? ''
1248
- if (textFields[0]) {
1249
- filters.push({ field: textFields[0], operator: 'contains', value: term })
1250
- rationale.push(`text contains "${term}"`)
1251
- }
1252
- }
1253
-
1254
- // Person-name routing -> match owner/contact fields.
1255
- const personOwners = ['sasha', 'jamie', 'casey', 'drew', 'robin', 'morgan', 'riley', 'quinn']
1256
- for (const n of personOwners) {
1257
- if (q.includes(n)) {
1258
- const ownerField = fields.find((f) => /owner|rep|assigned/i.test(f)) ?? fields.find((f) => /name/i.test(f))
1259
- if (ownerField) {
1260
- filters.push({ field: ownerField, operator: 'contains', value: n })
1261
- rationale.push(`owner ~ "${n}"`)
1262
- break
1263
- }
1264
- }
1265
- }
1266
-
1267
- // Region routing.
1268
- for (const r of ['NA', 'EMEA', 'APAC', 'LATAM']) {
1269
- if (q.toUpperCase().includes(r)) {
1270
- const regionField = fields.find((f) => /region/i.test(f))
1271
- if (regionField) {
1272
- filters.push({ field: regionField, operator: 'equals', value: r })
1273
- rationale.push(`region = ${r}`)
1274
- break
1275
- }
1276
- }
1277
- }
1278
-
1279
- // Status routing - any token in the query that matches a known status.
1280
- for (const s of ['active', 'pending', 'won', 'lost', 'live', 'paused', 'shipped', 'delivered']) {
1281
- if (q.includes(s)) {
1282
- const f = fields.find((f) => /status|stage/i.test(f))
1283
- if (f) {
1284
- filters.push({ field: f, operator: 'equals', value: s })
1285
- rationale.push(`status = ${s}`)
1286
- break
1287
- }
1288
- }
1289
- }
1290
-
1291
- // Sort detection.
1292
- if (/(highest|largest|biggest|top|most)/.test(q)) {
1293
- const f = numberFields[0]
1294
- if (f) { sort.push({ field: f, desc: true }); rationale.push(`sort by ${f} desc`) }
1295
- } else if (/(lowest|smallest|least|cheapest)/.test(q)) {
1296
- const f = numberFields[0]
1297
- if (f) { sort.push({ field: f, desc: false }); rationale.push(`sort by ${f} asc`) }
1298
- } else if (/(newest|recent|latest)/.test(q)) {
1299
- const dateField = fields.find((f) => /date|at|time/i.test(f))
1300
- if (dateField) { sort.push({ field: dateField, desc: true }); rationale.push(`sort by ${dateField} desc`) }
1301
- } else if (/(oldest)/.test(q)) {
1302
- const dateField = fields.find((f) => /date|at|time/i.test(f))
1303
- if (dateField) { sort.push({ field: dateField, desc: false }); rationale.push(`sort by ${dateField} asc`) }
1304
- }
1305
-
1306
- return {
1307
- filters,
1308
- sort,
1309
- rationale: rationale.length
1310
- ? `Interpreted: ${rationale.join(' AND ')}.`
1311
- : `Couldn't identify a clear filter for "${q}". Showing all rows.`,
1312
- }
1313
- }
1314
-
1315
- function buildMockSmartFill(prompt: string): { predictions: Array<{ rowIndex: number; value: unknown; confidence: number }>; rationale: string } {
1316
- // Extract the target column and the rows-to-fill block; copy the first
1317
- // example's "output" pattern verbatim so the demo always returns
1318
- // something believable. Real models do much better - that's the point.
1319
- const fieldMatch = prompt.match(/Target column:\s*(\w+)/)
1320
- const rowsMatch = prompt.match(/Rows to fill:\n([\s\S]*?)\n\n/)
1321
- const exMatch = prompt.match(/Example 1: input=.* -> output=(.+)/)
1322
- const targetField = fieldMatch?.[1] ?? ''
1323
- const rowLines = (rowsMatch?.[1] ?? '').split('\n').filter(Boolean)
1324
- const exampleOutput = exMatch?.[1] ? safeParse(exMatch[1]) : ''
1325
- const predictions = rowLines
1326
- .map((line) => {
1327
- const m = line.match(/^Row (\d+): (\{.+\})/)
1328
- if (!m) return null
1329
- const rowIndex = parseInt(m[1]!, 10)
1330
- const row = safeParse(m[2]!) as Record<string, unknown> | null
1331
- if (!row) return null
1332
- const value = inferFromRow(targetField, row, exampleOutput)
1333
- return { rowIndex, value, confidence: 0.78 + Math.random() * 0.18 }
1334
- })
1335
- .filter((p): p is { rowIndex: number; value: unknown; confidence: number } => !!p)
1336
- return {
1337
- predictions,
1338
- rationale: `Inferred from ${exMatch ? 'the supplied' : 'no'} examples; mocked deterministically for the demo.`,
1339
- }
1340
- }
1341
-
1342
- function safeParse(s: string): unknown {
1343
- try { return JSON.parse(s) } catch { return null }
1344
- }
1345
-
1346
- function inferFromRow(field: string, row: Record<string, unknown>, exampleOutput: unknown): unknown {
1347
- // Mock heuristics that produce a value that "looks right" in common
1348
- // demo scenarios. The real provider would route through a real model.
1349
- if (field === 'priority') {
1350
- const arr = Number(row.arr ?? row.amount ?? row.price ?? 0)
1351
- return arr > 100_000 ? 'high' : arr > 30_000 ? 'medium' : 'low'
1352
- }
1353
- if (field === 'tier') {
1354
- const arr = Number(row.arr ?? row.amount ?? 0)
1355
- return arr > 500_000 ? 'enterprise' : arr > 100_000 ? 'growth' : 'starter'
1356
- }
1357
- if (field === 'tags' || field === 'category') {
1358
- return typeof exampleOutput === 'string' ? exampleOutput : 'auto-tag'
1359
- }
1360
- if (typeof exampleOutput === 'string') return exampleOutput
1361
- if (typeof exampleOutput === 'number') return exampleOutput
1362
- return exampleOutput ?? 'auto'
1363
- }
1364
-
1365
- function buildMockSummary(prompt: string): AISummary {
1366
- const sliceMatch = prompt.match(/Slice size: (\d+) row/)
1367
- const n = sliceMatch ? parseInt(sliceMatch[1]!, 10) : 0
1368
- const fields = extractSummaryFields(prompt)
1369
- return {
1370
- text:
1371
- n === 1
1372
- ? `Single record. Notable signals come from ${fields.slice(0, 2).join(' and ') || 'the available fields'}.`
1373
- : `${n} rows in scope. The distribution skews toward live / active records, with a long tail in ${fields[0] ?? 'amount'}.`,
1374
- bullets: [
1375
- `${n} row${n === 1 ? '' : 's'} sampled`,
1376
- fields[0] ? `Largest variance in ${fields[0]}` : 'Tight clustering across visible fields',
1377
- fields[1] ? `${fields[1]} concentrates around the median` : 'Few outliers',
1378
- 'Mock summary - wire setAIProvider() to a real model for actual analysis',
1379
- ],
1380
- highlightedFields: fields.slice(0, 3),
1381
- }
1382
- }
1383
-
1384
- function extractSummaryFields(prompt: string): string[] {
1385
- const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
1386
- if (!m) return []
1387
- return (m[1] ?? '')
1388
- .split('\n')
1389
- .map((l) => l.match(/^- (\w+)/)?.[1])
1390
- .filter((s): s is string => !!s)
1391
- }
1392
-
1393
- function buildMockClassify(prompt: string): { predictions: Array<{ rowIndex: number; value: string; confidence: number }> } {
1394
- const labelsMatch = prompt.match(/Allowed labels[\s\S]*?:\n([\s\S]*?)\n\n/)
1395
- // Capture the label up to the first colon, whitespace or end-of-line so
1396
- // we don't pick up the rubric ("- at-risk: churn signals..." -> "at-risk").
1397
- const labels = (labelsMatch?.[1] ?? '')
1398
- .split('\n')
1399
- .map((l) => l.match(/^-\s*([^\s:]+)/)?.[1])
1400
- .filter((s): s is string => !!s)
1401
- const rowLines = (prompt.match(/Rows to classify[\s\S]*?:\n([\s\S]*?)\n\n/)?.[1] ?? '').split('\n').filter(Boolean)
1402
- const predictions = rowLines.map((line) => {
1403
- const m = line.match(/^Row (\d+): "(.*)"/)
1404
- if (!m || labels.length === 0) return null
1405
- const rowIndex = parseInt(m[1]!, 10)
1406
- const text = (m[2] ?? '').toLowerCase()
1407
- // Pick the label whose token appears in the text; otherwise hash.
1408
- const hit = labels.find((l) => text.includes(l.toLowerCase()))
1409
- const value = hit ?? labels[Math.abs(hashStr(text)) % labels.length]!
1410
- return { rowIndex, value, confidence: hit ? 0.92 : 0.6 + Math.random() * 0.2 }
1411
- }).filter((p): p is { rowIndex: number; value: string; confidence: number } => !!p)
1412
- return { predictions }
1413
- }
1414
-
1415
- function hashStr(s: string): number {
1416
- let h = 0
1417
- for (let i = 0; i < s.length; i += 1) h = (h * 31 + s.charCodeAt(i)) | 0
1418
- return h
1419
- }
1
+ /**
2
+ * Pro AI feature pack
3
+ * -------------------
4
+ *
5
+ * Three jobs every analyst wishes a data grid could do:
6
+ *
7
+ * 1. Natural-language filter / sort (`aiFilter`)
8
+ * "show me deals closing this quarter over $50k owned by Sasha"
9
+ * -> { filters: [...], sort: [...] }
10
+ *
11
+ * 2. Smart fill (`aiSmartFill`)
12
+ * User edits two cells in a column with example values; the
13
+ * Grid proposes the rest. Excel "Flash Fill" pattern.
14
+ *
15
+ * 3. Summarise rows (`aiSummarize`)
16
+ * Single row, the current selection, a group key, or the whole
17
+ * filtered view -> a one-paragraph summary.
18
+ *
19
+ * The grid stays headless / model-agnostic. The consumer supplies an
20
+ * `AIProvider` that knows how to call OpenAI / Anthropic / a local
21
+ * model / a server-side proxy. We never bundle a model client.
22
+ *
23
+ * Built-in + free: the AI helpers live in `@svgrid/grid`. They ship no model
24
+ * client and do nothing until you register a provider with `setAIProvider(...)`,
25
+ * so they add nothing to the base bundle unless you actually use them.
26
+ */
27
+
28
+ import type { RowData, SvGridApi, TableFeatures } from './index'
29
+ import { getExportProvider } from './export-provider'
30
+
31
+ // Export formats an AI export can plan. WRITING the enterprise formats (xlsx /
32
+ // pdf / html / xml / md) needs the export engine from `@svgrid/enterprise`
33
+ // (registered via the export-provider seam); csv / tsv / json are also handled
34
+ // by that engine when present. The union is declared locally so the free grid
35
+ // carries no dependency on the enterprise export module.
36
+ type ExportFormat = 'xlsx' | 'xls' | 'pdf' | 'csv' | 'tsv' | 'html' | 'json' | 'xml' | 'md'
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Provider contract
40
+ // ---------------------------------------------------------------------------
41
+
42
+ /**
43
+ * Shape every consumer-provided model adapter must implement. Keeping this
44
+ * tiny (one async call, two response formats) lets the same adapter drive
45
+ * OpenAI's `chat.completions`, Anthropic's `messages`, a self-hosted
46
+ * llama.cpp endpoint, or a server-side proxy. The grid only cares that the
47
+ * provider eventually returns a string we can parse.
48
+ */
49
+ export type AIProvider = (request: AIRequest) => Promise<string>
50
+
51
+ /** One call out to the model, as the grid builds it. Providers receive this. */
52
+ export type AIRequest = {
53
+ /** Full prompt the grid built for the model. Already includes column
54
+ * schema and any sampled rows where applicable. */
55
+ prompt: string
56
+ /** When 'json', the provider should ask the model to return strict
57
+ * JSON only - no prose. We parse the response with JSON.parse and
58
+ * throw a typed error on failure. */
59
+ responseFormat?: 'text' | 'json'
60
+ /** Honored if the underlying transport supports cancellation. */
61
+ signal?: AbortSignal
62
+ /** Free-form tag for telemetry / logging. One of: 'filter',
63
+ * 'smart-fill', 'summarize', 'classify'. */
64
+ task: AITask
65
+ /** Soft hint to the provider about how many tokens we expect back.
66
+ * Useful for routing small jobs to a cheaper model. */
67
+ maxOutputTokens?: number
68
+ }
69
+
70
+ /** Which helper produced a request - carried on {@link AIRequest} for routing and telemetry. */
71
+ export type AITask = 'filter' | 'smart-fill' | 'summarize' | 'classify' | 'export' | 'anomaly' | 'chart'
72
+
73
+ let provider: AIProvider | null = null
74
+
75
+ /**
76
+ * Register the model adapter every AI call will route through. Call once
77
+ * at app boot. Passing `null` clears the provider and AI calls revert to
78
+ * throwing "no provider" errors.
79
+ */
80
+ export function setAIProvider(p: AIProvider | null): void {
81
+ provider = p
82
+ }
83
+
84
+ /** The provider registered with `setAIProvider`, or null when none is. */
85
+ export function getAIProvider(): AIProvider | null {
86
+ return provider
87
+ }
88
+
89
+ /** Whether an AI provider is registered. Gate AI affordances on this so the UI stays honest. */
90
+ export function hasAIProvider(): boolean {
91
+ return provider != null
92
+ }
93
+
94
+ class NoProviderError extends Error {
95
+ constructor() {
96
+ super(
97
+ '@svgrid/grid ai: no AI provider registered. Call setAIProvider(fn) ' +
98
+ 'with an adapter that talks to OpenAI / Anthropic / your proxy.',
99
+ )
100
+ this.name = 'NoProviderError'
101
+ }
102
+ }
103
+
104
+ class BadJsonError extends Error {
105
+ constructor(raw: string) {
106
+ super(
107
+ '@svgrid/grid ai: provider returned non-JSON for a json-format request. ' +
108
+ `First 200 chars: ${raw.slice(0, 200)}`,
109
+ )
110
+ this.name = 'BadJsonError'
111
+ }
112
+ }
113
+
114
+ async function callProvider(req: AIRequest): Promise<string> {
115
+ if (!provider) throw new NoProviderError()
116
+ return provider(req)
117
+ }
118
+
119
+ async function callJSON<T>(req: AIRequest): Promise<T> {
120
+ const raw = await callProvider({ ...req, responseFormat: 'json' })
121
+ // Models occasionally wrap JSON in markdown code fences even when asked
122
+ // for raw JSON. Strip a single fenced block if present, then parse.
123
+ const stripped = raw.trim().replace(/^```(?:json)?\s*|\s*```$/g, '')
124
+ try {
125
+ return JSON.parse(stripped) as T
126
+ } catch {
127
+ throw new BadJsonError(raw)
128
+ }
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Helpers - build column schema + row sample from the grid API
133
+ // ---------------------------------------------------------------------------
134
+
135
+ type ColumnSchemaEntry = {
136
+ field: string
137
+ type: 'string' | 'number' | 'boolean' | 'date' | 'unknown'
138
+ sampleValues: unknown[]
139
+ }
140
+
141
+ /**
142
+ * Inspect the first N rows the grid is holding to infer a typed schema +
143
+ * a handful of sample values per column. This is the context every AI
144
+ * task needs and the most expensive thing to build, so the helpers cache
145
+ * the result inside one task call rather than calling api.getData()
146
+ * repeatedly.
147
+ */
148
+ function buildColumnSchema<
149
+ TFeatures extends TableFeatures,
150
+ TData extends RowData,
151
+ >(api: SvGridApi<TFeatures, TData>, sampleSize = 50): ColumnSchemaEntry[] {
152
+ const data = api.getData()
153
+ if (data.length === 0) return []
154
+ const slice = data.slice(0, Math.min(data.length, sampleSize))
155
+ const fields = new Set<string>()
156
+ for (const row of slice) {
157
+ for (const k of Object.keys(row as object)) fields.add(k)
158
+ }
159
+ const out: ColumnSchemaEntry[] = []
160
+ for (const field of fields) {
161
+ const values: unknown[] = []
162
+ for (const row of slice) {
163
+ const v = (row as Record<string, unknown>)[field]
164
+ if (v != null) values.push(v)
165
+ if (values.length >= 5) break
166
+ }
167
+ out.push({
168
+ field,
169
+ type: inferType(values),
170
+ sampleValues: values,
171
+ })
172
+ }
173
+ return out
174
+ }
175
+
176
+ function inferType(samples: unknown[]): ColumnSchemaEntry['type'] {
177
+ if (samples.length === 0) return 'unknown'
178
+ const v = samples[0]
179
+ if (typeof v === 'number') return 'number'
180
+ if (typeof v === 'boolean') return 'boolean'
181
+ if (typeof v === 'string') {
182
+ // Cheap ISO-date sniff so we route date-style filters correctly.
183
+ if (/^\d{4}-\d{2}-\d{2}/.test(v)) return 'date'
184
+ return 'string'
185
+ }
186
+ return 'unknown'
187
+ }
188
+
189
+ function schemaToPromptBlock(schema: ColumnSchemaEntry[]): string {
190
+ return schema
191
+ .map(
192
+ (c) =>
193
+ `- ${c.field} (${c.type}): e.g. ${c.sampleValues
194
+ .slice(0, 3)
195
+ .map((v) => JSON.stringify(v))
196
+ .join(', ')}`,
197
+ )
198
+ .join('\n')
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------
202
+ // 1. Natural-language filter / sort
203
+ // ---------------------------------------------------------------------------
204
+
205
+ /** One condition in a filter plan: a column, a comparison, and the value to match. */
206
+ export type AIFilterClause = {
207
+ field: string
208
+ operator: 'contains' | 'equals' | 'startsWith' | 'greaterThan' | 'lessThan' | 'isBlank'
209
+ value?: string
210
+ }
211
+ /** One ordering clause in a filter plan. */
212
+ export type AISortClause = { field: string; desc: boolean }
213
+
214
+ /** A natural-language query turned into filters and sorting, plus the model's reasoning. */
215
+ export type AIFilterResult = {
216
+ filters: AIFilterClause[]
217
+ sort: AISortClause[]
218
+ /** Plain-English explanation of how the model interpreted the query.
219
+ * Surface this in the UI so the user can confirm or undo. */
220
+ rationale: string
221
+ }
222
+
223
+ /** Options for `aiFilter` - preview the plan, or apply it straight to the grid. */
224
+ export type AIFilterOptions = {
225
+ /**
226
+ * When true, the helper not only RETURNS the plan but also applies it
227
+ * to the grid via `api.setFilter` / `api.setSort`. Defaults to false
228
+ * so callers can show a preview before committing.
229
+ */
230
+ apply?: boolean
231
+ signal?: AbortSignal
232
+ }
233
+
234
+ /**
235
+ * Translate a natural-language query into a filter+sort plan against
236
+ * the current grid's columns. The grid passes the column schema (names,
237
+ * types, sample values) to the model so it can pick the right field
238
+ * names without hallucinating.
239
+ */
240
+ export async function aiFilter<
241
+ TFeatures extends TableFeatures,
242
+ TData extends RowData,
243
+ >(
244
+ api: SvGridApi<TFeatures, TData>,
245
+ query: string,
246
+ opts: AIFilterOptions = {},
247
+ ): Promise<AIFilterResult> {
248
+ const schema = buildColumnSchema(api)
249
+ const prompt =
250
+ `You are a data-grid filter planner. Translate the user's natural-language ` +
251
+ `query into a strict-JSON plan that the grid can apply.\n\n` +
252
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
253
+ `Output JSON schema:\n` +
254
+ `{ "filters": [{"field": "<one of the columns above>", ` +
255
+ `"operator": "contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank", ` +
256
+ `"value": "<string>"}], ` +
257
+ `"sort": [{"field": "<column>", "desc": true|false}], ` +
258
+ `"rationale": "<one-sentence explanation>" }\n\n` +
259
+ `User query: ${query}\n\n` +
260
+ `Return JSON only, no prose.`
261
+
262
+ const result = await callJSON<AIFilterResult>({
263
+ prompt,
264
+ task: 'filter',
265
+ signal: opts.signal,
266
+ maxOutputTokens: 400,
267
+ })
268
+
269
+ // Defensive: drop anything that doesn't match a real column. Models love
270
+ // to invent plausible-sounding field names; we'd rather skip a clause
271
+ // than throw at runtime.
272
+ const valid = new Set(schema.map((c) => c.field))
273
+ result.filters = (result.filters ?? []).filter((f) => valid.has(f.field))
274
+ result.sort = (result.sort ?? []).filter((s) => valid.has(s.field))
275
+
276
+ if (opts.apply) {
277
+ api.clearAllFilters()
278
+ api.clearSort()
279
+ for (const f of result.filters) {
280
+ api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' })
281
+ }
282
+ // Multiple sort clauses get applied last-wins because the public
283
+ // `setSort` is single-key. Multi-sort is on the roadmap.
284
+ const last = result.sort[result.sort.length - 1]
285
+ if (last) api.setSort(last.field, last.desc ? 'desc' : 'asc')
286
+ }
287
+
288
+ return result
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // 2. Smart fill
293
+ // ---------------------------------------------------------------------------
294
+
295
+ /** One worked example teaching smart-fill what to produce for a row. */
296
+ export type AISmartFillExample = { input: Record<string, unknown>; output: unknown }
297
+
298
+ /** Proposed values for the blank cells of one column, each with a confidence score. */
299
+ export type AISmartFillResult<TValue = unknown> = {
300
+ field: string
301
+ predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>
302
+ rationale: string
303
+ }
304
+
305
+ /** Options for `aiSmartFill` - which column to fill, which rows, and the examples to learn from. */
306
+ export type AISmartFillOptions = {
307
+ /** Target column - the one whose values we want filled. */
308
+ field: string
309
+ /** Index of rows the model should propose values for. If omitted, every
310
+ * row whose current `field` value is `null`, `undefined` or `''` is
311
+ * selected automatically. */
312
+ targetRowIndices?: number[]
313
+ /**
314
+ * Worked examples the user has already filled in. Required - the
315
+ * model needs at least one to know the pattern, two or more to lock
316
+ * the schema. We don't pull these from the grid automatically because
317
+ * "edited" vs "untouched" isn't a state SvGrid exposes today.
318
+ */
319
+ examples: AISmartFillExample[]
320
+ signal?: AbortSignal
321
+ }
322
+
323
+ /**
324
+ * Given a column and a few user-provided examples, propose values for the
325
+ * untouched rows. Returns predictions only - the caller chooses whether to
326
+ * commit them via `api.setCellValue`. This is the right shape for an
327
+ * accept-per-cell UX with confidence-coloured highlights.
328
+ */
329
+ export async function aiSmartFill<
330
+ TFeatures extends TableFeatures,
331
+ TData extends RowData,
332
+ TValue = unknown,
333
+ >(
334
+ api: SvGridApi<TFeatures, TData>,
335
+ opts: AISmartFillOptions,
336
+ ): Promise<AISmartFillResult<TValue>> {
337
+ if (opts.examples.length === 0) {
338
+ throw new Error('@svgrid/grid ai: aiSmartFill requires at least one example.')
339
+ }
340
+ const data = api.getData()
341
+ const targets =
342
+ opts.targetRowIndices ??
343
+ data
344
+ .map((row, i) => {
345
+ const v = (row as Record<string, unknown>)[opts.field]
346
+ return v == null || v === '' ? i : -1
347
+ })
348
+ .filter((i) => i >= 0)
349
+
350
+ if (targets.length === 0) {
351
+ return { field: opts.field, predictions: [], rationale: 'No empty cells to fill.' }
352
+ }
353
+
354
+ const examplesBlock = opts.examples
355
+ .map((ex, i) => `Example ${i + 1}: input=${JSON.stringify(ex.input)} -> output=${JSON.stringify(ex.output)}`)
356
+ .join('\n')
357
+
358
+ const targetRowsBlock = targets
359
+ .map((i) => `Row ${i}: ${JSON.stringify(data[i])}`)
360
+ .join('\n')
361
+
362
+ const prompt =
363
+ `You are filling in a single column of a data grid based on user-provided ` +
364
+ `examples. Match the pattern in the examples exactly.\n\n` +
365
+ `Target column: ${opts.field}\n\n` +
366
+ `Examples:\n${examplesBlock}\n\n` +
367
+ `Rows to fill:\n${targetRowsBlock}\n\n` +
368
+ `Return strict JSON only:\n` +
369
+ `{ "predictions": [{"rowIndex": <number>, "value": <inferred value>, ` +
370
+ `"confidence": <0..1>}], "rationale": "<one-sentence pattern description>" }`
371
+
372
+ const result = await callJSON<{
373
+ predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>
374
+ rationale: string
375
+ }>({
376
+ prompt,
377
+ task: 'smart-fill',
378
+ signal: opts.signal,
379
+ maxOutputTokens: 600,
380
+ })
381
+
382
+ return {
383
+ field: opts.field,
384
+ predictions: result.predictions ?? [],
385
+ rationale: result.rationale ?? '',
386
+ }
387
+ }
388
+
389
+ // ---------------------------------------------------------------------------
390
+ // 3. Summarise
391
+ // ---------------------------------------------------------------------------
392
+
393
+ /** What to summarise: one row, the selection, a group, or the whole set. */
394
+ export type AISummarizeTarget =
395
+ | { kind: 'row'; rowIndex: number }
396
+ | { kind: 'all' }
397
+ | { kind: 'selection'; rowIndices: number[] }
398
+ | { kind: 'group'; field: string; value: unknown }
399
+
400
+ /** A generated summary: prose, bullets, and the columns the model leaned on. */
401
+ export type AISummary = {
402
+ text: string
403
+ bullets: string[]
404
+ /** Field names the model thinks are the most load-bearing for the
405
+ * story it just told. UI can highlight those columns. */
406
+ highlightedFields: string[]
407
+ }
408
+
409
+ /** Options for `aiSummarize` - the target, and optionally the question to answer. */
410
+ export type AISummarizeOptions = {
411
+ target: AISummarizeTarget
412
+ /** Optional question the user is trying to answer. Helps the model
413
+ * bias the summary toward the relevant columns. */
414
+ question?: string
415
+ signal?: AbortSignal
416
+ }
417
+
418
+ /**
419
+ * Ask the model to summarise a slice of the grid. Caps the row sample at
420
+ * a model-friendly size; for huge selections it samples uniformly so the
421
+ * summary stays representative without blowing the context window.
422
+ */
423
+ export async function aiSummarize<
424
+ TFeatures extends TableFeatures,
425
+ TData extends RowData,
426
+ >(
427
+ api: SvGridApi<TFeatures, TData>,
428
+ opts: AISummarizeOptions,
429
+ ): Promise<AISummary> {
430
+ const all = api.getData()
431
+ const rows: TData[] = (() => {
432
+ const t = opts.target
433
+ if (t.kind === 'row') {
434
+ const r = all[t.rowIndex]
435
+ return r ? [r] : []
436
+ }
437
+ if (t.kind === 'selection') {
438
+ return t.rowIndices.map((i) => all[i]).filter((r): r is TData => r != null)
439
+ }
440
+ if (t.kind === 'group') {
441
+ return all.filter((r) => (r as Record<string, unknown>)[t.field] === t.value)
442
+ }
443
+ return all.slice()
444
+ })()
445
+
446
+ if (rows.length === 0) {
447
+ return { text: 'No rows in scope.', bullets: [], highlightedFields: [] }
448
+ }
449
+
450
+ // Uniform sample to stay inside a sensible context budget.
451
+ const MAX_SAMPLE = 25
452
+ const sample = rows.length <= MAX_SAMPLE
453
+ ? rows
454
+ : Array.from({ length: MAX_SAMPLE }, (_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]!)
455
+
456
+ const schema = buildColumnSchema(api, 30)
457
+ const prompt =
458
+ `You are summarising a slice of a business data grid for a busy analyst.\n\n` +
459
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
460
+ `Slice size: ${rows.length} row(s). Sampled rows shown below.\n` +
461
+ `${sample.map((r) => JSON.stringify(r)).join('\n')}\n\n` +
462
+ (opts.question ? `User's question: ${opts.question}\n\n` : '') +
463
+ `Return strict JSON only:\n` +
464
+ `{ "text": "<one short paragraph>", ` +
465
+ `"bullets": ["<3-5 punchy bullets>"], ` +
466
+ `"highlightedFields": ["<column names the summary leans on>"] }`
467
+
468
+ const result = await callJSON<AISummary>({
469
+ prompt,
470
+ task: 'summarize',
471
+ signal: opts.signal,
472
+ maxOutputTokens: 600,
473
+ })
474
+ return {
475
+ text: result.text ?? '',
476
+ bullets: result.bullets ?? [],
477
+ highlightedFields: result.highlightedFields ?? [],
478
+ }
479
+ }
480
+
481
+ // ---------------------------------------------------------------------------
482
+ // 4. Classify (free-text -> bucketed value)
483
+ // ---------------------------------------------------------------------------
484
+
485
+ /** Options for `aiClassify` - the column to label and the categories to choose from. */
486
+ export type AIClassifyOptions = {
487
+ /** Column whose free-text we're classifying. */
488
+ inputField: string
489
+ /** Target column the model should write to. */
490
+ outputField: string
491
+ /** Allowed values. The model is constrained to pick one. */
492
+ classes: string[]
493
+ /** Optional one-line description of each class (acts as a labeling rubric). */
494
+ classDescriptions?: Record<string, string>
495
+ /** Rows to classify. Defaults to all. */
496
+ targetRowIndices?: number[]
497
+ signal?: AbortSignal
498
+ }
499
+
500
+ /** Proposed category labels per row, with the model's reasoning. */
501
+ export type AIClassifyResult = {
502
+ inputField: string
503
+ outputField: string
504
+ predictions: Array<{ rowIndex: number; value: string; confidence: number }>
505
+ }
506
+
507
+ /**
508
+ * Bucket free-text cells into one of a known set of classes. The model
509
+ * is constrained to pick from `opts.classes`; predictions outside the set
510
+ * are dropped so the caller can rely on the output being clean enum
511
+ * values it can write straight back into the grid.
512
+ */
513
+ export async function aiClassify<
514
+ TFeatures extends TableFeatures,
515
+ TData extends RowData,
516
+ >(
517
+ api: SvGridApi<TFeatures, TData>,
518
+ opts: AIClassifyOptions,
519
+ ): Promise<AIClassifyResult> {
520
+ const data = api.getData()
521
+ const targets = opts.targetRowIndices ?? data.map((_, i) => i)
522
+ const rubric = opts.classDescriptions
523
+ ? Object.entries(opts.classDescriptions)
524
+ .map(([k, v]) => `- ${k}: ${v}`)
525
+ .join('\n')
526
+ : opts.classes.map((c) => `- ${c}`).join('\n')
527
+
528
+ const rowsBlock = targets
529
+ .map((i) => `Row ${i}: ${JSON.stringify((data[i] as Record<string, unknown>)?.[opts.inputField] ?? '')}`)
530
+ .join('\n')
531
+
532
+ const prompt =
533
+ `You are a strict text classifier. For each row, pick exactly one ` +
534
+ `label from the list. If unsure, pick the closest match and lower the ` +
535
+ `confidence.\n\n` +
536
+ `Allowed labels (with optional rubric):\n${rubric}\n\n` +
537
+ `Rows to classify (text from column "${opts.inputField}"):\n${rowsBlock}\n\n` +
538
+ `Return strict JSON only:\n` +
539
+ `{ "predictions": [{"rowIndex": <number>, "value": "<label>", "confidence": <0..1>}] }`
540
+
541
+ const result = await callJSON<{
542
+ predictions: Array<{ rowIndex: number; value: string; confidence: number }>
543
+ }>({
544
+ prompt,
545
+ task: 'classify',
546
+ signal: opts.signal,
547
+ maxOutputTokens: Math.min(2000, 30 + targets.length * 30),
548
+ })
549
+
550
+ const allowed = new Set(opts.classes)
551
+ return {
552
+ inputField: opts.inputField,
553
+ outputField: opts.outputField,
554
+ predictions: (result.predictions ?? []).filter((p) => allowed.has(p.value)),
555
+ }
556
+ }
557
+
558
+ // ---------------------------------------------------------------------------
559
+ // 5. Natural-language export
560
+ // ---------------------------------------------------------------------------
561
+
562
+ const EXPORT_FORMATS: ExportFormat[] = ['xlsx', 'xls', 'pdf', 'csv', 'tsv', 'html', 'json', 'xml', 'md']
563
+
564
+ /** An export the model derived from a request: format, columns, and scope. */
565
+ export type AIExportPlan = {
566
+ format: ExportFormat
567
+ filters: AIFilterClause[]
568
+ sort: AISortClause[]
569
+ groupBy: string[]
570
+ /** Plain-English explanation of how the model read the request. */
571
+ rationale: string
572
+ }
573
+
574
+ /** Options for `aiExport` - preview the plan, or run the export it describes. */
575
+ export type AIExportOptions = {
576
+ /**
577
+ * Also apply the filter / sort / grouping to the grid (mutating the view) so
578
+ * it mirrors the export. Default FALSE - the export is self-contained (it
579
+ * computes its own rows), so the grid is left untouched unless you opt in.
580
+ */
581
+ apply?: boolean
582
+ /** Actually download the file. Default true; set false to preview the plan. */
583
+ run?: boolean
584
+ /** Base filename (no extension). Default 'export'. */
585
+ filename?: string
586
+ signal?: AbortSignal
587
+ }
588
+
589
+ /**
590
+ * Turn a natural-language request ("export EU orders from Q2 as a grouped PDF")
591
+ * into an export: the model returns a `{ format, filters, sort, groupBy }` plan
592
+ * against the grid's columns; we apply the filter/sort to the grid and hand the
593
+ * result to the registered export engine (@svgrid/enterprise). Returns the plan
594
+ * so the UI can show what it did (or preview it first with `run: false`).
595
+ */
596
+ export async function aiExport<
597
+ TFeatures extends TableFeatures,
598
+ TData extends RowData,
599
+ >(
600
+ api: SvGridApi<TFeatures, TData>,
601
+ query: string,
602
+ opts: AIExportOptions = {},
603
+ ): Promise<AIExportPlan> {
604
+ const schema = buildColumnSchema(api)
605
+ const prompt =
606
+ `You are an export assistant for a data grid. Translate the user's request ` +
607
+ `into a strict-JSON export plan.\n\n` +
608
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
609
+ `Output JSON schema:\n` +
610
+ `{ "format": "xlsx"|"xls"|"pdf"|"csv"|"tsv"|"html"|"json"|"xml"|"md", ` +
611
+ `"filters": [{"field":"<column>","operator":"contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank","value":"<string>"}], ` +
612
+ `"sort": [{"field":"<column>","desc":true|false}], ` +
613
+ `"groupBy": ["<column>"], ` +
614
+ `"rationale": "<one sentence>" }\n\n` +
615
+ `Rules: use the format the user names (default "xlsx"); only use column ` +
616
+ `names from the list above; "grouped" / "group by X" -> groupBy. ` +
617
+ `Return JSON only, no prose.\n\n` +
618
+ `User request: ${query}`
619
+
620
+ const plan = await callJSON<AIExportPlan>({
621
+ prompt,
622
+ task: 'export',
623
+ signal: opts.signal,
624
+ maxOutputTokens: 500,
625
+ })
626
+
627
+ // Defensive validation - drop invented fields, clamp the format.
628
+ const valid = new Set(schema.map((c) => c.field))
629
+ plan.format = EXPORT_FORMATS.includes(plan.format) ? plan.format : 'xlsx'
630
+ plan.filters = (plan.filters ?? []).filter((f) => valid.has(f.field))
631
+ plan.sort = (plan.sort ?? []).filter((s) => valid.has(s.field))
632
+ plan.groupBy = (plan.groupBy ?? []).filter((g) => valid.has(g))
633
+ plan.rationale = plan.rationale ?? ''
634
+
635
+ // Optionally mirror the plan onto the grid (opt-in). Off by default so the
636
+ // export never disturbs the user's current view.
637
+ if (opts.apply === true) {
638
+ api.clearAllFilters()
639
+ api.clearSort()
640
+ for (const f of plan.filters) {
641
+ api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' })
642
+ }
643
+ const last = plan.sort[plan.sort.length - 1]
644
+ if (last) api.setSort(last.field, last.desc ? 'desc' : 'asc')
645
+ if (plan.groupBy.length > 0) {
646
+ try {
647
+ api.setGroupBy(plan.groupBy)
648
+ } catch {
649
+ // grouping feature not enabled - the export still groups on its own
650
+ }
651
+ }
652
+ }
653
+
654
+ // Planning is always free; WRITING the file uses the export engine registered
655
+ // by @svgrid/enterprise (export-provider seam). Without it, we return the plan
656
+ // so the UI can still show what the AI decided - the download just no-ops.
657
+ const runExport = getExportProvider()
658
+ if (opts.run !== false && runExport) {
659
+ // Compute the export rows from the plan directly (filter + sort + make
660
+ // contiguous by group) rather than reading the grid's reactive displayed
661
+ // rows - so the download always has exactly the intended data.
662
+ const exportRows = applyPlanToRows(api.getData(), plan)
663
+ await runExport(api, {
664
+ format: plan.format,
665
+ filename: opts.filename ?? 'export',
666
+ rows: exportRows,
667
+ ...(plan.groupBy.length > 0 ? { groupBy: plan.groupBy } : {}),
668
+ })
669
+ }
670
+ return plan
671
+ }
672
+
673
+ /** Evaluate one AI filter clause against a raw row value. */
674
+ function matchesClause(row: Record<string, unknown>, clause: AIFilterClause): boolean {
675
+ const v = row[clause.field]
676
+ const val = clause.value ?? ''
677
+ switch (clause.operator) {
678
+ case 'contains':
679
+ return String(v ?? '').toLowerCase().includes(val.toLowerCase())
680
+ case 'equals':
681
+ return String(v ?? '').toLowerCase() === val.toLowerCase()
682
+ case 'startsWith':
683
+ return String(v ?? '').toLowerCase().startsWith(val.toLowerCase())
684
+ case 'greaterThan':
685
+ return Number(v) > Number(val)
686
+ case 'lessThan':
687
+ return Number(v) < Number(val)
688
+ case 'isBlank':
689
+ return v == null || v === ''
690
+ default:
691
+ return true
692
+ }
693
+ }
694
+
695
+ /** Filter + sort + (stable) group the raw rows per an export plan. */
696
+ function applyPlanToRows<TData extends RowData>(
697
+ data: ReadonlyArray<TData>,
698
+ plan: AIExportPlan,
699
+ ): TData[] {
700
+ let rows: TData[] = data.slice()
701
+ if (plan.filters.length > 0) {
702
+ rows = rows.filter((r) =>
703
+ plan.filters.every((f) => matchesClause(r as Record<string, unknown>, f)),
704
+ )
705
+ }
706
+ const last = plan.sort[plan.sort.length - 1]
707
+ if (last) {
708
+ rows = [...rows].sort((a, b) => {
709
+ const av = (a as Record<string, unknown>)[last.field]
710
+ const bv = (b as Record<string, unknown>)[last.field]
711
+ const na = Number(av)
712
+ const nb = Number(bv)
713
+ let cmp: number
714
+ if (Number.isFinite(na) && Number.isFinite(nb)) cmp = na - nb
715
+ else cmp = String(av ?? '').localeCompare(String(bv ?? ''))
716
+ return last.desc ? -cmp : cmp
717
+ })
718
+ }
719
+ // Contiguous grouping (first-seen order) so PDF group rows + Excel outline
720
+ // line up.
721
+ if (plan.groupBy.length > 0) {
722
+ const buckets = new Map<string, TData[]>()
723
+ for (const r of rows) {
724
+ const key = plan.groupBy
725
+ .map((k) => String((r as Record<string, unknown>)[k] ?? ''))
726
+ .join('')
727
+ const bucket = buckets.get(key)
728
+ if (bucket) bucket.push(r)
729
+ else buckets.set(key, [r])
730
+ }
731
+ rows = [...buckets.values()].flat()
732
+ }
733
+ return rows
734
+ }
735
+
736
+ // ---------------------------------------------------------------------------
737
+ // 6. Find anomalies
738
+ // ---------------------------------------------------------------------------
739
+
740
+ /** One flagged value, with why it stands out and how strongly. */
741
+ export type AIAnomaly = {
742
+ /** Index into the SCANNED rows (target order), when the model pins one row. */
743
+ rowIndex?: number
744
+ field?: string
745
+ value?: unknown
746
+ reason: string
747
+ severity: 'low' | 'medium' | 'high'
748
+ }
749
+
750
+ /** Everything an anomaly scan flagged across the rows it looked at. */
751
+ export type AIAnomalyResult = {
752
+ anomalies: AIAnomaly[]
753
+ summary: string
754
+ }
755
+
756
+ /** Options for `aiFindAnomalies` - which rows and columns to scan. */
757
+ export type AIAnomalyOptions = {
758
+ /** Which rows to scan. Defaults to the whole dataset. */
759
+ target?: AISummarizeTarget
760
+ /** Optional focus, e.g. "look at pricing and margins". */
761
+ question?: string
762
+ signal?: AbortSignal
763
+ }
764
+
765
+ function sliceForTarget<TFeatures extends TableFeatures, TData extends RowData>(
766
+ api: SvGridApi<TFeatures, TData>,
767
+ target: AISummarizeTarget,
768
+ ): TData[] {
769
+ const all = api.getData()
770
+ if (target.kind === 'row') {
771
+ const r = all[target.rowIndex]
772
+ return r ? [r] : []
773
+ }
774
+ if (target.kind === 'selection') {
775
+ return target.rowIndices.map((i) => all[i]).filter((r): r is TData => r != null)
776
+ }
777
+ if (target.kind === 'group') {
778
+ return all.filter((r) => (r as Record<string, unknown>)[target.field] === target.value)
779
+ }
780
+ return all.slice()
781
+ }
782
+
783
+ /**
784
+ * Scan a slice of the grid (all / selection / group) for anomalies - outliers,
785
+ * suspicious values, inconsistencies - and return a structured list plus a
786
+ * one-line summary. Pairs naturally with an export: "find the odd ones, then
787
+ * export just those".
788
+ */
789
+ export async function aiFindAnomalies<
790
+ TFeatures extends TableFeatures,
791
+ TData extends RowData,
792
+ >(
793
+ api: SvGridApi<TFeatures, TData>,
794
+ opts: AIAnomalyOptions = {},
795
+ ): Promise<AIAnomalyResult> {
796
+ const rows = sliceForTarget(api, opts.target ?? { kind: 'all' })
797
+ if (rows.length === 0) return { anomalies: [], summary: 'No rows in scope.' }
798
+
799
+ const MAX_SAMPLE = 40
800
+ const sample =
801
+ rows.length <= MAX_SAMPLE
802
+ ? rows
803
+ : Array.from(
804
+ { length: MAX_SAMPLE },
805
+ (_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]!,
806
+ )
807
+
808
+ const schema = buildColumnSchema(api, 30)
809
+ const prompt =
810
+ `You are a data-quality analyst. Scan the rows below for anomalies: ` +
811
+ `numeric outliers, impossible / inconsistent values, unexpected blanks, ` +
812
+ `and values that break the pattern of the column.\n\n` +
813
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
814
+ `Rows (index is 0-based into this list):\n` +
815
+ `${sample.map((r, i) => `${i}: ${JSON.stringify(r)}`).join('\n')}\n\n` +
816
+ (opts.question ? `Focus: ${opts.question}\n\n` : '') +
817
+ `Return strict JSON only:\n` +
818
+ `{ "anomalies": [{"rowIndex": <number|null>, "field": "<column|null>", ` +
819
+ `"reason": "<why it's odd>", "severity": "low"|"medium"|"high"}], ` +
820
+ `"summary": "<one sentence>" }`
821
+
822
+ const result = await callJSON<AIAnomalyResult>({
823
+ prompt,
824
+ task: 'anomaly',
825
+ signal: opts.signal,
826
+ maxOutputTokens: 800,
827
+ })
828
+ return {
829
+ anomalies: result.anomalies ?? [],
830
+ summary: result.summary ?? '',
831
+ }
832
+ }
833
+
834
+ // ---------------------------------------------------------------------------
835
+ // 7. Natural-language chart ("chart this")
836
+ // ---------------------------------------------------------------------------
837
+
838
+ /** Chart shapes the model may choose from when planning a visualisation. */
839
+ export type AIChartType = 'bar' | 'line' | 'area' | 'pie'
840
+
841
+ /** A chart the model proposed: its type, and the fields to plot. */
842
+ export type AIChartPlan = {
843
+ type: AIChartType
844
+ /** Group-by (category-axis) column field, or null. */
845
+ dimension: string | null
846
+ /** Split-by column field: one series per distinct value, or null. */
847
+ series: string | null
848
+ /** Measure (value-axis) column field, or null. */
849
+ measure: string | null
850
+ reduce: 'sum' | 'avg' | 'count'
851
+ stacked: boolean
852
+ logScale: boolean
853
+ timeAxis: boolean
854
+ valueFormat: 'number' | 'currency' | 'percent'
855
+ rationale: string
856
+ }
857
+
858
+ /** Options for `aiChart` - preview the plan, or render it into the grid. */
859
+ export type AIChartOptions = {
860
+ /** Apply the plan to the grid's chart panel (open + configure). Default false. */
861
+ apply?: boolean
862
+ signal?: AbortSignal
863
+ }
864
+
865
+ /**
866
+ * Translate a natural-language request into a chart plan for the grid's built-in
867
+ * `charting` panel. Validates every field against the real schema, then (with
868
+ * `apply: true`) pushes it into the panel through `api.configureChart`.
869
+ */
870
+ export async function aiChart<
871
+ TFeatures extends TableFeatures,
872
+ TData extends RowData,
873
+ >(
874
+ api: SvGridApi<TFeatures, TData>,
875
+ query: string,
876
+ opts: AIChartOptions = {},
877
+ ): Promise<AIChartPlan> {
878
+ const schema = buildColumnSchema(api)
879
+ const prompt =
880
+ `You are a charting assistant for a data grid. Translate the user's request ` +
881
+ `into a strict-JSON chart plan the grid can render.\n\n` +
882
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
883
+ `Output JSON schema:\n` +
884
+ `{ "type": "bar"|"line"|"area"|"pie", ` +
885
+ `"dimension": "<a categorical column to group by>", ` +
886
+ `"series": "<a second categorical column to split into series, or null>", ` +
887
+ `"measure": "<a numeric column to aggregate>", ` +
888
+ `"reduce": "sum"|"avg"|"count", ` +
889
+ `"stacked": true|false, ` +
890
+ `"logScale": true|false, ` +
891
+ `"timeAxis": true|false, ` +
892
+ `"valueFormat": "number"|"currency"|"percent", ` +
893
+ `"rationale": "<one-sentence explanation>" }\n\n` +
894
+ `Rules: pick "dimension" and "series" from text/date columns and "measure" ` +
895
+ `from a numeric column; use only column names from the list above; ` +
896
+ `"stacked"/"stack" -> stacked:true; "log"/"logarithmic" -> logScale:true; ` +
897
+ `"over time"/"by date"/a date dimension -> timeAxis:true; ` +
898
+ `money/revenue/price/$ -> valueFormat:"currency"; rate/%/share -> valueFormat:"percent"; ` +
899
+ `else valueFormat:"number". default reduce is "sum". ` +
900
+ `Return JSON only, no prose.\n\n` +
901
+ `User request: ${query}`
902
+
903
+ const plan = await callJSON<AIChartPlan>({
904
+ prompt,
905
+ task: 'chart',
906
+ signal: opts.signal,
907
+ maxOutputTokens: 300,
908
+ })
909
+
910
+ const valid = new Set(schema.map((c) => c.field))
911
+ const numericFields = new Set(schema.filter((c) => c.type === 'number').map((c) => c.field))
912
+ const CHART_TYPES: AIChartType[] = ['bar', 'line', 'area', 'pie']
913
+ plan.type = CHART_TYPES.includes(plan.type) ? plan.type : 'bar'
914
+ plan.dimension = plan.dimension && valid.has(plan.dimension) ? plan.dimension : null
915
+ plan.series = plan.series && valid.has(plan.series) && plan.series !== plan.dimension ? plan.series : null
916
+ plan.measure =
917
+ plan.measure && numericFields.has(plan.measure)
918
+ ? plan.measure
919
+ : (schema.find((c) => c.type === 'number')?.field ?? null)
920
+ plan.reduce = ['sum', 'avg', 'count'].includes(plan.reduce) ? plan.reduce : 'sum'
921
+ plan.stacked = plan.stacked === true
922
+ plan.logScale = plan.logScale === true
923
+ plan.timeAxis = plan.timeAxis === true
924
+ plan.valueFormat = ['number', 'currency', 'percent'].includes(plan.valueFormat) ? plan.valueFormat : 'number'
925
+ plan.rationale = plan.rationale ?? ''
926
+
927
+ if (opts.apply === true) {
928
+ const cfg = api as unknown as { configureChart?: (c: Record<string, unknown>) => void }
929
+ cfg.configureChart?.({
930
+ open: true,
931
+ type: plan.type,
932
+ dimension: plan.dimension,
933
+ series: plan.series,
934
+ measure: plan.measure,
935
+ reduce: plan.reduce,
936
+ stacked: plan.stacked,
937
+ logScale: plan.logScale,
938
+ timeAxis: plan.timeAxis,
939
+ valueFormat: plan.valueFormat,
940
+ })
941
+ }
942
+
943
+ return plan
944
+ }
945
+
946
+ /**
947
+ * Wire the grid's chart-panel AI button to the model: registers a handler (via
948
+ * `api.setChartAiHandler`) that runs `aiChart` and returns the plan for the
949
+ * panel to apply + explain. Call once after `onApiReady`. `installEnterprise`
950
+ * calls this for you.
951
+ */
952
+ export function enableAiCharting<
953
+ TFeatures extends TableFeatures,
954
+ TData extends RowData,
955
+ >(api: SvGridApi<TFeatures, TData>): void {
956
+ const hook = api as unknown as {
957
+ setChartAiHandler?: (
958
+ fn: ((prompt: string) => Promise<Record<string, unknown> | null>) | null,
959
+ ) => void
960
+ }
961
+ hook.setChartAiHandler?.(async (prompt: string) => {
962
+ const plan = await aiChart(api, prompt)
963
+ return {
964
+ type: plan.type,
965
+ dimension: plan.dimension,
966
+ series: plan.series,
967
+ measure: plan.measure,
968
+ reduce: plan.reduce,
969
+ stacked: plan.stacked,
970
+ logScale: plan.logScale,
971
+ timeAxis: plan.timeAxis,
972
+ valueFormat: plan.valueFormat,
973
+ rationale: plan.rationale,
974
+ }
975
+ })
976
+ }
977
+
978
+ /**
979
+ * Remove the natural-language chart handler, hiding the AI button in the chart
980
+ * panel. The inverse of `enableAiCharting`; safe to call when none was set.
981
+ */
982
+ export function disableAiCharting<
983
+ TFeatures extends TableFeatures,
984
+ TData extends RowData,
985
+ >(api: SvGridApi<TFeatures, TData>): void {
986
+ const hook = api as unknown as { setChartAiHandler?: (fn: null) => void }
987
+ hook.setChartAiHandler?.(null)
988
+ }
989
+
990
+ // ---------------------------------------------------------------------------
991
+ // 8. Mock provider for examples + tests
992
+ // ---------------------------------------------------------------------------
993
+
994
+ /**
995
+ * A deterministic provider that returns canned, schema-shaped responses
996
+ * for each task. Wire it in via `setAIProvider(mockAIProvider)` to make
997
+ * the AI demo work end-to-end without a real model key. Not for production.
998
+ */
999
+ export const mockAIProvider: AIProvider = async (req) => {
1000
+ // Tiny artificial delay so the UI's "thinking" state is visible.
1001
+ await new Promise((r) => setTimeout(r, 350 + Math.random() * 400))
1002
+
1003
+ if (req.task === 'filter') {
1004
+ const q = extractUserQuery(req.prompt)
1005
+ return JSON.stringify(buildMockFilter(req.prompt, q))
1006
+ }
1007
+ if (req.task === 'smart-fill') {
1008
+ return JSON.stringify(buildMockSmartFill(req.prompt))
1009
+ }
1010
+ if (req.task === 'summarize') {
1011
+ return JSON.stringify(buildMockSummary(req.prompt))
1012
+ }
1013
+ if (req.task === 'classify') {
1014
+ return JSON.stringify(buildMockClassify(req.prompt))
1015
+ }
1016
+ if (req.task === 'export') {
1017
+ return JSON.stringify(buildMockExport(req.prompt))
1018
+ }
1019
+ if (req.task === 'anomaly') {
1020
+ return JSON.stringify(buildMockAnomaly(req.prompt))
1021
+ }
1022
+ if (req.task === 'chart') {
1023
+ return JSON.stringify(buildMockChart(req.prompt))
1024
+ }
1025
+ return '{}'
1026
+ }
1027
+
1028
+ function buildMockChart(prompt: string): AIChartPlan {
1029
+ const q = extractUserRequest(prompt)
1030
+ const typed = extractFieldTypes(prompt)
1031
+ const textFields = typed.filter((f) => f.type === 'string' || f.type === 'date').map((f) => f.name)
1032
+ const numberFields = typed.filter((f) => f.type === 'number').map((f) => f.name)
1033
+
1034
+ const type: AIChartType =
1035
+ /\bline\b|\btrend\b|over time/.test(q) ? 'line'
1036
+ : /\barea\b/.test(q) ? 'area'
1037
+ : /\bpie\b|share|proportion|breakdown/.test(q) ? 'pie'
1038
+ : 'bar'
1039
+
1040
+ const byMatch = q.match(/\bby\s+([a-z0-9_ ]+?)(?:\s+(?:split|stacked|grouped|by|as|,|$))/)
1041
+ const pickText = (hint?: string): string | null => {
1042
+ if (hint) {
1043
+ const f = textFields.find((t) => t.toLowerCase() === hint.trim() || (hint.trim().length >= 4 && t.toLowerCase().includes(hint.trim())))
1044
+ if (f) return f
1045
+ }
1046
+ return null
1047
+ }
1048
+ const dimension = pickText(byMatch?.[1]) ?? textFields[0] ?? null
1049
+ const series =
1050
+ /\b(split|stack(?:ed)?|by product|by category|per)\b/.test(q)
1051
+ ? (textFields.find((t) => t !== dimension) ?? null)
1052
+ : null
1053
+ const measure = numberFields.find((n) => q.includes(n.toLowerCase())) ?? numberFields[0] ?? null
1054
+ const reduce: 'sum' | 'avg' | 'count' =
1055
+ /\b(average|avg|mean)\b/.test(q) ? 'avg' : /\b(count|number of|how many)\b/.test(q) ? 'count' : 'sum'
1056
+ const stacked = /\bstack(ed)?\b/.test(q)
1057
+ const logScale = /\b(log|logarithmic)\b/.test(q)
1058
+ const timeAxis = /\b(over time|by date|by day|by month|by week|time series|timeline|trend)\b/.test(q)
1059
+ const valueFormat: 'number' | 'currency' | 'percent' =
1060
+ /\b(currency|money|revenue|sales|price|cost|\$|dollar)\b/.test(q) || /(price|revenue|amount|cost|sales)/i.test(measure ?? '')
1061
+ ? 'currency'
1062
+ : /\b(percent|percentage|%|rate|share)\b/.test(q)
1063
+ ? 'percent'
1064
+ : 'number'
1065
+
1066
+ return {
1067
+ type, dimension, series, measure, reduce, stacked, logScale, timeAxis, valueFormat,
1068
+ rationale:
1069
+ `${type} chart of ${reduce}(${measure ?? 'value'}) by ${dimension ?? 'category'}` +
1070
+ `${series ? `, split by ${series}` : ''}${stacked ? ', stacked' : ''}` +
1071
+ `${logScale ? ', log scale' : ''}${timeAxis ? ', date axis' : ''} (mock - wire a real model for genuine parsing).`,
1072
+ }
1073
+ }
1074
+
1075
+ function extractUserRequest(prompt: string): string {
1076
+ const m = prompt.match(/User request:\s*([\s\S]+)$/)
1077
+ return (m?.[1] ?? '').trim().toLowerCase()
1078
+ }
1079
+
1080
+ function buildMockExport(prompt: string): AIExportPlan {
1081
+ const q = extractUserRequest(prompt)
1082
+ const fields = extractFields(prompt)
1083
+ // Reuse the filter mock (it reads "User query:"; feed it a compatible line).
1084
+ const filterPlan = buildMockFilter(prompt + `\nUser query: ${q}\n`, q)
1085
+
1086
+ // Format keyword routing.
1087
+ const format: ExportFormat =
1088
+ /\bpdf\b/.test(q) ? 'pdf'
1089
+ : /\bxls\b(?!x)/.test(q) || /97-2003|legacy excel/.test(q) ? 'xls'
1090
+ : /\b(xlsx|excel|spreadsheet|workbook)\b/.test(q) ? 'xlsx'
1091
+ : /\b(markdown|md)\b/.test(q) ? 'md'
1092
+ : /\bjson\b/.test(q) ? 'json'
1093
+ : /\bxml\b/.test(q) ? 'xml'
1094
+ : /\btsv\b/.test(q) ? 'tsv'
1095
+ : /\bhtml\b/.test(q) ? 'html'
1096
+ : /\bcsv\b/.test(q) ? 'csv'
1097
+ : 'xlsx'
1098
+
1099
+ // Grouping: "group by X" / "grouped by X", else "grouped" -> a categorical field.
1100
+ const groupBy: string[] = []
1101
+ const byMatch = q.match(/group(?:ed)?\s+by\s+([a-z0-9_ ,]+)/)
1102
+ if (byMatch) {
1103
+ for (const token of byMatch[1]!.split(/[, ]+/).filter(Boolean)) {
1104
+ // Exact field match, or a substring match only for tokens long enough to
1105
+ // be meaningful (so "a"/"as" don't match "amount").
1106
+ const f = fields.find(
1107
+ (ff) => ff.toLowerCase() === token || (token.length >= 4 && ff.toLowerCase().includes(token)),
1108
+ )
1109
+ if (f && !groupBy.includes(f)) groupBy.push(f)
1110
+ }
1111
+ } else if (/\bgroup(ed)?\b/.test(q)) {
1112
+ const cat = fields.find((f) => /region|country|category|status|stage|type|group|dept|team/i.test(f))
1113
+ if (cat) groupBy.push(cat)
1114
+ }
1115
+
1116
+ return {
1117
+ format,
1118
+ filters: filterPlan.filters,
1119
+ sort: filterPlan.sort,
1120
+ groupBy,
1121
+ rationale: `Export as ${format}${groupBy.length ? `, grouped by ${groupBy.join(' / ')}` : ''}${filterPlan.filters.length ? `; ${filterPlan.rationale}` : ''}`,
1122
+ }
1123
+ }
1124
+
1125
+ function buildMockAnomaly(prompt: string): AIAnomalyResult {
1126
+ // Parse the sampled rows, flag the numeric outliers per numeric field.
1127
+ const rowsBlock = prompt.match(/Rows \(index is 0-based into this list\):\n([\s\S]*?)\n\n/)?.[1] ?? ''
1128
+ const parsed = rowsBlock
1129
+ .split('\n')
1130
+ .map((line) => {
1131
+ const m = line.match(/^(\d+):\s*(\{[\s\S]*\})$/)
1132
+ if (!m) return null
1133
+ const row = safeParse(m[2]!) as Record<string, unknown> | null
1134
+ return row ? { idx: parseInt(m[1]!, 10), row } : null
1135
+ })
1136
+ .filter((r): r is { idx: number; row: Record<string, unknown> } => !!r)
1137
+
1138
+ if (parsed.length === 0) {
1139
+ return { anomalies: [], summary: 'No rows to scan (mock).' }
1140
+ }
1141
+
1142
+ // Genuinely numeric fields only: every value is null or a real number (so
1143
+ // booleans like `inStock` and id-ish strings are excluded). Also skip
1144
+ // identifier / row-index columns - a max "id" isn't an anomaly.
1145
+ const isIdLike = (f: string) => /(^id$|_id$|index|idx|^#|guid|uuid|serial|rownum)/i.test(f)
1146
+ const numericFields = Object.keys(parsed[0]!.row).filter(
1147
+ (f) =>
1148
+ !isIdLike(f) &&
1149
+ parsed.some((p) => typeof p.row[f] === 'number') &&
1150
+ parsed.every((p) => p.row[f] == null || typeof p.row[f] === 'number'),
1151
+ )
1152
+
1153
+ const anomalies: AIAnomaly[] = []
1154
+ for (const f of numericFields.slice(0, 2)) {
1155
+ let maxIdx = -1
1156
+ let maxVal = -Infinity
1157
+ for (const p of parsed) {
1158
+ const n = Number(p.row[f])
1159
+ if (Number.isFinite(n) && n > maxVal) {
1160
+ maxVal = n
1161
+ maxIdx = p.idx
1162
+ }
1163
+ }
1164
+ if (maxIdx >= 0) {
1165
+ anomalies.push({
1166
+ rowIndex: maxIdx,
1167
+ field: f,
1168
+ value: maxVal,
1169
+ reason: `${f} = ${maxVal} is the highest in the sample and may be an outlier`,
1170
+ severity: 'medium',
1171
+ })
1172
+ }
1173
+ }
1174
+
1175
+ return {
1176
+ anomalies,
1177
+ summary:
1178
+ anomalies.length > 0
1179
+ ? `Flagged ${anomalies.length} potential outlier${anomalies.length === 1 ? '' : 's'} (mock heuristic - wire a real model for genuine analysis).`
1180
+ : 'No obvious anomalies in the sample (mock).',
1181
+ }
1182
+ }
1183
+
1184
+ function extractUserQuery(prompt: string): string {
1185
+ const m = prompt.match(/User query:\s*(.+?)\n/)
1186
+ return (m?.[1] ?? '').toLowerCase()
1187
+ }
1188
+
1189
+ function extractFields(prompt: string): string[] {
1190
+ const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
1191
+ if (!m) return []
1192
+ return (m[1] ?? '')
1193
+ .split('\n')
1194
+ .map((l) => l.match(/^- (\w+)/)?.[1])
1195
+ .filter((s): s is string => !!s)
1196
+ }
1197
+
1198
+ /** Parse the "- name (type): ..." schema block into {name, type} pairs. */
1199
+ function extractFieldTypes(prompt: string): Array<{ name: string; type: string }> {
1200
+ const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
1201
+ if (!m) return []
1202
+ return (m[1] ?? '')
1203
+ .split('\n')
1204
+ .map((l) => {
1205
+ const mm = l.match(/^- (\w+)\s*\((\w+)\)/)
1206
+ return mm ? { name: mm[1]!, type: mm[2]! } : null
1207
+ })
1208
+ .filter((x): x is { name: string; type: string } => !!x)
1209
+ }
1210
+
1211
+ function buildMockFilter(prompt: string, q: string): AIFilterResult {
1212
+ const fields = extractFields(prompt)
1213
+ const filters: AIFilterClause[] = []
1214
+ const sort: AISortClause[] = []
1215
+ const rationale: string[] = []
1216
+
1217
+ // Greedy keyword routing. Real model would be smarter; this only needs
1218
+ // to convince the demo viewer the pipeline works.
1219
+ const numberWord = q.match(/(?:over|above|>|greater than)\s+\$?([\d.,]+)([kmb])?/)
1220
+ const lessWord = q.match(/(?:under|below|<|less than)\s+\$?([\d.,]+)([kmb])?/)
1221
+ // Pick a NUMBER-typed field (never a boolean like `inStock`), money-named
1222
+ // ones first so "$300" targets price/amount rather than a count/index.
1223
+ const numberTyped = extractFieldTypes(prompt).filter((f) => f.type === 'number').map((f) => f.name)
1224
+ const moneyRe = /(price|amount|cost|revenue|total|value|salary|arr|fee|spend|budget|sales)/i
1225
+ const numberPool = numberTyped.length > 0 ? numberTyped : fields
1226
+ const numberFields = [
1227
+ ...numberPool.filter((f) => moneyRe.test(f)),
1228
+ ...numberPool.filter((f) => !moneyRe.test(f)),
1229
+ ]
1230
+
1231
+ if (numberWord && numberFields[0]) {
1232
+ const raw = parseFloat(numberWord[1]!.replace(/,/g, ''))
1233
+ const mul = numberWord[2] === 'k' ? 1_000 : numberWord[2] === 'm' ? 1_000_000 : numberWord[2] === 'b' ? 1_000_000_000 : 1
1234
+ filters.push({ field: numberFields[0], operator: 'greaterThan', value: String(raw * mul) })
1235
+ rationale.push(`amount > ${raw}${numberWord[2] ?? ''}`)
1236
+ } else if (lessWord && numberFields[0]) {
1237
+ const raw = parseFloat(lessWord[1]!.replace(/,/g, ''))
1238
+ const mul = lessWord[2] === 'k' ? 1_000 : lessWord[2] === 'm' ? 1_000_000 : 1
1239
+ filters.push({ field: numberFields[0], operator: 'lessThan', value: String(raw * mul) })
1240
+ rationale.push(`amount < ${raw}${lessWord[2] ?? ''}`)
1241
+ }
1242
+
1243
+ // Quoted phrases -> contains on a likely text field.
1244
+ const quote = q.match(/"([^"]+)"|'([^']+)'/)
1245
+ const textFields = fields.filter((f) => /(name|company|customer|title|owner|status|region|category|industry)/i.test(f))
1246
+ if (quote) {
1247
+ const term = quote[1] ?? quote[2] ?? ''
1248
+ if (textFields[0]) {
1249
+ filters.push({ field: textFields[0], operator: 'contains', value: term })
1250
+ rationale.push(`text contains "${term}"`)
1251
+ }
1252
+ }
1253
+
1254
+ // Person-name routing -> match owner/contact fields.
1255
+ const personOwners = ['sasha', 'jamie', 'casey', 'drew', 'robin', 'morgan', 'riley', 'quinn']
1256
+ for (const n of personOwners) {
1257
+ if (q.includes(n)) {
1258
+ const ownerField = fields.find((f) => /owner|rep|assigned/i.test(f)) ?? fields.find((f) => /name/i.test(f))
1259
+ if (ownerField) {
1260
+ filters.push({ field: ownerField, operator: 'contains', value: n })
1261
+ rationale.push(`owner ~ "${n}"`)
1262
+ break
1263
+ }
1264
+ }
1265
+ }
1266
+
1267
+ // Region routing.
1268
+ for (const r of ['NA', 'EMEA', 'APAC', 'LATAM']) {
1269
+ if (q.toUpperCase().includes(r)) {
1270
+ const regionField = fields.find((f) => /region/i.test(f))
1271
+ if (regionField) {
1272
+ filters.push({ field: regionField, operator: 'equals', value: r })
1273
+ rationale.push(`region = ${r}`)
1274
+ break
1275
+ }
1276
+ }
1277
+ }
1278
+
1279
+ // Status routing - any token in the query that matches a known status.
1280
+ for (const s of ['active', 'pending', 'won', 'lost', 'live', 'paused', 'shipped', 'delivered']) {
1281
+ if (q.includes(s)) {
1282
+ const f = fields.find((f) => /status|stage/i.test(f))
1283
+ if (f) {
1284
+ filters.push({ field: f, operator: 'equals', value: s })
1285
+ rationale.push(`status = ${s}`)
1286
+ break
1287
+ }
1288
+ }
1289
+ }
1290
+
1291
+ // Sort detection.
1292
+ if (/(highest|largest|biggest|top|most)/.test(q)) {
1293
+ const f = numberFields[0]
1294
+ if (f) { sort.push({ field: f, desc: true }); rationale.push(`sort by ${f} desc`) }
1295
+ } else if (/(lowest|smallest|least|cheapest)/.test(q)) {
1296
+ const f = numberFields[0]
1297
+ if (f) { sort.push({ field: f, desc: false }); rationale.push(`sort by ${f} asc`) }
1298
+ } else if (/(newest|recent|latest)/.test(q)) {
1299
+ const dateField = fields.find((f) => /date|at|time/i.test(f))
1300
+ if (dateField) { sort.push({ field: dateField, desc: true }); rationale.push(`sort by ${dateField} desc`) }
1301
+ } else if (/(oldest)/.test(q)) {
1302
+ const dateField = fields.find((f) => /date|at|time/i.test(f))
1303
+ if (dateField) { sort.push({ field: dateField, desc: false }); rationale.push(`sort by ${dateField} asc`) }
1304
+ }
1305
+
1306
+ return {
1307
+ filters,
1308
+ sort,
1309
+ rationale: rationale.length
1310
+ ? `Interpreted: ${rationale.join(' AND ')}.`
1311
+ : `Couldn't identify a clear filter for "${q}". Showing all rows.`,
1312
+ }
1313
+ }
1314
+
1315
+ function buildMockSmartFill(prompt: string): { predictions: Array<{ rowIndex: number; value: unknown; confidence: number }>; rationale: string } {
1316
+ // Extract the target column and the rows-to-fill block; copy the first
1317
+ // example's "output" pattern verbatim so the demo always returns
1318
+ // something believable. Real models do much better - that's the point.
1319
+ const fieldMatch = prompt.match(/Target column:\s*(\w+)/)
1320
+ const rowsMatch = prompt.match(/Rows to fill:\n([\s\S]*?)\n\n/)
1321
+ const exMatch = prompt.match(/Example 1: input=.* -> output=(.+)/)
1322
+ const targetField = fieldMatch?.[1] ?? ''
1323
+ const rowLines = (rowsMatch?.[1] ?? '').split('\n').filter(Boolean)
1324
+ const exampleOutput = exMatch?.[1] ? safeParse(exMatch[1]) : ''
1325
+ const predictions = rowLines
1326
+ .map((line) => {
1327
+ const m = line.match(/^Row (\d+): (\{.+\})/)
1328
+ if (!m) return null
1329
+ const rowIndex = parseInt(m[1]!, 10)
1330
+ const row = safeParse(m[2]!) as Record<string, unknown> | null
1331
+ if (!row) return null
1332
+ const value = inferFromRow(targetField, row, exampleOutput)
1333
+ return { rowIndex, value, confidence: 0.78 + Math.random() * 0.18 }
1334
+ })
1335
+ .filter((p): p is { rowIndex: number; value: unknown; confidence: number } => !!p)
1336
+ return {
1337
+ predictions,
1338
+ rationale: `Inferred from ${exMatch ? 'the supplied' : 'no'} examples; mocked deterministically for the demo.`,
1339
+ }
1340
+ }
1341
+
1342
+ function safeParse(s: string): unknown {
1343
+ try { return JSON.parse(s) } catch { return null }
1344
+ }
1345
+
1346
+ function inferFromRow(field: string, row: Record<string, unknown>, exampleOutput: unknown): unknown {
1347
+ // Mock heuristics that produce a value that "looks right" in common
1348
+ // demo scenarios. The real provider would route through a real model.
1349
+ if (field === 'priority') {
1350
+ const arr = Number(row.arr ?? row.amount ?? row.price ?? 0)
1351
+ return arr > 100_000 ? 'high' : arr > 30_000 ? 'medium' : 'low'
1352
+ }
1353
+ if (field === 'tier') {
1354
+ const arr = Number(row.arr ?? row.amount ?? 0)
1355
+ return arr > 500_000 ? 'enterprise' : arr > 100_000 ? 'growth' : 'starter'
1356
+ }
1357
+ if (field === 'tags' || field === 'category') {
1358
+ return typeof exampleOutput === 'string' ? exampleOutput : 'auto-tag'
1359
+ }
1360
+ if (typeof exampleOutput === 'string') return exampleOutput
1361
+ if (typeof exampleOutput === 'number') return exampleOutput
1362
+ return exampleOutput ?? 'auto'
1363
+ }
1364
+
1365
+ function buildMockSummary(prompt: string): AISummary {
1366
+ const sliceMatch = prompt.match(/Slice size: (\d+) row/)
1367
+ const n = sliceMatch ? parseInt(sliceMatch[1]!, 10) : 0
1368
+ const fields = extractSummaryFields(prompt)
1369
+ return {
1370
+ text:
1371
+ n === 1
1372
+ ? `Single record. Notable signals come from ${fields.slice(0, 2).join(' and ') || 'the available fields'}.`
1373
+ : `${n} rows in scope. The distribution skews toward live / active records, with a long tail in ${fields[0] ?? 'amount'}.`,
1374
+ bullets: [
1375
+ `${n} row${n === 1 ? '' : 's'} sampled`,
1376
+ fields[0] ? `Largest variance in ${fields[0]}` : 'Tight clustering across visible fields',
1377
+ fields[1] ? `${fields[1]} concentrates around the median` : 'Few outliers',
1378
+ 'Mock summary - wire setAIProvider() to a real model for actual analysis',
1379
+ ],
1380
+ highlightedFields: fields.slice(0, 3),
1381
+ }
1382
+ }
1383
+
1384
+ function extractSummaryFields(prompt: string): string[] {
1385
+ const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
1386
+ if (!m) return []
1387
+ return (m[1] ?? '')
1388
+ .split('\n')
1389
+ .map((l) => l.match(/^- (\w+)/)?.[1])
1390
+ .filter((s): s is string => !!s)
1391
+ }
1392
+
1393
+ function buildMockClassify(prompt: string): { predictions: Array<{ rowIndex: number; value: string; confidence: number }> } {
1394
+ const labelsMatch = prompt.match(/Allowed labels[\s\S]*?:\n([\s\S]*?)\n\n/)
1395
+ // Capture the label up to the first colon, whitespace or end-of-line so
1396
+ // we don't pick up the rubric ("- at-risk: churn signals..." -> "at-risk").
1397
+ const labels = (labelsMatch?.[1] ?? '')
1398
+ .split('\n')
1399
+ .map((l) => l.match(/^-\s*([^\s:]+)/)?.[1])
1400
+ .filter((s): s is string => !!s)
1401
+ const rowLines = (prompt.match(/Rows to classify[\s\S]*?:\n([\s\S]*?)\n\n/)?.[1] ?? '').split('\n').filter(Boolean)
1402
+ const predictions = rowLines.map((line) => {
1403
+ const m = line.match(/^Row (\d+): "(.*)"/)
1404
+ if (!m || labels.length === 0) return null
1405
+ const rowIndex = parseInt(m[1]!, 10)
1406
+ const text = (m[2] ?? '').toLowerCase()
1407
+ // Pick the label whose token appears in the text; otherwise hash.
1408
+ const hit = labels.find((l) => text.includes(l.toLowerCase()))
1409
+ const value = hit ?? labels[Math.abs(hashStr(text)) % labels.length]!
1410
+ return { rowIndex, value, confidence: hit ? 0.92 : 0.6 + Math.random() * 0.2 }
1411
+ }).filter((p): p is { rowIndex: number; value: string; confidence: number } => !!p)
1412
+ return { predictions }
1413
+ }
1414
+
1415
+ function hashStr(s: string): number {
1416
+ let h = 0
1417
+ for (let i = 0; i < s.length; i += 1) h = (h * 31 + s.charCodeAt(i)) | 0
1418
+ return h
1419
+ }