@malloy-publisher/sdk 0.3.0 → 0.4.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 (244) hide show
  1. package/README.md +22 -9
  2. package/dist/DocumentStorageProvider-CyOJ0hqf.es.js +24443 -0
  3. package/dist/DocumentStorageProvider-DGPQEd_l.cjs.js +134 -0
  4. package/dist/RenderedResult-BnPzJ9Jf.es.js +549 -0
  5. package/dist/RenderedResult-Dp22kZsQ.cjs.js +115 -0
  6. package/dist/{ServerProvider-DSK9rfSY.es.js → ServerProvider-BWOEKg0O.es.js} +1256 -1318
  7. package/dist/ServerProvider-Cc489A3f.cjs.js +1 -0
  8. package/dist/builder/index.cjs.js +105 -0
  9. package/dist/builder/index.d.ts +2 -0
  10. package/dist/builder/index.es.js +9482 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/api.d.ts +100 -42
  13. package/dist/client/index.cjs.js +1 -1
  14. package/dist/client/index.es.js +1 -1
  15. package/dist/components/AppDialog.d.ts +30 -0
  16. package/dist/components/BackLink.d.ts +32 -0
  17. package/dist/components/Dashboard/Dashboard.d.ts +19 -14
  18. package/dist/components/Dashboard/DashboardBar.d.ts +21 -0
  19. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  20. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  21. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  22. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  23. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  24. package/dist/components/Dashboard/index.d.ts +2 -0
  25. package/dist/components/Dashboard/promoteMeasureRow.d.ts +7 -3
  26. package/dist/components/Dashboard/telemetry.d.ts +48 -0
  27. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  28. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +31 -0
  29. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +118 -0
  30. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +30 -0
  31. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  32. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  33. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  34. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  35. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  36. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  37. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  38. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  39. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  40. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  41. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  42. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  43. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  44. package/dist/components/DashboardBuilder/newDashboard.d.ts +17 -0
  45. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  46. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  47. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  48. package/dist/components/DashboardBuilder/spliceDocument.d.ts +53 -0
  49. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  50. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  51. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  52. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  53. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  54. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  55. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  56. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +7 -0
  57. package/dist/components/DocumentStorage/index.d.ts +1 -1
  58. package/dist/components/FloatingIconButton.d.ts +16 -0
  59. package/dist/components/ItemRow.d.ts +38 -0
  60. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +1 -2
  61. package/dist/components/Materializations/MaterializationRunsList.d.ts +1 -5
  62. package/dist/components/Materializations/Materializations.d.ts +7 -3
  63. package/dist/components/Materializations/ScopeButton.d.ts +18 -0
  64. package/dist/components/Materializations/SectionLabel.d.ts +7 -4
  65. package/dist/components/Materializations/TriggerLabel.d.ts +14 -0
  66. package/dist/components/Materializations/index.d.ts +0 -1
  67. package/dist/components/Package/ContentTypeIcon.d.ts +3 -5
  68. package/dist/components/Package/NewDashboardDialog.d.ts +18 -0
  69. package/dist/components/Package/index.d.ts +0 -1
  70. package/dist/components/PackageSection.d.ts +23 -0
  71. package/dist/components/Prose.d.ts +46 -0
  72. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  73. package/dist/components/RenderedResult/index.d.ts +1 -0
  74. package/dist/components/buttons.d.ts +53 -0
  75. package/dist/components/drill/index.d.ts +1 -1
  76. package/dist/components/drill/resolveDrill.d.ts +22 -0
  77. package/dist/components/drill/useDrill.d.ts +11 -2
  78. package/dist/components/index.d.ts +6 -0
  79. package/dist/components/styles.d.ts +49 -44
  80. package/dist/hooks/index.d.ts +2 -0
  81. package/dist/hooks/useCrudMutation.d.ts +42 -0
  82. package/dist/hooks/useDocumentControls.d.ts +70 -0
  83. package/dist/hooks/useQueryResult.d.ts +40 -0
  84. package/dist/index.cjs.js +22 -273
  85. package/dist/index.d.ts +1 -0
  86. package/dist/index.es.js +16888 -44451
  87. package/dist/telemetry/consoleEvents.d.ts +60 -0
  88. package/dist/utils/malloyLiteral.d.ts +11 -0
  89. package/dist/utils/sha256.d.ts +2 -0
  90. package/package.json +24 -9
  91. package/src/builder-entry.ts +55 -0
  92. package/src/components/AppDialog.tsx +115 -0
  93. package/src/components/BackLink.tsx +83 -0
  94. package/src/components/Connections/AddConnectionDialog.tsx +50 -70
  95. package/src/components/Connections/DeleteConnectionDialog.tsx +23 -50
  96. package/src/components/Connections/EditConnectionDialog.tsx +54 -73
  97. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  98. package/src/components/Dashboard/Dashboard.tsx +165 -175
  99. package/src/components/Dashboard/DashboardBar.tsx +88 -0
  100. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  101. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  102. package/src/components/Dashboard/DashboardTile.tsx +66 -123
  103. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  104. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  105. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  106. package/src/components/Dashboard/TileCard.tsx +120 -0
  107. package/src/components/Dashboard/index.ts +2 -0
  108. package/src/components/Dashboard/promoteMeasureRow.spec.ts +70 -0
  109. package/src/components/Dashboard/promoteMeasureRow.ts +33 -2
  110. package/src/components/Dashboard/telemetry.ts +51 -0
  111. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  112. package/src/components/DashboardBuilder/AddTileDialog.tsx +247 -0
  113. package/src/components/DashboardBuilder/BuilderToolbar.tsx +162 -0
  114. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +852 -0
  115. package/src/components/DashboardBuilder/DashboardBuilder.tsx +666 -0
  116. package/src/components/DashboardBuilder/DashboardEditor.package.spec.tsx +163 -0
  117. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +188 -0
  118. package/src/components/DashboardBuilder/DashboardEditor.tsx +567 -0
  119. package/src/components/DashboardBuilder/DiffDialog.tsx +122 -0
  120. package/src/components/DashboardBuilder/DrillDialog.tsx +269 -0
  121. package/src/components/DashboardBuilder/FilterDialog.tsx +562 -0
  122. package/src/components/DashboardBuilder/FilterStrip.tsx +126 -0
  123. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  124. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  125. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  126. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  127. package/src/components/DashboardBuilder/catalog.ts +225 -0
  128. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  129. package/src/components/DashboardBuilder/controls.ts +398 -0
  130. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  131. package/src/components/DashboardBuilder/diff.ts +93 -0
  132. package/src/components/DashboardBuilder/document.ts +209 -0
  133. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  134. package/src/components/DashboardBuilder/layout.ts +143 -0
  135. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  136. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  137. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  138. package/src/components/DashboardBuilder/newDashboard.spec.ts +40 -0
  139. package/src/components/DashboardBuilder/newDashboard.ts +48 -0
  140. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  141. package/src/components/DashboardBuilder/preview.ts +172 -0
  142. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  143. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  144. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  145. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1161 -0
  146. package/src/components/DashboardBuilder/spliceDocument.ts +1135 -0
  147. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  148. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  149. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +311 -0
  150. package/src/components/DashboardBuilder/useDashboardEditor.ts +201 -0
  151. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  152. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  153. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  154. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  155. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  156. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  157. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  158. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  159. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +12 -0
  160. package/src/components/DocumentStorage/index.ts +1 -0
  161. package/src/components/Environment/About.tsx +16 -62
  162. package/src/components/Environment/AddPackageDialog.tsx +85 -154
  163. package/src/components/Environment/Connections.tsx +125 -205
  164. package/src/components/Environment/DeletePackageDialog.tsx +32 -77
  165. package/src/components/Environment/EditPackageDialog.tsx +46 -58
  166. package/src/components/Environment/Environment.tsx +34 -36
  167. package/src/components/Environment/Packages.tsx +63 -128
  168. package/src/components/FloatingIconButton.tsx +41 -0
  169. package/src/components/Home/AddEnvironmentDialog.tsx +47 -70
  170. package/src/components/Home/DeleteEnvironmentDialog.tsx +32 -77
  171. package/src/components/Home/EditEnvironmentDialog.tsx +47 -61
  172. package/src/components/Home/Home.tsx +101 -214
  173. package/src/components/ItemRow.tsx +165 -0
  174. package/src/components/Materializations/CreateMaterializationDialog.tsx +34 -51
  175. package/src/components/Materializations/DeleteMaterializationDialog.tsx +31 -53
  176. package/src/components/Materializations/MaterializationDetailDialog.tsx +60 -69
  177. package/src/components/Materializations/MaterializationRunsList.tsx +29 -42
  178. package/src/components/Materializations/Materializations.tsx +137 -140
  179. package/src/components/Materializations/ScopeButton.tsx +85 -0
  180. package/src/components/Materializations/SectionLabel.tsx +7 -4
  181. package/src/components/Materializations/SetScheduleDialog.tsx +48 -89
  182. package/src/components/Materializations/TriggerLabel.tsx +36 -0
  183. package/src/components/Materializations/cron.spec.ts +113 -0
  184. package/src/components/Materializations/index.ts +0 -1
  185. package/src/components/Materializations/utils.spec.ts +182 -0
  186. package/src/components/Model/Model.tsx +6 -23
  187. package/src/components/Model/ModelCell.tsx +33 -72
  188. package/src/components/Notebook/Notebook.tsx +25 -88
  189. package/src/components/Notebook/NotebookCell.tsx +35 -183
  190. package/src/components/Package/ContentTypeIcon.spec.ts +22 -37
  191. package/src/components/Package/ContentTypeIcon.tsx +10 -12
  192. package/src/components/Package/NewDashboardDialog.spec.tsx +129 -0
  193. package/src/components/Package/NewDashboardDialog.tsx +265 -0
  194. package/src/components/Package/Package.tsx +179 -238
  195. package/src/components/Package/index.ts +0 -1
  196. package/src/components/PackageSection.tsx +85 -0
  197. package/src/components/Prose.spec.tsx +85 -0
  198. package/src/components/Prose.tsx +179 -0
  199. package/src/components/QueryResult/QueryResult.tsx +15 -43
  200. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +198 -0
  201. package/src/components/RenderedResult/RenderedResult.tsx +22 -8
  202. package/src/components/RenderedResult/ResultContainer.tsx +4 -12
  203. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  204. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  205. package/src/components/RenderedResult/index.ts +1 -0
  206. package/src/components/ResultsDialog.tsx +8 -32
  207. package/src/components/buttons.tsx +114 -0
  208. package/src/components/designSystem.spec.tsx +316 -0
  209. package/src/components/drill/index.ts +1 -0
  210. package/src/components/drill/resolveDrill.ts +22 -1
  211. package/src/components/drill/useDrill.spec.tsx +94 -0
  212. package/src/components/drill/useDrill.tsx +52 -12
  213. package/src/components/given/GivensPanel.tsx +1 -1
  214. package/src/components/given/paramCodec.spec.ts +1 -1
  215. package/src/components/index.ts +16 -0
  216. package/src/components/styles.ts +49 -122
  217. package/src/hooks/index.ts +13 -0
  218. package/src/hooks/useCrudMutation.spec.tsx +119 -0
  219. package/src/hooks/useCrudMutation.tsx +85 -0
  220. package/src/hooks/useDocumentControls.ts +170 -0
  221. package/src/hooks/useQueryResult.ts +82 -0
  222. package/src/index.ts +9 -0
  223. package/src/telemetry/consoleEvents.spec.ts +130 -0
  224. package/src/telemetry/consoleEvents.ts +124 -0
  225. package/src/theme/defaults.ts +34 -23
  226. package/src/theme/resolveTheme.spec.ts +9 -4
  227. package/src/theme/resolveTheme.ts +12 -8
  228. package/src/utils/malloyLiteral.spec.ts +43 -0
  229. package/src/utils/malloyLiteral.ts +76 -0
  230. package/src/utils/sha256.ts +13 -0
  231. package/test/README.md +1 -1
  232. package/test/serverProvider.tsx +5 -2
  233. package/vite.config.ts +5 -0
  234. package/dist/ServerProvider-CGnLjzag.cjs.js +0 -1
  235. package/dist/components/Materializations/CreateEnvMaterializationDialog.d.ts +0 -14
  236. package/dist/components/Materializations/EnvironmentMaterializations.d.ts +0 -7
  237. package/dist/components/Materializations/ScheduleCard.d.ts +0 -20
  238. package/dist/components/Materializations/TriggerChip.d.ts +0 -10
  239. package/dist/components/Package/Models.d.ts +0 -6
  240. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +0 -179
  241. package/src/components/Materializations/EnvironmentMaterializations.tsx +0 -267
  242. package/src/components/Materializations/ScheduleCard.tsx +0 -231
  243. package/src/components/Materializations/TriggerChip.tsx +0 -44
  244. package/src/components/Package/Models.tsx +0 -71
@@ -0,0 +1,85 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import Snackbar from "@mui/material/Snackbar";
5
+ import { useQueryClient, type QueryKey } from "@tanstack/react-query";
6
+ import * as React from "react";
7
+ import { useState } from "react";
8
+ import { useMutationWithApiError } from "./useQueryWithApiError";
9
+ import { reporting, type ConsoleResource } from "../telemetry/consoleEvents";
10
+
11
+ /**
12
+ * A write from a dialog: run it, close the dialog, refetch what it changed,
13
+ * and say what happened.
14
+ *
15
+ * Every create/edit/delete dialog in the Console does those four things in the
16
+ * same order and reported failure in one of two different ways depending on
17
+ * which file you were in. The shape is here once so the two conventions cannot
18
+ * drift back apart: a thrown `Error` shows its own message, because the API
19
+ * layer already turns a failed response into one worth reading, and anything
20
+ * else falls back to a sentence rather than `[object Object]`.
21
+ *
22
+ * `notice` is the Snackbar, wired and ready to render. It is returned rather
23
+ * than portalled from in here so a caller keeps it as a sibling of its dialog,
24
+ * where it was.
25
+ */
26
+ export function useCrudMutation<TVariables = void>({
27
+ mutationFn,
28
+ success,
29
+ invalidates,
30
+ closeDialog,
31
+ resource,
32
+ action,
33
+ }: {
34
+ mutationFn: (variables: TVariables) => Promise<unknown>;
35
+ /** What the snackbar says when the write lands: "Package created". */
36
+ success: string;
37
+ /** The query keys the write invalidates. Name the narrowest that covers it. */
38
+ invalidates: QueryKey[];
39
+ /**
40
+ * Closes the dialog. Runs on SUCCESS only — a write that failed leaves
41
+ * something to correct and retry, so the form has to stay — and before the
42
+ * refetch, so the dialog goes at once rather than after the list reloads.
43
+ *
44
+ * Not called `onSettled`: that name means "success or error" everywhere
45
+ * else in React Query, and this is the opposite of that.
46
+ */
47
+ closeDialog: () => void;
48
+ /** What is being written, for the event; see `ConsoleEvent`. */
49
+ resource: ConsoleResource;
50
+ action: "create" | "update" | "delete";
51
+ }) {
52
+ const queryClient = useQueryClient();
53
+ const [message, setMessage] = useState("");
54
+ const mutation = useMutationWithApiError({
55
+ // The same wrapper Connections and Materializations use, so there is one
56
+ // implementation of "a Console write reports itself" rather than one per
57
+ // shape of write.
58
+ mutationFn: reporting(resource, action, mutationFn),
59
+ onSuccess() {
60
+ closeDialog();
61
+ for (const queryKey of invalidates)
62
+ queryClient.invalidateQueries({ queryKey });
63
+ setMessage(success);
64
+ },
65
+ onError(error) {
66
+ setMessage(
67
+ error instanceof Error
68
+ ? error.message
69
+ : "An unknown error occurred",
70
+ );
71
+ },
72
+ });
73
+ return {
74
+ mutate: mutation.mutate,
75
+ isPending: mutation.isPending,
76
+ notice: (
77
+ <Snackbar
78
+ open={message !== ""}
79
+ autoHideDuration={6000}
80
+ onClose={() => setMessage("")}
81
+ message={message}
82
+ />
83
+ ) as React.ReactNode,
84
+ };
85
+ }
@@ -0,0 +1,170 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useCallback, useMemo } from "react";
5
+ import type { Given } from "../client";
6
+ import { useDrillSelf } from "../components/drill/useDrillSelf";
7
+ import type { GivensPanelProps } from "../components/given/GivensPanel";
8
+ import { useGivensState, type UseGivensStateResult } from "./useGivensState";
9
+ import { useSuggestOptions } from "./useSuggestOptions";
10
+
11
+ /**
12
+ * Everything a document's control row needs, from what the document declares.
13
+ *
14
+ * A dashboard, a notebook and the builder's harness each wired this by hand:
15
+ * the declared types read off the givens, the report to the host guarded on the
16
+ * document having loaded, `useGivensState`, `useSuggestOptions` for the pickers'
17
+ * options, `useDrillSelf` for `to=self`, and the same nine props into
18
+ * `GivensPanel`. Sixty lines each, with the same reasoning in the comments of
19
+ * each. This is that wiring once, so a control gains a behaviour on every
20
+ * surface at the same time.
21
+ */
22
+ export interface UseDocumentControlsOptions {
23
+ /** The document's declared givens. Empty until it has loaded. */
24
+ specs: Given[];
25
+ /**
26
+ * Whether the document has loaded. Reports to the host are WITHHELD until
27
+ * it has: before then the declared set is empty, so a report would say "no
28
+ * values, and I manage nothing", which a host reasonably reads as "clear
29
+ * what you wrote" — and during an in-app move from one document to the next
30
+ * that window sits between the two, so the parameters it would clear belong
31
+ * to the document now arriving. A document that genuinely declares no givens
32
+ * still reports, because by then the empty set is the answer rather than
33
+ * the absence of one.
34
+ */
35
+ loaded: boolean;
36
+ /** Where the controls start, from the file. A URL beats them. */
37
+ startingValues?: Record<string, string>;
38
+ /** Control values from the host, typically its URL query parameters. */
39
+ params?: Record<string, string>;
40
+ /**
41
+ * Applied values, for a host that wants them in its URL, with every name
42
+ * this document manages — `givens` alone says which parameters to write but
43
+ * not which to remove.
44
+ */
45
+ onGivensChange?: (
46
+ givens: Record<string, string>,
47
+ managed: readonly string[],
48
+ ) => void;
49
+ /**
50
+ * Which document the edits belong to. Without it the edits are keyed by
51
+ * their starting VALUES alone, so two documents whose starting values
52
+ * coincide (the common case: both empty) look like one, and the one you came
53
+ * from keeps filtering the one you moved to. The version belongs in it too,
54
+ * so a swap between versions drops the edits made to the other.
55
+ */
56
+ documentKey: string;
57
+ /** False batches changes behind Apply. */
58
+ autorun: boolean;
59
+ /** Where `suggest` queries run: the document's own model. */
60
+ environmentName: string;
61
+ packageName: string;
62
+ modelPath: string | undefined;
63
+ versionId?: string;
64
+ /** How the document names itself in a refused-drill warning. */
65
+ documentName: string;
66
+ }
67
+
68
+ export interface DocumentControls extends UseGivensStateResult {
69
+ /** Declared type per given name: what this document can set and how a value is encoded. */
70
+ declaredTypes: ReadonlyMap<string, string | undefined>;
71
+ options: Map<string, string[]>;
72
+ optionsLoading: boolean;
73
+ optionsFailed: ReadonlySet<string>;
74
+ /** For `useDrill`: whether a `to=self` on this given can be honoured. */
75
+ canSelf: (given: string) => boolean;
76
+ /** For `useDrill`: set the given to the clicked value, encoded for its type. */
77
+ onSelf: (given: string, rawValue: unknown) => void;
78
+ /** Everything `GivensPanel` takes except its layout: spread it in. */
79
+ panel: Omit<GivensPanelProps, "layout" | "title">;
80
+ }
81
+
82
+ export function useDocumentControls({
83
+ specs,
84
+ loaded,
85
+ startingValues,
86
+ params,
87
+ onGivensChange,
88
+ documentKey,
89
+ autorun,
90
+ environmentName,
91
+ packageName,
92
+ modelPath,
93
+ versionId,
94
+ documentName,
95
+ }: UseDocumentControlsOptions): DocumentControls {
96
+ const declaredTypes = useMemo(
97
+ () =>
98
+ new Map(
99
+ specs
100
+ .filter((spec) => spec.name !== undefined)
101
+ .map((spec) => [spec.name as string, spec.type]),
102
+ ),
103
+ [specs],
104
+ );
105
+
106
+ const report = useCallback(
107
+ (next: Record<string, string>) => {
108
+ if (!loaded) return;
109
+ onGivensChange?.(next, Array.from(declaredTypes.keys()));
110
+ },
111
+ [loaded, onGivensChange, declaredTypes],
112
+ );
113
+
114
+ const state = useGivensState({
115
+ declaredTypes,
116
+ startingValues,
117
+ params,
118
+ // Withheld, not accepted and dropped: `useGivensState` records what it
119
+ // last reported BEFORE calling out, so a report the callback threw away
120
+ // would be remembered as delivered and never retried, leaving a parameter
121
+ // stranded in the host's URL. Passing undefined skips the report and
122
+ // leaves its record untouched.
123
+ onParamsChange: loaded ? report : undefined,
124
+ documentKey,
125
+ autorun,
126
+ });
127
+
128
+ const {
129
+ options,
130
+ isLoading: optionsLoading,
131
+ failed: optionsFailed,
132
+ } = useSuggestOptions(
133
+ environmentName,
134
+ packageName,
135
+ modelPath,
136
+ specs,
137
+ versionId,
138
+ // So a suggest over a gated or scoped source carries the givens it needs.
139
+ { values: state.applied, declaredTypes },
140
+ );
141
+
142
+ const { canSelf, onSelf } = useDrillSelf({
143
+ declaredTypes,
144
+ setGiven: state.setGiven,
145
+ documentName,
146
+ });
147
+
148
+ return {
149
+ ...state,
150
+ declaredTypes,
151
+ options,
152
+ optionsLoading,
153
+ optionsFailed,
154
+ canSelf,
155
+ onSelf,
156
+ panel: {
157
+ givens: specs,
158
+ values: state.draft,
159
+ onChange: state.setGiven,
160
+ onReset: state.reset,
161
+ options,
162
+ optionsLoading,
163
+ optionsFailed,
164
+ // Absent means autorun; only an explicit `false` batches behind Apply.
165
+ apply: autorun
166
+ ? undefined
167
+ : { onApply: state.apply, pending: state.pending },
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,82 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { QueryKey } from "@tanstack/react-query";
5
+ import { useServer } from "../components/ServerProvider";
6
+ import { CHART_RESULT_QUERY_OPTIONS } from "../utils/queryClient";
7
+ import { useQueryWithApiError } from "./useQueryWithApiError";
8
+
9
+ /**
10
+ * One query against one model, as every result surface asks for it.
11
+ *
12
+ * A dashboard tile, a model page's named query and an embedded `QueryResult`
13
+ * each ran a query through `executeQueryModel` with their own copy of the
14
+ * request, their own cache key and their own loading and error states — three
15
+ * spellings of one thing, and one of them (the model cell) had no error state
16
+ * at all. This is the request and the key; `ResultPanel` is the states.
17
+ */
18
+ export interface QueryRequestSpec {
19
+ environmentName: string;
20
+ packageName: string;
21
+ modelPath: string;
22
+ /** The package version the caller's URI named, when it named one. */
23
+ versionId?: string;
24
+ /** A named query on the model. */
25
+ queryName?: string;
26
+ /** A run expression: `run: source -> view`. */
27
+ query?: string;
28
+ sourceName?: string;
29
+ /** The applied control values this query reads, already encoded. */
30
+ givens?: Record<string, unknown>;
31
+ }
32
+
33
+ /**
34
+ * The cache key: every value the request is built from, in a fixed order, so
35
+ * the key cannot drift out of step with the request. A version that reached
36
+ * the request alone would leave two versions of one query on a single cache
37
+ * entry, each able to serve the other's result. `useQueryWithApiError` appends
38
+ * the server, so one key never spans two of them.
39
+ */
40
+ export function queryResultKey(spec: QueryRequestSpec): QueryKey {
41
+ return [
42
+ "queryResult",
43
+ spec.environmentName,
44
+ spec.packageName,
45
+ spec.versionId,
46
+ spec.modelPath,
47
+ spec.queryName,
48
+ spec.query,
49
+ spec.sourceName,
50
+ // Re-runs when the applied values change, which is the whole point of a
51
+ // control row.
52
+ JSON.stringify(spec.givens ?? {}),
53
+ ];
54
+ }
55
+
56
+ export function useQueryResult(
57
+ spec: QueryRequestSpec,
58
+ { enabled = true }: { enabled?: boolean } = {},
59
+ ) {
60
+ const { apiClients } = useServer();
61
+ return useQueryWithApiError({
62
+ queryKey: queryResultKey(spec),
63
+ queryFn: () =>
64
+ apiClients.models.executeQueryModel(
65
+ spec.environmentName,
66
+ spec.packageName,
67
+ spec.modelPath,
68
+ {
69
+ queryName: spec.queryName,
70
+ query: spec.query,
71
+ sourceName: spec.sourceName,
72
+ givens: spec.givens,
73
+ versionId: spec.versionId,
74
+ },
75
+ ),
76
+ enabled,
77
+ ...CHART_RESULT_QUERY_OPTIONS,
78
+ });
79
+ }
80
+
81
+ /** What a result surface holds while a query runs: hand it to `ResultPanel`. */
82
+ export type QueryResultState = ReturnType<typeof useQueryResult>;
package/src/index.ts CHANGED
@@ -7,6 +7,15 @@ export { useServer } from "./components/ServerProvider";
7
7
  export * from "./hooks";
8
8
  export { useRawQueryData } from "./hooks/useRawQueryData";
9
9
  export * from "./theme";
10
+ // The Console's write events, and the seam a host installs a sink into. Set
11
+ // once at boot: the dialogs that write are not mounted by the host, so there
12
+ // is nothing to hand a handler to.
13
+ export {
14
+ setConsoleEventHandler,
15
+ type ConsoleEvent,
16
+ type ConsoleEventHandler,
17
+ type ConsoleResource,
18
+ } from "./telemetry/consoleEvents";
10
19
  export * from "./utils/formatting";
11
20
  // How a package's own files are addressed. Exported because a host that renders
12
21
  // its own "this path is not a model" state has to point at the URL that does
@@ -0,0 +1,130 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { afterEach, describe, expect, it, mock } from "bun:test";
5
+ import {
6
+ reportConsoleEvent,
7
+ reporting,
8
+ setConsoleEventHandler,
9
+ type ConsoleEvent,
10
+ } from "./consoleEvents";
11
+
12
+ const event = (over: Partial<ConsoleEvent> = {}): ConsoleEvent => ({
13
+ type: "console.mutation",
14
+ resource: "package",
15
+ action: "delete",
16
+ ok: true,
17
+ durationMs: 12,
18
+ ...over,
19
+ });
20
+
21
+ describe("console event sink", () => {
22
+ afterEach(() => setConsoleEventHandler(undefined));
23
+
24
+ it("delivers to the installed handler", () => {
25
+ const sink = mock((_e: ConsoleEvent) => {});
26
+ setConsoleEventHandler(sink);
27
+ reportConsoleEvent(event());
28
+ expect(sink).toHaveBeenCalledTimes(1);
29
+ expect(sink.mock.calls[0][0]).toMatchObject({
30
+ resource: "package",
31
+ action: "delete",
32
+ ok: true,
33
+ });
34
+ });
35
+
36
+ it("is a no-op when no host installed one", () => {
37
+ // An SDK embedded in someone else's app reports to nobody, and that has
38
+ // to be silent rather than a crash on every write.
39
+ expect(() => reportConsoleEvent(event())).not.toThrow();
40
+ });
41
+
42
+ it("replaces the handler rather than fanning out", () => {
43
+ const first = mock((_e: ConsoleEvent) => {});
44
+ const second = mock((_e: ConsoleEvent) => {});
45
+ setConsoleEventHandler(first);
46
+ setConsoleEventHandler(second);
47
+ reportConsoleEvent(event());
48
+ expect(first).not.toHaveBeenCalled();
49
+ expect(second).toHaveBeenCalledTimes(1);
50
+ });
51
+
52
+ it("swallows a sink that throws, so telemetry cannot break a write", () => {
53
+ // This is called from the success path of a delete. A sink bug that
54
+ // surfaced as a failed delete would be worse than the line it lost.
55
+ setConsoleEventHandler(() => {
56
+ throw new Error("the sink is broken");
57
+ });
58
+ expect(() => reportConsoleEvent(event())).not.toThrow();
59
+ });
60
+
61
+ it("carries the reason on a failure", () => {
62
+ const sink = mock((_e: ConsoleEvent) => {});
63
+ setConsoleEventHandler(sink);
64
+ reportConsoleEvent(event({ ok: false, reason: "Package is in use" }));
65
+ expect(sink.mock.calls[0][0]).toMatchObject({
66
+ ok: false,
67
+ reason: "Package is in use",
68
+ });
69
+ });
70
+ });
71
+
72
+ /**
73
+ * The wrapper both shapes of Console write go through. Its contract is that
74
+ * nothing downstream can tell it is there: same value out, same rejection out,
75
+ * and an event either way.
76
+ */
77
+ describe("reporting()", () => {
78
+ afterEach(() => setConsoleEventHandler(undefined));
79
+
80
+ it("returns the write's own value and reports a success", async () => {
81
+ const seen: ConsoleEvent[] = [];
82
+ setConsoleEventHandler((e) => seen.push(e));
83
+ const write = reporting("connection", "create", async (name: string) => ({
84
+ created: name,
85
+ }));
86
+
87
+ expect(await write("bigquery")).toEqual({ created: "bigquery" });
88
+ expect(seen).toHaveLength(1);
89
+ expect(seen[0]).toMatchObject({
90
+ resource: "connection",
91
+ action: "create",
92
+ ok: true,
93
+ });
94
+ expect(typeof seen[0].durationMs).toBe("number");
95
+ });
96
+
97
+ it("re-throws the write's own error, unchanged, and reports the failure", async () => {
98
+ const seen: ConsoleEvent[] = [];
99
+ setConsoleEventHandler((e) => seen.push(e));
100
+ const boom = new Error("Connection is in use");
101
+ // Takes a variable like the real delete does, so the call below is the
102
+ // shape a caller actually uses.
103
+ const write = reporting("connection", "delete", async (_name: string) => {
104
+ throw boom;
105
+ });
106
+
107
+ // The SAME error object: a caller that matches on it must still match.
108
+ await expect(write("bigquery")).rejects.toBe(boom);
109
+ expect(seen).toHaveLength(1);
110
+ expect(seen[0]).toMatchObject({
111
+ ok: false,
112
+ reason: "Connection is in use",
113
+ });
114
+ });
115
+
116
+ it("reports a rejection that is not an Error without inventing a message", async () => {
117
+ const seen: ConsoleEvent[] = [];
118
+ setConsoleEventHandler((e) => seen.push(e));
119
+ const write = reporting("package", "update", async (_name: string) => {
120
+ throw "a bare string";
121
+ });
122
+ await expect(write("storefront")).rejects.toBe("a bare string");
123
+ expect(seen[0].reason).toBe("An unknown error occurred");
124
+ });
125
+
126
+ it("is transparent when no sink is installed", async () => {
127
+ const write = reporting("scope", "update", async (n: number) => n * 2);
128
+ expect(await write(21)).toBe(42);
129
+ });
130
+ });
@@ -0,0 +1,124 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * What the Console reports about the things it CHANGES.
6
+ *
7
+ * The dashboard surfaces already report themselves through `DashboardEvent`,
8
+ * which the host wires per surface because each one is mounted with a
9
+ * dashboard's name. The Console's writes are not like that: create, edit and
10
+ * delete for environments, packages, connections and materializations happen
11
+ * inside dialogs the host never mounts directly, and there is no seam to pass
12
+ * a handler down through. So the sink is set once, by the host, at boot.
13
+ *
14
+ * Until now those writes reported to a six-second snackbar and nothing else.
15
+ * There was no record that a package had been deleted, or that a delete had
16
+ * failed — the operations whose outcome someone is most likely to be asked
17
+ * about afterwards.
18
+ */
19
+
20
+ /** The thing being written. */
21
+ export type ConsoleResource =
22
+ | "environment"
23
+ | "package"
24
+ | "connection"
25
+ | "materialization"
26
+ | "schedule"
27
+ | "scope";
28
+
29
+ export type ConsoleEvent = {
30
+ type: "console.mutation";
31
+ resource: ConsoleResource;
32
+ /** What was done to it. */
33
+ action: "create" | "update" | "delete";
34
+ ok: boolean;
35
+ durationMs: number;
36
+ /** Present when `ok` is false: the message the operator was shown. */
37
+ reason?: string;
38
+ };
39
+
40
+ export type ConsoleEventHandler = (event: ConsoleEvent) => void;
41
+
42
+ let handler: ConsoleEventHandler | undefined;
43
+
44
+ /**
45
+ * Install the host's sink. Called once at boot; called again, it replaces.
46
+ * Passing `undefined` removes it, which is what a test wants between cases.
47
+ */
48
+ export function setConsoleEventHandler(
49
+ next: ConsoleEventHandler | undefined,
50
+ ): void {
51
+ handler = next;
52
+ }
53
+
54
+ /**
55
+ * Report one event, if anyone is listening.
56
+ *
57
+ * Never throws, and never lets a sink's own failure reach the caller: this is
58
+ * called from the success and error paths of a write, and a telemetry bug that
59
+ * turned a successful delete into a visible error would be worse than the
60
+ * missing line it is reporting.
61
+ */
62
+ export function reportConsoleEvent(event: ConsoleEvent): void {
63
+ if (!handler) return;
64
+ try {
65
+ handler(event);
66
+ } catch {
67
+ // A sink that throws is the sink's problem, not the write's.
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Wrap a mutation's function so it reports itself.
73
+ *
74
+ * The write that reports is the `mutationFn`, not the hook around it, because
75
+ * the Console has two shapes of write and only one of them fits a shared hook.
76
+ * The CRUD dialogs each own a mutation, a snackbar and a dialog to close, and
77
+ * {@link useCrudMutation} holds all three. Connections and Materializations do
78
+ * not: they `mutateAsync` from a caller that awaits the promise, and share one
79
+ * snackbar across several mutations at the component level. Forcing those onto
80
+ * the dialog hook would mean giving them a snackbar each and a dialog to close
81
+ * that they do not have.
82
+ *
83
+ * Wrapping the function instead fits both, and reports the same event either
84
+ * way: it times what the caller actually waits on, it sees the rejection
85
+ * before any handler has turned it into a message, and it re-throws unchanged
86
+ * so nothing downstream can tell it is there.
87
+ */
88
+ export function reporting<F extends (variables: never) => Promise<unknown>>(
89
+ resource: ConsoleResource,
90
+ action: ConsoleEvent["action"],
91
+ mutationFn: F,
92
+ ): F {
93
+ // Returns the SAME function type it was given, so the mutation hook infers
94
+ // its variables from the wrapped function exactly as it did from the bare
95
+ // one. Re-declaring the signature with fresh type parameters broke that
96
+ // inference and collapsed the variables type to `void`.
97
+ return (async (variables: Parameters<F>[0]) => {
98
+ const startedAt = Date.now();
99
+ try {
100
+ const result = await mutationFn(variables);
101
+ reportConsoleEvent({
102
+ type: "console.mutation",
103
+ resource,
104
+ action,
105
+ ok: true,
106
+ durationMs: Date.now() - startedAt,
107
+ });
108
+ return result;
109
+ } catch (error) {
110
+ reportConsoleEvent({
111
+ type: "console.mutation",
112
+ resource,
113
+ action,
114
+ ok: false,
115
+ durationMs: Date.now() - startedAt,
116
+ reason:
117
+ error instanceof Error
118
+ ? error.message
119
+ : "An unknown error occurred",
120
+ });
121
+ throw error;
122
+ }
123
+ }) as F;
124
+ }