@holistics/anfra-sdk 0.10.2 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.js CHANGED
@@ -1,2207 +1,41 @@
1
+ import "./chunk-52LXBYQM.js";
2
+ import {
3
+ ATTR,
4
+ App,
5
+ Control,
6
+ CrossFilter,
7
+ DateDrillControl,
8
+ Filter,
9
+ InstalledPlugins,
10
+ LAYER_ATTRIBUTE,
11
+ Mapping,
12
+ OVERLAY_ID,
13
+ Query,
14
+ SANDBOX_GLOBAL,
15
+ Sdk,
16
+ VERSION,
17
+ bootstrap,
18
+ buildStructure,
19
+ createSdk,
20
+ installSandbox,
21
+ parseRef
22
+ } from "./chunk-O3S2GQ5N.js";
1
23
  import {
2
24
  FILTER_AGGREGATIONS
3
- } from "./chunk-H4XI4B7G.js";
25
+ } from "./chunk-XIUFHRZE.js";
26
+ import "./chunk-ADWBOQW2.js";
4
27
  import {
5
28
  PROVISION_ELEMENT_ID
6
29
  } from "./chunk-33B2D4U5.js";
30
+ import "./chunk-MIHZUF2H.js";
7
31
  import {
8
32
  DataAppError,
9
33
  PermissionError,
10
34
  QueryError,
11
35
  TransportError,
12
- ValidationError,
13
- __publicField
14
- } from "./chunk-KBXITYQK.js";
15
-
16
- // src/app/observable.ts
17
- var Observable = class {
18
- constructor(parent) {
19
- __publicField(this, "listeners", /* @__PURE__ */ new Set());
20
- __publicField(this, "parent");
21
- this.parent = parent;
22
- }
23
- subscribe(listener) {
24
- this.listeners.add(listener);
25
- return () => {
26
- this.listeners.delete(listener);
27
- };
28
- }
29
- /**
30
- * Public only so a child observable can bubble into its parent — an app subscriber sees every
31
- * entity's changes through one subscription. Subclasses call the protected `notify` instead.
32
- */
33
- notifyChange() {
34
- this.listeners.forEach((listener) => listener());
35
- this.parent?.notifyChange();
36
- }
37
- notify() {
38
- this.notifyChange();
39
- }
40
- };
41
-
42
- // src/app/query.ts
43
- var Query = class extends Observable {
44
- constructor(name, app, declaration) {
45
- super(app);
46
- __publicField(this, "kind", "query");
47
- __publicField(this, "name");
48
- __publicField(this, "declaration");
49
- __publicField(this, "dataset");
50
- __publicField(this, "app");
51
- __publicField(this, "_state", "idle");
52
- __publicField(this, "_result");
53
- __publicField(this, "_error");
54
- __publicField(this, "_page", 1);
55
- /**
56
- * A sort applied to the result, independent of the query's own AQL — the same mechanism a click
57
- * on a table's column header uses. Kept off the declaration so setting it never re-authors the
58
- * query. See docs/adr/0001.
59
- */
60
- __publicField(this, "_sort", []);
61
- /** The input signature of the last successful run; undefined until one has happened. */
62
- __publicField(this, "lastRunSignature");
63
- /**
64
- * Rows in the most recent page, not in the accumulated result. `fetchMore` appends, so comparing
65
- * the total against the page size would report "more" forever once two pages are held.
66
- */
67
- __publicField(this, "lastPageRows", 0);
68
- /** @internal Set by the executor so `abort()` can reach the in-flight request. */
69
- __publicField(this, "controller");
70
- if (!declaration.aql?.trim()) {
71
- throw new ValidationError(`Query '${name}' declares no AQL.`, name);
72
- }
73
- const { pageSize } = declaration;
74
- if (pageSize !== void 0 && !(Number.isInteger(pageSize) && pageSize >= 1)) {
75
- throw new ValidationError(
76
- `Query '${name}' declares pageSize ${pageSize}; it must be a whole number of at least 1.`,
77
- name
78
- );
79
- }
80
- this.name = name;
81
- this.app = app;
82
- this.declaration = declaration;
83
- this.dataset = app.datasetIndex(declaration.dataset, name);
84
- }
85
- /**
86
- * Bring the elements marked `data-anfra-query` with this query's name into view: scroll to the
87
- * first and show them all for a moment. False, and nothing done, when no element on the page is
88
- * marked with it yet; never throws, so an author's own button is safe.
89
- */
90
- locate() {
91
- return this.app.locate("query", this.name);
92
- }
93
- get state() {
94
- return this._state;
95
- }
96
- get result() {
97
- return this._result;
98
- }
99
- get error() {
100
- return this._error;
101
- }
102
- /** Rows per page, or undefined for a query that isn't paged and gets every row. */
103
- get pageSize() {
104
- return this.declaration.pageSize;
105
- }
106
- get page() {
107
- return this._page;
108
- }
109
- get sort() {
110
- return this._sort;
111
- }
112
- /** Replaces the sort applied to this query's result. Pass `[]` to clear it back to the AQL's own. */
113
- setSort(sort) {
114
- this._sort = [...sort];
115
- this.notify();
116
- }
117
- get hasMore() {
118
- if (!this._result || this.pageSize === void 0) return false;
119
- return this.lastPageRows >= this.pageSize;
120
- }
121
- /**
122
- * Everything that changes the rows: the declaration, the conditions reaching this query through
123
- * mappings, the conditions reaching it from the selection, the sort override, the app's timezone,
124
- * and the page. Compared against the last successful run to decide whether re-running would
125
- * produce anything new.
126
- */
127
- signature() {
128
- const conditions = this.app.mappingsTo(this.name).map((mapping) => ({
129
- field: mapping.field,
130
- aggregation: mapping.aggregation,
131
- condition: mapping.from.condition
132
- })).sort((a, b) => a.field.localeCompare(b.field) || JSON.stringify(a).localeCompare(JSON.stringify(b)));
133
- return JSON.stringify({
134
- declaration: this.declaration,
135
- conditions,
136
- selection: this.app.selectionConditionsFor(this.name, "pending"),
137
- // Separate from `selection`, and not optional: a selection sent as one expression leaves
138
- // `conditions` empty, so without this every such selection has the same signature as the
139
- // next one and the query is never re-run.
140
- selectionExpression: this.app.selectionExpressionFor(this.name, "pending"),
141
- sort: this._sort,
142
- timezone: this.app.timezone,
143
- page: this._page
144
- });
145
- }
146
- /**
147
- * False before the first run: with nothing applied there is nothing to have changed. Distinct
148
- * from `shouldRun`, which is true in that case precisely because there is no result yet.
149
- */
150
- get isDirty() {
151
- return this.lastRunSignature !== void 0 && this.signature() !== this.lastRunSignature;
152
- }
153
- /** @internal */
154
- shouldRun(force = false) {
155
- return force || this.lastRunSignature === void 0 || this.isDirty;
156
- }
157
- /** Stops the in-flight request for this query. The pending `execute()` resolves without it. */
158
- abort() {
159
- this.controller?.abort();
160
- }
161
- /** Fetches the next page and appends it. Rejects rather than swallowing, unlike `execute()`. */
162
- async fetchMore() {
163
- if (this.pageSize === void 0) {
164
- throw new ValidationError(`Query '${this.name}' declares no pageSize, so it has no more pages.`, this.name);
165
- }
166
- if (!this.hasMore) return;
167
- this._page += 1;
168
- await this.app.fetchPage(this);
169
- }
170
- /**
171
- * Exports this query's whole result as a file, and has the host save it for the reader.
172
- *
173
- * Every row, not only the pages loaded, with what the result on screen was last run with: the
174
- * mapped controls, the selection, the sort, the timezone. A control the reader changed but has
175
- * not applied is not in it. Resolves once the file is made and its download has started, with
176
- * its link and row count; rejects with a `DataAppError` naming this query, and changes nothing on
177
- * the query either way. Show the button when `Anfra.features.export` and
178
- * `Anfra.user.permissions.canExportData` are both true.
179
- */
180
- export(options = {}) {
181
- return this.app.exportQuery(this, options);
182
- }
183
- /**
184
- * Cross-filters this query's targets by the rows the reader picked.
185
- *
186
- * Replaces whatever was selected, here or in another query: an app holds one selection at a time.
187
- * Pass no rows to clear it. The SDK never sees the click, so the author calls this from their own
188
- * chart's handler, passing the result rows they rendered.
189
- *
190
- * `fields` narrows which result columns take part, for a chart that renders fewer than the query
191
- * returned. A measure or an adhoc column never takes part, whether or not it is named here.
192
- */
193
- select(rows, options = {}) {
194
- this.app.select(this, Array.isArray(rows) ? rows : [rows], options.fields);
195
- }
196
- /**
197
- * The rows of this query's current result that the reader has selected, for redrawing its own
198
- * highlight. Empty unless this query is the selection's source.
199
- *
200
- * Matched by value rather than by object identity. A source is never filtered by its own
201
- * selection, but it does re-run when it stops being some *other* query's target — which is
202
- * exactly what happens when the reader moves their selection from another panel to this one. Its
203
- * rows come back as new objects, and identity would drop the highlight at that moment.
204
- *
205
- * `app.selection.rows` still holds what the author passed, verbatim.
206
- */
207
- get selectedRows() {
208
- const { selection } = this.app;
209
- if (selection?.source !== this.name) return [];
210
- const rows = this._result?.rows;
211
- if (!rows) return selection.rows;
212
- const key = (row) => JSON.stringify(
213
- selection.fields.map((alias) => row[alias] ?? null)
214
- );
215
- const picked = new Set(selection.rows.map(key));
216
- return rows.filter((row) => picked.has(key(row)));
217
- }
218
- /** @internal */
219
- markExecuting() {
220
- this._state = "executing";
221
- this._error = void 0;
222
- this.notify();
223
- }
224
- /** @internal */
225
- markSuccess(result, signature, append) {
226
- this._state = "success";
227
- this._error = void 0;
228
- this.lastRunSignature = signature;
229
- this.lastPageRows = result.rows.length;
230
- if (append && this._result) {
231
- const rows = [...this._result.rows, ...result.rows];
232
- this._result = { ...result, rows, meta: { ...result.meta, numRows: rows.length } };
233
- } else {
234
- this._result = result;
235
- }
236
- this.notify();
237
- }
238
- /** @internal */
239
- markError(error) {
240
- this._state = "error";
241
- this._error = error;
242
- this.notify();
243
- }
244
- /** @internal Reverts an optimistic page bump when a `fetchMore` fails. */
245
- rewindPage() {
246
- if (this._page > 1) this._page -= 1;
247
- }
248
- /** @internal */
249
- resetPage() {
250
- this._page = 1;
251
- this.lastPageRows = 0;
252
- }
253
- toJSON() {
254
- return this.declaration;
255
- }
256
- };
257
-
258
- // src/app/controls.ts
259
- var DATE_GRAINS = ["year", "quarter", "month", "week", "day", "hour", "minute"];
260
- function assertGrain(entity, grain) {
261
- if (!DATE_GRAINS.includes(grain)) {
262
- throw new ValidationError(
263
- `Invalid grain '${grain}'. Expected one of: ${DATE_GRAINS.join(", ")}.`,
264
- entity
265
- );
266
- }
267
- }
268
- function drillCondition(entity, grain) {
269
- if (!grain) return { operator: "none" };
270
- assertGrain(entity, grain);
271
- return { operator: "transform_date_drill", values: [`datetrunc ${grain}`] };
272
- }
273
- function inferType(fieldType) {
274
- const type = fieldType.toLowerCase();
275
- if (type.includes("date") || type.includes("time")) return "date";
276
- if (type.includes("int") || type.includes("number") || type.includes("float") || type.includes("decimal")) return "number";
277
- if (type.includes("bool")) return "boolean";
278
- return "string";
279
- }
280
- function sameCondition(a, b) {
281
- return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
282
- }
283
- var Control = class extends Observable {
284
- constructor(name, app, initial) {
285
- super(app);
286
- __publicField(this, "name");
287
- __publicField(this, "app");
288
- __publicField(this, "pending");
289
- __publicField(this, "applied");
290
- __publicField(this, "initial");
291
- this.name = name;
292
- this.app = app;
293
- this.initial = initial;
294
- this.pending = initial;
295
- }
296
- /**
297
- * Bring the elements marked `data-anfra-control` with this control's name into view. False when
298
- * none is on the page yet; never throws.
299
- */
300
- locate() {
301
- return this.app.locate("control", this.name);
302
- }
303
- /** The reader's current value, which `execute()` will commit. */
304
- get condition() {
305
- return this.pending;
306
- }
307
- /** The value this control's mapped queries last ran with. Undefined before the first execution. */
308
- get appliedCondition() {
309
- return this.applied;
310
- }
311
- /**
312
- * False before the first execution: with nothing applied there is nothing to differ from, so a
313
- * control set from a URL at startup is not an unapplied change.
314
- */
315
- get isDirty() {
316
- return this.applied !== void 0 && !sameCondition(this.pending, this.applied);
317
- }
318
- setCondition(condition) {
319
- this.pending = condition;
320
- this.notify();
321
- }
322
- reset() {
323
- this.setCondition(this.initial);
324
- }
325
- /** @internal Called by the executor once the queries reading this control have been submitted. */
326
- commit() {
327
- this.applied = this.pending;
328
- }
329
- };
330
- var Filter = class extends Control {
331
- constructor(name, app, declaration, dataset, backend) {
332
- super(name, app, declaration.default ?? { operator: "is", values: [] });
333
- __publicField(this, "kind", "filter");
334
- __publicField(this, "declaration");
335
- __publicField(this, "type");
336
- __publicField(this, "resolved");
337
- __publicField(this, "datasetName");
338
- __publicField(this, "backend");
339
- __publicField(this, "loadedOptions");
340
- this.declaration = declaration;
341
- this.backend = backend;
342
- if (declaration.field) {
343
- if (!dataset) {
344
- throw new ValidationError(
345
- `Filter '${name}' names a field but no dataset. Pass \`dataset\` alongside \`field\`.`,
346
- name
347
- );
348
- }
349
- this.resolved = dataset.resolve(declaration.field, name);
350
- this.datasetName = dataset.descriptor.name;
351
- this.type = declaration.type ?? inferType(this.resolved.type);
352
- } else {
353
- if (!declaration.type) {
354
- throw new ValidationError(
355
- `Filter '${name}' is a manual filter, so it needs a \`type\`.`,
356
- name
357
- );
358
- }
359
- this.type = declaration.type;
360
- }
361
- this.assertValues(this.condition.values ?? []);
362
- this.assertValues(declaration.options ?? []);
363
- }
364
- setCondition(condition) {
365
- this.assertValues(condition.values ?? []);
366
- super.setCondition(condition);
367
- }
368
- /**
369
- * A number filter's values are strings, as query results give them, which keep every digit. A JS
370
- * number may already have lost some (`Number("9007199254740993")` is ...992), and nothing after
371
- * can tell, so the core API refuses one; this says so where the app hands it over.
372
- */
373
- assertValues(values) {
374
- if (this.type !== "number") return;
375
- const number = values.find((value) => typeof value === "number");
376
- if (number === void 0) return;
377
- throw new ValidationError(
378
- `Filter '${this.name}' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(number))}, not ${String(number)}), so none has lost a digit.`,
379
- this.name
380
- );
381
- }
382
- /** True for a field-backed filter, false for a manual one. The two are separate axes from `type`. */
383
- get isFieldBacked() {
384
- return this.resolved !== void 0;
385
- }
386
- /** A manual filter's static list, or whatever the last `loadOptions()` returned. */
387
- get options() {
388
- return this.loadedOptions ?? this.declaration.options ?? [];
389
- }
390
- /**
391
- * Fetches option values for a field-backed filter.
392
- *
393
- * Lazy rather than fetched up front: building a distinct-values query for every filter is slow,
394
- * and readers often touch none of them. The backend decides which values this reader may see.
395
- */
396
- async loadOptions(search, signal = new AbortController().signal) {
397
- const model = this.resolved?.modelName;
398
- if (!this.resolved || !model || !this.backend || !this.datasetName) return this.options;
399
- const options = await this.backend.fieldSuggestions(
400
- {
401
- dataset: this.datasetName,
402
- model,
403
- field: this.resolved.fieldName,
404
- q: search ?? ""
405
- },
406
- signal
407
- );
408
- this.loadedOptions = [...options ?? []];
409
- this.notify();
410
- return this.loadedOptions;
411
- }
412
- toJSON() {
413
- return this.declaration;
414
- }
415
- };
416
- var DateDrillControl = class extends Control {
417
- constructor(name, app, declaration = {}) {
418
- super(name, app, drillCondition(name, declaration.default));
419
- __publicField(this, "kind", "dateDrill");
420
- __publicField(this, "declaration");
421
- this.declaration = declaration;
422
- }
423
- setGrain(grain) {
424
- this.setCondition(drillCondition(this.name, grain));
425
- }
426
- toJSON() {
427
- return this.declaration;
428
- }
429
- };
430
-
431
- // src/app/mapping.ts
432
- var Mapping = class {
433
- constructor(from, to, field, aggregation) {
434
- __publicField(this, "kind", "control");
435
- __publicField(this, "from");
436
- __publicField(this, "to");
437
- __publicField(this, "field");
438
- __publicField(this, "aggregation");
439
- this.from = from;
440
- this.to = to;
441
- this.field = field;
442
- this.aggregation = aggregation;
443
- }
444
- /**
445
- * Includes the field, unlike Dashboard as Code's `${from}.${to}` — that form collides the moment
446
- * one control maps onto one query on two fields.
447
- */
448
- get id() {
449
- return `${this.from.name}.${this.to.name}.${this.field}`;
450
- }
451
- toJSON() {
452
- return {
453
- kind: this.kind,
454
- id: this.id,
455
- from: { kind: this.from.kind, name: this.from.name },
456
- to: { kind: "query", name: this.to.name },
457
- field: this.field,
458
- ...this.aggregation ? { aggregation: this.aggregation } : {}
459
- };
460
- }
461
- };
462
- var CrossFilter = class {
463
- constructor(from, to) {
464
- __publicField(this, "kind", "crossFilter");
465
- __publicField(this, "from");
466
- __publicField(this, "to");
467
- this.from = from;
468
- this.to = to;
469
- }
470
- /** No field to disambiguate, and one pair may only be declared once, so the pair is the id. */
471
- get id() {
472
- return `${this.from.name}.${this.to.name}`;
473
- }
474
- toJSON() {
475
- return {
476
- kind: this.kind,
477
- id: this.id,
478
- from: { kind: "query", name: this.from.name },
479
- to: { kind: "query", name: this.to.name }
480
- };
481
- }
482
- };
483
-
484
- // src/app/suggest.ts
485
- function editDistance(a, b) {
486
- const rows = a.length + 1;
487
- const cols = b.length + 1;
488
- let prev = Array.from({ length: cols }, (_, j) => j);
489
- for (let i = 1; i < rows; i++) {
490
- const curr = [i];
491
- for (let j = 1; j < cols; j++) {
492
- curr[j] = Math.min(
493
- prev[j] + 1,
494
- curr[j - 1] + 1,
495
- prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
496
- );
497
- }
498
- prev = curr;
499
- }
500
- return prev[cols - 1];
501
- }
502
- function suggest(value, candidates) {
503
- let best;
504
- let bestDistance = Infinity;
505
- candidates.forEach((candidate) => {
506
- const distance = editDistance(value.toLowerCase(), candidate.toLowerCase());
507
- if (distance < bestDistance) {
508
- bestDistance = distance;
509
- best = candidate;
510
- }
511
- });
512
- const threshold = Math.max(2, Math.floor(value.length / 3));
513
- return bestDistance <= threshold ? best : void 0;
514
- }
515
- function withSuggestion(message, value, candidates) {
516
- const hint = suggest(value, candidates);
517
- return hint ? `${message} Did you mean '${hint}'?` : message;
518
- }
519
-
520
- // src/app/validation.ts
521
- var DatasetIndex = class {
522
- constructor(descriptor) {
523
- __publicField(this, "descriptor");
524
- __publicField(this, "fields", /* @__PURE__ */ new Map());
525
- __publicField(this, "references");
526
- this.descriptor = descriptor;
527
- descriptor.data_models.forEach((model) => {
528
- model.fields.forEach((field) => {
529
- const modelName = String(model.name);
530
- this.fields.set(`${modelName}.${field.name}`, {
531
- modelName,
532
- fieldName: field.name,
533
- isMetric: false,
534
- type: field.type,
535
- label: field.label ?? field.name
536
- });
537
- });
538
- });
539
- descriptor.metrics.forEach((metric) => {
540
- this.fields.set(metric.name, {
541
- fieldName: metric.name,
542
- isMetric: true,
543
- type: metric.type,
544
- label: metric.label ?? metric.name
545
- });
546
- });
547
- this.references = [...this.fields.keys()];
548
- }
549
- resolve(reference, entity) {
550
- const field = this.fields.get(reference);
551
- if (field) return field;
552
- throw new ValidationError(
553
- withSuggestion(
554
- `Unknown field '${reference}' on dataset '${this.descriptor.name}'.`,
555
- reference,
556
- this.references
557
- ),
558
- entity
559
- );
560
- }
561
- };
562
- function resolveDataset(datasets, uname, entity) {
563
- const dataset = datasets[uname];
564
- if (dataset) return dataset;
565
- throw new ValidationError(
566
- withSuggestion(
567
- `Unknown dataset '${uname}'.`,
568
- uname,
569
- Object.keys(datasets)
570
- ),
571
- entity
572
- );
573
- }
574
- function assertValidFilterAggregation(aggregation, entity) {
575
- if (!FILTER_AGGREGATIONS.includes(aggregation)) {
576
- throw new ValidationError(
577
- withSuggestion(
578
- `Invalid filter aggregation '${aggregation}'.`,
579
- aggregation,
580
- [...FILTER_AGGREGATIONS]
581
- ),
582
- entity
583
- );
584
- }
585
- }
586
- function assertUniqueName(taken, name, kind) {
587
- if (!name) {
588
- throw new ValidationError(`A ${kind} needs a name.`);
589
- }
590
- for (const existing of taken) {
591
- if (existing === name) {
592
- throw new ValidationError(`'${name}' is already declared in this app.`, name);
593
- }
594
- }
595
- }
596
-
597
- // src/app/execution/submitQuery.ts
598
- function toFilter(mapping, condition) {
599
- if (!condition || condition.operator === "none" || condition.operator === "transform_date_drill") return void 0;
600
- const needsValues = !["is_null", "not_null", "is_true", "is_false", "transform_pop_none"].includes(condition.operator);
601
- if (needsValues && !condition.values?.length) return void 0;
602
- return {
603
- field: mapping.field,
604
- operator: condition.operator,
605
- values: condition.values ?? [],
606
- ...condition.modifier ? { modifier: condition.modifier } : {},
607
- ...mapping.aggregation ? { aggregation: mapping.aggregation } : {}
608
- };
609
- }
610
- function toDateDrill(mapping, condition) {
611
- if (condition?.operator !== "transform_date_drill") return void 0;
612
- const transformation = condition.values?.[0];
613
- if (typeof transformation !== "string") return void 0;
614
- const grain = transformation.replace(/^datetrunc\s+/, "");
615
- return { field: mapping.field, grain };
616
- }
617
- function toResult(query, data) {
618
- const columns = data.columns ?? [];
619
- const rows = (data.values ?? []).map((row) => {
620
- const record = {};
621
- columns.forEach((column, index) => {
622
- record[column.name] = row[index];
623
- });
624
- return record;
625
- });
626
- const { pageSize } = query;
627
- return {
628
- columns,
629
- rows,
630
- meta: {
631
- // Only a paged query has a page to report.
632
- ...pageSize !== void 0 ? { page: data.meta?.page ?? query.page, pageSize: data.meta?.pageSize ?? pageSize } : {},
633
- numRows: data.meta?.numRows ?? rows.length
634
- },
635
- ...data.debug ? { debug: data.debug } : {}
636
- };
637
- }
638
- function buildQuery(query, mappings, selection, context) {
639
- const mappedFilters = mappings.map((mapping) => toFilter(mapping, mapping.from.appliedCondition)).filter((filter) => filter !== void 0);
640
- const dateDrills = mappings.map((mapping) => toDateDrill(mapping, mapping.from.appliedCondition)).filter((drill) => drill !== void 0);
641
- const selectionFilters = selection.conditions.map((condition) => ({
642
- field: condition.field,
643
- operator: condition.operator,
644
- values: condition.values
645
- }));
646
- const conditions = selection.expression ? [{ expr: selection.expression }] : [];
647
- return {
648
- dataset: query.dataset.descriptor.name,
649
- aql: query.declaration.aql,
650
- input: {
651
- filters: [...mappedFilters, ...selectionFilters],
652
- conditions,
653
- sorts: query.sort.map((sort) => ({ field: sort.field, direction: sort.direction ?? "asc" })),
654
- dateDrills
655
- },
656
- // Omitted entirely when the app declares none, so the backend applies its own default rather
657
- // than the SDK guessing the browser's.
658
- ...context.timezone ? { timezone: context.timezone } : {}
659
- };
660
- }
661
- function buildRequest(query, mappings, selection, context) {
662
- return {
663
- ...buildQuery(query, mappings, selection, context),
664
- // Omitted for a query that declares no page size, so the backend returns every row.
665
- ...query.pageSize !== void 0 ? { page: query.page, pageSize: query.pageSize } : {},
666
- ...context.bustCache ? { bustCache: true } : {}
667
- };
668
- }
669
- function defaultExportFilename(query, title) {
670
- const safeTitle = title?.replace(/[/\\]/g, "-").replace(/\p{Cc}/gu, "").trim();
671
- return safeTitle ? `${safeTitle} - ${query.name}` : query.name;
672
- }
673
- function buildExportRequest(query, mappings, selection, context, options) {
674
- const format2 = options.format ?? "csv";
675
- const formatOptions = format2 === "csv" ? { bom: true, ...options.formatOptions } : options.formatOptions;
676
- return {
677
- ...buildQuery(query, mappings, selection, context),
678
- format: format2,
679
- ...formatOptions ? { formatOptions } : {},
680
- filename: options.filename?.trim() || defaultExportFilename(query, context.title)
681
- };
682
- }
683
- async function runQuery(query, mappings, selection, context, signal) {
684
- const request = buildRequest(query, mappings, selection, context);
685
- const data = await context.backend.submitQuery(request, signal);
686
- return toResult(query, data);
687
- }
688
-
689
- // src/app/aql.ts
690
- var LINE_SEPARATOR = String.fromCharCode(8232);
691
- var PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
692
- function literal(value, semanticType) {
693
- if (value === null) return "null";
694
- if (typeof value === "boolean") return value ? "true" : "false";
695
- if (semanticType === "number" && typeof value === "string") return numberLiteral(value);
696
- if (typeof value === "number") {
697
- if (!Number.isFinite(value)) {
698
- throw new RangeError(`Cannot express ${value} in AQL.`);
699
- }
700
- return Math.abs(value) >= 1e21 ? BigInt(value).toString() : String(value);
701
- }
702
- return JSON.stringify(value).split(LINE_SEPARATOR).join("\\u2028").split(PARAGRAPH_SEPARATOR).join("\\u2029");
703
- }
704
- function equals(field, value, semanticType) {
705
- return value === null ? `is(${field}, null)` : `${field} is ${literal(value, semanticType)}`;
706
- }
707
- var NON_FINITE = /* @__PURE__ */ new Set(["NaN", "Infinity", "-Infinity"]);
708
- var JSON_NUMBER = /^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
709
- function numberLiteral(value) {
710
- const match = JSON_NUMBER.exec(value);
711
- if (!match) {
712
- if (NON_FINITE.has(value)) throw new RangeError(`Cannot express ${value} in AQL.`);
713
- throw new TypeError(`${JSON.stringify(value)} is not a number: a number is a string in JSON's number syntax.`);
714
- }
715
- const [, sign, whole, fraction = "", exponent] = match;
716
- if (exponent === void 0) return value;
717
- const digits = whole + fraction;
718
- const point = whole.length + Number(exponent);
719
- let out;
720
- if (point <= 0) out = `0.${"0".repeat(-point)}${digits}`;
721
- else if (point >= digits.length) out = digits + "0".repeat(point - digits.length);
722
- else out = `${digits.slice(0, point)}.${digits.slice(point)}`;
723
- return sign + out.replace(/^0+(?=\d)/, "");
724
- }
725
- function dateRange(field, start, end) {
726
- return `${field} matches @(${start} until ${end})`;
727
- }
728
- function combine(fn, parts) {
729
- if (parts.length === 0) {
730
- throw new RangeError(`\`${fn}\` needs at least one operand.`);
731
- }
732
- return parts.length === 1 ? parts[0] : `${fn}(${parts.join(", ")})`;
733
- }
734
- var and = (parts) => combine("and", parts);
735
- var or = (parts) => combine("or", parts);
736
-
737
- // src/app/selection.ts
738
- var TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?/;
739
- var FIXED_MS = {
740
- week: 7 * 864e5,
741
- day: 864e5,
742
- hour: 36e5,
743
- minute: 6e4
744
- };
745
- function parseStamp(value) {
746
- if (typeof value !== "string") return void 0;
747
- const match = TIMESTAMP.exec(value);
748
- if (!match) return void 0;
749
- return {
750
- year: Number(match[1]),
751
- month: Number(match[2]) - 1,
752
- day: Number(match[3]),
753
- hour: Number(match[4] ?? 0),
754
- minute: Number(match[5] ?? 0),
755
- second: Number(match[6] ?? 0),
756
- hasTime: match[4] !== void 0
757
- };
758
- }
759
- function format(ms, hasTime) {
760
- const date = new Date(ms);
761
- const pad = (value) => String(value).padStart(2, "0");
762
- const day = `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
763
- if (!hasTime) return day;
764
- return `${day} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`;
765
- }
766
- function toMs(stamp) {
767
- return Date.UTC(stamp.year, stamp.month, stamp.day, stamp.hour, stamp.minute, stamp.second);
768
- }
769
- function normalise(value) {
770
- const stamp = parseStamp(value);
771
- if (!stamp) return void 0;
772
- return format(toMs(stamp), stamp.hasTime);
773
- }
774
- function addGrain(value, grain) {
775
- const stamp = parseStamp(value);
776
- if (!stamp) return void 0;
777
- const {
778
- year,
779
- month,
780
- day,
781
- hour,
782
- minute,
783
- second,
784
- hasTime
785
- } = stamp;
786
- if (grain === "year") return format(Date.UTC(year + 1, month, day, hour, minute, second), hasTime);
787
- if (grain === "quarter") return format(Date.UTC(year, month + 3, day, hour, minute, second), hasTime);
788
- if (grain === "month") return format(Date.UTC(year, month + 1, day, hour, minute, second), hasTime);
789
- return format(toMs(stamp) + FIXED_MS[grain], hasTime);
790
- }
791
- function grainOf(transformation) {
792
- if (!transformation?.startsWith("datetrunc ")) return void 0;
793
- return transformation.slice("datetrunc ".length);
794
- }
795
- function distinct(values) {
796
- const seen = /* @__PURE__ */ new Set();
797
- return values.filter((value) => {
798
- const key = `${typeof value}:${String(value)}`;
799
- if (seen.has(key)) return false;
800
- seen.add(key);
801
- return true;
802
- });
803
- }
804
- function isContiguous(values, grain) {
805
- const stamps = values.map(normalise);
806
- if (stamps.some((stamp) => stamp === void 0)) return false;
807
- const sorted = stamps.slice().sort();
808
- for (let index = 1; index < sorted.length; index += 1) {
809
- if (addGrain(sorted[index - 1], grain) !== sorted[index]) return false;
810
- }
811
- return true;
812
- }
813
- function dateRange2(field, values, grain) {
814
- const stamps = values.map(normalise);
815
- if (stamps.some((stamp) => stamp === void 0)) return void 0;
816
- const sorted = stamps.slice().sort();
817
- const start = sorted[0];
818
- const end = addGrain(sorted[sorted.length - 1], grain);
819
- if (!end) return void 0;
820
- const contiguous = isContiguous(values, grain);
821
- return {
822
- // End-exclusive: `until` is the start of the bucket after the last one selected.
823
- condition: { field, operator: "matches", values: [`${start} until ${end}`] },
824
- admits: contiguous ? values.length : Number.POSITIVE_INFINITY,
825
- lossy: !contiguous
826
- };
827
- }
828
- function deriveOne(field, transformation, raw) {
829
- const present = raw.filter((value) => value !== null && value !== void 0);
830
- const values = distinct(present);
831
- if (!values.length) {
832
- return { condition: { field, operator: "is_null", values: [] }, admits: 1, lossy: false };
833
- }
834
- const droppedNulls = present.length !== raw.length;
835
- const grain = grainOf(transformation);
836
- if (grain) {
837
- const range = dateRange2(field, values, grain);
838
- if (range) return { ...range, lossy: range.lossy || droppedNulls };
839
- }
840
- return {
841
- condition: { field, operator: "is", values },
842
- admits: values.length,
843
- lossy: droppedNulls
844
- };
845
- }
846
- function fieldReferenceOf(column) {
847
- return column.modelId ? `${column.modelId}.${column.fieldName}` : column.fieldName;
848
- }
849
- function selectionExpression(columnsByAlias, aliases, rows, transformations) {
850
- try {
851
- const perRow = rows.map((row) => and(aliases.map((alias) => {
852
- const column = columnsByAlias.get(alias);
853
- const field = fieldReferenceOf(column);
854
- const raw = row[alias] ?? null;
855
- const grain = grainOf(transformations[field]);
856
- if (grain && typeof raw === "string") {
857
- const start = normalise(raw);
858
- const end = addGrain(raw, grain);
859
- if (start && end) return dateRange(field, start, end);
860
- }
861
- if (raw !== null && typeof raw !== "string" && typeof raw !== "number" && typeof raw !== "boolean") {
862
- throw new TypeError("no AQL spelling");
863
- }
864
- return equals(field, raw, column.semantic_type);
865
- })));
866
- return or(perRow);
867
- } catch {
868
- return void 0;
869
- }
870
- }
871
- function deriveSelection(query, rows, fields, transformations = {}) {
872
- const columns = query.result?.columns ?? [];
873
- const columnsByAlias = new Map(columns.map((column) => [column.name, column]));
874
- fields?.forEach((alias) => {
875
- const column = columnsByAlias.get(alias);
876
- if (column) {
877
- if (column.adhoc) {
878
- throw new ValidationError(
879
- `Query '${query.name}' cannot cross-filter on '${alias}': 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.`,
880
- query.name
881
- );
882
- }
883
- if (column.isMeasure) {
884
- throw new ValidationError(
885
- `Query '${query.name}' cannot cross-filter on '${alias}': it is a measure, and a selection conditions dimensions only.`,
886
- query.name
887
- );
888
- }
889
- return;
890
- }
891
- throw new ValidationError(
892
- withSuggestion(
893
- `Query '${query.name}' has no column '${alias}' in its last result.`,
894
- alias,
895
- [...columnsByAlias.keys()]
896
- ),
897
- query.name
898
- );
899
- });
900
- const dimensionLike = columns.filter((column) => !column.isMeasure);
901
- const selectable = dimensionLike.filter((column) => !column.adhoc).map((column) => column.name);
902
- const aliases = fields ? [...fields] : selectable;
903
- if (!rows.length || !aliases.length) return void 0;
904
- const conditions = [];
905
- let admitted = 1;
906
- const droppedColumns = !fields && selectable.length !== dimensionLike.length;
907
- let collapseLossy = false;
908
- aliases.forEach((alias) => {
909
- const column = columnsByAlias.get(alias);
910
- const field = fieldReferenceOf(column);
911
- const derived = deriveOne(field, transformations[field], rows.map((row) => row[alias]));
912
- conditions.push(derived.condition);
913
- admitted *= derived.admits;
914
- collapseLossy = collapseLossy || derived.lossy;
915
- });
916
- const picked = new Set(rows.map((row) => JSON.stringify(aliases.map((alias) => row[alias] ?? null))));
917
- if (admitted > picked.size) collapseLossy = true;
918
- const sorted = conditions.sort((a, b) => a.field.localeCompare(b.field));
919
- const base = { source: query.name, rows: [...rows], fields: aliases };
920
- if (collapseLossy) {
921
- const expression = selectionExpression(columnsByAlias, aliases, rows, transformations);
922
- if (expression) {
923
- return {
924
- ...base,
925
- conditions: [],
926
- expression,
927
- lossy: droppedColumns
928
- };
929
- }
930
- }
931
- return { ...base, conditions: sorted, lossy: droppedColumns || collapseLossy };
932
- }
933
-
934
- // src/app/structure.ts
935
- var ATTR = {
936
- container: "data-anfra-container",
937
- block: "data-anfra-block",
938
- query: "data-anfra-query",
939
- control: "data-anfra-control",
940
- label: "data-anfra-label"
941
- };
942
- var MARKED = `[${ATTR.container}],[${ATTR.block}],[${ATTR.query}],[${ATTR.control}]`;
943
- function parseRef(token) {
944
- const match = /^(?:(\d+)\/)?([^/\s]+)$/.exec(token);
945
- if (!match) return void 0;
946
- return { app: match[1] === void 0 ? 0 : Number(match[1]), name: match[2] };
947
- }
948
- var tokens = (value) => (value ?? "").split(/\s+/).filter(Boolean);
949
- function markersFor(doc, kind, app, name) {
950
- const attr = kind === "query" ? ATTR.query : ATTR.control;
951
- return [...doc.querySelectorAll(`[${attr}]`)].filter((element) => tokens(element.getAttribute(attr)).some((token) => {
952
- const ref = parseRef(token);
953
- return ref?.app === app && ref.name === name;
954
- }));
955
- }
956
- var hasEntity = (apps, kind, ref) => {
957
- const app = apps[ref.app];
958
- if (!app) return false;
959
- return Object.prototype.hasOwnProperty.call(kind === "query" ? app.queries : app.controls, ref.name);
960
- };
961
- function buildStructure(doc, apps) {
962
- var _a;
963
- const roots = [];
964
- const elements = /* @__PURE__ */ new Map();
965
- const keysOf = /* @__PURE__ */ new Map();
966
- const nodeOf = /* @__PURE__ */ new Map();
967
- const kindOf = /* @__PURE__ */ new Map();
968
- const seenIds = { container: /* @__PURE__ */ new Set(), block: /* @__PURE__ */ new Set() };
969
- const usage = {};
970
- const place = (parent, node, element) => {
971
- const siblings = parent ? nodeOf.get(parent).children : roots;
972
- const prefix = parent ? `${nodeOf.get(parent).key}.` : "";
973
- const full = { ...node, key: `${prefix}${siblings.length}`, children: [] };
974
- siblings.push(full);
975
- elements.set(full.key, element);
976
- keysOf.set(element, [...keysOf.get(element) ?? [], full.key]);
977
- return full;
978
- };
979
- for (const element of doc.querySelectorAll(MARKED)) {
980
- const parent = element.parentElement?.closest(MARKED) ?? null;
981
- const containerId = element.getAttribute(ATTR.container);
982
- const blockId = element.getAttribute(ATTR.block);
983
- const label = element.getAttribute(ATTR.label) ?? void 0;
984
- const enclosingBlock = parent && (kindOf.get(parent) === "block" ? parent : parent.closest(`[${ATTR.block}]`));
985
- let own;
986
- if (containerId !== null || blockId !== null) {
987
- const kind = containerId !== null ? "container" : "block";
988
- const id = (containerId ?? blockId ?? "").trim();
989
- const problems = [];
990
- if (containerId !== null && blockId !== null) problems.push("This element is marked as a container and as a block. It counts as a container.");
991
- if (!id) problems.push(`This ${kind} has no id.`);
992
- else if (seenIds[kind].has(id)) problems.push(`Another ${kind} already has the id "${id}".`);
993
- else seenIds[kind].add(id);
994
- if (enclosingBlock) {
995
- problems.push(`A block can't hold a ${kind}. This one is inside the block "${enclosingBlock.getAttribute(ATTR.block)}".`);
996
- }
997
- own = place(parent, {
998
- kind,
999
- id,
1000
- ...label !== void 0 ? { label } : {},
1001
- problems
1002
- }, element);
1003
- nodeOf.set(element, own);
1004
- kindOf.set(element, kind);
1005
- }
1006
- const under = own ? element : parent;
1007
- for (const kind of ["query", "control"]) {
1008
- for (const token of tokens(element.getAttribute(kind === "query" ? ATTR.query : ATTR.control))) {
1009
- const ref = parseRef(token);
1010
- const problems = [];
1011
- if (!ref) problems.push(`Can't read "${token}". Write the ${kind}'s name, or app/name when the page has several apps.`);
1012
- else if (!hasEntity(apps, kind, ref)) {
1013
- problems.push(apps[ref.app] ? `No ${kind} is called "${ref.name}" in app ${ref.app}.` : `The page has no app ${ref.app}.`);
1014
- }
1015
- place(under, {
1016
- kind,
1017
- name: ref?.name ?? token,
1018
- app: ref?.app ?? 0,
1019
- problems
1020
- }, element);
1021
- if (ref && !problems.length) {
1022
- const key = `${ref.app}/${ref.name}`;
1023
- const entry = usage[_a = `${kind}:${key}`] ?? (usage[_a] = { elements: /* @__PURE__ */ new Set(), blocks: /* @__PURE__ */ new Set() });
1024
- entry.elements.add(element);
1025
- const block = own?.kind === "block" ? own.id : enclosingBlock?.getAttribute(ATTR.block);
1026
- if (block) entry.blocks.add(block);
1027
- }
1028
- }
1029
- }
1030
- }
1031
- const usageOut = Object.fromEntries(
1032
- Object.entries(usage).map(([key, entry]) => [key, { markers: entry.elements.size, blocks: [...entry.blocks] }])
1033
- );
1034
- return {
1035
- nodes: roots,
1036
- usage: usageOut,
1037
- elements,
1038
- keysOf
1039
- };
1040
- }
1041
- var usageKey = (kind, app, name) => `${kind}:${app}/${name}`;
1042
- function sizeOf(element) {
1043
- const rect = element.getBoundingClientRect();
1044
- return `${Math.round(rect.width)} \xD7 ${Math.round(rect.height)}`;
1045
- }
1046
- function describeNode(node, element, structure) {
1047
- const size = sizeOf(element);
1048
- if (node.kind === "container" || node.kind === "block") {
1049
- return {
1050
- kind: node.kind,
1051
- name: node.id ?? "",
1052
- ...node.label ? { label: node.label } : {},
1053
- size
1054
- };
1055
- }
1056
- const use = structure.usage[usageKey(node.kind, node.app ?? 0, node.name ?? "")];
1057
- return {
1058
- kind: node.kind,
1059
- name: node.name ?? "",
1060
- ...use && use.markers > 1 ? { note: `1 of ${use.markers}` } : {},
1061
- size
1062
- };
1063
- }
1064
-
1065
- // src/app/overlay.ts
1066
- var OVERLAY_ID = "anfra-overlay";
1067
- var FLASH_MS = 1500;
1068
- var BOX_STYLE = "position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;";
1069
- var LABEL_STYLE = "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);";
1070
- var PART_STYLE = {
1071
- kind: "color:#94a3b8;",
1072
- name: "color:#93c5fd;font-weight:700;",
1073
- label: "color:#f8fafc;",
1074
- note: "color:#94a3b8;",
1075
- size: "color:#94a3b8;margin-left:10px;"
1076
- };
1077
- var Overlay = class {
1078
- constructor(doc) {
1079
- __publicField(this, "doc", doc);
1080
- __publicField(this, "root");
1081
- __publicField(this, "shown", []);
1082
- __publicField(this, "text", { kind: "", name: "" });
1083
- __publicField(this, "timer");
1084
- __publicField(this, "reposition", () => this.draw());
1085
- const existing = doc.getElementById(OVERLAY_ID);
1086
- if (existing) {
1087
- this.root = existing;
1088
- } else {
1089
- this.root = doc.createElement("div");
1090
- this.root.id = OVERLAY_ID;
1091
- this.root.setAttribute("aria-hidden", "true");
1092
- this.root.setAttribute("style", "position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;");
1093
- (doc.body ?? doc.documentElement).appendChild(this.root);
1094
- }
1095
- }
1096
- /** Show the overlay on these elements, labelled, until `hide()` or the next `show()`. */
1097
- show(elements, text) {
1098
- this.clearTimer();
1099
- this.shown = [...elements];
1100
- this.text = text;
1101
- if (!this.shown.length) {
1102
- this.hide();
1103
- return;
1104
- }
1105
- this.root.style.display = "block";
1106
- this.draw();
1107
- this.doc.addEventListener("scroll", this.reposition, { capture: true, passive: true });
1108
- this.doc.defaultView?.addEventListener("resize", this.reposition);
1109
- }
1110
- /** Show for a moment, then hide. */
1111
- flash(elements, text, ms = FLASH_MS) {
1112
- this.show(elements, text);
1113
- this.timer = setTimeout(() => this.hide(), ms);
1114
- }
1115
- hide() {
1116
- this.clearTimer();
1117
- this.shown = [];
1118
- this.root.style.display = "none";
1119
- this.root.replaceChildren();
1120
- this.doc.removeEventListener("scroll", this.reposition, { capture: true });
1121
- this.doc.defaultView?.removeEventListener("resize", this.reposition);
1122
- }
1123
- get visible() {
1124
- return this.shown.length > 0;
1125
- }
1126
- clearTimer() {
1127
- if (this.timer !== void 0) clearTimeout(this.timer);
1128
- this.timer = void 0;
1129
- }
1130
- draw() {
1131
- const boxes = this.shown.map((element) => {
1132
- const r = element.getBoundingClientRect();
1133
- const box = this.doc.createElement("div");
1134
- box.setAttribute("style", `${BOX_STYLE}left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;`);
1135
- return box;
1136
- });
1137
- const first = this.shown[0].getBoundingClientRect();
1138
- const label = this.doc.createElement("div");
1139
- label.setAttribute("data-testid", "anfra-overlay-label");
1140
- const viewportHeight = this.doc.defaultView?.innerHeight ?? 0;
1141
- const top = first.top >= 26 ? first.top - 24 : Math.max(4, first.top + 4);
1142
- const left = Math.max(4, Math.min(first.left, (this.doc.defaultView?.innerWidth ?? 0) - 24));
1143
- label.setAttribute("style", `${LABEL_STYLE}left:${left}px;top:${Math.min(top, viewportHeight - 24)}px;`);
1144
- for (const part of ["kind", "name", "label", "note", "size"]) {
1145
- const value = this.text[part];
1146
- if (!value) continue;
1147
- const span = this.doc.createElement("span");
1148
- span.setAttribute("style", PART_STYLE[part]);
1149
- span.setAttribute("data-part", part);
1150
- span.textContent = value;
1151
- label.appendChild(span);
1152
- }
1153
- this.root.replaceChildren(...boxes, label);
1154
- }
1155
- };
1156
- var overlays = /* @__PURE__ */ new WeakMap();
1157
- function overlayFor(doc) {
1158
- let overlay = overlays.get(doc);
1159
- if (!overlay) {
1160
- overlay = new Overlay(doc);
1161
- overlays.set(doc, overlay);
1162
- }
1163
- return overlay;
1164
- }
1165
- function scrollTo(element) {
1166
- if (typeof element.scrollIntoView === "function") {
1167
- element.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });
1168
- }
1169
- }
1170
-
1171
- // src/app/app.ts
1172
- var NO_CONDITIONS = Object.freeze([]);
1173
- function isAbort(err) {
1174
- return err instanceof Error && err.name === "AbortError";
1175
- }
1176
- function superseded(query, controller) {
1177
- return query.controller !== controller;
1178
- }
1179
- function inspectError(error) {
1180
- return {
1181
- name: error.name,
1182
- message: error.message,
1183
- ...error.entity ? { entity: error.entity } : {},
1184
- ...typeof error.status === "number" ? { status: error.status } : {},
1185
- ...error.stack ? { stack: error.stack } : {}
1186
- };
1187
- }
1188
- function inspectQuery(query) {
1189
- const { result } = query;
1190
- return {
1191
- state: query.state,
1192
- isDirty: query.isDirty,
1193
- page: query.page,
1194
- hasMore: query.hasMore,
1195
- // Metadata, never rows: rows are the one unbounded thing here, and the one thing already on
1196
- // screen in the preview beside the panel.
1197
- columns: result ? result.columns.map((column) => ({ ...column })) : [],
1198
- rowCount: result?.meta.numRows ?? 0,
1199
- selectedRowCount: query.selectedRows.length,
1200
- signature: query.signature(),
1201
- ...query.error ? { error: inspectError(query.error) } : {},
1202
- ...result?.debug ? { debug: { ...result.debug } } : {}
1203
- };
1204
- }
1205
- function inspectControl(control) {
1206
- const { options } = control;
1207
- return {
1208
- kind: control.kind,
1209
- condition: { ...control.condition },
1210
- ...control.appliedCondition ? { appliedCondition: { ...control.appliedCondition } } : {},
1211
- isDirty: control.isDirty,
1212
- ...options ? { options: [...options] } : {}
1213
- };
1214
- }
1215
- function inspectSelection(selection) {
1216
- return {
1217
- source: selection.source,
1218
- fields: [...selection.fields],
1219
- rowCount: selection.rows.length,
1220
- conditions: selection.conditions.map((condition) => ({ ...condition })),
1221
- ...selection.expression ? { expression: selection.expression } : {},
1222
- lossy: selection.lossy
1223
- };
1224
- }
1225
- function selectionKey(selection) {
1226
- if (!selection) return "none";
1227
- return JSON.stringify({
1228
- source: selection.source,
1229
- conditions: selection.conditions,
1230
- expression: selection.expression
1231
- });
1232
- }
1233
- function toDataAppError(err, entity) {
1234
- if (err instanceof DataAppError) return err;
1235
- return new QueryError(err?.message ?? "The query failed.", entity, err);
1236
- }
1237
- function toExportError(err, entity) {
1238
- if (err instanceof DataAppError && err.entity) return err;
1239
- const message = err?.message || "The export failed.";
1240
- if (err instanceof PermissionError) return new PermissionError(message, entity);
1241
- if (err instanceof TransportError) return new TransportError(message, err.status, entity);
1242
- if (err instanceof ValidationError) return new ValidationError(message, entity);
1243
- return new QueryError(message, entity, err);
1244
- }
1245
- var App = class extends Observable {
1246
- constructor(declaration, datasets, backend, features) {
1247
- super();
1248
- __publicField(this, "title");
1249
- __publicField(this, "_timezone");
1250
- __publicField(this, "datasets");
1251
- __publicField(this, "backend");
1252
- __publicField(this, "features");
1253
- __publicField(this, "_queries", /* @__PURE__ */ new Map());
1254
- __publicField(this, "_controls", /* @__PURE__ */ new Map());
1255
- __publicField(this, "_mappings", []);
1256
- __publicField(this, "_crossFilters", []);
1257
- __publicField(this, "_selection");
1258
- __publicField(this, "_appliedSelection");
1259
- /**
1260
- * Whether a run has ever committed the selection. Needed because `undefined` is a real applied
1261
- * value — "nothing selected" — unlike a control's condition, which is always present.
1262
- */
1263
- __publicField(this, "selectionCommitted", false);
1264
- /**
1265
- * @internal This app's index among the frame's apps, which is how a marked element names it
1266
- * (`data-anfra-query="1/revenue"`); 0 unless set by the instance that created it.
1267
- */
1268
- __publicField(this, "index", 0);
1269
- this.title = declaration.title;
1270
- this._timezone = declaration.timezone;
1271
- this.datasets = datasets;
1272
- this.backend = backend;
1273
- this.features = features;
1274
- }
1275
- /* ----------------------------------------------------------------
1276
- Declaration
1277
- ---------------------------------------------------------------- */
1278
- get queries() {
1279
- return Object.fromEntries(this._queries);
1280
- }
1281
- get controls() {
1282
- return Object.fromEntries(this._controls);
1283
- }
1284
- /** Every edge in the app's entity graph, of both kinds. Narrow on `kind`. */
1285
- get mappings() {
1286
- return [...this._mappings, ...this._crossFilters];
1287
- }
1288
- get crossFilters() {
1289
- return this._crossFilters;
1290
- }
1291
- createQuery(name, declaration) {
1292
- this.assertNameFree(name, "query");
1293
- const query = new Query(name, this, declaration);
1294
- this._queries.set(name, query);
1295
- this.notify();
1296
- return query;
1297
- }
1298
- createFilter(name, declaration) {
1299
- this.assertNameFree(name, "filter");
1300
- const dataset = declaration.dataset ? this.datasetIndex(declaration.dataset, name) : this.soleDataset(name, declaration.field);
1301
- const filter = new Filter(name, this, declaration, dataset, this.backend);
1302
- this._controls.set(name, filter);
1303
- this.notify();
1304
- return filter;
1305
- }
1306
- createDateDrill(name, declaration = {}) {
1307
- if (this.features?.dateDrill === false) {
1308
- throw new ValidationError(
1309
- `Date drill '${name}' needs a capability this workspace has not enabled. Ask an admin to turn on \`interactive_control:date_drill\`.`,
1310
- name
1311
- );
1312
- }
1313
- this.assertNameFree(name, "date drill control");
1314
- const control = new DateDrillControl(name, this, declaration);
1315
- this._controls.set(name, control);
1316
- this.notify();
1317
- return control;
1318
- }
1319
- /**
1320
- * Declares one edge. Always explicit — the field is never inferred from the control's own field,
1321
- * because "the control happens to name a field this query also has" is exactly the coupling that
1322
- * breaks silently when someone renames a dimension.
1323
- *
1324
- * There is no `unmap`: a mapping you do not want is one you do not declare.
1325
- */
1326
- mapControl(from, to, options) {
1327
- if (!(from instanceof Control)) {
1328
- throw new ValidationError(
1329
- "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."
1330
- );
1331
- }
1332
- if (this._controls.get(from.name) !== from) {
1333
- throw new ValidationError(`Control '${from.name}' belongs to a different app.`, from.name);
1334
- }
1335
- if (this._queries.get(to.name) !== to) {
1336
- throw new ValidationError(`Query '${to.name}' belongs to a different app.`, to.name);
1337
- }
1338
- if (options.aggregation) {
1339
- assertValidFilterAggregation(options.aggregation, from.name);
1340
- }
1341
- const mapping = new Mapping(from, to, options.field, options.aggregation);
1342
- if (this._mappings.some((existing) => existing.id === mapping.id)) {
1343
- throw new ValidationError(`Mapping '${mapping.id}' is already declared.`, from.name);
1344
- }
1345
- this.assertAcyclic(mapping);
1346
- this._mappings.push(mapping);
1347
- this.notify();
1348
- return mapping;
1349
- }
1350
- /**
1351
- * Declares that selecting rows in `from` may cross-filter `to`.
1352
- *
1353
- * No field: which fields a selection conditions is decided when the reader picks rows, not here.
1354
- * Explicit, like every other edge — there is no "cross-filter everything on this dataset",
1355
- * because an author who adds a sixth query should not silently acquire five new edges.
1356
- *
1357
- * Declaring both directions is normal and is not a cycle: one selection is live at a time and
1358
- * never cascades, so `a -> b` and `b -> a` simply means either chart may drive the other.
1359
- */
1360
- mapCrossFilter(from, to) {
1361
- if (!(from instanceof Query) || !(to instanceof Query)) {
1362
- throw new ValidationError(
1363
- "mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field })."
1364
- );
1365
- }
1366
- if (this._queries.get(from.name) !== from) {
1367
- throw new ValidationError(`Query '${from.name}' belongs to a different app.`, from.name);
1368
- }
1369
- if (this._queries.get(to.name) !== to) {
1370
- throw new ValidationError(`Query '${to.name}' belongs to a different app.`, to.name);
1371
- }
1372
- if (from === to) {
1373
- throw new ValidationError(
1374
- `Query '${from.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.`,
1375
- from.name
1376
- );
1377
- }
1378
- if (from.declaration.dataset !== to.declaration.dataset) {
1379
- throw new ValidationError(
1380
- `Cross-filter '${from.name}' -> '${to.name}' spans two datasets ('${from.declaration.dataset}' and '${to.declaration.dataset}'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,
1381
- from.name
1382
- );
1383
- }
1384
- const edge = new CrossFilter(from, to);
1385
- if (this._crossFilters.some((existing) => existing.id === edge.id)) {
1386
- throw new ValidationError(`Cross-filter '${edge.id}' is already declared.`, from.name);
1387
- }
1388
- this._crossFilters.push(edge);
1389
- this.notify();
1390
- return edge;
1391
- }
1392
- /* ----------------------------------------------------------------
1393
- Selection
1394
- ---------------------------------------------------------------- */
1395
- /**
1396
- * What the reader has picked, if anything.
1397
- *
1398
- * Held here rather than on a query because it belongs to none of them: picking rows in a second
1399
- * query replaces it. Every control still owns its own condition — this is the one piece of
1400
- * reader state with no natural owner.
1401
- */
1402
- get selection() {
1403
- return this._selection;
1404
- }
1405
- /** The selection the cross-filtered queries last ran with. */
1406
- get appliedSelection() {
1407
- return this._appliedSelection;
1408
- }
1409
- clearSelection() {
1410
- if (!this._selection) return;
1411
- this._selection = void 0;
1412
- this.notify();
1413
- }
1414
- /** Part of the declaration, not the environment. Changing it makes every query dirty. */
1415
- setTimezone(timezone) {
1416
- this._timezone = timezone;
1417
- this.notify();
1418
- }
1419
- get timezone() {
1420
- return this._timezone;
1421
- }
1422
- /* ----------------------------------------------------------------
1423
- AppContext
1424
- ---------------------------------------------------------------- */
1425
- datasetIndex(uname, entity) {
1426
- return resolveDataset(this.datasets, uname, entity);
1427
- }
1428
- mappingsTo(queryName) {
1429
- return this._mappings.filter((mapping) => mapping.to.name === queryName);
1430
- }
1431
- /** The expression form, set only when the structured conditions would have been lossy. */
1432
- selectionExpressionFor(queryName, phase) {
1433
- return this.selectionFor(queryName, phase)?.expression;
1434
- }
1435
- selectionFor(queryName, phase) {
1436
- const selection = phase === "pending" ? this._selection : this._appliedSelection;
1437
- if (!selection) return void 0;
1438
- if (selection.source === queryName) return void 0;
1439
- const reached = this._crossFilters.some(
1440
- (edge) => edge.from.name === selection.source && edge.to.name === queryName
1441
- );
1442
- return reached ? selection : void 0;
1443
- }
1444
- selectionConditionsFor(queryName, phase) {
1445
- const selection = phase === "pending" ? this._selection : this._appliedSelection;
1446
- if (!selection) return NO_CONDITIONS;
1447
- if (selection.source === queryName) return NO_CONDITIONS;
1448
- const reached = this._crossFilters.some(
1449
- (edge) => edge.from.name === selection.source && edge.to.name === queryName
1450
- );
1451
- return reached ? selection.conditions : NO_CONDITIONS;
1452
- }
1453
- /**
1454
- * The transformation each of this query's fields is currently drawn at, from the date drills
1455
- * mapped onto it.
1456
- *
1457
- * `appliedCondition`, not `condition`: a drill the reader has changed but not applied has not
1458
- * rebucketed anything yet, so the rows they are clicking still belong to the applied grain.
1459
- */
1460
- drillTransformations(query) {
1461
- const byField = {};
1462
- this._mappings.forEach((mapping) => {
1463
- if (mapping.to !== query) return;
1464
- const condition = mapping.from.appliedCondition;
1465
- if (condition?.operator !== "transform_date_drill") return;
1466
- const [value] = condition.values ?? [];
1467
- if (typeof value === "string") byField[mapping.field] = value;
1468
- });
1469
- return byField;
1470
- }
1471
- select(query, rows, fields) {
1472
- if (this._queries.get(query.name) !== query) {
1473
- throw new ValidationError(`Query '${query.name}' belongs to a different app.`, query.name);
1474
- }
1475
- const selection = deriveSelection(query, rows, fields, this.drillTransformations(query));
1476
- if (selection?.lossy) {
1477
- console.warn(
1478
- `[anfra-sdk] The selection in '${query.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.`
1479
- );
1480
- }
1481
- this._selection = selection;
1482
- this.notify();
1483
- }
1484
- /* ----------------------------------------------------------------
1485
- Execution
1486
- ---------------------------------------------------------------- */
1487
- /** True when a control or the selection has changed since the queries reading it last ran. */
1488
- get hasChanges() {
1489
- return [...this._controls.values()].some((control) => control.isDirty) || this.isSelectionDirty;
1490
- }
1491
- /**
1492
- * False before the first execution, matching `Control.isDirty`: with nothing applied there is
1493
- * nothing to differ from, so a selection restored at startup is not an unapplied change.
1494
- */
1495
- get isSelectionDirty() {
1496
- if (!this.selectionCommitted) return false;
1497
- return selectionKey(this._selection) !== selectionKey(this._appliedSelection);
1498
- }
1499
- /**
1500
- * Runs every query that would produce something new, and resolves with which succeeded and which
1501
- * failed. Never rejects: a failed query sets its own `state` and `error`, because one broken
1502
- * query must not blank the other four. See docs/adr/0002.
1503
- */
1504
- async execute(options = {}) {
1505
- const targets = [...this._queries.values()].filter((query) => query.shouldRun(options.force));
1506
- this._controls.forEach((control) => control.commit());
1507
- this._appliedSelection = this._selection;
1508
- this.selectionCommitted = true;
1509
- targets.forEach((query) => {
1510
- query.controller?.abort();
1511
- query.resetPage();
1512
- });
1513
- const context = {
1514
- backend: this.backend,
1515
- timezone: this._timezone,
1516
- bustCache: options.bustCache
1517
- };
1518
- const succeeded = [];
1519
- const failed = [];
1520
- await Promise.all(targets.map(async (query) => {
1521
- const controller = new AbortController();
1522
- query.controller = controller;
1523
- const signature = query.signature();
1524
- query.markExecuting();
1525
- try {
1526
- const result = await runQuery(
1527
- query,
1528
- this.mappingsTo(query.name),
1529
- {
1530
- conditions: this.selectionConditionsFor(query.name, "applied"),
1531
- expression: this.selectionExpressionFor(query.name, "applied")
1532
- },
1533
- context,
1534
- controller.signal
1535
- );
1536
- if (superseded(query, controller)) return;
1537
- query.markSuccess(result, signature, false);
1538
- succeeded.push(query.name);
1539
- } catch (err) {
1540
- if (superseded(query, controller)) return;
1541
- if (isAbort(err)) return;
1542
- query.markError(toDataAppError(err, query.name));
1543
- failed.push(query.name);
1544
- } finally {
1545
- if (query.controller === controller) query.controller = void 0;
1546
- }
1547
- }));
1548
- return { succeeded, failed };
1549
- }
1550
- /** Re-runs everything and asks the server to skip its result cache. */
1551
- async refresh() {
1552
- return this.execute({ force: true, bustCache: true });
1553
- }
1554
- abort() {
1555
- this._queries.forEach((query) => query.abort());
1556
- }
1557
- /** @internal Backs `query.fetchMore()`. Rejects, so an explicit page request reports its failure. */
1558
- async fetchPage(query) {
1559
- const controller = new AbortController();
1560
- query.controller = controller;
1561
- const signature = query.signature();
1562
- query.markExecuting();
1563
- try {
1564
- const result = await runQuery(
1565
- query,
1566
- this.mappingsTo(query.name),
1567
- {
1568
- conditions: this.selectionConditionsFor(query.name, "applied"),
1569
- expression: this.selectionExpressionFor(query.name, "applied")
1570
- },
1571
- {
1572
- backend: this.backend,
1573
- timezone: this._timezone
1574
- },
1575
- controller.signal
1576
- );
1577
- query.markSuccess(result, signature, true);
1578
- } catch (err) {
1579
- query.rewindPage();
1580
- if (isAbort(err)) return;
1581
- const error = toDataAppError(err, query.name);
1582
- query.markError(error);
1583
- throw error;
1584
- } finally {
1585
- if (query.controller === controller) query.controller = void 0;
1586
- }
1587
- }
1588
- /**
1589
- * @internal Backs `query.export()`. Built from the applied state, as `fetchPage` is, so the file
1590
- * holds what the reader is looking at, every row of it. Touches nothing on the query.
1591
- */
1592
- async exportQuery(query, options = {}) {
1593
- const { backend } = this;
1594
- if (this.features?.export === false || !backend.exportQuery) {
1595
- throw new TransportError("This host cannot make exports.", void 0, query.name);
1596
- }
1597
- const request = buildExportRequest(
1598
- query,
1599
- this.mappingsTo(query.name),
1600
- {
1601
- conditions: this.selectionConditionsFor(query.name, "applied"),
1602
- expression: this.selectionExpressionFor(query.name, "applied")
1603
- },
1604
- { backend, timezone: this._timezone, title: this.title },
1605
- options
1606
- );
1607
- try {
1608
- return await backend.exportQuery(request, options.signal ?? new AbortController().signal);
1609
- } catch (err) {
1610
- if (isAbort(err)) throw err;
1611
- throw toExportError(err, query.name);
1612
- }
1613
- }
1614
- /* ----------------------------------------------------------------
1615
- Serialisation
1616
- ---------------------------------------------------------------- */
1617
- /**
1618
- * The declaration and nothing else — no datasets, no backend, no reader state. This is the
1619
- * shape a persisted Data App record will take, which is why mapping edges are already generic.
1620
- */
1621
- toJSON() {
1622
- const byKind = (kind) => Object.fromEntries(
1623
- [...this._controls.entries()].filter(([, control]) => control.kind === kind).map(([name, control]) => [name, control.toJSON()])
1624
- );
1625
- return {
1626
- ...this.title ? { title: this.title } : {},
1627
- ...this._timezone ? { timezone: this._timezone } : {},
1628
- queries: Object.fromEntries([...this._queries.entries()].map(([name, q]) => [name, q.toJSON()])),
1629
- filters: byKind("filter"),
1630
- dateDrills: byKind("dateDrill"),
1631
- mappings: [
1632
- ...this._mappings.map((mapping) => mapping.toJSON()),
1633
- ...this._crossFilters.map((edge) => edge.toJSON())
1634
- ]
1635
- };
1636
- }
1637
- /**
1638
- * Everything a host needs to render this app, as plain data.
1639
- *
1640
- * Separate from `toJSON()` rather than an option on it: `toJSON()` is the declaration and is the
1641
- * shape a persisted app takes, while this is a reading taken at a moment and already behind by
1642
- * the time anyone sees it. Written out field by field because the live objects cannot cross a
1643
- * port — getters are not cloned, and `Query.controller` holds an `AbortController` for exactly
1644
- * as long as someone is likely to be watching. See docs/adr/0007.
1645
- */
1646
- toInspectJSON() {
1647
- return {
1648
- ...this.title ? { title: this.title } : {},
1649
- ...this._timezone ? { timezone: this._timezone } : {},
1650
- hasChanges: this.hasChanges,
1651
- declaration: this.toJSON(),
1652
- queries: Object.fromEntries(
1653
- [...this._queries.entries()].map(([name, query]) => [name, inspectQuery(query)])
1654
- ),
1655
- controls: Object.fromEntries(
1656
- [...this._controls.entries()].map(([name, control]) => [name, inspectControl(control)])
1657
- ),
1658
- ...this._selection ? { selection: inspectSelection(this._selection) } : {},
1659
- ...this._appliedSelection ? { appliedSelection: inspectSelection(this._appliedSelection) } : {}
1660
- };
1661
- }
1662
- /**
1663
- * Bring an entity's marked elements into view: scroll to the first, show the overlay on all for
1664
- * a moment. False, and nothing done, when the document has none marked with it (or there is no
1665
- * document at all). Used by `Query.locate()` and `Control.locate()`, and by the bootstrap for a
1666
- * host's locate-by-entity.
1667
- */
1668
- locate(kind, name) {
1669
- const doc = globalThis.document;
1670
- if (!doc) return false;
1671
- const elements = markersFor(doc, kind, this.index, name);
1672
- if (!elements.length) return false;
1673
- scrollTo(elements[0]);
1674
- overlayFor(doc).flash(elements, {
1675
- kind,
1676
- name,
1677
- ...elements.length > 1 ? { note: `in ${elements.length} places` } : {}
1678
- });
1679
- return true;
1680
- }
1681
- /* ----------------------------------------------------------------
1682
- Internals
1683
- ---------------------------------------------------------------- */
1684
- assertNameFree(name, kind) {
1685
- assertUniqueName([...this._queries.keys(), ...this._controls.keys()], name, kind);
1686
- }
1687
- /**
1688
- * A field-backed filter usually lives in an app with one dataset, so requiring `dataset` on every
1689
- * filter would be noise. With several, it has to be said.
1690
- */
1691
- soleDataset(entity, field) {
1692
- if (!field) return void 0;
1693
- const unames = Object.keys(this.datasets);
1694
- if (unames.length === 1) return this.datasets[unames[0]];
1695
- throw new ValidationError(
1696
- unames.length ? `Filter '${entity}' names a field but the environment has ${unames.length} datasets. Say which one: ${unames.join(", ")}.` : `Filter '${entity}' names a field but the environment has no datasets.`,
1697
- entity
1698
- );
1699
- }
1700
- assertAcyclic(candidate) {
1701
- const edges = [...this._mappings, candidate];
1702
- const outgoing = /* @__PURE__ */ new Map();
1703
- edges.forEach((edge) => {
1704
- const key = edge.from.name;
1705
- outgoing.set(key, [...outgoing.get(key) ?? [], edge.to.name]);
1706
- });
1707
- const visiting = /* @__PURE__ */ new Set();
1708
- const done = /* @__PURE__ */ new Set();
1709
- const walk = (node) => {
1710
- if (visiting.has(node)) return true;
1711
- if (done.has(node)) return false;
1712
- visiting.add(node);
1713
- const cycle = (outgoing.get(node) ?? []).some(walk);
1714
- visiting.delete(node);
1715
- done.add(node);
1716
- return cycle;
1717
- };
1718
- if ([...outgoing.keys()].some(walk)) {
1719
- throw new ValidationError(
1720
- `Mapping '${candidate.id}' would make the app's mappings cyclic.`,
1721
- candidate.from.name
1722
- );
1723
- }
1724
- }
1725
- };
1726
-
1727
- // package.json
1728
- var version = "0.10.2";
1729
-
1730
- // src/app/sdk.ts
1731
- var VERSION = version;
1732
- var Sdk = class {
1733
- constructor(environment) {
1734
- __publicField(this, "version", VERSION);
1735
- __publicField(this, "_apps", []);
1736
- /**
1737
- * Readable on purpose: an agent can check a field name against the real schema before writing
1738
- * it. This is the useful half of runtime introspection *for an author*, which is why there is
1739
- * still no `describe()` on this surface. Describing a running app is a separate thing, addressed
1740
- * to the host rather than the author — see `App.toInspectJSON` and docs/adr/0007.
1741
- */
1742
- __publicField(this, "datasets");
1743
- /**
1744
- * Who the app is running as. Provisioned like `datasets` rather than fetched, so author code
1745
- * needs no await and no null check to greet someone or hide a control they cannot use.
1746
- */
1747
- __publicField(this, "user");
1748
- __publicField(this, "indices");
1749
- __publicField(this, "backend");
1750
- /**
1751
- * What the host can do beyond queries. `export` says whether `query.export()` can work here, and
1752
- * `render` whether `render()` can: show either's button only when it and
1753
- * `user.permissions.canExportData` are both true. `lineage` says whether `lineage()` can.
1754
- */
1755
- __publicField(this, "features");
1756
- __publicField(this, "renderHook");
1757
- if (!environment?.datasets) {
1758
- throw new ValidationError(
1759
- "No datasets provided. The host must call createSdk({ datasets }) before an app can be declared."
1760
- );
1761
- }
1762
- if (!environment.user) {
1763
- throw new ValidationError(
1764
- "No user provided. The host must call createSdk({ user }) before an app can be declared."
1765
- );
1766
- }
1767
- if (!environment.backend) {
1768
- throw new ValidationError(
1769
- "No backend provided. The host must call createSdk({ backend }) before an app can run a query."
1770
- );
1771
- }
1772
- this.datasets = Object.freeze({ ...environment.datasets });
1773
- this.user = Object.freeze({
1774
- ...environment.user,
1775
- permissions: Object.freeze({ ...environment.user.permissions })
1776
- });
1777
- this.indices = Object.fromEntries(
1778
- Object.entries(environment.datasets).map(([uname, descriptor]) => [
1779
- uname,
1780
- new DatasetIndex(descriptor)
1781
- ])
1782
- );
1783
- this.backend = environment.backend;
1784
- this.renderHook = environment.render;
1785
- this.features = Object.freeze({
1786
- ...environment.features,
1787
- // Known from the Backend itself when the host does not say. In a frame the bridge's Backend
1788
- // has every method, so there it is the host's provision that says.
1789
- export: environment.features?.export ?? typeof environment.backend.exportQuery === "function",
1790
- render: environment.features?.render ?? typeof environment.render === "function",
1791
- lineage: environment.features?.lineage ?? typeof environment.backend.lineage === "function"
1792
- });
1793
- }
1794
- createApp(declaration = {}) {
1795
- const app = new App(declaration, this.indices, this.backend, this.features);
1796
- app.index = this._apps.length;
1797
- this._apps.push(app);
1798
- return app;
1799
- }
1800
- /**
1801
- * Render the whole app, or one block or container of its structure by id, as a PNG or a PDF, and
1802
- * have the host save it for the reader. What is drawn is what the page shows now: `await
1803
- * app.execute()` first for fresh results. Elements marked `data-anfra-render="skip"` are left out.
1804
- * Rejects with a `ValidationError` naming what to fix.
1805
- */
1806
- render(request) {
1807
- if (!this.renderHook || this.features.render === false) {
1808
- return Promise.reject(new ValidationError("This host does not render Data Apps: check Anfra.features.render first."));
1809
- }
1810
- return this.renderHook(request);
1811
- }
1812
- /**
1813
- * Trace fields through the repo's catalog: what each one is built from (the fields, models and
1814
- * sources upstream of it), as a diagram to draw. Name each field by its parent and its name in
1815
- * it: `{ parent: 'orders', child: 'amount' }` for a model's field, `{ parent: 'ecommerce', child:
1816
- * 'revenue' }` for a dataset's metric. Nothing needs ingesting first: the host builds the repo's
1817
- * catalog when it has to. A field that cannot be traced answers its `error`, and the others still
1818
- * answer; a host that cannot trace lineage (see `features.lineage`) rejects with a
1819
- * `TransportError`.
1820
- */
1821
- lineage(targets, options = {}) {
1822
- const list = Array.isArray(targets) ? [...targets] : [targets];
1823
- const named = (s) => typeof s === "string" && s.trim() !== "";
1824
- if (list.length === 0 || list.some((t) => typeof t !== "object" || t === null || !named(t.parent) || !named(t.child))) {
1825
- return Promise.reject(new ValidationError(
1826
- "Anfra.lineage() takes a target or an array of targets, each by its parent and its name in it, such as { parent: 'ecommerce', child: 'revenue' }."
1827
- ));
1828
- }
1829
- if (!this.backend.lineage || this.features.lineage === false) {
1830
- return Promise.reject(new TransportError("This host cannot trace lineage: check Anfra.features.lineage first."));
1831
- }
1832
- const { limit, offset, signal = new AbortController().signal } = options;
1833
- return this.backend.lineage({
1834
- targets: list.map(({ parent, child }) => ({ parent, child })),
1835
- ...limit !== void 0 ? { limit } : {},
1836
- ...offset !== void 0 ? { offset } : {}
1837
- }, signal);
1838
- }
1839
- /**
1840
- * Every app this instance has built, for a host rendering an inspection panel.
1841
- *
1842
- * Not addressed to author code, which already holds whatever it created — this exists because the
1843
- * bootstrap does not, and cannot otherwise reach an app at all. Holding them means they outlive
1844
- * the author's own reference; the frame is discarded and rebuilt on every Run, which is what
1845
- * bounds it. See docs/adr/0007.
1846
- */
1847
- get apps() {
1848
- return this._apps;
1849
- }
1850
- };
1851
- function createSdk(environment) {
1852
- return new Sdk(environment);
1853
- }
1854
-
1855
- // src/app/sandbox.ts
1856
- var SANDBOX_GLOBAL = "Anfra";
1857
- function installSandbox(sdk, target = globalThis) {
1858
- const previous = target[SANDBOX_GLOBAL];
1859
- const existed = SANDBOX_GLOBAL in target;
1860
- target[SANDBOX_GLOBAL] = sdk;
1861
- return () => {
1862
- if (existed) {
1863
- target[SANDBOX_GLOBAL] = previous;
1864
- } else {
1865
- delete target[SANDBOX_GLOBAL];
1866
- }
1867
- };
1868
- }
1869
-
1870
- // src/app/pick.ts
1871
- function startPick(doc, handlers) {
1872
- let current = null;
1873
- const under = (event) => event.target instanceof Element ? event.target.closest(MARKED) : null;
1874
- const onMove = (event) => {
1875
- const element = under(event);
1876
- if (element === current) return;
1877
- current = element;
1878
- handlers.onHover(element);
1879
- };
1880
- const onClick = (event) => {
1881
- event.preventDefault();
1882
- event.stopPropagation();
1883
- const element = under(event);
1884
- if (element) handlers.onPick(element);
1885
- };
1886
- const onKey = (event) => {
1887
- if (event.key === "Escape") handlers.onCancel();
1888
- };
1889
- const options = { capture: true };
1890
- doc.addEventListener("mousemove", onMove, options);
1891
- doc.addEventListener("click", onClick, options);
1892
- doc.addEventListener("keydown", onKey, options);
1893
- return () => {
1894
- doc.removeEventListener("mousemove", onMove, options);
1895
- doc.removeEventListener("click", onClick, options);
1896
- doc.removeEventListener("keydown", onKey, options);
1897
- };
1898
- }
1899
-
1900
- // src/render/types.ts
1901
- var RENDERER_GLOBAL = "__anfraRenderer";
1902
-
1903
- // src/app/render.ts
1904
- var SKIP_ATTRIBUTE = "data-anfra-render";
1905
- var EXTENSIONS = { png: "png", pdf: "pdf" };
1906
- var SETTLE_MS = 1e4;
1907
- function filenameFor(request, doc, apps, element) {
1908
- const ext = EXTENSIONS[request.format];
1909
- let name = request.filename?.trim();
1910
- if (!name) {
1911
- const title = apps.find((app) => app.title)?.title || doc.title.trim() || "Data App";
1912
- const node = element && (element.getAttribute(ATTR.label) || request.block || request.container);
1913
- name = node ? `${title} - ${node}` : title;
1914
- }
1915
- name = name.replace(/[/\\]/g, "-").replace(/\p{Cc}/gu, "").trim() || "Data App";
1916
- return name.toLowerCase().endsWith(`.${ext}`) ? name : `${name}.${ext}`;
1917
- }
1918
- function targetOf(request, doc) {
1919
- if (request.block !== void 0 && request.container !== void 0) {
1920
- throw new ValidationError("Render a block or a container, not both.", request.block);
1921
- }
1922
- if (request.format !== "png" && request.format !== "pdf") {
1923
- throw new ValidationError(`Can't render as '${String(request.format)}': the formats are 'png' and 'pdf'.`);
1924
- }
1925
- const { pixelRatio } = request;
1926
- if (pixelRatio !== void 0 && !(Number.isFinite(pixelRatio) && pixelRatio > 0)) {
1927
- throw new ValidationError(`pixelRatio ${String(pixelRatio)} is not a positive number.`);
1928
- }
1929
- const kind = request.block !== void 0 ? "block" : request.container !== void 0 ? "container" : void 0;
1930
- if (!kind) return { element: null };
1931
- const id = request.block ?? request.container;
1932
- const element = [...doc.querySelectorAll(`[${ATTR[kind]}]`)].find((el) => el.getAttribute(ATTR[kind]) === id);
1933
- if (!element) throw new ValidationError(`No element is marked ${ATTR[kind]}="${id}" on the page.`, id);
1934
- return { element, entity: id };
1935
- }
1936
- function skip(element) {
1937
- return element.id === OVERLAY_ID || element.getAttribute(SKIP_ATTRIBUTE) === "skip";
1938
- }
1939
- function createRender(win, deps) {
1940
- let loading;
1941
- const load = () => {
1942
- const ready = win[RENDERER_GLOBAL];
1943
- if (ready) return Promise.resolve(ready);
1944
- loading ?? (loading = deps.ask.renderer().then((code) => {
1945
- const script = win.document.createElement("script");
1946
- script.textContent = code;
1947
- (win.document.head ?? win.document.documentElement).appendChild(script);
1948
- script.remove();
1949
- const installed = win[RENDERER_GLOBAL];
1950
- if (!installed) throw new ValidationError("The host sent a renderer that did not install.");
1951
- return installed;
1952
- }).catch((err) => {
1953
- loading = void 0;
1954
- throw err;
1955
- }));
1956
- return loading;
1957
- };
1958
- return async (request) => {
1959
- const doc = win.document;
1960
- const { element, entity } = targetOf(request ?? {}, doc);
1961
- const filename = filenameFor(request, doc, deps.apps(), element);
1962
- try {
1963
- const renderer = await load();
1964
- const drawing = await renderer.draw(element, { format: request.format, pixelRatio: request.pixelRatio, skip });
1965
- await deps.ask.saveFile({ blob: drawing.blob, filename });
1966
- return { filename, format: request.format, ...drawing };
1967
- } catch (err) {
1968
- if (err instanceof ValidationError && err.entity) throw err;
1969
- throw new ValidationError(err?.message || "The rendering failed.", entity);
1970
- }
1971
- };
1972
- }
1973
- async function settle(win, apps, timeout = SETTLE_MS) {
1974
- const busy = () => apps().some((app) => Object.values(app.queries).some((query) => query.state === "executing"));
1975
- const deadline = Date.now() + timeout;
1976
- while (busy() && Date.now() < deadline) {
1977
- await new Promise((resolve) => {
1978
- win.setTimeout(resolve, 100);
1979
- });
1980
- }
1981
- await new Promise((resolve) => {
1982
- win.requestAnimationFrame(() => resolve(void 0));
1983
- });
1984
- }
1985
-
1986
- // src/app/bootstrap.ts
1987
- function abortError() {
1988
- const err = new Error("Aborted");
1989
- err.name = "AbortError";
1990
- return err;
1991
- }
1992
- function toError(error) {
1993
- switch (error?.name) {
1994
- case "PermissionError":
1995
- return new PermissionError(error.message);
1996
- case "TransportError":
1997
- return new TransportError(error.message);
1998
- case "ValidationError":
1999
- return new ValidationError(error.message);
2000
- default:
2001
- return new QueryError(error?.message || "The query failed.");
2002
- }
2003
- }
2004
- function bootstrap(win) {
2005
- const element = win.document.getElementById(PROVISION_ELEMENT_ID);
2006
- if (!element?.textContent) throw new Error("anfra: this frame was not provisioned by a host.");
2007
- const provision = JSON.parse(element.textContent);
2008
- const post = (message) => win.parent.postMessage(message, provision.hostOrigin);
2009
- const pending = /* @__PURE__ */ new Map();
2010
- let nextId = 1;
2011
- let inspecting = false;
2012
- let timer;
2013
- win.addEventListener("message", (event) => {
2014
- if (event.source !== win.parent) return;
2015
- const message = event.data;
2016
- switch (message?.type) {
2017
- case "anfra:response": {
2018
- const call2 = pending.get(message.id);
2019
- if (!call2) return;
2020
- pending.delete(message.id);
2021
- if (message.ok) call2.resolve(message.result);
2022
- else call2.reject(toError(message.error));
2023
- return;
2024
- }
2025
- case "anfra:inspect-watch":
2026
- setInspecting(message.open);
2027
- return;
2028
- case "anfra:highlight":
2029
- highlight(message.node);
2030
- return;
2031
- case "anfra:locate":
2032
- locate(message.target);
2033
- return;
2034
- case "anfra:pick-watch":
2035
- setPicking(message.on);
2036
- return;
2037
- case "anfra:render": {
2038
- const { id } = message;
2039
- settle(win, () => instance.apps).then(() => instance.render(message.request)).then(
2040
- (result) => post({ type: "anfra:rendered", id, ok: true, result }),
2041
- (err) => post({ type: "anfra:rendered", id, ok: false, error: { name: err?.name ?? "ValidationError", message: err?.message ?? "The rendering failed." } })
2042
- );
2043
- return;
2044
- }
2045
- default:
2046
- }
2047
- });
2048
- function call(method, request, signal) {
2049
- return new Promise((resolve, reject) => {
2050
- if (signal.aborted) {
2051
- reject(abortError());
2052
- return;
2053
- }
2054
- const id = nextId++;
2055
- pending.set(id, { resolve, reject });
2056
- signal.addEventListener("abort", () => {
2057
- if (!pending.delete(id)) return;
2058
- post({ type: "anfra:cancel", id });
2059
- reject(abortError());
2060
- }, { once: true });
2061
- post({ type: "anfra:request", id, method, request });
2062
- });
2063
- }
2064
- const backend = {
2065
- submitQuery: (request, signal) => call("submitQuery", request, signal).then((result) => {
2066
- if (result.debug?.executedAt) result.debug.executedAt = new Date(result.debug.executedAt);
2067
- return result;
2068
- }),
2069
- fieldSuggestions: (request, signal) => call("fieldSuggestions", request, signal),
2070
- exportQuery: (request, signal) => call("exportQuery", request, signal).then((result) => {
2071
- result.expiresAt = new Date(result.expiresAt);
2072
- return result;
2073
- }),
2074
- lineage: (request, signal) => call("lineage", request, signal)
2075
- };
2076
- const render = createRender(win, {
2077
- ask: {
2078
- renderer: () => call("renderer", null, new AbortController().signal),
2079
- saveFile: (request) => call("saveFile", request, new AbortController().signal)
2080
- },
2081
- apps: () => instance.apps
2082
- });
2083
- const instance = createSdk({
2084
- datasets: provision.datasets,
2085
- user: provision.user,
2086
- backend,
2087
- render,
2088
- // A host older than `features` provisions none: say it can neither export, render nor trace,
2089
- // rather than let the bridge's Backend, which has every method, claim them.
2090
- features: { export: false, render: false, lineage: false, ...provision.features }
2091
- });
2092
- const doc = win.document;
2093
- let structure;
2094
- let lastStructureJson = "";
2095
- let observer;
2096
- let stopPick;
2097
- function postSnapshot() {
2098
- timer = void 0;
2099
- if (!inspecting) return;
2100
- try {
2101
- structure = buildStructure(doc, instance.apps);
2102
- lastStructureJson = JSON.stringify(structure.nodes);
2103
- post({
2104
- type: "anfra:inspect",
2105
- apps: instance.apps.map((app) => app.toInspectJSON()),
2106
- structure: { nodes: structure.nodes, usage: structure.usage }
2107
- });
2108
- } catch {
2109
- }
2110
- }
2111
- function scheduleSnapshot() {
2112
- if (inspecting && timer === void 0) timer = setTimeout(postSnapshot, 50);
2113
- }
2114
- function observeStructure() {
2115
- const Observer = win.MutationObserver;
2116
- if (observer || typeof Observer !== "function") return;
2117
- const watcher = new Observer(() => {
2118
- if (!inspecting || timer !== void 0) return;
2119
- try {
2120
- if (JSON.stringify(buildStructure(doc, instance.apps).nodes) !== lastStructureJson) scheduleSnapshot();
2121
- } catch {
2122
- }
2123
- });
2124
- observer = watcher;
2125
- watcher.observe(doc.documentElement, {
2126
- childList: true,
2127
- subtree: true,
2128
- attributes: true,
2129
- attributeFilter: ["data-anfra-container", "data-anfra-block", "data-anfra-query", "data-anfra-control", "data-anfra-label"]
2130
- });
2131
- }
2132
- function setInspecting(open) {
2133
- inspecting = open;
2134
- if (open) {
2135
- observeStructure();
2136
- postSnapshot();
2137
- } else {
2138
- observer?.disconnect();
2139
- observer = void 0;
2140
- setPicking(false);
2141
- overlayFor(doc).hide();
2142
- structure = void 0;
2143
- lastStructureJson = "";
2144
- }
2145
- }
2146
- function findNode(nodes, key) {
2147
- for (const node of nodes) {
2148
- if (node.key === key) return node;
2149
- const inner = findNode(node.children, key);
2150
- if (inner) return inner;
2151
- }
2152
- return void 0;
2153
- }
2154
- function highlight(key) {
2155
- const overlay = overlayFor(doc);
2156
- const node = key !== null && structure ? findNode(structure.nodes, key) : void 0;
2157
- const element2 = key !== null ? structure?.elements.get(key) : void 0;
2158
- if (!node || !element2 || !structure) {
2159
- overlay.hide();
2160
- return;
2161
- }
2162
- overlay.show([element2], describeNode(node, element2, structure));
2163
- }
2164
- function locate(target) {
2165
- if ("node" in target) {
2166
- const element2 = structure?.elements.get(target.node);
2167
- if (element2) scrollTo(element2);
2168
- highlight(target.node);
2169
- } else {
2170
- instance.apps[target.app]?.locate(target.kind, target.name);
2171
- }
2172
- scheduleSnapshot();
2173
- }
2174
- function setPicking(on) {
2175
- if (!on) {
2176
- stopPick?.();
2177
- stopPick = void 0;
2178
- return;
2179
- }
2180
- if (stopPick) return;
2181
- const keyOf = (element2) => structure?.keysOf.get(element2)?.[0];
2182
- stopPick = startPick(doc, {
2183
- onHover: (element2) => highlight(element2 ? keyOf(element2) ?? null : null),
2184
- onPick: (element2) => {
2185
- const key = keyOf(element2);
2186
- if (key !== void 0) post({ type: "anfra:picked", node: key });
2187
- },
2188
- onCancel: () => {
2189
- setPicking(false);
2190
- overlayFor(doc).hide();
2191
- post({ type: "anfra:picked", node: null });
2192
- }
2193
- });
2194
- }
2195
- const createApp = instance.createApp.bind(instance);
2196
- instance.createApp = (declaration) => {
2197
- const app = createApp(declaration);
2198
- app.subscribe(scheduleSnapshot);
2199
- scheduleSnapshot();
2200
- return app;
2201
- };
2202
- installSandbox(instance, win);
2203
- post({ type: "anfra:ready" });
2204
- }
36
+ ValidationError
37
+ } from "./chunk-KCTLO3CO.js";
38
+ import "./chunk-PKBMQBKP.js";
2205
39
  export {
2206
40
  App,
2207
41
  Control,
@@ -2210,6 +44,8 @@ export {
2210
44
  DateDrillControl,
2211
45
  FILTER_AGGREGATIONS,
2212
46
  Filter,
47
+ InstalledPlugins,
48
+ LAYER_ATTRIBUTE,
2213
49
  Mapping,
2214
50
  OVERLAY_ID,
2215
51
  PROVISION_ELEMENT_ID,