@holistics/anfra-sdk 0.8.0 → 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
@@ -81,7 +81,7 @@ function toColumns(columns) {
81
81
  return { ...column, semantic_type: semanticType, arrow_type: arrowType, db_type: dbType };
82
82
  });
83
83
  }
84
- async function answer(call) {
84
+ async function callCoreAPI(call) {
85
85
  let result;
86
86
  try {
87
87
  result = await call();
@@ -94,7 +94,7 @@ async function answer(call) {
94
94
  return data;
95
95
  }
96
96
  function runQuery(client, body, signal) {
97
- return answer(() => client.POST("/core.query", { body, signal }));
97
+ return callCoreAPI(() => client.POST("/core.query", { body, signal }));
98
98
  }
99
99
  function coreApiBackend(base, options = {}) {
100
100
  const client = typeof base === "string" ? coreClient(base) : base;
@@ -144,7 +144,7 @@ function coreApiBackend(base, options = {}) {
144
144
  },
145
145
  /** An export as `core.query.export`: the server runs the query to completion, then answers its link. */
146
146
  async exportQuery(request, signal) {
147
- const link = await answer(() => client.POST("/core.query.export", { body: toExportInput(request), signal }));
147
+ const link = await callCoreAPI(() => client.POST("/core.query.export", { body: toExportInput(request), signal }));
148
148
  return {
149
149
  url: link.url,
150
150
  filename: link.filename,
@@ -152,6 +152,10 @@ function coreApiBackend(base, options = {}) {
152
152
  rowCount: link.row_count,
153
153
  expiresAt: new Date(link.expires_at)
154
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 }));
155
159
  }
156
160
  };
157
161
  }
package/dist/app.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { P as Listener, a9 as Unsubscribe, D as DatasetDescriptor, E as EntityKind, k as Condition, H as FilterDeclaration, I as FilterValueType, B as Backend, l as ConditionValue, o as DateDrillDeclaration, p as DateGrain, G as FilterAggregation, m as ControlMappingJson, n as CrossFilterJson, a3 as SdkFeatures, a4 as Selection, a5 as SelectionCondition, a1 as Row, x as ExportOptions, y as ExportResult, Q as LocateKind, V as QueryDeclaration, Z as QueryState, X as QueryResult, Y as QuerySort, a as AppDeclaration, t as ExecuteOptions, u as ExecuteSummary, b as AppJson, J as InspectedApp, aa as User, a2 as SdkEnvironment, $ as RenderRequest, a0 as Rendering, O as InspectedStructure } from './types-IR4TNw-M.js';
2
- export { A as Aggregation, c as ArrowType, d as BackendCondition, e as BackendDateDrill, f as BackendExportRequest, g as BackendFilter, h as BackendQueryRequest, i as BackendQueryResult, j as BackendSort, C as ColumnMeta, q as DateTransformation, r as EntityRef, s as EntityUsage, v as ExportFormat, w as ExportFormatOptions, F as FILTER_AGGREGATIONS, z as FieldSuggestionsRequest, K as InspectedControl, L as InspectedError, M as InspectedQuery, N as InspectedSelection, R as LocateTarget, S as MappingJson, T as Operator, U as QueryDebug, W as QueryInput, _ as RenderFormat, a6 as SemanticType, a7 as StructureKind, a8 as StructureNode } from './types-IR4TNw-M.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-BmbS9J4V.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;
@@ -472,7 +472,7 @@ declare class Sdk {
472
472
  /**
473
473
  * What the host can do beyond queries. `export` says whether `query.export()` can work here, and
474
474
  * `render` whether `render()` can: show either's button only when it and
475
- * `user.permissions.canExportData` are both true.
475
+ * `user.permissions.canExportData` are both true. `lineage` says whether `lineage()` can.
476
476
  */
477
477
  readonly features: Readonly<SdkFeatures>;
478
478
  private readonly renderHook?;
@@ -485,6 +485,16 @@ declare class Sdk {
485
485
  * Rejects with a `ValidationError` naming what to fix.
486
486
  */
487
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>;
488
498
  /**
489
499
  * Every app this instance has built, for a host rendering an inspection panel.
490
500
  *
@@ -555,4 +565,4 @@ declare function buildStructure(doc: Document, apps: readonly App[]): BuiltStruc
555
565
  /** Provision the SDK in `win` from its host, and install it. Returns once `Anfra` exists. */
556
566
  declare function bootstrap(win: Window): void;
557
567
 
558
- 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, 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 };
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
@@ -1725,7 +1725,7 @@ var App = class extends Observable {
1725
1725
  };
1726
1726
 
1727
1727
  // package.json
1728
- var version = "0.8.0";
1728
+ var version = "0.9.0";
1729
1729
 
1730
1730
  // src/app/sdk.ts
1731
1731
  var VERSION = version;
@@ -1750,7 +1750,7 @@ var Sdk = class {
1750
1750
  /**
1751
1751
  * What the host can do beyond queries. `export` says whether `query.export()` can work here, and
1752
1752
  * `render` whether `render()` can: show either's button only when it and
1753
- * `user.permissions.canExportData` are both true.
1753
+ * `user.permissions.canExportData` are both true. `lineage` says whether `lineage()` can.
1754
1754
  */
1755
1755
  __publicField(this, "features");
1756
1756
  __publicField(this, "renderHook");
@@ -1787,7 +1787,8 @@ var Sdk = class {
1787
1787
  // Known from the Backend itself when the host does not say. In a frame the bridge's Backend
1788
1788
  // has every method, so there it is the host's provision that says.
1789
1789
  export: environment.features?.export ?? typeof environment.backend.exportQuery === "function",
1790
- render: environment.features?.render ?? typeof environment.render === "function"
1790
+ render: environment.features?.render ?? typeof environment.render === "function",
1791
+ lineage: environment.features?.lineage ?? typeof environment.backend.lineage === "function"
1791
1792
  });
1792
1793
  }
1793
1794
  createApp(declaration = {}) {
@@ -1808,6 +1809,33 @@ var Sdk = class {
1808
1809
  }
1809
1810
  return this.renderHook(request);
1810
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
+ }
1811
1839
  /**
1812
1840
  * Every app this instance has built, for a host rendering an inspection panel.
1813
1841
  *
@@ -2042,7 +2070,8 @@ function bootstrap(win) {
2042
2070
  exportQuery: (request, signal) => call("exportQuery", request, signal).then((result) => {
2043
2071
  result.expiresAt = new Date(result.expiresAt);
2044
2072
  return result;
2045
- })
2073
+ }),
2074
+ lineage: (request, signal) => call("lineage", request, signal)
2046
2075
  };
2047
2076
  const render = createRender(win, {
2048
2077
  ask: {
@@ -2056,9 +2085,9 @@ function bootstrap(win) {
2056
2085
  user: provision.user,
2057
2086
  backend,
2058
2087
  render,
2059
- // A host older than `features` provisions none: say it can neither export nor render, rather
2060
- // than let the bridge's Backend, which has every method, claim an export.
2061
- features: { export: false, render: false, ...provision.features }
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 }
2062
2091
  });
2063
2092
  const doc = win.document;
2064
2093
  let structure;
@@ -1,4 +1,4 @@
1
- import { h as BackendQueryRequest, z as FieldSuggestionsRequest, f as BackendExportRequest, a0 as Rendering, J as InspectedApp, O as InspectedStructure, R as LocateTarget, $ as RenderRequest, D as DatasetDescriptor, aa as User, a3 as SdkFeatures } from './types-IR4TNw-M.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
@@ -10,7 +10,7 @@ import { h as BackendQueryRequest, z as FieldSuggestionsRequest, f as BackendExp
10
10
  * What a frame may ask its host: the Backend's methods, and the two a rendering needs (the
11
11
  * renderer's code, and saving a file). The bridge serves these and nothing else.
12
12
  */
13
- type BridgeMethod = 'submitQuery' | 'fieldSuggestions' | 'exportQuery' | 'renderer' | 'saveFile';
13
+ type BridgeMethod = 'submitQuery' | 'fieldSuggestions' | 'exportQuery' | 'lineage' | 'renderer' | 'saveFile';
14
14
  /** A file the frame made, for the host to save for the reader: the frame cannot download. */
15
15
  interface SaveFileRequest {
16
16
  blob: Blob;
@@ -39,6 +39,11 @@ type FrameMessage = {
39
39
  id: number;
40
40
  method: 'fieldSuggestions';
41
41
  request: FieldSuggestionsRequest;
42
+ } | {
43
+ type: 'anfra:request';
44
+ id: number;
45
+ method: 'lineage';
46
+ request: BackendLineageRequest;
42
47
  }
43
48
  /** The host makes the file, starts saving it for the reader, then answers its link. */
44
49
  | {
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 BackendExportRequest, g as BackendFilter, h as BackendQueryRequest, i as BackendQueryResult, j as BackendSort, C as ColumnMeta, k as Condition, l as ConditionValue, m as ControlMappingJson, n as CrossFilterJson, D as DatasetDescriptor, o as DateDrillDeclaration, p as DateGrain, q as DateTransformation, E as EntityKind, r as EntityRef, s as EntityUsage, t as ExecuteOptions, u as ExecuteSummary, v as ExportFormat, w as ExportFormatOptions, x as ExportOptions, y as ExportResult, F as FILTER_AGGREGATIONS, z as FieldSuggestionsRequest, G as FilterAggregation, H as FilterDeclaration, I as FilterValueType, J as InspectedApp, K as InspectedControl, L as InspectedError, M as InspectedQuery, N as InspectedSelection, O as InspectedStructure, P as Listener, Q as LocateKind, R as LocateTarget, S as MappingJson, T as Operator, U as QueryDebug, V as QueryDeclaration, W as QueryInput, X as QueryResult, Y as QuerySort, Z as QueryState, _ as RenderFormat, $ as RenderRequest, a0 as Rendering, a1 as Row, a2 as SdkEnvironment, a3 as SdkFeatures, a4 as Selection, a5 as SelectionCondition, a6 as SemanticType, a7 as StructureKind, a8 as StructureNode, a9 as Unsubscribe, aa as User } from './types-IR4TNw-M.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-BmbS9J4V.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/host.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { J as InspectedApp, O as InspectedStructure, R as LocateTarget, $ as RenderRequest, a0 as Rendering, B as Backend, D as DatasetDescriptor, aa as User } from './types-IR4TNw-M.js';
2
- import { b as Provision } from './bridge-BmbS9J4V.js';
1
+ import { L as InspectedApp, Q as InspectedStructure, Z as LocateTarget, a7 as RenderRequest, a8 as Rendering, B as Backend, D as DatasetDescriptor, ai as User } from './types-DznT0m7F.js';
2
+ import { b as Provision } from './bridge-DUKdREoK.js';
3
3
 
4
4
  interface BridgeHandle {
5
5
  /** Ask the frame to post (or stop posting) inspection snapshots; survives the frame reloading. */
package/dist/host.js CHANGED
@@ -66,6 +66,42 @@ function serveBridge(frame, backend, callbacks = {}, options = {}) {
66
66
  const win = frame.ownerDocument.defaultView ?? window;
67
67
  const reply = (message) => frame.contentWindow?.postMessage(message, "*");
68
68
  const sendWatch = () => reply({ type: "anfra:inspect-watch", open: inspecting });
69
+ const save = async (request) => {
70
+ const now = Date.now();
71
+ while (saves.length && now - saves[0] >= SAVE_WINDOW_MS) saves.shift();
72
+ if (saving || saves.length >= SAVES_PER_WINDOW) {
73
+ throw new ValidationError("Too many files saved at once: try again in a few seconds.");
74
+ }
75
+ saving = true;
76
+ saves.push(now);
77
+ try {
78
+ await saveBlob(frame.ownerDocument, request);
79
+ } finally {
80
+ saving = false;
81
+ }
82
+ return null;
83
+ };
84
+ const answer = async (message, signal) => {
85
+ switch (message.method) {
86
+ case "submitQuery":
87
+ return backend.submitQuery(message.request, signal);
88
+ case "fieldSuggestions":
89
+ return backend.fieldSuggestions(message.request, signal);
90
+ case "exportQuery":
91
+ return exportAndSave(backend, frame.ownerDocument, message.request, signal);
92
+ case "lineage":
93
+ if (!backend.lineage) throw new TransportError("This host cannot trace lineage.");
94
+ return backend.lineage(message.request, signal);
95
+ case "renderer":
96
+ if (!rendering) throw new ValidationError(RENDERING_OFF);
97
+ return options.renderer;
98
+ case "saveFile":
99
+ if (!rendering) throw new ValidationError(RENDERING_OFF);
100
+ return save(message.request);
101
+ default:
102
+ throw new Error(`No such Backend method: ${String(message.method)}`);
103
+ }
104
+ };
69
105
  const onMessage = (event) => {
70
106
  if (event.source !== frame.contentWindow) return;
71
107
  const message = event.data;
@@ -97,24 +133,7 @@ function serveBridge(frame, backend, callbacks = {}, options = {}) {
97
133
  const { id } = message;
98
134
  const controller = new AbortController();
99
135
  inFlight.set(id, controller);
100
- const result = message.method === "submitQuery" ? backend.submitQuery(message.request, controller.signal) : message.method === "fieldSuggestions" ? backend.fieldSuggestions(message.request, controller.signal) : message.method === "exportQuery" ? exportAndSave(backend, frame.ownerDocument, message.request, controller.signal) : message.method === "renderer" || message.method === "saveFile" ? (async () => {
101
- if (!rendering) throw new ValidationError(RENDERING_OFF);
102
- if (message.method === "renderer") return options.renderer;
103
- const now = Date.now();
104
- while (saves.length && now - saves[0] >= SAVE_WINDOW_MS) saves.shift();
105
- if (saving || saves.length >= SAVES_PER_WINDOW) {
106
- throw new ValidationError("Too many files saved at once: try again in a few seconds.");
107
- }
108
- saving = true;
109
- saves.push(now);
110
- try {
111
- await saveBlob(frame.ownerDocument, message.request);
112
- } finally {
113
- saving = false;
114
- }
115
- return null;
116
- })() : Promise.reject(new Error(`No such Backend method: ${String(message.method)}`));
117
- result.then((value) => reply({ type: "anfra:response", id, ok: true, result: value })).catch((err) => {
136
+ answer(message, controller.signal).then((value) => reply({ type: "anfra:response", id, ok: true, result: value })).catch((err) => {
118
137
  if (err?.name === "AbortError") return;
119
138
  reply({ type: "anfra:response", id, ok: false, error: toBridgeError(err) });
120
139
  }).finally(() => inFlight.delete(id));
@@ -157,7 +176,7 @@ function serveBridge(frame, backend, callbacks = {}, options = {}) {
157
176
  }
158
177
 
159
178
  // frame-script:anfra-sdk:frame-script
160
- var anfra_sdk_frame_script_default = '"use strict";(()=>{var De=Object.defineProperty;var ct=(t,n,e)=>n in t?De(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var o=(t,n)=>De(t,"name",{value:n,configurable:!0});var c=(t,n,e)=>ct(t,typeof n!="symbol"?n+"":n,e);var ne=class ne extends Error{constructor(e,r){super(e);c(this,"entity");this.name=new.target.name,this.entity=r,Object.setPrototypeOf(this,new.target.prototype)}};o(ne,"DataAppError");var $=ne,re=class re extends ${};o(re,"ValidationError");var u=re,ie=class ie extends ${constructor(e,r,i){super(e,r);c(this,"cause");this.cause=i}};o(ie,"QueryError");var N=ie,oe=class oe extends ${};o(oe,"PermissionError");var I=oe,se=class se extends ${constructor(e,r,i){super(e,i);c(this,"status");this.status=r}};o(se,"TransportError");var O=se;var _e="anfra-provision";var ae=class ae{constructor(n){c(this,"listeners",new Set);c(this,"parent");this.parent=n}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}notifyChange(){this.listeners.forEach(n=>n()),this.parent?.notifyChange()}notify(){this.notifyChange()}};o(ae,"Observable");var F=ae;var le=class le extends F{constructor(e,r,i){super(r);c(this,"kind","query");c(this,"name");c(this,"declaration");c(this,"dataset");c(this,"app");c(this,"_state","idle");c(this,"_result");c(this,"_error");c(this,"_page",1);c(this,"_sort",[]);c(this,"lastRunSignature");c(this,"lastPageRows",0);c(this,"controller");if(!i.aql?.trim())throw new u(`Query \'${e}\' declares no AQL.`,e);let{pageSize:s}=i;if(s!==void 0&&!(Number.isInteger(s)&&s>=1))throw new u(`Query \'${e}\' declares pageSize ${s}; it must be a whole number of at least 1.`,e);this.name=e,this.app=r,this.declaration=i,this.dataset=r.datasetIndex(i.dataset,e)}locate(){return this.app.locate("query",this.name)}get state(){return this._state}get result(){return this._result}get error(){return this._error}get pageSize(){return this.declaration.pageSize}get page(){return this._page}get sort(){return this._sort}setSort(e){this._sort=[...e],this.notify()}get hasMore(){return!this._result||this.pageSize===void 0?!1:this.lastPageRows>=this.pageSize}signature(){let e=this.app.mappingsTo(this.name).map(r=>({field:r.field,aggregation:r.aggregation,condition:r.from.condition})).sort((r,i)=>r.field.localeCompare(i.field)||JSON.stringify(r).localeCompare(JSON.stringify(i)));return JSON.stringify({declaration:this.declaration,conditions:e,selection:this.app.selectionConditionsFor(this.name,"pending"),selectionExpression:this.app.selectionExpressionFor(this.name,"pending"),sort:this._sort,timezone:this.app.timezone,page:this._page})}get isDirty(){return this.lastRunSignature!==void 0&&this.signature()!==this.lastRunSignature}shouldRun(e=!1){return e||this.lastRunSignature===void 0||this.isDirty}abort(){this.controller?.abort()}async fetchMore(){if(this.pageSize===void 0)throw new u(`Query \'${this.name}\' declares no pageSize, so it has no more pages.`,this.name);this.hasMore&&(this._page+=1,await this.app.fetchPage(this))}export(e={}){return this.app.exportQuery(this,e)}select(e,r={}){this.app.select(this,Array.isArray(e)?e:[e],r.fields)}get selectedRows(){let{selection:e}=this.app;if(e?.source!==this.name)return[];let r=this._result?.rows;if(!r)return e.rows;let i=o(a=>JSON.stringify(e.fields.map(l=>a[l]??null)),"key"),s=new Set(e.rows.map(i));return r.filter(a=>s.has(i(a)))}markExecuting(){this._state="executing",this._error=void 0,this.notify()}markSuccess(e,r,i){if(this._state="success",this._error=void 0,this.lastRunSignature=r,this.lastPageRows=e.rows.length,i&&this._result){let s=[...this._result.rows,...e.rows];this._result={...e,rows:s,meta:{...e.meta,numRows:s.length}}}else this._result=e;this.notify()}markError(e){this._state="error",this._error=e,this.notify()}rewindPage(){this._page>1&&(this._page-=1)}resetPage(){this._page=1,this.lastPageRows=0}toJSON(){return this.declaration}};o(le,"Query");var M=le;var $e=["year","quarter","month","week","day","hour","minute"];function ut(t,n){if(!$e.includes(n))throw new u(`Invalid grain \'${n}\'. Expected one of: ${$e.join(", ")}.`,t)}o(ut,"assertGrain");function Oe(t,n){return n?(ut(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}o(Oe,"drillCondition");function pt(t){let n=t.toLowerCase();return n.includes("date")||n.includes("time")?"date":n.includes("int")||n.includes("number")||n.includes("float")||n.includes("decimal")?"number":n.includes("bool")?"boolean":"string"}o(pt,"inferType");function ft(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}o(ft,"sameCondition");var de=class de extends F{constructor(e,r,i){super(r);c(this,"name");c(this,"app");c(this,"pending");c(this,"applied");c(this,"initial");this.name=e,this.app=r,this.initial=i,this.pending=i}locate(){return this.app.locate("control",this.name)}get condition(){return this.pending}get appliedCondition(){return this.applied}get isDirty(){return this.applied!==void 0&&!ft(this.pending,this.applied)}setCondition(e){this.pending=e,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};o(de,"Control");var L=de,ce=class ce extends L{constructor(e,r,i,s,a){super(e,r,i.default??{operator:"is",values:[]});c(this,"kind","filter");c(this,"declaration");c(this,"type");c(this,"resolved");c(this,"datasetName");c(this,"backend");c(this,"loadedOptions");if(this.declaration=i,this.backend=a,i.field){if(!s)throw new u(`Filter \'${e}\' names a field but no dataset. Pass \\`dataset\\` alongside \\`field\\`.`,e);this.resolved=s.resolve(i.field,e),this.datasetName=s.descriptor.name,this.type=i.type??pt(this.resolved.type)}else{if(!i.type)throw new u(`Filter \'${e}\' is a manual filter, so it needs a \\`type\\`.`,e);this.type=i.type}this.assertValues(this.condition.values??[]),this.assertValues(i.options??[])}setCondition(e){this.assertValues(e.values??[]),super.setCondition(e)}assertValues(e){if(this.type!=="number")return;let r=e.find(i=>typeof i=="number");if(r!==void 0)throw new u(`Filter \'${this.name}\' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(r))}, not ${String(r)}), so none has lost a digit.`,this.name)}get isFieldBacked(){return this.resolved!==void 0}get options(){return this.loadedOptions??this.declaration.options??[]}async loadOptions(e,r=new AbortController().signal){let i=this.resolved?.modelName;if(!this.resolved||!i||!this.backend||!this.datasetName)return this.options;let s=await this.backend.fieldSuggestions({dataset:this.datasetName,model:i,field:this.resolved.fieldName,q:e??""},r);return this.loadedOptions=[...s??[]],this.notify(),this.loadedOptions}toJSON(){return this.declaration}};o(ce,"Filter");var G=ce,ue=class ue extends L{constructor(e,r,i={}){super(e,r,Oe(e,i.default));c(this,"kind","dateDrill");c(this,"declaration");this.declaration=i}setGrain(e){this.setCondition(Oe(this.name,e))}toJSON(){return this.declaration}};o(ue,"DateDrillControl");var U=ue;var pe=class pe{constructor(n,e,r,i){c(this,"kind","control");c(this,"from");c(this,"to");c(this,"field");c(this,"aggregation");this.from=n,this.to=e,this.field=r,this.aggregation=i}get id(){return`${this.from.name}.${this.to.name}.${this.field}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:this.from.kind,name:this.from.name},to:{kind:"query",name:this.to.name},field:this.field,...this.aggregation?{aggregation:this.aggregation}:{}}}};o(pe,"Mapping");var H=pe,fe=class fe{constructor(n,e){c(this,"kind","crossFilter");c(this,"from");c(this,"to");this.from=n,this.to=e}get id(){return`${this.from.name}.${this.to.name}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:"query",name:this.from.name},to:{kind:"query",name:this.to.name}}}};o(fe,"CrossFilter");var K=fe;var me=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function mt(t,n){let e=t.length+1,r=n.length+1,i=Array.from({length:r},(s,a)=>a);for(let s=1;s<e;s++){let a=[s];for(let l=1;l<r;l++)a[l]=Math.min(i[l]+1,a[l-1]+1,i[l-1]+(t[s-1]===n[l-1]?0:1));i=a}return i[r-1]}o(mt,"editDistance");function ht(t,n){let e,r=1/0;n.forEach(s=>{let a=mt(t.toLowerCase(),s.toLowerCase());a<r&&(r=a,e=s)});let i=Math.max(2,Math.floor(t.length/3));return r<=i?e:void 0}o(ht,"suggest");function P(t,n,e){let r=ht(n,e);return r?`${t} Did you mean \'${r}\'?`:t}o(P,"withSuggestion");var he=class he{constructor(n){c(this,"descriptor");c(this,"fields",new Map);c(this,"references");this.descriptor=n,n.data_models.forEach(e=>{e.fields.forEach(r=>{let i=String(e.name);this.fields.set(`${i}.${r.name}`,{modelName:i,fieldName:r.name,isMetric:!1,type:r.type,label:r.label??r.name})})}),n.metrics.forEach(e=>{this.fields.set(e.name,{fieldName:e.name,isMetric:!0,type:e.type,label:e.label??e.name})}),this.references=[...this.fields.keys()]}resolve(n,e){let r=this.fields.get(n);if(r)return r;throw new u(P(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};o(he,"DatasetIndex");var W=he;function Fe(t,n,e){let r=t[n];if(r)return r;throw new u(P(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}o(Fe,"resolveDataset");function Te(t,n){if(!me.includes(t))throw new u(P(`Invalid filter aggregation \'${t}\'.`,t,[...me]),n)}o(Te,"assertValidFilterAggregation");function Ne(t,n,e){if(!n)throw new u(`A ${e} needs a name.`);for(let r of t)if(r===n)throw new u(`\'${n}\' is already declared in this app.`,n)}o(Ne,"assertUniqueName");function gt(t,n){if(!(!n||n.operator==="none"||n.operator==="transform_date_drill"||!["is_null","not_null","is_true","is_false","transform_pop_none"].includes(n.operator)&&!n.values?.length))return{field:t.field,operator:n.operator,values:n.values??[],...n.modifier?{modifier:n.modifier}:{},...t.aggregation?{aggregation:t.aggregation}:{}}}o(gt,"toFilter");function yt(t,n){if(n?.operator!=="transform_date_drill")return;let e=n.values?.[0];if(typeof e!="string")return;let r=e.replace(/^datetrunc\\s+/,"");return{field:t.field,grain:r}}o(yt,"toDateDrill");function bt(t,n){let e=n.columns??[],r=(n.values??[]).map(s=>{let a={};return e.forEach((l,d)=>{a[l.name]=s[d]}),a}),{pageSize:i}=t;return{columns:e,rows:r,meta:{...i!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??i}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}o(bt,"toResult");function Ie(t,n,e,r){let i=n.map(d=>gt(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=n.map(d=>yt(d,d.from.appliedCondition)).filter(d=>d!==void 0),a=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),l=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...i,...a],conditions:l,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:s},...r.timezone?{timezone:r.timezone}:{}}}o(Ie,"buildQuery");function wt(t,n,e,r){return{...Ie(t,n,e,r),...t.pageSize!==void 0?{page:t.page,pageSize:t.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}o(wt,"buildRequest");function kt(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}o(kt,"defaultExportFilename");function Qe(t,n,e,r,i){let s=i.format??"csv",a=s==="csv"?{bom:!0,...i.formatOptions}:i.formatOptions;return{...Ie(t,n,e,r),format:s,...a?{formatOptions:a}:{},filename:i.filename?.trim()||kt(t,r.title)}}o(Qe,"buildExportRequest");async function ge(t,n,e,r,i){let s=wt(t,n,e,r),a=await r.backend.submitQuery(s,i);return bt(t,a)}o(ge,"runQuery");function xt(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return Et(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError(`Cannot express ${t} in AQL.`);return Math.abs(t)>=1e21?BigInt(t).toString():String(t)}return JSON.stringify(t).split("\\u2028").join("\\\\u2028").split("\\u2029").join("\\\\u2029")}o(xt,"literal");function Me(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${xt(n,e)}`}o(Me,"equals");var St=new Set(["NaN","Infinity","-Infinity"]),vt=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function Et(t){let n=vt.exec(t);if(!n)throw St.has(t)?new RangeError(`Cannot express ${t} in AQL.`):new TypeError(`${JSON.stringify(t)} is not a number: a number is a string in JSON\'s number syntax.`);let[,e,r,i="",s]=n;if(s===void 0)return t;let a=r+i,l=r.length+Number(s),d;return l<=0?d=`0.${"0".repeat(-l)}${a}`:l>=a.length?d=a+"0".repeat(l-a.length):d=`${a.slice(0,l)}.${a.slice(l)}`,e+d.replace(/^0+(?=\\d)/,"")}o(Et,"numberLiteral");function Le(t,n,e){return`${t} matches @(${n} until ${e})`}o(Le,"dateRange");function Pe(t,n){if(n.length===0)throw new RangeError(`\\`${t}\\` needs at least one operand.`);return n.length===1?n[0]:`${t}(${n.join(", ")})`}o(Pe,"combine");var Be=o(t=>Pe("and",t),"and"),ze=o(t=>Pe("or",t),"or");var Rt=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,Ct={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function Ve(t){if(typeof t!="string")return;let n=Rt.exec(t);if(n)return{year:Number(n[1]),month:Number(n[2])-1,day:Number(n[3]),hour:Number(n[4]??0),minute:Number(n[5]??0),second:Number(n[6]??0),hasTime:n[4]!==void 0}}o(Ve,"parseStamp");function V(t,n){let e=new Date(t),r=o(s=>String(s).padStart(2,"0"),"pad"),i=`${e.getUTCFullYear()}-${r(e.getUTCMonth()+1)}-${r(e.getUTCDate())}`;return n?`${i} ${r(e.getUTCHours())}:${r(e.getUTCMinutes())}:${r(e.getUTCSeconds())}`:i}o(V,"format");function qe(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}o(qe,"toMs");function ye(t){let n=Ve(t);if(n)return V(qe(n),n.hasTime)}o(ye,"normalise");function be(t,n){let e=Ve(t);if(!e)return;let{year:r,month:i,day:s,hour:a,minute:l,second:d,hasTime:p}=e;return V(n==="year"?Date.UTC(r+1,i,s,a,l,d):n==="quarter"?Date.UTC(r,i+3,s,a,l,d):n==="month"?Date.UTC(r,i+1,s,a,l,d):qe(e)+Ct[n],p)}o(be,"addGrain");function Je(t){if(t?.startsWith("datetrunc "))return t.slice(10)}o(Je,"grainOf");function At(t){let n=new Set;return t.filter(e=>{let r=`${typeof e}:${String(e)}`;return n.has(r)?!1:(n.add(r),!0)})}o(At,"distinct");function Dt(t,n){let e=t.map(ye);if(e.some(i=>i===void 0))return!1;let r=e.slice().sort();for(let i=1;i<r.length;i+=1)if(be(r[i-1],n)!==r[i])return!1;return!0}o(Dt,"isContiguous");function _t(t,n,e){let r=n.map(ye);if(r.some(d=>d===void 0))return;let i=r.slice().sort(),s=i[0],a=be(i[i.length-1],e);if(!a)return;let l=Dt(n,e);return{condition:{field:t,operator:"matches",values:[`${s} until ${a}`]},admits:l?n.length:Number.POSITIVE_INFINITY,lossy:!l}}o(_t,"dateRange");function $t(t,n,e){let r=e.filter(l=>l!=null),i=At(r);if(!i.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let s=r.length!==e.length,a=Je(n);if(a){let l=_t(t,i,a);if(l)return{...l,lossy:l.lossy||s}}return{condition:{field:t,operator:"is",values:i},admits:i.length,lossy:s}}o($t,"deriveOne");function je(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}o(je,"fieldReferenceOf");function Ot(t,n,e,r){try{let i=e.map(s=>Be(n.map(a=>{let l=t.get(a),d=je(l),p=s[a]??null,E=Je(r[d]);if(E&&typeof p=="string"){let x=ye(p),h=be(p,E);if(x&&h)return Le(d,x,h)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return Me(d,p,l.semantic_type)})));return ze(i)}catch{return}}o(Ot,"selectionExpression");function Ge(t,n,e,r={}){let i=t.result?.columns??[],s=new Map(i.map(g=>[g.name,g]));e?.forEach(g=>{let w=s.get(g);if(w){if(w.adhoc)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${g}\': it is a query-local AQL expression, which only this query\'s result carries. The target query would receive a condition naming a field it has never heard of.`,t.name);if(w.isMeasure)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${g}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new u(P(`Query \'${t.name}\' has no column \'${g}\' in its last result.`,g,[...s.keys()]),t.name)});let a=i.filter(g=>!g.isMeasure),l=a.filter(g=>!g.adhoc).map(g=>g.name),d=e?[...e]:l;if(!n.length||!d.length)return;let p=[],E=1,x=!e&&l.length!==a.length,h=!1;d.forEach(g=>{let w=s.get(g),D=je(w),T=$t(D,r[D],n.map(v=>v[g]));p.push(T.condition),E*=T.admits,h=h||T.lossy});let b=new Set(n.map(g=>JSON.stringify(d.map(w=>g[w]??null))));E>b.size&&(h=!0);let C=p.sort((g,w)=>g.field.localeCompare(w.field)),A={source:t.name,rows:[...n],fields:d};if(h){let g=Ot(s,d,n,r);if(g)return{...A,conditions:[],expression:g,lossy:x}}return{...A,conditions:C,lossy:x||h}}o(Ge,"deriveSelection");var S={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},Y=`[${S.container}],[${S.block}],[${S.query}],[${S.control}]`;function Ue(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}o(Ue,"parseRef");var He=o(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Ke(t,n,e,r){let i=n==="query"?S.query:S.control;return[...t.querySelectorAll(`[${i}]`)].filter(s=>He(s.getAttribute(i)).some(a=>{let l=Ue(a);return l?.app===e&&l.name===r}))}o(Ke,"markersFor");var Ft=o((t,n,e)=>{let r=t[e.app];return r?Object.prototype.hasOwnProperty.call(n==="query"?r.queries:r.controls,e.name):!1},"hasEntity");function we(t,n){var x;let e=[],r=new Map,i=new Map,s=new Map,a=new Map,l={container:new Set,block:new Set},d={},p=o((h,b,C)=>{let A=h?s.get(h).children:e,g=h?`${s.get(h).key}.`:"",w={...b,key:`${g}${A.length}`,children:[]};return A.push(w),r.set(w.key,C),i.set(C,[...i.get(C)??[],w.key]),w},"place");for(let h of t.querySelectorAll(Y)){let b=h.parentElement?.closest(Y)??null,C=h.getAttribute(S.container),A=h.getAttribute(S.block),g=h.getAttribute(S.label)??void 0,w=b&&(a.get(b)==="block"?b:b.closest(`[${S.block}]`)),D;if(C!==null||A!==null){let v=C!==null?"container":"block",_=(C??A??"").trim(),k=[];C!==null&&A!==null&&k.push("This element is marked as a container and as a block. It counts as a container."),_?l[v].has(_)?k.push(`Another ${v} already has the id "${_}".`):l[v].add(_):k.push(`This ${v} has no id.`),w&&k.push(`A block can\'t hold a ${v}. This one is inside the block "${w.getAttribute(S.block)}".`),D=p(b,{kind:v,id:_,...g!==void 0?{label:g}:{},problems:k},h),s.set(h,D),a.set(h,v)}let T=D?h:b;for(let v of["query","control"])for(let _ of He(h.getAttribute(v==="query"?S.query:S.control))){let k=Ue(_),Q=[];if(k?Ft(n,v,k)||Q.push(n[k.app]?`No ${v} is called "${k.name}" in app ${k.app}.`:`The page has no app ${k.app}.`):Q.push(`Can\'t read "${_}". Write the ${v}\'s name, or app/name when the page has several apps.`),p(T,{kind:v,name:k?.name??_,app:k?.app??0,problems:Q},h),k&&!Q.length){let z=`${k.app}/${k.name}`,J=d[x=`${v}:${z}`]??(d[x]={elements:new Set,blocks:new Set});J.elements.add(h);let f=D?.kind==="block"?D.id:w?.getAttribute(S.block);f&&J.blocks.add(f)}}}let E=Object.fromEntries(Object.entries(d).map(([h,b])=>[h,{markers:b.elements.size,blocks:[...b.blocks]}]));return{nodes:e,usage:E,elements:r,keysOf:i}}o(we,"buildStructure");var Tt=o((t,n,e)=>`${t}:${n}/${e}`,"usageKey");function Nt(t){let n=t.getBoundingClientRect();return`${Math.round(n.width)} \\xD7 ${Math.round(n.height)}`}o(Nt,"sizeOf");function We(t,n,e){let r=Nt(n);if(t.kind==="container"||t.kind==="block")return{kind:t.kind,name:t.id??"",...t.label?{label:t.label}:{},size:r};let i=e.usage[Tt(t.kind,t.app??0,t.name??"")];return{kind:t.kind,name:t.name??"",...i&&i.markers>1?{note:`1 of ${i.markers}`}:{},size:r}}o(We,"describeNode");var X="anfra-overlay";var It="position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;",Qt="position:fixed;max-width:60vw;display:flex;gap:6px;align-items:baseline;padding:3px 8px;border-radius:4px;background:#0f172a;color:#f8fafc;font:12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,0.35);",Mt={kind:"color:#94a3b8;",name:"color:#93c5fd;font-weight:700;",label:"color:#f8fafc;",note:"color:#94a3b8;",size:"color:#94a3b8;margin-left:10px;"},xe=class xe{constructor(n){c(this,"doc",n);c(this,"root");c(this,"shown",[]);c(this,"text",{kind:"",name:""});c(this,"timer");c(this,"reposition",o(()=>this.draw(),"reposition"));let e=n.getElementById(X);e?this.root=e:(this.root=n.createElement("div"),this.root.id=X,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),(n.body??n.documentElement).appendChild(this.root))}show(n,e){if(this.clearTimer(),this.shown=[...n],this.text=e,!this.shown.length){this.hide();return}this.root.style.display="block",this.draw(),this.doc.addEventListener("scroll",this.reposition,{capture:!0,passive:!0}),this.doc.defaultView?.addEventListener("resize",this.reposition)}flash(n,e,r=1500){this.show(n,e),this.timer=setTimeout(()=>this.hide(),r)}hide(){this.clearTimer(),this.shown=[],this.root.style.display="none",this.root.replaceChildren(),this.doc.removeEventListener("scroll",this.reposition,{capture:!0}),this.doc.defaultView?.removeEventListener("resize",this.reposition)}get visible(){return this.shown.length>0}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}draw(){let n=this.shown.map(l=>{let d=l.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${It}left:${d.left}px;top:${d.top}px;width:${d.width}px;height:${d.height}px;`),p}),e=this.shown[0].getBoundingClientRect(),r=this.doc.createElement("div");r.setAttribute("data-testid","anfra-overlay-label");let i=this.doc.defaultView?.innerHeight??0,s=e.top>=26?e.top-24:Math.max(4,e.top+4),a=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${Qt}left:${a}px;top:${Math.min(s,i-24)}px;`);for(let l of["kind","name","label","note","size"]){let d=this.text[l];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",Mt[l]),p.setAttribute("data-part",l),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};o(xe,"Overlay");var ke=xe,Ye=new WeakMap;function B(t){let n=Ye.get(t);return n||(n=new ke(t),Ye.set(t,n)),n}o(B,"overlayFor");function Z(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}o(Z,"scrollTo");var Se=Object.freeze([]);function ve(t){return t instanceof Error&&t.name==="AbortError"}o(ve,"isAbort");function Xe(t,n){return t.controller!==n}o(Xe,"superseded");function Lt(t){return{name:t.name,message:t.message,...t.entity?{entity:t.entity}:{},...typeof t.status=="number"?{status:t.status}:{},...t.stack?{stack:t.stack}:{}}}o(Lt,"inspectError");function Pt(t){let{result:n}=t;return{state:t.state,isDirty:t.isDirty,page:t.page,hasMore:t.hasMore,columns:n?n.columns.map(e=>({...e})):[],rowCount:n?.meta.numRows??0,selectedRowCount:t.selectedRows.length,signature:t.signature(),...t.error?{error:Lt(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}o(Pt,"inspectQuery");function Bt(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}o(Bt,"inspectControl");function Ze(t){return{source:t.source,fields:[...t.fields],rowCount:t.rows.length,conditions:t.conditions.map(n=>({...n})),...t.expression?{expression:t.expression}:{},lossy:t.lossy}}o(Ze,"inspectSelection");function et(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}o(et,"selectionKey");function tt(t,n){return t instanceof $?t:new N(t?.message??"The query failed.",n,t)}o(tt,"toDataAppError");function zt(t,n){if(t instanceof $&&t.entity)return t;let e=t?.message||"The export failed.";return t instanceof I?new I(e,n):t instanceof O?new O(e,t.status,n):t instanceof u?new u(e,n):new N(e,n,t)}o(zt,"toExportError");var Ee=class Ee extends F{constructor(e,r,i,s){super();c(this,"title");c(this,"_timezone");c(this,"datasets");c(this,"backend");c(this,"features");c(this,"_queries",new Map);c(this,"_controls",new Map);c(this,"_mappings",[]);c(this,"_crossFilters",[]);c(this,"_selection");c(this,"_appliedSelection");c(this,"selectionCommitted",!1);c(this,"index",0);this.title=e.title,this._timezone=e.timezone,this.datasets=r,this.backend=i,this.features=s}get queries(){return Object.fromEntries(this._queries)}get controls(){return Object.fromEntries(this._controls)}get mappings(){return[...this._mappings,...this._crossFilters]}get crossFilters(){return this._crossFilters}createQuery(e,r){this.assertNameFree(e,"query");let i=new M(e,this,r);return this._queries.set(e,i),this.notify(),i}createFilter(e,r){this.assertNameFree(e,"filter");let i=r.dataset?this.datasetIndex(r.dataset,e):this.soleDataset(e,r.field),s=new G(e,this,r,i,this.backend);return this._controls.set(e,s),this.notify(),s}createDateDrill(e,r={}){if(this.features?.dateDrill===!1)throw new u(`Date drill \'${e}\' needs a capability this workspace has not enabled. Ask an admin to turn on \\`interactive_control:date_drill\\`.`,e);this.assertNameFree(e,"date drill control");let i=new U(e,this,r);return this._controls.set(e,i),this.notify(),i}mapControl(e,r,i){if(!(e instanceof L))throw new u("mapControl expects a control as its source. To let one query cross-filter another, use app.mapCrossFilter(from, to) \\u2014 a cross-filter edge names no field.");if(this._controls.get(e.name)!==e)throw new u(`Control \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);i.aggregation&&Te(i.aggregation,e.name);let s=new H(e,r,i.field,i.aggregation);if(this._mappings.some(a=>a.id===s.id))throw new u(`Mapping \'${s.id}\' is already declared.`,e.name);return this.assertAcyclic(s),this._mappings.push(s),this.notify(),s}mapCrossFilter(e,r){if(!(e instanceof M)||!(r instanceof M))throw new u("mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field }).");if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);if(e===r)throw new u(`Query \'${e.name}\' cannot cross-filter itself. A source keeps its own rows so it can show what is selected; filtering it would erase the very rows the reader clicked.`,e.name);if(e.declaration.dataset!==r.declaration.dataset)throw new u(`Cross-filter \'${e.name}\' -> \'${r.name}\' spans two datasets (\'${e.declaration.dataset}\' and \'${r.declaration.dataset}\'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,e.name);let i=new K(e,r);if(this._crossFilters.some(s=>s.id===i.id))throw new u(`Cross-filter \'${i.id}\' is already declared.`,e.name);return this._crossFilters.push(i),this.notify(),i}get selection(){return this._selection}get appliedSelection(){return this._appliedSelection}clearSelection(){this._selection&&(this._selection=void 0,this.notify())}setTimezone(e){this._timezone=e,this.notify()}get timezone(){return this._timezone}datasetIndex(e,r){return Fe(this.datasets,e,r)}mappingsTo(e){return this._mappings.filter(r=>r.to.name===e)}selectionExpressionFor(e,r){return this.selectionFor(e,r)?.expression}selectionFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?void 0:this._crossFilters.some(a=>a.from.name===i.source&&a.to.name===e)?i:void 0}selectionConditionsFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?Se:this._crossFilters.some(a=>a.from.name===i.source&&a.to.name===e)?i.conditions:Se}drillTransformations(e){let r={};return this._mappings.forEach(i=>{if(i.to!==e)return;let s=i.from.appliedCondition;if(s?.operator!=="transform_date_drill")return;let[a]=s.values??[];typeof a=="string"&&(r[i.field]=a)}),r}select(e,r,i){if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);let s=Ge(e,r,i,this.drillTransformations(e));s?.lossy&&console.warn(`[anfra-sdk] The selection in \'${e.name}\' filters more broadly than it was made. Its conditions are combined field by field and ANDed, which cannot express "(A and B) or (C and D)", so the targets will also show combinations that were not selected. Select within one dimension, or narrow with \\`fields\\`, to avoid this.`),this._selection=s,this.notify()}get hasChanges(){return[...this._controls.values()].some(e=>e.isDirty)||this.isSelectionDirty}get isSelectionDirty(){return this.selectionCommitted?et(this._selection)!==et(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(l=>l.shouldRun(e.force));this._controls.forEach(l=>l.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(l=>{l.controller?.abort(),l.resetPage()});let i={backend:this.backend,timezone:this._timezone,bustCache:e.bustCache},s=[],a=[];return await Promise.all(r.map(async l=>{let d=new AbortController;l.controller=d;let p=l.signature();l.markExecuting();try{let E=await ge(l,this.mappingsTo(l.name),{conditions:this.selectionConditionsFor(l.name,"applied"),expression:this.selectionExpressionFor(l.name,"applied")},i,d.signal);if(Xe(l,d))return;l.markSuccess(E,p,!1),s.push(l.name)}catch(E){if(Xe(l,d)||ve(E))return;l.markError(tt(E,l.name)),a.push(l.name)}finally{l.controller===d&&(l.controller=void 0)}})),{succeeded:s,failed:a}}async refresh(){return this.execute({force:!0,bustCache:!0})}abort(){this._queries.forEach(e=>e.abort())}async fetchPage(e){let r=new AbortController;e.controller=r;let i=e.signature();e.markExecuting();try{let s=await ge(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone},r.signal);e.markSuccess(s,i,!0)}catch(s){if(e.rewindPage(),ve(s))return;let a=tt(s,e.name);throw e.markError(a),a}finally{e.controller===r&&(e.controller=void 0)}}async exportQuery(e,r={}){let{backend:i}=this;if(this.features?.export===!1||!i.exportQuery)throw new O("This host cannot make exports.",void 0,e.name);let s=Qe(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:i,timezone:this._timezone,title:this.title},r);try{return await i.exportQuery(s,r.signal??new AbortController().signal)}catch(a){throw ve(a)?a:zt(a,e.name)}}toJSON(){let e=o(r=>Object.fromEntries([...this._controls.entries()].filter(([,i])=>i.kind===r).map(([i,s])=>[i,s.toJSON()])),"byKind");return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},queries:Object.fromEntries([...this._queries.entries()].map(([r,i])=>[r,i.toJSON()])),filters:e("filter"),dateDrills:e("dateDrill"),mappings:[...this._mappings.map(r=>r.toJSON()),...this._crossFilters.map(r=>r.toJSON())]}}toInspectJSON(){return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},hasChanges:this.hasChanges,declaration:this.toJSON(),queries:Object.fromEntries([...this._queries.entries()].map(([e,r])=>[e,Pt(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,Bt(r)])),...this._selection?{selection:Ze(this._selection)}:{},...this._appliedSelection?{appliedSelection:Ze(this._appliedSelection)}:{}}}locate(e,r){let i=globalThis.document;if(!i)return!1;let s=Ke(i,e,this.index,r);return s.length?(Z(s[0]),B(i).flash(s,{kind:e,name:r,...s.length>1?{note:`in ${s.length} places`}:{}}),!0):!1}assertNameFree(e,r){Ne([...this._queries.keys(),...this._controls.keys()],e,r)}soleDataset(e,r){if(!r)return;let i=Object.keys(this.datasets);if(i.length===1)return this.datasets[i[0]];throw new u(i.length?`Filter \'${e}\' names a field but the environment has ${i.length} datasets. Say which one: ${i.join(", ")}.`:`Filter \'${e}\' names a field but the environment has no datasets.`,e)}assertAcyclic(e){let r=[...this._mappings,e],i=new Map;r.forEach(d=>{let p=d.from.name;i.set(p,[...i.get(p)??[],d.to.name])});let s=new Set,a=new Set,l=o(d=>{if(s.has(d))return!0;if(a.has(d))return!1;s.add(d);let p=(i.get(d)??[]).some(l);return s.delete(d),a.add(d),p},"walk");if([...i.keys()].some(l))throw new u(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};o(Ee,"App");var ee=Ee;var nt="0.8.0";var qt=nt,Ce=class Ce{constructor(n){c(this,"version",qt);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"features");c(this,"renderHook");if(!n?.datasets)throw new u("No datasets provided. The host must call createSdk({ datasets }) before an app can be declared.");if(!n.user)throw new u("No user provided. The host must call createSdk({ user }) before an app can be declared.");if(!n.backend)throw new u("No backend provided. The host must call createSdk({ backend }) before an app can run a query.");this.datasets=Object.freeze({...n.datasets}),this.user=Object.freeze({...n.user,permissions:Object.freeze({...n.user.permissions})}),this.indices=Object.fromEntries(Object.entries(n.datasets).map(([e,r])=>[e,new W(r)])),this.backend=n.backend,this.renderHook=n.render,this.features=Object.freeze({...n.features,export:n.features?.export??typeof n.backend.exportQuery=="function",render:n.features?.render??typeof n.render=="function"})}createApp(n={}){let e=new ee(n,this.indices,this.backend,this.features);return e.index=this._apps.length,this._apps.push(e),e}render(n){return!this.renderHook||this.features.render===!1?Promise.reject(new u("This host does not render Data Apps: check Anfra.features.render first.")):this.renderHook(n)}get apps(){return this._apps}};o(Ce,"Sdk");var Re=Ce;function rt(t){return new Re(t)}o(rt,"createSdk");var q="Anfra";function it(t,n=globalThis){let e=n[q],r=q in n;return n[q]=t,()=>{r?n[q]=e:delete n[q]}}o(it,"installSandbox");function ot(t,n){let e=null,r=o(d=>d.target instanceof Element?d.target.closest(Y):null,"under"),i=o(d=>{let p=r(d);p!==e&&(e=p,n.onHover(p))},"onMove"),s=o(d=>{d.preventDefault(),d.stopPropagation();let p=r(d);p&&n.onPick(p)},"onClick"),a=o(d=>{d.key==="Escape"&&n.onCancel()},"onKey"),l={capture:!0};return t.addEventListener("mousemove",i,l),t.addEventListener("click",s,l),t.addEventListener("keydown",a,l),()=>{t.removeEventListener("mousemove",i,l),t.removeEventListener("click",s,l),t.removeEventListener("keydown",a,l)}}o(ot,"startPick");var Ae="__anfraRenderer";var Jt="data-anfra-render",jt={png:"png",pdf:"pdf"},Gt=1e4;function Ut(t,n,e,r){let i=jt[t.format],s=t.filename?.trim();if(!s){let a=e.find(d=>d.title)?.title||n.title.trim()||"Data App",l=r&&(r.getAttribute(S.label)||t.block||t.container);s=l?`${a} - ${l}`:a}return s=s.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim()||"Data App",s.toLowerCase().endsWith(`.${i}`)?s:`${s}.${i}`}o(Ut,"filenameFor");function Ht(t,n){if(t.block!==void 0&&t.container!==void 0)throw new u("Render a block or a container, not both.",t.block);if(t.format!=="png"&&t.format!=="pdf")throw new u(`Can\'t render as \'${String(t.format)}\': the formats are \'png\' and \'pdf\'.`);let{pixelRatio:e}=t;if(e!==void 0&&!(Number.isFinite(e)&&e>0))throw new u(`pixelRatio ${String(e)} is not a positive number.`);let r=t.block!==void 0?"block":t.container!==void 0?"container":void 0;if(!r)return{element:null};let i=t.block??t.container,s=[...n.querySelectorAll(`[${S[r]}]`)].find(a=>a.getAttribute(S[r])===i);if(!s)throw new u(`No element is marked ${S[r]}="${i}" on the page.`,i);return{element:s,entity:i}}o(Ht,"targetOf");function Kt(t){return t.id===X||t.getAttribute(Jt)==="skip"}o(Kt,"skip");function st(t,n){let e,r=o(()=>{let i=t[Ae];return i?Promise.resolve(i):(e??(e=n.ask.renderer().then(s=>{let a=t.document.createElement("script");a.textContent=s,(t.document.head??t.document.documentElement).appendChild(a),a.remove();let l=t[Ae];if(!l)throw new u("The host sent a renderer that did not install.");return l}).catch(s=>{throw e=void 0,s})),e)},"load");return async i=>{let s=t.document,{element:a,entity:l}=Ht(i??{},s),d=Ut(i,s,n.apps(),a);try{let E=await(await r()).draw(a,{format:i.format,pixelRatio:i.pixelRatio,skip:Kt});return await n.ask.saveFile({blob:E.blob,filename:d}),{filename:d,format:i.format,...E}}catch(p){throw p instanceof u&&p.entity?p:new u(p?.message||"The rendering failed.",l)}}}o(st,"createRender");async function at(t,n,e=Gt){let r=o(()=>n().some(s=>Object.values(s.queries).some(a=>a.state==="executing")),"busy"),i=Date.now()+e;for(;r()&&Date.now()<i;)await new Promise(s=>{t.setTimeout(s,100)});await new Promise(s=>{t.requestAnimationFrame(()=>s(void 0))})}o(at,"settle");function lt(){let t=new Error("Aborted");return t.name="AbortError",t}o(lt,"abortError");function Wt(t){switch(t?.name){case"PermissionError":return new I(t.message);case"TransportError":return new O(t.message);case"ValidationError":return new u(t.message);default:return new N(t?.message||"The query failed.")}}o(Wt,"toError");function dt(t){let n=t.document.getElementById(_e);if(!n?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let e=JSON.parse(n.textContent),r=o(f=>t.parent.postMessage(f,e.hostOrigin),"post"),i=new Map,s=1,a=!1,l;t.addEventListener("message",f=>{if(f.source!==t.parent)return;let m=f.data;switch(m?.type){case"anfra:response":{let y=i.get(m.id);if(!y)return;i.delete(m.id),m.ok?y.resolve(m.result):y.reject(Wt(m.error));return}case"anfra:inspect-watch":v(m.open);return;case"anfra:highlight":k(m.node);return;case"anfra:locate":Q(m.target);return;case"anfra:pick-watch":z(m.on);return;case"anfra:render":{let{id:y}=m;at(t,()=>x.apps).then(()=>x.render(m.request)).then(R=>r({type:"anfra:rendered",id:y,ok:!0,result:R}),R=>r({type:"anfra:rendered",id:y,ok:!1,error:{name:R?.name??"ValidationError",message:R?.message??"The rendering failed."}}));return}default:}});function d(f,m,y){return new Promise((R,te)=>{if(y.aborted){te(lt());return}let j=s++;i.set(j,{resolve:R,reject:te}),y.addEventListener("abort",()=>{i.delete(j)&&(r({type:"anfra:cancel",id:j}),te(lt()))},{once:!0}),r({type:"anfra:request",id:j,method:f,request:m})})}o(d,"call");let p={submitQuery:o((f,m)=>d("submitQuery",f,m).then(y=>(y.debug?.executedAt&&(y.debug.executedAt=new Date(y.debug.executedAt)),y)),"submitQuery"),fieldSuggestions:o((f,m)=>d("fieldSuggestions",f,m),"fieldSuggestions"),exportQuery:o((f,m)=>d("exportQuery",f,m).then(y=>(y.expiresAt=new Date(y.expiresAt),y)),"exportQuery")},E=st(t,{ask:{renderer:o(()=>d("renderer",null,new AbortController().signal),"renderer"),saveFile:o(f=>d("saveFile",f,new AbortController().signal),"saveFile")},apps:o(()=>x.apps,"apps")}),x=rt({datasets:e.datasets,user:e.user,backend:p,render:E,features:{export:!1,render:!1,...e.features}}),h=t.document,b,C="",A,g;function w(){if(l=void 0,!!a)try{b=we(h,x.apps),C=JSON.stringify(b.nodes),r({type:"anfra:inspect",apps:x.apps.map(f=>f.toInspectJSON()),structure:{nodes:b.nodes,usage:b.usage}})}catch{}}o(w,"postSnapshot");function D(){a&&l===void 0&&(l=setTimeout(w,50))}o(D,"scheduleSnapshot");function T(){let f=t.MutationObserver;if(A||typeof f!="function")return;let m=new f(()=>{if(!(!a||l!==void 0))try{JSON.stringify(we(h,x.apps).nodes)!==C&&D()}catch{}});A=m,m.observe(h.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-anfra-container","data-anfra-block","data-anfra-query","data-anfra-control","data-anfra-label"]})}o(T,"observeStructure");function v(f){a=f,f?(T(),w()):(A?.disconnect(),A=void 0,z(!1),B(h).hide(),b=void 0,C="")}o(v,"setInspecting");function _(f,m){for(let y of f){if(y.key===m)return y;let R=_(y.children,m);if(R)return R}}o(_,"findNode");function k(f){let m=B(h),y=f!==null&&b?_(b.nodes,f):void 0,R=f!==null?b?.elements.get(f):void 0;if(!y||!R||!b){m.hide();return}m.show([R],We(y,R,b))}o(k,"highlight");function Q(f){if("node"in f){let m=b?.elements.get(f.node);m&&Z(m),k(f.node)}else x.apps[f.app]?.locate(f.kind,f.name);D()}o(Q,"locate");function z(f){if(!f){g?.(),g=void 0;return}if(g)return;let m=o(y=>b?.keysOf.get(y)?.[0],"keyOf");g=ot(h,{onHover:o(y=>k(y?m(y)??null:null),"onHover"),onPick:o(y=>{let R=m(y);R!==void 0&&r({type:"anfra:picked",node:R})},"onPick"),onCancel:o(()=>{z(!1),B(h).hide(),r({type:"anfra:picked",node:null})},"onCancel")})}o(z,"setPicking");let J=x.createApp.bind(x);x.createApp=f=>{let m=J(f);return m.subscribe(D),D(),m},it(x,t),r({type:"anfra:ready"})}o(dt,"bootstrap");dt(window);})();\n';
179
+ var anfra_sdk_frame_script_default = '"use strict";(()=>{var De=Object.defineProperty;var ct=(t,n,e)=>n in t?De(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var s=(t,n)=>De(t,"name",{value:n,configurable:!0});var c=(t,n,e)=>ct(t,typeof n!="symbol"?n+"":n,e);var ne=class ne extends Error{constructor(e,r){super(e);c(this,"entity");this.name=new.target.name,this.entity=r,Object.setPrototypeOf(this,new.target.prototype)}};s(ne,"DataAppError");var O=ne,re=class re extends O{};s(re,"ValidationError");var u=re,ie=class ie extends O{constructor(e,r,i){super(e,r);c(this,"cause");this.cause=i}};s(ie,"QueryError");var N=ie,oe=class oe extends O{};s(oe,"PermissionError");var I=oe,se=class se extends O{constructor(e,r,i){super(e,i);c(this,"status");this.status=r}};s(se,"TransportError");var $=se;var _e="anfra-provision";var ae=class ae{constructor(n){c(this,"listeners",new Set);c(this,"parent");this.parent=n}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}notifyChange(){this.listeners.forEach(n=>n()),this.parent?.notifyChange()}notify(){this.notifyChange()}};s(ae,"Observable");var T=ae;var le=class le extends T{constructor(e,r,i){super(r);c(this,"kind","query");c(this,"name");c(this,"declaration");c(this,"dataset");c(this,"app");c(this,"_state","idle");c(this,"_result");c(this,"_error");c(this,"_page",1);c(this,"_sort",[]);c(this,"lastRunSignature");c(this,"lastPageRows",0);c(this,"controller");if(!i.aql?.trim())throw new u(`Query \'${e}\' declares no AQL.`,e);let{pageSize:o}=i;if(o!==void 0&&!(Number.isInteger(o)&&o>=1))throw new u(`Query \'${e}\' declares pageSize ${o}; it must be a whole number of at least 1.`,e);this.name=e,this.app=r,this.declaration=i,this.dataset=r.datasetIndex(i.dataset,e)}locate(){return this.app.locate("query",this.name)}get state(){return this._state}get result(){return this._result}get error(){return this._error}get pageSize(){return this.declaration.pageSize}get page(){return this._page}get sort(){return this._sort}setSort(e){this._sort=[...e],this.notify()}get hasMore(){return!this._result||this.pageSize===void 0?!1:this.lastPageRows>=this.pageSize}signature(){let e=this.app.mappingsTo(this.name).map(r=>({field:r.field,aggregation:r.aggregation,condition:r.from.condition})).sort((r,i)=>r.field.localeCompare(i.field)||JSON.stringify(r).localeCompare(JSON.stringify(i)));return JSON.stringify({declaration:this.declaration,conditions:e,selection:this.app.selectionConditionsFor(this.name,"pending"),selectionExpression:this.app.selectionExpressionFor(this.name,"pending"),sort:this._sort,timezone:this.app.timezone,page:this._page})}get isDirty(){return this.lastRunSignature!==void 0&&this.signature()!==this.lastRunSignature}shouldRun(e=!1){return e||this.lastRunSignature===void 0||this.isDirty}abort(){this.controller?.abort()}async fetchMore(){if(this.pageSize===void 0)throw new u(`Query \'${this.name}\' declares no pageSize, so it has no more pages.`,this.name);this.hasMore&&(this._page+=1,await this.app.fetchPage(this))}export(e={}){return this.app.exportQuery(this,e)}select(e,r={}){this.app.select(this,Array.isArray(e)?e:[e],r.fields)}get selectedRows(){let{selection:e}=this.app;if(e?.source!==this.name)return[];let r=this._result?.rows;if(!r)return e.rows;let i=s(a=>JSON.stringify(e.fields.map(l=>a[l]??null)),"key"),o=new Set(e.rows.map(i));return r.filter(a=>o.has(i(a)))}markExecuting(){this._state="executing",this._error=void 0,this.notify()}markSuccess(e,r,i){if(this._state="success",this._error=void 0,this.lastRunSignature=r,this.lastPageRows=e.rows.length,i&&this._result){let o=[...this._result.rows,...e.rows];this._result={...e,rows:o,meta:{...e.meta,numRows:o.length}}}else this._result=e;this.notify()}markError(e){this._state="error",this._error=e,this.notify()}rewindPage(){this._page>1&&(this._page-=1)}resetPage(){this._page=1,this.lastPageRows=0}toJSON(){return this.declaration}};s(le,"Query");var L=le;var $e=["year","quarter","month","week","day","hour","minute"];function ut(t,n){if(!$e.includes(n))throw new u(`Invalid grain \'${n}\'. Expected one of: ${$e.join(", ")}.`,t)}s(ut,"assertGrain");function Oe(t,n){return n?(ut(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}s(Oe,"drillCondition");function pt(t){let n=t.toLowerCase();return n.includes("date")||n.includes("time")?"date":n.includes("int")||n.includes("number")||n.includes("float")||n.includes("decimal")?"number":n.includes("bool")?"boolean":"string"}s(pt,"inferType");function ft(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}s(ft,"sameCondition");var de=class de extends T{constructor(e,r,i){super(r);c(this,"name");c(this,"app");c(this,"pending");c(this,"applied");c(this,"initial");this.name=e,this.app=r,this.initial=i,this.pending=i}locate(){return this.app.locate("control",this.name)}get condition(){return this.pending}get appliedCondition(){return this.applied}get isDirty(){return this.applied!==void 0&&!ft(this.pending,this.applied)}setCondition(e){this.pending=e,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};s(de,"Control");var M=de,ce=class ce extends M{constructor(e,r,i,o,a){super(e,r,i.default??{operator:"is",values:[]});c(this,"kind","filter");c(this,"declaration");c(this,"type");c(this,"resolved");c(this,"datasetName");c(this,"backend");c(this,"loadedOptions");if(this.declaration=i,this.backend=a,i.field){if(!o)throw new u(`Filter \'${e}\' names a field but no dataset. Pass \\`dataset\\` alongside \\`field\\`.`,e);this.resolved=o.resolve(i.field,e),this.datasetName=o.descriptor.name,this.type=i.type??pt(this.resolved.type)}else{if(!i.type)throw new u(`Filter \'${e}\' is a manual filter, so it needs a \\`type\\`.`,e);this.type=i.type}this.assertValues(this.condition.values??[]),this.assertValues(i.options??[])}setCondition(e){this.assertValues(e.values??[]),super.setCondition(e)}assertValues(e){if(this.type!=="number")return;let r=e.find(i=>typeof i=="number");if(r!==void 0)throw new u(`Filter \'${this.name}\' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(r))}, not ${String(r)}), so none has lost a digit.`,this.name)}get isFieldBacked(){return this.resolved!==void 0}get options(){return this.loadedOptions??this.declaration.options??[]}async loadOptions(e,r=new AbortController().signal){let i=this.resolved?.modelName;if(!this.resolved||!i||!this.backend||!this.datasetName)return this.options;let o=await this.backend.fieldSuggestions({dataset:this.datasetName,model:i,field:this.resolved.fieldName,q:e??""},r);return this.loadedOptions=[...o??[]],this.notify(),this.loadedOptions}toJSON(){return this.declaration}};s(ce,"Filter");var G=ce,ue=class ue extends M{constructor(e,r,i={}){super(e,r,Oe(e,i.default));c(this,"kind","dateDrill");c(this,"declaration");this.declaration=i}setGrain(e){this.setCondition(Oe(this.name,e))}toJSON(){return this.declaration}};s(ue,"DateDrillControl");var U=ue;var pe=class pe{constructor(n,e,r,i){c(this,"kind","control");c(this,"from");c(this,"to");c(this,"field");c(this,"aggregation");this.from=n,this.to=e,this.field=r,this.aggregation=i}get id(){return`${this.from.name}.${this.to.name}.${this.field}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:this.from.kind,name:this.from.name},to:{kind:"query",name:this.to.name},field:this.field,...this.aggregation?{aggregation:this.aggregation}:{}}}};s(pe,"Mapping");var H=pe,fe=class fe{constructor(n,e){c(this,"kind","crossFilter");c(this,"from");c(this,"to");this.from=n,this.to=e}get id(){return`${this.from.name}.${this.to.name}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:"query",name:this.from.name},to:{kind:"query",name:this.to.name}}}};s(fe,"CrossFilter");var K=fe;var me=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function mt(t,n){let e=t.length+1,r=n.length+1,i=Array.from({length:r},(o,a)=>a);for(let o=1;o<e;o++){let a=[o];for(let l=1;l<r;l++)a[l]=Math.min(i[l]+1,a[l-1]+1,i[l-1]+(t[o-1]===n[l-1]?0:1));i=a}return i[r-1]}s(mt,"editDistance");function ht(t,n){let e,r=1/0;n.forEach(o=>{let a=mt(t.toLowerCase(),o.toLowerCase());a<r&&(r=a,e=o)});let i=Math.max(2,Math.floor(t.length/3));return r<=i?e:void 0}s(ht,"suggest");function P(t,n,e){let r=ht(n,e);return r?`${t} Did you mean \'${r}\'?`:t}s(P,"withSuggestion");var he=class he{constructor(n){c(this,"descriptor");c(this,"fields",new Map);c(this,"references");this.descriptor=n,n.data_models.forEach(e=>{e.fields.forEach(r=>{let i=String(e.name);this.fields.set(`${i}.${r.name}`,{modelName:i,fieldName:r.name,isMetric:!1,type:r.type,label:r.label??r.name})})}),n.metrics.forEach(e=>{this.fields.set(e.name,{fieldName:e.name,isMetric:!0,type:e.type,label:e.label??e.name})}),this.references=[...this.fields.keys()]}resolve(n,e){let r=this.fields.get(n);if(r)return r;throw new u(P(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};s(he,"DatasetIndex");var W=he;function Te(t,n,e){let r=t[n];if(r)return r;throw new u(P(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}s(Te,"resolveDataset");function Fe(t,n){if(!me.includes(t))throw new u(P(`Invalid filter aggregation \'${t}\'.`,t,[...me]),n)}s(Fe,"assertValidFilterAggregation");function Ne(t,n,e){if(!n)throw new u(`A ${e} needs a name.`);for(let r of t)if(r===n)throw new u(`\'${n}\' is already declared in this app.`,n)}s(Ne,"assertUniqueName");function gt(t,n){if(!(!n||n.operator==="none"||n.operator==="transform_date_drill"||!["is_null","not_null","is_true","is_false","transform_pop_none"].includes(n.operator)&&!n.values?.length))return{field:t.field,operator:n.operator,values:n.values??[],...n.modifier?{modifier:n.modifier}:{},...t.aggregation?{aggregation:t.aggregation}:{}}}s(gt,"toFilter");function yt(t,n){if(n?.operator!=="transform_date_drill")return;let e=n.values?.[0];if(typeof e!="string")return;let r=e.replace(/^datetrunc\\s+/,"");return{field:t.field,grain:r}}s(yt,"toDateDrill");function bt(t,n){let e=n.columns??[],r=(n.values??[]).map(o=>{let a={};return e.forEach((l,d)=>{a[l.name]=o[d]}),a}),{pageSize:i}=t;return{columns:e,rows:r,meta:{...i!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??i}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}s(bt,"toResult");function Ie(t,n,e,r){let i=n.map(d=>gt(d,d.from.appliedCondition)).filter(d=>d!==void 0),o=n.map(d=>yt(d,d.from.appliedCondition)).filter(d=>d!==void 0),a=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),l=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...i,...a],conditions:l,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:o},...r.timezone?{timezone:r.timezone}:{}}}s(Ie,"buildQuery");function wt(t,n,e,r){return{...Ie(t,n,e,r),...t.pageSize!==void 0?{page:t.page,pageSize:t.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}s(wt,"buildRequest");function kt(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}s(kt,"defaultExportFilename");function Qe(t,n,e,r,i){let o=i.format??"csv",a=o==="csv"?{bom:!0,...i.formatOptions}:i.formatOptions;return{...Ie(t,n,e,r),format:o,...a?{formatOptions:a}:{},filename:i.filename?.trim()||kt(t,r.title)}}s(Qe,"buildExportRequest");async function ge(t,n,e,r,i){let o=wt(t,n,e,r),a=await r.backend.submitQuery(o,i);return bt(t,a)}s(ge,"runQuery");function xt(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return Et(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError(`Cannot express ${t} in AQL.`);return Math.abs(t)>=1e21?BigInt(t).toString():String(t)}return JSON.stringify(t).split("\\u2028").join("\\\\u2028").split("\\u2029").join("\\\\u2029")}s(xt,"literal");function Le(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${xt(n,e)}`}s(Le,"equals");var St=new Set(["NaN","Infinity","-Infinity"]),vt=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function Et(t){let n=vt.exec(t);if(!n)throw St.has(t)?new RangeError(`Cannot express ${t} in AQL.`):new TypeError(`${JSON.stringify(t)} is not a number: a number is a string in JSON\'s number syntax.`);let[,e,r,i="",o]=n;if(o===void 0)return t;let a=r+i,l=r.length+Number(o),d;return l<=0?d=`0.${"0".repeat(-l)}${a}`:l>=a.length?d=a+"0".repeat(l-a.length):d=`${a.slice(0,l)}.${a.slice(l)}`,e+d.replace(/^0+(?=\\d)/,"")}s(Et,"numberLiteral");function Me(t,n,e){return`${t} matches @(${n} until ${e})`}s(Me,"dateRange");function Pe(t,n){if(n.length===0)throw new RangeError(`\\`${t}\\` needs at least one operand.`);return n.length===1?n[0]:`${t}(${n.join(", ")})`}s(Pe,"combine");var Be=s(t=>Pe("and",t),"and"),ze=s(t=>Pe("or",t),"or");var Rt=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,Ct={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function Ve(t){if(typeof t!="string")return;let n=Rt.exec(t);if(n)return{year:Number(n[1]),month:Number(n[2])-1,day:Number(n[3]),hour:Number(n[4]??0),minute:Number(n[5]??0),second:Number(n[6]??0),hasTime:n[4]!==void 0}}s(Ve,"parseStamp");function V(t,n){let e=new Date(t),r=s(o=>String(o).padStart(2,"0"),"pad"),i=`${e.getUTCFullYear()}-${r(e.getUTCMonth()+1)}-${r(e.getUTCDate())}`;return n?`${i} ${r(e.getUTCHours())}:${r(e.getUTCMinutes())}:${r(e.getUTCSeconds())}`:i}s(V,"format");function qe(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}s(qe,"toMs");function ye(t){let n=Ve(t);if(n)return V(qe(n),n.hasTime)}s(ye,"normalise");function be(t,n){let e=Ve(t);if(!e)return;let{year:r,month:i,day:o,hour:a,minute:l,second:d,hasTime:p}=e;return V(n==="year"?Date.UTC(r+1,i,o,a,l,d):n==="quarter"?Date.UTC(r,i+3,o,a,l,d):n==="month"?Date.UTC(r,i+1,o,a,l,d):qe(e)+Ct[n],p)}s(be,"addGrain");function je(t){if(t?.startsWith("datetrunc "))return t.slice(10)}s(je,"grainOf");function At(t){let n=new Set;return t.filter(e=>{let r=`${typeof e}:${String(e)}`;return n.has(r)?!1:(n.add(r),!0)})}s(At,"distinct");function Dt(t,n){let e=t.map(ye);if(e.some(i=>i===void 0))return!1;let r=e.slice().sort();for(let i=1;i<r.length;i+=1)if(be(r[i-1],n)!==r[i])return!1;return!0}s(Dt,"isContiguous");function _t(t,n,e){let r=n.map(ye);if(r.some(d=>d===void 0))return;let i=r.slice().sort(),o=i[0],a=be(i[i.length-1],e);if(!a)return;let l=Dt(n,e);return{condition:{field:t,operator:"matches",values:[`${o} until ${a}`]},admits:l?n.length:Number.POSITIVE_INFINITY,lossy:!l}}s(_t,"dateRange");function $t(t,n,e){let r=e.filter(l=>l!=null),i=At(r);if(!i.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let o=r.length!==e.length,a=je(n);if(a){let l=_t(t,i,a);if(l)return{...l,lossy:l.lossy||o}}return{condition:{field:t,operator:"is",values:i},admits:i.length,lossy:o}}s($t,"deriveOne");function Je(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}s(Je,"fieldReferenceOf");function Ot(t,n,e,r){try{let i=e.map(o=>Be(n.map(a=>{let l=t.get(a),d=Je(l),p=o[a]??null,E=je(r[d]);if(E&&typeof p=="string"){let x=ye(p),h=be(p,E);if(x&&h)return Me(d,x,h)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return Le(d,p,l.semantic_type)})));return ze(i)}catch{return}}s(Ot,"selectionExpression");function Ge(t,n,e,r={}){let i=t.result?.columns??[],o=new Map(i.map(g=>[g.name,g]));e?.forEach(g=>{let w=o.get(g);if(w){if(w.adhoc)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${g}\': it is a query-local AQL expression, which only this query\'s result carries. The target query would receive a condition naming a field it has never heard of.`,t.name);if(w.isMeasure)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${g}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new u(P(`Query \'${t.name}\' has no column \'${g}\' in its last result.`,g,[...o.keys()]),t.name)});let a=i.filter(g=>!g.isMeasure),l=a.filter(g=>!g.adhoc).map(g=>g.name),d=e?[...e]:l;if(!n.length||!d.length)return;let p=[],E=1,x=!e&&l.length!==a.length,h=!1;d.forEach(g=>{let w=o.get(g),D=Je(w),F=$t(D,r[D],n.map(v=>v[g]));p.push(F.condition),E*=F.admits,h=h||F.lossy});let b=new Set(n.map(g=>JSON.stringify(d.map(w=>g[w]??null))));E>b.size&&(h=!0);let C=p.sort((g,w)=>g.field.localeCompare(w.field)),A={source:t.name,rows:[...n],fields:d};if(h){let g=Ot(o,d,n,r);if(g)return{...A,conditions:[],expression:g,lossy:x}}return{...A,conditions:C,lossy:x||h}}s(Ge,"deriveSelection");var S={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},Y=`[${S.container}],[${S.block}],[${S.query}],[${S.control}]`;function Ue(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}s(Ue,"parseRef");var He=s(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Ke(t,n,e,r){let i=n==="query"?S.query:S.control;return[...t.querySelectorAll(`[${i}]`)].filter(o=>He(o.getAttribute(i)).some(a=>{let l=Ue(a);return l?.app===e&&l.name===r}))}s(Ke,"markersFor");var Tt=s((t,n,e)=>{let r=t[e.app];return r?Object.prototype.hasOwnProperty.call(n==="query"?r.queries:r.controls,e.name):!1},"hasEntity");function we(t,n){var x;let e=[],r=new Map,i=new Map,o=new Map,a=new Map,l={container:new Set,block:new Set},d={},p=s((h,b,C)=>{let A=h?o.get(h).children:e,g=h?`${o.get(h).key}.`:"",w={...b,key:`${g}${A.length}`,children:[]};return A.push(w),r.set(w.key,C),i.set(C,[...i.get(C)??[],w.key]),w},"place");for(let h of t.querySelectorAll(Y)){let b=h.parentElement?.closest(Y)??null,C=h.getAttribute(S.container),A=h.getAttribute(S.block),g=h.getAttribute(S.label)??void 0,w=b&&(a.get(b)==="block"?b:b.closest(`[${S.block}]`)),D;if(C!==null||A!==null){let v=C!==null?"container":"block",_=(C??A??"").trim(),k=[];C!==null&&A!==null&&k.push("This element is marked as a container and as a block. It counts as a container."),_?l[v].has(_)?k.push(`Another ${v} already has the id "${_}".`):l[v].add(_):k.push(`This ${v} has no id.`),w&&k.push(`A block can\'t hold a ${v}. This one is inside the block "${w.getAttribute(S.block)}".`),D=p(b,{kind:v,id:_,...g!==void 0?{label:g}:{},problems:k},h),o.set(h,D),a.set(h,v)}let F=D?h:b;for(let v of["query","control"])for(let _ of He(h.getAttribute(v==="query"?S.query:S.control))){let k=Ue(_),Q=[];if(k?Tt(n,v,k)||Q.push(n[k.app]?`No ${v} is called "${k.name}" in app ${k.app}.`:`The page has no app ${k.app}.`):Q.push(`Can\'t read "${_}". Write the ${v}\'s name, or app/name when the page has several apps.`),p(F,{kind:v,name:k?.name??_,app:k?.app??0,problems:Q},h),k&&!Q.length){let z=`${k.app}/${k.name}`,j=d[x=`${v}:${z}`]??(d[x]={elements:new Set,blocks:new Set});j.elements.add(h);let f=D?.kind==="block"?D.id:w?.getAttribute(S.block);f&&j.blocks.add(f)}}}let E=Object.fromEntries(Object.entries(d).map(([h,b])=>[h,{markers:b.elements.size,blocks:[...b.blocks]}]));return{nodes:e,usage:E,elements:r,keysOf:i}}s(we,"buildStructure");var Ft=s((t,n,e)=>`${t}:${n}/${e}`,"usageKey");function Nt(t){let n=t.getBoundingClientRect();return`${Math.round(n.width)} \\xD7 ${Math.round(n.height)}`}s(Nt,"sizeOf");function We(t,n,e){let r=Nt(n);if(t.kind==="container"||t.kind==="block")return{kind:t.kind,name:t.id??"",...t.label?{label:t.label}:{},size:r};let i=e.usage[Ft(t.kind,t.app??0,t.name??"")];return{kind:t.kind,name:t.name??"",...i&&i.markers>1?{note:`1 of ${i.markers}`}:{},size:r}}s(We,"describeNode");var X="anfra-overlay";var It="position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;",Qt="position:fixed;max-width:60vw;display:flex;gap:6px;align-items:baseline;padding:3px 8px;border-radius:4px;background:#0f172a;color:#f8fafc;font:12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,0.35);",Lt={kind:"color:#94a3b8;",name:"color:#93c5fd;font-weight:700;",label:"color:#f8fafc;",note:"color:#94a3b8;",size:"color:#94a3b8;margin-left:10px;"},xe=class xe{constructor(n){c(this,"doc",n);c(this,"root");c(this,"shown",[]);c(this,"text",{kind:"",name:""});c(this,"timer");c(this,"reposition",s(()=>this.draw(),"reposition"));let e=n.getElementById(X);e?this.root=e:(this.root=n.createElement("div"),this.root.id=X,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),(n.body??n.documentElement).appendChild(this.root))}show(n,e){if(this.clearTimer(),this.shown=[...n],this.text=e,!this.shown.length){this.hide();return}this.root.style.display="block",this.draw(),this.doc.addEventListener("scroll",this.reposition,{capture:!0,passive:!0}),this.doc.defaultView?.addEventListener("resize",this.reposition)}flash(n,e,r=1500){this.show(n,e),this.timer=setTimeout(()=>this.hide(),r)}hide(){this.clearTimer(),this.shown=[],this.root.style.display="none",this.root.replaceChildren(),this.doc.removeEventListener("scroll",this.reposition,{capture:!0}),this.doc.defaultView?.removeEventListener("resize",this.reposition)}get visible(){return this.shown.length>0}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}draw(){let n=this.shown.map(l=>{let d=l.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${It}left:${d.left}px;top:${d.top}px;width:${d.width}px;height:${d.height}px;`),p}),e=this.shown[0].getBoundingClientRect(),r=this.doc.createElement("div");r.setAttribute("data-testid","anfra-overlay-label");let i=this.doc.defaultView?.innerHeight??0,o=e.top>=26?e.top-24:Math.max(4,e.top+4),a=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${Qt}left:${a}px;top:${Math.min(o,i-24)}px;`);for(let l of["kind","name","label","note","size"]){let d=this.text[l];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",Lt[l]),p.setAttribute("data-part",l),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};s(xe,"Overlay");var ke=xe,Ye=new WeakMap;function B(t){let n=Ye.get(t);return n||(n=new ke(t),Ye.set(t,n)),n}s(B,"overlayFor");function Z(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}s(Z,"scrollTo");var Se=Object.freeze([]);function ve(t){return t instanceof Error&&t.name==="AbortError"}s(ve,"isAbort");function Xe(t,n){return t.controller!==n}s(Xe,"superseded");function Mt(t){return{name:t.name,message:t.message,...t.entity?{entity:t.entity}:{},...typeof t.status=="number"?{status:t.status}:{},...t.stack?{stack:t.stack}:{}}}s(Mt,"inspectError");function Pt(t){let{result:n}=t;return{state:t.state,isDirty:t.isDirty,page:t.page,hasMore:t.hasMore,columns:n?n.columns.map(e=>({...e})):[],rowCount:n?.meta.numRows??0,selectedRowCount:t.selectedRows.length,signature:t.signature(),...t.error?{error:Mt(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}s(Pt,"inspectQuery");function Bt(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}s(Bt,"inspectControl");function Ze(t){return{source:t.source,fields:[...t.fields],rowCount:t.rows.length,conditions:t.conditions.map(n=>({...n})),...t.expression?{expression:t.expression}:{},lossy:t.lossy}}s(Ze,"inspectSelection");function et(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}s(et,"selectionKey");function tt(t,n){return t instanceof O?t:new N(t?.message??"The query failed.",n,t)}s(tt,"toDataAppError");function zt(t,n){if(t instanceof O&&t.entity)return t;let e=t?.message||"The export failed.";return t instanceof I?new I(e,n):t instanceof $?new $(e,t.status,n):t instanceof u?new u(e,n):new N(e,n,t)}s(zt,"toExportError");var Ee=class Ee extends T{constructor(e,r,i,o){super();c(this,"title");c(this,"_timezone");c(this,"datasets");c(this,"backend");c(this,"features");c(this,"_queries",new Map);c(this,"_controls",new Map);c(this,"_mappings",[]);c(this,"_crossFilters",[]);c(this,"_selection");c(this,"_appliedSelection");c(this,"selectionCommitted",!1);c(this,"index",0);this.title=e.title,this._timezone=e.timezone,this.datasets=r,this.backend=i,this.features=o}get queries(){return Object.fromEntries(this._queries)}get controls(){return Object.fromEntries(this._controls)}get mappings(){return[...this._mappings,...this._crossFilters]}get crossFilters(){return this._crossFilters}createQuery(e,r){this.assertNameFree(e,"query");let i=new L(e,this,r);return this._queries.set(e,i),this.notify(),i}createFilter(e,r){this.assertNameFree(e,"filter");let i=r.dataset?this.datasetIndex(r.dataset,e):this.soleDataset(e,r.field),o=new G(e,this,r,i,this.backend);return this._controls.set(e,o),this.notify(),o}createDateDrill(e,r={}){if(this.features?.dateDrill===!1)throw new u(`Date drill \'${e}\' needs a capability this workspace has not enabled. Ask an admin to turn on \\`interactive_control:date_drill\\`.`,e);this.assertNameFree(e,"date drill control");let i=new U(e,this,r);return this._controls.set(e,i),this.notify(),i}mapControl(e,r,i){if(!(e instanceof M))throw new u("mapControl expects a control as its source. To let one query cross-filter another, use app.mapCrossFilter(from, to) \\u2014 a cross-filter edge names no field.");if(this._controls.get(e.name)!==e)throw new u(`Control \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);i.aggregation&&Fe(i.aggregation,e.name);let o=new H(e,r,i.field,i.aggregation);if(this._mappings.some(a=>a.id===o.id))throw new u(`Mapping \'${o.id}\' is already declared.`,e.name);return this.assertAcyclic(o),this._mappings.push(o),this.notify(),o}mapCrossFilter(e,r){if(!(e instanceof L)||!(r instanceof L))throw new u("mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field }).");if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);if(e===r)throw new u(`Query \'${e.name}\' cannot cross-filter itself. A source keeps its own rows so it can show what is selected; filtering it would erase the very rows the reader clicked.`,e.name);if(e.declaration.dataset!==r.declaration.dataset)throw new u(`Cross-filter \'${e.name}\' -> \'${r.name}\' spans two datasets (\'${e.declaration.dataset}\' and \'${r.declaration.dataset}\'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,e.name);let i=new K(e,r);if(this._crossFilters.some(o=>o.id===i.id))throw new u(`Cross-filter \'${i.id}\' is already declared.`,e.name);return this._crossFilters.push(i),this.notify(),i}get selection(){return this._selection}get appliedSelection(){return this._appliedSelection}clearSelection(){this._selection&&(this._selection=void 0,this.notify())}setTimezone(e){this._timezone=e,this.notify()}get timezone(){return this._timezone}datasetIndex(e,r){return Te(this.datasets,e,r)}mappingsTo(e){return this._mappings.filter(r=>r.to.name===e)}selectionExpressionFor(e,r){return this.selectionFor(e,r)?.expression}selectionFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?void 0:this._crossFilters.some(a=>a.from.name===i.source&&a.to.name===e)?i:void 0}selectionConditionsFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?Se:this._crossFilters.some(a=>a.from.name===i.source&&a.to.name===e)?i.conditions:Se}drillTransformations(e){let r={};return this._mappings.forEach(i=>{if(i.to!==e)return;let o=i.from.appliedCondition;if(o?.operator!=="transform_date_drill")return;let[a]=o.values??[];typeof a=="string"&&(r[i.field]=a)}),r}select(e,r,i){if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);let o=Ge(e,r,i,this.drillTransformations(e));o?.lossy&&console.warn(`[anfra-sdk] The selection in \'${e.name}\' filters more broadly than it was made. Its conditions are combined field by field and ANDed, which cannot express "(A and B) or (C and D)", so the targets will also show combinations that were not selected. Select within one dimension, or narrow with \\`fields\\`, to avoid this.`),this._selection=o,this.notify()}get hasChanges(){return[...this._controls.values()].some(e=>e.isDirty)||this.isSelectionDirty}get isSelectionDirty(){return this.selectionCommitted?et(this._selection)!==et(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(l=>l.shouldRun(e.force));this._controls.forEach(l=>l.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(l=>{l.controller?.abort(),l.resetPage()});let i={backend:this.backend,timezone:this._timezone,bustCache:e.bustCache},o=[],a=[];return await Promise.all(r.map(async l=>{let d=new AbortController;l.controller=d;let p=l.signature();l.markExecuting();try{let E=await ge(l,this.mappingsTo(l.name),{conditions:this.selectionConditionsFor(l.name,"applied"),expression:this.selectionExpressionFor(l.name,"applied")},i,d.signal);if(Xe(l,d))return;l.markSuccess(E,p,!1),o.push(l.name)}catch(E){if(Xe(l,d)||ve(E))return;l.markError(tt(E,l.name)),a.push(l.name)}finally{l.controller===d&&(l.controller=void 0)}})),{succeeded:o,failed:a}}async refresh(){return this.execute({force:!0,bustCache:!0})}abort(){this._queries.forEach(e=>e.abort())}async fetchPage(e){let r=new AbortController;e.controller=r;let i=e.signature();e.markExecuting();try{let o=await ge(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone},r.signal);e.markSuccess(o,i,!0)}catch(o){if(e.rewindPage(),ve(o))return;let a=tt(o,e.name);throw e.markError(a),a}finally{e.controller===r&&(e.controller=void 0)}}async exportQuery(e,r={}){let{backend:i}=this;if(this.features?.export===!1||!i.exportQuery)throw new $("This host cannot make exports.",void 0,e.name);let o=Qe(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:i,timezone:this._timezone,title:this.title},r);try{return await i.exportQuery(o,r.signal??new AbortController().signal)}catch(a){throw ve(a)?a:zt(a,e.name)}}toJSON(){let e=s(r=>Object.fromEntries([...this._controls.entries()].filter(([,i])=>i.kind===r).map(([i,o])=>[i,o.toJSON()])),"byKind");return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},queries:Object.fromEntries([...this._queries.entries()].map(([r,i])=>[r,i.toJSON()])),filters:e("filter"),dateDrills:e("dateDrill"),mappings:[...this._mappings.map(r=>r.toJSON()),...this._crossFilters.map(r=>r.toJSON())]}}toInspectJSON(){return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},hasChanges:this.hasChanges,declaration:this.toJSON(),queries:Object.fromEntries([...this._queries.entries()].map(([e,r])=>[e,Pt(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,Bt(r)])),...this._selection?{selection:Ze(this._selection)}:{},...this._appliedSelection?{appliedSelection:Ze(this._appliedSelection)}:{}}}locate(e,r){let i=globalThis.document;if(!i)return!1;let o=Ke(i,e,this.index,r);return o.length?(Z(o[0]),B(i).flash(o,{kind:e,name:r,...o.length>1?{note:`in ${o.length} places`}:{}}),!0):!1}assertNameFree(e,r){Ne([...this._queries.keys(),...this._controls.keys()],e,r)}soleDataset(e,r){if(!r)return;let i=Object.keys(this.datasets);if(i.length===1)return this.datasets[i[0]];throw new u(i.length?`Filter \'${e}\' names a field but the environment has ${i.length} datasets. Say which one: ${i.join(", ")}.`:`Filter \'${e}\' names a field but the environment has no datasets.`,e)}assertAcyclic(e){let r=[...this._mappings,e],i=new Map;r.forEach(d=>{let p=d.from.name;i.set(p,[...i.get(p)??[],d.to.name])});let o=new Set,a=new Set,l=s(d=>{if(o.has(d))return!0;if(a.has(d))return!1;o.add(d);let p=(i.get(d)??[]).some(l);return o.delete(d),a.add(d),p},"walk");if([...i.keys()].some(l))throw new u(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};s(Ee,"App");var ee=Ee;var nt="0.9.0";var qt=nt,Ce=class Ce{constructor(n){c(this,"version",qt);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"features");c(this,"renderHook");if(!n?.datasets)throw new u("No datasets provided. The host must call createSdk({ datasets }) before an app can be declared.");if(!n.user)throw new u("No user provided. The host must call createSdk({ user }) before an app can be declared.");if(!n.backend)throw new u("No backend provided. The host must call createSdk({ backend }) before an app can run a query.");this.datasets=Object.freeze({...n.datasets}),this.user=Object.freeze({...n.user,permissions:Object.freeze({...n.user.permissions})}),this.indices=Object.fromEntries(Object.entries(n.datasets).map(([e,r])=>[e,new W(r)])),this.backend=n.backend,this.renderHook=n.render,this.features=Object.freeze({...n.features,export:n.features?.export??typeof n.backend.exportQuery=="function",render:n.features?.render??typeof n.render=="function",lineage:n.features?.lineage??typeof n.backend.lineage=="function"})}createApp(n={}){let e=new ee(n,this.indices,this.backend,this.features);return e.index=this._apps.length,this._apps.push(e),e}render(n){return!this.renderHook||this.features.render===!1?Promise.reject(new u("This host does not render Data Apps: check Anfra.features.render first.")):this.renderHook(n)}lineage(n,e={}){let r=Array.isArray(n)?[...n]:[n],i=s(d=>typeof d=="string"&&d.trim()!=="","named");if(r.length===0||r.some(d=>typeof d!="object"||d===null||!i(d.parent)||!i(d.child)))return Promise.reject(new u("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\' }."));if(!this.backend.lineage||this.features.lineage===!1)return Promise.reject(new $("This host cannot trace lineage: check Anfra.features.lineage first."));let{limit:o,offset:a,signal:l=new AbortController().signal}=e;return this.backend.lineage({targets:r.map(({parent:d,child:p})=>({parent:d,child:p})),...o!==void 0?{limit:o}:{},...a!==void 0?{offset:a}:{}},l)}get apps(){return this._apps}};s(Ce,"Sdk");var Re=Ce;function rt(t){return new Re(t)}s(rt,"createSdk");var q="Anfra";function it(t,n=globalThis){let e=n[q],r=q in n;return n[q]=t,()=>{r?n[q]=e:delete n[q]}}s(it,"installSandbox");function ot(t,n){let e=null,r=s(d=>d.target instanceof Element?d.target.closest(Y):null,"under"),i=s(d=>{let p=r(d);p!==e&&(e=p,n.onHover(p))},"onMove"),o=s(d=>{d.preventDefault(),d.stopPropagation();let p=r(d);p&&n.onPick(p)},"onClick"),a=s(d=>{d.key==="Escape"&&n.onCancel()},"onKey"),l={capture:!0};return t.addEventListener("mousemove",i,l),t.addEventListener("click",o,l),t.addEventListener("keydown",a,l),()=>{t.removeEventListener("mousemove",i,l),t.removeEventListener("click",o,l),t.removeEventListener("keydown",a,l)}}s(ot,"startPick");var Ae="__anfraRenderer";var jt="data-anfra-render",Jt={png:"png",pdf:"pdf"},Gt=1e4;function Ut(t,n,e,r){let i=Jt[t.format],o=t.filename?.trim();if(!o){let a=e.find(d=>d.title)?.title||n.title.trim()||"Data App",l=r&&(r.getAttribute(S.label)||t.block||t.container);o=l?`${a} - ${l}`:a}return o=o.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim()||"Data App",o.toLowerCase().endsWith(`.${i}`)?o:`${o}.${i}`}s(Ut,"filenameFor");function Ht(t,n){if(t.block!==void 0&&t.container!==void 0)throw new u("Render a block or a container, not both.",t.block);if(t.format!=="png"&&t.format!=="pdf")throw new u(`Can\'t render as \'${String(t.format)}\': the formats are \'png\' and \'pdf\'.`);let{pixelRatio:e}=t;if(e!==void 0&&!(Number.isFinite(e)&&e>0))throw new u(`pixelRatio ${String(e)} is not a positive number.`);let r=t.block!==void 0?"block":t.container!==void 0?"container":void 0;if(!r)return{element:null};let i=t.block??t.container,o=[...n.querySelectorAll(`[${S[r]}]`)].find(a=>a.getAttribute(S[r])===i);if(!o)throw new u(`No element is marked ${S[r]}="${i}" on the page.`,i);return{element:o,entity:i}}s(Ht,"targetOf");function Kt(t){return t.id===X||t.getAttribute(jt)==="skip"}s(Kt,"skip");function st(t,n){let e,r=s(()=>{let i=t[Ae];return i?Promise.resolve(i):(e??(e=n.ask.renderer().then(o=>{let a=t.document.createElement("script");a.textContent=o,(t.document.head??t.document.documentElement).appendChild(a),a.remove();let l=t[Ae];if(!l)throw new u("The host sent a renderer that did not install.");return l}).catch(o=>{throw e=void 0,o})),e)},"load");return async i=>{let o=t.document,{element:a,entity:l}=Ht(i??{},o),d=Ut(i,o,n.apps(),a);try{let E=await(await r()).draw(a,{format:i.format,pixelRatio:i.pixelRatio,skip:Kt});return await n.ask.saveFile({blob:E.blob,filename:d}),{filename:d,format:i.format,...E}}catch(p){throw p instanceof u&&p.entity?p:new u(p?.message||"The rendering failed.",l)}}}s(st,"createRender");async function at(t,n,e=Gt){let r=s(()=>n().some(o=>Object.values(o.queries).some(a=>a.state==="executing")),"busy"),i=Date.now()+e;for(;r()&&Date.now()<i;)await new Promise(o=>{t.setTimeout(o,100)});await new Promise(o=>{t.requestAnimationFrame(()=>o(void 0))})}s(at,"settle");function lt(){let t=new Error("Aborted");return t.name="AbortError",t}s(lt,"abortError");function Wt(t){switch(t?.name){case"PermissionError":return new I(t.message);case"TransportError":return new $(t.message);case"ValidationError":return new u(t.message);default:return new N(t?.message||"The query failed.")}}s(Wt,"toError");function dt(t){let n=t.document.getElementById(_e);if(!n?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let e=JSON.parse(n.textContent),r=s(f=>t.parent.postMessage(f,e.hostOrigin),"post"),i=new Map,o=1,a=!1,l;t.addEventListener("message",f=>{if(f.source!==t.parent)return;let m=f.data;switch(m?.type){case"anfra:response":{let y=i.get(m.id);if(!y)return;i.delete(m.id),m.ok?y.resolve(m.result):y.reject(Wt(m.error));return}case"anfra:inspect-watch":v(m.open);return;case"anfra:highlight":k(m.node);return;case"anfra:locate":Q(m.target);return;case"anfra:pick-watch":z(m.on);return;case"anfra:render":{let{id:y}=m;at(t,()=>x.apps).then(()=>x.render(m.request)).then(R=>r({type:"anfra:rendered",id:y,ok:!0,result:R}),R=>r({type:"anfra:rendered",id:y,ok:!1,error:{name:R?.name??"ValidationError",message:R?.message??"The rendering failed."}}));return}default:}});function d(f,m,y){return new Promise((R,te)=>{if(y.aborted){te(lt());return}let J=o++;i.set(J,{resolve:R,reject:te}),y.addEventListener("abort",()=>{i.delete(J)&&(r({type:"anfra:cancel",id:J}),te(lt()))},{once:!0}),r({type:"anfra:request",id:J,method:f,request:m})})}s(d,"call");let p={submitQuery:s((f,m)=>d("submitQuery",f,m).then(y=>(y.debug?.executedAt&&(y.debug.executedAt=new Date(y.debug.executedAt)),y)),"submitQuery"),fieldSuggestions:s((f,m)=>d("fieldSuggestions",f,m),"fieldSuggestions"),exportQuery:s((f,m)=>d("exportQuery",f,m).then(y=>(y.expiresAt=new Date(y.expiresAt),y)),"exportQuery"),lineage:s((f,m)=>d("lineage",f,m),"lineage")},E=st(t,{ask:{renderer:s(()=>d("renderer",null,new AbortController().signal),"renderer"),saveFile:s(f=>d("saveFile",f,new AbortController().signal),"saveFile")},apps:s(()=>x.apps,"apps")}),x=rt({datasets:e.datasets,user:e.user,backend:p,render:E,features:{export:!1,render:!1,lineage:!1,...e.features}}),h=t.document,b,C="",A,g;function w(){if(l=void 0,!!a)try{b=we(h,x.apps),C=JSON.stringify(b.nodes),r({type:"anfra:inspect",apps:x.apps.map(f=>f.toInspectJSON()),structure:{nodes:b.nodes,usage:b.usage}})}catch{}}s(w,"postSnapshot");function D(){a&&l===void 0&&(l=setTimeout(w,50))}s(D,"scheduleSnapshot");function F(){let f=t.MutationObserver;if(A||typeof f!="function")return;let m=new f(()=>{if(!(!a||l!==void 0))try{JSON.stringify(we(h,x.apps).nodes)!==C&&D()}catch{}});A=m,m.observe(h.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-anfra-container","data-anfra-block","data-anfra-query","data-anfra-control","data-anfra-label"]})}s(F,"observeStructure");function v(f){a=f,f?(F(),w()):(A?.disconnect(),A=void 0,z(!1),B(h).hide(),b=void 0,C="")}s(v,"setInspecting");function _(f,m){for(let y of f){if(y.key===m)return y;let R=_(y.children,m);if(R)return R}}s(_,"findNode");function k(f){let m=B(h),y=f!==null&&b?_(b.nodes,f):void 0,R=f!==null?b?.elements.get(f):void 0;if(!y||!R||!b){m.hide();return}m.show([R],We(y,R,b))}s(k,"highlight");function Q(f){if("node"in f){let m=b?.elements.get(f.node);m&&Z(m),k(f.node)}else x.apps[f.app]?.locate(f.kind,f.name);D()}s(Q,"locate");function z(f){if(!f){g?.(),g=void 0;return}if(g)return;let m=s(y=>b?.keysOf.get(y)?.[0],"keyOf");g=ot(h,{onHover:s(y=>k(y?m(y)??null:null),"onHover"),onPick:s(y=>{let R=m(y);R!==void 0&&r({type:"anfra:picked",node:R})},"onPick"),onCancel:s(()=>{z(!1),B(h).hide(),r({type:"anfra:picked",node:null})},"onCancel")})}s(z,"setPicking");let j=x.createApp.bind(x);x.createApp=f=>{let m=j(f);return m.subscribe(D),D(),m},it(x,t),r({type:"anfra:ready"})}s(dt,"bootstrap");dt(window);})();\n';
161
180
 
162
181
  // src/host/frameScript.ts
163
182
  function builtFrameScript() {
@@ -223,7 +242,11 @@ function mountDataApp(options) {
223
242
  const provision = {
224
243
  datasets: options.datasets,
225
244
  user: options.user,
226
- features: { export: typeof options.backend.exportQuery === "function", render },
245
+ features: {
246
+ export: typeof options.backend.exportQuery === "function",
247
+ render,
248
+ lineage: typeof options.backend.lineage === "function"
249
+ },
227
250
  hostOrigin: doc.defaultView?.location.origin ?? "*"
228
251
  };
229
252
  frame.srcdoc = provisionDocument(options.definition, { baseHref: options.baseHref, provision, frameScript });