@holistics/anfra-sdk 0.11.1 → 0.13.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/README.md CHANGED
@@ -128,12 +128,12 @@ const host = createHost({ // one per page
128
128
  renderPlugin(), // Anfra.render(): the host saves PNGs and PDFs the frame makes
129
129
  inspectPlugin(), // what an inspect panel needs
130
130
  ],
131
+ allowOrigins: ['https://cdn.acme.com'], // optional: more origins apps may load from
131
132
  });
132
133
 
133
134
  const mounted = host.mount({
134
135
  container: document.querySelector('#data-app')!,
135
136
  definition: await (await fetch('/appserve/files/sales/overview.html')).text(),
136
- baseHref: '/appserve/files/sales/', // where its relative URLs resolve
137
137
  datasets,
138
138
  user,
139
139
  });
@@ -143,6 +143,12 @@ await mounted.call('inspect.watch', true); // start the snapshots
143
143
  mounted.unmount(); // when done
144
144
  ```
145
145
 
146
+ A frame runs under a content policy the host puts first in its document: scripts, styles and fonts
147
+ only from a few CDNs (cdnjs, jsDelivr, esm.sh, unpkg, Google Fonts) and the host's `allowOrigins`,
148
+ images from any `https://` server, and no network beyond those origins: data reaches the app over
149
+ the bridge only. A definition is one self-contained file; nothing beside it is served. See
150
+ `contentPolicy` and docs/designs/security.md.
151
+
146
152
  `host.mount` puts the definition in an iframe with `sandbox="allow-scripts"`, as its `srcdoc`, with
147
153
  the frame's kernel, the provisioned data and each plugin's frame setup ahead of it. Every call the
148
154
  frame makes, and every call a plugin makes of another, goes through the host's one pipeline to the
package/dist/api.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Client } from 'openapi-fetch';
2
- import { ak as paths, D as DatasetDescriptor, B as Backend, f as BackendExportRequest, al as components, i as BackendQueryRequest } from './types-plgahUrN.js';
3
- import { D as DataAppError } from './errors-CKvqVaqU.js';
2
+ import { ak as paths, al as components } from './types-B9DqPgWS.js';
3
+ import { DatasetDescriptor, Backend, BackendExportRequest, BackendQueryRequest } from './app.js';
4
+ import { DataAppError } from './app.js';
4
5
 
5
6
  /** The core API, typed from anfra core's spec (`api/openapi.yaml`, generated into `schema.d.ts`). */
6
7
  type CoreClient = Client<paths>;
@@ -70,4 +71,5 @@ interface ApiErrorBody {
70
71
  */
71
72
  declare function toSdkError(status: number, body: ApiErrorBody | undefined): DataAppError;
72
73
 
73
- export { type ApiErrorBody, type CoreApiBackendOptions, type CoreClient, type LoadedDatasets, SUGGESTION_LIMIT, components, coreApiBackend, coreClient, loadDatasets, paths, toDescriptor, toExportInput, toQueryInput, toSdkError };
74
+ export { SUGGESTION_LIMIT, components, coreApiBackend, coreClient, loadDatasets, paths, toDescriptor, toExportInput, toQueryInput, toSdkError };
75
+ export type { ApiErrorBody, CoreApiBackendOptions, CoreClient, LoadedDatasets };
package/dist/app.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { S as Sdk } from './bootstrap-BkiMDMcp.js';
2
- export { A as AnfraPlugins, a as App, C as Control, b as CrossFilter, D as DateDrillControl, c as DeprecatedFeatures, E as Edge, F as Filter, d as FrameKernel, I as InstalledPlugins, M as Mapping, O as OVERLAY_ID, e as PluginApi, f as PluginMembers, g as PluginName, P as PluginSetup, Q as Query, h as STRUCTURE_ATTRIBUTES, V as VERSION, i as bootstrap, j as buildStructure, k as createSdk, p as parseRef } from './bootstrap-BkiMDMcp.js';
1
+ import { S as Sdk } from './bootstrap-DctKHBAj.js';
2
+ export { A as AnfraPlugins, a as App, C as Control, b as CrossFilter, D as DateDrillControl, c as DeprecatedFeatures, E as Edge, F as Filter, d as FrameKernel, I as InstalledPlugins, M as Mapping, O as OVERLAY_ID, e as PluginApi, f as PluginMembers, g as PluginName, P as PluginSetup, Q as Query, h as STRUCTURE_ATTRIBUTES, V as VERSION, i as bootstrap, j as buildStructure, k as createSdk, p as parseRef } from './bootstrap-DctKHBAj.js';
3
3
  export { D as DataAppError, P as PermissionError, Q as QueryError, T as TransportError, V as ValidationError } from './errors-CKvqVaqU.js';
4
- 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 QueryTimings, a7 as RenderFormat, a8 as RenderRequest, a9 as Rendering, aa as Row, ab as SdkEnvironment, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, af as SemanticType, ag as StructureKind, ah as StructureNode, ai as Unsubscribe, aj as User } from './types-plgahUrN.js';
5
- export { B as BridgeError, a as BridgeMessage, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as PluginInfo, c as Provision } from './bridge-BCJklF4M.js';
4
+ 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 QueryTimings, a7 as RenderFormat, a8 as RenderRequest, a9 as Rendering, aa as Row, ab as SdkEnvironment, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, af as SemanticType, ag as StructureKind, ah as StructureNode, ai as Unsubscribe, aj as User } from './types-B9DqPgWS.js';
5
+ export { B as BridgeError, a as BridgeMessage, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as PluginInfo, c as Provision } from './bridge-_Ez5VZV9.js';
6
6
 
7
7
  declare const SANDBOX_GLOBAL = "Anfra";
8
8
  /**
package/dist/app.js CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  createSdk,
20
20
  installSandbox,
21
21
  parseRef
22
- } from "./chunk-O3S2GQ5N.js";
22
+ } from "./chunk-LW63RQZ2.js";
23
23
  import {
24
24
  FILTER_AGGREGATIONS
25
25
  } from "./chunk-XIUFHRZE.js";
@@ -27,7 +27,7 @@ import "./chunk-ADWBOQW2.js";
27
27
  import {
28
28
  PROVISION_ELEMENT_ID
29
29
  } from "./chunk-33B2D4U5.js";
30
- import "./chunk-MIHZUF2H.js";
30
+ import "./chunk-SIITHGUD.js";
31
31
  import {
32
32
  DataAppError,
33
33
  PermissionError,
@@ -1,6 +1,6 @@
1
1
  import { D as DataAppError, V as ValidationError, Q as QueryError, P as PermissionError, T as TransportError } from './errors-CKvqVaqU.js';
2
- import { X as Listener, ai as Unsubscribe, D as DatasetDescriptor, y as ExportOptions, z as ExportResult, a8 as RenderRequest, a9 as Rendering, W as LineageTarget, U as LineageOptions, V as LineageResult, 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, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, aa as Row, Y as LocateKind, a1 as QueryDeclaration, a5 as QueryState, a3 as QueryResult, a4 as QuerySort, a as AppDeclaration, u as ExecuteOptions, v as ExecuteSummary, f as BackendExportRequest, b as AppJson, L as InspectedApp, aj as User, ab as SdkEnvironment, Q as InspectedStructure } from './types-plgahUrN.js';
3
- import { b as PluginInfo } from './bridge-BCJklF4M.js';
2
+ import { X as Listener, ai as Unsubscribe, D as DatasetDescriptor, y as ExportOptions, z as ExportResult, a8 as RenderRequest, a9 as Rendering, W as LineageTarget, U as LineageOptions, V as LineageResult, 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, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, aa as Row, Y as LocateKind, a1 as QueryDeclaration, a5 as QueryState, a3 as QueryResult, a4 as QuerySort, a as AppDeclaration, u as ExecuteOptions, v as ExecuteSummary, f as BackendExportRequest, b as AppJson, L as InspectedApp, aj as User, ab as SdkEnvironment, Q as InspectedStructure } from './types-B9DqPgWS.js';
3
+ import { b as PluginInfo } from './bridge-_Ez5VZV9.js';
4
4
 
5
5
  interface NotificationTarget {
6
6
  notifyChange(): void;
@@ -721,4 +721,5 @@ type PluginSetup = readonly [name: string, setup: ((kernel: FrameKernel) => void
721
721
  /** Provision the SDK in `win` from its host, run the plugins' setups, and install it. Returns once `Anfra` exists. */
722
722
  declare function bootstrap(win: Window, setups?: readonly PluginSetup[]): void;
723
723
 
724
- export { type AnfraPlugins as A, Control as C, DateDrillControl as D, type Edge as E, Filter as F, InstalledPlugins as I, Mapping as M, OVERLAY_ID as O, type PluginSetup as P, Query as Q, Sdk as S, VERSION as V, App as a, CrossFilter as b, type DeprecatedFeatures as c, type FrameKernel as d, type PluginApi as e, type PluginMembers as f, type PluginName as g, ATTR as h, bootstrap as i, buildStructure as j, createSdk as k, parseRef as p };
724
+ export { Control as C, DateDrillControl as D, Filter as F, InstalledPlugins as I, Mapping as M, OVERLAY_ID as O, Query as Q, Sdk as S, VERSION as V, App as a, CrossFilter as b, ATTR as h, bootstrap as i, buildStructure as j, createSdk as k, parseRef as p };
725
+ export type { AnfraPlugins as A, Edge as E, PluginSetup as P, DeprecatedFeatures as c, FrameKernel as d, PluginApi as e, PluginMembers as f, PluginName as g };
@@ -1,4 +1,4 @@
1
- import { D as DatasetDescriptor, aj as User } from './types-plgahUrN.js';
1
+ import { D as DatasetDescriptor, aj as User } from './types-B9DqPgWS.js';
2
2
 
3
3
  /**
4
4
  * The bridge: the postMessage protocol between a Data App's frame (`app`'s bootstrap) and the
@@ -69,4 +69,5 @@ type HostMessage = Exclude<BridgeMessage, {
69
69
  type: 'anfra:ready';
70
70
  }>;
71
71
 
72
- export { type BridgeError as B, type FrameMessage as F, type HostMessage as H, PROVISION_ELEMENT_ID as P, type BridgeMessage as a, type PluginInfo as b, type Provision as c };
72
+ export { PROVISION_ELEMENT_ID as P };
73
+ export type { BridgeError as B, FrameMessage as F, HostMessage as H, BridgeMessage as a, PluginInfo as b, Provision as c };
package/dist/build.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { F as FrameHalf } from './plugin-C5cihcQD.js';
1
+ import { FrameHalf } from './host.js';
2
2
 
3
3
  /**
4
4
  * @holistics/anfra-sdk/build: building an SDK plugin's frame half into the script source a host
@@ -17,4 +17,5 @@ interface BuildFrameHalfOptions {
17
17
  /** Build a frame half: the setup, and the body if there is one, as script source for `plugin.frame`. */
18
18
  declare function buildFrameHalf(options: BuildFrameHalfOptions): Promise<FrameHalf>;
19
19
 
20
- export { type BuildFrameHalfOptions, buildFrameHalf };
20
+ export { buildFrameHalf };
21
+ export type { BuildFrameHalfOptions };
@@ -9,7 +9,7 @@ import {
9
9
  } from "./chunk-33B2D4U5.js";
10
10
  import {
11
11
  version
12
- } from "./chunk-MIHZUF2H.js";
12
+ } from "./chunk-SIITHGUD.js";
13
13
  import {
14
14
  DataAppError,
15
15
  PermissionError,
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.11.1";
2
+ var version = "0.13.0";
3
3
 
4
4
  export {
5
5
  version
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 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 QueryTimings, a7 as RenderFormat, a8 as RenderRequest, a9 as Rendering, aa as Row, ab as SdkEnvironment, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, af as SemanticType, ag as StructureKind, ah as StructureNode, ai as Unsubscribe, aj as User } from './types-plgahUrN.js';
3
- export { B as BridgeError, a as BridgeMessage, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as PluginInfo, c as Provision } from './bridge-BCJklF4M.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 QueryTimings, a7 as RenderFormat, a8 as RenderRequest, a9 as Rendering, aa as Row, ab as SdkEnvironment, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, af as SemanticType, ag as StructureKind, ah as StructureNode, ai as Unsubscribe, aj as User } from './types-B9DqPgWS.js';
3
+ export { B as BridgeError, a as BridgeMessage, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as PluginInfo, c as Provision } from './bridge-_Ez5VZV9.js';
package/dist/host.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { b as PluginInfo, c as Provision } from './bridge-BCJklF4M.js';
2
- import { D as DatasetDescriptor, aj as User } from './types-plgahUrN.js';
3
- import { C as CallOptions, P as Plugin, M as Middleware } from './plugin-C5cihcQD.js';
4
- export { a as CallContext, b as CallDefinition, c as CallHandler, d as Caller, E as EventCheck, F as FrameHalf, H as HandlerCallOptions, e as HandlerContext, f as HostHalf, g as MountContext, h as definePlugin } from './plugin-C5cihcQD.js';
1
+ import { PluginInfo, Provision } from './app.js';
2
+ import { DatasetDescriptor, User } from './app.js';
3
+ import { C as CallOptions, P as Plugin, M as Middleware } from './plugin-056-SKwd.js';
4
+ export { a as CallContext, b as CallDefinition, c as CallHandler, d as Caller, E as EventCheck, F as FrameHalf, H as HandlerCallOptions, e as HandlerContext, f as HostHalf, g as MountContext, h as definePlugin } from './plugin-056-SKwd.js';
5
5
 
6
6
  interface HostOptions {
7
7
  /** The plugins this page's Data Apps get. `core` is required: the app model runs its queries with it. */
@@ -10,14 +10,18 @@ interface HostOptions {
10
10
  middleware?: readonly Middleware[];
11
11
  /** The frame script; the one built into this package unless given (tests). */
12
12
  frameScript?: string;
13
+ /**
14
+ * Origins a Data App may load scripts, styles, fonts and images from, and fetch them from, beside
15
+ * the policy's own CDNs: each `https://<host>[:<port>]`, nothing after it. Never a way to the
16
+ * network at large (docs/designs/security.md).
17
+ */
18
+ allowOrigins?: readonly string[];
13
19
  }
14
20
  interface MountOptions {
15
21
  /** Where the frame goes: it is appended to this element. */
16
22
  container: HTMLElement;
17
23
  /** The Data App definition: its HTML, as its author wrote it. */
18
24
  definition: string;
19
- /** Where the definition's relative URLs resolve. */
20
- baseHref: string;
21
25
  datasets: Record<string, DatasetDescriptor>;
22
26
  user: User;
23
27
  title?: string;
@@ -51,8 +55,8 @@ interface Host {
51
55
  declare function createHost(options: HostOptions): Host;
52
56
 
53
57
  interface ProvisionOptions {
54
- /** Where the definition's relative URLs resolve: the directory it was read from. */
55
- baseHref: string;
58
+ /** The frame's content policy (`contentPolicy`), set before anything of the definition's. */
59
+ contentPolicy: string;
56
60
  provision: Provision;
57
61
  /** The frame script (`@holistics/anfra-sdk/app`'s kernel, as `__anfraKernel`), run before any of the definition's own. */
58
62
  frameScript: string;
@@ -72,11 +76,34 @@ declare function composeFrameScript(frameScript: string, setups?: readonly {
72
76
  setup: string;
73
77
  }[]): string;
74
78
  /**
75
- * A Data App's frame document: its definition, with its base URL, the provision data and the frame
76
- * script (the kernel and the plugins' setups) added at the top of its <head> (after <meta charset> when there is one, so the encoding is
77
- * still declared first), so `Anfra` exists before the definition's first script runs. The
78
- * definition itself never mentions the SDK.
79
+ * A Data App's frame document: its definition, with its content policy as the first element the
80
+ * parser meets, so it governs every script, style and fetch of the definition's, even one written
81
+ * ahead of its `<meta charset>`; then the provision data and the frame script (the kernel and the
82
+ * plugins' setups) at the top of its <head> (after <meta charset> when there is one, so the
83
+ * encoding is still declared first), so `Anfra` exists before the definition's first script runs.
84
+ * The definition itself never mentions the SDK.
79
85
  */
80
86
  declare function provisionDocument(definition: string, options: ProvisionOptions): string;
81
87
 
82
- export { CallOptions, type Host, type HostOptions, Middleware, type MountOptions, type MountedDataApp, Plugin, type ProvisionOptions, composeFrameScript, createHost, provisionDocument };
88
+ /**
89
+ * The content policy a Data App's frame runs under: libraries from a short list of CDNs, data only
90
+ * over the bridge. The sandbox keeps the frame away from the page around it; this keeps it away
91
+ * from the network, so an app, or a library it loads, cannot send what its reader can query to a
92
+ * server of its choosing (docs/designs/security.md).
93
+ */
94
+ /** Where an app may load scripts from, and styles and fonts beside them. */
95
+ declare const SCRIPT_ORIGINS: readonly string[];
96
+ /**
97
+ * An origin a host may add: `https://` with a host and nothing after it, as `URL` writes it, so it
98
+ * cannot widen a directive (a scheme, a wildcard) or end one (a space, a `;`).
99
+ */
100
+ declare function checkOrigin(origin: unknown): string;
101
+ /**
102
+ * The policy, with a host's own origins added to every source an app loads from, and to what it
103
+ * may fetch: the render plugin fetches the images, stylesheets and fonts it embeds in a picture.
104
+ * Nothing else is reachable. `'self'` is absent: the frame's origin is opaque, so it matches nothing.
105
+ */
106
+ declare function contentPolicy(allowOrigins?: readonly string[]): string;
107
+
108
+ export { CallOptions, Middleware, Plugin, SCRIPT_ORIGINS, checkOrigin, composeFrameScript, contentPolicy, createHost, provisionDocument };
109
+ export type { Host, HostOptions, MountOptions, MountedDataApp, ProvisionOptions };
package/dist/host.js CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  import "./chunk-PKBMQBKP.js";
17
17
 
18
18
  // anfra-sdk:anfra-sdk:frame-script
19
- var anfra_sdk_frame_script_default = '"use strict";var __anfraKernel=(()=>{var M=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var pt=Object.prototype.hasOwnProperty;var ut=(t,n,e)=>n in t?M(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var o=(t,n)=>M(t,"name",{value:n,configurable:!0});var ft=(t,n)=>{for(var e in n)M(t,e,{get:n[e],enumerable:!0})},mt=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of ct(n))!pt.call(t,i)&&i!==e&&M(t,i,{get:()=>n[i],enumerable:!(r=dt(n,i))||r.enumerable});return t};var ht=t=>mt(M({},"__esModule",{value:!0}),t);var c=(t,n,e)=>ut(t,typeof n!="symbol"?n+"":n,e);var rn={};ft(rn,{bootstrap:()=>at});var Se="anfra-provision";var U=class U 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(U,"DataAppError");var S=U,H=class H extends S{};o(H,"ValidationError");var u=H,Y=class Y extends S{constructor(e,r,i){super(e,r);c(this,"cause");this.cause=i}};o(Y,"QueryError");var D=Y,W=class W extends S{};o(W,"PermissionError");var R=W,X=class X extends S{constructor(e,r,i){super(e,i);c(this,"status");this.status=r}};o(X,"TransportError");var C=X;function Ce(){let t=new Error("Aborted");return t.name="AbortError",t}o(Ce,"abortError");function gt(t){return t?.name==="AbortError"}o(gt,"isAbortError");var yt=new Set(["ValidationError","QueryError","PermissionError","TransportError"]);function bt(t){let n=t;return n instanceof Error&&yt.has(n.name)?{name:n.name,message:n.message||"The call failed."}:{name:"QueryError",message:"The call failed."}}o(bt,"toBridgeError");function wt(t){switch(t?.name){case"PermissionError":return new R(t.message);case"TransportError":return new C(t.message);case"ValidationError":return new u(t.message);default:return new D(t?.message||"The call failed.")}}o(wt,"fromBridgeError");function Ae(t,n){let e=new Map,r=new Map,i=1,s=o((l,a,d)=>{let p=new AbortController;r.set(l,p),Promise.resolve().then(()=>n.answer(a,d,p.signal)).then(g=>{p.signal.aborted||t({type:"anfra:result",id:l,ok:!0,result:g})}).catch(g=>{p.signal.aborted||gt(g)||t({type:"anfra:result",id:l,ok:!1,error:bt(g)})}).finally(()=>{r.get(l)===p&&r.delete(l)})},"answer");return{call(l,a,d){return new Promise((p,g)=>{if(d?.aborted){g(Ce());return}let E=i++;e.set(E,{resolve:p,reject:g}),d?.addEventListener("abort",()=>{e.delete(E)&&(t({type:"anfra:cancel",id:E}),g(Ce()))},{once:!0}),t({type:"anfra:call",id:E,name:l,request:a})})},emit(l,a){t({type:"anfra:event",name:l,payload:a})},receive(l){switch(l?.type){case"anfra:call":return s(l.id,l.name,l.request),!0;case"anfra:result":{let a=e.get(l.id);return a&&(e.delete(l.id),l.ok?a.resolve(l.result):a.reject(wt(l.error))),!0}case"anfra:cancel":return r.get(l.id)?.abort(),r.delete(l.id),!0;case"anfra:event":return n.event(l.name,l.payload),!0;default:return!1}},close(l){r.forEach(a=>a.abort()),r.clear(),e.forEach(({reject:a})=>a(l)),e.clear()}}}o(Ae,"createEndpoint");var Z=class Z{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(Z,"Observable");var $=Z;var De=["year","quarter","month","week","day","hour","minute"];function xt(t,n){if(!De.includes(n))throw new u(`Invalid grain \'${n}\'. Expected one of: ${De.join(", ")}.`,t)}o(xt,"assertGrain");function Re(t,n){return n?(xt(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}o(Re,"drillCondition");function kt(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(kt,"inferType");function Et(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}o(Et,"sameCondition");var ee=class ee extends ${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&&!Et(this.pending,this.applied)}setCondition(e){this.pending=e,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};o(ee,"Control");var T=ee,te=class te extends T{constructor(e,r,i,s,l){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=l,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??kt(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(te,"Filter");var P=te,ne=class ne extends T{constructor(e,r,i={}){super(e,r,Re(e,i.default));c(this,"kind","dateDrill");c(this,"declaration");this.declaration=i}setGrain(e){this.setCondition(Re(this.name,e))}toJSON(){return this.declaration}};o(ne,"DateDrillControl");var z=ne;var v={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},_e=`[${v.container}],[${v.block}],[${v.query}],[${v.control}]`;function $e(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}o($e,"parseRef");var Te=o(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Oe(t,n,e,r){let i=n==="query"?v.query:v.control;return[...t.querySelectorAll(`[${i}]`)].filter(s=>Te(s.getAttribute(i)).some(l=>{let a=$e(l);return a?.app===e&&a.name===r}))}o(Oe,"markersFor");var vt=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 Fe(t,n){var E;let e=[],r=new Map,i=new Map,s=new Map,l=new Map,a={container:new Set,block:new Set},d={},p=o((h,f,y)=>{let b=h?s.get(h).children:e,m=h?`${s.get(h).key}.`:"",w={...f,key:`${m}${b.length}`,children:[]};return b.push(w),r.set(w.key,y),i.set(y,[...i.get(y)??[],w.key]),w},"place");for(let h of t.querySelectorAll(_e)){let f=h.parentElement?.closest(_e)??null,y=h.getAttribute(v.container),b=h.getAttribute(v.block),m=h.getAttribute(v.label)??void 0,w=f&&(l.get(f)==="block"?f:f.closest(`[${v.block}]`)),_;if(y!==null||b!==null){let k=y!==null?"container":"block",A=(y??b??"").trim(),x=[];y!==null&&b!==null&&x.push("This element is marked as a container and as a block. It counts as a container."),A?a[k].has(A)?x.push(`Another ${k} already has the id "${A}".`):a[k].add(A):x.push(`This ${k} has no id.`),w&&x.push(`A block can\'t hold a ${k}. This one is inside the block "${w.getAttribute(v.block)}".`),_=p(f,{kind:k,id:A,...m!==void 0?{label:m}:{},problems:x},h),s.set(h,_),l.set(h,k)}let N=_?h:f;for(let k of["query","control"])for(let A of Te(h.getAttribute(k==="query"?v.query:v.control))){let x=$e(A),L=[];if(x?vt(n,k,x)||L.push(n[x.app]?`No ${k} is called "${x.name}" in app ${x.app}.`:`The page has no app ${x.app}.`):L.push(`Can\'t read "${A}". Write the ${k}\'s name, or app/name when the page has several apps.`),p(N,{kind:k,name:x?.name??A,app:x?.app??0,problems:L},h),x&&!L.length){let lt=`${x.app}/${x.name}`,Ee=d[E=`${k}:${lt}`]??(d[E]={elements:new Set,blocks:new Set});Ee.elements.add(h);let ve=_?.kind==="block"?_.id:w?.getAttribute(v.block);ve&&Ee.blocks.add(ve)}}}let g=Object.fromEntries(Object.entries(d).map(([h,f])=>[h,{markers:f.elements.size,blocks:[...f.blocks]}]));return{nodes:e,usage:g,elements:r,keysOf:i}}o(Fe,"buildStructure");var Ne="data-anfra-layer",St="position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";function Ct(t){let n=t.querySelector(`[${Ne}]`);if(n instanceof(t.defaultView?.HTMLElement??HTMLElement))return n;let e=t.createElement("div");return e.setAttribute(Ne,""),e.setAttribute("style",St),(t.body??t.documentElement).appendChild(e),e}o(Ct,"layerOf");function Q(t,n){let e=Ct(t),r=[...e.children].find(s=>s.getAttribute("data-part")===n);if(r?.shadowRoot)return r.shadowRoot;let i=t.createElement("div");return i.setAttribute("data-part",n),e.appendChild(i),i.attachShadow({mode:"open"})}o(Q,"layerRoot");var Me="anfra-overlay",At=1500,Dt="position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;",Rt="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);",_t={kind:"color:#94a3b8;",name:"color:#93c5fd;font-weight:700;",label:"color:#f8fafc;",note:"color:#94a3b8;",size:"color:#94a3b8;margin-left:10px;"},ie=class ie{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=Q(n,"anfra"),r=e.getElementById(Me);r instanceof(n.defaultView?.HTMLElement??HTMLElement)?this.root=r:(this.root=n.createElement("div"),this.root.id=Me,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),e.appendChild(this.root))}show(n,e){if(this.clearTimer(),this.root.isConnected||Q(this.doc,"anfra").appendChild(this.root),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=At){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(a=>{let d=a.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${Dt}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),l=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${Rt}left:${l}px;top:${Math.min(s,i-24)}px;`);for(let a of["kind","name","label","note","size"]){let d=this.text[a];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",_t[a]),p.setAttribute("data-part",a),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};o(ie,"Overlay");var re=ie,Qe=new WeakMap;function V(t){let n=Qe.get(t);return n||(n=new re(t),Qe.set(t,n)),n}o(V,"overlayFor");function Ie(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}o(Ie,"scrollTo");function oe(t,n,e,r,i){if(r in n||t.has(r))throw new u(`Plugin \'${r}\' can\'t add \'${r}\' to a ${e}: it already has one.`);t.set(r,i)}o(oe,"addExtension");function j(t,n){return n?.forEach((e,r)=>{let i=!1,s;Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){return i||(s=e(t),i=!0),s}})}),t}o(j,"applyExtensions");var $t="anfra.body",se="__anfraBodyExports",Tt={DataAppError:S,ValidationError:u,QueryError:D,PermissionError:R,TransportError:C};function Ot(t,n){let e=t,r=t.document.createElement("script");r.textContent=`(function () { var __anfraBody;\n${n}\n;self[${JSON.stringify(se)}] = __anfraBody; })();`,(t.document.head??t.document.documentElement).appendChild(r),r.remove();let i=e[se];if(delete e[se],!i)throw new u("The host sent a plugin body that did not run.");return i.default??i}o(Ot,"runBody");function Be(t,n,e){let{window:r,sdk:i,endpoint:s}=n,l;return{plugin:t,window:r,sdk:i,errors:Tt,get overlay(){return V(r.document)},structure:o(()=>Fe(r.document,i.apps),"structure"),call:o((a,d,p)=>s.call(a,d??null,p),"call"),emit:o((a,d)=>s.emit(`${t}.${a}`,d??null),"emit"),handle(a,d){n.handlers.set(`${t}.${a}`,d)},on(a,d){let p=`${t}.${a}`;n.listeners.has(p)||n.listeners.set(p,new Set),n.listeners.get(p).add(d)},onApp(a){n.appListeners.add(a),i.apps.forEach(d=>a(d))},provide(a){if(t in i)throw new u(`Plugin \'${t}\' can\'t add a member Anfra already has.`);Object.defineProperty(i,t,{value:a,enumerable:!0})},provideOnQuery:o(a=>oe(i.extensions.query,e.Query.prototype,"query",t,a),"provideOnQuery"),provideOnControl:o(a=>oe(i.extensions.control,e.Control.prototype,"control",t,a),"provideOnControl"),layer:o(()=>Q(r.document,t),"layer"),body(){return l??(l=s.call($t,{plugin:t}).then(a=>Ot(r,a)).catch(a=>{throw l=void 0,a})),l}}}o(Be,"createKernel");var ae=class ae extends ${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._result.meta.hasMore??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))}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(l=>JSON.stringify(e.fields.map(a=>l[a]??null)),"key"),s=new Set(e.rows.map(i));return r.filter(l=>s.has(i(l)))}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(ae,"Query");var O=ae;var le=class le{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(le,"Mapping");var J=le,de=class de{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(de,"CrossFilter");var q=de;var ce=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function Ft(t,n){let e=t.length+1,r=n.length+1,i=Array.from({length:r},(s,l)=>l);for(let s=1;s<e;s++){let l=[s];for(let a=1;a<r;a++)l[a]=Math.min(i[a]+1,l[a-1]+1,i[a-1]+(t[s-1]===n[a-1]?0:1));i=l}return i[r-1]}o(Ft,"editDistance");function Nt(t,n){let e,r=1/0;n.forEach(s=>{let l=Ft(t.toLowerCase(),s.toLowerCase());l<r&&(r=l,e=s)});let i=Math.max(2,Math.floor(t.length/3));return r<=i?e:void 0}o(Nt,"suggest");function F(t,n,e){let r=Nt(n,e);return r?`${t} Did you mean \'${r}\'?`:t}o(F,"withSuggestion");var pe=class pe{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(F(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};o(pe,"DatasetIndex");var G=pe;function Le(t,n,e){let r=t[n];if(r)return r;throw new u(F(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}o(Le,"resolveDataset");function Pe(t,n){if(!ce.includes(t))throw new u(F(`Invalid filter aggregation \'${t}\'.`,t,[...ce]),n)}o(Pe,"assertValidFilterAggregation");function ze(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(ze,"assertUniqueName");function Mt(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(Mt,"toFilter");function Qt(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(Qt,"toDateDrill");function It(t,n){let e=n.columns??[],r=(n.values??[]).map(s=>{let l={};return e.forEach((a,d)=>{l[a.name]=s[d]}),l}),{pageSize:i}=t;return{columns:e,rows:r,meta:{...i!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??i,...n.meta?.hasMore!==void 0?{hasMore:n.meta.hasMore}:{}}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}o(It,"toResult");function Ve(t,n,e,r){let i=n.map(d=>Mt(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=n.map(d=>Qt(d,d.from.appliedCondition)).filter(d=>d!==void 0),l=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),a=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...i,...l],conditions:a,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:s},...r.timezone?{timezone:r.timezone}:{}}}o(Ve,"buildQuery");function Bt(t,n,e,r){return{...Ve(t,n,e,r),...t.pageSize!==void 0?{page:t.page,pageSize:t.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}o(Bt,"buildRequest");function Lt(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}o(Lt,"defaultExportFilename");function je(t,n,e,r,i){let s=i.format??"csv",l=s==="csv"?{bom:!0,...i.formatOptions}:i.formatOptions;return{...Ve(t,n,e,r),format:s,...l?{formatOptions:l}:{},filename:i.filename?.trim()||Lt(t,r.title)}}o(je,"buildExportRequest");async function ue(t,n,e,r,i){let s=Bt(t,n,e,r),l=await r.backend.submitQuery(s,i);return It(t,l)}o(ue,"runQuery");function Pt(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return jt(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(Pt,"literal");function Je(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${Pt(n,e)}`}o(Je,"equals");var zt=new Set(["NaN","Infinity","-Infinity"]),Vt=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function jt(t){let n=Vt.exec(t);if(!n)throw zt.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 l=r+i,a=r.length+Number(s),d;return a<=0?d=`0.${"0".repeat(-a)}${l}`:a>=l.length?d=l+"0".repeat(a-l.length):d=`${l.slice(0,a)}.${l.slice(a)}`,e+d.replace(/^0+(?=\\d)/,"")}o(jt,"numberLiteral");function qe(t,n,e){return`${t} matches @(${n} until ${e})`}o(qe,"dateRange");function Ge(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(Ge,"combine");var Ke=o(t=>Ge("and",t),"and"),Ue=o(t=>Ge("or",t),"or");var Jt=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,qt={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function He(t){if(typeof t!="string")return;let n=Jt.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(He,"parseStamp");function I(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(I,"format");function Ye(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}o(Ye,"toMs");function fe(t){let n=He(t);if(n)return I(Ye(n),n.hasTime)}o(fe,"normalise");function me(t,n){let e=He(t);if(!e)return;let{year:r,month:i,day:s,hour:l,minute:a,second:d,hasTime:p}=e;return I(n==="year"?Date.UTC(r+1,i,s,l,a,d):n==="quarter"?Date.UTC(r,i+3,s,l,a,d):n==="month"?Date.UTC(r,i+1,s,l,a,d):Ye(e)+qt[n],p)}o(me,"addGrain");function We(t){if(t?.startsWith("datetrunc "))return t.slice(10)}o(We,"grainOf");function Gt(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(Gt,"distinct");function Kt(t,n){let e=t.map(fe);if(e.some(i=>i===void 0))return!1;let r=e.slice().sort();for(let i=1;i<r.length;i+=1)if(me(r[i-1],n)!==r[i])return!1;return!0}o(Kt,"isContiguous");function Ut(t,n,e){let r=n.map(fe);if(r.some(d=>d===void 0))return;let i=r.slice().sort(),s=i[0],l=me(i[i.length-1],e);if(!l)return;let a=Kt(n,e);return{condition:{field:t,operator:"matches",values:[`${s} until ${l}`]},admits:a?n.length:Number.POSITIVE_INFINITY,lossy:!a}}o(Ut,"dateRange");function Ht(t,n,e){let r=e.filter(a=>a!=null),i=Gt(r);if(!i.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let s=r.length!==e.length,l=We(n);if(l){let a=Ut(t,i,l);if(a)return{...a,lossy:a.lossy||s}}return{condition:{field:t,operator:"is",values:i},admits:i.length,lossy:s}}o(Ht,"deriveOne");function Xe(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}o(Xe,"fieldReferenceOf");function Yt(t,n,e,r){try{let i=e.map(s=>Ke(n.map(l=>{let a=t.get(l),d=Xe(a),p=s[l]??null,g=We(r[d]);if(g&&typeof p=="string"){let E=fe(p),h=me(p,g);if(E&&h)return qe(d,E,h)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return Je(d,p,a.semantic_type)})));return Ue(i)}catch{return}}o(Yt,"selectionExpression");function Ze(t,n,e,r={}){let i=t.result?.columns??[],s=new Map(i.map(m=>[m.name,m]));e?.forEach(m=>{let w=s.get(m);if(w){if(w.adhoc)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${m}\': 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 \'${m}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new u(F(`Query \'${t.name}\' has no column \'${m}\' in its last result.`,m,[...s.keys()]),t.name)});let l=i.filter(m=>!m.isMeasure),a=l.filter(m=>!m.adhoc).map(m=>m.name),d=e?[...e]:a;if(!n.length||!d.length)return;let p=[],g=1,E=!e&&a.length!==l.length,h=!1;d.forEach(m=>{let w=s.get(m),_=Xe(w),N=Ht(_,r[_],n.map(k=>k[m]));p.push(N.condition),g*=N.admits,h=h||N.lossy});let f=new Set(n.map(m=>JSON.stringify(d.map(w=>m[w]??null))));g>f.size&&(h=!0);let y=p.sort((m,w)=>m.field.localeCompare(w.field)),b={source:t.name,rows:[...n],fields:d};if(h){let m=Yt(s,d,n,r);if(m)return{...b,conditions:[],expression:m,lossy:E}}return{...b,conditions:y,lossy:E||h}}o(Ze,"deriveSelection");var he=Object.freeze([]);function ge(t){return t instanceof Error&&t.name==="AbortError"}o(ge,"isAbort");function et(t,n){return t.controller!==n}o(et,"superseded");function Wt(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(Wt,"inspectError");function Xt(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:Wt(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}o(Xt,"inspectQuery");function Zt(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}o(Zt,"inspectControl");function tt(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(tt,"inspectSelection");function nt(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}o(nt,"selectionKey");function rt(t,n){return t instanceof S?t:new D(t?.message??"The query failed.",n,t)}o(rt,"toDataAppError");function en(t,n){if(t instanceof S&&t.entity)return t;let e=t?.message||"The export failed.";return t instanceof R?new R(e,n):t instanceof C?new C(e,t.status,n):t instanceof u?new u(e,n):new D(e,n,t)}o(en,"toExportError");var ye=class ye extends ${constructor(e,r,i,s,l){super();c(this,"extensions",l);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=j(new O(e,this,r),this.extensions?.query);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=j(new P(e,this,r,i,this.backend),this.extensions?.control);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=j(new z(e,this,r),this.extensions?.control);return this._controls.set(e,i),this.notify(),i}mapControl(e,r,i){if(!(e instanceof T))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&&Pe(i.aggregation,e.name);let s=new J(e,r,i.field,i.aggregation);if(this._mappings.some(l=>l.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 O)||!(r instanceof O))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 q(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 Le(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(l=>l.from.name===i.source&&l.to.name===e)?i:void 0}selectionConditionsFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?he:this._crossFilters.some(l=>l.from.name===i.source&&l.to.name===e)?i.conditions:he}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[l]=s.values??[];typeof l=="string"&&(r[i.field]=l)}),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=Ze(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?nt(this._selection)!==nt(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(a=>a.shouldRun(e.force));this._controls.forEach(a=>a.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(a=>{a.controller?.abort(),a.resetPage()});let i={backend:this.backend,timezone:this._timezone,bustCache:e.bustCache},s=[],l=[];return await Promise.all(r.map(async a=>{let d=new AbortController;a.controller=d;let p=a.signature();a.markExecuting();try{let g=await ue(a,this.mappingsTo(a.name),{conditions:this.selectionConditionsFor(a.name,"applied"),expression:this.selectionExpressionFor(a.name,"applied")},i,d.signal);if(et(a,d))return;a.markSuccess(g,p,!1),s.push(a.name)}catch(g){if(et(a,d)||ge(g))return;a.markError(rt(g,a.name)),l.push(a.name)}finally{a.controller===d&&(a.controller=void 0)}})),{succeeded:s,failed:l}}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 ue(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(),ge(s))return;let l=rt(s,e.name);throw e.markError(l),l}finally{e.controller===r&&(e.controller=void 0)}}async exportQuery(e,r,i){let s=je(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone,title:this.title},r);try{return await i(s,r.signal??new AbortController().signal)}catch(l){throw ge(l)?l:en(l,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,Xt(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,Zt(r)])),...this._selection?{selection:tt(this._selection)}:{},...this._appliedSelection?{appliedSelection:tt(this._appliedSelection)}:{}}}locate(e,r){let i=globalThis.document;if(!i)return!1;let s=Oe(i,e,this.index,r);return s.length?(Ie(s[0]),V(i).flash(s,{kind:e,name:r,...s.length>1?{note:`in ${s.length} places`}:{}}),!0):!1}assertNameFree(e,r){ze([...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,l=new Set,a=o(d=>{if(s.has(d))return!0;if(l.has(d))return!1;s.add(d);let p=(i.get(d)??[]).some(a);return s.delete(d),l.add(d),p},"walk");if([...i.keys()].some(a))throw new u(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};o(ye,"App");var K=ye;var it="0.11.1";var xe=class xe{constructor(n){c(this,"list");this.list=Object.freeze(n.map(({name:e,version:r})=>Object.freeze({name:e,version:r})))}has(n){return this.list.some(e=>e.name===n)}version(n){return this.list.find(e=>e.name===n)?.version}};o(xe,"InstalledPlugins");var be=xe,nn=it,ke=class ke{constructor(n){c(this,"version",nn);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"plugins");c(this,"gates");c(this,"deprecatedFeatures");c(this,"extensions",{query:new Map,control:new Map});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 G(r)])),this.backend=n.backend,this.gates=Object.freeze({...n.features}),this.plugins=new be(n.plugins??[])}get features(){return this.deprecatedFeatures||(console.warn("anfra: Anfra.features is deprecated and will be removed. Check Anfra.plugins.has(\'export\'), Anfra.plugins.has(\'render\') or Anfra.plugins.has(\'lineage\') instead."),this.deprecatedFeatures=Object.freeze({...this.gates,export:this.plugins.has("export"),render:this.plugins.has("render"),lineage:this.plugins.has("lineage")})),this.deprecatedFeatures}createApp(n={}){let e=new K(n,this.indices,this.backend,this.gates,this.extensions);return e.index=this._apps.length,this._apps.push(e),e}get apps(){return this._apps}};o(ke,"Sdk");var we=ke;function ot(t){return new we(t)}o(ot,"createSdk");var B="Anfra";function st(t,n=globalThis){let e=n[B],r=B in n;return n[B]=t,()=>{r?n[B]=e:delete n[B]}}o(st,"installSandbox");function at(t,n=[]){let e=t.document.getElementById(Se);if(!e?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let r=JSON.parse(e.textContent),i=o(f=>t.parent.postMessage(f,r.hostOrigin),"post"),s=new Map,l=new Map,a=Ae(i,{answer:o(async(f,y,b)=>{let m=s.get(f);if(!m)throw new C(`Nothing in this frame answers \'${f}\'.`);return m(y,b)},"answer"),event:o((f,y)=>{l.get(f)?.forEach(b=>{try{b(y)}catch{}})},"event")});t.addEventListener("message",f=>{f.source===t.parent&&a.receive(f.data)});let d={submitQuery:o((f,y)=>a.call("core.submitQuery",f,y).then(b=>(b.debug?.executedAt&&(b.debug.executedAt=new Date(b.debug.executedAt)),b)),"submitQuery"),fieldSuggestions:o((f,y)=>a.call("core.fieldSuggestions",f,y),"fieldSuggestions")},p=ot({datasets:r.datasets,user:r.user,backend:d,plugins:r.plugins??[]}),g=new Set,E=p.createApp.bind(p);p.createApp=f=>{let y=E(f);return g.forEach(b=>{try{b(y)}catch{}}),y};let h={window:t,sdk:p,endpoint:a,handlers:s,listeners:l,appListeners:g};for(let[f,y]of n)if(typeof y=="function")try{y(Be(f,h,{Query:O,Control:T}))}catch(b){t.console?.error(`anfra: plugin \'${f}\' failed to set up:`,b)}st(p,t),i({type:"anfra:ready"})}o(at,"bootstrap");return ht(rn);})();\n';
19
+ var anfra_sdk_frame_script_default = '"use strict";var __anfraKernel=(()=>{var M=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var pt=Object.prototype.hasOwnProperty;var ut=(t,n,e)=>n in t?M(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var o=(t,n)=>M(t,"name",{value:n,configurable:!0});var ft=(t,n)=>{for(var e in n)M(t,e,{get:n[e],enumerable:!0})},mt=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of ct(n))!pt.call(t,i)&&i!==e&&M(t,i,{get:()=>n[i],enumerable:!(r=dt(n,i))||r.enumerable});return t};var ht=t=>mt(M({},"__esModule",{value:!0}),t);var c=(t,n,e)=>ut(t,typeof n!="symbol"?n+"":n,e);var rn={};ft(rn,{bootstrap:()=>at});var Se="anfra-provision";var U=class U 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(U,"DataAppError");var S=U,H=class H extends S{};o(H,"ValidationError");var u=H,Y=class Y extends S{constructor(e,r,i){super(e,r);c(this,"cause");this.cause=i}};o(Y,"QueryError");var D=Y,W=class W extends S{};o(W,"PermissionError");var R=W,X=class X extends S{constructor(e,r,i){super(e,i);c(this,"status");this.status=r}};o(X,"TransportError");var C=X;function Ce(){let t=new Error("Aborted");return t.name="AbortError",t}o(Ce,"abortError");function gt(t){return t?.name==="AbortError"}o(gt,"isAbortError");var yt=new Set(["ValidationError","QueryError","PermissionError","TransportError"]);function bt(t){let n=t;return n instanceof Error&&yt.has(n.name)?{name:n.name,message:n.message||"The call failed."}:{name:"QueryError",message:"The call failed."}}o(bt,"toBridgeError");function wt(t){switch(t?.name){case"PermissionError":return new R(t.message);case"TransportError":return new C(t.message);case"ValidationError":return new u(t.message);default:return new D(t?.message||"The call failed.")}}o(wt,"fromBridgeError");function Ae(t,n){let e=new Map,r=new Map,i=1,s=o((l,a,d)=>{let p=new AbortController;r.set(l,p),Promise.resolve().then(()=>n.answer(a,d,p.signal)).then(g=>{p.signal.aborted||t({type:"anfra:result",id:l,ok:!0,result:g})}).catch(g=>{p.signal.aborted||gt(g)||t({type:"anfra:result",id:l,ok:!1,error:bt(g)})}).finally(()=>{r.get(l)===p&&r.delete(l)})},"answer");return{call(l,a,d){return new Promise((p,g)=>{if(d?.aborted){g(Ce());return}let E=i++;e.set(E,{resolve:p,reject:g}),d?.addEventListener("abort",()=>{e.delete(E)&&(t({type:"anfra:cancel",id:E}),g(Ce()))},{once:!0}),t({type:"anfra:call",id:E,name:l,request:a})})},emit(l,a){t({type:"anfra:event",name:l,payload:a})},receive(l){switch(l?.type){case"anfra:call":return s(l.id,l.name,l.request),!0;case"anfra:result":{let a=e.get(l.id);return a&&(e.delete(l.id),l.ok?a.resolve(l.result):a.reject(wt(l.error))),!0}case"anfra:cancel":return r.get(l.id)?.abort(),r.delete(l.id),!0;case"anfra:event":return n.event(l.name,l.payload),!0;default:return!1}},close(l){r.forEach(a=>a.abort()),r.clear(),e.forEach(({reject:a})=>a(l)),e.clear()}}}o(Ae,"createEndpoint");var Z=class Z{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(Z,"Observable");var $=Z;var De=["year","quarter","month","week","day","hour","minute"];function xt(t,n){if(!De.includes(n))throw new u(`Invalid grain \'${n}\'. Expected one of: ${De.join(", ")}.`,t)}o(xt,"assertGrain");function Re(t,n){return n?(xt(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}o(Re,"drillCondition");function kt(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(kt,"inferType");function Et(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}o(Et,"sameCondition");var ee=class ee extends ${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&&!Et(this.pending,this.applied)}setCondition(e){this.pending=e,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};o(ee,"Control");var T=ee,te=class te extends T{constructor(e,r,i,s,l){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=l,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??kt(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(te,"Filter");var P=te,ne=class ne extends T{constructor(e,r,i={}){super(e,r,Re(e,i.default));c(this,"kind","dateDrill");c(this,"declaration");this.declaration=i}setGrain(e){this.setCondition(Re(this.name,e))}toJSON(){return this.declaration}};o(ne,"DateDrillControl");var z=ne;var v={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},_e=`[${v.container}],[${v.block}],[${v.query}],[${v.control}]`;function $e(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}o($e,"parseRef");var Te=o(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Oe(t,n,e,r){let i=n==="query"?v.query:v.control;return[...t.querySelectorAll(`[${i}]`)].filter(s=>Te(s.getAttribute(i)).some(l=>{let a=$e(l);return a?.app===e&&a.name===r}))}o(Oe,"markersFor");var vt=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 Fe(t,n){var E;let e=[],r=new Map,i=new Map,s=new Map,l=new Map,a={container:new Set,block:new Set},d={},p=o((h,f,y)=>{let b=h?s.get(h).children:e,m=h?`${s.get(h).key}.`:"",w={...f,key:`${m}${b.length}`,children:[]};return b.push(w),r.set(w.key,y),i.set(y,[...i.get(y)??[],w.key]),w},"place");for(let h of t.querySelectorAll(_e)){let f=h.parentElement?.closest(_e)??null,y=h.getAttribute(v.container),b=h.getAttribute(v.block),m=h.getAttribute(v.label)??void 0,w=f&&(l.get(f)==="block"?f:f.closest(`[${v.block}]`)),_;if(y!==null||b!==null){let k=y!==null?"container":"block",A=(y??b??"").trim(),x=[];y!==null&&b!==null&&x.push("This element is marked as a container and as a block. It counts as a container."),A?a[k].has(A)?x.push(`Another ${k} already has the id "${A}".`):a[k].add(A):x.push(`This ${k} has no id.`),w&&x.push(`A block can\'t hold a ${k}. This one is inside the block "${w.getAttribute(v.block)}".`),_=p(f,{kind:k,id:A,...m!==void 0?{label:m}:{},problems:x},h),s.set(h,_),l.set(h,k)}let N=_?h:f;for(let k of["query","control"])for(let A of Te(h.getAttribute(k==="query"?v.query:v.control))){let x=$e(A),L=[];if(x?vt(n,k,x)||L.push(n[x.app]?`No ${k} is called "${x.name}" in app ${x.app}.`:`The page has no app ${x.app}.`):L.push(`Can\'t read "${A}". Write the ${k}\'s name, or app/name when the page has several apps.`),p(N,{kind:k,name:x?.name??A,app:x?.app??0,problems:L},h),x&&!L.length){let lt=`${x.app}/${x.name}`,Ee=d[E=`${k}:${lt}`]??(d[E]={elements:new Set,blocks:new Set});Ee.elements.add(h);let ve=_?.kind==="block"?_.id:w?.getAttribute(v.block);ve&&Ee.blocks.add(ve)}}}let g=Object.fromEntries(Object.entries(d).map(([h,f])=>[h,{markers:f.elements.size,blocks:[...f.blocks]}]));return{nodes:e,usage:g,elements:r,keysOf:i}}o(Fe,"buildStructure");var Ne="data-anfra-layer",St="position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";function Ct(t){let n=t.querySelector(`[${Ne}]`);if(n instanceof(t.defaultView?.HTMLElement??HTMLElement))return n;let e=t.createElement("div");return e.setAttribute(Ne,""),e.setAttribute("style",St),(t.body??t.documentElement).appendChild(e),e}o(Ct,"layerOf");function Q(t,n){let e=Ct(t),r=[...e.children].find(s=>s.getAttribute("data-part")===n);if(r?.shadowRoot)return r.shadowRoot;let i=t.createElement("div");return i.setAttribute("data-part",n),e.appendChild(i),i.attachShadow({mode:"open"})}o(Q,"layerRoot");var Me="anfra-overlay",At=1500,Dt="position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;",Rt="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);",_t={kind:"color:#94a3b8;",name:"color:#93c5fd;font-weight:700;",label:"color:#f8fafc;",note:"color:#94a3b8;",size:"color:#94a3b8;margin-left:10px;"},ie=class ie{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=Q(n,"anfra"),r=e.getElementById(Me);r instanceof(n.defaultView?.HTMLElement??HTMLElement)?this.root=r:(this.root=n.createElement("div"),this.root.id=Me,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),e.appendChild(this.root))}show(n,e){if(this.clearTimer(),this.root.isConnected||Q(this.doc,"anfra").appendChild(this.root),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=At){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(a=>{let d=a.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${Dt}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),l=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${Rt}left:${l}px;top:${Math.min(s,i-24)}px;`);for(let a of["kind","name","label","note","size"]){let d=this.text[a];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",_t[a]),p.setAttribute("data-part",a),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};o(ie,"Overlay");var re=ie,Qe=new WeakMap;function V(t){let n=Qe.get(t);return n||(n=new re(t),Qe.set(t,n)),n}o(V,"overlayFor");function Ie(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}o(Ie,"scrollTo");function oe(t,n,e,r,i){if(r in n||t.has(r))throw new u(`Plugin \'${r}\' can\'t add \'${r}\' to a ${e}: it already has one.`);t.set(r,i)}o(oe,"addExtension");function j(t,n){return n?.forEach((e,r)=>{let i=!1,s;Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){return i||(s=e(t),i=!0),s}})}),t}o(j,"applyExtensions");var $t="anfra.body",se="__anfraBodyExports",Tt={DataAppError:S,ValidationError:u,QueryError:D,PermissionError:R,TransportError:C};function Ot(t,n){let e=t,r=t.document.createElement("script");r.textContent=`(function () { var __anfraBody;\n${n}\n;self[${JSON.stringify(se)}] = __anfraBody; })();`,(t.document.head??t.document.documentElement).appendChild(r),r.remove();let i=e[se];if(delete e[se],!i)throw new u("The host sent a plugin body that did not run.");return i.default??i}o(Ot,"runBody");function Be(t,n,e){let{window:r,sdk:i,endpoint:s}=n,l;return{plugin:t,window:r,sdk:i,errors:Tt,get overlay(){return V(r.document)},structure:o(()=>Fe(r.document,i.apps),"structure"),call:o((a,d,p)=>s.call(a,d??null,p),"call"),emit:o((a,d)=>s.emit(`${t}.${a}`,d??null),"emit"),handle(a,d){n.handlers.set(`${t}.${a}`,d)},on(a,d){let p=`${t}.${a}`;n.listeners.has(p)||n.listeners.set(p,new Set),n.listeners.get(p).add(d)},onApp(a){n.appListeners.add(a),i.apps.forEach(d=>a(d))},provide(a){if(t in i)throw new u(`Plugin \'${t}\' can\'t add a member Anfra already has.`);Object.defineProperty(i,t,{value:a,enumerable:!0})},provideOnQuery:o(a=>oe(i.extensions.query,e.Query.prototype,"query",t,a),"provideOnQuery"),provideOnControl:o(a=>oe(i.extensions.control,e.Control.prototype,"control",t,a),"provideOnControl"),layer:o(()=>Q(r.document,t),"layer"),body(){return l??(l=s.call($t,{plugin:t}).then(a=>Ot(r,a)).catch(a=>{throw l=void 0,a})),l}}}o(Be,"createKernel");var ae=class ae extends ${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._result.meta.hasMore??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))}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(l=>JSON.stringify(e.fields.map(a=>l[a]??null)),"key"),s=new Set(e.rows.map(i));return r.filter(l=>s.has(i(l)))}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(ae,"Query");var O=ae;var le=class le{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(le,"Mapping");var J=le,de=class de{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(de,"CrossFilter");var q=de;var ce=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function Ft(t,n){let e=t.length+1,r=n.length+1,i=Array.from({length:r},(s,l)=>l);for(let s=1;s<e;s++){let l=[s];for(let a=1;a<r;a++)l[a]=Math.min(i[a]+1,l[a-1]+1,i[a-1]+(t[s-1]===n[a-1]?0:1));i=l}return i[r-1]}o(Ft,"editDistance");function Nt(t,n){let e,r=1/0;n.forEach(s=>{let l=Ft(t.toLowerCase(),s.toLowerCase());l<r&&(r=l,e=s)});let i=Math.max(2,Math.floor(t.length/3));return r<=i?e:void 0}o(Nt,"suggest");function F(t,n,e){let r=Nt(n,e);return r?`${t} Did you mean \'${r}\'?`:t}o(F,"withSuggestion");var pe=class pe{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(F(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};o(pe,"DatasetIndex");var G=pe;function Le(t,n,e){let r=t[n];if(r)return r;throw new u(F(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}o(Le,"resolveDataset");function Pe(t,n){if(!ce.includes(t))throw new u(F(`Invalid filter aggregation \'${t}\'.`,t,[...ce]),n)}o(Pe,"assertValidFilterAggregation");function ze(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(ze,"assertUniqueName");function Mt(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(Mt,"toFilter");function Qt(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(Qt,"toDateDrill");function It(t,n){let e=n.columns??[],r=(n.values??[]).map(s=>{let l={};return e.forEach((a,d)=>{l[a.name]=s[d]}),l}),{pageSize:i}=t;return{columns:e,rows:r,meta:{...i!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??i,...n.meta?.hasMore!==void 0?{hasMore:n.meta.hasMore}:{}}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}o(It,"toResult");function Ve(t,n,e,r){let i=n.map(d=>Mt(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=n.map(d=>Qt(d,d.from.appliedCondition)).filter(d=>d!==void 0),l=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),a=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...i,...l],conditions:a,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:s},...r.timezone?{timezone:r.timezone}:{}}}o(Ve,"buildQuery");function Bt(t,n,e,r){return{...Ve(t,n,e,r),...t.pageSize!==void 0?{page:t.page,pageSize:t.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}o(Bt,"buildRequest");function Lt(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}o(Lt,"defaultExportFilename");function je(t,n,e,r,i){let s=i.format??"csv",l=s==="csv"?{bom:!0,...i.formatOptions}:i.formatOptions;return{...Ve(t,n,e,r),format:s,...l?{formatOptions:l}:{},filename:i.filename?.trim()||Lt(t,r.title)}}o(je,"buildExportRequest");async function ue(t,n,e,r,i){let s=Bt(t,n,e,r),l=await r.backend.submitQuery(s,i);return It(t,l)}o(ue,"runQuery");function Pt(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return jt(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(Pt,"literal");function Je(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${Pt(n,e)}`}o(Je,"equals");var zt=new Set(["NaN","Infinity","-Infinity"]),Vt=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function jt(t){let n=Vt.exec(t);if(!n)throw zt.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 l=r+i,a=r.length+Number(s),d;return a<=0?d=`0.${"0".repeat(-a)}${l}`:a>=l.length?d=l+"0".repeat(a-l.length):d=`${l.slice(0,a)}.${l.slice(a)}`,e+d.replace(/^0+(?=\\d)/,"")}o(jt,"numberLiteral");function qe(t,n,e){return`${t} matches @(${n} until ${e})`}o(qe,"dateRange");function Ge(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(Ge,"combine");var Ke=o(t=>Ge("and",t),"and"),Ue=o(t=>Ge("or",t),"or");var Jt=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,qt={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function He(t){if(typeof t!="string")return;let n=Jt.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(He,"parseStamp");function I(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(I,"format");function Ye(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}o(Ye,"toMs");function fe(t){let n=He(t);if(n)return I(Ye(n),n.hasTime)}o(fe,"normalise");function me(t,n){let e=He(t);if(!e)return;let{year:r,month:i,day:s,hour:l,minute:a,second:d,hasTime:p}=e;return I(n==="year"?Date.UTC(r+1,i,s,l,a,d):n==="quarter"?Date.UTC(r,i+3,s,l,a,d):n==="month"?Date.UTC(r,i+1,s,l,a,d):Ye(e)+qt[n],p)}o(me,"addGrain");function We(t){if(t?.startsWith("datetrunc "))return t.slice(10)}o(We,"grainOf");function Gt(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(Gt,"distinct");function Kt(t,n){let e=t.map(fe);if(e.some(i=>i===void 0))return!1;let r=e.slice().sort();for(let i=1;i<r.length;i+=1)if(me(r[i-1],n)!==r[i])return!1;return!0}o(Kt,"isContiguous");function Ut(t,n,e){let r=n.map(fe);if(r.some(d=>d===void 0))return;let i=r.slice().sort(),s=i[0],l=me(i[i.length-1],e);if(!l)return;let a=Kt(n,e);return{condition:{field:t,operator:"matches",values:[`${s} until ${l}`]},admits:a?n.length:Number.POSITIVE_INFINITY,lossy:!a}}o(Ut,"dateRange");function Ht(t,n,e){let r=e.filter(a=>a!=null),i=Gt(r);if(!i.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let s=r.length!==e.length,l=We(n);if(l){let a=Ut(t,i,l);if(a)return{...a,lossy:a.lossy||s}}return{condition:{field:t,operator:"is",values:i},admits:i.length,lossy:s}}o(Ht,"deriveOne");function Xe(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}o(Xe,"fieldReferenceOf");function Yt(t,n,e,r){try{let i=e.map(s=>Ke(n.map(l=>{let a=t.get(l),d=Xe(a),p=s[l]??null,g=We(r[d]);if(g&&typeof p=="string"){let E=fe(p),h=me(p,g);if(E&&h)return qe(d,E,h)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return Je(d,p,a.semantic_type)})));return Ue(i)}catch{return}}o(Yt,"selectionExpression");function Ze(t,n,e,r={}){let i=t.result?.columns??[],s=new Map(i.map(m=>[m.name,m]));e?.forEach(m=>{let w=s.get(m);if(w){if(w.adhoc)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${m}\': 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 \'${m}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new u(F(`Query \'${t.name}\' has no column \'${m}\' in its last result.`,m,[...s.keys()]),t.name)});let l=i.filter(m=>!m.isMeasure),a=l.filter(m=>!m.adhoc).map(m=>m.name),d=e?[...e]:a;if(!n.length||!d.length)return;let p=[],g=1,E=!e&&a.length!==l.length,h=!1;d.forEach(m=>{let w=s.get(m),_=Xe(w),N=Ht(_,r[_],n.map(k=>k[m]));p.push(N.condition),g*=N.admits,h=h||N.lossy});let f=new Set(n.map(m=>JSON.stringify(d.map(w=>m[w]??null))));g>f.size&&(h=!0);let y=p.sort((m,w)=>m.field.localeCompare(w.field)),b={source:t.name,rows:[...n],fields:d};if(h){let m=Yt(s,d,n,r);if(m)return{...b,conditions:[],expression:m,lossy:E}}return{...b,conditions:y,lossy:E||h}}o(Ze,"deriveSelection");var he=Object.freeze([]);function ge(t){return t instanceof Error&&t.name==="AbortError"}o(ge,"isAbort");function et(t,n){return t.controller!==n}o(et,"superseded");function Wt(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(Wt,"inspectError");function Xt(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:Wt(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}o(Xt,"inspectQuery");function Zt(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}o(Zt,"inspectControl");function tt(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(tt,"inspectSelection");function nt(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}o(nt,"selectionKey");function rt(t,n){return t instanceof S?t:new D(t?.message??"The query failed.",n,t)}o(rt,"toDataAppError");function en(t,n){if(t instanceof S&&t.entity)return t;let e=t?.message||"The export failed.";return t instanceof R?new R(e,n):t instanceof C?new C(e,t.status,n):t instanceof u?new u(e,n):new D(e,n,t)}o(en,"toExportError");var ye=class ye extends ${constructor(e,r,i,s,l){super();c(this,"extensions",l);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=j(new O(e,this,r),this.extensions?.query);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=j(new P(e,this,r,i,this.backend),this.extensions?.control);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=j(new z(e,this,r),this.extensions?.control);return this._controls.set(e,i),this.notify(),i}mapControl(e,r,i){if(!(e instanceof T))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&&Pe(i.aggregation,e.name);let s=new J(e,r,i.field,i.aggregation);if(this._mappings.some(l=>l.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 O)||!(r instanceof O))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 q(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 Le(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(l=>l.from.name===i.source&&l.to.name===e)?i:void 0}selectionConditionsFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?he:this._crossFilters.some(l=>l.from.name===i.source&&l.to.name===e)?i.conditions:he}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[l]=s.values??[];typeof l=="string"&&(r[i.field]=l)}),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=Ze(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?nt(this._selection)!==nt(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(a=>a.shouldRun(e.force));this._controls.forEach(a=>a.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(a=>{a.controller?.abort(),a.resetPage()});let i={backend:this.backend,timezone:this._timezone,bustCache:e.bustCache},s=[],l=[];return await Promise.all(r.map(async a=>{let d=new AbortController;a.controller=d;let p=a.signature();a.markExecuting();try{let g=await ue(a,this.mappingsTo(a.name),{conditions:this.selectionConditionsFor(a.name,"applied"),expression:this.selectionExpressionFor(a.name,"applied")},i,d.signal);if(et(a,d))return;a.markSuccess(g,p,!1),s.push(a.name)}catch(g){if(et(a,d)||ge(g))return;a.markError(rt(g,a.name)),l.push(a.name)}finally{a.controller===d&&(a.controller=void 0)}})),{succeeded:s,failed:l}}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 ue(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(),ge(s))return;let l=rt(s,e.name);throw e.markError(l),l}finally{e.controller===r&&(e.controller=void 0)}}async exportQuery(e,r,i){let s=je(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone,title:this.title},r);try{return await i(s,r.signal??new AbortController().signal)}catch(l){throw ge(l)?l:en(l,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,Xt(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,Zt(r)])),...this._selection?{selection:tt(this._selection)}:{},...this._appliedSelection?{appliedSelection:tt(this._appliedSelection)}:{}}}locate(e,r){let i=globalThis.document;if(!i)return!1;let s=Oe(i,e,this.index,r);return s.length?(Ie(s[0]),V(i).flash(s,{kind:e,name:r,...s.length>1?{note:`in ${s.length} places`}:{}}),!0):!1}assertNameFree(e,r){ze([...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,l=new Set,a=o(d=>{if(s.has(d))return!0;if(l.has(d))return!1;s.add(d);let p=(i.get(d)??[]).some(a);return s.delete(d),l.add(d),p},"walk");if([...i.keys()].some(a))throw new u(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};o(ye,"App");var K=ye;var it="0.13.0";var xe=class xe{constructor(n){c(this,"list");this.list=Object.freeze(n.map(({name:e,version:r})=>Object.freeze({name:e,version:r})))}has(n){return this.list.some(e=>e.name===n)}version(n){return this.list.find(e=>e.name===n)?.version}};o(xe,"InstalledPlugins");var be=xe,nn=it,ke=class ke{constructor(n){c(this,"version",nn);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"plugins");c(this,"gates");c(this,"deprecatedFeatures");c(this,"extensions",{query:new Map,control:new Map});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 G(r)])),this.backend=n.backend,this.gates=Object.freeze({...n.features}),this.plugins=new be(n.plugins??[])}get features(){return this.deprecatedFeatures||(console.warn("anfra: Anfra.features is deprecated and will be removed. Check Anfra.plugins.has(\'export\'), Anfra.plugins.has(\'render\') or Anfra.plugins.has(\'lineage\') instead."),this.deprecatedFeatures=Object.freeze({...this.gates,export:this.plugins.has("export"),render:this.plugins.has("render"),lineage:this.plugins.has("lineage")})),this.deprecatedFeatures}createApp(n={}){let e=new K(n,this.indices,this.backend,this.gates,this.extensions);return e.index=this._apps.length,this._apps.push(e),e}get apps(){return this._apps}};o(ke,"Sdk");var we=ke;function ot(t){return new we(t)}o(ot,"createSdk");var B="Anfra";function st(t,n=globalThis){let e=n[B],r=B in n;return n[B]=t,()=>{r?n[B]=e:delete n[B]}}o(st,"installSandbox");function at(t,n=[]){let e=t.document.getElementById(Se);if(!e?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let r=JSON.parse(e.textContent),i=o(f=>t.parent.postMessage(f,r.hostOrigin),"post"),s=new Map,l=new Map,a=Ae(i,{answer:o(async(f,y,b)=>{let m=s.get(f);if(!m)throw new C(`Nothing in this frame answers \'${f}\'.`);return m(y,b)},"answer"),event:o((f,y)=>{l.get(f)?.forEach(b=>{try{b(y)}catch{}})},"event")});t.addEventListener("message",f=>{f.source===t.parent&&a.receive(f.data)});let d={submitQuery:o((f,y)=>a.call("core.submitQuery",f,y).then(b=>(b.debug?.executedAt&&(b.debug.executedAt=new Date(b.debug.executedAt)),b)),"submitQuery"),fieldSuggestions:o((f,y)=>a.call("core.fieldSuggestions",f,y),"fieldSuggestions")},p=ot({datasets:r.datasets,user:r.user,backend:d,plugins:r.plugins??[]}),g=new Set,E=p.createApp.bind(p);p.createApp=f=>{let y=E(f);return g.forEach(b=>{try{b(y)}catch{}}),y};let h={window:t,sdk:p,endpoint:a,handlers:s,listeners:l,appListeners:g};for(let[f,y]of n)if(typeof y=="function")try{y(Be(f,h,{Query:O,Control:T}))}catch(b){t.console?.error(`anfra: plugin \'${f}\' failed to set up:`,b)}st(p,t),i({type:"anfra:ready"})}o(at,"bootstrap");return ht(rn);})();\n';
20
20
 
21
21
  // src/host/frameScript.ts
22
22
  function builtFrameScript() {
@@ -52,24 +52,66 @@ function composeFrameScript(frameScript, setups = []) {
52
52
  ].join("\n");
53
53
  }
54
54
  var charsetRe = /<meta[^>]*charset[^>]*>/i;
55
- var headRe = /<head[^>]*>/i;
55
+ var headRe = /<head(?:\s[^>]*)?>/i;
56
+ var gap = "(?:\\s|<!--[\\s\\S]*?-->)*";
57
+ var preambleRe = new RegExp(`^${gap}(?:<!doctype[^>]*>${gap})?(?:<html(?:\\s[^>]*)?>${gap})?(?:<head(?:\\s[^>]*)?>)?`, "i");
56
58
  function provisionDocument(definition, options) {
59
+ const policy = `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(options.contentPolicy)}">`;
57
60
  const injected = [
58
- `<base href="${escapeAttribute(options.baseHref)}">`,
59
61
  `<script type="application/json" id="${PROVISION_ELEMENT_ID}">${scriptJSON(options.provision)}</script>`,
60
62
  `<script>${scriptCode(composeFrameScript(options.frameScript, options.setups))}</script>`
61
63
  ].join("\n");
64
+ const preamble = preambleRe.exec(definition)?.[0] ?? "";
65
+ const rest = definition.slice(preamble.length);
62
66
  for (const re of [charsetRe, headRe]) {
63
- const match = re.exec(definition);
67
+ const match = re.exec(rest);
64
68
  if (match) {
65
69
  const at = match.index + match[0].length;
66
- return `${definition.slice(0, at)}
70
+ return `${preamble}${policy}
71
+ ${rest.slice(0, at)}
67
72
  ${injected}
68
- ${definition.slice(at)}`;
73
+ ${rest.slice(at)}`;
69
74
  }
70
75
  }
71
- return `${injected}
72
- ${definition}`;
76
+ return `${preamble}${policy}
77
+ ${injected}
78
+ ${rest}`;
79
+ }
80
+
81
+ // src/host/policy.ts
82
+ var SCRIPT_ORIGINS = [
83
+ "https://cdnjs.cloudflare.com",
84
+ "https://cdn.jsdelivr.net",
85
+ "https://esm.sh",
86
+ "https://unpkg.com"
87
+ ];
88
+ var STYLE_ORIGINS = [...SCRIPT_ORIGINS, "https://fonts.googleapis.com"];
89
+ var FONT_ORIGINS = [...SCRIPT_ORIGINS, "https://fonts.gstatic.com"];
90
+ function checkOrigin(origin) {
91
+ let url;
92
+ try {
93
+ url = typeof origin === "string" ? new URL(origin) : void 0;
94
+ } catch {
95
+ }
96
+ if (!url || url.protocol !== "https:" || url.origin !== origin || url.host.includes("*")) {
97
+ throw new Error(`An allowed origin is https://<host>[:<port>], with no path, wildcard or trailing slash: got ${JSON.stringify(origin)}.`);
98
+ }
99
+ return origin;
100
+ }
101
+ function contentPolicy(allowOrigins = []) {
102
+ const extra = allowOrigins.map(checkOrigin);
103
+ const list = (...origins) => [.../* @__PURE__ */ new Set([...origins.flat(), ...extra])].join(" ");
104
+ return [
105
+ "default-src 'none'",
106
+ `script-src ${list([...SCRIPT_ORIGINS])} 'unsafe-inline' 'unsafe-eval'`,
107
+ `style-src ${list(STYLE_ORIGINS)} 'unsafe-inline'`,
108
+ `font-src ${list(FONT_ORIGINS)} data:`,
109
+ "img-src https: data: blob:",
110
+ `connect-src ${list(STYLE_ORIGINS, FONT_ORIGINS)} data: blob:`,
111
+ "frame-src 'none'",
112
+ "form-action 'none'",
113
+ "base-uri 'none'"
114
+ ].join("; ");
73
115
  }
74
116
 
75
117
  // src/host/runtime.ts
@@ -109,6 +151,7 @@ function install(plugins) {
109
151
  function createHost(options) {
110
152
  const plugins = [...options.plugins];
111
153
  const answers = install(plugins);
154
+ const policy = contentPolicy(options.allowOrigins);
112
155
  const middleware = [
113
156
  ...options.middleware ?? [],
114
157
  ...plugins.flatMap((plugin) => plugin.host?.middleware ?? [])
@@ -248,7 +291,7 @@ function createHost(options) {
248
291
  hostOrigin: win.location.origin
249
292
  };
250
293
  frame.srcdoc = provisionDocument(mountOptions.definition, {
251
- baseHref: mountOptions.baseHref,
294
+ contentPolicy: policy,
252
295
  provision,
253
296
  frameScript,
254
297
  setups: plugins.flatMap((plugin) => plugin.frame ? [{ name: plugin.name, setup: plugin.frame.setup }] : [])
@@ -271,7 +314,10 @@ function createHost(options) {
271
314
  };
272
315
  }
273
316
  export {
317
+ SCRIPT_ORIGINS,
318
+ checkOrigin,
274
319
  composeFrameScript,
320
+ contentPolicy,
275
321
  createHost,
276
322
  definePlugin,
277
323
  provisionDocument
@@ -128,4 +128,5 @@ interface Plugin {
128
128
  /** A plugin, checked (`checkPlugin`). A host checks every plugin it installs anyway. */
129
129
  declare function definePlugin<P extends Plugin>(plugin: P): P;
130
130
 
131
- export { type CallOptions as C, type EventCheck as E, type FrameHalf as F, type HandlerCallOptions as H, type Middleware as M, type Plugin as P, type CallContext as a, type CallDefinition as b, type CallHandler as c, type Caller as d, type HandlerContext as e, type HostHalf as f, type MountContext as g, definePlugin as h };
131
+ export { definePlugin as h };
132
+ export type { CallOptions as C, EventCheck as E, FrameHalf as F, HandlerCallOptions as H, Middleware as M, Plugin as P, CallContext as a, CallDefinition as b, CallHandler as c, Caller as d, HandlerContext as e, HostHalf as f, MountContext as g };
package/dist/plugins.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as Backend } from './types-plgahUrN.js';
2
- import { P as Plugin } from './plugin-C5cihcQD.js';
1
+ import { Backend } from './app.js';
2
+ import { Plugin } from './host.js';
3
3
 
4
4
  /**
5
5
  * `core`: running a Data App's queries and suggesting a filter's values. Every host installs it:
@@ -49,4 +49,5 @@ declare function renderPlugin(options?: RenderPluginOptions): Plugin;
49
49
 
50
50
  declare function inspectPlugin(): Plugin;
51
51
 
52
- export { type CoreBackend, type RenderPluginOptions, corePlugin, exportPlugin, inspectPlugin, lineagePlugin, pictureFilename, renderPlugin };
52
+ export { corePlugin, exportPlugin, inspectPlugin, lineagePlugin, pictureFilename, renderPlugin };
53
+ export type { CoreBackend, RenderPluginOptions };
package/dist/plugins.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-TQ7S5DRE.js";
4
4
  import {
5
5
  version
6
- } from "./chunk-MIHZUF2H.js";
6
+ } from "./chunk-SIITHGUD.js";
7
7
  import {
8
8
  ValidationError
9
9
  } from "./chunk-KCTLO3CO.js";
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { b as PluginInfo } from './bridge-BCJklF4M.js';
2
- import { aj as User, D as DatasetDescriptor } from './types-plgahUrN.js';
3
- import { S as Sdk, P as PluginSetup } from './bootstrap-BkiMDMcp.js';
1
+ import { PluginInfo } from './app.js';
2
+ import { User, DatasetDescriptor } from './app.js';
3
+ import { Sdk, PluginSetup } from './app.js';
4
4
  import './errors-CKvqVaqU.js';
5
5
 
6
6
  /** The reader a test frame is provisioned with unless given. */
@@ -44,4 +44,5 @@ interface TestFrame {
44
44
  declare const flush: () => Promise<unknown>;
45
45
  declare function testFrame(options?: TestFrameOptions): TestFrame;
46
46
 
47
- export { TEST_READER, type TestFrame, type TestFrameOptions, flush, testFrame };
47
+ export { TEST_READER, flush, testFrame };
48
+ export type { TestFrame, TestFrameOptions };
package/dist/testing.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  bootstrap
3
- } from "./chunk-O3S2GQ5N.js";
3
+ } from "./chunk-LW63RQZ2.js";
4
4
  import "./chunk-XIUFHRZE.js";
5
5
  import {
6
6
  createEndpoint
@@ -8,7 +8,7 @@ import {
8
8
  import {
9
9
  PROVISION_ELEMENT_ID
10
10
  } from "./chunk-33B2D4U5.js";
11
- import "./chunk-MIHZUF2H.js";
11
+ import "./chunk-SIITHGUD.js";
12
12
  import "./chunk-KCTLO3CO.js";
13
13
  import "./chunk-PKBMQBKP.js";
14
14
 
@@ -2391,4 +2391,5 @@ interface Backend {
2391
2391
  lineage?(request: BackendLineageRequest, signal: AbortSignal): Promise<LineageResult>;
2392
2392
  }
2393
2393
 
2394
- export { type Operator as $, type Aggregation as A, type Backend as B, type ColumnMeta as C, type DatasetDescriptor as D, type EntityKind as E, FILTER_AGGREGATIONS as F, type FieldLineage as G, type FieldSuggestionsRequest as H, type FilterAggregation as I, type FilterDeclaration as J, type FilterValueType as K, type InspectedApp as L, type InspectedControl as M, type InspectedError as N, type InspectedQuery as O, type InspectedSelection as P, type InspectedStructure as Q, type LineageCard as R, type LineageDiagram as S, type LineageNode as T, type LineageOptions as U, type LineageResult as V, type LineageTarget as W, type Listener as X, type LocateKind as Y, type LocateTarget as Z, type MappingJson as _, type AppDeclaration as a, type QueryDebug as a0, type QueryDeclaration as a1, type QueryInput as a2, type QueryResult as a3, type QuerySort as a4, type QueryState as a5, type QueryTimings as a6, type RenderFormat as a7, type RenderRequest as a8, type Rendering as a9, type Row as aa, type SdkEnvironment as ab, type SdkFeatures as ac, type Selection as ad, type SelectionCondition as ae, type SemanticType as af, type StructureKind as ag, type StructureNode as ah, type Unsubscribe as ai, type User as aj, type paths as ak, type components as al, type AppJson as b, type ArrowType as c, type BackendCondition as d, type BackendDateDrill as e, type BackendExportRequest as f, type BackendFilter as g, type BackendLineageRequest as h, type BackendQueryRequest as i, type BackendQueryResult as j, type BackendSort as k, type Condition as l, type ConditionValue as m, type ControlMappingJson as n, type CrossFilterJson as o, type DateDrillDeclaration as p, type DateGrain as q, type DateTransformation as r, type EntityRef as s, type EntityUsage as t, type ExecuteOptions as u, type ExecuteSummary as v, type ExportFormat as w, type ExportFormatOptions as x, type ExportOptions as y, type ExportResult as z };
2394
+ export { FILTER_AGGREGATIONS as F };
2395
+ export type { Operator as $, Aggregation as A, Backend as B, ColumnMeta as C, DatasetDescriptor as D, EntityKind as E, FieldLineage as G, FieldSuggestionsRequest as H, FilterAggregation as I, FilterDeclaration as J, FilterValueType as K, InspectedApp as L, InspectedControl as M, InspectedError as N, InspectedQuery as O, InspectedSelection as P, InspectedStructure as Q, LineageCard as R, LineageDiagram as S, LineageNode as T, LineageOptions as U, LineageResult as V, LineageTarget as W, Listener as X, LocateKind as Y, LocateTarget as Z, MappingJson as _, AppDeclaration as a, QueryDebug as a0, QueryDeclaration as a1, QueryInput as a2, QueryResult as a3, QuerySort as a4, QueryState as a5, QueryTimings as a6, RenderFormat as a7, RenderRequest as a8, Rendering as a9, Row as aa, SdkEnvironment as ab, SdkFeatures as ac, Selection as ad, SelectionCondition as ae, SemanticType as af, StructureKind as ag, StructureNode as ah, Unsubscribe as ai, User as aj, paths as ak, components as al, AppJson as b, ArrowType as c, BackendCondition as d, BackendDateDrill as e, BackendExportRequest as f, BackendFilter as g, BackendLineageRequest as h, BackendQueryRequest as i, BackendQueryResult as j, BackendSort as k, Condition as l, ConditionValue as m, ControlMappingJson as n, CrossFilterJson as o, DateDrillDeclaration as p, DateGrain as q, DateTransformation as r, EntityRef as s, EntityUsage as t, ExecuteOptions as u, ExecuteSummary as v, ExportFormat as w, ExportFormatOptions as x, ExportOptions as y, ExportResult as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holistics/anfra-sdk",
3
- "version": "0.11.1",
3
+ "version": "0.13.0",
4
4
  "description": "Data Apps on anfra: the authoring layer (app), what hosts one (host), anfra's plugins (plugins), the core API client (api), and their shared contract (common)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "html-to-image": "1.11.13",
67
67
  "jsdom": "^26.1.0",
68
68
  "openapi-typescript": "^7.13.0",
69
- "tsup": "^8.5.1",
69
+ "tsup": "^9.0.0",
70
70
  "typescript": "^5.9.3",
71
71
  "vitest": "^4.1.11"
72
72
  },