@malloy-publisher/sdk 0.0.248 → 0.0.249

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 (98) hide show
  1. package/README.md +32 -17
  2. package/dist/ServerProvider-CcfeBpt3.cjs.js +1 -0
  3. package/dist/{ServerProvider-BxEh3nFI.es.js → ServerProvider-EqBlMMqx.es.js} +1056 -905
  4. package/dist/client/api.d.ts +297 -6
  5. package/dist/client/index.cjs.js +1 -1
  6. package/dist/client/index.es.js +74 -70
  7. package/dist/components/Dashboard/Dashboard.d.ts +49 -0
  8. package/dist/components/Dashboard/DashboardTile.d.ts +48 -0
  9. package/dist/components/Dashboard/index.d.ts +2 -0
  10. package/dist/components/Notebook/Notebook.d.ts +46 -8
  11. package/dist/components/Notebook/NotebookCell.d.ts +37 -3
  12. package/dist/components/Notebook/runPlan.d.ts +29 -0
  13. package/dist/components/Notebook/types.d.ts +10 -0
  14. package/dist/components/Package/ContentTypeIcon.d.ts +17 -1
  15. package/dist/components/Package/Package.d.ts +1 -4
  16. package/dist/components/RenderedResult/RenderedResult.d.ts +7 -1
  17. package/dist/components/RenderedResult/ResultContainer.d.ts +3 -1
  18. package/dist/components/ResultsDialog.d.ts +4 -1
  19. package/dist/components/ServerProvider.d.ts +2 -1
  20. package/dist/components/click_helper.d.ts +10 -1
  21. package/dist/components/drill/index.d.ts +3 -0
  22. package/dist/components/drill/markDrillableCells.d.ts +55 -0
  23. package/dist/components/drill/resolveDrill.d.ts +159 -0
  24. package/dist/components/drill/useDrill.d.ts +63 -0
  25. package/dist/components/given/GivenInput.d.ts +27 -3
  26. package/dist/components/given/GivensPanel.d.ts +36 -7
  27. package/dist/components/given/filterValue.d.ts +117 -0
  28. package/dist/components/given/index.d.ts +1 -1
  29. package/dist/components/given/paramCodec.d.ts +60 -0
  30. package/dist/components/index.d.ts +4 -1
  31. package/dist/components/styles.d.ts +23 -0
  32. package/dist/constants/docLinks.d.ts +6 -0
  33. package/dist/{core-BuvlzSIX.es.js → core-DFBwNhvb.es.js} +1 -1
  34. package/dist/{core-C86Rb7tJ.cjs.js → core-DZk7z7ko.cjs.js} +1 -1
  35. package/dist/hooks/givenValue.d.ts +10 -0
  36. package/dist/hooks/index.d.ts +3 -1
  37. package/dist/hooks/useGivensState.d.ts +64 -0
  38. package/dist/hooks/useSuggestOptions.d.ts +78 -0
  39. package/dist/{index-BdtAZ5k6.es.js → index-CLcRrkxd.es.js} +41221 -39894
  40. package/dist/index-CWQXhe0D.cjs.js +338 -0
  41. package/dist/index.cjs.js +1 -1
  42. package/dist/index.es.js +77 -62
  43. package/dist/theme/types.d.ts +9 -0
  44. package/package.json +3 -1
  45. package/src/components/Connections/AddConnectionDialog.tsx +10 -1
  46. package/src/components/Dashboard/Dashboard.tsx +395 -0
  47. package/src/components/Dashboard/DashboardTile.tsx +150 -0
  48. package/src/components/Dashboard/index.ts +2 -0
  49. package/src/components/Home/Home.tsx +114 -23
  50. package/src/components/Notebook/Notebook.tsx +444 -390
  51. package/src/components/Notebook/NotebookCell.tsx +117 -3
  52. package/src/components/Notebook/runPlan.spec.ts +152 -0
  53. package/src/components/Notebook/runPlan.ts +64 -0
  54. package/src/components/Notebook/types.ts +11 -0
  55. package/src/components/Package/ContentTypeIcon.spec.ts +88 -0
  56. package/src/components/Package/ContentTypeIcon.tsx +77 -6
  57. package/src/components/Package/Package.tsx +148 -38
  58. package/src/components/RenderedResult/RenderedResult.tsx +309 -19
  59. package/src/components/RenderedResult/ResultContainer.tsx +28 -1
  60. package/src/components/ResultsDialog.tsx +5 -0
  61. package/src/components/ServerProvider.tsx +2 -0
  62. package/src/components/click_helper.ts +14 -1
  63. package/src/components/drill/index.ts +25 -0
  64. package/src/components/drill/markDrillableCells.dom.spec.ts +310 -0
  65. package/src/components/drill/markDrillableCells.spec.ts +106 -0
  66. package/src/components/drill/markDrillableCells.ts +311 -0
  67. package/src/components/drill/resolveDrill.spec.ts +446 -0
  68. package/src/components/drill/resolveDrill.ts +372 -0
  69. package/src/components/drill/useDrill.tsx +200 -0
  70. package/src/components/given/GivenInput.spec.tsx +495 -15
  71. package/src/components/given/GivenInput.tsx +562 -30
  72. package/src/components/given/GivensPanel.spec.tsx +172 -0
  73. package/src/components/given/GivensPanel.tsx +139 -32
  74. package/src/components/given/filterValue.spec.ts +361 -0
  75. package/src/components/given/filterValue.ts +204 -0
  76. package/src/components/given/index.ts +5 -1
  77. package/src/components/given/paramCodec.spec.ts +854 -0
  78. package/src/components/given/paramCodec.ts +480 -0
  79. package/src/components/index.ts +4 -1
  80. package/src/components/styles.ts +27 -3
  81. package/src/constants/docLinks.spec.ts +51 -0
  82. package/src/constants/docLinks.ts +26 -0
  83. package/src/hooks/givenValue.ts +10 -0
  84. package/src/hooks/index.ts +6 -4
  85. package/src/hooks/useGivensState.spec.ts +446 -0
  86. package/src/hooks/useGivensState.ts +337 -0
  87. package/src/hooks/useSuggestOptions.spec.ts +109 -0
  88. package/src/hooks/useSuggestOptions.ts +260 -0
  89. package/src/theme/buildTableCssVars.ts +4 -0
  90. package/src/theme/resolveTheme.spec.ts +13 -0
  91. package/src/theme/resolveTheme.ts +3 -0
  92. package/src/theme/types.ts +9 -0
  93. package/test/README.md +16 -10
  94. package/dist/ServerProvider-Dg5S1qBU.cjs.js +0 -1
  95. package/dist/hooks/useGivensForm.d.ts +0 -35
  96. package/dist/index-MES4MGpQ.cjs.js +0 -309
  97. package/src/hooks/useGivensForm.spec.ts +0 -99
  98. package/src/hooks/useGivensForm.ts +0 -107
@@ -0,0 +1,337 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { givensToParams, paramsToGivens } from "../components/given/paramCodec";
3
+ import type { GivenValue } from "./givenValue";
4
+
5
+ /**
6
+ * The state behind a control row: what the controls show, what the queries run
7
+ * with, and how a change gets from one to the other.
8
+ *
9
+ * Those are two different things whenever `autorun=false`. Editing three
10
+ * controls should re-run the queries once, when Apply is pressed, not three
11
+ * times on the way there, which matters most in a notebook, where one control
12
+ * change re-runs every cell in the document.
13
+ */
14
+ export interface UseGivensStateOptions {
15
+ /** Declared type per given name; decides how a URL value is read back. */
16
+ declaredTypes: ReadonlyMap<string, string | undefined>;
17
+ /**
18
+ * Starting values from `# artifact givens {…}`. Overridden by anything in
19
+ * `params`, so a link always wins over the file's defaults: otherwise a
20
+ * shared URL would not show what the sender was looking at.
21
+ */
22
+ startingValues?: Record<string, string>;
23
+ /**
24
+ * URL-carried values from the host. Read on mount and whenever they change
25
+ * beneath us (a drill navigating to a new URL for the same dashboard).
26
+ */
27
+ params?: Record<string, string>;
28
+ /**
29
+ * Called with the applied values whenever they change, for the host to write
30
+ * to the URL. It is the *applied* values, not the draft: a link should
31
+ * reproduce what the sender was looking at, not controls they had not
32
+ * committed yet.
33
+ */
34
+ onParamsChange?: (params: Record<string, string>) => void;
35
+ /**
36
+ * Identifies the document the edits belong to, so they are dropped when the
37
+ * host swaps documents underneath this hook. Without it the edits are keyed
38
+ * by their starting VALUES alone, and two documents whose starting values
39
+ * coincide (the common case: both empty) look like one, so the previous
40
+ * document's applied values keep filtering the new one.
41
+ */
42
+ documentKey?: string;
43
+ /** False batches changes behind Apply. */
44
+ autorun: boolean;
45
+ }
46
+
47
+ export interface UseGivensStateResult {
48
+ /** What the controls show. */
49
+ draft: Map<string, GivenValue>;
50
+ /** What queries should run with. Equal to `draft` when autorun. */
51
+ applied: Map<string, GivenValue>;
52
+ setGiven: (name: string, value: GivenValue) => void;
53
+ /**
54
+ * Back to where the document says the controls start, committed.
55
+ *
56
+ * Committed unconditionally, `autorun` or not: Reset is an explicit action
57
+ * like Apply, and leaving it pending makes the button look broken. And back
58
+ * to the *starting values* rather than to empty, because empty is not a
59
+ * state the document describes: clearing to it only to have the starting
60
+ * values flow back in from the URL is what made Reset run the queries twice.
61
+ */
62
+ reset: () => void;
63
+ /** Commit the draft. A no-op when autorun, where it is already committed. */
64
+ apply: () => void;
65
+ /** Whether the draft differs from what is applied. */
66
+ pending: boolean;
67
+ }
68
+
69
+ /**
70
+ * The user's edits, tagged with the starting point they were made against.
71
+ *
72
+ * The tag is what lets a new starting point take effect without an effect to
73
+ * clear the old edits, because edits whose key no longer matches are simply not
74
+ * read. A new starting point means a different dashboard, or the same one at a
75
+ * URL a drill has just pushed.
76
+ */
77
+ interface Edits {
78
+ key: string;
79
+ draft: Map<string, GivenValue>;
80
+ applied: Map<string, GivenValue>;
81
+ }
82
+
83
+ /** Values for givens the model no longer declares, dropped. */
84
+ function prune(
85
+ values: Map<string, GivenValue>,
86
+ declaredTypes: ReadonlyMap<string, string | undefined>,
87
+ ): Map<string, GivenValue> {
88
+ const stale = Array.from(values.keys()).filter(
89
+ (name) => !declaredTypes.has(name),
90
+ );
91
+ if (stale.length === 0) return values;
92
+ const next = new Map(values);
93
+ for (const name of stale) next.delete(name);
94
+ return next;
95
+ }
96
+
97
+ /**
98
+ * Entries in a fixed order, so the key below depends on the values and not on
99
+ * the order a host happened to build its object in. `URLSearchParams` iterates
100
+ * in the query string's own order, so `?B=2&A=1` and `?A=1&B=2` would otherwise
101
+ * be different starting points and re-key the reader's edits for nothing.
102
+ */
103
+ function stableEntries(source: Record<string, string> | undefined) {
104
+ return Object.entries(source ?? {}).sort(([a], [b]) => (a < b ? -1 : 1));
105
+ }
106
+
107
+ /** Same entries, same values: enough for state whose values are primitives. */
108
+ function sameParams(
109
+ a: Record<string, string>,
110
+ b: Record<string, string>,
111
+ ): boolean {
112
+ const aKeys = Object.keys(a);
113
+ if (aKeys.length !== Object.keys(b).length) return false;
114
+ return aKeys.every((key) => a[key] === b[key]);
115
+ }
116
+
117
+ export function useGivensState({
118
+ declaredTypes,
119
+ startingValues,
120
+ params,
121
+ onParamsChange,
122
+ documentKey,
123
+ autorun,
124
+ }: UseGivensStateOptions): UseGivensStateResult {
125
+ // Where the document says the controls start, with no URL in it. This is
126
+ // what Reset goes back to, so it deliberately ignores `params`: the URL is
127
+ // the thing being reset away from.
128
+ const startingPoint = useMemo(
129
+ () => paramsToGivens(startingValues ?? {}, declaredTypes),
130
+ // eslint-disable-next-line react-hooks/exhaustive-deps
131
+ [declaredTypes, JSON.stringify(startingValues)],
132
+ );
133
+
134
+ // The URL beats the file's starting values, per the precedence above.
135
+ const initial = useMemo(
136
+ () =>
137
+ paramsToGivens(
138
+ { ...(startingValues ?? {}), ...(params ?? {}) },
139
+ declaredTypes,
140
+ ),
141
+ // eslint-disable-next-line react-hooks/exhaustive-deps
142
+ [declaredTypes, JSON.stringify(startingValues), JSON.stringify(params)],
143
+ );
144
+
145
+ // Which starting point the edits below belong to. A change means a different
146
+ // document, or the same one at a different URL after a drill.
147
+ //
148
+ // The document is part of the key, not just the values. Keyed by values
149
+ // alone, navigating between two notebooks that both start empty produced
150
+ // equal keys, so the first notebook's applied values stayed `active` and
151
+ // filtered the second, while `lastReported` (equal to them already)
152
+ // suppressed the report that would have put them in the URL: the address bar
153
+ // and the running cells disagreed, and copying the URL reproduced neither.
154
+ //
155
+ // Built from the INPUTS that define a starting point, not from `initial`,
156
+ // which is those inputs already filtered by `declaredTypes`. Keying on the
157
+ // filtered map made the set of declared givens part of the key, so a model
158
+ // reload that merely dropped one given re-keyed everything and discarded the
159
+ // reader's edits to the givens that SURVIVED, which is the opposite of what
160
+ // `prune` below is written to do. Dropping stale values is `prune`'s job; a
161
+ // declaration change is not a new starting point.
162
+ const initialKey = useMemo(
163
+ () =>
164
+ JSON.stringify([
165
+ documentKey ?? null,
166
+ stableEntries(startingValues),
167
+ stableEntries(params),
168
+ ]),
169
+ // eslint-disable-next-line react-hooks/exhaustive-deps
170
+ [documentKey, JSON.stringify(startingValues), JSON.stringify(params)],
171
+ );
172
+
173
+ // KNOWN LIMITATION, latent today. A given that has a starting value cannot be
174
+ // cleared: `setGiven(name, null)` drops the key, the report omits it, the host
175
+ // removes it from the URL, `initial` recomputes from `startingValues` and
176
+ // still carries it, `initialKey` therefore changes, the edits are discarded as
177
+ // stale, and the control snaps back to the value the reader just cleared.
178
+ //
179
+ // Not reachable yet: no server populates `startingGivens`, and deliberately
180
+ // not fixed here, because the fix has to tell our OWN echo of the URL (which
181
+ // must not discard edits) from an externally pushed URL such as a drill
182
+ // arriving (which must), and that is the one piece of this hook the drill path
183
+ // depends on and is covered by live tests. Getting it wrong breaks something
184
+ // that works to fix something nothing can reach.
185
+ //
186
+ // The intended shape, for whoever makes it reachable: compare the incoming
187
+ // `params` against `lastReported` below, treat a match as our own echo, and
188
+ // keep the edits (and their key) across it. An explicit `cleared` set on
189
+ // `Edits` is the alternative and needs the same echo test to survive.
190
+ //
191
+ // Only the user's edits are state; `initial` is read through, not copied in.
192
+ //
193
+ // Copying it in on arrival cannot be made correct here. The starting values
194
+ // are not known on mount: they arrive with the manifest, a render later,
195
+ // and every way of adopting them afterwards is wrong in its own way. An
196
+ // effect hands the surfaces the empty map first and the real values a commit
197
+ // later, so a notebook link carrying parameters runs every cell bare and
198
+ // then runs the whole document again. A render-phase update avoids the extra
199
+ // commit but does not survive: React can restart a render attempt and drop
200
+ // the queued updates, which left the controls blank while a stale draft won.
201
+ //
202
+ // Reading through has neither problem. The first render that sees the
203
+ // manifest already reports the right values, and there is no second state to
204
+ // fall out of step with the props.
205
+ const [edits, setEdits] = useState<Edits | null>(null);
206
+ const active = edits?.key === initialKey ? edits : null;
207
+
208
+ // Edits whose key no longer matches are DISCARDED, not merely ignored. The
209
+ // line above stops reading them, which is enough until the key comes back:
210
+ // the key space is small (document plus starting values plus params) and is
211
+ // revisited routinely, so `a` -> `b` -> `a` from a clean link matched the
212
+ // abandoned edits again and re-applied a filter the URL did not carry, to a
213
+ // reader who had just opened the notebook fresh. Browser Back and a drill
214
+ // pushing a URL equal to an earlier one do the same thing.
215
+ //
216
+ // In an effect rather than during render: `active` already ignores them, so
217
+ // this cannot change what this render shows, and clearing is idempotent if
218
+ // React runs it more than once.
219
+ useEffect(() => {
220
+ if (edits !== null && edits.key !== initialKey) setEdits(null);
221
+ }, [edits, initialKey]);
222
+
223
+ // Drop values for givens that no longer exist, which is what a model reload
224
+ // can do while the page is open. Sending one the model no longer declares
225
+ // fails the query outright ("unknown given"), so a value outliving its
226
+ // declaration is worse than losing the edit. Values for givens that survive
227
+ // the reload are kept, since re-typing them would be the greater annoyance.
228
+ //
229
+ // `initial` needs none of this: `paramsToGivens` already keeps only declared
230
+ // names, which is why this narrows the edits alone.
231
+ const draft = useMemo(
232
+ () => prune(active?.draft ?? initial, declaredTypes),
233
+ [active, initial, declaredTypes],
234
+ );
235
+ const applied = useMemo(
236
+ () => prune(active?.applied ?? initial, declaredTypes),
237
+ [active, initial, declaredTypes],
238
+ );
239
+
240
+ // Edits are made against whatever is on screen now, so a first edit has to
241
+ // start from `initial` rather than from an empty map: otherwise setting one
242
+ // control would silently drop the starting values of the others.
243
+ const base = useCallback(
244
+ (prev: Edits | null): Edits =>
245
+ prev?.key === initialKey
246
+ ? prev
247
+ : { key: initialKey, draft: initial, applied: initial },
248
+ [initialKey, initial],
249
+ );
250
+
251
+ // Report applied values outward for the host to put in the URL. Skipped when
252
+ // they already match, so this cannot loop against a host that feeds its URL
253
+ // back in through `params`.
254
+ //
255
+ // Starting values are reported too, not just edits: the address bar is meant
256
+ // to show what the reader is looking at, so a dashboard opened at its
257
+ // declared defaults is already a link that reproduces them.
258
+ //
259
+ // The reference starts at the first render's values rather than empty. The
260
+ // control row is empty until the manifest arrives and says which givens
261
+ // exist, and an unseeded reference would report that emptiness on mount,
262
+ // telling the host to clear a URL whose parameters had not been read yet,
263
+ // wiping the state the link was carrying.
264
+ //
265
+ // ACCEPTED COST of that seeding: when the manifest is already cached, the
266
+ // first render knows the types, so the seed equals the URL's values and no
267
+ // initial report fires at all. A host that learns which names are its own
268
+ // FROM the reports (as `NotebookPage` does) therefore never learns them, and
269
+ // if a later model reload drops one of those givens, its parameter is left
270
+ // behind in the address bar. Kept because the alternative is worse: an
271
+ // unseeded reference wipes a shared link's parameters on mount for any
272
+ // consumer that wires this callback before the manifest lands, and a
273
+ // leftover parameter for an undeclared given is inert, since `paramsToGivens`
274
+ // ignores names the model does not declare.
275
+ const appliedParams = useMemo(
276
+ () => givensToParams(applied, declaredTypes),
277
+ [applied, declaredTypes],
278
+ );
279
+ const lastReported = useRef<Record<string, string>>(appliedParams);
280
+ useEffect(() => {
281
+ if (!onParamsChange) return;
282
+ if (sameParams(lastReported.current, appliedParams)) return;
283
+ lastReported.current = appliedParams;
284
+ onParamsChange(appliedParams);
285
+ }, [appliedParams, onParamsChange]);
286
+
287
+ const setGiven = useCallback(
288
+ (name: string, value: GivenValue) => {
289
+ setEdits((prev) => {
290
+ const from = base(prev);
291
+ const next = new Map(from.draft);
292
+ if (value === null) next.delete(name);
293
+ else next.set(name, value);
294
+ return {
295
+ key: from.key,
296
+ draft: next,
297
+ applied: autorun ? next : from.applied,
298
+ };
299
+ });
300
+ },
301
+ [autorun, base],
302
+ );
303
+
304
+ const reset = useCallback(() => {
305
+ setEdits((prev) => ({
306
+ key: base(prev).key,
307
+ draft: startingPoint,
308
+ applied: startingPoint,
309
+ }));
310
+ }, [base, startingPoint]);
311
+
312
+ const apply = useCallback(() => {
313
+ setEdits((prev) => {
314
+ const from = base(prev);
315
+ return { key: from.key, draft: from.draft, applied: from.draft };
316
+ });
317
+ }, [base]);
318
+
319
+ const pending = useMemo(() => {
320
+ if (autorun) return false;
321
+ if (draft.size !== applied.size) return true;
322
+ for (const [name, value] of draft) {
323
+ const other = applied.get(name);
324
+ // Dates are the one non-primitive here, so compare them by instant.
325
+ if (value instanceof Date && other instanceof Date) {
326
+ if (value.getTime() !== other.getTime()) return true;
327
+ } else if (Array.isArray(value) && Array.isArray(other)) {
328
+ if (String(value) !== String(other)) return true;
329
+ } else if (value !== other) {
330
+ return true;
331
+ }
332
+ }
333
+ return false;
334
+ }, [autorun, draft, applied]);
335
+
336
+ return { draft, applied, setGiven, reset, apply, pending };
337
+ }
@@ -0,0 +1,109 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import {
3
+ buildSuggestQuery,
4
+ readOptionValues,
5
+ SUGGEST_OPTION_LIMIT,
6
+ } from "./useSuggestOptions";
7
+
8
+ describe("readOptionValues", () => {
9
+ it("takes the named dimension's column", () => {
10
+ const rows = JSON.stringify([
11
+ { region: "us-east", orders: 12 },
12
+ { region: "us-west", orders: 8 },
13
+ ]);
14
+ expect(readOptionValues(rows, "region")).toEqual(["us-east", "us-west"]);
15
+ });
16
+
17
+ it("falls back to the first column", () => {
18
+ // A `suggest { query=… }` names no dimension, and its column can be
19
+ // called anything.
20
+ const rows = JSON.stringify([{ name: "Nike" }, { name: "Levi's" }]);
21
+ expect(readOptionValues(rows, undefined)).toEqual(["Nike", "Levi's"]);
22
+ });
23
+
24
+ it("drops nulls and duplicates", () => {
25
+ // "No value" is expressed by clearing the control, not by picking an
26
+ // empty option.
27
+ const rows = JSON.stringify([
28
+ { region: "us-east" },
29
+ { region: null },
30
+ { region: "us-east" },
31
+ ]);
32
+ expect(readOptionValues(rows, "region")).toEqual(["us-east"]);
33
+ });
34
+
35
+ it("renders a non-string value as text", () => {
36
+ const rows = JSON.stringify([{ year: 2024 }, { year: 2025 }]);
37
+ expect(readOptionValues(rows, "year")).toEqual(["2024", "2025"]);
38
+ });
39
+
40
+ it("is empty for the shapes that legitimately mean no values", () => {
41
+ // `result` is optional in the API contract, so an absent one is a
42
+ // response the server is allowed to send, and an empty list plainly
43
+ // means no values.
44
+ expect(readOptionValues(undefined, undefined)).toEqual([]);
45
+ expect(readOptionValues("[]", undefined)).toEqual([]);
46
+ });
47
+
48
+ it("throws on a response it cannot read, rather than reporting no values", () => {
49
+ // This used to return `[]` for both, which collapsed "the query failed"
50
+ // into "this dimension is empty": the control said "No matching values"
51
+ // about a populated dimension. Throwing is what reaches `failed` and
52
+ // puts "Options unavailable" on the control instead.
53
+ expect(() => readOptionValues("not json", undefined)).toThrow();
54
+ expect(() => readOptionValues('{"not":"an array"}', undefined)).toThrow();
55
+ });
56
+ });
57
+
58
+ describe("readOptionValues takes the OUTPUT column name", () => {
59
+ it("finds a joined dimension's column, which is its last segment", () => {
60
+ // `group_by: products.category` names its column `category`. Looking up
61
+ // the full path finds nothing and falls back to the first column, which is
62
+ // right only by luck when the query selects exactly one.
63
+ const rows = JSON.stringify([
64
+ { state: "CA", category: "Outerwear" },
65
+ { state: "NY", category: "Jeans" },
66
+ ]);
67
+ expect(readOptionValues(rows, "category")).toEqual([
68
+ "Outerwear",
69
+ "Jeans",
70
+ ]);
71
+ // The path spelling misses, and takes the wrong column.
72
+ expect(readOptionValues(rows, "products.category")).toEqual(["CA", "NY"]);
73
+ });
74
+ });
75
+
76
+ describe("the generated suggest query", () => {
77
+ // Asserts the text the hook actually sends, by calling the exported builder
78
+ // rather than a copy declared here. Rebuilding the string alongside the
79
+ // implementation would prove only that the test agrees with itself, which is
80
+ // no use for text that reaches a warehouse.
81
+ it("orders by the output field name, not the field path", () => {
82
+ // `order_by: products.category` is refused by the compiler ("order_by
83
+ // takes the name of a field in the query output, not a path"), which would
84
+ // have failed the option query for every joined dimension. Verified against
85
+ // a real DuckDB-backed model: the path form errors, this form returns the
86
+ // 10 categories.
87
+ expect(buildSuggestQuery("order_items", "products.category")).toBe(
88
+ "run: order_items -> {\n" +
89
+ " group_by: products.category\n" +
90
+ " order_by: category asc\n" +
91
+ ` limit: ${SUGGEST_OPTION_LIMIT}\n` +
92
+ "}",
93
+ );
94
+ });
95
+
96
+ it("is unchanged for a dimension that is already a bare name", () => {
97
+ expect(buildSuggestQuery("products", "category")).toContain(
98
+ "order_by: category asc",
99
+ );
100
+ });
101
+
102
+ it("always carries an explicit limit", () => {
103
+ // Otherwise the server's default row cap truncates in whatever order the
104
+ // warehouse returned, silently and differently each time.
105
+ expect(buildSuggestQuery("products", "category")).toContain(
106
+ `limit: ${SUGGEST_OPTION_LIMIT}`,
107
+ );
108
+ });
109
+ });