@malloy-publisher/sdk 0.7.0 → 0.8.1

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@malloy-publisher/sdk",
3
3
  "description": "Malloy Publisher SDK",
4
- "version": "0.7.0",
4
+ "version": "0.8.1",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.es.js",
@@ -63,6 +63,9 @@ const getDashboard = mock(
63
63
  data: { path: "dashboards/overview.malloy", givens: [], tiles: [] },
64
64
  }),
65
65
  );
66
+ const listModels = mock((_env: string, _pkg: string, _versionId?: string) =>
67
+ Promise.resolve({ data: [{ path: "data_app.malloy" }] }),
68
+ );
66
69
  const listDashboards = mock((_env: string, _pkg: string, _versionId?: string) =>
67
70
  Promise.resolve({ data: [{ name: "overview" }] }),
68
71
  );
@@ -94,7 +97,7 @@ const executeQueryModel = mock(
94
97
  const serverContext = { mutable: false };
95
98
  mockServerProvider(
96
99
  {
97
- models: { getModel, executeQueryModel, updateModelSource },
100
+ models: { getModel, executeQueryModel, updateModelSource, listModels },
98
101
  dashboards: { getDashboard, listDashboards },
99
102
  },
100
103
  serverContext,
@@ -137,6 +140,7 @@ beforeEach(() => {
137
140
  getModel.mockClear();
138
141
  getDashboard.mockClear();
139
142
  listDashboards.mockClear();
143
+ listModels.mockClear();
140
144
  updateModelSource.mockClear();
141
145
  // Uncleared, a tile query from an earlier test carries into the next one's
142
146
  // assertions, where it looks like the component under test made it.
@@ -200,6 +204,7 @@ describe("versionId", () => {
200
204
  "v7",
201
205
  ]);
202
206
  expect(listDashboards.mock.calls[0]).toEqual(["env", "pkg", "v7"]);
207
+ expect(listModels.mock.calls[0]).toEqual(["env", "pkg", "v7"]);
203
208
 
204
209
  // The key too, appended last, never spliced in the middle of it: a
205
210
  // version in the wrong slot is a key that cannot tell two versions of
@@ -28,34 +28,39 @@ source: a is scoped_orders extend {
28
28
  }`;
29
29
 
30
30
  const getModel = mock((_env: string, _pkg: string, path: string) =>
31
- Promise.resolve({
32
- data:
33
- path === "dashboards/overview.malloy"
34
- ? { modelPath: path, sourceText: PACKAGE_FILE }
35
- : {
36
- modelPath: path,
37
- sources: [
38
- {
39
- name: "scoped_orders",
40
- views: [{ name: "by_category" }, { name: "by_brand" }],
41
- },
42
- ],
43
- sourceInfos: [
44
- JSON.stringify({
45
- name: "scoped_orders",
46
- schema: {
47
- fields: [
48
- {
49
- name: "cat",
50
- kind: "dimension",
51
- type: { kind: "string_type" },
52
- },
53
- ],
54
- },
55
- }),
56
- ],
57
- },
58
- }),
31
+ path === "broken.malloy"
32
+ ? Promise.reject(new Error("reloading"))
33
+ : Promise.resolve({
34
+ data:
35
+ path === "dashboards/overview.malloy"
36
+ ? { modelPath: path, sourceText: PACKAGE_FILE }
37
+ : {
38
+ modelPath: path,
39
+ sources: [
40
+ {
41
+ name: "scoped_orders",
42
+ views: [
43
+ { name: "by_category" },
44
+ { name: "by_brand" },
45
+ ],
46
+ },
47
+ ],
48
+ sourceInfos: [
49
+ JSON.stringify({
50
+ name: "scoped_orders",
51
+ schema: {
52
+ fields: [
53
+ {
54
+ name: "cat",
55
+ kind: "dimension",
56
+ type: { kind: "string_type" },
57
+ },
58
+ ],
59
+ },
60
+ }),
61
+ ],
62
+ },
63
+ }),
59
64
  );
60
65
  const getDashboard = mock(() =>
61
66
  Promise.resolve({
@@ -66,8 +71,13 @@ const listDashboards = mock(() =>
66
71
  Promise.resolve({ data: [{ name: "overview" }, { name: "regions" }] }),
67
72
  );
68
73
  const executeQueryModel = mock(() => pending());
74
+ // What the package publishes: the catalog is built from these, not from
75
+ // whatever file the dashboard imports.
76
+ const listModels = mock(() =>
77
+ Promise.resolve({ data: [{ path: "data_app.malloy" }] }),
78
+ );
69
79
  mockServerProvider({
70
- models: { getModel, executeQueryModel },
80
+ models: { getModel, executeQueryModel, listModels },
71
81
  dashboards: { getDashboard, listDashboards },
72
82
  });
73
83
 
@@ -113,7 +123,11 @@ describe("DashboardEditor", () => {
113
123
  mount();
114
124
  expect(await screen.findByText("Storefront")).toBeDefined();
115
125
  expect(screen.getByLabelText("Tile by_cat")).toBeDefined();
116
- // The catalog came from the model the file imports, by its resolved path.
126
+ // The catalog came from the published models, and the file's import of
127
+ // scoped_orders is what keeps it on offer.
128
+ await waitFor(() =>
129
+ expect(listModels.mock.calls.length).toBeGreaterThan(0),
130
+ );
117
131
  await waitFor(() =>
118
132
  expect(
119
133
  getModel.mock.calls.some((call) => call[2] === "data_app.malloy"),
@@ -122,6 +136,22 @@ describe("DashboardEditor", () => {
122
136
  await screen.findByRole("button", { name: "Add tile", hidden: true });
123
137
  });
124
138
 
139
+ it("keeps the catalog when one published model fails to load", async () => {
140
+ listModels.mockImplementationOnce(() =>
141
+ Promise.resolve({
142
+ data: [{ path: "data_app.malloy" }, { path: "broken.malloy" }],
143
+ }),
144
+ );
145
+ mount();
146
+ await waitFor(() =>
147
+ expect(
148
+ getModel.mock.calls.some((call) => call[2] === "broken.malloy"),
149
+ ).toBe(true),
150
+ );
151
+ // Adding a tile needs a catalog, so the button is the proof it built.
152
+ await screen.findByRole("button", { name: "Add tile", hidden: true });
153
+ });
154
+
125
155
  it("saves an edit into the browser and marks it saved", async () => {
126
156
  const storage = mount();
127
157
  await screen.findByText("Storefront");
@@ -27,7 +27,11 @@ import { DashboardBar } from "../Dashboard/DashboardBar";
27
27
  import { Loading } from "../Loading";
28
28
  import { TILE_MAX_HEIGHT } from "../RenderedResult/resultSizing";
29
29
  import { useServer } from "../ServerProvider";
30
- import { buildCatalog, type PackageCatalog } from "./catalog";
30
+ import {
31
+ buildCatalog,
32
+ visibleToDashboard,
33
+ type PackageCatalog,
34
+ } from "./catalog";
31
35
  import { DashboardBuilder } from "./DashboardBuilder";
32
36
  import type { DashboardDocument } from "./document";
33
37
  import { previewGivens, previewTileQuery } from "./preview";
@@ -785,36 +789,51 @@ function Surface({
785
789
  [dashboardList, slug],
786
790
  );
787
791
 
788
- // The catalog: the models this file imports, which is where its tiles'
789
- // sources and their fields are declared.
790
- const importPaths = useMemo(() => {
792
+ // The catalog: what the package publishes, limited to what this file can
793
+ // see. A tile runs against this file and may read only the package surface,
794
+ // so offering a source from any other file would offer a tile that 404s.
795
+ // Files off the surface are not readable anyway (their model GET is 404).
796
+ const imports = useMemo(() => {
791
797
  const dir = modelPath.slice(0, modelPath.lastIndexOf("/") + 1);
792
- const resolved = new Set<string>();
793
- for (const imported of opened.document.imports) {
794
- const url = new URL(imported.from, `https://malloy.invalid/${dir}`);
795
- resolved.add(url.pathname.slice(1));
796
- }
797
- return [...resolved];
798
+ return opened.document.imports.map((imported) => ({
799
+ ...imported,
800
+ path: new URL(
801
+ imported.from,
802
+ `https://malloy.invalid/${dir}`,
803
+ ).pathname.slice(1),
804
+ }));
798
805
  }, [opened.document.imports, modelPath]);
799
806
  const { data: catalog } = useQueryWithApiError<PackageCatalog>({
800
807
  queryKey: [
801
808
  "dashboard-editor-catalog",
802
809
  environmentName,
803
810
  packageName,
804
- ...importPaths,
811
+ ...imports.map((i) => i.path),
805
812
  versionId,
806
813
  ],
807
814
  queryFn: async () => {
808
- const models = await Promise.all(
809
- importPaths.map((path) =>
815
+ const listed = (
816
+ await apiClients.models.listModels(
817
+ environmentName,
818
+ packageName,
819
+ versionId,
820
+ )
821
+ ).data.filter((m) => m.path && !m.error);
822
+ // One model that fails to load (a reload racing this fetch, say)
823
+ // costs the catalog that model's sources, not every suggestion.
824
+ const settled = await Promise.allSettled(
825
+ listed.map((m) =>
810
826
  apiClients.models
811
- .getModel(environmentName, packageName, path, versionId)
827
+ .getModel(environmentName, packageName, m.path!, versionId)
812
828
  .then((response) => response.data),
813
829
  ),
814
830
  );
815
- return buildCatalog(models);
831
+ const models = settled.flatMap((result) =>
832
+ result.status === "fulfilled" ? [result.value] : [],
833
+ );
834
+ return visibleToDashboard(buildCatalog(models), imports, models);
816
835
  },
817
- enabled: importPaths.length > 0,
836
+ enabled: imports.length > 0,
818
837
  });
819
838
 
820
839
  const [doc, setDoc] = useState(opened.document);
@@ -9,6 +9,7 @@ import {
9
9
  docOf,
10
10
  filterableFields,
11
11
  isDashboardModel,
12
+ visibleToDashboard,
12
13
  } from "./catalog";
13
14
 
14
15
  /**
@@ -137,6 +138,49 @@ describe("buildCatalog", () => {
137
138
  });
138
139
  });
139
140
 
141
+ describe("visibleToDashboard", () => {
142
+ const published: CompiledModel[] = [
143
+ {
144
+ path: "index.malloy",
145
+ sources: [{ name: "orders" }, { name: "users" }],
146
+ },
147
+ ];
148
+ const catalog = buildCatalog(published);
149
+ const names = (c: ReturnType<typeof buildCatalog>) =>
150
+ c.sources.map((s) => s.name).sort();
151
+
152
+ it("offers only the names a named import brings", () => {
153
+ const seen = visibleToDashboard(
154
+ catalog,
155
+ [{ kind: "names", names: ["orders"], path: "orders.malloy" }],
156
+ published,
157
+ );
158
+ expect(names(seen)).toEqual(["orders"]);
159
+ });
160
+
161
+ it("offers a published model's sources to a whole-file import of it", () => {
162
+ const seen = visibleToDashboard(
163
+ catalog,
164
+ [{ kind: "all", path: "index.malloy" }],
165
+ published,
166
+ );
167
+ expect(names(seen)).toEqual(["orders", "users"]);
168
+ });
169
+
170
+ it("offers everything published when a whole-file import cannot be read", () => {
171
+ // The imported file is off the surface, so what it declares is unknown.
172
+ const seen = visibleToDashboard(
173
+ catalog,
174
+ [
175
+ { kind: "names", names: ["orders"], path: "orders.malloy" },
176
+ { kind: "all", path: "hidden.malloy" },
177
+ ],
178
+ published,
179
+ );
180
+ expect(names(seen)).toEqual(["orders", "users"]);
181
+ });
182
+ });
183
+
140
184
  describe("filterableFields", () => {
141
185
  // Captured from the storefront package's `order_items`: a join's fields are
142
186
  // what people filter on, and a view is not a field at all.
@@ -223,3 +223,39 @@ export function buildCatalog(models: CompiledModel[]): PackageCatalog {
223
223
 
224
224
  return { sources };
225
225
  }
226
+
227
+ /**
228
+ * The part of the package catalog a dashboard file can actually use.
229
+ *
230
+ * The builder never writes an import, so a source the file cannot see would
231
+ * produce a tile that does not compile. A named import says exactly which
232
+ * names it brings. A whole-file import of a published model brings that
233
+ * model's sources. A whole-file import of a file off the surface cannot be
234
+ * read, so then every published source is offered and a wrong pick is caught
235
+ * by the compile check the editor already runs.
236
+ */
237
+ export function visibleToDashboard(
238
+ catalog: PackageCatalog,
239
+ imports: ReadonlyArray<
240
+ | { kind: "all"; path: string }
241
+ | { kind: "names"; names: string[]; path: string }
242
+ >,
243
+ published: CompiledModel[],
244
+ ): PackageCatalog {
245
+ const visible = new Set<string>();
246
+ for (const imported of imports) {
247
+ if (imported.kind === "names") {
248
+ for (const name of imported.names) visible.add(name);
249
+ continue;
250
+ }
251
+ const model = published.find((m) => pathOf(m) === imported.path);
252
+ if (!model) return catalog;
253
+ for (const source of model.sources ?? []) {
254
+ if (source.name) visible.add(source.name);
255
+ }
256
+ }
257
+ return {
258
+ ...catalog,
259
+ sources: catalog.sources.filter((source) => visible.has(source.name)),
260
+ };
261
+ }
@@ -40,6 +40,12 @@ function parseDataAppResource(resourceUri: string) {
40
40
  * height changes; we listen and resize the iframe to match so embedded
41
41
  * dashboards don't get a nested scrollbar.
42
42
  *
43
+ * When those two origins differ, the worker serving the app must name this
44
+ * SPA's origin in `PUBLISHER_FRAME_ANCESTORS`. The server's default is
45
+ * `frame-ancestors 'self'`, which permits only its own origin, so a
46
+ * cross-origin embed is refused by the browser and the iframe renders blank
47
+ * with nothing logged server-side. A same-origin deployment needs no setting.
48
+ *
43
49
  * Full-screen apps (e.g. slide decks) can opt out of content-height sizing
44
50
  * with `<meta name="publisher:fit" content="viewport">`, surfaced as
45
51
  * `DataApp.fit === "viewport"`. The iframe then fills the available viewport
@@ -27,6 +27,8 @@ import {
27
27
  formatTimestamp,
28
28
  isActiveStatus,
29
29
  parseMetadata,
30
+ refusedSourcesOf,
31
+ sourcesSummary,
30
32
  statusColor,
31
33
  statusLabel,
32
34
  } from "./utils";
@@ -47,6 +49,7 @@ export default function MaterializationDetailDialog({
47
49
  onClose,
48
50
  }: MaterializationDetailDialogProps) {
49
51
  const meta = materialization ? parseMetadata(materialization) : {};
52
+ const refused = materialization ? refusedSourcesOf(materialization) : [];
50
53
  const planSources = Object.values(buildPlan?.sources ?? {});
51
54
 
52
55
  return (
@@ -135,7 +138,7 @@ export default function MaterializationDetailDialog({
135
138
  />
136
139
  <DetailField
137
140
  label="Sources"
138
- value={`${meta.sourcesBuilt ?? 0} built · ${meta.sourcesReused ?? 0} reused`}
141
+ value={sourcesSummary(meta, " · ")}
139
142
  />
140
143
  <DetailField
141
144
  label="Force refresh"
@@ -170,6 +173,49 @@ export default function MaterializationDetailDialog({
170
173
  </Box>
171
174
  )}
172
175
 
176
+ {refused.length > 0 && (
177
+ <Box
178
+ sx={{
179
+ borderRadius: 2,
180
+ p: 2,
181
+ mb: 3,
182
+ border: "1px solid",
183
+ borderColor: "warning.main",
184
+ }}
185
+ >
186
+ <SectionLabel>
187
+ <Box component="span" sx={{ color: "warning.main" }}>
188
+ Refused sources
189
+ </Box>
190
+ </SectionLabel>
191
+ <Typography
192
+ variant="body2"
193
+ color="text.secondary"
194
+ sx={{ mb: 1 }}
195
+ >
196
+ Not built, because materializing them would be
197
+ unsafe. They serve live until the model changes.
198
+ </Typography>
199
+ {refused.map((r) => (
200
+ <Box key={r.name} sx={{ mt: 1 }}>
201
+ <Typography
202
+ variant="body2"
203
+ sx={{ fontFamily: MONO_FONT_FAMILY }}
204
+ >
205
+ {r.name}
206
+ </Typography>
207
+ <Typography
208
+ variant="body2"
209
+ color="text.secondary"
210
+ sx={{ whiteSpace: "pre-wrap" }}
211
+ >
212
+ {r.message}
213
+ </Typography>
214
+ </Box>
215
+ ))}
216
+ </Box>
217
+ )}
218
+
173
219
  <Box sx={{ mb: 3 }}>
174
220
  <SectionLabel>Build plan</SectionLabel>
175
221
  {planSources.length === 0 ? (
@@ -29,6 +29,7 @@ import {
29
29
  isActiveStatus,
30
30
  isTerminalStatus,
31
31
  parseMetadata,
32
+ sourcesSummary,
32
33
  statusColor,
33
34
  statusLabel,
34
35
  } from "./utils";
@@ -124,7 +125,7 @@ function MaterializationRow({
124
125
  const meta = parseMetadata(materialization);
125
126
  const sourcesLabel =
126
127
  meta.sourcesBuilt !== undefined || meta.sourcesReused !== undefined
127
- ? `${meta.sourcesBuilt ?? 0} built, ${meta.sourcesReused ?? 0} reused`
128
+ ? sourcesSummary(meta, ", ")
128
129
  : "-";
129
130
  const active = isActiveStatus(materialization.status);
130
131
  const terminal = isTerminalStatus(materialization.status);
@@ -10,6 +10,8 @@ import {
10
10
  isActiveStatus,
11
11
  isTerminalStatus,
12
12
  parseMetadata,
13
+ refusedSourcesOf,
14
+ sourcesSummary,
13
15
  statusColor,
14
16
  statusLabel,
15
17
  triggerLabel,
@@ -180,3 +182,57 @@ describe("formatRelativeTime", () => {
180
182
  expect(formatRelativeTime(undefined)).toBe("-");
181
183
  });
182
184
  });
185
+
186
+ describe("sourcesSummary", () => {
187
+ it("reads as built and reused on a run that refused nothing", () => {
188
+ expect(sourcesSummary({ sourcesBuilt: 2, sourcesReused: 1 }, ", ")).toBe(
189
+ "2 built, 1 reused",
190
+ );
191
+ });
192
+
193
+ it("names the refused count when the run skipped a source", () => {
194
+ expect(
195
+ sourcesSummary(
196
+ { sourcesBuilt: 5, sourcesReused: 0, sourcesRefused: 7 },
197
+ " · ",
198
+ ),
199
+ ).toBe("5 built · 0 reused · 7 refused");
200
+ });
201
+ });
202
+
203
+ describe("refusedSourcesOf", () => {
204
+ it("reads auto-run's metadata list and orchestrated failures marked refused", () => {
205
+ const materialization = {
206
+ metadata: {
207
+ refusedSources: {
208
+ "b@m": { name: "b", message: "b is gated" },
209
+ },
210
+ },
211
+ manifest: {
212
+ entries: {},
213
+ failures: {
214
+ x: {
215
+ sourceEntityId: "x",
216
+ sourceName: "a",
217
+ reason: "a reads a given",
218
+ refused: true,
219
+ },
220
+ y: {
221
+ sourceEntityId: "y",
222
+ sourceName: "c",
223
+ reason: "permission denied",
224
+ },
225
+ },
226
+ },
227
+ } as unknown as Materialization;
228
+
229
+ expect(refusedSourcesOf(materialization)).toEqual([
230
+ { name: "a", message: "a reads a given" },
231
+ { name: "b", message: "b is gated" },
232
+ ]);
233
+ });
234
+
235
+ it("is empty for a run that refused nothing", () => {
236
+ expect(refusedSourcesOf({} as Materialization)).toEqual([]);
237
+ });
238
+ });
@@ -81,6 +81,62 @@ export interface MaterializationMetadata {
81
81
  trigger?: "ON_DEMAND" | "SCHEDULER";
82
82
  sourcesBuilt?: number;
83
83
  sourcesReused?: number;
84
+ /**
85
+ * Persist sources the eligibility gate refused, so the run skipped them and
86
+ * they serve live. Absent when the run refused nothing; the refused sources
87
+ * themselves are named in `refusedSources`, beside this count.
88
+ */
89
+ sourcesRefused?: number;
90
+ /**
91
+ * The sources auto-run refused, keyed by sourceID. An orchestrated run
92
+ * reports its refusals in the manifest's `failures` instead, marked
93
+ * `refused`; {@link refusedSourcesOf} reads both.
94
+ */
95
+ refusedSources?: Record<string, { name: string; message: string }>;
96
+ }
97
+
98
+ /** One source a run did not build because the eligibility gate refused it. */
99
+ export interface RunRefusal {
100
+ name: string;
101
+ message: string;
102
+ }
103
+
104
+ /**
105
+ * Every source the run refused, from either place a run records one: the
106
+ * metadata list auto-run writes, and the `failures` an orchestrated run marks
107
+ * `refused`. Sorted by name so the list reads the same on every render.
108
+ */
109
+ export function refusedSourcesOf(
110
+ materialization: Materialization,
111
+ ): RunRefusal[] {
112
+ const fromMetadata = Object.values(
113
+ parseMetadata(materialization).refusedSources ?? {},
114
+ ).map((r) => ({ name: r.name, message: r.message }));
115
+ const fromFailures = Object.values(materialization.manifest?.failures ?? {})
116
+ .filter((f) => f.refused)
117
+ .map((f) => ({
118
+ name: f.sourceName ?? f.sourceEntityId,
119
+ message: f.reason,
120
+ }));
121
+ return [...fromMetadata, ...fromFailures].sort((a, b) =>
122
+ a.name.localeCompare(b.name),
123
+ );
124
+ }
125
+
126
+ /**
127
+ * The run's source counts, joined by `separator`. Refused sources are named
128
+ * only when there are some, so a clean run reads as it always has.
129
+ */
130
+ export function sourcesSummary(
131
+ meta: MaterializationMetadata,
132
+ separator: string,
133
+ ): string {
134
+ const parts = [
135
+ `${meta.sourcesBuilt ?? 0} built`,
136
+ `${meta.sourcesReused ?? 0} reused`,
137
+ ];
138
+ if (meta.sourcesRefused) parts.push(`${meta.sourcesRefused} refused`);
139
+ return parts.join(separator);
84
140
  }
85
141
 
86
142
  export function parseMetadata(