@svgrid/grid 2.2.16 → 2.2.17

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 (290) hide show
  1. package/README.md +1 -1
  2. package/dist/GridFooter.svelte +12 -11
  3. package/dist/SvAnchor.svelte +65 -0
  4. package/dist/SvAnchor.svelte.d.ts +24 -0
  5. package/dist/SvAspectRatio.svelte +38 -0
  6. package/dist/SvAspectRatio.svelte.d.ts +16 -0
  7. package/dist/SvAutoComplete.svelte +52 -7
  8. package/dist/SvAutoComplete.svelte.d.ts +4 -1
  9. package/dist/SvBlockquote.svelte +43 -0
  10. package/dist/SvBlockquote.svelte.d.ts +16 -0
  11. package/dist/SvCalendar.svelte +33 -2
  12. package/dist/SvCalendar.svelte.d.ts +8 -1
  13. package/dist/SvCheckBox.svelte +6 -2
  14. package/dist/SvCode.svelte +52 -0
  15. package/dist/SvCode.svelte.d.ts +19 -0
  16. package/dist/SvCollapsible.svelte +75 -0
  17. package/dist/SvCollapsible.svelte.d.ts +27 -0
  18. package/dist/SvColorInput.svelte +11 -17
  19. package/dist/SvColorInput.svelte.d.ts +2 -0
  20. package/dist/SvComboBox.svelte +85 -8
  21. package/dist/SvComboBox.svelte.d.ts +14 -0
  22. package/dist/SvCountryInput.svelte +2 -2
  23. package/dist/SvCountryInput.svelte.d.ts +1 -1
  24. package/dist/SvDropDownList.svelte +154 -51
  25. package/dist/SvDropDownList.svelte.d.ts +17 -3
  26. package/dist/SvDurationInput.svelte +59 -41
  27. package/dist/SvDurationInput.svelte.d.ts +18 -0
  28. package/dist/SvField.svelte +203 -12
  29. package/dist/SvField.svelte.d.ts +45 -8
  30. package/dist/SvForm.svelte +195 -21
  31. package/dist/SvForm.svelte.d.ts +23 -0
  32. package/dist/SvGrid.controller.svelte.d.ts +12 -1
  33. package/dist/SvGrid.controller.svelte.js +87 -7
  34. package/dist/SvGrid.svelte +383 -181
  35. package/dist/SvGrid.types.d.ts +123 -2
  36. package/dist/SvGridChartView.svelte +70 -0
  37. package/dist/SvGridChartView.svelte.d.ts +11 -0
  38. package/dist/SvGridDropdown.svelte +9 -2
  39. package/dist/SvGridSelect.svelte +5 -2
  40. package/dist/SvGridSelect.svelte.d.ts +1 -1
  41. package/dist/SvGroup.svelte +41 -0
  42. package/dist/SvGroup.svelte.d.ts +27 -0
  43. package/dist/SvHoverCard.svelte +70 -0
  44. package/dist/SvHoverCard.svelte.d.ts +41 -0
  45. package/dist/SvKbd.svelte +51 -0
  46. package/dist/SvKbd.svelte.d.ts +18 -0
  47. package/dist/SvList.svelte +55 -0
  48. package/dist/SvList.svelte.d.ts +23 -0
  49. package/dist/SvListBox.svelte +166 -77
  50. package/dist/SvListBox.svelte.d.ts +17 -4
  51. package/dist/SvLoadingOverlay.svelte +53 -0
  52. package/dist/SvLoadingOverlay.svelte.d.ts +28 -0
  53. package/dist/SvMark.svelte +36 -0
  54. package/dist/SvMark.svelte.d.ts +14 -0
  55. package/dist/SvMaskedInput.svelte +50 -35
  56. package/dist/SvMaskedInput.svelte.d.ts +17 -2
  57. package/dist/SvMenuList.svelte +32 -3
  58. package/dist/SvMenubar.svelte +200 -0
  59. package/dist/SvMenubar.svelte.d.ts +18 -0
  60. package/dist/SvMultiSelect.svelte +7 -4
  61. package/dist/SvMultiSelect.svelte.d.ts +1 -1
  62. package/dist/SvNumberInput.svelte +79 -42
  63. package/dist/SvNumberInput.svelte.d.ts +25 -0
  64. package/dist/SvOtpInput.svelte +2 -2
  65. package/dist/SvPasswordInput.svelte +51 -31
  66. package/dist/SvPasswordInput.svelte.d.ts +17 -0
  67. package/dist/SvPhoneInput.svelte +39 -28
  68. package/dist/SvPhoneInput.svelte.d.ts +4 -0
  69. package/dist/SvPopconfirm.svelte +79 -0
  70. package/dist/SvPopconfirm.svelte.d.ts +42 -0
  71. package/dist/SvPopover.svelte +87 -29
  72. package/dist/SvPopover.svelte.d.ts +18 -4
  73. package/dist/SvRadioGroup.svelte +5 -1
  74. package/dist/SvResult.svelte +73 -0
  75. package/dist/SvResult.svelte.d.ts +28 -0
  76. package/dist/SvSegmented.svelte +114 -0
  77. package/dist/SvSegmented.svelte.d.ts +29 -0
  78. package/dist/SvSimpleGrid.svelte +41 -0
  79. package/dist/SvSimpleGrid.svelte.d.ts +25 -0
  80. package/dist/SvSlider.svelte +23 -10
  81. package/dist/SvSpinner.svelte +43 -0
  82. package/dist/SvSpinner.svelte.d.ts +20 -0
  83. package/dist/SvStack.svelte +37 -0
  84. package/dist/SvStack.svelte.d.ts +24 -0
  85. package/dist/SvSwitchButton.svelte +6 -1
  86. package/dist/SvTagsInput.svelte +9 -5
  87. package/dist/SvText.svelte +76 -0
  88. package/dist/SvText.svelte.d.ts +31 -0
  89. package/dist/SvTextInput.svelte +75 -43
  90. package/dist/SvTextInput.svelte.d.ts +28 -1
  91. package/dist/SvTimePicker.svelte +32 -2
  92. package/dist/SvTimePicker.svelte.d.ts +8 -9
  93. package/dist/SvTitle.svelte +57 -0
  94. package/dist/SvTitle.svelte.d.ts +24 -0
  95. package/dist/SvToaster.svelte +41 -6
  96. package/dist/SvToggleButton.svelte +4 -1
  97. package/dist/SvTooltip.svelte +68 -34
  98. package/dist/SvTooltip.svelte.d.ts +14 -2
  99. package/dist/SvTree.svelte +81 -21
  100. package/dist/SvTree.svelte.d.ts +3 -2
  101. package/dist/SvTreeSelect.svelte +5 -2
  102. package/dist/SvTreeSelect.svelte.d.ts +1 -1
  103. package/dist/SvVisuallyHidden.svelte +49 -0
  104. package/dist/SvVisuallyHidden.svelte.d.ts +19 -0
  105. package/dist/ai.d.ts +289 -0
  106. package/dist/ai.js +1013 -0
  107. package/dist/board-view.svelte.d.ts +22 -0
  108. package/dist/board-view.svelte.js +13 -0
  109. package/dist/build-api.js +36 -6
  110. package/dist/cdn/GridMenus-0AK9O7qG.js +420 -0
  111. package/dist/cdn/GridMenus-BjUoCXoD.js +416 -0
  112. package/dist/cdn/SvDateTimePicker-CYC7gRER.js +2176 -0
  113. package/dist/cdn/SvDateTimePicker-DtQKd4Ns.js +2198 -0
  114. package/dist/cdn/SvGridChart-BcLCYvw9.js +1195 -0
  115. package/dist/cdn/SvGridChart-BhnFdLd0.js +1203 -0
  116. package/dist/cdn/SvGridChartPanel-Cmx9DHAS.js +561 -0
  117. package/dist/cdn/SvGridChartPanel-DvjwxLvK.js +577 -0
  118. package/dist/cdn/SvGridChartView-B40DTJSX.js +54 -0
  119. package/dist/cdn/SvGridChartView-PwqI4s02.js +53 -0
  120. package/dist/cdn/SvGridDropdown-DjALc_4f.js +255 -0
  121. package/dist/cdn/SvGridDropdown-hpnHvOGt.js +254 -0
  122. package/dist/cdn/chart-T1usDN0o.js +1212 -0
  123. package/dist/cdn/disclose-version-DoD9AFD_.js +2958 -0
  124. package/dist/cdn/export-format-JT5pWVT8.js +561 -0
  125. package/dist/cdn/popover-P-9P2YYn.js +69 -0
  126. package/dist/cdn/rolldown-runtime-Dy4uBu1J.js +11 -0
  127. package/dist/cdn/src-BLhdLmoN.js +25707 -0
  128. package/dist/cdn/src-BwnUVj3T.js +25623 -0
  129. package/dist/cdn/svgrid.js +9 -32897
  130. package/dist/cdn/svgrid.svelte-external.js +9 -30052
  131. package/dist/cell-formatting.d.ts +2 -2
  132. package/dist/cell-render.js +4 -4
  133. package/dist/chart-view.svelte.d.ts +25 -0
  134. package/dist/chart-view.svelte.js +14 -0
  135. package/dist/createCombobox.svelte.d.ts +5 -0
  136. package/dist/createCombobox.svelte.js +21 -5
  137. package/dist/createDropdownList.svelte.d.ts +3 -0
  138. package/dist/createDropdownList.svelte.js +8 -2
  139. package/dist/createForm.svelte.d.ts +18 -0
  140. package/dist/createForm.svelte.js +51 -6
  141. package/dist/createMenu.svelte.js +27 -0
  142. package/dist/createPopoverSelect.svelte.d.ts +3 -0
  143. package/dist/createPopoverSelect.svelte.js +9 -1
  144. package/dist/createSlider.svelte.d.ts +8 -21
  145. package/dist/createSlider.svelte.js +34 -0
  146. package/dist/createTooltip.svelte.d.ts +12 -0
  147. package/dist/createTooltip.svelte.js +72 -9
  148. package/dist/editor-contract.d.ts +15 -0
  149. package/dist/export-provider.d.ts +27 -0
  150. package/dist/export-provider.js +9 -0
  151. package/dist/filter-operators.d.ts +6 -0
  152. package/dist/filter-operators.js +33 -0
  153. package/dist/form-field.d.ts +45 -2
  154. package/dist/grid-messages.d.ts +61 -0
  155. package/dist/grid-messages.js +72 -0
  156. package/dist/group-display.d.ts +62 -0
  157. package/dist/group-display.js +78 -0
  158. package/dist/index.d.ts +36 -4
  159. package/dist/index.js +43 -2
  160. package/dist/js-scroller.svelte.d.ts +35 -0
  161. package/dist/js-scroller.svelte.js +154 -0
  162. package/dist/list-option.d.ts +46 -0
  163. package/dist/list-option.js +53 -0
  164. package/dist/menus.js +25 -11
  165. package/dist/pivot-view.svelte.d.ts +72 -0
  166. package/dist/pivot-view.svelte.js +13 -0
  167. package/dist/positioning.d.ts +111 -0
  168. package/dist/positioning.js +191 -0
  169. package/dist/scheduler-model.d.ts +3 -0
  170. package/dist/scheduler-model.js +22 -5
  171. package/dist/svgrid-wrapper.types.d.ts +18 -0
  172. package/dist/toast-store.svelte.d.ts +54 -0
  173. package/dist/toast-store.svelte.js +65 -15
  174. package/package.json +9 -1
  175. package/src/GridFooter.svelte +12 -11
  176. package/src/SvAnchor.svelte +65 -0
  177. package/src/SvAspectRatio.svelte +38 -0
  178. package/src/SvAutoComplete.svelte +52 -7
  179. package/src/SvBlockquote.svelte +43 -0
  180. package/src/SvCalendar.svelte +33 -2
  181. package/src/SvCalendar.test.ts +15 -0
  182. package/src/SvCheckBox.svelte +6 -2
  183. package/src/SvCode.svelte +52 -0
  184. package/src/SvCollapsible.svelte +75 -0
  185. package/src/SvColorInput.svelte +11 -17
  186. package/src/SvComboBox.svelte +85 -8
  187. package/src/SvCountryInput.svelte +2 -2
  188. package/src/SvDropDownList.svelte +154 -51
  189. package/src/SvDurationInput.svelte +59 -41
  190. package/src/SvField.svelte +203 -12
  191. package/src/SvForm.svelte +195 -21
  192. package/src/SvForm.test.ts +112 -0
  193. package/src/SvGrid.controller.svelte.ts +88 -7
  194. package/src/SvGrid.svelte +383 -181
  195. package/src/SvGrid.types.ts +125 -1
  196. package/src/SvGridChartView.svelte +70 -0
  197. package/src/SvGridDropdown.svelte +9 -2
  198. package/src/SvGridSelect.svelte +5 -2
  199. package/src/SvGroup.svelte +41 -0
  200. package/src/SvHoverCard.svelte +70 -0
  201. package/src/SvKbd.svelte +51 -0
  202. package/src/SvList.svelte +55 -0
  203. package/src/SvListBox.svelte +166 -77
  204. package/src/SvLoadingOverlay.svelte +53 -0
  205. package/src/SvMark.svelte +36 -0
  206. package/src/SvMaskedInput.svelte +50 -35
  207. package/src/SvMenuList.svelte +32 -3
  208. package/src/SvMenubar.svelte +200 -0
  209. package/src/SvMultiSelect.svelte +7 -4
  210. package/src/SvNumberInput.svelte +79 -42
  211. package/src/SvOtpInput.svelte +2 -2
  212. package/src/SvPasswordInput.svelte +51 -31
  213. package/src/SvPhoneInput.svelte +39 -28
  214. package/src/SvPopconfirm.svelte +79 -0
  215. package/src/SvPopover.svelte +87 -29
  216. package/src/SvRadioGroup.svelte +5 -1
  217. package/src/SvResult.svelte +73 -0
  218. package/src/SvSegmented.svelte +114 -0
  219. package/src/SvSimpleGrid.svelte +41 -0
  220. package/src/SvSlider.svelte +23 -10
  221. package/src/SvSpinner.svelte +43 -0
  222. package/src/SvStack.svelte +37 -0
  223. package/src/SvSwitchButton.svelte +6 -1
  224. package/src/SvTagsInput.svelte +9 -5
  225. package/src/SvText.svelte +76 -0
  226. package/src/SvTextInput.svelte +75 -43
  227. package/src/SvTimePicker.svelte +32 -2
  228. package/src/SvTitle.svelte +57 -0
  229. package/src/SvToaster.svelte +41 -6
  230. package/src/SvToaster.test.ts +32 -0
  231. package/src/SvToggleButton.svelte +4 -1
  232. package/src/SvTooltip.svelte +68 -34
  233. package/src/SvTree.svelte +81 -21
  234. package/src/SvTreeSelect.svelte +5 -2
  235. package/src/SvVisuallyHidden.svelte +49 -0
  236. package/src/ai.test.ts +502 -0
  237. package/src/ai.ts +1391 -0
  238. package/src/board-view.svelte.ts +33 -0
  239. package/src/build-api.coverage.test.ts +101 -0
  240. package/src/build-api.ts +43 -18
  241. package/src/builtin-editors.grid.test.ts +1 -1
  242. package/src/cell-formatting.ts +5 -5
  243. package/src/cell-render.ts +4 -4
  244. package/src/chart-view.svelte.ts +36 -0
  245. package/src/createCombobox.svelte.ts +17 -5
  246. package/src/createDropdownList.svelte.ts +8 -2
  247. package/src/createForm.svelte.ts +59 -6
  248. package/src/createMenu.svelte.ts +23 -0
  249. package/src/createPopoverSelect.svelte.ts +8 -1
  250. package/src/createSlider.svelte.ts +20 -0
  251. package/src/createTooltip.svelte.ts +67 -9
  252. package/src/editor-contract.ts +16 -0
  253. package/src/export-provider.ts +40 -0
  254. package/src/filter-operators.ts +37 -0
  255. package/src/form-field.ts +42 -2
  256. package/src/grid-messages.test.ts +24 -0
  257. package/src/grid-messages.ts +137 -0
  258. package/src/group-display.test.ts +77 -0
  259. package/src/group-display.ts +117 -0
  260. package/src/i18n.grid.test.ts +73 -0
  261. package/src/index.ts +91 -2
  262. package/src/js-scroller.svelte.ts +173 -0
  263. package/src/list-option.test.ts +56 -0
  264. package/src/list-option.ts +81 -0
  265. package/src/menus.test.ts +32 -0
  266. package/src/menus.ts +25 -12
  267. package/src/pivot-view.svelte.ts +90 -0
  268. package/src/pivot-view.test.ts +38 -0
  269. package/src/pivot.grid.test.ts +102 -0
  270. package/src/positioning.test.ts +141 -0
  271. package/src/positioning.ts +266 -0
  272. package/src/scheduler-model.test.ts +16 -0
  273. package/src/scheduler-model.ts +24 -5
  274. package/src/svgrid-wrapper.types.ts +23 -0
  275. package/src/svgrid.charting.test.ts +8 -1
  276. package/src/svgrid.comments-autocomplete.test.ts +7 -2
  277. package/src/svgrid.context-menu.test.ts +8 -3
  278. package/src/toast-store.svelte.ts +98 -0
  279. package/src/toast-store.test.ts +62 -1
  280. package/src/ui-breadth.test.ts +138 -0
  281. package/src/ui-buttons.test.ts +39 -0
  282. package/src/ui-inputs.test.ts +2 -2
  283. package/src/ui-range.test.ts +9 -0
  284. package/src/ui-selection.test.ts +36 -0
  285. package/src/ui-tier1.test.ts +1 -1
  286. package/src/virtual.test.ts +20 -6
  287. package/dist/SvGridBoard.svelte +0 -2339
  288. package/dist/SvGridBoard.svelte.d.ts +0 -31
  289. package/src/SvGridBoard.svelte +0 -2339
  290. package/src/board.test.ts +0 -927
package/dist/ai.js ADDED
@@ -0,0 +1,1013 @@
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
+ import { getExportProvider } from './export-provider';
28
+ let provider = null;
29
+ /**
30
+ * Register the model adapter every AI call will route through. Call once
31
+ * at app boot. Passing `null` clears the provider and AI calls revert to
32
+ * throwing "no provider" errors.
33
+ */
34
+ export function setAIProvider(p) {
35
+ provider = p;
36
+ }
37
+ export function getAIProvider() {
38
+ return provider;
39
+ }
40
+ export function hasAIProvider() {
41
+ return provider != null;
42
+ }
43
+ class NoProviderError extends Error {
44
+ constructor() {
45
+ super('@svgrid/enterprise/ai: no AI provider registered. Call setAIProvider(fn) ' +
46
+ 'with an adapter that talks to OpenAI / Anthropic / your proxy.');
47
+ this.name = 'NoProviderError';
48
+ }
49
+ }
50
+ class BadJsonError extends Error {
51
+ constructor(raw) {
52
+ super('@svgrid/enterprise/ai: provider returned non-JSON for a json-format request. ' +
53
+ `First 200 chars: ${raw.slice(0, 200)}`);
54
+ this.name = 'BadJsonError';
55
+ }
56
+ }
57
+ async function callProvider(req) {
58
+ if (!provider)
59
+ throw new NoProviderError();
60
+ return provider(req);
61
+ }
62
+ async function callJSON(req) {
63
+ const raw = await callProvider({ ...req, responseFormat: 'json' });
64
+ // Models occasionally wrap JSON in markdown code fences even when asked
65
+ // for raw JSON. Strip a single fenced block if present, then parse.
66
+ const stripped = raw.trim().replace(/^```(?:json)?\s*|\s*```$/g, '');
67
+ try {
68
+ return JSON.parse(stripped);
69
+ }
70
+ catch {
71
+ throw new BadJsonError(raw);
72
+ }
73
+ }
74
+ /**
75
+ * Inspect the first N rows the grid is holding to infer a typed schema +
76
+ * a handful of sample values per column. This is the context every AI
77
+ * task needs and the most expensive thing to build, so the helpers cache
78
+ * the result inside one task call rather than calling api.getData()
79
+ * repeatedly.
80
+ */
81
+ function buildColumnSchema(api, sampleSize = 50) {
82
+ const data = api.getData();
83
+ if (data.length === 0)
84
+ return [];
85
+ const slice = data.slice(0, Math.min(data.length, sampleSize));
86
+ const fields = new Set();
87
+ for (const row of slice) {
88
+ for (const k of Object.keys(row))
89
+ fields.add(k);
90
+ }
91
+ const out = [];
92
+ for (const field of fields) {
93
+ const values = [];
94
+ for (const row of slice) {
95
+ const v = row[field];
96
+ if (v != null)
97
+ values.push(v);
98
+ if (values.length >= 5)
99
+ break;
100
+ }
101
+ out.push({
102
+ field,
103
+ type: inferType(values),
104
+ sampleValues: values,
105
+ });
106
+ }
107
+ return out;
108
+ }
109
+ function inferType(samples) {
110
+ if (samples.length === 0)
111
+ return 'unknown';
112
+ const v = samples[0];
113
+ if (typeof v === 'number')
114
+ return 'number';
115
+ if (typeof v === 'boolean')
116
+ return 'boolean';
117
+ if (typeof v === 'string') {
118
+ // Cheap ISO-date sniff so we route date-style filters correctly.
119
+ if (/^\d{4}-\d{2}-\d{2}/.test(v))
120
+ return 'date';
121
+ return 'string';
122
+ }
123
+ return 'unknown';
124
+ }
125
+ function schemaToPromptBlock(schema) {
126
+ return schema
127
+ .map((c) => `- ${c.field} (${c.type}): e.g. ${c.sampleValues
128
+ .slice(0, 3)
129
+ .map((v) => JSON.stringify(v))
130
+ .join(', ')}`)
131
+ .join('\n');
132
+ }
133
+ /**
134
+ * Translate a natural-language query into a filter+sort plan against
135
+ * the current grid's columns. The grid passes the column schema (names,
136
+ * types, sample values) to the model so it can pick the right field
137
+ * names without hallucinating.
138
+ */
139
+ export async function aiFilter(api, query, opts = {}) {
140
+ const schema = buildColumnSchema(api);
141
+ const prompt = `You are a data-grid filter planner. Translate the user's natural-language ` +
142
+ `query into a strict-JSON plan that the grid can apply.\n\n` +
143
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
144
+ `Output JSON schema:\n` +
145
+ `{ "filters": [{"field": "<one of the columns above>", ` +
146
+ `"operator": "contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank", ` +
147
+ `"value": "<string>"}], ` +
148
+ `"sort": [{"field": "<column>", "desc": true|false}], ` +
149
+ `"rationale": "<one-sentence explanation>" }\n\n` +
150
+ `User query: ${query}\n\n` +
151
+ `Return JSON only, no prose.`;
152
+ const result = await callJSON({
153
+ prompt,
154
+ task: 'filter',
155
+ signal: opts.signal,
156
+ maxOutputTokens: 400,
157
+ });
158
+ // Defensive: drop anything that doesn't match a real column. Models love
159
+ // to invent plausible-sounding field names; we'd rather skip a clause
160
+ // than throw at runtime.
161
+ const valid = new Set(schema.map((c) => c.field));
162
+ result.filters = (result.filters ?? []).filter((f) => valid.has(f.field));
163
+ result.sort = (result.sort ?? []).filter((s) => valid.has(s.field));
164
+ if (opts.apply) {
165
+ api.clearAllFilters();
166
+ api.clearSort();
167
+ for (const f of result.filters) {
168
+ api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' });
169
+ }
170
+ // Multiple sort clauses get applied last-wins because the public
171
+ // `setSort` is single-key. Multi-sort is on the roadmap.
172
+ const last = result.sort[result.sort.length - 1];
173
+ if (last)
174
+ api.setSort(last.field, last.desc ? 'desc' : 'asc');
175
+ }
176
+ return result;
177
+ }
178
+ /**
179
+ * Given a column and a few user-provided examples, propose values for the
180
+ * untouched rows. Returns predictions only - the caller chooses whether to
181
+ * commit them via `api.setCellValue`. This is the right shape for an
182
+ * accept-per-cell UX with confidence-coloured highlights.
183
+ */
184
+ export async function aiSmartFill(api, opts) {
185
+ if (opts.examples.length === 0) {
186
+ throw new Error('@svgrid/enterprise/ai: aiSmartFill requires at least one example.');
187
+ }
188
+ const data = api.getData();
189
+ const targets = opts.targetRowIndices ??
190
+ data
191
+ .map((row, i) => {
192
+ const v = row[opts.field];
193
+ return v == null || v === '' ? i : -1;
194
+ })
195
+ .filter((i) => i >= 0);
196
+ if (targets.length === 0) {
197
+ return { field: opts.field, predictions: [], rationale: 'No empty cells to fill.' };
198
+ }
199
+ const examplesBlock = opts.examples
200
+ .map((ex, i) => `Example ${i + 1}: input=${JSON.stringify(ex.input)} -> output=${JSON.stringify(ex.output)}`)
201
+ .join('\n');
202
+ const targetRowsBlock = targets
203
+ .map((i) => `Row ${i}: ${JSON.stringify(data[i])}`)
204
+ .join('\n');
205
+ const prompt = `You are filling in a single column of a data grid based on user-provided ` +
206
+ `examples. Match the pattern in the examples exactly.\n\n` +
207
+ `Target column: ${opts.field}\n\n` +
208
+ `Examples:\n${examplesBlock}\n\n` +
209
+ `Rows to fill:\n${targetRowsBlock}\n\n` +
210
+ `Return strict JSON only:\n` +
211
+ `{ "predictions": [{"rowIndex": <number>, "value": <inferred value>, ` +
212
+ `"confidence": <0..1>}], "rationale": "<one-sentence pattern description>" }`;
213
+ const result = await callJSON({
214
+ prompt,
215
+ task: 'smart-fill',
216
+ signal: opts.signal,
217
+ maxOutputTokens: 600,
218
+ });
219
+ return {
220
+ field: opts.field,
221
+ predictions: result.predictions ?? [],
222
+ rationale: result.rationale ?? '',
223
+ };
224
+ }
225
+ /**
226
+ * Ask the model to summarise a slice of the grid. Caps the row sample at
227
+ * a model-friendly size; for huge selections it samples uniformly so the
228
+ * summary stays representative without blowing the context window.
229
+ */
230
+ export async function aiSummarize(api, opts) {
231
+ const all = api.getData();
232
+ const rows = (() => {
233
+ const t = opts.target;
234
+ if (t.kind === 'row') {
235
+ const r = all[t.rowIndex];
236
+ return r ? [r] : [];
237
+ }
238
+ if (t.kind === 'selection') {
239
+ return t.rowIndices.map((i) => all[i]).filter((r) => r != null);
240
+ }
241
+ if (t.kind === 'group') {
242
+ return all.filter((r) => r[t.field] === t.value);
243
+ }
244
+ return all.slice();
245
+ })();
246
+ if (rows.length === 0) {
247
+ return { text: 'No rows in scope.', bullets: [], highlightedFields: [] };
248
+ }
249
+ // Uniform sample to stay inside a sensible context budget.
250
+ const MAX_SAMPLE = 25;
251
+ const sample = rows.length <= MAX_SAMPLE
252
+ ? rows
253
+ : Array.from({ length: MAX_SAMPLE }, (_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]);
254
+ const schema = buildColumnSchema(api, 30);
255
+ const prompt = `You are summarising a slice of a business data grid for a busy analyst.\n\n` +
256
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
257
+ `Slice size: ${rows.length} row(s). Sampled rows shown below.\n` +
258
+ `${sample.map((r) => JSON.stringify(r)).join('\n')}\n\n` +
259
+ (opts.question ? `User's question: ${opts.question}\n\n` : '') +
260
+ `Return strict JSON only:\n` +
261
+ `{ "text": "<one short paragraph>", ` +
262
+ `"bullets": ["<3-5 punchy bullets>"], ` +
263
+ `"highlightedFields": ["<column names the summary leans on>"] }`;
264
+ const result = await callJSON({
265
+ prompt,
266
+ task: 'summarize',
267
+ signal: opts.signal,
268
+ maxOutputTokens: 600,
269
+ });
270
+ return {
271
+ text: result.text ?? '',
272
+ bullets: result.bullets ?? [],
273
+ highlightedFields: result.highlightedFields ?? [],
274
+ };
275
+ }
276
+ /**
277
+ * Bucket free-text cells into one of a known set of classes. The model
278
+ * is constrained to pick from `opts.classes`; predictions outside the set
279
+ * are dropped so the caller can rely on the output being clean enum
280
+ * values it can write straight back into the grid.
281
+ */
282
+ export async function aiClassify(api, opts) {
283
+ const data = api.getData();
284
+ const targets = opts.targetRowIndices ?? data.map((_, i) => i);
285
+ const rubric = opts.classDescriptions
286
+ ? Object.entries(opts.classDescriptions)
287
+ .map(([k, v]) => `- ${k}: ${v}`)
288
+ .join('\n')
289
+ : opts.classes.map((c) => `- ${c}`).join('\n');
290
+ const rowsBlock = targets
291
+ .map((i) => `Row ${i}: ${JSON.stringify(data[i]?.[opts.inputField] ?? '')}`)
292
+ .join('\n');
293
+ const prompt = `You are a strict text classifier. For each row, pick exactly one ` +
294
+ `label from the list. If unsure, pick the closest match and lower the ` +
295
+ `confidence.\n\n` +
296
+ `Allowed labels (with optional rubric):\n${rubric}\n\n` +
297
+ `Rows to classify (text from column "${opts.inputField}"):\n${rowsBlock}\n\n` +
298
+ `Return strict JSON only:\n` +
299
+ `{ "predictions": [{"rowIndex": <number>, "value": "<label>", "confidence": <0..1>}] }`;
300
+ const result = await callJSON({
301
+ prompt,
302
+ task: 'classify',
303
+ signal: opts.signal,
304
+ maxOutputTokens: Math.min(2000, 30 + targets.length * 30),
305
+ });
306
+ const allowed = new Set(opts.classes);
307
+ return {
308
+ inputField: opts.inputField,
309
+ outputField: opts.outputField,
310
+ predictions: (result.predictions ?? []).filter((p) => allowed.has(p.value)),
311
+ };
312
+ }
313
+ // ---------------------------------------------------------------------------
314
+ // 5. Natural-language export
315
+ // ---------------------------------------------------------------------------
316
+ const EXPORT_FORMATS = ['xlsx', 'xls', 'pdf', 'csv', 'tsv', 'html', 'json', 'xml', 'md'];
317
+ /**
318
+ * Turn a natural-language request ("export EU orders from Q2 as a grouped PDF")
319
+ * into an export: the model returns a `{ format, filters, sort, groupBy }` plan
320
+ * against the grid's columns; we apply the filter/sort to the grid and hand the
321
+ * result to the registered export engine (@svgrid/enterprise). Returns the plan
322
+ * so the UI can show what it did (or preview it first with `run: false`).
323
+ */
324
+ export async function aiExport(api, query, opts = {}) {
325
+ const schema = buildColumnSchema(api);
326
+ const prompt = `You are an export assistant for a data grid. Translate the user's request ` +
327
+ `into a strict-JSON export plan.\n\n` +
328
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
329
+ `Output JSON schema:\n` +
330
+ `{ "format": "xlsx"|"xls"|"pdf"|"csv"|"tsv"|"html"|"json"|"xml"|"md", ` +
331
+ `"filters": [{"field":"<column>","operator":"contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank","value":"<string>"}], ` +
332
+ `"sort": [{"field":"<column>","desc":true|false}], ` +
333
+ `"groupBy": ["<column>"], ` +
334
+ `"rationale": "<one sentence>" }\n\n` +
335
+ `Rules: use the format the user names (default "xlsx"); only use column ` +
336
+ `names from the list above; "grouped" / "group by X" -> groupBy. ` +
337
+ `Return JSON only, no prose.\n\n` +
338
+ `User request: ${query}`;
339
+ const plan = await callJSON({
340
+ prompt,
341
+ task: 'export',
342
+ signal: opts.signal,
343
+ maxOutputTokens: 500,
344
+ });
345
+ // Defensive validation - drop invented fields, clamp the format.
346
+ const valid = new Set(schema.map((c) => c.field));
347
+ plan.format = EXPORT_FORMATS.includes(plan.format) ? plan.format : 'xlsx';
348
+ plan.filters = (plan.filters ?? []).filter((f) => valid.has(f.field));
349
+ plan.sort = (plan.sort ?? []).filter((s) => valid.has(s.field));
350
+ plan.groupBy = (plan.groupBy ?? []).filter((g) => valid.has(g));
351
+ plan.rationale = plan.rationale ?? '';
352
+ // Optionally mirror the plan onto the grid (opt-in). Off by default so the
353
+ // export never disturbs the user's current view.
354
+ if (opts.apply === true) {
355
+ api.clearAllFilters();
356
+ api.clearSort();
357
+ for (const f of plan.filters) {
358
+ api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' });
359
+ }
360
+ const last = plan.sort[plan.sort.length - 1];
361
+ if (last)
362
+ api.setSort(last.field, last.desc ? 'desc' : 'asc');
363
+ if (plan.groupBy.length > 0) {
364
+ try {
365
+ api.setGroupBy(plan.groupBy);
366
+ }
367
+ catch {
368
+ // grouping feature not enabled - the export still groups on its own
369
+ }
370
+ }
371
+ }
372
+ // Planning is always free; WRITING the file uses the export engine registered
373
+ // by @svgrid/enterprise (export-provider seam). Without it, we return the plan
374
+ // so the UI can still show what the AI decided - the download just no-ops.
375
+ const runExport = getExportProvider();
376
+ if (opts.run !== false && runExport) {
377
+ // Compute the export rows from the plan directly (filter + sort + make
378
+ // contiguous by group) rather than reading the grid's reactive displayed
379
+ // rows - so the download always has exactly the intended data.
380
+ const exportRows = applyPlanToRows(api.getData(), plan);
381
+ await runExport(api, {
382
+ format: plan.format,
383
+ filename: opts.filename ?? 'export',
384
+ rows: exportRows,
385
+ ...(plan.groupBy.length > 0 ? { groupBy: plan.groupBy } : {}),
386
+ });
387
+ }
388
+ return plan;
389
+ }
390
+ /** Evaluate one AI filter clause against a raw row value. */
391
+ function matchesClause(row, clause) {
392
+ const v = row[clause.field];
393
+ const val = clause.value ?? '';
394
+ switch (clause.operator) {
395
+ case 'contains':
396
+ return String(v ?? '').toLowerCase().includes(val.toLowerCase());
397
+ case 'equals':
398
+ return String(v ?? '').toLowerCase() === val.toLowerCase();
399
+ case 'startsWith':
400
+ return String(v ?? '').toLowerCase().startsWith(val.toLowerCase());
401
+ case 'greaterThan':
402
+ return Number(v) > Number(val);
403
+ case 'lessThan':
404
+ return Number(v) < Number(val);
405
+ case 'isBlank':
406
+ return v == null || v === '';
407
+ default:
408
+ return true;
409
+ }
410
+ }
411
+ /** Filter + sort + (stable) group the raw rows per an export plan. */
412
+ function applyPlanToRows(data, plan) {
413
+ let rows = data.slice();
414
+ if (plan.filters.length > 0) {
415
+ rows = rows.filter((r) => plan.filters.every((f) => matchesClause(r, f)));
416
+ }
417
+ const last = plan.sort[plan.sort.length - 1];
418
+ if (last) {
419
+ rows = [...rows].sort((a, b) => {
420
+ const av = a[last.field];
421
+ const bv = b[last.field];
422
+ const na = Number(av);
423
+ const nb = Number(bv);
424
+ let cmp;
425
+ if (Number.isFinite(na) && Number.isFinite(nb))
426
+ cmp = na - nb;
427
+ else
428
+ cmp = String(av ?? '').localeCompare(String(bv ?? ''));
429
+ return last.desc ? -cmp : cmp;
430
+ });
431
+ }
432
+ // Contiguous grouping (first-seen order) so PDF group rows + Excel outline
433
+ // line up.
434
+ if (plan.groupBy.length > 0) {
435
+ const buckets = new Map();
436
+ for (const r of rows) {
437
+ const key = plan.groupBy
438
+ .map((k) => String(r[k] ?? ''))
439
+ .join('');
440
+ const bucket = buckets.get(key);
441
+ if (bucket)
442
+ bucket.push(r);
443
+ else
444
+ buckets.set(key, [r]);
445
+ }
446
+ rows = [...buckets.values()].flat();
447
+ }
448
+ return rows;
449
+ }
450
+ function sliceForTarget(api, target) {
451
+ const all = api.getData();
452
+ if (target.kind === 'row') {
453
+ const r = all[target.rowIndex];
454
+ return r ? [r] : [];
455
+ }
456
+ if (target.kind === 'selection') {
457
+ return target.rowIndices.map((i) => all[i]).filter((r) => r != null);
458
+ }
459
+ if (target.kind === 'group') {
460
+ return all.filter((r) => r[target.field] === target.value);
461
+ }
462
+ return all.slice();
463
+ }
464
+ /**
465
+ * Scan a slice of the grid (all / selection / group) for anomalies - outliers,
466
+ * suspicious values, inconsistencies - and return a structured list plus a
467
+ * one-line summary. Pairs naturally with an export: "find the odd ones, then
468
+ * export just those".
469
+ */
470
+ export async function aiFindAnomalies(api, opts = {}) {
471
+ const rows = sliceForTarget(api, opts.target ?? { kind: 'all' });
472
+ if (rows.length === 0)
473
+ return { anomalies: [], summary: 'No rows in scope.' };
474
+ const MAX_SAMPLE = 40;
475
+ const sample = rows.length <= MAX_SAMPLE
476
+ ? rows
477
+ : Array.from({ length: MAX_SAMPLE }, (_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]);
478
+ const schema = buildColumnSchema(api, 30);
479
+ const prompt = `You are a data-quality analyst. Scan the rows below for anomalies: ` +
480
+ `numeric outliers, impossible / inconsistent values, unexpected blanks, ` +
481
+ `and values that break the pattern of the column.\n\n` +
482
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
483
+ `Rows (index is 0-based into this list):\n` +
484
+ `${sample.map((r, i) => `${i}: ${JSON.stringify(r)}`).join('\n')}\n\n` +
485
+ (opts.question ? `Focus: ${opts.question}\n\n` : '') +
486
+ `Return strict JSON only:\n` +
487
+ `{ "anomalies": [{"rowIndex": <number|null>, "field": "<column|null>", ` +
488
+ `"reason": "<why it's odd>", "severity": "low"|"medium"|"high"}], ` +
489
+ `"summary": "<one sentence>" }`;
490
+ const result = await callJSON({
491
+ prompt,
492
+ task: 'anomaly',
493
+ signal: opts.signal,
494
+ maxOutputTokens: 800,
495
+ });
496
+ return {
497
+ anomalies: result.anomalies ?? [],
498
+ summary: result.summary ?? '',
499
+ };
500
+ }
501
+ /**
502
+ * Translate a natural-language request into a chart plan for the grid's built-in
503
+ * `charting` panel. Validates every field against the real schema, then (with
504
+ * `apply: true`) pushes it into the panel through `api.configureChart`.
505
+ */
506
+ export async function aiChart(api, query, opts = {}) {
507
+ const schema = buildColumnSchema(api);
508
+ const prompt = `You are a charting assistant for a data grid. Translate the user's request ` +
509
+ `into a strict-JSON chart plan the grid can render.\n\n` +
510
+ `Columns:\n${schemaToPromptBlock(schema)}\n\n` +
511
+ `Output JSON schema:\n` +
512
+ `{ "type": "bar"|"line"|"area"|"pie", ` +
513
+ `"dimension": "<a categorical column to group by>", ` +
514
+ `"series": "<a second categorical column to split into series, or null>", ` +
515
+ `"measure": "<a numeric column to aggregate>", ` +
516
+ `"reduce": "sum"|"avg"|"count", ` +
517
+ `"stacked": true|false, ` +
518
+ `"logScale": true|false, ` +
519
+ `"timeAxis": true|false, ` +
520
+ `"valueFormat": "number"|"currency"|"percent", ` +
521
+ `"rationale": "<one-sentence explanation>" }\n\n` +
522
+ `Rules: pick "dimension" and "series" from text/date columns and "measure" ` +
523
+ `from a numeric column; use only column names from the list above; ` +
524
+ `"stacked"/"stack" -> stacked:true; "log"/"logarithmic" -> logScale:true; ` +
525
+ `"over time"/"by date"/a date dimension -> timeAxis:true; ` +
526
+ `money/revenue/price/$ -> valueFormat:"currency"; rate/%/share -> valueFormat:"percent"; ` +
527
+ `else valueFormat:"number". default reduce is "sum". ` +
528
+ `Return JSON only, no prose.\n\n` +
529
+ `User request: ${query}`;
530
+ const plan = await callJSON({
531
+ prompt,
532
+ task: 'chart',
533
+ signal: opts.signal,
534
+ maxOutputTokens: 300,
535
+ });
536
+ const valid = new Set(schema.map((c) => c.field));
537
+ const numericFields = new Set(schema.filter((c) => c.type === 'number').map((c) => c.field));
538
+ const CHART_TYPES = ['bar', 'line', 'area', 'pie'];
539
+ plan.type = CHART_TYPES.includes(plan.type) ? plan.type : 'bar';
540
+ plan.dimension = plan.dimension && valid.has(plan.dimension) ? plan.dimension : null;
541
+ plan.series = plan.series && valid.has(plan.series) && plan.series !== plan.dimension ? plan.series : null;
542
+ plan.measure =
543
+ plan.measure && numericFields.has(plan.measure)
544
+ ? plan.measure
545
+ : (schema.find((c) => c.type === 'number')?.field ?? null);
546
+ plan.reduce = ['sum', 'avg', 'count'].includes(plan.reduce) ? plan.reduce : 'sum';
547
+ plan.stacked = plan.stacked === true;
548
+ plan.logScale = plan.logScale === true;
549
+ plan.timeAxis = plan.timeAxis === true;
550
+ plan.valueFormat = ['number', 'currency', 'percent'].includes(plan.valueFormat) ? plan.valueFormat : 'number';
551
+ plan.rationale = plan.rationale ?? '';
552
+ if (opts.apply === true) {
553
+ const cfg = api;
554
+ cfg.configureChart?.({
555
+ open: true,
556
+ type: plan.type,
557
+ dimension: plan.dimension,
558
+ series: plan.series,
559
+ measure: plan.measure,
560
+ reduce: plan.reduce,
561
+ stacked: plan.stacked,
562
+ logScale: plan.logScale,
563
+ timeAxis: plan.timeAxis,
564
+ valueFormat: plan.valueFormat,
565
+ });
566
+ }
567
+ return plan;
568
+ }
569
+ /**
570
+ * Wire the grid's chart-panel AI button to the model: registers a handler (via
571
+ * `api.setChartAiHandler`) that runs `aiChart` and returns the plan for the
572
+ * panel to apply + explain. Call once after `onApiReady`. `installEnterprise`
573
+ * calls this for you.
574
+ */
575
+ export function enableAiCharting(api) {
576
+ const hook = api;
577
+ hook.setChartAiHandler?.(async (prompt) => {
578
+ const plan = await aiChart(api, prompt);
579
+ return {
580
+ type: plan.type,
581
+ dimension: plan.dimension,
582
+ series: plan.series,
583
+ measure: plan.measure,
584
+ reduce: plan.reduce,
585
+ stacked: plan.stacked,
586
+ logScale: plan.logScale,
587
+ timeAxis: plan.timeAxis,
588
+ valueFormat: plan.valueFormat,
589
+ rationale: plan.rationale,
590
+ };
591
+ });
592
+ }
593
+ export function disableAiCharting(api) {
594
+ const hook = api;
595
+ hook.setChartAiHandler?.(null);
596
+ }
597
+ // ---------------------------------------------------------------------------
598
+ // 8. Mock provider for examples + tests
599
+ // ---------------------------------------------------------------------------
600
+ /**
601
+ * A deterministic provider that returns canned, schema-shaped responses
602
+ * for each task. Wire it in via `setAIProvider(mockAIProvider)` to make
603
+ * the AI demo work end-to-end without a real model key. Not for production.
604
+ */
605
+ export const mockAIProvider = async (req) => {
606
+ // Tiny artificial delay so the UI's "thinking" state is visible.
607
+ await new Promise((r) => setTimeout(r, 350 + Math.random() * 400));
608
+ if (req.task === 'filter') {
609
+ const q = extractUserQuery(req.prompt);
610
+ return JSON.stringify(buildMockFilter(req.prompt, q));
611
+ }
612
+ if (req.task === 'smart-fill') {
613
+ return JSON.stringify(buildMockSmartFill(req.prompt));
614
+ }
615
+ if (req.task === 'summarize') {
616
+ return JSON.stringify(buildMockSummary(req.prompt));
617
+ }
618
+ if (req.task === 'classify') {
619
+ return JSON.stringify(buildMockClassify(req.prompt));
620
+ }
621
+ if (req.task === 'export') {
622
+ return JSON.stringify(buildMockExport(req.prompt));
623
+ }
624
+ if (req.task === 'anomaly') {
625
+ return JSON.stringify(buildMockAnomaly(req.prompt));
626
+ }
627
+ if (req.task === 'chart') {
628
+ return JSON.stringify(buildMockChart(req.prompt));
629
+ }
630
+ return '{}';
631
+ };
632
+ function buildMockChart(prompt) {
633
+ const q = extractUserRequest(prompt);
634
+ const typed = extractFieldTypes(prompt);
635
+ const textFields = typed.filter((f) => f.type === 'string' || f.type === 'date').map((f) => f.name);
636
+ const numberFields = typed.filter((f) => f.type === 'number').map((f) => f.name);
637
+ const type = /\bline\b|\btrend\b|over time/.test(q) ? 'line'
638
+ : /\barea\b/.test(q) ? 'area'
639
+ : /\bpie\b|share|proportion|breakdown/.test(q) ? 'pie'
640
+ : 'bar';
641
+ const byMatch = q.match(/\bby\s+([a-z0-9_ ]+?)(?:\s+(?:split|stacked|grouped|by|as|,|$))/);
642
+ const pickText = (hint) => {
643
+ if (hint) {
644
+ const f = textFields.find((t) => t.toLowerCase() === hint.trim() || (hint.trim().length >= 4 && t.toLowerCase().includes(hint.trim())));
645
+ if (f)
646
+ return f;
647
+ }
648
+ return null;
649
+ };
650
+ const dimension = pickText(byMatch?.[1]) ?? textFields[0] ?? null;
651
+ const series = /\b(split|stack(?:ed)?|by product|by category|per)\b/.test(q)
652
+ ? (textFields.find((t) => t !== dimension) ?? null)
653
+ : null;
654
+ const measure = numberFields.find((n) => q.includes(n.toLowerCase())) ?? numberFields[0] ?? null;
655
+ const reduce = /\b(average|avg|mean)\b/.test(q) ? 'avg' : /\b(count|number of|how many)\b/.test(q) ? 'count' : 'sum';
656
+ const stacked = /\bstack(ed)?\b/.test(q);
657
+ const logScale = /\b(log|logarithmic)\b/.test(q);
658
+ const timeAxis = /\b(over time|by date|by day|by month|by week|time series|timeline|trend)\b/.test(q);
659
+ const valueFormat = /\b(currency|money|revenue|sales|price|cost|\$|dollar)\b/.test(q) || /(price|revenue|amount|cost|sales)/i.test(measure ?? '')
660
+ ? 'currency'
661
+ : /\b(percent|percentage|%|rate|share)\b/.test(q)
662
+ ? 'percent'
663
+ : 'number';
664
+ return {
665
+ type, dimension, series, measure, reduce, stacked, logScale, timeAxis, valueFormat,
666
+ rationale: `${type} chart of ${reduce}(${measure ?? 'value'}) by ${dimension ?? 'category'}` +
667
+ `${series ? `, split by ${series}` : ''}${stacked ? ', stacked' : ''}` +
668
+ `${logScale ? ', log scale' : ''}${timeAxis ? ', date axis' : ''} (mock - wire a real model for genuine parsing).`,
669
+ };
670
+ }
671
+ function extractUserRequest(prompt) {
672
+ const m = prompt.match(/User request:\s*([\s\S]+)$/);
673
+ return (m?.[1] ?? '').trim().toLowerCase();
674
+ }
675
+ function buildMockExport(prompt) {
676
+ const q = extractUserRequest(prompt);
677
+ const fields = extractFields(prompt);
678
+ // Reuse the filter mock (it reads "User query:"; feed it a compatible line).
679
+ const filterPlan = buildMockFilter(prompt + `\nUser query: ${q}\n`, q);
680
+ // Format keyword routing.
681
+ const format = /\bpdf\b/.test(q) ? 'pdf'
682
+ : /\bxls\b(?!x)/.test(q) || /97-2003|legacy excel/.test(q) ? 'xls'
683
+ : /\b(xlsx|excel|spreadsheet|workbook)\b/.test(q) ? 'xlsx'
684
+ : /\b(markdown|md)\b/.test(q) ? 'md'
685
+ : /\bjson\b/.test(q) ? 'json'
686
+ : /\bxml\b/.test(q) ? 'xml'
687
+ : /\btsv\b/.test(q) ? 'tsv'
688
+ : /\bhtml\b/.test(q) ? 'html'
689
+ : /\bcsv\b/.test(q) ? 'csv'
690
+ : 'xlsx';
691
+ // Grouping: "group by X" / "grouped by X", else "grouped" -> a categorical field.
692
+ const groupBy = [];
693
+ const byMatch = q.match(/group(?:ed)?\s+by\s+([a-z0-9_ ,]+)/);
694
+ if (byMatch) {
695
+ for (const token of byMatch[1].split(/[, ]+/).filter(Boolean)) {
696
+ // Exact field match, or a substring match only for tokens long enough to
697
+ // be meaningful (so "a"/"as" don't match "amount").
698
+ const f = fields.find((ff) => ff.toLowerCase() === token || (token.length >= 4 && ff.toLowerCase().includes(token)));
699
+ if (f && !groupBy.includes(f))
700
+ groupBy.push(f);
701
+ }
702
+ }
703
+ else if (/\bgroup(ed)?\b/.test(q)) {
704
+ const cat = fields.find((f) => /region|country|category|status|stage|type|group|dept|team/i.test(f));
705
+ if (cat)
706
+ groupBy.push(cat);
707
+ }
708
+ return {
709
+ format,
710
+ filters: filterPlan.filters,
711
+ sort: filterPlan.sort,
712
+ groupBy,
713
+ rationale: `Export as ${format}${groupBy.length ? `, grouped by ${groupBy.join(' / ')}` : ''}${filterPlan.filters.length ? `; ${filterPlan.rationale}` : ''}`,
714
+ };
715
+ }
716
+ function buildMockAnomaly(prompt) {
717
+ // Parse the sampled rows, flag the numeric outliers per numeric field.
718
+ const rowsBlock = prompt.match(/Rows \(index is 0-based into this list\):\n([\s\S]*?)\n\n/)?.[1] ?? '';
719
+ const parsed = rowsBlock
720
+ .split('\n')
721
+ .map((line) => {
722
+ const m = line.match(/^(\d+):\s*(\{[\s\S]*\})$/);
723
+ if (!m)
724
+ return null;
725
+ const row = safeParse(m[2]);
726
+ return row ? { idx: parseInt(m[1], 10), row } : null;
727
+ })
728
+ .filter((r) => !!r);
729
+ if (parsed.length === 0) {
730
+ return { anomalies: [], summary: 'No rows to scan (mock).' };
731
+ }
732
+ // Genuinely numeric fields only: every value is null or a real number (so
733
+ // booleans like `inStock` and id-ish strings are excluded). Also skip
734
+ // identifier / row-index columns - a max "id" isn't an anomaly.
735
+ const isIdLike = (f) => /(^id$|_id$|index|idx|^#|guid|uuid|serial|rownum)/i.test(f);
736
+ const numericFields = Object.keys(parsed[0].row).filter((f) => !isIdLike(f) &&
737
+ parsed.some((p) => typeof p.row[f] === 'number') &&
738
+ parsed.every((p) => p.row[f] == null || typeof p.row[f] === 'number'));
739
+ const anomalies = [];
740
+ for (const f of numericFields.slice(0, 2)) {
741
+ let maxIdx = -1;
742
+ let maxVal = -Infinity;
743
+ for (const p of parsed) {
744
+ const n = Number(p.row[f]);
745
+ if (Number.isFinite(n) && n > maxVal) {
746
+ maxVal = n;
747
+ maxIdx = p.idx;
748
+ }
749
+ }
750
+ if (maxIdx >= 0) {
751
+ anomalies.push({
752
+ rowIndex: maxIdx,
753
+ field: f,
754
+ value: maxVal,
755
+ reason: `${f} = ${maxVal} is the highest in the sample and may be an outlier`,
756
+ severity: 'medium',
757
+ });
758
+ }
759
+ }
760
+ return {
761
+ anomalies,
762
+ summary: anomalies.length > 0
763
+ ? `Flagged ${anomalies.length} potential outlier${anomalies.length === 1 ? '' : 's'} (mock heuristic - wire a real model for genuine analysis).`
764
+ : 'No obvious anomalies in the sample (mock).',
765
+ };
766
+ }
767
+ function extractUserQuery(prompt) {
768
+ const m = prompt.match(/User query:\s*(.+?)\n/);
769
+ return (m?.[1] ?? '').toLowerCase();
770
+ }
771
+ function extractFields(prompt) {
772
+ const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/);
773
+ if (!m)
774
+ return [];
775
+ return (m[1] ?? '')
776
+ .split('\n')
777
+ .map((l) => l.match(/^- (\w+)/)?.[1])
778
+ .filter((s) => !!s);
779
+ }
780
+ /** Parse the "- name (type): ..." schema block into {name, type} pairs. */
781
+ function extractFieldTypes(prompt) {
782
+ const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/);
783
+ if (!m)
784
+ return [];
785
+ return (m[1] ?? '')
786
+ .split('\n')
787
+ .map((l) => {
788
+ const mm = l.match(/^- (\w+)\s*\((\w+)\)/);
789
+ return mm ? { name: mm[1], type: mm[2] } : null;
790
+ })
791
+ .filter((x) => !!x);
792
+ }
793
+ function buildMockFilter(prompt, q) {
794
+ const fields = extractFields(prompt);
795
+ const filters = [];
796
+ const sort = [];
797
+ const rationale = [];
798
+ // Greedy keyword routing. Real model would be smarter; this only needs
799
+ // to convince the demo viewer the pipeline works.
800
+ const numberWord = q.match(/(?:over|above|>|greater than)\s+\$?([\d.,]+)([kmb])?/);
801
+ const lessWord = q.match(/(?:under|below|<|less than)\s+\$?([\d.,]+)([kmb])?/);
802
+ // Pick a NUMBER-typed field (never a boolean like `inStock`), money-named
803
+ // ones first so "$300" targets price/amount rather than a count/index.
804
+ const numberTyped = extractFieldTypes(prompt).filter((f) => f.type === 'number').map((f) => f.name);
805
+ const moneyRe = /(price|amount|cost|revenue|total|value|salary|arr|fee|spend|budget|sales)/i;
806
+ const numberPool = numberTyped.length > 0 ? numberTyped : fields;
807
+ const numberFields = [
808
+ ...numberPool.filter((f) => moneyRe.test(f)),
809
+ ...numberPool.filter((f) => !moneyRe.test(f)),
810
+ ];
811
+ if (numberWord && numberFields[0]) {
812
+ const raw = parseFloat(numberWord[1].replace(/,/g, ''));
813
+ const mul = numberWord[2] === 'k' ? 1000 : numberWord[2] === 'm' ? 1000000 : numberWord[2] === 'b' ? 1000000000 : 1;
814
+ filters.push({ field: numberFields[0], operator: 'greaterThan', value: String(raw * mul) });
815
+ rationale.push(`amount > ${raw}${numberWord[2] ?? ''}`);
816
+ }
817
+ else if (lessWord && numberFields[0]) {
818
+ const raw = parseFloat(lessWord[1].replace(/,/g, ''));
819
+ const mul = lessWord[2] === 'k' ? 1000 : lessWord[2] === 'm' ? 1000000 : 1;
820
+ filters.push({ field: numberFields[0], operator: 'lessThan', value: String(raw * mul) });
821
+ rationale.push(`amount < ${raw}${lessWord[2] ?? ''}`);
822
+ }
823
+ // Quoted phrases -> contains on a likely text field.
824
+ const quote = q.match(/"([^"]+)"|'([^']+)'/);
825
+ const textFields = fields.filter((f) => /(name|company|customer|title|owner|status|region|category|industry)/i.test(f));
826
+ if (quote) {
827
+ const term = quote[1] ?? quote[2] ?? '';
828
+ if (textFields[0]) {
829
+ filters.push({ field: textFields[0], operator: 'contains', value: term });
830
+ rationale.push(`text contains "${term}"`);
831
+ }
832
+ }
833
+ // Person-name routing -> match owner/contact fields.
834
+ const personOwners = ['sasha', 'jamie', 'casey', 'drew', 'robin', 'morgan', 'riley', 'quinn'];
835
+ for (const n of personOwners) {
836
+ if (q.includes(n)) {
837
+ const ownerField = fields.find((f) => /owner|rep|assigned/i.test(f)) ?? fields.find((f) => /name/i.test(f));
838
+ if (ownerField) {
839
+ filters.push({ field: ownerField, operator: 'contains', value: n });
840
+ rationale.push(`owner ~ "${n}"`);
841
+ break;
842
+ }
843
+ }
844
+ }
845
+ // Region routing.
846
+ for (const r of ['NA', 'EMEA', 'APAC', 'LATAM']) {
847
+ if (q.toUpperCase().includes(r)) {
848
+ const regionField = fields.find((f) => /region/i.test(f));
849
+ if (regionField) {
850
+ filters.push({ field: regionField, operator: 'equals', value: r });
851
+ rationale.push(`region = ${r}`);
852
+ break;
853
+ }
854
+ }
855
+ }
856
+ // Status routing - any token in the query that matches a known status.
857
+ for (const s of ['active', 'pending', 'won', 'lost', 'live', 'paused', 'shipped', 'delivered']) {
858
+ if (q.includes(s)) {
859
+ const f = fields.find((f) => /status|stage/i.test(f));
860
+ if (f) {
861
+ filters.push({ field: f, operator: 'equals', value: s });
862
+ rationale.push(`status = ${s}`);
863
+ break;
864
+ }
865
+ }
866
+ }
867
+ // Sort detection.
868
+ if (/(highest|largest|biggest|top|most)/.test(q)) {
869
+ const f = numberFields[0];
870
+ if (f) {
871
+ sort.push({ field: f, desc: true });
872
+ rationale.push(`sort by ${f} desc`);
873
+ }
874
+ }
875
+ else if (/(lowest|smallest|least|cheapest)/.test(q)) {
876
+ const f = numberFields[0];
877
+ if (f) {
878
+ sort.push({ field: f, desc: false });
879
+ rationale.push(`sort by ${f} asc`);
880
+ }
881
+ }
882
+ else if (/(newest|recent|latest)/.test(q)) {
883
+ const dateField = fields.find((f) => /date|at|time/i.test(f));
884
+ if (dateField) {
885
+ sort.push({ field: dateField, desc: true });
886
+ rationale.push(`sort by ${dateField} desc`);
887
+ }
888
+ }
889
+ else if (/(oldest)/.test(q)) {
890
+ const dateField = fields.find((f) => /date|at|time/i.test(f));
891
+ if (dateField) {
892
+ sort.push({ field: dateField, desc: false });
893
+ rationale.push(`sort by ${dateField} asc`);
894
+ }
895
+ }
896
+ return {
897
+ filters,
898
+ sort,
899
+ rationale: rationale.length
900
+ ? `Interpreted: ${rationale.join(' AND ')}.`
901
+ : `Couldn't identify a clear filter for "${q}". Showing all rows.`,
902
+ };
903
+ }
904
+ function buildMockSmartFill(prompt) {
905
+ // Extract the target column and the rows-to-fill block; copy the first
906
+ // example's "output" pattern verbatim so the demo always returns
907
+ // something believable. Real models do much better - that's the point.
908
+ const fieldMatch = prompt.match(/Target column:\s*(\w+)/);
909
+ const rowsMatch = prompt.match(/Rows to fill:\n([\s\S]*?)\n\n/);
910
+ const exMatch = prompt.match(/Example 1: input=.* -> output=(.+)/);
911
+ const targetField = fieldMatch?.[1] ?? '';
912
+ const rowLines = (rowsMatch?.[1] ?? '').split('\n').filter(Boolean);
913
+ const exampleOutput = exMatch?.[1] ? safeParse(exMatch[1]) : '';
914
+ const predictions = rowLines
915
+ .map((line) => {
916
+ const m = line.match(/^Row (\d+): (\{.+\})/);
917
+ if (!m)
918
+ return null;
919
+ const rowIndex = parseInt(m[1], 10);
920
+ const row = safeParse(m[2]);
921
+ if (!row)
922
+ return null;
923
+ const value = inferFromRow(targetField, row, exampleOutput);
924
+ return { rowIndex, value, confidence: 0.78 + Math.random() * 0.18 };
925
+ })
926
+ .filter((p) => !!p);
927
+ return {
928
+ predictions,
929
+ rationale: `Inferred from ${exMatch ? 'the supplied' : 'no'} examples; mocked deterministically for the demo.`,
930
+ };
931
+ }
932
+ function safeParse(s) {
933
+ try {
934
+ return JSON.parse(s);
935
+ }
936
+ catch {
937
+ return null;
938
+ }
939
+ }
940
+ function inferFromRow(field, row, exampleOutput) {
941
+ // Mock heuristics that produce a value that "looks right" in common
942
+ // demo scenarios. The real provider would route through a real model.
943
+ if (field === 'priority') {
944
+ const arr = Number(row.arr ?? row.amount ?? row.price ?? 0);
945
+ return arr > 100000 ? 'high' : arr > 30000 ? 'medium' : 'low';
946
+ }
947
+ if (field === 'tier') {
948
+ const arr = Number(row.arr ?? row.amount ?? 0);
949
+ return arr > 500000 ? 'enterprise' : arr > 100000 ? 'growth' : 'starter';
950
+ }
951
+ if (field === 'tags' || field === 'category') {
952
+ return typeof exampleOutput === 'string' ? exampleOutput : 'auto-tag';
953
+ }
954
+ if (typeof exampleOutput === 'string')
955
+ return exampleOutput;
956
+ if (typeof exampleOutput === 'number')
957
+ return exampleOutput;
958
+ return exampleOutput ?? 'auto';
959
+ }
960
+ function buildMockSummary(prompt) {
961
+ const sliceMatch = prompt.match(/Slice size: (\d+) row/);
962
+ const n = sliceMatch ? parseInt(sliceMatch[1], 10) : 0;
963
+ const fields = extractSummaryFields(prompt);
964
+ return {
965
+ text: n === 1
966
+ ? `Single record. Notable signals come from ${fields.slice(0, 2).join(' and ') || 'the available fields'}.`
967
+ : `${n} rows in scope. The distribution skews toward live / active records, with a long tail in ${fields[0] ?? 'amount'}.`,
968
+ bullets: [
969
+ `${n} row${n === 1 ? '' : 's'} sampled`,
970
+ fields[0] ? `Largest variance in ${fields[0]}` : 'Tight clustering across visible fields',
971
+ fields[1] ? `${fields[1]} concentrates around the median` : 'Few outliers',
972
+ 'Mock summary - wire setAIProvider() to a real model for actual analysis',
973
+ ],
974
+ highlightedFields: fields.slice(0, 3),
975
+ };
976
+ }
977
+ function extractSummaryFields(prompt) {
978
+ const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/);
979
+ if (!m)
980
+ return [];
981
+ return (m[1] ?? '')
982
+ .split('\n')
983
+ .map((l) => l.match(/^- (\w+)/)?.[1])
984
+ .filter((s) => !!s);
985
+ }
986
+ function buildMockClassify(prompt) {
987
+ const labelsMatch = prompt.match(/Allowed labels[\s\S]*?:\n([\s\S]*?)\n\n/);
988
+ // Capture the label up to the first colon, whitespace or end-of-line so
989
+ // we don't pick up the rubric ("- at-risk: churn signals..." -> "at-risk").
990
+ const labels = (labelsMatch?.[1] ?? '')
991
+ .split('\n')
992
+ .map((l) => l.match(/^-\s*([^\s:]+)/)?.[1])
993
+ .filter((s) => !!s);
994
+ const rowLines = (prompt.match(/Rows to classify[\s\S]*?:\n([\s\S]*?)\n\n/)?.[1] ?? '').split('\n').filter(Boolean);
995
+ const predictions = rowLines.map((line) => {
996
+ const m = line.match(/^Row (\d+): "(.*)"/);
997
+ if (!m || labels.length === 0)
998
+ return null;
999
+ const rowIndex = parseInt(m[1], 10);
1000
+ const text = (m[2] ?? '').toLowerCase();
1001
+ // Pick the label whose token appears in the text; otherwise hash.
1002
+ const hit = labels.find((l) => text.includes(l.toLowerCase()));
1003
+ const value = hit ?? labels[Math.abs(hashStr(text)) % labels.length];
1004
+ return { rowIndex, value, confidence: hit ? 0.92 : 0.6 + Math.random() * 0.2 };
1005
+ }).filter((p) => !!p);
1006
+ return { predictions };
1007
+ }
1008
+ function hashStr(s) {
1009
+ let h = 0;
1010
+ for (let i = 0; i < s.length; i += 1)
1011
+ h = (h * 31 + s.charCodeAt(i)) | 0;
1012
+ return h;
1013
+ }