@holistics/anfra-sdk 0.7.1 → 0.9.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.
package/dist/api.js CHANGED
@@ -2,8 +2,7 @@ import {
2
2
  PermissionError,
3
3
  QueryError,
4
4
  TransportError
5
- } from "./chunk-KCTLO3CO.js";
6
- import "./chunk-PKBMQBKP.js";
5
+ } from "./chunk-KBXITYQK.js";
7
6
 
8
7
  // src/api/client.ts
9
8
  import createClient from "openapi-fetch";
@@ -59,6 +58,18 @@ function toQueryInput(request) {
59
58
  ...request.timezone ? { timezone: request.timezone } : {}
60
59
  };
61
60
  }
61
+ function toExportInput(request) {
62
+ return {
63
+ query: request.aql,
64
+ dataset: request.dataset,
65
+ input: request.input,
66
+ ...request.timezone ? { timezone: request.timezone } : {},
67
+ // The server names its formats; one it does not know it refuses, with a message the author sees.
68
+ ...request.format ? { format: request.format } : {},
69
+ ...request.formatOptions ? { format_options: request.formatOptions } : {},
70
+ ...request.filename ? { filename: request.filename } : {}
71
+ };
72
+ }
62
73
  function toColumns(columns) {
63
74
  return columns.map((column) => {
64
75
  const { semantic_type: semanticType, arrow_type: arrowType, db_type: dbType } = column;
@@ -70,10 +81,10 @@ function toColumns(columns) {
70
81
  return { ...column, semantic_type: semanticType, arrow_type: arrowType, db_type: dbType };
71
82
  });
72
83
  }
73
- async function runQuery(client, body, signal) {
84
+ async function callCoreAPI(call) {
74
85
  let result;
75
86
  try {
76
- result = await client.POST("/core.query", { body, signal });
87
+ result = await call();
77
88
  } catch (err) {
78
89
  if (isAbort(err)) throw err;
79
90
  throw new TransportError(`The server could not be reached: ${err.message}`);
@@ -82,6 +93,9 @@ async function runQuery(client, body, signal) {
82
93
  if (!data) throw toSdkError(response.status, error?.error);
83
94
  return data;
84
95
  }
96
+ function runQuery(client, body, signal) {
97
+ return callCoreAPI(() => client.POST("/core.query", { body, signal }));
98
+ }
85
99
  function coreApiBackend(base, options = {}) {
86
100
  const client = typeof base === "string" ? coreClient(base) : base;
87
101
  return {
@@ -127,6 +141,21 @@ function coreApiBackend(base, options = {}) {
127
141
  page_size: SUGGESTION_LIMIT
128
142
  }, signal);
129
143
  return data.result.records.map((row) => row[0]).filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean");
144
+ },
145
+ /** An export as `core.query.export`: the server runs the query to completion, then answers its link. */
146
+ async exportQuery(request, signal) {
147
+ const link = await callCoreAPI(() => client.POST("/core.query.export", { body: toExportInput(request), signal }));
148
+ return {
149
+ url: link.url,
150
+ filename: link.filename,
151
+ format: link.format,
152
+ rowCount: link.row_count,
153
+ expiresAt: new Date(link.expires_at)
154
+ };
155
+ },
156
+ /** Lineage as `core.lineage`, whose answer is the SDK's as it is. */
157
+ lineage(request, signal) {
158
+ return callCoreAPI(() => client.POST("/core.lineage", { body: request, signal }));
130
159
  }
131
160
  };
132
161
  }
@@ -172,6 +201,7 @@ export {
172
201
  coreClient,
173
202
  loadDatasets,
174
203
  toDescriptor,
204
+ toExportInput,
175
205
  toQueryInput,
176
206
  toSdkError
177
207
  };
package/dist/app.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { L as Listener, a1 as Unsubscribe, D as DatasetDescriptor, E as EntityKind, j as Condition, w as FilterDeclaration, x as FilterValueType, B as Backend, k as ConditionValue, n as DateDrillDeclaration, o as DateGrain, v as FilterAggregation, l as ControlMappingJson, m as CrossFilterJson, X as SdkFeatures, Y as Selection, Z as SelectionCondition, V as Row, K as LocateKind, P as QueryDeclaration, U as QueryState, S as QueryResult, T as QuerySort, a as AppDeclaration, s as ExecuteOptions, t as ExecuteSummary, b as AppJson, I as InspectedApp, a2 as User, W as SdkEnvironment, J as InspectedStructure } from './types-BlzJVcUl.js';
2
- export { A as Aggregation, c as ArrowType, d as BackendCondition, e as BackendDateDrill, f as BackendFilter, g as BackendQueryRequest, h as BackendQueryResult, i as BackendSort, C as ColumnMeta, p as DateTransformation, q as EntityRef, r as EntityUsage, F as FILTER_AGGREGATIONS, u as FieldSuggestionsRequest, y as InspectedControl, z as InspectedError, G as InspectedQuery, H as InspectedSelection, M as LocateTarget, N as MappingJson, O as Operator, Q as QueryDebug, R as QueryInput, _ as SemanticType, $ as StructureKind, a0 as StructureNode } from './types-BlzJVcUl.js';
1
+ import { X as Listener, ah as Unsubscribe, D as DatasetDescriptor, E as EntityKind, l as Condition, J as FilterDeclaration, K as FilterValueType, B as Backend, m as ConditionValue, p as DateDrillDeclaration, q as DateGrain, I as FilterAggregation, n as ControlMappingJson, o as CrossFilterJson, ab as SdkFeatures, ac as Selection, ad as SelectionCondition, a9 as Row, y as ExportOptions, z as ExportResult, Y as LocateKind, a1 as QueryDeclaration, a5 as QueryState, a3 as QueryResult, a4 as QuerySort, a as AppDeclaration, u as ExecuteOptions, v as ExecuteSummary, b as AppJson, L as InspectedApp, ai as User, aa as SdkEnvironment, a7 as RenderRequest, a8 as Rendering, W as LineageTarget, U as LineageOptions, V as LineageResult, Q as InspectedStructure } from './types-DznT0m7F.js';
2
+ export { A as Aggregation, c as ArrowType, d as BackendCondition, e as BackendDateDrill, f as BackendExportRequest, g as BackendFilter, h as BackendLineageRequest, i as BackendQueryRequest, j as BackendQueryResult, k as BackendSort, C as ColumnMeta, r as DateTransformation, s as EntityRef, t as EntityUsage, w as ExportFormat, x as ExportFormatOptions, F as FILTER_AGGREGATIONS, G as FieldLineage, H as FieldSuggestionsRequest, M as InspectedControl, N as InspectedError, O as InspectedQuery, P as InspectedSelection, R as LineageCard, S as LineageDiagram, T as LineageNode, Z as LocateTarget, _ as MappingJson, $ as Operator, a0 as QueryDebug, a2 as QueryInput, a6 as RenderFormat, ae as SemanticType, af as StructureKind, ag as StructureNode } from './types-DznT0m7F.js';
3
3
  import { D as DataAppError } from './errors-CKvqVaqU.js';
4
4
  export { P as PermissionError, Q as QueryError, T as TransportError, V as ValidationError } from './errors-CKvqVaqU.js';
5
- export { B as BridgeError, a as BridgeMethod, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as Provision } from './bridge-BKx7u5mX.js';
5
+ export { B as BridgeError, a as BridgeMethod, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as Provision } from './bridge-DUKdREoK.js';
6
6
 
7
7
  interface NotificationTarget {
8
8
  notifyChange(): void;
@@ -190,6 +190,8 @@ interface AppContext {
190
190
  select(query: Query, rows: readonly Row[], fields?: readonly string[]): void;
191
191
  /** Runs one more page for a query that already has a result. */
192
192
  fetchPage(query: Query): Promise<void>;
193
+ /** Exports a query's whole result, with what it was last run with. */
194
+ exportQuery(query: Query, options?: ExportOptions): Promise<ExportResult>;
193
195
  /** Brings an entity's marked elements into view; false when none is on the page. */
194
196
  locate(kind: LocateKind, name: string): boolean;
195
197
  }
@@ -254,6 +256,17 @@ declare class Query extends Observable {
254
256
  abort(): void;
255
257
  /** Fetches the next page and appends it. Rejects rather than swallowing, unlike `execute()`. */
256
258
  fetchMore(): Promise<void>;
259
+ /**
260
+ * Exports this query's whole result as a file, and has the host save it for the reader.
261
+ *
262
+ * Every row, not only the pages loaded, with what the result on screen was last run with: the
263
+ * mapped controls, the selection, the sort, the timezone. A control the reader changed but has
264
+ * not applied is not in it. Resolves once the file is made and its download has started, with
265
+ * its link and row count; rejects with a `DataAppError` naming this query, and changes nothing on
266
+ * the query either way. Show the button when `Anfra.features.export` and
267
+ * `Anfra.user.permissions.canExportData` are both true.
268
+ */
269
+ export(options?: ExportOptions): Promise<ExportResult>;
257
270
  /**
258
271
  * Cross-filters this query's targets by the rows the reader picked.
259
272
  *
@@ -389,6 +402,11 @@ declare class App extends Observable implements AppContext {
389
402
  abort(): void;
390
403
  /** @internal Backs `query.fetchMore()`. Rejects, so an explicit page request reports its failure. */
391
404
  fetchPage(query: Query): Promise<void>;
405
+ /**
406
+ * @internal Backs `query.export()`. Built from the applied state, as `fetchPage` is, so the file
407
+ * holds what the reader is looking at, every row of it. Touches nothing on the query.
408
+ */
409
+ exportQuery(query: Query, options?: ExportOptions): Promise<ExportResult>;
392
410
  /**
393
411
  * The declaration and nothing else — no datasets, no backend, no reader state. This is the
394
412
  * shape a persisted Data App record will take, which is why mapping edges are already generic.
@@ -451,9 +469,32 @@ declare class Sdk {
451
469
  readonly user: Readonly<User>;
452
470
  private readonly indices;
453
471
  private readonly backend;
454
- private readonly features;
472
+ /**
473
+ * What the host can do beyond queries. `export` says whether `query.export()` can work here, and
474
+ * `render` whether `render()` can: show either's button only when it and
475
+ * `user.permissions.canExportData` are both true. `lineage` says whether `lineage()` can.
476
+ */
477
+ readonly features: Readonly<SdkFeatures>;
478
+ private readonly renderHook?;
455
479
  constructor(environment: SdkEnvironment);
456
480
  createApp(declaration?: AppDeclaration): App;
481
+ /**
482
+ * Render the whole app, or one block or container of its structure by id, as a PNG or a PDF, and
483
+ * have the host save it for the reader. What is drawn is what the page shows now: `await
484
+ * app.execute()` first for fresh results. Elements marked `data-anfra-render="skip"` are left out.
485
+ * Rejects with a `ValidationError` naming what to fix.
486
+ */
487
+ render(request: RenderRequest): Promise<Rendering>;
488
+ /**
489
+ * Trace fields through the repo's catalog: what each one is built from (the fields, models and
490
+ * sources upstream of it), as a diagram to draw. Name each field by its parent and its name in
491
+ * it: `{ parent: 'orders', child: 'amount' }` for a model's field, `{ parent: 'ecommerce', child:
492
+ * 'revenue' }` for a dataset's metric. Nothing needs ingesting first: the host builds the repo's
493
+ * catalog when it has to. A field that cannot be traced answers its `error`, and the others still
494
+ * answer; a host that cannot trace lineage (see `features.lineage`) rejects with a
495
+ * `TransportError`.
496
+ */
497
+ lineage(targets: LineageTarget | readonly LineageTarget[], options?: LineageOptions): Promise<LineageResult>;
457
498
  /**
458
499
  * Every app this instance has built, for a host rendering an inspection panel.
459
500
  *
@@ -524,4 +565,4 @@ declare function buildStructure(doc: Document, apps: readonly App[]): BuiltStruc
524
565
  /** Provision the SDK in `win` from its host, and install it. Returns once `Anfra` exists. */
525
566
  declare function bootstrap(win: Window): void;
526
567
 
527
- export { App, AppDeclaration, AppJson, Backend, Condition, ConditionValue, Control, ControlMappingJson, CrossFilter, CrossFilterJson, DataAppError, DatasetDescriptor, DateDrillControl, DateDrillDeclaration, DateGrain, type Edge, EntityKind, ExecuteOptions, ExecuteSummary, Filter, FilterAggregation, FilterDeclaration, FilterValueType, InspectedApp, InspectedStructure, Listener, LocateKind, Mapping, OVERLAY_ID, Query, QueryDeclaration, QueryResult, QuerySort, QueryState, Row, SANDBOX_GLOBAL, ATTR as STRUCTURE_ATTRIBUTES, Sdk, SdkEnvironment, SdkFeatures, Selection, SelectionCondition, Unsubscribe, User, VERSION, bootstrap, buildStructure, createSdk, installSandbox, parseRef };
568
+ export { App, AppDeclaration, AppJson, Backend, Condition, ConditionValue, Control, ControlMappingJson, CrossFilter, CrossFilterJson, DataAppError, DatasetDescriptor, DateDrillControl, DateDrillDeclaration, DateGrain, type Edge, EntityKind, ExecuteOptions, ExecuteSummary, ExportOptions, ExportResult, Filter, FilterAggregation, FilterDeclaration, FilterValueType, InspectedApp, InspectedStructure, LineageOptions, LineageResult, LineageTarget, Listener, LocateKind, Mapping, OVERLAY_ID, Query, QueryDeclaration, QueryResult, QuerySort, QueryState, RenderRequest, Rendering, Row, SANDBOX_GLOBAL, ATTR as STRUCTURE_ATTRIBUTES, Sdk, SdkEnvironment, SdkFeatures, Selection, SelectionCondition, Unsubscribe, User, VERSION, bootstrap, buildStructure, createSdk, installSandbox, parseRef };
package/dist/app.js CHANGED
@@ -9,11 +9,9 @@ import {
9
9
  PermissionError,
10
10
  QueryError,
11
11
  TransportError,
12
- ValidationError
13
- } from "./chunk-KCTLO3CO.js";
14
- import {
12
+ ValidationError,
15
13
  __publicField
16
- } from "./chunk-PKBMQBKP.js";
14
+ } from "./chunk-KBXITYQK.js";
17
15
 
18
16
  // src/app/observable.ts
19
17
  var Observable = class {
@@ -169,6 +167,19 @@ var Query = class extends Observable {
169
167
  this._page += 1;
170
168
  await this.app.fetchPage(this);
171
169
  }
170
+ /**
171
+ * Exports this query's whole result as a file, and has the host save it for the reader.
172
+ *
173
+ * Every row, not only the pages loaded, with what the result on screen was last run with: the
174
+ * mapped controls, the selection, the sort, the timezone. A control the reader changed but has
175
+ * not applied is not in it. Resolves once the file is made and its download has started, with
176
+ * its link and row count; rejects with a `DataAppError` naming this query, and changes nothing on
177
+ * the query either way. Show the button when `Anfra.features.export` and
178
+ * `Anfra.user.permissions.canExportData` are both true.
179
+ */
180
+ export(options = {}) {
181
+ return this.app.exportQuery(this, options);
182
+ }
172
183
  /**
173
184
  * Cross-filters this query's targets by the rows the reader picked.
174
185
  *
@@ -624,7 +635,7 @@ function toResult(query, data) {
624
635
  ...data.debug ? { debug: data.debug } : {}
625
636
  };
626
637
  }
627
- function buildRequest(query, mappings, selection, context) {
638
+ function buildQuery(query, mappings, selection, context) {
628
639
  const mappedFilters = mappings.map((mapping) => toFilter(mapping, mapping.from.appliedCondition)).filter((filter) => filter !== void 0);
629
640
  const dateDrills = mappings.map((mapping) => toDateDrill(mapping, mapping.from.appliedCondition)).filter((drill) => drill !== void 0);
630
641
  const selectionFilters = selection.conditions.map((condition) => ({
@@ -642,14 +653,33 @@ function buildRequest(query, mappings, selection, context) {
642
653
  sorts: query.sort.map((sort) => ({ field: sort.field, direction: sort.direction ?? "asc" })),
643
654
  dateDrills
644
655
  },
645
- // Omitted for a query that declares no page size, so the backend returns every row.
646
- ...query.pageSize !== void 0 ? { page: query.page, pageSize: query.pageSize } : {},
647
656
  // Omitted entirely when the app declares none, so the backend applies its own default rather
648
657
  // than the SDK guessing the browser's.
649
- ...context.timezone ? { timezone: context.timezone } : {},
658
+ ...context.timezone ? { timezone: context.timezone } : {}
659
+ };
660
+ }
661
+ function buildRequest(query, mappings, selection, context) {
662
+ return {
663
+ ...buildQuery(query, mappings, selection, context),
664
+ // Omitted for a query that declares no page size, so the backend returns every row.
665
+ ...query.pageSize !== void 0 ? { page: query.page, pageSize: query.pageSize } : {},
650
666
  ...context.bustCache ? { bustCache: true } : {}
651
667
  };
652
668
  }
669
+ function defaultExportFilename(query, title) {
670
+ const safeTitle = title?.replace(/[/\\]/g, "-").replace(/\p{Cc}/gu, "").trim();
671
+ return safeTitle ? `${safeTitle} - ${query.name}` : query.name;
672
+ }
673
+ function buildExportRequest(query, mappings, selection, context, options) {
674
+ const format2 = options.format ?? "csv";
675
+ const formatOptions = format2 === "csv" ? { bom: true, ...options.formatOptions } : options.formatOptions;
676
+ return {
677
+ ...buildQuery(query, mappings, selection, context),
678
+ format: format2,
679
+ ...formatOptions ? { formatOptions } : {},
680
+ filename: options.filename?.trim() || defaultExportFilename(query, context.title)
681
+ };
682
+ }
653
683
  async function runQuery(query, mappings, selection, context, signal) {
654
684
  const request = buildRequest(query, mappings, selection, context);
655
685
  const data = await context.backend.submitQuery(request, signal);
@@ -1204,6 +1234,14 @@ function toDataAppError(err, entity) {
1204
1234
  if (err instanceof DataAppError) return err;
1205
1235
  return new QueryError(err?.message ?? "The query failed.", entity, err);
1206
1236
  }
1237
+ function toExportError(err, entity) {
1238
+ if (err instanceof DataAppError && err.entity) return err;
1239
+ const message = err?.message || "The export failed.";
1240
+ if (err instanceof PermissionError) return new PermissionError(message, entity);
1241
+ if (err instanceof TransportError) return new TransportError(message, err.status, entity);
1242
+ if (err instanceof ValidationError) return new ValidationError(message, entity);
1243
+ return new QueryError(message, entity, err);
1244
+ }
1207
1245
  var App = class extends Observable {
1208
1246
  constructor(declaration, datasets, backend, features) {
1209
1247
  super();
@@ -1547,6 +1585,32 @@ var App = class extends Observable {
1547
1585
  if (query.controller === controller) query.controller = void 0;
1548
1586
  }
1549
1587
  }
1588
+ /**
1589
+ * @internal Backs `query.export()`. Built from the applied state, as `fetchPage` is, so the file
1590
+ * holds what the reader is looking at, every row of it. Touches nothing on the query.
1591
+ */
1592
+ async exportQuery(query, options = {}) {
1593
+ const { backend } = this;
1594
+ if (this.features?.export === false || !backend.exportQuery) {
1595
+ throw new TransportError("This host cannot make exports.", void 0, query.name);
1596
+ }
1597
+ const request = buildExportRequest(
1598
+ query,
1599
+ this.mappingsTo(query.name),
1600
+ {
1601
+ conditions: this.selectionConditionsFor(query.name, "applied"),
1602
+ expression: this.selectionExpressionFor(query.name, "applied")
1603
+ },
1604
+ { backend, timezone: this._timezone, title: this.title },
1605
+ options
1606
+ );
1607
+ try {
1608
+ return await backend.exportQuery(request, options.signal ?? new AbortController().signal);
1609
+ } catch (err) {
1610
+ if (isAbort(err)) throw err;
1611
+ throw toExportError(err, query.name);
1612
+ }
1613
+ }
1550
1614
  /* ----------------------------------------------------------------
1551
1615
  Serialisation
1552
1616
  ---------------------------------------------------------------- */
@@ -1661,7 +1725,7 @@ var App = class extends Observable {
1661
1725
  };
1662
1726
 
1663
1727
  // package.json
1664
- var version = "0.7.1";
1728
+ var version = "0.9.0";
1665
1729
 
1666
1730
  // src/app/sdk.ts
1667
1731
  var VERSION = version;
@@ -1683,7 +1747,13 @@ var Sdk = class {
1683
1747
  __publicField(this, "user");
1684
1748
  __publicField(this, "indices");
1685
1749
  __publicField(this, "backend");
1750
+ /**
1751
+ * What the host can do beyond queries. `export` says whether `query.export()` can work here, and
1752
+ * `render` whether `render()` can: show either's button only when it and
1753
+ * `user.permissions.canExportData` are both true. `lineage` says whether `lineage()` can.
1754
+ */
1686
1755
  __publicField(this, "features");
1756
+ __publicField(this, "renderHook");
1687
1757
  if (!environment?.datasets) {
1688
1758
  throw new ValidationError(
1689
1759
  "No datasets provided. The host must call createSdk({ datasets }) before an app can be declared."
@@ -1711,7 +1781,15 @@ var Sdk = class {
1711
1781
  ])
1712
1782
  );
1713
1783
  this.backend = environment.backend;
1714
- this.features = Object.freeze({ ...environment.features });
1784
+ this.renderHook = environment.render;
1785
+ this.features = Object.freeze({
1786
+ ...environment.features,
1787
+ // Known from the Backend itself when the host does not say. In a frame the bridge's Backend
1788
+ // has every method, so there it is the host's provision that says.
1789
+ export: environment.features?.export ?? typeof environment.backend.exportQuery === "function",
1790
+ render: environment.features?.render ?? typeof environment.render === "function",
1791
+ lineage: environment.features?.lineage ?? typeof environment.backend.lineage === "function"
1792
+ });
1715
1793
  }
1716
1794
  createApp(declaration = {}) {
1717
1795
  const app = new App(declaration, this.indices, this.backend, this.features);
@@ -1719,6 +1797,45 @@ var Sdk = class {
1719
1797
  this._apps.push(app);
1720
1798
  return app;
1721
1799
  }
1800
+ /**
1801
+ * Render the whole app, or one block or container of its structure by id, as a PNG or a PDF, and
1802
+ * have the host save it for the reader. What is drawn is what the page shows now: `await
1803
+ * app.execute()` first for fresh results. Elements marked `data-anfra-render="skip"` are left out.
1804
+ * Rejects with a `ValidationError` naming what to fix.
1805
+ */
1806
+ render(request) {
1807
+ if (!this.renderHook || this.features.render === false) {
1808
+ return Promise.reject(new ValidationError("This host does not render Data Apps: check Anfra.features.render first."));
1809
+ }
1810
+ return this.renderHook(request);
1811
+ }
1812
+ /**
1813
+ * Trace fields through the repo's catalog: what each one is built from (the fields, models and
1814
+ * sources upstream of it), as a diagram to draw. Name each field by its parent and its name in
1815
+ * it: `{ parent: 'orders', child: 'amount' }` for a model's field, `{ parent: 'ecommerce', child:
1816
+ * 'revenue' }` for a dataset's metric. Nothing needs ingesting first: the host builds the repo's
1817
+ * catalog when it has to. A field that cannot be traced answers its `error`, and the others still
1818
+ * answer; a host that cannot trace lineage (see `features.lineage`) rejects with a
1819
+ * `TransportError`.
1820
+ */
1821
+ lineage(targets, options = {}) {
1822
+ const list = Array.isArray(targets) ? [...targets] : [targets];
1823
+ const named = (s) => typeof s === "string" && s.trim() !== "";
1824
+ if (list.length === 0 || list.some((t) => typeof t !== "object" || t === null || !named(t.parent) || !named(t.child))) {
1825
+ return Promise.reject(new ValidationError(
1826
+ "Anfra.lineage() takes a target or an array of targets, each by its parent and its name in it, such as { parent: 'ecommerce', child: 'revenue' }."
1827
+ ));
1828
+ }
1829
+ if (!this.backend.lineage || this.features.lineage === false) {
1830
+ return Promise.reject(new TransportError("This host cannot trace lineage: check Anfra.features.lineage first."));
1831
+ }
1832
+ const { limit, offset, signal = new AbortController().signal } = options;
1833
+ return this.backend.lineage({
1834
+ targets: list.map(({ parent, child }) => ({ parent, child })),
1835
+ ...limit !== void 0 ? { limit } : {},
1836
+ ...offset !== void 0 ? { offset } : {}
1837
+ }, signal);
1838
+ }
1722
1839
  /**
1723
1840
  * Every app this instance has built, for a host rendering an inspection panel.
1724
1841
  *
@@ -1780,6 +1897,92 @@ function startPick(doc, handlers) {
1780
1897
  };
1781
1898
  }
1782
1899
 
1900
+ // src/render/types.ts
1901
+ var RENDERER_GLOBAL = "__anfraRenderer";
1902
+
1903
+ // src/app/render.ts
1904
+ var SKIP_ATTRIBUTE = "data-anfra-render";
1905
+ var EXTENSIONS = { png: "png", pdf: "pdf" };
1906
+ var SETTLE_MS = 1e4;
1907
+ function filenameFor(request, doc, apps, element) {
1908
+ const ext = EXTENSIONS[request.format];
1909
+ let name = request.filename?.trim();
1910
+ if (!name) {
1911
+ const title = apps.find((app) => app.title)?.title || doc.title.trim() || "Data App";
1912
+ const node = element && (element.getAttribute(ATTR.label) || request.block || request.container);
1913
+ name = node ? `${title} - ${node}` : title;
1914
+ }
1915
+ name = name.replace(/[/\\]/g, "-").replace(/\p{Cc}/gu, "").trim() || "Data App";
1916
+ return name.toLowerCase().endsWith(`.${ext}`) ? name : `${name}.${ext}`;
1917
+ }
1918
+ function targetOf(request, doc) {
1919
+ if (request.block !== void 0 && request.container !== void 0) {
1920
+ throw new ValidationError("Render a block or a container, not both.", request.block);
1921
+ }
1922
+ if (request.format !== "png" && request.format !== "pdf") {
1923
+ throw new ValidationError(`Can't render as '${String(request.format)}': the formats are 'png' and 'pdf'.`);
1924
+ }
1925
+ const { pixelRatio } = request;
1926
+ if (pixelRatio !== void 0 && !(Number.isFinite(pixelRatio) && pixelRatio > 0)) {
1927
+ throw new ValidationError(`pixelRatio ${String(pixelRatio)} is not a positive number.`);
1928
+ }
1929
+ const kind = request.block !== void 0 ? "block" : request.container !== void 0 ? "container" : void 0;
1930
+ if (!kind) return { element: null };
1931
+ const id = request.block ?? request.container;
1932
+ const element = [...doc.querySelectorAll(`[${ATTR[kind]}]`)].find((el) => el.getAttribute(ATTR[kind]) === id);
1933
+ if (!element) throw new ValidationError(`No element is marked ${ATTR[kind]}="${id}" on the page.`, id);
1934
+ return { element, entity: id };
1935
+ }
1936
+ function skip(element) {
1937
+ return element.id === OVERLAY_ID || element.getAttribute(SKIP_ATTRIBUTE) === "skip";
1938
+ }
1939
+ function createRender(win, deps) {
1940
+ let loading;
1941
+ const load = () => {
1942
+ const ready = win[RENDERER_GLOBAL];
1943
+ if (ready) return Promise.resolve(ready);
1944
+ loading ?? (loading = deps.ask.renderer().then((code) => {
1945
+ const script = win.document.createElement("script");
1946
+ script.textContent = code;
1947
+ (win.document.head ?? win.document.documentElement).appendChild(script);
1948
+ script.remove();
1949
+ const installed = win[RENDERER_GLOBAL];
1950
+ if (!installed) throw new ValidationError("The host sent a renderer that did not install.");
1951
+ return installed;
1952
+ }).catch((err) => {
1953
+ loading = void 0;
1954
+ throw err;
1955
+ }));
1956
+ return loading;
1957
+ };
1958
+ return async (request) => {
1959
+ const doc = win.document;
1960
+ const { element, entity } = targetOf(request ?? {}, doc);
1961
+ const filename = filenameFor(request, doc, deps.apps(), element);
1962
+ try {
1963
+ const renderer = await load();
1964
+ const drawing = await renderer.draw(element, { format: request.format, pixelRatio: request.pixelRatio, skip });
1965
+ await deps.ask.saveFile({ blob: drawing.blob, filename });
1966
+ return { filename, format: request.format, ...drawing };
1967
+ } catch (err) {
1968
+ if (err instanceof ValidationError && err.entity) throw err;
1969
+ throw new ValidationError(err?.message || "The rendering failed.", entity);
1970
+ }
1971
+ };
1972
+ }
1973
+ async function settle(win, apps, timeout = SETTLE_MS) {
1974
+ const busy = () => apps().some((app) => Object.values(app.queries).some((query) => query.state === "executing"));
1975
+ const deadline = Date.now() + timeout;
1976
+ while (busy() && Date.now() < deadline) {
1977
+ await new Promise((resolve) => {
1978
+ win.setTimeout(resolve, 100);
1979
+ });
1980
+ }
1981
+ await new Promise((resolve) => {
1982
+ win.requestAnimationFrame(() => resolve(void 0));
1983
+ });
1984
+ }
1985
+
1783
1986
  // src/app/bootstrap.ts
1784
1987
  function abortError() {
1785
1988
  const err = new Error("Aborted");
@@ -1792,6 +1995,8 @@ function toError(error) {
1792
1995
  return new PermissionError(error.message);
1793
1996
  case "TransportError":
1794
1997
  return new TransportError(error.message);
1998
+ case "ValidationError":
1999
+ return new ValidationError(error.message);
1795
2000
  default:
1796
2001
  return new QueryError(error?.message || "The query failed.");
1797
2002
  }
@@ -1829,6 +2034,14 @@ function bootstrap(win) {
1829
2034
  case "anfra:pick-watch":
1830
2035
  setPicking(message.on);
1831
2036
  return;
2037
+ case "anfra:render": {
2038
+ const { id } = message;
2039
+ settle(win, () => instance.apps).then(() => instance.render(message.request)).then(
2040
+ (result) => post({ type: "anfra:rendered", id, ok: true, result }),
2041
+ (err) => post({ type: "anfra:rendered", id, ok: false, error: { name: err?.name ?? "ValidationError", message: err?.message ?? "The rendering failed." } })
2042
+ );
2043
+ return;
2044
+ }
1832
2045
  default:
1833
2046
  }
1834
2047
  });
@@ -1853,9 +2066,29 @@ function bootstrap(win) {
1853
2066
  if (result.debug?.executedAt) result.debug.executedAt = new Date(result.debug.executedAt);
1854
2067
  return result;
1855
2068
  }),
1856
- fieldSuggestions: (request, signal) => call("fieldSuggestions", request, signal)
2069
+ fieldSuggestions: (request, signal) => call("fieldSuggestions", request, signal),
2070
+ exportQuery: (request, signal) => call("exportQuery", request, signal).then((result) => {
2071
+ result.expiresAt = new Date(result.expiresAt);
2072
+ return result;
2073
+ }),
2074
+ lineage: (request, signal) => call("lineage", request, signal)
1857
2075
  };
1858
- const instance = createSdk({ datasets: provision.datasets, user: provision.user, backend });
2076
+ const render = createRender(win, {
2077
+ ask: {
2078
+ renderer: () => call("renderer", null, new AbortController().signal),
2079
+ saveFile: (request) => call("saveFile", request, new AbortController().signal)
2080
+ },
2081
+ apps: () => instance.apps
2082
+ });
2083
+ const instance = createSdk({
2084
+ datasets: provision.datasets,
2085
+ user: provision.user,
2086
+ backend,
2087
+ render,
2088
+ // A host older than `features` provisions none: say it can neither export, render nor trace,
2089
+ // rather than let the bridge's Backend, which has every method, claim them.
2090
+ features: { export: false, render: false, lineage: false, ...provision.features }
2091
+ });
1859
2092
  const doc = win.document;
1860
2093
  let structure;
1861
2094
  let lastStructureJson = "";
@@ -1,4 +1,4 @@
1
- import { g as BackendQueryRequest, u as FieldSuggestionsRequest, I as InspectedApp, J as InspectedStructure, M as LocateTarget, D as DatasetDescriptor, a2 as User } from './types-BlzJVcUl.js';
1
+ import { i as BackendQueryRequest, H as FieldSuggestionsRequest, h as BackendLineageRequest, f as BackendExportRequest, a8 as Rendering, L as InspectedApp, Q as InspectedStructure, Z as LocateTarget, a7 as RenderRequest, D as DatasetDescriptor, ai as User, ab as SdkFeatures } from './types-DznT0m7F.js';
2
2
 
3
3
  /**
4
4
  * The bridge: the postMessage protocol between a Data App's frame (`app`'s bootstrap) and the
@@ -6,12 +6,22 @@ import { g as BackendQueryRequest, u as FieldSuggestionsRequest, I as InspectedA
6
6
  * makes to its Backend crosses here, and the host answers it.
7
7
  */
8
8
 
9
- /** The Backend methods a frame may call: the bridge serves these and nothing else. */
10
- type BridgeMethod = 'submitQuery' | 'fieldSuggestions';
9
+ /**
10
+ * What a frame may ask its host: the Backend's methods, and the two a rendering needs (the
11
+ * renderer's code, and saving a file). The bridge serves these and nothing else.
12
+ */
13
+ type BridgeMethod = 'submitQuery' | 'fieldSuggestions' | 'exportQuery' | 'lineage' | 'renderer' | 'saveFile';
14
+ /** A file the frame made, for the host to save for the reader: the frame cannot download. */
15
+ interface SaveFileRequest {
16
+ blob: Blob;
17
+ filename: string;
18
+ }
11
19
  /** What the host provisions a frame with, as JSON in `<script type="application/json" id="anfra-provision">`. */
12
20
  interface Provision {
13
21
  datasets: Record<string, DatasetDescriptor>;
14
22
  user: User;
23
+ /** What the host can do beyond queries: exports, rendering. Absent from a host older than this field. */
24
+ features?: SdkFeatures;
15
25
  /** The host page's origin: where the frame posts, so nothing else can read its messages. */
16
26
  hostOrigin: string;
17
27
  }
@@ -29,6 +39,42 @@ type FrameMessage = {
29
39
  id: number;
30
40
  method: 'fieldSuggestions';
31
41
  request: FieldSuggestionsRequest;
42
+ } | {
43
+ type: 'anfra:request';
44
+ id: number;
45
+ method: 'lineage';
46
+ request: BackendLineageRequest;
47
+ }
48
+ /** The host makes the file, starts saving it for the reader, then answers its link. */
49
+ | {
50
+ type: 'anfra:request';
51
+ id: number;
52
+ method: 'exportQuery';
53
+ request: BackendExportRequest;
54
+ }
55
+ /** The renderer's code, asked for on the frame's first rendering; answered as a string. */
56
+ | {
57
+ type: 'anfra:request';
58
+ id: number;
59
+ method: 'renderer';
60
+ request: null;
61
+ } | {
62
+ type: 'anfra:request';
63
+ id: number;
64
+ method: 'saveFile';
65
+ request: SaveFileRequest;
66
+ }
67
+ /** The answer to the host's `anfra:render`, by its id. */
68
+ | {
69
+ type: 'anfra:rendered';
70
+ id: number;
71
+ ok: true;
72
+ result: Rendering;
73
+ } | {
74
+ type: 'anfra:rendered';
75
+ id: number;
76
+ ok: false;
77
+ error: BridgeError;
32
78
  } | {
33
79
  type: 'anfra:cancel';
34
80
  id: number;
@@ -76,6 +122,12 @@ type HostMessage = {
76
122
  | {
77
123
  type: 'anfra:pick-watch';
78
124
  on: boolean;
125
+ }
126
+ /** Render the app or one node, once its queries settle, and save it; the frame answers `anfra:rendered`. */
127
+ | {
128
+ type: 'anfra:render';
129
+ id: number;
130
+ request: RenderRequest;
79
131
  };
80
132
 
81
133
  export { type BridgeError as B, type FrameMessage as F, type HostMessage as H, PROVISION_ELEMENT_ID as P, type BridgeMethod as a, type Provision as b };
@@ -1,6 +1,6 @@
1
- import {
2
- __publicField
3
- } from "./chunk-PKBMQBKP.js";
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
4
 
5
5
  // src/common/errors.ts
6
6
  var DataAppError = class extends Error {
@@ -33,6 +33,7 @@ var TransportError = class extends DataAppError {
33
33
  };
34
34
 
35
35
  export {
36
+ __publicField,
36
37
  DataAppError,
37
38
  ValidationError,
38
39
  QueryError,
package/dist/common.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { D as DataAppError, P as PermissionError, Q as QueryError, T as TransportError, V as ValidationError } from './errors-CKvqVaqU.js';
2
- export { A as Aggregation, a as AppDeclaration, b as AppJson, c as ArrowType, B as Backend, d as BackendCondition, e as BackendDateDrill, f as BackendFilter, g as BackendQueryRequest, h as BackendQueryResult, i as BackendSort, C as ColumnMeta, j as Condition, k as ConditionValue, l as ControlMappingJson, m as CrossFilterJson, D as DatasetDescriptor, n as DateDrillDeclaration, o as DateGrain, p as DateTransformation, E as EntityKind, q as EntityRef, r as EntityUsage, s as ExecuteOptions, t as ExecuteSummary, F as FILTER_AGGREGATIONS, u as FieldSuggestionsRequest, v as FilterAggregation, w as FilterDeclaration, x as FilterValueType, I as InspectedApp, y as InspectedControl, z as InspectedError, G as InspectedQuery, H as InspectedSelection, J as InspectedStructure, L as Listener, K as LocateKind, M as LocateTarget, N as MappingJson, O as Operator, Q as QueryDebug, P as QueryDeclaration, R as QueryInput, S as QueryResult, T as QuerySort, U as QueryState, V as Row, W as SdkEnvironment, X as SdkFeatures, Y as Selection, Z as SelectionCondition, _ as SemanticType, $ as StructureKind, a0 as StructureNode, a1 as Unsubscribe, a2 as User } from './types-BlzJVcUl.js';
3
- export { B as BridgeError, a as BridgeMethod, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as Provision } from './bridge-BKx7u5mX.js';
2
+ export { A as Aggregation, a as AppDeclaration, b as AppJson, c as ArrowType, B as Backend, d as BackendCondition, e as BackendDateDrill, f as BackendExportRequest, g as BackendFilter, h as BackendLineageRequest, i as BackendQueryRequest, j as BackendQueryResult, k as BackendSort, C as ColumnMeta, l as Condition, m as ConditionValue, n as ControlMappingJson, o as CrossFilterJson, D as DatasetDescriptor, p as DateDrillDeclaration, q as DateGrain, r as DateTransformation, E as EntityKind, s as EntityRef, t as EntityUsage, u as ExecuteOptions, v as ExecuteSummary, w as ExportFormat, x as ExportFormatOptions, y as ExportOptions, z as ExportResult, F as FILTER_AGGREGATIONS, G as FieldLineage, H as FieldSuggestionsRequest, I as FilterAggregation, J as FilterDeclaration, K as FilterValueType, L as InspectedApp, M as InspectedControl, N as InspectedError, O as InspectedQuery, P as InspectedSelection, Q as InspectedStructure, R as LineageCard, S as LineageDiagram, T as LineageNode, U as LineageOptions, V as LineageResult, W as LineageTarget, X as Listener, Y as LocateKind, Z as LocateTarget, _ as MappingJson, $ as Operator, a0 as QueryDebug, a1 as QueryDeclaration, a2 as QueryInput, a3 as QueryResult, a4 as QuerySort, a5 as QueryState, a6 as RenderFormat, a7 as RenderRequest, a8 as Rendering, a9 as Row, aa as SdkEnvironment, ab as SdkFeatures, ac as Selection, ad as SelectionCondition, ae as SemanticType, af as StructureKind, ag as StructureNode, ah as Unsubscribe, ai as User } from './types-DznT0m7F.js';
3
+ export { B as BridgeError, a as BridgeMethod, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as Provision } from './bridge-DUKdREoK.js';
package/dist/common.js CHANGED
@@ -10,8 +10,7 @@ import {
10
10
  QueryError,
11
11
  TransportError,
12
12
  ValidationError
13
- } from "./chunk-KCTLO3CO.js";
14
- import "./chunk-PKBMQBKP.js";
13
+ } from "./chunk-KBXITYQK.js";
15
14
  export {
16
15
  DataAppError,
17
16
  FILTER_AGGREGATIONS,