@malloy-publisher/sdk 0.12.0 → 0.12.2

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 (214) hide show
  1. package/README.md +79 -6
  2. package/dist/{RenderedResult-SgDlxzs9.cjs.js → RenderedResult-Cgw4iqev.cjs.js} +1 -1
  3. package/dist/{RenderedResult-D8bCgThO.es.js → RenderedResult-DEjFM1DL.es.js} +2 -2
  4. package/dist/ServerProvider-BRQl_cBo.cjs.js +1 -0
  5. package/dist/{ServerProvider-DBw-thY0.es.js → ServerProvider-RnliA2Ao.es.js} +1084 -723
  6. package/dist/builder/index.cjs.js +1 -1
  7. package/dist/builder/index.es.js +3 -3
  8. package/dist/client/api.d.ts +754 -41
  9. package/dist/client/index.cjs.js +1 -1
  10. package/dist/client/index.es.js +120 -110
  11. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +16 -1
  12. package/dist/components/Model/ExplorerPage.d.ts +9 -0
  13. package/dist/components/Model/Model.d.ts +27 -11
  14. package/dist/components/ModelViewer/AccessChips.d.ts +34 -0
  15. package/dist/components/ModelViewer/EmptyRow.d.ts +23 -0
  16. package/dist/components/ModelViewer/Facts.d.ts +15 -0
  17. package/dist/components/ModelViewer/FieldGroup.d.ts +31 -0
  18. package/dist/components/ModelViewer/FieldRow.d.ts +69 -0
  19. package/dist/components/ModelViewer/GivenFacts.d.ts +21 -0
  20. package/dist/components/ModelViewer/HeaderBar.d.ts +75 -0
  21. package/dist/components/ModelViewer/InlineDoc.d.ts +13 -0
  22. package/dist/components/ModelViewer/ModelGivensSection.d.ts +32 -0
  23. package/dist/components/ModelViewer/ModelSection.d.ts +21 -0
  24. package/dist/components/ModelViewer/ModelViewer.d.ts +91 -0
  25. package/dist/components/ModelViewer/QueriesGroup.d.ts +15 -0
  26. package/dist/components/ModelViewer/RowGlyph.d.ts +27 -0
  27. package/dist/components/ModelViewer/RunResult.d.ts +46 -0
  28. package/dist/components/ModelViewer/SampleValues.d.ts +20 -0
  29. package/dist/components/ModelViewer/SchemaJoin.d.ts +51 -0
  30. package/dist/components/ModelViewer/SchemaView.d.ts +52 -0
  31. package/dist/components/ModelViewer/SegmentIcons.d.ts +70 -0
  32. package/dist/components/ModelViewer/SourcesDropdown.d.ts +53 -0
  33. package/dist/components/ModelViewer/SourcesNav.d.ts +25 -0
  34. package/dist/components/ModelViewer/StatusPill.d.ts +56 -0
  35. package/dist/components/ModelViewer/ValueChip.d.ts +17 -0
  36. package/dist/components/ModelViewer/ViewRow.d.ts +36 -0
  37. package/dist/components/ModelViewer/clickableBox.d.ts +29 -0
  38. package/dist/components/ModelViewer/codeDisplay.d.ts +44 -0
  39. package/dist/components/ModelViewer/docAnnotations.d.ts +90 -0
  40. package/dist/components/ModelViewer/explorerModel.d.ts +12 -0
  41. package/dist/components/ModelViewer/extensions.d.ts +94 -0
  42. package/dist/components/ModelViewer/fieldCode.d.ts +74 -0
  43. package/dist/components/ModelViewer/fieldEntities.d.ts +45 -0
  44. package/dist/components/ModelViewer/fieldExpansion.d.ts +41 -0
  45. package/dist/components/ModelViewer/givenUsage.d.ts +71 -0
  46. package/dist/components/ModelViewer/headerCard.d.ts +31 -0
  47. package/dist/components/ModelViewer/httpStatus.d.ts +4 -0
  48. package/dist/components/ModelViewer/icons.d.ts +31 -0
  49. package/dist/components/ModelViewer/index.d.ts +9 -0
  50. package/dist/components/ModelViewer/joinAccess.d.ts +52 -0
  51. package/dist/components/ModelViewer/malloyRunText.d.ts +22 -0
  52. package/dist/components/ModelViewer/malloyText.d.ts +21 -0
  53. package/dist/components/ModelViewer/modelGivens.d.ts +61 -0
  54. package/dist/components/ModelViewer/modelGivensContext.d.ts +9 -0
  55. package/dist/components/ModelViewer/modelHeaderPresentation.d.ts +28 -0
  56. package/dist/components/ModelViewer/modelTextDeclarations.d.ts +32 -0
  57. package/dist/components/ModelViewer/modelTextParse.d.ts +27 -0
  58. package/dist/components/ModelViewer/namedQueryCode.d.ts +12 -0
  59. package/dist/components/ModelViewer/offSurface.d.ts +54 -0
  60. package/dist/components/ModelViewer/rowLayers.d.ts +30 -0
  61. package/dist/components/ModelViewer/runGate.d.ts +49 -0
  62. package/dist/components/ModelViewer/schemaModel.d.ts +109 -0
  63. package/dist/components/ModelViewer/sectionOpenCommand.d.ts +45 -0
  64. package/dist/components/ModelViewer/sourceAccess.d.ts +67 -0
  65. package/dist/components/ModelViewer/sourceLineage.d.ts +14 -0
  66. package/dist/components/ModelViewer/sourcePicker.d.ts +66 -0
  67. package/dist/components/ModelViewer/surface.d.ts +47 -0
  68. package/dist/components/ModelViewer/text.d.ts +6 -0
  69. package/dist/components/ModelViewer/theme.d.ts +63 -0
  70. package/dist/components/ModelViewer/tokens.d.ts +52 -0
  71. package/dist/components/ModelViewer/ui.d.ts +48 -0
  72. package/dist/components/ModelViewer/useDimensionSamples.d.ts +76 -0
  73. package/dist/components/ModelViewer/useModelSources.d.ts +92 -0
  74. package/dist/components/ModelViewer/useRunQuery.d.ts +115 -0
  75. package/dist/components/ReportBuilder/loadMalloy.d.ts +4 -0
  76. package/dist/components/ServerProvider.d.ts +17 -2
  77. package/dist/components/filter/utils.d.ts +1 -1
  78. package/dist/components/given/GivenInput.d.ts +7 -1
  79. package/dist/components/given/GivensPanel.d.ts +3 -1
  80. package/dist/components/given/filterSummary.d.ts +6 -0
  81. package/dist/components/given/useGivenUrlParams.d.ts +11 -0
  82. package/dist/components/index.d.ts +2 -1
  83. package/dist/components/modelPage.d.ts +36 -0
  84. package/dist/hooks/useDimensionalFilterRangeData.d.ts +9 -0
  85. package/dist/hooks/useSuggestOptions.d.ts +26 -2
  86. package/dist/index.cjs.js +47 -19
  87. package/dist/index.es.js +14137 -9697
  88. package/dist/useCompiledDocument-D88_2cGS.cjs.js +143 -0
  89. package/dist/{useCompiledDocument-CXMPtJkJ.es.js → useCompiledDocument-Dmm6xkom.es.js} +6975 -6893
  90. package/dist/utils/filterCondition.d.ts +14 -0
  91. package/dist/utils/malloyLiteral.d.ts +20 -1
  92. package/package.json +2 -2
  93. package/src/components/Materializations/MaterializationDetailDialog.tsx +33 -7
  94. package/src/components/Materializations/Materializations.tsx +47 -4
  95. package/src/components/Materializations/Materializations.versions.spec.tsx +140 -1
  96. package/src/components/Model/ExplorerPage.tsx +269 -0
  97. package/src/components/Model/Model.tsx +66 -250
  98. package/src/components/Model/ModelExplorer.spec.tsx +64 -1
  99. package/src/components/ModelViewer/AccessChips.tsx +149 -0
  100. package/src/components/ModelViewer/EmptyRow.tsx +71 -0
  101. package/src/components/ModelViewer/Facts.tsx +46 -0
  102. package/src/components/ModelViewer/FieldGroup.tsx +137 -0
  103. package/src/components/ModelViewer/FieldRow.tsx +566 -0
  104. package/src/components/ModelViewer/GivenFacts.tsx +89 -0
  105. package/src/components/ModelViewer/HeaderBar.tsx +362 -0
  106. package/src/components/ModelViewer/InlineDoc.tsx +50 -0
  107. package/src/components/ModelViewer/ModelGivensSection.tsx +142 -0
  108. package/src/components/ModelViewer/ModelSection.tsx +98 -0
  109. package/src/components/ModelViewer/ModelViewer.spec.tsx +937 -0
  110. package/src/components/ModelViewer/ModelViewer.tsx +777 -0
  111. package/src/components/ModelViewer/QueriesGroup.tsx +107 -0
  112. package/src/components/ModelViewer/RowGlyph.tsx +138 -0
  113. package/src/components/ModelViewer/RunResult.tsx +298 -0
  114. package/src/components/ModelViewer/SampleValues.tsx +97 -0
  115. package/src/components/ModelViewer/SchemaJoin.tsx +258 -0
  116. package/src/components/ModelViewer/SchemaView.tsx +222 -0
  117. package/src/components/ModelViewer/SegmentIcons.tsx +129 -0
  118. package/src/components/ModelViewer/SourcesDropdown.tsx +265 -0
  119. package/src/components/ModelViewer/SourcesNav.tsx +75 -0
  120. package/src/components/ModelViewer/StatusPill.tsx +145 -0
  121. package/src/components/ModelViewer/ValueChip.tsx +39 -0
  122. package/src/components/ModelViewer/ViewRow.tsx +274 -0
  123. package/src/components/ModelViewer/clickableBox.ts +59 -0
  124. package/src/components/ModelViewer/codeDisplay.spec.ts +176 -0
  125. package/src/components/ModelViewer/codeDisplay.ts +118 -0
  126. package/src/components/ModelViewer/docAnnotations.spec.ts +181 -0
  127. package/src/components/ModelViewer/docAnnotations.ts +244 -0
  128. package/src/components/ModelViewer/docAnnotations.typeDetail.spec.ts +114 -0
  129. package/src/components/ModelViewer/explorerModel.spec.ts +43 -0
  130. package/src/components/ModelViewer/explorerModel.ts +31 -0
  131. package/src/components/ModelViewer/extensions.tsx +112 -0
  132. package/src/components/ModelViewer/fieldCode.spec.ts +168 -0
  133. package/src/components/ModelViewer/fieldCode.ts +118 -0
  134. package/src/components/ModelViewer/fieldEntities.ts +63 -0
  135. package/src/components/ModelViewer/fieldExpansion.spec.ts +116 -0
  136. package/src/components/ModelViewer/fieldExpansion.ts +95 -0
  137. package/src/components/ModelViewer/givenUsage.spec.ts +304 -0
  138. package/src/components/ModelViewer/givenUsage.ts +325 -0
  139. package/src/components/ModelViewer/headerCard.tsx +102 -0
  140. package/src/components/ModelViewer/httpStatus.ts +15 -0
  141. package/src/components/ModelViewer/icons.tsx +67 -0
  142. package/src/components/ModelViewer/index.ts +26 -0
  143. package/src/components/ModelViewer/joinAccess.spec.ts +95 -0
  144. package/src/components/ModelViewer/joinAccess.ts +54 -0
  145. package/src/components/ModelViewer/malloyRunText.spec.ts +48 -0
  146. package/src/components/ModelViewer/malloyRunText.ts +51 -0
  147. package/src/components/ModelViewer/malloyText.spec.ts +47 -0
  148. package/src/components/ModelViewer/malloyText.ts +77 -0
  149. package/src/components/ModelViewer/modelGivens.ts +228 -0
  150. package/src/components/ModelViewer/modelGivensContext.ts +13 -0
  151. package/src/components/ModelViewer/modelHeaderPresentation.spec.ts +31 -0
  152. package/src/components/ModelViewer/modelHeaderPresentation.ts +41 -0
  153. package/src/components/ModelViewer/modelTextDeclarations.spec.ts +336 -0
  154. package/src/components/ModelViewer/modelTextDeclarations.ts +228 -0
  155. package/src/components/ModelViewer/modelTextParse.ts +112 -0
  156. package/src/components/ModelViewer/namedQueryCode.spec.ts +58 -0
  157. package/src/components/ModelViewer/namedQueryCode.ts +26 -0
  158. package/src/components/ModelViewer/offSurface.tsx +124 -0
  159. package/src/components/ModelViewer/rowLayers.tsx +104 -0
  160. package/src/components/ModelViewer/runGate.spec.ts +219 -0
  161. package/src/components/ModelViewer/runGate.ts +145 -0
  162. package/src/components/ModelViewer/schemaModel.defaultSource.spec.ts +126 -0
  163. package/src/components/ModelViewer/schemaModel.queries.spec.ts +37 -0
  164. package/src/components/ModelViewer/schemaModel.ts +300 -0
  165. package/src/components/ModelViewer/sectionOpenCommand.tsx +125 -0
  166. package/src/components/ModelViewer/sourceAccess.spec.ts +130 -0
  167. package/src/components/ModelViewer/sourceAccess.ts +194 -0
  168. package/src/components/ModelViewer/sourceLineage.spec.ts +73 -0
  169. package/src/components/ModelViewer/sourceLineage.ts +38 -0
  170. package/src/components/ModelViewer/sourcePicker.spec.ts +294 -0
  171. package/src/components/ModelViewer/sourcePicker.ts +162 -0
  172. package/src/components/ModelViewer/surface.ts +51 -0
  173. package/src/components/ModelViewer/text.tsx +33 -0
  174. package/src/components/ModelViewer/theme.spec.ts +38 -0
  175. package/src/components/ModelViewer/theme.ts +58 -0
  176. package/src/components/ModelViewer/tokens.ts +87 -0
  177. package/src/components/ModelViewer/ui.tsx +201 -0
  178. package/src/components/ModelViewer/useDimensionSamples.spec.tsx +139 -0
  179. package/src/components/ModelViewer/useDimensionSamples.ts +220 -0
  180. package/src/components/ModelViewer/useModelSources.spec.ts +110 -0
  181. package/src/components/ModelViewer/useModelSources.ts +238 -0
  182. package/src/components/ModelViewer/useRunQuery.spec.ts +50 -0
  183. package/src/components/ModelViewer/useRunQuery.ts +223 -0
  184. package/src/components/Package/Package.agents.spec.tsx +5 -4
  185. package/src/components/Package/Package.tsx +8 -1
  186. package/src/components/ReportBuilder/emptyStart.spec.ts +8 -0
  187. package/src/components/ReportBuilder/loadMalloy.ts +8 -1
  188. package/src/components/ServerProvider.tsx +29 -3
  189. package/src/components/filter/utils.ts +4 -60
  190. package/src/components/given/FilterButton.tsx +4 -1
  191. package/src/components/given/GivenInput.tsx +8 -0
  192. package/src/components/given/GivensPanel.tsx +6 -1
  193. package/src/components/given/filterSummary.spec.ts +31 -1
  194. package/src/components/given/filterSummary.ts +41 -19
  195. package/src/components/given/useGivenUrlParams.spec.tsx +32 -0
  196. package/src/components/given/useGivenUrlParams.ts +49 -14
  197. package/src/components/index.ts +6 -1
  198. package/src/components/legacy/malloynb/Notebook.spec.tsx +38 -4
  199. package/src/components/legacy/malloynb/NotebookCell.tsx +8 -2
  200. package/src/components/modelPage.spec.ts +79 -0
  201. package/src/components/modelPage.ts +48 -0
  202. package/src/hooks/useDimensionFilters.ts +3 -58
  203. package/src/hooks/useDimensionFiltersQuery.ts +3 -58
  204. package/src/hooks/useDimensionalFilterRangeData.spec.ts +57 -0
  205. package/src/hooks/useDimensionalFilterRangeData.ts +8 -63
  206. package/src/hooks/useSuggestOptions.dom.spec.ts +54 -1
  207. package/src/hooks/useSuggestOptions.spec.ts +71 -0
  208. package/src/hooks/useSuggestOptions.ts +102 -12
  209. package/src/utils/filterCondition.spec.ts +87 -0
  210. package/src/utils/filterCondition.ts +66 -0
  211. package/src/utils/malloyLiteral.spec.ts +53 -1
  212. package/src/utils/malloyLiteral.ts +47 -12
  213. package/dist/ServerProvider-BHfg1Ed6.cjs.js +0 -1
  214. package/dist/useCompiledDocument-D7X_K6YU.cjs.js +0 -142
@@ -0,0 +1,238 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useQuery } from "@tanstack/react-query";
5
+ import type * as Malloy from "@malloydata/malloy-interfaces";
6
+ import { extractCompiledModelGivens, type GivenInfo } from "./modelGivens";
7
+ import { extractSourceAccess, type SourceAccess } from "./sourceAccess";
8
+ import { getModelDocString } from "./docAnnotations";
9
+ import { useServer } from "../ServerProvider";
10
+
11
+ /** A model's named queries, as the publisher lists them on `CompiledModel.queries`. */
12
+ export interface ModelNamedQuery {
13
+ name?: string;
14
+ sourceName?: string;
15
+ annotations?: string[];
16
+ }
17
+
18
+ const EMPTY_SOURCES: Malloy.SourceInfo[] = [];
19
+ const EMPTY_QUERIES: ModelNamedQuery[] = [];
20
+ const EMPTY_GIVENS: GivenInfo[] = [];
21
+ const EMPTY_ACCESS: ReadonlyMap<string, SourceAccess> = new Map();
22
+
23
+ /** What the viewer keeps of a compiled model. */
24
+ export interface CompiledModelData {
25
+ sourceInfos: Malloy.SourceInfo[];
26
+ queries: ModelNamedQuery[];
27
+ /** The model file's Malloy text. Newer publishers return it on the compiled
28
+ * model (`sourceText`); older ones don't, and the SDK's type predates it,
29
+ * so it is read structurally and stays undefined when absent — the code
30
+ * view says so rather than showing an empty file. A SHAPE check, not a
31
+ * cast: through the router a declared-but-unsent field arrives as `null`,
32
+ * which must read as absent too. */
33
+ sourceText?: string;
34
+ /** The model's declared givens (shape-checked by extractCompiledModelGivens),
35
+ * so a run can say which defaults it used, or that it can't run without a
36
+ * value. */
37
+ givens: GivenInfo[];
38
+ /** Source name → its `#(authorize)` / `#(access_filter)` declarations (the
39
+ * compiled model's `sources[]`), for every source that declares either. */
40
+ access: ReadonlyMap<string, SourceAccess>;
41
+ /** The model file's own description (`##(doc)` / `##"`), from `modelInfo`. */
42
+ modelDoc?: string;
43
+ /** The model imports other files: an import-only model's page says why it
44
+ * is empty rather than reading as broken. */
45
+ hasImports: boolean;
46
+ }
47
+
48
+ /**
49
+ * Whether the compiled model imports other files. `modelDef` is returned by the
50
+ * server but absent from the typed `CompiledModel` (an internal compiler blob),
51
+ * so it is read by shape.
52
+ */
53
+ function importsOf(data: unknown): boolean {
54
+ const modelDef = (data as { modelDef?: unknown }).modelDef;
55
+ if (typeof modelDef !== "string") return false;
56
+ try {
57
+ const def = JSON.parse(modelDef) as { imports?: unknown[] };
58
+ return Array.isArray(def.imports) && def.imports.length > 0;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The model's own doc: from the compiled model's `modelInfo` (a JSON string of
66
+ * Malloy's `ModelInfo`) where it carries the model's annotations, else from the
67
+ * model file's text. The publisher's `modelInfo` leaves `annotations` out today,
68
+ * and a `##` line is a model annotation wherever it sits at the top level, so
69
+ * the text answers the same question. Undefined when neither has one.
70
+ */
71
+ export function modelDocOf(
72
+ modelInfo: unknown,
73
+ sourceText: string | undefined,
74
+ ): string | undefined {
75
+ if (typeof modelInfo === "string") {
76
+ try {
77
+ const doc = getModelDocString(
78
+ (JSON.parse(modelInfo) as Malloy.ModelInfo).annotations,
79
+ );
80
+ if (doc) return doc;
81
+ } catch {
82
+ // Unreadable: fall through to the text.
83
+ }
84
+ }
85
+ if (!sourceText) return undefined;
86
+ const lines = sourceText
87
+ .split("\n")
88
+ .filter((line) => /^##(\(doc\)|")/.test(line.trim()))
89
+ .map((value) => ({ value }));
90
+ return getModelDocString(lines);
91
+ }
92
+
93
+ /**
94
+ * The one shaping of a compiled-model response, for both hooks below: they
95
+ * share a cache key, so they must store one shape, and a function is a
96
+ * guarantee where a comment was not.
97
+ */
98
+ export async function fetchCompiledModel(
99
+ apiClients: ReturnType<typeof useServer>["apiClients"],
100
+ projectName: string,
101
+ packageName: string,
102
+ modelPath: string,
103
+ versionId?: string,
104
+ includeHiddenFilesAndSources?: boolean,
105
+ ): Promise<CompiledModelData> {
106
+ const response = await apiClients.models.getModel(
107
+ projectName,
108
+ packageName,
109
+ modelPath,
110
+ versionId,
111
+ includeHiddenFilesAndSources,
112
+ );
113
+ const sourceText = readSourceText(response.data);
114
+ return {
115
+ sourceInfos: (response.data.sourceInfos ?? []).map(
116
+ (s) => JSON.parse(s) as Malloy.SourceInfo,
117
+ ),
118
+ queries: (response.data.queries ?? []) as ModelNamedQuery[],
119
+ sourceText,
120
+ givens: extractCompiledModelGivens(modelPath, response.data),
121
+ access: extractSourceAccess(response.data),
122
+ modelDoc: modelDocOf(response.data.modelInfo, sourceText),
123
+ hasImports: importsOf(response.data),
124
+ };
125
+ }
126
+
127
+ /** `sourceText` off a compiled-model response, by shape (see {@link CompiledModelData}). */
128
+ function readSourceText(data: unknown): string | undefined {
129
+ const text = (data as { sourceText?: unknown }).sourceText;
130
+ return typeof text === "string" ? text : undefined;
131
+ }
132
+
133
+ /**
134
+ * The viewer's cache key for a compiled model, for a host that reads the same
135
+ * model (and shares the one compile), or refreshes it after a republish.
136
+ * A hidden file's read is its own entry: the curated read's 404 must never be
137
+ * served in its place, nor its text to a reader who can't edit the package.
138
+ */
139
+ export function modelQueryKey(
140
+ projectName: string,
141
+ packageName: string,
142
+ modelPath: string,
143
+ versionId?: string,
144
+ includeHiddenFilesAndSources = false,
145
+ ): readonly unknown[] {
146
+ return [
147
+ "model-viewer-sources",
148
+ projectName,
149
+ packageName,
150
+ modelPath,
151
+ versionId ?? "",
152
+ ...(includeHiddenFilesAndSources ? ["off-surface"] : []),
153
+ ];
154
+ }
155
+
156
+ /**
157
+ * A compiled model's query: its one cache key and fetch, for every reader of a
158
+ * compiled model. Compiling is server work, so
159
+ * a pinned version — which can't change — is kept for the page's life; `latest`
160
+ * goes stale like any other read.
161
+ */
162
+ export function compiledModelQuery(
163
+ apiClients: ReturnType<typeof useServer>["apiClients"],
164
+ projectName: string,
165
+ packageName: string,
166
+ modelPath: string,
167
+ versionId?: string,
168
+ includeHiddenFilesAndSources = false,
169
+ ) {
170
+ return {
171
+ queryKey: modelQueryKey(
172
+ projectName,
173
+ packageName,
174
+ modelPath,
175
+ versionId,
176
+ includeHiddenFilesAndSources,
177
+ ),
178
+ queryFn: () =>
179
+ fetchCompiledModel(
180
+ apiClients,
181
+ projectName,
182
+ packageName,
183
+ modelPath,
184
+ versionId,
185
+ includeHiddenFilesAndSources,
186
+ ),
187
+ ...(versionId && versionId !== "latest" ? { staleTime: Infinity } : {}),
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Fetch the compiled sources for a published model and parse them into
193
+ * `Malloy.SourceInfo` objects (`sourceInfos` is an array of JSON strings). The same
194
+ * response lists the model's named queries, so they ride along rather than
195
+ * costing a second fetch of the compiled model.
196
+ */
197
+ export function useModelSources(
198
+ projectName: string,
199
+ packageName: string,
200
+ modelPath: string,
201
+ versionId?: string,
202
+ /** False holds the read, e.g. until the page has resolved `latest` to the
203
+ * version it will read everything at. */
204
+ enabled = true,
205
+ /** Read a file the package's `index.malloy` hides, for a reader who can
206
+ * edit the package; anyone else is refused. */
207
+ includeHiddenFilesAndSources = false,
208
+ ) {
209
+ const { apiClients } = useServer();
210
+
211
+ const query = useQuery({
212
+ ...compiledModelQuery(
213
+ apiClients,
214
+ projectName,
215
+ packageName,
216
+ modelPath,
217
+ versionId,
218
+ includeHiddenFilesAndSources,
219
+ ),
220
+ enabled: enabled && Boolean(projectName && packageName && modelPath),
221
+ });
222
+
223
+ return {
224
+ sources: query.data?.sourceInfos ?? EMPTY_SOURCES,
225
+ queries: query.data?.queries ?? EMPTY_QUERIES,
226
+ sourceText: query.data?.sourceText,
227
+ givens: query.data?.givens ?? EMPTY_GIVENS,
228
+ access: query.data?.access ?? EMPTY_ACCESS,
229
+ modelDoc: query.data?.modelDoc,
230
+ hasImports: query.data?.hasImports ?? false,
231
+ isLoading: query.isLoading,
232
+ isError: query.isError,
233
+ error: query.error as Error | null,
234
+ // Exposed so the model pane's failure can offer a Retry: it replaces the
235
+ // whole surface, which guide §6a says owns its error and its way out.
236
+ refetch: query.refetch,
237
+ };
238
+ }
@@ -0,0 +1,50 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it, mock } from "bun:test";
5
+ import type { ApiClients } from "../ServerProvider";
6
+ import { runQueryOptions } from "./useRunQuery";
7
+
8
+ // A run of a file the package's index.malloy hides asks with includeHiddenFilesAndSources, and
9
+ // is cached apart from the curated run of the same file and query, whose 404 must
10
+ // never be served in its place.
11
+ describe("runQueryOptions", () => {
12
+ const call = (includeHiddenFilesAndSources?: boolean) => {
13
+ const executeQueryModel = mock((..._args: unknown[]) =>
14
+ Promise.resolve({ data: {} }),
15
+ );
16
+ const apiClients = {
17
+ models: { executeQueryModel },
18
+ } as unknown as ApiClients;
19
+ const options = runQueryOptions({
20
+ server: "http://demo.data.ms2.localhost/api/v0",
21
+ apiClients,
22
+ run: {
23
+ projectName: "env",
24
+ packageName: "pkg",
25
+ versionId: "1.0.0",
26
+ includeHiddenFilesAndSources,
27
+ },
28
+ modelPath: "customers.malloy",
29
+ query: "run: customers -> { select: * }",
30
+ });
31
+ return { options, executeQueryModel };
32
+ };
33
+
34
+ it("asks with includeHiddenFilesAndSources for a hidden file, under its own cache key", async () => {
35
+ const { options, executeQueryModel } = call(true);
36
+ await options.queryFn({});
37
+ expect(executeQueryModel.mock.calls[0][4]).toBe(true);
38
+ expect(executeQueryModel.mock.calls[0][5]).toEqual({ signal: undefined });
39
+ expect(options.queryKey.at(-1)).toBe("off-surface");
40
+ });
41
+
42
+ it("sends nothing extra, and keeps the shared key, for any other run", async () => {
43
+ const { options, executeQueryModel } = call(undefined);
44
+ await options.queryFn({});
45
+ expect(executeQueryModel.mock.calls[0][4]).toBeUndefined();
46
+ expect(executeQueryModel.mock.calls[0][5]).toEqual({ signal: undefined });
47
+ expect(options.queryKey).not.toContain("off-surface");
48
+ expect(options.queryKey).toEqual(call(false).options.queryKey);
49
+ });
50
+ });
@@ -0,0 +1,223 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useQuery } from "@tanstack/react-query";
5
+ import { useServer, type ApiClients } from "../ServerProvider";
6
+ import { givensKeyFor, type GivenInfo, type GivenRequest } from "./modelGivens";
7
+ import type { SourceAccess } from "./sourceAccess";
8
+
9
+ /** How one run ended, for a host that counts them. */
10
+ export interface QueryRunEvent {
11
+ outcome: "success" | "error";
12
+ durationMs: number;
13
+ }
14
+
15
+ /** What a run needs to address the served model: the same coordinates the
16
+ * explorer already reads the model's metadata with. */
17
+ export interface RunContext {
18
+ projectName: string;
19
+ packageName: string;
20
+ versionId?: string;
21
+ /** The model's declared givens — the declarations runGate reads to name a
22
+ * default a run fell back to, or to refuse where a blank one has none. The
23
+ * values a run sends are `givenValues` below. */
24
+ givens?: ReadonlyArray<GivenInfo>;
25
+ /** Source name → the givens a run on that source can use (givensForSource):
26
+ * what its declaration reads, plus the model-wide ones no source reads. The
27
+ * page's Givens section shows the same set, so a gate never asks for a given
28
+ * that section can't set. */
29
+ givensBySource?: ReadonlyMap<string, GivenInfo[]>;
30
+ /** Source name → the givens in `givensBySource` the scan can't tie to it
31
+ * either way (scanGivensForSource), for a source built on what its file
32
+ * doesn't declare: a run's card says it ran with them only where the source
33
+ * reads them. */
34
+ unknownGivensBySource?: ReadonlyMap<string, ReadonlySet<string>>;
35
+ /** Source name → labels of its `#(filter … required)` filters; a run can't
36
+ * supply them, so it refuses rather than 400. */
37
+ requiredFiltersBySource?: ReadonlyMap<string, string[]>;
38
+ /** Given values the reader set in the page's Givens section, in the request
39
+ * form a dashboard sends (`givensRequest`: typed, unset ones left out), sent
40
+ * with every run and part of its cache key (givensKeyFor). */
41
+ givenValues?: GivenRequest;
42
+ /** Run a file the package's index.malloy hides, for someone who can edit the
43
+ * package (offSurface.tsx). Anyone else is refused. */
44
+ includeHiddenFilesAndSources?: boolean;
45
+ /** Source name → its access declarations, so a refused run can say which
46
+ * rule refused it rather than a bare "no access". */
47
+ accessBySource?: ReadonlyMap<string, SourceAccess>;
48
+ /** Labels every run carries (`QueryRequest.queryMetadata`), for a host that
49
+ * tags its traffic by the surface it came from. */
50
+ queryMetadata?: Readonly<Record<string, string>>;
51
+ /** Called once per run that settles; a run the reader left is not reported. */
52
+ onQueryRun?: (event: QueryRunEvent) => void;
53
+ /** A result larger than this (bytes) is held behind a warning before it renders. */
54
+ maxResultSize?: number;
55
+ }
56
+
57
+ /** The givens a run on `sourceName` reads — the model's own for a named query. */
58
+ export function givensOfRun(
59
+ run: Pick<RunContext, "givens" | "givensBySource">,
60
+ sourceName: string | undefined,
61
+ ): ReadonlyArray<GivenInfo> | undefined {
62
+ return (
63
+ (sourceName ? run.givensBySource?.get(sourceName) : undefined) ??
64
+ run.givens
65
+ );
66
+ }
67
+
68
+ /**
69
+ * The run as one view, query or sample read sends it: with the given values of
70
+ * the givens it reads alone (`givens`, from {@link givensOfRun}, the set its
71
+ * gate and its source's Givens section use). A value set for a given it doesn't
72
+ * read neither reaches its request nor changes its cache key, so changing one
73
+ * leaves its result current rather than paying for the same query again.
74
+ */
75
+ export function runReading(
76
+ run: RunContext,
77
+ givens: ReadonlyArray<GivenInfo> | undefined,
78
+ ): RunContext {
79
+ if (!run.givenValues || !givens) return run;
80
+ const read = new Set(givens.map((g) => g.name));
81
+ const entries = Object.entries(run.givenValues).filter(([name]) =>
82
+ read.has(name),
83
+ );
84
+ return {
85
+ ...run,
86
+ givenValues:
87
+ entries.length > 0
88
+ ? (Object.fromEntries(entries) as GivenRequest)
89
+ : undefined,
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Run one Malloy query against a published model and hand back the publisher's
95
+ * `Result` JSON for `RenderedResult`: `executeQueryModel` with the query text,
96
+ * keyed by everything that decides its answer.
97
+ *
98
+ * Idle until `enabled`: browsing a source must cost nothing; a run happens on a
99
+ * click. And a result, once fetched, is final for this query text and version:
100
+ * it never goes stale and never refetches on focus or remount. Re-running is
101
+ * the card's own explicit control (`refetch`), because a warehouse query is
102
+ * billed.
103
+ */
104
+ export function useRunQuery({
105
+ run,
106
+ modelPath,
107
+ query,
108
+ enabled,
109
+ }: {
110
+ run: RunContext;
111
+ modelPath: string;
112
+ query: string;
113
+ enabled: boolean;
114
+ }) {
115
+ const { server, apiClients } = useServer();
116
+ const result = useQuery({
117
+ ...runQueryOptions({ server, apiClients, run, modelPath, query }),
118
+ enabled,
119
+ refetchOnWindowFocus: false,
120
+ refetchOnReconnect: false,
121
+ });
122
+ return {
123
+ result: result.data?.data.result,
124
+ isSuccess: result.isSuccess,
125
+ isLoading: result.isLoading,
126
+ isFetching: result.isFetching,
127
+ isError: result.isError,
128
+ error: result.error,
129
+ refetch: result.refetch,
130
+ };
131
+ }
132
+
133
+ /**
134
+ * The viewer's cache key for one run (a view's, a named query's), for a host
135
+ * that refreshes it or runs the same query itself (a download, say).
136
+ */
137
+ export function runQueryKey(
138
+ server: string,
139
+ run: Pick<
140
+ RunContext,
141
+ | "projectName"
142
+ | "packageName"
143
+ | "versionId"
144
+ | "givenValues"
145
+ | "includeHiddenFilesAndSources"
146
+ >,
147
+ modelPath: string,
148
+ query: string,
149
+ ): readonly unknown[] {
150
+ return [
151
+ "model-viewer-run",
152
+ server,
153
+ run.projectName,
154
+ run.packageName,
155
+ modelPath,
156
+ run.versionId ?? "",
157
+ query,
158
+ // The same serialization a notebook cell uses for its key (givensKeyFor).
159
+ givensKeyFor(run.givenValues),
160
+ // A hidden file's run is its own entry: the curated run's 404 must
161
+ // never be served in its place.
162
+ ...(run.includeHiddenFilesAndSources ? ["off-surface"] : []),
163
+ ];
164
+ }
165
+
166
+ /**
167
+ * A viewer run's cache key, request and caching, apart from the hook, so a host
168
+ * that runs the same query (a download, say) reuses a result the reader already
169
+ * ran, and one it runs is cached for the reader to open without paying again.
170
+ *
171
+ * A run is kept until the page goes (`staleTime: Infinity`): its inputs are all in
172
+ * the key. A failed run is reported in place with its own Retry, so it never
173
+ * retries silently — that would re-bill a query the reader can see failed.
174
+ */
175
+ export function runQueryOptions({
176
+ server,
177
+ apiClients,
178
+ run,
179
+ modelPath,
180
+ query,
181
+ }: {
182
+ server: string;
183
+ apiClients: ApiClients;
184
+ run: RunContext;
185
+ modelPath: string;
186
+ query: string;
187
+ }) {
188
+ const givens =
189
+ givensKeyFor(run.givenValues) === "" ? undefined : run.givenValues;
190
+ return {
191
+ queryKey: runQueryKey(server, run, modelPath, query),
192
+ queryFn: async ({ signal }: { signal?: AbortSignal }) => {
193
+ const started = performance.now();
194
+ const durationMs = () => Math.round(performance.now() - started);
195
+ try {
196
+ const result = await apiClients.models.executeQueryModel(
197
+ run.projectName,
198
+ run.packageName,
199
+ modelPath,
200
+ {
201
+ query,
202
+ versionId: run.versionId,
203
+ ...(givens && { givens }),
204
+ ...(run.queryMetadata && {
205
+ queryMetadata: { ...run.queryMetadata },
206
+ }),
207
+ },
208
+ run.includeHiddenFilesAndSources ? true : undefined,
209
+ { signal },
210
+ );
211
+ run.onQueryRun?.({ outcome: "success", durationMs: durationMs() });
212
+ return result;
213
+ } catch (error) {
214
+ // A run the reader left (or replaced) is not a failed one.
215
+ if (!signal?.aborted)
216
+ run.onQueryRun?.({ outcome: "error", durationMs: durationMs() });
217
+ throw error;
218
+ }
219
+ },
220
+ staleTime: Infinity,
221
+ retry: false,
222
+ } as const;
223
+ }
@@ -18,10 +18,11 @@ mockServerProvider(
18
18
  {
19
19
  versions: noVersions,
20
20
  packages: {
21
- getPackage: () =>
22
- Promise.resolve({
23
- data: { name: "pkg", ...(agents ? { agents } : {}) },
24
- }),
21
+ getPackage: () => Promise.resolve({ data: { name: "pkg" } }),
22
+ },
23
+ // The section reads the package's agents from their own route.
24
+ agents: {
25
+ listAgents: () => Promise.resolve({ data: agents ?? [] }),
25
26
  },
26
27
  reports: { listReports: () => Promise.resolve({ data: [] }) },
27
28
  models: { listModels: () => Promise.resolve({ data: [] }) },
@@ -211,6 +211,13 @@ export default function Package({
211
211
  ),
212
212
  });
213
213
 
214
+ // The package's agents, from their own route.
215
+ const agentsQuery = useQueryWithApiError({
216
+ queryKey: ["package-agents", environmentName, packageName, versionId],
217
+ queryFn: () =>
218
+ apiClients.agents.listAgents(environmentName, packageName, versionId),
219
+ });
220
+
214
221
  // One listing for both layouts, by path, shared with every other reader.
215
222
  const reportListing = useReportListing(
216
223
  environmentName,
@@ -351,7 +358,7 @@ export default function Package({
351
358
  ]);
352
359
 
353
360
  const description = pkgQuery.data?.data?.description ?? "";
354
- const agents = pkgQuery.data?.data?.agents ?? [];
361
+ const agents = agentsQuery.data?.data ?? [];
355
362
  const readmePath = (
356
363
  reports.find((r) => r.path === README_NOTEBOOK) ??
357
364
  reports.find((r) => isRootReadme(r.path))
@@ -127,5 +127,13 @@ source: a is one extend {
127
127
  expect(buildSuggestQuery(suggest!.source!, suggest!.dimension)).toBe(
128
128
  `run: a -> {\n group_by: products.category\n order_by: category asc\n limit: ${SUGGEST_OPTION_LIMIT + 1}\n}`,
129
129
  );
130
+ // On a server whose model page is the viewer, every name quoted.
131
+ expect(
132
+ buildSuggestQuery(suggest!.source!, suggest!.dimension, undefined, {
133
+ quoteNames: true,
134
+ }),
135
+ ).toBe(
136
+ `run: \`a\` -> {\n group_by: \`products\`.\`category\`\n order_by: \`category\` asc\n limit: ${SUGGEST_OPTION_LIMIT + 1}\n}`,
137
+ );
130
138
  });
131
139
  });
@@ -34,6 +34,13 @@ export async function loadMalloyTag(): Promise<MalloyTag> {
34
34
  return unwrapMalloyTag(await import("@malloydata/malloy-tag"));
35
35
  }
36
36
 
37
+ /**
38
+ * The Explorer's query builder, for `SourcesExplorer` alone: ESLint lets only
39
+ * the Explorer's callers import this (`EXPLORER_CALLERS`).
40
+ */
37
41
  export async function loadQueryBuilder(): Promise<QueryBuilder> {
38
- return unwrapQueryBuilder(await import("@malloydata/malloy-query-builder"));
42
+ return unwrapQueryBuilder(
43
+ // eslint-disable-next-line no-restricted-syntax -- the query builder's one loader, for the Explorer; every other rule still holds in this file
44
+ await import("@malloydata/malloy-query-builder"),
45
+ );
39
46
  }
@@ -22,6 +22,7 @@ import {
22
22
  ModelsApi,
23
23
  NotebooksApi,
24
24
  PackagesApi,
25
+ AgentsApi,
25
26
  PublisherApi,
26
27
  ReportsApi,
27
28
  VersionsApi,
@@ -33,6 +34,9 @@ import { ThemeProvider } from "../theme/ThemeContext";
33
34
  import type { ReportUiOverrides } from "../theme/ui";
34
35
  import type { Theme, ThemeMode } from "../theme/types";
35
36
  import { globalQueryClient } from "../utils/queryClient";
37
+ import { modelPageState, type ModelPage } from "./modelPage";
38
+
39
+ export type { ModelPage };
36
40
 
37
41
  const THEME_MODE_STORAGE_KEY = "publisher:themeMode";
38
42
 
@@ -80,6 +84,10 @@ export interface ServerContextValue {
80
84
  apiClients: ApiClients;
81
85
  /** `undefined` while `/status` loads (or failed) and the host passed no `mutable`. */
82
86
  mutable: boolean | undefined;
87
+ /**
88
+ * `/status` has neither answered nor failed yet, including while a retry is
89
+ * paused (offline, or a hidden tab).
90
+ */
83
91
  isLoadingStatus: boolean;
84
92
  /**
85
93
  * Instance-wide default theme, pulled from the `/api/v0/status` response.
@@ -87,6 +95,15 @@ export interface ServerContextValue {
87
95
  * theme in `publisher.config.json`.
88
96
  */
89
97
  instanceTheme?: Theme;
98
+ /**
99
+ * Which page `Model` shows, the server's `PUBLISHER_MODEL_PAGE` from
100
+ * `/status`: `explorer`, the Malloy Explorer, unless the server says
101
+ * `viewer`, and `viewer` when `/status` could not be read (see
102
+ * `modelPageOf`). `explorer` while `/status` loads and from a server
103
+ * that predates the setting, so wait on `isLoadingStatus` before showing
104
+ * anything the Explorer would replace.
105
+ */
106
+ modelPage: ModelPage;
90
107
  }
91
108
 
92
109
  const ServerContext = createContext<ServerContextValue | undefined>(undefined);
@@ -154,6 +171,7 @@ const getApiClients = (
154
171
  publisher: new PublisherApi(config, basePath, axiosInstance),
155
172
  environments: new EnvironmentsApi(config, basePath, axiosInstance),
156
173
  packages: new PackagesApi(config, basePath, axiosInstance),
174
+ agents: new AgentsApi(config, basePath, axiosInstance),
157
175
  dashboards: new DashboardsApi(config, basePath, axiosInstance),
158
176
  dataApps: new DataAppsApi(config, basePath, axiosInstance),
159
177
  notebooks: new NotebooksApi(config, basePath, axiosInstance),
@@ -203,14 +221,21 @@ const ServerProviderInner: React.FC<ServerProviderProps> = ({
203
221
 
204
222
  // Fetch /status via react-query so callers like the Theme Editor can
205
223
  // invalidate the "status" key after a write and pick up the new
206
- // instanceTheme without a full page reload.
224
+ // instanceTheme without a full page reload. Keyed by the server too: the
225
+ // query client is shared, and two providers on different servers must not
226
+ // read one server's model page, theme or frozen config.
207
227
  const statusQuery = useQuery({
208
- queryKey: ["status"],
228
+ queryKey: ["status", server],
229
+ // Retried, unlike the client's other reads: the model page depends on
230
+ // the answer for the whole session, and one dropped request would
231
+ // otherwise settle it.
232
+ retry: 3,
209
233
  queryFn: async () => {
210
234
  const response = await apiClients.publisher.getStatus();
211
235
  return response.data as {
212
236
  frozenConfig?: boolean;
213
237
  theme?: Theme;
238
+ modelPage?: ModelPage;
214
239
  };
215
240
  },
216
241
  });
@@ -221,7 +246,7 @@ const ServerProviderInner: React.FC<ServerProviderProps> = ({
221
246
 
222
247
  const frozenConfig = statusQuery.data?.frozenConfig;
223
248
  const instanceTheme = statusQuery.data?.theme;
224
- const isLoadingStatus = statusQuery.isLoading;
249
+ const { modelPage, isLoadingStatus } = modelPageState(statusQuery);
225
250
 
226
251
  // Preserve original semantics: while loading or on error, mirror the
227
252
  // mutableProp the caller passed in (which itself may be undefined).
@@ -290,6 +315,7 @@ const ServerProviderInner: React.FC<ServerProviderProps> = ({
290
315
  mutable,
291
316
  isLoadingStatus,
292
317
  instanceTheme,
318
+ modelPage,
293
319
  };
294
320
 
295
321
  return (